@nativestudio/cli 0.3.0-rc.1 → 0.3.0-rc.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (37) hide show
  1. package/COMPATIBILITY.json +7 -7
  2. package/README.md +19 -2
  3. package/components/runtime.json +3 -3
  4. package/components/runtime.tgz +0 -0
  5. package/dist/_chunks/{chunk-GIEYSDCG.js → chunk-66CUOZVI.js} +1 -1
  6. package/dist/_chunks/{chunk-MSOMVWKN.js → chunk-7S3DJ2QE.js} +1 -1
  7. package/dist/_chunks/{chunk-25EDDZQA.js → chunk-BVSTJQJI.js} +1 -1
  8. package/dist/_chunks/{chunk-G42IS5JF.js → chunk-C33A2DW4.js} +1 -1
  9. package/dist/_chunks/{chunk-RUMDDTON.js → chunk-C753RRRA.js} +1 -1
  10. package/dist/_chunks/chunk-K6LVS2IN.js +1 -0
  11. package/dist/_chunks/chunk-KHKUJXQX.js +1 -0
  12. package/dist/_chunks/{chunk-QC7RLTGU.js → chunk-VC3ODN3M.js} +1 -1
  13. package/dist/_chunks/{files-TBJVDQWU.js → files-FZEK2ZZJ.js} +1 -1
  14. package/dist/_chunks/local-main-NLFS74Q4.js +1 -0
  15. package/dist/_chunks/{local-mcp-JLPXXIDW.js → local-mcp-OLHBBVNN.js} +1 -1
  16. package/dist/_chunks/{main-4SNF5EKE.js → main-VRIQTI6R.js} +2 -2
  17. package/dist/_chunks/oauth-F7EZGVME.js +1 -0
  18. package/dist/_chunks/{project-connect-6MH2QG6G.js → project-connect-MXM7IY55.js} +1 -1
  19. package/dist/_chunks/{stdio-main-JEADWO7U.js → stdio-main-KOGQ5OWF.js} +1 -1
  20. package/dist/_types/cli/local/desktop-contract.d.ts +73 -0
  21. package/dist/_types/cli/local/desktop-owner.d.ts +2 -0
  22. package/dist/_types/cli/local/manager.d.ts +30 -2
  23. package/dist/_types/cli/local/mcp-tools.d.ts +2 -2
  24. package/dist/_types/cli/local/releases.d.ts +1 -0
  25. package/dist/_types/cli/local-management.d.ts +1 -0
  26. package/dist/_types/contracts/local-execution/ipc.d.ts +3 -3
  27. package/dist/_types/contracts/local-execution/lifecycle.d.ts +28 -0
  28. package/dist/_types/contracts/local-execution/local-navigation.d.ts +3 -3
  29. package/dist/_types/sdk/local-runtime-client.d.ts +4 -4
  30. package/dist/entry.js +1 -1
  31. package/dist/local-management.js +1 -1
  32. package/dist/local-navigation.js +1 -1
  33. package/package.json +1 -1
  34. package/dist/_chunks/chunk-EAZKDCLD.js +0 -1
  35. package/dist/_chunks/chunk-U2UKGYGF.js +0 -1
  36. package/dist/_chunks/local-main-SOERK22D.js +0 -1
  37. package/dist/_chunks/oauth-257CEUQH.js +0 -1
