@inkeep/open-knowledge 0.27.0-beta.3 → 0.27.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/assets/skills/discovery/SKILL.md +1 -1
- package/dist/assets/skills/project/SKILL.md +1 -1
- package/dist/cli.mjs +6 -6
- package/dist/constants-CVwzJpO0.mjs +2 -0
- package/dist/{dist-Dqzx7uaJ.mjs → dist-CZ4COUHS.mjs} +1 -1
- package/dist/{dist-BoFX-ULL.mjs → dist-CdVqgoPq.mjs} +3 -3
- package/dist/index.mjs +1 -1
- package/dist/{init-Cw5lSFda.mjs → init-BwsVFj6d.mjs} +4 -4
- package/dist/init-Cy4VefHD.mjs +1 -0
- package/dist/loader-B001Pjdw.mjs +1 -0
- package/dist/{loader-BB3StuVP.mjs → loader-BAIfIvBS.mjs} +2 -2
- package/dist/preview-BZSWO0Y0.mjs +1 -0
- package/dist/{preview-VQLx0qR6.mjs → preview-CeZQltbU.mjs} +2 -2
- package/dist/{repair-launch-json-DjbHjime.mjs → repair-launch-json-jEfxfrXs.mjs} +2 -2
- package/dist/{repair-mcp-configs-Zo0iqRkn.mjs → repair-mcp-configs-Dtldp8WO.mjs} +2 -2
- package/dist/{repair-skills-B9vf1LVl.mjs → repair-skills-D7TJAZll.mjs} +2 -2
- package/dist/repair-skills-DCZqW9al.mjs +1 -0
- package/dist/{src-DFyp-u5J.mjs → src-DPiL5xHq.mjs} +2 -2
- package/dist/{start-yTYIxEV0.mjs → start-B0I0cewI.mjs} +2 -2
- package/dist/start-tOskjO8p.mjs +1 -0
- package/dist/{write-project-skill-DVYnPUfx.mjs → write-project-skill-BEzL3S1a.mjs} +2 -2
- package/package.json +1 -1
- package/dist/constants-ZpA-rcTF.mjs +0 -2
- package/dist/init-C60Y8z32.mjs +0 -1
- package/dist/loader-AzVlDL9Q.mjs +0 -1
- package/dist/preview-DiEuCxlc.mjs +0 -1
- package/dist/repair-skills-rGTpTOuw.mjs +0 -1
- package/dist/start-yAdBlXBN.mjs +0 -1
package/dist/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{i as e,r as t,t as n}from"./gh-detect-KLjG6xCR.mjs";import{B as r,C as i,E as a,F as o,I as s,L as c,P as l,R as u,S as d,a as f,b as p,i as m,l as h,m as g,n as _,u as v,z as y}from"./init-
|
|
1
|
+
import{i as e,r as t,t as n}from"./gh-detect-KLjG6xCR.mjs";import{B as r,C as i,E as a,F as o,I as s,L as c,P as l,R as u,S as d,a as f,b as p,i as m,l as h,m as g,n as _,u as v,z as y}from"./init-BwsVFj6d.mjs";import{_ as b,b as x,d as S,f as C,i as w,l as T,m as E,n as D,r as O,t as k,u as A,v as j,y as M}from"./src-DPiL5xHq.mjs";import{a as N,c as P,g as F,h as I,i as L,l as R,m as z,r as B,t as V,u as H}from"./write-project-skill-BEzL3S1a.mjs";import{n as U}from"./loader-BAIfIvBS.mjs";import{n as W}from"./preview-CeZQltbU.mjs";import{n as G,t as K}from"./mcp-migrate-event-D0NrGjvc.mjs";export{N as ALL_EDITOR_IDS,P as EDITOR_LABELS,R as EDITOR_TARGETS,H as HOSTS_WITH_USER_SKILL_DIR,_ as LAUNCH_CONFIG_NAME,m as LAUNCH_UI_CHAIN_SENTINEL,f as LAUNCH_UI_CHAIN_V1,A as PATH_SHIM_BEGIN,S as PATH_SHIM_BLOCK_RE,C as PATH_SHIM_END,l as addOkPathsToGitExclude,V as assertProjectPathSafe,z as buildManagedServerEntry,O as buildMcpConfigDeclineEvent,K as buildMcpConfigMigrateEvent,h as classifyExistingMcpEntry,t as createTokenStore,n as detectGh,v as detectInstalledEditors,o as formatTrackedRemediation,s as getExcludedOkPaths,c as getOkArtifactPaths,I as isEntryUpToDate,F as isOwnManagedEntry,U as loadConfig,e as makeLazyProbeTokenStore,b as parseGitHubBlobUrl,j as parseGitHubShareUrl,M as parseGitHubTreeUrl,x as parseGitUrl,E as pathInstallMarkerPath,W as previewContent,u as probeTrackedOkPaths,g as readExistingMcpEntry,y as readSharingMode,r as removeOkPathsFromGitExclude,T as removeOwnMcpEntry,B as removeUserGlobalSkillBundle,a as resolveProjectRoot,w as runStop,p as scaffoldLaunchJson,G as truncatePriorEntry,L as userGlobalSkillBundleTargets,D as validateLocalFolderForShare,d as writeEditorMcpConfig,k as writeProjectAiIntegrations,i as writeUserMcpConfigs};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a as e,s as t,t as n}from"./chunk-C94x7I9S.mjs";import{Aa as r,Ba as i,Bt as a,Et as o,Yi as s,bn as c,mt as l,yi as u,za as d}from"./server-lock-iLcBw_q0-CdrK5Xfo.mjs";import{$n as f,D as p,Gn as m,K as h,O as g,Qn as _,Sa as v,Zn as y,_a as b,cr as x,d as S,ir as C,ma as w,na as T,ra as ee,ut as E,vn as te}from"./dist-BoFX-ULL.mjs";import{r as D,t as O}from"./esm-CsQUg9js.mjs";import{t as ne}from"./constants-ZpA-rcTF.mjs";import{a as re,d as ie,f as ae,l as k,m as oe,n as se,p as ce,r as le,t as A,v as ue,y as j}from"./write-project-skill-DVYnPUfx.mjs";import{t as M}from"./is-object-Cg453afR.mjs";import{i as N,n as de,o as P,r as fe,s as F,t as I}from"./colors-8SzMRIVy.mjs";import{t as pe}from"./preview-VQLx0qR6.mjs";import{createRequire as me}from"node:module";import{execFileSync as he}from"node:child_process";import ge,{dirname as L,isAbsolute as _e,join as R,relative as z,resolve as ve,sep as ye}from"node:path";import B from"node:process";import{fileURLToPath as be}from"node:url";import{homedir as xe}from"node:os";import{existsSync as V,lstatSync as Se,mkdirSync as Ce,readFileSync as H,readlinkSync as we,realpathSync as Te,statSync as Ee,writeFileSync as De}from"node:fs";import{randomUUID as Oe}from"node:crypto";import{inspect as ke,stripVTControlCharacters as Ae,styleText as U}from"node:util";import{AsyncLocalStorage as je,AsyncResource as Me}from"node:async_hooks";import{createServer as Ne,request as Pe}from"node:http";import*as Fe from"node:readline";import{connect as Ie}from"node:net";const Le=new Set([`emacs`,`vim`]);function Re(e){return Le.has(e)}function ze(){let e=process.env.INQUIRER_KEYBINDINGS;return e?Array.from(new Set(e.toLowerCase().split(/[\s,]+/).filter(Re))):[]}const Be=(e,t=[])=>e.name===`up`||t.includes(`vim`)&&e.name===`k`||t.includes(`emacs`)&&e.ctrl&&e.name===`p`,Ve=(e,t=[])=>e.name===`down`||t.includes(`vim`)&&e.name===`j`||t.includes(`emacs`)&&e.ctrl&&e.name===`n`,He=e=>e.name===`space`,Ue=e=>e.name===`backspace`,We=e=>`1234567890`.includes(e.name),Ge=e=>e.name===`enter`||e.name===`return`;var Ke=class extends Error{name=`AbortPromptError`;message=`Prompt was aborted`;constructor(e){super(),this.cause=e?.cause}},qe=class extends Error{name=`CancelPromptError`;message=`Prompt was canceled`},Je=class extends Error{name=`ExitPromptError`},Ye=class extends Error{name=`HookError`},Xe=class extends Error{name=`ValidationError`};const Ze=new je;function Qe(e){return{rl:e,hooks:[],hooksCleanup:[],hooksEffect:[],index:0,handleChange(){}}}function $e(e,t){let n=Qe(e);return Ze.run(n,()=>{function e(e){n.handleChange=()=>{n.index=0,e()},n.handleChange()}return t(e)})}function W(){let e=Ze.getStore();if(!e)throw new Ye(`[Inquirer] Hook functions can only be called from within a prompt`);return e}function et(){return W().rl}function tt(e){return Me.bind((...t)=>{let n=W(),r=!1,i=n.handleChange;n.handleChange=()=>{r=!0};let a=e(...t);return r&&i(),n.handleChange=i,a})}function nt(e){let t=W(),{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 rt(){W().handleChange()}const it={queue(e){let t=W(),{index:n}=t;t.hooksEffect.push(()=>{t.hooksCleanup[n]?.();let r=e(et());if(r!=null&&typeof r!=`function`)throw new Xe(`useEffect return value must be a cleanup function or nothing.`);t.hooksCleanup[n]=r})},run(){let e=W();tt(()=>{e.hooksEffect.forEach(e=>{e()}),e.hooksEffect.length=0})()},clearAll(){let e=W();e.hooksCleanup.forEach(e=>{e?.()}),e.hooksEffect.length=0,e.hooksCleanup.length=0}};function at(e){return typeof e==`function`}function G(e){return nt(t=>{let n=Me.bind(function(e){t.get()!==e&&(t.set(e),rt())});if(t.initialized)return[t.get(),n];let r=at(e)?e():e;return t.set(r),[r,n]})}function ot(e,t){nt(n=>{let r=n.get();(!Array.isArray(r)||t.some((e,t)=>!Object.is(e,r[t])))&&it.queue(e),n.set(t)})}function st(){return B.platform.startsWith(`win`)?!!B.env.CI||!!B.env.WT_SESSION||!!B.env.TERMINUS_SUBLIME||B.env.ConEmuTask===`{cmd::Cmder}`||B.env.TERM_PROGRAM===`Terminus-Sublime`||B.env.TERM_PROGRAM===`vscode`||B.env.TERM===`xterm-256color`||B.env.TERM===`alacritty`||B.env.TERMINAL_EMULATOR===`JetBrains-JediTerm`:B.env.TERM!==`linux`}const ct={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:`╱`},lt={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:`⅒`},ut={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`},dt={...ct,...lt},ft={...ct,...ut},K=st()?dt:ft;Object.entries(lt);const pt={prefix:{idle:U(`blue`,`?`),done:U(`green`,K.tick)},spinner:{interval:80,frames:[`⠋`,`⠙`,`⠹`,`⠸`,`⠼`,`⠴`,`⠦`,`⠧`,`⠇`,`⠏`].map(e=>U(`yellow`,e))},keybindings:[],style:{answer:e=>U(`cyan`,e),message:e=>U(`bold`,e),error:e=>U(`red`,`> ${e}`),defaultAnswer:e=>U(`dim`,`(${e})`),help:e=>U(`dim`,e),highlight:e=>U(`cyan`,e),key:e=>U(`cyan`,U(`bold`,`<${e}>`))}};function mt(){return{...pt,keybindings:ze()}}function ht(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 gt(...e){let t={};for(let n of e)for(let[e,r]of Object.entries(n)){let n=t[e];t[e]=ht(n)&&ht(r)?gt(n,r):r}return t}function _t(...e){return gt(mt(),...e.filter(e=>e!=null))}function vt({status:e=`idle`,theme:t}){let[n,r]=G(!1),[i,a]=G(0),{prefix:o,spinner:s}=_t(t);return ot(()=>{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 yt(e,t){return nt(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 bt(e){return G({current:e})[0]}function xt(e){let t=bt(e);t.current=e,ot(e=>{let n=!1,r=tt((r,i)=>{n||t.current(i,e)});return e.input.on(`keypress`,r),()=>{n=!0,e.input.removeListener(`keypress`,r)}},[])}var St=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 Ct=(()=>{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}})(),wt=e=>e===12288||e>=65281&&e<=65376||e>=65504&&e<=65510,Tt=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,Et=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]|\u001b\]8;[^;]*;.*?(?:\u0007|\u001b\u005c)/y,Dt=/[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y,Ot=/(?:(?![\uFF61-\uFF9F\uFF00-\uFFEF])[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}\p{Script=Tangut}]){1,1000}/uy,kt=/\t{1,1000}/y,At=/[\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,jt=/(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y,Mt=/\p{M}+/gu,Nt={limit:1/0,ellipsis:``},Pt=(e,t={},n={})=>{let r=t.limit??1/0,i=t.ellipsis??``,a=t?.ellipsisWidth??(i?Pt(i,Nt,n).width:0),o=n.controlWidth??0,s=n.tabWidth??8,c=n.emojiWidth??2,l=n.regularWidth??1,u=n.wideWidth??2,d=[[jt,l],[Et,0],[Dt,o],[kt,s],[At,c],[Ot,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(Mt,``)){let t=e.codePointAt(0)||0;if(S=wt(t)?2:Tt(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===Ot?Ct(e.slice(p,n.lastIndex)):n===At?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}},Ft={limit:1/0,ellipsis:``,ellipsisWidth:0},q=(e,t={})=>Pt(e,Ft,t).width,It=`]8;;`,Lt=RegExp(`(?:\\[(?<code>\\d+)m|\\${It}(?<uri>.*))`,`y`),Rt=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},zt=e=>`[${e}m`,Bt=e=>`${It}${e}`,Vt=(e,t,n)=>{let r=t[Symbol.iterator](),i=!1,a=!1,o=e.at(-1),s=o===void 0?0:q(o),c=r.next(),l=r.next(),u=0;for(;!c.done;){let o=c.value,d=q(o);s+d<=n?e[e.length-1]+=o:(e.push(o),s=0),(o===`\x1B`||o===``)&&(i=!0,a=t.startsWith(It,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())},Ht=e=>{let t=e.split(` `),n=t.length;for(;n&&!q(t[n-1]);)n--;return n===t.length?e:t.slice(0,n).join(` `)+t.slice(n).join(``)},Ut=(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=q(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=q(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(``),Vt(s,r,t),c=q(s.at(-1)??``);continue}if(c+i>t&&c&&i){if(n.wordWrap===!1&&c<t){Vt(s,r,t),c=q(s.at(-1)??``);continue}s.push(``),c=0}if(c+i>t&&n.wordWrap===!1){Vt(s,r,t),c=q(s.at(-1)??``);continue}s[s.length-1]+=r,c+=i}n.trim!==!1&&(s=s.map(e=>Ht(e)));let l=s.join(`
|
|
1
|
+
import{a as e,s as t,t as n}from"./chunk-C94x7I9S.mjs";import{Aa as r,Ba as i,Bt as a,Et as o,Yi as s,bn as c,mt as l,yi as u,za as d}from"./server-lock-iLcBw_q0-CdrK5Xfo.mjs";import{$n as f,D as p,Gn as m,K as h,O as g,Qn as _,Sa as v,Zn as y,_a as b,cr as x,d as S,ir as C,ma as w,na as T,ra as ee,ut as E,vn as te}from"./dist-CdVqgoPq.mjs";import{r as D,t as O}from"./esm-CsQUg9js.mjs";import{t as ne}from"./constants-CVwzJpO0.mjs";import{a as re,d as ie,f as ae,l as k,m as oe,n as se,p as ce,r as le,t as A,v as ue,y as j}from"./write-project-skill-BEzL3S1a.mjs";import{t as M}from"./is-object-Cg453afR.mjs";import{i as N,n as de,o as P,r as fe,s as F,t as I}from"./colors-8SzMRIVy.mjs";import{t as pe}from"./preview-CeZQltbU.mjs";import{createRequire as me}from"node:module";import{execFileSync as he}from"node:child_process";import ge,{dirname as L,isAbsolute as _e,join as R,relative as z,resolve as ve,sep as ye}from"node:path";import B from"node:process";import{fileURLToPath as be}from"node:url";import{homedir as xe}from"node:os";import{existsSync as V,lstatSync as Se,mkdirSync as Ce,readFileSync as H,readlinkSync as we,realpathSync as Te,statSync as Ee,writeFileSync as De}from"node:fs";import{randomUUID as Oe}from"node:crypto";import{inspect as ke,stripVTControlCharacters as Ae,styleText as U}from"node:util";import{AsyncLocalStorage as je,AsyncResource as Me}from"node:async_hooks";import{createServer as Ne,request as Pe}from"node:http";import*as Fe from"node:readline";import{connect as Ie}from"node:net";const Le=new Set([`emacs`,`vim`]);function Re(e){return Le.has(e)}function ze(){let e=process.env.INQUIRER_KEYBINDINGS;return e?Array.from(new Set(e.toLowerCase().split(/[\s,]+/).filter(Re))):[]}const Be=(e,t=[])=>e.name===`up`||t.includes(`vim`)&&e.name===`k`||t.includes(`emacs`)&&e.ctrl&&e.name===`p`,Ve=(e,t=[])=>e.name===`down`||t.includes(`vim`)&&e.name===`j`||t.includes(`emacs`)&&e.ctrl&&e.name===`n`,He=e=>e.name===`space`,Ue=e=>e.name===`backspace`,We=e=>`1234567890`.includes(e.name),Ge=e=>e.name===`enter`||e.name===`return`;var Ke=class extends Error{name=`AbortPromptError`;message=`Prompt was aborted`;constructor(e){super(),this.cause=e?.cause}},qe=class extends Error{name=`CancelPromptError`;message=`Prompt was canceled`},Je=class extends Error{name=`ExitPromptError`},Ye=class extends Error{name=`HookError`},Xe=class extends Error{name=`ValidationError`};const Ze=new je;function Qe(e){return{rl:e,hooks:[],hooksCleanup:[],hooksEffect:[],index:0,handleChange(){}}}function $e(e,t){let n=Qe(e);return Ze.run(n,()=>{function e(e){n.handleChange=()=>{n.index=0,e()},n.handleChange()}return t(e)})}function W(){let e=Ze.getStore();if(!e)throw new Ye(`[Inquirer] Hook functions can only be called from within a prompt`);return e}function et(){return W().rl}function tt(e){return Me.bind((...t)=>{let n=W(),r=!1,i=n.handleChange;n.handleChange=()=>{r=!0};let a=e(...t);return r&&i(),n.handleChange=i,a})}function nt(e){let t=W(),{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 rt(){W().handleChange()}const it={queue(e){let t=W(),{index:n}=t;t.hooksEffect.push(()=>{t.hooksCleanup[n]?.();let r=e(et());if(r!=null&&typeof r!=`function`)throw new Xe(`useEffect return value must be a cleanup function or nothing.`);t.hooksCleanup[n]=r})},run(){let e=W();tt(()=>{e.hooksEffect.forEach(e=>{e()}),e.hooksEffect.length=0})()},clearAll(){let e=W();e.hooksCleanup.forEach(e=>{e?.()}),e.hooksEffect.length=0,e.hooksCleanup.length=0}};function at(e){return typeof e==`function`}function G(e){return nt(t=>{let n=Me.bind(function(e){t.get()!==e&&(t.set(e),rt())});if(t.initialized)return[t.get(),n];let r=at(e)?e():e;return t.set(r),[r,n]})}function ot(e,t){nt(n=>{let r=n.get();(!Array.isArray(r)||t.some((e,t)=>!Object.is(e,r[t])))&&it.queue(e),n.set(t)})}function st(){return B.platform.startsWith(`win`)?!!B.env.CI||!!B.env.WT_SESSION||!!B.env.TERMINUS_SUBLIME||B.env.ConEmuTask===`{cmd::Cmder}`||B.env.TERM_PROGRAM===`Terminus-Sublime`||B.env.TERM_PROGRAM===`vscode`||B.env.TERM===`xterm-256color`||B.env.TERM===`alacritty`||B.env.TERMINAL_EMULATOR===`JetBrains-JediTerm`:B.env.TERM!==`linux`}const ct={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:`╱`},lt={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:`⅒`},ut={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`},dt={...ct,...lt},ft={...ct,...ut},K=st()?dt:ft;Object.entries(lt);const pt={prefix:{idle:U(`blue`,`?`),done:U(`green`,K.tick)},spinner:{interval:80,frames:[`⠋`,`⠙`,`⠹`,`⠸`,`⠼`,`⠴`,`⠦`,`⠧`,`⠇`,`⠏`].map(e=>U(`yellow`,e))},keybindings:[],style:{answer:e=>U(`cyan`,e),message:e=>U(`bold`,e),error:e=>U(`red`,`> ${e}`),defaultAnswer:e=>U(`dim`,`(${e})`),help:e=>U(`dim`,e),highlight:e=>U(`cyan`,e),key:e=>U(`cyan`,U(`bold`,`<${e}>`))}};function mt(){return{...pt,keybindings:ze()}}function ht(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 gt(...e){let t={};for(let n of e)for(let[e,r]of Object.entries(n)){let n=t[e];t[e]=ht(n)&&ht(r)?gt(n,r):r}return t}function _t(...e){return gt(mt(),...e.filter(e=>e!=null))}function vt({status:e=`idle`,theme:t}){let[n,r]=G(!1),[i,a]=G(0),{prefix:o,spinner:s}=_t(t);return ot(()=>{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 yt(e,t){return nt(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 bt(e){return G({current:e})[0]}function xt(e){let t=bt(e);t.current=e,ot(e=>{let n=!1,r=tt((r,i)=>{n||t.current(i,e)});return e.input.on(`keypress`,r),()=>{n=!0,e.input.removeListener(`keypress`,r)}},[])}var St=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 Ct=(()=>{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}})(),wt=e=>e===12288||e>=65281&&e<=65376||e>=65504&&e<=65510,Tt=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,Et=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]|\u001b\]8;[^;]*;.*?(?:\u0007|\u001b\u005c)/y,Dt=/[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y,Ot=/(?:(?![\uFF61-\uFF9F\uFF00-\uFFEF])[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}\p{Script=Tangut}]){1,1000}/uy,kt=/\t{1,1000}/y,At=/[\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,jt=/(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y,Mt=/\p{M}+/gu,Nt={limit:1/0,ellipsis:``},Pt=(e,t={},n={})=>{let r=t.limit??1/0,i=t.ellipsis??``,a=t?.ellipsisWidth??(i?Pt(i,Nt,n).width:0),o=n.controlWidth??0,s=n.tabWidth??8,c=n.emojiWidth??2,l=n.regularWidth??1,u=n.wideWidth??2,d=[[jt,l],[Et,0],[Dt,o],[kt,s],[At,c],[Ot,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(Mt,``)){let t=e.codePointAt(0)||0;if(S=wt(t)?2:Tt(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===Ot?Ct(e.slice(p,n.lastIndex)):n===At?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}},Ft={limit:1/0,ellipsis:``,ellipsisWidth:0},q=(e,t={})=>Pt(e,Ft,t).width,It=`]8;;`,Lt=RegExp(`(?:\\[(?<code>\\d+)m|\\${It}(?<uri>.*))`,`y`),Rt=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},zt=e=>`[${e}m`,Bt=e=>`${It}${e}`,Vt=(e,t,n)=>{let r=t[Symbol.iterator](),i=!1,a=!1,o=e.at(-1),s=o===void 0?0:q(o),c=r.next(),l=r.next(),u=0;for(;!c.done;){let o=c.value,d=q(o);s+d<=n?e[e.length-1]+=o:(e.push(o),s=0),(o===`\x1B`||o===``)&&(i=!0,a=t.startsWith(It,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())},Ht=e=>{let t=e.split(` `),n=t.length;for(;n&&!q(t[n-1]);)n--;return n===t.length?e:t.slice(0,n).join(` `)+t.slice(n).join(``)},Ut=(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=q(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=q(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(``),Vt(s,r,t),c=q(s.at(-1)??``);continue}if(c+i>t&&c&&i){if(n.wordWrap===!1&&c<t){Vt(s,r,t),c=q(s.at(-1)??``);continue}s.push(``),c=0}if(c+i>t&&n.wordWrap===!1){Vt(s,r,t),c=q(s.at(-1)??``);continue}s[s.length-1]+=r,c+=i}n.trim!==!1&&(s=s.map(e=>Ht(e)));let l=s.join(`
|
|
2
2
|
`),u=!1;for(let e=0;e<l.length;e++){let t=l[e];if(r+=t,u)u=!1;else if(u=t>=`\ud800`&&t<=`\udbff`,u)continue;if(t===`\x1B`||t===``){Lt.lastIndex=e+1;let t=Lt.exec(l)?.groups;if(t?.code!==void 0){let e=Number.parseFloat(t.code);i=e===39?void 0:e}else t?.uri!==void 0&&(a=t.uri.length===0?void 0:t.uri)}if(l[e+1]===`
|
|
3
3
|
`){a&&(r+=Bt(``));let e=i?Rt(i):void 0;i&&e&&(r+=zt(e))}else t===`
|
|
4
4
|
`&&(i&&Rt(i)&&(r+=zt(i)),a&&(r+=Bt(a)))}return r},Wt=/\r?\n/;function Gt(e,t,n){return String(e).normalize().split(Wt).map(e=>Ut(e,t,n)).join(`
|
|
@@ -628,7 +628,7 @@ export default function okBridge(pi: {
|
|
|
628
628
|
});
|
|
629
629
|
}
|
|
630
630
|
`}function bi(e,t){let n=z(t,e);return n.length>0&&!n.startsWith(`..`)&&!_e(n)}const xi=e=>{try{let t=he(`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??xe(),r=t.gitTopLevel??xi,i=ve(e),a;try{a=Te(i)}catch{a=i}let o=a,s=0;for(;s<30&&!(o===n||o===`/`||o===``);){if(x(o))return{projectRoot:o,defaultContentDir:`.`,ancestorPromoted:o!==a,gitRootPromoted:!1};let e=L(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??me(t);try{return n(R(L(be(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=Se(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=we(t)}catch(t){return $(`readlinkSync threw during symlink walk`,t),{readPath:null,writePath:e}}t=_e(i)?i:R(L(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(!M(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:${Oe()}`;if(e.headersSent||e.writableEnded||e.destroyed){console.error(`[ok ui] emitProblem called after headers sent — suppressed`,{type:n,status:t,instance:a});return}let o={type:n,title:r,status:t,instance:a,...i===void 0?{}:{detail:i}},s=c.safeParse(o);if(!s.success){console.error(`[ok ui] emitProblem produced an invalid ProblemDetails body:`,{issues:s.error.issues,originalStatus:t,body:o}),e.writeHead(500,{"Content-Type":`application/problem+json`,"X-Content-Type-Options":`nosniff`,"Cache-Control":`no-store`}),e.end(JSON.stringify({type:`urn:ok:error:internal-server-error`,title:`Internal server error.`,status:500,instance:a}));return}e.writeHead(t,{"Content-Type":`application/problem+json`,"X-Content-Type-Options":`nosniff`,"Cache-Control":`no-store`}),e.end(JSON.stringify(o))}const Bi=1e4;function Vi(e,t){let n=e.socket?.remoteAddress;if(n!==void 0&&!C(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&&!_(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&&!C(n)||!f(e.headers.host))return t.destroy(),!0;let r=e.headers.origin;return typeof r==`string`&&!_(r)?(t.destroy(),!0):!1}function Wi(e,t,n,r,i,a){a.add(t),t.once(`close`,()=>a.delete(t));let o=Ie({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=Ne((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=Pe({host:n,port:r,method:e.method,path:e.url,headers:{...a,host:`${n}:${r}`}},e=>{let n={...e.headers};for(let e of 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:a}=await import(`node:path`),{acquireUiLock:o,clearArmedPaneTarget:s,createAssetServeMiddleware:c,createContentFilter:f,readArmedPaneTarget:p,readServerLock:m,releaseUiLock:h,updateUiLockPort:g}=await import(`./dist-Dqzx7uaJ.mjs`),{default:_}=await import(`./build-gfyDk62R.mjs`),{resolveContentDir:v,resolveLockDir:y}=await import(`./dist-Dqzx7uaJ.mjs`),b=v(e.config,e.cwd),x=y(e.cwd);o(x,{port:0,worktreeRoot:e.cwd});let S=import.meta.dirname??new URL(`.`,import.meta.url).pathname,C=[a(S,`public`),a(S,`../../app/dist`),a(S,`../../../app/dist`)],w=e.assetDir??C.find(e=>t(e)),T=w?_(w,{single:!0,gzip:!0,etag:!0,dev:!0,extensions:[]}):null,ee=t(b)?c({contentFilter:f({projectDir:e.cwd,contentDir:b}),contentSirv:_(b,{dotfiles:!1,dev:!0,extensions:[]}),inlineExtensions:i,assetExtensions:r,blocklistExtensions:d}):null,E=e.port,te=null,D=(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`)){te?.();let n=m(x),r=e.headers.host??`localhost:${E}`,i=n&&n.port>0?`ws://${r}/collab`:null,a=p(x),o=JSON.stringify({collabUrl:i,previewUrl:null,port:E,paneTarget:a});t.setHeader(`Content-Type`,`application/json`),t.setHeader(`Cache-Control`,`no-store`),t.setHeader(`X-Content-Type-Options`,`nosniff`),t.statusCode=200,e.method===`HEAD`?t.end():t.end(o);return}if(n?.startsWith(`/api/`)){te?.();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:l,upstreamPort:r.port});return}if(T&&n?.startsWith(`/assets/`)){T(e,t,()=>{ee?ee(e,t,()=>$i(t)):$i(t)});return}if(ee){ee(e,t,()=>{T?T(e,t):$i(t)});return}if(T){T(e,t);return}$i(t)}},O=new Set,ne=(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,l,i.port,O)},re=()=>{for(let e of O)try{e.destroy()}catch{}O.clear()},ie=e.host===void 0?[`::1`,`127.0.0.1`]:[e.host],ae=[],k=e.port,oe=e=>e instanceof Error&&e.code===`EADDRINUSE`,se=async()=>{await Promise.all(ae.splice(0).map(e=>new Promise(t=>{try{e.close(()=>t())}catch{t()}})))},ce=async e=>{k=e;for(let e of ie){let t=n(D);t.on(`upgrade`,ne),ae.push(t),await new Promise((n,r)=>{let i=e=>r(e);t.once(`error`,i),t.listen(k,e,()=>{t.off(`error`,i);let e=t.address();typeof e==`object`&&e&&(k=e.port),n()})})}};try{try{await ce(e.port)}catch(t){if(e.fallbackToKernel===!0&&oe(t))await se(),await ce(0);else throw t}}catch(e){await se();try{h(x)}catch{}throw e}let le=k;E=le,g(x,le);let A=e.scheduler??u,ue=e.safetyNetMs??432e5,j=null,M=!1,N=!1,de=()=>{M||(M=!0,j!==null&&(A.clearTimeout(j),j=null))},P=()=>{if(de(),!N){N=!0;try{h(x)}catch{}}},fe=()=>{M||ue<=0||(j!==null&&(A.clearTimeout(j),j=null),j=A.setTimeout(()=>{j=null,console.warn(`[ui] safety-net (${ue}ms) reached — shutting down (D-025 backstop)`);try{e.onSafetyNet?.()}catch{}re();for(let e of ae)try{e.close()}catch{}P()},ue))},F=()=>{M||ue<=0||fe()};return te=F,fe(),{httpServers:ae,port:le,release:P,detachSafetyNet:de,nudgeSafetyNet:F,drainUpgradeSockets:re}}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-Dqzx7uaJ.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 O(`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-Dqzx7uaJ.mjs`),{resolveLockDir:i}=await import(`./dist-Dqzx7uaJ.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){w(e,`${JSON.stringify(t,null,2)}\n`)}function la(e,t){let n=mi(t);w(e,n.endsWith(`
|
|
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=Ne((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=Pe({host:n,port:r,method:e.method,path:e.url,headers:{...a,host:`${n}:${r}`}},e=>{let n={...e.headers};for(let e of 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:a}=await import(`node:path`),{acquireUiLock:o,clearArmedPaneTarget:s,createAssetServeMiddleware:c,createContentFilter:f,readArmedPaneTarget:p,readServerLock:m,releaseUiLock:h,updateUiLockPort:g}=await import(`./dist-CZ4COUHS.mjs`),{default:_}=await import(`./build-gfyDk62R.mjs`),{resolveContentDir:v,resolveLockDir:y}=await import(`./dist-CZ4COUHS.mjs`),b=v(e.config,e.cwd),x=y(e.cwd);o(x,{port:0,worktreeRoot:e.cwd});let S=import.meta.dirname??new URL(`.`,import.meta.url).pathname,C=[a(S,`public`),a(S,`../../app/dist`),a(S,`../../../app/dist`)],w=e.assetDir??C.find(e=>t(e)),T=w?_(w,{single:!0,gzip:!0,etag:!0,dev:!0,extensions:[]}):null,ee=t(b)?c({contentFilter:f({projectDir:e.cwd,contentDir:b}),contentSirv:_(b,{dotfiles:!1,dev:!0,extensions:[]}),inlineExtensions:i,assetExtensions:r,blocklistExtensions:d}):null,E=e.port,te=null,D=(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`)){te?.();let n=m(x),r=e.headers.host??`localhost:${E}`,i=n&&n.port>0?`ws://${r}/collab`:null,a=p(x),o=JSON.stringify({collabUrl:i,previewUrl:null,port:E,paneTarget:a});t.setHeader(`Content-Type`,`application/json`),t.setHeader(`Cache-Control`,`no-store`),t.setHeader(`X-Content-Type-Options`,`nosniff`),t.statusCode=200,e.method===`HEAD`?t.end():t.end(o);return}if(n?.startsWith(`/api/`)){te?.();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:l,upstreamPort:r.port});return}if(T&&n?.startsWith(`/assets/`)){T(e,t,()=>{ee?ee(e,t,()=>$i(t)):$i(t)});return}if(ee){ee(e,t,()=>{T?T(e,t):$i(t)});return}if(T){T(e,t);return}$i(t)}},O=new Set,ne=(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,l,i.port,O)},re=()=>{for(let e of O)try{e.destroy()}catch{}O.clear()},ie=e.host===void 0?[`::1`,`127.0.0.1`]:[e.host],ae=[],k=e.port,oe=e=>e instanceof Error&&e.code===`EADDRINUSE`,se=async()=>{await Promise.all(ae.splice(0).map(e=>new Promise(t=>{try{e.close(()=>t())}catch{t()}})))},ce=async e=>{k=e;for(let e of ie){let t=n(D);t.on(`upgrade`,ne),ae.push(t),await new Promise((n,r)=>{let i=e=>r(e);t.once(`error`,i),t.listen(k,e,()=>{t.off(`error`,i);let e=t.address();typeof e==`object`&&e&&(k=e.port),n()})})}};try{try{await ce(e.port)}catch(t){if(e.fallbackToKernel===!0&&oe(t))await se(),await ce(0);else throw t}}catch(e){await se();try{h(x)}catch{}throw e}let le=k;E=le,g(x,le);let A=e.scheduler??u,ue=e.safetyNetMs??432e5,j=null,M=!1,N=!1,de=()=>{M||(M=!0,j!==null&&(A.clearTimeout(j),j=null))},P=()=>{if(de(),!N){N=!0;try{h(x)}catch{}}},fe=()=>{M||ue<=0||(j!==null&&(A.clearTimeout(j),j=null),j=A.setTimeout(()=>{j=null,console.warn(`[ui] safety-net (${ue}ms) reached — shutting down (D-025 backstop)`);try{e.onSafetyNet?.()}catch{}re();for(let e of ae)try{e.close()}catch{}P()},ue))},F=()=>{M||ue<=0||fe()};return te=F,fe(),{httpServers:ae,port:le,release:P,detachSafetyNet:de,nudgeSafetyNet:F,drainUpgradeSockets:re}}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-CZ4COUHS.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 O(`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-CZ4COUHS.mjs`),{resolveLockDir:i}=await import(`./dist-CZ4COUHS.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){w(e,`${JSON.stringify(t,null,2)}\n`)}function la(e,t){let n=mi(t);w(e,n.endsWith(`
|
|
632
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(M(e)&&M(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
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:M(r)?r[n]:void 0}function ga(e,t,n,r,i){if(!V(e))return ca(e,ma(t,i,n,r)),{kind:`written`};let a;try{a=H(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=M(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
634
|
`)?`\r
|
|
@@ -655,6 +655,6 @@ UIPORT="\${PORT:-${Xi}}"
|
|
|
655
655
|
unset PORT
|
|
656
656
|
exec node "${ue()}" start --ui-port "$UIPORT"`],port:Xi,autoPort:!0}:{name:ka,runtimeExecutable:`/bin/sh`,runtimeArgs:[`-l`,`-c`,Ma],port:Xi,autoPort:!0};try{if(A(n,e),!V(n))return Ce(L(n),{recursive:!0}),De(n,`${JSON.stringify({version:Oa,configurations:[r]},null,2)}\n`,`utf-8`),{action:`created`,configPath:n};let t=H(n,`utf-8`).trim(),i=t?JSON.parse(t):{};if(!M(i))return{action:`failed`,configPath:n,error:`launch.json root is not an object`};let a=Array.isArray(i.configurations)?i.configurations:[],o=a.findIndex(e=>M(e)&&e.name===`open-knowledge-ui`);o>=0?a[o]=r:a.push(r);let s={...i,version:i.version??Oa,configurations:a};return De(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 Pa(e,t,n){try{return V(e.detectPath?.(t,n)??L(e.configPath(t,n)))}catch{return!1}}function Fa(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&&!Pa(e,t,r))return{editorId:e.id,label:e.label,action:`skipped-missing`,configPath:o,serverName:a};if(i!==void 0)try{A(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 La(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{Ce(L(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{b(`${o}.lock`,()=>{let t=Ai(o).writePath;if(Ce(L(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 Ia={pi:yi};function La(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=Ia[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{Ce(L(t),{recursive:!0})}catch(e){return o(e)}let l={action:`written`};try{b(`${t}.lock`,()=>{let e=null;try{e=H(t,`utf-8`)}catch{e=null}if(e===c){l.action=`overwritten`;return}w(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 Ra(e,t){let n=e.projectConfigPath?.(t);if(!(!n||!V(n)))return{editorId:e.id,label:e.label,path:n}}async function za(e){let t=j(e.editors).filter(e=>e.scope===`global`),n={mode:`published`,skipAvailabilityCheck:!0};return t.map(t=>Fa(t,``,n,e.home))}function Ba(e,t,n,r){let i=Ha(e,t,n,r);return i.kind===`present`?i.entry:null}function Va(e,t,n,r){let i=ha(e,t,r);if(!M(i))return{kind:`no-entry`};let a=i[n];return M(a)?{kind:`present`,entry:a}:{kind:`no-entry`}}function Ha(e,t,n,r){let i;try{i=r??e.configPath(t,n)}catch{return{kind:`absent`}}if(!V(i))return{kind:`absent`};try{if(Ee(i).size>ua)return{kind:`decline`,reason:`oversize`}}catch{return{kind:`decline`,reason:`unparseable`}}let a;try{a=H(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 Va(t,e.topLevelKey,o,e.serverMapSubKey)}let s=oa(a);return s?sa(s,e.topLevelKey)>1?{kind:`decline`,reason:`duplicate-container`}:Va(mr(s),e.topLevelKey,o,e.serverMapSubKey):{kind:`decline`,reason:`unparseable`}}async function Ua(e={}){let t=ve(e.cwd??process.cwd()),n=Si(t,{homeDir:e.home}),r=n.projectRoot,i=!V(R(r,`.ok`)),a=n.gitRootPromoted?z(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(`${F(`[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 te(r),l;try{l=m(r,{contentDir:o})}catch(t){let i=k.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(ne),d=!1;if(c.didInit)try{d=ee(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??Ya(r,e.home),h=e.editors??re.filter(e=>k[e].projectConfigPath!==void 0),g=j(p),_=j(h),v=e.mcp===!1||f===null,b=Array.from(new Map([...g,...v?[]:_].map(e=>[e.id,e])).values()),x=g.filter(t=>Pa(t,r,e.home)),C=[],w=[],D=new Set;for(let t of b){if(v){let n=``;try{n=t.configPath(r,e.home)}catch{}C.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`&&C.push(Fa(t,r,s,e.home)),ya(f)&&_.includes(t)&&t.projectConfigPath){let n=t.projectConfigPath(r),i=Fa(t,r,s,e.home,n);C.push(i),(i.action===`written`||i.action===`overwritten`)&&D.add(n)}}let O=new Set;for(let e of _){let t=e.projectSkillPath?.(r);!t||O.has(t)||(O.add(t),w.push(se(e,r)))}let ie=!v&&f!==null&&ya(f)?_.filter(e=>!e.projectConfigPath).map(e=>e.label):void 0,ae=v?[]:x.map(e=>Ra(e,r)).filter(e=>e!==void 0).filter(e=>!D.has(e.path)),oe=x.some(e=>e.id===`claude`)&&!v?Na(r,s):void 0,ce=e.installUserSkill??y,A=e.home??xe(),ue=Ta(e.skills),M=!1,N=!1,de=!1,P=!1;for(let t of E){let n=ue.has(t);if(await T(A,S[t],n).catch(()=>{}),n){M=!0;let n=await ce({home:e.home,bundleId:t,force:!0});n===`installed`?N=!0:n===`failed`?de=!0:P=!0}else try{le(A,t)}catch{}}let fe=de?`failed`:N?`installed`:M&&P?`skip-current`:`declined`,I=v?`skipped-flag`:`skipped-missing`,pe=C.find(e=>e.editorId===`claude`)??C[0]??{action:I,configPath:k.claude.configPath(r,e.home)},me=await Wa({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:C,projectSkills:w,legacyProjectConfigs:ae,launchJson:oe,skillInstall:fe,didGitInit:c.didInit,rootGitignoreCreated:d,gitRootPromoted:n.gitRootPromoted,promotedFromDir:a,contentDir:u?o:void 0,contentDirRequested:e.contentDir,contentScaffoldFailed:!1,mcpAction:pe.action,mcpPath:pe.configPath,mcpError:`error`in pe?pe.error:void 0,projectScopeUnsupportedLabels:ie,sharing:me}}async function Wa(e){let{projectRoot:t,desiredMode:n,explicitFlag:r}=e,i=An(t);if(i===`no-git`)return{kind:`no-exclude`,reason:`no-git`,localOnlyRequested:r===`local-only`};let a=Dn(t);if(n===`local-only`){let e=On(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`}:Ga(t,e,`add`)}if(i===`shared`)return{kind:`applied`,mode:`shared`,action:`noop`,appended:[],alreadyPresent:[],removed:[]};let o=kn(t,a);return o.kind===`no-exclude`?{kind:`no-exclude`,reason:o.reason,localOnlyRequested:!1}:Ga(t,o,`remove`)}function Ga(e,t,n){let r=An(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 Ka(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 qa(e,t){let n=[],r=e.editors.some(e=>e.action===`written`||e.action===`overwritten`),i=e.editors.some(e=>e.action===`failed`)||e.projectSkills.some(e=>e.action===`failed`),a=e.editors.length>0&&e.editors.every(e=>e.action===`skipped-flag`),o=e.editors.length>0&&e.editors.every(e=>e.action===`skipped-missing`),s=e=>{let n=e.configPath.startsWith(t)?z(t,e.configPath):e.configPath;switch(e.action){case`created`:return` app preview server ${n} configured for Claude Code Desktop embedded browser`;case`merged`:return` app preview server ${n} updated for Claude Code Desktop embedded browser`;case`failed`:return` app preview server ${n} FAILED: ${e.error}`}};e.didGitInit&&n.push(`Initialized git repo at ${t}/.git/ (default branch: main)`),e.rootGitignoreCreated&&n.push(`Seeded .gitignore at ${t}/.gitignore (.DS_Store)`);let c=R(t,`.ok`);if(e.contentCreated.length>0||e.contentUpdated.length>0?(n.push(I(`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(I(`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(I(`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(I(`MCP server configuration:`)),n.push(` No supported editor config directories detected; skipped MCP registration`);else{n.push(I(`MCP server configuration:`));for(let r of e.editors){let i=r.configPath.startsWith(t)?z(t,r.configPath):r.configPath.replace(/^\/Users\/[^/]+/,`~`),a=r.serverName===`open-knowledge`?``:` (${r.serverName})`,o=r.configScope===`project`?` (project)`:``,c=`${r.label}${o}`,l=` `.repeat(Math.max(1,20-c.length)),u=r.editorId===`claude-desktop`&&(r.action===`written`||r.action===`overwritten`)?` — quit and relaunch Claude Desktop to activate`:``;switch(r.action){case`written`:n.push(` ${c}${l}${i} ${P(`registered`)}${a}${u}`);break;case`overwritten`:n.push(` ${c}${l}${i} ${P(`updated`)}${a}${u}`);break;case`skipped-missing`:n.push(` ${c}${l}${i} config root missing; skipped`);break;case`failed`:n.push(` ${c}${l}${i} ${fe(`FAILED`)}: ${r.error}`);break;case`declined`:n.push(` ${c}${l}${i} left unchanged (${Ka(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(I(`Project-local skills:`));for(let r of e.projectSkills){let e=`${r.label} (project)`,i=` `.repeat(Math.max(1,20-e.length)),a=r.path?z(t,r.path):``;switch(r.action){case`written`:n.push(` ${e}${i}${a} ${P(`installed`)}`);break;case`overwritten`:n.push(` ${e}${i}${a} ${P(`updated`)}`);break;case`skipped-unsupported`:n.push(` ${e}${i}no known project skill surface; skipped`);break;case`failed`:n.push(` ${e}${i}${a} ${fe(`FAILED`)}: ${r.error}`);break}}}if(i&&(n.push(``),n.push(`For failed editors, add the MCP server entry or project skill manually. See:`),n.push(` https://github.com/inkeep/open-knowledge#mcp-setup`)),e.legacyProjectConfigs.length>0){n.push(``),n.push(`Project MCP configs found:`);for(let r of e.legacyProjectConfigs)n.push(` ${r.label} ${z(t,r.path)}`);n.push(` These project-local files may override the global config. Remove them if you want fully user-scoped MCP setup in this project.`)}if(e.skillInstall)switch(n.push(``),n.push(I(`User-global skill:`)),e.skillInstall){case`installed`:n.push(` open-knowledge ${P(`installed to detected agent hosts`)} via \`npx skills\``);break;case`skip-current`:n.push(` open-knowledge ${P(`already installed at current version`)}`);break;case`declined`:n.push(` open-knowledge ${de(`skipped (opted out via --no-skills)`)}`);break;case`failed`:n.push(` ${F(`open-knowledge install failed — MCP still configured; run manually:`)}`),n.push(` ${F(` 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(F(`⚠ --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(F(`⚠ 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(pe(e.preview,t))):e.previewWarning&&(n.push(``),n.push(`Content preview unavailable: ${e.previewWarning}`)),n.push(``),n.push(...Qa(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(`${P(`✓`)} ${I(`Next steps:`)}`),n.push(` 1. Open your editor (${N(r.join(` / `))})`),n.push(` 2. Approve the MCP server when prompted`),n.push(` 3. (Optional) scaffold the starter knowledge-base structure:`),n.push(` - ${N(`ok seed`)} — empty repo, Karpathy 3-layer`),n.push(` - ${N(`mcp__open-knowledge__discover`)} — existing repo, extract conventions`),n.push(` 4. Use the MCP workflow tools as you build the wiki:`),n.push(` - ${N(`mcp__open-knowledge__ingest`)} — capture an external source`),n.push(` - ${N(`mcp__open-knowledge__research`)} — gather sources and write findings`),n.push(` - ${N(`mcp__open-knowledge__consolidate`)} — promote research to canonical articles`)}return n.join(`
|
|
657
657
|
`)}function Ja(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 Ya(e,t){let n=[];for(let r of re)Pa(k[r],e,t)&&n.push(r);return n}function Xa(){let e={log:console.log,info:console.info,debug:console.debug},t=(...e)=>{process.stderr.write(`${e.map(e=>typeof e==`string`?e:ke(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 Za(){return new O(`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 D(`--scope <scope>`,`Write MCP config at user level, project level, or both`).choices([`user`,`project`,`both`])).addOption(new D(`--shared`,`Commit OK config alongside content (the default for fresh repos)`).conflicts(`localOnly`)).addOption(new D(`--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?Xa():null;try{let r;try{r=await Ua({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 p||e instanceof g){process.stderr.write(`${e.message}\n`),process.exitCode=78;return}if(e instanceof h){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.
|
|
658
|
-
`),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-
|
|
658
|
+
`),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-B001Pjdw.mjs`),{resolveContentDir:s}=await import(`./dist-CZ4COUHS.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-BZSWO0Y0.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(Ja(r,{contentDir:i,contentFileCount:a}),null,2)}\n`):process.stdout.write(`${qa(r,r.projectRoot)}\n`),(r.editors.some(e=>e.action===`failed`)||r.mcpAction===`failed`)&&(process.exitCode=1)}finally{r?.()}})}function Qa(e,t){let n=[];switch(e.kind){case`applied`:return n.push(I(`Sharing mode:`)),e.mode===`local-only`?e.action===`added`?n.push(` ${P(`local-only`)} — appended ${e.appended.length} path(s) to ${I(`${t}/.git/info/exclude`)} (per-clone, not committed).`):e.action===`noop`&&e.alreadyPresent.length>0?n.push(` ${P(`local-only`)} — already excluded; nothing to do.`):n.push(` ${P(`local-only`)}`):e.action===`removed`?n.push(` ${P(`shared`)} — removed OK paths from ${I(`${t}/.git/info/exclude`)}; commit the files to share with teammates.`):n.push(` ${P(`shared`)} — OK config will be committed alongside content.`),n;case`refused-tracked`:n.push(F(`Sharing mode: switch to local-only deferred`));for(let t of e.remediation.split(`
|
|
659
659
|
`))n.push(t.length>0?` ${t}`:``);return n.push(` Re-run ${N(`ok config-sharing unshare`)} after resolving to complete the switch.`),n;case`no-exclude`:if(e.localOnlyRequested)n.push(F(`Sharing mode: --local-only requested but no git repo found — option ignored`)),n.push(` Run ${N(`git init`)} (or open this folder via OK Desktop, which can scaffold a repo) and then ${N(`ok config-sharing unshare`)}.`);else if(e.reason===`no-git`)return[];else n.push(F(`Sharing mode unavailable: ${e.reason}.`));return n}}export{yr as A,kn as B,za as C,_i as D,Si as E,Nn as F,_t as G,pn as H,jn as I,G as K,Dn as L,mr as M,pr as N,kr as O,On as P,Mn as R,Fa as S,Ri as T,xt as U,En as V,vt as W,Ea as _,Ma as a,Na as b,Ja as c,qa as d,Qa as f,xa as g,Ta as h,ja as i,xr as j,br as k,Ha as l,Ba as m,ka as n,Ia as o,Za as p,Ge as q,Aa as r,Wa as s,wa as t,Ya as u,Ca as v,na as w,pa as x,Ua as y,An as z};
|
|
660
|
-
//# sourceMappingURL=init-
|
|
660
|
+
//# sourceMappingURL=init-BwsVFj6d.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{y as e}from"./init-BwsVFj6d.mjs";export{e as runInit};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{n as e}from"./loader-BAIfIvBS.mjs";export{e as loadConfig};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{$a as e,Wo as t,Xa as n,Ya as r}from"./server-lock-iLcBw_q0-CdrK5Xfo.mjs";import{_ as i,ga as a,ha as o}from"./dist-
|
|
1
|
+
import{$a as e,Wo as t,Xa as n,Ya as r}from"./server-lock-iLcBw_q0-CdrK5Xfo.mjs";import{_ as i,ga as a,ha as o}from"./dist-CdVqgoPq.mjs";import{t as s}from"./constants-CVwzJpO0.mjs";import{t as c}from"./is-object-Cg453afR.mjs";import{resolve as l}from"node:path";import{existsSync as u,readFileSync as d}from"node:fs";import{realpath as f}from"node:fs/promises";async function p(e){let t=l(e);try{return await f(t)}catch(e){if(e.code!==`ENOENT`){let n=e instanceof Error?e.message:String(e);console.warn(`[normalize-cwd] realpath failed for ${t}: ${n}`)}return t}}var m=t();function h(e,t){let n={...e};for(let r of Object.keys(t)){let i=e[r],a=t[r];c(a)&&c(i)?n[r]=h(i,a):a!==void 0&&(n[r]=a)}return n}function g(e){if(!u(e))return{value:null,path:e,source:null,doc:null};let t;try{t=d(e,`utf-8`)}catch(t){return console.warn(`[config] Failed to read ${e}: ${t instanceof Error?t.message:t}`),{value:null,path:e,source:null,doc:null}}let n=(0,m.parseDocument)(t);if(n.errors.length>0)return console.warn(`[config] Failed to parse ${e}: ${n.errors.map(e=>e.message).join(`; `)}`),{value:null,path:e,source:t,doc:null};let r=n.toJSON();return c(r)?{value:r,path:e,source:t,doc:n}:{value:null,path:e,source:t,doc:n}}function _(t,n){return t.map(t=>{let r=t.path.map(e=>typeof e==`symbol`?String(e):e),i={path:r,message:t.message,issueCode:t.code};if(n.doc!==null&&n.source!==null){let t=e({file:n.path,source:n.source,doc:n.doc,path:r});if(t!==void 0)return{...i,source:t}}return i})}function v(e){let t=e??process.cwd(),c=[],u=a(`user`,t),d=o({absPath:u}),f={};d.valid&&d.source!==void 0?(f=h(f,d.value),c.push(u)):d.valid;let p=l(t,`.ok`,s),m=g(p);if(m.value!==null){let e=r({value:m.value,file:m.path,source:m.source,doc:m.doc});if(e.length>0)throw Error(e.map(n).join(`
|
|
2
2
|
|
|
3
3
|
`));f=h(f,m.value),c.push(p)}let v=i.safeParse(f);if(!v.success){let e={code:`SCHEMA_INVALID`,issues:_(v.error.issues,m)};throw Error(n(e))}return{config:v.data,sources:c}}function y(e){let t=e.cacheMs??1e3,n=e.loadConfigFn??v,r=new Map,i=new Map,a=p(e.startupCwd);return async o=>{let s=await p(o??e.startupCwd),c=Date.now(),l=r.get(s);if(l&&l.expiresAt>c)return l.config;let u=i.get(s);if(u)return await u;let d=(async()=>{if(s===await a)return r.set(s,{config:e.startupConfig,expiresAt:Date.now()+t}),e.startupConfig;let i=n(s).config;return r.set(s,{config:i,expiresAt:Date.now()+t}),i})();i.set(s,d);try{return await d}finally{i.delete(s)}}}export{v as n,y as t};
|
|
4
|
-
//# sourceMappingURL=loader-
|
|
4
|
+
//# sourceMappingURL=loader-BAIfIvBS.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{n as e,t}from"./preview-CeZQltbU.mjs";export{t as formatPreviewBlock,e as previewContent};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{Yt as e}from"./dist-
|
|
1
|
+
import{Yt as e}from"./dist-CdVqgoPq.mjs";import"./constants-CVwzJpO0.mjs";import{join as t,relative as n}from"node:path";import{existsSync as r,lstatSync as i,readdirSync as a,realpathSync as o,statSync as s}from"node:fs";function c(r){let{projectDir:c,contentDir:l,sampleCap:u=5}=r,d=[],f=[];try{i(l)}catch(e){return{totalCount:0,sample:[],contentDir:l,warnings:[`cannot access content directory ${l}: ${e instanceof Error?e.message:String(e)}`]}}let p;try{p=e({projectDir:c,contentDir:l})}catch(e){return{totalCount:0,sample:[],contentDir:l,warnings:[e instanceof Error?e.message:String(e)]}}function m(e){let r;try{r=a(e,{withFileTypes:!0})}catch(t){let r=t instanceof Error?t.message:String(t);d.push(`could not read directory ${n(l,e)||`.`}: ${r}`);return}for(let i of r){let r=t(e,i.name);if(i.isSymbolicLink()){let e;try{e=o(r)}catch(e){let t=e.code;t===`ENOENT`||t===`ELOOP`?d.push(`broken or cyclic symlink: ${n(l,r)}`):d.push(`cannot resolve symlink ${n(l,r)}: ${t??`unknown error`}`);continue}let t;try{t=s(e)}catch{continue}if(t.isDirectory()){let e=n(l,r);if(p.isDirExcluded(e))continue;m(r)}else if(t.isFile()){let e=n(l,r);if(p.isExcluded(e))continue;f.push(e)}}else if(i.isDirectory()){let e=n(l,r);if(p.isDirExcluded(e))continue;m(r)}else if(i.isFile()){let e=n(l,r);if(p.isExcluded(e))continue;f.push(e)}}}return m(l),{totalCount:f.length,sample:f.slice(0,u),contentDir:l,warnings:d}}function l(e,i){let a=[],o=n(i,e.contentDir),s=o===``?`./`:`./${o}`;if(a.push(`Content:`),a.push(` Found ${e.totalCount} markdown files in ${s}`),e.sample.length>0){let t=e.sample.join(`, `),n=e.totalCount>e.sample.length?`, …`:``;a.push(` Sample: ${t}${n}`)}if(e.warnings.length>0)for(let t of e.warnings)a.push(` Warning: ${t}`);return a.push(``),r(t(i,`.ok`,`config.yml`))?(a.push(` To adjust scope, add patterns to .okignore at the project root.`),a.push(` To change the content root, edit .ok/config.yml → content.dir.`)):a.push(" Run `open-knowledge init` to scaffold config + .okignore."),a.push(``),a.push(` Re-check anytime: open-knowledge preview`),a.join(`
|
|
2
2
|
`)}export{c as n,l as t};
|
|
3
|
-
//# sourceMappingURL=preview-
|
|
3
|
+
//# sourceMappingURL=preview-CeZQltbU.mjs.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{b as e,r as t}from"./init-
|
|
2
|
-
//# sourceMappingURL=repair-launch-json-
|
|
1
|
+
import{b as e,r as t}from"./init-BwsVFj6d.mjs";import{t as n}from"./is-object-Cg453afR.mjs";import{join as r}from"node:path";import{existsSync as i,readFileSync as a}from"node:fs";const o=[[`@inkeep/open-knowledge`,`ui`],[`-y`,`@inkeep/open-knowledge`,`ui`],t];function s(e){if(e.runtimeExecutable===`/bin/sh`&&Array.isArray(e.runtimeArgs)){let t=e.runtimeArgs[2];if(typeof t==`string`){if(t.includes(`# ok-ui-v1`))return`canonical`;if(/# ok-ui-v\d+/.test(t))return`legacy-bare`}return`preserved`}if(e.runtimeExecutable===`npx`&&Array.isArray(e.runtimeArgs)){for(let t of o)if(c(e.runtimeArgs,t))return`legacy-bare`}return`preserved`}function c(e,t){if(e.length!==t.length)return!1;for(let n=0;n<t.length;n++)if(e[n]!==t[n])return!1;return!0}function l(t){let o=t.logger??u,c=r(t.projectDir,`.claude`,`launch.json`);if(t.reclaimDisableEnv===`1`)return o({event:`launch-json-repair-skipped`,reason:`reclaim-disabled`}),{outcome:{configPath:c,outcome:`skipped-reclaim-disabled`},repairedCount:0};if(!i(c))return{outcome:{configPath:c,outcome:`no-file`},repairedCount:0};let l;try{let e=a(c,`utf-8`).trim();l=e?JSON.parse(e):{}}catch(e){let t=e instanceof Error?e.message:String(e);return o({event:`launch-json-repair-read-failed`,configPath:c,error:t}),{outcome:{configPath:c,outcome:`read-failed`,error:t},repairedCount:0}}if(!n(l)){let e=`launch.json root is not an object`;return o({event:`launch-json-repair-read-failed`,configPath:c,error:e}),{outcome:{configPath:c,outcome:`read-failed`,error:e},repairedCount:0}}let d=l.configurations;if(!Array.isArray(d))return{outcome:{configPath:c,outcome:`no-entry`},repairedCount:0};let f=d.find(e=>n(e)&&e.name===`open-knowledge-ui`);if(!f)return{outcome:{configPath:c,outcome:`no-entry`},repairedCount:0};let p=s(f);if(p===`canonical`)return{outcome:{configPath:c,outcome:`canonical`},repairedCount:0};if(p===`preserved`)return{outcome:{configPath:c,outcome:`preserved`},repairedCount:0};let m=e(t.projectDir,{mode:`published`});if(m.action===`failed`){let e=m.error??`unknown write failure`;return o({event:`launch-json-repair-write-failed`,configPath:c,error:e}),{outcome:{configPath:c,outcome:`write-failed`,error:e},repairedCount:0}}return o({event:`launch-json-repair-applied`,configPath:c}),{outcome:{configPath:c,outcome:`repaired`},repairedCount:1}}function u(e){process.stderr.write(`${JSON.stringify(e)}\n`)}export{l as repairLaunchJson};
|
|
2
|
+
//# sourceMappingURL=repair-launch-json-jEfxfrXs.mjs.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{S as e,m as t}from"./init-
|
|
2
|
-
//# sourceMappingURL=repair-mcp-configs-
|
|
1
|
+
import{S as e,m as t}from"./init-BwsVFj6d.mjs";import{a as n,h as r,l as i}from"./write-project-skill-BEzL3S1a.mjs";import{t as a}from"./mcp-migrate-event-D0NrGjvc.mjs";import{homedir as o}from"node:os";function s(e){let t=e.logger??u,r=e.home??o(),a=[];if(e.reclaimDisableEnv===`1`)return t({event:`mcp-config-repair-skipped`,reason:`reclaim-disabled`}),{outcomes:a,repairedCount:0};for(let o of n){let n=i[o],s=c(()=>n.configPath(``,r));if(s!==null&&a.push(l({scope:`user`,editorId:o,target:n,home:r,cwd:``,configPath:s,configPathOverride:void 0,logger:t})),n.projectConfigPath){let r=n.projectConfigPath,i=c(()=>r(e.projectDir));i!==null&&a.push(l({scope:`project`,editorId:o,target:n,home:void 0,cwd:e.projectDir,configPath:i,configPathOverride:i,logger:t}))}}return{outcomes:a,repairedCount:a.filter(e=>e.outcome===`repaired`).length}}function c(e){try{return e()}catch{return null}}function l(n){let i={scope:n.scope,editorId:n.editorId,configPath:n.configPath},o=t(n.target,n.cwd,n.home,n.configPathOverride);if(o===null)return{...i,outcome:`no-entry`};if(r(o))return{...i,outcome:`canonical`};n.logger(a({scope:n.scope,surface:`cli-repair`,editorId:n.editorId,configPath:n.configPath,priorEntry:o}));let s=e(n.target,n.cwd,{mode:`published`,skipAvailabilityCheck:!0},n.home,n.configPathOverride);if(s.action===`failed`){let e=s.error??`unknown write failure`;return n.logger({event:`mcp-config-repair-write-failed`,scope:n.scope,editorId:n.editorId,configPath:n.configPath,error:e}),{...i,outcome:`write-failed`,error:e}}return s.action===`declined`?(n.logger({event:`mcp-config-repair-declined`,scope:n.scope,editorId:n.editorId,configPath:n.configPath,reason:s.declineReason}),{...i,outcome:`declined`}):{...i,outcome:`repaired`}}function u(e){process.stderr.write(`${JSON.stringify(e)}\n`)}export{s as repairMcpConfigs};
|
|
2
|
+
//# sourceMappingURL=repair-mcp-configs-Dtldp8WO.mjs.map
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{la as e}from"./server-lock-iLcBw_q0-CdrK5Xfo.mjs";import{Jr as t,Lr as n,Wr as r,d as i,ei as a,na as o,oa as s,ut as c,zr as l}from"./dist-
|
|
1
|
+
import{la as e}from"./server-lock-iLcBw_q0-CdrK5Xfo.mjs";import{Jr as t,Lr as n,Wr as r,d as i,ei as a,na as o,oa as s,ut as c,zr as l}from"./dist-CdVqgoPq.mjs";import{t as u}from"./esm-CsQUg9js.mjs";import{l as d,r as f,t as p,u as m}from"./write-project-skill-BEzL3S1a.mjs";import{dirname as h,join as g,resolve as _}from"node:path";import{homedir as v}from"node:os";import{existsSync as y,mkdirSync as b,readFileSync as x,readdirSync as S,rmSync as C,statSync as w,writeFileSync as T}from"node:fs";const E={existsSync:e=>y(e),isDirectory:e=>{try{return w(e).isDirectory()}catch(e){if(e.code===`ENOENT`)return!1;throw e}},readdirSync:e=>S(e),readFileSync:e=>x(e),writeFileSync:(e,t)=>{T(e,t)},mkdirSync:(e,t)=>{b(e,t)},rmSync:(e,t)=>{C(e,t)}},D={resolveProjectBundledSkillDir:()=>a(`project`,{checkDesktop:!1}),resolveUserBundledSkillDir:e=>a(e,{checkDesktop:!1}),readBundledVersion:()=>l(),readRecordedVersion:e=>r(e,`cli-hosts`),writeRecordedVersion:(e,t)=>s(e,`cli-hosts`,t,`cli-start`),recordEvent:e=>t(e),readBundleDecision:(e,t)=>n(e,t),writeBundleDecision:(e,t,n)=>o(e,t,n),removeBundleFromDisk:(e,t)=>f(e,t)};function O(e){process.stderr.write(`${JSON.stringify(e)}\n`)}function k(e,t,n){n.rmSync(t,{recursive:!0,force:!0}),n.mkdirSync(h(t),{recursive:!0}),A(e,t,n)}function A(e,t,n){n.mkdirSync(t,{recursive:!0});for(let r of n.readdirSync(e)){let i=g(e,r),a=g(t,r);n.isDirectory(i)?A(i,a,n):n.writeFileSync(a,n.readFileSync(i))}}function j(e,t,n,r,i,a){let o=[],s=g(e,`.agents`,`skills`,t),c=r.existsSync(s),l=!1;try{k(n,s,r),l=!0,o.push({kind:`central`,path:s,outcome:c?`overwritten`:`written`}),i({event:`user-skill-reclaim-central-written`,scope:`user`,path:s,preexisting:c,version:a})}catch(e){let t=e instanceof Error?e.message:String(e);o.push({kind:`central`,path:s,outcome:`failed`,error:t}),i({event:`user-skill-reclaim-central-failed`,scope:`user`,path:s,error:t})}for(let c of m){let l=g(e,c.hostDir),u=g(l,`skills`,t);if(u===s){o.push({kind:`host`,editorId:c.editorId,hostDir:c.hostDir,path:u,outcome:`skipped-collapsed-with-central`});continue}if(!r.existsSync(l)){o.push({kind:`host`,editorId:c.editorId,hostDir:c.hostDir,path:u,outcome:`skipped-host-absent`});continue}let d=r.existsSync(u);try{k(n,u,r),o.push({kind:`host`,editorId:c.editorId,hostDir:c.hostDir,path:u,outcome:d?`overwritten`:`written`}),i({event:`user-skill-reclaim-host-written`,scope:`user`,editorId:c.editorId,hostDir:c.hostDir,path:u,preexisting:d,version:a})}catch(e){let t=e instanceof Error?e.message:String(e);o.push({kind:`host`,editorId:c.editorId,hostDir:c.hostDir,path:u,outcome:`failed`,error:t}),i({event:`user-skill-reclaim-host-failed`,scope:`user`,editorId:c.editorId,hostDir:c.hostDir,path:u,error:t})}}return{entries:o,centralWritten:l}}function M(e,t){if(!e)return!1;try{if(!t.existsSync(e))return!1;let n=t.readFileSync(e).toString(`utf8`);return n.includes(`# ok-mcp-v1`)||n.includes(`# ok-mcp-win-v1`)}catch{return!1}}function N(e,t,n,r){let i;try{i=t.resolveProjectBundledSkillDir()}catch(e){return r({event:`project-skill-reclaim-bundle-missing`,scope:`project`,error:e instanceof Error?e.message:String(e)}),{outcome:`skipped`,reason:`bundle-missing`}}let a=[];for(let t of m){let o=g(e,t.hostDir,`skills`,`open-knowledge`),s=g(o,`SKILL.md`),c=n.existsSync(s),l=d[t.editorId]?.projectConfigPath?.(e),u=!c&&M(l,n);if(!c&&!u){a.push({editorId:t.editorId,hostDir:t.hostDir,path:o,outcome:`no-token`}),r({event:`project-skill-reclaim-no-token`,scope:`project`,editorId:t.editorId,path:o});continue}try{p(o,e),k(i,o,n);let s=c?`reclaimed`:`created`;a.push({editorId:t.editorId,hostDir:t.hostDir,path:o,outcome:s}),r({event:c?`project-skill-reclaim-reclaimed`:`project-skill-reclaim-created`,scope:`project`,editorId:t.editorId,path:o})}catch(e){let n=e instanceof Error?e.message:String(e);a.push({editorId:t.editorId,hostDir:t.hostDir,path:o,outcome:`failed`,error:n}),r({event:`project-skill-reclaim-failed`,scope:`project`,editorId:t.editorId,path:o,error:n})}}return{outcome:`done`,entries:a}}async function P(t,n,r,a){let o=e=>{n.recordEvent(e).catch(()=>{})},s=()=>new Date().toISOString(),l;try{l=await n.readBundledVersion()}catch(e){let t=e instanceof Error?e.message:String(e);return a({event:`user-skill-reclaim-version-read-failed`,scope:`user`,error:t}),o({ts:s(),surface:`cli-start`,target:`cli-hosts`,bundle:`discovery`,outcome:`failed`,reason:`version-read-failed:${t}`}),{outcome:`skipped`,reason:`version-read-failed`}}let u;try{u=await n.readRecordedVersion(t)}catch(e){a({event:`user-skill-reclaim-version-read-error`,scope:`user`,error:e instanceof Error?e.message:String(e)}),u=null}let d=[],f=null;for(let e of c)try{d.push({id:e,sourceDir:n.resolveUserBundledSkillDir(e)})}catch(e){f=e instanceof Error?e.message:String(e)}if(d.length===0)return a({event:`user-skill-reclaim-bundle-missing`,scope:`user`,error:f??`no user-global bundles`}),o({ts:s(),surface:`cli-start`,target:`cli-hosts`,outcome:`failed`,reason:`bundle-missing:${f}`}),{outcome:`skipped`,reason:`bundle-missing`};let p=[];for(let o of d){let s=i[o.id],c=r.existsSync(g(t,`.agents`,`skills`,s)),l=await n.readBundleDecision(t,s).catch(()=>null);if(!e(l,{installedOnDisk:c})){if(c)try{n.removeBundleFromDisk(t,o.id),a({event:`user-skill-reclaim-bundle-declined-removed`,scope:`user`,bundle:o.id})}catch(e){a({event:`user-skill-reclaim-bundle-remove-failed`,scope:`user`,bundle:o.id,error:e instanceof Error?e.message:String(e)})}continue}if(l===null&&c)try{await n.writeBundleDecision(t,s,!0)}catch(e){a({event:`user-skill-reclaim-grandfather-write-failed`,scope:`user`,bundle:o.id,error:e instanceof Error?e.message:String(e)})}p.push(o)}if(p.length===0)return{outcome:`skipped`,reason:`all-bundles-declined`};let m=p.every(e=>r.existsSync(g(t,`.agents`,`skills`,i[e.id])));if(u!==null&&u===l&&m)return a({event:`user-skill-reclaim-skipped-version-current`,scope:`user`,version:l}),{outcome:`skipped`,reason:`version-current`};let h=[],_=d.length===c.length,v=!0;for(let{id:e,sourceDir:n}of p){let o=j(t,i[e],n,r,a,l);h.push(...o.entries),o.centralWritten||(v=!1)}let y=h.some(e=>e.kind===`central`&&(e.outcome===`written`||e.outcome===`overwritten`));if(_&&v&&y){let e=null;try{await n.writeRecordedVersion(t,l),a({event:`user-skill-reclaim-version-recorded`,scope:`user`,version:l})}catch(t){e=t instanceof Error?t.message:String(t),a({event:`user-skill-reclaim-version-record-failed`,scope:`user`,version:l,error:e})}for(let{id:t}of p)o({ts:s(),surface:`cli-start`,target:`cli-hosts`,bundle:t,outcome:e===null?`installed`:`failed`,version:l,...e===null?{}:{reason:`state-write-failed:${e}`}})}else{let e=h.some(e=>e.kind===`host`&&e.outcome===`failed`);o({ts:s(),surface:`cli-start`,target:`cli-hosts`,outcome:`failed`,version:l,reason:e?`all-writes-failed`:`no-hosts-installed`})}return{outcome:`done`,version:l,entries:h}}async function F(e){let t=e.logger??O,n=e.fs??E,r=e.home??v(),i={...D,...e.deps};return e.reclaimDisableEnv===`1`?(t({event:`skill-repair-skipped`,reason:`reclaim-disabled`}),{status:`skipped`,reason:`reclaim-disabled`}):{status:`done`,project:N(e.projectDir,i,n,t),user:await P(r,i,n,t)}}function I(e){return e.status===`skipped`?e.reason===`reclaim-disabled`?0:1:e.project.outcome===`skipped`||e.user.outcome===`skipped`&&e.user.reason!==`version-current`&&e.user.reason!==`all-bundles-declined`||e.project.entries.some(e=>e.outcome===`failed`)||e.user.outcome===`done`&&e.user.entries.some(e=>e.outcome===`failed`)?1:0}function L(e){if(e.status===`skipped`)return`Skipped: ${e.reason}`;let t=[`Skill reclaim complete.`];if(e.project.outcome===`done`){let n=e.project.entries.filter(e=>e.outcome===`reclaimed`).length,r=e.project.entries.filter(e=>e.outcome===`created`).length,i=e.project.entries.filter(e=>e.outcome===`no-token`).length,a=e.project.entries.filter(e=>e.outcome===`failed`).length;t.push(` Project: ${n} reclaimed, ${r} created, ${i} no-token, ${a} failed.`)}else t.push(` Project: skipped (${e.project.reason}).`);if(e.user.outcome===`done`){let n=e.user.entries.filter(e=>e.outcome===`written`||e.outcome===`overwritten`).length,r=e.user.entries.filter(e=>e.outcome===`skipped-host-absent`||e.outcome===`skipped-collapsed-with-central`).length,i=e.user.entries.filter(e=>e.outcome===`failed`).length;t.push(` User (${e.user.version}): ${n} written, ${r} skipped, ${i} failed.`)}else t.push(` User: skipped (${e.user.reason}).`);return t.join(`
|
|
2
2
|
`)}function R(){return new u(`repair-skills`).description("Refresh bundled SKILL.md files for installed AI editors (project-local + user-global). Runs automatically during `ok start`; this command forces an explicit sweep.").action(async()=>{let e=await F({projectDir:_(process.cwd()),reclaimDisableEnv:process.env.OK_RECLAIM_DISABLE??null});process.stdout.write(`${L(e)}\n`),process.exitCode=I(e)})}export{R as n,F as t};
|
|
3
|
-
//# sourceMappingURL=repair-skills-
|
|
3
|
+
//# sourceMappingURL=repair-skills-D7TJAZll.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{t as e}from"./repair-skills-D7TJAZll.mjs";export{e as repairSkills};
|
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import{s as e}from"./chunk-C94x7I9S.mjs";import{c as t,l as n,s as r,u as i}from"./server-lock-iLcBw_q0-CdrK5Xfo.mjs";import{Mr as a,Nr as o,Tn as s,ii as c,ma as l,pn as u,xn as d}from"./dist-
|
|
1
|
+
import{s as e}from"./chunk-C94x7I9S.mjs";import{c as t,l as n,s as r,u as i}from"./server-lock-iLcBw_q0-CdrK5Xfo.mjs";import{Mr as a,Nr as o,Tn as s,ii as c,ma as l,pn as u,xn as d}from"./dist-CdVqgoPq.mjs";import{t as f}from"./esm-CsQUg9js.mjs";import"./gh-detect-KLjG6xCR.mjs";import{A as ee,D as p,S as m,T as h,b as te,j as g,k as _,l as v,x as y}from"./init-BwsVFj6d.mjs";import{g as ne,h as re,l as ie,n as ae}from"./write-project-skill-BEzL3S1a.mjs";import"./loader-BAIfIvBS.mjs";import{c as oe}from"./colors-8SzMRIVy.mjs";import"./preview-CeZQltbU.mjs";import{dirname as se,isAbsolute as b,join as x,relative as S,resolve as C}from"node:path";import{hostname as w}from"node:os";import{existsSync as T,lstatSync as E,readFileSync as D,readlinkSync as ce,rmSync as le,statSync as ue}from"node:fs";import{readFile as O,realpath as k}from"node:fs/promises";function A(e,a,o={}){let s=i(e,a);if(!T(s))return{status:`missing`,lockPath:s};let c;try{c=JSON.parse(D(s,`utf-8`))}catch{return{status:`corrupt`,lockPath:s}}if(!c||typeof c!=`object`||!n(c.pid))return{status:`corrupt`,lockPath:s};let l=c;if(!(o.isAlive??t)(l.pid))return{status:`dead-pid`,lockPath:s,lock:l};if(typeof l.machineId==`string`)return l.machineId===(o.machineId??r())?{status:`alive`,lockPath:s,lock:l}:{status:`foreign-host`,lockPath:s,lock:l};let u=o.host??w();return l.hostname===u?{status:`alive`,lockPath:s,lock:l}:{status:`foreign-host`,lockPath:s,lock:l}}function j(e){return e.replace(/:\d+$/,``)}function M(e){let t=e.trim();if(!t)return null;{let e=/^https?:\/\/([^/?#]+)\/([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?\/?$/.exec(t);if(e)return{protocol:`https`,hostname:j(e[1]),owner:e[2],name:e[3]}}{let e=/^ssh:\/\/(?:[\w.-]+@)?([^/?#]+)\/([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?\/?$/.exec(t);if(e)return{protocol:`ssh`,hostname:j(e[1]),owner:e[2],name:e[3]}}{let e=/^git:\/\/([^/?#]+)\/([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?\/?$/.exec(t);if(e)return{protocol:`git`,hostname:j(e[1]),owner:e[2],name:e[3]}}{let e=/^(?:[\w.-]+@)?([\w.-]+):([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?$/.exec(t);if(e?.[1].includes(`.`)||e&&t.startsWith(`git@`))return{protocol:`ssh`,hostname:e[1],owner:e[2],name:e[3]}}{let e=/^git:([\w.-]+)\/([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?\/?$/.exec(t);if(e)return{protocol:`git`,hostname:e[1],owner:e[2],name:e[3]}}if(!t.includes(`://`)&&!t.includes(`@`)&&!t.startsWith(`/`)){let e=/^([\w.-]+)\/([\w.\-~%]+?)(?:\.git)?$/.exec(t);if(e)return{protocol:`https`,hostname:`github.com`,owner:e[1],name:e[2]}}return null}function N(e){let t;try{t=new URL(e)}catch{return null}if(t.hostname!==`github.com`&&t.hostname!==`www.github.com`)return null;let n=t.pathname.split(`/`).filter(e=>e.length>0);if(n.length<5||n[2]!==`blob`)return null;let r,i,a,o;try{r=decodeURIComponent(n[0]),i=decodeURIComponent(n[1]),a=decodeURIComponent(n[3]),o=n.slice(4).map(e=>decodeURIComponent(e))}catch{return null}return!r||!i||!a||o.length===0||o.some(e=>e.length===0)?null:{owner:r,repo:i,branch:a,path:o.join(`/`)}}function P(e){let t;try{t=new URL(e)}catch{return null}if(t.hostname!==`github.com`&&t.hostname!==`www.github.com`)return null;let n=t.pathname.split(`/`);if(n.length<5||n[0]!==``||n[3]!==`tree`)return null;let r=n.slice(5);r.length===1&&r[0]===``&&r.pop();let i,a,o,s;try{i=decodeURIComponent(n[1]),a=decodeURIComponent(n[2]),o=decodeURIComponent(n[4]),s=r.map(e=>decodeURIComponent(e))}catch{return null}return!i||!a||!o||s.some(e=>e.length===0)?null:{owner:i,repo:a,branch:o,path:s.join(`/`)}}function F(e){let t=N(e);if(t)return{kind:`doc`,...t};let n=P(e);return n?{kind:`folder`,...n}:null}const I=`# >>> open-knowledge cli >>>`,L=`# <<< open-knowledge cli <<<`,R=/^# >>> open-knowledge cli >>>\n[\s\S]*?^# <<< open-knowledge cli <<<\n?/m;function z(e){return x(e,`Library`,`Application Support`,`OpenKnowledge`,`path-install.json`)}const B={existsSync:e=>T(e),readFileSync:(e,t)=>D(e,t),lstatSync:e=>E(e),readlinkSync:e=>ce(e)};function V(e,t=B){let n=z(e);if(!t.existsSync(n))return null;try{let e=JSON.parse(t.readFileSync(n,`utf8`));return e?.version===1?e:null}catch{return null}}function H(e){let t=e.replace(R,``);return{text:t,changed:t!==e,emptyAfter:t.trim()===``}}function U(e,t,n=B){try{return n.lstatSync(e).isSymbolicLink()?n.readlinkSync(e)===t:!1}catch{return!1}}function de(e){return re(e)||ne(e)||p(e)}function fe(e,t,n,r){let i=v(e,t,n,r);if(i.kind===`absent`||i.kind===`no-entry`)return{kind:`not-present`};if(i.kind===`decline`)return{kind:`declined`,reason:i.reason};if(!de(i.entry))return{kind:`left-foreign`};let a;try{a=r??e.configPath(t,n)}catch{return{kind:`not-present`}}let o=e.serverName(t);return e.format===`file`?(le(a,{force:!0}),{kind:`removed`}):e.format===`toml`?me(a,o):pe(a,e.topLevelKey,e.serverMapSubKey,o)}function pe(e,t,n,r){let i;try{i=D(e,`utf-8`)}catch{return{kind:`declined`,reason:`unparseable`}}if(Buffer.byteLength(i,`utf-8`)>10485760)return{kind:`declined`,reason:`oversize`};let{text:a,changed:o}=g(i,y(t,n,r));return o?(l(e,a,{mode:_(e)}),{kind:`removed`}):{kind:`not-present`}}function me(e,t){let n=h();if(n.backend===`fallback`)return{kind:`declined`,reason:`no-native-writer`};let r;try{r=D(e,`utf-8`)}catch{return{kind:`declined`,reason:`unparseable`}}let i=r.charCodeAt(0)===65279,a=i?r.slice(1):r,o=ee(a),s=a.trim()===``||a.endsWith(`
|
|
2
2
|
`),c;try{c=n.removeEntry(a,t)}catch{return{kind:`declined`,reason:`unparseable`}}if(!c.existed)return{kind:`not-present`};let u=c.text;s?u.endsWith(`
|
|
3
3
|
`)||(u=`${u}\n`):u=u.replace(/\n+$/,``),o&&(u=u.replace(/\r\n/g,`
|
|
4
4
|
`).replace(/\n/g,`\r
|
|
5
5
|
`));let d=`${i?``:``}${u}`;return d!==r&&l(e,d,{mode:_(e)}),{kind:`removed`}}const he=new Set([`start`,`stop`,`status`,`clean`,`ui`,`mcp`,`preview`,`deinit`]);function ge(e,t,n=s){if(e!==void 0&&!he.has(e))return null;let r=n(t);return r===null||r.distance===0?null:r.rootPath}let W=null;function _e(e){W=e}function G(){return W??process.cwd()}var K=e(oe(),1);function ve(e){return e==null?!1:e.includes(`--type=utility`)&&e.includes(`--utility-sub-type=node.mojom.NodeService`)}function ye(e,t=Date.now()){let n=new Date(e).getTime();if(Number.isNaN(n))return`—`;let r=t-n,i=Math.floor(r/1e3);if(i<60)return`${i}s`;let a=Math.floor(i/60);if(a<60)return`${a}m ago`;let o=Math.floor(a/60);return o<24?`${o}h ago`:`${Math.floor(o/24)}d ago`}function be(e,t,n,r,i,a){if(t.status===`missing`||t.status===`corrupt`)return null;let o=t.lock,s=null;if(n.status!==`missing`&&n.status!==`corrupt`){let e=n.lock;s={port:e.port,status:n.status,pid:e.pid,startedAt:e.startedAt,usage:a}}return{directory:o.worktreeRoot,server:{port:o.port,status:t.status,pid:o.pid,startedAt:o.startedAt,usage:i},ui:s,hostname:o.hostname,lockPath:t.lockPath,binary:r==null?null:d(r),command:r,isDesktop:ve(r)}}function xe(e){return e.ui==null?!1:e.ui.status===`alive`||e.ui.status===`foreign-host`}function q(e){let t=e.server.status;return t===`alive`||t===`foreign-host`?e.isDesktop?`desktop`:t===`alive`?`running`:`foreign`:t===`dead-pid`&&xe(e)?`ui-orphan`:`stale`}const Se=new Set([`running`,`desktop`,`foreign`,`ui-orphan`]);function Ce(e){switch(e){case`running`:return K.default.green(e);case`desktop`:return K.default.blue(e);case`foreign`:return K.default.cyan(e);case`ui-orphan`:return K.default.magenta(e);case`stale`:return K.default.yellow(e)}}function J(e){return e==null?`—`:`${e.cpuPercent.toFixed(1)}% / ${e.memPercent.toFixed(1)}%`}function we(e){return`${J(e.server.usage)} | ${J(e.ui?.usage??null)}`}function Te(e){return`${e.server.port===0?`(starting)`:String(e.server.port)} / ${e.ui==null||e.ui.status===`dead-pid`?`—`:String(e.ui.port)}`}function Ee(e){if(e.length===0)return`No open-knowledge servers found.`;let t=[`DIRECTORY`,`PORTS (API/UI)`,`CPU/MEM (API | UI)`,`STATUS`,`PID`,`STARTED`,`BINARY`],n=e.map(e=>{let t=q(e),n=t===`ui-orphan`&&e.ui!=null?e.ui.pid:e.server.pid;return[e.directory,Te(e),we(e),t,String(n),ye(e.server.startedAt),e.binary??`—`]}),r=t.length,i=t.map(e=>e.length);for(let e of n)for(let t=0;t<r;t++)i[t]=Math.max(i[t]??0,(e[t]??``).length);let a=t.map((e,t)=>e.padEnd(i[t]??0)).join(` `).trimEnd(),o=e.map((e,t)=>{let a=n[t]??[],o=[];for(let t=0;t<r;t++){let n=(a[t]??``).padEnd(i[t]??0);if(t===3){let r=a[t]??``;n=Ce(q(e))+` `.repeat(Math.max(0,(i[t]??0)-r.length))}o.push(n)}return o.join(` `).trimEnd()}),s=K.default.dim(`To stop a server: ok stop <port|pid|directory|all>`);return[a,...o,``,s].join(`
|
|
6
6
|
`)}async function Y(e={}){let t=e.discover??u,n=e.inspect??A,r=e.log??(e=>console.log(e)),i=e.resolveCommand??a,s=e.resolveUsage??o,c=await t(),l=[];for(let e of c){let t=n(e,`server`),r=n(e,`ui`),a=be(e,t,r,t.status===`missing`||t.status===`corrupt`?null:i(t.lock.pid),t.status===`missing`||t.status===`corrupt`?null:s(t.lock.pid),r.status===`missing`||r.status===`corrupt`?null:s(r.lock.pid));a!=null&&l.push(a)}if(e.json){let e=l.map(e=>({...e,displayStatus:q(e)}));r(JSON.stringify(e,null,2));return}r(Ee(e.all?l:l.filter(e=>Se.has(q(e)))))}function De(){return new f(`ps`).description(`List all running open-knowledge servers`).argument(`[modifier]`,`"all" to include stale (dead-pid) entries`).option(`--all`,`Include stale (dead-pid) entries (foreign-host shows by default)`).option(`--json`,`Emit structured JSON (always includes all statuses)`).action(async(e,t)=>{await Y({all:t.all===!0||e===`all`,json:t.json===!0})})}function Oe(e,n,r={}){let i=r.isAlive??t,a=[];for(let[t,r]of[[`server`,e],[`ui`,n]])(r.status===`alive`||r.status===`foreign-host`&&i(r.lock.pid))&&a.push({name:t,pid:r.lock.pid,port:r.lock.port});return{targets:a}}function X(e){let t=e.inspect??(t=>A(e.lockDir,t)),n=e.kill??((e,t)=>process.kill(e,t)),r=e.log??(e=>console.log(e)),i=e.error??(e=>console.error(e)),a=Oe(t(`server`),t(`ui`),{isAlive:e.isAlive});if(a.targets.length===0)return r(`No running open-knowledge processes.`),{stopped:[],failed:[],hadTargets:!1};let o=[],s=[];for(let e of a.targets)try{n(e.pid,`SIGTERM`),o.push(e)}catch(t){s.push({target:e,error:t instanceof Error?t.message:String(t)})}return o.length>0&&r(`Stopped: ${o.map(e=>`${e.name} (pid=${e.pid}, port=${e.port})`).join(`, `)}`),s.length>0&&i(`Failed to stop: ${s.map(({target:e,error:t})=>`${e.name} (pid=${e.pid}): ${t}`).join(`; `)}`),{stopped:o,failed:s,hadTargets:!0}}function Z(e,t){return e.status===`alive`?!0:e.status===`foreign-host`?t(e.lock.pid):!1}async function ke(e,n=t){let r=await u(),i=null;for(let t of r){let r=A(t,`server`),a=A(t,`ui`);if(Z(r,n)&&r.lock.port===e||Z(a,n)&&a.lock.port===e)return t;i===null&&(Z(r,n)&&r.lock.pid===e||Z(a,n)&&a.lock.pid===e)&&(i=t)}return i}function Q(e){let t=X({lockDir:e});return t.failed.length>0&&(process.exitCode=1),t}function Ae(e){return new f(`stop`).description(`Stop open-knowledge server(s). With no argument: stops the server for the current directory. Pass a port number, a directory path, or "all" to target globally.`).argument(`[target...]`,`port number, directory path (spaces OK), or "all"`).action(async n=>{let r=n.length===0?void 0:n.join(` `);if(r===void 0){e();let t=X({lockDir:c(process.cwd()),log:()=>{}});if(t.hadTargets){if(t.stopped.length>0){let e=t.stopped.map(e=>`${e.name} (pid=${e.pid}, port=${e.port})`).join(`, `);console.log(`Stopped: ${e}`)}t.failed.length>0&&(process.exitCode=1)}else await Y({});return}if(r===`all`){let e=await u();if(e.length===0){console.log(`No running open-knowledge servers found.`);return}let n=0;for(let r of e){let e=A(r,`server`),i=A(r,`ui`);!Z(e,t)&&!Z(i,t)||(Q(r),n++)}n===0&&console.log(`No running open-knowledge servers found.`);return}if(/^\d+$/.test(r)){let e=Number.parseInt(r,10),t=await ke(e);if(t===null){console.log(`No running open-knowledge server found with port or PID ${e}.`);return}Q(t);return}Q(c(C(G(),r)))})}function je(e){return{event:`mcp-config-decline`,scope:e.scope,surface:e.surface,editorId:e.editorId,reason:e.reason}}async function Me(e,t){let n,r;try{n=await k(C(e)),r=await k(C(se(e)))}catch{return{kind:`not-git`}}if(!$(n,r))return{kind:`symlink-escape`};let i=x(n,`.git`),a;try{a=ue(i)}catch{return{kind:`not-git`}}let o;if(a.isDirectory()){let e;try{e=await k(i)}catch{return{kind:`not-git`}}if(!$(e,n))return{kind:`symlink-escape`};o=e}else if(a.isFile()){let e;try{e=await O(i,`utf-8`)}catch{return{kind:`not-git`}}let t=/^gitdir:\s*(.+)$/m.exec(e.trim());if(!t)return{kind:`not-git`};let r=t[1].trim(),a=b(r)?r:C(n,r);try{o=await k(a)}catch{return{kind:`not-git`}}}else return{kind:`not-git`};let s=x(await Ne(o),`config`),c;try{c=await O(s,`utf-8`)}catch{return{kind:`not-git`}}let l=Fe(c);if(l===null)return{kind:`no-origin`};let u=M(l);if(u===null||u.hostname!==`github.com`)return{kind:`non-github`};let d=u.owner.toLowerCase()===t.owner.toLowerCase(),f=u.name.toLowerCase()===t.repo.toLowerCase();return!d||!f?{kind:`wrong-repo`,actualOwner:u.owner,actualRepo:u.name}:{kind:`ok`,gitRemoteUrl:`https://github.com/${u.owner}/${u.name}.git`}}async function Ne(e){let t;try{t=(await O(x(e,`commondir`),`utf-8`)).trim()}catch{return e}if(t.length===0)return e;let n=b(t)?t:C(e,t);try{return await k(n)}catch{return n}}function $(e,t){if(e===t)return!0;let n=S(t,e);return n.length>0&&!n.startsWith(`..`)&&!b(n)}function Pe(e){let t=e.indexOf(`#`),n=e.indexOf(`;`),r=-1;return t>=0&&n>=0?r=Math.min(t,n):t>=0?r=t:n>=0&&(r=n),(r===-1?e:e.slice(0,r)).trim()}function Fe(e){let t=!1;for(let n of e.split(/\r?\n/)){let e=Pe(n);if(e.length===0)continue;if(e.startsWith(`[`)){t=/^\[\s*remote\s+["']origin["']\s*\]$/.test(e);continue}if(!t)continue;let r=/^url\s*=\s*(.+)$/.exec(e);if(r)return Ie(r[1])}return null}function Ie(e){let t=e.trim();return t.startsWith(`"`)&&t.endsWith(`"`)||t.startsWith(`'`)&&t.endsWith(`'`)?t.slice(1,-1):t}const Le=[{id:`mcp-config`,write(e,t,n){let r=e.projectConfigPath?.(t);if(!r)return{integration:`mcp-config`,editorId:e.id,action:`skipped-unsupported`};try{let i=m(e,t,n,void 0,r);return i.action===`written`||i.action===`overwritten`?{integration:`mcp-config`,editorId:e.id,action:i.action,path:i.configPath}:i.action===`failed`?{integration:`mcp-config`,editorId:e.id,action:`failed`,path:i.configPath,error:i.error??`unknown failure`}:i.action===`declined`?{integration:`mcp-config`,editorId:e.id,action:`declined`,path:i.configPath,...i.declineReason===void 0?{}:{reason:i.declineReason}}:{integration:`mcp-config`,editorId:e.id,action:`failed`,path:i.configPath,error:`unexpected project-scope action: ${i.action}`}}catch(t){return{integration:`mcp-config`,editorId:e.id,action:`failed`,path:r,error:t instanceof Error?t.message:String(t)}}}},{id:`project-skill`,write(e,t,n){try{let n=ae(e,t);return{integration:`project-skill`,editorId:e.id,action:n.action,...n.path?{path:n.path}:{},...n.error?{error:n.error}:{}}}catch(t){return{integration:`project-skill`,editorId:e.id,action:`failed`,error:t instanceof Error?t.message:String(t)}}}}];function Re(e,t,n={},r=Le){let i=[];for(let a of t){let t=ie[a];for(let a of r)i.push(a.write(t,e,n))}return i}function ze(e,t,n={}){return{integrations:Re(e,t,n),claudeLaunchJson:t.includes(`claude`)?te(e,n):void 0}}export{N as _,Ae as a,M as b,ge as c,R as d,L as f,H as g,V as h,X as i,fe as l,z as m,Me as n,De as o,U as p,je as r,_e as s,ze as t,I as u,F as v,A as x,P as y};
|
|
7
|
-
//# sourceMappingURL=src-
|
|
7
|
+
//# sourceMappingURL=src-DPiL5xHq.mjs.map
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{Mn as e,ht as t}from"./server-lock-iLcBw_q0-CdrK5Xfo.mjs";import{cr as n,jr as r,xr as i}from"./dist-BoFX-ULL.mjs";import{n as a,t as o}from"./esm-CsQUg9js.mjs";import{i as s,t as c}from"./gh-detect-KLjG6xCR.mjs";import{n as l}from"./constants-ZpA-rcTF.mjs";import{spawn as u}from"node:child_process";import{basename as d,dirname as f,join as p}from"node:path";import{homedir as m}from"node:os";import{closeSync as h,existsSync as g,mkdirSync as _,openSync as v,statSync as y}from"node:fs";import{rm as b}from"node:fs/promises";import{setTimeout as x}from"node:timers/promises";const S=`OpenKnowledge.app`,C=`/Applications/${S}`;function w(){return{platform:process.platform,env:process.env,execPath:process.execPath,isTTY:process.stdout.isTTY,statSync:e=>{try{return y(e,{throwIfNoEntry:!1})??null}catch{return null}}}}function T(e){if(e.env.ELECTRON_RUN_AS_NODE===`1`){let t=/(.+?\.app)\/Contents\/MacOS\//.exec(e.execPath);if(t?.[1])return t[1]}if(E(e,C))return C;let t=p(e.homeDir??m(),`Applications`,S);return E(e,t)?t:null}function E(e,t){try{let n=p(t,`Contents`,`MacOS`,`OpenKnowledge`),r=e.statSync(n);return r&&typeof r.isFile==`function`?r.isFile():!1}catch{return!1}}function D(e){if(e.env.OK_FORCE_BROWSER===`1`)return{available:!1,reason:`force-browser`};if(e.platform!==`darwin`)return{available:!1,reason:`darwin-only`};let t;try{t=T(e)}catch{return{available:!1,reason:`stat-error`}}return t?e.env.OK_FORCE_DESKTOP===`1`?{available:!0,reason:`available`,bundlePath:t}:e.isTTY!==!0||e.env.SSH_CONNECTION||e.env.SSH_TTY?{available:!1,reason:`headless`,bundlePath:t}:{available:!0,reason:`available`,bundlePath:t}:{available:!1,reason:`no-bundle`}}function O(e){(e.log??(e=>console.error(e)))("Launching OpenKnowledge desktop (use `ok start` for the browser server, or `OK_FORCE_BROWSER=1` to always skip)");let t={...process.env};delete t.ELECTRON_RUN_AS_NODE,e.spawn(`open`,[`-b`,`com.inkeep.open-knowledge`],{detached:!0,stdio:`ignore`,env:t}).unref()}function k(e=`no-bundle`){switch(e){case`no-bundle`:return`Desktop app not found at ${C}. Install via DMG, or omit --mode for browser mode.`;case`darwin-only`:return`Desktop app is macOS-only on this release. Use --mode=browser, or omit --mode for the server fallback.`;case`headless`:return`Desktop launch is gated in headless contexts (CI, SSH, non-TTY stdout). Set OK_FORCE_DESKTOP=1 to override, or use --mode=browser.`;case`force-browser`:return`OK_FORCE_BROWSER=1 is set — desktop dispatch is disabled. Unset it to use --mode=app.`;case`stat-error`:return`Failed to inspect desktop bundle at ${C} (filesystem error). Check permissions or use --mode=browser.`;case`available`:return`Desktop app appears available at ${C} but launch dispatch did not fire (caller bug).`}}function A(e){return p(f(e),`..`,`Frameworks`,`OpenKnowledge Server.app`,`Contents`,`MacOS`,`OpenKnowledge Helper`)}const j=/\/[^/]+\.app\/Contents\/MacOS\/[^/]+$/;function M(e){if(e.platform!==`darwin`||!j.test(e.execPath))return null;let t=A(e.execPath);return e.exists(t)?t:null}function N(e={}){let t=e.execPath??process.execPath,n=e.platform??process.platform,r=e.argv??process.argv,i=e.exists??g,a=r[1];return a?{command:M({execPath:t,platform:n,exists:i})??t,prefixArgs:[a]}:(console.warn(`[self-spawn] process.argv[1] is empty — falling back to \`npx -y @inkeep/open-knowledge@latest\`. This re-introduces the registry-fetch surface that re-exec was fixing. Observed argv: ${JSON.stringify(r)}`),{command:`npx`,prefixArgs:[`-y`,`@inkeep/open-knowledge@latest`]})}function P(e,t){return e.host??t.HOST??`127.0.0.1`}function F(e){let t=d(e).replace(/[^\x20-\x7E]/g,``).trim().slice(0,64);return`open-knowledge-server ${t.length>0?t:`unknown`}`}var I=class extends Error{cwd;constructor(e){super("This directory isn't set up yet. Run `ok init` first, then `ok start` again."),this.name=`OkDirMissingError`,this.cwd=e}};function L(e){return e.uiLock?e.isAlive(e.uiLock.pid)?{action:`skip`,reason:`alive`,pid:e.uiLock.pid,port:e.uiLock.port}:{action:`spawn`,reason:`stale`,stalePid:e.uiLock.pid}:{action:`spawn`,reason:`absent`}}function R(t){g(t.lockDir)||_(t.lockDir,{recursive:!0});let n=v(p(t.lockDir,e),`w`),r=t.spawn??u,{PORT:i,...a}=process.env,o=N();try{let e=r(o.command,[...o.prefixArgs,...t.args??[`ui`]],{detached:!0,stdio:[`ignore`,`ignore`,n],cwd:t.cwd,env:{...a,ELECTRON_RUN_AS_NODE:`1`}});return e.unref(),e}finally{try{h(n)}catch{}}}function z(e,t,n){return e??(n===void 0?t:void 0)}function B(e,t){return e!==void 0&&t!==null&&t.port>0&&t.draining!==!0}function V(e,t,n){return e??(t!=null&&!n?1:0)}async function H(e){let t=e.spawn??u,n=N(),{PORT:r,...i}=process.env,a=t(n.command,[...n.prefixArgs,`ui`,`--port`,String(e.uiPort)],{cwd:e.cwd,stdio:`inherit`,env:{...i,ELECTRON_RUN_AS_NODE:`1`}}),o=!1,s=e=>{o=!0;try{a.kill(e)}catch{}},c=()=>s(`SIGINT`),l=()=>s(`SIGTERM`);process.once(`SIGINT`,c),process.once(`SIGTERM`,l),await new Promise(e=>{a.on(`exit`,(t,n)=>{process.exitCode=V(t,n,o),e()}),a.on(`error`,t=>{console.error(`[start] connect fallback: failed to spawn ok ui — ${t instanceof Error?t.message:String(t)}`),process.exitCode=1,e()})}),process.removeListener(`SIGINT`,c),process.removeListener(`SIGTERM`,l)}async function U(e){let t=e.now()+e.timeoutMs;for(;e.now()<t;){let t=e.readUiLock();if(t&&t.port>0)return t.port;await e.sleep(e.pollIntervalMs)}let n=e.readUiLock();return n&&n.port>0?n.port:null}const W=t;function G(e,t,n=e=>b(e,{recursive:!0,force:!0})){return async()=>{try{await e()}finally{try{await n(t)}catch(e){process.stderr.write(`[start] ephemeral temp dir reap failed for ${t}: ${e instanceof Error?e.message:String(e)}\n`)}}}}function K(e,t={}){let n=t.exit??(e=>process.exit(e)),r=t.getActiveHandles??(()=>{let e=process._getActiveHandles;return e?e.call(process):null});return async()=>{let i=!1;try{await e()}catch(e){i=!0,t.log?.error({err:e},`idle-shutdown: destroy failed — exiting anyway`)}finally{let e=null;try{let t=r();if(t!==null){e={};for(let n of t){let t=n?.constructor?.name??`unknown`;e[t]=(e[t]??0)+1}}}catch{e=null}t.log?.info({event:`idle-shutdown-exit`,exitCode:i?1:0,openHandles:e??{},handlesAvailable:e!==null},`idle-shutdown: teardown finished — exiting process`),n(i?1:0)}}}function q(e){let t=e.sigtermGraceMs??W,n=e.sigtermPollIntervalMs??200,r=e.sleep??(e=>x(e));return async()=>{try{let i=e.readUiLock();if(i&&e.isAlive(i.pid))try{e.killPid(i.pid,`SIGTERM`),e.log?.info({pid:i.pid,port:i.port},`idle-shutdown: SIGTERM UI sibling`);let a=Date.now()+t;for(;Date.now()<a&&e.isAlive(i.pid);)await r(n);if(e.isAlive(i.pid))try{e.killPid(i.pid,`SIGKILL`),e.log?.warn({pid:i.pid,graceMs:t},`idle-shutdown: SIGTERM grace expired — escalated to SIGKILL`)}catch(t){e.log?.error({pid:i.pid,err:t instanceof Error?t.message:String(t)},`idle-shutdown: SIGKILL failed`)}}catch(t){e.log?.warn({pid:i.pid,err:t instanceof Error?t.message:String(t)},`idle-shutdown: failed to SIGTERM UI sibling`)}}catch(t){e.log?.warn({err:t instanceof Error?t.message:String(t)},`idle-shutdown: UI lookup failed; proceeding with destroy`)}await e.destroy()}}async function J(e){let{config:t,cwd:a,host:o}=e,l=e.skipAutoInit??!1,u=e.skipUiAutoSpawn??!1,d=e.idleThresholdMs??18e5,{existsSync:f,mkdirSync:p}=await import(`node:fs`),{basename:m,dirname:h}=await import(`node:path`),{bootServer:g,getLogger:_,isProcessAlive:v,readUiLock:y,resolveContentDir:b,resolveLockDir:S,waitForServerLockDrain:C}=await import(`./dist-Dqzx7uaJ.mjs`),w=e.log??_(`start`),T=e.singleFile!==void 0,E=e.projectDir??a,D=T?r(e.singleFile).canonicalFilePath:void 0,O=D?h(D):void 0,k=D?m(D):void 0;if(!T){if(!l&&!n(a))throw new I(a);let t=process.env.OK_RECLAIM_DISABLE??null,r=e=>{let t=typeof e.event==`string`?e.event:``;(t.endsWith(`-failed`)||t.endsWith(`-error`)||t.endsWith(`-missing`))&&w.warn({event:e},`[start] reclaim sweep reported a problem`)};try{(e.repairMcpConfigsFn??(await import(`./repair-mcp-configs-Zo0iqRkn.mjs`)).repairMcpConfigs)({projectDir:a,reclaimDisableEnv:t,logger:r})}catch(e){w.warn({err:e},`[start] mcp-config repair sweep failed; continuing`)}try{(e.repairLaunchJsonFn??(await import(`./repair-launch-json-DjbHjime.mjs`)).repairLaunchJson)({projectDir:a,reclaimDisableEnv:t,logger:r})}catch(e){w.warn({err:e},`[start] launch.json repair sweep failed; continuing`)}try{await(e.repairSkillsFn??(await import(`./repair-skills-rGTpTOuw.mjs`)).repairSkills)({projectDir:a,reclaimDisableEnv:t,logger:r})}catch(e){w.warn({err:e},`[start] skill repair sweep failed; continuing`)}}let A=O??b(t,a);!T&&!f(A)&&(p(A,{recursive:!0}),w.info({contentDir:A},`Created content directory`));let j=null,M=async({lockDir:t})=>{if(j=L({uiLock:y(t),isAlive:v}),j.action===`spawn`&&!u)try{let n=e.uiPort===void 0?void 0:[`ui`,`--port`,String(e.uiPort)];R({lockDir:t,cwd:a,spawn:e.spawn,args:n}),w.info({reason:j.reason,uiPort:e.uiPort},`[start] auto-spawned ok ui sibling`)}catch(e){console.warn(`[start] failed to auto-spawn ok ui: ${e instanceof Error?e.message:String(e)}`)}else j.action===`skip`&&w.info({port:j.port,pid:j.pid},`UI already running at port ${j.port}`)},N=e.reactShellDistDir===void 0,P=s(),F=i();{let e=S(T?E:a),t=Date.now(),n=await C(e);n!==`no-drain`&&w.info({event:`start-waited-for-draining-predecessor`,outcome:n,waitedMs:Date.now()-t,drainLockDir:e},n===`released`?`[start] predecessor server finished draining — proceeding`:`[start] predecessor server still draining after wait — proceeding to collide`)}let z=await g({config:t,contentDir:A,projectDir:T?E:a,contentRoot:T?void 0:t.content.dir,port:e.port,host:o,quiet:!1,detectGh:c,tokenStore:P,embeddingsKeyStore:F,...T?{ephemeral:!0,singleDocRelPath:k,gitEnabled:!1,gitPreflight:()=>({ok:!0,version:`0.0.0`,resolvedPath:`git`,source:`PATH`})}:{},localOpCliArgs:[process.execPath,process.argv[1]],attachUiSibling:N,idleShutdownMs:d,skipAutoInit:!0,...N?{spawnUiSiblingFn:M}:{},idleShutdownHandler:t=>{let n=q({readUiLock:()=>y(z.lockDir),isAlive:v,killPid:(e,t)=>{process.kill(e,t)},destroy:t,log:w});return K(T?G(n,E):n,{log:w,exit:e.idleExit})},log:w,...e.serveContentAssets?{serveContentAssets:!0}:{},...e.reactShellDistDir?{reactShellDistDir:e.reactShellDistDir}:{}});j||={action:`skip`,reason:`alive`,pid:0,port:0};let B=j,V=null;if(B.action===`skip`)V=B.port>0?B.port:null;else if(!u){let t=e.uiBindTimeoutMs??3e3;V=await U({readUiLock:()=>y(z.lockDir),now:Date.now,sleep:e=>x(e),timeoutMs:t,pollIntervalMs:50}),V===null&&w.warn({timeoutMs:t},`[start] ok ui did not bind within timeout — banner falls back to API URL`)}return{httpServer:z.httpServer,destroy:z.destroy,lockDir:z.lockDir,contentDir:A,port:z.port,ready:z.ready,degraded:z.degraded,uiSpawnDecision:j,resolvedUiPort:V}}function ee(e){if(e===`browser`||e===`app`)return e;throw new a(`--mode must be 'browser' or 'app'`)}function te(e){let t=Number.parseInt(e,10);if(Number.isNaN(t)||t<1||t>65535)throw new a(`--ui-port must be a port number between 1 and 65535`);return t}function Y(e){return e.OK_CONSOLE_LEVEL!==void 0||e.LOG_LEVEL!==void 0?null:`warn`}function X(e){let t=[`Stopping OpenKnowledge…`,`Saving pending changes and releasing the server lock — this can take a few seconds.`];return e===`SIGINT`&&t.push(`Press Ctrl+C again to force quit.`),t}async function Z(e,t){let n=Y(process.env);n!==null&&(process.env.OK_CONSOLE_LEVEL=n);let{renderBanner:r}=await import(`./banner-BxCFCyu8.mjs`),{accent:i,dim:a,error:o,warning:s}=await import(`./colors-CmkIIbww.mjs`),c=process.cwd(),u=e;process.title=F(c);let d=P(t,process.env),f=t.port===void 0?void 0:Number(t.port),p=process.env.PORT?Number(process.env.PORT):void 0,m=t.uiPort===void 0?void 0:Number(t.uiPort),h=z(f,p,m);if(m!==void 0){let{readServerLock:e,resolveLockDir:t}=await import(`./dist-Dqzx7uaJ.mjs`);if(B(m,e(t(c)))){await H({cwd:c,uiPort:m});return}}let g;try{g=await J({config:u,cwd:c,host:d,port:h,...m===void 0?{}:{uiPort:m},...t.serveContentAssets?{serveContentAssets:!0}:{},...t.reactShellDistDir?{reactShellDistDir:t.reactShellDistDir}:{},...t.singleFile?{singleFile:t.singleFile}:{},...t.projectDir?{projectDir:t.projectDir}:{}})}catch(e){e instanceof I&&(console.error(o(e.message)),process.exit(1));let t=await import(`./dist-Dqzx7uaJ.mjs`);if((e instanceof t.GitNotAvailableError||e instanceof t.GitTooOldError)&&process.exit(78),(e instanceof t.SingleFileNotFoundError||e instanceof t.SingleFileNotAFileError||e instanceof t.SingleFileNotMarkdownError)&&(console.error(o(e.message)),process.exit(1)),m!==void 0&&Q(e,t)){await H({cwd:c,uiPort:m});return}let n=$(e,c,t);n!==null&&(console.error(o(n)),process.exit(1)),console.error(`${o(`Failed to start:`)} ${e instanceof Error?e.stack??e.message:String(e)}`),process.exit(1)}let _=!1,v=async e=>{if(_)return;_=!0;let[t,...n]=X(e);console.log(i(`\n${t}`));for(let e of n)console.log(a(` ${e}`));try{await g.destroy()}catch(e){console.error(`${o(`destroy() failed:`)} ${e instanceof Error?e.stack??e.message:String(e)}`),process.exitCode=1}process.exit(process.exitCode??0)};process.once(`SIGINT`,()=>{v(`SIGINT`)}),process.once(`SIGTERM`,()=>{v(`SIGTERM`)});let y=`http://${d}:${g.port}`,b=d===`0.0.0.0`||d===`::`?`http://0.0.0.0:${g.port}`:void 0,x=g.resolvedUiPort,S=x!==null&&x>0?`http://${d}:${x}`:y;console.log(r({name:`open-knowledge`,version:l,localUrl:S,apiUrl:S===y?void 0:y,networkUrl:b,nextSteps:[`Open the Editor URL in your browser to start editing.`]}));let C={"shadow-repo":`Version history and branch-switch safety unavailable`,"file-watcher":`External file changes will not sync to the editor`,"head-watcher":`Git branch switches may cause document inconsistency`};g.ready.then(async()=>{if(g.degraded.length>0){console.log();for(let e of g.degraded){let t=C[e]??`${e} (check server logs for details)`;console.warn(` ${s(`⚠`)} ${s(e)}: ${a(t)}`)}console.log()}if(t.open){let{openBrowser:e}=await import(`./open-browser-DHTbHSqx.mjs`);e(S)}}).catch(e=>{console.error(` ${o(`Server initialization failed:`)} ${e instanceof Error?e.message:String(e)}`)})}function Q(e,t){let n=t.ServerLockCollisionError;return n!==void 0&&e instanceof n}function $(e,t,n){let r=n.ServerLockCollisionError;if(r===void 0||!(e instanceof r))return null;try{let e=p(t,`.ok`),r=n.readServerLock(e);return r?r.kind===`interactive`?`OpenKnowledge desktop is currently running on this project. Quit it or use --cwd to point elsewhere.`:r.kind===`mcp-spawned`?"An MCP-spawned server holds this lock; it should release on idle-shutdown (~30 min). Or run `ok stop`.":"OpenKnowledge server is already running on this project — check `ok status` or `ok stop`.":"OpenKnowledge server is already running on this project — check `ok status` or `ok stop`."}catch{return null}}function ne(e){return new o(`start`).description(`Start the knowledge base collab server`).option(`-p, --port <port>`,`Server port`,void 0).option(`--ui-port <port>`,`Pin the ok ui sibling to <port> and connect (not exit) if a server already runs here — the worktree-preview recipe path`,te).option(`-H, --host <host>`,`Server host`,void 0).option(`--open`,`Open browser after start`).option(`--mode <mode>`,`Force dispatch mode: 'browser' or 'app'`,ee).option(`--serve-content-assets`,`Serve content assets from this server`).option(`--react-shell-dist-dir <path>`,`Serve React shell from <path> (suppresses ok ui sibling)`).option(`--single-file <path>`,`No-project ephemeral single-file mode: scope the server to one markdown file (git + MCP off)`).option(`--project-dir <dir>`,`Throwaway project root for --single-file (where ephemeral .ok/ state lives)`).action(async t=>{let n=e();if(t.mode===`app`){t.open&&(process.stderr.write(`error: option '--mode=app' cannot be combined with '--open' (--open opens a browser tab against the local server, which app mode does not boot)
|
|
1
|
+
import{Mn as e,ht as t}from"./server-lock-iLcBw_q0-CdrK5Xfo.mjs";import{cr as n,jr as r,xr as i}from"./dist-CdVqgoPq.mjs";import{n as a,t as o}from"./esm-CsQUg9js.mjs";import{i as s,t as c}from"./gh-detect-KLjG6xCR.mjs";import{n as l}from"./constants-CVwzJpO0.mjs";import{spawn as u}from"node:child_process";import{basename as d,dirname as f,join as p}from"node:path";import{homedir as m}from"node:os";import{closeSync as h,existsSync as g,mkdirSync as _,openSync as v,statSync as y}from"node:fs";import{rm as b}from"node:fs/promises";import{setTimeout as x}from"node:timers/promises";const S=`OpenKnowledge.app`,C=`/Applications/${S}`;function w(){return{platform:process.platform,env:process.env,execPath:process.execPath,isTTY:process.stdout.isTTY,statSync:e=>{try{return y(e,{throwIfNoEntry:!1})??null}catch{return null}}}}function T(e){if(e.env.ELECTRON_RUN_AS_NODE===`1`){let t=/(.+?\.app)\/Contents\/MacOS\//.exec(e.execPath);if(t?.[1])return t[1]}if(E(e,C))return C;let t=p(e.homeDir??m(),`Applications`,S);return E(e,t)?t:null}function E(e,t){try{let n=p(t,`Contents`,`MacOS`,`OpenKnowledge`),r=e.statSync(n);return r&&typeof r.isFile==`function`?r.isFile():!1}catch{return!1}}function D(e){if(e.env.OK_FORCE_BROWSER===`1`)return{available:!1,reason:`force-browser`};if(e.platform!==`darwin`)return{available:!1,reason:`darwin-only`};let t;try{t=T(e)}catch{return{available:!1,reason:`stat-error`}}return t?e.env.OK_FORCE_DESKTOP===`1`?{available:!0,reason:`available`,bundlePath:t}:e.isTTY!==!0||e.env.SSH_CONNECTION||e.env.SSH_TTY?{available:!1,reason:`headless`,bundlePath:t}:{available:!0,reason:`available`,bundlePath:t}:{available:!1,reason:`no-bundle`}}function O(e){(e.log??(e=>console.error(e)))("Launching OpenKnowledge desktop (use `ok start` for the browser server, or `OK_FORCE_BROWSER=1` to always skip)");let t={...process.env};delete t.ELECTRON_RUN_AS_NODE,e.spawn(`open`,[`-b`,`com.inkeep.open-knowledge`],{detached:!0,stdio:`ignore`,env:t}).unref()}function k(e=`no-bundle`){switch(e){case`no-bundle`:return`Desktop app not found at ${C}. Install via DMG, or omit --mode for browser mode.`;case`darwin-only`:return`Desktop app is macOS-only on this release. Use --mode=browser, or omit --mode for the server fallback.`;case`headless`:return`Desktop launch is gated in headless contexts (CI, SSH, non-TTY stdout). Set OK_FORCE_DESKTOP=1 to override, or use --mode=browser.`;case`force-browser`:return`OK_FORCE_BROWSER=1 is set — desktop dispatch is disabled. Unset it to use --mode=app.`;case`stat-error`:return`Failed to inspect desktop bundle at ${C} (filesystem error). Check permissions or use --mode=browser.`;case`available`:return`Desktop app appears available at ${C} but launch dispatch did not fire (caller bug).`}}function A(e){return p(f(e),`..`,`Frameworks`,`OpenKnowledge Server.app`,`Contents`,`MacOS`,`OpenKnowledge Helper`)}const j=/\/[^/]+\.app\/Contents\/MacOS\/[^/]+$/;function M(e){if(e.platform!==`darwin`||!j.test(e.execPath))return null;let t=A(e.execPath);return e.exists(t)?t:null}function N(e={}){let t=e.execPath??process.execPath,n=e.platform??process.platform,r=e.argv??process.argv,i=e.exists??g,a=r[1];return a?{command:M({execPath:t,platform:n,exists:i})??t,prefixArgs:[a]}:(console.warn(`[self-spawn] process.argv[1] is empty — falling back to \`npx -y @inkeep/open-knowledge@latest\`. This re-introduces the registry-fetch surface that re-exec was fixing. Observed argv: ${JSON.stringify(r)}`),{command:`npx`,prefixArgs:[`-y`,`@inkeep/open-knowledge@latest`]})}function P(e,t){return e.host??t.HOST??`127.0.0.1`}function F(e){let t=d(e).replace(/[^\x20-\x7E]/g,``).trim().slice(0,64);return`open-knowledge-server ${t.length>0?t:`unknown`}`}var I=class extends Error{cwd;constructor(e){super("This directory isn't set up yet. Run `ok init` first, then `ok start` again."),this.name=`OkDirMissingError`,this.cwd=e}};function L(e){return e.uiLock?e.isAlive(e.uiLock.pid)?{action:`skip`,reason:`alive`,pid:e.uiLock.pid,port:e.uiLock.port}:{action:`spawn`,reason:`stale`,stalePid:e.uiLock.pid}:{action:`spawn`,reason:`absent`}}function R(t){g(t.lockDir)||_(t.lockDir,{recursive:!0});let n=v(p(t.lockDir,e),`w`),r=t.spawn??u,{PORT:i,...a}=process.env,o=N();try{let e=r(o.command,[...o.prefixArgs,...t.args??[`ui`]],{detached:!0,stdio:[`ignore`,`ignore`,n],cwd:t.cwd,env:{...a,ELECTRON_RUN_AS_NODE:`1`}});return e.unref(),e}finally{try{h(n)}catch{}}}function z(e,t,n){return e??(n===void 0?t:void 0)}function B(e,t){return e!==void 0&&t!==null&&t.port>0&&t.draining!==!0}function V(e,t,n){return e??(t!=null&&!n?1:0)}async function H(e){let t=e.spawn??u,n=N(),{PORT:r,...i}=process.env,a=t(n.command,[...n.prefixArgs,`ui`,`--port`,String(e.uiPort)],{cwd:e.cwd,stdio:`inherit`,env:{...i,ELECTRON_RUN_AS_NODE:`1`}}),o=!1,s=e=>{o=!0;try{a.kill(e)}catch{}},c=()=>s(`SIGINT`),l=()=>s(`SIGTERM`);process.once(`SIGINT`,c),process.once(`SIGTERM`,l),await new Promise(e=>{a.on(`exit`,(t,n)=>{process.exitCode=V(t,n,o),e()}),a.on(`error`,t=>{console.error(`[start] connect fallback: failed to spawn ok ui — ${t instanceof Error?t.message:String(t)}`),process.exitCode=1,e()})}),process.removeListener(`SIGINT`,c),process.removeListener(`SIGTERM`,l)}async function U(e){let t=e.now()+e.timeoutMs;for(;e.now()<t;){let t=e.readUiLock();if(t&&t.port>0)return t.port;await e.sleep(e.pollIntervalMs)}let n=e.readUiLock();return n&&n.port>0?n.port:null}const W=t;function G(e,t,n=e=>b(e,{recursive:!0,force:!0})){return async()=>{try{await e()}finally{try{await n(t)}catch(e){process.stderr.write(`[start] ephemeral temp dir reap failed for ${t}: ${e instanceof Error?e.message:String(e)}\n`)}}}}function K(e,t={}){let n=t.exit??(e=>process.exit(e)),r=t.getActiveHandles??(()=>{let e=process._getActiveHandles;return e?e.call(process):null});return async()=>{let i=!1;try{await e()}catch(e){i=!0,t.log?.error({err:e},`idle-shutdown: destroy failed — exiting anyway`)}finally{let e=null;try{let t=r();if(t!==null){e={};for(let n of t){let t=n?.constructor?.name??`unknown`;e[t]=(e[t]??0)+1}}}catch{e=null}t.log?.info({event:`idle-shutdown-exit`,exitCode:i?1:0,openHandles:e??{},handlesAvailable:e!==null},`idle-shutdown: teardown finished — exiting process`),n(i?1:0)}}}function q(e){let t=e.sigtermGraceMs??W,n=e.sigtermPollIntervalMs??200,r=e.sleep??(e=>x(e));return async()=>{try{let i=e.readUiLock();if(i&&e.isAlive(i.pid))try{e.killPid(i.pid,`SIGTERM`),e.log?.info({pid:i.pid,port:i.port},`idle-shutdown: SIGTERM UI sibling`);let a=Date.now()+t;for(;Date.now()<a&&e.isAlive(i.pid);)await r(n);if(e.isAlive(i.pid))try{e.killPid(i.pid,`SIGKILL`),e.log?.warn({pid:i.pid,graceMs:t},`idle-shutdown: SIGTERM grace expired — escalated to SIGKILL`)}catch(t){e.log?.error({pid:i.pid,err:t instanceof Error?t.message:String(t)},`idle-shutdown: SIGKILL failed`)}}catch(t){e.log?.warn({pid:i.pid,err:t instanceof Error?t.message:String(t)},`idle-shutdown: failed to SIGTERM UI sibling`)}}catch(t){e.log?.warn({err:t instanceof Error?t.message:String(t)},`idle-shutdown: UI lookup failed; proceeding with destroy`)}await e.destroy()}}async function J(e){let{config:t,cwd:a,host:o}=e,l=e.skipAutoInit??!1,u=e.skipUiAutoSpawn??!1,d=e.idleThresholdMs??18e5,{existsSync:f,mkdirSync:p}=await import(`node:fs`),{basename:m,dirname:h}=await import(`node:path`),{bootServer:g,getLogger:_,isProcessAlive:v,readUiLock:y,resolveContentDir:b,resolveLockDir:S,waitForServerLockDrain:C}=await import(`./dist-CZ4COUHS.mjs`),w=e.log??_(`start`),T=e.singleFile!==void 0,E=e.projectDir??a,D=T?r(e.singleFile).canonicalFilePath:void 0,O=D?h(D):void 0,k=D?m(D):void 0;if(!T){if(!l&&!n(a))throw new I(a);let t=process.env.OK_RECLAIM_DISABLE??null,r=e=>{let t=typeof e.event==`string`?e.event:``;(t.endsWith(`-failed`)||t.endsWith(`-error`)||t.endsWith(`-missing`))&&w.warn({event:e},`[start] reclaim sweep reported a problem`)};try{(e.repairMcpConfigsFn??(await import(`./repair-mcp-configs-Dtldp8WO.mjs`)).repairMcpConfigs)({projectDir:a,reclaimDisableEnv:t,logger:r})}catch(e){w.warn({err:e},`[start] mcp-config repair sweep failed; continuing`)}try{(e.repairLaunchJsonFn??(await import(`./repair-launch-json-jEfxfrXs.mjs`)).repairLaunchJson)({projectDir:a,reclaimDisableEnv:t,logger:r})}catch(e){w.warn({err:e},`[start] launch.json repair sweep failed; continuing`)}try{await(e.repairSkillsFn??(await import(`./repair-skills-DCZqW9al.mjs`)).repairSkills)({projectDir:a,reclaimDisableEnv:t,logger:r})}catch(e){w.warn({err:e},`[start] skill repair sweep failed; continuing`)}}let A=O??b(t,a);!T&&!f(A)&&(p(A,{recursive:!0}),w.info({contentDir:A},`Created content directory`));let j=null,M=async({lockDir:t})=>{if(j=L({uiLock:y(t),isAlive:v}),j.action===`spawn`&&!u)try{let n=e.uiPort===void 0?void 0:[`ui`,`--port`,String(e.uiPort)];R({lockDir:t,cwd:a,spawn:e.spawn,args:n}),w.info({reason:j.reason,uiPort:e.uiPort},`[start] auto-spawned ok ui sibling`)}catch(e){console.warn(`[start] failed to auto-spawn ok ui: ${e instanceof Error?e.message:String(e)}`)}else j.action===`skip`&&w.info({port:j.port,pid:j.pid},`UI already running at port ${j.port}`)},N=e.reactShellDistDir===void 0,P=s(),F=i();{let e=S(T?E:a),t=Date.now(),n=await C(e);n!==`no-drain`&&w.info({event:`start-waited-for-draining-predecessor`,outcome:n,waitedMs:Date.now()-t,drainLockDir:e},n===`released`?`[start] predecessor server finished draining — proceeding`:`[start] predecessor server still draining after wait — proceeding to collide`)}let z=await g({config:t,contentDir:A,projectDir:T?E:a,contentRoot:T?void 0:t.content.dir,port:e.port,host:o,quiet:!1,detectGh:c,tokenStore:P,embeddingsKeyStore:F,...T?{ephemeral:!0,singleDocRelPath:k,gitEnabled:!1,gitPreflight:()=>({ok:!0,version:`0.0.0`,resolvedPath:`git`,source:`PATH`})}:{},localOpCliArgs:[process.execPath,process.argv[1]],attachUiSibling:N,idleShutdownMs:d,skipAutoInit:!0,...N?{spawnUiSiblingFn:M}:{},idleShutdownHandler:t=>{let n=q({readUiLock:()=>y(z.lockDir),isAlive:v,killPid:(e,t)=>{process.kill(e,t)},destroy:t,log:w});return K(T?G(n,E):n,{log:w,exit:e.idleExit})},log:w,...e.serveContentAssets?{serveContentAssets:!0}:{},...e.reactShellDistDir?{reactShellDistDir:e.reactShellDistDir}:{}});j||={action:`skip`,reason:`alive`,pid:0,port:0};let B=j,V=null;if(B.action===`skip`)V=B.port>0?B.port:null;else if(!u){let t=e.uiBindTimeoutMs??3e3;V=await U({readUiLock:()=>y(z.lockDir),now:Date.now,sleep:e=>x(e),timeoutMs:t,pollIntervalMs:50}),V===null&&w.warn({timeoutMs:t},`[start] ok ui did not bind within timeout — banner falls back to API URL`)}return{httpServer:z.httpServer,destroy:z.destroy,lockDir:z.lockDir,contentDir:A,port:z.port,ready:z.ready,degraded:z.degraded,uiSpawnDecision:j,resolvedUiPort:V}}function ee(e){if(e===`browser`||e===`app`)return e;throw new a(`--mode must be 'browser' or 'app'`)}function te(e){let t=Number.parseInt(e,10);if(Number.isNaN(t)||t<1||t>65535)throw new a(`--ui-port must be a port number between 1 and 65535`);return t}function Y(e){return e.OK_CONSOLE_LEVEL!==void 0||e.LOG_LEVEL!==void 0?null:`warn`}function X(e){let t=[`Stopping OpenKnowledge…`,`Saving pending changes and releasing the server lock — this can take a few seconds.`];return e===`SIGINT`&&t.push(`Press Ctrl+C again to force quit.`),t}async function Z(e,t){let n=Y(process.env);n!==null&&(process.env.OK_CONSOLE_LEVEL=n);let{renderBanner:r}=await import(`./banner-BxCFCyu8.mjs`),{accent:i,dim:a,error:o,warning:s}=await import(`./colors-CmkIIbww.mjs`),c=process.cwd(),u=e;process.title=F(c);let d=P(t,process.env),f=t.port===void 0?void 0:Number(t.port),p=process.env.PORT?Number(process.env.PORT):void 0,m=t.uiPort===void 0?void 0:Number(t.uiPort),h=z(f,p,m);if(m!==void 0){let{readServerLock:e,resolveLockDir:t}=await import(`./dist-CZ4COUHS.mjs`);if(B(m,e(t(c)))){await H({cwd:c,uiPort:m});return}}let g;try{g=await J({config:u,cwd:c,host:d,port:h,...m===void 0?{}:{uiPort:m},...t.serveContentAssets?{serveContentAssets:!0}:{},...t.reactShellDistDir?{reactShellDistDir:t.reactShellDistDir}:{},...t.singleFile?{singleFile:t.singleFile}:{},...t.projectDir?{projectDir:t.projectDir}:{}})}catch(e){e instanceof I&&(console.error(o(e.message)),process.exit(1));let t=await import(`./dist-CZ4COUHS.mjs`);if((e instanceof t.GitNotAvailableError||e instanceof t.GitTooOldError)&&process.exit(78),(e instanceof t.SingleFileNotFoundError||e instanceof t.SingleFileNotAFileError||e instanceof t.SingleFileNotMarkdownError)&&(console.error(o(e.message)),process.exit(1)),m!==void 0&&Q(e,t)){await H({cwd:c,uiPort:m});return}let n=$(e,c,t);n!==null&&(console.error(o(n)),process.exit(1)),console.error(`${o(`Failed to start:`)} ${e instanceof Error?e.stack??e.message:String(e)}`),process.exit(1)}let _=!1,v=async e=>{if(_)return;_=!0;let[t,...n]=X(e);console.log(i(`\n${t}`));for(let e of n)console.log(a(` ${e}`));try{await g.destroy()}catch(e){console.error(`${o(`destroy() failed:`)} ${e instanceof Error?e.stack??e.message:String(e)}`),process.exitCode=1}process.exit(process.exitCode??0)};process.once(`SIGINT`,()=>{v(`SIGINT`)}),process.once(`SIGTERM`,()=>{v(`SIGTERM`)});let y=`http://${d}:${g.port}`,b=d===`0.0.0.0`||d===`::`?`http://0.0.0.0:${g.port}`:void 0,x=g.resolvedUiPort,S=x!==null&&x>0?`http://${d}:${x}`:y;console.log(r({name:`open-knowledge`,version:l,localUrl:S,apiUrl:S===y?void 0:y,networkUrl:b,nextSteps:[`Open the Editor URL in your browser to start editing.`]}));let C={"shadow-repo":`Version history and branch-switch safety unavailable`,"file-watcher":`External file changes will not sync to the editor`,"head-watcher":`Git branch switches may cause document inconsistency`};g.ready.then(async()=>{if(g.degraded.length>0){console.log();for(let e of g.degraded){let t=C[e]??`${e} (check server logs for details)`;console.warn(` ${s(`⚠`)} ${s(e)}: ${a(t)}`)}console.log()}if(t.open){let{openBrowser:e}=await import(`./open-browser-DHTbHSqx.mjs`);e(S)}}).catch(e=>{console.error(` ${o(`Server initialization failed:`)} ${e instanceof Error?e.message:String(e)}`)})}function Q(e,t){let n=t.ServerLockCollisionError;return n!==void 0&&e instanceof n}function $(e,t,n){let r=n.ServerLockCollisionError;if(r===void 0||!(e instanceof r))return null;try{let e=p(t,`.ok`),r=n.readServerLock(e);return r?r.kind===`interactive`?`OpenKnowledge desktop is currently running on this project. Quit it or use --cwd to point elsewhere.`:r.kind===`mcp-spawned`?"An MCP-spawned server holds this lock; it should release on idle-shutdown (~30 min). Or run `ok stop`.":"OpenKnowledge server is already running on this project — check `ok status` or `ok stop`.":"OpenKnowledge server is already running on this project — check `ok status` or `ok stop`."}catch{return null}}function ne(e){return new o(`start`).description(`Start the knowledge base collab server`).option(`-p, --port <port>`,`Server port`,void 0).option(`--ui-port <port>`,`Pin the ok ui sibling to <port> and connect (not exit) if a server already runs here — the worktree-preview recipe path`,te).option(`-H, --host <host>`,`Server host`,void 0).option(`--open`,`Open browser after start`).option(`--mode <mode>`,`Force dispatch mode: 'browser' or 'app'`,ee).option(`--serve-content-assets`,`Serve content assets from this server`).option(`--react-shell-dist-dir <path>`,`Serve React shell from <path> (suppresses ok ui sibling)`).option(`--single-file <path>`,`No-project ephemeral single-file mode: scope the server to one markdown file (git + MCP off)`).option(`--project-dir <dir>`,`Throwaway project root for --single-file (where ephemeral .ok/ state lives)`).action(async t=>{let n=e();if(t.mode===`app`){t.open&&(process.stderr.write(`error: option '--mode=app' cannot be combined with '--open' (--open opens a browser tab against the local server, which app mode does not boot)
|
|
2
2
|
`),process.exit(2));let e=[];if(t.port!==void 0&&e.push(`--port`),t.uiPort!==void 0&&e.push(`--ui-port`),t.host!==void 0&&e.push(`--host`),e.length>0){let t=process.env.OK_LOG_LEVEL??`info`;(t===`debug`||t===`trace`)&&console.error(`--mode=app: ignoring ${e.join(`, `)}`)}let n=D(w());if(n.available){O({spawn:u});return}console.error(k(n.reason)),process.exit(1)}await Z(n,t)})}export{D as C,w as S,ne as _,V as a,K as b,F as c,z as d,P as f,R as g,B as h,q as i,X as l,Z as m,U as n,H as o,Y as p,J as r,L as s,I as t,Q as u,$ as v,O as w,N as x,G as y};
|
|
3
|
-
//# sourceMappingURL=start-
|
|
3
|
+
//# sourceMappingURL=start-B0I0cewI.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{_ as e,f as t,r as n}from"./start-B0I0cewI.mjs";export{n as bootStartServer,t as resolveHost,e as startCommand};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{It as e,S as t,an as n,wt as r}from"./server-lock-iLcBw_q0-CdrK5Xfo.mjs";import{d as i,ei as a,ut as o}from"./dist-
|
|
1
|
+
import{It as e,S as t,an as n,wt as r}from"./server-lock-iLcBw_q0-CdrK5Xfo.mjs";import{d as i,ei as a,ut as o}from"./dist-CdVqgoPq.mjs";import{basename as s,dirname as c,isAbsolute as l,join as u,posix as d,relative as ee,resolve as f,sep as p,win32 as m}from"node:path";import{homedir as h}from"node:os";import{cpSync as g,existsSync as _,lstatSync as v,mkdirSync as y,realpathSync as b,rmSync as x}from"node:fs";const S=t,C=r,w=e,T=`node`,E={MCP_DEBUG:`1`,OK_LOG_FILE:`/tmp/ok-mcp.log`},D=`# ok-mcp-v1`,O=`# ok-mcp-v1
|
|
2
2
|
USER_BUNDLE="$HOME/Applications/OpenKnowledge.app/Contents/Resources/cli/bin/ok.sh"
|
|
3
3
|
[ -f "$USER_BUNDLE" ] && [ -x "$USER_BUNDLE" ] && exec "$USER_BUNDLE" mcp
|
|
4
4
|
BUNDLE="/Applications/OpenKnowledge.app/Contents/Resources/cli/bin/ok.sh"
|
|
@@ -33,4 +33,4 @@ foreach ($d in $dirs) {
|
|
|
33
33
|
}
|
|
34
34
|
[Console]::Error.WriteLine('OpenKnowledge: install Node.js 24+ (npm i -g @inkeep/open-knowledge), then restart your editor')
|
|
35
35
|
exit 127`,j=`// ok-pi-bridge`,M=`${j}-v1`,N=`ok-pi-managed-extension`;function P(e){if(typeof e!=`object`||!e)return!1;let t=e;if(t.command===`/bin/sh`){if(!Array.isArray(t.args)||t.args[0]!==`-l`||t.args[1]!==`-c`)return!1;let e=t.args[2];return typeof e==`string`&&e.includes(`# ok-mcp-v1`)}if(t.command===`powershell`){if(!Array.isArray(t.args)||t.args[0]!==`-NoProfile`||t.args[1]!==`-NonInteractive`||t.args[2]!==`-Command`)return!1;let e=t.args[3];return typeof e==`string`&&e.includes(`# ok-mcp-win-v1`)}if(t.type===`local`&&Array.isArray(t.command)){if(t.command[0]===`/bin/sh`){if(t.command[1]!==`-l`||t.command[2]!==`-c`)return!1;let e=t.command[3];return typeof e==`string`&&e.includes(`# ok-mcp-v1`)}if(t.command[0]===`powershell`){if(t.command[1]!==`-NoProfile`||t.command[2]!==`-NonInteractive`||t.command[3]!==`-Command`)return!1;let e=t.command[4];return typeof e==`string`&&e.includes(`# ok-mcp-win-v1`)}return!1}if(t.command===`ok-pi-managed-extension`){if(!Array.isArray(t.args))return!1;let e=t.args[0];return typeof e==`string`&&e.startsWith(M)}return!1}function F(e=process.argv[1]){if(!e)throw Error(`Cannot infer the local CLI entry for --dev-mcp because process.argv[1] is empty.`);let t=f(e);if(s(t)===`cli.mjs`&&s(c(t))===`dist`)return t;let n=t.split(p),r=n.lastIndexOf(`packages`);if(r===-1||n[r+1]!==`cli`)throw Error(`Cannot infer the repo root for --dev-mcp from ${t}. Run the local CLI from this repo so the built dist path can be derived.`);let i=n.slice(0,r);return u(i.length===0?p:i.join(p),`packages`,`cli`,`dist`,`cli.mjs`)}function I(e={}){return e.mode===`dev`?{command:T,args:[F(),`mcp`],env:{...E}}:(e.platformName??process.platform)===`win32`?{command:`powershell`,args:[`-NoProfile`,`-NonInteractive`,`-Command`,A]}:{command:`/bin/sh`,args:[`-l`,`-c`,O]}}function te(e={}){return e.mode===`dev`?{type:`local`,enabled:!0,command:[T,F(),`mcp`],environment:{...E}}:(e.platformName??process.platform)===`win32`?{type:`local`,enabled:!0,command:[`powershell`,`-NoProfile`,`-NonInteractive`,`-Command`,A]}:{type:`local`,enabled:!0,command:[`/bin/sh`,`-l`,`-c`,O]}}function L(e){if(typeof e!=`object`||!e)return!1;let t=e;return R(t,I({mode:`published`,platformName:`darwin`}))||R(t,I({mode:`published`,platformName:`win32`}))}function R(e,t){if(Object.keys(e).length!==Object.keys(t).length||e.command!==t.command)return!1;let n=t.args;return!Array.isArray(n)||!Array.isArray(e.args)||e.args.length!==n.length?!1:e.args.every((e,t)=>e===n[t])}function z(e){return e===`win32`?m:d}function B(e={}){let t=e.platformName??process.platform,n=e.home??h(),r=e.env??process.env,i=z(t);return t===`darwin`?i.join(n,`Library`,`Application Support`):t===`win32`?r.APPDATA??i.join(n,`AppData`,`Roaming`):r.XDG_CONFIG_HOME??i.join(n,`.config`)}function V(e={}){let t=e.platformName??process.platform,n=e.home??h();return z(t).join(n,`.claude.json`)}function H(e={}){let t=e.platformName??process.platform,n=e.home??h(),r=e.env??process.env;if(t===`darwin`)return d.join(n,`Library`,`Application Support`,`Claude`,`claude_desktop_config.json`);if(t===`win32`){let e=r.APPDATA??m.join(n,`AppData`,`Roaming`);return m.join(e,`Claude`,`claude_desktop_config.json`)}throw Error(`Claude Desktop is not available on ${t}. Supported: macOS, Windows.`)}function U(e={}){let t=e.platformName??process.platform,n=e.home??h();return z(t).join(n,`.cursor`,`mcp.json`)}function W(e={}){let t=e.platformName??process.platform,n=e.home??h();return(e.env??process.env).CODEX_HOME??z(t).join(n,`.codex`)}function G(e={}){return z(e.platformName??process.platform).join(W(e),`config.toml`)}function K(e={}){let t=e.platformName??process.platform,n=e.home??h(),r=e.env??process.env,i=z(t);if(t===`win32`){let e=r.APPDATA??i.join(n,`AppData`,`Roaming`);return i.join(e,`opencode`)}let a=r.XDG_CONFIG_HOME??i.join(n,`.config`);return i.join(a,`opencode`)}function q(e={}){return z(e.platformName??process.platform).join(K(e),`opencode.json`)}function J(e={}){let t=e.platformName??process.platform,n=e.home??h();return z(t).join(n,`.openclaw`,`openclaw.json`)}function Y(e={}){let t=e.platformName??process.platform,n=e.home??h();return(e.env??process.env).PI_CODING_AGENT_DIR??z(t).join(n,`.pi`,`agent`)}const X={claude:{id:`claude`,label:C.claude,configPath:(e,t)=>V({home:t}),format:`json`,topLevelKey:`mcpServers`,serverName:()=>n,buildEntry:(e,t)=>I(t),scope:`global`,detectPath:(e,t)=>u(t??h(),`.claude`),projectConfigPath:e=>u(e,`.mcp.json`),projectSkillPath:e=>u(e,`.claude`,`skills`,`open-knowledge`,`SKILL.md`)},"claude-desktop":{id:`claude-desktop`,label:C[`claude-desktop`],configPath:(e,t)=>H({home:t}),format:`json`,topLevelKey:`mcpServers`,serverName:()=>n,buildEntry:(e,t)=>I(t),scope:`global`,detectPath:(e,t)=>c(H({home:t}))},cursor:{id:`cursor`,label:C.cursor,configPath:(e,t)=>U({home:t}),format:`json`,topLevelKey:`mcpServers`,serverName:()=>n,buildEntry:(e,t)=>I(t),scope:`global`,detectPath:(e,t)=>c(U({home:t})),projectConfigPath:e=>u(e,`.cursor`,`mcp.json`),projectSkillPath:e=>u(e,`.cursor`,`skills`,`open-knowledge`,`SKILL.md`)},codex:{id:`codex`,label:C.codex,configPath:(e,t)=>G({home:t}),format:`toml`,topLevelKey:`mcp_servers`,serverName:()=>n,buildEntry:(e,t)=>I(t),scope:`global`,detectPath:(e,t)=>c(G({home:t})),projectConfigPath:e=>u(e,`.codex`,`config.toml`),projectSkillPath:e=>u(e,`.codex`,`skills`,`open-knowledge`,`SKILL.md`)},opencode:{id:`opencode`,label:C.opencode,configPath:(e,t)=>q({home:t}),format:`json`,topLevelKey:`mcp`,serverName:()=>n,buildEntry:(e,t)=>te(t),scope:`global`,detectPath:(e,t)=>c(q({home:t})),projectConfigPath:e=>u(e,`opencode.json`),projectSkillPath:e=>u(e,`.opencode`,`skills`,`open-knowledge`,`SKILL.md`)},openclaw:{id:`openclaw`,label:C.openclaw,configPath:(e,t)=>J({home:t}),format:`json`,topLevelKey:`mcp`,serverMapSubKey:`servers`,serverName:()=>n,buildEntry:(e,t)=>I(t),scope:`global`,detectPath:(e,t)=>u(t??h(),`.openclaw`),offerOnlyWhenDetected:!0},pi:{id:`pi`,label:C.pi,configPath:()=>{throw Error("Pi has no user-global MCP config; OK's integration is the project-scoped bridge extension at .pi/extensions/open-knowledge.ts (run `ok init` in the project).")},format:`file`,topLevelKey:`mcpServers`,serverName:()=>n,buildEntry:()=>{throw Error(`Pi has no MCP entry shape; the managed bridge file is built by buildPiExtensionSource (integrations/pi-extension.ts).`)},scope:`project`,detectPath:(e,t)=>Y({home:t}),projectConfigPath:e=>u(e,`.pi`,`extensions`,`open-knowledge.ts`),projectSkillPath:e=>u(e,`.pi`,`skills`,`open-knowledge`,`SKILL.md`)}};function Z(e){let t=e.filter(e=>!Object.hasOwn(X,e));if(t.length>0)throw Error(`Unknown editor(s): ${t.join(`, `)}. Valid options: ${S.join(`, `)}`);return e.map(e=>X[e])}function Q(e){let t=[];for(let n of o){let r=i[n];t.push({path:u(e,`.agents`,`skills`,r),bundleId:n,scope:`central`});for(let i of w)t.push({path:u(e,i.hostDir,`skills`,r),bundleId:n,scope:`host`,hostDir:i.hostDir})}return t}function ne(e,t){let n=[];for(let r of Q(e))if(r.bundleId===t)try{x(r.path,{recursive:!0,force:!0})}catch(e){n.push(e instanceof Error?e:Error(String(e)))}if(n.length>0)throw AggregateError(n,`Failed to remove ${n.length} path(s) for ${t}`)}function $(e,t){let n;try{n=b(t)}catch{n=f(t)}let r;try{r=v(e)}catch(e){if(e.code!==`ENOENT`)throw e}if(r?.isSymbolicLink())throw Error(`Refusing to write through a symbolic link at ${e}. Remove the symlink and re-run project setup.`);let i=c(e);for(;i.length>1&&i!==p;){let t;try{t=b(i)}catch(e){if(e.code===`ENOENT`){i=c(i);continue}throw e}let r=ee(n,t);if(r===``||!r.startsWith(`..`)&&!l(r))return;throw Error(`Refusing to write at ${e}: ancestor ${i} resolves to ${t}, which is outside the project directory ${n}. A symbolic link in the path likely escapes the project. Remove the symlink and re-run project setup.`)}}function re(e,t){let n=e.projectSkillPath?.(t);if(!n)return{editorId:e.id,label:e.label,action:`skipped-unsupported`,path:``};try{let r=a(`project`,{checkDesktop:!0}),i=c(n);$(i,t);let o=_(n)?`overwritten`:`written`;return x(i,{recursive:!0,force:!0}),y(c(i),{recursive:!0}),g(r,i,{recursive:!0}),{editorId:e.id,label:e.label,action:o,path:n}}catch(t){return{editorId:e.id,label:e.label,action:`failed`,path:n,error:t instanceof Error?t.message:String(t)}}}export{B as _,S as a,C as c,j as d,M as f,L as g,P as h,Q as i,X as l,I as m,re as n,D as o,N as p,ne as r,k as s,$ as t,w as u,F as v,Z as y};
|
|
36
|
-
//# sourceMappingURL=write-project-skill-
|
|
36
|
+
//# sourceMappingURL=write-project-skill-BEzL3S1a.mjs.map
|
package/package.json
CHANGED
package/dist/init-C60Y8z32.mjs
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{y as e}from"./init-Cw5lSFda.mjs";export{e as runInit};
|
package/dist/loader-AzVlDL9Q.mjs
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{n as e}from"./loader-BB3StuVP.mjs";export{e as loadConfig};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{n as e,t}from"./preview-VQLx0qR6.mjs";export{t as formatPreviewBlock,e as previewContent};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{t as e}from"./repair-skills-B9vf1LVl.mjs";export{e as repairSkills};
|
package/dist/start-yAdBlXBN.mjs
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{_ as e,f as t,r as n}from"./start-yTYIxEV0.mjs";export{n as bootStartServer,t as resolveHost,e as startCommand};
|