@lensmcp/cluster 1.26.23 → 1.26.24

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (28) hide show
  1. package/README.md +1 -1
  2. package/executors/gateway/runtime/canvas-link.d.ts +31 -0
  3. package/executors/gateway/runtime/canvas-link.js +4 -0
  4. package/executors/gateway/runtime/chooser.d.ts +2 -2
  5. package/executors/gateway/runtime/chooser.js +13 -13
  6. package/executors/gateway/runtime/control.js +2 -2
  7. package/executors/gateway/runtime/frame-host.d.ts +17 -0
  8. package/executors/gateway/runtime/frame-host.js +1 -0
  9. package/executors/gateway/runtime/handler.d.ts +3 -0
  10. package/executors/gateway/runtime/handler.js +1 -1
  11. package/executors/gateway/runtime/lens-children.d.ts +2 -2
  12. package/executors/gateway/runtime/lens-children.js +1 -1
  13. package/executors/gateway/runtime/lens-hosts.d.ts +73 -0
  14. package/executors/gateway/runtime/lens-hosts.js +1 -0
  15. package/executors/gateway/runtime/lifecycle.js +4 -4
  16. package/executors/gateway/runtime/observability.d.ts +1 -1
  17. package/executors/gateway/runtime/parked-dashboards.d.ts +2 -2
  18. package/executors/gateway/runtime/registration-guards.d.ts +6 -1
  19. package/executors/gateway/runtime/registration-guards.js +1 -1
  20. package/executors/gateway/runtime/route-registry.d.ts +2 -2
  21. package/executors/gateway/runtime/server.js +2 -2
  22. package/executors/gateway/runtime/shared-build.d.ts +13 -0
  23. package/executors/gateway/runtime/shared-build.js +4 -4
  24. package/executors/gateway/runtime/types.d.ts +14 -1
  25. package/executors/gateway/runtime/types.js +1 -1
  26. package/executors/gateway/runtime/workspace-registry.d.ts +1 -1
  27. package/executors/trust/trust.impl.js +3 -3
  28. package/package.json +5 -5