@@ -1,2 +1,2 @@
1
- import{loginLink,openLoginBrowser}from"./chunk-VDNNFVTZ.js";import{NativeStudioAccountClient,accountError,accountServerOrigin,clientHome,connectionStatus,defaultConnection,readAccount,requireAccount,saveAccount,withAccountLock}from"./chunk-RUMDDTON.js";import"./chunk-GJ7BZJLW.js";import"./chunk-VPYAXWXY.js";import"./chunk-MSOMVWKN.js";import"./chunk-PUNG4ND7.js";import{readCredential,readInput}from"./chunk-25EDDZQA.js";import{write}from"./chunk-GIEYSDCG.js";import{NativeStudioSdkError}from"./chunk-6NVIN2NI.js";var aliases={find:"studio.start",overview:"studio.navigate",next:"studio.navigate",resume:"operation.get"};var auth=new Set(["--tenant","--origin","--mcp-url","--profile","--token-env","--token-file"]);var fields={find:{"--query":"search","--project":"projectId","--limit":"limit","--next":"next","--attention":"attention"},overview:{"--production":"productionId","--project":"projectId","--goal":"goal","--limit":"actionLimit","--next":"actionNext"},next:{"--production":"productionId","--project":"projectId","--goal":"goal","--limit":"actionLimit","--next":"actionNext"},resume:{"--production":"productionId","--operation":"operationId"},search:{"--query":"query","--project":"projectId","--group":"group","--family":"family","--limit":"limit","--next":"next"},describe:{"--tool":"tool","--project":"projectId","--reference":"schemaCursor"},groups:{"--project":"projectId"}};var NavigationCliCommands=new Set([...Object.keys(aliases),"capabilities"]);async function runNavigationCli(argv,stdin,call){const kind=argv[0]==="capabilities"?argv[1]?.startsWith("--")||!argv[1]?"groups":argv[1]:argv[0];const operation=argv[0]==="capabilities"?{groups:"studio.capability.groups",search:"studio.capability.search",describe:"studio.capability.describe"}[kind]:aliases[kind];const offset=argv[0]==="capabilities"&&argv[1]===kind?2:1;if(!operation||!fields[kind])throw Error("INVALID_INPUT");const forwarded=["call",operation],body={},seen=new Set;let input;for(let i=offset;i<argv.length;i+=2){const flag=argv[i],value=argv[i+1];if(!value||value.startsWith("--")||seen.has(flag))throw Error("INVALID_INPUT");seen.add(flag);if(auth.has(flag))forwarded.push(flag,value);else if(flag==="--input")input=value;else{const key=fields[kind][flag];if(!key)throw Error("INVALID_INPUT");body[key]=flag==="--limit"?Number(value):value}}if(input&&Object.keys(body).length)throw Error("INVALID_INPUT");forwarded.push("--input",input??"-");const generated=async function*(){yield Buffer.from(JSON.stringify(body))};return call(forwarded,input?stdin:generated())}import{randomBytes,randomUUID,createHash,timingSafeEqual}from"node:crypto";import{createServer}from"node:http";import{join}from"node:path";async function accountSignals(timeout,run){const cancelled=new AbortController,signal=AbortSignal.any([AbortSignal.timeout(timeout),cancelled.signal]);const stop=()=>cancelled.abort();process.once("SIGINT",stop);process.once("SIGTERM",stop);try{return await run(signal)}finally{process.off("SIGINT",stop);process.off("SIGTERM",stop)}}async function runAccountLogin(argv,environment,hooks={}){const options=new Map;for(let i=1;i<argv.length;i+=2){const key=argv[i],value=argv[i+1];if(!key||!["--server","--browser","--timeout-ms"].includes(key)||!value||value.startsWith("--")||options.has(key))accountError("ACCOUNT_LOGIN_INPUT_INVALID");options.set(key,value)}const configured=options.get("--server")??environment.NATIVESTUDIO_STUDIO_ORIGIN;if(!configured)return{exitCode:2,output:{semanticStatus:"NEEDS_INPUT",error:{code:"ACCOUNT_SERVER_REQUIRED",outcome:"NO_WRITE"},nextSteps:["nvs login --server <Studio-origin> (no Project required)"]}};const origin=accountServerOrigin(configured),browser=options.get("--browser")??"auto",timeout=options.get("--timeout-ms")??"180000";if(!["auto","manual"].includes(browser)||!/^\d+$/.test(timeout)||Number(timeout)<1e3||Number(timeout)>3e5)accountError("ACCOUNT_LOGIN_INPUT_INVALID");const root=await clientHome(environment,true);return withAccountLock(root,()=>accountSignals(Number(timeout),async signal=>{if((await readAccount(root))?.state==="REVOKE_PENDING")accountError("ACCOUNT_LOGOUT_OUTCOME_UNKNOWN","UNKNOWN");const client=new NativeStudioAccountClient({serverOrigin:origin});await client.metadata(signal);const verifier=randomBytes(32).toString("base64url"),state=randomBytes(32).toString("base64url"),path="/account-callback/"+randomUUID();let finish,receiving=false,sent=false;const callback=new Promise(done=>{finish=done});const server=createServer({maxHeaderSize:8192,headersTimeout:5e3,requestTimeout:5e3},(req,res)=>{res.setHeader("cache-control","no-store");res.setHeader("content-type","text/plain; charset=utf-8");res.setHeader("x-content-type-options","nosniff");const address=server.address(),host=address&&typeof address!=="string"?`127.0.0.1:${address.port}`:"";if(receiving||req.method!=="GET"||req.headers.host!==host||req.headers.origin||!req.url||!req.url.startsWith(path+"?")||req.url.length>2048){res.writeHead(400).end("Invalid account callback.");return}const url=new URL(req.url,`http://${host}`),received=url.searchParams.get("state");const keys=[...url.searchParams.keys()];if(url.pathname!==path||new Set(keys).size!==keys.length||keys.some(k=>!["state","iss","code","error"].includes(k))||!received||Buffer.byteLength(received)!==Buffer.byteLength(state)||!timingSafeEqual(Buffer.from(received),Buffer.from(state))||url.searchParams.get("iss")!==origin||(url.searchParams.has("error")?url.searchParams.get("error")!=="access_denied"||url.searchParams.has("code"):!/^[A-Za-z0-9_-]{43}$/.test(url.searchParams.get("code")??""))){res.writeHead(400).end("Invalid account callback.");return}receiving=true;res.end("Account confirmation received. Return to NativeStudio CLI.");finish(url.searchParams.get("code"))});server.maxConnections=8;const expired=()=>finish(null);signal.addEventListener("abort",expired,{once:true});const attempt=join(root,"account-login-attempt.json");let attemptFile;try{await new Promise((done,fail)=>{server.once("error",fail);server.listen(0,"127.0.0.1",done)});const address=server.address();if(!address||typeof address==="string")throw Error();const redirectUri=`http://127.0.0.1:${address.port}${path}`;const started=await client.start({redirectUri,state,codeChallenge:createHash("sha256").update(verifier).digest("base64url")},signal);const url=`${origin}/cli-authorize?requestId=${started.requestId}`;signal.throwIfAborted();if(hooks.authorize)await hooks.authorize(url,signal);else{process.stderr.write(`CLI account login request: ${started.requestId}
2
- `);if(browser==="manual")loginLink(url);else await openLoginBrowser(url,signal)}const code=await callback;if(!code)accountError(signal.aborted?signal.reason?.name==="TimeoutError"?"ACCOUNT_LOGIN_TIMED_OUT":"ACCOUNT_LOGIN_CANCELLED":"ACCOUNT_LOGIN_DENIED");const marker={version:1,serverOrigin:origin,requestId:started.requestId,state:"EXCHANGE_UNRESOLVED"};attemptFile=join(root,`account-login-attempt-${started.requestId}.json`);await write(attemptFile,JSON.stringify(marker),true);await write(attempt,JSON.stringify(marker));signal.throwIfAborted();sent=true;const session=await client.exchange({requestId:started.requestId,redirectUri,code,codeVerifier:verifier},signal);if(Date.parse(session.expiresAt)<=Date.now()||Date.parse(session.expiresAt)>Date.now()+36e5+3e4)accountError("ACCOUNT_SESSION_INVALID","UNKNOWN");await saveAccount(root,{version:1,epoch:randomUUID(),state:"ACTIVE",serverOrigin:origin,accessToken:session.accessToken,expiresAt:session.expiresAt,principalId:session.account.principalId,workspaceId:null,projectId:null});await write(attempt,JSON.stringify({...marker,state:"COMPLETED"}));await write(attemptFile,JSON.stringify({...marker,state:"COMPLETED"}));return{exitCode:0,output:{semanticStatus:"SUCCESS",authenticated:true,credentialPurpose:"CLI_ACCOUNT",serverOrigin:origin,expiresAt:session.expiresAt,account:session.account,nextSteps:["nvs workspaces","nvs workspace --id <workspace-id>","nvs projects"]}}}catch(error){if(sent){if(error instanceof NativeStudioSdkError&&error.outcome!=="UNKNOWN"){await write(attempt,JSON.stringify({version:1,state:"REJECTED"}));if(attemptFile)await write(attemptFile,JSON.stringify({version:1,state:"REJECTED"}));throw error}accountError("ACCOUNT_LOGIN_OUTCOME_UNKNOWN","UNKNOWN")}if(error instanceof NativeStudioSdkError&&error.outcome==="UNKNOWN")accountError("ACCOUNT_LOGIN_OUTCOME_UNKNOWN","UNKNOWN");if(signal.aborted)accountError(signal.reason?.name==="TimeoutError"?"ACCOUNT_LOGIN_TIMED_OUT":"ACCOUNT_LOGIN_CANCELLED");throw error}finally{signal.removeEventListener("abort",expired);server.closeAllConnections();await new Promise(done=>server.close(()=>done()))}}))}import{randomUUID as randomUUID2}from"node:crypto";import{z}from"zod";var AccountCommands=new Set(["whoami","workspaces","workspace","projects","project","logout"]);async function runAccountCommand(argv,environment){const command=argv[0],options=new Map;for(let i=1;i<argv.length;i+=2){const key=argv[i],value=argv[i+1];if(!key||!["--id","--limit","--next"].includes(key)||!value||value.startsWith("--")||options.has(key))accountError("ACCOUNT_COMMAND_INPUT_INVALID");options.set(key,value)}if(["workspace","project"].includes(command??"")?options.size!==1||!options.has("--id"):command==="projects"?options.has("--id"):options.size!==0)accountError("ACCOUNT_COMMAND_INPUT_INVALID");const root=await clientHome(environment,true);return withAccountLock(root,()=>accountSignals(15e3,async signal=>{const stored=await readAccount(root);if(command==="logout"){if(!stored||stored.state==="SIGNED_OUT")return{exitCode:0,output:{semanticStatus:"SUCCESS",authenticated:false,changed:false}};const client2=new NativeStudioAccountClient({serverOrigin:stored.serverOrigin,accessToken:stored.accessToken});const pending={...stored,state:"REVOKE_PENDING",workspaceId:null,projectId:null};await saveAccount(root,pending);try{await client2.logout(signal);await saveAccount(root,{...pending,state:"SIGNED_OUT",accessToken:null})}catch{accountError("ACCOUNT_LOGOUT_OUTCOME_UNKNOWN","UNKNOWN")}return{exitCode:0,output:{semanticStatus:"SUCCESS",authenticated:false,changed:true,nextSteps:["nvs login --server <Studio-origin>"]}}}const account=requireAccount(stored),client=new NativeStudioAccountClient({serverOrigin:account.serverOrigin,accessToken:account.accessToken});if(command==="whoami"||command==="workspaces"||command==="workspace"){const value2=await client.me(signal);if(value2.account.principalId!==account.principalId)accountError("ACCOUNT_IDENTITY_MISMATCH");if(command==="workspace"){const id=z.uuid().parse(options.get("--id"));if(!value2.account.tenants.some(t=>t.id===id))accountError("WORKSPACE_NOT_AUTHORIZED");await saveAccount(root,{...account,workspaceId:id,projectId:null,epoch:randomUUID2()});return{exitCode:0,output:{semanticStatus:"SUCCESS",workspaceId:id,nextSteps:["nvs projects"]}}}return{exitCode:0,output:{semanticStatus:"SUCCESS",authenticated:true,credentialPurpose:"CLI_ACCOUNT",verification:"LIVE_NATIVE_ACCOUNT",...command==="workspaces"?{workspaces:value2.account.tenants}:{account:value2.account,workspaceId:account.workspaceId,projectId:account.projectId,expiresAt:account.expiresAt},nextSteps:["nvs workspace --id <workspace-id>"]}}}if(!account.workspaceId)accountError("WORKSPACE_SELECTION_REQUIRED");if(command==="projects"){const limit=options.has("--limit")?z.coerce.number().int().min(1).max(100).parse(options.get("--limit")):void 0;const value2=await client.projects({tenantId:account.workspaceId,limit,next:options.get("--next")},signal);if(value2.items.some(p=>p.tenantId!==account.workspaceId))accountError("ACCOUNT_RESPONSE_SCOPE_MISMATCH");return{exitCode:0,output:{semanticStatus:"SUCCESS",...value2,nextSteps:["nvs project --id <project-id>"]}}}if(command!=="project")accountError("ACCOUNT_COMMAND_INPUT_INVALID");const projectId=z.uuid().parse(options.get("--id")),value=await client.project({tenantId:account.workspaceId,projectId},signal);if(value.project.id!==projectId||value.project.tenantId!==account.workspaceId)accountError("ACCOUNT_RESPONSE_SCOPE_MISMATCH");if(value.project.lifecycle!=="ACTIVE")accountError("PROJECT_ARCHIVED");await saveAccount(root,{...account,projectId,epoch:randomUUID2()});return{exitCode:0,output:{semanticStatus:"SUCCESS",project:value.project,connectionPage:`${account.serverOrigin}/projects/${projectId}/settings`,nextSteps:["Open connectionPage, then explicitly authorize this Project using nvs connect.","nvs status"]}}}))}var exits={SUCCESS:0,ACCEPTED:0,INVALID_INPUT:2,NOT_FOUND:3,BLOCKED:4,CAPABILITY_UNAVAILABLE:4,REVISION_CONFLICT:5};async function runRemoteCli(argv,environment=process.env,stdin=process.stdin){try{if(argv[0]==="connect")return await(await import("./project-connect-6MH2QG6G.js")).runProjectConnect(argv,environment);if(argv[0]==="login"){if(argv.includes("--mcp-url")){const{runProjectConnect}=await import("./project-connect-6MH2QG6G.js");const result=await runProjectConnect(["connect",...argv.slice(1)],environment);return{...result,output:{...result.output,deprecated:{code:"PROJECT_AUTH_IS_CONNECT",replacement:"nvs connect --mcp-url <project-connection-url>",note:"This legacy spelling authorizes one project; it does not establish a CLI account session."}}}}return await runAccountLogin(argv,environment)}if(AccountCommands.has(argv[0]??""))return await runAccountCommand(argv,environment);if(argv.length===1&&argv[0]==="status")return await connectionStatus(environment);if(NavigationCliCommands.has(argv[0]??""))return await runNavigationCli(argv,stdin,(args2,input2)=>runRemoteCli(args2,environment,input2));if(["auth-start","auth-complete"].includes(argv[0]??""))return await(await import("./oauth-257CEUQH.js")).runOAuthCommand(argv,stdin);if(!argv.length||argv.length===1&&["help","--help"].includes(argv[0]))return{exitCode:0,output:{product:"NativeStudio CLI",start:["nvs login --server <Studio-origin> \u2014 sign in/register your account in the browser; no project required.","nvs workspaces; nvs workspace --id <id>; nvs projects; nvs project --id <id>","nvs connect --mcp-url <project-connection-url> (project authorization; read-only by default)","nvs status","nvs find --query <intent>"],navigation:["nvs capabilities","nvs overview --production <uuid>","nvs next --production <uuid>","nvs resume --production <uuid> --operation <op_original>"],agentConnection:{command:"nvs",args:["mcp"],note:"Uses the private saved connection; no token in Agent configuration."},commands:["login --server <Studio-origin> | whoami | logout \u2014 independent account session","workspaces | workspace --id <id> | projects [--limit <n>] [--next <cursor>] | project --id <id>","connect --mcp-url <project-connection-url> \u2014 project authorization after account sign-in","status","find --query <text> [--project <uuid>]","overview | next --production <uuid> [--goal <text>]","resume --production <uuid> --operation <op_original>","capabilities [groups | search --query <text> --group <group> | describe --tool <name>]","mcp \u2014 connect the Agent using the private saved connection","local help \u2014 installed Runtime, scoped local MCP, explicit exact-version updates"],advanced:["operations","mcp --profile <private-file> | --mcp-url <endpoint> --token-env <NAME>|--token-file <private-file>","call <operation> --input <file|-> --tenant <uuid> --token-env <NAME> --origin <https-origin>","call <operation> --input <file|-> --tenant <uuid> --token-file <private-file> --mcp-url <https-endpoint>","auth-start --profile <new-private-file> --mcp-url <resource> --callback <receiver-url>","auth-complete --profile <private-file> --input <callback-json-file|->","call <operation> --profile <private-file> --tenant <uuid> --input <file|->"],note:"No automatic write retry. Transport abort does not cancel native Jobs."}};const{NativeStudioAgentClient,sdkOperations}=await import("./src-7F6ZEU3U.js");if(argv.length===1&&argv[0]==="operations")return{exitCode:0,output:{operations:Object.entries(sdkOperations).map(([name2,spec])=>({name:name2,readOnly:spec.readOnly??null,http:spec.request!==null}))}};const[command,name,...args]=argv;if(command!=="call"||!name||!Object.hasOwn(sdkOperations,name))throw Error();const options=new Map;const allowed=["--input","--tenant","--origin","--mcp-url","--token-env","--token-file","--profile"];for(let i=0;i<args.length;i+=2){const key2=args[i],value=args[i+1];if(!key2||!allowed.includes(key2)||!value||value.startsWith("--")||options.has(key2))throw Error();options.set(key2,value)}await defaultConnection(options,environment,true);if(!options.has("--input")||!options.has("--tenant")||(options.has("--profile")?options.has("--origin")||options.has("--mcp-url")||options.has("--token-file")||options.has("--token-env"):options.has("--origin")===options.has("--mcp-url")))throw Error();const key=name;const input=await readInput(options.get("--input"),stdin);const profile=options.has("--profile")?await(await import("./oauth-257CEUQH.js")).profileAuthorization(options.get("--profile")):null;const authorization=profile?.authorization??await readCredential(options,environment);const tenantId=options.get("--tenant");let output;if(profile||options.has("--mcp-url")){const{connectRemoteMcp}=await import("./mcp-EIMXNRH3.js");const connection=await connectRemoteMcp(profile?.resource??options.get("--mcp-url"),authorization,tenantId);try{output=await connection.studio.call(key,input)}finally{await connection.close()}}else{const studio=new NativeStudioAgentClient({tenantId,baseUrl:options.get("--origin"),authorization:()=>authorization});output=await studio.call(key,input)}const status=output?.semanticStatus;return{exitCode:status?exits[status]??1:0,output}}catch(error){const e=error instanceof NativeStudioSdkError?error:null;const accountRecovery={ACCOUNT_LOGIN_OUTCOME_UNKNOWN:["Start a fresh nvs login --server <Studio-origin>; never replay the old exchange."],ACCOUNT_LOGOUT_OUTCOME_UNKNOWN:["Retry nvs logout explicitly; local account use remains locked."],ACCOUNT_LOGIN_REQUIRED:["nvs login --server <Studio-origin>"],ACCOUNT_SESSION_EXPIRED_OR_REVOKED:["nvs login --server <Studio-origin>"],WORKSPACE_SELECTION_REQUIRED:["nvs workspaces","nvs workspace --id <workspace-id>"],PROJECT_CONNECTION_ACCOUNT_MISMATCH:["nvs whoami","nvs workspaces","nvs project --id <project-id>","nvs connect --mcp-url <project-connection-url>"],ACCOUNT_PROJECT_SELECTION_REQUIRED:["nvs whoami","nvs workspace --id <workspace-id>","nvs project --id <project-id>"],PROJECT_AUTHORIZED_CONNECTION_NOT_SELECTED:["Authorization may exist. Inspect Web grants; select the intended account/project before creating a fresh connection."]};return{exitCode:e?exits[e.semanticStatus]??1:2,output:{semanticStatus:e?.semanticStatus??"INVALID_INPUT",error:{code:e?.code??"INVALID_INPUT",outcome:e?.outcome??"NO_WRITE"},...e&&accountRecovery[e.code]?{nextSteps:accountRecovery[e.code]}:{},...["PROJECT_CONNECTION_REQUIRED","OAUTH_OUTCOME_UNKNOWN"].includes(e?.code??"")?{nextSteps:["nvs connect --mcp-url <project-connection-url>","nvs help"]}:{}}}}}export{runRemoteCli};
1
+ import{loginLink,openLoginBrowser}from"./chunk-VDNNFVTZ.js";import{NativeStudioAccountClient,accountError,accountServerOrigin,clientHome,connectionStatus,defaultConnection,readAccount,requireAccount,saveAccount,withAccountLock}from"./chunk-C753RRRA.js";import"./chunk-GJ7BZJLW.js";import"./chunk-VPYAXWXY.js";import"./chunk-7S3DJ2QE.js";import"./chunk-PUNG4ND7.js";import{readCredential,readInput}from"./chunk-BVSTJQJI.js";import{write}from"./chunk-66CUOZVI.js";import{NativeStudioSdkError}from"./chunk-6NVIN2NI.js";var aliases={find:"studio.start",overview:"studio.navigate",next:"studio.navigate",resume:"operation.get"};var auth=new Set(["--tenant","--origin","--mcp-url","--profile","--token-env","--token-file"]);var fields={find:{"--query":"search","--project":"projectId","--limit":"limit","--next":"next","--attention":"attention"},overview:{"--production":"productionId","--project":"projectId","--goal":"goal","--limit":"actionLimit","--next":"actionNext"},next:{"--production":"productionId","--project":"projectId","--goal":"goal","--limit":"actionLimit","--next":"actionNext"},resume:{"--production":"productionId","--operation":"operationId"},search:{"--query":"query","--project":"projectId","--group":"group","--family":"family","--limit":"limit","--next":"next"},describe:{"--tool":"tool","--project":"projectId","--reference":"schemaCursor"},groups:{"--project":"projectId"}};var NavigationCliCommands=new Set([...Object.keys(aliases),"capabilities"]);async function runNavigationCli(argv,stdin,call){const kind=argv[0]==="capabilities"?argv[1]?.startsWith("--")||!argv[1]?"groups":argv[1]:argv[0];const operation=argv[0]==="capabilities"?{groups:"studio.capability.groups",search:"studio.capability.search",describe:"studio.capability.describe"}[kind]:aliases[kind];const offset=argv[0]==="capabilities"&&argv[1]===kind?2:1;if(!operation||!fields[kind])throw Error("INVALID_INPUT");const forwarded=["call",operation],body={},seen=new Set;let input;for(let i=offset;i<argv.length;i+=2){const flag=argv[i],value=argv[i+1];if(!value||value.startsWith("--")||seen.has(flag))throw Error("INVALID_INPUT");seen.add(flag);if(auth.has(flag))forwarded.push(flag,value);else if(flag==="--input")input=value;else{const key=fields[kind][flag];if(!key)throw Error("INVALID_INPUT");body[key]=flag==="--limit"?Number(value):value}}if(input&&Object.keys(body).length)throw Error("INVALID_INPUT");forwarded.push("--input",input??"-");const generated=async function*(){yield Buffer.from(JSON.stringify(body))};return call(forwarded,input?stdin:generated())}import{randomBytes,randomUUID,createHash,timingSafeEqual}from"node:crypto";import{createServer}from"node:http";import{join}from"node:path";async function accountSignals(timeout,run){const cancelled=new AbortController,signal=AbortSignal.any([AbortSignal.timeout(timeout),cancelled.signal]);const stop=()=>cancelled.abort();process.once("SIGINT",stop);process.once("SIGTERM",stop);try{return await run(signal)}finally{process.off("SIGINT",stop);process.off("SIGTERM",stop)}}async function runAccountLogin(argv,environment,hooks={}){const options=new Map;for(let i=1;i<argv.length;i+=2){const key=argv[i],value=argv[i+1];if(!key||!["--server","--browser","--timeout-ms"].includes(key)||!value||value.startsWith("--")||options.has(key))accountError("ACCOUNT_LOGIN_INPUT_INVALID");options.set(key,value)}const configured=options.get("--server")??environment.NATIVESTUDIO_STUDIO_ORIGIN;if(!configured)return{exitCode:2,output:{semanticStatus:"NEEDS_INPUT",error:{code:"ACCOUNT_SERVER_REQUIRED",outcome:"NO_WRITE"},nextSteps:["nvs login --server <Studio-origin> (no Project required)"]}};const origin=accountServerOrigin(configured),browser=options.get("--browser")??"auto",timeout=options.get("--timeout-ms")??"180000";if(!["auto","manual"].includes(browser)||!/^\d+$/.test(timeout)||Number(timeout)<1e3||Number(timeout)>3e5)accountError("ACCOUNT_LOGIN_INPUT_INVALID");const root=await clientHome(environment,true);return withAccountLock(root,()=>accountSignals(Number(timeout),async signal=>{if((await readAccount(root))?.state==="REVOKE_PENDING")accountError("ACCOUNT_LOGOUT_OUTCOME_UNKNOWN","UNKNOWN");const client=new NativeStudioAccountClient({serverOrigin:origin});await client.metadata(signal);const verifier=randomBytes(32).toString("base64url"),state=randomBytes(32).toString("base64url"),path="/account-callback/"+randomUUID();let finish,receiving=false,sent=false;const callback=new Promise(done=>{finish=done});const server=createServer({maxHeaderSize:8192,headersTimeout:5e3,requestTimeout:5e3},(req,res)=>{res.setHeader("cache-control","no-store");res.setHeader("content-type","text/plain; charset=utf-8");res.setHeader("x-content-type-options","nosniff");const address=server.address(),host=address&&typeof address!=="string"?`127.0.0.1:${address.port}`:"";if(receiving||req.method!=="GET"||req.headers.host!==host||req.headers.origin||!req.url||!req.url.startsWith(path+"?")||req.url.length>2048){res.writeHead(400).end("Invalid account callback.");return}const url=new URL(req.url,`http://${host}`),received=url.searchParams.get("state");const keys=[...url.searchParams.keys()];if(url.pathname!==path||new Set(keys).size!==keys.length||keys.some(k=>!["state","iss","code","error"].includes(k))||!received||Buffer.byteLength(received)!==Buffer.byteLength(state)||!timingSafeEqual(Buffer.from(received),Buffer.from(state))||url.searchParams.get("iss")!==origin||(url.searchParams.has("error")?url.searchParams.get("error")!=="access_denied"||url.searchParams.has("code"):!/^[A-Za-z0-9_-]{43}$/.test(url.searchParams.get("code")??""))){res.writeHead(400).end("Invalid account callback.");return}receiving=true;res.end("Account confirmation received. Return to NativeStudio CLI.");finish(url.searchParams.get("code"))});server.maxConnections=8;const expired=()=>finish(null);signal.addEventListener("abort",expired,{once:true});const attempt=join(root,"account-login-attempt.json");let attemptFile;try{await new Promise((done,fail)=>{server.once("error",fail);server.listen(0,"127.0.0.1",done)});const address=server.address();if(!address||typeof address==="string")throw Error();const redirectUri=`http://127.0.0.1:${address.port}${path}`;const started=await client.start({redirectUri,state,codeChallenge:createHash("sha256").update(verifier).digest("base64url")},signal);const url=`${origin}/cli-authorize?requestId=${started.requestId}`;signal.throwIfAborted();if(hooks.authorize)await hooks.authorize(url,signal);else{process.stderr.write(`CLI account login request: ${started.requestId}
2
+ `);if(browser==="manual")loginLink(url);else await openLoginBrowser(url,signal)}const code=await callback;if(!code)accountError(signal.aborted?signal.reason?.name==="TimeoutError"?"ACCOUNT_LOGIN_TIMED_OUT":"ACCOUNT_LOGIN_CANCELLED":"ACCOUNT_LOGIN_DENIED");const marker={version:1,serverOrigin:origin,requestId:started.requestId,state:"EXCHANGE_UNRESOLVED"};attemptFile=join(root,`account-login-attempt-${started.requestId}.json`);await write(attemptFile,JSON.stringify(marker),true);await write(attempt,JSON.stringify(marker));signal.throwIfAborted();sent=true;const session=await client.exchange({requestId:started.requestId,redirectUri,code,codeVerifier:verifier},signal);if(Date.parse(session.expiresAt)<=Date.now()||Date.parse(session.expiresAt)>Date.now()+36e5+3e4)accountError("ACCOUNT_SESSION_INVALID","UNKNOWN");await saveAccount(root,{version:1,epoch:randomUUID(),state:"ACTIVE",serverOrigin:origin,accessToken:session.accessToken,expiresAt:session.expiresAt,principalId:session.account.principalId,workspaceId:null,projectId:null});await write(attempt,JSON.stringify({...marker,state:"COMPLETED"}));await write(attemptFile,JSON.stringify({...marker,state:"COMPLETED"}));return{exitCode:0,output:{semanticStatus:"SUCCESS",authenticated:true,credentialPurpose:"CLI_ACCOUNT",serverOrigin:origin,expiresAt:session.expiresAt,account:session.account,nextSteps:["nvs workspaces","nvs workspace --id <workspace-id>","nvs projects"]}}}catch(error){if(sent){if(error instanceof NativeStudioSdkError&&error.outcome!=="UNKNOWN"){await write(attempt,JSON.stringify({version:1,state:"REJECTED"}));if(attemptFile)await write(attemptFile,JSON.stringify({version:1,state:"REJECTED"}));throw error}accountError("ACCOUNT_LOGIN_OUTCOME_UNKNOWN","UNKNOWN")}if(error instanceof NativeStudioSdkError&&error.outcome==="UNKNOWN")accountError("ACCOUNT_LOGIN_OUTCOME_UNKNOWN","UNKNOWN");if(signal.aborted)accountError(signal.reason?.name==="TimeoutError"?"ACCOUNT_LOGIN_TIMED_OUT":"ACCOUNT_LOGIN_CANCELLED");throw error}finally{signal.removeEventListener("abort",expired);server.closeAllConnections();await new Promise(done=>server.close(()=>done()))}}))}import{randomUUID as randomUUID2}from"node:crypto";import{z}from"zod";var AccountCommands=new Set(["whoami","workspaces","workspace","projects","project","logout"]);async function runAccountCommand(argv,environment){const command=argv[0],options=new Map;for(let i=1;i<argv.length;i+=2){const key=argv[i],value=argv[i+1];if(!key||!["--id","--limit","--next"].includes(key)||!value||value.startsWith("--")||options.has(key))accountError("ACCOUNT_COMMAND_INPUT_INVALID");options.set(key,value)}if(["workspace","project"].includes(command??"")?options.size!==1||!options.has("--id"):command==="projects"?options.has("--id"):options.size!==0)accountError("ACCOUNT_COMMAND_INPUT_INVALID");const root=await clientHome(environment,true);return withAccountLock(root,()=>accountSignals(15e3,async signal=>{const stored=await readAccount(root);if(command==="logout"){if(!stored||stored.state==="SIGNED_OUT")return{exitCode:0,output:{semanticStatus:"SUCCESS",authenticated:false,changed:false}};const client2=new NativeStudioAccountClient({serverOrigin:stored.serverOrigin,accessToken:stored.accessToken});const pending={...stored,state:"REVOKE_PENDING",workspaceId:null,projectId:null};await saveAccount(root,pending);try{await client2.logout(signal);await saveAccount(root,{...pending,state:"SIGNED_OUT",accessToken:null})}catch{accountError("ACCOUNT_LOGOUT_OUTCOME_UNKNOWN","UNKNOWN")}return{exitCode:0,output:{semanticStatus:"SUCCESS",authenticated:false,changed:true,nextSteps:["nvs login --server <Studio-origin>"]}}}const account=requireAccount(stored),client=new NativeStudioAccountClient({serverOrigin:account.serverOrigin,accessToken:account.accessToken});if(command==="whoami"||command==="workspaces"||command==="workspace"){const value2=await client.me(signal);if(value2.account.principalId!==account.principalId)accountError("ACCOUNT_IDENTITY_MISMATCH");if(command==="workspace"){const id=z.uuid().parse(options.get("--id"));if(!value2.account.tenants.some(t=>t.id===id))accountError("WORKSPACE_NOT_AUTHORIZED");await saveAccount(root,{...account,workspaceId:id,projectId:null,epoch:randomUUID2()});return{exitCode:0,output:{semanticStatus:"SUCCESS",workspaceId:id,nextSteps:["nvs projects"]}}}return{exitCode:0,output:{semanticStatus:"SUCCESS",authenticated:true,credentialPurpose:"CLI_ACCOUNT",verification:"LIVE_NATIVE_ACCOUNT",...command==="workspaces"?{workspaces:value2.account.tenants}:{account:value2.account,workspaceId:account.workspaceId,projectId:account.projectId,expiresAt:account.expiresAt},nextSteps:["nvs workspace --id <workspace-id>"]}}}if(!account.workspaceId)accountError("WORKSPACE_SELECTION_REQUIRED");if(command==="projects"){const limit=options.has("--limit")?z.coerce.number().int().min(1).max(100).parse(options.get("--limit")):void 0;const value2=await client.projects({tenantId:account.workspaceId,limit,next:options.get("--next")},signal);if(value2.items.some(p=>p.tenantId!==account.workspaceId))accountError("ACCOUNT_RESPONSE_SCOPE_MISMATCH");return{exitCode:0,output:{semanticStatus:"SUCCESS",...value2,nextSteps:["nvs project --id <project-id>"]}}}if(command!=="project")accountError("ACCOUNT_COMMAND_INPUT_INVALID");const projectId=z.uuid().parse(options.get("--id")),value=await client.project({tenantId:account.workspaceId,projectId},signal);if(value.project.id!==projectId||value.project.tenantId!==account.workspaceId)accountError("ACCOUNT_RESPONSE_SCOPE_MISMATCH");if(value.project.lifecycle!=="ACTIVE")accountError("PROJECT_ARCHIVED");await saveAccount(root,{...account,projectId,epoch:randomUUID2()});return{exitCode:0,output:{semanticStatus:"SUCCESS",project:value.project,connectionPage:`${account.serverOrigin}/projects/${projectId}/settings`,nextSteps:["Open connectionPage, then explicitly authorize this Project using nvs connect.","nvs status"]}}}))}var exits={SUCCESS:0,ACCEPTED:0,INVALID_INPUT:2,NOT_FOUND:3,BLOCKED:4,CAPABILITY_UNAVAILABLE:4,REVISION_CONFLICT:5};async function runRemoteCli(argv,environment=process.env,stdin=process.stdin){try{if(argv[0]==="connect")return await(await import("./project-connect-MXM7IY55.js")).runProjectConnect(argv,environment);if(argv[0]==="login"){if(argv.includes("--mcp-url")){const{runProjectConnect}=await import("./project-connect-MXM7IY55.js");const result=await runProjectConnect(["connect",...argv.slice(1)],environment);return{...result,output:{...result.output,deprecated:{code:"PROJECT_AUTH_IS_CONNECT",replacement:"nvs connect --mcp-url <project-connection-url>",note:"This legacy spelling authorizes one project; it does not establish a CLI account session."}}}}return await runAccountLogin(argv,environment)}if(AccountCommands.has(argv[0]??""))return await runAccountCommand(argv,environment);if(argv.length===1&&argv[0]==="status")return await connectionStatus(environment);if(NavigationCliCommands.has(argv[0]??""))return await runNavigationCli(argv,stdin,(args2,input2)=>runRemoteCli(args2,environment,input2));if(["auth-start","auth-complete"].includes(argv[0]??""))return await(await import("./oauth-F7EZGVME.js")).runOAuthCommand(argv,stdin);if(!argv.length||argv.length===1&&["help","--help"].includes(argv[0]))return{exitCode:0,output:{product:"NativeStudio CLI",start:["nvs login --server <Studio-origin> \u2014 sign in/register your account in the browser; no project required.","nvs workspaces; nvs workspace --id <id>; nvs projects; nvs project --id <id>","nvs connect --mcp-url <project-connection-url> (project authorization; read-only by default)","nvs status","nvs find --query <intent>"],navigation:["nvs capabilities","nvs overview --production <uuid>","nvs next --production <uuid>","nvs resume --production <uuid> --operation <op_original>"],agentConnection:{command:"nvs",args:["mcp"],note:"Uses the private saved connection; no token in Agent configuration."},commands:["login --server <Studio-origin> | whoami | logout \u2014 independent account session","workspaces | workspace --id <id> | projects [--limit <n>] [--next <cursor>] | project --id <id>","connect --mcp-url <project-connection-url> \u2014 project authorization after account sign-in","status","find --query <text> [--project <uuid>]","overview | next --production <uuid> [--goal <text>]","resume --production <uuid> --operation <op_original>","capabilities [groups | search --query <text> --group <group> | describe --tool <name>]","mcp \u2014 connect the Agent using the private saved connection","local help \u2014 installed Runtime, scoped local MCP, explicit exact-version updates"],advanced:["operations","mcp --profile <private-file> | --mcp-url <endpoint> --token-env <NAME>|--token-file <private-file>","call <operation> --input <file|-> --tenant <uuid> --token-env <NAME> --origin <https-origin>","call <operation> --input <file|-> --tenant <uuid> --token-file <private-file> --mcp-url <https-endpoint>","auth-start --profile <new-private-file> --mcp-url <resource> --callback <receiver-url>","auth-complete --profile <private-file> --input <callback-json-file|->","call <operation> --profile <private-file> --tenant <uuid> --input <file|->"],note:"No automatic write retry. Transport abort does not cancel native Jobs."}};const{NativeStudioAgentClient,sdkOperations}=await import("./src-7F6ZEU3U.js");if(argv.length===1&&argv[0]==="operations")return{exitCode:0,output:{operations:Object.entries(sdkOperations).map(([name2,spec])=>({name:name2,readOnly:spec.readOnly??null,http:spec.request!==null}))}};const[command,name,...args]=argv;if(command!=="call"||!name||!Object.hasOwn(sdkOperations,name))throw Error();const options=new Map;const allowed=["--input","--tenant","--origin","--mcp-url","--token-env","--token-file","--profile"];for(let i=0;i<args.length;i+=2){const key2=args[i],value=args[i+1];if(!key2||!allowed.includes(key2)||!value||value.startsWith("--")||options.has(key2))throw Error();options.set(key2,value)}await defaultConnection(options,environment,true);if(!options.has("--input")||!options.has("--tenant")||(options.has("--profile")?options.has("--origin")||options.has("--mcp-url")||options.has("--token-file")||options.has("--token-env"):options.has("--origin")===options.has("--mcp-url")))throw Error();const key=name;const input=await readInput(options.get("--input"),stdin);const profile=options.has("--profile")?await(await import("./oauth-F7EZGVME.js")).profileAuthorization(options.get("--profile")):null;const authorization=profile?.authorization??await readCredential(options,environment);const tenantId=options.get("--tenant");let output;if(profile||options.has("--mcp-url")){const{connectRemoteMcp}=await import("./mcp-EIMXNRH3.js");const connection=await connectRemoteMcp(profile?.resource??options.get("--mcp-url"),authorization,tenantId);try{output=await connection.studio.call(key,input)}finally{await connection.close()}}else{const studio=new NativeStudioAgentClient({tenantId,baseUrl:options.get("--origin"),authorization:()=>authorization});output=await studio.call(key,input)}const status=output?.semanticStatus;return{exitCode:status?exits[status]??1:0,output}}catch(error){const e=error instanceof NativeStudioSdkError?error:null;const accountRecovery={ACCOUNT_LOGIN_OUTCOME_UNKNOWN:["Start a fresh nvs login --server <Studio-origin>; never replay the old exchange."],ACCOUNT_LOGOUT_OUTCOME_UNKNOWN:["Retry nvs logout explicitly; local account use remains locked."],ACCOUNT_LOGIN_REQUIRED:["nvs login --server <Studio-origin>"],ACCOUNT_SESSION_EXPIRED_OR_REVOKED:["nvs login --server <Studio-origin>"],WORKSPACE_SELECTION_REQUIRED:["nvs workspaces","nvs workspace --id <workspace-id>"],PROJECT_CONNECTION_ACCOUNT_MISMATCH:["nvs whoami","nvs workspaces","nvs project --id <project-id>","nvs connect --mcp-url <project-connection-url>"],ACCOUNT_PROJECT_SELECTION_REQUIRED:["nvs whoami","nvs workspace --id <workspace-id>","nvs project --id <project-id>"],PROJECT_AUTHORIZED_CONNECTION_NOT_SELECTED:["Authorization may exist. Inspect Web grants; select the intended account/project before creating a fresh connection."]};return{exitCode:e?exits[e.semanticStatus]??1:2,output:{semanticStatus:e?.semanticStatus??"INVALID_INPUT",error:{code:e?.code??"INVALID_INPUT",outcome:e?.outcome??"NO_WRITE"},...e&&accountRecovery[e.code]?{nextSteps:accountRecovery[e.code]}:{},...["PROJECT_CONNECTION_REQUIRED","OAUTH_OUTCOME_UNKNOWN"].includes(e?.code??"")?{nextSteps:["nvs connect --mcp-url <project-connection-url>","nvs help"]}:{}}}}}export{runRemoteCli};
@@ -0,0 +1 @@
1
+ import{profileAuthorization,runOAuthCommand}from"./chunk-C33A2DW4.js";import"./chunk-7S3DJ2QE.js";import"./chunk-PUNG4ND7.js";import"./chunk-BVSTJQJI.js";import"./chunk-66CUOZVI.js";import"./chunk-6NVIN2NI.js";export{profileAuthorization,runOAuthCommand};
@@ -1 +1 @@
1
- import{loginLink,openLoginBrowser}from"./chunk-VDNNFVTZ.js";import{clientHome,connectionError,projectConnection,readAccount,saveConnection}from"./chunk-RUMDDTON.js";import"./chunk-GJ7BZJLW.js";import"./chunk-VPYAXWXY.js";import{runOAuthCommand}from"./chunk-G42IS5JF.js";import{FileOAuthProvider}from"./chunk-MSOMVWKN.js";import"./chunk-PUNG4ND7.js";import"./chunk-25EDDZQA.js";import"./chunk-GIEYSDCG.js";import{NativeStudioSdkError}from"./chunk-6NVIN2NI.js";import{randomUUID,timingSafeEqual}from"node:crypto";import{createServer}from"node:http";import{join}from"node:path";async function runProjectConnect(argv,environment,hooks={}){if(argv[0]!=="connect")throw Error();const options=new Map;for(let i=1;i<argv.length;i+=2){const key=argv[i],value=argv[i+1];if(!key||!["--mcp-url","--scope","--timeout-ms","--browser"].includes(key)||!value||value.startsWith("--")||options.has(key))throw Error();options.set(key,value)}const resource=projectConnection(options.get("--mcp-url")??"");const scope=options.get("--scope")??"nvs:read";if(!["nvs:read","nvs:read nvs:write"].includes(scope))throw Error();const browser=options.get("--browser")??"auto";if(!["auto","manual"].includes(browser))throw Error();const timeout=options.get("--timeout-ms")??"180000";if(!/^\d+$/.test(timeout)||Number(timeout)<1e3||Number(timeout)>3e5)throw Error();const signal=AbortSignal.timeout(Number(timeout));const root=await clientHome(environment,true),profile=`profile-${randomUUID()}.json`;const path=join(root,profile),callbackPath=`/callback/${randomUUID()}`;const account=await readAccount(root);if(account&&(account.state!=="ACTIVE"||Date.parse(account.expiresAt)<=Date.now()||account.workspaceId!==resource.tenantId||account.projectId!==resource.projectId))connectionError("ACCOUNT_PROJECT_SELECTION_REQUIRED");let provider,receiving=false,redeeming=false;let finish;const callback=new Promise(resolve=>{finish=resolve});const server=createServer({maxHeaderSize:8192,requestTimeout:5e3,headersTimeout:5e3},(req,res)=>{res.setHeader("cache-control","no-store");res.setHeader("content-type","text/plain; charset=utf-8");res.setHeader("x-content-type-options","nosniff");const address=server.address();const host=address&&typeof address!=="string"?`127.0.0.1:${address.port}`:"";if(req.method!=="GET"||req.headers.host!==host||req.headers.origin||!req.url||req.url.length>4096||!req.url.startsWith(callbackPath+"?")||!provider||receiving){res.writeHead(400).end("Invalid authorization callback.");return}const url=new URL(req.url,`http://${host}`),state=url.searchParams.get("state");const expected=provider.data.state;const issuer=provider.data.discovery?.authorizationServerMetadata?.issuer??provider.data.discovery?.authorizationServerUrl;if(!state||Buffer.byteLength(state)!==Buffer.byteLength(expected)||!timingSafeEqual(Buffer.from(state),Buffer.from(expected))||url.searchParams.getAll("state").length!==1||url.pathname!==callbackPath||url.searchParams.getAll("iss").length!==1||url.searchParams.get("iss")!==issuer||(url.searchParams.has("error")?url.searchParams.has("code"):url.searchParams.getAll("code").length!==1||!url.searchParams.get("code"))){res.writeHead(400).end("Invalid authorization callback.");return}receiving=true;res.end("Authorization received. Return to NativeStudio CLI for the result.");finish(url.searchParams.has("error")?null:url.href)});server.maxConnections=8;const expired=()=>finish(null);signal.addEventListener("abort",expired,{once:true});try{await new Promise((resolve,reject)=>{server.once("error",reject);server.listen(0,"127.0.0.1",resolve)});const address=server.address();if(!address||typeof address==="string")throw Error();const redirect=`http://127.0.0.1:${address.port}${callbackPath}`;await runOAuthCommand(["auth-start","--profile",path,"--mcp-url",resource.resource,"--callback",redirect,"--scope",scope],empty(),signal);provider=await FileOAuthProvider.load(path);if(!provider.data.authorizationUrl)throw Error();signal.throwIfAborted();if(hooks.authorize)await hooks.authorize(provider.data.authorizationUrl,signal);else if(browser==="manual")loginLink(provider.data.authorizationUrl);else await openLoginBrowser(provider.data.authorizationUrl,signal);const received=await callback;if(!received)connectionError(signal.aborted?"LOGIN_TIMED_OUT":"LOGIN_DENIED");async function*input(){yield Buffer.from(JSON.stringify({callbackUrl:received}))}redeeming=true;await runOAuthCommand(["auth-complete","--profile",path,"--input","-"],input(),signal);const credentials=await saveConnection(root,profile,account?.epoch).catch(()=>{throw new NativeStudioSdkError("PROJECT_AUTHORIZED_CONNECTION_NOT_SELECTED","INTERNAL_OPERATIONAL_FAILURE","UNKNOWN")});return{exitCode:0,output:{semanticStatus:"SUCCESS",connected:true,credentialPurpose:"PROJECT_MCP",...resource,scope:credentials.scope,requestedScope:scope,nextSteps:["nvs status","nvs find --query <intent>","nvs mcp"]}}}catch(error){if(!redeeming&&signal.aborted)connectionError("LOGIN_TIMED_OUT");throw error}finally{signal.removeEventListener("abort",expired);server.closeAllConnections();await new Promise(resolve=>server.close(()=>resolve()))}}async function*empty(){}export{runProjectConnect};
1
+ import{loginLink,openLoginBrowser}from"./chunk-VDNNFVTZ.js";import{clientHome,connectionError,projectConnection,readAccount,saveConnection}from"./chunk-C753RRRA.js";import"./chunk-GJ7BZJLW.js";import"./chunk-VPYAXWXY.js";import{runOAuthCommand}from"./chunk-C33A2DW4.js";import{FileOAuthProvider}from"./chunk-7S3DJ2QE.js";import"./chunk-PUNG4ND7.js";import"./chunk-BVSTJQJI.js";import"./chunk-66CUOZVI.js";import{NativeStudioSdkError}from"./chunk-6NVIN2NI.js";import{randomUUID,timingSafeEqual}from"node:crypto";import{createServer}from"node:http";import{join}from"node:path";async function runProjectConnect(argv,environment,hooks={}){if(argv[0]!=="connect")throw Error();const options=new Map;for(let i=1;i<argv.length;i+=2){const key=argv[i],value=argv[i+1];if(!key||!["--mcp-url","--scope","--timeout-ms","--browser"].includes(key)||!value||value.startsWith("--")||options.has(key))throw Error();options.set(key,value)}const resource=projectConnection(options.get("--mcp-url")??"");const scope=options.get("--scope")??"nvs:read";if(!["nvs:read","nvs:read nvs:write"].includes(scope))throw Error();const browser=options.get("--browser")??"auto";if(!["auto","manual"].includes(browser))throw Error();const timeout=options.get("--timeout-ms")??"180000";if(!/^\d+$/.test(timeout)||Number(timeout)<1e3||Number(timeout)>3e5)throw Error();const signal=AbortSignal.timeout(Number(timeout));const root=await clientHome(environment,true),profile=`profile-${randomUUID()}.json`;const path=join(root,profile),callbackPath=`/callback/${randomUUID()}`;const account=await readAccount(root);if(account&&(account.state!=="ACTIVE"||Date.parse(account.expiresAt)<=Date.now()||account.workspaceId!==resource.tenantId||account.projectId!==resource.projectId))connectionError("ACCOUNT_PROJECT_SELECTION_REQUIRED");let provider,receiving=false,redeeming=false;let finish;const callback=new Promise(resolve=>{finish=resolve});const server=createServer({maxHeaderSize:8192,requestTimeout:5e3,headersTimeout:5e3},(req,res)=>{res.setHeader("cache-control","no-store");res.setHeader("content-type","text/plain; charset=utf-8");res.setHeader("x-content-type-options","nosniff");const address=server.address();const host=address&&typeof address!=="string"?`127.0.0.1:${address.port}`:"";if(req.method!=="GET"||req.headers.host!==host||req.headers.origin||!req.url||req.url.length>4096||!req.url.startsWith(callbackPath+"?")||!provider||receiving){res.writeHead(400).end("Invalid authorization callback.");return}const url=new URL(req.url,`http://${host}`),state=url.searchParams.get("state");const expected=provider.data.state;const issuer=provider.data.discovery?.authorizationServerMetadata?.issuer??provider.data.discovery?.authorizationServerUrl;if(!state||Buffer.byteLength(state)!==Buffer.byteLength(expected)||!timingSafeEqual(Buffer.from(state),Buffer.from(expected))||url.searchParams.getAll("state").length!==1||url.pathname!==callbackPath||url.searchParams.getAll("iss").length!==1||url.searchParams.get("iss")!==issuer||(url.searchParams.has("error")?url.searchParams.has("code"):url.searchParams.getAll("code").length!==1||!url.searchParams.get("code"))){res.writeHead(400).end("Invalid authorization callback.");return}receiving=true;res.end("Authorization received. Return to NativeStudio CLI for the result.");finish(url.searchParams.has("error")?null:url.href)});server.maxConnections=8;const expired=()=>finish(null);signal.addEventListener("abort",expired,{once:true});try{await new Promise((resolve,reject)=>{server.once("error",reject);server.listen(0,"127.0.0.1",resolve)});const address=server.address();if(!address||typeof address==="string")throw Error();const redirect=`http://127.0.0.1:${address.port}${callbackPath}`;await runOAuthCommand(["auth-start","--profile",path,"--mcp-url",resource.resource,"--callback",redirect,"--scope",scope],empty(),signal);provider=await FileOAuthProvider.load(path);if(!provider.data.authorizationUrl)throw Error();signal.throwIfAborted();if(hooks.authorize)await hooks.authorize(provider.data.authorizationUrl,signal);else if(browser==="manual")loginLink(provider.data.authorizationUrl);else await openLoginBrowser(provider.data.authorizationUrl,signal);const received=await callback;if(!received)connectionError(signal.aborted?"LOGIN_TIMED_OUT":"LOGIN_DENIED");async function*input(){yield Buffer.from(JSON.stringify({callbackUrl:received}))}redeeming=true;await runOAuthCommand(["auth-complete","--profile",path,"--input","-"],input(),signal);const credentials=await saveConnection(root,profile,account?.epoch).catch(()=>{throw new NativeStudioSdkError("PROJECT_AUTHORIZED_CONNECTION_NOT_SELECTED","INTERNAL_OPERATIONAL_FAILURE","UNKNOWN")});return{exitCode:0,output:{semanticStatus:"SUCCESS",connected:true,credentialPurpose:"PROJECT_MCP",...resource,scope:credentials.scope,requestedScope:scope,nextSteps:["nvs status","nvs find --query <intent>","nvs mcp"]}}}catch(error){if(!redeeming&&signal.aborted)connectionError("LOGIN_TIMED_OUT");throw error}finally{signal.removeEventListener("abort",expired);server.closeAllConnections();await new Promise(resolve=>server.close(()=>resolve()))}}async function*empty(){}export{runProjectConnect};
@@ -1 +1 @@
1
- import{defaultConnection}from"./chunk-RUMDDTON.js";import{StdioLines}from"./chunk-JFC6ZIGA.js";import"./chunk-GJ7BZJLW.js";import"./chunk-VPYAXWXY.js";import{FileOAuthProvider}from"./chunk-MSOMVWKN.js";import{secureEndpoint}from"./chunk-PUNG4ND7.js";import{readCredential}from"./chunk-25EDDZQA.js";import"./chunk-GIEYSDCG.js";import"./chunk-6NVIN2NI.js";async function stdioRelayConfig(argv,environment){const options=new Map;for(let i=0;i<argv.length;i+=2){const key=argv[i],value=argv[i+1];if(!key||!["--profile","--mcp-url","--token-env","--token-file","--timeout-ms","--discovery"].includes(key)||!value||value.startsWith("--")||options.has(key))throw Error();options.set(key,value)}await defaultConnection(options,environment,false);const discovery=options.get("--discovery");if(discovery!==void 0&&discovery!=="contextual-v1")throw Error();const timeout=options.get("--timeout-ms")??"30000";if(!/^\d+$/.test(timeout))throw Error();const timeoutMs=Number(timeout);if(!Number.isSafeInteger(timeoutMs)||timeoutMs<100||timeoutMs>3e5)throw Error();const profile=options.get("--profile");let endpoint,read;if(profile){if(options.has("--mcp-url")||options.has("--token-env")||options.has("--token-file"))throw Error();endpoint=secureEndpoint((await FileOAuthProvider.load(profile)).data.resource);read=async signal=>{const{profileAuthorization}=await import("./oauth-257CEUQH.js");const value=await profileAuthorization(profile,signal);if(secureEndpoint(value.resource).href!==endpoint.href)throw Error();return value.authorization}}else{if(!options.has("--mcp-url"))throw Error();endpoint=secureEndpoint(options.get("--mcp-url"));await readCredential(options,environment);read=()=>readCredential(options,environment)}let tail=Promise.resolve();return{endpoint,timeoutMs,...discovery?{discovery}:{},authorization(signal){const current=tail.then(()=>{signal.throwIfAborted();return read(signal)});tail=current.catch(()=>{});return current}}}import{isJSONRPCResultResponse}from"@modelcontextprotocol/client";var StdioContextualMenu=class{clear(){}request(request){return request}response(request,message){if(request.method!=="initialize"||!isJSONRPCResultResponse(message))return message;return{...message,result:{...message.result,instructions:["Navigation guidance: standard tools/list is stable. Use studio_start, studio_navigate and studio_capability_groups; describe returns a bounded public definition, not a tool-menu change. Follow native evidence and exact typed commands.",...typeof message.result.instructions==="string"?[message.result.instructions]:[]].join("\n")}}}};import{StreamableHTTPClientTransport,deserializeMessage,serializeMessage,isJSONRPCRequest,isJSONRPCNotification,isJSONRPCResultResponse as isJSONRPCResultResponse2,isJSONRPCErrorResponse}from"@modelcontextprotocol/client";var STDIO_RESPONSE_LIMIT=32*1024*1024;function stdioRelayFetch(config,shutdown){return async(input,init)=>{const target=new URL(input instanceof Request?input.url:String(input));if(target.href!==config.endpoint.href)throw Error();const signal=AbortSignal.any([shutdown,...init?.signal?[init.signal]:[],AbortSignal.timeout(config.timeoutMs)]);const authorization=await config.authorization(signal);signal.throwIfAborted();const headers=new Headers(init?.headers);headers.set("authorization",authorization);const response=await fetch(input,{...init,headers,signal,redirect:"error"});if(!response.body)return response;const declared=response.headers.get("content-length");if(declared&&(!/^\d+$/.test(declared)||Number(declared)>STDIO_RESPONSE_LIMIT)){await response.body.cancel();throw Error()}const reader=response.body.getReader();let size=0;const body=new ReadableStream({async pull(controller){try{const part=await reader.read();if(part.done){reader.releaseLock();controller.close();return}size+=part.value.byteLength;if(size>STDIO_RESPONSE_LIMIT){await reader.cancel();throw Error()}controller.enqueue(part.value)}catch(error){controller.error(error)}},async cancel(reason){await reader.cancel(reason);reader.releaseLock()}});return new Response(body,{status:response.status,statusText:response.statusText,headers:response.headers})}}var inputLimit=18*1024*1024;var concurrency=32;async function serveRemoteMcpStdio(config,input,output){const shutdown=new AbortController;const pending=new Map;const transport=new StreamableHTTPClientTransport(config.endpoint,{fetch:stdioRelayFetch(config,shutdown.signal),onInsufficientScope:"throw",reconnectionOptions:{maxRetries:0,maxReconnectionDelay:1,initialReconnectionDelay:1,reconnectionDelayGrowFactor:1}});const lines=new StdioLines(inputLimit);let queuedBytes=0,sends=0,stopped=false;let finish;const closed=new Promise(resolve=>{finish=resolve});const menu=config.discovery==="contextual-v1"?new StdioContextualMenu:void 0;function discard(id){const item=pending.get(id);if(item)clearTimeout(item.timer);pending.delete(id);return item}function write(message){if(stopped)return;const frame=serializeMessage(message);const bytes=Buffer.byteLength(frame);if(bytes>STDIO_RESPONSE_LIMIT||queuedBytes+bytes>STDIO_RESPONSE_LIMIT){void close(1);return}queuedBytes+=bytes;output.write(frame,error=>{queuedBytes-=bytes;if(error)void close(1)})}function fail(id,noWrite=false){const item=discard(id);item?.abort.abort();write({jsonrpc:"2.0",id,error:{code:-32603,message:"Remote MCP request unavailable",data:{semanticStatus:"INTERNAL_OPERATIONAL_FAILURE",outcome:noWrite?"NO_WRITE":"UNKNOWN"}}})}async function forward(message){if(isJSONRPCNotification(message)&&message.method==="notifications/cancelled"){const id=message.params?.requestId;if(typeof id==="string"||typeof id==="number")discard(id)?.abort.abort();if((transport.protocolVersion??"")>="2026-07-28")return}const request=isJSONRPCRequest(message)?message:null;if(request&&(pending.has(request.id)||pending.size>=concurrency||sends>=concurrency)){if(pending.has(request.id)){void close(2);return}fail(request.id,true);return}if(!request&&sends>=concurrency){void close(2);return}if(request){const version=request.method==="initialize"?request.params?.protocolVersion:request.params?._meta?.["io.modelcontextprotocol/protocolVersion"];if(typeof version==="string")transport.setProtocolVersion(version);const abort=new AbortController;const timer=setTimeout(()=>{if(pending.has(request.id))fail(request.id)},config.timeoutMs);timer.unref();pending.set(request.id,{abort,timer,request})}sends++;try{await transport.send(request&&menu?menu.request(request):message,request?{requestSignal:pending.get(request.id).abort.signal,onRequestStreamEnd:()=>{if(pending.has(request.id))fail(request.id)}}:{requestSignal:shutdown.signal})}catch{if(request&&pending.has(request.id))fail(request.id)}finally{sends--}}transport.onmessage=message=>{if(isJSONRPCResultResponse2(message)||isJSONRPCErrorResponse(message)){if(message.id===void 0)return;const item=discard(message.id);if(!item)return;if(item.request.method==="initialize"&&isJSONRPCResultResponse2(message)&&typeof message.result.protocolVersion==="string")transport.setProtocolVersion(message.result.protocolVersion);if(menu)message=menu.response(item.request,message)}if(isJSONRPCNotification(message)&&message.method==="notifications/tools/list_changed")menu?.clear();write(message)};transport.onerror=()=>{};function data(chunk){if(stopped)return;const bytes=Buffer.isBuffer(chunk)?chunk:Buffer.from(chunk);try{lines.push(bytes,line=>{void forward(deserializeMessage(new TextDecoder("utf-8",{fatal:true}).decode(line)));return!stopped})}catch{void close(2)}}function end(){void close(lines.incomplete?2:0)}function streamError(){void close(1)}async function close(code=0){if(stopped)return;stopped=true;shutdown.abort();for(const item of pending.values()){clearTimeout(item.timer);item.abort.abort()}pending.clear();menu?.clear();lines.clear();input.off("data",data).off("end",end).off("error",streamError);input.pause();output.off("error",streamError);try{await transport.close()}catch{code||=1}finish(code)}await transport.start();input.on("data",data).once("end",end).once("error",streamError);output.once("error",streamError);return{close,closed}}async function runMcpStdio(argv,environment){try{const config=await stdioRelayConfig(argv,environment);const handle=await serveRemoteMcpStdio(config,process.stdin,process.stdout);const stop=()=>{void handle.close()};process.once("SIGINT",stop);process.once("SIGTERM",stop);const code=await handle.closed;process.off("SIGINT",stop);process.off("SIGTERM",stop);if(code)process.stderr.write("NativeStudio MCP stdio connection failed.\n");return code}catch{process.stderr.write("NativeStudio MCP stdio configuration failed; run nvs status and nvs connect after account sign-in, or use explicit credentials.\n");return 2}}export{runMcpStdio};
1
+ import{defaultConnection}from"./chunk-C753RRRA.js";import{StdioLines}from"./chunk-JFC6ZIGA.js";import"./chunk-GJ7BZJLW.js";import"./chunk-VPYAXWXY.js";import{FileOAuthProvider}from"./chunk-7S3DJ2QE.js";import{secureEndpoint}from"./chunk-PUNG4ND7.js";import{readCredential}from"./chunk-BVSTJQJI.js";import"./chunk-66CUOZVI.js";import"./chunk-6NVIN2NI.js";async function stdioRelayConfig(argv,environment){const options=new Map;for(let i=0;i<argv.length;i+=2){const key=argv[i],value=argv[i+1];if(!key||!["--profile","--mcp-url","--token-env","--token-file","--timeout-ms","--discovery"].includes(key)||!value||value.startsWith("--")||options.has(key))throw Error();options.set(key,value)}await defaultConnection(options,environment,false);const discovery=options.get("--discovery");if(discovery!==void 0&&discovery!=="contextual-v1")throw Error();const timeout=options.get("--timeout-ms")??"30000";if(!/^\d+$/.test(timeout))throw Error();const timeoutMs=Number(timeout);if(!Number.isSafeInteger(timeoutMs)||timeoutMs<100||timeoutMs>3e5)throw Error();const profile=options.get("--profile");let endpoint,read;if(profile){if(options.has("--mcp-url")||options.has("--token-env")||options.has("--token-file"))throw Error();endpoint=secureEndpoint((await FileOAuthProvider.load(profile)).data.resource);read=async signal=>{const{profileAuthorization}=await import("./oauth-F7EZGVME.js");const value=await profileAuthorization(profile,signal);if(secureEndpoint(value.resource).href!==endpoint.href)throw Error();return value.authorization}}else{if(!options.has("--mcp-url"))throw Error();endpoint=secureEndpoint(options.get("--mcp-url"));await readCredential(options,environment);read=()=>readCredential(options,environment)}let tail=Promise.resolve();return{endpoint,timeoutMs,...discovery?{discovery}:{},authorization(signal){const current=tail.then(()=>{signal.throwIfAborted();return read(signal)});tail=current.catch(()=>{});return current}}}import{isJSONRPCResultResponse}from"@modelcontextprotocol/client";var StdioContextualMenu=class{clear(){}request(request){return request}response(request,message){if(request.method!=="initialize"||!isJSONRPCResultResponse(message))return message;return{...message,result:{...message.result,instructions:["Navigation guidance: standard tools/list is stable. Use studio_start, studio_navigate and studio_capability_groups; describe returns a bounded public definition, not a tool-menu change. Follow native evidence and exact typed commands.",...typeof message.result.instructions==="string"?[message.result.instructions]:[]].join("\n")}}}};import{StreamableHTTPClientTransport,deserializeMessage,serializeMessage,isJSONRPCRequest,isJSONRPCNotification,isJSONRPCResultResponse as isJSONRPCResultResponse2,isJSONRPCErrorResponse}from"@modelcontextprotocol/client";var STDIO_RESPONSE_LIMIT=32*1024*1024;function stdioRelayFetch(config,shutdown){return async(input,init)=>{const target=new URL(input instanceof Request?input.url:String(input));if(target.href!==config.endpoint.href)throw Error();const signal=AbortSignal.any([shutdown,...init?.signal?[init.signal]:[],AbortSignal.timeout(config.timeoutMs)]);const authorization=await config.authorization(signal);signal.throwIfAborted();const headers=new Headers(init?.headers);headers.set("authorization",authorization);const response=await fetch(input,{...init,headers,signal,redirect:"error"});if(!response.body)return response;const declared=response.headers.get("content-length");if(declared&&(!/^\d+$/.test(declared)||Number(declared)>STDIO_RESPONSE_LIMIT)){await response.body.cancel();throw Error()}const reader=response.body.getReader();let size=0;const body=new ReadableStream({async pull(controller){try{const part=await reader.read();if(part.done){reader.releaseLock();controller.close();return}size+=part.value.byteLength;if(size>STDIO_RESPONSE_LIMIT){await reader.cancel();throw Error()}controller.enqueue(part.value)}catch(error){controller.error(error)}},async cancel(reason){await reader.cancel(reason);reader.releaseLock()}});return new Response(body,{status:response.status,statusText:response.statusText,headers:response.headers})}}var inputLimit=18*1024*1024;var concurrency=32;async function serveRemoteMcpStdio(config,input,output){const shutdown=new AbortController;const pending=new Map;const transport=new StreamableHTTPClientTransport(config.endpoint,{fetch:stdioRelayFetch(config,shutdown.signal),onInsufficientScope:"throw",reconnectionOptions:{maxRetries:0,maxReconnectionDelay:1,initialReconnectionDelay:1,reconnectionDelayGrowFactor:1}});const lines=new StdioLines(inputLimit);let queuedBytes=0,sends=0,stopped=false;let finish;const closed=new Promise(resolve=>{finish=resolve});const menu=config.discovery==="contextual-v1"?new StdioContextualMenu:void 0;function discard(id){const item=pending.get(id);if(item)clearTimeout(item.timer);pending.delete(id);return item}function write(message){if(stopped)return;const frame=serializeMessage(message);const bytes=Buffer.byteLength(frame);if(bytes>STDIO_RESPONSE_LIMIT||queuedBytes+bytes>STDIO_RESPONSE_LIMIT){void close(1);return}queuedBytes+=bytes;output.write(frame,error=>{queuedBytes-=bytes;if(error)void close(1)})}function fail(id,noWrite=false){const item=discard(id);item?.abort.abort();write({jsonrpc:"2.0",id,error:{code:-32603,message:"Remote MCP request unavailable",data:{semanticStatus:"INTERNAL_OPERATIONAL_FAILURE",outcome:noWrite?"NO_WRITE":"UNKNOWN"}}})}async function forward(message){if(isJSONRPCNotification(message)&&message.method==="notifications/cancelled"){const id=message.params?.requestId;if(typeof id==="string"||typeof id==="number")discard(id)?.abort.abort();if((transport.protocolVersion??"")>="2026-07-28")return}const request=isJSONRPCRequest(message)?message:null;if(request&&(pending.has(request.id)||pending.size>=concurrency||sends>=concurrency)){if(pending.has(request.id)){void close(2);return}fail(request.id,true);return}if(!request&&sends>=concurrency){void close(2);return}if(request){const version=request.method==="initialize"?request.params?.protocolVersion:request.params?._meta?.["io.modelcontextprotocol/protocolVersion"];if(typeof version==="string")transport.setProtocolVersion(version);const abort=new AbortController;const timer=setTimeout(()=>{if(pending.has(request.id))fail(request.id)},config.timeoutMs);timer.unref();pending.set(request.id,{abort,timer,request})}sends++;try{await transport.send(request&&menu?menu.request(request):message,request?{requestSignal:pending.get(request.id).abort.signal,onRequestStreamEnd:()=>{if(pending.has(request.id))fail(request.id)}}:{requestSignal:shutdown.signal})}catch{if(request&&pending.has(request.id))fail(request.id)}finally{sends--}}transport.onmessage=message=>{if(isJSONRPCResultResponse2(message)||isJSONRPCErrorResponse(message)){if(message.id===void 0)return;const item=discard(message.id);if(!item)return;if(item.request.method==="initialize"&&isJSONRPCResultResponse2(message)&&typeof message.result.protocolVersion==="string")transport.setProtocolVersion(message.result.protocolVersion);if(menu)message=menu.response(item.request,message)}if(isJSONRPCNotification(message)&&message.method==="notifications/tools/list_changed")menu?.clear();write(message)};transport.onerror=()=>{};function data(chunk){if(stopped)return;const bytes=Buffer.isBuffer(chunk)?chunk:Buffer.from(chunk);try{lines.push(bytes,line=>{void forward(deserializeMessage(new TextDecoder("utf-8",{fatal:true}).decode(line)));return!stopped})}catch{void close(2)}}function end(){void close(lines.incomplete?2:0)}function streamError(){void close(1)}async function close(code=0){if(stopped)return;stopped=true;shutdown.abort();for(const item of pending.values()){clearTimeout(item.timer);item.abort.abort()}pending.clear();menu?.clear();lines.clear();input.off("data",data).off("end",end).off("error",streamError);input.pause();output.off("error",streamError);try{await transport.close()}catch{code||=1}finish(code)}await transport.start();input.on("data",data).once("end",end).once("error",streamError);output.once("error",streamError);return{close,closed}}async function runMcpStdio(argv,environment){try{const config=await stdioRelayConfig(argv,environment);const handle=await serveRemoteMcpStdio(config,process.stdin,process.stdout);const stop=()=>{void handle.close()};process.once("SIGINT",stop);process.once("SIGTERM",stop);const code=await handle.closed;process.off("SIGINT",stop);process.off("SIGTERM",stop);if(code)process.stderr.write("NativeStudio MCP stdio connection failed.\n");return code}catch{process.stderr.write("NativeStudio MCP stdio configuration failed; run nvs status and nvs connect after account sign-in, or use explicit credentials.\n");return 2}}export{runMcpStdio};
@@ -19,6 +19,16 @@ export declare const DesktopOwnerRequestSchema: z.ZodDiscriminatedUnion<[z.ZodOb
19
19
  reject: "reject";
20
20
  }>;
