lensmcp 1.26.6 → 1.26.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bundled/coordination.js +369 -367
- package/bundled/dashboard.js +734 -732
- package/bundled/goal-archive.js +47 -45
- package/bundled/main.js +403 -401
- package/bundled/migrations.js +3 -1
- package/bundled/project.js +2 -0
- package/bundled/shim.js +2 -0
- package/bundled/workspace-action-runner.js +233 -231
- package/lib/agent-plugins.js +2 -2
- package/lib/cli.js +18 -18
- package/package.json +4 -4
- package/plugin/.claude-plugin/plugin.json +1 -1
- package/plugins/lensmcp/.codex-plugin/plugin.json +1 -1
package/lib/cli.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";var
|
|
1
|
+
"use strict";var Dn=Object.defineProperty;var h=(e,o)=>Dn(e,"name",{value:o,configurable:!0});var Bn=Object.defineProperty,l=h((e,o)=>Bn(e,"name",{value:o,configurable:!0}),"l");import{spawn as St,spawnSync as L}from"node:child_process";import{existsSync as S,mkdirSync as se,readFileSync as U,readdirSync as Ve,realpathSync as Et,rmSync as Vn,statSync as Mt,writeFileSync as ne}from"node:fs";import{request as Pt}from"node:http";import{freemem as Fn,homedir as Gn,tmpdir as Un,totalmem as Hn,userInfo as Kn}from"node:os";import{basename as ge,dirname as D,isAbsolute as Wn,join as k,relative as Nt,resolve as P}from"node:path";import{fileURLToPath as Lt,pathToFileURL as W}from"node:url";import{agentReadsStdin as qn}from"./agent-stdin.js";import{derivePorts as Jn,ensureLensConfig as oe,isInstanceConfig as re,podNamespace as Ee,readLensConfig as G}from"./workspace-scope.js";import{commandUsage as Fe,onOutputBroken as zn,wantsHelp as Yn}from"./cli-help.js";import{SETUP_FLAGS as Tt,setupArgsProblem as Xn,setupStatusLines as Qn,setupStatusOf as Zn}from"./setup-args.js";import{logsFollow as eo}from"./logs-follow.js";import{lintByUnit as to,splitLintArgs as At,wantsLintBase as so}from"./lint-args.js";import{runLintCommand as no}from"./lint-command.js";import{decideRecycle as oo,hashConfig as ro}from"./recycle-policy.js";import{planMcpRestart as Ge}from"./mcp-restart.js";import{detectDuplicateRegistration as ao,disabledMcpServers as Rt,mcpServerNames as It,pluginEnabledInSettings as Ot}from"./duplicate-registration.js";import{readTrackedPid as io,stillSameProcess as co,writeTrackedPid as Ue}from"./process-identity.js";import{clusterPageHosts as lo,declFor as uo,lensmcpJsonProblem as fe,lensmcpServices as _t,readClusterPageDecls as po,withBridgeAllowedOrigins as ho}from"./bridge-origins.js";import{runForwardingSignals as He}from"./forward-signals.js";import{liveMcpSessions as mo,registerMcpSession as go}from"./mcp-sessions.js";import{dashboardLoginUrl as Me}from"./dashboard-login.js";import{recordAsked as fo}from"./agent-asked.js";import{remember as wo,shouldAnnounce as vo}from"./hook-memory.js";import{areaOffIn as yo}from"./project-area.js";import{isMcpMode as Dt,MCP_MODE_SOURCE_LABELS as Bt,MCP_PIN_PENDING_NOTICE as ko,mcpModeSwitchHint as Pe}from"./mcp-mode.js";import{effectiveMcpMode as bo,LENS_CONFIG as Co,probeIdentitySync as Ke,probeSharedMcp as Vt,probeSharedMcpSync as $o,readMcpWiring as ae,unchosenMcpModePin as xo,wireMcpMode as jo}from"./mcp-wiring.js";import{migrationSettled as So,pendingMigrationsCheck as Eo,setupMigrationsArgs as Mo,setupMigrationsLines as Po,setupMigrationsPlan as No,SETUP_MIGRATIONS_NO_ENTRY as Lo}from"./upgrade-migrations.js";import{gatewayDaemonEnv as Ft,openGatewayLog as Gt,secureLensLogs as To,sweepLensRuntimeFiles as Ao}from"./sweep.js";import{candidateSignals as Ro,findingLine as Io,findingsDigest as Oo,formatContext as _o,hookPayload as Ut,isHookEvent as Ht,select as Do}from"./status-policy.js";import{DEFAULT_BUDGET_MS as Bo,readStatus as Vo,withLensSession as ie}from"./status-client.js";import{readServiceMemory as Fo,runMemCommand as Go,socketOwnerGone as Uo}from"./mem-command.js";import{compactAfterStop as Ho,runHistoryCommand as Ko}from"./history-compact.js";import{instanceToolRoot as Wo,repairInstanceIdentity as qo,runInstance as Jo}from"./instance-command.js";import{lensRootFor as we,registryPath as ve}from"./instance-registry.js";import{parseToolArgs as zo,runToolCommand as Yo,TOOL_USAGE as Xo}from"./tool-command.js";import{walkProjectFiles as ce}from"./project-files.js";import{findTrustTarget as Qo,scanExecutorTarget as Zo}from"./executor-targets.js";import{LENS_SHARED_DIRS as er,lensIgnoreVerdict as tr}from"./lens-ignore.js";import{inspectBundle as sr,sourceMapVerdict as nr}from"./pod-source-maps.js";import{perfRulesVerdict as or,readPerfFindings as rr}from"./perf-rules-check.js";import{DISMISS_USAGE as ar,parseDismissArgs as ir,runDismissCommand as cr}from"./dismiss-command.js";import{runTypecheckCommand as dr}from"./typecheck-command.js";import{EXPECT_USAGE as lr,parseExpectArgs as ur,runExpectCommand as pr}from"./expect-command.js";import{parseRestartArgs as hr,RESTART_USAGE as mr,runRestartCommand as gr}from"./restart-command.js";import{parseUpdatesArgs as fr,runUpdatesCommand as wr,UPDATES_USAGE as vr}from"./updates-command.js";import{CALL_USAGE as yr,httpsCall as kr,parseCallArgs as br,runCallCommand as Cr}from"./call-command.js";import{otherCheckoutLines as Kt,refusalMessage as Ne,registrationState as We}from"./gateway-registration.js";import{controlRequest as Wt,graphVerdictLine as qe,registrationGraphFields as $r}from"./guest-graph.js";import{BUNDLED_DIR as xr,locateServerBundle as jr,MCP_SERVER_PROJECT as Sr,serverBundleNotFound as V}from"./server-bundle.js";import{detectSkew as Er,formatSkewContext as qt,readInstalledPlugin as Je,readInstalledPlugins as Jt,readVersions as zt,spawnRunner as Mr,syncPlugin as Pr,updateCommands as Nr}from"./plugin-version.js";import{AGENTS as Yt,agentById as Lr,codexInstalledVersion as Tr,installAgentPlugin as Xt,MARKETPLACE as Ar,PLUGIN_ID as Le,readPluginManifestVersion as Rr,resolvePluginRoot as Qt,spawnAgentRunner as ze}from"./agent-plugins.js";import{detectGlobalInstall as Ir,daemonVerdict as Or,detectPackageManager as _r,installedCliFor as Te,lensPackagesIn as Dr,missingFromRegistry as Br,planRestart as Vr,readConnectedWorkspaces as Zt,registryAnswer as Fr,restartGatewayWith as es,setupAfterUpgrade as Gr,setupWith as Ur,upgradeTargets as Hr}from"./upgrade.js";import{askYesNo as Ye,findUnfinishedRun as Xe,freeDiskBytes as Kr,handOffArgv as Wr,handOffEnv as ts,handOffPlan as qr,installsLeft as Jr,LOCK_PID_ENV as zr,lockLine as Yr,lockPath as Xr,lockRefusal as Qr,LOG_ENV as Zr,mergeFlags as ea,migrationsArgs as ta,migrationsJournalPath as ss,newRun as sa,openUpgradeLog as na,parseMigrationsAnswer as oa,parseStatusPending as ra,parseTeamAnswer as aa,PHASE2_ENV as ia,UPGRADE_ENV_KEYS as ca,withoutUpgradeEnv as ns,pidAlive as os,readLockHolder as rs,readRun as as,readSetupVersion as Ae,releaseUpgradeLock as da,restartDecision as la,resumeLines as ua,runPhase1 as pa,runPhase2 as is,startDecision as ha,takeUpgradeLock as ma,teed as cs,upgradeHome as Qe,upgradeLogPath as ga,writeRun as fa}from"./upgrade-run.js";import{isVersionsArchiveCommand as wa,restartLine as ds,runUseCommand as va,runVersionsArchiveCommand as ya,runVersionsCommand as ka}from"./store-command.js";import{isZeroTouch as ls}from"./zero-touch.js";import{daemonArgv as ba,findClusterEntry as Ca,findGatewayDaemon as $a,isGatewayDaemonCommand as xa,TRUST_ENTRY as ja}from"./gateway-daemon.js";import{currentLink as Sa,currentVersion as Re,installVersion as Ea,isStoredVersion as Ma,storedCli as Pa,storeHome as ye,useVersion as Na,versionDir as La}from"./store.js";import{binVersion as Ta,lensRestartPlan as Aa,rollbackLine as Ra,storePhase1 as Ia,upgradesOnStore as Oa}from"./store-upgrade.js";import{parseRunArgs as _a,planRun as Da,runInstrumented as Ba}from"./run-command.js";import{readWorkspaceConfig as Va,workspaceConfigSource as Fa}from"./lens-config.js";import{runAgentCommand as Ga,runServicesCommand as Ua}from"./lens-commands.js";const de=`lensmcp \u2014 CLI for LensMCP (FrontMCP-based observability for coding agents)
|
|
2
2
|
|
|
3
3
|
Usage:
|
|
4
4
|
lensmcp <command> [options]
|
|
@@ -984,37 +984,37 @@ Commands:
|
|
|
984
984
|
down or about to idle-stop.
|
|
985
985
|
--version Print the lensmcp version.
|
|
986
986
|
--help Show this help.
|
|
987
|
-
`;export async function runCli(e){const o=e.out??(r=>console.log(r)),t=e.err??(r=>console.error(r)),[s,...n]=e.argv;if(!s||s==="--help"||s==="-h")return o(le),{exitCode:0};if(s==="--version"||s==="-V")return o(B()),{exitCode:0};if(zn(n,s)){const r=n[0]!==void 0&&/^[a-z][a-z-]*$/.test(n[0])?Fe(le,`${s} ${n[0]}`):void 0;return o(r??Fe(le,s)??le),{exitCode:0}}switch(s){case"setup":return Vs(e,n,o,t);case"mcp":return hs(e,n,o,t);case"dashboard":return fs(e,n,o,t);case"gateway":{const r=et(e,n,o,t),i=_(n,{string:["--cwd","--project","--target"]});return(i.positional[0]??"").toLowerCase()==="stop"&&r.exitCode===0&&!n.includes("--no-compact")&&await Uo(P($(i.flags["--cwd"])??e.cwd),o,e.env),r}case"history":{const r=_(n,{string:["--cwd"]});return Ho(P($(r.flags["--cwd"])??e.cwd),n.filter((i,a)=>i!=="--cwd"&&n[a-1]!=="--cwd"),o,t,e.env)}case"bridge":return xs(e,n,o,t);case"install":return ot(e,n,o,t);case"plugin":case"plugins":return dn(e,n,o,t);case"upgrade":return za.has(_(n,{string:["--cwd","--worktree"]}).positional[0]??"")?pn(e,n,o,t):mt(e,n,o,t);case"trust":return rt(e,n,o,t);case"versions":{const r={env:e.env??process.env,lensVersion:l(()=>z().version,"lensVersion"),ownVersion:B(),cwd:e.cwd};return wa(n)?ya(n,o,t,r):ka(n,o,t,r)}case"use":return va(n,o,t,{env:e.env??process.env,lensVersion:l(()=>z().version,"lensVersion")});case"run":{const r=_a(n,e.cwd);if("error"in r)return t(r.error),{exitCode:2};const i=Da({cwd:P(r.cwd),...r.project?{project:r.project}:{},packageRoot:F(),env:{...process.env,...e.env??{}}});return"error"in i?(t(i.error),{exitCode:1}):{exitCode:await Ba(r.command,P(r.cwd),i.env,t)}}case"dev":case"build":case"verify":return{exitCode:await Ga(s,n,{cwd:e.cwd,packageRoot:F(),out:o,err:t})};case"services":return{exitCode:Ua(n,{cwd:e.cwd,packageRoot:F(),out:o,err:t,entry:O(e.cwd,"project.js"),notFound:V("project entry","project.js"),env:{...process.env,...e.env}})};case"status":return Ks(e,n,o);case"version-check":return Ws(e,n,o);case"doctor":return qs(e,n,o);case"project":return an(e,n,o,t);case"prune":return us(e,n,o,t);case"rollout":return Cn(e,n,t);case"logs":return Ln(e,n,o,t);case"dismiss":return js(e,n,o,t);case"expect":return Ss(e,n,o,t);case"lint":return Ts(e,n,t,o);case"typecheck":return Rs(e,n,t,o);case"debug":return Tn(e,n,o,t);case"mem":return Rn(e,n,o,t);case"restart":return Ms(e,n,o,t);case"updates":return Ps(e,n,o,t);case"actions":{const r=O(e.cwd,"workspace-action-runner.js");if(!r)return t(V("workspace action runner","workspace-action-runner.js")),{exitCode:1};try{const i=await import(W(r).href);return process.env.LENSMCP_WORKSPACE_ROOT=e.cwd,process.env.LENSMCP_ACTION_RUNNER=r,o(JSON.stringify(await i.workspaceActionsCli(n))),{exitCode:0}}catch(i){return t(i instanceof Error?i.message:String(i)),{exitCode:1}}}case"queue":{const r=O(e.cwd,"workspace-action-runner.js");if(!r)return t(V("machine queue","workspace-action-runner.js")),{exitCode:1};try{const i=await import(W(r).href);process.env.LENSMCP_ACTION_RUNNER=r;const a=await i.queueCli(n,{stdout:l(d=>process.stdout.write(d),"stdout"),stderr:l(d=>process.stderr.write(d),"stderr"),cwd:e.cwd,env:process.env});return a.out!==void 0&&o(a.out),{exitCode:a.exitCode}}catch(i){return t(i instanceof Error?i.message:String(i)),{exitCode:2}}}case"docker":{const r=O(e.cwd,"workspace-action-runner.js");if(!r)return t(V("Docker commands","workspace-action-runner.js")),{exitCode:1};try{const i=await import(W(r).href);if(!i.dockerCli)return t(`${r} was built before the Docker commands \u2014 rebuild it, or upgrade LensMCP.`),{exitCode:1};process.env.LENSMCP_ACTION_RUNNER=r;const a=await i.dockerCli(n,{stdout:l(d=>process.stdout.write(d),"stdout"),stderr:l(d=>process.stderr.write(d),"stderr"),cwd:e.cwd,env:{...process.env,...e.env??{}}});return a.out!==void 0&&o(a.out),{exitCode:a.exitCode}}catch(i){return t(i instanceof Error?i.message:String(i)),{exitCode:2}}}case"workers":case"worker":case"peers":return ls(e,s,n,o,t);case"call":return Ls(e,n,o,t);case"tool":return Es(e,n,o,t);case"instance":case"instances":return An(e,n,o,t);case"agent":return Us(e,n,o,t);default:return t(`Unknown command: ${s}`),t(le),{exitCode:2,message:`Unknown command: ${s}`}}}h(runCli,"runCli"),l(runCli,"runCli");async function ls(e,o,t,s,n){const r=O(e.cwd,"workspace-action-runner.js");if(!r)return n(V("Worker Macs commands","workspace-action-runner.js")),{exitCode:1};const i=new AbortController,a=l(()=>i.abort(),"stop");process.once("SIGINT",a);try{const d=await import(W(r).href);if(!d.peersCli)return n(`${r} was built before the Worker Macs commands \u2014 rebuild it, or upgrade LensMCP.`),{exitCode:1};const c=process.stdin.isTTY&&process.stdout.isTTY,u=l(async g=>{const{createInterface:m}=await import("node:readline"),w=m({input:process.stdin,output:process.stdout});return new Promise(f=>w.question(g,y=>{w.close(),f(y)}))},"ask"),p=await d.peersCli([o,...t],{stdout:l(g=>process.stdout.write(g),"stdout"),stderr:l(g=>process.stderr.write(g),"stderr"),cwd:e.cwd,env:{...process.env,...e.env??{}},version:B(),signal:i.signal,...c?{ask:u}:{}});return p.out!==void 0&&s(p.out),{exitCode:p.exitCode}}catch(d){return n(d instanceof Error?d.message:String(d)),{exitCode:2}}finally{process.removeListener("SIGINT",a)}}h(ls,"br"),l(ls,"runPeers");function us(e,o,t,s){const n=_(o,{string:["--cwd"],boolean:["--force"]}),r=P($(n.flags["--cwd"])??e.cwd),i=k(r,".lensmcp"),a=k(i,"gateway.log"),d=l(()=>{try{return Ve(i).reduce((g,m)=>{try{return g+Et(k(i,m)).size}catch{return g}},0)}catch{return 0}},"dirBytes"),c=l(g=>`${(g/1048576).toFixed(1)} MB`,"mb"),u=d();if(u===0)return t(`nothing to prune \u2014 no .lensmcp runtime files at ${i}`),{exitCode:0};if(n.flags["--force"]!==!0&&ps(i))return s("a gateway is running for this workspace \u2014 pruning now can drop a generation a live"),s("writer is still counting (issues/closed/foodguard-13). Stop it first:"),s(" lensmcp gateway stop"),s("\u2026or pass --force if you accept losing recent history."),{exitCode:1,message:"gateway running"};To(r,a),Lo(r);const p=d();return t(`pruned ${i}`),t(` ${c(u)} \u2192 ${c(p)} (reclaimed ${c(Math.max(0,u-p))})`),{exitCode:0}}h(us,"Cr"),l(us,"runPrune");function ps(e){try{return tt(k(e,"gateway.pid"))!==void 0}catch{return!1}}h(ps,"$r"),l(ps,"gatewayPidAlive");async function hs(e,o,t,s){const n=_(o,{string:["--cwd","--transport","--port","--mcp"]}),r=P($(n.flags["--cwd"])??e.cwd),i=ye({...process.env,...e.env??{}}),a=ve(r,i);a!==r&&s(`[lensmcp] ${r} is a checkout with no services of its own (instance create --no-start) \u2014 this session's lens is the main checkout's: ${a}`);const d=Wo(a,i);d&&s(`[lensmcp] ${a} is instance '${d}', but its .lensmcp/config.json had no instance identity \u2014 written back from its record`);const c=oe(a),u=$(n.flags["--transport"])??e.env?.LENSMCP_TRANSPORT??"stdio",p=$(n.flags["--port"])??e.env?.LENSMCP_PORT??String(c.ports.mcpHttp),g=ko(a,$(n.flags["--mcp"]),{...process.env,...e.env??{}})==="shared"&&u==="stdio",m=g?kt(a):void 0,w=m??yt(a);if(!w)return s(V("lensmcp-mcp server bundle","main.js")),{exitCode:1};Se(a);const f=e.env?.LENSMCP_EVENT_FILE??process.env.LENSMCP_EVENT_FILE??k(a,".lensmcp","events.jsonl"),y={...e.env??{},LENSMCP_TRANSPORT:u,LENSMCP_PORT:p,LENSMCP_EVENT_FILE:f};if(m)return{exitCode:await gs(m,a,y)};const v={...process.env,...y};if(u!=="stdio")return{exitCode:await He({label:`the MCP server (${w})`,args:[w],cwd:a,env:v},s)};const b=g?[w,"--cwd",a]:[w];return{exitCode:L(process.execPath,b,{cwd:a,stdio:"inherit",env:v}).status??1}}h(hs,"jr"),l(hs,"runMcp");async function ms(e){const o=kt(e);if(!o)return{reason:V("lensmcp-mcp shim bundle","shim.js")};const t=await import(W(o).href);if(typeof t.ensureLens!="function")return{reason:"this lensmcp's shim cannot start a lens on its own \u2014 upgrade lensmcp"};const s=await t.ensureLens({cwd:e});return s.ok?{ok:!0}:{reason:s.reason}}h(ms,"Sr"),l(ms,"ensureInstanceLens");async function gs(e,o,t){for(const[n,r]of Object.entries(t))r===void 0?delete process.env[n]:process.env[n]=r;process.chdir(o),process.once("exit",mo(o));const s=await import(W(e).href);return typeof s.runShim!="function"?new Promise(()=>{}):s.runShim({cwd:o})}h(gs,"xr"),l(gs,"runShimInProcess");async function fs(e,o,t,s){const n=_(o,{string:["--cwd","--port","--base"]}),r=P($(n.flags["--cwd"])??e.cwd),i=oe(r);if(!$(n.flags["--port"])&&!e.env?.LENSMCP_DASHBOARD_PORT){const p=I("GET","/list");if(p?.status===200&&(p.json?.workspaces??[]).some(g=>g.key===i.key)){const g=`https://lensmcp.local${i.dashboardBasePath}/`;t(`lensmcp dashboard \u2192 the gateway already runs this workspace's dashboard: ${g}`);const m=Pe(g,r,{...process.env,...e.env??{}});return m&&t(` sign in \u2192 ${m} (one use, 10 min \u2014 then this browser stays signed in)`),t(" (another, standalone: `lensmcp dashboard --port <a free port>`)"),{exitCode:0}}}const a=$(n.flags["--port"])??e.env?.LENSMCP_DASHBOARD_PORT??String(i.ports.dashboard),d=$(n.flags["--base"])??e.env?.LENSMCP_DASHBOARD_BASE??"",c=O(r,"dashboard.js");if(!c)return s(V("lensmcp dashboard bundle","dashboard.js")),{exitCode:1};Se(r);const u=e.env?.LENSMCP_EVENT_FILE??process.env.LENSMCP_EVENT_FILE??k(r,".lensmcp","events.jsonl");return t(`lensmcp dashboard \u2192 http://localhost:${a}${d||"/"} (reading ${u})`),{exitCode:await He({label:`the dashboard (${c})`,args:[c],cwd:r,env:{...process.env,...e.env??{},LENSMCP_DASHBOARD_PORT:a,LENSMCP_DASHBOARD_BASE:d,LENSMCP_EVENT_FILE:u}},s)}}h(fs,"Er"),l(fs,"runDashboard");function Qe(){return k(process.env.LENSMCP_HOME||Fn(),".lensmcp","control.sock")}h(Qe,"It"),l(Qe,"controlSocketPath");function I(e,o,t){const s=Qe();return S(s)?Kt(s,e,o,t):null}h(I,"A"),l(I,"daemonRequest");async function Ze(e,o,t){for(;;){const s=I("GET","/list"),n=s?.status===200&&s.json&&typeof s.json=="object"?s.json.workspaces??[]:[];if(We(n,e,o).kind==="mine")return!0;if(Date.now()>=t)return!1;await new Promise(r=>setTimeout(r,500))}}h(Ze,"Dt"),l(Ze,"servedFrom");function ws(){const e=I("GET","/status");if(e?.status!==200||!e.json||typeof e.json!="object")return;const o=e.json.daemon;return typeof o?.wsKey=="string"&&o.wsKey.length>0?o.wsKey:void 0}h(ws,"Mr"),l(ws,"daemonWsKey");function vs(e){const o={};for(const t of ce(e,s=>s==="project.json"))try{const s=JSON.parse(U(t,"utf8")),n=D(t);o[s.name??fe(n)]={root:Pt(e,n)||"."}}catch{}return o}h(vs,"Pr"),l(vs,"buildProjectsMap");function ys(e){const o=k(e,"node_modules",".bin",process.platform==="win32"?"nx.cmd":"nx");if(!S(o))return;const t=L(o,["graph","--print"],{cwd:e,encoding:"utf8",timeout:15e3,maxBuffer:32*1024*1024});if(!(t.status!==0||typeof t.stdout!="string"))try{const s=JSON.parse(t.stdout).graph?.dependencies;return s?Object.fromEntries(Object.entries(s).map(([n,r])=>[n,r.flatMap(i=>typeof i.target=="string"?[i.target]:[])])):void 0}catch{return}}h(ys,"Nr"),l(ys,"buildProjectDependencies");function ue(e,o,t=!0){return{wsKey:o,root:e,projects:vs(e),...t?Cr(e,()=>ys(e)):{}}}h(ue,"me"),l(ue,"gatewayRegistrationBody");function et(e,o,t,s){const n=_(o,{string:["--cwd","--project","--target"]}),r=(n.positional[0]??"status").toLowerCase(),i=o.includes("--json"),a=P($(n.flags["--cwd"])??e.cwd),d=oe(a),c=k(a,".lensmcp","gateway.pid"),u=k(a,".lensmcp","gateway.log"),p=k(a,".lensmcp","registered.json"),g=`https://lensmcp.local${d.dashboardBasePath}/`,m=l(()=>{const b=Pe(g,a,{...process.env,...e.env??{}});b&&t(` sign in \u2192 ${b} (one use, 10 min \u2014 then this browser stays signed in)`)},"printSignIn"),w=l(()=>{const b=we(a);if(b)return s(`gateway: ${b}`),{exitCode:1};const{pid:x,healed:E}=$e(c,a);if(x!==void 0&&Ce(x)){const j=classifyAliveGateway({oursOn443:J(a)!==void 0,port443Held:q().length>0,pidFileAgeMs:st(c)});if(j==="serving")return E&&t(`healed: adopted a running gateway (pid ${x}) the pid file had lost \u2014 no duplicate started.`),t(`gateway already running (pid ${x}).`),t(` dashboard \u2192 ${g}`),m(),{exitCode:0};if(j==="booting")return t(`gateway starting (pid ${x}) \u2014 :443 not bound yet.`),t(` dashboard \u2192 ${g}`),m(),t(` logs \u2192 ${u}`),{exitCode:0};xe(x,"SIGKILL"),Z(c),be(a,e.env,()=>{}),t(`reaped a dead gateway (pid ${x} was alive but nothing served :443 for this workspace).`)}const N=q()[0];if(N!==void 0){const j=I("GET","/list");if(j!==null){const R=j.status===200&&j.json&&typeof j.json=="object"?j.json.workspaces??[]:[],K=We(R,d.key,a);if(K.kind==="other-checkout"){for(const Q of Ht(d.key,K.root,a))s(Q);return{exitCode:1}}if(K.kind==="mine")return se(D(p),{recursive:!0}),ne(p,JSON.stringify({wsKey:d.key})),t(`already registered into the shared gateway daemon (pid ${N}).`),t(` dashboard \u2192 ${g}`),m(),{exitCode:0};const X=I("POST","/register",ue(a,d.key));if(X&&X.status===200){se(D(p),{recursive:!0}),ne(p,JSON.stringify({wsKey:d.key})),t(`registered '${d.key}' into the shared gateway daemon (pid ${N}).`),t(` dashboard \u2192 ${g}`);const Q=qe(X.json);return Q&&t(Q),m(),t(" the daemon hosts this workspace's services + dashboard; `lensmcp gateway stop` unregisters."),{exitCode:0}}return s(`failed to register into the gateway daemon: ${Le(X)??(X?JSON.stringify(X.json):"no response from the control socket")}`),{exitCode:1}}return s(`port :443 is held by pid ${N}, which is not this workspace's gateway.
|
|
988
|
-
Free it first (stop that process), then \`lensmcp gateway start\`.`),{exitCode:1}}const C=ks(a,$(n.flags["--project"]),$(n.flags["--target"])),T=$a(F(),{...process.env,...e.env??{}});if(T&&(C||S(k(a,"lensmcp.json")))){const j=Ft(a,u),R=jt(process.execPath,ba(T,a,C),{cwd:a,detached:!0,stdio:["ignore",j,j],env:Vt({...process.env,...e.env??{}},u)});return R.unref(),R.pid&&Ue(c,R.pid),t(`gateway starting \u2192 ${C?`${C.project}:${C.target}`:"lensmcp.json"} with lensmcp ${B()}, no nx run (pid ${R.pid??"?"})`),t(` dashboard \u2192 ${g}`),m(),t(` logs \u2192 ${u}`),t(" note: binding :443 needs privilege, and `lensmcp trust` once for the *.local hosts + TLS."),{exitCode:0}}if(!C)return s(`This workspace ('${d.key}') has no gateway target \u2014 no project declares the`),s("`@lensmcp/cluster:gateway` executor, so there is nothing here to launch on :443."),s(""),s(" \u2022 Joining a shared gateway? Start it in the workspace that OWNS it, then run"),s(" `lensmcp gateway start` here \u2014 this workspace registers into it (no local target needed)."),s(" \u2022 Should this workspace host its own gateway? Scaffold it: `lensmcp install`"),s(" (or `lensmcp setup` for the full install + trust bootstrap)."),s(" \u2022 Already have a differently-named target? `lensmcp gateway start --project <p> --target <t>`."),{exitCode:1};const A=je(a);if(!A)return s("Could not find the `nx` binary in the workspace. Install Nx first: `yarn add -D nx`."),{exitCode:1};const H=Ft(a,u),te=jt(A,["run",`${C.project}:${C.target}`],{cwd:a,detached:!0,stdio:["ignore",H,H],env:Vt({...process.env,...e.env??{}},u)});return te.unref(),te.pid&&Ue(c,te.pid),t(`gateway starting \u2192 ${C.project}:${C.target} (pid ${te.pid??"?"})`),t(` dashboard \u2192 ${g}`),m(),t(` logs \u2192 ${u}`),t(" note: binding :443 needs privilege \u2014 if it fails, run the gateway target with sudo,"),t(" and run `nx run gateway:trust` once for the *.local hosts + TLS."),{exitCode:0}},"start"),f=l(()=>{if(S(p)&&J(a)===void 0){let C=d.key;try{C=JSON.parse(U(p,"utf8")).wsKey??d.key}catch{}const T=I("POST","/unregister",{wsKey:C,root:a});Z(p);const A=Le(T);return t(A??(T&&T.status===200?`unregistered '${C}' from the shared gateway daemon.`:"unregister sent (the daemon may already be gone).")),{exitCode:0}}Z(p);const{pid:b,healed:x}=$e(c,a);if(b===void 0)return t("gateway not running."),Z(c),{exitCode:0};x&&t(`healed: found an orphaned gateway (pid ${b}) the pid file had lost \u2014 stopping it.`),xe(b);let E=!1;if(!nt(6e3)){E=!0,xe(b,"SIGKILL");const C=J(a);if(C!==void 0)try{process.kill(C,"SIGKILL")}catch{}else q().length>0&&t(":443 is still held by a process that is not this workspace's gateway \u2014 leaving it alone.");nt(3e3)}const N=J(a);return N!==void 0&&N!==b&&(xe(N,"SIGKILL"),E=!0),Z(c),E&&be(a,e.env,()=>{}),t(`gateway stopped (pid ${b})${E?" \u2014 forced (a child ignored SIGTERM)":""}.`),{exitCode:0}},"stop"),y=l(()=>{const{pid:b,healed:x}=$e(c,a),E=b!==void 0&&Ce(b)?classifyAliveGateway({oursOn443:J(a)!==void 0,port443Held:q().length>0,pidFileAgeMs:st(c)}):void 0,N=E==="serving"||E==="booting";if(i){const j=I("GET","/status"),R=j?.status===200&&j.json&&typeof j.json=="object"?j.json:null,K=S(p),X=N?"daemon":R&&K?"guest":R?"other":"stopped";return t(JSON.stringify({thisWorkspace:d.key,role:X,dashboardUrl:g,dashboardLoginUrl:Pe(g,a,{...process.env,...e.env??{}})??null,chooserUrl:"https://lensmcp.local/",logFile:u,daemonLogFile:(()=>{const Q=Ie();return Q&&Q!==a?k(Q,".lensmcp","gateway.log"):u})(),mcp:ct(a,e.env??process.env),daemon:R?.daemon??null,workspaces:R?.workspaces??[],services:R?.services??[]})),{exitCode:N||R&&K?0:1}}const C=I("GET","/list"),T=C?.status===200&&C.json&&typeof C.json=="object"?C.json.workspaces??[]:[],A=l(()=>{if(T.length!==0){t(` workspaces (${T.length} registered):`);for(const j of T){if(t(` \u2022 ${j.key} (${j.routes??0} routes, ${j.services??0} services)${j.key===d.key?" \u2190 this workspace":""}`),j.key===d.key||!j.root)continue;const R=Pe(`https://lensmcp.local${G(j.root).dashboardBasePath}/`,j.root,{...process.env,...e.env??{},LENSMCP_DASHBOARD_TOKEN:void 0});R&&t(` sign in \u2192 ${R}`)}}},"printWorkspaces"),H=l(()=>{const j=ct(a,e.env??process.env);t(j.mode==="shared"?` mcp \u2192 shared ${j.url} ${j.healthy?"(up)":j.remedy?`(REFUSED \u2014 ${j.error}; ${j.remedy})`:`(DOWN \u2014 ${j.error??"no answer"})`}`:" mcp \u2192 embedded (one server per agent session \u2014 opted out of shared)")},"printMcp"),te=l(()=>{const j=I("GET","/status"),R=j?.status===200&&j.json&&typeof j.json=="object"?j.json.daemon:void 0,K=me(a);R?.version&&K&&R.version!==K&&t(` version \u2192 ${cs(R.version,K)}`)},"printVersionSkew");if(N)return t(E==="booting"?`gateway: starting (pid ${b}) \u2014 :443 not bound yet`:`gateway: running (pid ${b}) \u2014 DAEMON on :443${x?" \u2014 recovered a stale pid file":""}`),t(` workspace \u2192 ${d.key}`),t(` dashboard \u2192 ${g}`),m(),t(" chooser \u2192 https://lensmcp.local/"),t(` logs \u2192 ${u}`),H(),te(),A(),{exitCode:0};if(S(p)&&C?.status===200){const j=q()[0];t(`gateway: registered into a shared daemon${j!==void 0?` (pid ${j})`:""} \u2014 this workspace is a guest`),t(` workspace \u2192 ${d.key}`),t(` dashboard \u2192 ${g}`),m(),t(` logs \u2192 ${u} (this workspace's pods)`);const R=Ie();return R&&R!==a&&t(` ${k(R,".lensmcp","gateway.log")} (the daemon's own log \u2014 gateway-level lines land there)`),t(" attach \u2192 `lensmcp logs <service>` (live, from any workspace)"),t(" stop \u2192 `lensmcp gateway stop` (unregisters; the daemon keeps running)"),H(),te(),A(),{exitCode:0}}return E==="zombie"?(t(`gateway: NOT serving \u2014 tracked pid ${b} is alive but nothing holds :443 for this workspace`),t(" (a crashed gateway under a wedged nx wrapper) \u2014 run `lensmcp gateway restart` to recover."),t(` workspace \u2192 ${d.key}`),t(` logs \u2192 ${u}`),H(),A(),{exitCode:1}):(t("gateway: stopped"),t(` workspace \u2192 ${d.key}`),t(` dashboard \u2192 ${g}`),m(),H(),{exitCode:1})},"status"),v=l(()=>{const b=I("GET","/status");if(b?.status!==200||!b.json||typeof b.json!="object")return t(i?JSON.stringify({daemon:null,workspaces:[],services:[]}):"gateway: no daemon answers on the control socket \u2014 nothing is hosted."),{exitCode:1};const x=b.json;if(i)return t(JSON.stringify(x)),{exitCode:0};t(`daemon: pid ${x.daemon?.pid??"?"} \xB7 owner ${x.daemon?.wsKey??"?"}${x.daemon?.version?` \xB7 lensmcp ${x.daemon.version}`:""}`);for(const E of x.workspaces??[]){t(` ${E.isDaemon?"\u2605":"\xB7"} ${E.key.padEnd(16)} ${String(E.routes??0).padStart(3)} routes ${String(E.services??0).padStart(3)} services ${E.root??""}`);for(const N of(x.services??[]).filter(C=>(C.wsKey??x.daemon?.wsKey)===E.key))t(` ${N.project.padEnd(16)} ${(N.state??"unknown").padEnd(9)} ${N.host??""}`)}return{exitCode:0}},"list");switch(r){case"start":return w();case"stop":return f();case"list":return v();case"restart":return f(),be(a,e.env,t),w();case"status":return y();default:return s(`Unknown gateway subcommand: ${r} (use start | stop | status | restart | list)`),{exitCode:2}}}h(et,"Ft"),l(et,"runGateway");function be(e,o,t){const s=je(e);if(!s){t(" (graph refresh skipped \u2014 no nx binary found in the workspace)");return}const n={...process.env,...o??{}},r=l(i=>L(s,i,{cwd:e,env:n,stdio:"ignore"}).status===0,"tryNx");if(r(["reset","--only-daemon"])||r(["daemon","--stop"])){t(" nx project graph refreshed \u2014 a lib/app added since boot will now resolve.");return}t(" (graph refresh best-effort failed \u2014 if a new project does not resolve, run `nx reset`)")}h(be,"Ee"),l(be,"refreshNxGraph");function ks(e,o,t){return Qo(e,"@lensmcp/cluster:gateway",o,t)||(o||t?{project:o??"gateway",target:t??"serve"}:void 0)}h(ks,"Lr"),l(ks,"findGatewayTarget");function tt(e){const o=ao(e);if(o)return io(o.pid,o.stamp)?o.pid:void 0}h(tt,"Gt"),l(tt,"readPid");function Ce(e){try{return process.kill(e,0),!0}catch(o){return o.code==="EPERM"}}h(Ce,"Me"),l(Ce,"isAlive");function q(){try{const e=L("lsof",["-nP","-iTCP:443","-sTCP:LISTEN","-t"],{encoding:"utf8"});return e.status!==0||!e.stdout?[]:[...new Set(e.stdout.split(/\s+/).map(Number).filter(o=>Number.isInteger(o)&&o>0))]}catch{return[]}}h(q,"z"),l(q,"pidsOnPort443");function bs(e){try{return(L("ps",["-o","command=","-p",String(e)],{encoding:"utf8"}).stdout??"").trim()}catch{return""}}h(bs,"Tr"),l(bs,"processCmd");function J(e){const o=k(e,"node_modules","nx","dist","bin","run-executor.js"),t=k(e,"node_modules","@lensmcp","cluster");for(const s of q()){const n=bs(s);if(n.includes(o)||n.includes(t)||xa(n,e))return s}}h(J,"Y"),l(J,"gatewayOnPort443");function st(e){try{return Date.now()-Et(e).mtimeMs}catch{return}}h(st,"Vt"),l(st,"pidFileAgeMs");const Ha=18e4;export function classifyAliveGateway(e){if(e.oursOn443)return"serving";const o=e.pidFileAgeMs!==void 0&&e.pidFileAgeMs<(e.bootGraceMs??Ha);return!e.port443Held&&o?"booting":"zombie"}h(classifyAliveGateway,"classifyAliveGateway"),l(classifyAliveGateway,"classifyAliveGateway");function $e(e,o){const t=tt(e);if(t!==void 0&&Ce(t))return{pid:t,healed:!1};const s=J(o);if(s!==void 0){try{Ue(e,s)}catch{}return{pid:s,healed:!0}}return{healed:!1}}h($e,"Pe"),l($e,"reconcileGateway");function xe(e,o="SIGTERM"){try{process.kill(-e,o)}catch{try{process.kill(e,o)}catch{}}}h(xe,"Ne"),l(xe,"killGatewayTree");function nt(e){const o=Date.now()+e;for(;;){if(q().length===0)return!0;if(Date.now()>=o)return!1;L("sleep",["0.15"])}}h(nt,"Ut"),l(nt,"waitForPortFree");function Cs(e){const o=L("curl",["-s","-o","/dev/null","-m","8","-w","%{ssl_verify_result}",`https://${e}/`],{encoding:"utf8"}),t=(o.stdout??"").trim();return o.status===0&&t==="0"?"trusted":t&&t!=="0"?"untrusted":"unknown"}h(Cs,"Ar"),l(Cs,"probeHostTrust");function $s(e){const o=Ot(e);for(const t of ce(e,s=>s==="project.json"))try{const s=JSON.parse(U(t,"utf8")),n=lo(o,s.name??fe(D(t)),s)?.host;if(n&&!n.includes("*"))return n}catch{}}h($s,"_r"),l($s,"firstClusterHost");function Z(e){try{Bn(e,{force:!0})}catch{}}h(Z,"Z"),l(Z,"rmFile");async function xs(e,o,t,s){const n=_(o,{string:["--cwd","--host","--port"]}),r=P($(n.flags["--cwd"])??e.cwd),i=we(r);if(i)return s(`bridge: ${i}`),{exitCode:1};const a=oe(r),d=$(n.flags["--host"])??e.env?.LENSMCP_WS_HOST??process.env.LENSMCP_WS_HOST,c=$(n.flags["--port"])??e.env?.LENSMCP_WS_PORT??process.env.LENSMCP_WS_PORT??String(a.ports.bridge),u=xn(r);if(!u)return s(`Could not locate the lensmcp bridge bundle.
|
|
987
|
+
`;export async function runCli(e){const o=e.out??(r=>console.log(r)),t=e.err??(r=>console.error(r)),[s,...n]=e.argv;if(!s||s==="--help"||s==="-h")return o(de),{exitCode:0};if(s==="--version"||s==="-V")return o(B()),{exitCode:0};if(Yn(n,s)){const r=n[0]!==void 0&&/^[a-z][a-z-]*$/.test(n[0])?Fe(de,`${s} ${n[0]}`):void 0;return o(r??Fe(de,s)??de),{exitCode:0}}switch(s){case"setup":return Fs(e,n,o,t);case"mcp":return ms(e,n,o,t);case"dashboard":return ws(e,n,o,t);case"gateway":{const r=tt(e,n,o,t),i=_(n,{string:["--cwd","--project","--target"]});return(i.positional[0]??"").toLowerCase()==="stop"&&r.exitCode===0&&!n.includes("--no-compact")&&await Ho(P($(i.flags["--cwd"])??e.cwd),o,e.env),r}case"history":{const r=_(n,{string:["--cwd"]});return Ko(P($(r.flags["--cwd"])??e.cwd),n.filter((i,a)=>i!=="--cwd"&&n[a-1]!=="--cwd"),o,t,e.env)}case"bridge":return js(e,n,o,t);case"install":return rt(e,n,o,t);case"plugin":case"plugins":return ln(e,n,o,t);case"upgrade":return za.has(_(n,{string:["--cwd","--worktree"]}).positional[0]??"")?hn(e,n,o,t):gt(e,n,o,t);case"trust":return at(e,n,o,t);case"versions":{const r={env:e.env??process.env,lensVersion:l(()=>z().version,"lensVersion"),ownVersion:B(),cwd:e.cwd};return wa(n)?ya(n,o,t,r):ka(n,o,t,r)}case"use":return va(n,o,t,{env:e.env??process.env,lensVersion:l(()=>z().version,"lensVersion")});case"run":{const r=_a(n,e.cwd);if("error"in r)return t(r.error),{exitCode:2};const i=Da({cwd:P(r.cwd),...r.project?{project:r.project}:{},packageRoot:F(),env:{...process.env,...e.env??{}}});return"error"in i?(t(i.error),{exitCode:1}):{exitCode:await Ba(r.command,P(r.cwd),i.env,t)}}case"dev":case"build":case"verify":return{exitCode:await Ga(s,n,{cwd:e.cwd,packageRoot:F(),out:o,err:t})};case"services":return{exitCode:Ua(n,{cwd:e.cwd,packageRoot:F(),out:o,err:t,entry:O(e.cwd,"project.js"),notFound:V("project entry","project.js"),env:{...process.env,...e.env}})};case"status":return Ws(e,n,o);case"version-check":return qs(e,n,o);case"doctor":return Js(e,n,o);case"project":return cn(e,n,o,t);case"prune":return ps(e,n,o,t);case"rollout":return $n(e,n,t);case"logs":return Tn(e,n,o,t);case"dismiss":return Ss(e,n,o,t);case"expect":return Es(e,n,o,t);case"lint":return As(e,n,t,o);case"typecheck":return Is(e,n,t,o);case"debug":return An(e,n,o,t);case"mem":return In(e,n,o,t);case"restart":return Ps(e,n,o,t);case"updates":return Ns(e,n,o,t);case"actions":{const r=O(e.cwd,"workspace-action-runner.js");if(!r)return t(V("workspace action runner","workspace-action-runner.js")),{exitCode:1};try{const i=await import(W(r).href);return process.env.LENSMCP_WORKSPACE_ROOT=e.cwd,process.env.LENSMCP_ACTION_RUNNER=r,o(JSON.stringify(await i.workspaceActionsCli(n))),{exitCode:0}}catch(i){return t(i instanceof Error?i.message:String(i)),{exitCode:1}}}case"queue":{const r=O(e.cwd,"workspace-action-runner.js");if(!r)return t(V("machine queue","workspace-action-runner.js")),{exitCode:1};try{const i=await import(W(r).href);process.env.LENSMCP_ACTION_RUNNER=r;const a=await i.queueCli(n,{stdout:l(d=>process.stdout.write(d),"stdout"),stderr:l(d=>process.stderr.write(d),"stderr"),cwd:e.cwd,env:process.env});return a.out!==void 0&&o(a.out),{exitCode:a.exitCode}}catch(i){return t(i instanceof Error?i.message:String(i)),{exitCode:2}}}case"docker":{const r=O(e.cwd,"workspace-action-runner.js");if(!r)return t(V("Docker commands","workspace-action-runner.js")),{exitCode:1};try{const i=await import(W(r).href);if(!i.dockerCli)return t(`${r} was built before the Docker commands \u2014 rebuild it, or upgrade LensMCP.`),{exitCode:1};process.env.LENSMCP_ACTION_RUNNER=r;const a=await i.dockerCli(n,{stdout:l(d=>process.stdout.write(d),"stdout"),stderr:l(d=>process.stderr.write(d),"stderr"),cwd:e.cwd,env:{...process.env,...e.env??{}}});return a.out!==void 0&&o(a.out),{exitCode:a.exitCode}}catch(i){return t(i instanceof Error?i.message:String(i)),{exitCode:2}}}case"workers":case"worker":case"peers":return us(e,s,n,o,t);case"call":return Ts(e,n,o,t);case"tool":return Ms(e,n,o,t);case"instance":case"instances":return Rn(e,n,o,t);case"agent":return Hs(e,n,o,t);default:return t(`Unknown command: ${s}`),t(de),{exitCode:2,message:`Unknown command: ${s}`}}}h(runCli,"runCli"),l(runCli,"runCli");async function us(e,o,t,s,n){const r=O(e.cwd,"workspace-action-runner.js");if(!r)return n(V("Worker Macs commands","workspace-action-runner.js")),{exitCode:1};const i=new AbortController,a=l(()=>i.abort(),"stop");process.once("SIGINT",a);try{const d=await import(W(r).href);if(!d.peersCli)return n(`${r} was built before the Worker Macs commands \u2014 rebuild it, or upgrade LensMCP.`),{exitCode:1};const c=process.stdin.isTTY&&process.stdout.isTTY,u=l(async g=>{const{createInterface:m}=await import("node:readline"),w=m({input:process.stdin,output:process.stdout});return new Promise(f=>w.question(g,y=>{w.close(),f(y)}))},"ask"),p=await d.peersCli([o,...t],{stdout:l(g=>process.stdout.write(g),"stdout"),stderr:l(g=>process.stderr.write(g),"stderr"),cwd:e.cwd,env:{...process.env,...e.env??{}},version:B(),signal:i.signal,...c?{ask:u}:{}});return p.out!==void 0&&s(p.out),{exitCode:p.exitCode}}catch(d){return n(d instanceof Error?d.message:String(d)),{exitCode:2}}finally{process.removeListener("SIGINT",a)}}h(us,"br"),l(us,"runPeers");function ps(e,o,t,s){const n=_(o,{string:["--cwd"],boolean:["--force"]}),r=P($(n.flags["--cwd"])??e.cwd),i=k(r,".lensmcp"),a=k(i,"gateway.log"),d=l(()=>{try{return Ve(i).reduce((g,m)=>{try{return g+Mt(k(i,m)).size}catch{return g}},0)}catch{return 0}},"dirBytes"),c=l(g=>`${(g/1048576).toFixed(1)} MB`,"mb"),u=d();if(u===0)return t(`nothing to prune \u2014 no .lensmcp runtime files at ${i}`),{exitCode:0};if(n.flags["--force"]!==!0&&hs(i))return s("a gateway is running for this workspace \u2014 pruning now can drop a generation a live"),s("writer is still counting (issues/closed/foodguard-13). Stop it first:"),s(" lensmcp gateway stop"),s("\u2026or pass --force if you accept losing recent history."),{exitCode:1,message:"gateway running"};Ao(r,a),To(r);const p=d();return t(`pruned ${i}`),t(` ${c(u)} \u2192 ${c(p)} (reclaimed ${c(Math.max(0,u-p))})`),{exitCode:0}}h(ps,"Cr"),l(ps,"runPrune");function hs(e){try{return st(k(e,"gateway.pid"))!==void 0}catch{return!1}}h(hs,"$r"),l(hs,"gatewayPidAlive");async function ms(e,o,t,s){const n=_(o,{string:["--cwd","--transport","--port","--mcp"]}),r=P($(n.flags["--cwd"])??e.cwd),i=ve({...process.env,...e.env??{}}),a=we(r,i);a!==r&&s(`[lensmcp] ${r} is a checkout with no services of its own (instance create --no-start) \u2014 this session's lens is the main checkout's: ${a}`);const d=qo(a,i);d&&s(`[lensmcp] ${a} is instance '${d}', but its .lensmcp/config.json had no instance identity \u2014 written back from its record`);const c=oe(a),u=$(n.flags["--transport"])??e.env?.LENSMCP_TRANSPORT??"stdio",p=$(n.flags["--port"])??e.env?.LENSMCP_PORT??String(c.ports.mcpHttp),g=bo(a,$(n.flags["--mcp"]),{...process.env,...e.env??{}})==="shared"&&u==="stdio",m=g?bt(a):void 0,w=m??kt(a);if(!w)return s(V("lensmcp-mcp server bundle","main.js")),{exitCode:1};je(a);const f=e.env?.LENSMCP_EVENT_FILE??process.env.LENSMCP_EVENT_FILE??k(a,".lensmcp","events.jsonl"),y={...e.env??{},LENSMCP_TRANSPORT:u,LENSMCP_PORT:p,LENSMCP_EVENT_FILE:f};if(m)return{exitCode:await fs(m,a,y)};const v={...process.env,...y};if(u!=="stdio")return{exitCode:await He({label:`the MCP server (${w})`,args:[w],cwd:a,env:v},s)};const b=g?[w,"--cwd",a]:[w];return{exitCode:L(process.execPath,b,{cwd:a,stdio:"inherit",env:v}).status??1}}h(ms,"jr"),l(ms,"runMcp");async function gs(e){const o=bt(e);if(!o)return{reason:V("lensmcp-mcp shim bundle","shim.js")};const t=await import(W(o).href);if(typeof t.ensureLens!="function")return{reason:"this lensmcp's shim cannot start a lens on its own \u2014 upgrade lensmcp"};const s=await t.ensureLens({cwd:e});return s.ok?{ok:!0}:{reason:s.reason}}h(gs,"Sr"),l(gs,"ensureInstanceLens");async function fs(e,o,t){for(const[n,r]of Object.entries(t))r===void 0?delete process.env[n]:process.env[n]=r;process.chdir(o),process.once("exit",go(o));const s=await import(W(e).href);return typeof s.runShim!="function"?new Promise(()=>{}):s.runShim({cwd:o})}h(fs,"xr"),l(fs,"runShimInProcess");async function ws(e,o,t,s){const n=_(o,{string:["--cwd","--port","--base"]}),r=P($(n.flags["--cwd"])??e.cwd),i=oe(r);if(!$(n.flags["--port"])&&!e.env?.LENSMCP_DASHBOARD_PORT){const p=I("GET","/list");if(p?.status===200&&(p.json?.workspaces??[]).some(g=>g.key===i.key)){const g=`https://lensmcp.local${i.dashboardBasePath}/`;t(`lensmcp dashboard \u2192 the gateway already runs this workspace's dashboard: ${g}`);const m=Me(g,r,{...process.env,...e.env??{}});return m&&t(` sign in \u2192 ${m} (one use, 10 min \u2014 then this browser stays signed in)`),t(" (another, standalone: `lensmcp dashboard --port <a free port>`)"),{exitCode:0}}}const a=$(n.flags["--port"])??e.env?.LENSMCP_DASHBOARD_PORT??String(i.ports.dashboard),d=$(n.flags["--base"])??e.env?.LENSMCP_DASHBOARD_BASE??"",c=O(r,"dashboard.js");if(!c)return s(V("lensmcp dashboard bundle","dashboard.js")),{exitCode:1};je(r);const u=e.env?.LENSMCP_EVENT_FILE??process.env.LENSMCP_EVENT_FILE??k(r,".lensmcp","events.jsonl");return t(`lensmcp dashboard \u2192 http://localhost:${a}${d||"/"} (reading ${u})`),{exitCode:await He({label:`the dashboard (${c})`,args:[c],cwd:r,env:{...process.env,...e.env??{},LENSMCP_DASHBOARD_PORT:a,LENSMCP_DASHBOARD_BASE:d,LENSMCP_EVENT_FILE:u}},s)}}h(ws,"Er"),l(ws,"runDashboard");function Ze(){return k(process.env.LENSMCP_HOME||Gn(),".lensmcp","control.sock")}h(Ze,"Dt"),l(Ze,"controlSocketPath");function I(e,o,t){const s=Ze();return S(s)?Wt(s,e,o,t):null}h(I,"A"),l(I,"daemonRequest");async function et(e,o,t){for(;;){const s=I("GET","/list"),n=s?.status===200&&s.json&&typeof s.json=="object"?s.json.workspaces??[]:[];if(We(n,e,o).kind==="mine")return!0;if(Date.now()>=t)return!1;await new Promise(r=>setTimeout(r,500))}}h(et,"Ft"),l(et,"servedFrom");function vs(){const e=I("GET","/status");if(e?.status!==200||!e.json||typeof e.json!="object")return;const o=e.json.daemon;return typeof o?.wsKey=="string"&&o.wsKey.length>0?o.wsKey:void 0}h(vs,"Mr"),l(vs,"daemonWsKey");function ys(e){const o={};for(const t of ce(e,s=>s==="project.json"))try{const s=JSON.parse(U(t,"utf8")),n=D(t);o[s.name??ge(n)]={root:Nt(e,n)||"."}}catch{}return o}h(ys,"Pr"),l(ys,"buildProjectsMap");function ks(e){const o=k(e,"node_modules",".bin",process.platform==="win32"?"nx.cmd":"nx");if(!S(o))return;const t=L(o,["graph","--print"],{cwd:e,encoding:"utf8",timeout:15e3,maxBuffer:32*1024*1024});if(!(t.status!==0||typeof t.stdout!="string"))try{const s=JSON.parse(t.stdout).graph?.dependencies;return s?Object.fromEntries(Object.entries(s).map(([n,r])=>[n,r.flatMap(i=>typeof i.target=="string"?[i.target]:[])])):void 0}catch{return}}h(ks,"Nr"),l(ks,"buildProjectDependencies");function le(e,o,t=!0){return{wsKey:o,root:e,projects:ys(e),...t?$r(e,()=>ks(e)):{}}}h(le,"fe"),l(le,"gatewayRegistrationBody");function tt(e,o,t,s){const n=_(o,{string:["--cwd","--project","--target"]}),r=(n.positional[0]??"status").toLowerCase(),i=o.includes("--json"),a=P($(n.flags["--cwd"])??e.cwd),d=oe(a),c=k(a,".lensmcp","gateway.pid"),u=k(a,".lensmcp","gateway.log"),p=k(a,".lensmcp","registered.json"),g=`https://lensmcp.local${d.dashboardBasePath}/`,m=l(()=>{const b=Me(g,a,{...process.env,...e.env??{}});b&&t(` sign in \u2192 ${b} (one use, 10 min \u2014 then this browser stays signed in)`)},"printSignIn"),w=l(()=>{const b=fe(a);if(b)return s(`gateway: ${b}`),{exitCode:1};const{pid:x,healed:E}=Ce(c,a);if(x!==void 0&&be(x)){const j=classifyAliveGateway({oursOn443:J(a)!==void 0,port443Held:q().length>0,pidFileAgeMs:nt(c)});if(j==="serving")return E&&t(`healed: adopted a running gateway (pid ${x}) the pid file had lost \u2014 no duplicate started.`),t(`gateway already running (pid ${x}).`),t(` dashboard \u2192 ${g}`),m(),{exitCode:0};if(j==="booting")return t(`gateway starting (pid ${x}) \u2014 :443 not bound yet.`),t(` dashboard \u2192 ${g}`),m(),t(` logs \u2192 ${u}`),{exitCode:0};$e(x,"SIGKILL"),Z(c),ke(a,e.env,()=>{}),t(`reaped a dead gateway (pid ${x} was alive but nothing served :443 for this workspace).`)}const N=q()[0];if(N!==void 0){const j=I("GET","/list");if(j!==null){const R=j.status===200&&j.json&&typeof j.json=="object"?j.json.workspaces??[]:[],K=We(R,d.key,a);if(K.kind==="other-checkout"){for(const Q of Kt(d.key,K.root,a))s(Q);return{exitCode:1}}if(K.kind==="mine")return se(D(p),{recursive:!0}),ne(p,JSON.stringify({wsKey:d.key})),t(`already registered into the shared gateway daemon (pid ${N}).`),t(` dashboard \u2192 ${g}`),m(),{exitCode:0};const X=I("POST","/register",le(a,d.key));if(X&&X.status===200){se(D(p),{recursive:!0}),ne(p,JSON.stringify({wsKey:d.key})),t(`registered '${d.key}' into the shared gateway daemon (pid ${N}).`),t(` dashboard \u2192 ${g}`);const Q=qe(X.json);return Q&&t(Q),m(),t(" the daemon hosts this workspace's services + dashboard; `lensmcp gateway stop` unregisters."),{exitCode:0}}return s(`failed to register into the gateway daemon: ${Ne(X)??(X?JSON.stringify(X.json):"no response from the control socket")}`),{exitCode:1}}return s(`port :443 is held by pid ${N}, which is not this workspace's gateway.
|
|
988
|
+
Free it first (stop that process), then \`lensmcp gateway start\`.`),{exitCode:1}}const C=bs(a,$(n.flags["--project"]),$(n.flags["--target"])),T=$a(F(),{...process.env,...e.env??{}});if(T&&(C||S(k(a,"lensmcp.json")))){const j=Gt(a,u),R=St(process.execPath,ba(T,a,C),{cwd:a,detached:!0,stdio:["ignore",j,j],env:Ft({...process.env,...e.env??{}},u)});return R.unref(),R.pid&&Ue(c,R.pid),t(`gateway starting \u2192 ${C?`${C.project}:${C.target}`:"lensmcp.json"} with lensmcp ${B()}, no nx run (pid ${R.pid??"?"})`),t(` dashboard \u2192 ${g}`),m(),t(` logs \u2192 ${u}`),t(" note: binding :443 needs privilege, and `lensmcp trust` once for the *.local hosts + TLS."),{exitCode:0}}if(!C)return s(`This workspace ('${d.key}') has no gateway target \u2014 no project declares the`),s("`@lensmcp/cluster:gateway` executor, so there is nothing here to launch on :443."),s(""),s(" \u2022 Joining a shared gateway? Start it in the workspace that OWNS it, then run"),s(" `lensmcp gateway start` here \u2014 this workspace registers into it (no local target needed)."),s(" \u2022 Should this workspace host its own gateway? Scaffold it: `lensmcp install`"),s(" (or `lensmcp setup` for the full install + trust bootstrap)."),s(" \u2022 Already have a differently-named target? `lensmcp gateway start --project <p> --target <t>`."),{exitCode:1};const A=xe(a);if(!A)return s("Could not find the `nx` binary in the workspace. Install Nx first: `yarn add -D nx`."),{exitCode:1};const H=Gt(a,u),te=St(A,["run",`${C.project}:${C.target}`],{cwd:a,detached:!0,stdio:["ignore",H,H],env:Ft({...process.env,...e.env??{}},u)});return te.unref(),te.pid&&Ue(c,te.pid),t(`gateway starting \u2192 ${C.project}:${C.target} (pid ${te.pid??"?"})`),t(` dashboard \u2192 ${g}`),m(),t(` logs \u2192 ${u}`),t(" note: binding :443 needs privilege \u2014 if it fails, run the gateway target with sudo,"),t(" and run `nx run gateway:trust` once for the *.local hosts + TLS."),{exitCode:0}},"start"),f=l(()=>{if(S(p)&&J(a)===void 0){let C=d.key;try{C=JSON.parse(U(p,"utf8")).wsKey??d.key}catch{}const T=I("POST","/unregister",{wsKey:C,root:a});Z(p);const A=Ne(T);return t(A??(T&&T.status===200?`unregistered '${C}' from the shared gateway daemon.`:"unregister sent (the daemon may already be gone).")),{exitCode:0}}Z(p);const{pid:b,healed:x}=Ce(c,a);if(b===void 0)return t("gateway not running."),Z(c),{exitCode:0};x&&t(`healed: found an orphaned gateway (pid ${b}) the pid file had lost \u2014 stopping it.`),$e(b);let E=!1;if(!ot(6e3)){E=!0,$e(b,"SIGKILL");const C=J(a);if(C!==void 0)try{process.kill(C,"SIGKILL")}catch{}else q().length>0&&t(":443 is still held by a process that is not this workspace's gateway \u2014 leaving it alone.");ot(3e3)}const N=J(a);return N!==void 0&&N!==b&&($e(N,"SIGKILL"),E=!0),Z(c),E&&ke(a,e.env,()=>{}),t(`gateway stopped (pid ${b})${E?" \u2014 forced (a child ignored SIGTERM)":""}.`),{exitCode:0}},"stop"),y=l(()=>{const{pid:b,healed:x}=Ce(c,a),E=b!==void 0&&be(b)?classifyAliveGateway({oursOn443:J(a)!==void 0,port443Held:q().length>0,pidFileAgeMs:nt(c)}):void 0,N=E==="serving"||E==="booting";if(i){const j=I("GET","/status"),R=j?.status===200&&j.json&&typeof j.json=="object"?j.json:null,K=S(p),X=N?"daemon":R&&K?"guest":R?"other":"stopped";return t(JSON.stringify({thisWorkspace:d.key,role:X,dashboardUrl:g,dashboardLoginUrl:Me(g,a,{...process.env,...e.env??{}})??null,chooserUrl:"https://lensmcp.local/",logFile:u,daemonLogFile:(()=>{const Q=Ie();return Q&&Q!==a?k(Q,".lensmcp","gateway.log"):u})(),mcp:dt(a,e.env??process.env),daemon:R?.daemon??null,workspaces:R?.workspaces??[],services:R?.services??[]})),{exitCode:N||R&&K?0:1}}const C=I("GET","/list"),T=C?.status===200&&C.json&&typeof C.json=="object"?C.json.workspaces??[]:[],A=l(()=>{if(T.length!==0){t(` workspaces (${T.length} registered):`);for(const j of T){if(t(` \u2022 ${j.key} (${j.routes??0} routes, ${j.services??0} services)${j.key===d.key?" \u2190 this workspace":""}`),j.key===d.key||!j.root)continue;const R=Me(`https://lensmcp.local${G(j.root).dashboardBasePath}/`,j.root,{...process.env,...e.env??{},LENSMCP_DASHBOARD_TOKEN:void 0});R&&t(` sign in \u2192 ${R}`)}}},"printWorkspaces"),H=l(()=>{const j=dt(a,e.env??process.env);t(j.mode==="shared"?` mcp \u2192 shared ${j.url} ${j.healthy?"(up)":j.remedy?`(REFUSED \u2014 ${j.error}; ${j.remedy})`:`(DOWN \u2014 ${j.error??"no answer"})`}`:" mcp \u2192 embedded (one server per agent session \u2014 opted out of shared)")},"printMcp"),te=l(()=>{const j=I("GET","/status"),R=j?.status===200&&j.json&&typeof j.json=="object"?j.json.daemon:void 0,K=he(a);R?.version&&K&&R.version!==K&&t(` version \u2192 ${ds(R.version,K)}`)},"printVersionSkew");if(N)return t(E==="booting"?`gateway: starting (pid ${b}) \u2014 :443 not bound yet`:`gateway: running (pid ${b}) \u2014 DAEMON on :443${x?" \u2014 recovered a stale pid file":""}`),t(` workspace \u2192 ${d.key}`),t(` dashboard \u2192 ${g}`),m(),t(" chooser \u2192 https://lensmcp.local/"),t(` logs \u2192 ${u}`),H(),te(),A(),{exitCode:0};if(S(p)&&C?.status===200){const j=q()[0];t(`gateway: registered into a shared daemon${j!==void 0?` (pid ${j})`:""} \u2014 this workspace is a guest`),t(` workspace \u2192 ${d.key}`),t(` dashboard \u2192 ${g}`),m(),t(` logs \u2192 ${u} (this workspace's pods)`);const R=Ie();return R&&R!==a&&t(` ${k(R,".lensmcp","gateway.log")} (the daemon's own log \u2014 gateway-level lines land there)`),t(" attach \u2192 `lensmcp logs <service>` (live, from any workspace)"),t(" stop \u2192 `lensmcp gateway stop` (unregisters; the daemon keeps running)"),H(),te(),A(),{exitCode:0}}return E==="zombie"?(t(`gateway: NOT serving \u2014 tracked pid ${b} is alive but nothing holds :443 for this workspace`),t(" (a crashed gateway under a wedged nx wrapper) \u2014 run `lensmcp gateway restart` to recover."),t(` workspace \u2192 ${d.key}`),t(` logs \u2192 ${u}`),H(),A(),{exitCode:1}):(t("gateway: stopped"),t(` workspace \u2192 ${d.key}`),t(` dashboard \u2192 ${g}`),m(),H(),{exitCode:1})},"status"),v=l(()=>{const b=I("GET","/status");if(b?.status!==200||!b.json||typeof b.json!="object")return t(i?JSON.stringify({daemon:null,workspaces:[],services:[]}):"gateway: no daemon answers on the control socket \u2014 nothing is hosted."),{exitCode:1};const x=b.json;if(i)return t(JSON.stringify(x)),{exitCode:0};t(`daemon: pid ${x.daemon?.pid??"?"} \xB7 owner ${x.daemon?.wsKey??"?"}${x.daemon?.version?` \xB7 lensmcp ${x.daemon.version}`:""}`);for(const E of x.workspaces??[]){t(` ${E.isDaemon?"\u2605":"\xB7"} ${E.key.padEnd(16)} ${String(E.routes??0).padStart(3)} routes ${String(E.services??0).padStart(3)} services ${E.root??""}`);for(const N of(x.services??[]).filter(C=>(C.wsKey??x.daemon?.wsKey)===E.key))t(` ${N.project.padEnd(16)} ${(N.state??"unknown").padEnd(9)} ${N.host??""}`)}return{exitCode:0}},"list");switch(r){case"start":return w();case"stop":return f();case"list":return v();case"restart":return f(),ke(a,e.env,t),w();case"status":return y();default:return s(`Unknown gateway subcommand: ${r} (use start | stop | status | restart | list)`),{exitCode:2}}}h(tt,"Gt"),l(tt,"runGateway");function ke(e,o,t){const s=xe(e);if(!s){t(" (graph refresh skipped \u2014 no nx binary found in the workspace)");return}const n={...process.env,...o??{}},r=l(i=>L(s,i,{cwd:e,env:n,stdio:"ignore"}).status===0,"tryNx");if(r(["reset","--only-daemon"])||r(["daemon","--stop"])){t(" nx project graph refreshed \u2014 a lib/app added since boot will now resolve.");return}t(" (graph refresh best-effort failed \u2014 if a new project does not resolve, run `nx reset`)")}h(ke,"Ee"),l(ke,"refreshNxGraph");function bs(e,o,t){return Zo(e,"@lensmcp/cluster:gateway",o,t)||(o||t?{project:o??"gateway",target:t??"serve"}:void 0)}h(bs,"Lr"),l(bs,"findGatewayTarget");function st(e){const o=io(e);if(o)return co(o.pid,o.stamp)?o.pid:void 0}h(st,"Vt"),l(st,"readPid");function be(e){try{return process.kill(e,0),!0}catch(o){return o.code==="EPERM"}}h(be,"Me"),l(be,"isAlive");function q(){try{const e=L("lsof",["-nP","-iTCP:443","-sTCP:LISTEN","-t"],{encoding:"utf8"});return e.status!==0||!e.stdout?[]:[...new Set(e.stdout.split(/\s+/).map(Number).filter(o=>Number.isInteger(o)&&o>0))]}catch{return[]}}h(q,"z"),l(q,"pidsOnPort443");function Cs(e){try{return(L("ps",["-o","command=","-p",String(e)],{encoding:"utf8"}).stdout??"").trim()}catch{return""}}h(Cs,"Tr"),l(Cs,"processCmd");function J(e){const o=k(e,"node_modules","nx","dist","bin","run-executor.js"),t=k(e,"node_modules","@lensmcp","cluster");for(const s of q()){const n=Cs(s);if(n.includes(o)||n.includes(t)||xa(n,e))return s}}h(J,"Y"),l(J,"gatewayOnPort443");function nt(e){try{return Date.now()-Mt(e).mtimeMs}catch{return}}h(nt,"Ut"),l(nt,"pidFileAgeMs");const Ha=18e4;export function classifyAliveGateway(e){if(e.oursOn443)return"serving";const o=e.pidFileAgeMs!==void 0&&e.pidFileAgeMs<(e.bootGraceMs??Ha);return!e.port443Held&&o?"booting":"zombie"}h(classifyAliveGateway,"classifyAliveGateway"),l(classifyAliveGateway,"classifyAliveGateway");function Ce(e,o){const t=st(e);if(t!==void 0&&be(t))return{pid:t,healed:!1};const s=J(o);if(s!==void 0){try{Ue(e,s)}catch{}return{pid:s,healed:!0}}return{healed:!1}}h(Ce,"Pe"),l(Ce,"reconcileGateway");function $e(e,o="SIGTERM"){try{process.kill(-e,o)}catch{try{process.kill(e,o)}catch{}}}h($e,"Ne"),l($e,"killGatewayTree");function ot(e){const o=Date.now()+e;for(;;){if(q().length===0)return!0;if(Date.now()>=o)return!1;L("sleep",["0.15"])}}h(ot,"Bt"),l(ot,"waitForPortFree");function $s(e){const o=L("curl",["-s","-o","/dev/null","-m","8","-w","%{ssl_verify_result}",`https://${e}/`],{encoding:"utf8"}),t=(o.stdout??"").trim();return o.status===0&&t==="0"?"trusted":t&&t!=="0"?"untrusted":"unknown"}h($s,"Ar"),l($s,"probeHostTrust");function xs(e){const o=_t(e);for(const t of ce(e,s=>s==="project.json"))try{const s=JSON.parse(U(t,"utf8")),n=uo(o,s.name??ge(D(t)),s)?.host;if(n&&!n.includes("*"))return n}catch{}}h(xs,"_r"),l(xs,"firstClusterHost");function Z(e){try{Vn(e,{force:!0})}catch{}}h(Z,"Z"),l(Z,"rmFile");async function js(e,o,t,s){const n=_(o,{string:["--cwd","--host","--port"]}),r=P($(n.flags["--cwd"])??e.cwd),i=fe(r);if(i)return s(`bridge: ${i}`),{exitCode:1};const a=oe(r),d=$(n.flags["--host"])??e.env?.LENSMCP_WS_HOST??process.env.LENSMCP_WS_HOST,c=$(n.flags["--port"])??e.env?.LENSMCP_WS_PORT??process.env.LENSMCP_WS_PORT??String(a.ports.bridge),u=jn(r);if(!u)return s(`Could not locate the lensmcp bridge bundle.
|
|
989
989
|
Looked in (in order):
|
|
990
990
|
\u2022 <cli-package>/bundled/bridge.js (published bin)
|
|
991
991
|
\u2022 <workspace>/libs/bridge/dist/main.js (dev build)
|
|
992
|
-
For dev: \`yarn nx build @lensmcp/bridge\`.`),{exitCode:1};
|
|
992
|
+
For dev: \`yarn nx build @lensmcp/bridge\`.`),{exitCode:1};je(r);const p=e.env?.LENSMCP_EVENT_FILE??process.env.LENSMCP_EVENT_FILE??k(r,".lensmcp","events.jsonl"),g={...process.env,...e.env??{},LENSMCP_EVENT_FILE:p};d&&(g.LENSMCP_WS_HOST=d),c&&(g.LENSMCP_WS_PORT=c);const m=lo(po(ce(r,f=>f==="project.json"),_t(r))),w=ho(g.LENSMCP_BRIDGE_ALLOWED_ORIGINS,m);return w&&(g.LENSMCP_BRIDGE_ALLOWED_ORIGINS=w),t(`lensmcp bridge \u2192 ws://${d??"127.0.0.1"}:${c??"5747"} (forwarding to ${p})`),m.length>0&&t(` admitting this workspace's cluster hosts: ${m.join(", ")}`),{exitCode:await He({label:`the bridge (${u})`,args:[u],cwd:r,env:g},s)}}h(js,"Or"),l(js,"runBridge");async function Ss(e,o,t,s){const n=ir(o);if("error"in n)return s(`lensmcp dismiss: ${n.error}`),s(ar),{exitCode:2};const r=P(n.cwd??e.cwd),i={...process.env,...e.env??{}},a=await cr(n,{session:l(d=>ie({cwd:r,env:i,budgetMs:8e3,clientName:"lensmcp-dismiss"},d),"session")});for(const d of a.lines)(a.exitCode===2?s:t)(d);return{exitCode:a.exitCode}}h(Ss,"Ir"),l(Ss,"runDismiss");async function Es(e,o,t,s){const n=ur(o);if("error"in n)return s(`lensmcp expect: ${n.error}`),s(lr),{exitCode:2};const r=P(n.cwd??e.cwd),i={...process.env,...e.env??{}},a=await pr(n,{session:l(d=>ie({cwd:r,env:i,budgetMs:8e3,clientName:"lensmcp-expect"},d),"session")});for(const d of a.lines)(a.exitCode===0?t:s)(d);return{exitCode:a.exitCode}}h(Es,"Dr"),l(Es,"runExpect");async function Ms(e,o,t,s){const n=zo(o);if("error"in n)return s(`lensmcp tool: ${n.error}`),s(Xo),{exitCode:2};const r={...process.env,...e.env??{}};let i=we(P(n.cwd??e.cwd),ve(r));if(n.instance){const u=Wo(I("GET","/list"),n.instance,G(i));if(typeof u=="string")return s(`lensmcp tool --instance ${n.instance}: ${u}`),{exitCode:1};i=u.root}const a=n.input==="-"?U(0,"utf8"):n.input,d=Date.now(),c=await Yo(n,a,async(u,p)=>{const g=l(()=>ie({cwd:i,env:r,budgetMs:Math.max(1e3,n.timeoutS*1e3-(Date.now()-d)),clientName:"lensmcp-tool"},w=>w.call(u,p)),"call");let m=await g();if(!m.available&&n.instance&&/no server on this workspace/.test(m.reason)){const w=await gs(i);if("reason"in w)return{available:!1,reason:`${m.reason}, and none could be started there \u2014 ${w.reason}`};s(`lensmcp tool: started the lens server of ${n.instance} (${i})`),m=await g()}return m.available?{available:!0,value:m.value}:{available:!1,reason:m.reason}});for(const u of c.out)t(u);for(const u of c.err)s(u);return{exitCode:c.exitCode}}h(Ms,"Fr"),l(Ms,"runTool");async function Ps(e,o,t,s){if(_(o,{string:["--cwd"],boolean:["--yes"]}).positional.length===0)return Ls(e,o,t,s);const n=hr(o);if("error"in n)return s(`lensmcp restart: ${n.error}`),s(mr),{exitCode:2};const r=G(P(n.cwd??e.cwd)),i=re(r)?r.instance:void 0,a=await gr(n,{here:{key:r.key,baseKey:i?.baseKey??r.key,...i?{instance:i.name}:{}},request:l((d,c,u)=>I(d,c,u),"request"),now:l(()=>Date.now(),"now"),sleep:l(d=>new Promise(c=>setTimeout(c,d)),"sleep")});if(n.json)t(JSON.stringify({...a.result,answer:a.lines.join(" ")},null,2));else for(const d of a.lines)(a.exitCode===0||a.exitCode===3?t:s)(d);return{exitCode:a.exitCode}}h(Ps,"Gr"),l(Ps,"runRestart");function Ns(e,o,t,s){const n=fr(o);if("error"in n)return s(`lensmcp updates: ${n.error}`),s(vr),{exitCode:2};const r=P(n.cwd??e.cwd);let i=r;try{i=Et(r)}catch{}let a;try{a=Kn().username}catch{a=process.env.USER||process.env.LOGNAME||"person"}const d=wr(n,{root:i,user:a,request:l((c,u,p,g)=>{const m=Ze();return S(m)?Wt(m,c,u,p,g):null},"request"),now:l(()=>Date.now(),"now")});if(n.json)t(JSON.stringify(d.result,null,2));else for(const c of d.lines)(d.exitCode===0||d.exitCode===3?t:s)(c);return{exitCode:d.exitCode}}h(Ns,"Vr"),l(Ns,"runUpdates");async function Ls(e,o,t,s){const n=_(o,{string:["--cwd"],boolean:["--yes"]}),r=n.flags["--yes"]===!0,i=P($(n.flags["--cwd"])??e.cwd),a=ns({...process.env,...e.env??{}}),d=Qe(a),c=ye({env:a}),u=z(),p=a.LENSMCP_NO_STORE==="1"?void 0:Re(c),g=Xe(d),m=Aa({...g?.phase==="finish"?{unfinished:g.to}:{},...u.version?{running:u.version}:{},...p?{current:p}:{}});if(m.kind==="resume")return t(`an unfinished upgrade to ${m.to}: resuming it \u2014 its restart names the team and asks first`),gt({...e,cwd:i},[m.to,"--resume","--cwd",i,...r?["--yes"]:[]],t,s);if(m.kind==="nothing")return t(m.why),{exitCode:0};const w=Ie(),f=mt(c,m.current);if(!w||!f)return s(`the daemon runs ${m.running} and ${m.current} is current, but ${w?`lensmcp ${m.current} is not whole in the store`:"the daemon does not say which workspace owns it"} \u2014 run \`lensmcp gateway restart\` in its workspace.`),{exitCode:1};const y=Zt({home:d}),v=[w,...y.filter(C=>u.registeredKeys.includes(C.key)&&C.root!==w).map(C=>C.root)],b=ht(i,a,B()),x=await la({activities:v.map(C=>({...b(C),key:y.find(T=>T.root===C)?.key??ge(C)})),tty:Se(),yes:r,dryRun:!1,ask:Ye,ownerRoot:w});for(const C of x.lines)t(C);if(!x.restart)return{exitCode:x.answer==="no"?0:1};if(x.answer===void 0&&!r&&Se()&&!await Ye(`Restart the lens onto ${m.current}? Every workspace it serves loses it for a minute or more`))return t(" restart \u2192 not now"),{exitCode:0};if(t(` restart \u2192 the daemon ('${u.wsKey??ge(w)}') runs ${m.running}; restarting it with lensmcp ${m.current} \u2026`),es(f,w,a)!==0)return s(` restart \u2192 \`lensmcp gateway restart\` failed in ${w} \u2014 check \`lensmcp gateway status\` there.`),{exitCode:1};if(!await wt(18e4))return s(" restart \u2192 the restarted daemon did not answer within 3 minutes \u2014 check `lensmcp gateway status`."),{exitCode:1};const E=Date.now()+15e3;for(const C of y.filter(T=>u.registeredKeys.includes(T.key)&&T.root!==w)){if(await et(C.key,C.root,E))continue;const T=I("POST","/register",le(C.root,C.key));t(T?.status===200?` restart \u2192 re-registered '${C.key}'`:` restart \u2192 '${C.key}' is not back \u2014 \`lensmcp gateway start\` in ${C.root}`)}const N=z();return t(N.version===m.current?` daemon \u2192 now running ${m.current} \u2713`:` daemon \u2192 runs ${N.version??"an unknown version"}, not ${m.current} \u2014 check \`lensmcp gateway status\``),{exitCode:N.version===m.current?0:1}}h(Ls,"Ur"),l(Ls,"runLensRestart");async function Ts(e,o,t,s){const n=br(o);if("error"in n)return s(`lensmcp call: ${n.error}`),s(yr),{exitCode:2};const r=P(n.cwd??e.cwd),i=G(r),a=re(i)?i.instance:void 0,d=await Cr(n,{here:{key:i.key,baseKey:a?.baseKey??i.key,...a?{instance:a.name}:{}},request:l((c,u,p)=>I(c,u,p),"request"),send:l(c=>kr(c),"send"),readFile:l(c=>U(P(r,c),"utf8"),"readFile"),now:l(()=>Date.now(),"now")});if(n.json)t(JSON.stringify(d.result,null,2));else for(const c of d.lines)(d.exitCode===0?t:s)(c);return{exitCode:d.exitCode}}h(Ts,"Br"),l(Ts,"runCall");async function As(e,o,t,s=n=>console.log(n)){const n=At(o),r=P(n.cwd??e.cwd),i={...process.env,...e.env??{}};if(to(n.runnerArgs))return Rs(n.runnerArgs,r,i,t,s);const a=Sn(r);if(!a)return t(`Could not locate the lensmcp lint runner.
|
|
993
993
|
Looked in (in order):
|
|
994
994
|
\u2022 <cli-package>/bundled/lint-runner.js (published bin)
|
|
995
995
|
\u2022 <workspace>/libs/session/dist/lint-runner.js (dev build)
|
|
996
|
-
For dev: \`yarn nx build @lensmcp/session\`.`),{exitCode:2};const d=e.env?.LENSMCP_EVENT_FILE??process.env.LENSMCP_EVENT_FILE??k(r,".lensmcp","events.jsonl");let c,u="";if(
|
|
996
|
+
For dev: \`yarn nx build @lensmcp/session\`.`),{exitCode:2};const d=e.env?.LENSMCP_EVENT_FILE??process.env.LENSMCP_EVENT_FILE??k(r,".lensmcp","events.jsonl");let c,u="";if(so(n.runnerArgs)){const p=await ie({cwd:we(r,ve(i)),env:i,budgetMs:8e3,clientName:"lensmcp-lint"},g=>g.read("lint://base"));p.available?p.value&&typeof p.value=="object"?c=JSON.stringify(p.value):u="this checkout\u2019s lens does not answer lint://base (a lensmcp from before it kept the lint status)":u=`no lens answered: ${p.reason}`}return{exitCode:L(process.execPath,[a,...n.runnerArgs],{cwd:r,stdio:[c===void 0?"inherit":"pipe","inherit","inherit"],...c===void 0?{}:{input:c},env:{...i,LENSMCP_EVENT_FILE:d,LENSMCP_LINT_BASE:c===void 0?"":"stdin",LENSMCP_LINT_BASE_WHY:u}}).status??2}}h(As,"Hr"),l(As,"runLint");async function Rs(e,o,t,s,n){if((e.includes("--")?e.slice(0,e.indexOf("--")):e).includes("--sha")){const i=O(o,"workspace-action-runner.js");if(!i)return s(V("cold lint (the action runner)","workspace-action-runner.js")),{exitCode:2};try{const a=await import(W(i).href);if(!a.lintColdCli)return s(`${i} was built before cold lints \u2014 rebuild it, or upgrade LensMCP.`),{exitCode:2};process.env.LENSMCP_ACTION_RUNNER=i;const d=await a.lintColdCli([...e],{stdout:l(c=>process.stdout.write(c),"stdout"),stderr:l(c=>process.stderr.write(c),"stderr"),cwd:o,env:t});return d.out&&n(d.out),{exitCode:d.exitCode}}catch(a){return s(a instanceof Error?a.message:String(a)),{exitCode:2}}}const r=Ct(o);return r?{exitCode:await no(e,o,{runner:l((i,a={})=>{const d=L(process.execPath,[r,"lint",...i],{cwd:o,stdio:[a.input===void 0?"inherit":"pipe",a.capture?"pipe":"inherit","inherit"],...a.input===void 0?{}:{input:a.input},encoding:"utf8",maxBuffer:268435456,env:{...t,...a.env??{}}});return{status:d.status,stdout:a.capture?String(d.stdout??""):""}},"runner"),call:l(async(i,a)=>{const d=await ie({cwd:we(o,ve(t)),env:t,budgetMs:a,clientName:"lensmcp-lint"},c=>c.call("lint",i));return d.available?{available:!0,...d.value}:{available:!1,reason:d.reason}},"call"),err:s})}:(s(`Could not locate the lensmcp static-checks runner.
|
|
997
997
|
Looked in (in order):
|
|
998
998
|
\u2022 <cli-package>/bundled/static-checks-runner.js (published bin)
|
|
999
999
|
\u2022 <workspace>/libs/static-checks/dist/runner.js (dev build)
|
|
1000
|
-
For dev: \`yarn nx build @lensmcp/static-checks\`.`),{exitCode:2})}h(
|
|
1000
|
+
For dev: \`yarn nx build @lensmcp/static-checks\`.`),{exitCode:2})}h(Rs,"Wr"),l(Rs,"runLintByUnit");async function Is(e,o,t,s=n=>console.log(n)){const n=At(o),r=P(n.cwd??e.cwd),i={...process.env,...e.env??{}};if(n.runnerArgs.includes("--sha")){const d=O(r,"workspace-action-runner.js");if(!d)return t(V("cold type check (the action runner)","workspace-action-runner.js")),{exitCode:2};try{const c=await import(W(d).href);if(!c.typecheckColdCli)return t(`${d} was built before cold type checks \u2014 rebuild it, or upgrade LensMCP.`),{exitCode:2};process.env.LENSMCP_ACTION_RUNNER=d;const u=await c.typecheckColdCli(n.runnerArgs,{stdout:l(p=>process.stdout.write(p),"stdout"),stderr:l(p=>process.stderr.write(p),"stderr"),cwd:r,env:i});return u.out&&s(u.out),{exitCode:u.exitCode}}catch(c){return t(c instanceof Error?c.message:String(c)),{exitCode:2}}}const a=Ct(r);return a?{exitCode:await dr(n.runnerArgs,r,{runner:l((d,c={})=>{const u=L(process.execPath,[a,"typecheck",...d],{cwd:r,stdio:[c.input===void 0?"inherit":"pipe",c.capture?"pipe":"inherit","inherit"],...c.input===void 0?{}:{input:c.input},encoding:"utf8",maxBuffer:268435456,env:{...i,...c.env??{}}});return{status:u.status,stdout:c.capture?String(u.stdout??""):""}},"runner"),call:l(async(d,c)=>{const u=await ie({cwd:we(r,ve(i)),env:i,budgetMs:c,clientName:"lensmcp-typecheck"},p=>p.call("typecheck",d));return u.available?{available:!0,...u.value}:{available:!1,reason:u.reason}},"call"),heavy:l(async d=>{const c=O(r,"workspace-action-runner.js");if(!c)return{unavailable:V("machine queue","workspace-action-runner.js")};try{const u=await import(W(c).href);process.env.LENSMCP_ACTION_RUNNER=c;const p=Math.min(65536,Math.max(256,Math.ceil(d.needMb))),g=["run","--lane","heavy","--priority","2","--work","typecheck","--heap",String(p),"--label",d.label,"--",process.execPath,a,"typecheck",...d.args];return(await u.queueCli(g,{stdout:l(m=>process.stdout.write(m),"stdout"),stderr:l(m=>process.stderr.write(m),"stderr"),cwd:r,env:i})).exitCode}catch(u){return{unavailable:`the machine queue could not be joined \u2014 ${u instanceof Error?u.message:String(u)}`}}},"heavy"),err:t})}:(t(`Could not locate the lensmcp static-checks runner.
|
|
1001
1001
|
Looked in (in order):
|
|
1002
1002
|
\u2022 <cli-package>/bundled/static-checks-runner.js (published bin)
|
|
1003
1003
|
\u2022 <workspace>/libs/static-checks/dist/runner.js (dev build)
|
|
1004
|
-
For dev: \`yarn nx build @lensmcp/static-checks\`.`),{exitCode:2})}h(
|
|
1005
|
-
`)}catch{}}h(Is,"qr"),l(Is,"writeSetupState");async function Os(e,o,t,s){const n=ae(e,t),r=o?{mode:o.mode,source:"flag"}:n,i=r.mode;if(s(""),s(`[mcp] mode \u2192 ${i} (${Dt[r.source]})`),o?.wrote&&s(` wrote ${bo}`),i==="embedded"){s(" every agent session builds its OWN MCP server, and keeps serving"),s(" the bundle it started with until that session exits."),s(` ${Ne(r)}`);return}s(` sessions proxy into ONE shared server at ${n.url}`),s(" .mcp.json is unchanged \u2014 `lensmcp mcp` is a thin stdio shim into it."),s(` ${Ne(r)}`);const a=await Bt(n.url);if(!a.ok&&!a.remedy){s(` \xB7 not up yet (${a.error??"unknown"}) \u2014 the next session starts it on demand`);return}a.ok||s(` ! refused: ${a.error}`);const d=me(e)??B(),c=Ge({identity:Ke(n.port),targetVersion:d,expectedRoot:Oe(e),expectedKey:oe(e).key,port:n.port,selfPid:process.pid});if(!c.kill){s(a.ok?` \u2713 already up \u2014 ${a.server??"MCP"} (protocol ${a.protocolVersion??"?"}) \u2014 ${c.reason}`:` ! not restarted (${c.reason}) \u2014 ${a.remedy}`);return}try{process.kill(c.pid,"SIGTERM"),s(` \u21BA restarted the shared server \u2014 it was ${c.reason}; the next session brings it up on ${d}`)}catch(u){s(` ! the shared server is ${c.reason} and could not be stopped (pid ${c.pid}): ${u.message}`)}}h(Os,"Jr"),l(Os,"applyMcpModeStep");function _s(e,o,t){const s=Jt({cwd:e,cliVersion:B()}),n=Mr({run:Er(o),facts:s,installed:l(()=>Je(e)?.version,"installed")});if(!(n.outcome==="current"||n.outcome==="unknown")){if(t(""),n.outcome==="ahead"){t(`[plugin] ${n.from} \u2014 newer than this workspace's lensmcp ${n.to}; another workspace's lensmcp installed it, and it stays.`),t(" `lensmcp upgrade` brings this workspace up to it.");return}if(n.outcome==="updated"){t(`[plugin] ${n.from} \u2192 ${n.to}`),t(" restart Claude Code for the new plugin to load.");return}t(`[plugin] the Claude Code plugin is ${n.from}, this lensmcp is ${n.to}.`),t(` could not update it automatically (${n.detail??"unknown reason"}). Run:`);for(const r of n.commands??[])t(` ${r}`);t(" \u2026then restart Claude Code.")}}h(_s,"zr"),l(_s,"applyPluginSyncStep");const Ka=5*6e4;function Ds(e,o,t){try{const s=B(),n=Po({env:o,holder:os(Xe(o)),alive:ns,instance:re(G(e)),to:s});if(!n.run){n.line&&(t(""),t(n.line));return}t("");const r=O(e,"migrations.js");if(!r){t(No);return}const i=k(F(),"bin.js"),a=Ae(e),d=Eo({root:e,to:s,journalExists:S(ts(e)),...a?{setupBefore:a}:{},...S(i)?{cliBin:i}:{}}),c=he(r,d,e,o,Ka);for(const u of Mo({root:e,to:s,...c}))t(u)}catch(s){t(`[migrations] could not run (${s instanceof Error?s.message:String(s)}) \u2014 setup goes on`)}}h(Ds,"Xr"),l(Ds,"runSetupMigrations");function Bs(e,o,t){const s=Qn(e,me(e)??B());for(const n of o?[JSON.stringify(s,null,2)]:Xn(s))t(n);return{exitCode:0}}h(Bs,"Qr"),l(Bs,"runSetupStatus");async function Vs(e,o,t,s){const n=_(o,{string:[...Lt.string],boolean:[...Lt.boolean]}),r=P($(n.flags["--cwd"])??e.cwd),i={...e,cwd:r},a=Yn(n.flags,n.positional);if(a)return s(a),s(Fe(le,"setup")??"Usage: lensmcp setup [flags] | lensmcp setup status"),{exitCode:2};if(n.positional[0]==="status")return Bs(r,n.flags["--json"]===!0,t);const d=we(r);if(d)return s(`setup: ${d}`),{exitCode:1};const c=$(n.flags["--mcp"]);if(c!==void 0&&!_t(c))return s(`setup: --mcp must be "embedded" or "shared" (got "${c}").`),{exitCode:1};t("lensmcp setup \u2014 first-time bootstrap (install \u2192 trust \u2192 pods)"),t("");const u=ds(r);t(u?"[1/3] install \u2014 skipped: lensmcp.json declares this project and nothing of LensMCP is in it; its services start instrumented from this machine's lensmcp":"[1/3] install \u2014 plugin, .mcp.json, nx config, vite/nest wiring");const p=u?{exitCode:0}:ot(i,o,t,s);if(p.exitCode!==0)return s(""),s("setup: the install step failed \u2014 fix the above and re-run `lensmcp setup`."),p;t(""),t("[2/3] trust \u2014 dev CA \u2192 System keychain, /etc/hosts, DNS flush (sudo, only for what is missing)");const g=rt(i,o,t,s);if(g.exitCode!==0)return s(""),s("setup: the trust step failed \u2014 run `lensmcp setup` directly in a terminal so sudo can prompt."),g;t(""),t("[3/3] pods \u2014 recycle this workspace's devservers, reconcile the gateway");const m=oe(r),w=m.key,f=no({previous:it(r),current:at(r),disabled:n.flags["--no-recycle"]===!0}),y=f.recycle?Pn(r,Me(m),t,f.reason):(t(` \xB7 pods left running \u2014 ${f.reason}`),{killed:0,stale:0});Nn(i,r,w,t);const v=_t(c)?xo(r,c):void 0;Ds(r,{...process.env,...e.env??{}},t),await Os(r,v,e.env??process.env,t);try{_s(r,{...process.env,...e.env??{}},t)}catch{}return Is(r,f.recycle),t(""),t("\u2713 setup complete."),(y.killed>0||y.stale>0)&&t(` recycled ${y.killed} pod${y.killed===1?"":"s"}`+(y.stale>0?` (+${y.stale} stale socket${y.stale===1?"":"s"} cleared)`:"")+" \u2014 they come back on the new wiring."),t(" next: lensmcp gateway start (the :443 front door \u2014 needs sudo)"),t(" verify: lensmcp doctor"),{exitCode:0}}h(Vs,"Zr"),l(Vs,"runSetup");const Fs=64*1024*1024,Gs=3e4,Wa=10*6e4;async function Us(e,o,t,s){if(o[0]==="archive")return Hs(e,o.slice(1),s);const n=o[0]==="hook";if(o[0]!=="asked"&&!n){const i=O(e.cwd,"coordination.js");if(!i)return s(V("agent coordination entry","coordination.js")),{exitCode:1};const a=Wn(o)?U(0,"utf8"):void 0,d=o.some(g=>g==="--cwd"||g.startsWith("--cwd=")),c=o[0]==="skill"?Wa:Gs,u=L(process.execPath,[i,...o,...d?[]:["--cwd",e.cwd]],{cwd:e.cwd,env:{...process.env,...e.env},encoding:"utf8",timeout:c,maxBuffer:Fs,...a!==void 0?{input:a}:{}}),p=u.error?.code;return p==="ENOBUFS"||p==="ETIMEDOUT"?(s(p==="ENOBUFS"?`lensmcp agent ${o[0]??""}: the answer is over ${Fs/(1024*1024)} MB \u2014 nothing was printed. Narrow it (agent tasks --state / --role / --parent) or read the board on the Team page.`:o[0]==="skill"?`lensmcp agent skill: no answer in ${c/6e4} minutes \u2014 nothing was printed. A draft it started is kept: lensmcp agent skill list names it, and Team \u203A Skills shows its run.`:`lensmcp agent ${o[0]??""}: no answer in ${Gs/1e3} s \u2014 nothing was printed (the coordination store may be busy; try again).`),{exitCode:1}):(u.stdout&&t(u.stdout.trimEnd()),u.stderr&&s(u.stderr.trimEnd()),{exitCode:u.status??1})}const r=await new Promise(i=>{if(process.stdin.isTTY){i("");return}let a="";const d=l(()=>{clearTimeout(u),process.stdin.removeListener("data",c),process.stdin.removeListener("end",d),process.stdin.removeListener("error",d),process.stdin.pause(),i(a)},"finish"),c=l(p=>{a+=p,a.length>1e6&&d()},"data"),u=setTimeout(d,n?300:2e3);process.stdin.setEncoding("utf8"),process.stdin.on("data",c),process.stdin.on("end",d),process.stdin.on("error",d)});if(n){const i=O(e.cwd,"coordination.js");if(!i||r.length>1e6)return{exitCode:0};const a={...process.env,...e.env},d=o.includes("SessionStart")&&a.LENSMCP_LAUNCH_ID||void 0,c=L(process.execPath,[i,...o,"--cwd",e.cwd],{cwd:e.cwd,env:a,input:r,encoding:"utf8",timeout:d?qa:2200,maxBuffer:64e3,stdio:["pipe","pipe","pipe"]});return c.status===0&&c.stdout?t(c.stdout.trimEnd()):d&&t(launchedStartMissed(d)),{exitCode:0}}return go(r,{env:{...process.env,...e.env??{}},cwd:e.cwd}),{exitCode:0}}h(Us,"ti"),l(Us,"runAgent");const qa=4e3;export function launchedStartMissed(e){return`LensMCP's start hook did not finish, so no credential reached you. If this conversation already holds a LensMCP credential (you are a resumed worker), call agent_session { action: "resume", credential: <the newest one you hold>, launch: "${e.slice(0,80)}" } before any other LensMCP call; otherwise agent_join as your brief says.`}h(launchedStartMissed,"launchedStartMissed"),l(launchedStartMissed,"launchedStartMissed");function Hs(e,o,t){const s=o[0];if(!s||o.length>1||s.startsWith("-"))return t("Usage: lensmcp agent archive <taskId> \u2014 writes the task's archive (its events, run review, performance, flows, AI calls and test runs) into ~/.lensmcp/team-archive/<workspace>/<goal>/"),{exitCode:2};const n=O(e.cwd,"goal-archive.js");if(!n)return t(V("goal archive writer","goal-archive.js")),{exitCode:1};const r=L(process.execPath,[n,"--goal",s,"--root",e.cwd],{cwd:e.cwd,env:{...process.env,...e.env},stdio:"inherit"});return r.error?(t(`lensmcp agent archive: ${r.error.message}`),{exitCode:1}):{exitCode:r.status??1}}h(Hs,"si"),l(Hs,"runAgentArchive");async function Ks(e,o,t){const s=_(o,{string:["--cwd","--hook","--timeout","--session"],boolean:["--json","--quiet"]}),n=P($(s.flags["--cwd"])??e.cwd),r=$(s.flags["--hook"]),i=Ut(r)?r:void 0,a=$(s.flags["--session"]);if(r!==void 0&&i===void 0)return{exitCode:0};if(r!==void 0&&vo(n,"lens"))return{exitCode:0};const d=s.flags["--json"]===!0,c=s.flags["--quiet"]===!0||r!==void 0,u=Number($(s.flags["--timeout"])??""),p=Number.isFinite(u)&&u>0?u:Do,g={...process.env,...e.env??{}};try{const m=await Bo({cwd:n,env:g,budgetMs:p,verify:l(y=>Ao(y).map(v=>v.resource),"verify")});if(!m.available)return d&&!c?t(JSON.stringify({available:!1,workspace:m.source.workspace,mode:m.source.mode,reason:m.reason,elapsedMs:m.elapsedMs})):c||t(`lensmcp status \u2014 ${m.source.workspace}: unavailable (${m.reason})`),{exitCode:0};const w=_o(m.status,m.evidence,Date.now()),f=Oo(w,{workspace:m.source.workspace,includeUnmonitored:i==="SessionStart"||!c});if(d)return c&&f===void 0?{exitCode:0}:(t(JSON.stringify({available:!0,workspace:m.source.workspace,mode:m.source.mode,url:m.source.url,aggregate:m.status.status??"unknown",elapsedMs:m.elapsedMs,findings:w.findings,suppressed:w.suppressed,unmonitored:w.unmonitored})),{exitCode:0});if(i){const y=Io(w.findings);return wo(a,y)?(f!==void 0&&t(Gt(i,f)),a&&fo(a,y),{exitCode:0}):{exitCode:0}}if(c)return f!==void 0&&t(f),{exitCode:0};if(t(`lensmcp status \u2014 ${m.source.workspace} (${m.source.mode}, ${m.source.url})`),t(` aggregate says: ${m.status.status??"unknown"} (read in ${m.elapsedMs}ms)`),w.findings.length===0)t(" nothing actionable that this command can vouch for.");else for(const y of w.findings)t(` \u2022 ${Ro(y)}`);for(const y of w.suppressed)t(` \xB7 not reported \u2014 ${y.kind}: ${y.reason}`);return w.unmonitored.length>0&&t(` \xB7 unmonitored (unknown, NOT clean): ${w.unmonitored.join(", ")}`),{exitCode:0}}catch(m){return c||t(`lensmcp status: unavailable (${m instanceof Error?m.message:String(m)})`),{exitCode:0}}}h(Ks,"oi"),l(Ks,"runStatus");function Ws(e,o,t){const s=_(o,{string:["--cwd","--hook","--plugin-root"],boolean:["--json","--quiet"]}),n=P($(s.flags["--cwd"])??e.cwd),r=$(s.flags["--hook"]),i=Ut(r)?r:void 0;if(r!==void 0&&i===void 0)return{exitCode:0};const a=s.flags["--json"]===!0,d=s.flags["--quiet"]===!0||r!==void 0,c=$(s.flags["--plugin-root"]);try{const u=Jt({cwd:n,cliVersion:B(),...c?{pluginRoot:c}:{}}),p=Sr(u);if(a)return d&&!p?{exitCode:0}:(t(JSON.stringify({...u,skew:p??null})),{exitCode:0});if(i)return p&&t(Gt(i,Wt(p))),{exitCode:0};if(d)return p&&t(Wt(p)),{exitCode:0};if(t(`lensmcp version-check \u2014 ${u.pluginId??"lensmcp plugin"}`),t(` plugin ${u.plugin??"unknown"}${u.pluginSource?` (${u.pluginSource})`:""}`),t(` project ${u.project??"unknown"} (node_modules/lensmcp)`),t(` cli ${u.cli??"unknown"} (the binary running now)`),!p)return t(u.plugin&&(u.project??u.cli)?" \u2713 in step.":" ? cannot compare \u2014 one of the versions is unreadable (staying silent)."),{exitCode:0};t(` \u2717 the plugin is ${p.direction} \u2014 update it, then restart Claude Code:`);for(const g of Pr(p))t(` ${g}`);return{exitCode:0}}catch(u){return d||t(`lensmcp version-check: unavailable (${u instanceof Error?u.message:String(u)})`),{exitCode:0}}}h(Ws,"ri"),l(Ws,"runVersionCheck");async function qs(e,o,t){const s=_(o,{string:["--cwd"],boolean:["--json"]}),n=P($(s.flags["--cwd"])??e.cwd),r=s.flags["--json"]===!0,i=[];zs(i),Ys(n,i),Xs(n,i),Qs(n,e.env??process.env,i),await Zs(n,e.env??process.env,i),en(n,i),tn(n,{...process.env,...e.env??{}},i),Js({...process.env,...e.env??{}},i),sn(n,i),nn(n,i);const a=rn(e,n,i);!a||a.needs.includes("chrome")?cn(i):M(i,"info","Chrome for browser:// capture","no feature that is on needs it"),await In(n,i),await On(n,e.env??process.env,i);const d=i.some(u=>u.status==="fail"),c=i.some(u=>u.status==="warn");if(r)return t(JSON.stringify({ok:!d,summary:{total:i.length,failed:i.filter(u=>u.status==="fail").length,warnings:i.filter(u=>u.status==="warn").length},checks:i},null,2)),{exitCode:d?1:0};for(const u of i){const p=u.status==="pass"?"\u2713":u.status==="info"?"\xB7":u.status==="warn"?"!":"\u2717";t(`${p} ${u.label}${u.detail?` \u2014 ${u.detail}`:""}`),u.status!=="pass"&&u.hint&&t(` \u21B3 ${u.hint}`)}return t(""),t(d?"doctor: issues found (see \u2717 above).":c?"doctor: ok, with warnings (!).":"doctor: all checks passed."),{exitCode:d?1:0}}h(qs,"ii"),l(qs,"runDoctor");function Js(e,o){if(e.LENSMCP_NO_STORE==="1")return;const t=ke({env:e}),s=Re(t);if(!s)return;const n=z().version;cs(n,s)?M(o,"warn",`LensMCP store: ${s} is current`,`the running lens runs ${n}`,`it keeps ${n} until it restarts: lensmcp restart`):M(o,"pass",`LensMCP store: ${s} is current`,n?"the running lens runs it":"no lens runs now")}h(Js,"ai"),l(Js,"checkStore");function M(e,o,t,s,n){e.push({status:o,label:t,detail:s,hint:n})}h(M,"M"),l(M,"add");function zs(e){const o=Number(process.versions.node.split(".")[0]);o>=20?M(e,"pass",`Node ${process.versions.node}`):o>=18?M(e,"warn",`Node ${process.versions.node}`,"older than recommended","upgrade to Node 20+ for best results"):M(e,"fail",`Node ${process.versions.node}`,"too old","LensMCP needs Node 18+ (20+ recommended)")}h(zs,"ci"),l(zs,"checkNode");function Ys(e,o){const t=we(e);t&&M(o,"fail","lensmcp.json parses",t,"fix the JSON in lensmcp.json, or remove it");const s=k(e,"nx.json");if(!S(s)){M(o,"fail","nx.json at workspace root","missing","run `lensmcp` from inside a Nx workspace");return}let n;try{n=JSON.parse(U(s,"utf8"))}catch(c){M(o,"fail","nx.json parses",c.message,"fix the JSON syntax in nx.json");return}const r=(n.plugins??[]).some(c=>typeof c=="string"?c==="@lensmcp/nx-plugin":!!c&&typeof c=="object"&&c.plugin==="@lensmcp/nx-plugin"),i=Va(e),a=!r&&S(k(e,"lensmcp.json"))&&!t;M(o,r||a?"pass":"fail",a?"lensmcp.json declares this project (no @lensmcp/nx-plugin needed)":"@lensmcp/nx-plugin registered in nx.json#plugins",r||a?void 0:"not registered",r||a?void 0:"run `lensmcp install`");const d=Fa(e,"schemaVersion");M(o,i.schemaVersion===1?"pass":"warn",d==="lensmcp.json"?"lensmcp config in lensmcp.json":"lensmcp config block in nx.json",i.schemaVersion===1?void 0:"missing",i.schemaVersion===1?void 0:"run `lensmcp install` to write the config defaults")}h(Ys,"di"),l(Ys,"checkWorkspace");function Xs(e,o){const t=k(e,".mcp.json");if(!S(t)){M(o,"warn",".mcp.json with a lensmcp server","missing","run `lensmcp install` so agents auto-discover the MCP server");return}try{const s=JSON.parse(U(t,"utf8")),n=!!s.mcpServers&&!!s.mcpServers.lensmcp;M(o,n?"pass":"warn",".mcp.json registers the lensmcp MCP server",n?void 0:"no lensmcp entry",n?void 0:"run `lensmcp install`")}catch(s){M(o,"warn",".mcp.json parses",s.message,"fix the JSON syntax in .mcp.json")}}h(Xs,"li"),l(Xs,"checkMcpConfig");function Qs(e,o,t){const s=pe(k(e,".claude","settings.json")),n=pe(k(e,".claude","settings.local.json")),r=Yt({cwd:e}),i=r?pe(k(r.root,"plugin",".mcp.json")):void 0,a=Rt(i),d=qt(),c=It(s,de)||It(n,de)||d.some(p=>p.scope==="user"||p.projectPath===e),u=ro({workspaceServers:Rt(pe(k(e,".mcp.json"))),pluginServers:a,pluginEnabled:c,pluginReadable:i!==void 0,disabledServers:[...At(s),...At(n)],mcpMode:ae(e,o).mode});M(t,u.duplicated||u.indeterminate?"warn":"pass","the MCP server is registered exactly once",u.duplicated||u.indeterminate?u.detail:void 0,u.duplicated||u.indeterminate?u.hint:void 0)}h(Qs,"pi"),l(Qs,"checkDuplicateRegistration");function Ie(){const e=I("GET","/status");if(!e||e.status!==200)return;const o=e.json?.daemon,t=e.json?.workspaces;if(!(!o?.wsKey||!Array.isArray(t)))return t.find(s=>s.key===o.wsKey)?.root}h(Ie,"Ke"),l(Ie,"daemonOwnerRoot");function pe(e){try{return JSON.parse(U(e,"utf8"))}catch{return}}h(pe,"ge"),l(pe,"readJsonFile");async function Zs(e,o,t){$o(e)&&!jo(e,"mcp-pin-default")&&M(t,"info","MCP mode pin",yo);const s=ae(e,o),n=Dt[s.source];if(M(t,"pass","MCP mode",s.mode==="shared"?`shared (${n}) \u2014 sessions proxy into ${s.url}`:`embedded (${n}) \u2014 one MCP server per agent session; ${Ne(s)}`,Ne(s)),s.mode!=="shared")return;const r=await Bt(s.url);if(r.ok){M(t,"pass","shared MCP server",`${r.server??"MCP"} @ ${s.url} (protocol ${r.protocolVersion??"?"})`);return}if(r.remedy){M(t,"warn","shared MCP server",`not usable at ${s.url} \u2014 ${r.error??"refused"}`,r.remedy);return}const i=ho(e);if(i.length===0){M(t,"info","shared MCP server",`not running at ${s.url} \u2014 no agent session is open on this workspace; the next one starts it`,"`lensmcp gateway start` starts it now");return}const a=`${i.length} agent session${i.length===1?" is":"s are"} open (pid ${i.join(", ")})`;M(t,"warn","shared MCP server",`not running at ${s.url} \u2014 ${r.error??"no answer"}, yet ${a}`,"each is on an embedded fallback or restarts the server on its next call \u2014 its stderr names why it could not attach; `lensmcp gateway start` starts it now")}h(Zs,"ui"),l(Zs,"checkMcpMode");function ct(e,o){const t=ae(e,o);if(t.mode!=="shared")return{mode:t.mode,url:t.url,port:t.port,healthy:!1};const s=Co(t.url);return{mode:t.mode,url:t.url,port:t.port,healthy:s.ok,...s.server?{server:s.server}:{},...s.error?{error:s.error}:{},...s.remedy?{remedy:s.remedy}:{}}}h(ct,"zt"),l(ct,"mcpStatusBlock");function en(e,o){const t=yt(e);M(o,t?"pass":"fail","lensmcp-mcp server bundle reachable",t??"missing",t?void 0:`dev: \`yarn nx build ${jr}\``)}h(en,"hi"),l(en,"checkServerBundle");const Ja=3e4;function tn(e,o,t){try{const s=O(e,"migrations.js");if(!s)return;const n=lt(e),r=he(s,["status","--root",n,"--json"],n,o,Ja),i=r.code===0?ra(r.stdout):void 0,a=i?So(i,me(n)??B()):void 0;a&&M(t,a.status,a.label,a.detail,a.hint)}catch{}}h(tn,"mi"),l(tn,"checkUpgradeMigrations");function sn(e,o){const t=k(e,".lensmcp");M(o,S(t)?"pass":"warn",".lensmcp/ runtime directory",S(t)?void 0:"not created yet",S(t)?void 0:"created automatically on first `lensmcp mcp` run");const s=er(e);M(o,s.runtimeIgnored?"pass":"warn",".gitignore keeps .lensmcp/ runtime state out of git",s.runtimeIgnored?void 0:"not ignored \u2014 events, logs and tokens could be committed",s.runtimeIgnored?void 0:"add `**/.lensmcp/*` to .gitignore (lensmcp install does this)"),M(o,s.sharedIgnored.length?"warn":"pass",`.gitignore keeps the team's .lensmcp folders (${Zo.map(n=>`${n}/`).join(", ")})`,s.sharedIgnored.length?`${s.by} ignores ${s.sharedIgnored.map(n=>`.lensmcp/${n}/`).join(", ")} \u2014 ${s.sharedIgnored.every(n=>n==="team/skills")?"the project's own skills":"the analyzer instructions"} in it would not reach the team`:void 0,s.sharedIgnored.length&&s.sharedIgnored.every(n=>n==="team/skills")?"a line of this .gitignore keeps a skill's files out (`git check-ignore -v .lensmcp/team/skills/a-skill/sources.json` names it) \u2014 take it out, or add `!**/.lensmcp/team/skills/**` after it":s.sharedIgnored.length?"ignore `**/.lensmcp/*` instead of `.lensmcp/` and add `!**/.lensmcp/<folder>/` for each \u2014 lensmcp install rewrites it":void 0)}h(sn,"gi"),l(sn,"checkRuntimeDir");function nn(e,o){if(ds(e)){M(o,"pass","lens mode: lensmcp.json declares the services \u2014 they start instrumented from this machine's lensmcp, with no Vite or Nest wiring and no agent-dev targets");return}const t=ce(e,d=>/^vite\.config\.[cm]?[jt]s$/.test(d)),s=t.filter(d=>/lensmcpVitePlugin|@lensmcp\/vite-plugin/.test(ee(d)));if(t.length>0){const d=s.length===t.length;M(o,d?"pass":"warn",`Vite wiring: ${s.length}/${t.length} config(s) use the LensMCP plugin`,void 0,d?void 0:"wire each: `nx g @lensmcp/nx-plugin:setup-vite <project>`")}const n=ce(e,d=>d==="main.ts").filter(d=>/NestFactory\.create|createLensmcpNestApp/.test(ee(d))),r=n.filter(d=>/createLensmcpNestApp/.test(ee(d)));if(n.length>0){const d=r.length===n.length;M(o,d?"pass":"warn",`Nest wiring: ${r.length}/${n.length} bootstrap(s) use createLensmcpNestApp`,void 0,d?void 0:"wire each: `nx g @lensmcp/nx-plugin:setup-nest <project>`")}const i=ce(e,d=>d==="project.json"||d==="package.json").map(d=>ee(d)),a=i.filter(d=>/"agent-dev"/.test(d));i.some(d=>/@lensmcp\/cluster:gateway/.test(d))?M(o,"pass","dev lifecycle: cluster gateway owns it (agent-dev not required)",a.length>0?`${a.length} project(s) ALSO declare agent-dev \u2014 that races the gateway`:void 0,a.length>0?"remove agent-dev from gateway-managed projects; the gateway already serves them":void 0):M(o,a.length>0?"pass":"warn",`agent-dev targets: ${a.length} project(s)`,void 0,a.length>0?void 0:"no project wired \u2014 run setup-vite / setup-nest")}h(nn,"wi"),l(nn,"checkProjectWiring");const on=3e4;function rn(e,o,t){const s=O(o,"project.js");if(!s)return;const n=L(process.execPath,[s,"--doctor","--cwd",o],{cwd:o,env:{...process.env,...e.env},encoding:"utf8",timeout:on,maxBuffer:8*1024*1024});let r;try{r=JSON.parse(n.stdout)}catch{M(t,"warn","Features","could not be read",(n.stderr||n.error?.message||"").trim().split(`
|
|
1006
|
-
`)[0]||"run `lensmcp project` to see why");return}const i=r.waiting.length?` \xB7 ${r.waiting.length} waiting for the app to run`:"";M(t,"pass","Features",`${r.on} on, ${r.ready} ready${i}${r.file.exists?" (lensmcp.json)":" (no lensmcp.json \u2014 everything on)"}`);for(const a of r.file.problems)M(t,"warn","lensmcp.json",a,"fix it, then run `lensmcp project`");for(const a of r.setup){const d=a.missing[0],c=a.area==="platform"?"":` \u2014 or turn it off in lensmcp.json ("${a.area}": { "${a.id}": false })`,u=a.missing.length>1?` \xB7 \`lensmcp project ${a.id}\` for the rest`:"";M(t,"warn",`${a.title} (${a.id}) needs setup`,d?`${d.title}: ${d.saw}`:void 0,`${d?.fix.replace(/\.$/,"")||`lensmcp project ${a.id}`}${c}${u}`)}return r}h(
|
|
1007
|
-
${b}`).join("")}`);break}}return{exitCode:w?1:0}}h(
|
|
1004
|
+
For dev: \`yarn nx build @lensmcp/static-checks\`.`),{exitCode:2})}h(Is,"Kr"),l(Is,"runTypecheck");function rt(e,o,t,s){const n=_(o,{string:["--cwd","--register-host-config"],boolean:["--skip-format","--yes"]}),r=P($(n.flags["--cwd"])??e.cwd);if(!S(k(r,"nx.json")))return s(`No nx.json found at ${r}.`),s("Run `lensmcp install` from inside a Nx workspace."),{exitCode:1};const i=xe(r);if(!i)return s("Could not find the `nx` binary in the host workspace. Install Nx first: `yarn add -D nx`."),{exitCode:1};const a=["g","@lensmcp/nx-plugin:init","--no-interactive"];return n.flags["--skip-format"]===!0&&a.push("--skipFormat"),n.flags["--register-host-config"]&&a.push(`--registerHostConfig=${String(n.flags["--register-host-config"])}`),t(`> ${i} ${a.join(" ")}`),{exitCode:L(i,a,{cwd:r,stdio:"inherit",env:{...process.env,...e.env??{}}}).status??1}}h(rt,"Ht"),l(rt,"runInstall");function at(e,o,t,s){const n=_(o,{string:["--cwd","--project","--target"]}),r=P($(n.flags["--cwd"])??e.cwd),i=fe(r);if(i)return s(`trust: ${i}`),{exitCode:1};const a=S(k(r,"lensmcp.json"));if(!S(k(r,"nx.json"))&&!a)return s(`No nx.json or lensmcp.json found at ${r}.`),s("Run `lensmcp trust` from inside a Nx workspace (after `lensmcp install`), or a project lensmcp.json declares."),{exitCode:1};const d=S(k(r,"nx.json"))?xe(r):void 0,c=Ca(F(),ja);if(!d&&!(a&&c))return s("Could not find the `nx` binary in the workspace. Install Nx first: `yarn add -D nx`."),{exitCode:1};const u=Qo(r,$(n.flags["--project"]),$(n.flags["--target"])),p=I("GET","/list"),g=p?.status===200&&J(r)===void 0,m=!!c&&a&&(!d||!u);if(!u&&!m){if(s("This workspace has no trust target \u2014 no project declares the `@lensmcp/cluster:trust` executor."),s(""),g){const b=vs();s(` A shared gateway daemon${b?` (owned by '${b}')`:""} already serves this workspace, and`),s(" TLS rides ITS certificate authority. Run `lensmcp trust` in THAT workspace \u2014 it owns the CA \u2014"),s(" and this workspace is trusted too (restart the browser once if it cached a cert error).")}else s(" \u2022 Should this workspace own its gateway (and its CA)? Scaffold it first: `lensmcp install`,"),s(" then re-run `lensmcp trust`."),s(" \u2022 Joining a shared gateway? Run `lensmcp trust` in the workspace that owns the daemon.");return s(" \u2022 Already have a differently-named target? `lensmcp trust --project <p> --target <t>`."),{exitCode:1}}Se()||t(" note: trust runs `sudo` for the CA + /etc/hosts \u2014 run it in a real terminal if a step is needed."),g&&(t(" a shared gateway daemon serves this workspace \u2014 TLS rides ITS (already-trusted) CA, not a separate"),t(" one here. Setting up /etc/hosts only (trusting the CA is the DAEMON workspace's job)."));const w=`sudo asks only if ${g?"/etc/hosts is missing a host":"the CA is not trusted yet or /etc/hosts is missing a host"}`,[f,y]=m?[process.execPath,[c,"--root",r,...u?["--project",u.project,"--target",u.target]:[]]]:[d,["run",`${u.project}:${u.target}`]];t(m?`> lensmcp trust: ${u?`${u.project}:${u.target}`:"lensmcp.json's services"}, without nx (${w})`:`> ${d} run ${u.project}:${u.target} (${w})`);const v=L(f,[...y],{cwd:r,stdio:"inherit",env:{...process.env,...e.env??{},...g?{LENSMCP_TRUST_HOSTS_ONLY:"1"}:{}}});if(g&&v.status===0){const b=xs(r);if(b){const x=$s(b);t(""),x==="trusted"?t(` \u2713 ${b} \u2192 served by the daemon with a TRUSTED cert \u2014 you're set (restart the browser once if it cached an error).`):x==="untrusted"&&!(p?.json?.workspaces??[]).some(E=>E.key===G(r).key)?t(` ? ${b} \u2192 not on the daemon's cert yet \u2014 a workspace's hosts join it when the workspace registers (\`lensmcp gateway start\`, or setup's next step). Still refused after that? Run \`lensmcp trust\` in the DAEMON workspace.`):t(x==="untrusted"?` \u2717 ${b} \u2192 the daemon's cert is NOT trusted yet. Run \`lensmcp trust\` in the DAEMON workspace (it owns the CA), then restart your browser.`:` ? ${b} \u2192 couldn't reach it to verify (is the daemon running?). /etc/hosts is set; TLS rides the daemon's CA.`)}}return{exitCode:v.status??1}}h(at,"Wt"),l(at,"runTrust");function it(e){const o=he(e)??B(),t=ro(ee(k(e,".lensmcp","config.json")));return{version:o,...t?{configHash:t}:{}}}h(it,"Kt"),l(it,"currentRecycleStamp");function ct(e){const o=ue(k(e,".lensmcp","setup-state.json"))?.recycled;return o&&typeof o=="object"?o:void 0}h(ct,"qt"),l(ct,"readRecycleStamp");function Os(e,o){je(e);const t={version:B(),completedAt:new Date().toISOString(),steps:{install:!0,trust:!0},recycled:o?it(e):ct(e)??{}};try{ne(k(e,".lensmcp","setup-state.json"),`${JSON.stringify(t,null,2)}
|
|
1005
|
+
`)}catch{}}h(Os,"qr"),l(Os,"writeSetupState");async function _s(e,o,t,s){const n=ae(e,t),r=o?{mode:o.mode,source:"flag"}:n,i=r.mode;if(s(""),s(`[mcp] mode \u2192 ${i} (${Bt[r.source]})`),o?.wrote&&s(` wrote ${Co}`),i==="embedded"){s(" every agent session builds its OWN MCP server, and keeps serving"),s(" the bundle it started with until that session exits."),s(` ${Pe(r)}`);return}s(` sessions proxy into ONE shared server at ${n.url}`),s(" .mcp.json is unchanged \u2014 `lensmcp mcp` is a thin stdio shim into it."),s(` ${Pe(r)}`);const a=await Vt(n.url);if(!a.ok&&!a.remedy){s(` \xB7 not up yet (${a.error??"unknown"}) \u2014 the next session starts it on demand`);return}a.ok||s(` ! refused: ${a.error}`);const d=he(e)??B(),c=Ge({identity:Ke(n.port),targetVersion:d,expectedRoot:Oe(e),expectedKey:oe(e).key,port:n.port,selfPid:process.pid});if(!c.kill){s(a.ok?` \u2713 already up \u2014 ${a.server??"MCP"} (protocol ${a.protocolVersion??"?"}) \u2014 ${c.reason}`:` ! not restarted (${c.reason}) \u2014 ${a.remedy}`);return}try{process.kill(c.pid,"SIGTERM"),s(` \u21BA restarted the shared server \u2014 it was ${c.reason}; the next session brings it up on ${d}`)}catch(u){s(` ! the shared server is ${c.reason} and could not be stopped (pid ${c.pid}): ${u.message}`)}}h(_s,"Jr"),l(_s,"applyMcpModeStep");function Ds(e,o,t){const s=zt({cwd:e,cliVersion:B()}),n=Pr({run:Mr(o),facts:s,installed:l(()=>Je(e)?.version,"installed")});if(!(n.outcome==="current"||n.outcome==="unknown")){if(t(""),n.outcome==="ahead"){t(`[plugin] ${n.from} \u2014 newer than this workspace's lensmcp ${n.to}; another workspace's lensmcp installed it, and it stays.`),t(" `lensmcp upgrade` brings this workspace up to it.");return}if(n.outcome==="updated"){t(`[plugin] ${n.from} \u2192 ${n.to}`),t(" restart Claude Code for the new plugin to load.");return}t(`[plugin] the Claude Code plugin is ${n.from}, this lensmcp is ${n.to}.`),t(` could not update it automatically (${n.detail??"unknown reason"}). Run:`);for(const r of n.commands??[])t(` ${r}`);t(" \u2026then restart Claude Code.")}}h(Ds,"zr"),l(Ds,"applyPluginSyncStep");const Ka=5*6e4;function Bs(e,o,t){try{const s=B(),n=No({env:o,holder:rs(Qe(o)),alive:os,instance:re(G(e)),to:s});if(!n.run){n.line&&(t(""),t(n.line));return}t("");const r=O(e,"migrations.js");if(!r){t(Lo);return}const i=k(F(),"bin.js"),a=Ae(e),d=Mo({root:e,to:s,journalExists:S(ss(e)),...a?{setupBefore:a}:{},...S(i)?{cliBin:i}:{}}),c=pe(r,d,e,o,Ka);for(const u of Po({root:e,to:s,...c}))t(u)}catch(s){t(`[migrations] could not run (${s instanceof Error?s.message:String(s)}) \u2014 setup goes on`)}}h(Bs,"Xr"),l(Bs,"runSetupMigrations");function Vs(e,o,t){const s=Zn(e,he(e)??B());for(const n of o?[JSON.stringify(s,null,2)]:Qn(s))t(n);return{exitCode:0}}h(Vs,"Qr"),l(Vs,"runSetupStatus");async function Fs(e,o,t,s){const n=_(o,{string:[...Tt.string],boolean:[...Tt.boolean]}),r=P($(n.flags["--cwd"])??e.cwd),i={...e,cwd:r},a=Xn(n.flags,n.positional);if(a)return s(a),s(Fe(de,"setup")??"Usage: lensmcp setup [flags] | lensmcp setup status"),{exitCode:2};if(n.positional[0]==="status")return Vs(r,n.flags["--json"]===!0,t);const d=fe(r);if(d)return s(`setup: ${d}`),{exitCode:1};const c=$(n.flags["--mcp"]);if(c!==void 0&&!Dt(c))return s(`setup: --mcp must be "embedded" or "shared" (got "${c}").`),{exitCode:1};t("lensmcp setup \u2014 first-time bootstrap (install \u2192 trust \u2192 pods)"),t("");const u=ls(r);t(u?"[1/3] install \u2014 skipped: lensmcp.json declares this project and nothing of LensMCP is in it; its services start instrumented from this machine's lensmcp":"[1/3] install \u2014 plugin, .mcp.json, nx config, vite/nest wiring");const p=u?{exitCode:0}:rt(i,o,t,s);if(p.exitCode!==0)return s(""),s("setup: the install step failed \u2014 fix the above and re-run `lensmcp setup`."),p;t(""),t("[2/3] trust \u2014 dev CA \u2192 System keychain, /etc/hosts, DNS flush (sudo, only for what is missing)");const g=at(i,o,t,s);if(g.exitCode!==0)return s(""),s("setup: the trust step failed \u2014 run `lensmcp setup` directly in a terminal so sudo can prompt."),g;t(""),t("[3/3] pods \u2014 recycle this workspace's devservers, reconcile the gateway");const m=oe(r),w=m.key,f=oo({previous:ct(r),current:it(r),disabled:n.flags["--no-recycle"]===!0}),y=f.recycle?Nn(r,Ee(m),t,f.reason):(t(` \xB7 pods left running \u2014 ${f.reason}`),{killed:0,stale:0});Ln(i,r,w,t);const v=Dt(c)?jo(r,c):void 0;Bs(r,{...process.env,...e.env??{}},t),await _s(r,v,e.env??process.env,t);try{Ds(r,{...process.env,...e.env??{}},t)}catch{}return Os(r,f.recycle),t(""),t("\u2713 setup complete."),(y.killed>0||y.stale>0)&&t(` recycled ${y.killed} pod${y.killed===1?"":"s"}`+(y.stale>0?` (+${y.stale} stale socket${y.stale===1?"":"s"} cleared)`:"")+" \u2014 they come back on the new wiring."),t(" next: lensmcp gateway start (the :443 front door \u2014 needs sudo)"),t(" verify: lensmcp doctor"),{exitCode:0}}h(Fs,"Zr"),l(Fs,"runSetup");const Gs=64*1024*1024,Us=3e4,Wa=10*6e4;async function Hs(e,o,t,s){if(o[0]==="archive")return Ks(e,o.slice(1),s);const n=o[0]==="hook";if(o[0]!=="asked"&&!n){const i=O(e.cwd,"coordination.js");if(!i)return s(V("agent coordination entry","coordination.js")),{exitCode:1};const a=qn(o)?U(0,"utf8"):void 0,d=o.some(g=>g==="--cwd"||g.startsWith("--cwd=")),c=o[0]==="skill"?Wa:Us,u=L(process.execPath,[i,...o,...d?[]:["--cwd",e.cwd]],{cwd:e.cwd,env:{...process.env,...e.env},encoding:"utf8",timeout:c,maxBuffer:Gs,...a!==void 0?{input:a}:{}}),p=u.error?.code;return p==="ENOBUFS"||p==="ETIMEDOUT"?(s(p==="ENOBUFS"?`lensmcp agent ${o[0]??""}: the answer is over ${Gs/(1024*1024)} MB \u2014 nothing was printed. Narrow it (agent tasks --state / --role / --parent) or read the board on the Team page.`:o[0]==="skill"?`lensmcp agent skill: no answer in ${c/6e4} minutes \u2014 nothing was printed. A draft it started is kept: lensmcp agent skill list names it, and Team \u203A Skills shows its run.`:`lensmcp agent ${o[0]??""}: no answer in ${Us/1e3} s \u2014 nothing was printed (the coordination store may be busy; try again).`),{exitCode:1}):(u.stdout&&t(u.stdout.trimEnd()),u.stderr&&s(u.stderr.trimEnd()),{exitCode:u.status??1})}const r=await new Promise(i=>{if(process.stdin.isTTY){i("");return}let a="";const d=l(()=>{clearTimeout(u),process.stdin.removeListener("data",c),process.stdin.removeListener("end",d),process.stdin.removeListener("error",d),process.stdin.pause(),i(a)},"finish"),c=l(p=>{a+=p,a.length>1e6&&d()},"data"),u=setTimeout(d,n?300:2e3);process.stdin.setEncoding("utf8"),process.stdin.on("data",c),process.stdin.on("end",d),process.stdin.on("error",d)});if(n){const i=O(e.cwd,"coordination.js");if(!i||r.length>1e6)return{exitCode:0};const a={...process.env,...e.env},d=o.includes("SessionStart")&&a.LENSMCP_LAUNCH_ID||void 0,c=L(process.execPath,[i,...o,"--cwd",e.cwd],{cwd:e.cwd,env:a,input:r,encoding:"utf8",timeout:d?qa:2200,maxBuffer:64e3,stdio:["pipe","pipe","pipe"]});return c.status===0&&c.stdout?t(c.stdout.trimEnd()):d&&t(launchedStartMissed(d)),{exitCode:0}}return fo(r,{env:{...process.env,...e.env??{}},cwd:e.cwd}),{exitCode:0}}h(Hs,"ti"),l(Hs,"runAgent");const qa=4e3;export function launchedStartMissed(e){return`LensMCP's start hook did not finish, so no credential reached you. If this conversation already holds a LensMCP credential (you are a resumed worker), call agent_session { action: "resume", credential: <the newest one you hold>, launch: "${e.slice(0,80)}" } before any other LensMCP call; otherwise agent_join as your brief says.`}h(launchedStartMissed,"launchedStartMissed"),l(launchedStartMissed,"launchedStartMissed");function Ks(e,o,t){const s=o[0];if(!s||o.length>1||s.startsWith("-"))return t("Usage: lensmcp agent archive <taskId> \u2014 writes the task's archive (its events, run review, performance, flows, AI calls and test runs) into ~/.lensmcp/team-archive/<workspace>/<goal>/"),{exitCode:2};const n=O(e.cwd,"goal-archive.js");if(!n)return t(V("goal archive writer","goal-archive.js")),{exitCode:1};const r=L(process.execPath,[n,"--goal",s,"--root",e.cwd],{cwd:e.cwd,env:{...process.env,...e.env},stdio:"inherit"});return r.error?(t(`lensmcp agent archive: ${r.error.message}`),{exitCode:1}):{exitCode:r.status??1}}h(Ks,"si"),l(Ks,"runAgentArchive");async function Ws(e,o,t){const s=_(o,{string:["--cwd","--hook","--timeout","--session"],boolean:["--json","--quiet"]}),n=P($(s.flags["--cwd"])??e.cwd),r=$(s.flags["--hook"]),i=Ht(r)?r:void 0,a=$(s.flags["--session"]);if(r!==void 0&&i===void 0)return{exitCode:0};if(r!==void 0&&yo(n,"lens"))return{exitCode:0};const d=s.flags["--json"]===!0,c=s.flags["--quiet"]===!0||r!==void 0,u=Number($(s.flags["--timeout"])??""),p=Number.isFinite(u)&&u>0?u:Bo,g={...process.env,...e.env??{}};try{const m=await Vo({cwd:n,env:g,budgetMs:p,verify:l(y=>Ro(y).map(v=>v.resource),"verify")});if(!m.available)return d&&!c?t(JSON.stringify({available:!1,workspace:m.source.workspace,mode:m.source.mode,reason:m.reason,elapsedMs:m.elapsedMs})):c||t(`lensmcp status \u2014 ${m.source.workspace}: unavailable (${m.reason})`),{exitCode:0};const w=Do(m.status,m.evidence,Date.now()),f=_o(w,{workspace:m.source.workspace,includeUnmonitored:i==="SessionStart"||!c});if(d)return c&&f===void 0?{exitCode:0}:(t(JSON.stringify({available:!0,workspace:m.source.workspace,mode:m.source.mode,url:m.source.url,aggregate:m.status.status??"unknown",elapsedMs:m.elapsedMs,findings:w.findings,suppressed:w.suppressed,unmonitored:w.unmonitored})),{exitCode:0});if(i){const y=Oo(w.findings);return vo(a,y)?(f!==void 0&&t(Ut(i,f)),a&&wo(a,y),{exitCode:0}):{exitCode:0}}if(c)return f!==void 0&&t(f),{exitCode:0};if(t(`lensmcp status \u2014 ${m.source.workspace} (${m.source.mode}, ${m.source.url})`),t(` aggregate says: ${m.status.status??"unknown"} (read in ${m.elapsedMs}ms)`),w.findings.length===0)t(" nothing actionable that this command can vouch for.");else for(const y of w.findings)t(` \u2022 ${Io(y)}`);for(const y of w.suppressed)t(` \xB7 not reported \u2014 ${y.kind}: ${y.reason}`);return w.unmonitored.length>0&&t(` \xB7 unmonitored (unknown, NOT clean): ${w.unmonitored.join(", ")}`),{exitCode:0}}catch(m){return c||t(`lensmcp status: unavailable (${m instanceof Error?m.message:String(m)})`),{exitCode:0}}}h(Ws,"oi"),l(Ws,"runStatus");function qs(e,o,t){const s=_(o,{string:["--cwd","--hook","--plugin-root"],boolean:["--json","--quiet"]}),n=P($(s.flags["--cwd"])??e.cwd),r=$(s.flags["--hook"]),i=Ht(r)?r:void 0;if(r!==void 0&&i===void 0)return{exitCode:0};const a=s.flags["--json"]===!0,d=s.flags["--quiet"]===!0||r!==void 0,c=$(s.flags["--plugin-root"]);try{const u=zt({cwd:n,cliVersion:B(),...c?{pluginRoot:c}:{}}),p=Er(u);if(a)return d&&!p?{exitCode:0}:(t(JSON.stringify({...u,skew:p??null})),{exitCode:0});if(i)return p&&t(Ut(i,qt(p))),{exitCode:0};if(d)return p&&t(qt(p)),{exitCode:0};if(t(`lensmcp version-check \u2014 ${u.pluginId??"lensmcp plugin"}`),t(` plugin ${u.plugin??"unknown"}${u.pluginSource?` (${u.pluginSource})`:""}`),t(` project ${u.project??"unknown"} (node_modules/lensmcp)`),t(` cli ${u.cli??"unknown"} (the binary running now)`),!p)return t(u.plugin&&(u.project??u.cli)?" \u2713 in step.":" ? cannot compare \u2014 one of the versions is unreadable (staying silent)."),{exitCode:0};t(` \u2717 the plugin is ${p.direction} \u2014 update it, then restart Claude Code:`);for(const g of Nr(p))t(` ${g}`);return{exitCode:0}}catch(u){return d||t(`lensmcp version-check: unavailable (${u instanceof Error?u.message:String(u)})`),{exitCode:0}}}h(qs,"ri"),l(qs,"runVersionCheck");async function Js(e,o,t){const s=_(o,{string:["--cwd"],boolean:["--json"]}),n=P($(s.flags["--cwd"])??e.cwd),r=s.flags["--json"]===!0,i=[];Ys(i),Xs(n,i),Qs(n,i),Zs(n,e.env??process.env,i),await en(n,e.env??process.env,i),tn(n,i),sn(n,{...process.env,...e.env??{}},i),zs({...process.env,...e.env??{}},i),nn(n,i),on(n,i);const a=an(e,n,i);!a||a.needs.includes("chrome")?dn(i):M(i,"info","Chrome for browser:// capture","no feature that is on needs it"),await On(n,i),await _n(n,e.env??process.env,i);const d=i.some(u=>u.status==="fail"),c=i.some(u=>u.status==="warn");if(r)return t(JSON.stringify({ok:!d,summary:{total:i.length,failed:i.filter(u=>u.status==="fail").length,warnings:i.filter(u=>u.status==="warn").length},checks:i},null,2)),{exitCode:d?1:0};for(const u of i){const p=u.status==="pass"?"\u2713":u.status==="info"?"\xB7":u.status==="warn"?"!":"\u2717";t(`${p} ${u.label}${u.detail?` \u2014 ${u.detail}`:""}`),u.status!=="pass"&&u.hint&&t(` \u21B3 ${u.hint}`)}return t(""),t(d?"doctor: issues found (see \u2717 above).":c?"doctor: ok, with warnings (!).":"doctor: all checks passed."),{exitCode:d?1:0}}h(Js,"ii"),l(Js,"runDoctor");function zs(e,o){if(e.LENSMCP_NO_STORE==="1")return;const t=ye({env:e}),s=Re(t);if(!s)return;const n=z().version;ds(n,s)?M(o,"warn",`LensMCP store: ${s} is current`,`the running lens runs ${n}`,`it keeps ${n} until it restarts: lensmcp restart`):M(o,"pass",`LensMCP store: ${s} is current`,n?"the running lens runs it":"no lens runs now")}h(zs,"ai"),l(zs,"checkStore");function M(e,o,t,s,n){e.push({status:o,label:t,detail:s,hint:n})}h(M,"M"),l(M,"add");function Ys(e){const o=Number(process.versions.node.split(".")[0]);o>=20?M(e,"pass",`Node ${process.versions.node}`):o>=18?M(e,"warn",`Node ${process.versions.node}`,"older than recommended","upgrade to Node 20+ for best results"):M(e,"fail",`Node ${process.versions.node}`,"too old","LensMCP needs Node 18+ (20+ recommended)")}h(Ys,"ci"),l(Ys,"checkNode");function Xs(e,o){const t=fe(e);t&&M(o,"fail","lensmcp.json parses",t,"fix the JSON in lensmcp.json, or remove it");const s=k(e,"nx.json");if(!S(s)){M(o,"fail","nx.json at workspace root","missing","run `lensmcp` from inside a Nx workspace");return}let n;try{n=JSON.parse(U(s,"utf8"))}catch(c){M(o,"fail","nx.json parses",c.message,"fix the JSON syntax in nx.json");return}const r=(n.plugins??[]).some(c=>typeof c=="string"?c==="@lensmcp/nx-plugin":!!c&&typeof c=="object"&&c.plugin==="@lensmcp/nx-plugin"),i=Va(e),a=!r&&S(k(e,"lensmcp.json"))&&!t;M(o,r||a?"pass":"fail",a?"lensmcp.json declares this project (no @lensmcp/nx-plugin needed)":"@lensmcp/nx-plugin registered in nx.json#plugins",r||a?void 0:"not registered",r||a?void 0:"run `lensmcp install`");const d=Fa(e,"schemaVersion");M(o,i.schemaVersion===1?"pass":"warn",d==="lensmcp.json"?"lensmcp config in lensmcp.json":"lensmcp config block in nx.json",i.schemaVersion===1?void 0:"missing",i.schemaVersion===1?void 0:"run `lensmcp install` to write the config defaults")}h(Xs,"di"),l(Xs,"checkWorkspace");function Qs(e,o){const t=k(e,".mcp.json");if(!S(t)){M(o,"warn",".mcp.json with a lensmcp server","missing","run `lensmcp install` so agents auto-discover the MCP server");return}try{const s=JSON.parse(U(t,"utf8")),n=!!s.mcpServers&&!!s.mcpServers.lensmcp;M(o,n?"pass":"warn",".mcp.json registers the lensmcp MCP server",n?void 0:"no lensmcp entry",n?void 0:"run `lensmcp install`")}catch(s){M(o,"warn",".mcp.json parses",s.message,"fix the JSON syntax in .mcp.json")}}h(Qs,"li"),l(Qs,"checkMcpConfig");function Zs(e,o,t){const s=ue(k(e,".claude","settings.json")),n=ue(k(e,".claude","settings.local.json")),r=Qt({cwd:e}),i=r?ue(k(r.root,"plugin",".mcp.json")):void 0,a=It(i),d=Jt(),c=Ot(s,Le)||Ot(n,Le)||d.some(p=>p.scope==="user"||p.projectPath===e),u=ao({workspaceServers:It(ue(k(e,".mcp.json"))),pluginServers:a,pluginEnabled:c,pluginReadable:i!==void 0,disabledServers:[...Rt(s),...Rt(n)],mcpMode:ae(e,o).mode});M(t,u.duplicated||u.indeterminate?"warn":"pass","the MCP server is registered exactly once",u.duplicated||u.indeterminate?u.detail:void 0,u.duplicated||u.indeterminate?u.hint:void 0)}h(Zs,"pi"),l(Zs,"checkDuplicateRegistration");function Ie(){const e=I("GET","/status");if(!e||e.status!==200)return;const o=e.json?.daemon,t=e.json?.workspaces;if(!(!o?.wsKey||!Array.isArray(t)))return t.find(s=>s.key===o.wsKey)?.root}h(Ie,"qe"),l(Ie,"daemonOwnerRoot");function ue(e){try{return JSON.parse(U(e,"utf8"))}catch{return}}h(ue,"me"),l(ue,"readJsonFile");async function en(e,o,t){xo(e)&&!So(e,"mcp-pin-default")&&M(t,"info","MCP mode pin",ko);const s=ae(e,o),n=Bt[s.source];if(M(t,"pass","MCP mode",s.mode==="shared"?`shared (${n}) \u2014 sessions proxy into ${s.url}`:`embedded (${n}) \u2014 one MCP server per agent session; ${Pe(s)}`,Pe(s)),s.mode!=="shared")return;const r=await Vt(s.url);if(r.ok){M(t,"pass","shared MCP server",`${r.server??"MCP"} @ ${s.url} (protocol ${r.protocolVersion??"?"})`);return}if(r.remedy){M(t,"warn","shared MCP server",`not usable at ${s.url} \u2014 ${r.error??"refused"}`,r.remedy);return}const i=mo(e);if(i.length===0){M(t,"info","shared MCP server",`not running at ${s.url} \u2014 no agent session is open on this workspace; the next one starts it`,"`lensmcp gateway start` starts it now");return}const a=`${i.length} agent session${i.length===1?" is":"s are"} open (pid ${i.join(", ")})`;M(t,"warn","shared MCP server",`not running at ${s.url} \u2014 ${r.error??"no answer"}, yet ${a}`,"each is on an embedded fallback or restarts the server on its next call \u2014 its stderr names why it could not attach; `lensmcp gateway start` starts it now")}h(en,"ui"),l(en,"checkMcpMode");function dt(e,o){const t=ae(e,o);if(t.mode!=="shared")return{mode:t.mode,url:t.url,port:t.port,healthy:!1};const s=$o(t.url);return{mode:t.mode,url:t.url,port:t.port,healthy:s.ok,...s.server?{server:s.server}:{},...s.error?{error:s.error}:{},...s.remedy?{remedy:s.remedy}:{}}}h(dt,"Yt"),l(dt,"mcpStatusBlock");function tn(e,o){const t=kt(e);M(o,t?"pass":"fail","lensmcp-mcp server bundle reachable",t??"missing",t?void 0:`dev: \`yarn nx build ${Sr}\``)}h(tn,"hi"),l(tn,"checkServerBundle");const Ja=3e4;function sn(e,o,t){try{const s=O(e,"migrations.js");if(!s)return;const n=ut(e),r=pe(s,["status","--root",n,"--json"],n,o,Ja),i=r.code===0?ra(r.stdout):void 0,a=i?Eo(i,he(n)??B()):void 0;a&&M(t,a.status,a.label,a.detail,a.hint)}catch{}}h(sn,"mi"),l(sn,"checkUpgradeMigrations");function nn(e,o){const t=k(e,".lensmcp");M(o,S(t)?"pass":"warn",".lensmcp/ runtime directory",S(t)?void 0:"not created yet",S(t)?void 0:"created automatically on first `lensmcp mcp` run");const s=tr(e);M(o,s.runtimeIgnored?"pass":"warn",".gitignore keeps .lensmcp/ runtime state out of git",s.runtimeIgnored?void 0:"not ignored \u2014 events, logs and tokens could be committed",s.runtimeIgnored?void 0:"add `**/.lensmcp/*` to .gitignore (lensmcp install does this)"),M(o,s.sharedIgnored.length?"warn":"pass",`.gitignore keeps the team's .lensmcp folders (${er.map(n=>`${n}/`).join(", ")})`,s.sharedIgnored.length?`${s.by} ignores ${s.sharedIgnored.map(n=>`.lensmcp/${n}/`).join(", ")} \u2014 ${s.sharedIgnored.every(n=>n==="team/skills")?"the project's own skills":"the analyzer instructions"} in it would not reach the team`:void 0,s.sharedIgnored.length&&s.sharedIgnored.every(n=>n==="team/skills")?"a line of this .gitignore keeps a skill's files out (`git check-ignore -v .lensmcp/team/skills/a-skill/sources.json` names it) \u2014 take it out, or add `!**/.lensmcp/team/skills/**` after it":s.sharedIgnored.length?"ignore `**/.lensmcp/*` instead of `.lensmcp/` and add `!**/.lensmcp/<folder>/` for each \u2014 lensmcp install rewrites it":void 0)}h(nn,"gi"),l(nn,"checkRuntimeDir");function on(e,o){if(ls(e)){M(o,"pass","lens mode: lensmcp.json declares the services \u2014 they start instrumented from this machine's lensmcp, with no Vite or Nest wiring and no agent-dev targets");return}const t=ce(e,d=>/^vite\.config\.[cm]?[jt]s$/.test(d)),s=t.filter(d=>/lensmcpVitePlugin|@lensmcp\/vite-plugin/.test(ee(d)));if(t.length>0){const d=s.length===t.length;M(o,d?"pass":"warn",`Vite wiring: ${s.length}/${t.length} config(s) use the LensMCP plugin`,void 0,d?void 0:"wire each: `nx g @lensmcp/nx-plugin:setup-vite <project>`")}const n=ce(e,d=>d==="main.ts").filter(d=>/NestFactory\.create|createLensmcpNestApp/.test(ee(d))),r=n.filter(d=>/createLensmcpNestApp/.test(ee(d)));if(n.length>0){const d=r.length===n.length;M(o,d?"pass":"warn",`Nest wiring: ${r.length}/${n.length} bootstrap(s) use createLensmcpNestApp`,void 0,d?void 0:"wire each: `nx g @lensmcp/nx-plugin:setup-nest <project>`")}const i=ce(e,d=>d==="project.json"||d==="package.json").map(d=>ee(d)),a=i.filter(d=>/"agent-dev"/.test(d));i.some(d=>/@lensmcp\/cluster:gateway/.test(d))?M(o,"pass","dev lifecycle: cluster gateway owns it (agent-dev not required)",a.length>0?`${a.length} project(s) ALSO declare agent-dev \u2014 that races the gateway`:void 0,a.length>0?"remove agent-dev from gateway-managed projects; the gateway already serves them":void 0):M(o,a.length>0?"pass":"warn",`agent-dev targets: ${a.length} project(s)`,void 0,a.length>0?void 0:"no project wired \u2014 run setup-vite / setup-nest")}h(on,"wi"),l(on,"checkProjectWiring");const rn=3e4;function an(e,o,t){const s=O(o,"project.js");if(!s)return;const n=L(process.execPath,[s,"--doctor","--cwd",o],{cwd:o,env:{...process.env,...e.env},encoding:"utf8",timeout:rn,maxBuffer:8*1024*1024});let r;try{r=JSON.parse(n.stdout)}catch{M(t,"warn","Features","could not be read",(n.stderr||n.error?.message||"").trim().split(`
|
|
1006
|
+
`)[0]||"run `lensmcp project` to see why");return}const i=r.waiting.length?` \xB7 ${r.waiting.length} waiting for the app to run`:"";M(t,"pass","Features",`${r.on} on, ${r.ready} ready${i}${r.file.exists?" (lensmcp.json)":" (no lensmcp.json \u2014 everything on)"}`);for(const a of r.file.problems)M(t,"warn","lensmcp.json",a,"fix it, then run `lensmcp project`");for(const a of r.setup){const d=a.missing[0],c=a.area==="platform"?"":` \u2014 or turn it off in lensmcp.json ("${a.area}": { "${a.id}": false })`,u=a.missing.length>1?` \xB7 \`lensmcp project ${a.id}\` for the rest`:"";M(t,"warn",`${a.title} (${a.id}) needs setup`,d?`${d.title}: ${d.saw}`:void 0,`${d?.fix.replace(/\.$/,"")||`lensmcp project ${a.id}`}${c}${u}`)}return r}h(an,"yi"),l(an,"checkFeatures");function cn(e,o,t,s){const n=_(o,{string:["--cwd"],boolean:["--json"]}),r=P($(n.flags["--cwd"])??e.cwd),i=O(r,"project.js");if(!i)return s(V("project entry","project.js")),{exitCode:1};const a=L(process.execPath,[i,...n.positional.slice(0,1),...n.flags["--json"]===!0?["--json"]:[],"--cwd",r],{cwd:r,env:{...process.env,...e.env},encoding:"utf8",timeout:rn,maxBuffer:16*1024*1024});return a.error?(s(`lensmcp project: ${a.error.message}`),{exitCode:1}):(a.stdout&&t(a.stdout.trimEnd()),a.stderr&&s(a.stderr.trimEnd()),{exitCode:a.status??1})}h(cn,"ki"),l(cn,"runProject");function dn(e){const o=process.env.CHROME_PATH,t=process.platform==="darwin"?["/Applications/Google Chrome.app/Contents/MacOS/Google Chrome","/Applications/Chromium.app/Contents/MacOS/Chromium"]:process.platform==="win32"?["C:/Program Files/Google/Chrome/Application/chrome.exe","C:/Program Files (x86)/Google/Chrome/Application/chrome.exe"]:["/usr/bin/google-chrome","/usr/bin/chromium-browser","/usr/bin/chromium","/usr/bin/google-chrome-stable"],s=(o&&S(o)?o:void 0)??t.find(n=>S(n));M(e,s?"pass":"warn","Chrome for browser:// capture",s?ge(s):"not found",s?void 0:"install Chrome or set CHROME_PATH (only needed for browser capture)")}h(dn,"vi"),l(dn,"checkChrome");function ee(e){try{return U(e,"utf8")}catch{return""}}h(ee,"ee"),l(ee,"safeRead");function ln(e,o,t,s){const n=_(o,{string:["--cwd","--from","--scope"]}),r=(n.positional[0]??"").toLowerCase();if(r!=="install"&&r!=="status")return s("Usage: lensmcp plugin <install|status> [claude|codex] [--from <dir>] [--scope <user|project|local>] [--cwd <dir>]"),{exitCode:2};const i=P($(n.flags["--cwd"])??e.cwd),a=n.positional[1]?.toLowerCase(),d=a?Lr(a):void 0;if(a&&!d)return s(`Unknown agent: ${a} (use claude | codex)`),{exitCode:2};const c=d?[d]:[...Yt],u=$(n.flags["--from"]),p=Qt({cwd:i,...u?{from:u}:{},selfRoot:F()});if(!p)return s("Could not find a lensmcp package to install the plugins from."),s("Run inside a workspace with lensmcp installed, or pass --from <package-root>."),{exitCode:1};t(`plugin package: ${p.root}${p.version?` (lensmcp ${p.version})`:""}`+(p.source==="self"?" \u2014 the running CLI itself (no workspace install found; prefer a workspace)":""));const g=ze({...process.env,...e.env??{}});if(r==="status"){for(const f of c){const y=Rr(p.root,f),v=f.id==="claude"?Je(i)?.version:Tr(g),b=v?y?v===y?`installed ${v} \u2014 current`:`installed ${v}, the package ships ${y} \u2014 \`lensmcp plugin install ${f.id}\``:`installed ${v} (this package ships no ${f.label} plugin \u2014 it arrived in ${f.since})`:`not installed \u2014 \`lensmcp plugin install ${f.id}\``;t(` ${f.label.padEnd(11)} \u2192 ${b}`)}return{exitCode:0}}const m=$(n.flags["--scope"]);let w=!1;for(const f of c){const y=f.id==="claude"?m??Je(i)?.scope:void 0,v=Xt(f,{root:p.root,...y?{scope:y}:{}},{run:g});switch(v.outcome){case"installed":t(` ${f.label.padEnd(11)} \u2192 installed${v.version?` ${v.version}`:""} \u2014 ${v.restartHint}`);break;case"skipped-no-cli":d&&(w=!0),t(` ${f.label.padEnd(11)} \u2192 skipped (${v.detail})`);break;case"skipped-not-packaged":d&&(w=!0),t(` ${f.label.padEnd(11)} \u2192 skipped \u2014 ${v.detail}`);break;case"failed":w=!0,s(` ${f.label.padEnd(11)} \u2192 FAILED \u2014 ${v.detail}`),s(` run by hand:${v.commands.map(b=>`
|
|
1007
|
+
${b}`).join("")}`);break}}return{exitCode:w?1:0}}h(ln,"bi"),l(ln,"runPlugin");function z(){const e=I("GET","/status");if(e?.status!==200||!e.json||typeof e.json!="object")return{registeredKeys:[]};const o=e.json;return{...typeof o.daemon?.wsKey=="string"?{wsKey:o.daemon.wsKey}:{},...typeof o.daemon?.version=="string"?{version:o.daemon.version}:{},registeredKeys:(o.workspaces??[]).flatMap(t=>typeof t.key=="string"?[t.key]:[])}}h(z,"X"),l(z,"snapshotDaemon");function lt(e){let o=P(e);for(let t=0;t<8;t++){const s=k(o,"package.json");if(S(s)&&/"(?:lensmcp|@lensmcp\/[^"]+)"\s*:/.test(ee(s)))return{key:G(o).key,root:o};const n=D(o);if(n===o)break;o=n}}h(lt,"Qt"),l(lt,"findLensmcpWorkspace");function un(e,o,t,s=!1){if(e){const i=e.replace(/^v/,"");if(!/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/.test(i)){t(`Not a version: ${e} (expected e.g. 1.20.1)`);return}if(!s&&Fr(o("npm",["view",`lensmcp@${i}`,"version"]),i)==="absent"){const a=o("npm",["view","lensmcp","version"]),d=a&&a.code===0?(a.stdout??"").trim().split(`
|
|
1008
1008
|
`).filter(Boolean).pop():void 0;t(`lensmcp ${i} is not on the npm registry${d?` (the newest there is ${d})`:""} \u2014 nothing was changed.`),t("If it was published a moment ago, run this again in a minute. `--no-registry-check` skips the question.");return}return i}const n=o("npm",["view","lensmcp","version"]),r=n&&n.code===0?(n.stdout??"").trim().split(`
|
|
1009
|
-
`).filter(Boolean).pop():void 0;if(!r||!/^\d+\.\d+\.\d+/.test(r)){t("Could not resolve the latest lensmcp version from the npm registry \u2014 pass one explicitly: `lensmcp upgrade 1.20.1`.");return}return r}h(
|
|
1010
|
-
`).length} lines) \u2014 paste it into your coding agent.`),{exitCode:0};s("No clipboard here (pbcopy) \u2014 the prompt follows; copy it into your coding agent.")}return m.stdout&&t(m.stdout.trimEnd()),m.stderr&&s(m.stderr.trimEnd()),{exitCode:m.status??1}}h(
|
|
1011
|
-
${r.error.message}`:""}`}}h(
|
|
1012
|
-
`).filter(Boolean).pop()??"","lastLine");function ut(e,o,t,s){const n=Te(e,o),r=n?k(D(n),$r,"migrations.js"):void 0;return r&&S(r)?r:t===o?O(s,"migrations.js"):void 0}h(ut,"tn"),l(ut,"migrationsEntryFor");function pt(e,o,t){const s=O(e,"migrations.js");return n=>{if(!s)return{root:n,goals:[],launches:[],unknown:"no migrations entry to read it with"};const r=he(s,["team","--root",n,"--json"],n,o,Qa);return aa(r.stdout,n)??{root:n,goals:[],launches:[],unknown:r.code===2?`lensmcp ${t}'s migrations entry has no team read`:gn(r.stderr)||`exited ${r.code}`}}}h(pt,"nn"),l(pt,"upgradeTeamRead");function _e(e,o){return e.store?Re(e.store):vt(o)}h(_e,"Je"),l(_e,"lensInstalledFor");const ht=l((e,o)=>Ma(e,o)?Pa(La(e,o)):void 0,"storedCliFor");function De(e,o,t){return e.store?ht(e.store,t):Te(o,t)}h(De,"Ye"),l(De,"cliForUpgrade");function fn(e){let o=P(e);for(let t=0;t<8;t++){if(S(k(o,".lensmcp","config.json"))||S(k(o,"lensmcp.json")))return{key:G(o).key,root:o};const s=D(o);if(s===o)break;o=s}}h(fn,"Ni"),l(fn,"findLensWorkspace");async function mt(e,o,t,s){const n=_(o,{string:["--cwd","--from"],boolean:["--dry-run","--no-install","--no-plugins","--no-global","--no-restart","--no-registry-check","--no-setup","--yes","--resume"]}),r=P($(n.flags["--cwd"])??e.cwd),i=n.flags["--dry-run"]===!0,a={...process.env,...e.env??{}},d=a[ia]==="1",c=Number(a[zr]),u=a[Zr];for(const A of ca)delete process.env[A];const p=ss(a),g=Xt(p),m=Xe(p),w=B(),f=n.flags["--resume"]===!0,y=n.flags["--no-registry-check"]===!0||$(n.flags["--from"])!==void 0;let v,b;if(f){const A=n.positional[0]?.replace(/^v/,"");b=A?rs(m,A):Ye(m),v=b?.to??A}else{if(v=ln(n.positional[0],g,s,y),!v)return{exitCode:1};b=rs(m,v)}const x=ha({...b?{existing:b}:{},resume:f,...v?{to:v}:{},home:m});if(x.kind==="error"||!v)return s(x.kind==="error"?x.message:"lensmcp upgrade --resume: name the version to resume"),{exitCode:1};const E=i?void 0:na(u||ga(m,Date.now()),`# lensmcp upgrade ${v} \u2014 lensmcp ${w}, pid ${process.pid}, ${new Date().toISOString()}${d?" \u2014 phase 2 (the hand-off)":""}`),N=is(t,E,"out"),C=is(s,E,"err");let T;if(i){const A=os(m);A&&A!=="unreadable"&&ns(A.pid)&&N(` lock \u2192 another upgrade (pid ${A.pid}) holds ${Xr(m)} \u2014 a dry run changes nothing, so it goes on`)}else{if(T=ma(m,{pid:process.pid,now:Date.now,to:v,...d&&Number.isInteger(c)&&c>0?{inheritFrom:c}:{}}),!T.ok)return C(Qr(T)),{exitCode:1};const A=Yr(T);A&&N(A)}try{const A=x.kind==="resume"?x.run.store?.home:Oa(ke({env:p}),F(),p)?ke({env:p}):void 0,H=$(n.flags["--from"]);return await wn({ctx:e,cwd:r,dryRun:i,env:p,run:g,home:m,own:w,child:d,...d&&Number.isInteger(c)&&c>0?{parentLockPid:c}:{},version:v,given:mn(n.flags),noRegistryCheck:y,...E?{log:E}:{},out:N,err:C,...A?{store:A}:{},...H?{from:P(H)}:{}},x)}finally{T?.ok&&T.took!=="inherited"&&da(m,process.pid)}}h(mt,"sn"),l(mt,"runUpgrade");async function wn(e,o){const{version:t,out:s,err:n}=e,r=l(f=>_e(e,f),"installed"),i=l(f=>S(ts(f)),"journalExists"),a=l(f=>{e.dryRun||fa(e.home,f)},"save"),d=pt(e.cwd,e.env,e.own);let c;if(o.kind==="resume"){if(c=o.run,c.flags=ea(c.flags,e.given),e.log&&!c.logs.includes(e.log.path)&&c.logs.push(e.log.path),!e.child)for(const f of ua(c,e.home))s(f)}else{const f=Qt({home:e.home}),y=dt(e.cwd)??(e.store?fn(e.cwd):void 0),{targets:v,instances:b}=Hr(y,f,N=>re(G(N)));if(v.length===0&&b.length>0)return n(`Only worktree instances here (${b.map(N=>N.key).join(", ")}): an instance runs its own commit's lens and \`upgrade\` leaves it alone. Run it in the main checkout.`),{exitCode:1};if(v.length===0&&!e.store)return n("No LensMCP workspace found: ~/.lensmcp/workspaces.json is empty and no package.json above the current directory depends on lensmcp."),{exitCode:1};const x=Ye(e.home);x&&x.to!==t&&s(` note \u2192 an unfinished upgrade to ${x.to} (started ${x.startedAt}) is left as it is \u2014 \`lensmcp upgrade ${x.to}\` continues it`);const E=z();if(c=sa({to:t,by:e.own,cwd:e.cwd,flags:e.given,before:E,known:f,targets:v,instances:b,now:Date.now(),...e.log?{log:e.log.path}:{}}),e.store&&(c.store={home:e.store}),s(`upgrade \u2192 lensmcp ${t}${e.dryRun?" (dry run \u2014 nothing will be changed)":""}`),E.wsKey&&s(` daemon \u2192 '${E.wsKey}' on :443${E.version?`, running ${E.version}`:""}, hosting ${E.registeredKeys.length} workspace${E.registeredKeys.length===1?"":"s"}`),e.store&&s(` store \u2192 ${e.store}/versions/${t}, made current \u2014 no package.json or lockfile is touched (POSIX only: macOS, Linux)`),s(` will change \u2192 ${v.length} workspace${v.length===1?"":"s"} (${v.map(N=>N.key).join(", ")})${e.given.noInstall||e.store?"":" + install"} + the migrations${e.given.noGlobal||e.store?"":" + the global CLI"}${e.given.noPlugins?"":" + the Claude/Codex plugins"}${e.given.noRestart?"":" + the :443 daemon"}`),!e.noRegistryCheck&&!e.store){const N=Dr(v.flatMap(T=>["package.json","yarn.lock","package-lock.json","pnpm-lock.yaml"].map(A=>ee(k(T.root,A))))),C=Br(N,t,T=>e.run("npm",["view",`${T}@${t}`,"version"]));if(C.length===0&&s(` registry \u2192 all ${N.length} packages these workspaces install are published at ${t}`),C.length>0)return n(`lensmcp ${t} is not fully published yet \u2014 ${C.length} of the ${N.length} packages these workspaces install are not on the npm registry at ${t}:`),n(` ${C.join(", ")}`),n("A release publishes its packages one by one; run this again in a minute. Nothing was changed. (`--no-registry-check` skips the question.)"),{exitCode:1}}}if(e.store&&!e.child&&c.phase==="install"){const f=e.store,y=Ia({home:f,to:t,dryRun:e.dryRun,out:s,err:n,install:l(()=>Ea(f,t,{env:e.env,...e.from?{spec:e.from}:{}}),"install"),verify:l(v=>Ta(v,e.env),"verify"),use:l(()=>Na(f,t),"use")});if(!y.ok)return a(c),e.log&&s(` log \u2192 ${e.log.path}`),{exitCode:1};for(const v of c.targets){if(v.setupBefore===void 0){const b=Ae(v.root);b&&(v.setupBefore=b)}v.installedBefore===void 0&&y.previous&&(v.installedBefore=y.previous),e.dryRun?v.dryInstall=!0:v.install="installed"}c.store={home:f,...y.previous?{previous:y.previous}:c.store?.previous?{previous:c.store.previous}:{}},e.dryRun||(c.phase="finish"),a(c)}if(!e.store&&!e.child&&(o.kind==="fresh"||Jr(c,r).length>0)&&pa(c,{out:s,err:n,dryRun:e.dryRun,installed:r,packageManager:l(f=>_r(f),"packageManager"),install:l((f,y)=>L(y.name,y.install,{cwd:f,stdio:"inherit",env:e.env}).status??1,"install"),freeDisk:Kr,memory:l(()=>({free:Vn(),total:Un(),platform:process.platform}),"memory"),team:d,plan:l((f,y,v)=>{const b=ut(f.root,t,e.own,e.cwd);if(!b)return;const x=Te(f.root,t),E=he(b,ta({command:"plan",root:f.root,to:t,from:y,machine:v,...x?{cliBin:x}:{}}),f.root,e.env,hn);return oa(E.stdout)??{error:gn(E.stderr)||`exited ${E.code}`}},"plan"),journalExists:i,save:a}).refused)return e.log&&s(` log \u2192 ${e.log.path}`),{exitCode:1};if(e.dryRun)return{exitCode:(await as(c,gt(e,c,{installed:r,journalExists:i,team:d,save:a}))).exitCode};const u=c.targets.filter(f=>r(f.root)===t);if(!u.length&&!e.store){const f=c.targets.filter(v=>v.install==="skipped"),y=c.targets.some(v=>v.install==="restored"||v.install==="unreadable");return f.length&&!y?s(` finish \u2192 the install is yours (--no-install): run it in ${f.map(v=>v.root).join(", ")}, then \`lensmcp upgrade ${t}\` again \u2014 it resumes here, and lensmcp ${t} runs the migrations, the restart and setup`):n(` finish \u2192 no workspace holds lensmcp ${t}, so there is nothing to finish the upgrade with${y?" (each failed install was restored)":""}. Fix it, then run \`lensmcp upgrade ${t}\` again: it resumes here.`),a(c),e.log&&s(` log \u2192 ${e.log.path}`),{exitCode:f.length&&!y?0:1}}const p=c.before.wsKey?u.find(f=>f.key===c.before.wsKey):void 0,g=e.store?ht(e.store,t):Te((p??u[0]).root,t),m=qr({own:e.own,to:t,...g?{bin:g}:{},child:e.child});if(m.mode==="spawn"){s(` hand-off \u2192 lensmcp ${t} runs the rest of the upgrade (${m.bin} upgrade ${t} --resume)`),a(c);const f=L(process.execPath,Wr(m.bin,t,e.cwd,c.flags.yes),{cwd:e.cwd,stdio:"inherit",env:es(e.env,{lockPid:process.pid,...e.log?{log:e.log.path}:{}})});return f.error?(n(` hand-off \u2192 could not start lensmcp ${t} (${f.error.message}) \u2014 run \`lensmcp upgrade ${t}\` again: it resumes here.`),{exitCode:1}):{exitCode:f.status??1}}if(m.mode==="none")return n(` hand-off \u2192 ${m.why} \u2014 run \`lensmcp upgrade ${t}\` again once it is: it resumes here.`),a(c),{exitCode:1};e.child||s(` hand-off \u2192 ${m.why}: phase 2 runs in this process`);const w=await as(c,gt(e,c,{installed:r,journalExists:i,team:d,save:a}));return c.store?.previous&&c.store.previous!==t&&s(` ${Ra(c.store.previous)}`),{exitCode:w.exitCode}}h(wn,"Li"),l(wn,"upgradeInPhases");function gt(e,o,t){const s=e.version,n=e.own===s?O(e.cwd,"migrations.js"):o.targets.map(r=>ut(r.root,s,e.own,e.cwd)).find(r=>r!==void 0);return{out:e.out,err:e.err,dryRun:e.dryRun,tty:Ee(),own:e.own,ask:l(async r=>{const i=await ze(r);return e.log?.write(`${r} [y/N] ${i?"y":"N"}`),i},"ask"),installed:t.installed,journalExists:t.journalExists,setupVersion:Ae,...n?{migrations:l(r=>he(n,r,e.cwd,e.env,r[0]==="apply"?Xa:hn),"migrations")}:{},cliBin:l(r=>De(e,r,s),"cliBin"),team:t.team,save:t.save,...e.log?{log:e.log.path}:{},steps:{global:l(()=>e.store?(e.out(" global \u2192 the store is the machine's install: a global `lensmcp` forwards to its current version"),{state:"skipped",note:"the store"}):vn(e),"global"),plugins:l((r,i)=>yn(e,r,i),"plugins"),mcp:l((r,i)=>{for(const a of r.targets)i.includes(a)||e.out(` mcp \u2192 '${a.key}' left alone \u2014 its install did not land, so there is no ${s} bundle to restart it onto`);return un(i,s,e.dryRun,e.out),{state:"done"}},"mcp"),restart:l((r,i,a)=>kn(e,r,a),"restart"),setup:l(r=>bn(e,r),"setup"),daemon:l(r=>{const i=z();if(!i.version)return;const a=i.wsKey?r.targets.find(c=>c.key===i.wsKey)?.root:void 0,d=a?_e(e,a):void 0;return Or({reported:i.version,target:s,...d?{ownerInstalled:d}:{},...a?{ownerRoot:a}:{}})},"daemon")}}}h(gt,"on"),l(gt,"upgradePhase2Io");function vn(e){const o=Ir(e.run);return o?o.version===e.version?(e.out(` global \u2192 already ${o.version}`),{state:"done"}):e.dryRun?(e.out(` global \u2192 ${o.version} \u2192 ${e.version} (npm i -g lensmcp@${e.version})`),{state:"done"}):(e.out(` global \u2192 ${o.version} \u2192 ${e.version}`),(L("npm",["install","-g",`lensmcp@${e.version}`],{stdio:"inherit",env:e.env,timeout:3e5}).status??1)!==0?(e.err(` the global install failed \u2014 run by hand: npm i -g lensmcp@${e.version}`),{state:"failed",note:"npm i -g failed"}):{state:"done"}):{state:"done",note:"no global install"}}h(vn,"Ti"),l(vn,"upgradeGlobalStep");function yn(e,o,t){if(e.store){const r=k(Sa(e.store),"node_modules","lensmcp");return e.dryRun?(e.out(` plugins \u2192 would re-read Claude Code + Codex from ${r}`),{state:"done"}):(wt(r,e.cwd,e.env,e.out,e.err),{state:"done"})}const s=(o.before.wsKey?t.find(r=>r.key===o.before.wsKey):void 0)??t[0];if(!s)return e.out(` plugins \u2192 skipped (no workspace holds lensmcp ${e.version} to install them from)`),{state:"skipped",note:"nothing landed"};const n=k(s.root,"node_modules","lensmcp");return e.dryRun?(e.out(` plugins \u2192 would re-install Claude Code + Codex from ${n}`),{state:"done"}):(wt(n,e.cwd,e.env,e.out,e.err),{state:"done"})}h(yn,"Ri"),l(yn,"upgradePluginsStep");async function kn(e,o,t){const{version:s,out:n,err:r}=e,i=o.targets.filter(p=>p.install==="installed"||e.dryRun&&p.dryInstall===!0),a=Vr({...o.before.wsKey?{daemonWsKey:o.before.wsKey}:{},...o.before.version?{daemonVersion:o.before.version}:{},targetVersion:s,registeredKeys:o.before.registeredKeys,known:o.known,upgraded:i});if(a.steps.length===0)return n(` restart \u2192 nothing to do${a.note?` (${a.note})`:""}`),{state:"done",note:"nothing to restart"};if(!e.dryRun&&o.before.version!==s&&z().version===s)return n(` restart \u2192 the daemon already runs ${s} \u2014 nothing to restart`),{state:"done",note:"already restarted"};const d=await t();if(!d.restart)return{state:"deferred",note:d.why??"deferred"};let c,u;for(const p of a.steps){if(e.dryRun){n(` restart \u2192 would ${p.action==="restart"?`restart the daemon ('${p.key}')`:`re-register '${p.key}'`}${p.reason==="rehost"?" (not upgraded \u2014 re-hosted so the daemon restart does not drop it)":p.reason==="stale-daemon"?" (its files are current but the process still runs the old bundle)":""}`);continue}if(p.action==="restart"){const g=De(e,p.root,s);if(n(` restart \u2192 gateway daemon ('${p.key}') ${g?`with lensmcp ${s}`:`in-process (no lensmcp ${s} on disk in ${p.root})`} \u2026`),(g?Zt(g,p.root,e.env):et({...e.ctx,cwd:p.root},["restart"],n,r).exitCode)!==0){c=`the daemon restart ('${p.key}') failed`,r(` ${c} \u2014 fix it, then \`lensmcp gateway start\` in each guest workspace.`);break}if(!await ft(18e4)){c="the restarted daemon did not answer within 3 minutes",r(` ${c} \u2014 check \`lensmcp gateway status\`; guests need \`lensmcp gateway start\` once it is up.`);break}}else{if(await Ze(p.key,p.root,u??=Date.now()+15e3)){n(` restart \u2192 '${p.key}' is back \u2014 the daemon re-hosted it`);continue}const g=I("POST","/register",ue(p.root,p.key));if(g&&g.status===200){try{se(k(p.root,".lensmcp"),{recursive:!0}),ne(k(p.root,".lensmcp","registered.json"),JSON.stringify({wsKey:p.key}))}catch{}n(` restart \u2192 re-registered '${p.key}'${p.reason==="rehost"?" (not upgraded \u2014 re-hosted after the daemon restart)":""}`);const m=qe(g.json);m&&n(m)}else c=`re-registering '${p.key}' failed`,r(` ${c} \u2014 ${Le(g)??`run \`lensmcp gateway start\` in ${p.root}`}.`)}}return e.dryRun?{state:"done"}:c?{state:"failed",note:c,acted:!0}:{state:"done",acted:!0}}h(kn,"Ai"),l(kn,"upgradeRestartStep");function bn(e,o){const{version:t,out:s,err:n}=e,r=o.flags.noSetup||o.flags.noRestart;if(e.dryRun)return r||s(` setup \u2192 would run \`lensmcp setup --no-recycle\` with lensmcp ${t} in each workspace whose setup is then behind (\`--no-setup\` skips it)`),{state:"done"};let i=0;for(const a of o.targets){const d=Ae(a.root),c=_e(e,a.root),u=De(e,a.root,t),p=Gr({key:a.key,root:a.root,targetVersion:t,...d?{setupVersion:d}:{},...c?{installedVersion:c}:{},...u?{bin:u}:{},skip:r});if(p.action==="remind"&&s(p.line),p.action!=="run")continue;s(` setup \u2192 '${a.key}': lensmcp setup --no-recycle with lensmcp ${t} (the lens tools are gated until it has run) \u2026`);const g=e.child&&e.parentLockPid?e.parentLockPid:process.pid,m=Ur(p.bin,a.root,es(e.env,{lockPid:g}));m===0?s(` setup \u2192 '${a.key}' is set up for ${t} \u2014 the lens tools are open`):(i++,n(` setup \u2192 '${a.key}': \`lensmcp setup\` exited ${m} \u2014 the lens tools stay gated; run \`lensmcp setup\` in ${a.root} in a terminal.`))}return i?{state:"failed",note:`${i} setup${i===1?"":"s"} failed`}:r?{state:"skipped",note:o.flags.noSetup?"--no-setup":"--no-restart"}:{state:"done"}}h(bn,"_i"),l(bn,"upgradeSetupStep");async function ft(e){const o=Date.now()+e;for(;;){if(I("GET","/list")?.status===200)return!0;if(Date.now()>=o)return!1;await new Promise(t=>setTimeout(t,2e3))}}h(ft,"rn"),l(ft,"waitForDaemon");function wt(e,o,t,s,n){const r=l((i,a,d)=>{try{const c=L(i,a,{encoding:"utf8",timeout:12e4,env:t,stdio:["ignore","pipe","pipe"],...d?{cwd:d}:{}});return c.error&&c.error.code==="ENOENT"?{ok:!1,detail:`\`${i}\` is not on PATH`}:(c.status??1)!==0?{ok:!1,detail:`${c.stderr??""}
|
|
1009
|
+
`).filter(Boolean).pop():void 0;if(!r||!/^\d+\.\d+\.\d+/.test(r)){t("Could not resolve the latest lensmcp version from the npm registry \u2014 pass one explicitly: `lensmcp upgrade 1.20.1`.");return}return r}h(un,"Ci"),l(un,"resolveTargetVersion");function pn(e,o,t,s){for(const n of e){let r;try{r=ae(n.root,process.env)}catch{continue}if(r.mode!=="shared")continue;const i=Ge({identity:Ke(r.port),targetVersion:o,expectedRoot:Oe(n.root),expectedKey:n.key,port:r.port,selfPid:process.pid});if(!i.kill){s(` mcp \u2192 '${n.key}' :${r.port} \u2014 ${i.reason}`);continue}if(t){s(` mcp \u2192 would restart '${n.key}' :${r.port} (pid ${i.pid}) \u2014 ${i.reason}`);continue}try{process.kill(i.pid,"SIGTERM"),s(` mcp \u2192 restarted '${n.key}' :${r.port} \u2014 was ${i.reason}; the next session respawns it on ${o}`)}catch(a){s(` mcp \u2192 could not stop '${n.key}' :${r.port} (pid ${i.pid}): ${a.message}`)}}}h(pn,"$i"),l(pn,"restartSharedMcpServers");const za=new Set(["status","prompt","check"]),Ya=12e4;function ut(e){const o=lt(e)?.root??e,t=G(o),s=t.instance?.mainRoot;return re(t)&&typeof s=="string"&&S(s)?s:o}h(ut,"Zt"),l(ut,"migrationsRoot");function hn(e,o,t,s){const n=_(o,{string:["--cwd","--worktree"],boolean:["--json","--copy"]}),[r,...i]=n.positional,a=P($(n.flags["--cwd"])??e.cwd),d=O(a,"migrations.js");if(!d)return s(V("upgrade migrations entry","migrations.js")),{exitCode:1};const c=ut(a),u=r==="prompt"&&n.flags["--copy"]===!0,p=$(n.flags["--worktree"]),g=[d,r,...i,"--root",c,...n.flags["--json"]===!0&&!u?["--json"]:[],...p?["--worktree",p]:[]],m=L(process.execPath,g,{cwd:c,env:{...process.env,...e.env},encoding:"utf8",timeout:Ya,maxBuffer:32*1024*1024});if(m.error)return s(`lensmcp upgrade ${r}: ${m.error.message}`),{exitCode:1};if(u&&m.status===0&&m.stdout){const w=L("pbcopy",[],{input:m.stdout,encoding:"utf8",timeout:1e4});if(!w.error&&w.status===0)return t(`The prompt for ${i[0]} is on the clipboard (${m.stdout.trimEnd().split(`
|
|
1010
|
+
`).length} lines) \u2014 paste it into your coding agent.`),{exitCode:0};s("No clipboard here (pbcopy) \u2014 the prompt follows; copy it into your coding agent.")}return m.stdout&&t(m.stdout.trimEnd()),m.stderr&&s(m.stderr.trimEnd()),{exitCode:m.status??1}}h(hn,"xi"),l(hn,"runUpgradeMigrations");function Oe(e){try{return Et(e)}catch{return e}}h(Oe,"Je"),l(Oe,"canonicalRootPath");const mn=12e4,Xa=15*6e4,Qa=3e4;function gn(e){return{noInstall:e["--no-install"]===!0,noPlugins:e["--no-plugins"]===!0,noGlobal:e["--no-global"]===!0,noRestart:e["--no-restart"]===!0,noSetup:e["--no-setup"]===!0,yes:e["--yes"]===!0}}h(gn,"Pi"),l(gn,"upgradeRunFlags");function pe(e,o,t,s,n){const r=L(process.execPath,[e,...o],{cwd:t,env:s,encoding:"utf8",timeout:n,maxBuffer:33554432});return{code:r.status??1,stdout:r.stdout??"",stderr:`${r.stderr??""}${r.error?`
|
|
1011
|
+
${r.error.message}`:""}`}}h(pe,"ge"),l(pe,"runMigrationsEntry");const fn=l(e=>e.trim().split(`
|
|
1012
|
+
`).filter(Boolean).pop()??"","lastLine");function pt(e,o,t,s){const n=Te(e,o),r=n?k(D(n),xr,"migrations.js"):void 0;return r&&S(r)?r:t===o?O(s,"migrations.js"):void 0}h(pt,"nn"),l(pt,"migrationsEntryFor");function ht(e,o,t){const s=O(e,"migrations.js");return n=>{if(!s)return{root:n,goals:[],launches:[],unknown:"no migrations entry to read it with"};const r=pe(s,["team","--root",n,"--json"],n,o,Qa);return aa(r.stdout,n)??{root:n,goals:[],launches:[],unknown:r.code===2?`lensmcp ${t}'s migrations entry has no team read`:fn(r.stderr)||`exited ${r.code}`}}}h(ht,"sn"),l(ht,"upgradeTeamRead");function _e(e,o){return e.store?Re(e.store):yt(o)}h(_e,"ze"),l(_e,"lensInstalledFor");const mt=l((e,o)=>Ma(e,o)?Pa(La(e,o)):void 0,"storedCliFor");function De(e,o,t){return e.store?mt(e.store,t):Te(o,t)}h(De,"Xe"),l(De,"cliForUpgrade");function wn(e){let o=P(e);for(let t=0;t<8;t++){if(S(k(o,".lensmcp","config.json"))||S(k(o,"lensmcp.json")))return{key:G(o).key,root:o};const s=D(o);if(s===o)break;o=s}}h(wn,"Ni"),l(wn,"findLensWorkspace");async function gt(e,o,t,s){const n=_(o,{string:["--cwd","--from"],boolean:["--dry-run","--no-install","--no-plugins","--no-global","--no-restart","--no-registry-check","--no-setup","--yes","--resume"]}),r=P($(n.flags["--cwd"])??e.cwd),i=n.flags["--dry-run"]===!0,a={...process.env,...e.env??{}},d=a[ia]==="1",c=Number(a[zr]),u=a[Zr];for(const A of ca)delete process.env[A];const p=ns(a),g=ze(p),m=Qe(p),w=B(),f=n.flags["--resume"]===!0,y=n.flags["--no-registry-check"]===!0||$(n.flags["--from"])!==void 0;let v,b;if(f){const A=n.positional[0]?.replace(/^v/,"");b=A?as(m,A):Xe(m),v=b?.to??A}else{if(v=un(n.positional[0],g,s,y),!v)return{exitCode:1};b=as(m,v)}const x=ha({...b?{existing:b}:{},resume:f,...v?{to:v}:{},home:m});if(x.kind==="error"||!v)return s(x.kind==="error"?x.message:"lensmcp upgrade --resume: name the version to resume"),{exitCode:1};const E=i?void 0:na(u||ga(m,Date.now()),`# lensmcp upgrade ${v} \u2014 lensmcp ${w}, pid ${process.pid}, ${new Date().toISOString()}${d?" \u2014 phase 2 (the hand-off)":""}`),N=cs(t,E,"out"),C=cs(s,E,"err");let T;if(i){const A=rs(m);A&&A!=="unreadable"&&os(A.pid)&&N(` lock \u2192 another upgrade (pid ${A.pid}) holds ${Xr(m)} \u2014 a dry run changes nothing, so it goes on`)}else{if(T=ma(m,{pid:process.pid,now:Date.now,to:v,...d&&Number.isInteger(c)&&c>0?{inheritFrom:c}:{}}),!T.ok)return C(Qr(T)),{exitCode:1};const A=Yr(T);A&&N(A)}try{const A=x.kind==="resume"?x.run.store?.home:Oa(ye({env:p}),F(),p)?ye({env:p}):void 0,H=$(n.flags["--from"]);return await vn({ctx:e,cwd:r,dryRun:i,env:p,run:g,home:m,own:w,child:d,...d&&Number.isInteger(c)&&c>0?{parentLockPid:c}:{},version:v,given:gn(n.flags),noRegistryCheck:y,...E?{log:E}:{},out:N,err:C,...A?{store:A}:{},...H?{from:P(H)}:{}},x)}finally{T?.ok&&T.took!=="inherited"&&da(m,process.pid)}}h(gt,"on"),l(gt,"runUpgrade");async function vn(e,o){const{version:t,out:s,err:n}=e,r=l(f=>_e(e,f),"installed"),i=l(f=>S(ss(f)),"journalExists"),a=l(f=>{e.dryRun||fa(e.home,f)},"save"),d=ht(e.cwd,e.env,e.own);let c;if(o.kind==="resume"){if(c=o.run,c.flags=ea(c.flags,e.given),e.log&&!c.logs.includes(e.log.path)&&c.logs.push(e.log.path),!e.child)for(const f of ua(c,e.home))s(f)}else{const f=Zt({home:e.home}),y=lt(e.cwd)??(e.store?wn(e.cwd):void 0),{targets:v,instances:b}=Hr(y,f,N=>re(G(N)));if(v.length===0&&b.length>0)return n(`Only worktree instances here (${b.map(N=>N.key).join(", ")}): an instance runs its own commit's lens and \`upgrade\` leaves it alone. Run it in the main checkout.`),{exitCode:1};if(v.length===0&&!e.store)return n("No LensMCP workspace found: ~/.lensmcp/workspaces.json is empty and no package.json above the current directory depends on lensmcp."),{exitCode:1};const x=Xe(e.home);x&&x.to!==t&&s(` note \u2192 an unfinished upgrade to ${x.to} (started ${x.startedAt}) is left as it is \u2014 \`lensmcp upgrade ${x.to}\` continues it`);const E=z();if(c=sa({to:t,by:e.own,cwd:e.cwd,flags:e.given,before:E,known:f,targets:v,instances:b,now:Date.now(),...e.log?{log:e.log.path}:{}}),e.store&&(c.store={home:e.store}),s(`upgrade \u2192 lensmcp ${t}${e.dryRun?" (dry run \u2014 nothing will be changed)":""}`),E.wsKey&&s(` daemon \u2192 '${E.wsKey}' on :443${E.version?`, running ${E.version}`:""}, hosting ${E.registeredKeys.length} workspace${E.registeredKeys.length===1?"":"s"}`),e.store&&s(` store \u2192 ${e.store}/versions/${t}, made current \u2014 no package.json or lockfile is touched (POSIX only: macOS, Linux)`),s(` will change \u2192 ${v.length} workspace${v.length===1?"":"s"} (${v.map(N=>N.key).join(", ")})${e.given.noInstall||e.store?"":" + install"} + the migrations${e.given.noGlobal||e.store?"":" + the global CLI"}${e.given.noPlugins?"":" + the Claude/Codex plugins"}${e.given.noRestart?"":" + the :443 daemon"}`),!e.noRegistryCheck&&!e.store){const N=Dr(v.flatMap(T=>["package.json","yarn.lock","package-lock.json","pnpm-lock.yaml"].map(A=>ee(k(T.root,A))))),C=Br(N,t,T=>e.run("npm",["view",`${T}@${t}`,"version"]));if(C.length===0&&s(` registry \u2192 all ${N.length} packages these workspaces install are published at ${t}`),C.length>0)return n(`lensmcp ${t} is not fully published yet \u2014 ${C.length} of the ${N.length} packages these workspaces install are not on the npm registry at ${t}:`),n(` ${C.join(", ")}`),n("A release publishes its packages one by one; run this again in a minute. Nothing was changed. (`--no-registry-check` skips the question.)"),{exitCode:1}}}if(e.store&&!e.child&&c.phase==="install"){const f=e.store,y=Ia({home:f,to:t,dryRun:e.dryRun,out:s,err:n,install:l(()=>Ea(f,t,{env:e.env,...e.from?{spec:e.from}:{}}),"install"),verify:l(v=>Ta(v,e.env),"verify"),use:l(()=>Na(f,t),"use")});if(!y.ok)return a(c),e.log&&s(` log \u2192 ${e.log.path}`),{exitCode:1};for(const v of c.targets){if(v.setupBefore===void 0){const b=Ae(v.root);b&&(v.setupBefore=b)}v.installedBefore===void 0&&y.previous&&(v.installedBefore=y.previous),e.dryRun?v.dryInstall=!0:v.install="installed"}c.store={home:f,...y.previous?{previous:y.previous}:c.store?.previous?{previous:c.store.previous}:{}},e.dryRun||(c.phase="finish"),a(c)}if(!e.store&&!e.child&&(o.kind==="fresh"||Jr(c,r).length>0)&&pa(c,{out:s,err:n,dryRun:e.dryRun,installed:r,packageManager:l(f=>_r(f),"packageManager"),install:l((f,y)=>L(y.name,y.install,{cwd:f,stdio:"inherit",env:e.env}).status??1,"install"),freeDisk:Kr,memory:l(()=>({free:Fn(),total:Hn(),platform:process.platform}),"memory"),team:d,plan:l((f,y,v)=>{const b=pt(f.root,t,e.own,e.cwd);if(!b)return;const x=Te(f.root,t),E=pe(b,ta({command:"plan",root:f.root,to:t,from:y,machine:v,...x?{cliBin:x}:{}}),f.root,e.env,mn);return oa(E.stdout)??{error:fn(E.stderr)||`exited ${E.code}`}},"plan"),journalExists:i,save:a}).refused)return e.log&&s(` log \u2192 ${e.log.path}`),{exitCode:1};if(e.dryRun)return{exitCode:(await is(c,ft(e,c,{installed:r,journalExists:i,team:d,save:a}))).exitCode};const u=c.targets.filter(f=>r(f.root)===t);if(!u.length&&!e.store){const f=c.targets.filter(v=>v.install==="skipped"),y=c.targets.some(v=>v.install==="restored"||v.install==="unreadable");return f.length&&!y?s(` finish \u2192 the install is yours (--no-install): run it in ${f.map(v=>v.root).join(", ")}, then \`lensmcp upgrade ${t}\` again \u2014 it resumes here, and lensmcp ${t} runs the migrations, the restart and setup`):n(` finish \u2192 no workspace holds lensmcp ${t}, so there is nothing to finish the upgrade with${y?" (each failed install was restored)":""}. Fix it, then run \`lensmcp upgrade ${t}\` again: it resumes here.`),a(c),e.log&&s(` log \u2192 ${e.log.path}`),{exitCode:f.length&&!y?0:1}}const p=c.before.wsKey?u.find(f=>f.key===c.before.wsKey):void 0,g=e.store?mt(e.store,t):Te((p??u[0]).root,t),m=qr({own:e.own,to:t,...g?{bin:g}:{},child:e.child});if(m.mode==="spawn"){s(` hand-off \u2192 lensmcp ${t} runs the rest of the upgrade (${m.bin} upgrade ${t} --resume)`),a(c);const f=L(process.execPath,Wr(m.bin,t,e.cwd,c.flags.yes),{cwd:e.cwd,stdio:"inherit",env:ts(e.env,{lockPid:process.pid,...e.log?{log:e.log.path}:{}})});return f.error?(n(` hand-off \u2192 could not start lensmcp ${t} (${f.error.message}) \u2014 run \`lensmcp upgrade ${t}\` again: it resumes here.`),{exitCode:1}):{exitCode:f.status??1}}if(m.mode==="none")return n(` hand-off \u2192 ${m.why} \u2014 run \`lensmcp upgrade ${t}\` again once it is: it resumes here.`),a(c),{exitCode:1};e.child||s(` hand-off \u2192 ${m.why}: phase 2 runs in this process`);const w=await is(c,ft(e,c,{installed:r,journalExists:i,team:d,save:a}));return c.store?.previous&&c.store.previous!==t&&s(` ${Ra(c.store.previous)}`),{exitCode:w.exitCode}}h(vn,"Li"),l(vn,"upgradeInPhases");function ft(e,o,t){const s=e.version,n=e.own===s?O(e.cwd,"migrations.js"):o.targets.map(r=>pt(r.root,s,e.own,e.cwd)).find(r=>r!==void 0);return{out:e.out,err:e.err,dryRun:e.dryRun,tty:Se(),own:e.own,ask:l(async r=>{const i=await Ye(r);return e.log?.write(`${r} [y/N] ${i?"y":"N"}`),i},"ask"),installed:t.installed,journalExists:t.journalExists,setupVersion:Ae,...n?{migrations:l(r=>pe(n,r,e.cwd,e.env,r[0]==="apply"?Xa:mn),"migrations")}:{},cliBin:l(r=>De(e,r,s),"cliBin"),team:t.team,save:t.save,...e.log?{log:e.log.path}:{},steps:{global:l(()=>e.store?(e.out(" global \u2192 the store is the machine's install: a global `lensmcp` forwards to its current version"),{state:"skipped",note:"the store"}):yn(e),"global"),plugins:l((r,i)=>kn(e,r,i),"plugins"),mcp:l((r,i)=>{for(const a of r.targets)i.includes(a)||e.out(` mcp \u2192 '${a.key}' left alone \u2014 its install did not land, so there is no ${s} bundle to restart it onto`);return pn(i,s,e.dryRun,e.out),{state:"done"}},"mcp"),restart:l((r,i,a)=>bn(e,r,a),"restart"),setup:l(r=>Cn(e,r),"setup"),daemon:l(r=>{const i=z();if(!i.version)return;const a=i.wsKey?r.targets.find(c=>c.key===i.wsKey)?.root:void 0,d=a?_e(e,a):void 0;return Or({reported:i.version,target:s,...d?{ownerInstalled:d}:{},...a?{ownerRoot:a}:{}})},"daemon")}}}h(ft,"rn"),l(ft,"upgradePhase2Io");function yn(e){const o=Ir(e.run);return o?o.version===e.version?(e.out(` global \u2192 already ${o.version}`),{state:"done"}):e.dryRun?(e.out(` global \u2192 ${o.version} \u2192 ${e.version} (npm i -g lensmcp@${e.version})`),{state:"done"}):(e.out(` global \u2192 ${o.version} \u2192 ${e.version}`),(L("npm",["install","-g",`lensmcp@${e.version}`],{stdio:"inherit",env:e.env,timeout:3e5}).status??1)!==0?(e.err(` the global install failed \u2014 run by hand: npm i -g lensmcp@${e.version}`),{state:"failed",note:"npm i -g failed"}):{state:"done"}):{state:"done",note:"no global install"}}h(yn,"Ti"),l(yn,"upgradeGlobalStep");function kn(e,o,t){if(e.store){const r=k(Sa(e.store),"node_modules","lensmcp");return e.dryRun?(e.out(` plugins \u2192 would re-read Claude Code + Codex from ${r}`),{state:"done"}):(vt(r,e.cwd,e.env,e.out,e.err),{state:"done"})}const s=(o.before.wsKey?t.find(r=>r.key===o.before.wsKey):void 0)??t[0];if(!s)return e.out(` plugins \u2192 skipped (no workspace holds lensmcp ${e.version} to install them from)`),{state:"skipped",note:"nothing landed"};const n=k(s.root,"node_modules","lensmcp");return e.dryRun?(e.out(` plugins \u2192 would re-install Claude Code + Codex from ${n}`),{state:"done"}):(vt(n,e.cwd,e.env,e.out,e.err),{state:"done"})}h(kn,"Ri"),l(kn,"upgradePluginsStep");async function bn(e,o,t){const{version:s,out:n,err:r}=e,i=o.targets.filter(p=>p.install==="installed"||e.dryRun&&p.dryInstall===!0),a=Vr({...o.before.wsKey?{daemonWsKey:o.before.wsKey}:{},...o.before.version?{daemonVersion:o.before.version}:{},targetVersion:s,registeredKeys:o.before.registeredKeys,known:o.known,upgraded:i});if(a.steps.length===0)return n(` restart \u2192 nothing to do${a.note?` (${a.note})`:""}`),{state:"done",note:"nothing to restart"};if(!e.dryRun&&o.before.version!==s&&z().version===s)return n(` restart \u2192 the daemon already runs ${s} \u2014 nothing to restart`),{state:"done",note:"already restarted"};const d=await t();if(!d.restart)return{state:"deferred",note:d.why??"deferred"};let c,u;for(const p of a.steps){if(e.dryRun){n(` restart \u2192 would ${p.action==="restart"?`restart the daemon ('${p.key}')`:`re-register '${p.key}'`}${p.reason==="rehost"?" (not upgraded \u2014 re-hosted so the daemon restart does not drop it)":p.reason==="stale-daemon"?" (its files are current but the process still runs the old bundle)":""}`);continue}if(p.action==="restart"){const g=De(e,p.root,s);if(n(` restart \u2192 gateway daemon ('${p.key}') ${g?`with lensmcp ${s}`:`in-process (no lensmcp ${s} on disk in ${p.root})`} \u2026`),(g?es(g,p.root,e.env):tt({...e.ctx,cwd:p.root},["restart"],n,r).exitCode)!==0){c=`the daemon restart ('${p.key}') failed`,r(` ${c} \u2014 fix it, then \`lensmcp gateway start\` in each guest workspace.`);break}if(!await wt(18e4)){c="the restarted daemon did not answer within 3 minutes",r(` ${c} \u2014 check \`lensmcp gateway status\`; guests need \`lensmcp gateway start\` once it is up.`);break}}else{if(await et(p.key,p.root,u??=Date.now()+15e3)){n(` restart \u2192 '${p.key}' is back \u2014 the daemon re-hosted it`);continue}const g=I("POST","/register",le(p.root,p.key));if(g&&g.status===200){try{se(k(p.root,".lensmcp"),{recursive:!0}),ne(k(p.root,".lensmcp","registered.json"),JSON.stringify({wsKey:p.key}))}catch{}n(` restart \u2192 re-registered '${p.key}'${p.reason==="rehost"?" (not upgraded \u2014 re-hosted after the daemon restart)":""}`);const m=qe(g.json);m&&n(m)}else c=`re-registering '${p.key}' failed`,r(` ${c} \u2014 ${Ne(g)??`run \`lensmcp gateway start\` in ${p.root}`}.`)}}return e.dryRun?{state:"done"}:c?{state:"failed",note:c,acted:!0}:{state:"done",acted:!0}}h(bn,"Ai"),l(bn,"upgradeRestartStep");function Cn(e,o){const{version:t,out:s,err:n}=e,r=o.flags.noSetup||o.flags.noRestart;if(e.dryRun)return r||s(` setup \u2192 would run \`lensmcp setup --no-recycle\` with lensmcp ${t} in each workspace whose setup is then behind (\`--no-setup\` skips it)`),{state:"done"};let i=0;for(const a of o.targets){const d=Ae(a.root),c=_e(e,a.root),u=De(e,a.root,t),p=Gr({key:a.key,root:a.root,targetVersion:t,...d?{setupVersion:d}:{},...c?{installedVersion:c}:{},...u?{bin:u}:{},skip:r});if(p.action==="remind"&&s(p.line),p.action!=="run")continue;s(` setup \u2192 '${a.key}': lensmcp setup --no-recycle with lensmcp ${t} (the lens tools are gated until it has run) \u2026`);const g=e.child&&e.parentLockPid?e.parentLockPid:process.pid,m=Ur(p.bin,a.root,ts(e.env,{lockPid:g}));m===0?s(` setup \u2192 '${a.key}' is set up for ${t} \u2014 the lens tools are open`):(i++,n(` setup \u2192 '${a.key}': \`lensmcp setup\` exited ${m} \u2014 the lens tools stay gated; run \`lensmcp setup\` in ${a.root} in a terminal.`))}return i?{state:"failed",note:`${i} setup${i===1?"":"s"} failed`}:r?{state:"skipped",note:o.flags.noSetup?"--no-setup":"--no-restart"}:{state:"done"}}h(Cn,"_i"),l(Cn,"upgradeSetupStep");async function wt(e){const o=Date.now()+e;for(;;){if(I("GET","/list")?.status===200)return!0;if(Date.now()>=o)return!1;await new Promise(t=>setTimeout(t,2e3))}}h(wt,"an"),l(wt,"waitForDaemon");function vt(e,o,t,s,n){const r=l((i,a,d)=>{try{const c=L(i,a,{encoding:"utf8",timeout:12e4,env:t,stdio:["ignore","pipe","pipe"],...d?{cwd:d}:{}});return c.error&&c.error.code==="ENOENT"?{ok:!1,detail:`\`${i}\` is not on PATH`}:(c.status??1)!==0?{ok:!1,detail:`${c.stderr??""}
|
|
1013
1013
|
${c.stdout??""}`.trim().split(`
|
|
1014
|
-
`).filter(Boolean).pop()||`exited ${c.status}`}:{ok:!0}}catch(c){return{ok:!1,detail:c.message}}},"exec");for(const i of
|
|
1014
|
+
`).filter(Boolean).pop()||`exited ${c.status}`}:{ok:!0}}catch(c){return{ok:!1,detail:c.message}}},"exec");for(const i of Yt){if(!S(k(e,i.manifest))){s(` plugins \u2192 ${i.label} skipped \u2014 ${e} ships no ${i.manifest} (the plugin arrived in ${i.since})`);continue}if(i.id==="codex"){const c=Xt(i,{root:e},{run:ze(t)});c.outcome==="installed"?s(` plugins \u2192 Codex installed \u2014 ${i.restartHint}`):c.outcome==="failed"?s(` plugins \u2192 Codex not updated (${c.detail}) \u2014 run: ${c.commands.join(" && ")}`):s(` plugins \u2192 Codex skipped (${c.detail})`);continue}const a=r(i.bin,["plugin","marketplace","add",e]);if(!a.ok){s(` plugins \u2192 ${i.label} skipped (${a.detail})`);continue}r(i.bin,["plugin","marketplace","update",Ar]);const d=Jt();if(d.length===0){const c=r(i.bin,["plugin","install",Le,"--yes"]);s(c.ok?` plugins \u2192 Claude Code installed \u2014 ${i.restartHint}`:` plugins \u2192 Claude Code install failed (${c.detail}) \u2014 run: claude plugin install ${Le} --yes`);continue}for(const c of d){const u=c.scope&&c.scope!=="user"?["--scope",c.scope]:[],p=r(i.bin,["plugin","update",c.id,...u],c.projectPath??o),g=c.projectPath?` (${c.projectPath})`:"";p.ok?s(` plugins \u2192 Claude Code updated${g} \u2014 ${i.restartHint}`):(n(` plugins \u2192 Claude Code update failed${g}: ${p.detail}`),n(` run by hand${c.projectPath?` from ${c.projectPath}`:""}: claude plugin update ${c.id}${u.length>0?` --scope ${c.scope}`:""}`))}}}h(vt,"cn"),l(vt,"syncAgentPlugins");function F(){let e=D(Lt(import.meta.url));for(let o=0;o<4;o++){if(S(k(e,"package.json")))return e;const t=D(e);if(t===e)break;e=t}return e}h(F,"V"),l(F,"cliPackageRoot");function yt(e){try{const o=JSON.parse(U(k(e,"node_modules","lensmcp","package.json"),"utf8"));return typeof o.version=="string"?o.version:void 0}catch{return}}h(yt,"dn"),l(yt,"readProjectLensmcpVersion");function he(e){return Re(ye())??yt(e)}h(he,"we"),l(he,"lensVersionFor");function B(){try{return JSON.parse(U(k(F(),"package.json"),"utf8")).version}catch{return"0.0.0"}}h(B,"F"),l(B,"readCliVersion");function $n(e,o,t){const s=P(e.cwd),n=xn(s);return n?{exitCode:L(process.execPath,[n,...o],{stdio:"inherit",cwd:s,env:{...process.env,...e.env}}).status??1}:(t(`Could not locate the lensmcp rollout helper (@lensmcp/cluster).
|
|
1015
1015
|
Looked for main.rollout.js (walking up from cwd):
|
|
1016
1016
|
\u2022 <dir>/node_modules/@lensmcp/cluster/executors/gateway/main.rollout.js
|
|
1017
1017
|
\u2022 <dir>/dist/libs/cluster/executors/gateway/main.rollout.js
|
|
1018
|
-
Install @lensmcp/cluster, or \`yarn nx build @lensmcp/cluster\` in the workspace.`),{exitCode:1})}h(
|
|
1019
|
-
`)[0]?.trim());return Number.isInteger(t)&&t>0?t:void 0}catch{return}}h(
|
|
1020
|
-
`).find(t=>t.startsWith("n"));return o&&o.slice(1).trim()||void 0}catch{return}}h(
|
|
1018
|
+
Install @lensmcp/cluster, or \`yarn nx build @lensmcp/cluster\` in the workspace.`),{exitCode:1})}h($n,"Oi"),l($n,"runRollout");function xn(e){let o=e;for(let t=0;t<6;t++){for(const n of[k(o,"node_modules","@lensmcp","cluster","executors","gateway","main.rollout.js"),k(o,"dist","libs","cluster","executors","gateway","main.rollout.js")])if(S(n))return n;const s=D(o);if(s===o)break;o=s}}h(xn,"Ii"),l(xn,"findRolloutBundle");function kt(e){return O(e,"main.js")}h(kt,"ln"),l(kt,"findMcpBinary");function bt(e){return O(e,"shim.js")}h(bt,"pn"),l(bt,"findShimBinary");function O(e,o){return jr(e,o,F())}h(O,"_"),l(O,"findServerBundle");function jn(e){const o=k(F(),"bundled","bridge.js");if(S(o))return o;let t=e;for(let s=0;s<5;s++){const n=k(t,"libs","bridge","dist","main.js");if(S(n))return n;const r=D(t);if(r===t)break;t=r}}h(jn,"Di"),l(jn,"findBridgeBundle");function Sn(e){const o=k(F(),"bundled","lint-runner.js");if(S(o))return o;let t=e;for(let s=0;s<5;s++){const n=k(t,"libs","session","dist","lint-runner.js");if(S(n))return n;const r=D(t);if(r===t)break;t=r}}h(Sn,"Fi"),l(Sn,"findLintRunner");function Ct(e){const o=k(F(),"bundled","static-checks-runner.js");if(S(o))return o;let t=e;for(let s=0;s<5;s++){const n=k(t,"libs","static-checks","dist","runner.js");if(S(n))return n;const r=D(t);if(r===t)break;t=r}}h(Ct,"un"),l(Ct,"findStaticChecksRunner");function xe(e){let o=e;for(let t=0;t<5;t++){const s=k(o,"node_modules",".bin","nx");if(S(s))return s;const n=D(o);if(n===o)break;o=n}}h(xe,"Le"),l(xe,"findNxBinary");function je(e){const o=k(e,".lensmcp");S(o)||se(o,{recursive:!0})}h(je,"Te"),l(je,"ensureLensmcpDir");function Se(){return!!(process.stdin.isTTY&&process.stdout.isTTY)}h(Se,"Re"),l(Se,"isInteractive");function me(){const e=Un(),o=[],t=l((s,n)=>{try{for(const r of Ve(s,{withFileTypes:!0})){if(!r.isDirectory()||!r.name.endsWith("-devserver"))continue;const i=k(s,r.name,"parent.sock");S(i)&&!Uo(i)&&o.push({service:r.name.slice(0,-10),wsKey:n,sock:i})}}catch{}},"scan");t(e,"");try{for(const s of Ve(e,{withFileTypes:!0}))s.isDirectory()&&/^[a-z0-9][a-z0-9-]*$/.test(s.name)&&!s.name.endsWith("-devserver")&&t(k(e,s.name),s.name)}catch{}return o.sort((s,n)=>`${s.wsKey}/${s.service}`.localeCompare(`${n.wsKey}/${n.service}`))}h(me,"ye"),l(me,"discoverDevserverSocks");const Y=l(e=>e.wsKey?`${e.wsKey}/${e.service}`:e.service,"fullServiceName");function $t(e){try{const o=L("lsof",["-t",e],{encoding:"utf8"}),t=Number((o.stdout??"").split(`
|
|
1019
|
+
`)[0]?.trim());return Number.isInteger(t)&&t>0?t:void 0}catch{return}}h($t,"hn"),l($t,"pidOnSocket");function xt(e){try{const o=L("ps",["-o","pgid=","-p",String(e)],{encoding:"utf8"}),t=Number((o.stdout??"").trim());return Number.isInteger(t)&&t>1?t:void 0}catch{return}}h(xt,"fn"),l(xt,"pgidOf");function En(e){try{const o=(L("lsof",["-a","-p",String(e),"-d","cwd","-Fn"],{encoding:"utf8"}).stdout??"").split(`
|
|
1020
|
+
`).find(t=>t.startsWith("n"));return o&&o.slice(1).trim()||void 0}catch{return}}h(En,"Gi"),l(En,"cwdOfPid");function Mn(e,o){const t=Nt(P(e),P(o));return t===""||!t.startsWith("..")&&!Wn(t)}h(Mn,"Vi"),l(Mn,"isInside");function Pn(e,o){return me().filter(t=>{if(t.wsKey)return t.wsKey===o;const s=$t(t.sock),n=s!==void 0?En(s):void 0;return n!==void 0&&Mn(e,n)})}h(Pn,"Ui"),l(Pn,"workspaceDevservers");function Nn(e,o,t,s){const n=Pn(e,o);if(n.length===0)return t(" no devserver pods running for this workspace \u2014 nothing to recycle."),{killed:0,stale:0};s&&t(` \xB7 recycling ${n.length} pod${n.length===1?"":"s"} because ${s}`);const r=new Set;for(const d of[process.pid,...q()]){const c=xt(d);c!==void 0&&r.add(c)}let i=0,a=0;for(const d of n){const c=Y(d),u=$t(d.sock);if(u===void 0){Z(d.sock),t(` \u2713 ${c} \u2014 stale socket removed (no process held it)`),a++;continue}const p=xt(u),g=p!==void 0&&!r.has(p),m=l(w=>{try{g?process.kill(-p,w):process.kill(u,w)}catch{}},"signal");m("SIGTERM"),jt(u,5e3)||(m("SIGKILL"),jt(u,2e3)),Z(d.sock),t(` \u2713 ${c} \u2014 stopped (pid ${u}${g?`, group ${p}`:", parent only"})`),i++}return{killed:i,stale:a}}h(Nn,"Bi"),l(Nn,"reapWorkspacePods");function jt(e,o){const t=Date.now()+o;for(;;){if(!be(e))return!0;if(Date.now()>=t)return!1;L("sleep",["0.15"])}}h(jt,"mn"),l(jt,"waitForPidGone");function Ln(e,o,t,s){const n=k(o,".lensmcp","gateway.pid"),r=k(o,".lensmcp","registered.json"),{pid:i,healed:a}=Ce(n,o);if(a&&s(` healed: adopted a running gateway (pid ${i}) the pid file had lost.`),ke(o,e.env,g=>s(` ${g}`)),J(o)!==void 0){s(` gateway: this workspace owns the :443 daemon (pid ${i??"?"}) \u2014 left running, pods respawn fresh.`);return}const d=I("GET","/list");if(d?.status!==200){s(" gateway: not running. Start it when you are ready: lensmcp gateway start");return}const c=d.json&&typeof d.json=="object"?d.json.workspaces??[]:[],u=We(c,t,o);if(u.kind==="other-checkout"){for(const g of Kt(t,u.root,o))s(` gateway: ${g}`);return}if(u.kind==="mine"){se(D(r),{recursive:!0}),ne(r,JSON.stringify({wsKey:t})),s(` gateway: '${t}' is already registered into the shared daemon \u2014 left serving.`);return}const p=I("POST","/register",le(o,t));if(p&&p.status===200){se(D(r),{recursive:!0}),ne(r,JSON.stringify({wsKey:t})),s(` gateway: registered '${t}' into the shared daemon \u2014 it now hosts this workspace.`);const g=qe(p.json);g&&s(g);return}s(` gateway: a shared daemon is up but registering this workspace failed \u2014 ${Ne(p)??"run `lensmcp gateway start`"}.`)}h(Ln,"Hi"),l(Ln,"reconcileGatewayAfterSetup");function Be(e,o,t,s){let n=o.filter(r=>r.service===e||Y(r)===e);if(!e.includes("/"))try{const r=G(t),i=Ee(r),a=n.filter(d=>d.wsKey===i);(re(r)||n.length>1&&a.length===1)&&(n=a)}catch{}return n.length===0?(s(`No running service named "${e}".`),o.length>0&&s(`Running: ${o.map(Y).join(", ")}`),null):n.length>1?(s(`"${e}" is ambiguous \u2014 use one of: ${n.map(Y).join(", ")}`),null):n[0]}h(Be,"Qe"),l(Be,"resolveServiceSock");async function Tn(e,o,t,s){const n=_(o,{string:["--tail","--cwd"],boolean:["--no-follow","--follow","--plain","--color"]}),r=n.positional[0],i=me();if(!r){if(i.length===0)t("No running services found (no devserver control sockets under $TMPDIR)."),t("Start one with `yarn nx serve <project>` or `lensmcp gateway start`.");else{t("Running services \u2014 attach with `lensmcp logs <service>`:");for(const w of i)t(` ${Y(w)}`)}return{exitCode:0}}const a=Be(r,i,P($(n.flags["--cwd"])??e.cwd),s);if(!a)return{exitCode:1};const{follow:d,hint:c}=eo({noFollow:n.flags["--no-follow"]===!0,follow:n.flags["--follow"]===!0,color:n.flags["--color"]===!0,isTTY:process.stdout.isTTY===!0}),u=Number($(n.flags["--tail"])??NaN),p=Number.isInteger(u)&&u>=0?u:100,g=n.flags["--plain"]===!0||n.flags["--color"]!==!0&&!process.stdout.isTTY,m=`/webpack/logs?tail=${p}&follow=${d?1:0}${g?"&plain=1":""}`;return new Promise(w=>{const f=Pt({socketPath:a.sock,path:m,method:"GET"},y=>{y.on("data",v=>process.stdout.write(v)),zn(()=>{y.destroy(),w({exitCode:0})}),y.on("end",()=>{c&&s(c),w({exitCode:0})}),y.on("error",()=>w({exitCode:1}))});f.on("error",y=>{s(`Cannot attach to ${Y(a)}: ${y.message}`),s("The devserver may have crashed leaving a stale socket \u2014 restart the service and retry."),w({exitCode:1})}),f.end()})}h(Tn,"Wi"),l(Tn,"runLogs");async function An(e,o,t,s){const n=_(o,{string:["--port","--cwd"]}),r=n.positional[0],i=me();if(!r)return s("Usage: lensmcp debug <service> [--port <base>]"),i.length>0&&s(`Running: ${i.map(Y).join(", ")}`),{exitCode:2};const a=Be(r,i,P($(n.flags["--cwd"])??e.cwd),s);if(!a)return{exitCode:1};const d=Number($(n.flags["--port"])??"")||void 0,c=`/webpack/debug${d?`?port=${d}`:""}`,u=await new Promise(g=>{const m=Pt({socketPath:a.sock,path:c,method:"POST"},w=>{let f="";w.on("data",y=>f+=y),w.on("end",()=>g(f)),w.on("error",()=>g(null))});m.on("error",()=>g(null)),m.end()});if(u===null)return s(`Cannot reach ${Y(a)} \u2014 the devserver may have crashed leaving a stale socket.`),{exitCode:1};let p;try{p=JSON.parse(u)}catch{return s(`Unexpected response from the devserver: ${u.slice(0,200)}`),{exitCode:1}}t(`Inspectors open on ${Y(a)} \u2014 in place, no restart:`);for(const g of p.pods??[])t(` pod #${g.id} ${g.inspectorUrl??"(no url reported \u2014 check lensmcp logs)"}`);for(const g of p.workers??[])t(` worker ${g.name} ${g.inspectorUrl??`127.0.0.1:${g.port}`}`);return t(p.fixedPorts&&p.basePort?`Attach WebStorm (Run \u2192 Attach to Node.js/Chrome) to 127.0.0.1:${p.basePort} \u2014 or click the "Debugger listening" link in \`lensmcp logs ${r}\`.`:`Attach with one of the URLs above \u2014 Chrome DevTools (devtools://devtools/bundled/js_app.html?ws=<host:port/uuid>), VS Code (attach, "websocketAddress"), or WebStorm's click-to-attach on the URL. The ports are ephemeral and do not answer /json/list, so a host:port attach finds nothing; set LENSMCP_DEBUG_FIXED_PORTS=1 if your IDE needs one.`),{exitCode:0}}h(An,"Ki"),l(An,"runDebug");async function Rn(e,o,t,s){return Jo(o,e.cwd,{daemonRequest:I,registrationBody:le,git:l((n,r)=>{const i=L("git",r,{cwd:n,encoding:"utf8",timeout:1e4});return i.status===0&&typeof i.stdout=="string"&&i.stdout.trim()?i.stdout.trim():void 0},"git"),stopMcpServer:l((n,r)=>{let i;try{i=S(k(n,".lensmcp","config.json"))?ae(n,e.env??process.env).port:Jn(r).mcpHttp}catch{return}const a=Ge({identity:Ke(i),targetVersion:B(),expectedRoot:Oe(n),expectedKey:r,port:i,selfPid:process.pid,stopFor:"its worktree instance was removed"});if(!a.kill)return a.reason.startsWith("no shared MCP server answered")?void 0:`left :${i} alone \u2014 ${a.reason}`;try{return process.kill(a.pid,"SIGTERM"),`stopped its lens server :${i} (pid ${a.pid})`}catch(d){return`could not stop its lens server :${i} (pid ${a.pid}): ${d.message}`}},"stopMcpServer"),env:e.env??process.env},t,s)}h(Rn,"qi"),l(Rn,"runInstance");async function In(e,o,t,s){return Go(o,e.cwd,t,s,{discover:me,resolveService:Be,workspaceKey:l(n=>{try{return Ee(G(n))}catch{return}},"workspaceKey"),analyzerScript:k(D(Lt(import.meta.url)),"heap-analyzer-main.js"),env:e.env??process.env})}h(In,"Ji"),l(In,"runMem");async function On(e,o){let t;try{t=Ee(G(e))}catch{t=void 0}const s=[],n=[];for(const i of me().filter(a=>a.wsKey===t||a.wsKey==="")){const a=await Fo(i);if(!a.memory){i.wsKey===t&&n.push(`${i.service}: ${a.error??"no answer"}`);continue}const d=a.memory.bundle.path;if(i.wsKey===""&&!d.startsWith(e+"/"))continue;const c=a.memory.pods.map(p=>p.latest?.sourceMaps).filter(p=>typeof p=="boolean"),u=await sr(d);s.push({service:i.service,...c.length?{sourceMaps:c.some(Boolean)}:{},...u?{bundle:u}:{}})}const r=nr(s,n);M(o,r.status,"running services keep one copy of their bundle text",r.detail,r.hint)}h(On,"zi"),l(On,"checkPodSourceMaps");async function _n(e,o,t){const s=or(await rr(e,o));M(t,s.status,"performance rules (perf://rules)",s.detail,s.hint)}h(_n,"Yi"),l(_n,"checkPerfRules");function $(e){if(e!==void 0)return typeof e=="string"?e:void 0}h($,"$"),l($,"stringFlag");function _(e,o={}){const t=new Set(o.string??[]),s=new Set(o.boolean??[]),n={},r=[];for(let i=0;i<e.length;i++){const a=e[i];if(a.startsWith("--")){const d=a.indexOf("="),c=d===-1?a:a.slice(0,d);if(s.has(c))n[c]=!0;else if(t.has(c))if(d!==-1)n[c]=a.slice(d+1);else{const u=e[i+1];u===void 0||u.startsWith("--")?n[c]="":(n[c]=u,i++)}else n[c]=d===-1?!0:a.slice(d+1)}else r.push(a)}return{flags:n,positional:r}}h(_,"O"),l(_,"parseFlags");
|