@lensmcp/cluster 1.25.55 → 1.25.56

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.
@@ -20,9 +20,21 @@ export declare function isLoopbackRequest(req: Pick<http.IncomingMessage, 'socke
20
20
  * Home-relative, last two segments: `/Users/dana/work/acme/web` → `~/…/acme/web`.
21
21
  */
22
22
  export declare function displayRoot(root: string, home?: string): string;
23
+ /** A parked on-demand worktree whose dashboard this daemon keeps (parked-dashboards.ts) — never in the registry file,
24
+ * which says what the daemon SERVES. */
25
+ export interface ParkedChooserEntry {
26
+ key: string;
27
+ root: string;
28
+ /** Its dashboard's path under the lens host (`/foodguard-gate1`). */
29
+ base: string;
30
+ name: string;
31
+ baseKey: string;
32
+ apex: string;
33
+ }
23
34
  /** Render the chooser HTML from the registry entries (+ which key is running in THIS gateway). A worktree instance
24
- * (`entry.instance`) is listed UNDER its project, not beside it. */
25
- export declare function renderChooserPage(entries: WorkspaceEntry[], currentKey: string): string;
35
+ * (`entry.instance`) is listed UNDER its project, not beside it. A `parked` worktree takes the place of a stale entry of
36
+ * its own key (a daemon that died with it registered) and opens its dashboard like a live one. */
37
+ export declare function renderChooserPage(entries: WorkspaceEntry[], currentKey: string, parked?: readonly ParkedChooserEntry[]): string;
26
38
  /**
27
39
  * Serve the chooser at the dashboard-host root. Reads the registry fresh so live status is current.
28
40
  *
@@ -32,4 +44,4 @@ export declare function renderChooserPage(entries: WorkspaceEntry[], currentKey:
32
44
  * (issues/closed/codex-security-26). A caller from elsewhere gets the same 404 any other unrouted path
33
45
  * gets: a landing page that announces itself to the network is not a 404 page.
34
46
  */
35
- export declare function serveChooser(res: http.ServerResponse, currentKey: string, req?: Pick<http.IncomingMessage, 'socket'>): void;
47
+ export declare function serveChooser(res: http.ServerResponse, currentKey: string, req?: Pick<http.IncomingMessage, 'socket'>, parked?: readonly ParkedChooserEntry[]): void;
@@ -1,16 +1,16 @@
1
- "use strict";var m=Object.defineProperty;var l=(a,t)=>m(a,"name",{value:t,configurable:!0});var b=Object.defineProperty,i=l((a,t)=>b(a,"name",{value:t,configurable:!0}),"i");Object.defineProperty(exports,"__esModule",{value:!0}),exports.isLoopbackRequest=isLoopbackRequest,exports.displayRoot=displayRoot,exports.renderChooserPage=renderChooserPage,exports.serveChooser=serveChooser;const node_os_1=require("node:os"),workspace_registry_1=require("./workspace-registry"),esc=i(a=>a.replace(/[&<>"']/g,t=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"})[t]),"esc");function isLoopbackRequest(a){const t=a.socket?.remoteAddress;if(!t)return!1;const o=t.startsWith("::ffff:")?t.slice(7):t;return o==="::1"||o==="127.0.0.1"||/^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(o)}l(isLoopbackRequest,"isLoopbackRequest"),i(isLoopbackRequest,"isLoopbackRequest");function displayRoot(a,t=(0,node_os_1.homedir)()){const o=a.replace(/\/+$/,"").split("/").filter(Boolean),c=o.slice(-2).join("/");if(!c)return"/";const p=t!==""&&(a===t||a.startsWith(`${t}/`)),s=o.length>2;return p?s?`~/\u2026/${c}`:`~/${c}`:s?`\u2026/${c}`:`/${c}`}l(displayRoot,"displayRoot"),i(displayRoot,"displayRoot");function renderChooserPage(a,t){const o=a.map(e=>({...e,live:e.key===t||(0,workspace_registry_1.isWorkspaceLive)(e)})).sort((e,n)=>Number(n.live)-Number(e.live)||e.key.localeCompare(n.key)),c=new Set(o.map(e=>e.key)),p=i(e=>!!e.instance&&c.has(e.instance.baseKey),"nested"),s=o.filter(e=>!p(e)),x=i(e=>o.filter(n=>n.instance?.baseKey===e),"worktreesOf"),f=i(e=>e.key===t?'<span class="badge here">running here</span>':e.live?'<span class="badge live">live</span>':'<span class="badge off">offline</span>',"badgeOf"),h=i(e=>{const n=x(e);if(n.length===0)return"";const d=n.map(r=>{const g=`<span class="wt-name">${esc(r.instance?.name??r.key)}</span> ${f(r)}<span class="wt-apex">${esc(r.instance?.apex??"")}</span>`;return r.live?`<a class="wt is-live" href="${esc(r.base)}/">${g}<span class="open">Open \u2192</span></a>`:`<div class="wt is-off">${g}</div>`}).join(`
2
- `);return`
3
- <div class="worktrees"><div class="wt-head">Worktrees \xB7 ${n.filter(r=>r.live).length} running</div>
4
- ${d}
5
- </div>`},"worktreeList"),u=s.length===0?'<p class="empty">No workspaces registered yet. Start a gateway in a workspace (<code>lensmcp gateway start</code>) and it will appear here.</p>':s.map(e=>{const n=e.live?'<span class="open">Open dashboard \u2192</span>':'<span class="hint">start its gateway to open</span>',d=e.instance?`<div class="root">worktree <b>${esc(e.instance.name)}</b> of ${esc(e.instance.baseKey)} \xB7 ${esc(e.instance.apex)}</div>`:"",r=`<div class="card-main">
6
- <div class="key">${esc(e.key)} ${f(e)}</div>
7
- <div class="root">${esc(displayRoot(e.root))}</div>${d}
1
+ "use strict";var w=Object.defineProperty;var l=(t,a)=>w(t,"name",{value:a,configurable:!0});var y=Object.defineProperty,r=l((t,a)=>y(t,"name",{value:a,configurable:!0}),"r");Object.defineProperty(exports,"__esModule",{value:!0}),exports.isLoopbackRequest=isLoopbackRequest,exports.displayRoot=displayRoot,exports.renderChooserPage=renderChooserPage,exports.serveChooser=serveChooser;const node_os_1=require("node:os"),workspace_registry_1=require("./workspace-registry"),esc=r(t=>t.replace(/[&<>"']/g,a=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"})[a]),"esc");function isLoopbackRequest(t){const a=t.socket?.remoteAddress;if(!a)return!1;const o=a.startsWith("::ffff:")?a.slice(7):a;return o==="::1"||o==="127.0.0.1"||/^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(o)}l(isLoopbackRequest,"isLoopbackRequest"),r(isLoopbackRequest,"isLoopbackRequest");function displayRoot(t,a=(0,node_os_1.homedir)()){const o=t.replace(/\/+$/,"").split("/").filter(Boolean),p=o.slice(-2).join("/");if(!p)return"/";const n=a!==""&&(t===a||t.startsWith(`${a}/`)),c=o.length>2;return n?c?`~/\u2026/${p}`:`~/${p}`:c?`\u2026/${p}`:`/${p}`}l(displayRoot,"displayRoot"),r(displayRoot,"displayRoot");function renderChooserPage(t,a,o=[]){const p=new Set(o.map(e=>e.key)),n=[...t.filter(e=>!p.has(e.key)).map(e=>({...e,live:e.key===a||(0,workspace_registry_1.isWorkspaceLive)(e),parked:!1})),...o.map(e=>({key:e.key,root:e.root,base:e.base,pid:0,updatedAt:"",instance:{name:e.name,baseKey:e.baseKey,apex:e.apex},live:!1,parked:!0}))].sort((e,s)=>Number(s.live)-Number(e.live)||e.key.localeCompare(s.key)),c=r(e=>e.live||e.parked,"opens"),h=new Set(n.map(e=>e.key)),u=r(e=>!!e.instance&&h.has(e.instance.baseKey),"nested"),d=n.filter(e=>!u(e)),k=r(e=>n.filter(s=>s.instance?.baseKey===e),"worktreesOf"),x=r(e=>e.key===a?'<span class="badge here">running here</span>':e.live?'<span class="badge live">live</span>':e.parked?'<span class="badge parked">parked</span>':'<span class="badge off">offline</span>',"badgeOf"),m=r(e=>{const s=k(e);if(s.length===0)return"";const g=s.map(i=>{const b=`<span class="wt-name">${esc(i.instance?.name??i.key)}</span> ${x(i)}<span class="wt-apex">${esc(i.instance?.apex??"")}</span>`;return c(i)?`<a class="wt is-live" href="${esc(i.base)}/">${b}<span class="open">Open \u2192</span></a>`:`<div class="wt is-off">${b}</div>`}).join(`
2
+ `),f=s.filter(i=>i.parked).length;return`
3
+ <div class="worktrees"><div class="wt-head">Worktrees \xB7 ${s.filter(i=>i.live).length} running${f?` \xB7 ${f} parked`:""}</div>
4
+ ${g}
5
+ </div>`},"worktreeList"),v=d.length===0?'<p class="empty">No workspaces registered yet. Start a gateway in a workspace (<code>lensmcp gateway start</code>) and it will appear here.</p>':d.map(e=>{const s=c(e)?'<span class="open">Open dashboard \u2192</span>':'<span class="hint">start its gateway to open</span>',g=e.instance?`<div class="root">worktree <b>${esc(e.instance.name)}</b> of ${esc(e.instance.baseKey)} \xB7 ${esc(e.instance.apex)}</div>`:"",f=`<div class="card-main">
6
+ <div class="key">${esc(e.key)} ${x(e)}</div>
7
+ <div class="root">${esc(displayRoot(e.root))}</div>${g}
8
8
  </div>
9
- <div class="card-action">${n}</div>`;return`<div class="group">${e.live?`<a class="card is-live" href="${esc(e.base)}/">
10
- ${r}
9
+ <div class="card-action">${s}</div>`;return`<div class="group">${c(e)?`<a class="card is-live" href="${esc(e.base)}/">
10
+ ${f}
11
11
  </a>`:`<div class="card is-off">
12
- ${r}
13
- </div>`}${h(e.key)}</div>`}).join(`
12
+ ${f}
13
+ </div>`}${m(e.key)}</div>`}).join(`
14
14
  `);return`<!doctype html>
15
15
  <html lang="en"><head>
16
16
  <meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">
@@ -36,6 +36,7 @@
36
36
  .badge.here { background: rgba(51,85,255,.16); color: #8aa8ff; }
37
37
  .badge.live { background: rgba(38,190,120,.15); color: #4fd699; }
38
38
  .badge.off { background: rgba(139,147,163,.14); color: #9aa1b0; }
39
+ .badge.parked { background: rgba(214,170,60,.14); color: #d9b55a; }
39
40
  .card-action { flex-shrink: 0; }
40
41
  .open { color: #8aa8ff; font-weight: 600; font-size: 13.5px; text-decoration: none; }
41
42
  .hint { color: #6b7280; font-size: 12.5px; }
@@ -55,10 +56,10 @@
55
56
  <body><div class="wrap">
56
57
  <header>
57
58
  <h1>LensMCP workspaces</h1>
58
- <p class="sub">Pick a workspace to open its dashboard. ${s.filter(e=>e.live).length} live \xB7 ${s.length} known${o.length>s.length?` \xB7 ${o.length-s.length} worktree${o.length-s.length===1?"":"s"}`:""}.</p>
59
+ <p class="sub">Pick a workspace to open its dashboard. ${d.filter(e=>e.live).length} live \xB7 ${d.length} known${n.length>d.length?` \xB7 ${n.length-d.length} worktree${n.length-d.length===1?"":"s"}`:""}.</p>
59
60
  </header>
60
61
  <div class="list">
61
- ${u}
62
+ ${v}
62
63
  </div>
63
64
  <footer>Served by the gateway on <code>lensmcp.local</code>. This list updates as gateways start and stop.</footer>
64
- </div></body></html>`}l(renderChooserPage,"renderChooserPage"),i(renderChooserPage,"renderChooserPage");function serveChooser(a,t,o){if(o&&!isLoopbackRequest(o)){a.writeHead(404,{"content-type":"text/plain; charset=utf-8","cache-control":"no-store"}),a.end("not found");return}const c=renderChooserPage((0,workspace_registry_1.readWorkspaces)(),t);a.writeHead(200,{"content-type":"text/html; charset=utf-8","cache-control":"no-store"}),a.end(c)}l(serveChooser,"serveChooser"),i(serveChooser,"serveChooser");
65
+ </div></body></html>`}l(renderChooserPage,"renderChooserPage"),r(renderChooserPage,"renderChooserPage");function serveChooser(t,a,o,p=[]){if(o&&!isLoopbackRequest(o)){t.writeHead(404,{"content-type":"text/plain; charset=utf-8","cache-control":"no-store"}),t.end("not found");return}const n=renderChooserPage((0,workspace_registry_1.readWorkspaces)(),a,p);t.writeHead(200,{"content-type":"text/html; charset=utf-8","cache-control":"no-store"}),t.end(n)}l(serveChooser,"serveChooser"),r(serveChooser,"serveChooser");
@@ -1,2 +1,2 @@
1
1
  "use strict";var M=Object.defineProperty;var m=(d,r)=>M(d,"name",{value:r,configurable:!0});var W=Object.defineProperty,f=m((d,r)=>W(d,"name",{value:r,configurable:!0}),"f");Object.defineProperty(exports,"__esModule",{value:!0}),exports.clusterVersion=void 0,exports.instanceSummary=instanceSummary,exports.controlSocketPath=controlSocketPath,exports.versionAtLoad=versionAtLoad,exports.readClusterVersion=readClusterVersion,exports.ensureOwnerOnlyDir=ensureOwnerOnlyDir,exports.startControlServer=startControlServer;const tslib_1=require("tslib"),fs=tslib_1.__importStar(require("node:fs")),http=tslib_1.__importStar(require("node:http")),os=tslib_1.__importStar(require("node:os")),path=tslib_1.__importStar(require("node:path")),discovery_1=require("./discovery"),guest_graph_1=require("./guest-graph"),guest_replay_1=require("./guest-replay"),on_demand_1=require("./on-demand"),registration_guards_1=require("./registration-guards"),scope_1=require("./scope"),awake_1=require("./awake"),warm_start_1=require("./warm-start"),service_keys_1=require("./service-keys"),workspace_log_1=require("./workspace-log"),workspace_middleware_1=require("./workspace-middleware");function instanceSummary(d){const r=d?.instance;return r?{instance:r.name,baseKey:r.baseKey,apex:r.apex,baseApex:r.baseApex,...r.frozen?{frozen:!0}:{}}:{}}m(instanceSummary,"instanceSummary"),f(instanceSummary,"instanceSummary");function controlSocketPath(){const d=process.env.LENSMCP_HOME||os.homedir();return path.join(d,".lensmcp","control.sock")}m(controlSocketPath,"controlSocketPath"),f(controlSocketPath,"controlSocketPath");const CONTROL_BODY_BYTES=1e6;class BodyTooLarge extends Error{static{m(this,"BodyTooLarge")}static{f(this,"BodyTooLarge")}constructor(r){super(`body too large (over ${r} bytes)`),this.limit=r}}exports.clusterVersion=versionAtLoad(()=>readClusterVersion(__dirname));function versionAtLoad(d){const r=d();return()=>r}m(versionAtLoad,"versionAtLoad"),f(versionAtLoad,"versionAtLoad");function readClusterVersion(d){let r=d;for(let g=0;g<6;g++){const h=path.join(r,"package.json");if(fs.existsSync(h))try{const c=JSON.parse(fs.readFileSync(h,"utf8"));if(c.name==="@lensmcp/cluster"&&typeof c.version=="string")return c.version}catch{}const S=path.dirname(r);if(S===r)break;r=S}}m(readClusterVersion,"readClusterVersion"),f(readClusterVersion,"readClusterVersion");function readJsonBody(d,r=CONTROL_BODY_BYTES){return new Promise((g,h)=>{const S=[];let c=0,j=!1;d.on("data",$=>{if(!j){if(c+=$.length,c>r){j=!0,S.length=0,h(new BodyTooLarge(r));return}S.push($)}}),d.on("end",()=>{if(j)return;const $=Buffer.concat(S).toString("utf8");try{g({value:$?JSON.parse($):{},bytes:c})}catch(D){h(D)}}),d.on("error",h)})}m(readJsonBody,"readJsonBody"),f(readJsonBody,"readJsonBody");function graphShare(d,r){return r-Buffer.byteLength(JSON.stringify({...d,projectGraph:null}))}m(graphShare,"graphShare"),f(graphShare,"graphShare");function graphVerdict(d){return d?d.refused===void 0?{forwarded:!0,accepted:!0}:{forwarded:!0,accepted:!1,reason:d.refused}:{forwarded:!1,accepted:!1}}m(graphVerdict,"graphVerdict"),f(graphVerdict,"graphVerdict");function ensureOwnerOnlyDir(d){try{fs.mkdirSync(d,{recursive:!0,mode:448})}catch{}try{const r=fs.lstatSync(d);return r.isDirectory()?((r.mode&63)!==0&&fs.chmodSync(d,448),!0):!1}catch{return!1}}m(ensureOwnerOnlyDir,"ensureOwnerOnlyDir"),f(ensureOwnerOnlyDir,"ensureOwnerOnlyDir");function startControlServer(d){const{rt:r}=d,g=d.env??process.env,h=controlSocketPath(),S=path.dirname(h);ensureOwnerOnlyDir(S)||console.warn(`[gateway] control home ${S} is not a usable owner-only directory \u2014 refusing to expose the control plane there.`);try{fs.unlinkSync(h)}catch{}const c=f((e,t,u)=>{e.writeHead(t,{"content-type":"application/json"}),e.end(JSON.stringify(u))},"send"),j=f(async(e,t,u=!1)=>{if(!e.wsKey||!e.root)return{status:400,json:{error:"wsKey and root are required"}};const s=e.projects??{},o=(0,discovery_1.projectSourceRoots)(e.root,s,e.projectDependencies),n=(0,scope_1.readLensScope)(e.root),a=n.key===e.wsKey,l=a&&n.sockNs!==e.wsKey?n.sockNs:void 0,{routes:y,services:i,instance:w}=(0,discovery_1.discoverRoutes)(e.root,s,void 0,e.wsKey,o,l,a?n.instance:void 0),v=(0,workspace_middleware_1.findGatewayMiddleware)(e.root,s),k={wsKey:e.wsKey,...l?{sockNs:l}:{},root:e.root,routes:y,services:i,...w?{instance:w}:{},...v?{middleware:v}:{}},p=(0,registration_guards_1.refuseRegistration)(r.registry,k);if(p)return console.warn(`[gateway] refused to register '${e.wsKey}' from ${e.root}: ${p.error}`),{status:409,json:p};if(u)return w?{status:200,json:{wsKey:e.wsKey,root:e.root,...instanceSummary(k),env:w.env}}:{status:400,json:{error:`'${e.wsKey}' has no resolvable instance configuration`}};const _=(0,on_demand_1.runCapRefusal)(r.registry,k,g);if(_)return console.warn(`[gateway] refused to register '${e.wsKey}' from ${e.root}: ${_.error}`),{status:409,json:_};w?.onDemand&&(k.lastUseAt=Date.now());try{const K=(0,service_keys_1.adoptServiceKeys)(r,e.root,i,e.wsKey);K.added.length>0&&console.log(`[gateway] adopted east-west keys for ${e.wsKey}: ${K.added.join(", ")}`),K.regenerated.length>0&&console.warn(`[gateway] ${e.root} carried another workspace's east-west keys (a copied key file) \u2014 new keys for ${e.wsKey}: ${K.regenerated.join(", ")}`)}catch(K){console.error(`[gateway] could not adopt east-west keys for ${e.wsKey}: ${K.message}`)}try{(0,workspace_log_1.workspaceLogWriter)(e.root)?.(`[gateway] ${new Date().toISOString()} this workspace ('${e.wsKey}') is served by the daemon at ${r.root} (pid ${process.pid}); its gateway-level log is ${path.join(r.root,".lensmcp","gateway.log")}. Pod output for this workspace follows here. Attach live with \`lensmcp logs <service>\`.
2
- `)}catch{}let O;if(r.graphStores){const K={root:e.root,daemonRoot:r.root,otherRoots:r.registry.keys().filter(P=>P!==e.wsKey).flatMap(P=>r.registry.get(P)?.root??[])};O=e.projectGraph===void 0?void 0:(0,guest_graph_1.admitForwardedGraph)(e.projectGraph,{...K,bytes:graphShare(e,t)}),O?.refused!==void 0&&console.warn(`[gateway] refused the project graph '${e.wsKey}' forwarded from ${e.root}: ${O.refused} \u2014 its services start through \`nx run\` until the gateway computes it`),(0,registration_guards_1.sameRoot)(e.root,r.root)||r.graphStores.set((0,guest_graph_1.createGuestGraphStore)({wsKey:e.wsKey,root:e.root,...O?{admission:O}:{},context:K}))}return r.registry.register(k),await d.onRegister?.(k),r.rebuildRoutes(),r.root&&!(0,registration_guards_1.sameRoot)(e.root,r.root)&&(0,guest_replay_1.recordGuest)({wsKey:e.wsKey,root:e.root,projects:s,...e.projectDependencies?{projectDependencies:e.projectDependencies}:{},daemonRoot:r.root,registeredAt:new Date().toISOString(),...w?.onDemand?{onDemand:!0}:{}}),w?.onDemand&&console.log(`[gateway] registered on-demand worktree '${w.name}' (${e.wsKey}) \u2014 nothing starts until its run asks (POST /awake); parked after ${(0,on_demand_1.worktreeRunIdleSec)(g)}s unused (${on_demand_1.WORKTREE_RUN_IDLE_ENV})`),{status:200,json:{ok:!0,wsKey:e.wsKey,routes:y.length,services:i.length,workspaces:r.registry.keys(),...r.graphStores?{projectGraph:graphVerdict(O)}:{},...(0,on_demand_1.runSummary)(k,g)}}},"register"),$=f(e=>{const t=r.registry.unregister(e);if(t){for(const u of t.services){const s=(0,service_keys_1.serviceKeyId)(u.wsKey??e,u.project),o=r.serviceKeys[s];o&&(delete r.serviceKeys[s],r.keyToProject.delete(o),r.keyToWorkspace?.delete(o))}for(const u of t.services)d.killService(u,"workspace unregistered");return r.graphStores?.delete(t.root),(0,guest_replay_1.forgetGuest)(e),d.onUnregister?.(t),t}},"unregisterWorkspace"),D=f((e,t,u={})=>{try{fs.rmSync(path.join(e.root,".lensmcp","registered.json"),{force:!0})}catch{}const s=e.instance?.name??e.wsKey,o=(0,on_demand_1.worktreeRunIdleSec)(g);console.log(`[gateway] ${new Date().toISOString()} parked on-demand worktree '${s}' (${e.wsKey}): ${t==="idle"?`no request and no hold for ${o}s (${on_demand_1.WORKTREE_RUN_IDLE_ENV})`:"asked"} \u2014 its services, frontends, capture, dashboard and build host are stopped; its data is kept.`),d.emitWorkspace?.(e,"info",`worktree parked: ${s} (${t==="idle"?`unused for ${o}s`:"asked"})`,"cluster-worktree:parked",{kind:"worktree-parked",wsKey:e.wsKey,name:s,why:t,...t==="idle"?{idleSec:o}:{},...u})},"announceParked"),G=f(e=>t=>(t&&(0,on_demand_1.touchStart)(r.registry,e),t),"touchedStart"),E=f((e,t)=>{const u=r.registry.get(e);if(!u)return{error:`no workspace '${e}' is registered`,workspaces:r.registry.keys()};const s=u.services.find(o=>o.project===t);return s?{svc:s}:{error:`'${e}' has no service '${t}'`,services:u.services.map(o=>o.project)}},"findService"),b=f(e=>{let t=(e.stoppingUntil??0)>Date.now();if(e.stoppingPid)try{process.kill(e.stoppingPid,0),t=!0}catch{e.stoppingPid=void 0}return{service:e.project,state:e.state,stopped:e.manualStopped===!0&&!t,ready:!e.manualStopped&&e.state==="up"&&e.pool.socks.length>0,busy:t||e.actionStarting===!0||!!e.rolling||!!(e.restart&&!e.restart.done),failure:e.actionFailure??(!e.manualStopped&&e.restart?.done?.ok===!1?e.restart.done.error:void 0)}},"serviceView"),U=f((e,t)=>(e.manualStopped=!1,e.actionFailure=void 0,e.restart=void 0,e.actionStarting=!0,t(e).then(u=>(!u&&!e.manualStopped&&(e.actionFailure="Service did not become ready"),u),u=>(e.actionFailure=String(u).slice(0,500),!1)).finally(()=>{e.actionStarting=!1})),"startService"),R=f((e,t)=>({project:e.project,wsKey:e.wsKey,host:e.decl.host,state:e.state,...e.generation!==void 0?{generation:e.generation}:{},...e.restart?{restart:e.restart}:{},...(0,awake_1.idleFields)(e,(0,warm_start_1.serviceIdleSec)(r,e,g),t),...e.lastStartError?{error:e.lastStartError}:{}}),"statusRow");let q=Promise.resolve();const L=d.startTurn??(e=>{const t=q.then(e);return q=t.catch(()=>{}),t}),T=f(e=>({wsKey:e.wsKey,service:e.project,state:e.state,...e.generation!==void 0?{generation:e.generation}:{},...e.restart?{restart:e.restart}:{}}),"restartView"),x=f((e,t,u,s,o)=>{const n=o+Math.round(u*1e3),a=[],l=f((i,w)=>({at:o,outcome:i,...w?{reason:w}:{}}),"asked");for(const i of t)i.awakeUntil=Math.max(i.awakeUntil??0,n),i.state==="up"?i.wake=l("up"):b(i).busy?i.wake=l("skipped","a stop, start or restart of it is under way \u2014 `lensmcp instance status` shows how it ends"):i.manualStopped&&!s?i.wake=l("skipped","stopped by hand \u2014 name it to start it"):d.ensureService?(i.manualStopped=!1,i.wake=l("queued"),a.push({svc:i,wake:i.wake})):i.wake=l("failed","this gateway cannot start services"),d.emitService?.(i,"info",`awake until ${new Date(i.awakeUntil).toISOString()}: ${i.project}`,{kind:"service-awake",project:i.project,until:i.awakeUntil,forSec:u,wake:i.wake.outcome});const y=d.ensureService;return a.length>0&&y&&L(()=>(0,awake_1.wakeServices)(a,{start:f(i=>U(i,y).then(G(i)),"start"),available:d.available??(()=>(0,warm_start_1.availableMemory)()),minFreeBytes:d.minFreeBytes??(0,warm_start_1.warmMinFreeBytes)(),current:f(i=>!r.stopped?.()&&!!r.registry.get(i.wsKey)?.services.includes(i),"current"),busy:f(i=>b(i).busy,"busy"),emit:f((i,w,v,k)=>d.emitService?.(i,w,v,k),"emit"),log:f(i=>console.log(i),"log")})).catch(i=>console.error(`[gateway] wake of ${e.wsKey} failed:`,i)),n},"holdAndWake"),A=f(e=>{(0,on_demand_1.isOnDemand)(e)&&r.registry.get(e.wsKey)===e&&(0,guest_replay_1.updateGuest)(e.wsKey,{runUntil:(0,on_demand_1.holdEnd)(e)})},"heldRun"),N=http.createServer((e,t)=>{(async()=>{try{const u=(e.url??"").split("?")[0];if(e.method==="GET"&&u==="/list")return c(t,200,{workspaces:r.registry.keys().map(s=>{const o=r.registry.get(s);return{key:s,root:o?.root,routes:o?.routes.length??0,services:o?.services.length??0,...instanceSummary(o),...(0,on_demand_1.runSummary)(o,g)}})});if(e.method==="GET"&&u==="/status"){const s=(0,exports.clusterVersion)();return c(t,200,{daemon:{pid:process.pid,wsKey:r.wsKey,...s?{version:s}:{}},workspaces:r.registry.keys().map(o=>{const n=r.registry.get(o);return{key:o,root:n?.root,routes:n?.routes.length??0,services:n?.services.length??0,isDaemon:o===r.wsKey,...instanceSummary(n),...(0,on_demand_1.runSummary)(n,g)}}),services:r.registry.allServices().map(o=>R(o,Date.now()))})}if(e.method==="GET"&&u==="/instance-env"){const s=new URL(e.url??"/","http://control").searchParams.get("wsKey")??"",o=r.registry.get(s);return o?o.instance?c(t,200,{wsKey:s,root:o.root,...instanceSummary(o),env:o.instance.env}):c(t,404,{error:`'${s}' is not an instance`}):c(t,404,{error:`no workspace '${s}' is registered`})}if(e.method==="POST"&&u==="/instance-env"){const{value:s,bytes:o}=await readJsonBody(e,CONTROL_BODY_BYTES+guest_graph_1.MAX_FORWARDED_GRAPH_BYTES),n=await j(s,o,!0);return c(t,n.status,n.json)}if(u==="/service"&&(e.method==="GET"||e.method==="POST")){const s=e.method==="GET"?Object.fromEntries(new URL(e.url??"/","http://control").searchParams):(await readJsonBody(e)).value??{};if(typeof s.wsKey!="string"||typeof s.service!="string")return c(t,400,{error:"wsKey and service are required"});const o=E(s.wsKey,s.service);if("error"in o)return c(t,404,o);const n=o.svc,a=f(()=>b(n),"view");if(e.method==="GET")return c(t,200,a());const l=s.action;if(!["start","stop","restart"].includes(String(l)))return c(t,400,{error:"action must be start, stop or restart"});if(a().busy&&!(l==="stop"&&n.actionStarting&&!n.rolling))return c(t,409,{error:"A service lifecycle operation is already in progress"});if(l==="stop")return!n.proc&&n.pool.socks.length&&!n.manualStopped?c(t,409,{error:"This gateway does not own the adopted service process; stop it with its owner"}):(n.manualStopped=!0,n.stoppingPid=n.proc?.pid,n.stoppingUntil=Date.now()+(n.proc?1600:0),d.killService(n,"workspace action stop"),n.state="down",c(t,202,a()));if(l==="restart"){if(!d.restartService)return c(t,501,{error:"This gateway cannot restart services"});(0,on_demand_1.touchStart)(r.registry,n);const i=d.restartService(n,{hard:s.hard===!0,reason:"workspace action restart"});return"refused"in i?c(t,409,{error:i.refused}):c(t,202,{...a(),restart:i.restart})}if(!d.ensureService)return c(t,501,{error:"This gateway cannot start services"});const y=n.state!=="up"&&!n.proc;return(0,on_demand_1.touchStart)(r.registry,n),U(n,d.ensureService).then(G(n)),c(t,202,{...a(),started:y})}if(e.method==="POST"&&u==="/awake"){const s=(await readJsonBody(e)).value??{},o=typeof s.wsKey=="string"?s.wsKey:"";if(!o)return c(t,400,{error:"wsKey is required"});const n=typeof s.forSec=="number"?s.forSec:NaN;if(!Number.isFinite(n)||n<0)return c(t,400,{error:"forSec is required: the seconds to hold them awake, 0 to release the hold"});if(n>awake_1.MAX_AWAKE_SEC)return c(t,400,{error:`forSec ${n} is over the ${awake_1.MAX_AWAKE_SEC} s (4 h) a hold may last \u2014 ask again before it ends to keep them longer`,maxSec:awake_1.MAX_AWAKE_SEC});const a=s.services;if(a!==void 0&&(!Array.isArray(a)||a.length===0||!a.every(p=>typeof p=="string"&&p.length>0)))return c(t,400,{error:"services, when given, names one service or more"});const l=r.registry.get(o);if(!l)return c(t,404,{error:`no workspace '${o}' is registered`,workspaces:r.registry.keys()});const y=[];for(const p of a??[]){const _=E(o,p);if("error"in _)return c(t,404,_);y.includes(_.svc)||y.push(_.svc)}const i=y.length>0,w=!i&&s.warmOnly===!0;i||y.push(...w?l.services.filter(p=>p.decl.eager):l.services);const v=Date.now();if(n===0){for(const p of y)(p.awakeUntil??0)<=v||(p.awakeUntil=v,d.emitService?.(p,"info",`awake hold released: ${p.project}`,{kind:"service-awake",project:p.project,until:null,released:!0}));return A(l),c(t,202,{ok:!0,wsKey:o,forSec:0,released:!0,...w?{warmOnly:!0}:{},services:y.map(p=>R(p,v)),...(0,on_demand_1.runSummary)(l,g)})}const k=x(l,y,n,i,v);return(0,on_demand_1.isOnDemand)(l)&&(l.lastUseAt=v),A(l),c(t,202,{ok:!0,wsKey:o,forSec:n,until:k,...w?{warmOnly:!0}:{},services:y.map(p=>R(p,v)),...(0,on_demand_1.runSummary)(l,g)})}if(u==="/restart"&&(e.method==="POST"||e.method==="GET")){const s=e.method==="GET"?Object.fromEntries(new URL(e.url??"/","http://control").searchParams):(await readJsonBody(e)).value??{},o=typeof s.wsKey=="string"?s.wsKey:"",n=typeof s.service=="string"?s.service:"";if(!o||!n)return c(t,400,{error:"wsKey and service are required"});const a=E(o,n);if("error"in a)return c(t,404,a);const l=a.svc;if(e.method==="GET")return c(t,200,T(l));if(!d.restartService)return c(t,501,{error:"this gateway cannot restart a service"});(0,on_demand_1.touchStart)(r.registry,l);const y=typeof s.reason=="string"&&s.reason.trim()?s.reason.trim().slice(0,200):"asked for",i=d.restartService(l,{hard:s.hard===!0,reason:y});return"refused"in i?c(t,409,{error:i.refused,...T(l)}):c(t,202,{ok:!0,already:i.already,...T(l)})}if(e.method==="GET"&&u==="/identities"||e.method==="POST"&&u==="/act"){const s=e.method==="GET"?Object.fromEntries(new URL(e.url??"/","http://control").searchParams):(await readJsonBody(e)).value??{},o=typeof s.wsKey=="string"?s.wsKey:"";if(!o)return c(t,400,{error:"wsKey is required"});if(!r.registry.get(o)&&o!==r.wsKey)return c(t,404,{error:`no workspace '${o}' is registered`,workspaces:r.registry.keys()});if(!d.act)return c(t,501,{error:"acting as a signed-in user is turned off on this gateway (LENSMCP_GW_ACT=0)"});if(e.method==="GET")return c(t,200,{wsKey:o,identities:d.act.list(o)});const n=f(i=>typeof s[i]=="string"&&s[i].trim()?s[i].trim().slice(0,256):void 0,"pick"),a=n("user"),l=n("tenant"),y=d.act.mint(o,{...a?{user:a}:{},...l?{tenant:l}:{}});return"error"in y?c(t,404,{wsKey:o,...y}):c(t,200,{wsKey:o,...y})}if(e.method==="POST"&&u==="/register"){const{value:s,bytes:o}=await readJsonBody(e,CONTROL_BODY_BYTES+guest_graph_1.MAX_FORWARDED_GRAPH_BYTES),n=await j(s,o);return c(t,n.status,n.json)}if(e.method==="POST"&&u==="/unregister"){const s=(await readJsonBody(e)).value;if(!s.wsKey)return c(t,400,{error:"wsKey is required"});const o=(0,registration_guards_1.refuseUnregistration)(r.registry,{wsKey:s.wsKey,...s.root?{root:s.root}:{}},r.wsKey);if(o)return console.warn(`[gateway] refused to unregister '${s.wsKey}'${s.root?` for ${s.root}`:""}: ${o.error}`),c(t,409,o);const n=$(s.wsKey);return n&&(0,on_demand_1.isOnDemand)(n)&&D(n,"asked"),r.rebuildRoutes(),c(t,200,{ok:!0,removed:!!n,workspaces:r.registry.keys(),...n&&(0,on_demand_1.isOnDemand)(n)?{parked:!0}:{}})}c(t,404,{error:"not found"})}catch(u){if(u instanceof BodyTooLarge)return e.resume(),c(t,413,{error:u.message});c(t,500,{error:u.message})}})()});return N.listen(h,()=>{try{fs.chmodSync(h,384)}catch(e){console.warn(`[gateway] could not restrict ${h} to 0600:`,e.message)}}),{socketPath:h,async replay(){const e=Date.now(),{replay:t,gone:u,parked:s}=(0,guest_replay_1.guestsToReplay)(r.root,(0,guest_replay_1.readGuests)(),e),o={replayed:[],refused:[],gone:u.map(a=>a.wsKey),parked:s.map(a=>a.wsKey)};for(const a of u)(0,guest_replay_1.forgetGuest)(a.wsKey),console.log(`[gateway] not re-hosting '${a.wsKey}': ${a.root} is no longer a workspace \u2014 forgotten`);const n=f((a,l)=>{(0,guest_replay_1.forgetGuest)(a.wsKey);try{fs.rmSync(path.join(a.root,".lensmcp","registered.json"),{force:!0})}catch{}console.log(`[gateway] not re-hosting on-demand worktree '${a.wsKey}': ${l} \u2014 it stays parked (\`lensmcp instance run\` runs it)`)},"leaveParked");for(const a of s)n(a,a.runUntil?`its run ended at ${new Date(a.runUntil).toISOString()}`:"no run held it");for(const a of t)if(!r.registry.has(a.wsKey))try{const l=await j({wsKey:a.wsKey,root:a.root,projects:a.projects,...a.projectDependencies?{projectDependencies:a.projectDependencies}:{}},0);if(l.status===200){o.replayed.push(a.wsKey),console.log(`[gateway] re-hosted '${a.wsKey}' (${a.root}) \u2014 registered before this daemon restarted`);const y=r.registry.get(a.wsKey),i=(a.runUntil??0)-Date.now();a.onDemand&&y&&(0,on_demand_1.isOnDemand)(y)&&i>0&&(x(y,y.services.filter(w=>w.decl.eager),i/1e3,!1,Date.now()),A(y))}else a.onDemand&&l.json.code==="run-cap"?(o.parked.push(a.wsKey),n(a,`${l.json.max??"?"} on-demand worktrees already run (LENSMCP_WORKTREE_RUN_MAX)`)):(o.refused.push(a.wsKey),console.warn(`[gateway] could not re-host '${a.wsKey}' (${a.root}): ${JSON.stringify(l.json)} \u2014 \`lensmcp gateway start\` there`))}catch(l){o.refused.push(a.wsKey),console.warn(`[gateway] could not re-host '${a.wsKey}' (${a.root}): ${l.message}`)}return o},parkIdle(e=Date.now()){if(r.stopped?.())return[];const t=[];for(const u of r.registry.keys()){if(u===r.wsKey)continue;const s=r.registry.get(u);if(!s||!(0,on_demand_1.isOnDemand)(s))continue;const o=(0,on_demand_1.parkVerdict)(s,e,g);if(!o.ok)continue;const n=s.lastUseAt;$(u)&&(t.push(u),D(s,"idle",{parkAt:o.parkAt,...n!==void 0?{lastUseAt:n}:{}}))}return t.length>0&&r.rebuildRoutes(),t},close:f(()=>{N.close();try{fs.unlinkSync(h)}catch{}},"close")}}m(startControlServer,"startControlServer"),f(startControlServer,"startControlServer");
2
+ `)}catch{}let O;if(r.graphStores){const K={root:e.root,daemonRoot:r.root,otherRoots:r.registry.keys().filter(P=>P!==e.wsKey).flatMap(P=>r.registry.get(P)?.root??[])};O=e.projectGraph===void 0?void 0:(0,guest_graph_1.admitForwardedGraph)(e.projectGraph,{...K,bytes:graphShare(e,t)}),O?.refused!==void 0&&console.warn(`[gateway] refused the project graph '${e.wsKey}' forwarded from ${e.root}: ${O.refused} \u2014 its services start through \`nx run\` until the gateway computes it`),(0,registration_guards_1.sameRoot)(e.root,r.root)||r.graphStores.set((0,guest_graph_1.createGuestGraphStore)({wsKey:e.wsKey,root:e.root,...O?{admission:O}:{},context:K}))}return r.registry.register(k),await d.onRegister?.(k),r.rebuildRoutes(),r.root&&!(0,registration_guards_1.sameRoot)(e.root,r.root)&&(0,guest_replay_1.recordGuest)({wsKey:e.wsKey,root:e.root,projects:s,...e.projectDependencies?{projectDependencies:e.projectDependencies}:{},daemonRoot:r.root,registeredAt:new Date().toISOString(),...w?.onDemand?{onDemand:!0}:{}}),w?.onDemand&&console.log(`[gateway] registered on-demand worktree '${w.name}' (${e.wsKey}) \u2014 nothing starts until its run asks (POST /awake); parked after ${(0,on_demand_1.worktreeRunIdleSec)(g)}s unused (${on_demand_1.WORKTREE_RUN_IDLE_ENV})`),{status:200,json:{ok:!0,wsKey:e.wsKey,routes:y.length,services:i.length,workspaces:r.registry.keys(),...r.graphStores?{projectGraph:graphVerdict(O)}:{},...(0,on_demand_1.runSummary)(k,g)}}},"register"),$=f(e=>{const t=r.registry.unregister(e);if(t){for(const u of t.services){const s=(0,service_keys_1.serviceKeyId)(u.wsKey??e,u.project),o=r.serviceKeys[s];o&&(delete r.serviceKeys[s],r.keyToProject.delete(o),r.keyToWorkspace?.delete(o))}for(const u of t.services)d.killService(u,"workspace unregistered");return r.graphStores?.delete(t.root),(0,guest_replay_1.forgetGuest)(e),d.onUnregister?.(t),t}},"unregisterWorkspace"),D=f((e,t,u={})=>{try{fs.rmSync(path.join(e.root,".lensmcp","registered.json"),{force:!0})}catch{}const s=e.instance?.name??e.wsKey,o=(0,on_demand_1.worktreeRunIdleSec)(g);console.log(`[gateway] ${new Date().toISOString()} parked on-demand worktree '${s}' (${e.wsKey}): ${t==="idle"?`no request and no hold for ${o}s (${on_demand_1.WORKTREE_RUN_IDLE_ENV})`:"asked"} \u2014 its services, frontends, capture, dashboard and build host are stopped; its data is kept.`),d.emitWorkspace?.(e,"info",`worktree parked: ${s} (${t==="idle"?`unused for ${o}s`:"asked"})`,"cluster-worktree:parked",{kind:"worktree-parked",wsKey:e.wsKey,name:s,why:t,...t==="idle"?{idleSec:o}:{},...u})},"announceParked"),G=f(e=>t=>(t&&(0,on_demand_1.touchStart)(r.registry,e),t),"touchedStart"),b=f((e,t)=>{const u=r.registry.get(e);if(!u)return{error:`no workspace '${e}' is registered`,workspaces:r.registry.keys()};const s=u.services.find(o=>o.project===t);return s?{svc:s}:{error:`'${e}' has no service '${t}'`,services:u.services.map(o=>o.project)}},"findService"),E=f(e=>{let t=(e.stoppingUntil??0)>Date.now();if(e.stoppingPid)try{process.kill(e.stoppingPid,0),t=!0}catch{e.stoppingPid=void 0}return{service:e.project,state:e.state,stopped:e.manualStopped===!0&&!t,ready:!e.manualStopped&&e.state==="up"&&e.pool.socks.length>0,busy:t||e.actionStarting===!0||!!e.rolling||!!(e.restart&&!e.restart.done),failure:e.actionFailure??(!e.manualStopped&&e.restart?.done?.ok===!1?e.restart.done.error:void 0)}},"serviceView"),U=f((e,t)=>(e.manualStopped=!1,e.actionFailure=void 0,e.restart=void 0,e.actionStarting=!0,t(e).then(u=>(!u&&!e.manualStopped&&(e.actionFailure="Service did not become ready"),u),u=>(e.actionFailure=String(u).slice(0,500),!1)).finally(()=>{e.actionStarting=!1})),"startService"),R=f((e,t)=>({project:e.project,wsKey:e.wsKey,host:e.decl.host,state:e.state,...e.generation!==void 0?{generation:e.generation}:{},...e.restart?{restart:e.restart}:{},...(0,awake_1.idleFields)(e,(0,warm_start_1.serviceIdleSec)(r,e,g),t),...e.lastStartError?{error:e.lastStartError}:{}}),"statusRow");let q=Promise.resolve();const L=d.startTurn??(e=>{const t=q.then(e);return q=t.catch(()=>{}),t}),T=f(e=>({wsKey:e.wsKey,service:e.project,state:e.state,...e.generation!==void 0?{generation:e.generation}:{},...e.restart?{restart:e.restart}:{}}),"restartView"),x=f((e,t,u,s,o)=>{const n=o+Math.round(u*1e3),a=[],l=f((i,w)=>({at:o,outcome:i,...w?{reason:w}:{}}),"asked");for(const i of t)i.awakeUntil=Math.max(i.awakeUntil??0,n),i.state==="up"?i.wake=l("up"):E(i).busy?i.wake=l("skipped","a stop, start or restart of it is under way \u2014 `lensmcp instance status` shows how it ends"):i.manualStopped&&!s?i.wake=l("skipped","stopped by hand \u2014 name it to start it"):d.ensureService?(i.manualStopped=!1,i.wake=l("queued"),a.push({svc:i,wake:i.wake})):i.wake=l("failed","this gateway cannot start services"),d.emitService?.(i,"info",`awake until ${new Date(i.awakeUntil).toISOString()}: ${i.project}`,{kind:"service-awake",project:i.project,until:i.awakeUntil,forSec:u,wake:i.wake.outcome});const y=d.ensureService;return a.length>0&&y&&L(()=>(0,awake_1.wakeServices)(a,{start:f(i=>U(i,y).then(G(i)),"start"),available:d.available??(()=>(0,warm_start_1.availableMemory)()),minFreeBytes:d.minFreeBytes??(0,warm_start_1.warmMinFreeBytes)(),current:f(i=>!r.stopped?.()&&!!r.registry.get(i.wsKey)?.services.includes(i),"current"),busy:f(i=>E(i).busy,"busy"),emit:f((i,w,v,k)=>d.emitService?.(i,w,v,k),"emit"),log:f(i=>console.log(i),"log")})).catch(i=>console.error(`[gateway] wake of ${e.wsKey} failed:`,i)),n},"holdAndWake"),A=f(e=>{(0,on_demand_1.isOnDemand)(e)&&r.registry.get(e.wsKey)===e&&(0,guest_replay_1.updateGuest)(e.wsKey,{runUntil:(0,on_demand_1.holdEnd)(e)})},"heldRun"),N=http.createServer((e,t)=>{(async()=>{try{const u=(e.url??"").split("?")[0];if(e.method==="GET"&&u==="/list")return c(t,200,{workspaces:r.registry.keys().map(s=>{const o=r.registry.get(s);return{key:s,root:o?.root,routes:o?.routes.length??0,services:o?.services.length??0,...instanceSummary(o),...(0,on_demand_1.runSummary)(o,g)}})});if(e.method==="GET"&&u==="/status"){const s=(0,exports.clusterVersion)();return c(t,200,{daemon:{pid:process.pid,wsKey:r.wsKey,...s?{version:s}:{}},capabilities:{candidateRuntimeProof:1},workspaces:r.registry.keys().map(o=>{const n=r.registry.get(o);return{key:o,root:n?.root,routes:n?.routes.length??0,services:n?.services.length??0,isDaemon:o===r.wsKey,...instanceSummary(n),...(0,on_demand_1.runSummary)(n,g)}}),services:r.registry.allServices().map(o=>R(o,Date.now()))})}if(e.method==="GET"&&u==="/instance-env"){const s=new URL(e.url??"/","http://control").searchParams.get("wsKey")??"",o=r.registry.get(s);return o?o.instance?c(t,200,{wsKey:s,root:o.root,...instanceSummary(o),env:o.instance.env}):c(t,404,{error:`'${s}' is not an instance`}):c(t,404,{error:`no workspace '${s}' is registered`})}if(e.method==="POST"&&u==="/instance-env"){const{value:s,bytes:o}=await readJsonBody(e,CONTROL_BODY_BYTES+guest_graph_1.MAX_FORWARDED_GRAPH_BYTES),n=await j(s,o,!0);return c(t,n.status,n.json)}if(u==="/service"&&(e.method==="GET"||e.method==="POST")){const s=e.method==="GET"?Object.fromEntries(new URL(e.url??"/","http://control").searchParams):(await readJsonBody(e)).value??{};if(typeof s.wsKey!="string"||typeof s.service!="string")return c(t,400,{error:"wsKey and service are required"});const o=b(s.wsKey,s.service);if("error"in o)return c(t,404,o);const n=o.svc,a=f(()=>E(n),"view");if(e.method==="GET")return c(t,200,a());const l=s.action;if(!["start","stop","restart"].includes(String(l)))return c(t,400,{error:"action must be start, stop or restart"});if(a().busy&&!(l==="stop"&&n.actionStarting&&!n.rolling))return c(t,409,{error:"A service lifecycle operation is already in progress"});if(l==="stop")return!n.proc&&n.pool.socks.length&&!n.manualStopped?c(t,409,{error:"This gateway does not own the adopted service process; stop it with its owner"}):(n.manualStopped=!0,n.stoppingPid=n.proc?.pid,n.stoppingUntil=Date.now()+(n.proc?1600:0),d.killService(n,"workspace action stop"),n.state="down",c(t,202,a()));if(l==="restart"){if(!d.restartService)return c(t,501,{error:"This gateway cannot restart services"});(0,on_demand_1.touchStart)(r.registry,n);const i=d.restartService(n,{hard:s.hard===!0,reason:"workspace action restart"});return"refused"in i?c(t,409,{error:i.refused}):c(t,202,{...a(),restart:i.restart})}if(!d.ensureService)return c(t,501,{error:"This gateway cannot start services"});const y=n.state!=="up"&&!n.proc;return(0,on_demand_1.touchStart)(r.registry,n),U(n,d.ensureService).then(G(n)),c(t,202,{...a(),started:y})}if(e.method==="POST"&&u==="/awake"){const s=(await readJsonBody(e)).value??{},o=typeof s.wsKey=="string"?s.wsKey:"";if(!o)return c(t,400,{error:"wsKey is required"});const n=typeof s.forSec=="number"?s.forSec:NaN;if(!Number.isFinite(n)||n<0)return c(t,400,{error:"forSec is required: the seconds to hold them awake, 0 to release the hold"});if(n>awake_1.MAX_AWAKE_SEC)return c(t,400,{error:`forSec ${n} is over the ${awake_1.MAX_AWAKE_SEC} s (4 h) a hold may last \u2014 ask again before it ends to keep them longer`,maxSec:awake_1.MAX_AWAKE_SEC});const a=s.services;if(a!==void 0&&(!Array.isArray(a)||a.length===0||!a.every(p=>typeof p=="string"&&p.length>0)))return c(t,400,{error:"services, when given, names one service or more"});const l=r.registry.get(o);if(!l)return c(t,404,{error:`no workspace '${o}' is registered`,workspaces:r.registry.keys()});const y=[];for(const p of a??[]){const _=b(o,p);if("error"in _)return c(t,404,_);y.includes(_.svc)||y.push(_.svc)}const i=y.length>0,w=!i&&s.warmOnly===!0;i||y.push(...w?l.services.filter(p=>p.decl.eager):l.services);const v=Date.now();if(n===0){for(const p of y)(p.awakeUntil??0)<=v||(p.awakeUntil=v,d.emitService?.(p,"info",`awake hold released: ${p.project}`,{kind:"service-awake",project:p.project,until:null,released:!0}));return A(l),c(t,202,{ok:!0,wsKey:o,forSec:0,released:!0,...w?{warmOnly:!0}:{},services:y.map(p=>R(p,v)),...(0,on_demand_1.runSummary)(l,g)})}const k=x(l,y,n,i,v);return(0,on_demand_1.isOnDemand)(l)&&(l.lastUseAt=v),A(l),c(t,202,{ok:!0,wsKey:o,forSec:n,until:k,...w?{warmOnly:!0}:{},services:y.map(p=>R(p,v)),...(0,on_demand_1.runSummary)(l,g)})}if(u==="/restart"&&(e.method==="POST"||e.method==="GET")){const s=e.method==="GET"?Object.fromEntries(new URL(e.url??"/","http://control").searchParams):(await readJsonBody(e)).value??{},o=typeof s.wsKey=="string"?s.wsKey:"",n=typeof s.service=="string"?s.service:"";if(!o||!n)return c(t,400,{error:"wsKey and service are required"});const a=b(o,n);if("error"in a)return c(t,404,a);const l=a.svc;if(e.method==="GET")return c(t,200,T(l));if(!d.restartService)return c(t,501,{error:"this gateway cannot restart a service"});(0,on_demand_1.touchStart)(r.registry,l);const y=typeof s.reason=="string"&&s.reason.trim()?s.reason.trim().slice(0,200):"asked for",i=d.restartService(l,{hard:s.hard===!0,reason:y});return"refused"in i?c(t,409,{error:i.refused,...T(l)}):c(t,202,{ok:!0,already:i.already,...T(l)})}if(e.method==="GET"&&u==="/identities"||e.method==="POST"&&u==="/act"){const s=e.method==="GET"?Object.fromEntries(new URL(e.url??"/","http://control").searchParams):(await readJsonBody(e)).value??{},o=typeof s.wsKey=="string"?s.wsKey:"";if(!o)return c(t,400,{error:"wsKey is required"});if(!r.registry.get(o)&&o!==r.wsKey)return c(t,404,{error:`no workspace '${o}' is registered`,workspaces:r.registry.keys()});if(!d.act)return c(t,501,{error:"acting as a signed-in user is turned off on this gateway (LENSMCP_GW_ACT=0)"});if(e.method==="GET")return c(t,200,{wsKey:o,identities:d.act.list(o)});const n=f(i=>typeof s[i]=="string"&&s[i].trim()?s[i].trim().slice(0,256):void 0,"pick"),a=n("user"),l=n("tenant"),y=d.act.mint(o,{...a?{user:a}:{},...l?{tenant:l}:{}});return"error"in y?c(t,404,{wsKey:o,...y}):c(t,200,{wsKey:o,...y})}if(e.method==="POST"&&u==="/register"){const{value:s,bytes:o}=await readJsonBody(e,CONTROL_BODY_BYTES+guest_graph_1.MAX_FORWARDED_GRAPH_BYTES),n=await j(s,o);return c(t,n.status,n.json)}if(e.method==="POST"&&u==="/unregister"){const s=(await readJsonBody(e)).value;if(!s.wsKey)return c(t,400,{error:"wsKey is required"});const o=(0,registration_guards_1.refuseUnregistration)(r.registry,{wsKey:s.wsKey,...s.root?{root:s.root}:{}},r.wsKey);if(o)return console.warn(`[gateway] refused to unregister '${s.wsKey}'${s.root?` for ${s.root}`:""}: ${o.error}`),c(t,409,o);const n=$(s.wsKey);return n&&(0,on_demand_1.isOnDemand)(n)&&D(n,"asked"),r.rebuildRoutes(),c(t,200,{ok:!0,removed:!!n,workspaces:r.registry.keys(),...n&&(0,on_demand_1.isOnDemand)(n)?{parked:!0}:{}})}c(t,404,{error:"not found"})}catch(u){if(u instanceof BodyTooLarge)return e.resume(),c(t,413,{error:u.message});c(t,500,{error:u.message})}})()});return N.listen(h,()=>{try{fs.chmodSync(h,384)}catch(e){console.warn(`[gateway] could not restrict ${h} to 0600:`,e.message)}}),{socketPath:h,async replay(){const e=Date.now(),{replay:t,gone:u,parked:s}=(0,guest_replay_1.guestsToReplay)(r.root,(0,guest_replay_1.readGuests)(),e),o={replayed:[],refused:[],gone:u.map(a=>a.wsKey),parked:s.map(a=>a.wsKey)};for(const a of u)(0,guest_replay_1.forgetGuest)(a.wsKey),console.log(`[gateway] not re-hosting '${a.wsKey}': ${a.root} is no longer a workspace \u2014 forgotten`);const n=f((a,l)=>{(0,guest_replay_1.forgetGuest)(a.wsKey);try{fs.rmSync(path.join(a.root,".lensmcp","registered.json"),{force:!0})}catch{}console.log(`[gateway] not re-hosting on-demand worktree '${a.wsKey}': ${l} \u2014 it stays parked (\`lensmcp instance run\` runs it)`)},"leaveParked");for(const a of s)n(a,a.runUntil?`its run ended at ${new Date(a.runUntil).toISOString()}`:"no run held it");for(const a of t)if(!r.registry.has(a.wsKey))try{const l=await j({wsKey:a.wsKey,root:a.root,projects:a.projects,...a.projectDependencies?{projectDependencies:a.projectDependencies}:{}},0);if(l.status===200){o.replayed.push(a.wsKey),console.log(`[gateway] re-hosted '${a.wsKey}' (${a.root}) \u2014 registered before this daemon restarted`);const y=r.registry.get(a.wsKey),i=(a.runUntil??0)-Date.now();a.onDemand&&y&&(0,on_demand_1.isOnDemand)(y)&&i>0&&(x(y,y.services.filter(w=>w.decl.eager),i/1e3,!1,Date.now()),A(y))}else a.onDemand&&l.json.code==="run-cap"?(o.parked.push(a.wsKey),n(a,`${l.json.max??"?"} on-demand worktrees already run (LENSMCP_WORKTREE_RUN_MAX)`)):(o.refused.push(a.wsKey),console.warn(`[gateway] could not re-host '${a.wsKey}' (${a.root}): ${JSON.stringify(l.json)} \u2014 \`lensmcp gateway start\` there`))}catch(l){o.refused.push(a.wsKey),console.warn(`[gateway] could not re-host '${a.wsKey}' (${a.root}): ${l.message}`)}return o},parkIdle(e=Date.now()){if(r.stopped?.())return[];const t=[];for(const u of r.registry.keys()){if(u===r.wsKey)continue;const s=r.registry.get(u);if(!s||!(0,on_demand_1.isOnDemand)(s))continue;const o=(0,on_demand_1.parkVerdict)(s,e,g);if(!o.ok)continue;const n=s.lastUseAt;$(u)&&(t.push(u),D(s,"idle",{parkAt:o.parkAt,...n!==void 0?{lastUseAt:n}:{}}))}return t.length>0&&r.rebuildRoutes(),t},close:f(()=>{N.close();try{fs.unlinkSync(h)}catch{}},"close")}}m(startControlServer,"startControlServer"),f(startControlServer,"startControlServer");
@@ -93,6 +93,18 @@ export interface ChildGraphOutput {
93
93
  * for the admission to refuse.
94
94
  */
95
95
  export declare function forwardedGraphInChild(root: string, env: NodeJS.ProcessEnv, script?: RunnerScript | undefined): Promise<ChildGraphOutput>;
96
+ /**
97
+ * The gateway's OWN workspace's graph, computed in a fresh child process: `graph-snapshot.js` in the same environment a
98
+ * guest's is computed in ({@link forwardedGraphInChild}, {@link guestGraphEnv} — no nx daemon, plugins in-process). The
99
+ * store falls back to it once a computation in the gateway's own process has failed (project-graph-store.ts
100
+ * `setFallback`): nx's state in a long-lived process can stay broken after one failure, and FoodGuard's did for four
101
+ * hours, until a restart (issues/open/overseer-16). A fresh process starts clean every time.
102
+ *
103
+ * The admission a guest's graph passes refuses this root (the gateway reads its own graph itself), so the checks it
104
+ * still needs are made here: the size, the format, that it describes this root, and its shape. The store fingerprints
105
+ * the declaring files itself, by its own rule.
106
+ */
107
+ export declare function ownGraphInFreshProcess(root: string, env?: NodeJS.ProcessEnv, run?: (root: string, env: NodeJS.ProcessEnv) => Promise<ChildGraphOutput>): Promise<ComputedProjectGraph>;
96
108
  export interface GuestGraphStoreParams {
97
109
  /** The registered workspace's key — for the log lines. */
98
110
  wsKey: string;
@@ -1,2 +1,2 @@
1
- "use strict";var _=Object.defineProperty;var u=(e,r)=>_(e,"name",{value:r,configurable:!0});var l=Object.defineProperty,f=u((e,r)=>l(e,"name",{value:r,configurable:!0}),"f");Object.defineProperty(exports,"__esModule",{value:!0}),exports.GUEST_GRAPH_RETRY_MS=exports.MAX_FORWARDED_PROJECTS=exports.MAX_FORWARDED_GRAPH_BYTES=exports.FORWARDED_GRAPH_FORMAT=void 0,exports.ownedByThisUser=ownedByThisUser,exports.admitForwardedGraph=admitForwardedGraph,exports.compactSourceMaps=compactSourceMaps,exports.projectsOnly=projectsOnly,exports.snapshotWorkspaceGraph=snapshotWorkspaceGraph,exports.graphSnapshotScript=graphSnapshotScript,exports.guestGraphEnv=guestGraphEnv,exports.forwardedGraphInChild=forwardedGraphInChild,exports.createGuestGraphStore=createGuestGraphStore;const tslib_1=require("tslib"),node_child_process_1=require("node:child_process"),fs=tslib_1.__importStar(require("node:fs")),os=tslib_1.__importStar(require("node:os")),path=tslib_1.__importStar(require("node:path")),pod_env_1=require("./pod-env"),project_graph_store_1=require("./project-graph-store"),registration_guards_1=require("./registration-guards");exports.FORWARDED_GRAPH_FORMAT=1,exports.MAX_FORWARDED_GRAPH_BYTES=8*1024*1024,exports.MAX_FORWARDED_PROJECTS=2e4,exports.GUEST_GRAPH_RETRY_MS=6e4;const GUEST_GRAPH_TIMEOUT_MS=12e4,SIGNATURE=/^(?:-|\?|\d+(?:\.\d+)?:\d+:\d+)$/;function megabytes(e){return`${(e/(1024*1024)).toFixed(1)} MB`}u(megabytes,"megabytes"),f(megabytes,"megabytes");const isRecord=f(e=>!!e&&typeof e=="object"&&!Array.isArray(e),"isRecord");function insideWorkspace(e){return e===""||path.isAbsolute(e)||/^[a-zA-Z]:/.test(e)?!1:!path.posix.normalize(e.replace(/\\/g,"/")).split("/").includes("..")}u(insideWorkspace,"insideWorkspace"),f(insideWorkspace,"insideWorkspace");function ownedByThisUser(e){const r=fs.statSync(e,{throwIfNoEntry:!1});if(!r?.isDirectory())return!1;if(typeof process.getuid!="function")return!0;const t=process.getuid();return r.uid===t||t===0&&r.uid===Number(process.env.SUDO_UID)}u(ownedByThisUser,"ownedByThisUser"),f(ownedByThisUser,"ownedByThisUser");function relativeDeclaringFiles(e,r){return(0,project_graph_store_1.declaringFiles)(e,r).map(t=>path.relative(e,t).split(path.sep).join("/"))}u(relativeDeclaringFiles,"relativeDeclaringFiles"),f(relativeDeclaringFiles,"relativeDeclaringFiles");function shapeProblem(e){if(!isRecord(e)||!isRecord(e.nodes)||!isRecord(e.dependencies))return"it has no `nodes` and `dependencies`";const r=e.nodes,t=Object.keys(r);if(t.length>exports.MAX_FORWARDED_PROJECTS)return`it names ${t.length} projects (at most ${exports.MAX_FORWARDED_PROJECTS})`;for(const o of t){const s=r[o];if(!isRecord(s)||s.name!==o||typeof s.type!="string"||!isRecord(s.data))return`project '${o}' is not a project node`;const n=s.data.root;if(typeof n!="string"||!insideWorkspace(n))return`project '${o}' has a root outside the workspace (${String(n)})`;const p=s.data.targets;if(p!==void 0&&(!isRecord(p)||!Object.values(p).every(isRecord)))return`project '${o}' has malformed targets`}for(const[o,s]of Object.entries(e.dependencies)){if(!(o in r)||!Array.isArray(s))return`the dependencies of '${o}' are not a known project's`;for(const n of s)if(!isRecord(n)||n.source!==o||typeof n.target!="string"||!(n.target in r)||typeof n.type!="string")return`a dependency of '${o}' is malformed`}}u(shapeProblem,"shapeProblem"),f(shapeProblem,"shapeProblem");function sourceMapsProblem(e){if(e!==void 0){if(!isRecord(e))return"its source maps are not a map";for(const[r,t]of Object.entries(e)){if(!isRecord(t))return`the source map of ${r} is malformed`;for(const o of Object.values(t))if(!Array.isArray(o)||o.length!==2||o[0]!==null&&typeof o[0]!="string"||typeof o[1]!="string")return`the source map of ${r} is malformed`}}}u(sourceMapsProblem,"sourceMapsProblem"),f(sourceMapsProblem,"sourceMapsProblem");function admitForwardedGraph(e,r){const t=f(a=>({refused:a}),"refuse");if(r.bytes>exports.MAX_FORWARDED_GRAPH_BYTES)return t(`${megabytes(r.bytes)} is over the ${megabytes(exports.MAX_FORWARDED_GRAPH_BYTES)} limit`);if(!isRecord(e))return t("it is not a project graph");if(e.format!==exports.FORWARDED_GRAPH_FORMAT)return t(`its format is ${String(e.format)}, and this gateway reads ${exports.FORWARDED_GRAPH_FORMAT}`);const o=e.root;if(typeof o!="string"||!path.isAbsolute(o))return t("it does not say which workspace it describes");if(!(0,registration_guards_1.sameRoot)(o,r.root))return t(`it describes ${o}, not the registering workspace ${r.root}`);if((0,registration_guards_1.sameRoot)(r.root,r.daemonRoot))return t(`${r.root} is the gateway's own workspace \u2014 the gateway reads that graph itself`);if(r.otherRoots.some(a=>(0,registration_guards_1.sameRoot)(a,r.root)))return t(`${r.root} is registered under another key`);if(!ownedByThisUser(r.root))return t(`${r.root} is not a directory this user owns`);const s=e.startedAt;if(typeof s!="number"||!Number.isFinite(s))return t("it does not say when it was computed");const n=shapeProblem(e.projectGraph)??sourceMapsProblem(e.sourceMaps);if(n)return t(n);const p=e.projectGraph,i=e.files;if(!isRecord(i))return t("it carries no fingerprint of its declaring files");const c=(0,registration_guards_1.canonicalRoot)(r.root),h=relativeDeclaringFiles(c,p),d=Object.keys(i),g=h.filter(a=>!(a in i));return g.length>0||d.length!==h.length?t(`its fingerprint does not cover exactly the files that declare it${g.length>0?` (no ${g[0]})`:""}`):Object.values(i).every(a=>typeof a=="string"&&SIGNATURE.test(a))?{snapshot:{root:c,startedAt:s,files:new Map(h.map(a=>[path.join(c,a),i[a]])),projectGraph:{nodes:p.nodes,dependencies:p.dependencies,externalNodes:{}},...e.sourceMaps!==void 0?{sourceMaps:e.sourceMaps}:{}}}:t("its fingerprint is malformed")}u(admitForwardedGraph,"admitForwardedGraph"),f(admitForwardedGraph,"admitForwardedGraph");function compactSourceMaps(e,r){const t={};for(const o of Object.values(e.nodes)){const s=r[o.data.root];if(!s)continue;const n=new Set;for(const i of Object.keys(o.data.targets??{})){const c=`targets.${i}`,h=new Set;for(const[d,g]of Object.entries(s)){if(d!==c&&!d.startsWith(`${c}.`))continue;const a=JSON.stringify(g);h.has(a)||(h.add(a),n.add(d))}}const p={};for(const[i,c]of Object.entries(s))n.has(i)&&(p[i]=c);t[o.data.root]=p}return t}u(compactSourceMaps,"compactSourceMaps"),f(compactSourceMaps,"compactSourceMaps");function projectsOnly(e){const r={};for(const[t,o]of Object.entries(e.dependencies))t in e.nodes&&(r[t]=o.filter(s=>s.target in e.nodes));return{nodes:e.nodes,dependencies:r}}u(projectsOnly,"projectsOnly"),f(projectsOnly,"projectsOnly");async function snapshotWorkspaceGraph(e,r=()=>(0,project_graph_store_1.computeProjectGraphInProcess)(e)){const t=Date.now(),o=(0,project_graph_store_1.filesystemNow)(),s=await r(),n=projectsOnly(s.projectGraph),p={};for(const i of(0,project_graph_store_1.declaringFiles)(e,s.projectGraph)){const c=fs.statSync(i,{throwIfNoEntry:!1});p[path.relative(e,i).split(path.sep).join("/")]=c&&c.mtimeMs>o?"?":(0,project_graph_store_1.statSignature)(i)}return{format:exports.FORWARDED_GRAPH_FORMAT,root:e,startedAt:t,projectGraph:n,...s.sourceMaps?{sourceMaps:compactSourceMaps(n,s.sourceMaps)}:{},files:p}}u(snapshotWorkspaceGraph,"snapshotWorkspaceGraph"),f(snapshotWorkspaceGraph,"snapshotWorkspaceGraph");function graphSnapshotScript(e=path.join(__dirname,"../../..")){const r=path.join(e,"graph-snapshot.js");if(fs.existsSync(r))return{path:r,execArgv:[]};const t=path.join(e,"graph-snapshot.ts");if(fs.existsSync(t))try{return{path:t,execArgv:["--require",require.resolve("@swc-node/register")]}}catch{return}}u(graphSnapshotScript,"graphSnapshotScript"),f(graphSnapshotScript,"graphSnapshotScript");function guestGraphEnv(e,r,t){const o={...(0,pod_env_1.podBaseEnv)(e,r,t)};for(const s of Object.keys(o))(s.startsWith("NX_TASK_")||["NX_WORKSPACE_ROOT","NX_WORKSPACE_ROOT_PATH","NX_WORKSPACE_DATA_DIRECTORY","NX_PROJECT_GRAPH_CACHE_DIRECTORY"].includes(s))&&delete o[s];return o.NX_DAEMON="false",o.NX_ISOLATE_PLUGINS="false",o}u(guestGraphEnv,"guestGraphEnv"),f(guestGraphEnv,"guestGraphEnv");function forwardedGraphInChild(e,r,t=graphSnapshotScript()){if(!t)return Promise.reject(new Error("graph-snapshot.js is missing from @lensmcp/cluster"));const o=fs.mkdtempSync(path.join(os.tmpdir(),"lensmcp-graph-")),s=path.join(o,"graph.json");return new Promise((n,p)=>{let i="";const c=(0,node_child_process_1.spawn)(process.execPath,[...t.execArgv,t.path,s],{cwd:e,env:r,stdio:["ignore","ignore","pipe"]});c.stderr?.on("data",d=>{i.length<4096&&(i+=d.toString())});const h=setTimeout(()=>c.kill("SIGKILL"),GUEST_GRAPH_TIMEOUT_MS);h.unref(),c.on("error",d=>{clearTimeout(h),p(d)}),c.on("exit",(d,g)=>{if(clearTimeout(h),d!==0){const a=i.trim().split(`
2
- `).pop();p(new Error(`the graph computation in ${e} exited ${g??d}${a?` \u2014 ${a}`:""}`));return}try{const a=fs.statSync(s).size;n({bytes:a,graph:a>exports.MAX_FORWARDED_GRAPH_BYTES?void 0:JSON.parse(fs.readFileSync(s,"utf8"))})}catch(a){p(a)}})}).finally(()=>fs.rmSync(o,{recursive:!0,force:!0}))}u(forwardedGraphInChild,"forwardedGraphInChild"),f(forwardedGraphInChild,"forwardedGraphInChild");function createGuestGraphStore(e,r=process.env){const{wsKey:t,admission:o,context:s}=e,n=(0,registration_guards_1.canonicalRoot)(e.root),p=e.compute??(()=>forwardedGraphInChild(n,guestGraphEnv(r,s.daemonRoot,n))),i=o===void 0?"its registration forwarded none":o.refused!==void 0?`the project graph its registration forwarded was refused: ${o.refused}`:void 0;return(0,project_graph_store_1.createProjectGraphStore)(n,async()=>{const{graph:c,bytes:h}=await p(),d=admitForwardedGraph(c,{...s,bytes:h});if(d.refused!==void 0)throw new Error(`the computed project graph was refused: ${d.refused}`);return{projectGraph:d.snapshot.projectGraph,...d.snapshot.sourceMaps?{sourceMaps:d.snapshot.sourceMaps}:{}}},{...o?.snapshot?{seed:o.snapshot}:{},...i?{error:i}:{},retryAfterFailureMs:exports.GUEST_GRAPH_RETRY_MS,onRefreshed:f(c=>console.log(`[gateway] project graph of '${t}' (${n}) refreshed \u2014 ${Object.keys(c.projectGraph.nodes).length} projects; its services start through the serve runner again`),"onRefreshed")})}u(createGuestGraphStore,"createGuestGraphStore"),f(createGuestGraphStore,"createGuestGraphStore");
1
+ "use strict";var R=Object.defineProperty;var f=(e,r)=>R(e,"name",{value:r,configurable:!0});var _=Object.defineProperty,d=f((e,r)=>_(e,"name",{value:r,configurable:!0}),"d");Object.defineProperty(exports,"__esModule",{value:!0}),exports.GUEST_GRAPH_RETRY_MS=exports.MAX_FORWARDED_PROJECTS=exports.MAX_FORWARDED_GRAPH_BYTES=exports.FORWARDED_GRAPH_FORMAT=void 0,exports.ownedByThisUser=ownedByThisUser,exports.admitForwardedGraph=admitForwardedGraph,exports.compactSourceMaps=compactSourceMaps,exports.projectsOnly=projectsOnly,exports.snapshotWorkspaceGraph=snapshotWorkspaceGraph,exports.graphSnapshotScript=graphSnapshotScript,exports.guestGraphEnv=guestGraphEnv,exports.forwardedGraphInChild=forwardedGraphInChild,exports.ownGraphInFreshProcess=ownGraphInFreshProcess,exports.createGuestGraphStore=createGuestGraphStore;const tslib_1=require("tslib"),node_child_process_1=require("node:child_process"),fs=tslib_1.__importStar(require("node:fs")),os=tslib_1.__importStar(require("node:os")),path=tslib_1.__importStar(require("node:path")),pod_env_1=require("./pod-env"),project_graph_store_1=require("./project-graph-store"),registration_guards_1=require("./registration-guards");exports.FORWARDED_GRAPH_FORMAT=1,exports.MAX_FORWARDED_GRAPH_BYTES=8*1024*1024,exports.MAX_FORWARDED_PROJECTS=2e4,exports.GUEST_GRAPH_RETRY_MS=6e4;const GUEST_GRAPH_TIMEOUT_MS=12e4,SIGNATURE=/^(?:-|\?|\d+(?:\.\d+)?:\d+:\d+)$/;function megabytes(e){return`${(e/(1024*1024)).toFixed(1)} MB`}f(megabytes,"megabytes"),d(megabytes,"megabytes");const isRecord=d(e=>!!e&&typeof e=="object"&&!Array.isArray(e),"isRecord");function insideWorkspace(e){return e===""||path.isAbsolute(e)||/^[a-zA-Z]:/.test(e)?!1:!path.posix.normalize(e.replace(/\\/g,"/")).split("/").includes("..")}f(insideWorkspace,"insideWorkspace"),d(insideWorkspace,"insideWorkspace");function ownedByThisUser(e){const r=fs.statSync(e,{throwIfNoEntry:!1});if(!r?.isDirectory())return!1;if(typeof process.getuid!="function")return!0;const o=process.getuid();return r.uid===o||o===0&&r.uid===Number(process.env.SUDO_UID)}f(ownedByThisUser,"ownedByThisUser"),d(ownedByThisUser,"ownedByThisUser");function relativeDeclaringFiles(e,r){return(0,project_graph_store_1.declaringFiles)(e,r).map(o=>path.relative(e,o).split(path.sep).join("/"))}f(relativeDeclaringFiles,"relativeDeclaringFiles"),d(relativeDeclaringFiles,"relativeDeclaringFiles");function shapeProblem(e){if(!isRecord(e)||!isRecord(e.nodes)||!isRecord(e.dependencies))return"it has no `nodes` and `dependencies`";const r=e.nodes,o=Object.keys(r);if(o.length>exports.MAX_FORWARDED_PROJECTS)return`it names ${o.length} projects (at most ${exports.MAX_FORWARDED_PROJECTS})`;for(const t of o){const s=r[t];if(!isRecord(s)||s.name!==t||typeof s.type!="string"||!isRecord(s.data))return`project '${t}' is not a project node`;const n=s.data.root;if(typeof n!="string"||!insideWorkspace(n))return`project '${t}' has a root outside the workspace (${String(n)})`;const a=s.data.targets;if(a!==void 0&&(!isRecord(a)||!Object.values(a).every(isRecord)))return`project '${t}' has malformed targets`}for(const[t,s]of Object.entries(e.dependencies)){if(!(t in r)||!Array.isArray(s))return`the dependencies of '${t}' are not a known project's`;for(const n of s)if(!isRecord(n)||n.source!==t||typeof n.target!="string"||!(n.target in r)||typeof n.type!="string")return`a dependency of '${t}' is malformed`}}f(shapeProblem,"shapeProblem"),d(shapeProblem,"shapeProblem");function sourceMapsProblem(e){if(e!==void 0){if(!isRecord(e))return"its source maps are not a map";for(const[r,o]of Object.entries(e)){if(!isRecord(o))return`the source map of ${r} is malformed`;for(const t of Object.values(o))if(!Array.isArray(t)||t.length!==2||t[0]!==null&&typeof t[0]!="string"||typeof t[1]!="string")return`the source map of ${r} is malformed`}}}f(sourceMapsProblem,"sourceMapsProblem"),d(sourceMapsProblem,"sourceMapsProblem");function admitForwardedGraph(e,r){const o=d(p=>({refused:p}),"refuse");if(r.bytes>exports.MAX_FORWARDED_GRAPH_BYTES)return o(`${megabytes(r.bytes)} is over the ${megabytes(exports.MAX_FORWARDED_GRAPH_BYTES)} limit`);if(!isRecord(e))return o("it is not a project graph");if(e.format!==exports.FORWARDED_GRAPH_FORMAT)return o(`its format is ${String(e.format)}, and this gateway reads ${exports.FORWARDED_GRAPH_FORMAT}`);const t=e.root;if(typeof t!="string"||!path.isAbsolute(t))return o("it does not say which workspace it describes");if(!(0,registration_guards_1.sameRoot)(t,r.root))return o(`it describes ${t}, not the registering workspace ${r.root}`);if((0,registration_guards_1.sameRoot)(r.root,r.daemonRoot))return o(`${r.root} is the gateway's own workspace \u2014 the gateway reads that graph itself`);if(r.otherRoots.some(p=>(0,registration_guards_1.sameRoot)(p,r.root)))return o(`${r.root} is registered under another key`);if(!ownedByThisUser(r.root))return o(`${r.root} is not a directory this user owns`);const s=e.startedAt;if(typeof s!="number"||!Number.isFinite(s))return o("it does not say when it was computed");const n=shapeProblem(e.projectGraph)??sourceMapsProblem(e.sourceMaps);if(n)return o(n);const a=e.projectGraph,i=e.files;if(!isRecord(i))return o("it carries no fingerprint of its declaring files");const c=(0,registration_guards_1.canonicalRoot)(r.root),h=relativeDeclaringFiles(c,a),u=Object.keys(i),l=h.filter(p=>!(p in i));return l.length>0||u.length!==h.length?o(`its fingerprint does not cover exactly the files that declare it${l.length>0?` (no ${l[0]})`:""}`):Object.values(i).every(p=>typeof p=="string"&&SIGNATURE.test(p))?{snapshot:{root:c,startedAt:s,files:new Map(h.map(p=>[path.join(c,p),i[p]])),projectGraph:{nodes:a.nodes,dependencies:a.dependencies,externalNodes:{}},...e.sourceMaps!==void 0?{sourceMaps:e.sourceMaps}:{}}}:o("its fingerprint is malformed")}f(admitForwardedGraph,"admitForwardedGraph"),d(admitForwardedGraph,"admitForwardedGraph");function compactSourceMaps(e,r){const o={};for(const t of Object.values(e.nodes)){const s=r[t.data.root];if(!s)continue;const n=new Set;for(const i of Object.keys(t.data.targets??{})){const c=`targets.${i}`,h=new Set;for(const[u,l]of Object.entries(s)){if(u!==c&&!u.startsWith(`${c}.`))continue;const p=JSON.stringify(l);h.has(p)||(h.add(p),n.add(u))}}const a={};for(const[i,c]of Object.entries(s))n.has(i)&&(a[i]=c);o[t.data.root]=a}return o}f(compactSourceMaps,"compactSourceMaps"),d(compactSourceMaps,"compactSourceMaps");function projectsOnly(e){const r={};for(const[o,t]of Object.entries(e.dependencies))o in e.nodes&&(r[o]=t.filter(s=>s.target in e.nodes));return{nodes:e.nodes,dependencies:r}}f(projectsOnly,"projectsOnly"),d(projectsOnly,"projectsOnly");async function snapshotWorkspaceGraph(e,r=()=>(0,project_graph_store_1.computeProjectGraphInProcess)(e)){const o=Date.now(),t=(0,project_graph_store_1.filesystemNow)(),s=await r(),n=projectsOnly(s.projectGraph),a={};for(const i of(0,project_graph_store_1.declaringFiles)(e,s.projectGraph)){const c=fs.statSync(i,{throwIfNoEntry:!1});a[path.relative(e,i).split(path.sep).join("/")]=c&&c.mtimeMs>t?"?":(0,project_graph_store_1.statSignature)(i)}return{format:exports.FORWARDED_GRAPH_FORMAT,root:e,startedAt:o,projectGraph:n,...s.sourceMaps?{sourceMaps:compactSourceMaps(n,s.sourceMaps)}:{},files:a}}f(snapshotWorkspaceGraph,"snapshotWorkspaceGraph"),d(snapshotWorkspaceGraph,"snapshotWorkspaceGraph");function graphSnapshotScript(e=path.join(__dirname,"../../..")){const r=path.join(e,"graph-snapshot.js");if(fs.existsSync(r))return{path:r,execArgv:[]};const o=path.join(e,"graph-snapshot.ts");if(fs.existsSync(o))try{return{path:o,execArgv:["--require",require.resolve("@swc-node/register")]}}catch{return}}f(graphSnapshotScript,"graphSnapshotScript"),d(graphSnapshotScript,"graphSnapshotScript");function guestGraphEnv(e,r,o){const t={...(0,pod_env_1.podBaseEnv)(e,r,o)};for(const s of Object.keys(t))(s.startsWith("NX_TASK_")||["NX_WORKSPACE_ROOT","NX_WORKSPACE_ROOT_PATH","NX_WORKSPACE_DATA_DIRECTORY","NX_PROJECT_GRAPH_CACHE_DIRECTORY"].includes(s))&&delete t[s];return t.NX_DAEMON="false",t.NX_ISOLATE_PLUGINS="false",t}f(guestGraphEnv,"guestGraphEnv"),d(guestGraphEnv,"guestGraphEnv");function forwardedGraphInChild(e,r,o=graphSnapshotScript()){if(!o)return Promise.reject(new Error("graph-snapshot.js is missing from @lensmcp/cluster"));const t=fs.mkdtempSync(path.join(os.tmpdir(),"lensmcp-graph-")),s=path.join(t,"graph.json");return new Promise((n,a)=>{let i="";const c=(0,node_child_process_1.spawn)(process.execPath,[...o.execArgv,o.path,s],{cwd:e,env:r,stdio:["ignore","ignore","pipe"]});c.stderr?.on("data",u=>{i.length<4096&&(i+=u.toString())});const h=setTimeout(()=>c.kill("SIGKILL"),GUEST_GRAPH_TIMEOUT_MS);h.unref(),c.on("error",u=>{clearTimeout(h),a(u)}),c.on("exit",(u,l)=>{if(clearTimeout(h),u!==0){const p=i.trim().split(`
2
+ `).pop();a(new Error(`the graph computation in ${e} exited ${l??u}${p?` \u2014 ${p}`:""}`));return}try{const p=fs.statSync(s).size;n({bytes:p,graph:p>exports.MAX_FORWARDED_GRAPH_BYTES?void 0:JSON.parse(fs.readFileSync(s,"utf8"))})}catch(p){a(p)}})}).finally(()=>fs.rmSync(t,{recursive:!0,force:!0}))}f(forwardedGraphInChild,"forwardedGraphInChild"),d(forwardedGraphInChild,"forwardedGraphInChild");async function ownGraphInFreshProcess(e,r=process.env,o=(t,s)=>forwardedGraphInChild(t,s)){const{graph:t,bytes:s}=await o(e,guestGraphEnv(r,e,e)),n=d(h=>new Error(`the project graph computed in a fresh process was refused: ${h}`),"refused");if(s>exports.MAX_FORWARDED_GRAPH_BYTES)throw n(`${megabytes(s)} is over the ${megabytes(exports.MAX_FORWARDED_GRAPH_BYTES)} limit`);if(!isRecord(t))throw n("it is not a project graph");if(t.format!==exports.FORWARDED_GRAPH_FORMAT)throw n(`its format is ${String(t.format)}, and this gateway reads ${exports.FORWARDED_GRAPH_FORMAT}`);const a=t.root;if(typeof a!="string"||!(0,registration_guards_1.sameRoot)(a,e))throw n(`it describes ${String(a)}, not ${e}`);const i=shapeProblem(t.projectGraph)??sourceMapsProblem(t.sourceMaps);if(i)throw n(i);const c=t.projectGraph;return{projectGraph:{nodes:c.nodes,dependencies:c.dependencies,externalNodes:{}},...t.sourceMaps!==void 0?{sourceMaps:t.sourceMaps}:{}}}f(ownGraphInFreshProcess,"ownGraphInFreshProcess"),d(ownGraphInFreshProcess,"ownGraphInFreshProcess");function createGuestGraphStore(e,r=process.env){const{wsKey:o,admission:t,context:s}=e,n=(0,registration_guards_1.canonicalRoot)(e.root),a=e.compute??(()=>forwardedGraphInChild(n,guestGraphEnv(r,s.daemonRoot,n))),i=t===void 0?"its registration forwarded none":t.refused!==void 0?`the project graph its registration forwarded was refused: ${t.refused}`:void 0;return(0,project_graph_store_1.createProjectGraphStore)(n,async()=>{const{graph:c,bytes:h}=await a(),u=admitForwardedGraph(c,{...s,bytes:h});if(u.refused!==void 0)throw new Error(`the computed project graph was refused: ${u.refused}`);return{projectGraph:u.snapshot.projectGraph,...u.snapshot.sourceMaps?{sourceMaps:u.snapshot.sourceMaps}:{}}},{...t?.snapshot?{seed:t.snapshot}:{},...i?{error:i}:{},retryAfterFailureMs:exports.GUEST_GRAPH_RETRY_MS,onRefreshed:d(c=>console.log(`[gateway] project graph of '${o}' (${n}) refreshed \u2014 ${Object.keys(c.projectGraph.nodes).length} projects; its services start through the serve runner again`),"onRefreshed")})}f(createGuestGraphStore,"createGuestGraphStore"),d(createGuestGraphStore,"createGuestGraphStore");
@@ -1 +1 @@
1
- "use strict";var b=Object.defineProperty;var g=(u,n)=>b(u,"name",{value:n,configurable:!0});var T=Object.defineProperty,f=g((u,n)=>T(u,"name",{value:n,configurable:!0}),"f");Object.defineProperty(exports,"__esModule",{value:!0}),exports.mayBeParkedHost=mayBeParkedHost,exports.createHandler=createHandler;const manifest_1=require("../manifest"),service_keys_1=require("./service-keys"),gateway_errors_1=require("../gateway-errors"),discovery_1=require("./discovery"),edge_1=require("./edge"),observability_1=require("./observability"),chooser_1=require("./chooser"),on_demand_1=require("./on-demand");function mayBeParkedHost(u){return!u||!u.host||u.host.startsWith("*.")}g(mayBeParkedHost,"mayBeParkedHost"),f(mayBeParkedHost,"mayBeParkedHost");function createHandler(u){const{rt:n,obs:h,auth:m,proxy:S,hooks:c}=u,E=u.parkedHosts??(0,on_demand_1.createParkedHostLookup)({registry:f(()=>n.registry,"registry")}),_=f(e=>(e.headers.host||"").split(":")[0],"hostOf"),R=f((e,r)=>{if((0,edge_1.cors)(e,r,n.routes),e.method==="OPTIONS"){r.writeHead(204,{"access-control-allow-methods":edge_1.PREFLIGHT_METHODS_NOROUTE,"access-control-allow-headers":String(e.headers["access-control-request-headers"]??"*"),"access-control-max-age":edge_1.PREFLIGHT_MAX_AGE}),r.end();return}const s=(e.headers.host||"").split(":")[0],l=n.routes.filter(t=>t.host&&(0,manifest_1.hostMatches)(t.host,s)&&t.prefix),o=(e.url??"/").split("?")[0];if((o==="/"||o==="/index.html"||o==="")&&n.routes.some(t=>t.host&&(0,manifest_1.hostMatches)(t.host,s)&&t.project===observability_1.LENS_DASHBOARD_PROJECT)){(0,chooser_1.serveChooser)(r,n.wsKey,e);return}if(l.length>0&&(o==="/health"||o==="/healthz")){const t=l.map(d=>({project:d.project,prefix:d.prefix,pods:d.pool?((0,discovery_1.pickSock)(d.pool,0),d.pool.socks.length):void 0,state:d.svc?.state??(d.target?"up":"unknown")})),p=t.every(d=>d.state!=="down"||!0);r.writeHead(p?200:503,{"content-type":"application/json"}),r.end(JSON.stringify({status:"ok",host:s,services:t},null,2));return}if(l.length>0&&o==="/.well-known/services"){r.writeHead(200,{"content-type":"application/json"}),r.end(JSON.stringify({host:s,services:l.map(t=>({prefix:t.prefix,project:t.project,internal:!!t.internal}))},null,2));return}(0,edge_1.sendError)(r,e,404,"not_found",l.length>0?`No service mounted at ${o}. Mounted on ${s}: ${[...new Set(l.map(t=>t.prefix))].join(", ")} (+ /health, /.well-known/services)`:"No gateway route for this hostname.")},"handleNoRoute"),O=f(async(e,r)=>{if(!e.headers.host){const t=e.authority??e.headers[":authority"];t&&(e.headers.host=t)}(0,edge_1.stripOwnedHeaders)(e);let s=h.beginTrace(e);const l=Date.now();(0,gateway_errors_1.ensureRequestId)(e),s&&(h.traceStep(s,"received",{host:s.host,method:s.method,url:s.url}),e.__lensmcpTrace=s);const o=c.httpContext(e,r,s);try{const t=e.url??"/",p=(0,edge_1.canonicalize)(t);if(p===void 0){h.traceStep(s,"bad-path",{}),h.finishTrace(s,"gateway",400),(0,edge_1.sendError)(r,e,400,"bad_request","Bad Request");return}const d=p.policy,v=p.path+p.query;if(v!==t&&(0,edge_1.rememberRawTarget)(e,t),e.url=v,(0,edge_1.resolveClientIp)(n,e),c.has("onRequest")&&(await c.run("onRequest",o),o.responded()))return;const a=(0,manifest_1.matchRoute)(n.routes,_(e),d+p.query);if(mayBeParkedHost(a)){const i=E.match(_(e));if(i){const y=(0,on_demand_1.parkedAnswer)(i,String(e.headers.accept??""));h.traceStep(s,"worktree-parked",{worktree:i.name}),h.finishTrace(s,"gateway",y.status),r.writeHead(y.status,y.headers),r.end(y.body);return}}if(!a){R(e,r);return}o.route=a,(0,on_demand_1.touchRun)(n.registry,a,r);const w=h.startHeadlessFlow(e,a,s,l);if(w!==s&&(s=w,o.trace=w,e.__lensmcpTrace=w),h.traceStep(s,"route-match",{project:a.project,...a.prefix?{prefix:a.prefix}:{},...a.host?{routeHost:a.host}:{},...a.internal?{internal:!0}:{}}),e.method==="OPTIONS"){(0,edge_1.cors)(e,r,n.routes),r.writeHead(204,{"access-control-allow-methods":edge_1.PREFLIGHT_METHODS_ROUTED,"access-control-allow-headers":String(e.headers["access-control-request-headers"]??"*"),"access-control-max-age":edge_1.PREFLIGHT_MAX_AGE}),r.end();return}if((0,edge_1.cors)(e,r,n.routes),c.has("beforeAuth")&&(await c.run("beforeAuth",o),o.responded()))return;if(a.internal){const i=m.internal(e,a,s);if(!i.ok){h.finishTrace(s,a.project,i.status,void 0,a),(0,edge_1.sendError)(r,e,i.status,i.reason,i.detail);return}o.caller=i.caller}else{const i=m.public(e,a,s,d);if(!i.ok){h.finishTrace(s,a.project,i.status,void 0,a),(0,edge_1.sendError)(r,e,i.status,i.reason,i.detail);return}if(o.claims=i.claims,c.has("afterAuth")&&(await c.run("afterAuth",o),o.responded()))return}const H=a.pool?n.serviceKeys[(0,service_keys_1.serviceKeyId)(a.svc?.wsKey,a.project)]:void 0;if(H&&(e.headers["x-internal-token"]=H),(0,edge_1.stampForwardingHeaders)(n,e),c.has("beforeForward")&&(await c.run("beforeForward",o),o.responded()))return;c.has("onResponse")&&r.on("close",()=>{o.status=r.statusCode??0,c.run("onResponse",o)});const k=a.project===observability_1.LENS_DASHBOARD_PROJECT&&a.target?n.hostedDashboards?.get(a.target):void 0;k&&await k.serve(r),S.forward(a,e,r)}catch(t){o.error=t,console.error(`[gateway] ${new Date().toISOString()} pipeline error traceId=${(0,gateway_errors_1.ensureRequestId)(e)}: ${t?.stack??String(t)}`),c.has("onError")&&await c.run("onError",o),o.responded()||(0,edge_1.sendError)(r,e,500,"internal","Internal gateway error.")}},"runPipeline");return(e,r)=>{O(e,r)}}g(createHandler,"createHandler"),f(createHandler,"createHandler");
1
+ "use strict";var q=Object.defineProperty;var m=(u,n)=>q(u,"name",{value:n,configurable:!0});var T=Object.defineProperty,l=m((u,n)=>T(u,"name",{value:n,configurable:!0}),"l");Object.defineProperty(exports,"__esModule",{value:!0}),exports.mayBeParkedHost=mayBeParkedHost,exports.createHandler=createHandler;const manifest_1=require("../manifest"),service_keys_1=require("./service-keys"),gateway_errors_1=require("../gateway-errors"),discovery_1=require("./discovery"),edge_1=require("./edge"),observability_1=require("./observability"),chooser_1=require("./chooser"),on_demand_1=require("./on-demand");function mayBeParkedHost(u){return!u||!u.host||u.host.startsWith("*.")}m(mayBeParkedHost,"mayBeParkedHost"),l(mayBeParkedHost,"mayBeParkedHost");function createHandler(u){const{rt:n,obs:p,auth:g,proxy:H,hooks:c}=u,E=u.parkedHosts??(0,on_demand_1.createParkedHostLookup)({registry:l(()=>n.registry,"registry")}),k=l(e=>(e.headers.host||"").split(":")[0],"hostOf"),S=l(()=>(n.parkedDashboards?.list()??[]).flatMap(e=>e.base?[{key:e.key,root:e.root,base:e.base,name:e.name,baseKey:e.baseKey,apex:e.apex??""}]:[]),"parkedChooserEntries"),R=l((e,r)=>{const t=n.parkedDashboards?.list().find(s=>s.key===r);if(!t?.host||!t.base)return;const h=(e.headers.host||"").split(":")[1];return`${n.https?"https":"http"}://${t.host}${h?`:${h}`:""}${t.base}/`},"parkedDashboardUrl"),x=l((e,r)=>{if((0,edge_1.cors)(e,r,n.routes),e.method==="OPTIONS"){r.writeHead(204,{"access-control-allow-methods":edge_1.PREFLIGHT_METHODS_NOROUTE,"access-control-allow-headers":String(e.headers["access-control-request-headers"]??"*"),"access-control-max-age":edge_1.PREFLIGHT_MAX_AGE}),r.end();return}const t=(e.headers.host||"").split(":")[0],h=n.routes.filter(o=>o.host&&(0,manifest_1.hostMatches)(o.host,t)&&o.prefix),s=(e.url??"/").split("?")[0];if((s==="/"||s==="/index.html"||s==="")&&n.routes.some(o=>o.host&&(0,manifest_1.hostMatches)(o.host,t)&&o.project===observability_1.LENS_DASHBOARD_PROJECT)){(0,chooser_1.serveChooser)(r,n.wsKey,e,S());return}if(h.length>0&&(s==="/health"||s==="/healthz")){const o=h.map(d=>({project:d.project,prefix:d.prefix,pods:d.pool?((0,discovery_1.pickSock)(d.pool,0),d.pool.socks.length):void 0,state:d.svc?.state??(d.target?"up":"unknown")})),f=o.every(d=>d.state!=="down"||!0);r.writeHead(f?200:503,{"content-type":"application/json"}),r.end(JSON.stringify({status:"ok",host:t,services:o},null,2));return}if(h.length>0&&s==="/.well-known/services"){r.writeHead(200,{"content-type":"application/json"}),r.end(JSON.stringify({host:t,services:h.map(o=>({prefix:o.prefix,project:o.project,internal:!!o.internal}))},null,2));return}(0,edge_1.sendError)(r,e,404,"not_found",h.length>0?`No service mounted at ${s}. Mounted on ${t}: ${[...new Set(h.map(o=>o.prefix))].join(", ")} (+ /health, /.well-known/services)`:"No gateway route for this hostname.")},"handleNoRoute"),O=l(async(e,r)=>{if(!e.headers.host){const o=e.authority??e.headers[":authority"];o&&(e.headers.host=o)}(0,edge_1.stripOwnedHeaders)(e);let t=p.beginTrace(e);const h=Date.now();(0,gateway_errors_1.ensureRequestId)(e),t&&(p.traceStep(t,"received",{host:t.host,method:t.method,url:t.url}),e.__lensmcpTrace=t);const s=c.httpContext(e,r,t);try{const o=e.url??"/",f=(0,edge_1.canonicalize)(o);if(f===void 0){p.traceStep(t,"bad-path",{}),p.finishTrace(t,"gateway",400),(0,edge_1.sendError)(r,e,400,"bad_request","Bad Request");return}const d=f.policy,_=f.path+f.query;if(_!==o&&(0,edge_1.rememberRawTarget)(e,o),e.url=_,(0,edge_1.resolveClientIp)(n,e),c.has("onRequest")&&(await c.run("onRequest",s),s.responded()))return;const a=(0,manifest_1.matchRoute)(n.routes,k(e),d+f.query);if(mayBeParkedHost(a)){const i=E.match(k(e));if(i){const w=(0,on_demand_1.parkedAnswer)(i,String(e.headers.accept??""),R(e,i.key));p.traceStep(t,"worktree-parked",{worktree:i.name}),p.finishTrace(t,"gateway",w.status),r.writeHead(w.status,w.headers),r.end(w.body);return}}if(!a){x(e,r);return}s.route=a,(0,on_demand_1.touchRun)(n.registry,a,r);const y=p.startHeadlessFlow(e,a,t,h);if(y!==t&&(t=y,s.trace=y,e.__lensmcpTrace=y),p.traceStep(t,"route-match",{project:a.project,...a.prefix?{prefix:a.prefix}:{},...a.host?{routeHost:a.host}:{},...a.internal?{internal:!0}:{}}),e.method==="OPTIONS"){(0,edge_1.cors)(e,r,n.routes),r.writeHead(204,{"access-control-allow-methods":edge_1.PREFLIGHT_METHODS_ROUTED,"access-control-allow-headers":String(e.headers["access-control-request-headers"]??"*"),"access-control-max-age":edge_1.PREFLIGHT_MAX_AGE}),r.end();return}if((0,edge_1.cors)(e,r,n.routes),c.has("beforeAuth")&&(await c.run("beforeAuth",s),s.responded()))return;if(a.internal){const i=g.internal(e,a,t);if(!i.ok){p.finishTrace(t,a.project,i.status,void 0,a),(0,edge_1.sendError)(r,e,i.status,i.reason,i.detail);return}s.caller=i.caller}else{const i=g.public(e,a,t,d);if(!i.ok){p.finishTrace(t,a.project,i.status,void 0,a),(0,edge_1.sendError)(r,e,i.status,i.reason,i.detail);return}if(s.claims=i.claims,c.has("afterAuth")&&(await c.run("afterAuth",s),s.responded()))return}const v=a.pool?n.serviceKeys[(0,service_keys_1.serviceKeyId)(a.svc?.wsKey,a.project)]:void 0;if(v&&(e.headers["x-internal-token"]=v),(0,edge_1.stampForwardingHeaders)(n,e),c.has("beforeForward")&&(await c.run("beforeForward",s),s.responded()))return;c.has("onResponse")&&r.on("close",()=>{s.status=r.statusCode??0,c.run("onResponse",s)});const b=a.project===observability_1.LENS_DASHBOARD_PROJECT&&a.target?n.hostedDashboards?.get(a.target):void 0;b&&await b.serve(r),H.forward(a,e,r)}catch(o){s.error=o,console.error(`[gateway] ${new Date().toISOString()} pipeline error traceId=${(0,gateway_errors_1.ensureRequestId)(e)}: ${o?.stack??String(o)}`),c.has("onError")&&await c.run("onError",s),s.responded()||(0,edge_1.sendError)(r,e,500,"internal","Internal gateway error.")}},"runPipeline");return(e,r)=>{O(e,r)}}m(createHandler,"createHandler"),l(createHandler,"createHandler");
@@ -69,6 +69,19 @@ export interface LensChildren {
69
69
  * distinct port, append its `lensmcp.local/<key>` route to its fragment. Returns a reaper (kills the
70
70
  * child WITHOUT auto-heal respawn) for the daemon to call on unregister — or undefined if no bundle. */
71
71
  hostWorkspaceDashboard(fragment: WorkspaceFragment): Promise<(() => void) | undefined>;
72
+ /** Host a PARKED on-demand worktree's dashboard (parked-dashboards.ts): a standalone `lensmcp.local/<key>` route, its
73
+ * dashboard started only by a request for it, in the worktree's root and on its bus. Where it answers and a reaper —
74
+ * or undefined: no bundle, `dashboard: false`, or a root whose config is not that instance's. */
75
+ hostParkedDashboard(w: {
76
+ key: string;
77
+ name: string;
78
+ baseKey: string;
79
+ root: string;
80
+ }): Promise<{
81
+ host: string;
82
+ base: string;
83
+ reap: () => void;
84
+ } | undefined>;
72
85
  /** Host a REGISTERED workspace's `lens:true` FRONTEND apps (completes model-A "the daemon hosts
73
86
  * everything"): spawn each app's vite (+ capture) in the workspace's OWN root + event bus, on a
74
87
  * collision-safe port, and point its route target at that port. Returns a reaper for unregister. */
@@ -1 +1 @@
1
- "use strict";var me=Object.defineProperty;var L=(s,h)=>me(s,"name",{value:h,configurable:!0});var ve=Object.defineProperty,c=L((s,h)=>ve(s,"name",{value:h,configurable:!0}),"c");Object.defineProperty(exports,"__esModule",{value:!0}),exports.probePortFree=probePortFree,exports.probePortListening=probePortListening,exports.probeWatcherHealth=probeWatcherHealth,exports.waitForPortFree=waitForPortFree,exports.viteArgPort=viteArgPort,exports.describeChildExit=describeChildExit,exports.signalChild=signalChild,exports.claimPort=claimPort,exports.createLensChildren=createLensChildren;const tslib_1=require("tslib"),net=tslib_1.__importStar(require("node:net")),path=tslib_1.__importStar(require("node:path")),node_child_process_1=require("node:child_process"),lens_frontend_1=require("@lensmcp/nx-plugin/lens-frontend"),hmr_reload_1=require("./hmr-reload"),own_log_1=require("./own-log"),process_name_1=require("../../../process-name"),pod_env_1=require("./pod-env"),control_1=require("./control"),scope_1=require("./scope"),workspace_registry_1=require("./workspace-registry"),lifecycle_1=require("./lifecycle"),types_1=require("./types"),observability_1=require("./observability"),hosted_dashboard_1=require("./hosted-dashboard"),HEAL_BASE_MS=1500,HEAL_MAX_MS=3e4,HEAL_HEALTHY_MS=2e4,DASHBOARD_SWEEP_MS=15e3;function tryBind(s,h){return new Promise(f=>{const _=net.createServer();_.unref(),_.once("error",p=>{const w=p.code??"";f(w==="EADDRINUSE"||w==="EACCES"?"in-use":"unavailable")}),_.listen(h===void 0?{port:s}:{port:s,host:h},()=>_.close(()=>f("free")))})}L(tryBind,"tryBind"),c(tryBind,"tryBind");async function probePortFree(s){for(const h of[void 0,"0.0.0.0","127.0.0.1","::1"])if(await tryBind(s,h)==="in-use")return!1;return!0}L(probePortFree,"probePortFree"),c(probePortFree,"probePortFree");function probeConnect(s,h,f){return new Promise(_=>{let p=!1;const w=net.createConnection({host:s,port:h});w.unref();const b=setTimeout(()=>R(!1),f);b.unref?.();function R(H){p||(p=!0,clearTimeout(b),w.destroy(),_(H))}L(R,"M"),c(R,"finish"),w.once("connect",()=>R(!0)),w.once("error",()=>R(!1))})}L(probeConnect,"probeConnect"),c(probeConnect,"probeConnect");async function probePortListening(s,h=1e3){return await probeConnect("127.0.0.1",s,h)?!0:probeConnect("::1",s,h)}L(probePortListening,"probePortListening"),c(probePortListening,"probePortListening");async function probeWatcherHealth(s,h=1500){try{const f=new AbortController,_=setTimeout(()=>f.abort(),h);_.unref?.();try{const p=await fetch(`http://127.0.0.1:${s}/__lensmcp/watcher-health`,{signal:f.signal});if(!p.ok)return null;const w=await p.json();if(typeof w?.lastFsSetEventAt!="number")return null;const b=Array.isArray(w.recentEvents)?w.recentEvents.filter(R=>R&&typeof R.path=="string"&&typeof R.at=="number"&&typeof R.sequence=="number"&&["add","addDir","unlink","unlinkDir"].includes(R.kind)):[];return{schemaVersion:w.schemaVersion===2?2:1,ready:w.ready!==!1,sequence:typeof w.sequence=="number"?w.sequence:0,lastFsSetEventAt:w.lastFsSetEventAt,fsSetEvents:typeof w.fsSetEvents=="number"?w.fsSetEvents:0,recentEvents:b}}finally{clearTimeout(_)}}catch{return null}}L(probeWatcherHealth,"probeWatcherHealth"),c(probeWatcherHealth,"probeWatcherHealth");const sleepUnref=c(s=>new Promise(h=>{setTimeout(h,s).unref?.()}),"sleepUnref");async function waitForPortFree(s,h,f={}){const _=f.isPortFree??probePortFree,p=Math.max(1,f.intervalMs??types_1.PORT_FREE_POLL_MS),w=Date.now()+Math.max(0,h);for(;;){if(await _(s))return!0;const b=w-Date.now();if(b<=0)return!1;await sleepUnref(Math.min(p,b))}}L(waitForPortFree,"waitForPortFree"),c(waitForPortFree,"waitForPortFree");function viteArgPort(s){const h=c(f=>Number.isInteger(f)&&f>0&&f<65536?f:void 0,"valid");for(let f=0;f<s.length;f+=1){const _=s[f];if(_==="--port")return h(Number(s[f+1]));if(_.startsWith("--port="))return h(Number(_.slice(7)))}}L(viteArgPort,"viteArgPort"),c(viteArgPort,"viteArgPort");function describeChildExit(s){return s.signalCode?`killed by ${s.signalCode}`:s.exitCode===null?"exit status unknown":`exit code ${s.exitCode}`}L(describeChildExit,"describeChildExit"),c(describeChildExit,"describeChildExit");function signalChild(s,h){if(s.pid===void 0)return!1;try{return s.kill(h)}catch{return!1}}L(signalChild,"signalChild"),c(signalChild,"signalChild");async function claimPort(s,h,f,_){let p=s;for(;h.has(p)||_?.has(p)||!await f(p);)p+=1;return h.add(p),p}L(claimPort,"claimPort"),c(claimPort,"claimPort");function createLensChildren(s,h,f,_){const{emit:p}=h,w=_?.isPortFree??probePortFree,b=(f.ports?.length?f.ports:[443]).join(","),R=(0,control_1.clusterVersion)(),H={LENSMCP_GATEWAY_PID:String(process.pid),...R?{LENSMCP_GATEWAY_VERSION:R}:{}},ne=_?.probeWatcherHealth??probeWatcherHealth,j=[],Y=new Map,A=new Map,x=new Map,z=new Map,q=new Set;let F;const m=new Map,C=new Set,X=new Set,J=new Set,W=new Map;s.hostedDashboards=W;let I;const fe=c(()=>{I||(I=setInterval(()=>{if(!s.stopped())for(const e of W.values())e.tick()},DASHBOARD_SWEEP_MS),I.unref?.())},"startDashboardSweeper"),T=new Set,M=new Map,K=new WeakMap,U=new Set,re=c((e,r,n)=>{if(U.has(e))return;U.add(e);const t=setInterval(()=>{(async()=>{if(s.stopped()||C.has(e)){clearInterval(t),U.delete(e);return}await w(r)&&(clearInterval(t),U.delete(e),console.log(`[gateway] lens child ${e}: :${r} freed \u2014 respawning.`),n())})().catch(()=>{})},types_1.LENS_PARKED_PORT_REPROBE_MS);t.unref?.()},"parkUntilPortFree"),B=c(async(e,r,n)=>{const t=await claimPort(e,r,w,n?.reserved);return t!==e&&(n?.heldBy?console.log(`[gateway] handoff: :${e} is held by ${n.heldBy} \u2014 replacement on :${t}.`):console.warn(`[gateway] port ${e} is unavailable (another process holds it \u2014 an orphan from a crashed gateway?) \u2014 using ${t} instead.`)),t},"claimFreePort"),ge=c((e,r,n)=>{const t=n?.LENSMCP_FRONTEND_KEY,o=Number(n?.LENSMCP_FRONTEND_GENERATION);if(!t||!Number.isFinite(o))return;const a=[...M.get(t)?.generations??[]].find(i=>i.generation===o);a&&(e.endsWith(":vite")?a.vite=r:e.endsWith(":browser-capture")&&(a.capture=r))},"attachRespawnedGenerationChild"),V=c(e=>{e.exitCode!==null||e.signalCode!==null||e.pid===void 0||(X.add(e),signalChild(e,"SIGTERM"),setTimeout(()=>{e.exitCode===null&&e.signalCode===null&&signalChild(e,"SIGKILL")},types_1.LENS_RECYCLE_KILL_GRACE_MS).unref?.())},"retireChild"),he=c((e,r)=>{const n=m.get(e);!n||n===r||n.exitCode!==null||n.signalCode!==null||(console.warn(`[gateway] lens child ${e}: a replacement took the label \u2014 retiring the previous child (pid ${n.pid??"?"}).`),V(n))},"retireLabelHolder"),k=c((e,r,n,t,o=!1,a,i,l)=>{const E=Date.now(),g=(0,own_log_1.gatewayLogTakeover)()!==void 0,d=(0,node_child_process_1.spawn)(r,n,{cwd:i??s.root,env:{...(0,pod_env_1.podBaseEnv)(process.env,s.root,i??s.root),...t??{},LENSMCP_PARENT_PID:String(process.pid)},stdio:g?["inherit","pipe","pipe"]:"inherit"});g&&(d.stdout?.on("data",P=>process.stdout.write(P)),d.stderr?.on("data",P=>process.stderr.write(P))),j.push(d),he(e,d),m.set(e,d),ge(e,d,t);const $=e==="vite"||e.endsWith(":vite"),v=typeof t?.LENSMCP_EVENT_FILE=="string"?t.LENSMCP_EVENT_FILE:void 0,y=v&&v!==s.eventFile?v:void 0,u=$?viteArgPort(n):l;$&&A.set(d,{key:t?.LENSMCP_FRONTEND_KEY??`${i??s.root}:${t?.LENSMCP_PROJECT??"app"}`,project:t?.LENSMCP_PROJECT??"app",workspaceRoot:i??s.root,spawnedAt:E,port:u,probeFails:0,listening:!1,generation:Number(t?.LENSMCP_FRONTEND_GENERATION??0),role:t?.LENSMCP_FRONTEND_ROLE==="replacement"?"replacement":"active",...y?{bus:y}:{}});const S=e==="lens-mcp"?"lens-mcp":e==="lens-dashboard"||e.startsWith("lens-dashboard:")?"lens-dashboard":void 0;return S&&u!==void 0&&(p("info",`lens child starting: ${S} (:${u})`,`cluster-lens-child:${S}`,{kind:"lens-child-starting",project:S,label:e,pid:d.pid,port:u},void 0,y),(async()=>{const P=Date.now()+types_1.LENS_REPLACEMENT_READY_MS;for(;!s.stopped()&&Date.now()<P;){if(d.exitCode!==null||d.signalCode!==null||C.has(e))return;if(await probePortListening(u,Math.min(500,types_1.LENS_PROBE_TIMEOUT_MS))){p("info",`lens child up: ${S} (:${u})`,`cluster-lens-child:${S}`,{kind:"lens-child-up",project:S,label:e,pid:d.pid,port:u},void 0,y);return}await sleepUnref(150)}})().catch(()=>{})),d.on("error",P=>{if(d.pid!==void 0){console.warn(`[gateway] lens child ${e}: ${P.message}`);return}const D=j.indexOf(d);D>=0&&j.splice(D,1),m.get(e)===d&&m.delete(e),A.delete(d),X.delete(d),console.error(`[gateway] lens child ${e} failed to spawn (${P.message}) \u2014 not started, not retried.`)}),d.on("exit",(P,D)=>{const de=j.indexOf(d);de>=0&&j.splice(de,1),m.get(e)===d&&m.delete(e);const O=A.get(d);if(A.delete(d),X.delete(d))return;const Ne=C.delete(e);if(s.stopped()||Ne||(S?p("warning",`lens child exited: ${S}`,`cluster-lens-child:${S}`,{kind:"lens-child-exit",project:S,label:e,pid:d.pid,code:P,signal:D},void 0,y):O&&p("warning",`lens frontend exited: ${O.project}`,`cluster-lens-child:${O.project}`,{kind:"lens-child-exit",project:O.project,label:e,pid:d.pid,code:P,signal:D,generation:O.generation,port:O.port,ranMs:Date.now()-E},void 0,y),O&&Se(d,O)))return;const pe=Date.now()-E,N=Y.get(e)??{attempts:0,portConflicts:0};(async()=>{const be=u!==void 0&&!await w(u),ue=(0,lifecycle_1.isPortConflictExit)({code:P,signal:D,ranMs:pe,portHeld:be},{fastFailMs:types_1.CHILD_START_FAIL_MS});if(ue&&N.portConflicts<types_1.MAX_PORT_CONFLICT_RETRIES)N.portConflicts+=1,Y.set(e,N),console.warn(`[gateway] lens child ${e} lost the :${u} bind race (EADDRINUSE, code=${P}); waiting for the port, then retrying (port-retry ${N.portConflicts}/${types_1.MAX_PORT_CONFLICT_RETRIES}; crash budget untouched).`);else if(ue){N.portConflicts=0,Y.set(e,N),console.warn(`[gateway] lens child ${e}: :${u} persistently held after ${types_1.MAX_PORT_CONFLICT_RETRIES} bind races \u2014 another server owns it (an external/shared daemon?). Parking; re-probing every ${Math.round(types_1.LENS_PARKED_PORT_REPROBE_MS/1e3)}s, will respawn if it frees.`),p("warning",`lens child parked: ${e} (:${u} held externally)`,`cluster-lens-child:${e}`,{kind:"lens-child-parked",label:e,port:u}),re(e,u,()=>k(e,r,n,t,o,a,i,l));return}else{N.portConflicts=0,pe>=HEAL_HEALTHY_MS&&(N.attempts=0);const Ee=Math.min(HEAL_MAX_MS,HEAL_BASE_MS*2**N.attempts);N.attempts+=1,Y.set(e,N),console.warn(`[gateway] lens child ${e} exited (code=${P} sig=${D}); auto-healing in ${Math.round(Ee/1e3)}s (attempt ${N.attempts}).`),await sleepUnref(Ee)}s.stopped()||C.has(e)||(u!==void 0&&!await waitForPortFree(u,types_1.PORT_FREE_WAIT_MS,{isPortFree:w,intervalMs:types_1.PORT_FREE_POLL_MS})&&console.warn(`[gateway] lens child ${e}: :${u} still held after ${Math.round(types_1.PORT_FREE_WAIT_MS/1e3)}s \u2014 spawning anyway.`),!(s.stopped()||C.has(e))&&k(e,r,n,t,o,a,i,l))})().catch(()=>{})}),d},"spawnManagedChild"),se=c(e=>{const r=`${e.wsKey}:${e.project}`,n=M.get(r);if(n)return n;const t={key:r,...e,sourceDirs:e.frontend.sourceRoots?.length?e.frontend.sourceRoots:[e.projectRoot],generation:0,state:"starting",generations:new Set,disposed:!1};M.set(r,t);for(const o of e.routes)o.lens&&(o.lens.workspaceKey??=e.wsKey,K.set(o.lens,t));return e.frontend.workspaceKey??=e.wsKey,K.set(e.frontend,t),t},"registerFrontend"),we=c(e=>{if(!types_1.LENS_WATCH_SCOPE_ENABLED)return{};const r=path.resolve(e.projectRoot),n=e.sourceDirs.map(t=>path.resolve(t)).filter(t=>t!==r);return n.length>0?{LENSMCP_WATCH_DIRS:n.join(path.delimiter)}:{}},"lensWatchScopeEnv"),ae=c((e,r,n)=>{const t=++e.generation,o=`${e.key}:g${t}:`,a=`${o}vite`,i=`${o}browser-capture`;C.delete(a),C.delete(i);const l=c((d,$,v,y,u,S)=>k(d,$,v,y,u,S,e.workspaceRoot),"spawnInRoot"),E=(0,lens_frontend_1.spawnLensFrontend)({projectRoot:e.projectRoot,workspaceRoot:e.workspaceRoot,project:e.project,eventFile:e.eventFile,port:r,chrome:!0,headless:!0,viteEnv:{...e.frontend.env??{},...e.frontend.frozen?{LENSMCP_FREEZE:"1"}:{},LENSMCP_PROJECT:e.project,...e.replayWorkspace?{LENSMCP_REPLAY_WORKSPACE:e.replayWorkspace}:{},LENSMCP_FRONTEND_KEY:e.key,LENSMCP_FRONTEND_GENERATION:String(t),LENSMCP_FRONTEND_ROLE:n,...we(e),NX_DAEMON:"false",NX_ISOLATE_PLUGINS:"false"},labelPrefix:o,log:c(d=>console.log(d),"log")},l),g={ownerKey:e.key,generation:t,port:r,labelPrefix:o,vite:E?.vite??m.get(a),capture:m.get(i)};return e.generations.add(g),g},"spawnFrontendGeneration"),G=c((e,r)=>{if(!e)return;M.get(e.ownerKey)?.generations.delete(e);const n=[[`${e.labelPrefix}browser-capture`,e.capture],[`${e.labelPrefix}vite`,e.vite]];for(const[t,o]of n)C.add(t),o&&V(o);r&&T.delete(e.port)},"terminateGeneration"),_e=c(async e=>{const r=Date.now()+types_1.LENS_REPLACEMENT_READY_MS;for(;!s.stopped()&&Date.now()<r;){const n=e.vite;if(!n||n.exitCode!==null||n.signalCode!==null)return!1;if(await probePortListening(e.port,Math.min(500,types_1.LENS_PROBE_TIMEOUT_MS))){const t=await ne(e.port);if(!t||t.ready)return!0}await sleepUnref(150)}return!1},"waitForGenerationReady"),Z=c(async e=>{const r=e?.vite;return!!(e&&r&&r.exitCode===null&&r.signalCode===null&&await probePortListening(e.port,Math.min(500,types_1.LENS_PROBE_TIMEOUT_MS)))},"generationIsServing"),Q=c(e=>!e.disposed&&!s.stopped()&&M.get(e.key)===e,"frontendIsCurrent"),ee=c((e,r)=>{if(!Q(e))return Promise.resolve(!1);if(e.replacement)return e.replacement;const n=e.active;e.state=n?"replacing":"starting",e.reason=r,e.startedAt=Date.now();const t=(async()=>{let o,a;const i=Date.now();try{const l=new Set;for(const u of M.values())u!==e&&l.add(u.desiredPort);const E=n&&n.port===e.desiredPort?`g${n.generation}`:void 0,g=await B(e.desiredPort,T,{reserved:l,heldBy:E});if(a=g,!Q(e))return T.delete(g),!1;o=ae(e,g,"replacement"),e.candidate=o;const d=await Z(n);console.log(`[gateway] lens handoff start: ${e.key} g${n?.generation??0}\u2192g${o.generation} :${n?.port??"down"}\u2192:${g} reason=${r}`),p("info",`lens handoff starting: ${e.project}`,`cluster-lens-app:${e.project}`,{kind:"lens-handoff-start",wsKey:e.wsKey,project:e.project,reason:r,generation:o.generation,oldPort:n?.port,newPort:g,oldServing:d},void 0,e.eventFile===s.eventFile?void 0:e.eventFile);const $=await _e(o);if(!Q(e))return G(o,!0),e.candidate=void 0,!1;if(!$){G(o,!0),e.candidate=void 0;const u=await Z(n);return e.state=u?"ready":"failed",u&&(e.reason=void 0,e.startedAt=void 0),console.error(`[gateway] lens handoff failed: ${e.key} g${o.generation} did not become ready within ${types_1.LENS_REPLACEMENT_READY_MS}ms; ${e.state==="ready"?"old generation kept serving":"no active generation"}.`),p("warning",`lens handoff failed: ${e.project}`,`cluster-lens-app:${e.project}`,{kind:"lens-handoff-failed",wsKey:e.wsKey,project:e.project,reason:r,generation:o.generation,port:g,durationMs:Date.now()-i,oldKept:u},void 0,e.eventFile===s.eventFile?void 0:e.eventFile),!1}for(const u of e.routes)u.target=`http://localhost:${o.port}`,u.lens&&(u.lens.port=o.port);e.frontend.port=o.port,e.active=o,e.candidate=void 0,e.state="ready",e.reason=void 0,e.startedAt=void 0;const v=o.vite?A.get(o.vite):void 0;v&&(v.role="active",v.listening=!0);const y=(0,hmr_reload_1.broadcastFullReload)(s,e.key);if(console.log(`[gateway] lens handoff ready: ${e.key} g${o.generation} :${o.port} in ${Date.now()-i}ms; draining g${n?.generation??0}${y>0?`; reloading ${y} tab(s)`:""}.`),p("info",`lens handoff complete: ${e.project}`,`cluster-lens-app:${e.project}`,{kind:"lens-handoff-complete",wsKey:e.wsKey,project:e.project,reason:r,generation:o.generation,oldPort:n?.port,newPort:o.port,durationMs:Date.now()-i,reloadedTabs:y},void 0,e.eventFile===s.eventFile?void 0:e.eventFile),n){const u=`${n.labelPrefix}browser-capture`;C.add(u),n.capture&&V(n.capture),setTimeout(()=>G(n,!0),types_1.LENS_REPLACEMENT_DRAIN_MS).unref?.()}return!0}catch(l){G(o,!0),!o&&a!==void 0&&T.delete(a),e.candidate=void 0;const E=await Z(n);e.state=E?"ready":"failed",E&&(e.reason=void 0,e.startedAt=void 0);const g=l.message;return console.error(`[gateway] lens handoff failed: ${e.key}: ${g}`),p("warning",`lens handoff failed: ${e.project}`,`cluster-lens-app:${e.project}`,{kind:"lens-handoff-failed",wsKey:e.wsKey,project:e.project,reason:r,generation:o?.generation??e.generation,port:o?.port??a,durationMs:Date.now()-i,oldKept:E,error:g},void 0,e.eventFile===s.eventFile?void 0:e.eventFile),!1}finally{e.replacement=void 0}})();return e.replacement=t,t},"rollFrontend"),ie=c((e,r)=>{e.active=ae(e,r,"active"),e.state="starting",e.startedAt=Date.now()},"spawnInitialFrontend"),Se=c((e,r)=>{const n=M.get(r.key);return!n||types_1.LENS_RESTART_MODE==="in-place"?!1:(n.candidate?.vite===e||n.active?.vite!==e||(n.state="starting",n.reason="child-exit",n.startedAt=Date.now(),console.warn(`[gateway] lens frontend exited: ${n.key} g${r.generation} :${r.port} (${describeChildExit(e)}); starting an alternate-port replacement.`),ee(n,"child-exit")),!0)},"handleManagedViteExit");s.lensSupervisor=types_1.LENS_RESTART_MODE==="rolling"?{status(e){const r=K.get(e);return r?{state:r.state,generation:r.candidate?.generation??r.active?.generation??r.generation,reason:r.reason,startedAt:r.startedAt}:void 0},recover(e,r){const n=K.get(e);return n?ee(n,r):Promise.resolve(!1)}}:void 0;let te=!1,le=0;const ye=c(()=>{te||Date.now()-le<types_1.POD_STALE_SCAN_MS||(te=!0,le=Date.now(),(async()=>{const e=new Map;for(const r of[...M.values()]){if(s.stopped())return;let n=e.get(r.workspaceRoot);if(!n){const g=(0,scope_1.readSourceSetOptions)(r.workspaceRoot);n={pass:(0,lifecycle_1.sourceScanPass)(r.workspaceRoot,g.exclude,{ignoreTests:g.ignoreTests}),startedAt:Date.now()},e.set(r.workspaceRoot,n)}const t=n.startedAt,o=await n.pass.snapshot(r.sourceDirs);if(M.get(r.key)!==r)continue;const a=r.sourceSnapshot,i=r.sourceScanStartedAt;if(r.sourceSnapshot=o,r.sourceScanStartedAt=t,!a)continue;const l=Date.now(),E=(0,lifecycle_1.diffSourceSets)(a,o,l,(0,lifecycle_1.sourceChangeWindowMs)(l,i,types_1.POD_STALE_SCAN_MS,types_1.POD_RECYCLE_SETTLE_MS));E&&(r.sourceChange=E,p("info",`source file set changed for ${r.key}`,`cluster-lens-app:${r.project}`,{kind:"source-set-changed",scoped:!0,wsKey:r.wsKey,project:r.project,added:E.added,removed:E.removed,truncated:E.truncated},void 0,r.eventFile===s.eventFile?void 0:r.eventFile))}})().catch(()=>{}).finally(()=>{te=!1}))},"scanFrontendSourceSets");let oe=!1;const Pe=c(async(e,r)=>{if(!oe){oe=!0;try{for(const[n,t]of[...A]){if(s.stopped())return;if(t.port===void 0||n.exitCode!==null||n.signalCode!==null)continue;if(await probePortListening(t.port,types_1.LENS_PROBE_TIMEOUT_MS)){if(t.probeFails=0,!t.listening){t.listening=!0;const l=M.get(t.key);l?.active?.vite===n&&(l.state="ready",l.reason=void 0),p("info",`lens app up: ${t.project} (vite :${t.port} listening)`,`cluster-lens-app:${t.project}`,{kind:"service-up",project:t.project,port:t.port},void 0,t.bus)}continue}const o=t.listening?e.graceMs:Math.max(e.graceMs,e.neverListenedGraceMs);if(Date.now()-t.spawnedAt<o){t.probeFails=0;continue}if(!r)continue;t.probeFails+=1;const a=(0,lifecycle_1.lensChildWedged)({spawnedAt:t.spawnedAt,probeFails:t.probeFails,hasListened:t.listening},x.get(t.key)??0,Date.now(),e);if(!a)continue;const i=t.listening?"its listener VANISHED (was up, now refusing)":`it NEVER bound within the ${Math.round(o/1e3)}s boot allowance`;x.set(t.key,Date.now()),t.probeFails=0,t.listening=!1,console.error(`[gateway] wedge recycle: lens app ${t.project} is ALIVE but NOT LISTENING on :${t.port} after ${Math.max(2,e.failureThreshold)} probes \u2014 ${i} \u2014 SIGKILL; a fresh vite is coming.`),p("warning",`wedge recycle: ${t.project} (${a})`,`cluster-lens-app:${t.project}`,{kind:"pod-recycle",project:t.project,reason:a,port:t.port},void 0,t.bus),signalChild(n,"SIGKILL")}}finally{oe=!1}}},"probeLensChildren"),Le=c(()=>{if(F||!types_1.POD_RECYCLE_ENABLED&&!types_1.LENS_PROBE_ENABLED)return;const e={graceMs:types_1.POD_STALE_GRACE_MS,settleMs:types_1.POD_RECYCLE_SETTLE_MS,cooldownMs:types_1.POD_STALE_RECYCLE_COOLDOWN_MS};F=setInterval(()=>{if(s.stopped()||A.size===0||(ce(),!types_1.POD_RECYCLE_ENABLED))return;ye();const r=Date.now();for(const[n,t]of A){const o=M.get(t.key);if(o?.frontend.frozen)continue;const a=o?.sourceChange?.changedAt??0,i=x.get(t.key)??0;(0,lifecycle_1.lensFrontendStale)(t.spawnedAt,i,a,r,e)&&((z.get(t.key)??0)>=a||q.has(t.key)||(q.add(t.key),(async()=>{try{const l=o?.sourceChange,E=l&&!l.truncated?[...l.added,...l.removed].map(v=>path.resolve(t.workspaceRoot,v)):[],g=types_1.LENS_WATCHER_PROBE_ENABLED&&t.port!==void 0?(0,lifecycle_1.lensWatcherVerdict)(await ne(t.port),a,l?.windowMs??types_1.POD_STALE_SCAN_MS+types_1.POD_RECYCLE_SETTLE_MS,E):"unknown";if(g==="heard"){z.set(t.key,a),console.log(`[gateway] stale source set: lens app ${t.project} watcher CONFIRMED the change \u2014 no recycle, HMR intact.`),p("info",`stale check: ${t.project} watcher confirmed \u2014 no recycle`,`cluster-lens-app:${t.project}`,{kind:"pod-stale-verified",project:t.project},void 0,t.bus);return}if(g==="unknown"&&types_1.LENS_WATCHER_UNVERIFIED==="keep"){console.log(`[gateway] stale source set: lens app ${t.project} unverifiable (no watcher testimony) \u2014 keeping it (LENSMCP_LENS_WATCHER_UNVERIFIED=keep).`);return}if(n.exitCode!==null||n.signalCode!==null)return;x.set(t.key,Date.now());const d=M.get(t.key);if(types_1.LENS_RESTART_MODE==="rolling"&&d){console.log(`[gateway] stale refresh: lens app ${t.key} (stale-source-set) \u2014 watcher ${g==="missed"?"missed the exact path change":"unverifiable"}; preparing a standby without dropping traffic.`),p("warning",`stale refresh: ${t.project} (stale-source-set)`,`cluster-lens-app:${t.project}`,{kind:"pod-refresh",wsKey:d.wsKey,project:t.project,reason:"stale-source-set",watcher:g,added:l?.added,removed:l?.removed},void 0,t.bus),await ee(d,"stale-source-set");return}t.listening=!1,console.log(`[gateway] zombie recycle: lens app ${t.project} (stale-source-set) \u2014 watcher ${g==="missed"?"SILENT across the change":"unverifiable"}; restarting it`),p("warning",`zombie recycle: ${t.project} (stale-source-set)`,`cluster-lens-app:${t.project}`,{kind:"pod-recycle",project:t.project,reason:"stale-source-set",watcher:g},void 0,t.bus);const $=(0,hmr_reload_1.broadcastFullReload)(s,t.key);$>0&&console.log(`[gateway] \u2192 told ${$} open tab(s) to reload (stale optimize-dep generation)`),signalChild(n,"SIGTERM"),setTimeout(()=>{n.exitCode===null&&n.signalCode===null&&(console.log(`[gateway] zombie recycle: lens app ${t.project} ignored SIGTERM for ${Math.round(types_1.LENS_RECYCLE_KILL_GRACE_MS/1e3)}s \u2014 escalating to SIGKILL.`),signalChild(n,"SIGKILL"))},types_1.LENS_RECYCLE_KILL_GRACE_MS).unref?.()}finally{q.delete(t.key)}})()))}},Math.min(types_1.POD_STALE_SCAN_MS,15e3)),F.unref?.()},"startLensSweeper"),Re=c(async()=>{const e=[...new Map(s.routes.filter(t=>t.lens).map(t=>[t.project,t.lens])).values()],r=f.dashboard!==!1,n=f.mcp!==!1&&e.length>0;if(r){const t=(0,lens_frontend_1.findDashboardBundle)(s.root);if(!t)console.warn("[gateway] lens dashboard bundle not found \u2014 skipping. Install the self-contained CLI: `npm i -D lensmcp` (it ships `bundled/dashboard.js`), or `yarn nx build @lensmcp/lensmcp-mcp` in-repo.");else{const o=(0,scope_1.readLensScope)(s.root),a=await B(f.dashboardPort??o.dashboardPort,J),i=f.lensHost??"lensmcp.local",l=o.basePath;s.registry.appendRoutes(s.wsKey,[{host:i,prefix:l,project:observability_1.LENS_DASHBOARD_PROJECT,target:`http://localhost:${a}`}]),s.rebuildRoutes(),(0,workspace_registry_1.registerWorkspace)({key:o.key,root:s.root,base:l,pid:process.pid,procStamp:(0,workspace_registry_1.processStamp)(process.pid),updatedAt:new Date().toISOString()}),console.log(`[gateway] starting lens dashboard \u2192 http://localhost:${a} (routed at https://${i}${l}/)`),p("info",`lens dashboard up: ${i}${l} \u2192 :${a}`,"cluster-lens-dashboard",{kind:"lens-dashboard-up",host:i,port:a,base:l}),k("lens-dashboard",(0,process_name_1.namedExecPath)((0,process_name_1.processName)("lensmcp",o.key,"dashboard")),[t],{LENSMCP_EVENT_FILE:s.eventFile,LENSMCP_PROCESS_ROLE:"dashboard",LENSMCP_DASHBOARD_PORT:String(a),LENSMCP_DASHBOARD_BASE:l,LENSMCP_REPLAY_WORKSPACE:o.key,LENSMCP_GATEWAY_PORTS:b,...H},!1,void 0,void 0,a)}}if(n){const t=(0,lens_frontend_1.findMcpBundle)(s.root);if(!t)console.warn("[gateway] MCP server bundle not found \u2014 skipping (lens apps will still publish to the bus; an external `lensmcp mcp` can read it). Install: `npm i -D lensmcp`.");else{const o=(0,scope_1.readLensScope)(s.root),a=Number(process.env.LENSMCP_PORT??o.mcpHttpPort),i=c(()=>{console.log(`[gateway] starting lens MCP server on 127.0.0.1:${a} (${t})`),k("lens-mcp",(0,process_name_1.namedExecPath)((0,process_name_1.processName)("lensmcp",o.key,"mcp")),[t],{LENSMCP_EVENT_FILE:s.eventFile,LENSMCP_PROCESS_ROLE:"mcp",LENSMCP_TRANSPORT:process.env.LENSMCP_TRANSPORT??"http",LENSMCP_PORT:String(a),LENSMCP_WORKSPACE_KEY:o.key,LENSMCP_REPLAY_WORKSPACE:o.key,LENSMCP_WORKSPACE_ROOT:s.root},!1,void 0,void 0,a)},"spawnMcp");await w(a)?i():(console.warn(`[gateway] lens MCP port :${a} is already served \u2014 an external lensmcp server (a shared daemon?) owns this workspace's MCP; not spawning a second. Re-probing every ${Math.round(types_1.LENS_PARKED_PORT_REPROBE_MS/1e3)}s; will take over if it frees.`),p("info",`lens MCP served externally on :${a} \u2014 gateway parked its own`,"cluster-lens-child:lens-mcp",{kind:"lens-child-up",project:"lens-mcp",label:"lens-mcp",port:a,external:!0}),re("lens-mcp",a,i))}}for(const t of e){if(t.started)continue;t.started=!0;const o=t.port,a=(s.registry.get(s.wsKey)?.routes??s.routes).filter(E=>E.lens?.project===t.project),i=await B(t.port,T);for(const E of a)E.lens&&(E.lens.port=i),E.target=`http://localhost:${i}`;t.port=i;const l=se({wsKey:s.wsKey,replayWorkspace:s.wsKey,project:t.project,workspaceRoot:s.root,projectRoot:t.projectRoot,eventFile:s.eventFile,routes:a,frontend:t,desiredPort:o});try{ie(l,i),p("info",`lens app started: ${t.project} (vite :${t.port})`,`cluster-lens-app:${t.project}`,{kind:"lens-app-up",project:t.project,port:t.port})}catch(E){T.delete(i),l.state="failed",console.error(`[gateway] lens app ${t.project}: ${E.message}`)}}Le()},"bootSingletonsAndApps"),Ce=c(async e=>{if(f.dashboard===!1)return;const r=(0,lens_frontend_1.findDashboardBundle)(s.root);if(!r)return;const n=(0,scope_1.readLensScope)(e.root),t=f.lensHost??"lensmcp.local",o=n.basePath,a=await B(n.dashboardPort,J),i=`lens-dashboard:${e.wsKey}`,l=path.join(e.root,".lensmcp","events.jsonl");C.delete(i);const E=`http://localhost:${a}`;s.registry.appendRoutes(e.wsKey,[{host:t,prefix:o,project:observability_1.LENS_DASHBOARD_PROJECT,target:E}]),(0,workspace_registry_1.registerWorkspace)({key:e.wsKey,root:e.root,base:o,pid:process.pid,procStamp:(0,workspace_registry_1.processStamp)(process.pid),updatedAt:new Date().toISOString(),...e.instance?{instance:{name:e.instance.name,baseKey:e.instance.baseKey,apex:e.instance.apex}}:{}}),console.log(`[gateway] hosting dashboard for workspace '${e.wsKey}' \u2192 http://localhost:${a} (routed at https://${t}${o}/)`),p("info",`lens dashboard up: ${t}${o} \u2192 :${a}`,"cluster-lens-dashboard",{kind:"lens-dashboard-up",host:t,port:a,base:o});const g=(0,process_name_1.namedExecPath)((0,process_name_1.processName)("lensmcp",e.wsKey,"dashboard")),d={LENSMCP_EVENT_FILE:l,LENSMCP_PROCESS_ROLE:"dashboard",LENSMCP_DASHBOARD_PORT:String(a),LENSMCP_DASHBOARD_BASE:o,LENSMCP_WS_KEY:e.wsKey,LENSMCP_HOSTED_GUEST:"1",LENSMCP_REPLAY_WORKSPACE:e.instance?.baseKey??e.wsKey,...e.sockNs?{LENSMCP_SOCK_NS:e.sockNs}:{},LENSMCP_GATEWAY_PORTS:b,...H};let $=!1,v=!1;const y=c(()=>{const S=m.get(i);S&&V(S),m.delete(i)},"retireHolder"),u=(0,hosted_dashboard_1.createHostedDashboard)(e.wsKey,{idleMs:(0,hosted_dashboard_1.dashboardIdleMs)(),start:c(async()=>{C.delete(i),v&&await waitForPortFree(a,types_1.PORT_FREE_WAIT_MS,{isPortFree:w,intervalMs:types_1.PORT_FREE_POLL_MS}),!($||s.stopped())&&k(i,g,[r],d,!1,void 0,e.root,a)},"start"),stop:c(()=>{v=!0,C.add(i),y()},"stop"),listening:c(()=>probePortListening(a,Math.min(500,types_1.LENS_PROBE_TIMEOUT_MS)),"listening"),servicesUp:c(()=>(s.registry.get(e.wsKey)?.services??[]).some(S=>S.state!=="down"),"servicesUp")});return W.set(E,u),fe(),u.tick(),()=>{$=!0,u.dispose(),W.get(E)===u&&W.delete(E),C.add(i),J.delete(a),(0,workspace_registry_1.unregisterWorkspace)(e.wsKey),y()}},"hostWorkspaceDashboard"),Me=c(async e=>{const r=new Map;for(const o of e.routes){if(!o.lens)continue;const a=r.get(o.lens.project)??[];a.push(o),r.set(o.lens.project,a)}if(r.size===0)return()=>{};const n=path.join(e.root,".lensmcp","events.jsonl"),t=[];for(const[o,a]of r){const i=a[0].lens;if(i.started)continue;const l=await B(i.port,T),E=i.port;for(const d of a)d.lens.started=!0,d.lens.port=l,d.target=`http://localhost:${l}`;const g=se({wsKey:e.wsKey,replayWorkspace:e.instance?.baseKey??e.wsKey,project:o,workspaceRoot:e.root,projectRoot:i.projectRoot,eventFile:n,routes:a,frontend:i,desiredPort:E});t.push(g),console.log(`[gateway] hosting lens app '${o}' of '${e.wsKey}' \u2192 vite :${l}`);try{ie(g,l),p("info",`lens app started: ${e.wsKey}/${o} (vite :${l})`,`cluster-lens-app:${e.wsKey}:${o}`,{kind:"lens-app-up",project:o,port:l},void 0,n)}catch(d){T.delete(l),g.state="failed",console.error(`[gateway] lens app ${e.wsKey}/${o}: ${d.message}`)}}return()=>{for(const o of t){o.disposed=!0;for(const a of[...o.generations])G(a,!0);for(const a of o.routes)a.lens&&K.delete(a.lens);K.delete(o.frontend),x.delete(o.key),z.delete(o.key),q.delete(o.key),M.delete(o.key)}}},"hostWorkspaceApps"),$e=c(async(e=2500)=>{F&&(clearInterval(F),F=void 0),I&&(clearInterval(I),I=void 0);const r=[...j];for(const o of r)signalChild(o,"SIGTERM");const n=c(o=>o.exitCode===null&&o.signalCode===null,"alive"),t=Date.now()+e;for(;Date.now()<t&&r.some(n);)await new Promise(o=>setTimeout(o,100));for(const o of r)n(o)&&signalChild(o,"SIGKILL")},"reapAll"),ce=c(()=>Pe({graceMs:types_1.LENS_PROBE_GRACE_MS,failureThreshold:types_1.LENS_PROBE_FAILS,cooldownMs:types_1.LENS_PROBE_COOLDOWN_MS,neverListenedGraceMs:types_1.LENS_PROBE_BOOT_GRACE_MS},types_1.LENS_PROBE_ENABLED),"probeLensFrontends");return{spawnManagedChild:k,bootSingletonsAndApps:Re,hostWorkspaceDashboard:Ce,hostWorkspaceApps:Me,probeLensFrontends:ce,reapAll:$e}}L(createLensChildren,"createLensChildren"),c(createLensChildren,"createLensChildren");
1
+ "use strict";var Ae=Object.defineProperty;var P=(s,g)=>Ae(s,"name",{value:g,configurable:!0});var ke=Object.defineProperty,c=P((s,g)=>ke(s,"name",{value:g,configurable:!0}),"c");Object.defineProperty(exports,"__esModule",{value:!0}),exports.probePortFree=probePortFree,exports.probePortListening=probePortListening,exports.probeWatcherHealth=probeWatcherHealth,exports.waitForPortFree=waitForPortFree,exports.viteArgPort=viteArgPort,exports.describeChildExit=describeChildExit,exports.signalChild=signalChild,exports.claimPort=claimPort,exports.createLensChildren=createLensChildren;const tslib_1=require("tslib"),fs=tslib_1.__importStar(require("node:fs")),net=tslib_1.__importStar(require("node:net")),path=tslib_1.__importStar(require("node:path")),node_child_process_1=require("node:child_process"),lens_frontend_1=require("@lensmcp/nx-plugin/lens-frontend"),hmr_reload_1=require("./hmr-reload"),own_log_1=require("./own-log"),process_name_1=require("../../../process-name"),pod_env_1=require("./pod-env"),control_1=require("./control"),scope_1=require("./scope"),workspace_registry_1=require("./workspace-registry"),lifecycle_1=require("./lifecycle"),types_1=require("./types"),observability_1=require("./observability"),hosted_dashboard_1=require("./hosted-dashboard"),HEAL_BASE_MS=1500,HEAL_MAX_MS=3e4,HEAL_HEALTHY_MS=2e4,DASHBOARD_SWEEP_MS=15e3;function tryBind(s,g){return new Promise(h=>{const _=net.createServer();_.unref(),_.once("error",p=>{const w=p.code??"";h(w==="EADDRINUSE"||w==="EACCES"?"in-use":"unavailable")}),_.listen(g===void 0?{port:s}:{port:s,host:g},()=>_.close(()=>h("free")))})}P(tryBind,"tryBind"),c(tryBind,"tryBind");async function probePortFree(s){for(const g of[void 0,"0.0.0.0","127.0.0.1","::1"])if(await tryBind(s,g)==="in-use")return!1;return!0}P(probePortFree,"probePortFree"),c(probePortFree,"probePortFree");function probeConnect(s,g,h){return new Promise(_=>{let p=!1;const w=net.createConnection({host:s,port:g});w.unref();const m=setTimeout(()=>L(!1),h);m.unref?.();function L(G){p||(p=!0,clearTimeout(m),w.destroy(),_(G))}P(L,"C"),c(L,"finish"),w.once("connect",()=>L(!0)),w.once("error",()=>L(!1))})}P(probeConnect,"probeConnect"),c(probeConnect,"probeConnect");async function probePortListening(s,g=1e3){return await probeConnect("127.0.0.1",s,g)?!0:probeConnect("::1",s,g)}P(probePortListening,"probePortListening"),c(probePortListening,"probePortListening");async function probeWatcherHealth(s,g=1500){try{const h=new AbortController,_=setTimeout(()=>h.abort(),g);_.unref?.();try{const p=await fetch(`http://127.0.0.1:${s}/__lensmcp/watcher-health`,{signal:h.signal});if(!p.ok)return null;const w=await p.json();if(typeof w?.lastFsSetEventAt!="number")return null;const m=Array.isArray(w.recentEvents)?w.recentEvents.filter(L=>L&&typeof L.path=="string"&&typeof L.at=="number"&&typeof L.sequence=="number"&&["add","addDir","unlink","unlinkDir"].includes(L.kind)):[];return{schemaVersion:w.schemaVersion===2?2:1,ready:w.ready!==!1,sequence:typeof w.sequence=="number"?w.sequence:0,lastFsSetEventAt:w.lastFsSetEventAt,fsSetEvents:typeof w.fsSetEvents=="number"?w.fsSetEvents:0,recentEvents:m}}finally{clearTimeout(_)}}catch{return null}}P(probeWatcherHealth,"probeWatcherHealth"),c(probeWatcherHealth,"probeWatcherHealth");const sleepUnref=c(s=>new Promise(g=>{setTimeout(g,s).unref?.()}),"sleepUnref");async function waitForPortFree(s,g,h={}){const _=h.isPortFree??probePortFree,p=Math.max(1,h.intervalMs??types_1.PORT_FREE_POLL_MS),w=Date.now()+Math.max(0,g);for(;;){if(await _(s))return!0;const m=w-Date.now();if(m<=0)return!1;await sleepUnref(Math.min(p,m))}}P(waitForPortFree,"waitForPortFree"),c(waitForPortFree,"waitForPortFree");function viteArgPort(s){const g=c(h=>Number.isInteger(h)&&h>0&&h<65536?h:void 0,"valid");for(let h=0;h<s.length;h+=1){const _=s[h];if(_==="--port")return g(Number(s[h+1]));if(_.startsWith("--port="))return g(Number(_.slice(7)))}}P(viteArgPort,"viteArgPort"),c(viteArgPort,"viteArgPort");function describeChildExit(s){return s.signalCode?`killed by ${s.signalCode}`:s.exitCode===null?"exit status unknown":`exit code ${s.exitCode}`}P(describeChildExit,"describeChildExit"),c(describeChildExit,"describeChildExit");function signalChild(s,g){if(s.pid===void 0)return!1;try{return s.kill(g)}catch{return!1}}P(signalChild,"signalChild"),c(signalChild,"signalChild");async function claimPort(s,g,h,_){let p=s;for(;g.has(p)||_?.has(p)||!await h(p);)p+=1;return g.add(p),p}P(claimPort,"claimPort"),c(claimPort,"claimPort");function createLensChildren(s,g,h,_){const{emit:p}=g,w=_?.isPortFree??probePortFree,m=(h.ports?.length?h.ports:[443]).join(","),L=(0,control_1.clusterVersion)(),G={LENSMCP_GATEWAY_PID:String(process.pid),...L?{LENSMCP_GATEWAY_VERSION:L}:{}},ne=_?.probeWatcherHealth??probeWatcherHealth,j=[],Y=new Map,k=new Map,x=new Map,z=new Map,q=new Set;let F;const A=new Map,R=new Set,X=new Set,J=new Set,W=new Map;s.hostedDashboards=W;let I;const fe=c(()=>{I||(I=setInterval(()=>{if(!s.stopped())for(const e of W.values())e.tick()},DASHBOARD_SWEEP_MS),I.unref?.())},"startDashboardSweeper"),T=new Set,M=new Map,K=new WeakMap,U=new Set,re=c((e,r,n)=>{if(U.has(e))return;U.add(e);const t=setInterval(()=>{(async()=>{if(s.stopped()||R.has(e)){clearInterval(t),U.delete(e);return}await w(r)&&(clearInterval(t),U.delete(e),console.log(`[gateway] lens child ${e}: :${r} freed \u2014 respawning.`),n())})().catch(()=>{})},types_1.LENS_PARKED_PORT_REPROBE_MS);t.unref?.()},"parkUntilPortFree"),B=c(async(e,r,n)=>{const t=await claimPort(e,r,w,n?.reserved);return t!==e&&(n?.heldBy?console.log(`[gateway] handoff: :${e} is held by ${n.heldBy} \u2014 replacement on :${t}.`):console.warn(`[gateway] port ${e} is unavailable (another process holds it \u2014 an orphan from a crashed gateway?) \u2014 using ${t} instead.`)),t},"claimFreePort"),ge=c((e,r,n)=>{const t=n?.LENSMCP_FRONTEND_KEY,o=Number(n?.LENSMCP_FRONTEND_GENERATION);if(!t||!Number.isFinite(o))return;const a=[...M.get(t)?.generations??[]].find(i=>i.generation===o);a&&(e.endsWith(":vite")?a.vite=r:e.endsWith(":browser-capture")&&(a.capture=r))},"attachRespawnedGenerationChild"),V=c(e=>{e.exitCode!==null||e.signalCode!==null||e.pid===void 0||(X.add(e),signalChild(e,"SIGTERM"),setTimeout(()=>{e.exitCode===null&&e.signalCode===null&&signalChild(e,"SIGKILL")},types_1.LENS_RECYCLE_KILL_GRACE_MS).unref?.())},"retireChild"),we=c((e,r)=>{const n=A.get(e);!n||n===r||n.exitCode!==null||n.signalCode!==null||(console.warn(`[gateway] lens child ${e}: a replacement took the label \u2014 retiring the previous child (pid ${n.pid??"?"}).`),V(n))},"retireLabelHolder"),D=c((e,r,n,t,o=!1,a,i,l)=>{const f=Date.now(),E=(0,own_log_1.gatewayLogTakeover)()!==void 0,d=(0,node_child_process_1.spawn)(r,n,{cwd:i??s.root,env:{...(0,pod_env_1.podBaseEnv)(process.env,s.root,i??s.root),...t??{},LENSMCP_PARENT_PID:String(process.pid)},stdio:E?["inherit","pipe","pipe"]:"inherit"});E&&(d.stdout?.on("data",S=>process.stdout.write(S)),d.stderr?.on("data",S=>process.stderr.write(S))),j.push(d),we(e,d),A.set(e,d),ge(e,d,t);const N=e==="vite"||e.endsWith(":vite"),C=typeof t?.LENSMCP_EVENT_FILE=="string"?t.LENSMCP_EVENT_FILE:void 0,v=C&&C!==s.eventFile?C:void 0,u=N?viteArgPort(n):l;N&&k.set(d,{key:t?.LENSMCP_FRONTEND_KEY??`${i??s.root}:${t?.LENSMCP_PROJECT??"app"}`,project:t?.LENSMCP_PROJECT??"app",workspaceRoot:i??s.root,spawnedAt:f,port:u,probeFails:0,listening:!1,generation:Number(t?.LENSMCP_FRONTEND_GENERATION??0),role:t?.LENSMCP_FRONTEND_ROLE==="replacement"?"replacement":"active",...v?{bus:v}:{}});const y=e==="lens-mcp"?"lens-mcp":e==="lens-dashboard"||e.startsWith("lens-dashboard:")?"lens-dashboard":void 0;return y&&u!==void 0&&(p("info",`lens child starting: ${y} (:${u})`,`cluster-lens-child:${y}`,{kind:"lens-child-starting",project:y,label:e,pid:d.pid,port:u},void 0,v),(async()=>{const S=Date.now()+types_1.LENS_REPLACEMENT_READY_MS;for(;!s.stopped()&&Date.now()<S;){if(d.exitCode!==null||d.signalCode!==null||R.has(e))return;if(await probePortListening(u,Math.min(500,types_1.LENS_PROBE_TIMEOUT_MS))){p("info",`lens child up: ${y} (:${u})`,`cluster-lens-child:${y}`,{kind:"lens-child-up",project:y,label:e,pid:d.pid,port:u},void 0,v);return}await sleepUnref(150)}})().catch(()=>{})),d.on("error",S=>{if(d.pid!==void 0){console.warn(`[gateway] lens child ${e}: ${S.message}`);return}const $=j.indexOf(d);$>=0&&j.splice($,1),A.get(e)===d&&A.delete(e),k.delete(d),X.delete(d),console.error(`[gateway] lens child ${e} failed to spawn (${S.message}) \u2014 not started, not retried.`)}),d.on("exit",(S,$)=>{const pe=j.indexOf(d);pe>=0&&j.splice(pe,1),A.get(e)===d&&A.delete(e);const O=k.get(d);if(k.delete(d),X.delete(d))return;const Ne=R.delete(e);if(s.stopped()||Ne||(y?p("warning",`lens child exited: ${y}`,`cluster-lens-child:${y}`,{kind:"lens-child-exit",project:y,label:e,pid:d.pid,code:S,signal:$},void 0,v):O&&p("warning",`lens frontend exited: ${O.project}`,`cluster-lens-child:${O.project}`,{kind:"lens-child-exit",project:O.project,label:e,pid:d.pid,code:S,signal:$,generation:O.generation,port:O.port,ranMs:Date.now()-f},void 0,v),O&&ye(d,O)))return;const ue=Date.now()-f,b=Y.get(e)??{attempts:0,portConflicts:0};(async()=>{const me=u!==void 0&&!await w(u),Ee=(0,lifecycle_1.isPortConflictExit)({code:S,signal:$,ranMs:ue,portHeld:me},{fastFailMs:types_1.CHILD_START_FAIL_MS});if(Ee&&b.portConflicts<types_1.MAX_PORT_CONFLICT_RETRIES)b.portConflicts+=1,Y.set(e,b),console.warn(`[gateway] lens child ${e} lost the :${u} bind race (EADDRINUSE, code=${S}); waiting for the port, then retrying (port-retry ${b.portConflicts}/${types_1.MAX_PORT_CONFLICT_RETRIES}; crash budget untouched).`);else if(Ee){b.portConflicts=0,Y.set(e,b),console.warn(`[gateway] lens child ${e}: :${u} persistently held after ${types_1.MAX_PORT_CONFLICT_RETRIES} bind races \u2014 another server owns it (an external/shared daemon?). Parking; re-probing every ${Math.round(types_1.LENS_PARKED_PORT_REPROBE_MS/1e3)}s, will respawn if it frees.`),p("warning",`lens child parked: ${e} (:${u} held externally)`,`cluster-lens-child:${e}`,{kind:"lens-child-parked",label:e,port:u}),re(e,u,()=>D(e,r,n,t,o,a,i,l));return}else{b.portConflicts=0,ue>=HEAL_HEALTHY_MS&&(b.attempts=0);const he=Math.min(HEAL_MAX_MS,HEAL_BASE_MS*2**b.attempts);b.attempts+=1,Y.set(e,b),console.warn(`[gateway] lens child ${e} exited (code=${S} sig=${$}); auto-healing in ${Math.round(he/1e3)}s (attempt ${b.attempts}).`),await sleepUnref(he)}s.stopped()||R.has(e)||(u!==void 0&&!await waitForPortFree(u,types_1.PORT_FREE_WAIT_MS,{isPortFree:w,intervalMs:types_1.PORT_FREE_POLL_MS})&&console.warn(`[gateway] lens child ${e}: :${u} still held after ${Math.round(types_1.PORT_FREE_WAIT_MS/1e3)}s \u2014 spawning anyway.`),!(s.stopped()||R.has(e))&&D(e,r,n,t,o,a,i,l))})().catch(()=>{})}),d},"spawnManagedChild"),se=c(e=>{const r=`${e.wsKey}:${e.project}`,n=M.get(r);if(n)return n;const t={key:r,...e,sourceDirs:e.frontend.sourceRoots?.length?e.frontend.sourceRoots:[e.projectRoot],generation:0,state:"starting",generations:new Set,disposed:!1};M.set(r,t);for(const o of e.routes)o.lens&&(o.lens.workspaceKey??=e.wsKey,K.set(o.lens,t));return e.frontend.workspaceKey??=e.wsKey,K.set(e.frontend,t),t},"registerFrontend"),_e=c(e=>{if(!types_1.LENS_WATCH_SCOPE_ENABLED)return{};const r=path.resolve(e.projectRoot),n=e.sourceDirs.map(t=>path.resolve(t)).filter(t=>t!==r);return n.length>0?{LENSMCP_WATCH_DIRS:n.join(path.delimiter)}:{}},"lensWatchScopeEnv"),ae=c((e,r,n)=>{const t=++e.generation,o=`${e.key}:g${t}:`,a=`${o}vite`,i=`${o}browser-capture`;R.delete(a),R.delete(i);const l=c((d,N,C,v,u,y)=>D(d,N,C,v,u,y,e.workspaceRoot),"spawnInRoot"),f=(0,lens_frontend_1.spawnLensFrontend)({projectRoot:e.projectRoot,workspaceRoot:e.workspaceRoot,project:e.project,eventFile:e.eventFile,port:r,chrome:!0,headless:!0,viteEnv:{...e.frontend.env??{},...e.frontend.frozen?{LENSMCP_FREEZE:"1"}:{},LENSMCP_PROJECT:e.project,...e.replayWorkspace?{LENSMCP_REPLAY_WORKSPACE:e.replayWorkspace}:{},LENSMCP_FRONTEND_KEY:e.key,LENSMCP_FRONTEND_GENERATION:String(t),LENSMCP_FRONTEND_ROLE:n,..._e(e),NX_DAEMON:"false",NX_ISOLATE_PLUGINS:"false"},labelPrefix:o,log:c(d=>console.log(d),"log")},l),E={ownerKey:e.key,generation:t,port:r,labelPrefix:o,vite:f?.vite??A.get(a),capture:A.get(i)};return e.generations.add(E),E},"spawnFrontendGeneration"),H=c((e,r)=>{if(!e)return;M.get(e.ownerKey)?.generations.delete(e);const n=[[`${e.labelPrefix}browser-capture`,e.capture],[`${e.labelPrefix}vite`,e.vite]];for(const[t,o]of n)R.add(t),o&&V(o);r&&T.delete(e.port)},"terminateGeneration"),Se=c(async e=>{const r=Date.now()+types_1.LENS_REPLACEMENT_READY_MS;for(;!s.stopped()&&Date.now()<r;){const n=e.vite;if(!n||n.exitCode!==null||n.signalCode!==null)return!1;if(await probePortListening(e.port,Math.min(500,types_1.LENS_PROBE_TIMEOUT_MS))){const t=await ne(e.port);if(!t||t.ready)return!0}await sleepUnref(150)}return!1},"waitForGenerationReady"),Z=c(async e=>{const r=e?.vite;return!!(e&&r&&r.exitCode===null&&r.signalCode===null&&await probePortListening(e.port,Math.min(500,types_1.LENS_PROBE_TIMEOUT_MS)))},"generationIsServing"),Q=c(e=>!e.disposed&&!s.stopped()&&M.get(e.key)===e,"frontendIsCurrent"),ee=c((e,r)=>{if(!Q(e))return Promise.resolve(!1);if(e.replacement)return e.replacement;const n=e.active;e.state=n?"replacing":"starting",e.reason=r,e.startedAt=Date.now();const t=(async()=>{let o,a;const i=Date.now();try{const l=new Set;for(const u of M.values())u!==e&&l.add(u.desiredPort);const f=n&&n.port===e.desiredPort?`g${n.generation}`:void 0,E=await B(e.desiredPort,T,{reserved:l,heldBy:f});if(a=E,!Q(e))return T.delete(E),!1;o=ae(e,E,"replacement"),e.candidate=o;const d=await Z(n);console.log(`[gateway] lens handoff start: ${e.key} g${n?.generation??0}\u2192g${o.generation} :${n?.port??"down"}\u2192:${E} reason=${r}`),p("info",`lens handoff starting: ${e.project}`,`cluster-lens-app:${e.project}`,{kind:"lens-handoff-start",wsKey:e.wsKey,project:e.project,reason:r,generation:o.generation,oldPort:n?.port,newPort:E,oldServing:d},void 0,e.eventFile===s.eventFile?void 0:e.eventFile);const N=await Se(o);if(!Q(e))return H(o,!0),e.candidate=void 0,!1;if(!N){H(o,!0),e.candidate=void 0;const u=await Z(n);return e.state=u?"ready":"failed",u&&(e.reason=void 0,e.startedAt=void 0),console.error(`[gateway] lens handoff failed: ${e.key} g${o.generation} did not become ready within ${types_1.LENS_REPLACEMENT_READY_MS}ms; ${e.state==="ready"?"old generation kept serving":"no active generation"}.`),p("warning",`lens handoff failed: ${e.project}`,`cluster-lens-app:${e.project}`,{kind:"lens-handoff-failed",wsKey:e.wsKey,project:e.project,reason:r,generation:o.generation,port:E,durationMs:Date.now()-i,oldKept:u},void 0,e.eventFile===s.eventFile?void 0:e.eventFile),!1}for(const u of e.routes)u.target=`http://localhost:${o.port}`,u.lens&&(u.lens.port=o.port);e.frontend.port=o.port,e.active=o,e.candidate=void 0,e.state="ready",e.reason=void 0,e.startedAt=void 0;const C=o.vite?k.get(o.vite):void 0;C&&(C.role="active",C.listening=!0);const v=(0,hmr_reload_1.broadcastFullReload)(s,e.key);if(console.log(`[gateway] lens handoff ready: ${e.key} g${o.generation} :${o.port} in ${Date.now()-i}ms; draining g${n?.generation??0}${v>0?`; reloading ${v} tab(s)`:""}.`),p("info",`lens handoff complete: ${e.project}`,`cluster-lens-app:${e.project}`,{kind:"lens-handoff-complete",wsKey:e.wsKey,project:e.project,reason:r,generation:o.generation,oldPort:n?.port,newPort:o.port,durationMs:Date.now()-i,reloadedTabs:v},void 0,e.eventFile===s.eventFile?void 0:e.eventFile),n){const u=`${n.labelPrefix}browser-capture`;R.add(u),n.capture&&V(n.capture),setTimeout(()=>H(n,!0),types_1.LENS_REPLACEMENT_DRAIN_MS).unref?.()}return!0}catch(l){H(o,!0),!o&&a!==void 0&&T.delete(a),e.candidate=void 0;const f=await Z(n);e.state=f?"ready":"failed",f&&(e.reason=void 0,e.startedAt=void 0);const E=l.message;return console.error(`[gateway] lens handoff failed: ${e.key}: ${E}`),p("warning",`lens handoff failed: ${e.project}`,`cluster-lens-app:${e.project}`,{kind:"lens-handoff-failed",wsKey:e.wsKey,project:e.project,reason:r,generation:o?.generation??e.generation,port:o?.port??a,durationMs:Date.now()-i,oldKept:f,error:E},void 0,e.eventFile===s.eventFile?void 0:e.eventFile),!1}finally{e.replacement=void 0}})();return e.replacement=t,t},"rollFrontend"),ie=c((e,r)=>{e.active=ae(e,r,"active"),e.state="starting",e.startedAt=Date.now()},"spawnInitialFrontend"),ye=c((e,r)=>{const n=M.get(r.key);return!n||types_1.LENS_RESTART_MODE==="in-place"?!1:(n.candidate?.vite===e||n.active?.vite!==e||(n.state="starting",n.reason="child-exit",n.startedAt=Date.now(),console.warn(`[gateway] lens frontend exited: ${n.key} g${r.generation} :${r.port} (${describeChildExit(e)}); starting an alternate-port replacement.`),ee(n,"child-exit")),!0)},"handleManagedViteExit");s.lensSupervisor=types_1.LENS_RESTART_MODE==="rolling"?{status(e){const r=K.get(e);return r?{state:r.state,generation:r.candidate?.generation??r.active?.generation??r.generation,reason:r.reason,startedAt:r.startedAt}:void 0},recover(e,r){const n=K.get(e);return n?ee(n,r):Promise.resolve(!1)}}:void 0;let te=!1,le=0;const ve=c(()=>{te||Date.now()-le<types_1.POD_STALE_SCAN_MS||(te=!0,le=Date.now(),(async()=>{const e=new Map;for(const r of[...M.values()]){if(s.stopped())return;let n=e.get(r.workspaceRoot);if(!n){const E=(0,scope_1.readSourceSetOptions)(r.workspaceRoot);n={pass:(0,lifecycle_1.sourceScanPass)(r.workspaceRoot,E.exclude,{ignoreTests:E.ignoreTests}),startedAt:Date.now()},e.set(r.workspaceRoot,n)}const t=n.startedAt,o=await n.pass.snapshot(r.sourceDirs);if(M.get(r.key)!==r)continue;const a=r.sourceSnapshot,i=r.sourceScanStartedAt;if(r.sourceSnapshot=o,r.sourceScanStartedAt=t,!a)continue;const l=Date.now(),f=(0,lifecycle_1.diffSourceSets)(a,o,l,(0,lifecycle_1.sourceChangeWindowMs)(l,i,types_1.POD_STALE_SCAN_MS,types_1.POD_RECYCLE_SETTLE_MS));f&&(r.sourceChange=f,p("info",`source file set changed for ${r.key}`,`cluster-lens-app:${r.project}`,{kind:"source-set-changed",scoped:!0,wsKey:r.wsKey,project:r.project,added:f.added,removed:f.removed,truncated:f.truncated},void 0,r.eventFile===s.eventFile?void 0:r.eventFile))}})().catch(()=>{}).finally(()=>{te=!1}))},"scanFrontendSourceSets");let oe=!1;const Pe=c(async(e,r)=>{if(!oe){oe=!0;try{for(const[n,t]of[...k]){if(s.stopped())return;if(t.port===void 0||n.exitCode!==null||n.signalCode!==null)continue;if(await probePortListening(t.port,types_1.LENS_PROBE_TIMEOUT_MS)){if(t.probeFails=0,!t.listening){t.listening=!0;const l=M.get(t.key);l?.active?.vite===n&&(l.state="ready",l.reason=void 0),p("info",`lens app up: ${t.project} (vite :${t.port} listening)`,`cluster-lens-app:${t.project}`,{kind:"service-up",project:t.project,port:t.port},void 0,t.bus)}continue}const o=t.listening?e.graceMs:Math.max(e.graceMs,e.neverListenedGraceMs);if(Date.now()-t.spawnedAt<o){t.probeFails=0;continue}if(!r)continue;t.probeFails+=1;const a=(0,lifecycle_1.lensChildWedged)({spawnedAt:t.spawnedAt,probeFails:t.probeFails,hasListened:t.listening},x.get(t.key)??0,Date.now(),e);if(!a)continue;const i=t.listening?"its listener VANISHED (was up, now refusing)":`it NEVER bound within the ${Math.round(o/1e3)}s boot allowance`;x.set(t.key,Date.now()),t.probeFails=0,t.listening=!1,console.error(`[gateway] wedge recycle: lens app ${t.project} is ALIVE but NOT LISTENING on :${t.port} after ${Math.max(2,e.failureThreshold)} probes \u2014 ${i} \u2014 SIGKILL; a fresh vite is coming.`),p("warning",`wedge recycle: ${t.project} (${a})`,`cluster-lens-app:${t.project}`,{kind:"pod-recycle",project:t.project,reason:a,port:t.port},void 0,t.bus),signalChild(n,"SIGKILL")}}finally{oe=!1}}},"probeLensChildren"),Le=c(()=>{if(F||!types_1.POD_RECYCLE_ENABLED&&!types_1.LENS_PROBE_ENABLED)return;const e={graceMs:types_1.POD_STALE_GRACE_MS,settleMs:types_1.POD_RECYCLE_SETTLE_MS,cooldownMs:types_1.POD_STALE_RECYCLE_COOLDOWN_MS};F=setInterval(()=>{if(s.stopped()||k.size===0||(de(),!types_1.POD_RECYCLE_ENABLED))return;ve();const r=Date.now();for(const[n,t]of k){const o=M.get(t.key);if(o?.frontend.frozen)continue;const a=o?.sourceChange?.changedAt??0,i=x.get(t.key)??0;(0,lifecycle_1.lensFrontendStale)(t.spawnedAt,i,a,r,e)&&((z.get(t.key)??0)>=a||q.has(t.key)||(q.add(t.key),(async()=>{try{const l=o?.sourceChange,f=l&&!l.truncated?[...l.added,...l.removed].map(C=>path.resolve(t.workspaceRoot,C)):[],E=types_1.LENS_WATCHER_PROBE_ENABLED&&t.port!==void 0?(0,lifecycle_1.lensWatcherVerdict)(await ne(t.port),a,l?.windowMs??types_1.POD_STALE_SCAN_MS+types_1.POD_RECYCLE_SETTLE_MS,f):"unknown";if(E==="heard"){z.set(t.key,a),console.log(`[gateway] stale source set: lens app ${t.project} watcher CONFIRMED the change \u2014 no recycle, HMR intact.`),p("info",`stale check: ${t.project} watcher confirmed \u2014 no recycle`,`cluster-lens-app:${t.project}`,{kind:"pod-stale-verified",project:t.project},void 0,t.bus);return}if(E==="unknown"&&types_1.LENS_WATCHER_UNVERIFIED==="keep"){console.log(`[gateway] stale source set: lens app ${t.project} unverifiable (no watcher testimony) \u2014 keeping it (LENSMCP_LENS_WATCHER_UNVERIFIED=keep).`);return}if(n.exitCode!==null||n.signalCode!==null)return;x.set(t.key,Date.now());const d=M.get(t.key);if(types_1.LENS_RESTART_MODE==="rolling"&&d){console.log(`[gateway] stale refresh: lens app ${t.key} (stale-source-set) \u2014 watcher ${E==="missed"?"missed the exact path change":"unverifiable"}; preparing a standby without dropping traffic.`),p("warning",`stale refresh: ${t.project} (stale-source-set)`,`cluster-lens-app:${t.project}`,{kind:"pod-refresh",wsKey:d.wsKey,project:t.project,reason:"stale-source-set",watcher:E,added:l?.added,removed:l?.removed},void 0,t.bus),await ee(d,"stale-source-set");return}t.listening=!1,console.log(`[gateway] zombie recycle: lens app ${t.project} (stale-source-set) \u2014 watcher ${E==="missed"?"SILENT across the change":"unverifiable"}; restarting it`),p("warning",`zombie recycle: ${t.project} (stale-source-set)`,`cluster-lens-app:${t.project}`,{kind:"pod-recycle",project:t.project,reason:"stale-source-set",watcher:E},void 0,t.bus);const N=(0,hmr_reload_1.broadcastFullReload)(s,t.key);N>0&&console.log(`[gateway] \u2192 told ${N} open tab(s) to reload (stale optimize-dep generation)`),signalChild(n,"SIGTERM"),setTimeout(()=>{n.exitCode===null&&n.signalCode===null&&(console.log(`[gateway] zombie recycle: lens app ${t.project} ignored SIGTERM for ${Math.round(types_1.LENS_RECYCLE_KILL_GRACE_MS/1e3)}s \u2014 escalating to SIGKILL.`),signalChild(n,"SIGKILL"))},types_1.LENS_RECYCLE_KILL_GRACE_MS).unref?.()}finally{q.delete(t.key)}})()))}},Math.min(types_1.POD_STALE_SCAN_MS,15e3)),F.unref?.()},"startLensSweeper"),Re=c(async()=>{const e=[...new Map(s.routes.filter(t=>t.lens).map(t=>[t.project,t.lens])).values()],r=h.dashboard!==!1,n=h.mcp!==!1&&e.length>0;if(r){const t=(0,lens_frontend_1.findDashboardBundle)(s.root);if(!t)console.warn("[gateway] lens dashboard bundle not found \u2014 skipping. Install the self-contained CLI: `npm i -D lensmcp` (it ships `bundled/dashboard.js`), or `yarn nx build @lensmcp/lensmcp-mcp` in-repo.");else{const o=(0,scope_1.readLensScope)(s.root),a=await B(h.dashboardPort??o.dashboardPort,J),i=h.lensHost??"lensmcp.local",l=o.basePath;s.registry.appendRoutes(s.wsKey,[{host:i,prefix:l,project:observability_1.LENS_DASHBOARD_PROJECT,target:`http://localhost:${a}`}]),s.rebuildRoutes(),(0,workspace_registry_1.registerWorkspace)({key:o.key,root:s.root,base:l,pid:process.pid,procStamp:(0,workspace_registry_1.processStamp)(process.pid),updatedAt:new Date().toISOString()}),console.log(`[gateway] starting lens dashboard \u2192 http://localhost:${a} (routed at https://${i}${l}/)`),p("info",`lens dashboard up: ${i}${l} \u2192 :${a}`,"cluster-lens-dashboard",{kind:"lens-dashboard-up",host:i,port:a,base:l}),D("lens-dashboard",(0,process_name_1.namedExecPath)((0,process_name_1.processName)("lensmcp",o.key,"dashboard")),[t],{LENSMCP_EVENT_FILE:s.eventFile,LENSMCP_PROCESS_ROLE:"dashboard",LENSMCP_DASHBOARD_PORT:String(a),LENSMCP_DASHBOARD_BASE:l,LENSMCP_REPLAY_WORKSPACE:o.key,LENSMCP_GATEWAY_PORTS:m,...G},!1,void 0,void 0,a)}}if(n){const t=(0,lens_frontend_1.findMcpBundle)(s.root);if(!t)console.warn("[gateway] MCP server bundle not found \u2014 skipping (lens apps will still publish to the bus; an external `lensmcp mcp` can read it). Install: `npm i -D lensmcp`.");else{const o=(0,scope_1.readLensScope)(s.root),a=Number(process.env.LENSMCP_PORT??o.mcpHttpPort),i=c(()=>{console.log(`[gateway] starting lens MCP server on 127.0.0.1:${a} (${t})`),D("lens-mcp",(0,process_name_1.namedExecPath)((0,process_name_1.processName)("lensmcp",o.key,"mcp")),[t],{LENSMCP_EVENT_FILE:s.eventFile,LENSMCP_PROCESS_ROLE:"mcp",LENSMCP_TRANSPORT:process.env.LENSMCP_TRANSPORT??"http",LENSMCP_PORT:String(a),LENSMCP_WORKSPACE_KEY:o.key,LENSMCP_REPLAY_WORKSPACE:o.key,LENSMCP_WORKSPACE_ROOT:s.root},!1,void 0,void 0,a)},"spawnMcp");await w(a)?i():(console.warn(`[gateway] lens MCP port :${a} is already served \u2014 an external lensmcp server (a shared daemon?) owns this workspace's MCP; not spawning a second. Re-probing every ${Math.round(types_1.LENS_PARKED_PORT_REPROBE_MS/1e3)}s; will take over if it frees.`),p("info",`lens MCP served externally on :${a} \u2014 gateway parked its own`,"cluster-lens-child:lens-mcp",{kind:"lens-child-up",project:"lens-mcp",label:"lens-mcp",port:a,external:!0}),re("lens-mcp",a,i))}}for(const t of e){if(t.started)continue;t.started=!0;const o=t.port,a=(s.registry.get(s.wsKey)?.routes??s.routes).filter(f=>f.lens?.project===t.project),i=await B(t.port,T);for(const f of a)f.lens&&(f.lens.port=i),f.target=`http://localhost:${i}`;t.port=i;const l=se({wsKey:s.wsKey,replayWorkspace:s.wsKey,project:t.project,workspaceRoot:s.root,projectRoot:t.projectRoot,eventFile:s.eventFile,routes:a,frontend:t,desiredPort:o});try{ie(l,i),p("info",`lens app started: ${t.project} (vite :${t.port})`,`cluster-lens-app:${t.project}`,{kind:"lens-app-up",project:t.project,port:t.port})}catch(f){T.delete(i),l.state="failed",console.error(`[gateway] lens app ${t.project}: ${f.message}`)}}Le()},"bootSingletonsAndApps"),ce=c(async e=>{if(h.dashboard===!1)return;const r=(0,lens_frontend_1.findDashboardBundle)(s.root);if(!r)return;const n=e.parked===!0,t=(0,scope_1.readLensScope)(e.root),o=h.lensHost??"lensmcp.local",a=t.basePath,i=await B(t.dashboardPort,J),l=n?`lens-dashboard-parked:${e.wsKey}`:`lens-dashboard:${e.wsKey}`,f=path.join(e.root,".lensmcp","events.jsonl");R.delete(l);const E=`http://localhost:${i}`,d=[{host:o,prefix:a,project:observability_1.LENS_DASHBOARD_PROJECT,target:E}];n?(s.registry.setStandalone(e.wsKey,d),console.log(`[gateway] hosting the dashboard of parked worktree '${e.wsKey}' \u2192 http://localhost:${i} (routed at https://${o}${a}/; it starts on a request, nothing else of the worktree does)`),p("info",`lens dashboard of a parked worktree: ${o}${a} \u2192 :${i}`,"cluster-lens-dashboard",{kind:"lens-dashboard-up",host:o,port:i,base:a,parked:!0})):(s.registry.appendRoutes(e.wsKey,d),(0,workspace_registry_1.registerWorkspace)({key:e.wsKey,root:e.root,base:a,pid:process.pid,procStamp:(0,workspace_registry_1.processStamp)(process.pid),updatedAt:new Date().toISOString(),...e.instance?{instance:{name:e.instance.name,baseKey:e.instance.baseKey,apex:e.instance.apex??""}}:{}}),console.log(`[gateway] hosting dashboard for workspace '${e.wsKey}' \u2192 http://localhost:${i} (routed at https://${o}${a}/)`),p("info",`lens dashboard up: ${o}${a} \u2192 :${i}`,"cluster-lens-dashboard",{kind:"lens-dashboard-up",host:o,port:i,base:a}));const N=(0,process_name_1.namedExecPath)((0,process_name_1.processName)("lensmcp",e.wsKey,"dashboard")),C={LENSMCP_EVENT_FILE:f,LENSMCP_PROCESS_ROLE:"dashboard",LENSMCP_DASHBOARD_PORT:String(i),LENSMCP_DASHBOARD_BASE:a,LENSMCP_WS_KEY:e.wsKey,LENSMCP_HOSTED_GUEST:"1",LENSMCP_REPLAY_WORKSPACE:e.instance?.baseKey??e.wsKey,...e.sockNs?{LENSMCP_SOCK_NS:e.sockNs}:{},LENSMCP_GATEWAY_PORTS:m,...G};let v=!1,u=!1;const y=c(()=>{const $=A.get(l);$&&V($),A.delete(l)},"retireHolder"),S=(0,hosted_dashboard_1.createHostedDashboard)(e.wsKey,{idleMs:n?(0,hosted_dashboard_1.dashboardIdleMs)()??hosted_dashboard_1.DEFAULT_DASHBOARD_IDLE_SEC*1e3:(0,hosted_dashboard_1.dashboardIdleMs)(),start:c(async()=>{if(R.delete(l),u&&await waitForPortFree(i,types_1.PORT_FREE_WAIT_MS,{isPortFree:w,intervalMs:types_1.PORT_FREE_POLL_MS}),!(v||s.stopped())){if(n&&!fs.existsSync(e.root))throw new Error(`its checkout ${e.root} is gone`);D(l,N,[r],C,!1,void 0,e.root,i)}},"start"),stop:c(()=>{u=!0,R.add(l),y()},"stop"),listening:c(()=>probePortListening(i,Math.min(500,types_1.LENS_PROBE_TIMEOUT_MS)),"listening"),servicesUp:c(()=>!n&&(s.registry.get(e.wsKey)?.services??[]).some($=>$.state!=="down"),"servicesUp")});return W.set(E,S),fe(),S.tick(),{host:o,base:a,reap:c(()=>{v=!0,S.dispose(),W.get(E)===S&&W.delete(E),R.add(l),J.delete(i),n?s.registry.dropStandalone(e.wsKey,d):(0,workspace_registry_1.unregisterWorkspace)(e.wsKey),y()},"reap")}},"hostDashboard"),Me=c(async e=>(await ce({wsKey:e.wsKey,root:e.root,...e.sockNs?{sockNs:e.sockNs}:{},...e.instance?{instance:e.instance}:{}}))?.reap,"hostWorkspaceDashboard"),Ce=c(async e=>{const r=(0,scope_1.readLensScope)(e.root);if(r.key!==e.key)return;const n=r.sockNs!==e.key?r.sockNs:void 0;return ce({wsKey:e.key,root:e.root,...n?{sockNs:n}:{},instance:{name:e.name,baseKey:e.baseKey},parked:!0})},"hostParkedDashboard"),$e=c(async e=>{const r=new Map;for(const o of e.routes){if(!o.lens)continue;const a=r.get(o.lens.project)??[];a.push(o),r.set(o.lens.project,a)}if(r.size===0)return()=>{};const n=path.join(e.root,".lensmcp","events.jsonl"),t=[];for(const[o,a]of r){const i=a[0].lens;if(i.started)continue;const l=await B(i.port,T),f=i.port;for(const d of a)d.lens.started=!0,d.lens.port=l,d.target=`http://localhost:${l}`;const E=se({wsKey:e.wsKey,replayWorkspace:e.instance?.baseKey??e.wsKey,project:o,workspaceRoot:e.root,projectRoot:i.projectRoot,eventFile:n,routes:a,frontend:i,desiredPort:f});t.push(E),console.log(`[gateway] hosting lens app '${o}' of '${e.wsKey}' \u2192 vite :${l}`);try{ie(E,l),p("info",`lens app started: ${e.wsKey}/${o} (vite :${l})`,`cluster-lens-app:${e.wsKey}:${o}`,{kind:"lens-app-up",project:o,port:l},void 0,n)}catch(d){T.delete(l),E.state="failed",console.error(`[gateway] lens app ${e.wsKey}/${o}: ${d.message}`)}}return()=>{for(const o of t){o.disposed=!0;for(const a of[...o.generations])H(a,!0);for(const a of o.routes)a.lens&&K.delete(a.lens);K.delete(o.frontend),x.delete(o.key),z.delete(o.key),q.delete(o.key),M.delete(o.key)}}},"hostWorkspaceApps"),be=c(async(e=2500)=>{F&&(clearInterval(F),F=void 0),I&&(clearInterval(I),I=void 0);const r=[...j];for(const o of r)signalChild(o,"SIGTERM");const n=c(o=>o.exitCode===null&&o.signalCode===null,"alive"),t=Date.now()+e;for(;Date.now()<t&&r.some(n);)await new Promise(o=>setTimeout(o,100));for(const o of r)n(o)&&signalChild(o,"SIGKILL")},"reapAll"),de=c(()=>Pe({graceMs:types_1.LENS_PROBE_GRACE_MS,failureThreshold:types_1.LENS_PROBE_FAILS,cooldownMs:types_1.LENS_PROBE_COOLDOWN_MS,neverListenedGraceMs:types_1.LENS_PROBE_BOOT_GRACE_MS},types_1.LENS_PROBE_ENABLED),"probeLensFrontends");return{spawnManagedChild:D,bootSingletonsAndApps:Re,hostWorkspaceDashboard:Me,hostParkedDashboard:Ce,hostWorkspaceApps:$e,probeLensFrontends:de,reapAll:be}}P(createLensChildren,"createLensChildren"),c(createLensChildren,"createLensChildren");