21
21
  version: z.ZodString;
22
+ }, z.core.$strict>, z.ZodObject<{
23
+ operation: z.ZodLiteral<"tools-prepare">;
24
+ version: z.ZodString;
25
+ choice: z.ZodDiscriminatedUnion<[z.ZodObject<{
26
+ mode: z.ZodLiteral<"MANAGED">;
27
+ }, z.core.$strict>, z.ZodObject<{
28
+ mode: z.ZodLiteral<"INSTALLED">;
29
+ ffmpeg: z.ZodString;
30
+ ffprobe: z.ZodString;
31
+ }, z.core.$strict>], "mode">;
22
32
  }, z.core.$strict>, z.ZodObject<{
23
33
  operation: z.ZodLiteral<"configure">;
24
34
  channelFingerprint: z.ZodString;
@@ -40,6 +50,10 @@ export declare const DesktopRuntimeStatusSchema: z.ZodObject<{
40
50
  }>;
41
51
  activeVersion: z.ZodNullable<z.ZodString>;
42
52
  phase: z.ZodString;
53
+ toolMode: z.ZodOptional<z.ZodNullable<z.ZodEnum<{
54
+ MANAGED: "MANAGED";
55
+ INSTALLED: "INSTALLED";
56
+ }>>>;
43
57
  }, z.core.$strict>;