@@ -0,0 +1,73 @@
1
+ /**
2
+ * THE HOST MOVE (planning/canvas phase H, D7): LensMCP's dashboard moved from `lensmcp.local` to `lensmcp.localhost`,
3
+ * and a canvas's frame has a host of its own, `lensmcp.canvas.localhost`. `.localhost` is loopback by standard (RFC
4
+ * 6761): a browser and the OS resolver answer it with no `/etc/hosts` line, where `.local` is mDNS's name space and
5
+ * waited about 5 s per AAAA miss.
6
+ *
7
+ * Two releases of compatibility (through 1.27.x), so nothing a person or a script holds breaks on the day:
8
+ *
9
+ * - THE CERTIFICATE keeps `lensmcp.local` as an extra name ({@link lensCertNames}), with the frame host: a 308 for a
10
+ * name the certificate does not carry would fail at TLS, before any redirect is read.
11
+ * - A BROWSER'S PAGE LOAD on `lensmcp.local` is sent on with a 308 to the same path on `lensmcp.localhost` — a bookmark,
12
+ * a link an older CLI printed (a sign-in link too: its code rides along in the query, and is redeemed there).
13
+ * - EVERYTHING ELSE on `lensmcp.local` is an ALIAS, served as the new host would be: a script's call, an open tab's API
14
+ * call or stream, and — what a redirect would break — a worker Mac's tunnel. A tunnel request carries the organizer's
15
+ * browser's headers, a navigation's too; a 308 to `lensmcp.localhost` would send that browser to its OWN Mac's
16
+ * dashboard (review finding «H: worker tunnels redirected to the wrong Mac»). The tunnel marks every request it carries
17
+ * ({@link PEER_TUNNEL_HEADER}), and those are always the alias.
18
+ * - An operator's own `lensHost` is left as it is: nothing moved for them.
19
+ *
20
+ * The names are protocol-types `lens-hosts.ts`'s (and `CANVAS_FRAME_HOST`, `PEER_TUNNEL_HEADER`): cluster does not depend
21
+ * on that package at runtime, so they are written twice and lens-hosts.spec.ts holds them equal.
22
+ */
23
+ import type * as http from 'node:http';
24
+ /** The dashboard's host. */
25
+ export declare const LENS_HOST = "lensmcp.localhost";
26
+ /** The dashboard's host before the move: an extra certificate name, a 308 for a page load, an alias for the rest. */
27
+ export declare const LEGACY_LENS_HOST = "lensmcp.local";
28
+ /** The canvas frame's host (D7): a site of its own, under the reserved `canvas.localhost` (D9). Static files only. */
29
+ export declare const CANVAS_FRAME_HOST = "lensmcp.canvas.localhost";
30
+ /** The key-free canvas link's path on the dashboard host: `/canvas/<id>` (canvas-link.ts). */
31
+ export declare const CANVAS_LINK_PATH = "/canvas";
32
+ /** What a worker Mac's tunnel stamps on every request it carries (apps/agent `peers/remote-instance.ts`). */
33
+ export declare const PEER_TUNNEL_HEADER = "x-lensmcp-peer-tunnel";
34
+ /** The dashboard host this gateway serves: the operator's `lensHost`, else {@link LENS_HOST}. */
35
+ export declare function lensHostOf(option: string | undefined): string;
36
+ /** A `Host` header's name, lower-case, without its port. */
37
+ export declare function hostNameOf(header: string | undefined): string;
38
+ /** A `Host` header's port, when it names one (digits only), else `''`. */
39
+ export declare function hostPortOf(header: string | undefined): string;
40
+ /**
41
+ * The names the gateway's certificate carries beyond its routes' hosts while it serves a dashboard: the canvas frame
42
+ * host, and — when the dashboard is on {@link LENS_HOST} — the old {@link LEGACY_LENS_HOST}, through the window.
43
+ */
44
+ export declare function lensCertNames(routes: readonly {
45
+ project?: string;
46
+ host?: string;
47
+ }[], lensHost: string): string[];
48
+ /**
49
+ * A page load: what a browser does when the person opens, follows or types a link — the one request a 308 belongs to.
50
+ * `Sec-Fetch-Mode: navigate` says so where a browser sends it; without it, a GET asking for HTML.
51
+ */
52
+ export declare function isPageLoad(req: {
53
+ method?: string;
54
+ headers: http.IncomingHttpHeaders;
55
+ }): boolean;
56
+ export type LegacyHostAnswer =
57
+ /** A 308 to this URL: the same path and query on the new host, same scheme and port. */
58
+ {
59
+ redirect: string;
60
+ }
61
+ /** Served as this `Host` would be (the new host, same port). */
62
+ | {
63
+ alias: string;
64
+ };
65
+ /**
66
+ * What a request addressed to `lensmcp.local` gets while the dashboard is on `lensmcp.localhost` — `undefined` for any
67
+ * other request (another host, or a gateway whose operator chose its own `lensHost`). `rawUrl` is the target as the
68
+ * browser sent it: the redirect gives it back as it came.
69
+ */
70
+ export declare function legacyLensHostAnswer(req: {
71
+ method?: string;
72
+ headers: http.IncomingHttpHeaders;
73
+ }, rawUrl: string, lensHost: string, https: boolean): LegacyHostAnswer | undefined;
@@ -0,0 +1 @@
1
+ "use strict";var _=Object.defineProperty;var r=(e,t)=>_(e,"name",{value:t,configurable:!0});var a=Object.defineProperty,s=r((e,t)=>a(e,"name",{value:t,configurable:!0}),"s");Object.defineProperty(exports,"__esModule",{value:!0}),exports.PEER_TUNNEL_HEADER=exports.CANVAS_LINK_PATH=exports.CANVAS_FRAME_HOST=exports.LEGACY_LENS_HOST=exports.LENS_HOST=void 0,exports.lensHostOf=lensHostOf,exports.hostNameOf=hostNameOf,exports.hostPortOf=hostPortOf,exports.lensCertNames=lensCertNames,exports.isPageLoad=isPageLoad,exports.legacyLensHostAnswer=legacyLensHostAnswer,exports.LENS_HOST="lensmcp.localhost",exports.LEGACY_LENS_HOST="lensmcp.local",exports.CANVAS_FRAME_HOST="lensmcp.canvas.localhost",exports.CANVAS_LINK_PATH="/canvas",exports.PEER_TUNNEL_HEADER="x-lensmcp-peer-tunnel";const DASHBOARD_PROJECT="(lens-dashboard)";function lensHostOf(e){return e?.trim().toLowerCase()||exports.LENS_HOST}r(lensHostOf,"lensHostOf"),s(lensHostOf,"lensHostOf");function hostNameOf(e){const t=(e??"").trim().toLowerCase();return t.startsWith("[")?t.slice(0,t.indexOf("]")+1):t.split(":")[0]??""}r(hostNameOf,"hostNameOf"),s(hostNameOf,"hostNameOf");function hostPortOf(e){return/^[^:[\]]+:(\d{1,5})$/.exec((e??"").trim())?.[1]??""}r(hostPortOf,"hostPortOf"),s(hostPortOf,"hostPortOf");function lensCertNames(e,t){return e.some(o=>o.project===DASHBOARD_PROJECT)?t===exports.LENS_HOST?[exports.CANVAS_FRAME_HOST,exports.LEGACY_LENS_HOST]:[exports.CANVAS_FRAME_HOST]:[]}r(lensCertNames,"lensCertNames"),s(lensCertNames,"lensCertNames");function isPageLoad(e){if(e.method!=="GET"&&e.method!=="HEAD")return!1;const t=e.headers["sec-fetch-mode"];return typeof t=="string"?t==="navigate":/\btext\/html\b/i.test(String(e.headers.accept??""))}r(isPageLoad,"isPageLoad"),s(isPageLoad,"isPageLoad");function legacyLensHostAnswer(e,t,o,E){if(o!==exports.LENS_HOST||hostNameOf(e.headers.host)!==exports.LEGACY_LENS_HOST)return;const n=hostPortOf(e.headers.host),p=`${exports.LENS_HOST}${n?`:${n}`:""}`;if(e.headers[exports.PEER_TUNNEL_HEADER]!==void 0||!isPageLoad(e))return{alias:p};const c=t.startsWith("/")&&!t.startsWith("//")?t:"/";return{redirect:`${E?"https":"http"}://${p}${c}`}}r(legacyLensHostAnswer,"legacyLensHostAnswer"),s(legacyLensHostAnswer,"legacyLensHostAnswer");
@@ -1,4 +1,4 @@
1
- "use strict";var pt=Object.defineProperty;var m=(t,i)=>pt(t,"name",{value:i,configurable:!0});var ct=Object.defineProperty,s=m((t,i)=>ct(t,"name",{value:i,configurable:!0}),"s");Object.defineProperty(exports,"__esModule",{value:!0}),exports.startErrorText=startErrorText,exports.scaleTarget=scaleTarget,exports.isLoopbackHostname=isLoopbackHostname,exports.isOwnRunnerCommand=isOwnRunnerCommand,exports.isRunnerOf=isRunnerOf,exports.isTestSourcePath=isTestSourcePath,exports.sourceScanPass=sourceScanPass,exports.sourceSetSnapshot=sourceSetSnapshot,exports.sourceSetSignature=sourceSetSignature,exports.diffSourceSets=diffSourceSets,exports.sourceChangeWindowMs=sourceChangeWindowMs,exports.sourceScopeDirs=sourceScopeDirs,exports.podRecycleReason=podRecycleReason,exports.lensFrontendStale=lensFrontendStale,exports.lensWatcherVerdict=lensWatcherVerdict,exports.podWatcherVerdict=podWatcherVerdict,exports.lensChildWedged=lensChildWedged,exports.isPortConflictExit=isPortConflictExit,exports.podChangeClock=podChangeClock,exports.createServiceLayer=createServiceLayer,exports.chooseStalePodKillTarget=chooseStalePodKillTarget;const tslib_1=require("tslib"),node_child_process_1=require("node:child_process"),node_crypto_1=require("node:crypto"),fs=tslib_1.__importStar(require("node:fs")),http=tslib_1.__importStar(require("node:http")),net=tslib_1.__importStar(require("node:net")),path=tslib_1.__importStar(require("node:path")),node_util_1=require("node:util"),discovery_1=require("./discovery"),instance_1=require("./instance"),pod_sock_1=require("../../../pod-sock"),scope_1=require("./scope"),pod_env_1=require("./pod-env"),pod_probe_1=require("./pod-probe"),service_keys_1=require("./service-keys"),workspace_log_1=require("./workspace-log"),own_log_1=require("./own-log"),inspector_secret_1=require("../../../inspector-secret"),pod_output_1=require("./pod-output"),serve_launch_1=require("./serve-launch"),shared_build_1=require("./shared-build"),service_updates_1=require("./service-updates"),awake_1=require("./awake"),warm_start_1=require("./warm-start"),protocol_1=require("../../../shared-build/protocol"),types_1=require("./types"),exit_reason_1=require("../../../exit-reason"),handoff_retire_1=require("../../../handoff-retire"),process_name_1=require("../../../process-name"),orphan_reaper_1=require("./orphan-reaper");function eastWestEnv(t,i){const l={},p=t.serviceKeys[(0,service_keys_1.serviceKeyId)(i.wsKey,i.project)];if(p&&(l.LENSMCP_SERVICE_KEY=p),t.https){const $=require("../../../basic-ssl").caCertPath();fs.existsSync($)&&(l.NODE_EXTRA_CA_CERTS=$)}return l}m(eastWestEnv,"eastWestEnv"),s(eastWestEnv,"eastWestEnv");const sleep=s(t=>new Promise(i=>setTimeout(i,t)),"sleep"),SRC_EXCLUDE=new Set(["node_modules","dist","tmp","coverage","build","out","target"]),SRC_EXT=new Set([".ts",".tsx",".js",".jsx",".mjs",".cjs",".css",".scss",".sass",".less",".json",".html",".htm",".vue",".svelte",".mdx"]),SCAN_FILE_CAP=1e5;function fnv1a(t){let i=2166136261;for(let l=0;l<t.length;l+=1)i^=t.charCodeAt(l),i=Math.imul(i,16777619);return i>>>0}m(fnv1a,"fnv1a"),s(fnv1a,"fnv1a");const execFileP=(0,node_util_1.promisify)(node_child_process_1.execFile);async function gitIgnoredPaths(t){try{const{stdout:i}=await execFileP("git",["ls-files","--others","--directory","--ignored","--exclude-standard","-z"],{cwd:t,maxBuffer:33554432,timeout:1e4,windowsHide:!0});return new Set(i.split("\0").filter(Boolean))}catch{return new Set}}m(gitIgnoredPaths,"gitIgnoredPaths"),s(gitIgnoredPaths,"gitIgnoredPaths");function startErrorText(t,i){return[t,...(i??[]).slice(-(types_1.START_ERROR_LINES-1))].join(`
2
- `)}m(startErrorText,"startErrorText"),s(startErrorText,"startErrorText");function scaleTarget(t,i=fs.existsSync){if(t.decl.adminUrl)return{url:t.decl.adminUrl};const l=path.join(t.pool.dir,"parent.sock");return i(l)?{socketPath:l}:t.decl.port?{url:`http://localhost:${t.decl.port}`}:void 0}m(scaleTarget,"scaleTarget"),s(scaleTarget,"scaleTarget");function isLoopbackHostname(t){const i=t.toLowerCase().replace(/^\[(.*)\]$/,"$1").replace(/\.$/,"");return i==="localhost"||i.endsWith(".localhost")?!0:net.isIPv4(i)?i.split(".")[0]==="127":net.isIPv6(i)&&new URL(`http://[${i}]/`).hostname==="[::1]"}m(isLoopbackHostname,"isLoopbackHostname"),s(isLoopbackHostname,"isLoopbackHostname");function postScale(t,i,l){let p;if("socketPath"in t)p=http.request({socketPath:t.socketPath,path:"/webpack/scale",method:"POST",headers:{"content-type":"application/json"}},$=>$.resume());else{const $=t.url.startsWith("https"),M=$?require("node:https"):http,_={method:"POST"};$&&isLoopbackHostname(new URL(t.url).hostname)&&(_.rejectUnauthorized=!1),l&&(_.lookup=l),p=M.request(`${t.url}/webpack/scale`,_,A=>A.resume())}return p.on("error",()=>{}),p.end(JSON.stringify({pods:i})),p}m(postScale,"postScale"),s(postScale,"postScale");function isOwnRunnerCommand(t,i){return(0,serve_launch_1.isServeRunnerCommand)(t)?(0,serve_launch_1.isServeRunnerCommandOf)(t,i):t.includes("/node_modules/nx/")?t.includes(`${i.replace(/\/+$/,"")}/node_modules/nx/`):!0}m(isOwnRunnerCommand,"isOwnRunnerCommand"),s(isOwnRunnerCommand,"isOwnRunnerCommand");function isRunnerOf(t,i,l){const p=i.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return!new RegExp(`(^|\\s)run ${p}(:|\\s|$)`).test(t)||!(0,serve_launch_1.isServeRunnerCommand)(t)&&!/\bnx(\.js)?\b/.test(t)?!1:isOwnRunnerCommand(t,l)}m(isRunnerOf,"isRunnerOf"),s(isRunnerOf,"isRunnerOf");const TEST_FILE_RE=/\.(spec|test|e2e|e2e-spec|stories)\.[cm]?[jt]sx?$/,TEST_DIR_SEGMENTS=new Set(["__tests__","__mocks__","__snapshots__"]);function isTestSourcePath(t){const i=t.split("/"),l=i[i.length-1]??"";if(TEST_FILE_RE.test(l))return!0;for(let p=0;p<i.length-1;p+=1)if(TEST_DIR_SEGMENTS.has(i[p]))return!0;return!1}m(isTestSourcePath,"isTestSourcePath"),s(isTestSourcePath,"isTestSourcePath");function sourceScanPass(t,i,l){const p=l?.ignoreTests??!0;let $;const M=new Map,_=`tree:${path.resolve(t)}`,A=s(E=>path.relative(t,E).split(path.sep).join("/"),"rel"),C=s(async(E,j)=>{const R=await($??=gitIgnoredPaths(t)),D=[],F=new Set;let L=!1;const X=s(async(te,S)=>{if(D.length>=SCAN_FILE_CAP){L=!0;return}let O;try{O=await fs.promises.readdir(te,{withFileTypes:!0})}catch{return}S&&F.add(A(te));for(const z of O){if(D.length>=SCAN_FILE_CAP){L=!0;return}const W=z.name,re=path.join(te,W);if(z.isDirectory()){if(!S||W.startsWith(".")||SRC_EXCLUDE.has(W)||i?.has(W)||W.endsWith("-devserver")||R.has(`${A(re)}/`))continue;await X(re,!0)}else if(z.isFile()){const oe=W.lastIndexOf(".");if(oe<=0||!SRC_EXT.has(W.slice(oe)))continue;const J=A(re);if(R.has(J)||p&&isTestSourcePath(J))continue;D.push(J)}}},"walk");return await X(E,j),{paths:D,entered:F,truncated:L}},"walkDir"),b=s((E,j)=>{let R=M.get(E);return R||(R=j(),M.set(E,R)),R},"memo"),ce=s(async()=>{const E=M.get(_);if(!E)return;const j=await E;return j.truncated?void 0:j},"wideWalk"),B=new Set,le=s(()=>b(`files:${path.resolve(t)}`,async()=>{const E=await ce();return E?{paths:E.paths.filter(j=>!j.includes("/")),entered:B,truncated:!1}:C(t,!1)}),"rootFiles"),de=s(E=>b(`tree:${path.resolve(E)}`,async()=>{const j=await ce(),R=A(E);if(j?.entered.has(R)){const D=`${R}/`;return{paths:R===""?j.paths:j.paths.filter(F=>F.startsWith(D)),entered:B,truncated:!1}}return C(E,!0)}),"subtree"),V=s(E=>{const j=new Set;let R=0,D=E.some(L=>L.truncated);const F=s(L=>j.has(L)?!0:j.size>=SCAN_FILE_CAP?(D=!0,!1):(j.add(L),R^=fnv1a(L),!0),"add");for(const L of E)if(!L.paths.every(F))break;return{signature:`${j.size}:${(R>>>0).toString(36)}`,paths:j,truncated:D}},"compose");return{async snapshot(E){if(!E||E.length===0)return V([await b(_,()=>C(t,!0))]);const j=[await le()];for(const R of E)j.push(await de(R));return V(j)}}}m(sourceScanPass,"sourceScanPass"),s(sourceScanPass,"sourceScanPass");async function sourceSetSnapshot(t,i,l,p){return sourceScanPass(t,l,p).snapshot(i)}m(sourceSetSnapshot,"sourceSetSnapshot"),s(sourceSetSnapshot,"sourceSetSnapshot");async function sourceSetSignature(t,i,l,p){return(await sourceSetSnapshot(t,i,l,p)).signature}m(sourceSetSignature,"sourceSetSignature"),s(sourceSetSignature,"sourceSetSignature");const SOURCE_DIFF_PATH_CAP=128;function diffSourceSets(t,i,l,p){if(t.paths.size===i.paths.size){let A=!0;for(const C of t.paths)if(!i.paths.has(C)){A=!1;break}if(A)return null}const $=[],M=[];let _=t.truncated||i.truncated;for(const A of i.paths)t.paths.has(A)||($.length+M.length<SOURCE_DIFF_PATH_CAP?$.push(A):_=!0);for(const A of t.paths)i.paths.has(A)||($.length+M.length<SOURCE_DIFF_PATH_CAP?M.push(A):_=!0);return{changedAt:l,added:$,removed:M,truncated:_,...p!==void 0?{windowMs:p}:{}}}m(diffSourceSets,"diffSourceSets"),s(diffSourceSets,"diffSourceSets");function sourceChangeWindowMs(t,i,l,p){const $=i&&i>0?t-i:l;return Math.max($,l)+p}m(sourceChangeWindowMs,"sourceChangeWindowMs"),s(sourceChangeWindowMs,"sourceChangeWindowMs");function sourceScopeDirs(t,i,l,p,$){const M=s(C=>{const b=path.relative(t,C).split(path.sep).filter(Boolean);return b.length===0||b[0].startsWith("..")?"":b[0]},"bucketOf")(i);if(!M)return[];const _=new Set(l.filter(Boolean)),A=new Set([M]);for(const C of p)C.startsWith(".")||SRC_EXCLUDE.has(C)||$?.has(C)||C.endsWith("-devserver")||_.has(C)||A.add(C);return[...A].sort().map(C=>path.join(t,C))}m(sourceScopeDirs,"sourceScopeDirs"),s(sourceScopeDirs,"sourceScopeDirs");function podRecycleReason(t,i,l,p){return!t.proc||t.state!=="up"||t.spawnAt==null||t.inflight>0||(t.activeWork??0)>0||i-t.lastUsed<p.settleMs||t.lastStaleRecycleAt!=null&&i-t.lastStaleRecycleAt<p.cooldownMs?null:l>0&&l-t.spawnAt>p.graceMs?"stale-source-set":p.maxAgeMs>0&&i-t.spawnAt>p.maxAgeMs?"max-age":null}m(podRecycleReason,"podRecycleReason"),s(podRecycleReason,"podRecycleReason");function lensFrontendStale(t,i,l,p,$){return!(p-i<$.cooldownMs||l<=0||l-t<=$.graceMs||p-l<$.settleMs)}m(lensFrontendStale,"lensFrontendStale"),s(lensFrontendStale,"lensFrontendStale");function lensWatcherVerdict(t,i,l,p=[]){if(!t)return"unknown";if("schemaVersion"in t&&t.schemaVersion>=2&&p.length>0){const $=i-l,M=new Set(t.recentEvents.filter(_=>_.at>=$).map(_=>path.resolve(_.path)));return p.every(_=>M.has(path.resolve(_)))?"heard":"missed"}return t.lastFsSetEventAt>=i-l?"heard":"missed"}m(lensWatcherVerdict,"lensWatcherVerdict"),s(lensWatcherVerdict,"lensWatcherVerdict");function podWatcherVerdict(t,i,l){if(!t)return"unknown";if(t.degraded)return"degraded";const p=i-l;return t.lastWatchRunAt>=p||t.lastBuildAt>=p?"heard":"silent"}m(podWatcherVerdict,"podWatcherVerdict"),s(podWatcherVerdict,"podWatcherVerdict");function lensChildWedged(t,i,l,p){const $=t.hasListened?p.graceMs:Math.max(p.graceMs,p.neverListenedGraceMs);return l-t.spawnedAt<$||l-i<p.cooldownMs||t.probeFails<Math.max(2,p.failureThreshold)?null:"wedged-no-listener"}m(lensChildWedged,"lensChildWedged"),s(lensChildWedged,"lensChildWedged");function isPortConflictExit(t,i){return t.signal||t.code===null||t.code===0||t.ranMs>i.fastFailMs?!1:t.portHeld}m(isPortConflictExit,"isPortConflictExit"),s(isPortConflictExit,"isPortConflictExit");function podChangeClock(t,i){const l=t.sourceSetChangedFor?.get(i);if(l!==void 0){const p=t.sourceSetChangesFor?.get(i);return{at:l,...p?{change:p}:{},scope:"project"}}return t.sourceSetScoped?.has(i)?{at:0,scope:"none"}:{at:t.sourceSetChangedAt??0,...t.sourceSetChange?{change:t.sourceSetChange}:{},scope:"workspace"}}m(podChangeClock,"podChangeClock"),s(podChangeClock,"podChangeClock");const changeEvidence=s(t=>{if(!t)return"no path evidence";const i=[...t.added.map(l=>`+${l}`),...t.removed.map(l=>`-${l}`)];return i.length?`${i.slice(0,3).join(", ")}${i.length>3?` (+${i.length-3} more)`:""}`:"no path evidence"},"changeEvidence");function createServiceLayer(t,i,l={}){const p=l.spawnProcess??node_child_process_1.spawn,$=l.probeAlive??pod_probe_1.probePodAlive,M=l.killTree??((e,r="SIGTERM")=>{try{process.kill(-e.pid,r)}catch{try{e.kill(r)}catch{}}}),_=l.sharedBuild??(0,shared_build_1.createSharedBuildRelay)(t),A=s((e,r="SIGTERM")=>{_.detach(e),M(e,r)},"killTree"),C=l.handoffDrainMs??(0,handoff_retire_1.handoffDrainBoundMs)(),b=l.treeAlive??(e=>{if(!e.pid||!(e instanceof node_child_process_1.ChildProcess))return!1;try{return process.kill(-e.pid,0),!0}catch(r){return r.code==="EPERM"}}),ce=l.retirePollMs??1e3,B=l.rollReadyMs??types_1.POD_ROLL_READY_MS,le=l.rollPollMs??750,de=l.maxConcurrentRolls??types_1.POD_MAX_CONCURRENT_ROLLS,V=de>0?de:Number.POSITIVE_INFINITY,E=l.maxConcurrentColdStarts??types_1.MAX_COLD_STARTS,j=E>0?E:Number.POSITIVE_INFINITY;let R=0;const D=[],F=s(()=>R<j?(R+=1,Promise.resolve()):new Promise(e=>{D.push(()=>{R+=1,e()})}),"acquireColdSlot"),L=s(()=>{R-=1,D.shift()?.()},"releaseColdSlot"),{emit:X}=i,te=s(e=>e.wsKey===t.wsKey||!fs.existsSync(path.join(e.root,"package.json"))?void 0:path.join(e.root,".lensmcp","events.jsonl"),"serviceBus"),S=s((e,r,o,n,d)=>X(r,o,n,{wsKey:e.wsKey,...d},void 0,te(e)),"emitSvc"),O=s(e=>(e.scannedAt=0,(0,discovery_1.pickSock)(e,t.scanTtlMs)?e.socks.length:0),"scanNow"),z=s((e,r)=>{let o;try{o=(0,node_child_process_1.execFileSync)("ps",["ax","-ww","-o","pid=,pgid=,command="],{encoding:"utf8",timeout:5e3})}catch{return 0}const n=e.proc?.pid;let d=0;for(const a of o.split(`
3
- `)){const c=a.match(/^\s*(\d+)\s+(\d+)\s+(.*)$/);if(!c)continue;const u=Number(c[1]),v=Number(c[2]);if(isRunnerOf(c[3],r,e.root)&&!(u===process.pid||u===n)&&!(n!==void 0&&v===n)){try{process.kill(-v,"SIGKILL")}catch{try{process.kill(u,"SIGKILL")}catch{}}d+=1}}return d>0&&(console.log(`[gateway] ${r}: reaped ${d} stale runner tree(s) \u2014 a foreign generation of this service (holding nx's task lock, or its pool)`),S(e,"warning",`stale-runner reap: ${e.project} (${d} foreign tree(s))`,`cluster-service:${e.project}`,{kind:"stale-runner-reap",project:e.project,reaped:d})),d},"reapForeignRunners"),W=s((e,r)=>({...(0,pod_env_1.podBaseEnv)(process.env,t.root,e.root),...e.instanceEnv?{...e.instanceEnv,LENSMCP_SOCKET_ONLY:"1"}:{},...e.frozen?{LENSMCP_FREEZE:"1",LENSMCP_TYPECHECK:"off"}:{},...!e.frozen&&t.updates?.startsHeld(e.wsKey,e.project)?{LENSMCP_UPDATES_HELD:"1"}:{},NX_DAEMON:"false",NX_ISOLATE_PLUGINS:"false",...e.wsKey?{LENSMCP_WS_KEY:e.wsKey}:{},...e.sockNs?{LENSMCP_SOCK_NS:e.sockNs}:{},LENSMCP_EVENT_FILE:e.wsKey===t.wsKey?t.eventFile:path.join(e.root,".lensmcp","events.jsonl"),LENSMCP_GATEWAY_PID:String(process.pid),LENSMCP_POD_GENERATION:String(r),...eastWestEnv(t,e)}),"serviceEnv"),re=s((e,r,o,n)=>{const d=W(e,r),a=e.wsKey||path.basename(e.root),c=(0,serve_launch_1.planServiceLaunch)({stores:t.graphStores,root:e.root,project:e.project,decl:e.decl,childCount:n,baseEnv:d});if(c.kind==="runner"){const w=_.offeredTo(e),f=p((0,process_name_1.namedExecPath)((0,process_name_1.processName)(a,e.project,serve_launch_1.SERVE_RUNNER_ROLE)),[...c.script.execArgv,c.script.path,...(0,serve_launch_1.serveRunnerArgs)(o,n,e.root)],{cwd:e.root,detached:!0,env:w?{...c.env,[protocol_1.SHARED_BUILD_ENV]:"1"}:c.env,stdio:["ignore","pipe","pipe","ipc"]});return w&&_.attach(e,r,f),(0,service_updates_1.listenHeldReports)(e,f,()=>t.updates),f.send?.(c.message,k=>{k&&console.error(`[gateway] ${o}: could not hand the task to its runner (${k.message})`)}),{proc:f,launcher:"runner"}}console.log(`[gateway] ${o}: starting through nx run \u2014 ${c.reason}`);const u=path.join(e.root,"node_modules","nx","dist","bin","nx.js"),v=(0,process_name_1.namedExecPath)((0,process_name_1.processName)(a,e.project,"nx")),[g,h]=fs.existsSync(u)?[v,[u,"run",o,`--childCount=${n}`]]:["yarn",["nx","run",o,`--childCount=${n}`]];return{proc:p(g,h,{cwd:e.root,detached:!0,env:d,stdio:["ignore","pipe","pipe"]}),launcher:"nx"}},"startServiceTree"),oe=new WeakMap,J=s((e,r,o)=>{const n=`${e.project}:${e.decl.serveTarget??"serve-hmr"}`,d=Math.max(1,e.decl.minPods??1),{proc:a,launcher:c}=re(e,r,n,d);oe.set(a,c),o==="active"&&(e.launcher=c),o==="active"&&(e.lastErrors=[],e.buildFailed=!1,e.faults=new pod_output_1.PodFaults,e.outputTail=[]);const u=s(h=>{const w=h.toString();for(const f of w.split(`
4
- `)){const k=(0,pod_output_1.classifyPodLine)(f),{clean:T,broken:q,healthy:se}=k,y=T;if(o==="active"&&e.outputTail&&T.trim()&&(e.outputTail.push(T.trimEnd().slice(0,400)),e.outputTail.length>types_1.OUTPUT_TAIL_LINES&&e.outputTail.shift()),q){e.lastErrors.push(T),e.lastErrors.length>12&&e.lastErrors.shift(),e.buildFailed=!0;const x=Date.now();(T!==e.lastErrorEmitSig||x-(e.lastErrorEmitAt??0)>=types_1.SERVICE_ERROR_THROTTLE_MS)&&(e.lastErrorEmitSig=T,e.lastErrorEmitAt=x,S(e,"error",`service error: ${e.project}`,`cluster-service:${e.project}`,{kind:"service-error",project:e.project,line:T,fault:k.fault}))}se&&(e.buildFailed=!1);const P=(e.faults??=new pod_output_1.PodFaults).observe(k);if(P){e.lastErrorEmitSig=void 0;const x=P.open.length===0;S(e,"info",`${x?"service recovered":`${P.closed.join(" + ")} recovered`}: ${e.project}`,`cluster-service:${e.project}`,{kind:x?"service-recovered":"service-fault-closed",project:e.project,line:T,closed:P.closed,open:P.open})}!e.lockBlockedAt&&/Waiting for .+ in another nx process/.test(y)&&(e.lockBlockedAt=Date.now(),console.log(`[gateway] ${n}: spawn blocked by a stale nx runner \u2014 breaking the lock + respawning`),S(e,"warning",`nx task lock: ${e.project} blocked by a stale runner \u2014 auto-breaking`,`cluster-service:${e.project}`,{kind:"nx-lock-break",project:e.project}),setTimeout(()=>{t.stopped()||!e.lockBlockedAt||(U(e,"parked on a foreign nx task lock \u2014 recycling",{announce:!1}),z(e,n),setTimeout(()=>{!t.stopped()&&!e.proc&&e.state==="down"&&Y(e)},1500).unref?.())},250).unref?.())}},"sniff"),v=e.wsKey&&e.wsKey!==t.wsKey&&e.root?(0,workspace_log_1.workspaceLogWriter)(e.root):void 0,g=s(h=>{const w=(0,own_log_1.linePrefixer)(e.project);return f=>{if(t.stopped())return;const k=(0,inspector_secret_1.redactInspectorUrls)(f.toString());u(k);const T=w(k);h.write(T),v?.(T)}},"relay");return a.stdout?.on("data",g(process.stdout)),a.stderr?.on("data",g(process.stderr)),a.on("exit",(h,w)=>{if(e.proc!==a||(e.proc=void 0,e.state="down",t.stopped()))return;const f=(0,exit_reason_1.describeExit)(h,w);if(console.log(`[gateway] ${n} exited (${h??"no code"}${w?`, ${w}`:""}${e.inflight?`, ${e.inflight} request(s) in flight`:""})${f?` \u2014 ${f}`:""}`),S(e,h===0?"info":"warning",`service down: ${e.project} (exit ${h})`,`cluster-service:${e.project}`,{kind:"service-down",project:e.project,code:h,...w?{signal:w}:{}}),h===0||e.buildFailed)return;if(e.root!==t.root&&!fs.existsSync(path.join(e.root,"package.json"))){console.log(`[gateway] not respawning ${e.project}: its workspace folder ${e.root} is gone \u2014 the gateway drops the workspace at its next sweep`),S(e,"warning",`not respawning ${e.project}: its workspace folder is gone`,`cluster-service:${e.project}`,{kind:"service-root-gone",project:e.project,root:e.root});return}const k=Date.now();if(e.restarts=(e.restarts??[]).filter(q=>k-q<types_1.SERVICE_RESTART_WINDOW_MS),e.restarts.length>=types_1.SERVICE_MAX_RESTARTS){S(e,"error",`service crash-looping: ${e.project} \u2014 ${types_1.SERVICE_MAX_RESTARTS}+ restarts/min, not auto-respawning (the next request retries)`,`cluster-service:${e.project}`,{kind:"service-crash-loop",project:e.project});return}e.restarts.push(k);const T=Math.min(8e3,500*2**(e.restarts.length-1));setTimeout(()=>{t.stopped()||e.proc||e.state!=="down"||(console.log(`[gateway] self-heal: respawning ${e.project} (restart ${e.restarts.length}/${types_1.SERVICE_MAX_RESTARTS})`),S(e,"info",`self-heal: respawning ${e.project}`,`cluster-service:${e.project}`,{kind:"service-respawn",project:e.project,attempt:e.restarts.length}),Y(e))},T)}),a},"launchServiceProcess"),Y=s(e=>{if(t.stopped()||e.manualStopped)return;const r=`${e.project}:${e.decl.serveTarget??"serve-hmr"}`,o=Math.max(1,e.decl.minPods??1);l.reapForeign!==!1&&z(e,r),e.lockBlockedAt=void 0,console.log(`[gateway] starting ${r} (pods=${o})\u2026`),S(e,"info",`service starting: ${e.project} (${o} pod${o>1?"s":""})`,`cluster-service:${e.project}`,{kind:"service-starting",project:e.project,pods:o}),e.state="starting",e.spawnAt=Date.now(),e.generation=(e.generation??0)+1,e.proc=J(e,e.generation,"active")},"spawnService"),Ie=s(async e=>{const r=e.pool.socks[0];if(!r)return;const o=await(0,pod_probe_1.probePodAlive)(r,void 0,t.serviceKeys[(0,service_keys_1.serviceKeyId)(e.wsKey,e.project)]);o&&(e.activeWork=o.activeWork,o.watcher&&(e.watcher=o.watcher))},"refreshActiveWork"),Oe=s(e=>{try{const r=Number(fs.readFileSync(`${e}.owner`,"utf8").trim());return Number.isInteger(r)&&r>1?r:void 0}catch{return}},"readOwnerSidecar"),Ne=s(async e=>{const r=t.serviceKeys[(0,service_keys_1.serviceKeyId)(e.wsKey,e.project)];if(!r)return[];const o=(0,node_crypto_1.createHash)("sha256").update(r).digest("hex").slice(0,8),n=[];for(const d of e.pool.socks){const a=await(0,pod_probe_1.probePodAlive)(d,void 0,r);a&&(!a.keyFingerprint||a.keyFingerprint!==o)&&n.push({sock:d,pid:a.pid})}return n},"staleAdoptedSocks"),Ke=s((e,r)=>{const o=r.map(n=>n.sock);for(const{sock:n,pid:d}of r){const a=chooseStalePodKillTarget(d,Oe(n),process.pid);if(a!==void 0)try{process.kill(a,"SIGTERM")}catch{}try{fs.unlinkSync(n)}catch{}try{fs.unlinkSync(`${n}.owner`)}catch{}}e.pool.socks=e.pool.socks.filter(n=>!o.includes(n)),e.pool.idx=-1,e.pool.scannedAt=0},"evictStaleAdopted"),pe=s((e,r)=>{if(e.state==="up")return!1;e.state="up",e.lastStartError=void 0,e.wedgeRecycles=0;const o=e.pool.socks.length;return S(e,"info",`service up: ${e.project} (${o} pods, ${r})`,`cluster-service:${e.project}`,{kind:"service-up",project:e.project,pods:o,adopted:r==="adopted"}),!0},"markUp"),Se=s(async e=>{if(e.manualStopped)return!1;if(O(e.pool)>0){const n=await Ne(e);if(e.manualStopped)return!1;if(n.length>0&&(console.error(`[gateway] ${e.project}: ${n.length} adopted pod(s) hold a foreign east-west key \u2014 evicting instead of adopting.`),S(e,"warning",`stale adoption: ${e.project} (foreign east-west key)`,`cluster-service:${e.project}`,{kind:"pod-recycle",project:e.project,reason:"stale-adoption",pods:n.length}),e.proc&&U(e,"stale adoption (foreign east-west key)"),Ke(e,n)),e.pool.socks.length>0)return pe(e,"adopted"),!0}if(t.stopped())return!1;let r=!1;const o=s(()=>e.state!=="starting"&&!e.proc,"notStarted");if(o())if(e.coldWait)await e.coldWait;else{R>=j&&(console.log(`[gateway] cold start queued: ${e.project}${e.wsKey&&e.wsKey!==t.wsKey?` (${e.wsKey})`:""} \u2014 ${R} starting, ${D.length} ahead (LENSMCP_MAX_COLD_STARTS=${j}).`),S(e,"info",`cold start queued: ${e.project}`,`cluster-service:${e.project}`,{kind:"cold-start-queued",project:e.project,inFlight:R,ahead:D.length}));const n=F();if(e.coldWait=n,await n,e.coldWait=void 0,r=!0,t.stopped()||e.manualStopped)return L(),!1;o()&&Y(e)}try{const n=await Fe(e);return n?e.lastStartError=void 0:!t.stopped()&&!e.manualStopped&&(e.lastStartError=startErrorText(fe(e),e.outputTail)),n}finally{r&&L()}},"ensureUp"),Fe=s(async e=>{const r=Date.now()+t.startupTimeoutMs,o=Date.now()+12e3;for(;!t.stopped()&&!e.manualStopped&&Date.now()<r;){if(await sleep(Math.min(700,t.startupTimeoutMs/4)),e.manualStopped||e.buildFailed&&Date.now()>o)return!1;if(O(e.pool)>0){e.state="up",e.buildFailed=!1;const n=e.spawnAt?Date.now()-e.spawnAt:void 0;return console.log(`[gateway] ${e.project} up (${e.pool.socks.length} pods${n?`, cold start ${n}ms`:""})`),S(e,"info",`cold start: ${e.project} (${e.pool.socks.length} pods, ${n??"?"}ms)`,`cluster-service:${e.project}`,{kind:"cold-start",project:e.project,pods:e.pool.socks.length,durationMs:n}),!0}if(e.state==="down")return!1}return!1},"waitForPods"),We=s(e=>{const r=e.decl.maxPods??e.decl.minPods??1,o=e.pool.socks.length,n=scaleTarget(e);!n||o===0||o>=r||e.inflight<=o||Date.now()-e.lastScaleAt<5e3||(e.lastScaleAt=Date.now(),postScale(n,o+1,l.scaleLookup),console.log(`[gateway] autoscale ${e.project}: ${o} \u2192 ${o+1} pods (inflight ${e.inflight})`),S(e,"info",`autoscale: ${e.project} ${o} \u2192 ${o+1} pods`,`cluster-service:${e.project}`,{kind:"autoscale",project:e.project,from:o,to:o+1,inflight:e.inflight}))},"scaleUp"),ue=l.killGraceMs??types_1.TREE_KILL_GRACE_MS,N=new Map,Ce=s(e=>{const r=N.get(e);if(!r||(N.delete(e),clearTimeout(r.timer),!b(e)))return;const{svc:o,why:n}=r;console.log(`[gateway] ${o.project}: its tree (pid ${e.pid}) was still running ${Math.round(ue/1e3)}s after it was told to stop (${n}) \u2014 killing it (SIGKILL).`),S(o,"warning",`tree force-killed: ${o.project} (it ignored SIGTERM)`,`cluster-service:${o.project}`,{kind:"tree-force-killed",project:o.project,why:n,pid:e.pid,graceMs:ue}),M(e,"SIGKILL")},"settleDyingTree"),ve=s((e,r,o)=>{if(A(r,"SIGTERM"),ue<=0||N.has(r))return;const n=setTimeout(()=>Ce(r),ue);n.unref?.(),N.set(r,{svc:e,why:o,timer:n})},"stopTree"),qe=s(async(e=3e3)=>{const r=Date.now()+e;for(;N.size>0;){for(const[o,n]of[...N])b(o)||(clearTimeout(n.timer),N.delete(o));if(N.size===0||Date.now()>=r)break;await sleep(100)}for(const o of[...N.keys()])Ce(o)},"finishDyingTrees"),U=s((e,r,o)=>{if(!e.proc)return;console.log(`[gateway] ${e.project} ${r} \u2014 scaling to zero.`),o?.announce!==!1&&S(e,"info",`idle kill: ${e.project} (${r})`,`cluster-service:${e.project}`,{kind:"idle-kill",project:e.project,why:r});const n=e.proc;try{n.stdout?.removeAllListeners("data"),n.stderr?.removeAllListeners("data"),n.removeAllListeners("exit")}catch{}(0,discovery_1.stopRoutingTo)(e.pool),ve(e,n,r),e.proc=void 0,e.state="down",setTimeout(()=>{ge(e),e.pool.socks=[],e.pool.scannedAt=0},1200).unref?.()},"killSpawned"),ge=s(e=>{try{for(const r of fs.readdirSync(e.pool.dir)){if(!r.endsWith(".sock"))continue;const o=path.join(e.pool.dir,r);try{const n=Number(fs.readFileSync(`${o}.owner`,"utf8").trim());if(Number.isFinite(n)&&n>0)try{process.kill(n,0);continue}catch{}}catch{}try{fs.unlinkSync(o)}catch{}try{fs.unlinkSync(`${o}.owner`)}catch{}}}catch{}},"sweepDeadOwnerSocks");let Q=0;const ye=[],Ge=s(()=>Q<V?(Q+=1,Promise.resolve()):new Promise(e=>{ye.push(()=>{Q+=1,e()})}),"acquireRollSlot"),Ve=s(()=>{Q-=1,ye.shift()?.()},"releaseRollSlot"),$e=s(async(e,r,o)=>{O(e.pool);for(const n of e.pool.socks){const d=await $(n,void 0,o);if(d&&r(d.podGeneration))return!0}return!1},"anyPodAnswers"),he=new Map,Ue=s((e,r,o)=>{const n=C>0&&(0,handoff_retire_1.requestHandoffRetire)(e.pool.dir,o);if(A(r,"SIGTERM"),!n)return;const d=e.wsKey&&e.wsKey!==t.wsKey&&e.root?(0,workspace_log_1.workspaceLogWriter)(e.root):void 0,a=s(se=>y=>{if(t.stopped())return;const P=(0,inspector_secret_1.redactInspectorUrls)(y.toString()).replace(/^(?=.)/gm,`[${e.project} g${o} retiring] `);se.write(P),d?.(P)},"say"),c=a(process.stdout),u=a(process.stderr);r.stdout?.on("data",c),r.stderr?.on("data",u);let v,g=!1;const h=s(()=>{g=!0,clearTimeout(v),r.stdout?.removeListener("data",c),r.stderr?.removeListener("data",u),r.removeListener("close",h)},"releaseLogs");r.once("close",h);let w=!1;const f=s(()=>{w||(w=!0,clearTimeout(k),clearInterval(q),t.stopped()?h():g||(v=setTimeout(h,1e3),v.unref?.()),he.delete(r),(0,handoff_retire_1.clearHandoffRetire)(e.pool.dir,o),ge(e),e.pool.scannedAt=0)},"end"),k=setTimeout(()=>{console.error(`[gateway] pod handoff: ${e.project} g${o} was still running ${C}ms after it was retired \u2014 killing it.`),M(r,"SIGKILL"),f()},C);k.unref?.();const T=s(()=>{if(!w){if(t.stopped()){f();return}b(r)||(console.log(`[gateway] pod handoff: ${e.project} g${o} finished its in-flight work and exited.`),f())}},"look"),q=setInterval(T,ce);q.unref?.(),r.once("exit",T),he.set(r,()=>{f(),ve(e,r,"the gateway is stopping")})},"retireReplacedTree"),He=l.standbyGraceMs??3e4,I=new Map,Be=s((e,r,o,n,d)=>{const a=d+B+He,c=setTimeout(()=>xe(r),Math.max(0,a-Date.now()));c.unref?.(),I.set(r,{svc:e,generation:o,reason:n,beganAt:d,deadlineAt:a,timer:c})},"holdStandby"),Xe=s(e=>{const r=I.get(e);r&&(clearTimeout(r.timer),I.delete(e))},"releaseStandby"),Z=s((e,r)=>{const o=I.get(e);if(!o)return!1;clearTimeout(o.timer),I.delete(e);const{svc:n,generation:d}=o;try{e.stdout?.removeAllListeners("data"),e.stderr?.removeAllListeners("data")}catch{}return(0,discovery_1.stopRoutingTo)(n.pool,a=>(0,pod_sock_1.podSockGeneration)(a)===d),ve(n,e,`standby g${d}: ${r}`),setTimeout(()=>ge(n),1200).unref?.(),!0},"endStandby"),Me=s((e,r)=>{const o=r.oldServing?`old generation g${r.fromGen} kept serving`:`and the old generation g${r.fromGen} is NOT serving (${r.oldGone?"its tree is gone":"none of its pods answers"}) \u2014 the service is down until it recovers`;console.error(`[gateway] pod handoff failed: ${e.project} g${r.generation}: ${r.why} \u2014 ${o}.`),e.rollFailure=`${r.why} \u2014 ${o}`,S(e,r.oldServing?"warning":"error",`pod handoff failed: ${e.project}`,`cluster-service:${e.project}`,{kind:"pod-handoff-failed",project:e.project,reason:r.reason,generation:r.generation,error:r.why,durationMs:Date.now()-r.beganAt,oldServing:r.oldServing})},"reportStandbyFailed"),xe=s(e=>{const r=I.get(e);if(!r)return;const{svc:o,generation:n,reason:d,beganAt:a}=r,c=`the standby outlived its roll (${Math.round((Date.now()-a)/1e3)}s; a roll waits ${Math.round(B/1e3)}s for it)`;Z(e,c);const u=o.proc,v=t.serviceKeys[(0,service_keys_1.serviceKeyId)(o.wsKey,o.project)];(async()=>{const g=!u||u.exitCode!==null||u.signalCode!==null,h=g?!1:await Promise.race([$e(o,f=>f!==n,v).catch(()=>!1),sleep(2e3).then(()=>{})]),w=!t.stopped()&&!g&&(h??O(o.pool)>0);Me(o,{reason:d,generation:n,fromGen:o.generation??n-1,why:c,beganAt:a,oldServing:w,oldGone:g})})()},"outlivedRoll"),Ye=s(()=>{for(const[e,r]of[...I])Date.now()>=r.deadlineAt?xe(e):!r.svc.rolling&&r.svc.proc!==e&&(console.error(`[gateway] pod handoff: ${r.svc.project} g${r.generation} is a standby whose roll is over \u2014 stopping it.`),Z(e,"its roll is over"))},"sweepStandbys"),ze=s(()=>{for(const e of[...he.values()])e();for(const e of[...I.keys()])Z(e,"the gateway is stopping")},"stopRetiringTrees"),me=s((e,r)=>{if(e.rolling)return e.rolling;const o=e.proc;if(!o||t.stopped())return Promise.resolve(!1);if(e.launcher==="nx")return console.log(`[gateway] pod handoff skipped: ${e.project} runs through nx run, which starts one instance of a target at a time \u2014 no standby can overlap it (reason=${r}).`),Promise.resolve(!1);Q>=V&&console.log(`[gateway] pod handoff queued: ${e.project} reason=${r} \u2014 ${Q} roll(s) in flight, ${ye.length} ahead (LENSMCP_POD_MAX_CONCURRENT_ROLLS=${V}).`);const n=(async()=>{await Ge();try{return await Je(e,o,r)}finally{Ve()}})().finally(()=>{e.rolling=void 0});return e.rolling=n,n},"rollPod"),Je=s(async(e,r,o)=>{const n=e.proc;if(n!==r||t.stopped())return!1;const d=e.generation??0,a=d+1,c=Date.now();e.lastStaleRecycleAt=c,console.log(`[gateway] pod handoff start: ${e.project} g${d}\u2192g${a} reason=${o} \u2014 standby spawning, old generation keeps serving.`),S(e,"info",`pod handoff starting: ${e.project} (${o})`,`cluster-service:${e.project}`,{kind:"pod-handoff-start",project:e.project,reason:o,generation:a,fromGeneration:d});const u=J(e,a,"standby"),v=t.serviceKeys[(0,service_keys_1.serviceKeyId)(e.wsKey,e.project)];Be(e,u,a,o,c);let g=!1;try{const h=c+B;let w;for(;!t.stopped()&&Date.now()<h&&I.has(u)&&!(u.exitCode!==null||u.signalCode!==null);){O(e.pool);for(const f of e.pool.socks)if((await $(f,void 0,v))?.podGeneration===a){w=f;break}if(w)break;await sleep(le)}if(!I.has(u))return!1;if(!w||t.stopped()){const f=t.stopped()?"gateway stopping":u.exitCode!==null||u.signalCode!==null?`standby exited (${u.exitCode??u.signalCode})`:`standby not ready within ${Math.round(B/1e3)}s`;Z(u,f);const k=!t.stopped()&&e.proc===n&&n.exitCode===null&&n.signalCode===null&&await $e(e,T=>T!==a,v);return Me(e,{reason:o,generation:a,fromGen:d,why:f,beganAt:c,oldServing:k,oldGone:e.proc!==n||n.exitCode!==null||n.signalCode!==null}),!1}if(e.proc!==n)return Z(u,"the service was replaced underneath the roll"),!1;Xe(u),g=!0,e.proc=u,e.launcher=oe.get(u),e.generation=a,e.spawnAt=c,e.state="up",e.watcher=void 0,e.staleVerifiedAt=void 0,e.staleKeptAt=void 0,e.buildFailed=!1,e.lastErrors=[];try{n.stdout?.removeAllListeners("data"),n.stderr?.removeAllListeners("data"),n.removeAllListeners("exit")}catch{}return(0,discovery_1.stopRoutingTo)(e.pool,f=>(0,pod_sock_1.podSockGeneration)(f)!==a&&path.join(e.pool.dir,f)!==w),Ue(e,n,d),setTimeout(()=>{ge(e),e.pool.scannedAt=0},1200).unref?.(),console.log(`[gateway] pod handoff ready: ${e.project} g${a} answered on ${path.basename(w)} in ${Date.now()-c}ms; retiring g${d}.`),S(e,"info",`pod handoff complete: ${e.project}`,`cluster-service:${e.project}`,{kind:"pod-handoff-complete",project:e.project,reason:o,generation:a,fromGeneration:d,durationMs:Date.now()-c}),!0}finally{g||Z(u,"its roll ended without it")}},"runRoll"),Qe=s((e,r)=>{if(t.stopped())return{refused:"the gateway is stopping"};const o=e.restart&&!e.restart.done?e.restart:void 0,n=o?void 0:Ze(e);if(n&&"refused"in n)return console.error(`[gateway] restart refused: ${e.project}${e.wsKey!==t.wsKey?` (${e.wsKey})`:""} \u2014 ${n.refused}`),S(e,"warning",`restart refused: ${e.project}`,`cluster-service:${e.project}`,{kind:"service-restart",phase:"refused",project:e.project,reason:r.reason,error:n.refused}),{refused:n.refused};const d=n&&"applied"in n?n:void 0;if(e.manualStopped=!1,e.actionFailure=void 0,o)return{restart:o,already:!0};if(!e.proc&&e.state!=="down")return{refused:`${e.project} is served by pods this gateway adopted from an earlier one \u2014 it has no tree of its own to replace. \`lensmcp gateway restart\` starts every service under this gateway.`};const a=e.proc?r.hard||e.launcher==="nx"||e.state!=="up"?"hard":"rolling":"start",c={how:a,reason:r.reason,startedAt:Date.now(),...e.proc&&e.generation!==void 0?{fromGeneration:e.generation}:{},...d?{env:d.applied}:{}};d&&(e.instanceEnv=d.env),e.restart=c,e.lastUsed=c.startedAt;const u=c.env?{envFingerprint:c.env.fingerprint,envChanged:c.env.changed}:{},v=c.env?` Instance variables ${c.env.fingerprint}: ${c.env.changed.length?`changed ${c.env.changed.join(", ")}`:"unchanged"}.`:"";return console.log(`[gateway] restart asked: ${e.project}${e.wsKey!==t.wsKey?` (${e.wsKey})`:""} \u2014 ${a} (${r.reason}).${v}`),S(e,"info",`restart asked: ${e.project} (${a})`,`cluster-service:${e.project}`,{kind:"service-restart",phase:"started",project:e.project,how:a,reason:r.reason,...c.fromGeneration!==void 0?{fromGeneration:c.fromGeneration}:{},...u}),s(async()=>{if(a==="start")return await Se(e)?{ok:!0}:{ok:!1,error:fe(e)};if(a==="rolling")return e.rolling&&await e.rolling,e.proc?(e.rollFailure=void 0,await me(e,r.reason)?{ok:!0}:{ok:!1,error:e.rollFailure??"the new tree did not take over"}):await Se(e)?{ok:!0}:{ok:!1,error:fe(e)};if(U(e,`restart asked (${r.reason})`,{announce:!1}),await sleep(1500),t.stopped())return{ok:!1,error:"the gateway is stopping"};let g=!1;e.proc||(await F(),g=!0,!e.proc&&e.state!=="starting"&&Y(e));try{const h=e.proc,w=e.generation,f=t.serviceKeys[(0,service_keys_1.serviceKeyId)(e.wsKey,e.project)],k=Date.now()+t.startupTimeoutMs;for(;!t.stopped()&&Date.now()<k;){if(!h||e.proc!==h||h.exitCode!==null||h.signalCode!==null)return{ok:!1,error:fe(e)};if(await $e(e,T=>T===w,f))return pe(e,"observed"),e.buildFailed=!1,{ok:!0};await sleep(le)}return{ok:!1,error:t.stopped()?"the gateway is stopping":`no pod of the new tree answered within ${Math.round(t.startupTimeoutMs/1e3)}s`}}finally{g&&L()}},"run")().catch(g=>({ok:!1,error:g.message})).then(g=>{c.done={ok:g.ok,at:Date.now(),...e.generation!==void 0?{generation:e.generation}:{},...g.error?{error:g.error}:{}},g.ok&&(e.lastUsed=c.done.at);const h=Math.round((c.done.at-c.startedAt)/100)/10;g.ok?console.log(`[gateway] restarted: ${e.project} \u2014 g${c.done.generation??"?"} serving after ${h}s (${a}).`):console.error(`[gateway] restart failed: ${e.project} \u2014 ${g.error} (${a}, after ${h}s).`),S(e,g.ok?"info":"error",g.ok?`restarted: ${e.project}`:`restart failed: ${e.project}`,`cluster-service:${e.project}`,{kind:"service-restart",phase:g.ok?"done":"failed",project:e.project,how:a,reason:r.reason,...c.fromGeneration!==void 0?{fromGeneration:c.fromGeneration}:{},...c.done.generation!==void 0?{generation:c.done.generation}:{},durationMs:c.done.at-c.startedAt,...g.error?{error:g.error}:{},...u})}),{restart:c,already:!1}},"restartService"),Ze=s(e=>{if(!e.instanceBuiltins)return;const r=(0,instance_1.readInstanceEnvStrict)(e.root,e.instanceBuiltins);if("reason"in r)return{refused:`the instance variables of ${e.project} could not be read again \u2014 ${r.reason}. Nothing was restarted: the running tree keeps what it has. Fix the file, then restart it again.`};const o=e.instanceEnv??{};return{env:r.env,applied:{fingerprint:(0,instance_1.instanceEnvFingerprint)(r.env),fromFingerprint:(0,instance_1.instanceEnvFingerprint)(o),changed:(0,instance_1.changedInstanceEnvNames)(o,r.env)}}},"restartEnv"),fe=s(e=>e.buildFailed?`its build failed${e.lastErrors?.length?`: ${e.lastErrors[e.lastErrors.length-1]}`:""}`:e.proc&&(e.proc.exitCode!==null||e.proc.signalCode!==null)?`its tree exited (${e.proc.exitCode??e.proc.signalCode})`:!e.proc&&e.state==="down"?"its tree exited before a pod answered":`no pod answered within ${Math.round(t.startupTimeoutMs/1e3)}s`,"startFailure"),Pe=s(e=>{const r=Date.now();e.restarts=(e.restarts??[]).filter(n=>r-n<types_1.SERVICE_RESTART_WINDOW_MS);const o=(e.wedgeRecycles??0)+1;if(e.restarts.length>=types_1.SERVICE_MAX_RESTARTS||o>types_1.SERVICE_MAX_RESTARTS){const n=e.restarts.length>=types_1.SERVICE_MAX_RESTARTS?`wedged ${types_1.SERVICE_MAX_RESTARTS}+\xD7/min`:`recycled ${types_1.SERVICE_MAX_RESTARTS}\xD7 in a row and no pod came up`;S(e,"error",`service crash-looping: ${e.project} \u2014 ${n}, not auto-recycling (the next request retries)`,`cluster-service:${e.project}`,{kind:"service-crash-loop",project:e.project,recycles:o-1}),U(e,"wedged (crash-loop cap) \u2014 leaving down for the next request",{announce:!1});return}e.wedgeRecycles=o,e.restarts.push(r),console.log(`[gateway] self-heal: recycling WEDGED ${e.project} (live parent, 0 live pods; attempt ${o}/${types_1.SERVICE_MAX_RESTARTS} with no pod up since the first, ${e.restarts.length} in the last minute; ${e.inflight??0} request(s) in flight \u2014 jobs held by the dead pod keep their locks until they expire)`),S(e,"warning",`self-heal: recycling wedged ${e.project} (0 live pods)`,`cluster-service:${e.project}`,{kind:"service-recycle",project:e.project,attempt:o,inWindow:e.restarts.length}),U(e,"wedged: 0 live pods \u2014 recycling",{announce:!1}),setTimeout(()=>{!t.stopped()&&!e.proc&&e.state==="down"&&Y(e)},1500).unref?.()},"recycleWedged"),et={maxAgeMs:types_1.POD_MAX_AGE_MS,graceMs:types_1.POD_STALE_GRACE_MS,settleMs:types_1.POD_RECYCLE_SETTLE_MS,cooldownMs:types_1.POD_STALE_RECYCLE_COOLDOWN_MS};let Ee;const ne=new Map,_e=new Map;let je=!1,ke=0,we=0;const tt=s(()=>{const e=t.projectRoots??{},r=new Set(t.services.map(n=>n.project));for(const n of t.routes)n.lens&&r.add(n.lens.project);const o=new Set;for(const n of r){const d=e[n];if(!d)continue;const a=path.relative(t.root,d).split(path.sep).filter(Boolean)[0];a&&!a.startsWith("..")&&o.add(a)}return[...o]},"managedBuckets"),rt=s((e,r,o,n)=>{const d=t.projectSourceRoots?.[e];if(d?.length)return d;const a=t.projectRoots?.[e];if(!a)return;const c=sourceScopeDirs(t.root,a,o,r,n);return c.length>0?c:void 0},"scopeFor"),ot=s(()=>{if(je||Date.now()-ke<types_1.POD_STALE_SCAN_MS)return;je=!0,ke=Date.now();const e=ke;(async()=>{const r=(0,scope_1.readSourceSetOptions)(t.root),o=r.exclude,n={ignoreTests:r.ignoreTests},d=sourceScanPass(t.root,o,n),a=await d.snapshot(),c=Date.now(),u=sourceChangeWindowMs(c,we,types_1.POD_STALE_SCAN_MS,types_1.POD_RECYCLE_SETTLE_MS),v=Ee?diffSourceSets(Ee,a,c,u):null;if(v&&(t.sourceSetChangedAt=c,t.sourceSetChange=v,X("info","source file set changed \u2014 stale pods recycle when idle","cluster-gateway",{kind:"source-set-changed",added:v.added,removed:v.removed,truncated:v.truncated})),Ee=a,!t.projectRoots){we=e;return}let g;try{g=(await fs.promises.readdir(t.root,{withFileTypes:!0})).filter(y=>y.isDirectory()).map(y=>y.name)}catch{return}const h=tt(),w=new Set(t.services.map(y=>y.project));for(const y of t.routes)y.lens&&w.add(y.lens.project);const f=new Map;for(const y of w){const P=rt(y,g,h,o);if(!P)continue;const x=P.join("|"),G=f.get(x)??{dirs:P,projects:[]};G.projects.push(y),f.set(x,G)}const k=Date.now(),T=sourceChangeWindowMs(k,we,types_1.POD_STALE_SCAN_MS,types_1.POD_RECYCLE_SETTLE_MS);we=e;const q=s((y,P,x)=>{t.sourceSetChangedFor??=new Map,t.sourceSetChangesFor??=new Map;for(const G of y)t.sourceSetChangedFor.set(G,P),t.sourceSetChangesFor.set(G,x)},"stampScoped"),se=new Set([...f.values()].flatMap(y=>y.projects));for(const y of[...t.sourceSetScoped??[]])se.has(y)||t.sourceSetScoped.delete(y);for(const[y,{dirs:P,projects:x}]of f){const G=await d.snapshot(P),Te=ne.get(y);if(Te||x.some(K=>_e.has(K))){t.sourceSetScoped??=new Set;for(const K of x)t.sourceSetScoped.add(K)}ne.set(y,G);const Ae=new Map;for(const K of x){const H=_e.get(K);if(H===void 0||H===y)continue;const ee=Ae.get(H)??[];ee.push(K),Ae.set(H,ee)}for(const K of x)_e.set(K,y);for(const[K,H]of Ae){const ee=ne.get(K),ie=ee?diffSourceSets(ee,G,k,T):v;ie&&(q(H,ee?k:c,ie),X("info",`source file set changed \u2014 ${H.join(", ")}'s watch scope was re-keyed`,"cluster-gateway",{kind:"source-set-changed",scoped:!0,rescoped:!0,projects:H,added:ie.added,removed:ie.removed,truncated:ie.truncated}))}if(!Te)continue;const ae=diffSourceSets(Te,G,k,T);ae&&(q(x,k,ae),X("info",`source file set changed in ${x.join(", ")}'s scope`,"cluster-gateway",{kind:"source-set-changed",scoped:!0,projects:x,added:ae.added,removed:ae.removed,truncated:ae.truncated}))}for(const y of[...ne.keys()])f.has(y)||ne.delete(y)})().catch(()=>{}).finally(()=>{je=!1})},"maybeScanSourceSet"),nt=s((e,r)=>{const o=podChangeClock(t,e.project),n=o.change,d=`${o.scope==="project"?"in its scope":"in the workspace (its scope is not known)"}: ${changeEvidence(n)}`,a=n?.windowMs??types_1.POD_STALE_SCAN_MS+types_1.POD_RECYCLE_SETTLE_MS,c=podWatcherVerdict(e.watcher,r,a),u=s(g=>(e.staleKeptAt!==r&&(e.staleKeptAt=r,console.log(`[gateway] stale source set: pod ${e.project} ${g} \u2014 no recycle.`)),!1),"keep");if(c==="heard")return e.staleVerifiedAt=r,S(e,"info",`stale check: ${e.project} watcher confirmed \u2014 no recycle`,`cluster-service:${e.project}`,{kind:"pod-stale-verified",project:e.project,watcher:c}),u(`watcher CONFIRMED alive across the change (last build ${new Date(e.watcher?.lastBuildAt??0).toISOString()})`);if(c==="degraded")return console.log(`[gateway] stale source set: pod ${e.project} watcher DEGRADED (${e.watcher?.degraded}) \u2014 recycling.`),!0;const v=s(g=>(e.staleKeptAt!==r&&(e.staleKeptAt=r,console.log(`[gateway] stale source set: pod ${e.project} ${g}; the change ${d} \u2014 recycling.`)),!0),"recycling");return c==="silent"?types_1.POD_WATCHER_SILENT==="keep"?u("watcher alive but quiet across the change \u2014 keeping it (LENSMCP_POD_WATCHER_SILENT=keep; a live watcher cannot miss an add it will need)"):v("watcher alive but quiet across the change"):types_1.POD_WATCHER_UNVERIFIED==="keep"?u("unverifiable (no watcher testimony \u2014 older devserver bundle?) \u2014 keeping it (LENSMCP_POD_WATCHER_UNVERIFIED=keep)"):v("watcher unverifiable (no testimony yet \u2014 a pod that never rebuilt, or an older devserver bundle)")},"podStaleRecycleAllowed"),Le=s(e=>types_1.POD_RECYCLE_MODE==="rolling"&&!!e.proc&&e.launcher!=="nx","recycleRolls"),st=s((e,r)=>{if(e.lastStaleRecycleAt=Date.now(),Le(e)){me(e,r);return}console.log(`[gateway] zombie recycle: ${e.project} (${r}) \u2014 stale fs view; fresh pod incoming`);const o=!!e.decl.eager;S(e,"warning",`zombie recycle: ${e.project} (${r})`,`cluster-service:${e.project}`,{kind:"pod-recycle",project:e.project,reason:r,respawn:o}),U(e,`${r} \u2014 recycling stale pod`,{announce:!1}),o&&setTimeout(()=>{!t.stopped()&&!e.proc&&e.state==="down"&&Y(e)},1500).unref?.()},"recyclePod"),Re=new Set,at=s(e=>{const r=setInterval(()=>{if(e&&!t.stopped())try{e()}catch(o){console.error("[gateway] park sweep error:",o)}dt().catch(o=>console.error("[gateway] sweep error:",o))},t.sweepMs);return r.unref(),r},"startSweeper"),it=l.listProcesses??(()=>{try{return(0,orphan_reaper_1.parsePsRows)((0,node_child_process_1.execFileSync)("ps",orphan_reaper_1.PS_ROW_ARGS,{encoding:"utf8",timeout:5e3}))}catch{return[]}}),De=l.signalProcess??((e,r)=>{process.kill(e,r)});let be=0;const lt=s(()=>{if(typeof process.getuid!="function")return 0;const e=t.registry?t.registry.allServices():t.services;if(e.length===0)return 0;const r=e.map(a=>({label:a.wsKey||path.basename(a.root),project:a.project,root:a.root,svc:a})),o=new Set;for(const a of e)a.proc?.pid&&o.add(a.proc.pid);for(const a of[...he.keys(),...N.keys(),...I.keys()])a.pid&&o.add(a.pid);const n=[...new Set((0,process_name_1.defaultLinkDirs)().flatMap(a=>{try{return[a,fs.realpathSync(a)]}catch{return[a]}}))];let d=0;for(const a of(0,orphan_reaper_1.findOrphanExecutors)(it(),r,{linkDirs:n,uid:process.getuid(),selfPid:process.pid,ownGroups:o})){const{row:c}=a;try{De(a.group?-c.pgid:c.pid,"SIGKILL")}catch(v){if(v.code!=="ESRCH"||!a.group)continue;try{De(c.pid,"SIGKILL")}catch{continue}}d+=1;const u=a.owner.svc;console.log(`[gateway] reaped an orphaned executor of ${u.project} (${a.role}, pid ${c.pid}${a.group?`, group ${c.pgid}`:""}, parent gone) \u2014 a stopped tree it outlived: ${c.command.slice(0,160)}`),S(u,"warning",`orphan reap: ${u.project} (pid ${c.pid})`,`cluster-service:${u.project}`,{kind:"orphan-executor-reap",project:u.project,pid:c.pid,pgid:c.pgid,role:a.role,group:a.group})}return d},"reapOrphanExecutors"),dt=s(async()=>{{if(t.stopped())return;Ye(),l.reapForeign!==!1&&types_1.ORPHAN_REAP_EVERY_MS>0&&Date.now()-be>=types_1.ORPHAN_REAP_EVERY_MS&&(be=Date.now(),lt());for(const r of t.graphStores?.all()??[])r.refreshIfStale();types_1.POD_RECYCLE_ENABLED&&ot();let e=0;for(const r of t.registry?t.registry.allServices():t.services){if(t.stopped()||!r.proc){r.wedgedSince=void 0;continue}const o=path.resolve(r.root)===path.resolve(t.root),n=(0,warm_start_1.serviceIdleSec)(t,r),d=(0,awake_1.idleStopAt)(r,n);if(d!==void 0&&r.state==="up"&&(!r.restart||r.restart.done)&&r.inflight===0&&Date.now()>d){r.lastIdleStop={at:Date.now(),why:`no request for ${n}s${(r.awakeUntil??0)>r.lastUsed?" after its hold ended":""}`},U(r,`idle ${n}s`),r.wedgedSince=void 0;continue}const a=r.state==="starting"&&r.spawnAt!==void 0&&Date.now()-r.spawnAt<t.startupTimeoutMs,c=O(r.pool)>0;if(c||a){if(r.wedgedSince=void 0,c&&pe(r,"observed"),c&&!a&&types_1.POD_RECYCLE_ENABLED&&o){const u=podChangeClock(t,r.project).at;await Ie(r);const v=(r.staleVerifiedAt??0)>=u&&u>0,g=podRecycleReason(r,Date.now(),v?0:u,et);if(g==="stale-source-set"&&!nt(r,u)||!g)continue;const h=t.updates?.stateOf(r.wsKey,r.project);if(h==="held"||h==="manual"){const w=`${r.wsKey}/${r.project}:${g}`;Re.has(w)||(Re.add(w),console.log(`[gateway] ${r.project}: ${g} recycle waits \u2014 the service is ${h} (planning/updates), its update decides again`));continue}if(Re.delete(`${r.wsKey}/${r.project}:${g}`),!Le(r)){if(e>=V){console.log(`[gateway] zombie recycle deferred: ${r.project} (${g}) \u2014 ${e} pod(s) already recycled kill-first this sweep (LENSMCP_POD_MAX_CONCURRENT_ROLLS=${V}); it goes on a later sweep.`);continue}e+=1}st(r,g)}continue}r.wedgedSince??=Date.now(),Date.now()-r.wedgedSince>types_1.WEDGE_RECYCLE_GRACE_MS&&(r.wedgedSince=void 0,Pe(r))}}},"sweepOnce");return{scanNow:O,spawnService:Y,ensureUp:Se,scaleUp:We,killSpawned:U,markUp:pe,emitSvc:S,startSweeper:at,rollPod:me,restartService:Qe,recycleWedged:Pe,stopRetiringTrees:ze,finishDyingTrees:qe,stopBuildHost:s(e=>e===void 0?_.stop():_.release(e),"stopBuildHost"),sharedUpdates:_}}m(createServiceLayer,"createServiceLayer"),s(createServiceLayer,"createServiceLayer");function chooseStalePodKillTarget(t,i,l){if(!(t===void 0||!Number.isInteger(t)||t<=1)&&!(i!==void 0&&i!==t)&&t!==l)return t}m(chooseStalePodKillTarget,"chooseStalePodKillTarget"),s(chooseStalePodKillTarget,"chooseStalePodKillTarget");
1
+ "use strict";var wt=Object.defineProperty;var E=(t,c)=>wt(t,"name",{value:c,configurable:!0});var ht=Object.defineProperty,a=E((t,c)=>ht(t,"name",{value:c,configurable:!0}),"a");Object.defineProperty(exports,"__esModule",{value:!0}),exports.startErrorText=startErrorText,exports.scaleTarget=scaleTarget,exports.isLoopbackHostname=isLoopbackHostname,exports.isOwnRunnerCommand=isOwnRunnerCommand,exports.isRunnerOf=isRunnerOf,exports.isTestSourcePath=isTestSourcePath,exports.sourceScanPass=sourceScanPass,exports.sourceSetSnapshot=sourceSetSnapshot,exports.sourceSetSignature=sourceSetSignature,exports.diffSourceSets=diffSourceSets,exports.sourceChangeWindowMs=sourceChangeWindowMs,exports.sourceScopeDirs=sourceScopeDirs,exports.podRecycleReason=podRecycleReason,exports.lensFrontendStale=lensFrontendStale,exports.lensWatcherVerdict=lensWatcherVerdict,exports.podWatcherVerdict=podWatcherVerdict,exports.lensChildWedged=lensChildWedged,exports.isPortConflictExit=isPortConflictExit,exports.podChangeClock=podChangeClock,exports.createServiceLayer=createServiceLayer,exports.chooseStalePodKillTarget=chooseStalePodKillTarget;const tslib_1=require("tslib"),node_child_process_1=require("node:child_process"),node_crypto_1=require("node:crypto"),fs=tslib_1.__importStar(require("node:fs")),http=tslib_1.__importStar(require("node:http")),net=tslib_1.__importStar(require("node:net")),path=tslib_1.__importStar(require("node:path")),node_util_1=require("node:util"),discovery_1=require("./discovery"),instance_1=require("./instance"),pod_sock_1=require("../../../pod-sock"),scope_1=require("./scope"),pod_env_1=require("./pod-env"),pod_probe_1=require("./pod-probe"),service_keys_1=require("./service-keys"),workspace_log_1=require("./workspace-log"),own_log_1=require("./own-log"),inspector_secret_1=require("../../../inspector-secret"),pod_output_1=require("./pod-output"),serve_launch_1=require("./serve-launch"),shared_build_1=require("./shared-build"),service_updates_1=require("./service-updates"),awake_1=require("./awake"),warm_start_1=require("./warm-start"),protocol_1=require("../../../shared-build/protocol"),types_1=require("./types"),exit_reason_1=require("../../../exit-reason"),handoff_retire_1=require("../../../handoff-retire"),process_name_1=require("../../../process-name"),orphan_reaper_1=require("./orphan-reaper");function eastWestEnv(t,c){const d={},p=t.serviceKeys[(0,service_keys_1.serviceKeyId)(c.wsKey,c.project)];if(p&&(d.LENSMCP_SERVICE_KEY=p),t.https){const $=require("../../../basic-ssl").caCertPath();fs.existsSync($)&&(d.NODE_EXTRA_CA_CERTS=$)}return d}E(eastWestEnv,"eastWestEnv"),a(eastWestEnv,"eastWestEnv");const sleep=a(t=>new Promise(c=>setTimeout(c,t)),"sleep"),SRC_EXCLUDE=new Set(["node_modules","dist","tmp","coverage","build","out","target"]),SRC_EXT=new Set([".ts",".tsx",".js",".jsx",".mjs",".cjs",".css",".scss",".sass",".less",".json",".html",".htm",".vue",".svelte",".mdx"]),SCAN_FILE_CAP=1e5;function fnv1a(t){let c=2166136261;for(let d=0;d<t.length;d+=1)c^=t.charCodeAt(d),c=Math.imul(c,16777619);return c>>>0}E(fnv1a,"fnv1a"),a(fnv1a,"fnv1a");const execFileP=(0,node_util_1.promisify)(node_child_process_1.execFile);async function gitIgnoredPaths(t){try{const{stdout:c}=await execFileP("git",["ls-files","--others","--directory","--ignored","--exclude-standard","-z"],{cwd:t,maxBuffer:33554432,timeout:1e4,windowsHide:!0});return new Set(c.split("\0").filter(Boolean))}catch{return new Set}}E(gitIgnoredPaths,"gitIgnoredPaths"),a(gitIgnoredPaths,"gitIgnoredPaths");function startErrorText(t,c){return[t,...(c??[]).slice(-(types_1.START_ERROR_LINES-1))].join(`
2
+ `)}E(startErrorText,"startErrorText"),a(startErrorText,"startErrorText");function scaleTarget(t,c=fs.existsSync){if(t.decl.adminUrl)return{url:t.decl.adminUrl};const d=path.join(t.pool.dir,"parent.sock");return c(d)?{socketPath:d}:t.decl.port?{url:`http://localhost:${t.decl.port}`}:void 0}E(scaleTarget,"scaleTarget"),a(scaleTarget,"scaleTarget");function isLoopbackHostname(t){const c=t.toLowerCase().replace(/^\[(.*)\]$/,"$1").replace(/\.$/,"");return c==="localhost"||c.endsWith(".localhost")?!0:net.isIPv4(c)?c.split(".")[0]==="127":net.isIPv6(c)&&new URL(`http://[${c}]/`).hostname==="[::1]"}E(isLoopbackHostname,"isLoopbackHostname"),a(isLoopbackHostname,"isLoopbackHostname");function postScale(t,c,d){let p;if("socketPath"in t)p=http.request({socketPath:t.socketPath,path:"/webpack/scale",method:"POST",headers:{"content-type":"application/json"}},$=>$.resume());else{const $=t.url.startsWith("https"),C=$?require("node:https"):http,m={method:"POST"};$&&isLoopbackHostname(new URL(t.url).hostname)&&(m.rejectUnauthorized=!1),d&&(m.lookup=d),p=C.request(`${t.url}/webpack/scale`,m,A=>A.resume())}return p.on("error",()=>{}),p.end(JSON.stringify({pods:c})),p}E(postScale,"postScale"),a(postScale,"postScale");function isOwnRunnerCommand(t,c){return(0,serve_launch_1.isServeRunnerCommand)(t)?(0,serve_launch_1.isServeRunnerCommandOf)(t,c):t.includes("/node_modules/nx/")?t.includes(`${c.replace(/\/+$/,"")}/node_modules/nx/`):!0}E(isOwnRunnerCommand,"isOwnRunnerCommand"),a(isOwnRunnerCommand,"isOwnRunnerCommand");function isRunnerOf(t,c,d){const p=c.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return!new RegExp(`(^|\\s)run ${p}(:|\\s|$)`).test(t)||!(0,serve_launch_1.isServeRunnerCommand)(t)&&!/\bnx(\.js)?\b/.test(t)?!1:isOwnRunnerCommand(t,d)}E(isRunnerOf,"isRunnerOf"),a(isRunnerOf,"isRunnerOf");const TEST_FILE_RE=/\.(spec|test|e2e|e2e-spec|stories)\.[cm]?[jt]sx?$/,TEST_DIR_SEGMENTS=new Set(["__tests__","__mocks__","__snapshots__"]);function isTestSourcePath(t){const c=t.split("/"),d=c[c.length-1]??"";if(TEST_FILE_RE.test(d))return!0;for(let p=0;p<c.length-1;p+=1)if(TEST_DIR_SEGMENTS.has(c[p]))return!0;return!1}E(isTestSourcePath,"isTestSourcePath"),a(isTestSourcePath,"isTestSourcePath");function sourceScanPass(t,c,d){const p=d?.ignoreTests??!0;let $;const C=new Map,m=`tree:${path.resolve(t)}`,A=a(_=>path.relative(t,_).split(path.sep).join("/"),"rel"),M=a(async(_,k)=>{const R=await($??=gitIgnoredPaths(t)),D=[],F=new Set;let b=!1;const U=a(async(z,S)=>{if(D.length>=SCAN_FILE_CAP){b=!0;return}let O;try{O=await fs.promises.readdir(z,{withFileTypes:!0})}catch{return}S&&F.add(A(z));for(const J of O){if(D.length>=SCAN_FILE_CAP){b=!0;return}const W=J.name,re=path.join(z,W);if(J.isDirectory()){if(!S||W.startsWith(".")||SRC_EXCLUDE.has(W)||c?.has(W)||W.endsWith("-devserver")||R.has(`${A(re)}/`))continue;await U(re,!0)}else if(J.isFile()){const oe=W.lastIndexOf(".");if(oe<=0||!SRC_EXT.has(W.slice(oe)))continue;const Z=A(re);if(R.has(Z)||p&&isTestSourcePath(Z))continue;D.push(Z)}}},"walk");return await U(_,k),{paths:D,entered:F,truncated:b}},"walkDir"),L=a((_,k)=>{let R=C.get(_);return R||(R=k(),C.set(_,R)),R},"memo"),ce=a(async()=>{const _=C.get(m);if(!_)return;const k=await _;return k.truncated?void 0:k},"wideWalk"),X=new Set,de=a(()=>L(`files:${path.resolve(t)}`,async()=>{const _=await ce();return _?{paths:_.paths.filter(k=>!k.includes("/")),entered:X,truncated:!1}:M(t,!1)}),"rootFiles"),le=a(_=>L(`tree:${path.resolve(_)}`,async()=>{const k=await ce(),R=A(_);if(k?.entered.has(R)){const D=`${R}/`;return{paths:R===""?k.paths:k.paths.filter(F=>F.startsWith(D)),entered:X,truncated:!1}}return M(_,!0)}),"subtree"),V=a(_=>{const k=new Set;let R=0,D=_.some(b=>b.truncated);const F=a(b=>k.has(b)?!0:k.size>=SCAN_FILE_CAP?(D=!0,!1):(k.add(b),R^=fnv1a(b),!0),"add");for(const b of _)if(!b.paths.every(F))break;return{signature:`${k.size}:${(R>>>0).toString(36)}`,paths:k,truncated:D}},"compose");return{async snapshot(_){if(!_||_.length===0)return V([await L(m,()=>M(t,!0))]);const k=[await de()];for(const R of _)k.push(await le(R));return V(k)}}}E(sourceScanPass,"sourceScanPass"),a(sourceScanPass,"sourceScanPass");async function sourceSetSnapshot(t,c,d,p){return sourceScanPass(t,d,p).snapshot(c)}E(sourceSetSnapshot,"sourceSetSnapshot"),a(sourceSetSnapshot,"sourceSetSnapshot");async function sourceSetSignature(t,c,d,p){return(await sourceSetSnapshot(t,c,d,p)).signature}E(sourceSetSignature,"sourceSetSignature"),a(sourceSetSignature,"sourceSetSignature");const SOURCE_DIFF_PATH_CAP=128;function diffSourceSets(t,c,d,p){if(t.paths.size===c.paths.size){let A=!0;for(const M of t.paths)if(!c.paths.has(M)){A=!1;break}if(A)return null}const $=[],C=[];let m=t.truncated||c.truncated;for(const A of c.paths)t.paths.has(A)||($.length+C.length<SOURCE_DIFF_PATH_CAP?$.push(A):m=!0);for(const A of t.paths)c.paths.has(A)||($.length+C.length<SOURCE_DIFF_PATH_CAP?C.push(A):m=!0);return{changedAt:d,added:$,removed:C,truncated:m,...p!==void 0?{windowMs:p}:{}}}E(diffSourceSets,"diffSourceSets"),a(diffSourceSets,"diffSourceSets");function sourceChangeWindowMs(t,c,d,p){const $=c&&c>0?t-c:d;return Math.max($,d)+p}E(sourceChangeWindowMs,"sourceChangeWindowMs"),a(sourceChangeWindowMs,"sourceChangeWindowMs");function sourceScopeDirs(t,c,d,p,$){const C=a(M=>{const L=path.relative(t,M).split(path.sep).filter(Boolean);return L.length===0||L[0].startsWith("..")?"":L[0]},"bucketOf")(c);if(!C)return[];const m=new Set(d.filter(Boolean)),A=new Set([C]);for(const M of p)M.startsWith(".")||SRC_EXCLUDE.has(M)||$?.has(M)||M.endsWith("-devserver")||m.has(M)||A.add(M);return[...A].sort().map(M=>path.join(t,M))}E(sourceScopeDirs,"sourceScopeDirs"),a(sourceScopeDirs,"sourceScopeDirs");function podRecycleReason(t,c,d,p){return!t.proc||t.state!=="up"||t.spawnAt==null||t.inflight>0||(t.activeWork??0)>0||c-t.lastUsed<p.settleMs||t.lastStaleRecycleAt!=null&&c-t.lastStaleRecycleAt<p.cooldownMs?null:d>0&&d-t.spawnAt>p.graceMs?"stale-source-set":p.maxAgeMs>0&&c-t.spawnAt>p.maxAgeMs?"max-age":null}E(podRecycleReason,"podRecycleReason"),a(podRecycleReason,"podRecycleReason");function lensFrontendStale(t,c,d,p,$){return!(p-c<$.cooldownMs||d<=0||d-t<=$.graceMs||p-d<$.settleMs)}E(lensFrontendStale,"lensFrontendStale"),a(lensFrontendStale,"lensFrontendStale");function lensWatcherVerdict(t,c,d,p=[]){if(!t)return"unknown";if("schemaVersion"in t&&t.schemaVersion>=2&&p.length>0){const $=c-d,C=new Set(t.recentEvents.filter(m=>m.at>=$).map(m=>path.resolve(m.path)));return p.every(m=>C.has(path.resolve(m)))?"heard":"missed"}return t.lastFsSetEventAt>=c-d?"heard":"missed"}E(lensWatcherVerdict,"lensWatcherVerdict"),a(lensWatcherVerdict,"lensWatcherVerdict");function podWatcherVerdict(t,c,d){if(!t)return"unknown";if(t.degraded)return"degraded";const p=c-d;return t.lastWatchRunAt>=p||t.lastBuildAt>=p?"heard":"silent"}E(podWatcherVerdict,"podWatcherVerdict"),a(podWatcherVerdict,"podWatcherVerdict");function lensChildWedged(t,c,d,p){const $=t.hasListened?p.graceMs:Math.max(p.graceMs,p.neverListenedGraceMs);return d-t.spawnedAt<$||d-c<p.cooldownMs||t.probeFails<Math.max(2,p.failureThreshold)?null:"wedged-no-listener"}E(lensChildWedged,"lensChildWedged"),a(lensChildWedged,"lensChildWedged");function isPortConflictExit(t,c){return t.signal||t.code===null||t.code===0||t.ranMs>c.fastFailMs?!1:t.portHeld}E(isPortConflictExit,"isPortConflictExit"),a(isPortConflictExit,"isPortConflictExit");function podChangeClock(t,c){const d=t.sourceSetChangedFor?.get(c);if(d!==void 0){const p=t.sourceSetChangesFor?.get(c);return{at:d,...p?{change:p}:{},scope:"project"}}return t.sourceSetScoped?.has(c)?{at:0,scope:"none"}:{at:t.sourceSetChangedAt??0,...t.sourceSetChange?{change:t.sourceSetChange}:{},scope:"workspace"}}E(podChangeClock,"podChangeClock"),a(podChangeClock,"podChangeClock");const changeEvidence=a(t=>{if(!t)return"no path evidence";const c=[...t.added.map(d=>`+${d}`),...t.removed.map(d=>`-${d}`)];return c.length?`${c.slice(0,3).join(", ")}${c.length>3?` (+${c.length-3} more)`:""}`:"no path evidence"},"changeEvidence");function createServiceLayer(t,c,d={}){const p=d.spawnProcess??node_child_process_1.spawn,$=d.probeAlive??pod_probe_1.probePodAlive,C=d.killTree??((e,o="SIGTERM")=>{try{process.kill(-e.pid,o)}catch{try{e.kill(o)}catch{}}}),m=d.sharedBuild??(0,shared_build_1.createSharedBuildRelay)(t),A=a((e,o="SIGTERM")=>{m.detach(e),C(e,o)},"killTree"),M=d.handoffDrainMs??(0,handoff_retire_1.handoffDrainBoundMs)(),L=d.treeAlive??(e=>{if(!e.pid||!(e instanceof node_child_process_1.ChildProcess))return!1;try{return process.kill(-e.pid,0),!0}catch(o){return o.code==="EPERM"}}),ce=d.retirePollMs??1e3,X=d.rollReadyMs??types_1.POD_ROLL_READY_MS,de=d.rollPollMs??750,le=d.maxConcurrentRolls??types_1.POD_MAX_CONCURRENT_ROLLS,V=le>0?le:Number.POSITIVE_INFINITY,_=d.maxConcurrentColdStarts??types_1.MAX_COLD_STARTS,k=_>0?_:Number.POSITIVE_INFINITY;let R=0;const D=[],F=a(()=>R<k?(R+=1,Promise.resolve()):new Promise(e=>{D.push(()=>{R+=1,e()})}),"acquireColdSlot"),b=a(()=>{R-=1,D.shift()?.()},"releaseColdSlot"),{emit:U}=c,z=a(e=>e.wsKey===t.wsKey||!fs.existsSync(path.join(e.root,"package.json"))?void 0:path.join(e.root,".lensmcp","events.jsonl"),"serviceBus"),S=a((e,o,r,s,l)=>U(o,r,s,{wsKey:e.wsKey,...l},void 0,z(e)),"emitSvc"),O=a(e=>(e.scannedAt=0,(0,discovery_1.pickSock)(e,t.scanTtlMs)?e.socks.length:0),"scanNow"),J=a((e,o)=>{let r;try{r=(0,node_child_process_1.execFileSync)("ps",["ax","-ww","-o","pid=,pgid=,command="],{encoding:"utf8",timeout:5e3})}catch{return 0}const s=e.proc?.pid;let l=0;for(const n of r.split(`
3
+ `)){const i=n.match(/^\s*(\d+)\s+(\d+)\s+(.*)$/);if(!i)continue;const u=Number(i[1]),w=Number(i[2]);if(isRunnerOf(i[3],o,e.root)&&!(u===process.pid||u===s)&&!(s!==void 0&&w===s)){try{process.kill(-w,"SIGKILL")}catch{try{process.kill(u,"SIGKILL")}catch{}}l+=1}}return l>0&&(console.log(`[gateway] ${o}: reaped ${l} stale runner tree(s) \u2014 a foreign generation of this service (holding nx's task lock, or its pool)`),S(e,"warning",`stale-runner reap: ${e.project} (${l} foreign tree(s))`,`cluster-service:${e.project}`,{kind:"stale-runner-reap",project:e.project,reaped:l})),l},"reapForeignRunners"),W=a((e,o)=>({...(0,pod_env_1.podBaseEnv)(process.env,t.root,e.root),...e.instanceEnv?{...e.instanceEnv,LENSMCP_SOCKET_ONLY:"1"}:{},...e.frozen?{LENSMCP_FREEZE:"1",LENSMCP_TYPECHECK:"off"}:{},...!e.frozen&&t.updates?.startsHeld(e.wsKey,e.project)?{LENSMCP_UPDATES_HELD:"1"}:{},NX_DAEMON:"false",NX_ISOLATE_PLUGINS:"false",...e.wsKey?{LENSMCP_WS_KEY:e.wsKey}:{},...e.sockNs?{LENSMCP_SOCK_NS:e.sockNs}:{},LENSMCP_EVENT_FILE:e.wsKey===t.wsKey?t.eventFile:path.join(e.root,".lensmcp","events.jsonl"),LENSMCP_GATEWAY_PID:String(process.pid),LENSMCP_POD_GENERATION:String(o),...eastWestEnv(t,e)}),"serviceEnv"),re=a((e,o,r,s)=>{const l=W(e,o),n=e.wsKey||path.basename(e.root),i=(0,serve_launch_1.planServiceLaunch)({stores:t.graphStores,root:e.root,project:e.project,decl:e.decl,childCount:s,baseEnv:l});if(i.kind==="runner"){const v=m.offeredTo(e),f=p((0,process_name_1.namedExecPath)((0,process_name_1.processName)(n,e.project,serve_launch_1.SERVE_RUNNER_ROLE)),[...i.script.execArgv,i.script.path,...(0,serve_launch_1.serveRunnerArgs)(r,s,e.root)],{cwd:e.root,detached:!0,env:v?{...i.env,[protocol_1.SHARED_BUILD_ENV]:"1"}:i.env,stdio:["ignore","pipe","pipe","ipc"]});return v&&m.attach(e,o,f),(0,service_updates_1.listenHeldReports)(e,f,()=>t.updates),f.send?.(i.message,j=>{j&&console.error(`[gateway] ${r}: could not hand the task to its runner (${j.message})`)}),{proc:f,launcher:"runner"}}console.log(`[gateway] ${r}: starting through nx run \u2014 ${i.reason}`);const u=path.join(e.root,"node_modules","nx","dist","bin","nx.js"),w=(0,process_name_1.namedExecPath)((0,process_name_1.processName)(n,e.project,"nx")),[g,h]=fs.existsSync(u)?[w,[u,"run",r,`--childCount=${s}`]]:["yarn",["nx","run",r,`--childCount=${s}`]];return{proc:p(g,h,{cwd:e.root,detached:!0,env:l,stdio:["ignore","pipe","pipe"]}),launcher:"nx"}},"startServiceTree"),oe=new WeakMap,Z=a((e,o,r)=>{const s=`${e.project}:${e.decl.serveTarget??"serve-hmr"}`,l=Math.max(1,e.decl.minPods??1),{proc:n,launcher:i}=re(e,o,s,l);oe.set(n,i),r==="active"&&(e.launcher=i),r==="active"&&(e.lastErrors=[],e.buildFailed=!1,e.faults=new pod_output_1.PodFaults,e.outputTail=[]);const u=a(h=>{const v=h.toString();for(const f of v.split(`
4
+ `)){const j=(0,pod_output_1.classifyPodLine)(f),{clean:T,broken:q,healthy:ne}=j,y=T;if(r==="active"&&e.outputTail&&T.trim()&&(e.outputTail.push(T.trimEnd().slice(0,400)),e.outputTail.length>types_1.OUTPUT_TAIL_LINES&&e.outputTail.shift()),q){e.lastErrors.push(T),e.lastErrors.length>12&&e.lastErrors.shift(),e.buildFailed=!0;const x=Date.now();(T!==e.lastErrorEmitSig||x-(e.lastErrorEmitAt??0)>=types_1.SERVICE_ERROR_THROTTLE_MS)&&(e.lastErrorEmitSig=T,e.lastErrorEmitAt=x,S(e,"error",`service error: ${e.project}`,`cluster-service:${e.project}`,{kind:"service-error",project:e.project,line:T,fault:j.fault}))}ne&&(e.buildFailed=!1);const P=(e.faults??=new pod_output_1.PodFaults).observe(j);if(P){e.lastErrorEmitSig=void 0;const x=P.open.length===0;S(e,"info",`${x?"service recovered":`${P.closed.join(" + ")} recovered`}: ${e.project}`,`cluster-service:${e.project}`,{kind:x?"service-recovered":"service-fault-closed",project:e.project,line:T,closed:P.closed,open:P.open})}!e.lockBlockedAt&&/Waiting for .+ in another nx process/.test(y)&&(e.lockBlockedAt=Date.now(),console.log(`[gateway] ${s}: spawn blocked by a stale nx runner \u2014 breaking the lock + respawning`),S(e,"warning",`nx task lock: ${e.project} blocked by a stale runner \u2014 auto-breaking`,`cluster-service:${e.project}`,{kind:"nx-lock-break",project:e.project}),setTimeout(()=>{t.stopped()||!e.lockBlockedAt||(B(e,"parked on a foreign nx task lock \u2014 recycling",{announce:!1}),J(e,s),setTimeout(()=>{!t.stopped()&&!e.proc&&e.state==="down"&&Y(e)},1500).unref?.())},250).unref?.())}},"sniff"),w=e.wsKey&&e.wsKey!==t.wsKey&&e.root?(0,workspace_log_1.workspaceLogWriter)(e.root):void 0,g=a(h=>{const v=(0,own_log_1.linePrefixer)(e.project);return f=>{if(t.stopped())return;const j=(0,inspector_secret_1.redactInspectorUrls)(f.toString());u(j);const T=v(j);h.write(T),w?.(T)}},"relay");return n.stdout?.on("data",g(process.stdout)),n.stderr?.on("data",g(process.stderr)),n.on("exit",(h,v)=>{if(e.proc!==n||(e.proc=void 0,e.state="down",t.stopped()))return;const f=(0,exit_reason_1.describeExit)(h,v);if(console.log(`[gateway] ${s} exited (${h??"no code"}${v?`, ${v}`:""}${e.inflight?`, ${e.inflight} request(s) in flight`:""})${f?` \u2014 ${f}`:""}`),S(e,h===0?"info":"warning",`service down: ${e.project} (exit ${h})`,`cluster-service:${e.project}`,{kind:"service-down",project:e.project,code:h,...v?{signal:v}:{}}),h===0||e.buildFailed)return;if(e.root!==t.root&&!fs.existsSync(path.join(e.root,"package.json"))){console.log(`[gateway] not respawning ${e.project}: its workspace folder ${e.root} is gone \u2014 the gateway drops the workspace at its next sweep`),S(e,"warning",`not respawning ${e.project}: its workspace folder is gone`,`cluster-service:${e.project}`,{kind:"service-root-gone",project:e.project,root:e.root});return}const j=Date.now();if(e.restarts=(e.restarts??[]).filter(q=>j-q<types_1.SERVICE_RESTART_WINDOW_MS),e.restarts.length>=types_1.SERVICE_MAX_RESTARTS){S(e,"error",`service crash-looping: ${e.project} \u2014 ${types_1.SERVICE_MAX_RESTARTS}+ restarts/min, not auto-respawning (the next request retries)`,`cluster-service:${e.project}`,{kind:"service-crash-loop",project:e.project});return}e.restarts.push(j);const T=Math.min(8e3,500*2**(e.restarts.length-1));setTimeout(()=>{t.stopped()||e.proc||e.state!=="down"||(console.log(`[gateway] self-heal: respawning ${e.project} (restart ${e.restarts.length}/${types_1.SERVICE_MAX_RESTARTS})`),S(e,"info",`self-heal: respawning ${e.project}`,`cluster-service:${e.project}`,{kind:"service-respawn",project:e.project,attempt:e.restarts.length}),Y(e))},T)}),n},"launchServiceProcess"),Y=a(e=>{if(t.stopped()||e.manualStopped)return;const o=`${e.project}:${e.decl.serveTarget??"serve-hmr"}`,r=Math.max(1,e.decl.minPods??1);d.reapForeign!==!1&&J(e,o),e.lockBlockedAt=void 0,console.log(`[gateway] starting ${o} (pods=${r})\u2026`),S(e,"info",`service starting: ${e.project} (${r} pod${r>1?"s":""})`,`cluster-service:${e.project}`,{kind:"service-starting",project:e.project,pods:r}),e.state="starting",e.spawnAt=Date.now(),e.generation=(e.generation??0)+1,e.proc=Z(e,e.generation,"active")},"spawnService"),Ne=a(async e=>{const o=e.pool.socks[0];if(!o)return;const r=await(0,pod_probe_1.probePodAlive)(o,void 0,t.serviceKeys[(0,service_keys_1.serviceKeyId)(e.wsKey,e.project)]);r&&(e.activeWork=r.activeWork,r.watcher&&(e.watcher=r.watcher))},"refreshActiveWork"),Ke=a(e=>{try{const o=Number(fs.readFileSync(`${e}.owner`,"utf8").trim());return Number.isInteger(o)&&o>1?o:void 0}catch{return}},"readOwnerSidecar"),Fe=a(async e=>{const o=t.serviceKeys[(0,service_keys_1.serviceKeyId)(e.wsKey,e.project)];if(!o)return[];const r=(0,node_crypto_1.createHash)("sha256").update(o).digest("hex").slice(0,8),s=[];for(const l of e.pool.socks){const n=await(0,pod_probe_1.probePodAlive)(l,void 0,o);n&&(!n.keyFingerprint||n.keyFingerprint!==r)&&s.push({sock:l,pid:n.pid})}return s},"staleAdoptedSocks"),We=a((e,o)=>{const r=o.map(s=>s.sock);for(const{sock:s,pid:l}of o){const n=chooseStalePodKillTarget(l,Ke(s),process.pid);if(n!==void 0)try{process.kill(n,"SIGTERM")}catch{}try{fs.unlinkSync(s)}catch{}try{fs.unlinkSync(`${s}.owner`)}catch{}}e.pool.socks=e.pool.socks.filter(s=>!r.includes(s)),e.pool.idx=-1,e.pool.scannedAt=0},"evictStaleAdopted"),pe=a((e,o)=>{if(e.state==="up")return!1;e.state="up",e.lastStartError=void 0,e.wedgeRecycles=0;const r=e.pool.socks.length;return S(e,"info",`service up: ${e.project} (${r} pods, ${o})`,`cluster-service:${e.project}`,{kind:"service-up",project:e.project,pods:r,adopted:o==="adopted"}),!0},"markUp"),ve=a(async e=>{if(e.manualStopped)return!1;if(O(e.pool)>0){const s=await Fe(e);if(e.manualStopped)return!1;if(s.length>0&&(console.error(`[gateway] ${e.project}: ${s.length} adopted pod(s) hold a foreign east-west key \u2014 evicting instead of adopting.`),S(e,"warning",`stale adoption: ${e.project} (foreign east-west key)`,`cluster-service:${e.project}`,{kind:"pod-recycle",project:e.project,reason:"stale-adoption",pods:s.length}),e.proc&&B(e,"stale adoption (foreign east-west key)"),We(e,s)),e.pool.socks.length>0)return pe(e,"adopted"),!0}if(t.stopped())return!1;let o=!1;const r=a(()=>e.state!=="starting"&&!e.proc,"notStarted");if(r())if(e.coldWait)await e.coldWait;else{R>=k&&(console.log(`[gateway] cold start queued: ${e.project}${e.wsKey&&e.wsKey!==t.wsKey?` (${e.wsKey})`:""} \u2014 ${R} starting, ${D.length} ahead (LENSMCP_MAX_COLD_STARTS=${k}).`),S(e,"info",`cold start queued: ${e.project}`,`cluster-service:${e.project}`,{kind:"cold-start-queued",project:e.project,inFlight:R,ahead:D.length}));const s=F();if(e.coldWait=s,await s,e.coldWait=void 0,o=!0,t.stopped()||e.manualStopped)return b(),!1;r()&&Y(e)}try{const s=await qe(e);return s?e.lastStartError=void 0:!t.stopped()&&!e.manualStopped&&(e.lastStartError=startErrorText(fe(e),e.outputTail)),s}finally{o&&b()}},"ensureUp"),qe=a(async e=>{const o=Date.now()+t.startupTimeoutMs,r=Date.now()+12e3;for(;!t.stopped()&&!e.manualStopped&&Date.now()<o;){if(await sleep(Math.min(700,t.startupTimeoutMs/4)),e.manualStopped||e.buildFailed&&Date.now()>r)return!1;if(O(e.pool)>0){e.state="up",e.buildFailed=!1;const s=e.spawnAt?Date.now()-e.spawnAt:void 0;return console.log(`[gateway] ${e.project} up (${e.pool.socks.length} pods${s?`, cold start ${s}ms`:""})`),S(e,"info",`cold start: ${e.project} (${e.pool.socks.length} pods, ${s??"?"}ms)`,`cluster-service:${e.project}`,{kind:"cold-start",project:e.project,pods:e.pool.socks.length,durationMs:s}),!0}if(e.state==="down")return!1}return!1},"waitForPods"),Ge=a(e=>{const o=e.decl.maxPods??e.decl.minPods??1,r=e.pool.socks.length,s=scaleTarget(e);!s||r===0||r>=o||e.inflight<=r||Date.now()-e.lastScaleAt<5e3||(e.lastScaleAt=Date.now(),postScale(s,r+1,d.scaleLookup),console.log(`[gateway] autoscale ${e.project}: ${r} \u2192 ${r+1} pods (inflight ${e.inflight})`),S(e,"info",`autoscale: ${e.project} ${r} \u2192 ${r+1} pods`,`cluster-service:${e.project}`,{kind:"autoscale",project:e.project,from:r,to:r+1,inflight:e.inflight}))},"scaleUp"),ue=d.killGraceMs??types_1.TREE_KILL_GRACE_MS,N=new Map,xe=a(e=>{const o=N.get(e);if(!o||(N.delete(e),clearTimeout(o.timer),!L(e)))return;const{svc:r,why:s}=o;console.log(`[gateway] ${r.project}: its tree (pid ${e.pid}) was still running ${Math.round(ue/1e3)}s after it was told to stop (${s}) \u2014 killing it (SIGKILL).`),S(r,"warning",`tree force-killed: ${r.project} (it ignored SIGTERM)`,`cluster-service:${r.project}`,{kind:"tree-force-killed",project:r.project,why:s,pid:e.pid,graceMs:ue}),C(e,"SIGKILL")},"settleDyingTree"),Se=a((e,o,r)=>{if(A(o,"SIGTERM"),ue<=0||N.has(o))return;const s=setTimeout(()=>xe(o),ue);s.unref?.(),N.set(o,{svc:e,why:r,timer:s})},"stopTree"),Ve=a(async(e=3e3)=>{const o=Date.now()+e;for(;N.size>0;){for(const[r,s]of[...N])L(r)||(clearTimeout(s.timer),N.delete(r));if(N.size===0||Date.now()>=o)break;await sleep(100)}for(const r of[...N.keys()])xe(r)},"finishDyingTrees"),B=a((e,o,r)=>{if(!e.proc)return;console.log(`[gateway] ${e.project} ${o} \u2014 scaling to zero.`),r?.announce!==!1&&S(e,"info",`idle kill: ${e.project} (${o})`,`cluster-service:${e.project}`,{kind:"idle-kill",project:e.project,why:o});const s=e.proc;try{s.stdout?.removeAllListeners("data"),s.stderr?.removeAllListeners("data"),s.removeAllListeners("exit")}catch{}(0,discovery_1.stopRoutingTo)(e.pool),Se(e,s,o),e.proc=void 0,e.state="down",setTimeout(()=>{ge(e),e.pool.socks=[],e.pool.scannedAt=0},1200).unref?.()},"killSpawned"),ge=a(e=>{try{for(const o of fs.readdirSync(e.pool.dir)){if(!o.endsWith(".sock"))continue;const r=path.join(e.pool.dir,o);try{const s=Number(fs.readFileSync(`${r}.owner`,"utf8").trim());if(Number.isFinite(s)&&s>0)try{process.kill(s,0);continue}catch{}}catch{}try{fs.unlinkSync(r)}catch{}try{fs.unlinkSync(`${r}.owner`)}catch{}}}catch{}},"sweepDeadOwnerSocks");let Q=0;const ye=[],Ue=a(()=>Q<V?(Q+=1,Promise.resolve()):new Promise(e=>{ye.push(()=>{Q+=1,e()})}),"acquireRollSlot"),Be=a(()=>{Q-=1,ye.shift()?.()},"releaseRollSlot"),$e=a(async(e,o,r)=>{O(e.pool);for(const s of e.pool.socks){const l=await $(s,void 0,r);if(l&&o(l.podGeneration))return!0}return!1},"anyPodAnswers"),he=new Map,He=a((e,o,r)=>{const s=M>0&&(0,handoff_retire_1.requestHandoffRetire)(e.pool.dir,r);if(A(o,"SIGTERM"),!s)return;const l=e.wsKey&&e.wsKey!==t.wsKey&&e.root?(0,workspace_log_1.workspaceLogWriter)(e.root):void 0,n=a(ne=>y=>{if(t.stopped())return;const P=(0,inspector_secret_1.redactInspectorUrls)(y.toString()).replace(/^(?=.)/gm,`[${e.project} g${r} retiring] `);ne.write(P),l?.(P)},"say"),i=n(process.stdout),u=n(process.stderr);o.stdout?.on("data",i),o.stderr?.on("data",u);let w,g=!1;const h=a(()=>{g=!0,clearTimeout(w),o.stdout?.removeListener("data",i),o.stderr?.removeListener("data",u),o.removeListener("close",h)},"releaseLogs");o.once("close",h);let v=!1;const f=a(()=>{v||(v=!0,clearTimeout(j),clearInterval(q),t.stopped()?h():g||(w=setTimeout(h,1e3),w.unref?.()),he.delete(o),(0,handoff_retire_1.clearHandoffRetire)(e.pool.dir,r),ge(e),e.pool.scannedAt=0)},"end"),j=setTimeout(()=>{console.error(`[gateway] pod handoff: ${e.project} g${r} was still running ${M}ms after it was retired \u2014 killing it.`),C(o,"SIGKILL"),f()},M);j.unref?.();const T=a(()=>{if(!v){if(t.stopped()){f();return}L(o)||(console.log(`[gateway] pod handoff: ${e.project} g${r} finished its in-flight work and exited.`),f())}},"look"),q=setInterval(T,ce);q.unref?.(),o.once("exit",T),he.set(o,()=>{f(),Se(e,o,"the gateway is stopping")})},"retireReplacedTree"),Xe=d.standbyGraceMs??3e4,I=new Map,Ye=a((e,o,r,s,l)=>{const n=l+X+Xe,i=setTimeout(()=>be(o),Math.max(0,n-Date.now()));i.unref?.(),I.set(o,{svc:e,generation:r,reason:s,beganAt:l,deadlineAt:n,timer:i})},"holdStandby"),ze=a(e=>{const o=I.get(e);o&&(clearTimeout(o.timer),I.delete(e))},"releaseStandby"),ee=a((e,o)=>{const r=I.get(e);if(!r)return!1;clearTimeout(r.timer),I.delete(e);const{svc:s,generation:l}=r;try{e.stdout?.removeAllListeners("data"),e.stderr?.removeAllListeners("data")}catch{}return(0,discovery_1.stopRoutingTo)(s.pool,n=>(0,pod_sock_1.podSockGeneration)(n)===l),Se(s,e,`standby g${l}: ${o}`),setTimeout(()=>ge(s),1200).unref?.(),!0},"endStandby"),Pe=a((e,o)=>{const r=o.oldServing?`old generation g${o.fromGen} kept serving`:`and the old generation g${o.fromGen} is NOT serving (${o.oldGone?"its tree is gone":"none of its pods answers"}) \u2014 the service is down until it recovers`;console.error(`[gateway] pod handoff failed: ${e.project} g${o.generation}: ${o.why} \u2014 ${r}.`),e.rollFailure=`${o.why} \u2014 ${r}`,S(e,o.oldServing?"warning":"error",`pod handoff failed: ${e.project}`,`cluster-service:${e.project}`,{kind:"pod-handoff-failed",project:e.project,reason:o.reason,generation:o.generation,error:o.why,durationMs:Date.now()-o.beganAt,oldServing:o.oldServing})},"reportStandbyFailed"),be=a(e=>{const o=I.get(e);if(!o)return;const{svc:r,generation:s,reason:l,beganAt:n}=o,i=`the standby outlived its roll (${Math.round((Date.now()-n)/1e3)}s; a roll waits ${Math.round(X/1e3)}s for it)`;ee(e,i);const u=r.proc,w=t.serviceKeys[(0,service_keys_1.serviceKeyId)(r.wsKey,r.project)];(async()=>{const g=!u||u.exitCode!==null||u.signalCode!==null,h=g?!1:await Promise.race([$e(r,f=>f!==s,w).catch(()=>!1),sleep(2e3).then(()=>{})]),v=!t.stopped()&&!g&&(h??O(r.pool)>0);Pe(r,{reason:l,generation:s,fromGen:r.generation??s-1,why:i,beganAt:n,oldServing:v,oldGone:g})})()},"outlivedRoll"),Je=a(()=>{for(const[e,o]of[...I])Date.now()>=o.deadlineAt?be(e):!o.svc.rolling&&o.svc.proc!==e&&(console.error(`[gateway] pod handoff: ${o.svc.project} g${o.generation} is a standby whose roll is over \u2014 stopping it.`),ee(e,"its roll is over"))},"sweepStandbys"),Ze=a(()=>{for(const e of[...he.values()])e();for(const e of[...I.keys()])ee(e,"the gateway is stopping")},"stopRetiringTrees"),me=a((e,o)=>{if(e.rolling)return e.rolling;const r=e.proc;if(!r||t.stopped())return Promise.resolve(!1);if(e.launcher==="nx")return console.log(`[gateway] pod handoff skipped: ${e.project} runs through nx run, which starts one instance of a target at a time \u2014 no standby can overlap it (reason=${o}).`),Promise.resolve(!1);Q>=V&&console.log(`[gateway] pod handoff queued: ${e.project} reason=${o} \u2014 ${Q} roll(s) in flight, ${ye.length} ahead (LENSMCP_POD_MAX_CONCURRENT_ROLLS=${V}).`);const s=(async()=>{await Ue();try{return await Qe(e,r,o)}finally{Be()}})().finally(()=>{e.rolling=void 0});return e.rolling=s,s},"rollPod"),Qe=a(async(e,o,r)=>{const s=e.proc;if(s!==o||t.stopped())return!1;const l=e.generation??0,n=l+1,i=Date.now();e.lastStaleRecycleAt=i,console.log(`[gateway] pod handoff start: ${e.project} g${l}\u2192g${n} reason=${r} \u2014 standby spawning, old generation keeps serving.`),S(e,"info",`pod handoff starting: ${e.project} (${r})`,`cluster-service:${e.project}`,{kind:"pod-handoff-start",project:e.project,reason:r,generation:n,fromGeneration:l});const u=Z(e,n,"standby"),w=t.serviceKeys[(0,service_keys_1.serviceKeyId)(e.wsKey,e.project)];Ye(e,u,n,r,i);let g=!1;try{const h=i+X;let v;for(;!t.stopped()&&Date.now()<h&&I.has(u)&&!(u.exitCode!==null||u.signalCode!==null);){O(e.pool);for(const f of e.pool.socks)if((await $(f,void 0,w))?.podGeneration===n){v=f;break}if(v)break;await sleep(de)}if(!I.has(u))return!1;if(!v||t.stopped()){const f=t.stopped()?"gateway stopping":u.exitCode!==null||u.signalCode!==null?`standby exited (${u.exitCode??u.signalCode})`:`standby not ready within ${Math.round(X/1e3)}s`;ee(u,f);const j=!t.stopped()&&e.proc===s&&s.exitCode===null&&s.signalCode===null&&await $e(e,T=>T!==n,w);return Pe(e,{reason:r,generation:n,fromGen:l,why:f,beganAt:i,oldServing:j,oldGone:e.proc!==s||s.exitCode!==null||s.signalCode!==null}),!1}if(e.proc!==s)return ee(u,"the service was replaced underneath the roll"),!1;ze(u),g=!0,e.proc=u,e.launcher=oe.get(u),e.generation=n,e.spawnAt=i,e.state="up",e.watcher=void 0,e.staleVerifiedAt=void 0,e.staleKeptAt=void 0,e.buildFailed=!1,e.lastErrors=[];try{s.stdout?.removeAllListeners("data"),s.stderr?.removeAllListeners("data"),s.removeAllListeners("exit")}catch{}return(0,discovery_1.stopRoutingTo)(e.pool,f=>(0,pod_sock_1.podSockGeneration)(f)!==n&&path.join(e.pool.dir,f)!==v),He(e,s,l),setTimeout(()=>{ge(e),e.pool.scannedAt=0},1200).unref?.(),console.log(`[gateway] pod handoff ready: ${e.project} g${n} answered on ${path.basename(v)} in ${Date.now()-i}ms; retiring g${l}.`),S(e,"info",`pod handoff complete: ${e.project}`,`cluster-service:${e.project}`,{kind:"pod-handoff-complete",project:e.project,reason:r,generation:n,fromGeneration:l,durationMs:Date.now()-i}),!0}finally{g||ee(u,"its roll ended without it")}},"runRoll"),et=a((e,o)=>{if(t.stopped())return{refused:"the gateway is stopping"};const r=e.restart&&!e.restart.done?e.restart:void 0,s=r?void 0:tt(e);if(s&&"refused"in s)return console.error(`[gateway] restart refused: ${e.project}${e.wsKey!==t.wsKey?` (${e.wsKey})`:""} \u2014 ${s.refused}`),S(e,"warning",`restart refused: ${e.project}`,`cluster-service:${e.project}`,{kind:"service-restart",phase:"refused",project:e.project,reason:o.reason,error:s.refused}),{refused:s.refused};const l=s&&"applied"in s?s:void 0;if(e.manualStopped=!1,e.actionFailure=void 0,r)return{restart:r,already:!0};if(!e.proc&&e.state!=="down")return{refused:`${e.project} is served by pods this gateway adopted from an earlier one \u2014 it has no tree of its own to replace. \`lensmcp gateway restart\` starts every service under this gateway.`};const n=e.proc?o.hard||e.launcher==="nx"||e.state!=="up"?"hard":"rolling":"start",i={how:n,reason:o.reason,startedAt:Date.now(),...e.proc&&e.generation!==void 0?{fromGeneration:e.generation}:{},...l?{env:l.applied}:{}};l&&(e.instanceEnv=l.env),e.restart=i,e.lastUsed=i.startedAt;const u=i.env?{envFingerprint:i.env.fingerprint,envChanged:i.env.changed}:{},w=i.env?` Instance variables ${i.env.fingerprint}: ${i.env.changed.length?`changed ${i.env.changed.join(", ")}`:"unchanged"}.`:"";return console.log(`[gateway] restart asked: ${e.project}${e.wsKey!==t.wsKey?` (${e.wsKey})`:""} \u2014 ${n} (${o.reason}).${w}`),S(e,"info",`restart asked: ${e.project} (${n})`,`cluster-service:${e.project}`,{kind:"service-restart",phase:"started",project:e.project,how:n,reason:o.reason,...i.fromGeneration!==void 0?{fromGeneration:i.fromGeneration}:{},...u}),a(async()=>{if(n==="start")return await ve(e)?{ok:!0}:{ok:!1,error:fe(e)};if(n==="rolling")return e.rolling&&await e.rolling,e.proc?(e.rollFailure=void 0,await me(e,o.reason)?{ok:!0}:{ok:!1,error:e.rollFailure??"the new tree did not take over"}):await ve(e)?{ok:!0}:{ok:!1,error:fe(e)};if(B(e,`restart asked (${o.reason})`,{announce:!1}),await sleep(1500),t.stopped())return{ok:!1,error:"the gateway is stopping"};let g=!1;e.proc||(await F(),g=!0,!e.proc&&e.state!=="starting"&&Y(e));try{const h=e.proc,v=e.generation,f=t.serviceKeys[(0,service_keys_1.serviceKeyId)(e.wsKey,e.project)],j=Date.now()+t.startupTimeoutMs;for(;!t.stopped()&&Date.now()<j;){if(!h||e.proc!==h||h.exitCode!==null||h.signalCode!==null)return{ok:!1,error:fe(e)};if(await $e(e,T=>T===v,f))return pe(e,"observed"),e.buildFailed=!1,{ok:!0};await sleep(de)}return{ok:!1,error:t.stopped()?"the gateway is stopping":`no pod of the new tree answered within ${Math.round(t.startupTimeoutMs/1e3)}s`}}finally{g&&b()}},"run")().catch(g=>({ok:!1,error:g.message})).then(g=>{i.done={ok:g.ok,at:Date.now(),...e.generation!==void 0?{generation:e.generation}:{},...g.error?{error:g.error}:{}},g.ok&&(e.lastUsed=i.done.at);const h=Math.round((i.done.at-i.startedAt)/100)/10;g.ok?console.log(`[gateway] restarted: ${e.project} \u2014 g${i.done.generation??"?"} serving after ${h}s (${n}).`):console.error(`[gateway] restart failed: ${e.project} \u2014 ${g.error} (${n}, after ${h}s).`),S(e,g.ok?"info":"error",g.ok?`restarted: ${e.project}`:`restart failed: ${e.project}`,`cluster-service:${e.project}`,{kind:"service-restart",phase:g.ok?"done":"failed",project:e.project,how:n,reason:o.reason,...i.fromGeneration!==void 0?{fromGeneration:i.fromGeneration}:{},...i.done.generation!==void 0?{generation:i.done.generation}:{},durationMs:i.done.at-i.startedAt,...g.error?{error:g.error}:{},...u})}),{restart:i,already:!1}},"restartService"),tt=a(e=>{if(!e.instanceBuiltins)return;const o=(0,instance_1.readInstanceEnvStrict)(e.root,e.instanceBuiltins);if("reason"in o)return{refused:`the instance variables of ${e.project} could not be read again \u2014 ${o.reason}. Nothing was restarted: the running tree keeps what it has. Fix the file, then restart it again.`};const r=e.instanceEnv??{};return{env:o.env,applied:{fingerprint:(0,instance_1.instanceEnvFingerprint)(o.env),fromFingerprint:(0,instance_1.instanceEnvFingerprint)(r),changed:(0,instance_1.changedInstanceEnvNames)(r,o.env)}}},"restartEnv"),rt=a(e=>{const o=e.proc?m.firstBuild(e):void 0;return!!o&&"waiting"in o},"awaitsSharedBuild"),fe=a(e=>e.buildFailed?`its build failed${e.lastErrors?.length?`: ${e.lastErrors[e.lastErrors.length-1]}`:""}`:e.proc&&(e.proc.exitCode!==null||e.proc.signalCode!==null)?`its tree exited (${e.proc.exitCode??e.proc.signalCode})`:!e.proc&&e.state==="down"?"its tree exited before a pod answered":rt(e)?`no pod answered within ${Math.round(t.startupTimeoutMs/1e3)}s \u2014 its first build from the workspace's build host has not finished yet; it starts once the build reaches it`:`no pod answered within ${Math.round(t.startupTimeoutMs/1e3)}s`,"startFailure"),De=a(e=>{const o=Date.now();e.restarts=(e.restarts??[]).filter(s=>o-s<types_1.SERVICE_RESTART_WINDOW_MS);const r=(e.wedgeRecycles??0)+1;if(e.restarts.length>=types_1.SERVICE_MAX_RESTARTS||r>types_1.SERVICE_MAX_RESTARTS){const s=e.restarts.length>=types_1.SERVICE_MAX_RESTARTS?`wedged ${types_1.SERVICE_MAX_RESTARTS}+\xD7/min`:`recycled ${types_1.SERVICE_MAX_RESTARTS}\xD7 in a row and no pod came up`;S(e,"error",`service crash-looping: ${e.project} \u2014 ${s}, not auto-recycling (the next request retries)`,`cluster-service:${e.project}`,{kind:"service-crash-loop",project:e.project,recycles:r-1}),B(e,"wedged (crash-loop cap) \u2014 leaving down for the next request",{announce:!1});return}e.wedgeRecycles=r,e.restarts.push(o),console.log(`[gateway] self-heal: recycling WEDGED ${e.project} (live parent, 0 live pods; attempt ${r}/${types_1.SERVICE_MAX_RESTARTS} with no pod up since the first, ${e.restarts.length} in the last minute; ${e.inflight??0} request(s) in flight \u2014 jobs held by the dead pod keep their locks until they expire)`),S(e,"warning",`self-heal: recycling wedged ${e.project} (0 live pods)`,`cluster-service:${e.project}`,{kind:"service-recycle",project:e.project,attempt:r,inWindow:e.restarts.length}),B(e,"wedged: 0 live pods \u2014 recycling",{announce:!1}),setTimeout(()=>{!t.stopped()&&!e.proc&&e.state==="down"&&Y(e)},1500).unref?.()},"recycleWedged"),ot={maxAgeMs:types_1.POD_MAX_AGE_MS,graceMs:types_1.POD_STALE_GRACE_MS,settleMs:types_1.POD_RECYCLE_SETTLE_MS,cooldownMs:types_1.POD_STALE_RECYCLE_COOLDOWN_MS};let Ee;const se=new Map,_e=new Map;let ke=!1,je=0,we=0;const st=a(()=>{const e=t.projectRoots??{},o=new Set(t.services.map(s=>s.project));for(const s of t.routes)s.lens&&o.add(s.lens.project);const r=new Set;for(const s of o){const l=e[s];if(!l)continue;const n=path.relative(t.root,l).split(path.sep).filter(Boolean)[0];n&&!n.startsWith("..")&&r.add(n)}return[...r]},"managedBuckets"),nt=a((e,o,r,s)=>{const l=t.projectSourceRoots?.[e];if(l?.length)return l;const n=t.projectRoots?.[e];if(!n)return;const i=sourceScopeDirs(t.root,n,r,o,s);return i.length>0?i:void 0},"scopeFor"),at=a(()=>{if(ke||Date.now()-je<types_1.POD_STALE_SCAN_MS)return;ke=!0,je=Date.now();const e=je;(async()=>{const o=(0,scope_1.readSourceSetOptions)(t.root),r=o.exclude,s={ignoreTests:o.ignoreTests},l=sourceScanPass(t.root,r,s),n=await l.snapshot(),i=Date.now(),u=sourceChangeWindowMs(i,we,types_1.POD_STALE_SCAN_MS,types_1.POD_RECYCLE_SETTLE_MS),w=Ee?diffSourceSets(Ee,n,i,u):null;if(w&&(t.sourceSetChangedAt=i,t.sourceSetChange=w,U("info","source file set changed \u2014 stale pods recycle when idle","cluster-gateway",{kind:"source-set-changed",added:w.added,removed:w.removed,truncated:w.truncated})),Ee=n,!t.projectRoots){we=e;return}let g;try{g=(await fs.promises.readdir(t.root,{withFileTypes:!0})).filter(y=>y.isDirectory()).map(y=>y.name)}catch{return}const h=st(),v=new Set(t.services.map(y=>y.project));for(const y of t.routes)y.lens&&v.add(y.lens.project);const f=new Map;for(const y of v){const P=nt(y,g,h,r);if(!P)continue;const x=P.join("|"),G=f.get(x)??{dirs:P,projects:[]};G.projects.push(y),f.set(x,G)}const j=Date.now(),T=sourceChangeWindowMs(j,we,types_1.POD_STALE_SCAN_MS,types_1.POD_RECYCLE_SETTLE_MS);we=e;const q=a((y,P,x)=>{t.sourceSetChangedFor??=new Map,t.sourceSetChangesFor??=new Map;for(const G of y)t.sourceSetChangedFor.set(G,P),t.sourceSetChangesFor.set(G,x)},"stampScoped"),ne=new Set([...f.values()].flatMap(y=>y.projects));for(const y of[...t.sourceSetScoped??[]])ne.has(y)||t.sourceSetScoped.delete(y);for(const[y,{dirs:P,projects:x}]of f){const G=await l.snapshot(P),Me=se.get(y);if(Me||x.some(K=>_e.has(K))){t.sourceSetScoped??=new Set;for(const K of x)t.sourceSetScoped.add(K)}se.set(y,G);const Ce=new Map;for(const K of x){const H=_e.get(K);if(H===void 0||H===y)continue;const te=Ce.get(H)??[];te.push(K),Ce.set(H,te)}for(const K of x)_e.set(K,y);for(const[K,H]of Ce){const te=se.get(K),ie=te?diffSourceSets(te,G,j,T):w;ie&&(q(H,te?j:i,ie),U("info",`source file set changed \u2014 ${H.join(", ")}'s watch scope was re-keyed`,"cluster-gateway",{kind:"source-set-changed",scoped:!0,rescoped:!0,projects:H,added:ie.added,removed:ie.removed,truncated:ie.truncated}))}if(!Me)continue;const ae=diffSourceSets(Me,G,j,T);ae&&(q(x,j,ae),U("info",`source file set changed in ${x.join(", ")}'s scope`,"cluster-gateway",{kind:"source-set-changed",scoped:!0,projects:x,added:ae.added,removed:ae.removed,truncated:ae.truncated}))}for(const y of[...se.keys()])f.has(y)||se.delete(y)})().catch(()=>{}).finally(()=>{ke=!1})},"maybeScanSourceSet"),it=a((e,o)=>{const r=podChangeClock(t,e.project),s=r.change,l=`${r.scope==="project"?"in its scope":"in the workspace (its scope is not known)"}: ${changeEvidence(s)}`,n=s?.windowMs??types_1.POD_STALE_SCAN_MS+types_1.POD_RECYCLE_SETTLE_MS,i=podWatcherVerdict(e.watcher,o,n),u=a(g=>(e.staleKeptAt!==o&&(e.staleKeptAt=o,console.log(`[gateway] stale source set: pod ${e.project} ${g} \u2014 no recycle.`)),!1),"keep");if(i==="heard")return e.staleVerifiedAt=o,S(e,"info",`stale check: ${e.project} watcher confirmed \u2014 no recycle`,`cluster-service:${e.project}`,{kind:"pod-stale-verified",project:e.project,watcher:i}),u(`watcher CONFIRMED alive across the change (last build ${new Date(e.watcher?.lastBuildAt??0).toISOString()})`);if(i==="degraded")return console.log(`[gateway] stale source set: pod ${e.project} watcher DEGRADED (${e.watcher?.degraded}) \u2014 recycling.`),!0;const w=a(g=>(e.staleKeptAt!==o&&(e.staleKeptAt=o,console.log(`[gateway] stale source set: pod ${e.project} ${g}; the change ${l} \u2014 recycling.`)),!0),"recycling");return i==="silent"?types_1.POD_WATCHER_SILENT==="keep"?u("watcher alive but quiet across the change \u2014 keeping it (LENSMCP_POD_WATCHER_SILENT=keep; a live watcher cannot miss an add it will need)"):w("watcher alive but quiet across the change"):types_1.POD_WATCHER_UNVERIFIED==="keep"?u("unverifiable (no watcher testimony \u2014 older devserver bundle?) \u2014 keeping it (LENSMCP_POD_WATCHER_UNVERIFIED=keep)"):w("watcher unverifiable (no testimony yet \u2014 a pod that never rebuilt, or an older devserver bundle)")},"podStaleRecycleAllowed"),Le=a(e=>types_1.POD_RECYCLE_MODE==="rolling"&&!!e.proc&&e.launcher!=="nx","recycleRolls"),ct=a((e,o)=>{if(e.lastStaleRecycleAt=Date.now(),Le(e)){me(e,o);return}console.log(`[gateway] zombie recycle: ${e.project} (${o}) \u2014 stale fs view; fresh pod incoming`);const r=!!e.decl.eager;S(e,"warning",`zombie recycle: ${e.project} (${o})`,`cluster-service:${e.project}`,{kind:"pod-recycle",project:e.project,reason:o,respawn:r}),B(e,`${o} \u2014 recycling stale pod`,{announce:!1}),r&&setTimeout(()=>{!t.stopped()&&!e.proc&&e.state==="down"&&Y(e)},1500).unref?.()},"recyclePod"),Re=new Set;let Te,Ae=0;const dt=a(e=>{const o=Date.now(),r=Te===void 0?0:o-Te;if(Te=o,r<=t.sweepMs+types_1.SWEEP_WAKE_GAP_MS)return;Ae=o;const s=e.filter(n=>n.proc&&(n.state==="starting"||n.wedgedSince!==void 0)).map(n=>n.project);console.log(`[gateway] no sweep for ${Math.round(r/1e3)}s (it runs every ${Math.round(t.sweepMs/1e3)}s): the machine slept, or the gateway was frozen \u2014 the startup window and the wedge grace start again now, so no service is recycled as wedged for that time${s.length?` (${s.join(", ")})`:""}`);const l=new Map([[void 0,t.wsKey]]);for(const n of e){const i=z(n);l.has(i)||l.set(i,n.wsKey)}for(const[n,i]of l)U("info",`gateway woke: no sweep for ${Math.round(r/1e3)}s \u2014 the startup and wedge clocks start again`,"cluster-gateway",{kind:"gateway-wake",project:"gateway",...i?{wsKey:i}:{},gapMs:r,sweepMs:t.sweepMs,from:o-r},void 0,n)},"noticeWake"),lt=a((e,o)=>{if(e.state!=="starting"||e.spawnAt===void 0)return!1;const r=m.firstBuild(e);if(r&&"waiting"in r)return!0;const s=r&&"builtAt"in r?r.builtAt:0;return o-Math.max(e.spawnAt,s,Ae)<t.startupTimeoutMs},"inStartWindow"),pt=a(e=>{const o=setInterval(()=>{if(e&&!t.stopped())try{e()}catch(r){console.error("[gateway] park sweep error:",r)}ft().catch(r=>console.error("[gateway] sweep error:",r))},t.sweepMs);return o.unref(),o},"startSweeper"),ut=d.listProcesses??(()=>{try{return(0,orphan_reaper_1.parsePsRows)((0,node_child_process_1.execFileSync)("ps",orphan_reaper_1.PS_ROW_ARGS,{encoding:"utf8",timeout:5e3}))}catch{return[]}}),Ie=d.signalProcess??((e,o)=>{process.kill(e,o)});let Oe=0;const gt=a(()=>{if(typeof process.getuid!="function")return 0;const e=t.registry?t.registry.allServices():t.services;if(e.length===0)return 0;const o=e.map(n=>({label:n.wsKey||path.basename(n.root),project:n.project,root:n.root,svc:n})),r=new Set;for(const n of e)n.proc?.pid&&r.add(n.proc.pid);for(const n of[...he.keys(),...N.keys(),...I.keys()])n.pid&&r.add(n.pid);const s=[...new Set((0,process_name_1.defaultLinkDirs)().flatMap(n=>{try{return[n,fs.realpathSync(n)]}catch{return[n]}}))];let l=0;for(const n of(0,orphan_reaper_1.findOrphanExecutors)(ut(),o,{linkDirs:s,uid:process.getuid(),selfPid:process.pid,ownGroups:r})){const{row:i}=n;try{Ie(n.group?-i.pgid:i.pid,"SIGKILL")}catch(w){if(w.code!=="ESRCH"||!n.group)continue;try{Ie(i.pid,"SIGKILL")}catch{continue}}l+=1;const u=n.owner.svc;console.log(`[gateway] reaped an orphaned executor of ${u.project} (${n.role}, pid ${i.pid}${n.group?`, group ${i.pgid}`:""}, parent gone) \u2014 a stopped tree it outlived: ${i.command.slice(0,160)}`),S(u,"warning",`orphan reap: ${u.project} (pid ${i.pid})`,`cluster-service:${u.project}`,{kind:"orphan-executor-reap",project:u.project,pid:i.pid,pgid:i.pgid,role:n.role,group:n.group})}return l},"reapOrphanExecutors"),ft=a(async()=>{{if(t.stopped())return;const e=t.registry?t.registry.allServices():t.services;dt(e),Je(),d.reapForeign!==!1&&types_1.ORPHAN_REAP_EVERY_MS>0&&Date.now()-Oe>=types_1.ORPHAN_REAP_EVERY_MS&&(Oe=Date.now(),gt());for(const r of t.graphStores?.all()??[])r.refreshIfStale();types_1.POD_RECYCLE_ENABLED&&at();let o=0;for(const r of e){if(t.stopped()||!r.proc){r.wedgedSince=void 0;continue}const s=path.resolve(r.root)===path.resolve(t.root),l=(0,warm_start_1.serviceIdleSec)(t,r),n=(0,awake_1.idleStopAt)(r,l);if(n!==void 0&&r.state==="up"&&(!r.restart||r.restart.done)&&r.inflight===0&&Date.now()>n){r.lastIdleStop={at:Date.now(),why:`no request for ${l}s${(r.awakeUntil??0)>r.lastUsed?" after its hold ended":""}`},B(r,`idle ${l}s`),r.wedgedSince=void 0;continue}const i=lt(r,Date.now()),u=O(r.pool)>0;if(u||i){if(r.wedgedSince=void 0,u&&pe(r,"observed"),u&&!i&&types_1.POD_RECYCLE_ENABLED&&s){const w=podChangeClock(t,r.project).at;await Ne(r);const g=(r.staleVerifiedAt??0)>=w&&w>0,h=podRecycleReason(r,Date.now(),g?0:w,ot);if(h==="stale-source-set"&&!it(r,w)||!h)continue;const v=t.updates?.stateOf(r.wsKey,r.project);if(v==="held"||v==="manual"){const f=`${r.wsKey}/${r.project}:${h}`;Re.has(f)||(Re.add(f),console.log(`[gateway] ${r.project}: ${h} recycle waits \u2014 the service is ${v} (planning/updates), its update decides again`));continue}if(Re.delete(`${r.wsKey}/${r.project}:${h}`),!Le(r)){if(o>=V){console.log(`[gateway] zombie recycle deferred: ${r.project} (${h}) \u2014 ${o} pod(s) already recycled kill-first this sweep (LENSMCP_POD_MAX_CONCURRENT_ROLLS=${V}); it goes on a later sweep.`);continue}o+=1}ct(r,h)}continue}(r.wedgedSince===void 0||r.wedgedSince<Ae)&&(r.wedgedSince=Date.now()),Date.now()-r.wedgedSince>types_1.WEDGE_RECYCLE_GRACE_MS&&(r.wedgedSince=void 0,De(r))}}},"sweepOnce");return{scanNow:O,spawnService:Y,ensureUp:ve,scaleUp:Ge,killSpawned:B,markUp:pe,emitSvc:S,startSweeper:pt,rollPod:me,restartService:et,recycleWedged:De,stopRetiringTrees:Ze,finishDyingTrees:Ve,stopBuildHost:a(e=>e===void 0?m.stop():m.release(e),"stopBuildHost"),sharedUpdates:m}}E(createServiceLayer,"createServiceLayer"),a(createServiceLayer,"createServiceLayer");function chooseStalePodKillTarget(t,c,d){if(!(t===void 0||!Number.isInteger(t)||t<=1)&&!(c!==void 0&&c!==t)&&t!==d)return t}E(chooseStalePodKillTarget,"chooseStalePodKillTarget"),a(chooseStalePodKillTarget,"chooseStalePodKillTarget");
@@ -2,7 +2,7 @@ import type * as http from 'node:http';
2
2
  import type { GwTrace, Route } from './types';
