@nativestudio/cli 0.3.0-rc.20 → 0.3.0-rc.21

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 (57) hide show
  1. package/COMPATIBILITY.json +8 -8
  2. package/components/runtime.json +4 -4
  3. package/components/runtime.tgz +0 -0
  4. package/dist/_chunks/{chunk-APNZQZFB.js → chunk-2S7FI3HF.js} +1 -1
  5. package/dist/_chunks/{chunk-OSO6KRE2.js → chunk-3RNDOAQI.js} +1 -1
  6. package/dist/_chunks/{chunk-QK4XPVKT.js → chunk-4AD4PNUX.js} +1 -1
  7. package/dist/_chunks/{chunk-D74NHT4I.js → chunk-5Y7J2OYL.js} +1 -1
  8. package/dist/_chunks/{chunk-GLAF74UU.js → chunk-76E5R3OC.js} +1 -1
  9. package/dist/_chunks/{chunk-4PAVWOPA.js → chunk-7IVAYDU3.js} +1 -1
  10. package/dist/_chunks/{chunk-L3QA7FLZ.js → chunk-DMA53YVU.js} +1 -1
  11. package/dist/_chunks/{chunk-AFNJRZLJ.js → chunk-ETK7GYCB.js} +1 -1
  12. package/dist/_chunks/{chunk-ELUJ44BO.js → chunk-FFXSXE3G.js} +1 -1
  13. package/dist/_chunks/{chunk-HBDPYWMI.js → chunk-H4FH6STZ.js} +1 -1
  14. package/dist/_chunks/{chunk-6EZX2TRX.js → chunk-LDBXGRCQ.js} +1 -1
  15. package/dist/_chunks/{chunk-K35CWLDH.js → chunk-LTNJ45JP.js} +1 -1
  16. package/dist/_chunks/{chunk-MLZ3ZPGU.js → chunk-MZWEFYHE.js} +1 -1
  17. package/dist/_chunks/{chunk-ROGOASYF.js → chunk-PQCA4X5H.js} +1 -1
  18. package/dist/_chunks/{chunk-IYDHDLTR.js → chunk-SM2I7TJ3.js} +1 -1
  19. package/dist/_chunks/{chunk-FVY3PLG7.js → chunk-VXYZCCCQ.js} +1 -1
  20. package/dist/_chunks/{chunk-UYKCN5DU.js → chunk-VYCNG6TR.js} +1 -1
  21. package/dist/_chunks/{chunk-4M2SOMSN.js → chunk-WLQMICJN.js} +1 -1
  22. package/dist/_chunks/{chunk-NG4BDFEY.js → chunk-X5MVC46N.js} +1 -1
  23. package/dist/_chunks/{chunk-XUSVNPR5.js → chunk-X5PBZTKX.js} +1 -1
  24. package/dist/_chunks/{chunk-LBK42NHW.js → chunk-ZMJYBUS3.js} +1 -1
  25. package/dist/_chunks/{chunk-QE7O57PQ.js → chunk-ZYXHPTT2.js} +1 -1
  26. package/dist/_chunks/component-contract-2JHTRTOB.js +1 -0
  27. package/dist/_chunks/{component-preflight-WECLCZLF.js → component-preflight-6OWDQAZT.js} +1 -1
  28. package/dist/_chunks/{device-management-TLRUMZL5.js → device-management-JPS4HG34.js} +1 -1
  29. package/dist/_chunks/{device-preflight-C7FFUXI2.js → device-preflight-GTQ67H7C.js} +1 -1
  30. package/dist/_chunks/{devices-inventory-BZF53UAU.js → devices-inventory-E6ZLXCVR.js} +1 -1
  31. package/dist/_chunks/{devices-main-V3YHCB2C.js → devices-main-2BMCANKU.js} +1 -1
  32. package/dist/_chunks/{host-component-Q5IHRHRI.js → host-component-ZYQ5ETVL.js} +1 -1
  33. package/dist/_chunks/{host-help-7BGYR4ET.js → host-help-VNLA3YOV.js} +1 -1
  34. package/dist/_chunks/{host-main-JLIBRHC2.js → host-main-KLWW7R47.js} +1 -1
  35. package/dist/_chunks/{library-main-ATRFEAVN.js → library-main-3WWH7UYV.js} +1 -1
  36. package/dist/_chunks/{local-main-KTYCLHDA.js → local-main-5BW63USP.js} +1 -1
  37. package/dist/_chunks/{local-mcp-ISMU6ADI.js → local-mcp-AARKBDU5.js} +1 -1
  38. package/dist/_chunks/{main-MOZS2EK3.js → main-LGYJ3ZCN.js} +1 -1
  39. package/dist/_chunks/mcp-BLSK636Q.js +1 -0
  40. package/dist/_chunks/{observe-entry-E6DFHIMW.js → observe-entry-JVZAMB7N.js} +1 -1
  41. package/dist/_chunks/{remote-client-T75C45JO.js → remote-client-25Z65VJU.js} +1 -1
  42. package/dist/_chunks/{render-main-OGCO2LX4.js → render-main-6Z3DKCWL.js} +1 -1
  43. package/dist/_chunks/{source-import-55JJ26AA.js → source-import-PNMCMTK7.js} +1 -1
  44. package/dist/_chunks/{src-V2K52JDH.js → src-7HSJFRVQ.js} +1 -1
  45. package/dist/_chunks/{workspace-main-3P56DSEQ.js → workspace-main-QX5JGEMR.js} +1 -1
  46. package/dist/_types/contracts/interface/operation.d.ts +59 -0
  47. package/dist/_types/contracts/interface/production-snapshot.d.ts +25 -0
  48. package/dist/_types/contracts/interface/query.d.ts +25 -0
  49. package/dist/_types/contracts/lifecycle-event-projections.d.ts +2 -2
  50. package/dist/_types/contracts/navigation-context.d.ts +49 -1
  51. package/dist/_types/contracts/navigation.d.ts +1 -1
  52. package/dist/entry.js +1 -1
  53. package/dist/local-management.js +1 -1
  54. package/dist/local-navigation.js +1 -1
  55. package/package.json +1 -1
  56. package/dist/_chunks/component-contract-KXK7WIUI.js +0 -1
  57. package/dist/_chunks/mcp-M2SO3J2H.js +0 -1