44
58
  export declare const DesktopUpdateCheckSchema: z.ZodObject<{
45
59
  protocol: z.ZodLiteral<"NVS_DESKTOP_RUNTIME_UPDATES_V1">;
@@ -57,6 +71,10 @@ export declare const DesktopOwnerPlanSchema: z.ZodObject<{
57
71
  APPLY: "APPLY";
58
72
  RECOVER: "RECOVER";
59
73
  }>;
74
+ toolMode: z.ZodOptional<z.ZodEnum<{
75
+ MANAGED: "MANAGED";
76
+ INSTALLED: "INSTALLED";
77
+ }>>;
60
78
  planId: z.ZodUUID;
61
79
  fingerprint: z.ZodString;
62
80
  version: z.ZodString;
@@ -87,6 +105,10 @@ export declare const desktopOwnerResponses: {
87
105
  }>;
88
106
  activeVersion: z.ZodNullable<z.ZodString>;
89
107
  phase: z.ZodString;
108
+ toolMode: z.ZodOptional<z.ZodNullable<z.ZodEnum<{
109
+ MANAGED: "MANAGED";
110
+ INSTALLED: "INSTALLED";
111
+ }>>>;
90
112
  }, z.core.$strict>;
91
113
  readonly start: z.ZodObject<{
92
114
  protocol: z.ZodLiteral<"NVS_DESKTOP_RUNTIME_STATUS_V1">;
@@ -98,6 +120,10 @@ export declare const desktopOwnerResponses: {
98
120
  }>;
99
121
  activeVersion: z.ZodNullable<z.ZodString>;
100
122
  phase: z.ZodString;
123
+ toolMode: z.ZodOptional<z.ZodNullable<z.ZodEnum<{
124
+ MANAGED: "MANAGED";
125
+ INSTALLED: "INSTALLED";
126
+ }>>>;
101
127
  }, z.core.$strict>;