3
3
  export type Severity = 'info' | 'warning' | 'error';
4
4
  /**
5
- * The lens's OWN dashboard route project (the value `lens-children.ts` gives the `lensmcp.local/<key>/`
5
+ * The lens's OWN dashboard route project (the value `lens-children.ts` gives the `lensmcp.localhost/<key>/`
6
6
  * route). Traffic to it is the lens UI talking to its own control-plane API (`/<key>/api/stream` and
7
7
  * on-demand `/<key>/api/*` reads) — pure self-observation with NO app-diagnostic value. Its SUCCESSFUL request narration + traffic
8
8
  * edges are suppressed from the bus (the same "don't bloat the bus" rationale as header-less traffic); a 5xx
@@ -8,7 +8,7 @@ export interface ParkedDashboard {
8
8
  root: string;
9
9
  /** Its own apex (`gate1.foodguard.localhost`), when its base's hosts name one. */
10
10
  apex?: string;
11
- /** Where its dashboard answers (`lensmcp.local` + `/<key>`) — absent when this gateway hosts no dashboards. */
11
+ /** Where its dashboard answers (`lensmcp.localhost` + `/<key>`) — absent when this gateway hosts no dashboards. */
12
12
  host?: string;
13
13
  base?: string;
14
14
  }
@@ -45,7 +45,7 @@ export interface ParkedDashboards {
45
45
  * there was one. The caller rebuilds the routes, as a registration does anyway.
46
46
  */
47
47
  drop(wsKey: string): Promise<boolean>;
48
- /** The parked worktrees and where each one's dashboard answers — what the chooser at `lensmcp.local/` lists. */
48
+ /** The parked worktrees and where each one's dashboard answers — what the chooser at `lensmcp.localhost/` lists. */
49
49
  list(): ParkedDashboard[];
50
50
  /** The daemon stops: every parked dashboard goes. */
51
51
  close(): void;
@@ -10,7 +10,7 @@ export interface HostConflict {
10
10
  heldByRoot: string;
11
11
  }
12
12
  export interface Refusal {
13
- error: 'key-in-use' | 'host-conflict' | 'not-your-registration' | 'daemon-workspace' | 'reserved-host';
13
+ error: 'key-in-use' | 'host-conflict' | 'not-your-registration' | 'daemon-workspace' | 'reserved-host' | 'reserved-key';
14
14
  /** One sentence a person can act on. The CLI prints it as is. */
15
15
  message: string;
16
16
  heldByRoot?: string;
@@ -25,6 +25,11 @@ export declare function hostConflicts(registry: RouteRegistry, fragment: Workspa
25
25
  * them, as a host or as an apex; only LensMCP's own dashboard routes do.
26
26
  */
27
27
  export declare const RESERVED_HOSTS: readonly string[];
28
+ /**
29
+ * Workspace keys LensMCP keeps for itself: `canvas` — `lensmcp.localhost/canvas/<id>` is the key-free canvas link
30
+ * (canvas-link.ts, planning/canvas §8), so no workspace's dashboard may be mounted at `/canvas`.
31
+ */
32
+ export declare const RESERVED_WORKSPACE_KEYS: readonly string[];
28
33
  /** The reserved name a host or apex falls under, if any. */
29
34
  export declare function reservedHostOf(name: string | undefined): string | undefined;
30
35
  /** Why this registration must not go in — or `undefined` when it may. */
@@ -1 +1 @@
1
- "use strict";var f=Object.defineProperty;var a=(o,e)=>f(o,"name",{value:e,configurable:!0});var u=Object.defineProperty,i=a((o,e)=>u(o,"name",{value:e,configurable:!0}),"i");Object.defineProperty(exports,"__esModule",{value:!0}),exports.RESERVED_HOSTS=exports.sameRoot=void 0,exports.canonicalRoot=canonicalRoot,exports.hostConflicts=hostConflicts,exports.reservedHostOf=reservedHostOf,exports.refuseRegistration=refuseRegistration,exports.refuseUnregistration=refuseUnregistration;const tslib_1=require("tslib"),fs=tslib_1.__importStar(require("node:fs")),path=tslib_1.__importStar(require("node:path"));function canonicalRoot(o){try{return fs.realpathSync(o)}catch{return path.resolve(o)}}a(canonicalRoot,"canonicalRoot"),i(canonicalRoot,"canonicalRoot");const sameRoot=i((o,e)=>canonicalRoot(o)===canonicalRoot(e),"sameRoot");exports.sameRoot=sameRoot;function claim(o){return o.host?`${o.host.toLowerCase()} ${o.prefix??""}`:o.apex?`* ${o.apex.toLowerCase()}`:void 0}a(claim,"claim"),i(claim,"claim");function hostConflicts(o,e){const n=[],t=new Set;for(const r of o.keys()){if(r===e.wsKey)continue;const s=o.get(r);if(!s)continue;const c=new Set(s.routes.map(claim));for(const h of e.routes){const l=claim(h);!l||!c.has(l)||t.has(l)||(t.add(l),n.push({host:h.host??`(default for ${h.apex})`,...h.prefix?{prefix:h.prefix}:{},heldBy:r,heldByRoot:s.root}))}}return n}a(hostConflicts,"hostConflicts"),i(hostConflicts,"hostConflicts");const describeConflict=i(o=>`${o.host}${o.prefix??""} (served by '${o.heldBy}')`,"describeConflict");exports.RESERVED_HOSTS=["lensmcp.localhost","canvas.localhost","lensmcp.local"];const DASHBOARD_PROJECT="(lens-dashboard)";function reservedHostOf(o){const e=(o??"").trim().toLowerCase().replace(/\.$/,"");if(e)return exports.RESERVED_HOSTS.find(n=>e===n||e.endsWith(`.${n}`))}a(reservedHostOf,"reservedHostOf"),i(reservedHostOf,"reservedHostOf");function refuseRegistration(o,e){const n=e.routes.filter(s=>s.project!==DASHBOARD_PROJECT).map(s=>({route:s,name:reservedHostOf(s.host)??reservedHostOf(s.apex)})).filter(s=>s.name!==void 0);if(n.length>0){const s=[...new Set(n.map(c=>c.route.host??`*.${c.route.apex}`))].slice(0,6).join(", ");return{error:"reserved-host",message:`'${e.wsKey}' declares ${s}, under a name LensMCP keeps for itself (${exports.RESERVED_HOSTS.join(", ")} and every name below them): its dashboard and the canvas frame live there. Give the app hosts of its own (an apex like \`${e.wsKey}.localhost\`).`}}const t=o.get(e.wsKey);if(t&&!(0,exports.sameRoot)(t.root,e.root))return{error:"key-in-use",heldByRoot:t.root,message:`'${e.wsKey}' is already served from ${t.root}. ${e.root} is another checkout that derives the same key, and two checkouts cannot share a key or hosts behind one gateway: registering this one would replace the other's routes. To serve it beside the other under hosts of its own, run \`lensmcp instance start\` in ${e.root}; otherwise run \`lensmcp gateway stop\` in ${t.root} first.`};const r=hostConflicts(o,e);if(r.length>0){const s=r.slice(0,6).map(describeConflict).join(", "),c=r.length>6?`, and ${r.length-6} more`:"";return{error:"host-conflict",conflicts:r,message:`'${e.wsKey}' declares ${r.length===1?"a host":`${r.length} hosts`} another workspace already serves: ${s}${c}. The workspace registered first would win every request to ${r.length===1?"it":"them"}, so this registration is refused. Two workspaces behind one gateway need different hosts \u2014 for a second checkout of a workspace, \`lensmcp instance start\` in it serves it under hosts named after it.`}}}a(refuseRegistration,"refuseRegistration"),i(refuseRegistration,"refuseRegistration");function refuseUnregistration(o,e,n){const t=o.get(e.wsKey);if(t&&e.root&&!(0,exports.sameRoot)(t.root,e.root))return{error:"not-your-registration",heldByRoot:t.root,message:`'${e.wsKey}' is served from ${t.root}, not from ${e.root} \u2014 nothing of this checkout is registered, so nothing was removed.`};if(t&&n!==void 0&&e.wsKey===n)return{error:"daemon-workspace",heldByRoot:t.root,message:`'${e.wsKey}' is the workspace that owns the gateway \u2014 unregistering it would leave :443 serving without it. Stop the gateway instead: \`lensmcp gateway stop\` in ${t.root}.`}}a(refuseUnregistration,"refuseUnregistration"),i(refuseUnregistration,"refuseUnregistration");
1
+ "use strict";var p=Object.defineProperty;var a=(o,e)=>p(o,"name",{value:e,configurable:!0});var l=Object.defineProperty,i=a((o,e)=>l(o,"name",{value:e,configurable:!0}),"i");Object.defineProperty(exports,"__esModule",{value:!0}),exports.RESERVED_WORKSPACE_KEYS=exports.RESERVED_HOSTS=exports.sameRoot=void 0,exports.canonicalRoot=canonicalRoot,exports.hostConflicts=hostConflicts,exports.reservedHostOf=reservedHostOf,exports.refuseRegistration=refuseRegistration,exports.refuseUnregistration=refuseUnregistration;const tslib_1=require("tslib"),fs=tslib_1.__importStar(require("node:fs")),path=tslib_1.__importStar(require("node:path"));function canonicalRoot(o){try{return fs.realpathSync(o)}catch{return path.resolve(o)}}a(canonicalRoot,"canonicalRoot"),i(canonicalRoot,"canonicalRoot");const sameRoot=i((o,e)=>canonicalRoot(o)===canonicalRoot(e),"sameRoot");exports.sameRoot=sameRoot;function claim(o){return o.host?`${o.host.toLowerCase()} ${o.prefix??""}`:o.apex?`* ${o.apex.toLowerCase()}`:void 0}a(claim,"claim"),i(claim,"claim");function hostConflicts(o,e){const n=[],t=new Set;for(const r of o.keys()){if(r===e.wsKey)continue;const s=o.get(r);if(!s)continue;const c=new Set(s.routes.map(claim));for(const h of e.routes){const f=claim(h);!f||!c.has(f)||t.has(f)||(t.add(f),n.push({host:h.host??`(default for ${h.apex})`,...h.prefix?{prefix:h.prefix}:{},heldBy:r,heldByRoot:s.root}))}}return n}a(hostConflicts,"hostConflicts"),i(hostConflicts,"hostConflicts");const describeConflict=i(o=>`${o.host}${o.prefix??""} (served by '${o.heldBy}')`,"describeConflict");exports.RESERVED_HOSTS=["lensmcp.localhost","canvas.localhost","lensmcp.local"],exports.RESERVED_WORKSPACE_KEYS=["canvas"];const DASHBOARD_PROJECT="(lens-dashboard)";function reservedHostOf(o){const e=(o??"").trim().toLowerCase().replace(/\.$/,"");if(e)return exports.RESERVED_HOSTS.find(n=>e===n||e.endsWith(`.${n}`))}a(reservedHostOf,"reservedHostOf"),i(reservedHostOf,"reservedHostOf");function refuseRegistration(o,e){if(exports.RESERVED_WORKSPACE_KEYS.includes(e.wsKey.toLowerCase()))return{error:"reserved-key",message:`'${e.wsKey}' is a workspace key LensMCP keeps for itself: lensmcp.localhost/${e.wsKey}/<id> is the key-free canvas link. Give the workspace another key (\`key\` in its .lensmcp/config.json).`};const n=e.routes.filter(s=>s.project!==DASHBOARD_PROJECT).map(s=>({route:s,name:reservedHostOf(s.host)??reservedHostOf(s.apex)})).filter(s=>s.name!==void 0);if(n.length>0){const s=[...new Set(n.map(c=>c.route.host??`*.${c.route.apex}`))].slice(0,6).join(", ");return{error:"reserved-host",message:`'${e.wsKey}' declares ${s}, under a name LensMCP keeps for itself (${exports.RESERVED_HOSTS.join(", ")} and every name below them): its dashboard and the canvas frame live there. Give the app hosts of its own (an apex like \`${e.wsKey}.localhost\`).`}}const t=o.get(e.wsKey);if(t&&!(0,exports.sameRoot)(t.root,e.root))return{error:"key-in-use",heldByRoot:t.root,message:`'${e.wsKey}' is already served from ${t.root}. ${e.root} is another checkout that derives the same key, and two checkouts cannot share a key or hosts behind one gateway: registering this one would replace the other's routes. To serve it beside the other under hosts of its own, run \`lensmcp instance start\` in ${e.root}; otherwise run \`lensmcp gateway stop\` in ${t.root} first.`};const r=hostConflicts(o,e);if(r.length>0){const s=r.slice(0,6).map(describeConflict).join(", "),c=r.length>6?`, and ${r.length-6} more`:"";return{error:"host-conflict",conflicts:r,message:`'${e.wsKey}' declares ${r.length===1?"a host":`${r.length} hosts`} another workspace already serves: ${s}${c}. The workspace registered first would win every request to ${r.length===1?"it":"them"}, so this registration is refused. Two workspaces behind one gateway need different hosts \u2014 for a second checkout of a workspace, \`lensmcp instance start\` in it serves it under hosts named after it.`}}}a(refuseRegistration,"refuseRegistration"),i(refuseRegistration,"refuseRegistration");function refuseUnregistration(o,e,n){const t=o.get(e.wsKey);if(t&&e.root&&!(0,exports.sameRoot)(t.root,e.root))return{error:"not-your-registration",heldByRoot:t.root,message:`'${e.wsKey}' is served from ${t.root}, not from ${e.root} \u2014 nothing of this checkout is registered, so nothing was removed.`};if(t&&n!==void 0&&e.wsKey===n)return{error:"daemon-workspace",heldByRoot:t.root,message:`'${e.wsKey}' is the workspace that owns the gateway \u2014 unregistering it would leave :443 serving without it. Stop the gateway instead: \`lensmcp gateway stop\` in ${t.root}.`}}a(refuseUnregistration,"refuseUnregistration"),i(refuseUnregistration,"refuseUnregistration");
@@ -8,7 +8,7 @@ export interface WorkspaceFragment {
8
8
  /** Absolute workspace root — the fragment's provenance (for the chooser + reaping). */
9
9
  root: string;
10
10
  /** Every route this workspace contributes (host + path mounts, internal.*, its default catch-all, and —
11
- * appended after discovery — its `lensmcp.local/<key>` dashboard route). */
11
+ * appended after discovery — its `lensmcp.localhost/<key>` dashboard route). */
12
12
  routes: Route[];
13
13
  /** The pod-service controllers this workspace owns (scale-from-zero lifecycle is per-service). */
14
14
  services: ServiceCtl[];
@@ -27,7 +27,7 @@ export interface WorkspaceFragment {
27
27
  export declare class RouteRegistry {
28
28
  private readonly fragments;
29
29
  /**
30
- * Routes that belong to NO registered workspace, by an id: a parked on-demand worktree's `lensmcp.local/<key>/`
30
+ * Routes that belong to NO registered workspace, by an id: a parked on-demand worktree's `lensmcp.localhost/<key>/`
31
31
  * dashboard route (parked-dashboards.ts). Only `merged()` sees them — a parked worktree stays unregistered to
32
32
  * everything else (`has`, `keys`, `/list`, the run cap, the parked-host check).
33
33
  */