infra-kit 0.13.0 → 0.15.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.
Files changed (41) hide show
  1. package/dist/{chunk-FKA65HOC.js → chunk-3UE375II.js} +2 -2
  2. package/dist/{chunk-FKA65HOC.js.map → chunk-3UE375II.js.map} +1 -1
  3. package/dist/chunk-4RZM53X7.js +7 -0
  4. package/dist/{chunk-EU7LD5IV.js.map → chunk-4RZM53X7.js.map} +3 -3
  5. package/dist/{chunk-VDBJ73LS.js → chunk-DVXTZPQ5.js} +1 -1
  6. package/dist/chunk-DVXTZPQ5.js.map +7 -0
  7. package/dist/{chunk-D76UWTR5.js → chunk-EZ4DIT5A.js} +3 -3
  8. package/dist/{chunk-D76UWTR5.js.map → chunk-EZ4DIT5A.js.map} +1 -1
  9. package/dist/chunk-I23MDR4X.js +5 -0
  10. package/dist/chunk-I23MDR4X.js.map +7 -0
  11. package/dist/{chunk-CMF7HEVU.js → chunk-IT6XJWTW.js} +2 -2
  12. package/dist/chunk-IT6XJWTW.js.map +7 -0
  13. package/dist/{chunk-BQPSXIH2.js → chunk-MH37P7W4.js} +2 -2
  14. package/dist/chunk-PP3ZZKB3.js +12 -0
  15. package/dist/chunk-PP3ZZKB3.js.map +7 -0
  16. package/dist/{chunk-Z4ZY2G4O.js → chunk-ZTAUGYJF.js} +2 -2
  17. package/dist/cli.js +117 -109
  18. package/dist/cli.js.map +4 -4
  19. package/dist/dev-server.js +21 -21
  20. package/dist/dev-server.js.map +3 -3
  21. package/dist/{dev-wizard-run-SHX5YW6J.js → dev-wizard-run-6PLC5YEW.js} +2 -2
  22. package/dist/env-load-NURS7WNH.js +2 -0
  23. package/dist/mcp-proxy.js +7 -7
  24. package/dist/mcp-proxy.js.map +3 -3
  25. package/dist/{persistent-ink-dev-ui-P65EJCC6.js → persistent-ink-dev-ui-ZSOS3CF4.js} +2 -2
  26. package/dist/update-check.js +1 -1
  27. package/package.json +3 -3
  28. package/readme.md +5 -2
  29. package/dist/chunk-CMF7HEVU.js.map +0 -7
  30. package/dist/chunk-EU7LD5IV.js +0 -7
  31. package/dist/chunk-LR57E6IP.js +0 -10
  32. package/dist/chunk-LR57E6IP.js.map +0 -7
  33. package/dist/chunk-QSTGO43H.js +0 -4
  34. package/dist/chunk-QSTGO43H.js.map +0 -7
  35. package/dist/chunk-VDBJ73LS.js.map +0 -7
  36. package/dist/env-load-EYVU4TIM.js +0 -2
  37. /package/dist/{chunk-BQPSXIH2.js.map → chunk-MH37P7W4.js.map} +0 -0
  38. /package/dist/{chunk-Z4ZY2G4O.js.map → chunk-ZTAUGYJF.js.map} +0 -0
  39. /package/dist/{dev-wizard-run-SHX5YW6J.js.map → dev-wizard-run-6PLC5YEW.js.map} +0 -0
  40. /package/dist/{env-load-EYVU4TIM.js.map → env-load-NURS7WNH.js.map} +0 -0
  41. /package/dist/{persistent-ink-dev-ui-P65EJCC6.js.map → persistent-ink-dev-ui-ZSOS3CF4.js.map} +0 -0
@@ -1,2 +1,2 @@
1
- import{a as b,b as k,d as w,n as C}from"./chunk-Y3RW74TE.js";import{a as g,e as h,j as x}from"./chunk-EU7LD5IV.js";import{P as d,ca as v}from"./chunk-D76UWTR5.js";import"./chunk-MFAFQVTW.js";import"./chunk-FKA65HOC.js";import{e as y}from"./chunk-QSTGO43H.js";import"./chunk-QWVLAZ6N.js";import B from"@inquirer/checkbox";import j from"@inquirer/confirm";import _,{Separator as U}from"@inquirer/select";import{loadDev as I,loadPackageConfig as K}from"@slip-stream-kit/config/internal";import R from"node:path";import m from"node:process";var W=e=>e.split("/")[0],D=e=>new Map(e.apps.map(r=>[r.name,r])),$=e=>e.localCapable&&e.cloudCapable,N=(e,r,a)=>$(r)?a[`${e} ${r.path}`]??(r.cloudCapable?"cloud":"local"):r.localCapable?"local":"cloud",O=(e,r,a)=>{let n=new Set,t=new Map;for(let o of e){let s=r.get(W(o));for(let i of s?.backends??[]){t.set(i.packageName,i.ownerApp);for(let l of i.routes)N(o,l,a)==="local"&&n.add(i.packageName)}}return{localPkgs:n,ownerByPkg:t}},E=(e,r)=>{let a={},n=!1;for(let t of e?.backends??[]){let o=r.has(t.packageName);for(let s of t.routes){let i=s.localCapable&&o?"local":"cloud";a[s.path]=i,i==="cloud"&&(n=!0)}}return{overrides:a,anyCloud:n}},M=(e,r)=>{let a=D(r),n=e.targets.filter(c=>c.endsWith("/ui")),t=e.targets.filter(c=>c.endsWith("/api")),{localPkgs:o,ownerByPkg:s}=O(n,a,e.sources),i={},l=!1;for(let c of n){let{overrides:f,anyCloud:p}=E(a.get(W(c)),o);p&&(l=!0),i[c]=Object.keys(f).length>0?{proxy:f}:{}}for(let c of t)i[c]??={};for(let c of o){let f=s.get(c);f!=null&&(i[`${f}/api`]??={})}return{presetDef:{apps:i,orca:e.orca},anyCloudRoute:l,targetKeys:Object.keys(i).sort()}},z=(e,r)=>{let a=[`--target=${e.targetKeys.join(",")}`];return r.watch||a.push("--no-watch"),r.orca&&a.push("--orca"),{flags:a.join(" ")}};var P={output:m.stderr,clearPromptOnDone:!0},V={select:e=>h(r=>_({message:e.message,choices:e.choices,default:e.default},r),{...P,whenHeadless:"refuse"}),checkbox:e=>h(r=>B({message:e.message,choices:e.choices},r),{...P,whenHeadless:"refuse"}),confirm:e=>h(r=>j({message:e.message,default:e.default},r),{...P,whenHeadless:"refuse"})},q=(e,r)=>{let a=new Map;for(let[n,t]of Object.entries(e)){let o={path:n,localCapable:t.from.includes("local"),cloudCapable:t.from.includes("cloud"),default:t.default},s=a.get(t.packageName);s?(s.routes.push(o),s.localCapable=s.localCapable||o.localCapable,s.cloudCapable=s.cloudCapable||o.cloudCapable):a.set(t.packageName,{packageName:t.packageName,routes:[o],localCapable:o.localCapable,cloudCapable:o.cloudCapable,ownerApp:r.get(t.packageName)})}return[...a.values()]},L=async(e,r,a)=>{try{let n=(await I(e))?.proxy?.routes;return n?q(n,a):[]}catch(n){return d.warn(`\u26A0\uFE0F Skipping ${r}: its dev config failed to load \u2014 ${n instanceof Error?n.message:String(n)}`),[]}},T=async e=>{let r=k(e),a=w(e),n=await v(),t=new Map(r.map(p=>[p.packageName,p.name])),o=new Map(r.map(p=>[p.name,p.packageName])),s=new Set(a.map(p=>p.name)),i=new Set(r.map(p=>p.name)),l=[...new Set([...i,...s])].sort(),c=await Promise.all(l.map(async p=>{let u=s.has(p);return{name:p,hasApi:i.has(p),hasUi:u,apiPackage:o.get(p),backends:u?await L(R.join(e,"apps",p,"ui"),p,t):[],deployedUrlEnv:u?(await K(R.join(e,"apps",p,"ui")).catch(()=>{}))?.deployedUrlEnv:void 0}})),f=await x();return{apps:c,presets:Object.keys(n.devServersPresets??{}),environments:Object.keys(f?.envs??{}).sort()}},F=e=>{let r=[];for(let a of e.apps){if(a.hasUi){let n=a.backends.flatMap(o=>o.routes.map(s=>s.path)),t=n.length>0?`frontend \u2014 proxies ${[...n].sort().join(", ")}`:"frontend";r.push({name:`${a.name}/ui`,value:`${a.name}/ui`,description:t})}a.hasApi&&!a.hasUi&&r.push({name:`${a.name}/api`,value:`${a.name}/api`,description:"backend"})}return r},H=e=>{let r={api:e.apps.filter(t=>t.hasApi).map(t=>t.name),ui:e.apps.filter(t=>t.hasUi).map(t=>t.name)},a={},n=new Map;for(let t of e.apps){t.apiPackage!=null&&(a[t.name]=t.apiPackage);for(let o of t.backends)for(let s of o.routes)n.set(`${t.name} ${s.path}`,o.packageName)}return{discovered:r,apiPkgByApp:a,routePkg:(t,o)=>n.get(`${t} ${o}`)}},Z=(e,r)=>C({__wizard__:e},H(r)).map(a=>a.message),G="INFRA_KIT_DEV_WIZARD_ORCA",J=()=>m.env[G]==="1",Q=async(e,r,a)=>{let n=new Map(r.apps.map(o=>[o.name,o])),t={};for(let o of a){let s=n.get(o.split("/")[0]);for(let i of s?.backends??[])for(let l of i.routes){if(!l.localCapable||!l.cloudCapable)continue;let c=await e.select({message:`\u{1F500} ${o} ${l.path} \u2192 local or cloud?`,choices:[{name:"local (this machine)",value:"local"},{name:"cloud",value:"cloud"}],default:l.default??"local"});t[`${o} ${l.path}`]=c}}return t},X=(e,r,a)=>e.apps.find(n=>n.name===r)?.backends.flatMap(n=>n.routes).find(n=>n.path===a),Y=(e,r)=>{let a=[];for(let[n,t]of Object.entries(e.presetDef.apps??{})){if(!n.endsWith("/ui")||!t.proxy)continue;let o=n.split("/")[0];for(let[s,i]of Object.entries(t.proxy)){let l=X(r,o,s),c=l&&l.localCapable&&l.cloudCapable?"":" (only option)";a.push(` ${n} ${s} \u2192 ${i}${c}`)}}if(a.length!==0){d.info("Resolved routes:");for(let n of[...a].sort())d.info(n)}},ee=async(e,r)=>{let{downloadEnvSecrets:a}=await import("./env-load-EYVU4TIM.js"),n=await a(e);return new Map(r.flatMap(t=>{let o=n.get(t);return o===void 0?[]:[[t,o]]}))},re=async(e,r,a,n)=>{let t=r.flatMap(s=>{let i=a.apps.find(l=>`${l.name}/ui`===s);return i?.deployedUrlEnv?[i.deployedUrlEnv]:[]}),o=t.length>0?await n(e,t):new Map;m.env[y]=e;for(let s of t){let i=o.get(s);i?m.env[s]=i:(delete m.env[s],d.warn(`\u2601\uFE0F "${e}" holds no ${s}; routes that go to the deployed app will fail until it does.`))}},S=async(e,r,a)=>{if(r.apps.length===0)return d.warn("No apps discovered to run."),null;let n=await e.checkbox({message:"\u{1F4E6} Which packages?",choices:F(r)});if(n.length===0)return d.warn("No packages selected."),null;let t=n.filter(u=>u.endsWith("/ui")),o=await Q(e,r,t),s=await e.confirm({message:"\u{1F440} Rebuild & restart on save (watch)?",default:!0}),i=J()?await e.confirm({message:"\u{1F9E9} Run each app in its own Orca pane?",default:!1}):!1,l={targets:n,sources:o,watch:s,orca:i},c=M(l,r);if(c.anyCloudRoute){if(r.environments.length===0)return d.warn("\u2601\uFE0F This selection routes to a cloud environment, but no environment token is loaded."),d.warn(" Run `infra-kit env-load` to add one, then re-run the wizard."),null;l.env=await e.select({message:"\u2601\uFE0F Point cloud routes at which environment?",choices:r.environments.map(u=>({name:u,value:u}))}),await re(l.env,t,r,a)}let f=Z(c.presetDef,r);if(f.length>0){d.warn("\u26A0\uFE0F Proxy audit found issues with this selection:");for(let u of f)d.warn(` \u2022 ${u}`);return null}Y(c,r),ae(c,l);let p=c.targetKeys.filter(u=>u.endsWith("/api")).map(u=>u.split("/")[0]);return i&&p.length>0?{include:p,presetDef:c.presetDef,watch:s,orca:!0}:(i&&d.info("\u2139\uFE0F Orca needs at least one local backend (panes are backend-only) \u2014 running in-process instead."),{presetDef:c.presetDef,watch:s,orca:!1})},ae=(e,r)=>{g.setInteractive();let a=z(e,r);g.addOption(a.flags,!0),g.print(),d.info("\u2139\uFE0F Prefer a short name? Save this selection as a devPreset and run `infra-kit dev <name>`.")},te=async(e,r)=>{let a=await e.confirm({message:"\u{1F440} Rebuild & restart on save (watch)?",default:!0});return g.setInteractive(),g.addOption(r,!0),a||g.addOption("--no-watch",!0),g.print(),{preset:r,watch:a,orca:!1}},A=" manual",ne=async(e,r,a=ee)=>{if(r.presets.length===0)return S(e,r,a);let n=await e.select({message:"\u{1F680} Start from a preset, or configure manually?",choices:[...r.presets.map(t=>({name:t,value:t})),new U(" "),{name:"Manual (custom)\u2026",value:A}]});return n===A?S(e,r,a):te(e,n)},ke=async(e=V,r=b(m.cwd()))=>ne(e,await T(r));export{A as MANUAL_CHOICE,G as WIZARD_ORCA_VAR,Z as auditManualPlan,V as defaultPrompts,T as gatherWizardModel,L as loadBackends,ke as runDevWizard,ne as runWizardFlow};
2
- //# sourceMappingURL=dev-wizard-run-SHX5YW6J.js.map
1
+ import{a as b,b as k,d as w,n as C}from"./chunk-Y3RW74TE.js";import{a as g,e as h,j as x}from"./chunk-4RZM53X7.js";import{P as d,da as v}from"./chunk-EZ4DIT5A.js";import"./chunk-MFAFQVTW.js";import"./chunk-3UE375II.js";import{f as y}from"./chunk-I23MDR4X.js";import"./chunk-QWVLAZ6N.js";import B from"@inquirer/checkbox";import j from"@inquirer/confirm";import _,{Separator as U}from"@inquirer/select";import{loadDev as I,loadPackageConfig as K}from"@slip-stream-kit/config/internal";import R from"node:path";import m from"node:process";var W=e=>e.split("/")[0],D=e=>new Map(e.apps.map(r=>[r.name,r])),$=e=>e.localCapable&&e.cloudCapable,N=(e,r,a)=>$(r)?a[`${e} ${r.path}`]??(r.cloudCapable?"cloud":"local"):r.localCapable?"local":"cloud",O=(e,r,a)=>{let n=new Set,t=new Map;for(let o of e){let s=r.get(W(o));for(let i of s?.backends??[]){t.set(i.packageName,i.ownerApp);for(let l of i.routes)N(o,l,a)==="local"&&n.add(i.packageName)}}return{localPkgs:n,ownerByPkg:t}},E=(e,r)=>{let a={},n=!1;for(let t of e?.backends??[]){let o=r.has(t.packageName);for(let s of t.routes){let i=s.localCapable&&o?"local":"cloud";a[s.path]=i,i==="cloud"&&(n=!0)}}return{overrides:a,anyCloud:n}},M=(e,r)=>{let a=D(r),n=e.targets.filter(c=>c.endsWith("/ui")),t=e.targets.filter(c=>c.endsWith("/api")),{localPkgs:o,ownerByPkg:s}=O(n,a,e.sources),i={},l=!1;for(let c of n){let{overrides:f,anyCloud:p}=E(a.get(W(c)),o);p&&(l=!0),i[c]=Object.keys(f).length>0?{proxy:f}:{}}for(let c of t)i[c]??={};for(let c of o){let f=s.get(c);f!=null&&(i[`${f}/api`]??={})}return{presetDef:{apps:i,orca:e.orca},anyCloudRoute:l,targetKeys:Object.keys(i).sort()}},z=(e,r)=>{let a=[`--target=${e.targetKeys.join(",")}`];return r.watch||a.push("--no-watch"),r.orca&&a.push("--orca"),{flags:a.join(" ")}};var P={output:m.stderr,clearPromptOnDone:!0},V={select:e=>h(r=>_({message:e.message,choices:e.choices,default:e.default},r),{...P,whenHeadless:"refuse"}),checkbox:e=>h(r=>B({message:e.message,choices:e.choices},r),{...P,whenHeadless:"refuse"}),confirm:e=>h(r=>j({message:e.message,default:e.default},r),{...P,whenHeadless:"refuse"})},q=(e,r)=>{let a=new Map;for(let[n,t]of Object.entries(e)){let o={path:n,localCapable:t.from.includes("local"),cloudCapable:t.from.includes("cloud"),default:t.default},s=a.get(t.packageName);s?(s.routes.push(o),s.localCapable=s.localCapable||o.localCapable,s.cloudCapable=s.cloudCapable||o.cloudCapable):a.set(t.packageName,{packageName:t.packageName,routes:[o],localCapable:o.localCapable,cloudCapable:o.cloudCapable,ownerApp:r.get(t.packageName)})}return[...a.values()]},L=async(e,r,a)=>{try{let n=(await I(e))?.proxy?.routes;return n?q(n,a):[]}catch(n){return d.warn(`\u26A0\uFE0F Skipping ${r}: its dev config failed to load \u2014 ${n instanceof Error?n.message:String(n)}`),[]}},T=async e=>{let r=k(e),a=w(e),n=await v(),t=new Map(r.map(p=>[p.packageName,p.name])),o=new Map(r.map(p=>[p.name,p.packageName])),s=new Set(a.map(p=>p.name)),i=new Set(r.map(p=>p.name)),l=[...new Set([...i,...s])].sort(),c=await Promise.all(l.map(async p=>{let u=s.has(p);return{name:p,hasApi:i.has(p),hasUi:u,apiPackage:o.get(p),backends:u?await L(R.join(e,"apps",p,"ui"),p,t):[],deployedUrlEnv:u?(await K(R.join(e,"apps",p,"ui")).catch(()=>{}))?.deployedUrlEnv:void 0}})),f=await x();return{apps:c,presets:Object.keys(n.devServersPresets??{}),environments:Object.keys(f?.envs??{}).sort()}},F=e=>{let r=[];for(let a of e.apps){if(a.hasUi){let n=a.backends.flatMap(o=>o.routes.map(s=>s.path)),t=n.length>0?`frontend \u2014 proxies ${[...n].sort().join(", ")}`:"frontend";r.push({name:`${a.name}/ui`,value:`${a.name}/ui`,description:t})}a.hasApi&&!a.hasUi&&r.push({name:`${a.name}/api`,value:`${a.name}/api`,description:"backend"})}return r},H=e=>{let r={api:e.apps.filter(t=>t.hasApi).map(t=>t.name),ui:e.apps.filter(t=>t.hasUi).map(t=>t.name)},a={},n=new Map;for(let t of e.apps){t.apiPackage!=null&&(a[t.name]=t.apiPackage);for(let o of t.backends)for(let s of o.routes)n.set(`${t.name} ${s.path}`,o.packageName)}return{discovered:r,apiPkgByApp:a,routePkg:(t,o)=>n.get(`${t} ${o}`)}},Z=(e,r)=>C({__wizard__:e},H(r)).map(a=>a.message),G="INFRA_KIT_DEV_WIZARD_ORCA",J=()=>m.env[G]==="1",Q=async(e,r,a)=>{let n=new Map(r.apps.map(o=>[o.name,o])),t={};for(let o of a){let s=n.get(o.split("/")[0]);for(let i of s?.backends??[])for(let l of i.routes){if(!l.localCapable||!l.cloudCapable)continue;let c=await e.select({message:`\u{1F500} ${o} ${l.path} \u2192 local or cloud?`,choices:[{name:"local (this machine)",value:"local"},{name:"cloud",value:"cloud"}],default:l.default??"local"});t[`${o} ${l.path}`]=c}}return t},X=(e,r,a)=>e.apps.find(n=>n.name===r)?.backends.flatMap(n=>n.routes).find(n=>n.path===a),Y=(e,r)=>{let a=[];for(let[n,t]of Object.entries(e.presetDef.apps??{})){if(!n.endsWith("/ui")||!t.proxy)continue;let o=n.split("/")[0];for(let[s,i]of Object.entries(t.proxy)){let l=X(r,o,s),c=l&&l.localCapable&&l.cloudCapable?"":" (only option)";a.push(` ${n} ${s} \u2192 ${i}${c}`)}}if(a.length!==0){d.info("Resolved routes:");for(let n of[...a].sort())d.info(n)}},ee=async(e,r)=>{let{downloadEnvSecrets:a}=await import("./env-load-NURS7WNH.js"),n=await a(e);return new Map(r.flatMap(t=>{let o=n.get(t);return o===void 0?[]:[[t,o]]}))},re=async(e,r,a,n)=>{let t=r.flatMap(s=>{let i=a.apps.find(l=>`${l.name}/ui`===s);return i?.deployedUrlEnv?[i.deployedUrlEnv]:[]}),o=t.length>0?await n(e,t):new Map;m.env[y]=e;for(let s of t){let i=o.get(s);i?m.env[s]=i:(delete m.env[s],d.warn(`\u2601\uFE0F "${e}" holds no ${s}; routes that go to the deployed app will fail until it does.`))}},S=async(e,r,a)=>{if(r.apps.length===0)return d.warn("No apps discovered to run."),null;let n=await e.checkbox({message:"\u{1F4E6} Which packages?",choices:F(r)});if(n.length===0)return d.warn("No packages selected."),null;let t=n.filter(u=>u.endsWith("/ui")),o=await Q(e,r,t),s=await e.confirm({message:"\u{1F440} Rebuild & restart on save (watch)?",default:!0}),i=J()?await e.confirm({message:"\u{1F9E9} Run each app in its own Orca pane?",default:!1}):!1,l={targets:n,sources:o,watch:s,orca:i},c=M(l,r);if(c.anyCloudRoute){if(r.environments.length===0)return d.warn("\u2601\uFE0F This selection routes to a cloud environment, but no environment token is loaded."),d.warn(" Run `infra-kit env-load` to add one, then re-run the wizard."),null;l.env=await e.select({message:"\u2601\uFE0F Point cloud routes at which environment?",choices:r.environments.map(u=>({name:u,value:u}))}),await re(l.env,t,r,a)}let f=Z(c.presetDef,r);if(f.length>0){d.warn("\u26A0\uFE0F Proxy audit found issues with this selection:");for(let u of f)d.warn(` \u2022 ${u}`);return null}Y(c,r),ae(c,l);let p=c.targetKeys.filter(u=>u.endsWith("/api")).map(u=>u.split("/")[0]);return i&&p.length>0?{include:p,presetDef:c.presetDef,watch:s,orca:!0}:(i&&d.info("\u2139\uFE0F Orca needs at least one local backend (panes are backend-only) \u2014 running in-process instead."),{presetDef:c.presetDef,watch:s,orca:!1})},ae=(e,r)=>{g.setInteractive();let a=z(e,r);g.addOption(a.flags,!0),g.print(),d.info("\u2139\uFE0F Prefer a short name? Save this selection as a devPreset and run `infra-kit dev <name>`.")},te=async(e,r)=>{let a=await e.confirm({message:"\u{1F440} Rebuild & restart on save (watch)?",default:!0});return g.setInteractive(),g.addOption(r,!0),a||g.addOption("--no-watch",!0),g.print(),{preset:r,watch:a,orca:!1}},A=" manual",ne=async(e,r,a=ee)=>{if(r.presets.length===0)return S(e,r,a);let n=await e.select({message:"\u{1F680} Start from a preset, or configure manually?",choices:[...r.presets.map(t=>({name:t,value:t})),new U(" "),{name:"Manual (custom)\u2026",value:A}]});return n===A?S(e,r,a):te(e,n)},ke=async(e=V,r=b(m.cwd()))=>ne(e,await T(r));export{A as MANUAL_CHOICE,G as WIZARD_ORCA_VAR,Z as auditManualPlan,V as defaultPrompts,T as gatherWizardModel,L as loadBackends,ke as runDevWizard,ne as runWizardFlow};
2
+ //# sourceMappingURL=dev-wizard-run-6PLC5YEW.js.map
@@ -0,0 +1,2 @@
1
+ import{A as g,B as h,C as i,D as j,E as k,F as l,G as m,u as a,v as b,w as c,x as d,y as e,z as f}from"./chunk-PP3ZZKB3.js";import"./chunk-4RZM53X7.js";import"./chunk-EZ4DIT5A.js";import"./chunk-MFAFQVTW.js";import"./chunk-3UE375II.js";import"./chunk-I23MDR4X.js";import"./chunk-QWVLAZ6N.js";export{e as DOPPLER_MAX_OUTPUT_BYTES,j as assertDopplerOutputSize,h as assertTokenScope,f as buildDopplerChildEnv,a as buildEnvLoadFileLines,g as downloadEnvSecrets,d as envLoad,m as envLoadMcpTool,l as parseDopplerSecretsJson,b as resolveEnvLoadRoots,k as shellSingleQuote,i as translateDopplerDownloadError,c as writeEnvLoadFile};
2
+ //# sourceMappingURL=env-load-NURS7WNH.js.map
package/dist/mcp-proxy.js CHANGED
@@ -1,11 +1,11 @@
1
1
  #!/usr/bin/env node