102
128
  readonly stop: z.ZodObject<{
103
129
  protocol: z.ZodLiteral<"NVS_DESKTOP_RUNTIME_STATUS_V1">;
@@ -109,6 +135,10 @@ export declare const desktopOwnerResponses: {
109
135
  }>;
110
136
  activeVersion: z.ZodNullable<z.ZodString>;
111
137
  phase: z.ZodString;
138
+ toolMode: z.ZodOptional<z.ZodNullable<z.ZodEnum<{
139
+ MANAGED: "MANAGED";
140
+ INSTALLED: "INSTALLED";
141
+ }>>>;
112
142
  }, z.core.$strict>;
113
143
  readonly configure: z.ZodObject<{
114
144
  protocol: z.ZodLiteral<"NVS_DESKTOP_RUNTIME_STATUS_V1">;
@@ -120,6 +150,10 @@ export declare const desktopOwnerResponses: {
120
150
  }>;
121
151
  activeVersion: z.ZodNullable<z.ZodString>;
122
152
  phase: z.ZodString;
153
+ toolMode: z.ZodOptional<z.ZodNullable<z.ZodEnum<{
154
+ MANAGED: "MANAGED";
155
+ INSTALLED: "INSTALLED";
156
+ }>>>;
123
157
  }, z.core.$strict>;