@@ -1 +1 @@
1
- import{workspaceCaller}from"./chunk-NG4BDFEY.js";import{StdioLines}from"./chunk-JFC6ZIGA.js";import"./chunk-OSO6KRE2.js";import"./chunk-UYKCN5DU.js";import{LocalMcpTools,localTools}from"./chunk-QK4XPVKT.js";import{desktopDeviceConnector}from"./chunk-AFNJRZLJ.js";import"./chunk-IYDHDLTR.js";import{LocalMcpFailureSchema}from"./chunk-6EZX2TRX.js";import"./chunk-3TOXIJ7K.js";import"./chunk-QGK6G6YS.js";import"./chunk-GLAF74UU.js";import{localCliVersion}from"./chunk-2UYKJ6YN.js";import"./chunk-APNZQZFB.js";import"./chunk-7P2NA6TH.js";import"./chunk-27KI24GK.js";import"./chunk-7I7ARCY7.js";import"./chunk-DLW42PJ6.js";import"./chunk-WTJVS2VS.js";import"./chunk-KOCUZ3AE.js";import{NativeStudioSdkError}from"./chunk-TT7IA5HB.js";import{z}from"zod";import{homedir}from"node:os";import{join,resolve}from"node:path";import{deserializeMessage,SUPPORTED_PROTOCOL_VERSIONS,LATEST_PROTOCOL_VERSION,serializeMessage,isJSONRPCRequest,isJSONRPCNotification}from"@modelcontextprotocol/client";async function selectedConnector(home,env){const caller=await workspaceCaller(env);if(!caller)throw new NativeStudioSdkError("AUTHORIZATION_REQUIRED","BLOCKED","NO_WRITE");return desktopDeviceConnector(home,{origin:caller.serverOrigin,tenantId:caller.tenantId,principalId:caller.principalId})}async function serveLocalMcp(tools,input,output){const identity=await localCliVersion();const visible=[...tools.names??Object.keys(localTools).filter(name=>!name.startsWith("local_library_"))].sort(),pending=new Map;let initialized=false,closed=false;const frames=new StdioLines(65536);let finish;const ended=new Promise(resolve2=>{finish=resolve2});const send=message=>{if(closed)return;if(output.writableLength>512*1024){close(1);return}output.write(serializeMessage(message))};const error=(id,code,message)=>send({jsonrpc:"2.0",id,error:{code,message}});async function dispatch(r){if(pending.has(r.id)||pending.size>=8){error(r.id,-32e3,"Local request capacity unavailable");return}const abort=new AbortController;const timer=setTimeout(()=>abort.abort(),3e4);pending.set(r.id,abort);try{let result;if(r.method==="initialize"){if(initialized)throw Error();const v=r.params?.protocolVersion;if(typeof v!=="string")throw Error();const protocol=SUPPORTED_PROTOCOL_VERSIONS.includes(v)?v:LATEST_PROTOCOL_VERSION;initialized=true;result={protocolVersion:protocol,serverInfo:{name:"native-studio-local",version:identity.version},capabilities:{tools:{}},instructions:"Use local_navigate and local_capability_describe for scoped guidance. The standard tool list stays stable. Local tools inspect scoped mechanics. Use nvs mcp for workspace, Project and render business actions. Cloud owns native admission. Updates require a human CLI approval; MCP cannot stop or replace Runtime."}}else if(!initialized)throw Error();else if(r.method==="ping")result={};else if(r.method==="tools/list"){if(r.params?.cursor!==void 0)throw Error();result={tools:visible.map(name=>tools.schema(name))}}else if(r.method==="tools/call"){const name=r.params?.name;if(typeof name!=="string"||!visible.includes(name))throw Error();let data;try{data=await tools.call(name,r.params?.arguments??{},abort.signal)}catch(cause){const code=cause instanceof z.ZodError?"INVALID_INPUT":cause instanceof NativeStudioSdkError&&["AUTHORIZATION_REQUIRED","FORBIDDEN","LOCAL_RUNTIME_UNAVAILABLE"].includes(cause.code)?cause.code:"LOCAL_CAPABILITY_UNAVAILABLE";const failure=LocalMcpFailureSchema.parse({semanticStatus:code==="INVALID_INPUT"?"INVALID_INPUT":"BLOCKED",error:{code,outcome:"NO_WRITE"},nextActions:[{surface:"CLI",operation:"local.status",availability:"AVAILABLE",reason:code==="FORBIDDEN"||code==="AUTHORIZATION_REQUIRED"?"AUTHORIZATION_REQUIRED":"UNAVAILABLE"}]});send({jsonrpc:"2.0",id:r.id,result:{isError:true,content:[{type:"text",text:JSON.stringify(failure)}],structuredContent:failure}});return}result={content:[{type:"text",text:JSON.stringify(data)}],structuredContent:data}}else{error(r.id,-32601,"Local method unavailable");return}send({jsonrpc:"2.0",id:r.id,result})}catch{error(r.id,-32602,"Local capability unavailable or authorization required")}finally{clearTimeout(timer);pending.delete(r.id)}}function onData(b){try{frames.push(b,line=>{const message=deserializeMessage(line.toString());if(isJSONRPCRequest(message))void dispatch(message);else if(isJSONRPCNotification(message)){if(message.method==="notifications/cancelled"){const id=message.params?.requestId;if(typeof id==="string"||typeof id==="number")pending.get(id)?.abort()}}else throw Error();return!closed})}catch{close(1)}}function close(code=0){if(closed)return;closed=true;for(const abort of pending.values())abort.abort();input.off("data",onData);finish(code)}input.on("data",onData);input.once("end",()=>close(frames.incomplete?1:0));input.once("error",()=>close(1));output.once("error",()=>close(1));return{closed:ended,close:async()=>close()}}async function runLocalMcp(argv){try{const flags=new Map;const library=argv.includes("--with-library");if(argv.filter(k=>k==="--with-library").length>1)throw Error();argv=argv.filter(k=>k!=="--with-library");for(let i=0;i<argv.length;i+=2){const k=argv[i],v=argv[i+1];if(!k||!["--connector","--home"].includes(k)||!v||flags.has(k))throw Error();flags.set(k,v)}const home=resolve(flags.get("--home")??process.env.NATIVESTUDIO_CLIENT_HOME??join(homedir(),".nativestudio","client"));const env={...process.env,NATIVESTUDIO_CLIENT_HOME:home};const connector=flags.get("--connector")??await selectedConnector(home,env);const tools=await LocalMcpTools.open(resolve(connector),home,library);const service=await serveLocalMcp(tools,process.stdin,process.stdout);return await service.closed}catch{process.stderr.write("Local MCP needs a current device connector. Use nvs mcp for workspace, Project and render business tools.\n");return 2}}export{runLocalMcp,serveLocalMcp};
1
+ import{workspaceCaller}from"./chunk-X5MVC46N.js";import{StdioLines}from"./chunk-JFC6ZIGA.js";import"./chunk-3RNDOAQI.js";import"./chunk-VYCNG6TR.js";import{LocalMcpTools,localTools}from"./chunk-4AD4PNUX.js";import{desktopDeviceConnector}from"./chunk-ETK7GYCB.js";import"./chunk-SM2I7TJ3.js";import{LocalMcpFailureSchema}from"./chunk-LDBXGRCQ.js";import"./chunk-3TOXIJ7K.js";import"./chunk-QGK6G6YS.js";import"./chunk-76E5R3OC.js";import{localCliVersion}from"./chunk-2UYKJ6YN.js";import"./chunk-2S7FI3HF.js";import"./chunk-7P2NA6TH.js";import"./chunk-27KI24GK.js";import"./chunk-7I7ARCY7.js";import"./chunk-DLW42PJ6.js";import"./chunk-WTJVS2VS.js";import"./chunk-KOCUZ3AE.js";import{NativeStudioSdkError}from"./chunk-TT7IA5HB.js";import{z}from"zod";import{homedir}from"node:os";import{join,resolve}from"node:path";import{deserializeMessage,SUPPORTED_PROTOCOL_VERSIONS,LATEST_PROTOCOL_VERSION,serializeMessage,isJSONRPCRequest,isJSONRPCNotification}from"@modelcontextprotocol/client";async function selectedConnector(home,env){const caller=await workspaceCaller(env);if(!caller)throw new NativeStudioSdkError("AUTHORIZATION_REQUIRED","BLOCKED","NO_WRITE");return desktopDeviceConnector(home,{origin:caller.serverOrigin,tenantId:caller.tenantId,principalId:caller.principalId})}async function serveLocalMcp(tools,input,output){const identity=await localCliVersion();const visible=[...tools.names??Object.keys(localTools).filter(name=>!name.startsWith("local_library_"))].sort(),pending=new Map;let initialized=false,closed=false;const frames=new StdioLines(65536);let finish;const ended=new Promise(resolve2=>{finish=resolve2});const send=message=>{if(closed)return;if(output.writableLength>512*1024){close(1);return}output.write(serializeMessage(message))};const error=(id,code,message)=>send({jsonrpc:"2.0",id,error:{code,message}});async function dispatch(r){if(pending.has(r.id)||pending.size>=8){error(r.id,-32e3,"Local request capacity unavailable");return}const abort=new AbortController;const timer=setTimeout(()=>abort.abort(),3e4);pending.set(r.id,abort);try{let result;if(r.method==="initialize"){if(initialized)throw Error();const v=r.params?.protocolVersion;if(typeof v!=="string")throw Error();const protocol=SUPPORTED_PROTOCOL_VERSIONS.includes(v)?v:LATEST_PROTOCOL_VERSION;initialized=true;result={protocolVersion:protocol,serverInfo:{name:"native-studio-local",version:identity.version},capabilities:{tools:{}},instructions:"Use local_navigate and local_capability_describe for scoped guidance. The standard tool list stays stable. Local tools inspect scoped mechanics. Use nvs mcp for workspace, Project and render business actions. Cloud owns native admission. Updates require a human CLI approval; MCP cannot stop or replace Runtime."}}else if(!initialized)throw Error();else if(r.method==="ping")result={};else if(r.method==="tools/list"){if(r.params?.cursor!==void 0)throw Error();result={tools:visible.map(name=>tools.schema(name))}}else if(r.method==="tools/call"){const name=r.params?.name;if(typeof name!=="string"||!visible.includes(name))throw Error();let data;try{data=await tools.call(name,r.params?.arguments??{},abort.signal)}catch(cause){const code=cause instanceof z.ZodError?"INVALID_INPUT":cause instanceof NativeStudioSdkError&&["AUTHORIZATION_REQUIRED","FORBIDDEN","LOCAL_RUNTIME_UNAVAILABLE"].includes(cause.code)?cause.code:"LOCAL_CAPABILITY_UNAVAILABLE";const failure=LocalMcpFailureSchema.parse({semanticStatus:code==="INVALID_INPUT"?"INVALID_INPUT":"BLOCKED",error:{code,outcome:"NO_WRITE"},nextActions:[{surface:"CLI",operation:"local.status",availability:"AVAILABLE",reason:code==="FORBIDDEN"||code==="AUTHORIZATION_REQUIRED"?"AUTHORIZATION_REQUIRED":"UNAVAILABLE"}]});send({jsonrpc:"2.0",id:r.id,result:{isError:true,content:[{type:"text",text:JSON.stringify(failure)}],structuredContent:failure}});return}result={content:[{type:"text",text:JSON.stringify(data)}],structuredContent:data}}else{error(r.id,-32601,"Local method unavailable");return}send({jsonrpc:"2.0",id:r.id,result})}catch{error(r.id,-32602,"Local capability unavailable or authorization required")}finally{clearTimeout(timer);pending.delete(r.id)}}function onData(b){try{frames.push(b,line=>{const message=deserializeMessage(line.toString());if(isJSONRPCRequest(message))void dispatch(message);else if(isJSONRPCNotification(message)){if(message.method==="notifications/cancelled"){const id=message.params?.requestId;if(typeof id==="string"||typeof id==="number")pending.get(id)?.abort()}}else throw Error();return!closed})}catch{close(1)}}function close(code=0){if(closed)return;closed=true;for(const abort of pending.values())abort.abort();input.off("data",onData);finish(code)}input.on("data",onData);input.once("end",()=>close(frames.incomplete?1:0));input.once("error",()=>close(1));output.once("error",()=>close(1));return{closed:ended,close:async()=>close()}}async function runLocalMcp(argv){try{const flags=new Map;const library=argv.includes("--with-library");if(argv.filter(k=>k==="--with-library").length>1)throw Error();argv=argv.filter(k=>k!=="--with-library");for(let i=0;i<argv.length;i+=2){const k=argv[i],v=argv[i+1];if(!k||!["--connector","--home"].includes(k)||!v||flags.has(k))throw Error();flags.set(k,v)}const home=resolve(flags.get("--home")??process.env.NATIVESTUDIO_CLIENT_HOME??join(homedir(),".nativestudio","client"));const env={...process.env,NATIVESTUDIO_CLIENT_HOME:home};const connector=flags.get("--connector")??await selectedConnector(home,env);const tools=await LocalMcpTools.open(resolve(connector),home,library);const service=await serveLocalMcp(tools,process.stdin,process.stdout);return await service.closed}catch{process.stderr.write("Local MCP needs a current device connector. Use nvs mcp for workspace, Project and render business tools.\n");return 2}}export{runLocalMcp,serveLocalMcp};
@@ -1,2 +1,2 @@
1
1
  import{loginLink,openLoginBrowser}from"./chunk-OW6R4MAQ.js";import{readInput}from"./chunk-QGK6G6YS.js";import{NativeStudioAccountClient,accountError,accountServerOrigin,clientHome,connectionStatus,defaultConnection,readAccount,requireAccount,saveAccount,withAccountLock}from"./chunk-27KI24GK.js";import"./chunk-7I7ARCY7.js";import{write}from"./chunk-DLW42PJ6.js";import"./chunk-WTJVS2VS.js";import"./chunk-KOCUZ3AE.js";import{NativeStudioSdkError}from"./chunk-TT7IA5HB.js";var aliases={find:"studio.start",overview:"studio.navigate",next:"studio.navigate",resume:"operation.get",skill:"workspace.caller"};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"},skill:{}};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"&&kind!=="skill")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))};const result=await call(forwarded,input?stdin:generated());return kind==="skill"&&result.exitCode===0?{...result,output:result.output.skill}:result}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:account.workspaceId===id?account.projectId:null,epoch:account.workspaceId===id?account.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});return{exitCode:0,output:{semanticStatus:"SUCCESS",project:value.project,connectionPage:`${account.serverOrigin}/projects/${projectId}/settings`,nextSteps:["Use the existing workspace connection; run nvs connect if this workspace is not connected.","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("./connect-7TJDWXV4.js")).runConnect(argv,environment);if(argv[0]==="login")return await runAccountLogin(argv,environment);if(argv[0]==="render")return await(await import("./render-main-OGCO2LX4.js")).renderCommand(argv.slice(1),environment,stdin);if(argv[0]==="devices")return await(await import("./devices-main-V3YHCB2C.js")).devicesCommand(argv.slice(1),environment,stdin);if(argv[0]==="import")return await(await import("./source-import-55JJ26AA.js")).importSourceCommand(argv.slice(1),environment,stdin);if(AccountCommands.has(argv[0]??"")){const business=await(await import("./workspace-main-3P56DSEQ.js")).workspaceCommand(argv,environment);return business??await runAccountCommand(argv,environment)}if(argv.length===1&&argv[0]==="status")return await connectionStatus(environment);if(argv[0]==="series")return await(await import("./series-main-FBERVYWG.js")).runSeriesCli(argv.slice(1),stdin,(args2,input2)=>runRemoteCli(args2,environment,input2));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-RPME2XYB.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 (authorizes the selected workspace once; supports its Projects and devices)","nvs status","nvs skill \u2014 read the configured SKILL download URL through the existing connection","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 <workspace-connection-url>] \u2014 authorize the workspace once for its Projects and devices","status","observe --input <scope-json|-> [--max-polls <1..1000>] [--timeout-ms <1..1800000>] \u2014 bounded JSON Lines feedback/events; Ctrl-C ends observation only","skill \u2014 read the configured SKILL download URL/status; no automatic download","find --query <text> [--project <uuid>]","overview | next --production <uuid> [--goal <text>]","resume --production <uuid> --operation <op_original>","series help \u2014 list and read project series, publish, bind and recover original receipts","capabilities [groups | search --query <text> --group <group> | describe --tool <name>]","call <operation> with --capability-version <sha256> \u2014 require the described definition on member MCP","devices inventory [--device <uuid>] [--after <uuid>] [--limit <1..50>] [--mcp-url <workspace-url> --token-file <private-file>] \u2014 read Workspace device registration and connection facts; no project required","devices list --kind preview|final|library|<processor-kind> [--project <uuid>] [--device <uuid>] [--mcp-url <workspace-url> --token-file <private-file>] \u2014 read candidates for this Project task; connection alone does not imply eligibility","devices status --input <json|-> \u2014 read an owned node by deviceId on the saved tenant connection","devices enrollment-issue|enrollment-lookup --input <json|-> \u2014 issue or read the OAuth agent's original enrollment","devices enroll|revoke|receipt --input <json|-> \u2014 uses the saved tenant OAuth and original native command","render preview|final --production <uuid> --request <stable-uuid> [--project <uuid>] [--device <uuid>] [--validation-mode TENANT_TRUSTED_VALIDATOR] \u2014 tenant device only; saves original receipt","render eligibility --kind preview|final --production <uuid> [--project <uuid>] [--device <uuid>] \u2014 read current Production basis and device qualification","render receipt --kind preview|final --production <uuid> --request <original-uuid> [--project <uuid>] \u2014 query the original native admission without resubmitting","render receipt --input <private-json|-> \u2014 read a NVS_RENDER_RECEIPT_V1 handoff with the same authorized grant","render status|download --kind preview|final --production <uuid> --render <uuid> [--project <uuid>] [--output <file>]","mcp \u2014 connect the Agent using the private saved connection","local help \u2014 installed Runtime, scoped local MCP, explicit exact-version updates","host help \u2014 own an execution component, enroll through the existing MCP session and inspect per-action JSON schemas offline"],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|->","import project|original --input <intent.json|-> --file <media> --tenant <uuid> --origin <https-origin> --token-file <private-file>"],note:"No automatic write retry. Transport abort does not cancel native Jobs."}};const{CapabilityVersionSchema,NativeStudioMcpClient,sdkOperations,sdkMcpTools,sdkCarrierDifferences,assertCarrierCoverage}=await import("./src-V2K52JDH.js");if(argv.length===1&&argv[0]==="operations"){assertCarrierCoverage(sdkOperations,sdkCarrierDifferences);return{exitCode:0,output:{operations:Object.entries(sdkOperations).map(([name2,spec])=>({name:name2,readOnly:spec.readOnly??null,http:spec.request!==null,mcp:sdkMcpTools[name2],carrierDifference:Object.hasOwn(sdkCarrierDifferences,name2)?sdkCarrierDifferences[name2]:null}))}}}const[command,name,...args]=argv;if(command!=="call"||!name||!Object.hasOwn(sdkOperations,name))throw Error();if(name==="rough-cut.media-ticket"||name==="final-render.media-ticket")throw Error();const options=new Map;const allowed=["--input","--tenant","--origin","--mcp-url","--token-env","--token-file","--profile","--transport","--capability-version"];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)}if(!options.has("--input"))throw Error();const key=name;const capabilityVersion=CapabilityVersionSchema.optional().parse(options.get("--capability-version"));const httpOnly=sdkMcpTools[key]===null;const versionUnavailable=()=>new NativeStudioSdkError("CAPABILITY_UNAVAILABLE","CAPABILITY_UNAVAILABLE","NO_WRITE");if(capabilityVersion&&(httpOnly||options.has("--origin")||options.get("--transport")==="http"))throw versionUnavailable();const privateInput=["provider.configure","webhook.configure","webhook.secret.prepare"].includes(key);await defaultConnection(options,environment,true);const input=await readInput(options.get("--input"),stdin,privateInput);const output=await(await import("./remote-client-T75C45JO.js")).withRemoteClient(options,environment,httpOnly,studio=>{const command2=input;if(!capabilityVersion)return studio.call(key,command2);if(!(studio instanceof NativeStudioMcpClient))throw versionUnavailable();return studio.call(key,command2,{capabilityVersion})});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>"],CONNECTION_ACCOUNT_MISMATCH:["nvs whoami","nvs workspaces","nvs project --id <project-id>","nvs connect --mcp-url <workspace-connection-url>"],ACCOUNT_PROJECT_SELECTION_REQUIRED:["nvs whoami","nvs workspace --id <workspace-id>","nvs project --id <project-id>"],AUTHORIZED_CONNECTION_NOT_SELECTED:["Authorization may exist. Inspect Web grants; select the intended account/workspace 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?.issues.length?{issues:e.issues}:{},...e?.capabilityMismatch?{details:e.capabilityMismatch}:{}},...e&&accountRecovery[e.code]?{nextSteps:accountRecovery[e.code]}:{},...["TENANT_CONNECTION_REQUIRED","OAUTH_OUTCOME_UNKNOWN"].includes(e?.code??"")?{nextSteps:["nvs connect --mcp-url <workspace-connection-url>","nvs help"]}:{}}}}}export{runRemoteCli};
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:account.workspaceId===id?account.projectId:null,epoch:account.workspaceId===id?account.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});return{exitCode:0,output:{semanticStatus:"SUCCESS",project:value.project,connectionPage:`${account.serverOrigin}/projects/${projectId}/settings`,nextSteps:["Use the existing workspace connection; run nvs connect if this workspace is not connected.","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("./connect-7TJDWXV4.js")).runConnect(argv,environment);if(argv[0]==="login")return await runAccountLogin(argv,environment);if(argv[0]==="render")return await(await import("./render-main-6Z3DKCWL.js")).renderCommand(argv.slice(1),environment,stdin);if(argv[0]==="devices")return await(await import("./devices-main-2BMCANKU.js")).devicesCommand(argv.slice(1),environment,stdin);if(argv[0]==="import")return await(await import("./source-import-PNMCMTK7.js")).importSourceCommand(argv.slice(1),environment,stdin);if(AccountCommands.has(argv[0]??"")){const business=await(await import("./workspace-main-QX5JGEMR.js")).workspaceCommand(argv,environment);return business??await runAccountCommand(argv,environment)}if(argv.length===1&&argv[0]==="status")return await connectionStatus(environment);if(argv[0]==="series")return await(await import("./series-main-FBERVYWG.js")).runSeriesCli(argv.slice(1),stdin,(args2,input2)=>runRemoteCli(args2,environment,input2));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-RPME2XYB.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 (authorizes the selected workspace once; supports its Projects and devices)","nvs status","nvs skill \u2014 read the configured SKILL download URL through the existing connection","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 <workspace-connection-url>] \u2014 authorize the workspace once for its Projects and devices","status","observe --input <scope-json|-> [--max-polls <1..1000>] [--timeout-ms <1..1800000>] \u2014 bounded JSON Lines feedback/events; Ctrl-C ends observation only","skill \u2014 read the configured SKILL download URL/status; no automatic download","find --query <text> [--project <uuid>]","overview | next --production <uuid> [--goal <text>]","resume --production <uuid> --operation <op_original>","series help \u2014 list and read project series, publish, bind and recover original receipts","capabilities [groups | search --query <text> --group <group> | describe --tool <name>]","call <operation> with --capability-version <sha256> \u2014 require the described definition on member MCP","devices inventory [--device <uuid>] [--after <uuid>] [--limit <1..50>] [--mcp-url <workspace-url> --token-file <private-file>] \u2014 read Workspace device registration and connection facts; no project required","devices list --kind preview|final|library|<processor-kind> [--project <uuid>] [--device <uuid>] [--mcp-url <workspace-url> --token-file <private-file>] \u2014 read candidates for this Project task; connection alone does not imply eligibility","devices status --input <json|-> \u2014 read an owned node by deviceId on the saved tenant connection","devices enrollment-issue|enrollment-lookup --input <json|-> \u2014 issue or read the OAuth agent's original enrollment","devices enroll|revoke|receipt --input <json|-> \u2014 uses the saved tenant OAuth and original native command","render preview|final --production <uuid> --request <stable-uuid> [--project <uuid>] [--device <uuid>] [--validation-mode TENANT_TRUSTED_VALIDATOR] \u2014 tenant device only; saves original receipt","render eligibility --kind preview|final --production <uuid> [--project <uuid>] [--device <uuid>] \u2014 read current Production basis and device qualification","render receipt --kind preview|final --production <uuid> --request <original-uuid> [--project <uuid>] \u2014 query the original native admission without resubmitting","render receipt --input <private-json|-> \u2014 read a NVS_RENDER_RECEIPT_V1 handoff with the same authorized grant","render status|download --kind preview|final --production <uuid> --render <uuid> [--project <uuid>] [--output <file>]","mcp \u2014 connect the Agent using the private saved connection","local help \u2014 installed Runtime, scoped local MCP, explicit exact-version updates","host help \u2014 own an execution component, enroll through the existing MCP session and inspect per-action JSON schemas offline"],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|->","import project|original --input <intent.json|-> --file <media> --tenant <uuid> --origin <https-origin> --token-file <private-file>"],note:"No automatic write retry. Transport abort does not cancel native Jobs."}};const{CapabilityVersionSchema,NativeStudioMcpClient,sdkOperations,sdkMcpTools,sdkCarrierDifferences,assertCarrierCoverage}=await import("./src-7HSJFRVQ.js");if(argv.length===1&&argv[0]==="operations"){assertCarrierCoverage(sdkOperations,sdkCarrierDifferences);return{exitCode:0,output:{operations:Object.entries(sdkOperations).map(([name2,spec])=>({name:name2,readOnly:spec.readOnly??null,http:spec.request!==null,mcp:sdkMcpTools[name2],carrierDifference:Object.hasOwn(sdkCarrierDifferences,name2)?sdkCarrierDifferences[name2]:null}))}}}const[command,name,...args]=argv;if(command!=="call"||!name||!Object.hasOwn(sdkOperations,name))throw Error();if(name==="rough-cut.media-ticket"||name==="final-render.media-ticket")throw Error();const options=new Map;const allowed=["--input","--tenant","--origin","--mcp-url","--token-env","--token-file","--profile","--transport","--capability-version"];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)}if(!options.has("--input"))throw Error();const key=name;const capabilityVersion=CapabilityVersionSchema.optional().parse(options.get("--capability-version"));const httpOnly=sdkMcpTools[key]===null;const versionUnavailable=()=>new NativeStudioSdkError("CAPABILITY_UNAVAILABLE","CAPABILITY_UNAVAILABLE","NO_WRITE");if(capabilityVersion&&(httpOnly||options.has("--origin")||options.get("--transport")==="http"))throw versionUnavailable();const privateInput=["provider.configure","webhook.configure","webhook.secret.prepare"].includes(key);await defaultConnection(options,environment,true);const input=await readInput(options.get("--input"),stdin,privateInput);const output=await(await import("./remote-client-25Z65VJU.js")).withRemoteClient(options,environment,httpOnly,studio=>{const command2=input;if(!capabilityVersion)return studio.call(key,command2);if(!(studio instanceof NativeStudioMcpClient))throw versionUnavailable();return studio.call(key,command2,{capabilityVersion})});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>"],CONNECTION_ACCOUNT_MISMATCH:["nvs whoami","nvs workspaces","nvs project --id <project-id>","nvs connect --mcp-url <workspace-connection-url>"],ACCOUNT_PROJECT_SELECTION_REQUIRED:["nvs whoami","nvs workspace --id <workspace-id>","nvs project --id <project-id>"],AUTHORIZED_CONNECTION_NOT_SELECTED:["Authorization may exist. Inspect Web grants; select the intended account/workspace 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?.issues.length?{issues:e.issues}:{},...e?.capabilityMismatch?{details:e.capabilityMismatch}:{}},...e&&accountRecovery[e.code]?{nextSteps:accountRecovery[e.code]}:{},...["TENANT_CONNECTION_REQUIRED","OAUTH_OUTCOME_UNKNOWN"].includes(e?.code??"")?{nextSteps:["nvs connect --mcp-url <workspace-connection-url>","nvs help"]}:{}}}}}export{runRemoteCli};
@@ -0,0 +1 @@
1
+ import{connectRemoteMcp}from"./chunk-76E5R3OC.js";import"./chunk-2UYKJ6YN.js";import"./chunk-2S7FI3HF.js";import"./chunk-WTJVS2VS.js";import"./chunk-KOCUZ3AE.js";import"./chunk-TT7IA5HB.js";export{connectRemoteMcp};
@@ -1 +1 @@
1
- import{withRemoteClient}from"./chunk-XUSVNPR5.js";import{readInput}from"./chunk-QGK6G6YS.js";import{observeProduction}from"./chunk-APNZQZFB.js";import"./chunk-27KI24GK.js";import"./chunk-7I7ARCY7.js";import"./chunk-DLW42PJ6.js";import"./chunk-WTJVS2VS.js";import"./chunk-KOCUZ3AE.js";import{NativeStudioSdkError}from"./chunk-TT7IA5HB.js";async function runObservationCli(argv,emit,signal,environment=process.env,stdin=process.stdin){const lifetime=new AbortController;let timer;const observationSignal=AbortSignal.any([signal,lifetime.signal]);try{const options=new Map;const allowed=["--input","--tenant","--profile","--origin","--mcp-url","--token-env","--token-file","--transport","--max-polls","--timeout-ms","--max-events","--max-bytes"];for(let n=0;n<argv.length;n+=2){const key=argv[n],value=argv[n+1];if(!key||!allowed.includes(key)||!value||value.startsWith("--")||options.has(key))throw Error();options.set(key,value)}if(!options.has("--input"))throw Error();const number=key=>{const value=options.get(key);if(value!==void 0&&!/^[1-9][0-9]{0,8}$/.test(value))throw Error();return value===void 0?{}:{[key.slice(2).replace(/-([a-z])/g,(_,x)=>x.toUpperCase())]:Number(value)}};const limits=Object.assign({},...["--max-polls","--timeout-ms","--max-events","--max-bytes"].map(number));const timeout=Number(options.get("--timeout-ms")??3e5);if(!Number.isSafeInteger(timeout)||timeout<1||timeout>18e5)throw Error();timer=setTimeout(()=>lifetime.abort(),timeout);const input=await readInput(options.get("--input"),stdin,false,observationSignal);if(typeof input.productionId!=="string")throw Error();const productionId=input.productionId;await withRemoteClient(options,environment,false,async client=>{for await(const page of observeProduction(client,{...input,productionId},{...limits,signal:observationSignal})){observationSignal.throwIfAborted();await emit({kind:"production.events",data:page},observationSignal)}},{signal:observationSignal,maxJsonBytes:128*1024});await emit({kind:"observation.ended",reason:"POLL_LIMIT",nativeWorkCancelled:false},observationSignal);return 0}catch(error){if(signal.aborted)return 130;if(lifetime.signal.aborted)return 0;const e=error instanceof NativeStudioSdkError?error:null;await emit({kind:"observation.ended",reason:lifetime.signal.aborted?"OBSERVATION_LIMIT":e?.code??"INVALID_INPUT",outcome:e?.outcome??"NO_WRITE",nativeWorkCancelled:false},observationSignal).catch(()=>{});return lifetime.signal.aborted||e?.code==="OBSERVATION_LIMIT"?0:e?4:2}finally{if(timer)clearTimeout(timer);lifetime.abort()}}async function runObservationEntry(argv){const controller=new AbortController;const stop=()=>controller.abort();process.on("SIGINT",stop);process.on("SIGTERM",stop);try{return await runObservationCli(argv,(value,writeSignal)=>new Promise((resolve,reject)=>{if(writeSignal.aborted){reject(writeSignal.reason);return}const aborted=()=>{cleanup();reject(writeSignal.reason)};const failed=error=>{cleanup();controller.abort();reject(error)};const cleanup=()=>{writeSignal.removeEventListener("abort",aborted);process.stdout.off("error",failed)};writeSignal.addEventListener("abort",aborted,{once:true});process.stdout.once("error",failed);process.stdout.write(JSON.stringify(value)+"\n",error=>{cleanup();if(error)reject(error);else resolve()})}),controller.signal)}finally{controller.abort();process.stdin.pause();process.off("SIGINT",stop);process.off("SIGTERM",stop)}}export{runObservationEntry};
1
+ import{withRemoteClient}from"./chunk-X5PBZTKX.js";import{readInput}from"./chunk-QGK6G6YS.js";import{observeProduction}from"./chunk-2S7FI3HF.js";import"./chunk-27KI24GK.js";import"./chunk-7I7ARCY7.js";import"./chunk-DLW42PJ6.js";import"./chunk-WTJVS2VS.js";import"./chunk-KOCUZ3AE.js";import{NativeStudioSdkError}from"./chunk-TT7IA5HB.js";async function runObservationCli(argv,emit,signal,environment=process.env,stdin=process.stdin){const lifetime=new AbortController;let timer;const observationSignal=AbortSignal.any([signal,lifetime.signal]);try{const options=new Map;const allowed=["--input","--tenant","--profile","--origin","--mcp-url","--token-env","--token-file","--transport","--max-polls","--timeout-ms","--max-events","--max-bytes"];for(let n=0;n<argv.length;n+=2){const key=argv[n],value=argv[n+1];if(!key||!allowed.includes(key)||!value||value.startsWith("--")||options.has(key))throw Error();options.set(key,value)}if(!options.has("--input"))throw Error();const number=key=>{const value=options.get(key);if(value!==void 0&&!/^[1-9][0-9]{0,8}$/.test(value))throw Error();return value===void 0?{}:{[key.slice(2).replace(/-([a-z])/g,(_,x)=>x.toUpperCase())]:Number(value)}};const limits=Object.assign({},...["--max-polls","--timeout-ms","--max-events","--max-bytes"].map(number));const timeout=Number(options.get("--timeout-ms")??3e5);if(!Number.isSafeInteger(timeout)||timeout<1||timeout>18e5)throw Error();timer=setTimeout(()=>lifetime.abort(),timeout);const input=await readInput(options.get("--input"),stdin,false,observationSignal);if(typeof input.productionId!=="string")throw Error();const productionId=input.productionId;await withRemoteClient(options,environment,false,async client=>{for await(const page of observeProduction(client,{...input,productionId},{...limits,signal:observationSignal})){observationSignal.throwIfAborted();await emit({kind:"production.events",data:page},observationSignal)}},{signal:observationSignal,maxJsonBytes:128*1024});await emit({kind:"observation.ended",reason:"POLL_LIMIT",nativeWorkCancelled:false},observationSignal);return 0}catch(error){if(signal.aborted)return 130;if(lifetime.signal.aborted)return 0;const e=error instanceof NativeStudioSdkError?error:null;await emit({kind:"observation.ended",reason:lifetime.signal.aborted?"OBSERVATION_LIMIT":e?.code??"INVALID_INPUT",outcome:e?.outcome??"NO_WRITE",nativeWorkCancelled:false},observationSignal).catch(()=>{});return lifetime.signal.aborted||e?.code==="OBSERVATION_LIMIT"?0:e?4:2}finally{if(timer)clearTimeout(timer);lifetime.abort()}}async function runObservationEntry(argv){const controller=new AbortController;const stop=()=>controller.abort();process.on("SIGINT",stop);process.on("SIGTERM",stop);try{return await runObservationCli(argv,(value,writeSignal)=>new Promise((resolve,reject)=>{if(writeSignal.aborted){reject(writeSignal.reason);return}const aborted=()=>{cleanup();reject(writeSignal.reason)};const failed=error=>{cleanup();controller.abort();reject(error)};const cleanup=()=>{writeSignal.removeEventListener("abort",aborted);process.stdout.off("error",failed)};writeSignal.addEventListener("abort",aborted,{once:true});process.stdout.once("error",failed);process.stdout.write(JSON.stringify(value)+"\n",error=>{cleanup();if(error)reject(error);else resolve()})}),controller.signal)}finally{controller.abort();process.stdin.pause();process.off("SIGINT",stop);process.off("SIGTERM",stop)}}export{runObservationEntry};
@@ -1 +1 @@
1
- import{withRemoteClient}from"./chunk-XUSVNPR5.js";import"./chunk-QGK6G6YS.js";import"./chunk-APNZQZFB.js";import"./chunk-27KI24GK.js";import"./chunk-7I7ARCY7.js";import"./chunk-DLW42PJ6.js";import"./chunk-WTJVS2VS.js";import"./chunk-KOCUZ3AE.js";import"./chunk-TT7IA5HB.js";export{withRemoteClient};
1
+ import{withRemoteClient}from"./chunk-X5PBZTKX.js";import"./chunk-QGK6G6YS.js";import"./chunk-2S7FI3HF.js";import"./chunk-27KI24GK.js";import"./chunk-7I7ARCY7.js";import"./chunk-DLW42PJ6.js";import"./chunk-WTJVS2VS.js";import"./chunk-KOCUZ3AE.js";import"./chunk-TT7IA5HB.js";export{withRemoteClient};
@@ -1 +1 @@
1
- import{callerRenderConnection,renderReceiptScope}from"./chunk-OSO6KRE2.js";import"./chunk-UYKCN5DU.js";import"./chunk-3TOXIJ7K.js";import{readInput}from"./chunk-QGK6G6YS.js";import"./chunk-GLAF74UU.js";import"./chunk-2UYKJ6YN.js";import{DeviceRenderDownloadSchema,DeviceRenderIntentSchema,DeviceRenderReadSchema,DeviceRenderReceiptHandoffSchema,PreparedDeviceRenderSchema,renderDeviceSelection}from"./chunk-APNZQZFB.js";import{clientHome}from"./chunk-27KI24GK.js";import"./chunk-7I7ARCY7.js";import{directory,optional,sha256,write}from"./chunk-DLW42PJ6.js";import{CapabilityVersionMismatchSchema,InterfaceSemanticStatusSchema}from"./chunk-WTJVS2VS.js";import"./chunk-KOCUZ3AE.js";import{NativeStudioSdkError}from"./chunk-TT7IA5HB.js";import{z}from"zod";import{join,resolve}from"node:path";async function assertRenderProject(studio,scope,productionId,options){const snapshot=await studio.call("production.snapshot",{productionId},options);if(snapshot.tenantId!==scope.tenantId||snapshot.projectId!==scope.projectId||snapshot.productionId!==productionId)throw new NativeStudioSdkError("FORBIDDEN","BLOCKED","NO_WRITE")}var receipt=z.strictObject({scope:z.string(),intent:DeviceRenderIntentSchema,prepared:PreparedDeviceRenderSchema});var savedRenderFailure=z.strictObject({code:z.string().regex(/^[A-Z][A-Z0-9_]{0,119}$/),outcome:z.enum(["NO_WRITE","REJECTED"]),semanticStatus:InterfaceSemanticStatusSchema,details:CapabilityVersionMismatchSchema.optional()});function requestPrefix(root,scope,requestId){const binding=scope.resource+"#"+sha256(scope.profile)+"#"+scope.projectId;return{binding,prefix:join(root,sha256(binding+"\n"+requestId))}}async function findRequest(root,conn,requestId){const legacy=requestPrefix(root,conn.scope,requestId);if(!conn.externalCredential)return{...legacy,saved:await optional(legacy.prefix+".request.json")};const{principalId,grantId}=await renderReceiptScope(conn.studio,conn.scope);const current=requestPrefix(root,{...conn.scope,profile:`oauth-grant:${principalId}/${grantId}`},requestId);const saved=await optional(current.prefix+".request.json");if(saved!==null)return{...current,saved};const old=await optional(legacy.prefix+".request.json");return old===null?{...current,saved:null}:{...legacy,saved:old}}function unknownReceipt(productionId,idempotencyKey){return{exitCode:1,output:{semanticStatus:"BLOCKED",error:{code:"OUTCOME_UNKNOWN",outcome:"UNKNOWN"},idempotencyKey,productionId,nextAction:"Read the original receipt with the same request or its prepared command."}}}async function readNativeReceipt(conn,prepared,prefix){try{return{exitCode:0,output:await conn.studio.deviceRenders.receipt(prepared)}}catch(error){if(!(error instanceof NativeStudioSdkError)||!["NOT_FOUND","OUTCOME_UNKNOWN","TRANSPORT_UNAVAILABLE","REQUEST_ABORTED"].includes(error.code))throw error;if(error.code==="NOT_FOUND"&&prefix){const failure=savedRenderFailure.safeParse(await optional(prefix+".failure.json").catch(()=>null));if(failure.success){const{code,outcome,semanticStatus,details}=failure.data;throw new NativeStudioSdkError(code,semanticStatus,outcome,null,[],details)}}return unknownReceipt(prepared.command.productionId,prepared.command.idempotencyKey)}}async function readTransferredReceipt(flags,env,stdin){if([...flags.keys()].some(key=>!["--input","--mcp-url","--token-file"].includes(key)))throw Error();const{scope,prepared}=DeviceRenderReceiptHandoffSchema.parse(await readInput(flags.get("--input"),stdin,true));if(prepared.command.tenantId!==scope.tenantId)throw Error();const conn=await callerRenderConnection(env,new Map([...flags,["--project",scope.projectId]]),false);try{if(conn.scope.resource!==scope.resource||conn.scope.tenantId!==scope.tenantId)throw new NativeStudioSdkError("FORBIDDEN","BLOCKED","NO_WRITE");const verified=await renderReceiptScope(conn.studio,conn.scope);if(verified.principalId!==scope.principalId||verified.grantId!==scope.grantId)throw new NativeStudioSdkError("FORBIDDEN","BLOCKED","NO_WRITE");await assertRenderProject(conn.studio,verified,prepared.command.productionId);return await readNativeReceipt(conn,prepared)}finally{await conn.close().catch(()=>{})}}async function readRenderSetup(kind,flags,env){const allowed=["--kind","--production","--project","--mcp-url","--token-file",kind==="receipt"?"--request":"--device"];if([...flags.keys()].some(key=>!allowed.includes(key)))throw Error();const renderKind=DeviceRenderReadSchema.shape.kind.parse(flags.get("--kind"));const productionId=z.uuid().parse(flags.get("--production"));const requestId=kind==="receipt"?z.uuid().parse(flags.get("--request")):void 0;const deviceId=z.uuid().optional().parse(flags.get("--device"));const conn=await callerRenderConnection(env,flags,false);const{scope,studio}=conn;try{await assertRenderProject(studio,scope,productionId);if(requestId){const home=await clientHome(env).catch(error=>{if(error.code==="ENOENT")return null;throw error});if(!home)return unknownReceipt(productionId,requestId);const{binding,prefix,saved}=await findRequest(join(home,"renders"),conn,requestId);if(!saved)return unknownReceipt(productionId,requestId);const{scope:savedScope,intent,prepared}=receipt.parse(saved);if(savedScope!==binding||intent.kind!==renderKind||prepared.kind!==renderKind||intent.productionId!==productionId||prepared.command.productionId!==productionId||prepared.command.tenantId!==scope.tenantId||intent.idempotencyKey!==requestId||prepared.command.idempotencyKey!==requestId||prepared.command.deviceExecution.deviceId!==intent.deviceId||prepared.command.deviceExecution.validationMode!==intent.validationMode)throw new NativeStudioSdkError("REVISION_CONFLICT","REVISION_CONFLICT","NO_WRITE");return await readNativeReceipt(conn,prepared,prefix)}const[basis,candidates]=await Promise.all([studio.deviceRenders.basis({kind:renderKind,productionId}),studio.deviceRenders.list({kind:renderKind,projectId:scope.projectId,deviceId})]);const{state}=renderDeviceSelection(candidates,deviceId);const eligible=basis.basis!==null&&state==="AVAILABLE";const selectionBlocker=state==="DEVICE_SELECTION_REQUIRED"||state==="INCOMPLETE_INVENTORY"?[state]:[];return{exitCode:eligible?0:4,output:{semanticStatus:eligible?"SUCCESS":"BLOCKED",productionId,...basis,blockers:[...basis.blockers,...selectionBlocker],eligible,candidates,deviceStatus:state==="INCOMPLETE_INVENTORY"?"INCONCLUSIVE":state==="UNAVAILABLE"?"UNAVAILABLE":"AVAILABLE"}}}finally{await conn.close().catch(()=>{})}}async function renderCommand(argv,env,stdin=process.stdin){const[kind,...args]=argv,flags=new Map;for(let i=0;i<args.length;i+=2){const k=args[i],v=args[i+1];if(!k||!v||v.startsWith("--")||flags.has(k)||!["--production","--project","--request","--device","--profile-id","--validation-mode","--kind","--render","--role","--output","--mcp-url","--token-file","--input"].includes(k))throw Error();flags.set(k,v)}if(flags.has("--input")){if(kind!=="receipt")throw Error();return readTransferredReceipt(flags,env,stdin)}if(kind==="eligibility"||kind==="receipt")return readRenderSetup(kind,flags,env);if(kind==="status"||kind==="download"){const allowed=new Set(["--kind","--project","--production","--render","--mcp-url","--token-file",...kind==="download"?["--role","--output"]:[]]);if(Array.from(flags.keys()).some(key=>!allowed.has(key)))throw Error();const input=DeviceRenderReadSchema.parse({kind:flags.get("--kind"),productionId:flags.get("--production"),renderId:flags.get("--render")});const conn2=await callerRenderConnection(env,flags,false);try{if(kind==="status"){const view=await conn2.studio.deviceRenders.get(input);if(view.projectId!==conn2.scope.projectId)throw new NativeStudioSdkError("FORBIDDEN","BLOCKED","NO_WRITE");return{exitCode:0,output:view}}const filename=flags.get("--output");if(!filename)throw Error();const request=DeviceRenderDownloadSchema.parse({...input,role:flags.get("--role")??"VIDEO"});const output=await conn2.studio.deviceRenders.download(request,void 0,conn2.scope.projectId);if(output.object.projectId!==conn2.scope.projectId)throw new NativeStudioSdkError("FORBIDDEN","BLOCKED","NO_WRITE");await write(resolve(filename),output.bytes,true);return{exitCode:0,output:{semanticStatus:"SUCCESS",renderId:output.renderId,representationId:output.representationId,byteSize:output.object.byteSize,checksumSha256:output.object.checksumSha256}}}finally{await conn2.close().catch(()=>{})}}if(["--kind","--render","--role","--output"].some(key=>flags.has(key)))throw Error();const intent=DeviceRenderIntentSchema.parse({kind,productionId:flags.get("--production"),idempotencyKey:z.uuid().parse(flags.get("--request")),...flags.has("--device")?{deviceId:flags.get("--device")}:{},...flags.has("--profile-id")?{profileId:flags.get("--profile-id")}:{},...flags.has("--validation-mode")?{validationMode:flags.get("--validation-mode")}:{}});const conn=await callerRenderConnection(env,flags);try{await assertRenderProject(conn.studio,conn.scope,intent.productionId);const root=await directory(join(await clientHome(env,true),"renders"));const{binding,prefix,saved:previous}=await findRequest(root,conn,intent.idempotencyKey);if(previous){const old=receipt.parse(previous);if(old.scope!==binding||JSON.stringify(old.intent)!==JSON.stringify(intent))throw new NativeStudioSdkError("REVISION_CONFLICT","REVISION_CONFLICT","NO_WRITE");const result=await optional(prefix+".result.json");if(result)return{exitCode:0,output:result};return await readNativeReceipt(conn,old.prepared,prefix)}const prepared=await conn.studio.deviceRenders.prepare(intent);try{await write(prefix+".request.json",JSON.stringify({scope:binding,intent,prepared}),true)}catch(error){if(error.code!=="EEXIST")throw error;return unknownReceipt(intent.productionId,intent.idempotencyKey)}let output;try{output=await conn.studio.deviceRenders.start(prepared)}catch(e){if(e instanceof NativeStudioSdkError&&e.outcome!=="UNKNOWN")await write(prefix+".failure.json",JSON.stringify({code:e.code,outcome:e.outcome,semanticStatus:e.semanticStatus,...e.capabilityMismatch&&{details:e.capabilityMismatch}}),true).catch(()=>{});throw e}try{await write(prefix+".result.json",JSON.stringify(output),true)}catch{throw new NativeStudioSdkError("OUTCOME_UNKNOWN","BLOCKED","UNKNOWN")}return{exitCode:0,output}}finally{await conn.close().catch(()=>{})}}export{renderCommand};
1
+ import{callerRenderConnection,renderReceiptScope}from"./chunk-3RNDOAQI.js";import"./chunk-VYCNG6TR.js";import"./chunk-3TOXIJ7K.js";import{readInput}from"./chunk-QGK6G6YS.js";import"./chunk-76E5R3OC.js";import"./chunk-2UYKJ6YN.js";import{DeviceRenderDownloadSchema,DeviceRenderIntentSchema,DeviceRenderReadSchema,DeviceRenderReceiptHandoffSchema,PreparedDeviceRenderSchema,renderDeviceSelection}from"./chunk-2S7FI3HF.js";import{clientHome}from"./chunk-27KI24GK.js";import"./chunk-7I7ARCY7.js";import{directory,optional,sha256,write}from"./chunk-DLW42PJ6.js";import{CapabilityVersionMismatchSchema,InterfaceSemanticStatusSchema}from"./chunk-WTJVS2VS.js";import"./chunk-KOCUZ3AE.js";import{NativeStudioSdkError}from"./chunk-TT7IA5HB.js";import{z}from"zod";import{join,resolve}from"node:path";async function assertRenderProject(studio,scope,productionId,options){const snapshot=await studio.call("production.snapshot",{productionId},options);if(snapshot.tenantId!==scope.tenantId||snapshot.projectId!==scope.projectId||snapshot.productionId!==productionId)throw new NativeStudioSdkError("FORBIDDEN","BLOCKED","NO_WRITE")}var receipt=z.strictObject({scope:z.string(),intent:DeviceRenderIntentSchema,prepared:PreparedDeviceRenderSchema});var savedRenderFailure=z.strictObject({code:z.string().regex(/^[A-Z][A-Z0-9_]{0,119}$/),outcome:z.enum(["NO_WRITE","REJECTED"]),semanticStatus:InterfaceSemanticStatusSchema,details:CapabilityVersionMismatchSchema.optional()});function requestPrefix(root,scope,requestId){const binding=scope.resource+"#"+sha256(scope.profile)+"#"+scope.projectId;return{binding,prefix:join(root,sha256(binding+"\n"+requestId))}}async function findRequest(root,conn,requestId){const legacy=requestPrefix(root,conn.scope,requestId);if(!conn.externalCredential)return{...legacy,saved:await optional(legacy.prefix+".request.json")};const{principalId,grantId}=await renderReceiptScope(conn.studio,conn.scope);const current=requestPrefix(root,{...conn.scope,profile:`oauth-grant:${principalId}/${grantId}`},requestId);const saved=await optional(current.prefix+".request.json");if(saved!==null)return{...current,saved};const old=await optional(legacy.prefix+".request.json");return old===null?{...current,saved:null}:{...legacy,saved:old}}function unknownReceipt(productionId,idempotencyKey){return{exitCode:1,output:{semanticStatus:"BLOCKED",error:{code:"OUTCOME_UNKNOWN",outcome:"UNKNOWN"},idempotencyKey,productionId,nextAction:"Read the original receipt with the same request or its prepared command."}}}async function readNativeReceipt(conn,prepared,prefix){try{return{exitCode:0,output:await conn.studio.deviceRenders.receipt(prepared)}}catch(error){if(!(error instanceof NativeStudioSdkError)||!["NOT_FOUND","OUTCOME_UNKNOWN","TRANSPORT_UNAVAILABLE","REQUEST_ABORTED"].includes(error.code))throw error;if(error.code==="NOT_FOUND"&&prefix){const failure=savedRenderFailure.safeParse(await optional(prefix+".failure.json").catch(()=>null));if(failure.success){const{code,outcome,semanticStatus,details}=failure.data;throw new NativeStudioSdkError(code,semanticStatus,outcome,null,[],details)}}return unknownReceipt(prepared.command.productionId,prepared.command.idempotencyKey)}}async function readTransferredReceipt(flags,env,stdin){if([...flags.keys()].some(key=>!["--input","--mcp-url","--token-file"].includes(key)))throw Error();const{scope,prepared}=DeviceRenderReceiptHandoffSchema.parse(await readInput(flags.get("--input"),stdin,true));if(prepared.command.tenantId!==scope.tenantId)throw Error();const conn=await callerRenderConnection(env,new Map([...flags,["--project",scope.projectId]]),false);try{if(conn.scope.resource!==scope.resource||conn.scope.tenantId!==scope.tenantId)throw new NativeStudioSdkError("FORBIDDEN","BLOCKED","NO_WRITE");const verified=await renderReceiptScope(conn.studio,conn.scope);if(verified.principalId!==scope.principalId||verified.grantId!==scope.grantId)throw new NativeStudioSdkError("FORBIDDEN","BLOCKED","NO_WRITE");await assertRenderProject(conn.studio,verified,prepared.command.productionId);return await readNativeReceipt(conn,prepared)}finally{await conn.close().catch(()=>{})}}async function readRenderSetup(kind,flags,env){const allowed=["--kind","--production","--project","--mcp-url","--token-file",kind==="receipt"?"--request":"--device"];if([...flags.keys()].some(key=>!allowed.includes(key)))throw Error();const renderKind=DeviceRenderReadSchema.shape.kind.parse(flags.get("--kind"));const productionId=z.uuid().parse(flags.get("--production"));const requestId=kind==="receipt"?z.uuid().parse(flags.get("--request")):void 0;const deviceId=z.uuid().optional().parse(flags.get("--device"));const conn=await callerRenderConnection(env,flags,false);const{scope,studio}=conn;try{await assertRenderProject(studio,scope,productionId);if(requestId){const home=await clientHome(env).catch(error=>{if(error.code==="ENOENT")return null;throw error});if(!home)return unknownReceipt(productionId,requestId);const{binding,prefix,saved}=await findRequest(join(home,"renders"),conn,requestId);if(!saved)return unknownReceipt(productionId,requestId);const{scope:savedScope,intent,prepared}=receipt.parse(saved);if(savedScope!==binding||intent.kind!==renderKind||prepared.kind!==renderKind||intent.productionId!==productionId||prepared.command.productionId!==productionId||prepared.command.tenantId!==scope.tenantId||intent.idempotencyKey!==requestId||prepared.command.idempotencyKey!==requestId||prepared.command.deviceExecution.deviceId!==intent.deviceId||prepared.command.deviceExecution.validationMode!==intent.validationMode)throw new NativeStudioSdkError("REVISION_CONFLICT","REVISION_CONFLICT","NO_WRITE");return await readNativeReceipt(conn,prepared,prefix)}const[basis,candidates]=await Promise.all([studio.deviceRenders.basis({kind:renderKind,productionId}),studio.deviceRenders.list({kind:renderKind,projectId:scope.projectId,deviceId})]);const{state}=renderDeviceSelection(candidates,deviceId);const eligible=basis.basis!==null&&state==="AVAILABLE";const selectionBlocker=state==="DEVICE_SELECTION_REQUIRED"||state==="INCOMPLETE_INVENTORY"?[state]:[];return{exitCode:eligible?0:4,output:{semanticStatus:eligible?"SUCCESS":"BLOCKED",productionId,...basis,blockers:[...basis.blockers,...selectionBlocker],eligible,candidates,deviceStatus:state==="INCOMPLETE_INVENTORY"?"INCONCLUSIVE":state==="UNAVAILABLE"?"UNAVAILABLE":"AVAILABLE"}}}finally{await conn.close().catch(()=>{})}}async function renderCommand(argv,env,stdin=process.stdin){const[kind,...args]=argv,flags=new Map;for(let i=0;i<args.length;i+=2){const k=args[i],v=args[i+1];if(!k||!v||v.startsWith("--")||flags.has(k)||!["--production","--project","--request","--device","--profile-id","--validation-mode","--kind","--render","--role","--output","--mcp-url","--token-file","--input"].includes(k))throw Error();flags.set(k,v)}if(flags.has("--input")){if(kind!=="receipt")throw Error();return readTransferredReceipt(flags,env,stdin)}if(kind==="eligibility"||kind==="receipt")return readRenderSetup(kind,flags,env);if(kind==="status"||kind==="download"){const allowed=new Set(["--kind","--project","--production","--render","--mcp-url","--token-file",...kind==="download"?["--role","--output"]:[]]);if(Array.from(flags.keys()).some(key=>!allowed.has(key)))throw Error();const input=DeviceRenderReadSchema.parse({kind:flags.get("--kind"),productionId:flags.get("--production"),renderId:flags.get("--render")});const conn2=await callerRenderConnection(env,flags,false);try{if(kind==="status"){const view=await conn2.studio.deviceRenders.get(input);if(view.projectId!==conn2.scope.projectId)throw new NativeStudioSdkError("FORBIDDEN","BLOCKED","NO_WRITE");return{exitCode:0,output:view}}const filename=flags.get("--output");if(!filename)throw Error();const request=DeviceRenderDownloadSchema.parse({...input,role:flags.get("--role")??"VIDEO"});const output=await conn2.studio.deviceRenders.download(request,void 0,conn2.scope.projectId);if(output.object.projectId!==conn2.scope.projectId)throw new NativeStudioSdkError("FORBIDDEN","BLOCKED","NO_WRITE");await write(resolve(filename),output.bytes,true);return{exitCode:0,output:{semanticStatus:"SUCCESS",renderId:output.renderId,representationId:output.representationId,byteSize:output.object.byteSize,checksumSha256:output.object.checksumSha256}}}finally{await conn2.close().catch(()=>{})}}if(["--kind","--render","--role","--output"].some(key=>flags.has(key)))throw Error();const intent=DeviceRenderIntentSchema.parse({kind,productionId:flags.get("--production"),idempotencyKey:z.uuid().parse(flags.get("--request")),...flags.has("--device")?{deviceId:flags.get("--device")}:{},...flags.has("--profile-id")?{profileId:flags.get("--profile-id")}:{},...flags.has("--validation-mode")?{validationMode:flags.get("--validation-mode")}:{}});const conn=await callerRenderConnection(env,flags);try{await assertRenderProject(conn.studio,conn.scope,intent.productionId);const root=await directory(join(await clientHome(env,true),"renders"));const{binding,prefix,saved:previous}=await findRequest(root,conn,intent.idempotencyKey);if(previous){const old=receipt.parse(previous);if(old.scope!==binding||JSON.stringify(old.intent)!==JSON.stringify(intent))throw new NativeStudioSdkError("REVISION_CONFLICT","REVISION_CONFLICT","NO_WRITE");const result=await optional(prefix+".result.json");if(result)return{exitCode:0,output:result};return await readNativeReceipt(conn,old.prepared,prefix)}const prepared=await conn.studio.deviceRenders.prepare(intent);try{await write(prefix+".request.json",JSON.stringify({scope:binding,intent,prepared}),true)}catch(error){if(error.code!=="EEXIST")throw error;return unknownReceipt(intent.productionId,intent.idempotencyKey)}let output;try{output=await conn.studio.deviceRenders.start(prepared)}catch(e){if(e instanceof NativeStudioSdkError&&e.outcome!=="UNKNOWN")await write(prefix+".failure.json",JSON.stringify({code:e.code,outcome:e.outcome,semanticStatus:e.semanticStatus,...e.capabilityMismatch&&{details:e.capabilityMismatch}}),true).catch(()=>{});throw e}try{await write(prefix+".result.json",JSON.stringify(output),true)}catch{throw new NativeStudioSdkError("OUTCOME_UNKNOWN","BLOCKED","UNKNOWN")}return{exitCode:0,output}}finally{await conn.close().catch(()=>{})}}export{renderCommand};
@@ -1 +1 @@
1
- import{profileAuthorization}from"./chunk-3TOXIJ7K.js";import{readCredential,readInput}from"./chunk-QGK6G6YS.js";import{NativeStudioAgentClient}from"./chunk-APNZQZFB.js";import{profileHttpOrigin}from"./chunk-7P2NA6TH.js";import{defaultConnection,tenantConnection}from"./chunk-27KI24GK.js";import"./chunk-7I7ARCY7.js";import"./chunk-DLW42PJ6.js";import"./chunk-WTJVS2VS.js";import"./chunk-KOCUZ3AE.js";import"./chunk-TT7IA5HB.js";import{constants,open}from"node:fs/promises";async function sourceBytes(path,maxBytes){const file=await open(path,constants.O_RDONLY|constants.O_NOFOLLOW);try{const stat=await file.stat();if(!stat.isFile()||stat.size<1||stat.size>maxBytes)throw Error();const bytes=Buffer.alloc(stat.size);let offset=0;while(offset<bytes.length){const{bytesRead}=await file.read(bytes,offset,bytes.length-offset,offset);if(!bytesRead)throw Error();offset+=bytesRead}if((await file.read(Buffer.alloc(1),0,1,offset)).bytesRead)throw Error();return bytes}finally{await file.close()}}async function importSourceCommand([kind,...args],env,stdin){if(kind!=="project"&&kind!=="original")throw Error();const flags=new Map;for(let index=0;index<args.length;index+=2){const name=args[index],value=args[index+1];if(!name||!value||value.startsWith("--")||flags.has(name)||!["--input","--file","--tenant","--origin","--mcp-url","--profile","--token-env","--token-file"].includes(name))throw Error();flags.set(name,value)}await defaultConnection(flags,env,true);const profile=flags.get("--profile");if(profile?["--origin","--mcp-url","--token-env","--token-file"].some(key=>flags.has(key)):flags.has("--origin")===flags.has("--mcp-url"))throw Error();const connected=profile?await profileAuthorization(profile):null;const resource=connected?.resource??flags.get("--mcp-url");const scope=resource?tenantConnection(resource):null;if(scope&&flags.has("--tenant")&&flags.get("--tenant")!==scope.tenantId)throw Error();const input=flags.get("--input"),file=flags.get("--file"),tenantId=scope?.tenantId??flags.get("--tenant"),baseUrl=flags.get("--origin")??(connected&&profile?await profileHttpOrigin(profile,connected.resource):resource?new URL(resource).origin:void 0);if(!input||!file||!tenantId||!baseUrl)throw Error();const authorization=connected?.authorization??await readCredential(flags,env);const studio=new NativeStudioAgentClient({tenantId,baseUrl,authorization:()=>authorization});const intent=await readInput(input,stdin);const bytes=await sourceBytes(file,(kind==="project"?8:128)*1024*1024);const receipt=kind==="project"?await studio.directSources.importProjectSource(intent,bytes):await studio.directSources.importOriginal(intent,bytes);if(receipt.state==="SUBMITTED")return{exitCode:0,output:receipt};const output="registration"in receipt?{artifactId:receipt.registration.artifact.id,representationId:receipt.registration.primaryRepresentation.id}:{artifactId:receipt.original.artifactId,representationId:receipt.original.representationId,sourceId:receipt.original.sourceId,version:receipt.original.version};return{exitCode:0,output:{state:receipt.state,...output}}}export{importSourceCommand};
1
+ import{profileAuthorization}from"./chunk-3TOXIJ7K.js";import{readCredential,readInput}from"./chunk-QGK6G6YS.js";import{NativeStudioAgentClient}from"./chunk-2S7FI3HF.js";import{profileHttpOrigin}from"./chunk-7P2NA6TH.js";import{defaultConnection,tenantConnection}from"./chunk-27KI24GK.js";import"./chunk-7I7ARCY7.js";import"./chunk-DLW42PJ6.js";import"./chunk-WTJVS2VS.js";import"./chunk-KOCUZ3AE.js";import"./chunk-TT7IA5HB.js";import{constants,open}from"node:fs/promises";async function sourceBytes(path,maxBytes){const file=await open(path,constants.O_RDONLY|constants.O_NOFOLLOW);try{const stat=await file.stat();if(!stat.isFile()||stat.size<1||stat.size>maxBytes)throw Error();const bytes=Buffer.alloc(stat.size);let offset=0;while(offset<bytes.length){const{bytesRead}=await file.read(bytes,offset,bytes.length-offset,offset);if(!bytesRead)throw Error();offset+=bytesRead}if((await file.read(Buffer.alloc(1),0,1,offset)).bytesRead)throw Error();return bytes}finally{await file.close()}}async function importSourceCommand([kind,...args],env,stdin){if(kind!=="project"&&kind!=="original")throw Error();const flags=new Map;for(let index=0;index<args.length;index+=2){const name=args[index],value=args[index+1];if(!name||!value||value.startsWith("--")||flags.has(name)||!["--input","--file","--tenant","--origin","--mcp-url","--profile","--token-env","--token-file"].includes(name))throw Error();flags.set(name,value)}await defaultConnection(flags,env,true);const profile=flags.get("--profile");if(profile?["--origin","--mcp-url","--token-env","--token-file"].some(key=>flags.has(key)):flags.has("--origin")===flags.has("--mcp-url"))throw Error();const connected=profile?await profileAuthorization(profile):null;const resource=connected?.resource??flags.get("--mcp-url");const scope=resource?tenantConnection(resource):null;if(scope&&flags.has("--tenant")&&flags.get("--tenant")!==scope.tenantId)throw Error();const input=flags.get("--input"),file=flags.get("--file"),tenantId=scope?.tenantId??flags.get("--tenant"),baseUrl=flags.get("--origin")??(connected&&profile?await profileHttpOrigin(profile,connected.resource):resource?new URL(resource).origin:void 0);if(!input||!file||!tenantId||!baseUrl)throw Error();const authorization=connected?.authorization??await readCredential(flags,env);const studio=new NativeStudioAgentClient({tenantId,baseUrl,authorization:()=>authorization});const intent=await readInput(input,stdin);const bytes=await sourceBytes(file,(kind==="project"?8:128)*1024*1024);const receipt=kind==="project"?await studio.directSources.importProjectSource(intent,bytes):await studio.directSources.importOriginal(intent,bytes);if(receipt.state==="SUBMITTED")return{exitCode:0,output:receipt};const output="registration"in receipt?{artifactId:receipt.registration.artifact.id,representationId:receipt.registration.primaryRepresentation.id}:{artifactId:receipt.original.artifactId,representationId:receipt.original.representationId,sourceId:receipt.original.sourceId,version:receipt.original.version};return{exitCode:0,output:{state:receipt.state,...output}}}export{importSourceCommand};
@@ -1 +1 @@
1
- import{CapabilityDescribeSchema,CapabilityGroupsSchema,CapabilityInvocationInputSchema,CapabilityInvocationOutputSchema,DeviceDiscoveryInputSchema,DeviceEnrollmentHandoffSchema,DeviceEnrollmentObservationSchema,DeviceEnrollmentScopeSchema,DeviceEnrollmentTicketSchema,DeviceRenderAdmissionSchema,DeviceRenderDownloadSchema,DeviceRenderIntentSchema,DeviceRenderReadSchema,DeviceRenderReceiptHandoffSchema,DeviceStatusInputSchema,DeviceStatusSchema,FinalRenderViewSchema,LocalLibraryAdmissionSchema,LocalLibraryCommandQuerySchema,LocalLibraryCommandSchema,LocalLibraryCommandStatusSchema,LocalLibraryProjectionPageSchema,LocalLibraryProjectionQuerySchema,LocalLibraryReferenceSchema,McpEntryToolNames,NativeStudioAgentClient,NativeStudioDeviceRenders,NativeStudioMcpClient,NativeStudioNavigationClient,NativeStudioNavigationFacade,NativeStudioRuntimeAuthorityClient,NavigationGroupIdSchema,NavigationGroups,NavigationProfile,NavigationProfileKey,NavigationToolNames,PreparedDeviceRenderSchema,ProjectDeviceListSchema,RoughCutViewSchema,TenantRenderMediaTicketSchema,WorkspaceDeviceListInputSchema,WorkspaceDeviceListSchema,WorkspaceStatusSchema,assertCarrierCoverage,issueDeviceEnrollment,lookupDeviceEnrollment,navigationGroup,observeProduction,queryPages,readFederationLifecycleResult,recoverDeviceEnrollment,renderDeviceSelection,sdkCarrierDifferences,sdkImageMediaTools,sdkMcpTools,sdkOperations,submitDeviceEnrollment,validateDeviceEnrollmentHandoff,verifyWebhookNotification,waitForOperation}from"./chunk-APNZQZFB.js";import{CapabilityVersionMismatchSchema,CapabilityVersionSchema,InterfaceSemanticStatusSchema}from"./chunk-WTJVS2VS.js";import{NativeStudioSdkError,sdkInputError}from"./chunk-TT7IA5HB.js";export{CapabilityDescribeSchema,CapabilityGroupsSchema,CapabilityInvocationInputSchema,CapabilityInvocationOutputSchema,CapabilityVersionMismatchSchema,CapabilityVersionSchema,DeviceDiscoveryInputSchema,DeviceEnrollmentHandoffSchema,DeviceEnrollmentObservationSchema,DeviceEnrollmentScopeSchema,DeviceEnrollmentTicketSchema,DeviceRenderAdmissionSchema,DeviceRenderDownloadSchema,DeviceRenderIntentSchema,DeviceRenderReadSchema,DeviceRenderReceiptHandoffSchema,DeviceStatusInputSchema,DeviceStatusSchema,FinalRenderViewSchema,InterfaceSemanticStatusSchema,LocalLibraryAdmissionSchema,LocalLibraryCommandQuerySchema,LocalLibraryCommandSchema,LocalLibraryCommandStatusSchema,LocalLibraryProjectionPageSchema,LocalLibraryProjectionQuerySchema,LocalLibraryReferenceSchema,McpEntryToolNames,NativeStudioAgentClient,NativeStudioDeviceRenders,NativeStudioMcpClient,NativeStudioNavigationClient,NativeStudioNavigationFacade,NativeStudioRuntimeAuthorityClient,NativeStudioSdkError,NavigationGroupIdSchema,NavigationGroups,NavigationProfile,NavigationProfileKey,NavigationToolNames,PreparedDeviceRenderSchema,ProjectDeviceListSchema,RoughCutViewSchema,TenantRenderMediaTicketSchema,WorkspaceDeviceListInputSchema,WorkspaceDeviceListSchema,WorkspaceStatusSchema,assertCarrierCoverage,issueDeviceEnrollment,lookupDeviceEnrollment,navigationGroup,observeProduction,queryPages,readFederationLifecycleResult,recoverDeviceEnrollment,renderDeviceSelection,sdkCarrierDifferences,sdkImageMediaTools,sdkInputError,sdkMcpTools,sdkOperations,submitDeviceEnrollment,validateDeviceEnrollmentHandoff,verifyWebhookNotification,waitForOperation};
1
+ import{CapabilityDescribeSchema,CapabilityGroupsSchema,CapabilityInvocationInputSchema,CapabilityInvocationOutputSchema,DeviceDiscoveryInputSchema,DeviceEnrollmentHandoffSchema,DeviceEnrollmentObservationSchema,DeviceEnrollmentScopeSchema,DeviceEnrollmentTicketSchema,DeviceRenderAdmissionSchema,DeviceRenderDownloadSchema,DeviceRenderIntentSchema,DeviceRenderReadSchema,DeviceRenderReceiptHandoffSchema,DeviceStatusInputSchema,DeviceStatusSchema,FinalRenderViewSchema,LocalLibraryAdmissionSchema,LocalLibraryCommandQuerySchema,LocalLibraryCommandSchema,LocalLibraryCommandStatusSchema,LocalLibraryProjectionPageSchema,LocalLibraryProjectionQuerySchema,LocalLibraryReferenceSchema,McpEntryToolNames,NativeStudioAgentClient,NativeStudioDeviceRenders,NativeStudioMcpClient,NativeStudioNavigationClient,NativeStudioNavigationFacade,NativeStudioRuntimeAuthorityClient,NavigationGroupIdSchema,NavigationGroups,NavigationProfile,NavigationProfileKey,NavigationToolNames,PreparedDeviceRenderSchema,ProjectDeviceListSchema,RoughCutViewSchema,TenantRenderMediaTicketSchema,WorkspaceDeviceListInputSchema,WorkspaceDeviceListSchema,WorkspaceStatusSchema,assertCarrierCoverage,issueDeviceEnrollment,lookupDeviceEnrollment,navigationGroup,observeProduction,queryPages,readFederationLifecycleResult,recoverDeviceEnrollment,renderDeviceSelection,sdkCarrierDifferences,sdkImageMediaTools,sdkMcpTools,sdkOperations,submitDeviceEnrollment,validateDeviceEnrollmentHandoff,verifyWebhookNotification,waitForOperation}from"./chunk-2S7FI3HF.js";import{CapabilityVersionMismatchSchema,CapabilityVersionSchema,InterfaceSemanticStatusSchema}from"./chunk-WTJVS2VS.js";import{NativeStudioSdkError,sdkInputError}from"./chunk-TT7IA5HB.js";export{CapabilityDescribeSchema,CapabilityGroupsSchema,CapabilityInvocationInputSchema,CapabilityInvocationOutputSchema,CapabilityVersionMismatchSchema,CapabilityVersionSchema,DeviceDiscoveryInputSchema,DeviceEnrollmentHandoffSchema,DeviceEnrollmentObservationSchema,DeviceEnrollmentScopeSchema,DeviceEnrollmentTicketSchema,DeviceRenderAdmissionSchema,DeviceRenderDownloadSchema,DeviceRenderIntentSchema,DeviceRenderReadSchema,DeviceRenderReceiptHandoffSchema,DeviceStatusInputSchema,DeviceStatusSchema,FinalRenderViewSchema,InterfaceSemanticStatusSchema,LocalLibraryAdmissionSchema,LocalLibraryCommandQuerySchema,LocalLibraryCommandSchema,LocalLibraryCommandStatusSchema,LocalLibraryProjectionPageSchema,LocalLibraryProjectionQuerySchema,LocalLibraryReferenceSchema,McpEntryToolNames,NativeStudioAgentClient,NativeStudioDeviceRenders,NativeStudioMcpClient,NativeStudioNavigationClient,NativeStudioNavigationFacade,NativeStudioRuntimeAuthorityClient,NativeStudioSdkError,NavigationGroupIdSchema,NavigationGroups,NavigationProfile,NavigationProfileKey,NavigationToolNames,PreparedDeviceRenderSchema,ProjectDeviceListSchema,RoughCutViewSchema,TenantRenderMediaTicketSchema,WorkspaceDeviceListInputSchema,WorkspaceDeviceListSchema,WorkspaceStatusSchema,assertCarrierCoverage,issueDeviceEnrollment,lookupDeviceEnrollment,navigationGroup,observeProduction,queryPages,readFederationLifecycleResult,recoverDeviceEnrollment,renderDeviceSelection,sdkCarrierDifferences,sdkImageMediaTools,sdkInputError,sdkMcpTools,sdkOperations,submitDeviceEnrollment,validateDeviceEnrollmentHandoff,verifyWebhookNotification,waitForOperation};
@@ -1 +1 @@
1
- import{workspaceCommand,workspaceProject}from"./chunk-UYKCN5DU.js";import"./chunk-3TOXIJ7K.js";import"./chunk-QGK6G6YS.js";import"./chunk-GLAF74UU.js";import"./chunk-2UYKJ6YN.js";import"./chunk-APNZQZFB.js";import"./chunk-27KI24GK.js";import"./chunk-7I7ARCY7.js";import"./chunk-DLW42PJ6.js";import"./chunk-WTJVS2VS.js";import"./chunk-KOCUZ3AE.js";import"./chunk-TT7IA5HB.js";export{workspaceCommand,workspaceProject};
1
+ import{workspaceCommand,workspaceProject}from"./chunk-VYCNG6TR.js";import"./chunk-3TOXIJ7K.js";import"./chunk-QGK6G6YS.js";import"./chunk-76E5R3OC.js";import"./chunk-2UYKJ6YN.js";import"./chunk-2S7FI3HF.js";import"./chunk-27KI24GK.js";import"./chunk-7I7ARCY7.js";import"./chunk-DLW42PJ6.js";import"./chunk-WTJVS2VS.js";import"./chunk-KOCUZ3AE.js";import"./chunk-TT7IA5HB.js";export{workspaceCommand,workspaceProject};
@@ -4,6 +4,39 @@ export declare const OperationTargetSchema: z.ZodObject<{
4
4
  id: z.ZodString;
5
5
  version: z.ZodNullable<z.ZodInt>;
6
6
  }, z.core.$strip>;
7
+ export declare const OperationFailureReasonSchema: z.ZodEnum<{
8
+ AMBIGUOUS: "AMBIGUOUS";
9
+ PERMANENT_OPERATIONAL: "PERMANENT_OPERATIONAL";
10
+ SEMANTIC: "SEMANTIC";
11
+ RATE_LIMIT: "RATE_LIMIT";
12
+ TRANSIENT: "TRANSIENT";
13
+ NOT_RECORDED: "NOT_RECORDED";
14
+ }>;
15
+ export declare const OperationFailureSchema: z.ZodObject<{
16
+ reasonCodes: z.ZodArray<z.ZodEnum<{
17
+ AMBIGUOUS: "AMBIGUOUS";
18
+ PERMANENT_OPERATIONAL: "PERMANENT_OPERATIONAL";
19
+ SEMANTIC: "SEMANTIC";
20
+ RATE_LIMIT: "RATE_LIMIT";
21
+ TRANSIENT: "TRANSIENT";
22
+ NOT_RECORDED: "NOT_RECORDED";
23
+ }>>;
24
+ summary: z.ZodString;
25
+ next: z.ZodDiscriminatedUnion<[z.ZodObject<{
26
+ capability: z.ZodLiteral<"operation.get">;
27
+ input: z.ZodObject<{
28
+ tenantId: z.core.$ZodBranded<z.ZodUUID, "TenantId", "out">;
29
+ productionId: z.core.$ZodBranded<z.ZodUUID, "ProductionId", "out">;
30
+ operationId: z.core.$ZodBranded<z.ZodString, "OperationId", "out">;
31
+ }, z.core.$strict>;
32
+ }, z.core.$strict>, z.ZodObject<{
33
+ capability: z.ZodLiteral<"production.snapshot">;
34
+ input: z.ZodObject<{
35
+ tenantId: z.core.$ZodBranded<z.ZodUUID, "TenantId", "out">;
36
+ productionId: z.core.$ZodBranded<z.ZodUUID, "ProductionId", "out">;
37
+ }, z.core.$strict>;
38
+ }, z.core.$strict>], "capability">;
39
+ }, z.core.$strict>;
7
40
  export declare const OperationSummarySchema: z.ZodObject<{
8
41
  humanLinks: z.ZodOptional<z.ZodDiscriminatedUnion<[z.ZodObject<{
9
42
  status: z.ZodLiteral<"AVAILABLE">;
@@ -74,6 +107,31 @@ export declare const OperationSummarySchema: z.ZodObject<{
74
107
  attempts: z.ZodInt;
75
108
  }, z.core.$strip>;
76
109
  blockers: z.ZodArray<z.ZodString>;
110
+ failure: z.ZodOptional<z.ZodObject<{
111
+ reasonCodes: z.ZodArray<z.ZodEnum<{
112
+ AMBIGUOUS: "AMBIGUOUS";
113
+ PERMANENT_OPERATIONAL: "PERMANENT_OPERATIONAL";
114
+ SEMANTIC: "SEMANTIC";
115
+ RATE_LIMIT: "RATE_LIMIT";
116
+ TRANSIENT: "TRANSIENT";
117
+ NOT_RECORDED: "NOT_RECORDED";
118
+ }>>;
119
+ summary: z.ZodString;
120
+ next: z.ZodDiscriminatedUnion<[z.ZodObject<{
121
+ capability: z.ZodLiteral<"operation.get">;
122
+ input: z.ZodObject<{
123
+ tenantId: z.core.$ZodBranded<z.ZodUUID, "TenantId", "out">;
124
+ productionId: z.core.$ZodBranded<z.ZodUUID, "ProductionId", "out">;
125
+ operationId: z.core.$ZodBranded<z.ZodString, "OperationId", "out">;
126
+ }, z.core.$strict>;
127
+ }, z.core.$strict>, z.ZodObject<{
128
+ capability: z.ZodLiteral<"production.snapshot">;
129
+ input: z.ZodObject<{
130
+ tenantId: z.core.$ZodBranded<z.ZodUUID, "TenantId", "out">;
131
+ productionId: z.core.$ZodBranded<z.ZodUUID, "ProductionId", "out">;
132
+ }, z.core.$strict>;
133
+ }, z.core.$strict>], "capability">;
134
+ }, z.core.$strict>>;
77
135
  nextActions: z.ZodArray<z.ZodObject<{
78
136
  capability: z.ZodString;
79
137
  targetType: z.ZodString;
@@ -87,5 +145,6 @@ export declare const OperationSummarySchema: z.ZodObject<{
87
145
  startedAt: z.ZodISODateTime;
88
146
  updatedAt: z.ZodISODateTime;
89
147
  }, z.core.$strip>;
148
+ export type OperationFailure = z.infer<typeof OperationFailureSchema>;
90
149
  export type OperationTarget = z.infer<typeof OperationTargetSchema>;
91
150
  export type OperationSummary = z.infer<typeof OperationSummarySchema>;
@@ -678,6 +678,31 @@ export declare const ProductionSnapshotSchema: z.ZodObject<{
678
678
  attempts: z.ZodInt;
679
679
  }, z.core.$strip>;
680
680
  blockers: z.ZodArray<z.ZodString>;
681
+ failure: z.ZodOptional<z.ZodObject<{
682
+ reasonCodes: z.ZodArray<z.ZodEnum<{
683
+ AMBIGUOUS: "AMBIGUOUS";
684
+ PERMANENT_OPERATIONAL: "PERMANENT_OPERATIONAL";
685
+ SEMANTIC: "SEMANTIC";
686
+ RATE_LIMIT: "RATE_LIMIT";
687
+ TRANSIENT: "TRANSIENT";
688
+ NOT_RECORDED: "NOT_RECORDED";
689
+ }>>;
690
+ summary: z.ZodString;
691
+ next: z.ZodDiscriminatedUnion<[z.ZodObject<{
692
+ capability: z.ZodLiteral<"operation.get">;
693
+ input: z.ZodObject<{
694
+ tenantId: z.core.$ZodBranded<z.ZodUUID, "TenantId", "out">;
695
+ productionId: z.core.$ZodBranded<z.ZodUUID, "ProductionId", "out">;
696
+ operationId: z.core.$ZodBranded<z.ZodString, "OperationId", "out">;
697
+ }, z.core.$strict>;
698
+ }, z.core.$strict>, z.ZodObject<{
699
+ capability: z.ZodLiteral<"production.snapshot">;
700
+ input: z.ZodObject<{
701
+ tenantId: z.core.$ZodBranded<z.ZodUUID, "TenantId", "out">;
702
+ productionId: z.core.$ZodBranded<z.ZodUUID, "ProductionId", "out">;
703
+ }, z.core.$strict>;
704
+ }, z.core.$strict>], "capability">;
705
+ }, z.core.$strict>>;
681
706
  nextActions: z.ZodArray<z.ZodObject<{
682
707
  capability: z.ZodString;
683
708
  targetType: z.ZodString;
@@ -166,6 +166,31 @@ export declare const OperationQueryPageSchema: z.ZodObject<{
166
166
  attempts: z.ZodInt;
167
167
  }, z.core.$strip>;
168
168
  blockers: z.ZodArray<z.ZodString>;
169
+ failure: z.ZodOptional<z.ZodObject<{
170
+ reasonCodes: z.ZodArray<z.ZodEnum<{
171
+ AMBIGUOUS: "AMBIGUOUS";
172
+ PERMANENT_OPERATIONAL: "PERMANENT_OPERATIONAL";
173
+ SEMANTIC: "SEMANTIC";
174
+ RATE_LIMIT: "RATE_LIMIT";
175
+ TRANSIENT: "TRANSIENT";
176
+ NOT_RECORDED: "NOT_RECORDED";
177
+ }>>;
178
+ summary: z.ZodString;
179
+ next: z.ZodDiscriminatedUnion<[z.ZodObject<{
180
+ capability: z.ZodLiteral<"operation.get">;
181
+ input: z.ZodObject<{
182
+ tenantId: z.core.$ZodBranded<z.ZodUUID, "TenantId", "out">;
183
+ productionId: z.core.$ZodBranded<z.ZodUUID, "ProductionId", "out">;
184
+ operationId: z.core.$ZodBranded<z.ZodString, "OperationId", "out">;
185
+ }, z.core.$strict>;
186
+ }, z.core.$strict>, z.ZodObject<{
187
+ capability: z.ZodLiteral<"production.snapshot">;
188
+ input: z.ZodObject<{
189
+ tenantId: z.core.$ZodBranded<z.ZodUUID, "TenantId", "out">;
190
+ productionId: z.core.$ZodBranded<z.ZodUUID, "ProductionId", "out">;
191
+ }, z.core.$strict>;
192
+ }, z.core.$strict>], "capability">;
193
+ }, z.core.$strict>>;
169
194
  nextActions: z.ZodArray<z.ZodObject<{
170
195
  capability: z.ZodString;
171
196
  targetType: z.ZodString;
@@ -28,9 +28,9 @@ export declare const WebhookAttemptViewSchema: z.ZodObject<{
28
28
  attemptId: z.ZodUUID;
29
29
  runtimeAttemptId: z.ZodUUID;
30
30
  outcome: z.ZodEnum<{
31
+ TRANSIENT: "TRANSIENT";
31
32
  STARTED: "STARTED";
32
33
  ACKNOWLEDGED: "ACKNOWLEDGED";
33
- TRANSIENT: "TRANSIENT";
34
34
  PERMANENT: "PERMANENT";
35
35
  SKIPPED: "SKIPPED";
36
36
  }>;
@@ -149,9 +149,9 @@ export declare const WebhookAttemptPageSchema: z.ZodObject<{
149
149
  attemptId: z.ZodUUID;
150
150
  runtimeAttemptId: z.ZodUUID;
151
151
  outcome: z.ZodEnum<{
152
+ TRANSIENT: "TRANSIENT";
152
153
  STARTED: "STARTED";
153
154
  ACKNOWLEDGED: "ACKNOWLEDGED";
154
- TRANSIENT: "TRANSIENT";
155
155
  PERMANENT: "PERMANENT";
156
156
  SKIPPED: "SKIPPED";
157
157
  }>;
@@ -223,6 +223,54 @@ export declare const StudioNavigationSchema: z.ZodObject<{
223
223
  }, z.core.$strict>;
224
224
  }, z.core.$strict>;
225
225
  }, z.core.$strict>], "tool">>;
226
+ failure: z.ZodOptional<z.ZodObject<{
227
+ reasonCodes: z.ZodArray<z.ZodEnum<{
228
+ AMBIGUOUS: "AMBIGUOUS";
229
+ PERMANENT_OPERATIONAL: "PERMANENT_OPERATIONAL";
230
+ SEMANTIC: "SEMANTIC";
231
+ RATE_LIMIT: "RATE_LIMIT";
232
+ TRANSIENT: "TRANSIENT";
233
+ NOT_RECORDED: "NOT_RECORDED";
234
+ }>>;
235
+ summary: z.ZodString;
236
+ next: z.ZodNullable<z.ZodUnion<readonly [z.ZodDiscriminatedUnion<[z.ZodObject<{
237
+ tool: z.ZodLiteral<"operation_get">;
238
+ arguments: z.ZodObject<{
239
+ tenantId: z.core.$ZodBranded<z.ZodUUID, "TenantId", "out">;
240
+ productionId: z.core.$ZodBranded<z.ZodUUID, "ProductionId", "out">;
241
+ operationId: z.core.$ZodBranded<z.ZodString, "OperationId", "out">;
242
+ }, z.core.$strict>;
243
+ }, z.core.$strict>, z.ZodObject<{
244
+ tool: z.ZodLiteral<"studio_capability_query">;
245
+ arguments: z.ZodObject<{
246
+ tenantId: z.core.$ZodBranded<z.ZodUUID, "TenantId", "out">;
247
+ capabilityVersion: z.ZodOptional<z.ZodString>;
248
+ tool: z.ZodLiteral<"operation_get">;
249
+ arguments: z.ZodObject<{
250
+ tenantId: z.core.$ZodBranded<z.ZodUUID, "TenantId", "out">;
251
+ productionId: z.core.$ZodBranded<z.ZodUUID, "ProductionId", "out">;
252
+ operationId: z.core.$ZodBranded<z.ZodString, "OperationId", "out">;
253
+ }, z.core.$strict>;
254
+ }, z.core.$strict>;
255
+ }, z.core.$strict>], "tool">, z.ZodObject<{
256
+ tool: z.ZodLiteral<"production_snapshot">;
257
+ arguments: z.ZodObject<{
258
+ tenantId: z.core.$ZodBranded<z.ZodUUID, "TenantId", "out">;
259
+ productionId: z.core.$ZodBranded<z.ZodUUID, "ProductionId", "out">;
260
+ }, z.core.$strict>;
261
+ }, z.core.$strict>, z.ZodObject<{
262
+ tool: z.ZodLiteral<"studio_capability_query">;
263
+ arguments: z.ZodObject<{
264
+ tenantId: z.core.$ZodBranded<z.ZodUUID, "TenantId", "out">;
265
+ capabilityVersion: z.ZodOptional<z.ZodString>;
266
+ tool: z.ZodLiteral<"production_snapshot">;
267
+ arguments: z.ZodObject<{
268
+ tenantId: z.core.$ZodBranded<z.ZodUUID, "TenantId", "out">;
269
+ productionId: z.core.$ZodBranded<z.ZodUUID, "ProductionId", "out">;
270
+ }, z.core.$strict>;
271
+ }, z.core.$strict>;
272
+ }, z.core.$strict>]>>;
273
+ }, z.core.$strict>>;
226
274
  targetCount: z.ZodInt;
227
275
  blockerCount: z.ZodInt;
228
276
  evidence: z.ZodObject<{
@@ -234,8 +282,8 @@ export declare const StudioNavigationSchema: z.ZodObject<{
234
282
  tenantId: z.core.$ZodBranded<z.ZodUUID, "TenantId", "out">;
235
283
  catalogVersion: z.ZodString;
236
284
  outcome: z.ZodEnum<{
237
- MATCHES: "MATCHES";
238
285
  AMBIGUOUS: "AMBIGUOUS";
286
+ MATCHES: "MATCHES";
239
287
  NO_MATCH: "NO_MATCH";
240
288
  }>;
241
289
  candidates: z.ZodArray<z.ZodObject<{
@@ -145,8 +145,8 @@ export declare const CapabilitySearchSchema: z.ZodObject<{
145
145
  tenantId: z.core.$ZodBranded<z.ZodUUID, "TenantId", "out">;
146
146
  catalogVersion: z.ZodString;
147
147
  outcome: z.ZodEnum<{
148
- MATCHES: "MATCHES";
149
148
  AMBIGUOUS: "AMBIGUOUS";
149
+ MATCHES: "MATCHES";
150
150
  NO_MATCH: "NO_MATCH";
151
151
  }>;
152
152
  candidates: z.ZodArray<z.ZodObject<{
package/dist/entry.js CHANGED
@@ -1,2 +1,2 @@
1
1
  #!/usr/bin/env node
2
- if(process.argv[2]==="observe"){process.exitCode=await(await import("./_chunks/observe-entry-E6DFHIMW.js")).runObservationEntry(process.argv.slice(3))}else if(process.argv[2]==="host"){const{runHostCli}=await import("./_chunks/host-main-JLIBRHC2.js");const result=await runHostCli(process.argv.slice(3));process.stdout.write(JSON.stringify(result.output)+"\n");process.exitCode=result.exitCode}else if(process.argv[2]==="local"){if(process.argv[3]==="mcp"){const{runLocalMcp}=await import("./_chunks/local-mcp-ISMU6ADI.js");process.exitCode=await runLocalMcp(process.argv.slice(4))}else{const{runLocalCli}=await import("./_chunks/local-main-KTYCLHDA.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-HNLJCG45.js");process.exitCode=await runMcpStdio(process.argv.slice(3),process.env)}else{const{runRemoteCli}=await import("./_chunks/main-MOZS2EK3.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]==="observe"){process.exitCode=await(await import("./_chunks/observe-entry-JVZAMB7N.js")).runObservationEntry(process.argv.slice(3))}else if(process.argv[2]==="host"){const{runHostCli}=await import("./_chunks/host-main-KLWW7R47.js");const result=await runHostCli(process.argv.slice(3));process.stdout.write(JSON.stringify(result.output)+"\n");process.exitCode=result.exitCode}else if(process.argv[2]==="local"){if(process.argv[3]==="mcp"){const{runLocalMcp}=await import("./_chunks/local-mcp-AARKBDU5.js");process.exitCode=await runLocalMcp(process.argv.slice(4))}else{const{runLocalCli}=await import("./_chunks/local-main-5BW63USP.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-HNLJCG45.js");process.exitCode=await runMcpStdio(process.argv.slice(3),process.env)}else{const{runRemoteCli}=await import("./_chunks/main-LGYJ3ZCN.js");const result=await runRemoteCli(process.argv.slice(2));process.stdout.write(JSON.stringify(result.output)+"\n");process.exitCode=result.exitCode}
@@ -1 +1 @@
1
- import{prepareInstalledCpuSpeech}from"./_chunks/chunk-FVY3PLG7.js";import{configureDesktopChannel,desktopChannelInfo,desktopRuntimeChannel}from"./_chunks/chunk-4PAVWOPA.js";import{DesktopBootstrapReplySchema,DesktopBootstrapRequestSchema,DesktopOwnerRequestSchema,DesktopRuntimeStatusSchema,desktopOwnerResponses,runDesktopAgentRequest,runDesktopOfflineRequest,runDesktopStorageRequest,runDesktopWorkspaceRequest}from"./_chunks/chunk-4M2SOMSN.js";import{DesktopLibraryImportRequestSchema,DesktopLibraryImportSeedSchema,DesktopLibraryMediaRequestSchema,DesktopLibraryPrepareRequestSchema,DesktopLibraryReplySchema,DesktopLibraryRequestSchema,prepareDesktopLibraryImport,runDesktopLibraryImport,runDesktopLibraryMedia,runDesktopLibraryRequest}from"./_chunks/chunk-L3QA7FLZ.js";import{desktopDevicePending,runDesktopDeviceRequest}from"./_chunks/chunk-ROGOASYF.js";import"./_chunks/chunk-HBDPYWMI.js";import{disableDesktopAutomation}from"./_chunks/chunk-MLZ3ZPGU.js";import{LocalInstallationManager,captureInstalledTools,ownerClient,socketAbsent,toolPreference}from"./_chunks/chunk-ELUJ44BO.js";import{desktopDeviceConnector}from"./_chunks/chunk-AFNJRZLJ.js";import{DesktopDeviceReplySchema,DesktopDeviceScopeSchema}from"./_chunks/chunk-IYDHDLTR.js";import{LocalReleaseSchema,catalogue,newerVersion}from"./_chunks/chunk-6EZX2TRX.js";import{canonicalLocalJson}from"./_chunks/chunk-APNZQZFB.js";import{directory,fail,optional,read,sha256,write}from"./_chunks/chunk-DLW42PJ6.js";import"./_chunks/chunk-WTJVS2VS.js";import"./_chunks/chunk-TT7IA5HB.js";async function desktopRuntimeStatus(manager){const status=await manager.status();const stopped=!status.running&&status.activeVersion?await socketAbsent((await manager.configuration()).stateDirectory):false;const active=(await manager.ledger.current()).value.active;const tools=active?.toolsConfigPath?await toolPreference(active.toolsConfigPath,null):null;return DesktopRuntimeStatusSchema.parse({protocol:"NVS_DESKTOP_RUNTIME_STATUS_V1",state:status.running?"RUNNING":stopped?"STOPPED":status.activeVersion?"UNAVAILABLE":"INSTALL_REQUIRED",activeVersion:status.activeVersion,phase:status.phase,toolMode:tools?.mode??null,...tools?.cpuSpeech?{speech:{voiceIds:tools.cpuSpeech.voiceIds}}:{}})}import{z}from"zod";import{join}from"node:path";import{randomUUID}from"node:crypto";var digest=z.string().regex(/^[a-f0-9]{64}$/);var intentSchema=z.strictObject({id:z.uuid(),channel:z.strictObject({protocol:z.literal("NVS_DESKTOP_RUNTIME_CHANNEL_V1"),catalogueUrl:z.string().url(),publicKey:z.string()}),release:LocalReleaseSchema,installationRevision:z.int().nonnegative(),expiresAt:z.iso.datetime()});async function runDesktopBootstrap(home,raw,bundled){const{call}=DesktopBootstrapRequestSchema.parse(raw),manager=await LocalInstallationManager.open(home),root=await directory(join(home,"bootstrap-plans"));let intent,fingerprint;if(call.action==="prepare"){const info=await desktopChannelInfo(manager,bundled);if(!info.channelFingerprint)fail("DESKTOP_CHANNEL_REQUIRED");const configuration=info.configured?await manager.configuration():null;if(configuration&&!configuration.publicKeyFile)fail("DESKTOP_CHANNEL_CHANGED");const channel=desktopRuntimeChannel(configuration?{protocol:"NVS_DESKTOP_RUNTIME_CHANNEL_V1",catalogueUrl:configuration.catalogueUrl,publicKey:(await read(configuration.publicKeyFile,16384)).toString()}:bundled);const publicKeyFile=join(root,channel.fingerprint+".pem");try{await write(publicKeyFile,channel.value.publicKey,true)}catch(e){if(e.code!=="EEXIST"||(await read(publicKeyFile,16384)).toString()!==channel.value.publicKey)throw e}const trusted=await catalogue({catalogueUrl:channel.value.catalogueUrl,publicKeyFile});const candidates=trusted.signed.catalogue.releases.filter(r=>r.descriptor.workProtocol==="NVS_LOCAL_WORK_V2"&&r.descriptor.platform.os===process.platform&&r.descriptor.platform.architecture===process.arch&&!!r.tools);const release=candidates.reduce((a,b)=>!a||newerVersion(b.descriptor.version,a.descriptor.version)?b:a,null);if(!release)fail("LOCAL_PROFILE_UNAVAILABLE");intent=intentSchema.parse({id:randomUUID(),channel:channel.value,release,installationRevision:(await manager.ledger.current()).value.revision,expiresAt:new Date(Math.min(Date.now()+18e5,Date.parse(trusted.signed.catalogue.expiresAt))).toISOString()});fingerprint=sha256(canonicalLocalJson(intent));await write(join(root,intent.id+".json"),canonicalLocalJson({intent,fingerprint}),true)}else{const saved=z.strictObject({intent:intentSchema,fingerprint:digest}).parse(JSON.parse((await read(join(root,call.id+".json"),131072)).toString()));intent=saved.intent;fingerprint=saved.fingerprint;if(fingerprint!==call.fingerprint||fingerprint!==sha256(canonicalLocalJson(intent))||intent.id!==call.id)fail("PLAN_CHANGED");const receiptFile=join(root,intent.id+".installation.json");const receipt=z.strictObject({id:z.uuid(),fingerprint:digest}).nullable().parse(await optional(receiptFile));if(receipt){const state=(await manager.ledger.current()).value;if(state.transition){if(state.transition.planId!==receipt.id)fail("RECOVERY_REQUIRED");await manager.reconcile(receipt.id,receipt.fingerprint)}}else{if(Date.parse(intent.expiresAt)<=Date.now()||(await manager.ledger.current()).value.revision!==intent.installationRevision)fail("PLAN_CHANGED");const trust=desktopRuntimeChannel(intent.channel);await configureDesktopChannel(manager,trust.fingerprint,intent.channel);const plan=await manager.prepare(intent.release.descriptor.version,{mode:"MANAGED"});if(canonicalLocalJson(plan.release)!==canonicalLocalJson(intent.release))fail("PLAN_CHANGED");await write(receiptFile,canonicalLocalJson({id:plan.planId,fingerprint:plan.fingerprint}),true);await manager.apply(plan.planId,plan.fingerprint)}const installed=(await manager.ledger.current()).value;if(installed.transition||canonicalLocalJson(installed.active?.descriptor)!==canonicalLocalJson(intent.release.descriptor))fail("RECOVERY_REQUIRED");const configuration=await manager.configuration(),report=await(await ownerClient(configuration.stateDirectory)).doctor();if(!report.executionProfiles?.includes("STUDIO_MEDIA_V2"))fail("LOCAL_PROFILE_UNAVAILABLE");if((await desktopRuntimeStatus(manager)).state!=="RUNNING")fail("RECOVERY_REQUIRED")}return DesktopBootstrapReplySchema.parse({id:intent.id,fingerprint,version:intent.release.descriptor.version,host:new URL(intent.channel.catalogueUrl).host,bytes:intent.release.package.byteSize+Object.values(intent.release.tools??{}).reduce((sum,a)=>sum+a.byteSize,0),expiresAt:intent.expiresAt,installed:call.action==="apply"})}async function runDesktopOwnerRequest(home,raw,bundledChannel){const request=DesktopOwnerRequestSchema.parse(raw),manager=await LocalInstallationManager.open(home);let result;switch(request.operation){case"library":result=await runDesktopLibraryRequest(home,request);break;case"library-import":result=await runDesktopLibraryImport(home,request);break;case"library-import-prepare":result=await prepareDesktopLibraryImport(request);break;case"bootstrap":result=await runDesktopBootstrap(home,request,bundledChannel);break;case"agent":result=await runDesktopAgentRequest(home,request);break;case"offline":result=await runDesktopOfflineRequest(home,request);break;case"storage":result=await runDesktopStorageRequest(home,request);break;case"workspace":result=await runDesktopWorkspaceRequest(home,request);break;case"device":result=await runDesktopDeviceRequest(home,request);break;case"status":case"start":case"stop":if(request.operation==="start")await manager.start();if(request.operation==="stop"){await disableDesktopAutomation(home);await manager.stop()}result=await desktopRuntimeStatus(manager);break;case"configuration":result=await desktopChannelInfo(manager,bundledChannel);break;case"configure":await configureDesktopChannel(manager,request.channelFingerprint,bundledChannel);result=await desktopRuntimeStatus(manager);break;case"check":{const checked=await manager.check();result={protocol:"NVS_DESKTOP_RUNTIME_UPDATES_V1",activeVersion:checked.installation.activeVersion,versions:checked.available.map(v=>({version:v.version,rejected:checked.rejectedVersions.includes(v.version)})),notifications:checked.notifications};break}case"speech-prepare":{const prepared=await prepareInstalledCpuSpeech(manager,request.input),plan=prepared.plan;result={protocol:"NVS_DESKTOP_OWNER_PLAN_V1",plan:{kind:"APPLY",toolMode:plan.toolSelection?.mode,planId:plan.planId,fingerprint:plan.fingerprint,version:plan.release.descriptor.version,previousVersion:(await manager.status()).activeVersion,expiresAt:plan.expiresAt,phase:"PREPARED"}};break}case"prepare":case"tools-prepare":{const choice=request.operation==="tools-prepare"?request.choice.mode==="MANAGED"?request.choice:await captureInstalledTools(request.choice):void 0;const plan=await manager.prepare(request.version,choice);result={protocol:"NVS_DESKTOP_OWNER_PLAN_V1",plan:{kind:"APPLY",...choice?{toolMode:choice.mode}:{},planId:plan.planId,fingerprint:plan.fingerprint,version:plan.release.descriptor.version,previousVersion:(await manager.status()).activeVersion,expiresAt:plan.expiresAt,phase:"PREPARED"}};break}case"recovery":{const current=(await manager.ledger.current()).value,transition=current.transition;let plan=null;if(transition){const original=await manager.plan(transition.planId);if(original.fingerprint!==transition.fingerprint)fail("PLAN_CHANGED");plan={kind:"RECOVER",planId:original.planId,fingerprint:original.fingerprint,version:original.release.descriptor.version,previousVersion:transition.previous?.descriptor.version??null,expiresAt:original.expiresAt,phase:transition.phase}}result={protocol:"NVS_DESKTOP_OWNER_PLAN_V1",plan};break}case"apply":case"recover":if(request.operation==="apply")await manager.apply(request.planId,request.fingerprint);else await manager.reconcile(request.planId,request.fingerprint);result=await desktopRuntimeStatus(manager);break;case"reject":await manager.reject(request.version);result=await desktopRuntimeStatus(manager);break}return desktopOwnerResponses[request.operation].parse(result)}import{lstat,readFile,chmod}from"node:fs/promises";import{join as join2,isAbsolute,dirname}from"node:path";async function verifiedSource(source,expected,limit){if(!isAbsolute(source)||!/^[a-f0-9]{64}$/.test(expected))fail("DESKTOP_DISTRIBUTION_INVALID");const stat=await lstat(source);if(!stat.isFile()||stat.isSymbolicLink()||stat.size>limit)fail("DESKTOP_DISTRIBUTION_INVALID");const bytes=await readFile(source);if(bytes.length>limit||sha256(bytes)!==expected)fail("DESKTOP_DISTRIBUTION_INVALID");return bytes}async function retain(target,bytes,expected,limit,mode){try{if(sha256(await read(target,limit))!==expected)fail("DESKTOP_DISTRIBUTION_INVALID")}catch(error){if(error.code!=="ENOENT")throw error;try{await write(target,bytes,true)}catch(error2){if(error2.code!=="EEXIST")throw error2}if(sha256(await read(target,limit))!==expected)fail("DESKTOP_DISTRIBUTION_INVALID")}await chmod(target,mode)}async function materializeDesktopNode(home,source,expected,licenseDigest){const bytes=await verifiedSource(source,expected,160*1024*1024);const license=licenseDigest?await verifiedSource(join2(dirname(source),"LICENSE.txt"),licenseDigest,2*1024*1024):null;const base=await directory(join2(await directory(home),"nodes",expected)),target=join2(base,process.platform==="win32"?"node.exe":"node");if(license)await retain(join2(base,"LICENSE.txt"),license,licenseDigest,2*1024*1024,256);await retain(target,bytes,expected,160*1024*1024,320);return target}async function runLocalManagement(home,operation){if(!["status","start","stop"].includes(operation))throw Error("INVALID_INPUT");const manager=await LocalInstallationManager.open(home);if(operation==="start")await manager.start();if(operation==="stop")await manager.stop();return desktopRuntimeStatus(manager)}export{DesktopDeviceReplySchema,DesktopDeviceScopeSchema,DesktopLibraryImportRequestSchema,DesktopLibraryImportSeedSchema,DesktopLibraryMediaRequestSchema,DesktopLibraryPrepareRequestSchema,DesktopLibraryReplySchema,DesktopLibraryRequestSchema,DesktopOwnerRequestSchema,desktopDeviceConnector,desktopDevicePending,desktopOwnerResponses,desktopRuntimeChannel,materializeDesktopNode,prepareDesktopLibraryImport,runDesktopLibraryMedia,runDesktopOwnerRequest,runLocalManagement};
1
+ import{prepareInstalledCpuSpeech}from"./_chunks/chunk-VXYZCCCQ.js";import{configureDesktopChannel,desktopChannelInfo,desktopRuntimeChannel}from"./_chunks/chunk-7IVAYDU3.js";import{DesktopBootstrapReplySchema,DesktopBootstrapRequestSchema,DesktopOwnerRequestSchema,DesktopRuntimeStatusSchema,desktopOwnerResponses,runDesktopAgentRequest,runDesktopOfflineRequest,runDesktopStorageRequest,runDesktopWorkspaceRequest}from"./_chunks/chunk-WLQMICJN.js";import{DesktopLibraryImportRequestSchema,DesktopLibraryImportSeedSchema,DesktopLibraryMediaRequestSchema,DesktopLibraryPrepareRequestSchema,DesktopLibraryReplySchema,DesktopLibraryRequestSchema,prepareDesktopLibraryImport,runDesktopLibraryImport,runDesktopLibraryMedia,runDesktopLibraryRequest}from"./_chunks/chunk-DMA53YVU.js";import{desktopDevicePending,runDesktopDeviceRequest}from"./_chunks/chunk-PQCA4X5H.js";import"./_chunks/chunk-H4FH6STZ.js";import{disableDesktopAutomation}from"./_chunks/chunk-MZWEFYHE.js";import{LocalInstallationManager,captureInstalledTools,ownerClient,socketAbsent,toolPreference}from"./_chunks/chunk-FFXSXE3G.js";import{desktopDeviceConnector}from"./_chunks/chunk-ETK7GYCB.js";import{DesktopDeviceReplySchema,DesktopDeviceScopeSchema}from"./_chunks/chunk-SM2I7TJ3.js";import{LocalReleaseSchema,catalogue,newerVersion}from"./_chunks/chunk-LDBXGRCQ.js";import{canonicalLocalJson}from"./_chunks/chunk-2S7FI3HF.js";import{directory,fail,optional,read,sha256,write}from"./_chunks/chunk-DLW42PJ6.js";import"./_chunks/chunk-WTJVS2VS.js";import"./_chunks/chunk-TT7IA5HB.js";async function desktopRuntimeStatus(manager){const status=await manager.status();const stopped=!status.running&&status.activeVersion?await socketAbsent((await manager.configuration()).stateDirectory):false;const active=(await manager.ledger.current()).value.active;const tools=active?.toolsConfigPath?await toolPreference(active.toolsConfigPath,null):null;return DesktopRuntimeStatusSchema.parse({protocol:"NVS_DESKTOP_RUNTIME_STATUS_V1",state:status.running?"RUNNING":stopped?"STOPPED":status.activeVersion?"UNAVAILABLE":"INSTALL_REQUIRED",activeVersion:status.activeVersion,phase:status.phase,toolMode:tools?.mode??null,...tools?.cpuSpeech?{speech:{voiceIds:tools.cpuSpeech.voiceIds}}:{}})}import{z}from"zod";import{join}from"node:path";import{randomUUID}from"node:crypto";var digest=z.string().regex(/^[a-f0-9]{64}$/);var intentSchema=z.strictObject({id:z.uuid(),channel:z.strictObject({protocol:z.literal("NVS_DESKTOP_RUNTIME_CHANNEL_V1"),catalogueUrl:z.string().url(),publicKey:z.string()}),release:LocalReleaseSchema,installationRevision:z.int().nonnegative(),expiresAt:z.iso.datetime()});async function runDesktopBootstrap(home,raw,bundled){const{call}=DesktopBootstrapRequestSchema.parse(raw),manager=await LocalInstallationManager.open(home),root=await directory(join(home,"bootstrap-plans"));let intent,fingerprint;if(call.action==="prepare"){const info=await desktopChannelInfo(manager,bundled);if(!info.channelFingerprint)fail("DESKTOP_CHANNEL_REQUIRED");const configuration=info.configured?await manager.configuration():null;if(configuration&&!configuration.publicKeyFile)fail("DESKTOP_CHANNEL_CHANGED");const channel=desktopRuntimeChannel(configuration?{protocol:"NVS_DESKTOP_RUNTIME_CHANNEL_V1",catalogueUrl:configuration.catalogueUrl,publicKey:(await read(configuration.publicKeyFile,16384)).toString()}:bundled);const publicKeyFile=join(root,channel.fingerprint+".pem");try{await write(publicKeyFile,channel.value.publicKey,true)}catch(e){if(e.code!=="EEXIST"||(await read(publicKeyFile,16384)).toString()!==channel.value.publicKey)throw e}const trusted=await catalogue({catalogueUrl:channel.value.catalogueUrl,publicKeyFile});const candidates=trusted.signed.catalogue.releases.filter(r=>r.descriptor.workProtocol==="NVS_LOCAL_WORK_V2"&&r.descriptor.platform.os===process.platform&&r.descriptor.platform.architecture===process.arch&&!!r.tools);const release=candidates.reduce((a,b)=>!a||newerVersion(b.descriptor.version,a.descriptor.version)?b:a,null);if(!release)fail("LOCAL_PROFILE_UNAVAILABLE");intent=intentSchema.parse({id:randomUUID(),channel:channel.value,release,installationRevision:(await manager.ledger.current()).value.revision,expiresAt:new Date(Math.min(Date.now()+18e5,Date.parse(trusted.signed.catalogue.expiresAt))).toISOString()});fingerprint=sha256(canonicalLocalJson(intent));await write(join(root,intent.id+".json"),canonicalLocalJson({intent,fingerprint}),true)}else{const saved=z.strictObject({intent:intentSchema,fingerprint:digest}).parse(JSON.parse((await read(join(root,call.id+".json"),131072)).toString()));intent=saved.intent;fingerprint=saved.fingerprint;if(fingerprint!==call.fingerprint||fingerprint!==sha256(canonicalLocalJson(intent))||intent.id!==call.id)fail("PLAN_CHANGED");const receiptFile=join(root,intent.id+".installation.json");const receipt=z.strictObject({id:z.uuid(),fingerprint:digest}).nullable().parse(await optional(receiptFile));if(receipt){const state=(await manager.ledger.current()).value;if(state.transition){if(state.transition.planId!==receipt.id)fail("RECOVERY_REQUIRED");await manager.reconcile(receipt.id,receipt.fingerprint)}}else{if(Date.parse(intent.expiresAt)<=Date.now()||(await manager.ledger.current()).value.revision!==intent.installationRevision)fail("PLAN_CHANGED");const trust=desktopRuntimeChannel(intent.channel);await configureDesktopChannel(manager,trust.fingerprint,intent.channel);const plan=await manager.prepare(intent.release.descriptor.version,{mode:"MANAGED"});if(canonicalLocalJson(plan.release)!==canonicalLocalJson(intent.release))fail("PLAN_CHANGED");await write(receiptFile,canonicalLocalJson({id:plan.planId,fingerprint:plan.fingerprint}),true);await manager.apply(plan.planId,plan.fingerprint)}const installed=(await manager.ledger.current()).value;if(installed.transition||canonicalLocalJson(installed.active?.descriptor)!==canonicalLocalJson(intent.release.descriptor))fail("RECOVERY_REQUIRED");const configuration=await manager.configuration(),report=await(await ownerClient(configuration.stateDirectory)).doctor();if(!report.executionProfiles?.includes("STUDIO_MEDIA_V2"))fail("LOCAL_PROFILE_UNAVAILABLE");if((await desktopRuntimeStatus(manager)).state!=="RUNNING")fail("RECOVERY_REQUIRED")}return DesktopBootstrapReplySchema.parse({id:intent.id,fingerprint,version:intent.release.descriptor.version,host:new URL(intent.channel.catalogueUrl).host,bytes:intent.release.package.byteSize+Object.values(intent.release.tools??{}).reduce((sum,a)=>sum+a.byteSize,0),expiresAt:intent.expiresAt,installed:call.action==="apply"})}async function runDesktopOwnerRequest(home,raw,bundledChannel){const request=DesktopOwnerRequestSchema.parse(raw),manager=await LocalInstallationManager.open(home);let result;switch(request.operation){case"library":result=await runDesktopLibraryRequest(home,request);break;case"library-import":result=await runDesktopLibraryImport(home,request);break;case"library-import-prepare":result=await prepareDesktopLibraryImport(request);break;case"bootstrap":result=await runDesktopBootstrap(home,request,bundledChannel);break;case"agent":result=await runDesktopAgentRequest(home,request);break;case"offline":result=await runDesktopOfflineRequest(home,request);break;case"storage":result=await runDesktopStorageRequest(home,request);break;case"workspace":result=await runDesktopWorkspaceRequest(home,request);break;case"device":result=await runDesktopDeviceRequest(home,request);break;case"status":case"start":case"stop":if(request.operation==="start")await manager.start();if(request.operation==="stop"){await disableDesktopAutomation(home);await manager.stop()}result=await desktopRuntimeStatus(manager);break;case"configuration":result=await desktopChannelInfo(manager,bundledChannel);break;case"configure":await configureDesktopChannel(manager,request.channelFingerprint,bundledChannel);result=await desktopRuntimeStatus(manager);break;case"check":{const checked=await manager.check();result={protocol:"NVS_DESKTOP_RUNTIME_UPDATES_V1",activeVersion:checked.installation.activeVersion,versions:checked.available.map(v=>({version:v.version,rejected:checked.rejectedVersions.includes(v.version)})),notifications:checked.notifications};break}case"speech-prepare":{const prepared=await prepareInstalledCpuSpeech(manager,request.input),plan=prepared.plan;result={protocol:"NVS_DESKTOP_OWNER_PLAN_V1",plan:{kind:"APPLY",toolMode:plan.toolSelection?.mode,planId:plan.planId,fingerprint:plan.fingerprint,version:plan.release.descriptor.version,previousVersion:(await manager.status()).activeVersion,expiresAt:plan.expiresAt,phase:"PREPARED"}};break}case"prepare":case"tools-prepare":{const choice=request.operation==="tools-prepare"?request.choice.mode==="MANAGED"?request.choice:await captureInstalledTools(request.choice):void 0;const plan=await manager.prepare(request.version,choice);result={protocol:"NVS_DESKTOP_OWNER_PLAN_V1",plan:{kind:"APPLY",...choice?{toolMode:choice.mode}:{},planId:plan.planId,fingerprint:plan.fingerprint,version:plan.release.descriptor.version,previousVersion:(await manager.status()).activeVersion,expiresAt:plan.expiresAt,phase:"PREPARED"}};break}case"recovery":{const current=(await manager.ledger.current()).value,transition=current.transition;let plan=null;if(transition){const original=await manager.plan(transition.planId);if(original.fingerprint!==transition.fingerprint)fail("PLAN_CHANGED");plan={kind:"RECOVER",planId:original.planId,fingerprint:original.fingerprint,version:original.release.descriptor.version,previousVersion:transition.previous?.descriptor.version??null,expiresAt:original.expiresAt,phase:transition.phase}}result={protocol:"NVS_DESKTOP_OWNER_PLAN_V1",plan};break}case"apply":case"recover":if(request.operation==="apply")await manager.apply(request.planId,request.fingerprint);else await manager.reconcile(request.planId,request.fingerprint);result=await desktopRuntimeStatus(manager);break;case"reject":await manager.reject(request.version);result=await desktopRuntimeStatus(manager);break}return desktopOwnerResponses[request.operation].parse(result)}import{lstat,readFile,chmod}from"node:fs/promises";import{join as join2,isAbsolute,dirname}from"node:path";async function verifiedSource(source,expected,limit){if(!isAbsolute(source)||!/^[a-f0-9]{64}$/.test(expected))fail("DESKTOP_DISTRIBUTION_INVALID");const stat=await lstat(source);if(!stat.isFile()||stat.isSymbolicLink()||stat.size>limit)fail("DESKTOP_DISTRIBUTION_INVALID");const bytes=await readFile(source);if(bytes.length>limit||sha256(bytes)!==expected)fail("DESKTOP_DISTRIBUTION_INVALID");return bytes}async function retain(target,bytes,expected,limit,mode){try{if(sha256(await read(target,limit))!==expected)fail("DESKTOP_DISTRIBUTION_INVALID")}catch(error){if(error.code!=="ENOENT")throw error;try{await write(target,bytes,true)}catch(error2){if(error2.code!=="EEXIST")throw error2}if(sha256(await read(target,limit))!==expected)fail("DESKTOP_DISTRIBUTION_INVALID")}await chmod(target,mode)}async function materializeDesktopNode(home,source,expected,licenseDigest){const bytes=await verifiedSource(source,expected,160*1024*1024);const license=licenseDigest?await verifiedSource(join2(dirname(source),"LICENSE.txt"),licenseDigest,2*1024*1024):null;const base=await directory(join2(await directory(home),"nodes",expected)),target=join2(base,process.platform==="win32"?"node.exe":"node");if(license)await retain(join2(base,"LICENSE.txt"),license,licenseDigest,2*1024*1024,256);await retain(target,bytes,expected,160*1024*1024,320);return target}async function runLocalManagement(home,operation){if(!["status","start","stop"].includes(operation))throw Error("INVALID_INPUT");const manager=await LocalInstallationManager.open(home);if(operation==="start")await manager.start();if(operation==="stop")await manager.stop();return desktopRuntimeStatus(manager)}export{DesktopDeviceReplySchema,DesktopDeviceScopeSchema,DesktopLibraryImportRequestSchema,DesktopLibraryImportSeedSchema,DesktopLibraryMediaRequestSchema,DesktopLibraryPrepareRequestSchema,DesktopLibraryReplySchema,DesktopLibraryRequestSchema,DesktopOwnerRequestSchema,desktopDeviceConnector,desktopDevicePending,desktopOwnerResponses,desktopRuntimeChannel,materializeDesktopNode,prepareDesktopLibraryImport,runDesktopLibraryMedia,runDesktopOwnerRequest,runLocalManagement};
@@ -1 +1 @@
1
- import{LocalMcpTools}from"./_chunks/chunk-QK4XPVKT.js";import{desktopDeviceConnector}from"./_chunks/chunk-AFNJRZLJ.js";import{DesktopDeviceScopeSchema}from"./_chunks/chunk-IYDHDLTR.js";import"./_chunks/chunk-6EZX2TRX.js";import"./_chunks/chunk-APNZQZFB.js";import"./_chunks/chunk-DLW42PJ6.js";import"./_chunks/chunk-WTJVS2VS.js";import"./_chunks/chunk-TT7IA5HB.js";async function openDesktopDeviceTools(raw,home){const scope=DesktopDeviceScopeSchema.parse(raw);return LocalMcpTools.open(await desktopDeviceConnector(home,scope),home)}export{LocalMcpTools,openDesktopDeviceTools};
1
+ import{LocalMcpTools}from"./_chunks/chunk-4AD4PNUX.js";import{desktopDeviceConnector}from"./_chunks/chunk-ETK7GYCB.js";import{DesktopDeviceScopeSchema}from"./_chunks/chunk-SM2I7TJ3.js";import"./_chunks/chunk-LDBXGRCQ.js";import"./_chunks/chunk-2S7FI3HF.js";import"./_chunks/chunk-DLW42PJ6.js";import"./_chunks/chunk-WTJVS2VS.js";import"./_chunks/chunk-TT7IA5HB.js";async function openDesktopDeviceTools(raw,home){const scope=DesktopDeviceScopeSchema.parse(raw);return LocalMcpTools.open(await desktopDeviceConnector(home,scope),home)}export{LocalMcpTools,openDesktopDeviceTools};