2
- import{x as G}from"./chunk-CMF7HEVU.js";import"./chunk-AWFGP6GY.js";import{a as M}from"./chunk-MFAFQVTW.js";import{a as W,c as H,k as T,m as E,o as K}from"./chunk-QSTGO43H.js";import p from"node:process";var ve=/^[a-z][a-z0-9-]*$/,ye=/^[A-Z_]\w*$/i,Pe=(e,r,n)=>r==="--name"?e.name!==null?"--name given twice":ve.test(n)?(e.name=n,null):`--name "${n}" must be lowercase letters, digits and hyphens`:r==="--env"||r==="--unset"?ye.test(n)?M.has(n)?`${r} "${n}" is process plumbing, not a credential`:(r==="--env"?e.env.push(n):e.unset.push(n),null):`${r} "${n}" is not an environment-variable name`:`unknown flag ${r}`,Se=(e,r)=>{let n=0;for(;n<e.length;){let o=e[n];if(o==="--")return{separator:n};if(!o.startsWith("--"))return{problem:`missing "--" before the upstream command (saw "${o}")`};let a=e[n+1];if(a===void 0||a.startsWith("--"))return{problem:`${o} needs a value`};let m=Pe(r,o,a);if(m!==null)return{problem:m};n+=2}return{problem:'missing "--" before the upstream command'}},Q=e=>{let r={name:null,env:[],unset:[]},n=Se(e,r);if("problem"in n)return{ok:!1,problem:n.problem};if(r.name===null)return{ok:!1,problem:"missing --name"};if(r.env.length===0)return{ok:!1,problem:"missing --env (at least one variable to read)"};let o=e[n.separator+1];return o===void 0||o.length===0?{ok:!1,problem:'missing upstream command after "--"'}:{ok:!0,spec:{name:r.name,command:o,args:e.slice(n.separator+2),env:r.env,unset:r.unset}}};import{spawnSync as xe}from"node:child_process";import C from"node:fs";import x from"node:path";import O from"node:process";var Y=e=>x.join(E(),"mcp-proxy",e),be=e=>e.replaceAll(/[^\w.-]/g,"_").slice(0,64),Z=(e,r)=>x.join(r,`profile-${be(e)}.json`),A=(e,r)=>{let n=x.isAbsolute(e)?[e]:(r??O.env.PATH??"").split(x.delimiter).map(o=>x.join(o,e));for(let o of n)try{let a=C.statSync(o);return`stat-${a.size}-${Math.trunc(a.mtimeMs)}`}catch{}return"unknown"},X=(e,r=["--version"],n)=>{try{let o=xe(e,[...r],{encoding:"utf8",timeout:5e3,env:n==null?O.env:{...O.env,PATH:n}});if(o.status!==0)return A(e,n);let a=`${o.stdout}`.trim().split(`
3
- `)[0]?.trim()??"";return a.length>0?a:A(e,n)}catch{return A(e,n)}},ee=(e,r)=>{try{let n=JSON.parse(C.readFileSync(Z(e,r),"utf8"));return n.version!==e||!Array.isArray(n.tools)?null:{version:e,protocolVersion:typeof n.protocolVersion=="string"?n.protocolVersion:"",capabilities:n.capabilities??{},tools:n.tools}}catch{return null}},ne=(e,r)=>{try{return C.mkdirSync(r,{recursive:!0}),K(Z(e.version,r),`${JSON.stringify(e)}
4
- `,384),!0}catch{return!1}};import we from"node:path";import L from"node:process";var Ee="no-session",Me="IK_MCP_ENV_FILE",Re=()=>{let e=L.env[H];return e!=null&&e.length>0?e:Ee},R=()=>{let e=L.env[Me];return e!=null&&e.length>0?e:we.join(E(),Re(),W)},$e=(e,r)=>{let n=e[r];if(n!=null&&n.length>0)return n;let o=L.env[r];return o!=null&&o.length>0?o:""},re=(e,r=R())=>{let n=T(r),o={};for(let a of e){let m=$e(n,a);if(m.length===0)return null;o[a]=m}return o},te=(e,r=R())=>{let n=new Set(e);return Object.keys(T(r)).filter(o=>!n.has(o))};var $=(e,r)=>{let n="";e.setEncoding("utf8"),e.on("data",o=>{n+=o;let a=n.indexOf(`
2
+ import{x as Z}from"./chunk-IT6XJWTW.js";import"./chunk-AWFGP6GY.js";import{a as M}from"./chunk-MFAFQVTW.js";import{a as H,c as K,d as G,l as A,n as b,p as Q,r as Y}from"./chunk-I23MDR4X.js";import p from"node:process";var Se=/^[a-z][a-z0-9-]*$/,we=/^[A-Z_]\w*$/i,xe=(e,r,n)=>r==="--name"?e.name!==null?"--name given twice":Se.test(n)?(e.name=n,null):`--name "${n}" must be lowercase letters, digits and hyphens`:r==="--env"||r==="--unset"?we.test(n)?M.has(n)?`${r} "${n}" is process plumbing, not a credential`:(r==="--env"?e.env.push(n):e.unset.push(n),null):`${r} "${n}" is not an environment-variable name`:`unknown flag ${r}`,Ee=(e,r)=>{let n=0;for(;n<e.length;){let o=e[n];if(o==="--")return{separator:n};if(!o.startsWith("--"))return{problem:`missing "--" before the upstream command (saw "${o}")`};let a=e[n+1];if(a===void 0||a.startsWith("--"))return{problem:`${o} needs a value`};let m=xe(r,o,a);if(m!==null)return{problem:m};n+=2}return{problem:'missing "--" before the upstream command'}},X=e=>{let r={name:null,env:[],unset:[]},n=Ee(e,r);if("problem"in n)return{ok:!1,problem:n.problem};if(r.name===null)return{ok:!1,problem:"missing --name"};if(r.env.length===0)return{ok:!1,problem:"missing --env (at least one variable to read)"};let o=e[n.separator+1];return o===void 0||o.length===0?{ok:!1,problem:'missing upstream command after "--"'}:{ok:!0,spec:{name:r.name,command:o,args:e.slice(n.separator+2),env:r.env,unset:r.unset}}};import{spawnSync as be}from"node:child_process";import C from"node:fs";import w from"node:path";import L from"node:process";var ee=e=>w.join(b(),"mcp-proxy",e),Me=e=>e.replaceAll(/[^\w.-]/g,"_").slice(0,64),ne=(e,r)=>w.join(r,`profile-${Me(e)}.json`),O=(e,r)=>{let n=w.isAbsolute(e)?[e]:(r??L.env.PATH??"").split(w.delimiter).map(o=>w.join(o,e));for(let o of n)try{let a=C.statSync(o);return`stat-${a.size}-${Math.trunc(a.mtimeMs)}`}catch{}return"unknown"},re=(e,r=["--version"],n)=>{try{let o=be(e,[...r],{encoding:"utf8",timeout:5e3,env:n==null?L.env:{...L.env,PATH:n}});if(o.status!==0)return O(e,n);let a=`${o.stdout}`.trim().split(`
3
+ `)[0]?.trim()??"";return a.length>0?a:O(e,n)}catch{return O(e,n)}},te=(e,r)=>{try{let n=JSON.parse(C.readFileSync(ne(e,r),"utf8"));return n.version!==e||!Array.isArray(n.tools)?null:{version:e,protocolVersion:typeof n.protocolVersion=="string"?n.protocolVersion:"",capabilities:n.capabilities??{},tools:n.tools}}catch{return null}},oe=(e,r)=>{try{return C.mkdirSync(r,{recursive:!0}),Q(ne(e.version,r),`${JSON.stringify(e)}
4
+ `,384),!0}catch{return!1}};import F from"node:path";import R from"node:process";var Re="no-session",$e="IK_MCP_ENV_FILE",ke=()=>{let e=R.env[G];return e!=null&&e.length>0?e:Re},$=()=>{let e=R.env[$e];return e!=null&&e.length>0?e:F.join(b(),ke(),H)},_e=(e,r)=>{let n=e[r];if(n!=null&&n.length>0)return n;let o=R.env[r];return o!=null&&o.length>0?o:""},se=(e,r=$())=>{let n=Y(F.join(F.dirname(r),K),R.cwd())?A(r):{},o={};for(let a of e){let m=_e(n,a);if(m.length===0)return null;o[a]=m}return o},ie=(e,r=$())=>{let n=new Set(e);return Object.keys(A(r)).filter(o=>!n.has(o))};var k=(e,r)=>{let n="";e.setEncoding("utf8"),e.on("data",o=>{n+=o;let a=n.indexOf(`
5
5
  `);for(;a!==-1;){let m=n.slice(0,a);n=n.slice(a+1);let f=m.endsWith("\r")?m.slice(0,-1):m;f.trim().length>0&&r(f),a=n.indexOf(`
6
- `)}})};import{spawn as ke}from"node:child_process";import Je from"node:os";import F from"node:path";import k from"node:process";var Ie=()=>{let e=k.env.GOBIN;if(e!=null&&e.length>0)return e;let r=k.env.GOPATH;return F.join(r!=null&&r.length>0?r:F.join(Je.homedir(),"go"),"bin")},Ve=15e3,_e=12e4,Ne=M,oe=(e,r={})=>{let n=e.command,o=e.args,a=r.readyTimeoutMs??Ve,m=r.requestTimeoutMs??_e,f=r.log??(()=>{}),ce=r.onServerMessage??(()=>{}),de=`${Ie()}${F.delimiter}${k.env.PATH??""}`,z={},d=null,y=null,_=0,ue=(t,i)=>{for(let s of t.pending.values())s.reject(new Error(i));t.pending.clear()},P=(t,i)=>{t.closed||(t.closed=!0,ue(t,`${e.name} upstream ${i}`),t.child.kill())},pe=(t,i)=>{let s;try{s=JSON.parse(i)}catch{f(`ignoring non-JSON line from ${n}`);return}if(s.method!=null){if(s.id==null){ce(s);return}f(`refusing server-initiated request ${s.method}`),w(t,{jsonrpc:"2.0",id:s.id,error:{code:-32601,message:"client requests are not supported by this shim"}});return}if(s.id==null)return;let l=t.pending.get(Number(s.id));l&&(t.pending.delete(Number(s.id)),l.resolve(l.clientId===void 0?s:{...s,id:l.clientId}))},w=(t,i)=>{t.closed||t.child.stdin.write(`${JSON.stringify(i)}
7
- `)},q=(t,i,s)=>{if(t.closed)return Promise.reject(new Error(`${e.name} upstream is closed`));let l=t.nextId;return t.nextId+=1,new Promise((c,S)=>{let B=setTimeout(()=>{t.pending.delete(l),S(new Error(`${n} did not answer ${i.method??"request"} within ${m}ms`))},m);t.pending.set(l,{clientId:s,resolve:N=>{clearTimeout(B),c(N)},reject:N=>{clearTimeout(B),S(N)}}),w(t,{...i,jsonrpc:"2.0",id:l})})},me=async t=>{let i,s=new Promise((l,c)=>{i=setTimeout(()=>{c(new Error(`${n} did not answer initialize within ${a}ms`))},a)});try{return await Promise.race([t,s])}finally{i&&clearTimeout(i)}},fe=t=>{let i={...k.env,...r.extraEnv,PATH:de,...t};for(let s of e.unset)i[s]="";for(let s of r.stripFromChildEnv?.()??[])Ne.has(s)||delete i[s];return ke(n,[...o],{env:i,stdio:["pipe","pipe","pipe"]})},ge=async(t,i)=>{let s=fe(t),l={child:s,key:JSON.stringify(t),generation:i,pending:new Map,nextId:1,handshake:null,closed:!1};$(s.stdout,c=>{pe(l,c)}),s.stderr.on("data",c=>{for(let S of c.toString().trimEnd().split(`
8
- `))S.length>0&&f(`${n}: ${S}`)}),s.on("error",c=>{P(l,`failed to start: ${c.message}`)}),s.on("exit",c=>{P(l,`exited with code ${String(c)}`)});try{l.handshake=await me(q(l,{method:"initialize",params:z}))}catch(c){throw P(l,"handshake failed"),c}return w(l,{jsonrpc:"2.0",method:"notifications/initialized"}),f(`serving ${e.name} (${n})`),l},he=async t=>{let i=JSON.stringify(t);if(d&&!d.closed&&d.key===i)return d;if(y&&y.key===i)return y.promise;_+=1;let s=_;d&&f(`${e.name}: a listed variable changed \u2014 replacing upstream`);let l=(async()=>{let c=await ge(t,s);if(s!==_)throw P(c,"superseded by a newer target"),new Error(`${e.name} upstream superseded by a newer target`);return d&&P(d,"replaced"),d=c,c})();y={key:i,generation:s,promise:l};try{return await l}finally{y?.generation===s&&(y=null)}};return{setInitializeParams:t=>{z=t},request:async(t,i)=>{let s=await he(i);return q(s,{method:t.method,params:t.params},t.id)},notifyIfActive:t=>!d||d.closed?!1:(w(d,{jsonrpc:"2.0",method:t.method,params:t.params}),!0),handshake:()=>d?.handshake??null,dispose:()=>{d&&P(d,"disposed"),d=null}}};var Te=Number(p.env.IK_MCP_POLL_MS??2e3),ie="2025-06-18",ae={tools:{listChanged:!0}},g=e=>{p.stderr.write(`ik-mcp: ${e}
6
+ `)}})};import{spawn as Ie}from"node:child_process";import Je from"node:os";import j from"node:path";import _ from"node:process";var Ve=()=>{let e=_.env.GOBIN;if(e!=null&&e.length>0)return e;let r=_.env.GOPATH;return j.join(r!=null&&r.length>0?r:j.join(Je.homedir(),"go"),"bin")},Ne=15e3,Te=12e4,Ae=M,ae=(e,r={})=>{let n=e.command,o=e.args,a=r.readyTimeoutMs??Ne,m=r.requestTimeoutMs??Te,f=r.log??(()=>{}),pe=r.onServerMessage??(()=>{}),me=`${Ve()}${j.delimiter}${_.env.PATH??""}`,q={},d=null,y=null,N=0,fe=(t,i)=>{for(let s of t.pending.values())s.reject(new Error(i));t.pending.clear()},P=(t,i)=>{t.closed||(t.closed=!0,fe(t,`${e.name} upstream ${i}`),t.child.kill())},ge=(t,i)=>{let s;try{s=JSON.parse(i)}catch{f(`ignoring non-JSON line from ${n}`);return}if(s.method!=null){if(s.id==null){pe(s);return}f(`refusing server-initiated request ${s.method}`),E(t,{jsonrpc:"2.0",id:s.id,error:{code:-32601,message:"client requests are not supported by this shim"}});return}if(s.id==null)return;let l=t.pending.get(Number(s.id));l&&(t.pending.delete(Number(s.id)),l.resolve(l.clientId===void 0?s:{...s,id:l.clientId}))},E=(t,i)=>{t.closed||t.child.stdin.write(`${JSON.stringify(i)}
7
+ `)},B=(t,i,s)=>{if(t.closed)return Promise.reject(new Error(`${e.name} upstream is closed`));let l=t.nextId;return t.nextId+=1,new Promise((c,S)=>{let W=setTimeout(()=>{t.pending.delete(l),S(new Error(`${n} did not answer ${i.method??"request"} within ${m}ms`))},m);t.pending.set(l,{clientId:s,resolve:T=>{clearTimeout(W),c(T)},reject:T=>{clearTimeout(W),S(T)}}),E(t,{...i,jsonrpc:"2.0",id:l})})},he=async t=>{let i,s=new Promise((l,c)=>{i=setTimeout(()=>{c(new Error(`${n} did not answer initialize within ${a}ms`))},a)});try{return await Promise.race([t,s])}finally{i&&clearTimeout(i)}},ve=t=>{let i={..._.env,...r.extraEnv,PATH:me,...t};for(let s of e.unset)i[s]="";for(let s of r.stripFromChildEnv?.()??[])Ae.has(s)||delete i[s];return Ie(n,[...o],{env:i,stdio:["pipe","pipe","pipe"]})},ye=async(t,i)=>{let s=ve(t),l={child:s,key:JSON.stringify(t),generation:i,pending:new Map,nextId:1,handshake:null,closed:!1};k(s.stdout,c=>{ge(l,c)}),s.stderr.on("data",c=>{for(let S of c.toString().trimEnd().split(`
8
+ `))S.length>0&&f(`${n}: ${S}`)}),s.on("error",c=>{P(l,`failed to start: ${c.message}`)}),s.on("exit",c=>{P(l,`exited with code ${String(c)}`)});try{l.handshake=await he(B(l,{method:"initialize",params:q}))}catch(c){throw P(l,"handshake failed"),c}return E(l,{jsonrpc:"2.0",method:"notifications/initialized"}),f(`serving ${e.name} (${n})`),l},Pe=async t=>{let i=JSON.stringify(t);if(d&&!d.closed&&d.key===i)return d;if(y&&y.key===i)return y.promise;N+=1;let s=N;d&&f(`${e.name}: a listed variable changed \u2014 replacing upstream`);let l=(async()=>{let c=await ye(t,s);if(s!==N)throw P(c,"superseded by a newer target"),new Error(`${e.name} upstream superseded by a newer target`);return d&&P(d,"replaced"),d=c,c})();y={key:i,generation:s,promise:l};try{return await l}finally{y?.generation===s&&(y=null)}};return{setInitializeParams:t=>{q=t},request:async(t,i)=>{let s=await Pe(i);return B(s,{method:t.method,params:t.params},t.id)},notifyIfActive:t=>!d||d.closed?!1:(E(d,{jsonrpc:"2.0",method:t.method,params:t.params}),!0),handshake:()=>d?.handshake??null,dispose:()=>{d&&P(d,"disposed"),d=null}}};var Oe=Number(p.env.IK_MCP_POLL_MS??2e3),ce="2025-06-18",de={tools:{listChanged:!0}},g=e=>{p.stderr.write(`ik-mcp: ${e}
9
9
  `)},h=e=>{p.stdout.write(`${JSON.stringify(e)}
10
- `)};G((e,r)=>{e.outcome==="failed"&&g(e.kind==="link"?`${r} failed: ${e.link} -> ${e.target}`:`${r} failed: ${e.node} <- ${e.source}`)});var I=Q(p.argv.slice(2)),j=I.ok?null:`${I.problem} \u2014 run \`ik setup\` to regenerate this .mcp.json entry`,u=I.ok?I.spec:null,v=u===null?null:oe(u,{log:g,onServerMessage:h,stripFromChildEnv:()=>te(u.env)}),D=()=>u===null?null:re(u.env),se=null,J,V=()=>(se??=u===null?"unknown":X(u.command,["--version"],p.env.PATH),se),le=()=>u===null?null:Y(u.name),b=()=>{if(J===void 0){let e=le();J=e===null?null:ee(V(),e)}return J},Ae=e=>{let r=le();if(r===null)return;let n=b(),o={version:V(),protocolVersion:e.protocolVersion??n?.protocolVersion??ie,capabilities:e.capabilities??n?.capabilities??ae,tools:e.tools??n?.tools??[]};J=o,ne(o,r)},Oe=e=>{h({jsonrpc:"2.0",id:e.id,result:{protocolVersion:b()?.protocolVersion??ie,capabilities:b()?.capabilities??ae,serverInfo:{name:u?.name??"ik-mcp",version:V()}}})},U=!1,Ce=()=>{let e=setInterval(()=>{U||D()===null||(U=!0,clearInterval(e),g("credentials appeared \u2014 announcing tools/list_changed"),h({jsonrpc:"2.0",method:"notifications/tools/list_changed"}))},Te);e.unref()},Le=async(e,r)=>{let n=await v.request(e,r),o=n.result?.tools;if(Array.isArray(o)){let a=v.handshake()?.result;Ae({tools:o,capabilities:a?.capabilities,protocolVersion:a?.protocolVersion})}h(n)},Fe=e=>{h({jsonrpc:"2.0",id:e.id,result:{tools:b()?.tools??[]}})},je=e=>{if(v?.setInitializeParams(e.params),Oe(e),j!==null){g(`degraded: ${j}`);return}if(g(`${u.name}: env file ${R()}; reads ${u.env.join(", ")}; upstream ${u.command} ${V()}; cache ${b()?"warm":"cold"}`),D()!==null){U=!0;return}g("no credentials yet \u2014 deferring"),Ce()},Ue=e=>{if(e.method==="tools/list"){Fe(e);return}e.id!=null&&h({jsonrpc:"2.0",id:e.id,error:{code:-32e3,message:j??`${u.name}: credentials are not loaded yet (${u.env.join(", ")}) \u2014 run 'ik env-load'`}})},De=async e=>{if(e.method==null)return;if(e.method==="initialize"){je(e);return}let r=D();if(r===null||v===null){Ue(e);return}if(e.id==null){e.method!=="notifications/initialized"&&v.notifyIfActive(e);return}if(e.method==="tools/list"){await Le(e,r);return}h(await v.request(e,r))},ze=e=>{let r;try{r=JSON.parse(e)}catch{g("ignoring non-JSON line from client");return}De(r).catch(n=>{let o=n instanceof Error?n.message:String(n);g(o),r.id!=null&&h({jsonrpc:"2.0",id:r.id,error:{code:-32e3,message:o}})})};p.on("exit",()=>{v?.dispose()});p.on("SIGTERM",()=>{p.exit(0)});p.on("SIGINT",()=>{p.exit(0)});$(p.stdin,ze);p.stdin.on("end",()=>{p.exit(0)});
10
+ `)};Z((e,r)=>{e.outcome==="failed"&&g(e.kind==="link"?`${r} failed: ${e.link} -> ${e.target}`:`${r} failed: ${e.node} <- ${e.source}`)});var J=X(p.argv.slice(2)),U=J.ok?null:`${J.problem} \u2014 run \`ik setup\` to regenerate this .mcp.json entry`,u=J.ok?J.spec:null,v=u===null?null:ae(u,{log:g,onServerMessage:h,stripFromChildEnv:()=>ie(u.env)}),z=()=>u===null?null:se(u.env),le=null,I,V=()=>(le??=u===null?"unknown":re(u.command,["--version"],p.env.PATH),le),ue=()=>u===null?null:ee(u.name),x=()=>{if(I===void 0){let e=ue();I=e===null?null:te(V(),e)}return I},Le=e=>{let r=ue();if(r===null)return;let n=x(),o={version:V(),protocolVersion:e.protocolVersion??n?.protocolVersion??ce,capabilities:e.capabilities??n?.capabilities??de,tools:e.tools??n?.tools??[]};I=o,oe(o,r)},Ce=e=>{h({jsonrpc:"2.0",id:e.id,result:{protocolVersion:x()?.protocolVersion??ce,capabilities:x()?.capabilities??de,serverInfo:{name:u?.name??"ik-mcp",version:V()}}})},D=!1,Fe=()=>{let e=setInterval(()=>{D||z()===null||(D=!0,clearInterval(e),g("credentials appeared \u2014 announcing tools/list_changed"),h({jsonrpc:"2.0",method:"notifications/tools/list_changed"}))},Oe);e.unref()},je=async(e,r)=>{let n=await v.request(e,r),o=n.result?.tools;if(Array.isArray(o)){let a=v.handshake()?.result;Le({tools:o,capabilities:a?.capabilities,protocolVersion:a?.protocolVersion})}h(n)},Ue=e=>{h({jsonrpc:"2.0",id:e.id,result:{tools:x()?.tools??[]}})},De=e=>{if(v?.setInitializeParams(e.params),Ce(e),U!==null){g(`degraded: ${U}`);return}if(g(`${u.name}: env file ${$()}; reads ${u.env.join(", ")}; upstream ${u.command} ${V()}; cache ${x()?"warm":"cold"}`),z()!==null){D=!0;return}g("no credentials yet \u2014 deferring"),Fe()},ze=e=>{if(e.method==="tools/list"){Ue(e);return}e.id!=null&&h({jsonrpc:"2.0",id:e.id,error:{code:-32e3,message:U??`${u.name}: credentials are not loaded yet (${u.env.join(", ")}) \u2014 run 'ik env-load'`}})},qe=async e=>{if(e.method==null)return;if(e.method==="initialize"){De(e);return}let r=z();if(r===null||v===null){ze(e);return}if(e.id==null){e.method!=="notifications/initialized"&&v.notifyIfActive(e);return}if(e.method==="tools/list"){await je(e,r);return}h(await v.request(e,r))},Be=e=>{let r;try{r=JSON.parse(e)}catch{g("ignoring non-JSON line from client");return}qe(r).catch(n=>{let o=n instanceof Error?n.message:String(n);g(o),r.id!=null&&h({jsonrpc:"2.0",id:r.id,error:{code:-32e3,message:o}})})};p.on("exit",()=>{v?.dispose()});p.on("SIGTERM",()=>{p.exit(0)});p.on("SIGINT",()=>{p.exit(0)});k(p.stdin,Be);p.stdin.on("end",()=>{p.exit(0)});
11
11
  //# sourceMappingURL=mcp-proxy.js.map
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../src/entry/mcp-proxy.ts", "../src/lib/mcp-proxy/argv.ts", "../src/lib/mcp-proxy/cache.ts", "../src/lib/mcp-proxy/env-vars.ts", "../src/lib/mcp-proxy/line-stream.ts", "../src/lib/mcp-proxy/upstream.ts"],
4
- "sourcesContent": ["#!/usr/bin/env node\n// The hashbang must stay on line 1: this entry is published as the `ik-mcp` bin and is exec'd\n// directly by the MCP client, not invoked as `node dist/mcp-proxy.js`.\nimport process from 'node:process'\n\nimport { bootPortlessLink } from 'src/dev/proxy/portless-link'\nimport { parseProxyArgv } from 'src/lib/mcp-proxy/argv'\nimport { proxyCacheDir, readBinaryVersion, readProfile, writeProfile } from 'src/lib/mcp-proxy/cache'\nimport type { UpstreamProfile } from 'src/lib/mcp-proxy/cache'\nimport { readListedVars, readUnlistedNames, resolveEnvFilePath } from 'src/lib/mcp-proxy/env-vars'\nimport type { ProxyVars } from 'src/lib/mcp-proxy/env-vars'\nimport { onEachLine } from 'src/lib/mcp-proxy/line-stream'\nimport { createUpstream } from 'src/lib/mcp-proxy/upstream'\nimport type { JsonRpcMessage, ProxySpec, Upstream } from 'src/lib/mcp-proxy/upstream'\n\nconst CREDENTIAL_POLL_MS = Number(process.env.IK_MCP_POLL_MS ?? 2000)\n\n/**\n * Answered on a cold cache, when no upstream has ever been observed on this machine. Pinned rather\n * than echoed from the client: echoing back whatever a client asks for claims support for a\n * revision nothing here has ever spoken. Only `tools` is claimed \u2014 every MCP server has tools, not\n * every one has resources, and claiming `resources` for one that lacks them makes a client issue\n * `resources/list` and get \"method not found\".\n */\nconst FALLBACK_PROTOCOL_VERSION = '2025-06-18'\nconst FALLBACK_CAPABILITIES = { tools: { listChanged: true } }\n\nconst log = (message: string): void => {\n process.stderr.write(`ik-mcp: ${message}\\n`)\n}\n\nconst write = (payload: JsonRpcMessage): void => {\n process.stdout.write(`${JSON.stringify(payload)}\\n`)\n}\n\n// This bin is the process Claude Code keeps alive, so it is where `~/.infra-kit/portless` converges on\n// a machine that only ever runs the MCP surface. fs-only and synchronous \u2014 nothing is spawned before the\n// handshake \u2014 and stdout is the transport, so only a failure earns a stderr line; the ordinary outcomes\n// are `doctor`'s to show.\nbootPortlessLink((result, message) => {\n if (result.outcome === 'failed')\n log(\n result.kind === 'link'\n ? `${message} failed: ${result.link} -> ${result.target}`\n : `${message} failed: ${result.node} <- ${result.source}`,\n )\n})\n\nconst parsed = parseProxyArgv(process.argv.slice(2))\n\n/**\n * Bad argv is the same state as \"no credentials yet\", not a crash: the handshake is answered, the\n * tool list is empty, and every other request says what is wrong and how to fix it. A proxy that\n * exits on a typo in `.mcp.json` is a dead server the client cannot recover.\n */\nconst degraded: string | null = parsed.ok\n ? null\n : `${parsed.problem} \u2014 run \\`ik setup\\` to regenerate this .mcp.json entry`\nconst spec: ProxySpec | null = parsed.ok ? parsed.spec : null\n\nconst upstream: Upstream | null =\n spec === null\n ? null\n : createUpstream(spec, {\n log,\n // Server-initiated notifications belong to the client and travel verbatim.\n onServerMessage: write,\n // Everything the launching shell picked up from the same env file, minus the listed names,\n // is deleted from the child's inherited environment.\n stripFromChildEnv: () => {\n return readUnlistedNames(spec.env)\n },\n })\n\nconst readVars = (): ProxyVars | null => {\n return spec === null ? null : readListedVars(spec.env)\n}\n\n// Both are resolved on first use, never at module load: `readBinaryVersion` spawns a process and\n// can block for up to its timeout, and doing that before stdin is wired delays the handshake of\n// every session \u2014 including ones that never touch the upstream.\nlet versionCache: string | null = null\nlet profileCache: UpstreamProfile | null | undefined\n\nconst binaryVersion = (): string => {\n versionCache ??=\n // No spec means no upstream to ask, and importing package.json for a version string would drag\n // the whole manifest \u2014 dependency names included \u2014 into a bundle the guard keeps flat.\n spec === null ? 'unknown' : readBinaryVersion(spec.command, ['--version'], process.env.PATH)\n\n return versionCache\n}\n\nconst cacheDir = (): string | null => {\n return spec === null ? null : proxyCacheDir(spec.name)\n}\n\nconst profile = (): UpstreamProfile | null => {\n if (profileCache === undefined) {\n const dir = cacheDir()\n\n profileCache = dir === null ? null : readProfile(binaryVersion(), dir)\n }\n\n return profileCache\n}\n\n/** Fold whatever the live upstream just told us into the on-disk profile. */\nconst rememberProfile = (patch: Partial<UpstreamProfile>): void => {\n const dir = cacheDir()\n\n if (dir === null) return\n\n const current = profile()\n\n const next: UpstreamProfile = {\n version: binaryVersion(),\n protocolVersion: patch.protocolVersion ?? current?.protocolVersion ?? FALLBACK_PROTOCOL_VERSION,\n capabilities: patch.capabilities ?? current?.capabilities ?? FALLBACK_CAPABILITIES,\n tools: patch.tools ?? current?.tools ?? [],\n }\n\n profileCache = next\n writeProfile(next, dir)\n}\n\n/**\n * Answer `initialize` without spawning anything.\n *\n * Spawning here would forfeit lazy start \u2014 a session that never touches the upstream would still\n * pay for a child. The cost is that a first-ever session reports the pinned fallback capabilities\n * and is corrected once a real handshake has been seen; MCP has no capability-change notification,\n * so that correction lands on the NEXT session.\n */\nconst answerInitialize = (message: JsonRpcMessage): void => {\n write({\n jsonrpc: '2.0',\n id: message.id,\n result: {\n protocolVersion: profile()?.protocolVersion ?? FALLBACK_PROTOCOL_VERSION,\n capabilities: profile()?.capabilities ?? FALLBACK_CAPABILITIES,\n serverInfo: { name: spec?.name ?? 'ik-mcp', version: binaryVersion() },\n },\n })\n}\n\nlet announced = false\n\n/**\n * Credentials arrive mid-session, and stdio keeps a server-to-client channel open the whole time \u2014\n * so the moment they appear the client can be told to list again. Polls the env file ONLY: there is\n * no config to poll, so there is no mid-edit \"invalid config\" window and no path by which a watcher\n * could tear down a live upstream.\n */\nconst watchForCredentials = (): void => {\n const timer = setInterval(() => {\n if (announced || readVars() === null) return\n\n announced = true\n clearInterval(timer)\n log('credentials appeared \u2014 announcing tools/list_changed')\n write({ jsonrpc: '2.0', method: 'notifications/tools/list_changed' })\n }, CREDENTIAL_POLL_MS)\n\n timer.unref()\n}\n\nconst forwardToolsList = async (message: JsonRpcMessage, vars: ProxyVars): Promise<void> => {\n const response = await upstream!.request(message, vars)\n const tools = (response.result as { tools?: unknown[] } | undefined)?.tools\n\n if (Array.isArray(tools)) {\n const handshake = upstream!.handshake()?.result as { protocolVersion?: string; capabilities?: unknown } | undefined\n\n rememberProfile({ tools, capabilities: handshake?.capabilities, protocolVersion: handshake?.protocolVersion })\n }\n\n write(response)\n}\n\n/** Before credentials exist, the tool list is answered from cache \u2014 never with an error. */\nconst answerToolsListFromCache = (message: JsonRpcMessage): void => {\n write({ jsonrpc: '2.0', id: message.id, result: { tools: profile()?.tools ?? [] } })\n}\n\n/** Answers the handshake and arms the watcher; deliberately spawns nothing. */\nconst handleInitialize = (message: JsonRpcMessage): void => {\n upstream?.setInitializeParams(message.params)\n answerInitialize(message)\n\n if (degraded !== null) {\n log(`degraded: ${degraded}`)\n\n return\n }\n\n // Always name the resolved path and the spec: when either is wrong (a stale XDG_CACHE_HOME, a\n // session id the client never inherited, a drifted .mcp.json) nothing else in the session says so.\n // Names only \u2014 the VALUES are credentials.\n log(\n `${spec!.name}: env file ${resolveEnvFilePath()}; reads ${spec!.env.join(', ')}; upstream ${spec!.command} ${binaryVersion()}; cache ${profile() ? 'warm' : 'cold'}`,\n )\n\n if (readVars() !== null) {\n announced = true\n\n return\n }\n\n log('no credentials yet \u2014 deferring')\n watchForCredentials()\n}\n\n/** The pre-`env-load` state (or bad argv), which is normal and must never look like a protocol failure. */\nconst answerWithoutCredentials = (message: JsonRpcMessage): void => {\n if (message.method === 'tools/list') {\n answerToolsListFromCache(message)\n\n return\n }\n\n if (message.id == null) return\n\n write({\n jsonrpc: '2.0',\n id: message.id,\n error: {\n code: -32000,\n message:\n degraded ?? `${spec!.name}: credentials are not loaded yet (${spec!.env.join(', ')}) \u2014 run 'ik env-load'`,\n },\n })\n}\n\nconst handle = async (message: JsonRpcMessage): Promise<void> => {\n // An id with no method is a RESPONSE, not a request. A well-behaved client sends none \u2014 the\n // proxy refuses server-initiated requests, so there is nothing to answer \u2014 and treating one as a\n // request would spawn an upstream and reply `no method undefined`.\n if (message.method == null) return\n\n if (message.method === 'initialize') {\n handleInitialize(message)\n\n return\n }\n\n const vars = readVars()\n\n if (vars === null || upstream === null) {\n answerWithoutCredentials(message)\n\n return\n }\n\n if (message.id == null) {\n // Never spawns. `notifications/initialized` in particular is answered by not relaying it at\n // all: every child gets its own from the handshake replay, and forwarding the client's would\n // make the mandatory handshake defeat lazy start.\n if (message.method !== 'notifications/initialized') upstream.notifyIfActive(message)\n\n return\n }\n\n if (message.method === 'tools/list') {\n await forwardToolsList(message, vars)\n\n return\n }\n\n write(await upstream.request(message, vars))\n}\n\nconst onLine = (line: string): void => {\n let message: JsonRpcMessage\n\n try {\n message = JSON.parse(line) as JsonRpcMessage\n } catch {\n log('ignoring non-JSON line from client')\n\n return\n }\n\n handle(message).catch((error: unknown) => {\n const detail = error instanceof Error ? error.message : String(error)\n\n log(detail)\n\n if (message.id != null) {\n write({ jsonrpc: '2.0', id: message.id, error: { code: -32000, message: detail } })\n }\n })\n}\n\nprocess.on('exit', () => {\n upstream?.dispose()\n})\nprocess.on('SIGTERM', () => {\n process.exit(0)\n})\nprocess.on('SIGINT', () => {\n process.exit(0)\n})\n\nonEachLine(process.stdin, onLine)\n\n// The client closing its end is the ordinary way this server ends.\nprocess.stdin.on('end', () => {\n process.exit(0)\n})\n", "import { PROTECTED_CHILD_ENV_NAMES } from './protected-env'\nimport type { ProxySpec } from './upstream'\n\n/** Mirrors the config schema's name rule; re-checked here because the name becomes a cache subdir. */\nconst NAME_PATTERN = /^[a-z][a-z0-9-]*$/\n/** Mirrors `envVarName` in the config schema. */\nconst ENV_VAR_PATTERN = /^[A-Z_]\\w*$/i\n\nexport type ParsedArgv = { ok: true; spec: ProxySpec } | { ok: false; problem: string }\n\ninterface Flags {\n name: string | null\n env: string[]\n unset: string[]\n}\n\n/** Apply one `--flag value` pair, or say why it cannot be applied. */\nconst applyFlag = (flags: Flags, flag: string, value: string): string | null => {\n if (flag === '--name') {\n if (flags.name !== null) return '--name given twice'\n if (!NAME_PATTERN.test(value)) return `--name \"${value}\" must be lowercase letters, digits and hyphens`\n\n flags.name = value\n\n return null\n }\n\n if (flag === '--env' || flag === '--unset') {\n if (!ENV_VAR_PATTERN.test(value)) return `${flag} \"${value}\" is not an environment-variable name`\n // Mirrors the schema refinement, because hand-written argv (the `claude mcp add --scope local`\n // path) never passes through the schema \u2014 and `--unset PATH` would blank PATH and ENOENT the spawn.\n if (PROTECTED_CHILD_ENV_NAMES.has(value)) return `${flag} \"${value}\" is process plumbing, not a credential`\n\n if (flag === '--env') flags.env.push(value)\n else flags.unset.push(value)\n\n return null\n }\n\n return `unknown flag ${flag}`\n}\n\n/** Walk the flag half; returns the index of the `--` separator or a problem. */\nconst readFlags = (argv: readonly string[], flags: Flags): { separator: number } | { problem: string } => {\n let index = 0\n\n while (index < argv.length) {\n const flag = argv[index]!\n\n if (flag === '--') return { separator: index }\n\n // A bare word where a flag belongs is the upstream command arriving early \u2014 the separator\n // is what is missing, and that is the more useful thing to say than \"cmd needs a value\".\n if (!flag.startsWith('--')) return { problem: `missing \"--\" before the upstream command (saw \"${flag}\")` }\n\n const value = argv[index + 1]\n\n // A value that looks like a flag (`--env --`) would otherwise eat the separator and turn the\n // upstream command into a flag \u2014 the case that spawns the wrong binary instead of refusing.\n if (value === undefined || value.startsWith('--')) return { problem: `${flag} needs a value` }\n\n const problem = applyFlag(flags, flag, value)\n\n if (problem !== null) return { problem }\n\n index += 2\n }\n\n return { problem: 'missing \"--\" before the upstream command' }\n}\n\n/**\n * Parse the argv `ik setup` derived: `--name N (--env V)+ (--unset V)* -- <command> [args...]`.\n *\n * Every flag VALUE is validated, not only `--name`. The first `--` in flag position ends our half;\n * everything after it is the upstream's, verbatim, `--`s and all.\n */\n// Node builtins only, on purpose. Pulling commander in here would drag it into the proxy bundle,\n// which the chunk-isolation guard forbids \u2014 and a four-flag grammar does not need it.\nexport const parseProxyArgv = (argv: readonly string[]): ParsedArgv => {\n const flags: Flags = { name: null, env: [], unset: [] }\n const walked = readFlags(argv, flags)\n\n if ('problem' in walked) return { ok: false, problem: walked.problem }\n if (flags.name === null) return { ok: false, problem: 'missing --name' }\n if (flags.env.length === 0) return { ok: false, problem: 'missing --env (at least one variable to read)' }\n\n const command = argv[walked.separator + 1]\n\n if (command === undefined || command.length === 0)\n return { ok: false, problem: 'missing upstream command after \"--\"' }\n\n return {\n ok: true,\n spec: { name: flags.name, command, args: argv.slice(walked.separator + 2), env: flags.env, unset: flags.unset },\n }\n}\n", "import { spawnSync } from 'node:child_process'\nimport fs from 'node:fs'\nimport path from 'node:path'\nimport process from 'node:process'\n\nimport { atomicWriteFileSync, getCacheRoot } from 'src/lib/constants'\n\n/**\n * What a session can answer with before any child exists: the tool list and the\n * capability payload the upstream last reported.\n *\n * Capabilities are cached alongside the tools because MCP has no\n * capability-change notification \u2014 a deferred `initialize` must state them up front\n * and can never correct itself, so the honest answer has to come from disk.\n */\nexport interface UpstreamProfile {\n version: string\n protocolVersion: string\n capabilities: unknown\n tools: unknown[]\n}\n\n/**\n * Proxy state lives under the CACHE root, never `~/.infra-kit` \u2014 that is\n * `USER_CONFIG_DIR_NAME`, the auto-seeded project-config registry, where a\n * throwaway derived file has no business living. One subdir per configured name.\n */\nexport const proxyCacheDir = (name: string): string => {\n return path.join(getCacheRoot(), 'mcp-proxy', name)\n}\n\n/** Keeps a version string usable as one path segment. */\nconst safeSegment = (version: string): string => {\n return version.replaceAll(/[^\\w.-]/g, '_').slice(0, 64)\n}\n\nexport const profilePath = (version: string, dir: string): string => {\n return path.join(dir, `profile-${safeSegment(version)}.json`)\n}\n\n/**\n * A cache key for a binary that does not answer `--version`: its resolved path's size and mtime.\n *\n * Both change on every upgrade, which is all the key has to guarantee. Hashing the file would too,\n * but a Go binary is tens of megabytes and this runs at session start.\n */\nexport const binaryFingerprint = (binary: string, searchPath?: string): string => {\n const candidates = path.isAbsolute(binary)\n ? [binary]\n : (searchPath ?? process.env.PATH ?? '').split(path.delimiter).map((dir) => {\n return path.join(dir, binary)\n })\n\n for (const candidate of candidates) {\n try {\n const stat = fs.statSync(candidate)\n\n return `stat-${stat.size}-${Math.trunc(stat.mtimeMs)}`\n } catch {\n // not here; try the next PATH entry\n }\n }\n\n return 'unknown'\n}\n\n/**\n * The upstream binary's self-reported version, falling back to {@link binaryFingerprint}.\n * This is the cache key, so an upgrade that changes the tool set can never be served\n * a stale list \u2014 the new version simply looks at a different file.\n */\nexport const readBinaryVersion = (\n binary: string,\n versionArgs: readonly string[] = ['--version'],\n searchPath?: string,\n): string => {\n try {\n // The same PATH the upstream spawn uses. Without it, a `go install` layout \u2014 where\n // mcp-grafana lives only in GOBIN \u2014 probes as ENOENT, every version collapses into\n // one 'unknown' cache bucket, and an upgrade is served the previous tool list.\n const result = spawnSync(binary, [...versionArgs], {\n encoding: 'utf8',\n timeout: 5000,\n env: searchPath == null ? process.env : { ...process.env, PATH: searchPath },\n })\n\n if (result.status !== 0) return binaryFingerprint(binary, searchPath)\n\n const reported = `${result.stdout}`.trim().split('\\n')[0]?.trim() ?? ''\n\n return reported.length > 0 ? reported : binaryFingerprint(binary, searchPath)\n } catch {\n return binaryFingerprint(binary, searchPath)\n }\n}\n\n/**\n * The cached profile for this binary version, or null.\n *\n * Every failure is a null, never a throw: a torn or truncated file must degrade to\n * \"no cache yet\", because the alternative is an exception on the deferred\n * `initialize` path \u2014 which would kill the session the cache exists to rescue.\n */\nexport const readProfile = (version: string, dir: string): UpstreamProfile | null => {\n try {\n const parsed = JSON.parse(fs.readFileSync(profilePath(version, dir), 'utf8')) as Partial<UpstreamProfile>\n\n if (parsed.version !== version || !Array.isArray(parsed.tools)) return null\n\n return {\n version,\n protocolVersion: typeof parsed.protocolVersion === 'string' ? parsed.protocolVersion : '',\n capabilities: parsed.capabilities ?? {},\n tools: parsed.tools,\n }\n } catch {\n return null\n }\n}\n\n/**\n * Persist a profile. Best-effort: a cache that cannot be written is a slower next\n * session, not a broken one.\n */\nexport const writeProfile = (profile: UpstreamProfile, dir: string): boolean => {\n try {\n fs.mkdirSync(dir, { recursive: true })\n // Atomic, because two sessions can write this concurrently and a half-written\n // file reads back as \"no tools\" \u2014 a silently toolless session with no error.\n atomicWriteFileSync(profilePath(profile.version, dir), `${JSON.stringify(profile)}\\n`, 0o600)\n\n return true\n } catch {\n return false\n }\n}\n", "import path from 'node:path'\nimport process from 'node:process'\n\nimport { ENV_LOAD_FILE, INFRA_KIT_SESSION_VAR, getCacheRoot, parseVarsFromEnvFile } from 'src/lib/constants'\n\n/**\n * Session id used when the proxy inherits none. `getSessionCacheDir()` THROWS in that case,\n * which is correct for a command and fatal for a server \u2014 a proxy that throws at startup is a\n * dead MCP server, so it degrades to a fixed dir instead.\n */\nexport const NO_SESSION = 'no-session'\n\n/** Escape hatch for tests and for pointing the proxy at a hand-written file. */\nexport const ENV_FILE_OVERRIDE_VAR = 'IK_MCP_ENV_FILE'\n\n/** The listed variables' values, keyed by name, in the order the spec listed them. */\nexport type ProxyVars = Record<string, string>\n\nexport const resolveSessionId = (): string => {\n const session = process.env[INFRA_KIT_SESSION_VAR]\n\n return session != null && session.length > 0 ? session : NO_SESSION\n}\n\n/**\n * Where `ik env-load` writes for this session. Goes through `getCacheRoot()` so\n * `XDG_CACHE_HOME` is honoured \u2014 a hardcoded `~/.cache` would silently read a path\n * nothing ever writes on any box that sets it.\n */\nexport const resolveEnvFilePath = (): string => {\n const override = process.env[ENV_FILE_OVERRIDE_VAR]\n\n if (override != null && override.length > 0) return override\n\n return path.join(getCacheRoot(), resolveSessionId(), ENV_LOAD_FILE)\n}\n\n/** The file wins over the inherited environment, per name. */\nconst pick = (fileVars: Record<string, string>, name: string): string => {\n const fromFile = fileVars[name]\n\n if (fromFile != null && fromFile.length > 0) return fromFile\n\n const fromEnv = process.env[name]\n\n return fromEnv != null && fromEnv.length > 0 ? fromEnv : ''\n}\n\n/**\n * The values of `names`, or null while any of them is missing \u2014 the normal state before\n * `ik env-load` runs, which must never be an error.\n *\n * Built by iterating `names`, not the file, so the record's key order \u2014 and therefore its\n * JSON, which is the respawn key \u2014 is stable however Doppler happens to order the file.\n */\nexport const readListedVars = (names: readonly string[], filePath: string = resolveEnvFilePath()): ProxyVars | null => {\n const fileVars = parseVarsFromEnvFile(filePath)\n const vars: ProxyVars = {}\n\n for (const name of names) {\n const value = pick(fileVars, name)\n\n if (value.length === 0) return null\n\n vars[name] = value\n }\n\n return vars\n}\n\n/**\n * Every name the env file defines that the spec does NOT list.\n *\n * The child inherits this process's environment, and this process was launched from a shell\n * that had normally sourced the very file these came from \u2014 so without stripping them by name,\n * every production secret reaches the child by inheritance regardless of what the spec lists.\n */\nexport const readUnlistedNames = (names: readonly string[], filePath: string = resolveEnvFilePath()): string[] => {\n const listed = new Set(names)\n\n return Object.keys(parseVarsFromEnvFile(filePath)).filter((name) => {\n return !listed.has(name)\n })\n}\n", "/**\n * Newline framing for a JSON-RPC stdio stream.\n *\n * Deliberately not `node:readline`. That module is fenced off outside\n * `src/lib/prompts/` because it is the shape a future interactive stdin reader would\n * take, and the prompts module owns the stdin refcount. This is a transport, not a\n * prompt \u2014 but the fence has no exemptions and is worth more intact than this is worth\n * saving, and hand framing is a dozen lines with no buffering semantics to inherit.\n */\nexport const onEachLine = (stream: NodeJS.ReadableStream, visit: (line: string) => void): void => {\n let buffer = ''\n\n stream.setEncoding('utf8')\n stream.on('data', (chunk: string) => {\n buffer += chunk\n\n let boundary = buffer.indexOf('\\n')\n\n while (boundary !== -1) {\n const raw = buffer.slice(0, boundary)\n\n buffer = buffer.slice(boundary + 1)\n\n // A peer that writes CRLF must not hand us a trailing CR inside the JSON.\n const line = raw.endsWith('\\r') ? raw.slice(0, -1) : raw\n\n if (line.trim().length > 0) visit(line)\n\n boundary = buffer.indexOf('\\n')\n }\n })\n}\n", "import type { Buffer } from 'node:buffer'\nimport { spawn } from 'node:child_process'\nimport type { ChildProcessWithoutNullStreams } from 'node:child_process'\nimport os from 'node:os'\nimport path from 'node:path'\nimport process from 'node:process'\n\nimport type { ProxyVars } from './env-vars'\nimport { onEachLine } from './line-stream'\nimport { PROTECTED_CHILD_ENV_NAMES } from './protected-env'\n\nexport interface JsonRpcMessage {\n jsonrpc?: string\n id?: string | number\n method?: string\n params?: unknown\n result?: unknown\n error?: { code: number; message: string }\n}\n\n/**\n * What one configured server is: the argv-borne half of an `mcp.<name>` entry.\n *\n * `env` names are injected inline from {@link ProxyVars}; `unset` names are forced empty so a stale\n * file-based credential can never outrank the inline one (measured for mcp-grafana: an inline token\n * takes precedence over `..._TOKEN_FILE`, but only if the file variable is not also set).\n */\nexport interface ProxySpec {\n name: string\n command: string\n args: readonly string[]\n env: readonly string[]\n unset: readonly string[]\n}\n\nexport interface UpstreamOptions {\n extraEnv?: NodeJS.ProcessEnv\n readyTimeoutMs?: number\n /**\n * Per-request ceiling. A child that answers the handshake and then goes silent must\n * not hang every later request for the rest of the session.\n */\n requestTimeoutMs?: number\n /**\n * Names to DELETE from the child's inherited environment \u2014 the unlisted secrets the\n * launching shell picked up from the same env file.\n */\n stripFromChildEnv?: () => readonly string[]\n log?: (message: string) => void\n /** Notifications and server-initiated requests, which travel to the client verbatim. */\n onServerMessage?: (message: JsonRpcMessage) => void\n}\n\n/** `go install` lands the binary in GOBIN, which a GUI-launched process never has on PATH. */\nconst goBinDir = (): string => {\n const explicit = process.env.GOBIN\n\n if (explicit != null && explicit.length > 0) return explicit\n\n const goPath = process.env.GOPATH\n\n return path.join(goPath != null && goPath.length > 0 ? goPath : path.join(os.homedir(), 'go'), 'bin')\n}\n\nconst DEFAULT_READY_TIMEOUT_MS = 15_000\nconst DEFAULT_REQUEST_TIMEOUT_MS = 120_000\n\nconst NEVER_STRIP = PROTECTED_CHILD_ENV_NAMES\n\ninterface Deferred {\n /** Absent for the shim's OWN requests, whose answers must never reach the client. */\n clientId?: string | number\n resolve: (message: JsonRpcMessage) => void\n reject: (error: Error) => void\n}\n\ninterface Session {\n child: ChildProcessWithoutNullStreams\n /** JSON of the ordered vars record \u2014 the respawn key. */\n key: string\n generation: number\n pending: Map<number, Deferred>\n nextId: number\n handshake: JsonRpcMessage | null\n closed: boolean\n}\n\nexport interface Upstream {\n setInitializeParams: (params: unknown) => void\n request: (message: JsonRpcMessage, vars: ProxyVars) => Promise<JsonRpcMessage>\n /** Forwards only when an upstream already exists; never spawns one. */\n notifyIfActive: (message: JsonRpcMessage) => boolean\n /** The upstream's own `initialize` result, once one has been observed. */\n handshake: () => JsonRpcMessage | null\n dispose: () => void\n}\n\nexport const createUpstream = (spec: ProxySpec, options: UpstreamOptions = {}): Upstream => {\n const binary = spec.command\n const args = spec.args\n const readyTimeoutMs = options.readyTimeoutMs ?? DEFAULT_READY_TIMEOUT_MS\n const requestTimeoutMs = options.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS\n const log = options.log ?? ((): void => {})\n const onServerMessage = options.onServerMessage ?? ((): void => {})\n\n const searchPath = `${goBinDir()}${path.delimiter}${process.env.PATH ?? ''}`\n\n let initializeParams: unknown = {}\n let active: Session | null = null\n let starting: { key: string; generation: number; promise: Promise<Session> } | null = null\n let generation = 0\n\n const failPending = (session: Session, reason: string): void => {\n for (const deferred of session.pending.values()) deferred.reject(new Error(reason))\n session.pending.clear()\n }\n\n const closeSession = (session: Session, reason: string): void => {\n if (session.closed) return\n\n session.closed = true\n // In-flight work is ERRORED, never silently dropped: a caller waiting on a killed\n // upstream would otherwise hang for the rest of the session.\n failPending(session, `${spec.name} upstream ${reason}`)\n session.child.kill()\n }\n\n // A response carries an id and no method; anything with a method is server-initiated\n // and belongs to the client. Routing on `method` first is what keeps the shim's own\n // ids from ever being confused with the client's.\n const handleLine = (session: Session, line: string): void => {\n let message: JsonRpcMessage\n\n try {\n message = JSON.parse(line) as JsonRpcMessage\n } catch {\n log(`ignoring non-JSON line from ${binary}`)\n\n return\n }\n\n if (message.method != null) {\n if (message.id == null) {\n onServerMessage(message)\n\n return\n }\n\n // A server-initiated REQUEST carries the upstream's own id. Relaying it would send\n // the client an id from a namespace it does not own, and the client's answer would\n // re-enter as a fresh request with no method. mcp-grafana initiates none today, so\n // refusing is honest and cannot mis-route.\n log(`refusing server-initiated request ${message.method}`)\n send(session, {\n jsonrpc: '2.0',\n id: message.id,\n error: { code: -32601, message: 'client requests are not supported by this shim' },\n })\n\n return\n }\n\n if (message.id == null) return\n\n const deferred = session.pending.get(Number(message.id))\n\n if (!deferred) return\n\n session.pending.delete(Number(message.id))\n\n // Map back: the client only ever sees the id IT chose. Resolving with the wire id\n // would hand the client an answer labelled with the shim's private numbering.\n deferred.resolve(deferred.clientId === undefined ? message : { ...message, id: deferred.clientId })\n }\n\n const send = (session: Session, message: JsonRpcMessage): void => {\n if (session.closed) return\n\n session.child.stdin.write(`${JSON.stringify(message)}\\n`)\n }\n\n /**\n * Send on the shim's OWN id namespace and await the answer.\n *\n * `clientId` is what makes the namespace real: present, the answer is re-labelled and\n * relayed; absent, it is consumed here. The replayed handshake takes the absent form,\n * so a client request numbered `0` can never collide with it.\n */\n const sendRequest = (\n session: Session,\n message: JsonRpcMessage,\n clientId?: string | number,\n ): Promise<JsonRpcMessage> => {\n // A session can be closed between `ensure` resolving and the write landing \u2014 a\n // dispose, a crash, a swap. Registering here anyway would leave the caller pending\n // forever, because the rejection sweep has already run.\n if (session.closed) return Promise.reject(new Error(`${spec.name} upstream is closed`))\n\n const upstreamId = session.nextId\n\n session.nextId += 1\n\n return new Promise<JsonRpcMessage>((resolve, reject) => {\n const timer = setTimeout(() => {\n session.pending.delete(upstreamId)\n reject(new Error(`${binary} did not answer ${message.method ?? 'request'} within ${requestTimeoutMs}ms`))\n }, requestTimeoutMs)\n\n session.pending.set(upstreamId, {\n clientId,\n resolve: (answer: JsonRpcMessage): void => {\n clearTimeout(timer)\n resolve(answer)\n },\n reject: (error: Error): void => {\n clearTimeout(timer)\n reject(error)\n },\n })\n send(session, { ...message, jsonrpc: '2.0', id: upstreamId })\n })\n }\n\n const withDeadline = async (promise: Promise<JsonRpcMessage>): Promise<JsonRpcMessage> => {\n let timer: NodeJS.Timeout | undefined\n\n const deadline = new Promise<never>((_resolve, reject) => {\n timer = setTimeout(() => {\n reject(new Error(`${binary} did not answer initialize within ${readyTimeoutMs}ms`))\n }, readyTimeoutMs)\n })\n\n try {\n return await Promise.race([promise, deadline])\n } finally {\n if (timer) clearTimeout(timer)\n }\n }\n\n const spawnChild = (vars: ProxyVars): ChildProcessWithoutNullStreams => {\n // Listed variables go INLINE \u2014 no credential is written to disk by this proxy at all.\n const childEnv: NodeJS.ProcessEnv = { ...process.env, ...options.extraEnv, PATH: searchPath, ...vars }\n\n // Forced empty rather than deleted: a deleted name would be re-inherited by anything the\n // child spawns from ITS parent's environment; an empty string is an explicit \"no\".\n for (const name of spec.unset) childEnv[name] = ''\n\n // Applied LAST, over the fully merged environment, so no earlier layer can put a\n // secret back. The proxy is normally launched from a shell that sourced the very env\n // file these names came from, and inheritance \u2014 not the listed-names read filter \u2014 is\n // the path by which a production secret would otherwise reach the child.\n for (const name of options.stripFromChildEnv?.() ?? []) {\n if (!NEVER_STRIP.has(name)) delete childEnv[name]\n }\n\n return spawn(binary, [...args], {\n env: childEnv,\n stdio: ['pipe', 'pipe', 'pipe'],\n }) as ChildProcessWithoutNullStreams\n }\n\n const startSession = async (vars: ProxyVars, gen: number): Promise<Session> => {\n const child = spawnChild(vars)\n\n const session: Session = {\n child,\n key: JSON.stringify(vars),\n generation: gen,\n pending: new Map(),\n nextId: 1,\n handshake: null,\n closed: false,\n }\n\n onEachLine(child.stdout, (line) => {\n handleLine(session, line)\n })\n\n child.stderr.on('data', (chunk: Buffer) => {\n // Per LINE, not per chunk: mcp-grafana emits several log lines in one write, and\n // prefixing only the first leaves the rest looking like they came from elsewhere \u2014\n // which matters, because this is the only window into the upstream a user gets.\n for (const line of chunk.toString().trimEnd().split('\\n')) {\n if (line.length > 0) log(`${binary}: ${line}`)\n }\n })\n\n child.on('error', (error: Error) => {\n closeSession(session, `failed to start: ${error.message}`)\n })\n\n child.on('exit', (code) => {\n closeSession(session, `exited with code ${String(code)}`)\n })\n\n try {\n // A child that spawns and never answers must not hang every later request, so the\n // handshake \u2014 not the spawn \u2014 is what readiness means, and it is bounded.\n session.handshake = await withDeadline(sendRequest(session, { method: 'initialize', params: initializeParams }))\n } catch (error) {\n closeSession(session, 'handshake failed')\n throw error\n }\n\n send(session, { jsonrpc: '2.0', method: 'notifications/initialized' })\n log(`serving ${spec.name} (${binary})`)\n\n return session\n }\n\n const ensure = async (vars: ProxyVars): Promise<Session> => {\n const key = JSON.stringify(vars)\n\n if (active && !active.closed && active.key === key) return active\n if (starting && starting.key === key) return starting.promise\n\n generation += 1\n\n const gen = generation\n\n // Which variable changed is deliberately not logged: the values are credentials.\n if (active) log(`${spec.name}: a listed variable changed \u2014 replacing upstream`)\n\n const promise = (async (): Promise<Session> => {\n const session = await startSession(vars, gen)\n\n // A newer target superseded this start while it was in flight. Binding to it now\n // would serve the OLD credentials for the rest of the session.\n if (gen !== generation) {\n closeSession(session, 'superseded by a newer target')\n throw new Error(`${spec.name} upstream superseded by a newer target`)\n }\n\n if (active) closeSession(active, 'replaced')\n active = session\n\n return session\n })()\n\n starting = { key, generation: gen, promise }\n\n try {\n return await promise\n } finally {\n if (starting?.generation === gen) starting = null\n }\n }\n\n return {\n setInitializeParams: (params: unknown): void => {\n initializeParams = params\n },\n request: async (message: JsonRpcMessage, vars: ProxyVars): Promise<JsonRpcMessage> => {\n const session = await ensure(vars)\n\n return sendRequest(session, { method: message.method, params: message.params }, message.id)\n },\n notifyIfActive: (message: JsonRpcMessage): boolean => {\n // Deliberately does NOT call `ensure`. A client notification arriving before any\n // request would otherwise spawn an upstream for a session that has asked the\n // server nothing \u2014 which is exactly what lazy start exists to avoid.\n if (!active || active.closed) return false\n\n send(active, { jsonrpc: '2.0', method: message.method, params: message.params })\n\n return true\n },\n handshake: (): JsonRpcMessage | null => {\n return active?.handshake ?? null\n },\n dispose: (): void => {\n if (active) closeSession(active, 'disposed')\n active = null\n },\n }\n}\n"],
5
- "mappings": ";gLAGA,OAAOA,MAAa,eCCpB,IAAMC,GAAe,oBAEfC,GAAkB,eAWlBC,GAAY,CAACC,EAAcC,EAAcC,IACzCD,IAAS,SACPD,EAAM,OAAS,KAAa,qBAC3BH,GAAa,KAAKK,CAAK,GAE5BF,EAAM,KAAOE,EAEN,MAJ+B,WAAWA,CAAK,kDAOpDD,IAAS,SAAWA,IAAS,UAC1BH,GAAgB,KAAKI,CAAK,EAG3BC,EAA0B,IAAID,CAAK,EAAU,GAAGD,CAAI,KAAKC,CAAK,2CAE9DD,IAAS,QAASD,EAAM,IAAI,KAAKE,CAAK,EACrCF,EAAM,MAAM,KAAKE,CAAK,EAEpB,MARkC,GAAGD,CAAI,KAAKC,CAAK,wCAWrD,gBAAgBD,CAAI,GAIvBG,GAAY,CAACC,EAAyBL,IAA8D,CACxG,IAAIM,EAAQ,EAEZ,KAAOA,EAAQD,EAAK,QAAQ,CAC1B,IAAMJ,EAAOI,EAAKC,CAAK,EAEvB,GAAIL,IAAS,KAAM,MAA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C,GAAiBhC,EAASiC,CAAI,EAEpC,MACF,CAEAhC,EAAM,MAAMQ,EAAS,QAAQT,EAASiC,CAAI,CAAC,CAC7C,EAEMS,GAAUC,GAAuB,CACrC,IAAI3C,EAEJ,GAAI,CACFA,EAAU,KAAK,MAAM2C,CAAI,CAC3B,MAAQ,CACN5C,EAAI,oCAAoC,EAExC,MACF,CAEA0C,GAAOzC,CAAO,EAAE,MAAO4C,GAAmB,CACxC,IAAMC,EAASD,aAAiB,MAAQA,EAAM,QAAU,OAAOA,CAAK,EAEpE7C,EAAI8C,CAAM,EAEN7C,EAAQ,IAAM,MAChBC,EAAM,CAAE,QAAS,MAAO,GAAID,EAAQ,GAAI,MAAO,CAAE,KAAM,MAAQ,QAAS6C,CAAO,CAAE,CAAC,CAEtF,CAAC,CACH,EAEAjD,EAAQ,GAAG,OAAQ,IAAM,CACvBa,GAAU,QAAQ,CACpB,CAAC,EACDb,EAAQ,GAAG,UAAW,IAAM,CAC1BA,EAAQ,KAAK,CAAC,CAChB,CAAC,EACDA,EAAQ,GAAG,SAAU,IAAM,CACzBA,EAAQ,KAAK,CAAC,CAChB,CAAC,EAEDkD,EAAWlD,EAAQ,MAAO8C,EAAM,EAGhC9C,EAAQ,MAAM,GAAG,MAAO,IAAM,CAC5BA,EAAQ,KAAK,CAAC,CAChB,CAAC",
6
- "names": ["process", "NAME_PATTERN", "ENV_VAR_PATTERN", "applyFlag", "flags", "flag", "value", "PROTECTED_CHILD_ENV_NAMES", "readFlags", "argv", "index", "problem", "parseProxyArgv", "walked", "command", "spawnSync", "fs", "path", "process", "proxyCacheDir", "name", "path", "getCacheRoot", "safeSegment", "version", "profilePath", "dir", "binaryFingerprint", "binary", "searchPath", "candidates", "process", "candidate", "stat", "fs", "readBinaryVersion", "versionArgs", "result", "spawnSync", "reported", "readProfile", "parsed", "writeProfile", "profile", "atomicWriteFileSync", "path", "process", "NO_SESSION", "ENV_FILE_OVERRIDE_VAR", "resolveSessionId", "session", "process", "INFRA_KIT_SESSION_VAR", "resolveEnvFilePath", "override", "path", "getCacheRoot", "ENV_LOAD_FILE", "pick", "fileVars", "name", "fromFile", "fromEnv", "readListedVars", "names", "filePath", "parseVarsFromEnvFile", "vars", "value", "readUnlistedNames", "listed", "onEachLine", "stream", "visit", "buffer", "chunk", "boundary", "raw", "line", "spawn", "os", "path", "process", "goBinDir", "explicit", "process", "goPath", "path", "os", "DEFAULT_READY_TIMEOUT_MS", "DEFAULT_REQUEST_TIMEOUT_MS", "NEVER_STRIP", "PROTECTED_CHILD_ENV_NAMES", "createUpstream", "spec", "options", "binary", "args", "readyTimeoutMs", "requestTimeoutMs", "log", "onServerMessage", "searchPath", "initializeParams", "active", "starting", "generation", "failPending", "session", "reason", "deferred", "closeSession", "handleLine", "line", "message", "send", "sendRequest", "clientId", "upstreamId", "resolve", "reject", "timer", "answer", "error", "withDeadline", "promise", "deadline", "_resolve", "spawnChild", "vars", "childEnv", "name", "spawn", "startSession", "gen", "child", "onEachLine", "chunk", "code", "ensure", "key", "params", "CREDENTIAL_POLL_MS", "process", "FALLBACK_PROTOCOL_VERSION", "FALLBACK_CAPABILITIES", "log", "message", "write", "payload", "bootPortlessLink", "result", "parsed", "parseProxyArgv", "degraded", "spec", "upstream", "createUpstream", "readUnlistedNames", "readVars", "readListedVars", "versionCache", "profileCache", "binaryVersion", "readBinaryVersion", "cacheDir", "proxyCacheDir", "profile", "dir", "readProfile", "rememberProfile", "patch", "current", "next", "writeProfile", "answerInitialize", "announced", "watchForCredentials", "timer", "forwardToolsList", "vars", "response", "tools", "handshake", "answerToolsListFromCache", "handleInitialize", "resolveEnvFilePath", "answerWithoutCredentials", "handle", "onLine", "line", "error", "detail", "onEachLine"]
4
+ "sourcesContent": ["#!/usr/bin/env node\n// The hashbang must stay on line 1: this entry is published as the `ik-mcp` bin and is exec'd\n// directly by the MCP client, not invoked as `node dist/mcp-proxy.js`.\nimport process from 'node:process'\n\nimport { bootPortlessLink } from 'src/dev/proxy/portless-link'\nimport { parseProxyArgv } from 'src/lib/mcp-proxy/argv'\nimport { proxyCacheDir, readBinaryVersion, readProfile, writeProfile } from 'src/lib/mcp-proxy/cache'\nimport type { UpstreamProfile } from 'src/lib/mcp-proxy/cache'\nimport { readListedVars, readUnlistedNames, resolveEnvFilePath } from 'src/lib/mcp-proxy/env-vars'\nimport type { ProxyVars } from 'src/lib/mcp-proxy/env-vars'\nimport { onEachLine } from 'src/lib/mcp-proxy/line-stream'\nimport { createUpstream } from 'src/lib/mcp-proxy/upstream'\nimport type { JsonRpcMessage, ProxySpec, Upstream } from 'src/lib/mcp-proxy/upstream'\n\nconst CREDENTIAL_POLL_MS = Number(process.env.IK_MCP_POLL_MS ?? 2000)\n\n/**\n * Answered on a cold cache, when no upstream has ever been observed on this machine. Pinned rather\n * than echoed from the client: echoing back whatever a client asks for claims support for a\n * revision nothing here has ever spoken. Only `tools` is claimed \u2014 every MCP server has tools, not\n * every one has resources, and claiming `resources` for one that lacks them makes a client issue\n * `resources/list` and get \"method not found\".\n */\nconst FALLBACK_PROTOCOL_VERSION = '2025-06-18'\nconst FALLBACK_CAPABILITIES = { tools: { listChanged: true } }\n\nconst log = (message: string): void => {\n process.stderr.write(`ik-mcp: ${message}\\n`)\n}\n\nconst write = (payload: JsonRpcMessage): void => {\n process.stdout.write(`${JSON.stringify(payload)}\\n`)\n}\n\n// This bin is the process Claude Code keeps alive, so it is where `~/.infra-kit/portless` converges on\n// a machine that only ever runs the MCP surface. fs-only and synchronous \u2014 nothing is spawned before the\n// handshake \u2014 and stdout is the transport, so only a failure earns a stderr line; the ordinary outcomes\n// are `doctor`'s to show.\nbootPortlessLink((result, message) => {\n if (result.outcome === 'failed')\n log(\n result.kind === 'link'\n ? `${message} failed: ${result.link} -> ${result.target}`\n : `${message} failed: ${result.node} <- ${result.source}`,\n )\n})\n\nconst parsed = parseProxyArgv(process.argv.slice(2))\n\n/**\n * Bad argv is the same state as \"no credentials yet\", not a crash: the handshake is answered, the\n * tool list is empty, and every other request says what is wrong and how to fix it. A proxy that\n * exits on a typo in `.mcp.json` is a dead server the client cannot recover.\n */\nconst degraded: string | null = parsed.ok\n ? null\n : `${parsed.problem} \u2014 run \\`ik setup\\` to regenerate this .mcp.json entry`\nconst spec: ProxySpec | null = parsed.ok ? parsed.spec : null\n\nconst upstream: Upstream | null =\n spec === null\n ? null\n : createUpstream(spec, {\n log,\n // Server-initiated notifications belong to the client and travel verbatim.\n onServerMessage: write,\n // Everything the launching shell picked up from the same env file, minus the listed names,\n // is deleted from the child's inherited environment.\n stripFromChildEnv: () => {\n return readUnlistedNames(spec.env)\n },\n })\n\nconst readVars = (): ProxyVars | null => {\n return spec === null ? null : readListedVars(spec.env)\n}\n\n// Both are resolved on first use, never at module load: `readBinaryVersion` spawns a process and\n// can block for up to its timeout, and doing that before stdin is wired delays the handshake of\n// every session \u2014 including ones that never touch the upstream.\nlet versionCache: string | null = null\nlet profileCache: UpstreamProfile | null | undefined\n\nconst binaryVersion = (): string => {\n versionCache ??=\n // No spec means no upstream to ask, and importing package.json for a version string would drag\n // the whole manifest \u2014 dependency names included \u2014 into a bundle the guard keeps flat.\n spec === null ? 'unknown' : readBinaryVersion(spec.command, ['--version'], process.env.PATH)\n\n return versionCache\n}\n\nconst cacheDir = (): string | null => {\n return spec === null ? null : proxyCacheDir(spec.name)\n}\n\nconst profile = (): UpstreamProfile | null => {\n if (profileCache === undefined) {\n const dir = cacheDir()\n\n profileCache = dir === null ? null : readProfile(binaryVersion(), dir)\n }\n\n return profileCache\n}\n\n/** Fold whatever the live upstream just told us into the on-disk profile. */\nconst rememberProfile = (patch: Partial<UpstreamProfile>): void => {\n const dir = cacheDir()\n\n if (dir === null) return\n\n const current = profile()\n\n const next: UpstreamProfile = {\n version: binaryVersion(),\n protocolVersion: patch.protocolVersion ?? current?.protocolVersion ?? FALLBACK_PROTOCOL_VERSION,\n capabilities: patch.capabilities ?? current?.capabilities ?? FALLBACK_CAPABILITIES,\n tools: patch.tools ?? current?.tools ?? [],\n }\n\n profileCache = next\n writeProfile(next, dir)\n}\n\n/**\n * Answer `initialize` without spawning anything.\n *\n * Spawning here would forfeit lazy start \u2014 a session that never touches the upstream would still\n * pay for a child. The cost is that a first-ever session reports the pinned fallback capabilities\n * and is corrected once a real handshake has been seen; MCP has no capability-change notification,\n * so that correction lands on the NEXT session.\n */\nconst answerInitialize = (message: JsonRpcMessage): void => {\n write({\n jsonrpc: '2.0',\n id: message.id,\n result: {\n protocolVersion: profile()?.protocolVersion ?? FALLBACK_PROTOCOL_VERSION,\n capabilities: profile()?.capabilities ?? FALLBACK_CAPABILITIES,\n serverInfo: { name: spec?.name ?? 'ik-mcp', version: binaryVersion() },\n },\n })\n}\n\nlet announced = false\n\n/**\n * Credentials arrive mid-session, and stdio keeps a server-to-client channel open the whole time \u2014\n * so the moment they appear the client can be told to list again. Polls the env file ONLY: there is\n * no config to poll, so there is no mid-edit \"invalid config\" window and no path by which a watcher\n * could tear down a live upstream.\n */\nconst watchForCredentials = (): void => {\n const timer = setInterval(() => {\n if (announced || readVars() === null) return\n\n announced = true\n clearInterval(timer)\n log('credentials appeared \u2014 announcing tools/list_changed')\n write({ jsonrpc: '2.0', method: 'notifications/tools/list_changed' })\n }, CREDENTIAL_POLL_MS)\n\n timer.unref()\n}\n\nconst forwardToolsList = async (message: JsonRpcMessage, vars: ProxyVars): Promise<void> => {\n const response = await upstream!.request(message, vars)\n const tools = (response.result as { tools?: unknown[] } | undefined)?.tools\n\n if (Array.isArray(tools)) {\n const handshake = upstream!.handshake()?.result as { protocolVersion?: string; capabilities?: unknown } | undefined\n\n rememberProfile({ tools, capabilities: handshake?.capabilities, protocolVersion: handshake?.protocolVersion })\n }\n\n write(response)\n}\n\n/** Before credentials exist, the tool list is answered from cache \u2014 never with an error. */\nconst answerToolsListFromCache = (message: JsonRpcMessage): void => {\n write({ jsonrpc: '2.0', id: message.id, result: { tools: profile()?.tools ?? [] } })\n}\n\n/** Answers the handshake and arms the watcher; deliberately spawns nothing. */\nconst handleInitialize = (message: JsonRpcMessage): void => {\n upstream?.setInitializeParams(message.params)\n answerInitialize(message)\n\n if (degraded !== null) {\n log(`degraded: ${degraded}`)\n\n return\n }\n\n // Always name the resolved path and the spec: when either is wrong (a stale XDG_CACHE_HOME, a\n // session id the client never inherited, a drifted .mcp.json) nothing else in the session says so.\n // Names only \u2014 the VALUES are credentials.\n log(\n `${spec!.name}: env file ${resolveEnvFilePath()}; reads ${spec!.env.join(', ')}; upstream ${spec!.command} ${binaryVersion()}; cache ${profile() ? 'warm' : 'cold'}`,\n )\n\n if (readVars() !== null) {\n announced = true\n\n return\n }\n\n log('no credentials yet \u2014 deferring')\n watchForCredentials()\n}\n\n/** The pre-`env-load` state (or bad argv), which is normal and must never look like a protocol failure. */\nconst answerWithoutCredentials = (message: JsonRpcMessage): void => {\n if (message.method === 'tools/list') {\n answerToolsListFromCache(message)\n\n return\n }\n\n if (message.id == null) return\n\n write({\n jsonrpc: '2.0',\n id: message.id,\n error: {\n code: -32000,\n message:\n degraded ?? `${spec!.name}: credentials are not loaded yet (${spec!.env.join(', ')}) \u2014 run 'ik env-load'`,\n },\n })\n}\n\nconst handle = async (message: JsonRpcMessage): Promise<void> => {\n // An id with no method is a RESPONSE, not a request. A well-behaved client sends none \u2014 the\n // proxy refuses server-initiated requests, so there is nothing to answer \u2014 and treating one as a\n // request would spawn an upstream and reply `no method undefined`.\n if (message.method == null) return\n\n if (message.method === 'initialize') {\n handleInitialize(message)\n\n return\n }\n\n const vars = readVars()\n\n if (vars === null || upstream === null) {\n answerWithoutCredentials(message)\n\n return\n }\n\n if (message.id == null) {\n // Never spawns. `notifications/initialized` in particular is answered by not relaying it at\n // all: every child gets its own from the handshake replay, and forwarding the client's would\n // make the mandatory handshake defeat lazy start.\n if (message.method !== 'notifications/initialized') upstream.notifyIfActive(message)\n\n return\n }\n\n if (message.method === 'tools/list') {\n await forwardToolsList(message, vars)\n\n return\n }\n\n write(await upstream.request(message, vars))\n}\n\nconst onLine = (line: string): void => {\n let message: JsonRpcMessage\n\n try {\n message = JSON.parse(line) as JsonRpcMessage\n } catch {\n log('ignoring non-JSON line from client')\n\n return\n }\n\n handle(message).catch((error: unknown) => {\n const detail = error instanceof Error ? error.message : String(error)\n\n log(detail)\n\n if (message.id != null) {\n write({ jsonrpc: '2.0', id: message.id, error: { code: -32000, message: detail } })\n }\n })\n}\n\nprocess.on('exit', () => {\n upstream?.dispose()\n})\nprocess.on('SIGTERM', () => {\n process.exit(0)\n})\nprocess.on('SIGINT', () => {\n process.exit(0)\n})\n\nonEachLine(process.stdin, onLine)\n\n// The client closing its end is the ordinary way this server ends.\nprocess.stdin.on('end', () => {\n process.exit(0)\n})\n", "import { PROTECTED_CHILD_ENV_NAMES } from './protected-env'\nimport type { ProxySpec } from './upstream'\n\n/** Mirrors the config schema's name rule; re-checked here because the name becomes a cache subdir. */\nconst NAME_PATTERN = /^[a-z][a-z0-9-]*$/\n/** Mirrors `envVarName` in the config schema. */\nconst ENV_VAR_PATTERN = /^[A-Z_]\\w*$/i\n\nexport type ParsedArgv = { ok: true; spec: ProxySpec } | { ok: false; problem: string }\n\ninterface Flags {\n name: string | null\n env: string[]\n unset: string[]\n}\n\n/** Apply one `--flag value` pair, or say why it cannot be applied. */\nconst applyFlag = (flags: Flags, flag: string, value: string): string | null => {\n if (flag === '--name') {\n if (flags.name !== null) return '--name given twice'\n if (!NAME_PATTERN.test(value)) return `--name \"${value}\" must be lowercase letters, digits and hyphens`\n\n flags.name = value\n\n return null\n }\n\n if (flag === '--env' || flag === '--unset') {\n if (!ENV_VAR_PATTERN.test(value)) return `${flag} \"${value}\" is not an environment-variable name`\n // Mirrors the schema refinement, because hand-written argv (the `claude mcp add --scope local`\n // path) never passes through the schema \u2014 and `--unset PATH` would blank PATH and ENOENT the spawn.\n if (PROTECTED_CHILD_ENV_NAMES.has(value)) return `${flag} \"${value}\" is process plumbing, not a credential`\n\n if (flag === '--env') flags.env.push(value)\n else flags.unset.push(value)\n\n return null\n }\n\n return `unknown flag ${flag}`\n}\n\n/** Walk the flag half; returns the index of the `--` separator or a problem. */\nconst readFlags = (argv: readonly string[], flags: Flags): { separator: number } | { problem: string } => {\n let index = 0\n\n while (index < argv.length) {\n const flag = argv[index]!\n\n if (flag === '--') return { separator: index }\n\n // A bare word where a flag belongs is the upstream command arriving early \u2014 the separator\n // is what is missing, and that is the more useful thing to say than \"cmd needs a value\".\n if (!flag.startsWith('--')) return { problem: `missing \"--\" before the upstream command (saw \"${flag}\")` }\n\n const value = argv[index + 1]\n\n // A value that looks like a flag (`--env --`) would otherwise eat the separator and turn the\n // upstream command into a flag \u2014 the case that spawns the wrong binary instead of refusing.\n if (value === undefined || value.startsWith('--')) return { problem: `${flag} needs a value` }\n\n const problem = applyFlag(flags, flag, value)\n\n if (problem !== null) return { problem }\n\n index += 2\n }\n\n return { problem: 'missing \"--\" before the upstream command' }\n}\n\n/**\n * Parse the argv `ik setup` derived: `--name N (--env V)+ (--unset V)* -- <command> [args...]`.\n *\n * Every flag VALUE is validated, not only `--name`. The first `--` in flag position ends our half;\n * everything after it is the upstream's, verbatim, `--`s and all.\n */\n// Node builtins only, on purpose. Pulling commander in here would drag it into the proxy bundle,\n// which the chunk-isolation guard forbids \u2014 and a four-flag grammar does not need it.\nexport const parseProxyArgv = (argv: readonly string[]): ParsedArgv => {\n const flags: Flags = { name: null, env: [], unset: [] }\n const walked = readFlags(argv, flags)\n\n if ('problem' in walked) return { ok: false, problem: walked.problem }\n if (flags.name === null) return { ok: false, problem: 'missing --name' }\n if (flags.env.length === 0) return { ok: false, problem: 'missing --env (at least one variable to read)' }\n\n const command = argv[walked.separator + 1]\n\n if (command === undefined || command.length === 0)\n return { ok: false, problem: 'missing upstream command after \"--\"' }\n\n return {\n ok: true,\n spec: { name: flags.name, command, args: argv.slice(walked.separator + 2), env: flags.env, unset: flags.unset },\n }\n}\n", "import { spawnSync } from 'node:child_process'\nimport fs from 'node:fs'\nimport path from 'node:path'\nimport process from 'node:process'\n\nimport { atomicWriteFileSync, getCacheRoot } from 'src/lib/constants'\n\n/**\n * What a session can answer with before any child exists: the tool list and the\n * capability payload the upstream last reported.\n *\n * Capabilities are cached alongside the tools because MCP has no\n * capability-change notification \u2014 a deferred `initialize` must state them up front\n * and can never correct itself, so the honest answer has to come from disk.\n */\nexport interface UpstreamProfile {\n version: string\n protocolVersion: string\n capabilities: unknown\n tools: unknown[]\n}\n\n/**\n * Proxy state lives under the CACHE root, never `~/.infra-kit` \u2014 that is\n * `USER_CONFIG_DIR_NAME`, the auto-seeded project-config registry, where a\n * throwaway derived file has no business living. One subdir per configured name.\n */\nexport const proxyCacheDir = (name: string): string => {\n return path.join(getCacheRoot(), 'mcp-proxy', name)\n}\n\n/** Keeps a version string usable as one path segment. */\nconst safeSegment = (version: string): string => {\n return version.replaceAll(/[^\\w.-]/g, '_').slice(0, 64)\n}\n\nexport const profilePath = (version: string, dir: string): string => {\n return path.join(dir, `profile-${safeSegment(version)}.json`)\n}\n\n/**\n * A cache key for a binary that does not answer `--version`: its resolved path's size and mtime.\n *\n * Both change on every upgrade, which is all the key has to guarantee. Hashing the file would too,\n * but a Go binary is tens of megabytes and this runs at session start.\n */\nexport const binaryFingerprint = (binary: string, searchPath?: string): string => {\n const candidates = path.isAbsolute(binary)\n ? [binary]\n : (searchPath ?? process.env.PATH ?? '').split(path.delimiter).map((dir) => {\n return path.join(dir, binary)\n })\n\n for (const candidate of candidates) {\n try {\n const stat = fs.statSync(candidate)\n\n return `stat-${stat.size}-${Math.trunc(stat.mtimeMs)}`\n } catch {\n // not here; try the next PATH entry\n }\n }\n\n return 'unknown'\n}\n\n/**\n * The upstream binary's self-reported version, falling back to {@link binaryFingerprint}.\n * This is the cache key, so an upgrade that changes the tool set can never be served\n * a stale list \u2014 the new version simply looks at a different file.\n */\nexport const readBinaryVersion = (\n binary: string,\n versionArgs: readonly string[] = ['--version'],\n searchPath?: string,\n): string => {\n try {\n // The same PATH the upstream spawn uses. Without it, a `go install` layout \u2014 where\n // mcp-grafana lives only in GOBIN \u2014 probes as ENOENT, every version collapses into\n // one 'unknown' cache bucket, and an upgrade is served the previous tool list.\n const result = spawnSync(binary, [...versionArgs], {\n encoding: 'utf8',\n timeout: 5000,\n env: searchPath == null ? process.env : { ...process.env, PATH: searchPath },\n })\n\n if (result.status !== 0) return binaryFingerprint(binary, searchPath)\n\n const reported = `${result.stdout}`.trim().split('\\n')[0]?.trim() ?? ''\n\n return reported.length > 0 ? reported : binaryFingerprint(binary, searchPath)\n } catch {\n return binaryFingerprint(binary, searchPath)\n }\n}\n\n/**\n * The cached profile for this binary version, or null.\n *\n * Every failure is a null, never a throw: a torn or truncated file must degrade to\n * \"no cache yet\", because the alternative is an exception on the deferred\n * `initialize` path \u2014 which would kill the session the cache exists to rescue.\n */\nexport const readProfile = (version: string, dir: string): UpstreamProfile | null => {\n try {\n const parsed = JSON.parse(fs.readFileSync(profilePath(version, dir), 'utf8')) as Partial<UpstreamProfile>\n\n if (parsed.version !== version || !Array.isArray(parsed.tools)) return null\n\n return {\n version,\n protocolVersion: typeof parsed.protocolVersion === 'string' ? parsed.protocolVersion : '',\n capabilities: parsed.capabilities ?? {},\n tools: parsed.tools,\n }\n } catch {\n return null\n }\n}\n\n/**\n * Persist a profile. Best-effort: a cache that cannot be written is a slower next\n * session, not a broken one.\n */\nexport const writeProfile = (profile: UpstreamProfile, dir: string): boolean => {\n try {\n fs.mkdirSync(dir, { recursive: true })\n // Atomic, because two sessions can write this concurrently and a half-written\n // file reads back as \"no tools\" \u2014 a silently toolless session with no error.\n atomicWriteFileSync(profilePath(profile.version, dir), `${JSON.stringify(profile)}\\n`, 0o600)\n\n return true\n } catch {\n return false\n }\n}\n", "import path from 'node:path'\nimport process from 'node:process'\n\nimport {\n ENV_LOAD_FILE,\n ENV_LOAD_ROOT_FILE,\n INFRA_KIT_SESSION_VAR,\n getCacheRoot,\n isInEnvLoadScope,\n parseVarsFromEnvFile,\n} from 'src/lib/constants'\n\n/**\n * Session id used when the proxy inherits none. `getSessionCacheDir()` THROWS in that case,\n * which is correct for a command and fatal for a server \u2014 a proxy that throws at startup is a\n * dead MCP server, so it degrades to a fixed dir instead.\n */\nexport const NO_SESSION = 'no-session'\n\n/** Escape hatch for tests and for pointing the proxy at a hand-written file. */\nexport const ENV_FILE_OVERRIDE_VAR = 'IK_MCP_ENV_FILE'\n\n/** The listed variables' values, keyed by name, in the order the spec listed them. */\nexport type ProxyVars = Record<string, string>\n\nexport const resolveSessionId = (): string => {\n const session = process.env[INFRA_KIT_SESSION_VAR]\n\n return session != null && session.length > 0 ? session : NO_SESSION\n}\n\n/**\n * Where `ik env-load` writes for this session. Goes through `getCacheRoot()` so\n * `XDG_CACHE_HOME` is honoured \u2014 a hardcoded `~/.cache` would silently read a path\n * nothing ever writes on any box that sets it.\n */\nexport const resolveEnvFilePath = (): string => {\n const override = process.env[ENV_FILE_OVERRIDE_VAR]\n\n if (override != null && override.length > 0) return override\n\n return path.join(getCacheRoot(), resolveSessionId(), ENV_LOAD_FILE)\n}\n\n/** The file wins over the inherited environment, per name. */\nconst pick = (fileVars: Record<string, string>, name: string): string => {\n const fromFile = fileVars[name]\n\n if (fromFile != null && fromFile.length > 0) return fromFile\n\n const fromEnv = process.env[name]\n\n return fromEnv != null && fromEnv.length > 0 ? fromEnv : ''\n}\n\n/**\n * The values of `names`, or null while any of them is missing \u2014 the normal state before\n * `ik env-load` runs, which must never be an error.\n *\n * Built by iterating `names`, not the file, so the record's key order \u2014 and therefore its\n * JSON, which is the respawn key \u2014 is stable however Doppler happens to order the file.\n */\nexport const readListedVars = (names: readonly string[], filePath: string = resolveEnvFilePath()): ProxyVars | null => {\n // Another repo's load must not configure this repo's MCP server; the inherited environment still can.\n const fileVars = isInEnvLoadScope(path.join(path.dirname(filePath), ENV_LOAD_ROOT_FILE), process.cwd())\n ? parseVarsFromEnvFile(filePath)\n : {}\n const vars: ProxyVars = {}\n\n for (const name of names) {\n const value = pick(fileVars, name)\n\n if (value.length === 0) return null\n\n vars[name] = value\n }\n\n return vars\n}\n\n/**\n * Every name the env file defines that the spec does NOT list.\n *\n * The child inherits this process's environment, and this process was launched from a shell\n * that had normally sourced the very file these came from \u2014 so without stripping them by name,\n * every production secret reaches the child by inheritance regardless of what the spec lists.\n */\nexport const readUnlistedNames = (names: readonly string[], filePath: string = resolveEnvFilePath()): string[] => {\n const listed = new Set(names)\n\n return Object.keys(parseVarsFromEnvFile(filePath)).filter((name) => {\n return !listed.has(name)\n })\n}\n", "/**\n * Newline framing for a JSON-RPC stdio stream.\n *\n * Deliberately not `node:readline`. That module is fenced off outside\n * `src/lib/prompts/` because it is the shape a future interactive stdin reader would\n * take, and the prompts module owns the stdin refcount. This is a transport, not a\n * prompt \u2014 but the fence has no exemptions and is worth more intact than this is worth\n * saving, and hand framing is a dozen lines with no buffering semantics to inherit.\n */\nexport const onEachLine = (stream: NodeJS.ReadableStream, visit: (line: string) => void): void => {\n let buffer = ''\n\n stream.setEncoding('utf8')\n stream.on('data', (chunk: string) => {\n buffer += chunk\n\n let boundary = buffer.indexOf('\\n')\n\n while (boundary !== -1) {\n const raw = buffer.slice(0, boundary)\n\n buffer = buffer.slice(boundary + 1)\n\n // A peer that writes CRLF must not hand us a trailing CR inside the JSON.\n const line = raw.endsWith('\\r') ? raw.slice(0, -1) : raw\n\n if (line.trim().length > 0) visit(line)\n\n boundary = buffer.indexOf('\\n')\n }\n })\n}\n", "import type { Buffer } from 'node:buffer'\nimport { spawn } from 'node:child_process'\nimport type { ChildProcessWithoutNullStreams } from 'node:child_process'\nimport os from 'node:os'\nimport path from 'node:path'\nimport process from 'node:process'\n\nimport type { ProxyVars } from './env-vars'\nimport { onEachLine } from './line-stream'\nimport { PROTECTED_CHILD_ENV_NAMES } from './protected-env'\n\nexport interface JsonRpcMessage {\n jsonrpc?: string\n id?: string | number\n method?: string\n params?: unknown\n result?: unknown\n error?: { code: number; message: string }\n}\n\n/**\n * What one configured server is: the argv-borne half of an `mcp.<name>` entry.\n *\n * `env` names are injected inline from {@link ProxyVars}; `unset` names are forced empty so a stale\n * file-based credential can never outrank the inline one (measured for mcp-grafana: an inline token\n * takes precedence over `..._TOKEN_FILE`, but only if the file variable is not also set).\n */\nexport interface ProxySpec {\n name: string\n command: string\n args: readonly string[]\n env: readonly string[]\n unset: readonly string[]\n}\n\nexport interface UpstreamOptions {\n extraEnv?: NodeJS.ProcessEnv\n readyTimeoutMs?: number\n /**\n * Per-request ceiling. A child that answers the handshake and then goes silent must\n * not hang every later request for the rest of the session.\n */\n requestTimeoutMs?: number\n /**\n * Names to DELETE from the child's inherited environment \u2014 the unlisted secrets the\n * launching shell picked up from the same env file.\n */\n stripFromChildEnv?: () => readonly string[]\n log?: (message: string) => void\n /** Notifications and server-initiated requests, which travel to the client verbatim. */\n onServerMessage?: (message: JsonRpcMessage) => void\n}\n\n/** `go install` lands the binary in GOBIN, which a GUI-launched process never has on PATH. */\nconst goBinDir = (): string => {\n const explicit = process.env.GOBIN\n\n if (explicit != null && explicit.length > 0) return explicit\n\n const goPath = process.env.GOPATH\n\n return path.join(goPath != null && goPath.length > 0 ? goPath : path.join(os.homedir(), 'go'), 'bin')\n}\n\nconst DEFAULT_READY_TIMEOUT_MS = 15_000\nconst DEFAULT_REQUEST_TIMEOUT_MS = 120_000\n\nconst NEVER_STRIP = PROTECTED_CHILD_ENV_NAMES\n\ninterface Deferred {\n /** Absent for the shim's OWN requests, whose answers must never reach the client. */\n clientId?: string | number\n resolve: (message: JsonRpcMessage) => void\n reject: (error: Error) => void\n}\n\ninterface Session {\n child: ChildProcessWithoutNullStreams\n /** JSON of the ordered vars record \u2014 the respawn key. */\n key: string\n generation: number\n pending: Map<number, Deferred>\n nextId: number\n handshake: JsonRpcMessage | null\n closed: boolean\n}\n\nexport interface Upstream {\n setInitializeParams: (params: unknown) => void\n request: (message: JsonRpcMessage, vars: ProxyVars) => Promise<JsonRpcMessage>\n /** Forwards only when an upstream already exists; never spawns one. */\n notifyIfActive: (message: JsonRpcMessage) => boolean\n /** The upstream's own `initialize` result, once one has been observed. */\n handshake: () => JsonRpcMessage | null\n dispose: () => void\n}\n\nexport const createUpstream = (spec: ProxySpec, options: UpstreamOptions = {}): Upstream => {\n const binary = spec.command\n const args = spec.args\n const readyTimeoutMs = options.readyTimeoutMs ?? DEFAULT_READY_TIMEOUT_MS\n const requestTimeoutMs = options.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS\n const log = options.log ?? ((): void => {})\n const onServerMessage = options.onServerMessage ?? ((): void => {})\n\n const searchPath = `${goBinDir()}${path.delimiter}${process.env.PATH ?? ''}`\n\n let initializeParams: unknown = {}\n let active: Session | null = null\n let starting: { key: string; generation: number; promise: Promise<Session> } | null = null\n let generation = 0\n\n const failPending = (session: Session, reason: string): void => {\n for (const deferred of session.pending.values()) deferred.reject(new Error(reason))\n session.pending.clear()\n }\n\n const closeSession = (session: Session, reason: string): void => {\n if (session.closed) return\n\n session.closed = true\n // In-flight work is ERRORED, never silently dropped: a caller waiting on a killed\n // upstream would otherwise hang for the rest of the session.\n failPending(session, `${spec.name} upstream ${reason}`)\n session.child.kill()\n }\n\n // A response carries an id and no method; anything with a method is server-initiated\n // and belongs to the client. Routing on `method` first is what keeps the shim's own\n // ids from ever being confused with the client's.\n const handleLine = (session: Session, line: string): void => {\n let message: JsonRpcMessage\n\n try {\n message = JSON.parse(line) as JsonRpcMessage\n } catch {\n log(`ignoring non-JSON line from ${binary}`)\n\n return\n }\n\n if (message.method != null) {\n if (message.id == null) {\n onServerMessage(message)\n\n return\n }\n\n // A server-initiated REQUEST carries the upstream's own id. Relaying it would send\n // the client an id from a namespace it does not own, and the client's answer would\n // re-enter as a fresh request with no method. mcp-grafana initiates none today, so\n // refusing is honest and cannot mis-route.\n log(`refusing server-initiated request ${message.method}`)\n send(session, {\n jsonrpc: '2.0',\n id: message.id,\n error: { code: -32601, message: 'client requests are not supported by this shim' },\n })\n\n return\n }\n\n if (message.id == null) return\n\n const deferred = session.pending.get(Number(message.id))\n\n if (!deferred) return\n\n session.pending.delete(Number(message.id))\n\n // Map back: the client only ever sees the id IT chose. Resolving with the wire id\n // would hand the client an answer labelled with the shim's private numbering.\n deferred.resolve(deferred.clientId === undefined ? message : { ...message, id: deferred.clientId })\n }\n\n const send = (session: Session, message: JsonRpcMessage): void => {\n if (session.closed) return\n\n session.child.stdin.write(`${JSON.stringify(message)}\\n`)\n }\n\n /**\n * Send on the shim's OWN id namespace and await the answer.\n *\n * `clientId` is what makes the namespace real: present, the answer is re-labelled and\n * relayed; absent, it is consumed here. The replayed handshake takes the absent form,\n * so a client request numbered `0` can never collide with it.\n */\n const sendRequest = (\n session: Session,\n message: JsonRpcMessage,\n clientId?: string | number,\n ): Promise<JsonRpcMessage> => {\n // A session can be closed between `ensure` resolving and the write landing \u2014 a\n // dispose, a crash, a swap. Registering here anyway would leave the caller pending\n // forever, because the rejection sweep has already run.\n if (session.closed) return Promise.reject(new Error(`${spec.name} upstream is closed`))\n\n const upstreamId = session.nextId\n\n session.nextId += 1\n\n return new Promise<JsonRpcMessage>((resolve, reject) => {\n const timer = setTimeout(() => {\n session.pending.delete(upstreamId)\n reject(new Error(`${binary} did not answer ${message.method ?? 'request'} within ${requestTimeoutMs}ms`))\n }, requestTimeoutMs)\n\n session.pending.set(upstreamId, {\n clientId,\n resolve: (answer: JsonRpcMessage): void => {\n clearTimeout(timer)\n resolve(answer)\n },\n reject: (error: Error): void => {\n clearTimeout(timer)\n reject(error)\n },\n })\n send(session, { ...message, jsonrpc: '2.0', id: upstreamId })\n })\n }\n\n const withDeadline = async (promise: Promise<JsonRpcMessage>): Promise<JsonRpcMessage> => {\n let timer: NodeJS.Timeout | undefined\n\n const deadline = new Promise<never>((_resolve, reject) => {\n timer = setTimeout(() => {\n reject(new Error(`${binary} did not answer initialize within ${readyTimeoutMs}ms`))\n }, readyTimeoutMs)\n })\n\n try {\n return await Promise.race([promise, deadline])\n } finally {\n if (timer) clearTimeout(timer)\n }\n }\n\n const spawnChild = (vars: ProxyVars): ChildProcessWithoutNullStreams => {\n // Listed variables go INLINE \u2014 no credential is written to disk by this proxy at all.\n const childEnv: NodeJS.ProcessEnv = { ...process.env, ...options.extraEnv, PATH: searchPath, ...vars }\n\n // Forced empty rather than deleted: a deleted name would be re-inherited by anything the\n // child spawns from ITS parent's environment; an empty string is an explicit \"no\".\n for (const name of spec.unset) childEnv[name] = ''\n\n // Applied LAST, over the fully merged environment, so no earlier layer can put a\n // secret back. The proxy is normally launched from a shell that sourced the very env\n // file these names came from, and inheritance \u2014 not the listed-names read filter \u2014 is\n // the path by which a production secret would otherwise reach the child.\n for (const name of options.stripFromChildEnv?.() ?? []) {\n if (!NEVER_STRIP.has(name)) delete childEnv[name]\n }\n\n return spawn(binary, [...args], {\n env: childEnv,\n stdio: ['pipe', 'pipe', 'pipe'],\n }) as ChildProcessWithoutNullStreams\n }\n\n const startSession = async (vars: ProxyVars, gen: number): Promise<Session> => {\n const child = spawnChild(vars)\n\n const session: Session = {\n child,\n key: JSON.stringify(vars),\n generation: gen,\n pending: new Map(),\n nextId: 1,\n handshake: null,\n closed: false,\n }\n\n onEachLine(child.stdout, (line) => {\n handleLine(session, line)\n })\n\n child.stderr.on('data', (chunk: Buffer) => {\n // Per LINE, not per chunk: mcp-grafana emits several log lines in one write, and\n // prefixing only the first leaves the rest looking like they came from elsewhere \u2014\n // which matters, because this is the only window into the upstream a user gets.\n for (const line of chunk.toString().trimEnd().split('\\n')) {\n if (line.length > 0) log(`${binary}: ${line}`)\n }\n })\n\n child.on('error', (error: Error) => {\n closeSession(session, `failed to start: ${error.message}`)\n })\n\n child.on('exit', (code) => {\n closeSession(session, `exited with code ${String(code)}`)\n })\n\n try {\n // A child that spawns and never answers must not hang every later request, so the\n // handshake \u2014 not the spawn \u2014 is what readiness means, and it is bounded.\n session.handshake = await withDeadline(sendRequest(session, { method: 'initialize', params: initializeParams }))\n } catch (error) {\n closeSession(session, 'handshake failed')\n throw error\n }\n\n send(session, { jsonrpc: '2.0', method: 'notifications/initialized' })\n log(`serving ${spec.name} (${binary})`)\n\n return session\n }\n\n const ensure = async (vars: ProxyVars): Promise<Session> => {\n const key = JSON.stringify(vars)\n\n if (active && !active.closed && active.key === key) return active\n if (starting && starting.key === key) return starting.promise\n\n generation += 1\n\n const gen = generation\n\n // Which variable changed is deliberately not logged: the values are credentials.\n if (active) log(`${spec.name}: a listed variable changed \u2014 replacing upstream`)\n\n const promise = (async (): Promise<Session> => {\n const session = await startSession(vars, gen)\n\n // A newer target superseded this start while it was in flight. Binding to it now\n // would serve the OLD credentials for the rest of the session.\n if (gen !== generation) {\n closeSession(session, 'superseded by a newer target')\n throw new Error(`${spec.name} upstream superseded by a newer target`)\n }\n\n if (active) closeSession(active, 'replaced')\n active = session\n\n return session\n })()\n\n starting = { key, generation: gen, promise }\n\n try {\n return await promise\n } finally {\n if (starting?.generation === gen) starting = null\n }\n }\n\n return {\n setInitializeParams: (params: unknown): void => {\n initializeParams = params\n },\n request: async (message: JsonRpcMessage, vars: ProxyVars): Promise<JsonRpcMessage> => {\n const session = await ensure(vars)\n\n return sendRequest(session, { method: message.method, params: message.params }, message.id)\n },\n notifyIfActive: (message: JsonRpcMessage): boolean => {\n // Deliberately does NOT call `ensure`. A client notification arriving before any\n // request would otherwise spawn an upstream for a session that has asked the\n // server nothing \u2014 which is exactly what lazy start exists to avoid.\n if (!active || active.closed) return false\n\n send(active, { jsonrpc: '2.0', method: message.method, params: message.params })\n\n return true\n },\n handshake: (): JsonRpcMessage | null => {\n return active?.handshake ?? null\n },\n dispose: (): void => {\n if (active) closeSession(active, 'disposed')\n active = null\n },\n }\n}\n"],
5
+ "mappings": ";8LAGA,OAAOA,MAAa,eCCpB,IAAMC,GAAe,oBAEfC,GAAkB,eAWlBC,GAAY,CAACC,EAAcC,EAAcC,IACzCD,IAAS,SACPD,EAAM,OAAS,KAAa,qBAC3BH,GAAa,KAAKK,CAAK,GAE5BF,EAAM,KAAOE,EAEN,MAJ+B,WAAWA,CAAK,kDAOpDD,IAAS,SAAWA,IAAS,UAC1BH,GAA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GhC9C,EAAQ,MAAM,GAAG,MAAO,IAAM,CAC5BA,EAAQ,KAAK,CAAC,CAChB,CAAC",
6
+ "names": ["process", "NAME_PATTERN", "ENV_VAR_PATTERN", "applyFlag", "flags", "flag", "value", "PROTECTED_CHILD_ENV_NAMES", "readFlags", "argv", "index", "problem", "parseProxyArgv", "walked", "command", "spawnSync", "fs", "path", "process", "proxyCacheDir", "name", "path", "getCacheRoot", "safeSegment", "version", "profilePath", "dir", "binaryFingerprint", "binary", "searchPath", "candidates", "process", "candidate", "stat", "fs", "readBinaryVersion", "versionArgs", "result", "spawnSync", "reported", "readProfile", "parsed", "writeProfile", "profile", "atomicWriteFileSync", "path", "process", "NO_SESSION", "ENV_FILE_OVERRIDE_VAR", "resolveSessionId", "session", "process", "INFRA_KIT_SESSION_VAR", "resolveEnvFilePath", "override", "path", "getCacheRoot", "ENV_LOAD_FILE", "pick", "fileVars", "name", "fromFile", "fromEnv", "readListedVars", "names", "filePath", "isInEnvLoadScope", "ENV_LOAD_ROOT_FILE", "parseVarsFromEnvFile", "vars", "value", "readUnlistedNames", "listed", "onEachLine", "stream", "visit", "buffer", "chunk", "boundary", "raw", "line", "spawn", "os", "path", "process", "goBinDir", "explicit", "process", "goPath", "path", "os", "DEFAULT_READY_TIMEOUT_MS", "DEFAULT_REQUEST_TIMEOUT_MS", "NEVER_STRIP", "PROTECTED_CHILD_ENV_NAMES", "createUpstream", "spec", "options", "binary", "args", "readyTimeoutMs", "requestTimeoutMs", "log", "onServerMessage", "searchPath", "initializeParams", "active", "starting", "generation", "failPending", "session", "reason", "deferred", "closeSession", "handleLine", "line", "message", "send", "sendRequest", "clientId", "upstreamId", "resolve", "reject", "timer", "answer", "error", "withDeadline", "promise", "deadline", "_resolve", "spawnChild", "vars", "childEnv", "name", "spawn", "startSession", "gen", "child", "onEachLine", "chunk", "code", "ensure", "key", "params", "CREDENTIAL_POLL_MS", "process", "FALLBACK_PROTOCOL_VERSION", "FALLBACK_CAPABILITIES", "log", "message", "write", "payload", "bootPortlessLink", "result", "parsed", "parseProxyArgv", "degraded", "spec", "upstream", "createUpstream", "readUnlistedNames", "readVars", "readListedVars", "versionCache", "profileCache", "binaryVersion", "readBinaryVersion", "cacheDir", "proxyCacheDir", "profile", "dir", "readProfile", "rememberProfile", "patch", "current", "next", "writeProfile", "answerInitialize", "announced", "watchForCredentials", "timer", "forwardToolsList", "vars", "response", "tools", "handshake", "answerToolsListFromCache", "handleInitialize", "resolveEnvFilePath", "answerWithoutCredentials", "handle", "onLine", "line", "error", "detail", "onEachLine"]
7
7
  }
@@ -1,2 +1,2 @@
1
- import{b as p}from"./chunk-VDBJ73LS.js";import{a as l}from"./chunk-WIZJQ57Q.js";import{render as z}from"ink";import T from"node:process";import{Box as u,Text as h}from"ink";import{useEffect as x,useState as F}from"react";import{jsx as f,jsxs as m}from"react/jsx-runtime";var v=r=>{let{phase:e,narration:t}=r,[i,n]=F(0);return x(()=>{let a=setInterval(()=>{n(o=>o+1)},S);return()=>{clearInterval(a)}},[]),m(u,{flexDirection:"column",children:[m(u,{children:[f(h,{color:"cyan",children:c[i%c.length]}),f(h,{dimColor:!0,children:` ${e}`})]}),t?f(h,{dimColor:!0,children:t}):null]})},c=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],S=80;import{Box as b,Static as w,Text as L}from"ink";import{Fragment as D,jsx as s,jsxs as B}from"react/jsx-runtime";var g=r=>{let{headerLines:e,logLines:t,footerLines:i}=r,n=[...e,...t],a=P(i,r.maxFooterLines);return B(D,{children:[s(w,{items:n,children:(o,d)=>s(L,{children:o},d)}),s(b,{flexDirection:"column",children:a.map((o,d)=>s(L,{children:o},d))})]})},P=(r,e)=>{if(e==null||e<1||r.length<=e)return r;let t=r.slice(0,e-1);return[...t,` \u2026 +${r.length-t.length} more`]};import{jsx as y}from"react/jsx-runtime";var R=class{renderer;renderFn;stdout;verbose;now;instance=null;finalized=!1;persistent=!1;phase="";narration="";headerLines=[];logLines=[];footerLines=[];constructor(e){this.verbose=e.verbose??!1,this.renderFn=e.render??z,this.stdout=e.stdout??l(T.stdout),this.now=e.now??(()=>new Date),this.renderer=new p({appendLog:e.appendLog,verbose:this.verbose,isTTY:!0,write:t=>{this.stdout.write(t)},now:this.now})}logFn=(e,t="info")=>{this.log(e,t)};renderBoot(){let e=y(v,{phase:this.phase,narration:this.narration});if(this.instance){this.instance.rerender(e);return}this.instance=this.renderFn(e,{stdout:this.stdout,exitOnCtrlC:!1,patchConsole:!1})}unmount(){this.instance&&(this.instance.unmount(),this.instance=null)}narrate(e){if(this.renderer.teeOnly(e,"info"),this.persistent){this.verbose&&(this.logLines.push(e),this.rerenderPersistent());return}this.finalized||(this.narration=e,this.instance&&this.renderBoot())}log(e,t="info",i={}){let n=t!=="debug"||this.verbose;if(this.persistent){i.tee!==!1&&this.renderer.teeOnly(e,t),n&&(this.logLines.push(e),this.rerenderPersistent());return}n&&this.unmount(),this.renderer.log(e,t,i)}bootStep(e){this.renderer.teeOnly(e,"info"),!this.finalized&&(this.phase=e,this.renderBoot())}ready(e){this.headerLines=this.renderer.formatHeaderLines(e),this.footerLines=this.renderer.formatFooterLines(e),this.logLines=[];for(let t of this.headerLines)this.renderer.teeOnly(t,"info");this.finalized=!0,this.persistent=!0,typeof this.stdout.on=="function"&&this.stdout.on("resize",this.onResize),this.rerenderPersistent()}maxFooterLines(){return Math.max(3,(this.stdout.rows??24)-6)}rerenderPersistent(){let e=y(g,{headerLines:this.headerLines,logLines:this.logLines,footerLines:this.footerLines,maxFooterLines:this.maxFooterLines()});if(this.instance){this.instance.rerender(e);return}this.instance=this.renderFn(e,{stdout:this.stdout,exitOnCtrlC:!1,patchConsole:!1})}onResize=()=>{this.persistent&&this.rerenderPersistent()};refresh(e){this.persistent&&(this.footerLines=this.renderer.formatFooterLines(e),this.rerenderPersistent())}dispose(){this.persistent&&(this.rerenderPersistent(),typeof this.stdout.off=="function"&&this.stdout.off("resize",this.onResize)),this.finalized=!0,this.persistent=!1,this.unmount()}};export{R as PersistentInkDevUi};
2
- //# sourceMappingURL=persistent-ink-dev-ui-P65EJCC6.js.map
1
+ import{b as p}from"./chunk-DVXTZPQ5.js";import{a as l}from"./chunk-WIZJQ57Q.js";import{render as z}from"ink";import T from"node:process";import{Box as u,Text as h}from"ink";import{useEffect as x,useState as F}from"react";import{jsx as f,jsxs as m}from"react/jsx-runtime";var v=r=>{let{phase:e,narration:t}=r,[i,n]=F(0);return x(()=>{let a=setInterval(()=>{n(o=>o+1)},S);return()=>{clearInterval(a)}},[]),m(u,{flexDirection:"column",children:[m(u,{children:[f(h,{color:"cyan",children:c[i%c.length]}),f(h,{dimColor:!0,children:` ${e}`})]}),t?f(h,{dimColor:!0,children:t}):null]})},c=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],S=80;import{Box as b,Static as w,Text as L}from"ink";import{Fragment as D,jsx as s,jsxs as B}from"react/jsx-runtime";var g=r=>{let{headerLines:e,logLines:t,footerLines:i}=r,n=[...e,...t],a=P(i,r.maxFooterLines);return B(D,{children:[s(w,{items:n,children:(o,d)=>s(L,{children:o},d)}),s(b,{flexDirection:"column",children:a.map((o,d)=>s(L,{children:o},d))})]})},P=(r,e)=>{if(e==null||e<1||r.length<=e)return r;let t=r.slice(0,e-1);return[...t,` \u2026 +${r.length-t.length} more`]};import{jsx as y}from"react/jsx-runtime";var R=class{renderer;renderFn;stdout;verbose;now;instance=null;finalized=!1;persistent=!1;phase="";narration="";headerLines=[];logLines=[];footerLines=[];constructor(e){this.verbose=e.verbose??!1,this.renderFn=e.render??z,this.stdout=e.stdout??l(T.stdout),this.now=e.now??(()=>new Date),this.renderer=new p({appendLog:e.appendLog,verbose:this.verbose,isTTY:!0,write:t=>{this.stdout.write(t)},now:this.now})}logFn=(e,t="info")=>{this.log(e,t)};renderBoot(){let e=y(v,{phase:this.phase,narration:this.narration});if(this.instance){this.instance.rerender(e);return}this.instance=this.renderFn(e,{stdout:this.stdout,exitOnCtrlC:!1,patchConsole:!1})}unmount(){this.instance&&(this.instance.unmount(),this.instance=null)}narrate(e){if(this.renderer.teeOnly(e,"info"),this.persistent){this.verbose&&(this.logLines.push(e),this.rerenderPersistent());return}this.finalized||(this.narration=e,this.instance&&this.renderBoot())}log(e,t="info",i={}){let n=t!=="debug"||this.verbose;if(this.persistent){i.tee!==!1&&this.renderer.teeOnly(e,t),n&&(this.logLines.push(e),this.rerenderPersistent());return}n&&this.unmount(),this.renderer.log(e,t,i)}bootStep(e){this.renderer.teeOnly(e,"info"),!this.finalized&&(this.phase=e,this.renderBoot())}ready(e){this.headerLines=this.renderer.formatHeaderLines(e),this.footerLines=this.renderer.formatFooterLines(e),this.logLines=[];for(let t of this.headerLines)this.renderer.teeOnly(t,"info");this.finalized=!0,this.persistent=!0,typeof this.stdout.on=="function"&&this.stdout.on("resize",this.onResize),this.rerenderPersistent()}maxFooterLines(){return Math.max(3,(this.stdout.rows??24)-6)}rerenderPersistent(){let e=y(g,{headerLines:this.headerLines,logLines:this.logLines,footerLines:this.footerLines,maxFooterLines:this.maxFooterLines()});if(this.instance){this.instance.rerender(e);return}this.instance=this.renderFn(e,{stdout:this.stdout,exitOnCtrlC:!1,patchConsole:!1})}onResize=()=>{this.persistent&&this.rerenderPersistent()};refresh(e){this.persistent&&(this.footerLines=this.renderer.formatFooterLines(e),this.rerenderPersistent())}dispose(){this.persistent&&(this.rerenderPersistent(),typeof this.stdout.off=="function"&&this.stdout.off("resize",this.onResize)),this.finalized=!0,this.persistent=!1,this.unmount()}};export{R as PersistentInkDevUi};
2
+ //# sourceMappingURL=persistent-ink-dev-ui-ZSOS3CF4.js.map
@@ -1,2 +1,2 @@
1
- import{p as i}from"./chunk-BQPSXIH2.js";import"./chunk-AWFGP6GY.js";import{a as t}from"./chunk-FKA65HOC.js";import"./chunk-QSTGO43H.js";import a from"node:fs";import o from"node:process";import{fileURLToPath as s}from"node:url";var m=r=>{let n=r.indexOf("--parent-pid");if(n===-1)return;let e=Number(r[n+1]);return Number.isInteger(e)&&e>0?e:void 0},p=()=>a.realpathSync(s(new URL("./cli.js",import.meta.url))),d=async()=>{await i(t.version,{selfRealPath:p(),parentPid:m(o.argv)})};d().catch(()=>{o.exitCode=0});
1
+ import{p as i}from"./chunk-MH37P7W4.js";import"./chunk-AWFGP6GY.js";import{a as t}from"./chunk-3UE375II.js";import"./chunk-I23MDR4X.js";import a from"node:fs";import o from"node:process";import{fileURLToPath as s}from"node:url";var m=r=>{let n=r.indexOf("--parent-pid");if(n===-1)return;let e=Number(r[n+1]);return Number.isInteger(e)&&e>0?e:void 0},p=()=>a.realpathSync(s(new URL("./cli.js",import.meta.url))),d=async()=>{await i(t.version,{selfRealPath:p(),parentPid:m(o.argv)})};d().catch(()=>{o.exitCode=0});
2
2
  //# sourceMappingURL=update-check.js.map
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "infra-kit",
3
3
  "type": "module",
4
- "version": "0.13.0",
4
+ "version": "0.15.0",
5
5
  "repository": {
6
6
  "type": "git",
7
7
  "url": "git+https://github.com/ArthurSaenz/infra-kit.git",
@@ -26,7 +26,7 @@
26
26
  "@inquirer/input": "^5.1.6",
27
27
  "@inquirer/password": "^5.2.2",
28
28
  "@inquirer/select": "^5.2.5",
29
- "@slip-stream-kit/config": "^0.13.0",
29
+ "@slip-stream-kit/config": "^0.15.0",
30
30
  "chalk": "^6.0.0",
31
31
  "chokidar": "^5.0.0",
32
32
  "commander": "^15.0.0",
@@ -41,7 +41,7 @@
41
41
  "zx": "^8.8.5"
42
42
  },
43
43
  "devDependencies": {
44
- "@slip-stream-kit/eslint-plugin": "0.13.0",
44
+ "@slip-stream-kit/eslint-plugin": "0.15.0",
45
45
  "@types/aws-lambda": "^8.10.163",
46
46
  "@types/react": "19.3.0",
47
47
  "@wl/eslint-config": "0.1.0",
package/readme.md CHANGED
@@ -66,7 +66,7 @@ An `e2e` package (declared, or inferred from `apps/<app>/tests` / a `@playwright
66
66
  | | `release deploy-selected --from <ci\|local>` | Deploy chosen services — in CI, or from this machine |
67
67
  | | `release deliver` | Deliver to prod (CLI-only, irreversible) |
68
68
  | | `release remove` | Tear down one release — worktree, IDE folders, PR, local and remote branches, then the Jira fix version last. Refuses a merged PR, a released fix version, or one with issues attached (`--move-issues-to` is the opt-in). Resumable: a partially-removed release re-runs cleanly. Over MCP the Jira step is never attempted (`jira: 'manual'`) |
69
- | **Worktrees** | `worktrees add` | Create a new git worktree |
69
+ | **Worktrees** | `worktrees add` | Create release worktrees (`--versions` / `--all`), or feature worktrees on `feature/<name>` (`--feature <name> [--base <dev\|release>]`, base `dev` by default) |
70
70
  | | `worktrees list` | List all worktrees |
71
71
  | | `worktrees remove` | Remove a worktree (no `--force`; a branch git refuses is reported and the command exits non-zero; a leftover git already unregistered that holds only `.omc/state`, `.omc/sessions` or `.DS_Store` is swept automatically) |
72
72
  | | `worktrees sync` | Sync worktree state (same removal and failure reporting as `worktrees remove`) |
@@ -75,7 +75,10 @@ An `e2e` package (declared, or inferred from `apps/<app>/tests` / a `@playwright
75
75
  | | `env-load` | Load env secrets into shell |
76
76
  | | `env-clear` | Clear loaded secrets |
77
77
  | | `env-token-list` | List redacted service tokens |
78
- | **Configuration** | `config-get` | Print the fully merged infra-kit config (read-only) |
78
+ | | `env-token-set [env]` | Add or replace an env’s Doppler service token — masked prompt, piped stdin (`op read … \| ik env-token-set dev`), `--from-env <VAR>`, or `--from-file <path>` for several `<env>=<token>` lines; validated against Doppler before writing; no env → picker incl. a new env |
79
+ | **Configuration** | `config-get` | Print the fully merged infra-kit config, or one top-level key (`config-get ide`) (read-only) |
80
+ | | `config-set <key> <value>` | Set a top-level key in this project’s per-machine override (`--global` for every project); JSON or bare-string value, kept only if the config still loads |
81
+ | | `config-unset <key>` | Remove a top-level key from the per-machine override (`--global` likewise) |
79
82
  | | `config path` | Print config file locations |
80
83
  | | `config edit` | Edit infra-kit.json in `$EDITOR` |
81
84
  | **Vendor** | `vendor check` | Validate vendor mirrors |