124
158
  readonly apply: z.ZodObject<{
125
159
  protocol: z.ZodLiteral<"NVS_DESKTOP_RUNTIME_STATUS_V1">;
@@ -131,6 +165,10 @@ export declare const desktopOwnerResponses: {
131
165
  }>;
132
166
  activeVersion: z.ZodNullable<z.ZodString>;
133
167
  phase: z.ZodString;
168
+ toolMode: z.ZodOptional<z.ZodNullable<z.ZodEnum<{
169
+ MANAGED: "MANAGED";
170
+ INSTALLED: "INSTALLED";
171
+ }>>>;
134
172
  }, z.core.$strict>;
135
173
  readonly recover: z.ZodObject<{
136
174
  protocol: z.ZodLiteral<"NVS_DESKTOP_RUNTIME_STATUS_V1">;
@@ -142,6 +180,10 @@ export declare const desktopOwnerResponses: {
142
180
  }>;
143
181
  activeVersion: z.ZodNullable<z.ZodString>;
144
182
  phase: z.ZodString;
183
+ toolMode: z.ZodOptional<z.ZodNullable<z.ZodEnum<{
184
+ MANAGED: "MANAGED";
185
+ INSTALLED: "INSTALLED";
186
+ }>>>;
145
187
  }, z.core.$strict>;
146
188
  readonly reject: z.ZodObject<{
147
189
  protocol: z.ZodLiteral<"NVS_DESKTOP_RUNTIME_STATUS_V1">;
@@ -153,6 +195,10 @@ export declare const desktopOwnerResponses: {
153
195
  }>;
154
196
  activeVersion: z.ZodNullable<z.ZodString>;
155
197
  phase: z.ZodString;
198
+ toolMode: z.ZodOptional<z.ZodNullable<z.ZodEnum<{
199
+ MANAGED: "MANAGED";
200
+ INSTALLED: "INSTALLED";
201
+ }>>>;
156
202
  }, z.core.$strict>;
157
203
  readonly check: z.ZodObject<{
158
204
  protocol: z.ZodLiteral<"NVS_DESKTOP_RUNTIME_UPDATES_V1">;
@@ -181,6 +227,29 @@ export declare const desktopOwnerResponses: {
181
227
  APPLY: "APPLY";
182
228
  RECOVER: "RECOVER";
183
229
  }>;
230
+ toolMode: z.ZodOptional<z.ZodEnum<{
231
+ MANAGED: "MANAGED";
232
+ INSTALLED: "INSTALLED";
233
+ }>>;
234
+ planId: z.ZodUUID;
235
+ fingerprint: z.ZodString;
236
+ version: z.ZodString;
237
+ previousVersion: z.ZodNullable<z.ZodString>;
238
+ expiresAt: z.ZodISODateTime;
239
+ phase: z.ZodString;
240
+ }, z.core.$strict>>;
241
+ }, z.core.$strict>;
242
+ readonly "tools-prepare": z.ZodObject<{
243
+ protocol: z.ZodLiteral<"NVS_DESKTOP_OWNER_PLAN_V1">;
244
+ plan: z.ZodNullable<z.ZodObject<{
245
+ kind: z.ZodEnum<{
246
+ APPLY: "APPLY";
247
+ RECOVER: "RECOVER";
248
+ }>;
249
+ toolMode: z.ZodOptional<z.ZodEnum<{
250
+ MANAGED: "MANAGED";
251
+ INSTALLED: "INSTALLED";
252
+ }>>;
184
253
  planId: z.ZodUUID;
185
254
  fingerprint: z.ZodString;
186
255
  version: z.ZodString;
@@ -196,6 +265,10 @@ export declare const desktopOwnerResponses: {
196
265
  APPLY: "APPLY";
197
266
  RECOVER: "RECOVER";
198
267
  }>;
268
+ toolMode: z.ZodOptional<z.ZodEnum<{
269
+ MANAGED: "MANAGED";
270
+ INSTALLED: "INSTALLED";
271
+ }>>;
199
272
  planId: z.ZodUUID;
200
273
  fingerprint: z.ZodString;
201
274
  version: z.ZodString;
@@ -9,6 +9,7 @@ export declare function runDesktopOwnerRequest(home: string, raw: unknown, bundl
9
9
  previousVersion: string | null;
10
10
  expiresAt: string;
11
11
  phase: string;
12
+ toolMode?: "MANAGED" | "INSTALLED" | undefined;
12
13
  } | null;
13
14
  } | {
14
15
  protocol: "NVS_DESKTOP_CHANNEL_INFO_V1";
@@ -21,6 +22,7 @@ export declare function runDesktopOwnerRequest(home: string, raw: unknown, bundl
21
22
  state: "UNAVAILABLE" | "RUNNING" | "INSTALL_REQUIRED" | "STOPPED";
22
23
  activeVersion: string | null;
23
24
  phase: string;
25
+ toolMode?: "MANAGED" | "INSTALLED" | null | undefined;
24
26
  } | {
25
27
  protocol: "NVS_DESKTOP_RUNTIME_UPDATES_V1";
26
28
  activeVersion: string | null;
@@ -104,7 +104,7 @@ export declare class LocalInstallationManager {
104
104
  notifications: boolean;
105
105
  rejectedVersions: string[];
106
106
  }>;
107
- prepare(version: string): Promise<{
107
+ prepare(version: string, choice?: unknown): Promise<{
108
108
  protocol: "NVS_LOCAL_UPDATE_PLAN_V1";
109
109
  planId: string;
110
110
  installationRevision: number;
@@ -151,6 +151,20 @@ export declare class LocalInstallationManager {
151
151
  fingerprint: string;
152
152
  createdAt: string;
153
153
  expiresAt: string;
154
+ trustFingerprint?: string | undefined;
155
+ toolSelection?: {
156
+ mode: "MANAGED";
157
+ } | {
158
+ ffmpeg: {
159
+ path: string;
160
+ digest: string;
161
+ };
162
+ ffprobe: {
163
+ path: string;
164
+ digest: string;
165
+ };
166
+ mode: "INSTALLED";
167
+ } | undefined;
154
168
  }>;
155
169
  plan(id: string): Promise<{
156
170
  protocol: "NVS_LOCAL_UPDATE_PLAN_V1";
@@ -199,6 +213,20 @@ export declare class LocalInstallationManager {
199
213
  fingerprint: string;
200
214
  createdAt: string;
201
215
  expiresAt: string;
216
+ trustFingerprint?: string | undefined;
217
+ toolSelection?: {
218
+ mode: "MANAGED";
219
+ } | {
220
+ ffmpeg: {
221
+ path: string;
222
+ digest: string;
223
+ };
224
+ ffprobe: {
225
+ path: string;
226
+ digest: string;
227
+ };
228
+ mode: "INSTALLED";
229
+ } | undefined;
202
230
  }>;
203
231
  private transition;
204
232
  apply(id: string, approval: string): Promise<{
@@ -340,7 +368,7 @@ export declare class LocalInstallationManager {
340
368
  runningVersion: string | null;
341
369
  availableVersion: string | null;
342
370
  executablePath: string | null;
343
- installOwner: "UNKNOWN" | "PROJECT" | "NPM_GLOBAL" | "NPX" | "MANAGED" | "TARBALL";
371
+ installOwner: "UNKNOWN" | "PROJECT" | "MANAGED" | "NPM_GLOBAL" | "NPX" | "TARBALL";
344
372
  }[];
345
373
  authorizedProjects: {
346
374
  tenantId: string;
@@ -263,9 +263,9 @@ export declare class LocalMcpTools {
263
263
  installOwner: z.ZodEnum<{
264
264
  UNKNOWN: "UNKNOWN";
265
265
  PROJECT: "PROJECT";
266
+ MANAGED: "MANAGED";
266
267
  NPM_GLOBAL: "NPM_GLOBAL";
267
268
  NPX: "NPX";
268
- MANAGED: "MANAGED";
269
269
  TARBALL: "TARBALL";
270
270
  }>;
271
271
  }, z.core.$strict>>;
@@ -381,9 +381,9 @@ export declare class LocalMcpTools {
381
381
  installOwner: z.ZodEnum<{
382
382
  UNKNOWN: "UNKNOWN";
383
383
  PROJECT: "PROJECT";
384
+ MANAGED: "MANAGED";
384
385
  NPM_GLOBAL: "NPM_GLOBAL";
385
386
  NPX: "NPX";
386
- MANAGED: "MANAGED";
387
387
  TARBALL: "TARBALL";
388
388
  }>;
389
389
  }, z.core.$strict>>;
@@ -54,6 +54,7 @@ export declare function catalogue(trust: ReleaseTrust, signal?: AbortSignal): Pr
54
54
  };
55
55
  fingerprint: string;
56
56
  origin: string;
57
+ trustFingerprint: string;
57
58
  }>;
58
59
  export declare function select(signed: LocalSignedCatalogue, version: string): {
59
60
  descriptor: {
@@ -8,4 +8,5 @@ export declare function runLocalManagement(home: string, operation: "status" | "
8
8
  state: "UNAVAILABLE" | "RUNNING" | "INSTALL_REQUIRED" | "STOPPED";
9
9
  activeVersion: string | null;
10
10
  phase: string;
11
+ toolMode?: "MANAGED" | "INSTALLED" | null | undefined;
11
12
  }>;
@@ -422,9 +422,9 @@ export declare const LocalVersionReportSchema: z.ZodObject<{
422
422
  installOwner: z.ZodEnum<{
423
423
  UNKNOWN: "UNKNOWN";
424
424
  PROJECT: "PROJECT";
425
+ MANAGED: "MANAGED";
425
426
  NPM_GLOBAL: "NPM_GLOBAL";
426
427
  NPX: "NPX";
427
- MANAGED: "MANAGED";
428
428
  TARBALL: "TARBALL";
429
429
  }>;
430
430
  }, z.core.$strict>;
@@ -454,9 +454,9 @@ export declare const LocalRuntimeStatusSchema: z.ZodObject<{
454
454
  installOwner: z.ZodEnum<{
455
455
  UNKNOWN: "UNKNOWN";
456
456
  PROJECT: "PROJECT";
457
+ MANAGED: "MANAGED";
457
458
  NPM_GLOBAL: "NPM_GLOBAL";
458
459
  NPX: "NPX";
459
- MANAGED: "MANAGED";
460
460
  TARBALL: "TARBALL";
461
461
  }>;
462
462
  }, z.core.$strict>>;
@@ -740,9 +740,9 @@ export declare const LocalIpcResponseSchema: z.ZodDiscriminatedUnion<[z.ZodObjec
740
740
  installOwner: z.ZodEnum<{
741
741
  UNKNOWN: "UNKNOWN";
742
742
  PROJECT: "PROJECT";
743
+ MANAGED: "MANAGED";
743
744
  NPM_GLOBAL: "NPM_GLOBAL";
744
745
  NPX: "NPX";
745
- MANAGED: "MANAGED";
746
746
  TARBALL: "TARBALL";
747
747
  }>;
748
748
  }, z.core.$strict>>;
@@ -217,12 +217,26 @@ export declare const LocalSignedCatalogueSchema: z.ZodObject<{
217
217
  }, z.core.$strict>;
218
218
  signature: z.ZodString;
219
219
  }, z.core.$strict>;
220
+ export declare const LocalToolChoiceSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{
221
+ mode: z.ZodLiteral<"MANAGED">;
222
+ }, z.core.$strict>, z.ZodObject<{
223
+ ffmpeg: z.ZodObject<{
224
+ path: z.ZodString;
225
+ digest: z.ZodString;
226
+ }, z.core.$strict>;
227
+ ffprobe: z.ZodObject<{
228
+ path: z.ZodString;
229
+ digest: z.ZodString;
230
+ }, z.core.$strict>;
231
+ mode: z.ZodLiteral<"INSTALLED">;
232
+ }, z.core.$strict>], "mode">;
220
233
  export declare const LocalUpdatePlanSchema: z.ZodObject<{
221
234
  protocol: z.ZodLiteral<"NVS_LOCAL_UPDATE_PLAN_V1">;
222
235
  planId: z.ZodPipe<z.ZodUUID, z.ZodTransform<string, string>>;
223
236
  installationRevision: z.ZodInt;
224
237
  runtimeRevision: z.ZodNullable<z.ZodInt>;
225
238
  catalogueFingerprint: z.ZodString;
239
+ trustFingerprint: z.ZodOptional<z.ZodString>;
226
240
  release: z.ZodObject<{
227
241
  descriptor: z.ZodObject<{
228
242
  protocol: z.ZodLiteral<"NVS_RUNTIME_DESCRIPTOR_V1">;
@@ -268,6 +282,19 @@ export declare const LocalUpdatePlanSchema: z.ZodObject<{
268
282
  }, z.core.$strict>;
269
283
  }, z.core.$strict>>;
270
284
  }, z.core.$strict>;
285
+ toolSelection: z.ZodOptional<z.ZodDiscriminatedUnion<[z.ZodObject<{
286
+ mode: z.ZodLiteral<"MANAGED">;
287
+ }, z.core.$strict>, z.ZodObject<{
288
+ ffmpeg: z.ZodObject<{
289
+ path: z.ZodString;
290
+ digest: z.ZodString;
291
+ }, z.core.$strict>;
292
+ ffprobe: z.ZodObject<{
293
+ path: z.ZodString;
294
+ digest: z.ZodString;
295
+ }, z.core.$strict>;
296
+ mode: z.ZodLiteral<"INSTALLED">;
297
+ }, z.core.$strict>], "mode">>;
271
298
  fingerprint: z.ZodString;
272
299
  createdAt: z.ZodISODateTime;
273
300
  expiresAt: z.ZodISODateTime;
@@ -317,3 +344,4 @@ export type LocalSessionConnector = z.infer<typeof LocalSessionConnectorSchema>;
317
344
  export type LocalRelease = z.infer<typeof LocalReleaseSchema>;
318
345
  export type LocalSignedCatalogue = z.infer<typeof LocalSignedCatalogueSchema>;
319
346
  export type LocalUpdatePlan = z.infer<typeof LocalUpdatePlanSchema>;
347
+ export type LocalToolChoice = z.infer<typeof LocalToolChoiceSchema>;
@@ -215,9 +215,9 @@ export declare const LocalMcpUpdateSchema: z.ZodObject<{
215
215
  installOwner: z.ZodEnum<{
216
216
  UNKNOWN: "UNKNOWN";
217
217
  PROJECT: "PROJECT";
218
+ MANAGED: "MANAGED";
218
219
  NPM_GLOBAL: "NPM_GLOBAL";
219
220
  NPX: "NPX";
220
- MANAGED: "MANAGED";
221
221
  TARBALL: "TARBALL";
222
222
  }>;
223
223
  }, z.core.$strict>>;
@@ -498,9 +498,9 @@ export declare const LocalMcpOutputSchemas: {
498
498
  installOwner: z.ZodEnum<{
499
499
  UNKNOWN: "UNKNOWN";
500
500
  PROJECT: "PROJECT";
501
+ MANAGED: "MANAGED";
501
502
  NPM_GLOBAL: "NPM_GLOBAL";
502
503
  NPX: "NPX";
503
- MANAGED: "MANAGED";
504
504
  TARBALL: "TARBALL";
505
505
  }>;
506
506
  }, z.core.$strict>>;
@@ -636,9 +636,9 @@ export declare const LocalMcpOutputSchemas: {
636
636
  installOwner: z.ZodEnum<{
637
637
  UNKNOWN: "UNKNOWN";
638
638
  PROJECT: "PROJECT";
639
+ MANAGED: "MANAGED";
639
640
  NPM_GLOBAL: "NPM_GLOBAL";
640
641
  NPX: "NPX";
641
- MANAGED: "MANAGED";
642
642
  TARBALL: "TARBALL";
643
643
  }>;
644
644
  }, z.core.$strict>>;
@@ -124,7 +124,7 @@ export declare class NativeStudioLocalRuntimeClient {
124
124
  runningVersion: string | null;
125
125
  availableVersion: string | null;
126
126
  executablePath: string | null;
127
- installOwner: "UNKNOWN" | "PROJECT" | "NPM_GLOBAL" | "NPX" | "MANAGED" | "TARBALL";
127
+ installOwner: "UNKNOWN" | "PROJECT" | "MANAGED" | "NPM_GLOBAL" | "NPX" | "TARBALL";
128
128
  }[];
129
129
  authorizedProjects: {
130
130
  tenantId: string;
@@ -361,7 +361,7 @@ export declare class NativeStudioLocalRuntimeClient {
361
361
  runningVersion: string | null;
362
362
  availableVersion: string | null;
363
363
  executablePath: string | null;
364
- installOwner: "UNKNOWN" | "PROJECT" | "NPM_GLOBAL" | "NPX" | "MANAGED" | "TARBALL";
364
+ installOwner: "UNKNOWN" | "PROJECT" | "MANAGED" | "NPM_GLOBAL" | "NPX" | "TARBALL";
365
365
  }[];
366
366
  authorizedProjects: {
367
367
  tenantId: string;
@@ -921,8 +921,8 @@ export declare class NativeStudioLocalRuntimeClient {
921
921
  }
922
922
  export { LocalSessionConnectorSchema } from "../contracts/local-execution/index.js";
923
923
  export { NativeStudioSdkError } from "./errors.js";
924
- export { LocalRuntimeDescriptorSchema, LocalManagementInventorySchema, LocalSignedCatalogueSchema, LocalReleaseSchema, LocalUpdatePlanSchema, LocalClientNextActionSchema, canonicalLocalJson, LocalSessionConnectorSchema as LocalConnectorSchema, } from "../contracts/local-execution/index.js";
925
- export type { LocalRelease, LocalSignedCatalogue, LocalUpdatePlan, LocalRuntimeDescriptor, LocalSessionConnector, } from "../contracts/local-execution/index.js";
924
+ export { LocalRuntimeDescriptorSchema, LocalManagementInventorySchema, LocalSignedCatalogueSchema, LocalReleaseSchema, LocalUpdatePlanSchema, LocalToolChoiceSchema, LocalClientNextActionSchema, canonicalLocalJson, LocalSessionConnectorSchema as LocalConnectorSchema, } from "../contracts/local-execution/index.js";
925
+ export type { LocalRelease, LocalSignedCatalogue, LocalUpdatePlan, LocalToolChoice, LocalRuntimeDescriptor, LocalSessionConnector, } from "../contracts/local-execution/index.js";
926
926
  export { NativeStudioLocalDeviceClient } from "./local-runtime/device-client.js";
927
927
  export { EnrollLocalDeviceSchema, GrantLocalDeviceSchema, RevokeLocalDeviceSchema, RevokeLocalDeviceGrantSchema, StartLocalPreviewSchema, LocalDeviceTransportConfigurationSchema, } from "../contracts/local-execution/index.js";
928
928
  export { LocalToolSelectionSchema, LocalWorkScopeSchema, } from "../contracts/local-execution/index.js";
package/dist/entry.js CHANGED
@@ -1,2 +1,2 @@
1
1
  #!/usr/bin/env node
2
- if(process.argv[2]==="local"){if(process.argv[3]==="mcp"){const{runLocalMcp}=await import("./_chunks/local-mcp-JLPXXIDW.js");process.exitCode=await runLocalMcp(process.argv.slice(4))}else{const{runLocalCli}=await import("./_chunks/local-main-SOERK22D.js");const result=await runLocalCli(process.argv.slice(3));process.stdout.write(JSON.stringify(result.output)+"\n");process.exitCode=result.exitCode}}else if(process.argv[2]==="mcp"){const{runMcpStdio}=await import("./_chunks/stdio-main-JEADWO7U.js");process.exitCode=await runMcpStdio(process.argv.slice(3),process.env)}else{const{runRemoteCli}=await import("./_chunks/main-4SNF5EKE.js");const result=await runRemoteCli(process.argv.slice(2));process.stdout.write(JSON.stringify(result.output)+"\n");process.exitCode=result.exitCode}
2
+ if(process.argv[2]==="local"){if(process.argv[3]==="mcp"){const{runLocalMcp}=await import("./_chunks/local-mcp-OLHBBVNN.js");process.exitCode=await runLocalMcp(process.argv.slice(4))}else{const{runLocalCli}=await import("./_chunks/local-main-NLFS74Q4.js");const result=await runLocalCli(process.argv.slice(3));process.stdout.write(JSON.stringify(result.output)+"\n");process.exitCode=result.exitCode}}else if(process.argv[2]==="mcp"){const{runMcpStdio}=await import("./_chunks/stdio-main-KOGQ5OWF.js");process.exitCode=await runMcpStdio(process.argv.slice(3),process.env)}else{const{runRemoteCli}=await import("./_chunks/main-VRIQTI6R.js");const result=await runRemoteCli(process.argv.slice(2));process.stdout.write(JSON.stringify(result.output)+"\n");process.exitCode=result.exitCode}