@nativestudio/cli 0.3.0-rc.19 → 0.3.0-rc.20
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/COMPATIBILITY.json +8 -8
- package/components/runtime.json +4 -4
- package/components/runtime.tgz +0 -0
- package/dist/_chunks/{chunk-WXEERCXN.js → chunk-4M2SOMSN.js} +1 -1
- package/dist/_chunks/{chunk-2GV47BUV.js → chunk-4PAVWOPA.js} +1 -1
- package/dist/_chunks/{chunk-CTCEGOC7.js → chunk-6EZX2TRX.js} +1 -1
- package/dist/_chunks/{chunk-BZPQB66Z.js → chunk-AFNJRZLJ.js} +1 -1
- package/dist/_chunks/chunk-APNZQZFB.js +1 -0
- package/dist/_chunks/chunk-D74NHT4I.js +45 -0
- package/dist/_chunks/chunk-ELUJ44BO.js +1 -0
- package/dist/_chunks/{chunk-AIR7YOFU.js → chunk-FVY3PLG7.js} +1 -1
- package/dist/_chunks/{chunk-4NCE337I.js → chunk-GLAF74UU.js} +1 -1
- package/dist/_chunks/{chunk-GQ32ZQTM.js → chunk-HBDPYWMI.js} +1 -1
- package/dist/_chunks/{chunk-5TKBEFRX.js → chunk-IYDHDLTR.js} +1 -1
- package/dist/_chunks/{chunk-2MKMGMA4.js → chunk-K35CWLDH.js} +1 -1
- package/dist/_chunks/{chunk-HIBT6NXN.js → chunk-L3QA7FLZ.js} +1 -1
- package/dist/_chunks/chunk-LBK42NHW.js +1 -0
- package/dist/_chunks/{chunk-J2IYRUVM.js → chunk-MLZ3ZPGU.js} +1 -1
- package/dist/_chunks/{chunk-PAIJRAJB.js → chunk-NG4BDFEY.js} +1 -1
- package/dist/_chunks/chunk-OSO6KRE2.js +1 -0
- package/dist/_chunks/chunk-QE7O57PQ.js +1 -0
- package/dist/_chunks/{chunk-JL4MUI7K.js → chunk-QK4XPVKT.js} +1 -1
- package/dist/_chunks/{chunk-67QDMD7M.js → chunk-ROGOASYF.js} +1 -1
- package/dist/_chunks/{chunk-TIHGZGU3.js → chunk-UYKCN5DU.js} +1 -1
- package/dist/_chunks/{chunk-5G3AJAKI.js → chunk-XUSVNPR5.js} +1 -1
- package/dist/_chunks/component-contract-KXK7WIUI.js +1 -0
- package/dist/_chunks/component-preflight-WECLCZLF.js +1 -0
- package/dist/_chunks/device-management-TLRUMZL5.js +1 -0
- package/dist/_chunks/{device-preflight-QAPMMHWK.js → device-preflight-C7FFUXI2.js} +1 -1
- package/dist/_chunks/{devices-inventory-WZ3QAPTS.js → devices-inventory-BZF53UAU.js} +1 -1
- package/dist/_chunks/{devices-main-XKRRLX5B.js → devices-main-V3YHCB2C.js} +1 -1
- package/dist/_chunks/host-component-Q5IHRHRI.js +1 -0
- package/dist/_chunks/host-help-7BGYR4ET.js +1 -0
- package/dist/_chunks/host-main-JLIBRHC2.js +1 -0
- package/dist/_chunks/{library-main-4BQ2J73H.js → library-main-ATRFEAVN.js} +1 -1
- package/dist/_chunks/{local-main-GBC2HPD4.js → local-main-KTYCLHDA.js} +1 -1
- package/dist/_chunks/{local-mcp-FXHB3CKF.js → local-mcp-ISMU6ADI.js} +1 -1
- package/dist/_chunks/{main-R7DV24KT.js → main-MOZS2EK3.js} +1 -1
- package/dist/_chunks/mcp-M2SO3J2H.js +1 -0
- package/dist/_chunks/{observe-entry-NKXTUZYF.js → observe-entry-E6DFHIMW.js} +1 -1
- package/dist/_chunks/{remote-client-TIFVZEGG.js → remote-client-T75C45JO.js} +1 -1
- package/dist/_chunks/render-main-OGCO2LX4.js +1 -0
- package/dist/_chunks/series-main-FBERVYWG.js +1 -0
- package/dist/_chunks/{source-import-YYRII5FQ.js → source-import-55JJ26AA.js} +1 -1
- package/dist/_chunks/src-V2K52JDH.js +1 -0
- package/dist/_chunks/{workspace-main-LD56MMI6.js → workspace-main-3P56DSEQ.js} +1 -1
- package/dist/_types/cli/local/manager.d.ts +1 -1
- package/dist/_types/cli/local/mcp-tools.d.ts +2 -2
- package/dist/_types/cli/local/releases.d.ts +1 -0
- package/dist/_types/contracts/enterprise-brand.d.ts +302 -0
- package/dist/_types/contracts/index.d.ts +6 -0
- package/dist/_types/contracts/local-execution/ipc.d.ts +3 -3
- package/dist/_types/contracts/local-execution/lifecycle.d.ts +1 -1
- package/dist/_types/contracts/local-execution/local-navigation.d.ts +5 -5
- package/dist/_types/contracts/render-readiness.d.ts +175 -0
- package/dist/_types/contracts/series-canon.d.ts +97 -0
- package/dist/_types/contracts/series-character.d.ts +23 -0
- package/dist/_types/contracts/series-improvement.d.ts +1639 -0
- package/dist/_types/contracts/series-standard.d.ts +1641 -0
- package/dist/_types/sdk/local-runtime-client.d.ts +2 -2
- package/dist/entry.js +1 -1
- package/dist/local-management.js +1 -1
- package/dist/local-navigation.js +1 -1
- package/package.json +1 -1
- package/dist/_chunks/chunk-226SBV53.js +0 -1
- package/dist/_chunks/chunk-H46NB5FL.js +0 -1
- package/dist/_chunks/chunk-IF6AUKH3.js +0 -1
- package/dist/_chunks/chunk-LZPPTW2K.js +0 -1
- package/dist/_chunks/chunk-UITIQHVU.js +0 -45
- package/dist/_chunks/component-contract-HETXQ2J4.js +0 -1
- package/dist/_chunks/device-management-NP7HAXRU.js +0 -1
- package/dist/_chunks/host-component-H3Q7TU5Y.js +0 -1
- package/dist/_chunks/host-help-SBXGX457.js +0 -1
- package/dist/_chunks/host-main-VUEGUFTU.js +0 -1
- package/dist/_chunks/mcp-6D4KHCCL.js +0 -1
- package/dist/_chunks/render-main-KMP4SMK7.js +0 -1
- package/dist/_chunks/src-IX5ZVGZS.js +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
import{readCredential}from"./chunk-QGK6G6YS.js";import{NativeStudioAgentClient}from"./chunk-
|
|
1
|
+
import{readCredential}from"./chunk-QGK6G6YS.js";import{NativeStudioAgentClient}from"./chunk-APNZQZFB.js";import{defaultConnection}from"./chunk-27KI24GK.js";async function withRemoteClient(options,environment,httpOnly,action,budgets={}){budgets.signal?.throwIfAborted();await defaultConnection(options,environment,true);budgets.signal?.throwIfAborted();if(!options.has("--tenant")||(options.has("--profile")?["--origin","--mcp-url","--token-file","--token-env"].some(k=>options.has(k)):options.has("--origin")===options.has("--mcp-url")))throw Error();const transport=options.get("--transport");if(transport&&!["http","mcp"].includes(transport))throw Error();if(!options.has("--profile")&&transport&&transport!==(options.has("--origin")?"http":"mcp"))throw Error();const profile=options.has("--profile")?await(await import("./oauth-RPME2XYB.js")).profileAuthorization(options.get("--profile"),budgets.signal):null;const authorization=profile?.authorization??await readCredential(options,environment);budgets.signal?.throwIfAborted();const profileHttp=profile&&(transport==="http"||!transport&&httpOnly);if(!profileHttp&&(profile||options.has("--mcp-url"))){if(httpOnly)throw Error();const connection=await(await import("./mcp-M2SO3J2H.js")).connectRemoteMcp(profile?.resource??options.get("--mcp-url"),authorization,options.get("--tenant"),budgets);try{budgets.signal?.throwIfAborted();return await action(connection.studio)}finally{await connection.close()}}const baseUrl=profileHttp?await(await import("./http-profile-3VVSWYA5.js")).profileHttpOrigin(options.get("--profile"),profile.resource,budgets.signal):options.get("--origin");budgets.signal?.throwIfAborted();return action(new NativeStudioAgentClient({tenantId:options.get("--tenant"),baseUrl,authorization:()=>authorization,...budgets.maxJsonBytes?{maxJsonBytes:budgets.maxJsonBytes}:{}}))}export{withRemoteClient};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{ComponentCommandSchema,HostComponentRequestSchema}from"./chunk-QE7O57PQ.js";import"./chunk-4M2SOMSN.js";import"./chunk-L3QA7FLZ.js";import"./chunk-MLZ3ZPGU.js";import"./chunk-ELUJ44BO.js";import"./chunk-IYDHDLTR.js";import"./chunk-6EZX2TRX.js";import"./chunk-APNZQZFB.js";import"./chunk-DLW42PJ6.js";import"./chunk-WTJVS2VS.js";import"./chunk-TT7IA5HB.js";export{ComponentCommandSchema,HostComponentRequestSchema};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{assertComponentConfiguration,componentDevice,observeComponent}from"./chunk-LBK42NHW.js";import{observeLoginHost}from"./chunk-D74NHT4I.js";import"./chunk-QE7O57PQ.js";import{desktopRuntimeChannel}from"./chunk-4PAVWOPA.js";import"./chunk-4M2SOMSN.js";import"./chunk-L3QA7FLZ.js";import"./chunk-MLZ3ZPGU.js";import{captureInstalledTools,installationSource,verifyCaptionDirectory}from"./chunk-ELUJ44BO.js";import"./chunk-AFNJRZLJ.js";import"./chunk-IYDHDLTR.js";import{LocalToolSelectionSchema}from"./chunk-6EZX2TRX.js";import"./chunk-APNZQZFB.js";import"./chunk-7I7ARCY7.js";import{LocalClientError,assertExecutable,read}from"./chunk-DLW42PJ6.js";import"./chunk-WTJVS2VS.js";import"./chunk-KOCUZ3AE.js";import"./chunk-TT7IA5HB.js";import{realpath}from"node:fs/promises";import{delimiter,isAbsolute,join}from"node:path";function reason(error,fallback){return error instanceof LocalClientError&&/^[A-Z][A-Z0-9_]{0,79}$/.test(error.code)?error.code:fallback}async function toolPath(name,explicit){const path=process.platform==="win32"?name+".exe":name;const choices=explicit?[explicit]:(process.env.PATH??"").split(delimiter).filter(isAbsolute).slice(0,64).map(root=>join(root,path));for(const candidate of choices){if(!isAbsolute(candidate))continue;try{const actual=await realpath(candidate);await assertExecutable(actual);return actual}catch{}}}async function componentPreflight(home,scope,call,manager,receipts){const observedAt=new Date().toISOString();const platform={os:process.platform,architecture:process.arch,node:process.versions.node};const configuration=manager&&await assertComponentConfiguration(manager,scope);const installation=manager&&(await manager.ledger.current()).value;const last=manager&&(await receipts.snapshot()).latest;const status=(body,exitCode=0)=>({exitCode,output:{protocol:"NVS_HOST_PREFLIGHT_V1",observedAt,kind:call.kind,platform,componentHome:home,installationRevision:installation?.revision??0,installedVersion:installation?.active?.descriptor.version??null,...body}});const blocked=(reasonCode,nextAction,facts2={})=>status({state:"BLOCKED",reasonCode,nextAction,...facts2},4);if(last?.phase==="SENDING")return blocked(last.reasonCode,{surface:"HOST_COMPONENT",action:"observe-original",requestId:last.command.requestId});if(installation?.transition)return blocked("INSTALLATION_RECOVERY_REQUIRED",{surface:"HOST_COMPONENT",action:"reconcile-install",planId:installation.transition.planId,fingerprint:installation.transition.fingerprint,expectedRevision:installation.revision});if(last?.outcome==="UNKNOWN")return blocked(last.reasonCode,{surface:"HOST_COMPONENT",action:"receipt",requestId:last.command.requestId});if(process.platform!=="win32"&&Buffer.byteLength(join(home,"rt","runtime.sock"))>100)return blocked("SOCKET_PATH_TOO_LONG",{surface:"HOST_OWNER",action:"SELECT_PRIVATE_HOME"});const login=await observeLoginHost().then(state=>({state,reasonCode:state==="UNAVAILABLE"?"LOGIN_SERVICE_UNAVAILABLE":null}),error=>({state:"UNAVAILABLE",reasonCode:reason(error,"LOGIN_SERVICE_UNAVAILABLE")}));const host={loginService:login};if(call.source==="SIGNED_CHANNEL"&&call.version==="latest")return blocked("EXACT_RELEASE_VERSION_REQUIRED",{surface:"HOST_OWNER",action:"SELECT_EXACT_RELEASE"},host);const configured=configuration?.catalogueUrl&&configuration.publicKeyFile?{catalogueUrl:configuration.catalogueUrl,publicKeyFile:configuration.publicKeyFile}:null;let trust={...configured??{},rejectedVersions:configuration?.rejectedVersions??[]};const bundled=call.source==="BUNDLED";const fullMedia=call.kind!=="library";const active=installation?.active;const pinned=fullMedia&&active?.toolsConfigPath&&!call.tools?LocalToolSelectionSchema.parse(JSON.parse((await read(active.toolsConfigPath,32768)).toString())):null;const activeCaptions=active&&manager?join(manager.ledger.slotPath(active),"dist/captions"):void 0;const captionPath=call.tools?.captionAssetsDirectory??activeCaptions;let localCaptions=false;if(fullMedia&&captionPath){try{await verifyCaptionDirectory(captionPath);localCaptions=true}catch(error){if(call.tools?.captionAssetsDirectory)return blocked(reason(error,"CAPTION_ASSET_UNAVAILABLE"),{surface:"HOST_OWNER",action:"PROVIDE_MATCHING_CAPTION_ASSETS"},host)}}const[ffmpeg,ffprobe]=fullMedia?await Promise.all([toolPath("ffmpeg",call.tools?.ffmpeg??pinned?.ffmpeg.path),toolPath("ffprobe",call.tools?.ffprobe??pinned?.ffprobe.path)]):[void 0,void 0];const missingTools=[!ffmpeg&&"FFMPEG",!ffprobe&&"FFPROBE"].filter(name=>name!==false);let release;try{if(call.channel&&(!bundled||fullMedia&&(!localCaptions||missingTools.length))){const{value}=desktopRuntimeChannel({...call.channel,protocol:"NVS_DESKTOP_RUNTIME_CHANNEL_V1"});if(configured&&(configured.catalogueUrl!==value.catalogueUrl||(await read(configured.publicKeyFile,16384)).toString().trim()!==value.publicKey.trim()))return blocked("DEPENDENCY_CHANNEL_CHANGED",{surface:"HOST_OWNER",action:"CHECK_CONFIGURED_RELEASE_CHANNEL"},host);if(!configured)trust={...trust,catalogueUrl:value.catalogueUrl,publicKey:value.publicKey}}const dependencyChannel=fullMedia&&(!localCaptions||missingTools.length>0)&&!!trust.catalogueUrl;release=(await installationSource(trust,call.version,bundled,dependencyChannel)).release}catch(error){return blocked(reason(error,"RELEASE_OBSERVATION_UNAVAILABLE"),{surface:"HOST_OWNER",action:"CHECK_RELEASE_SOURCE"},host)}const facts={...host,release:{version:release.descriptor.version,source:call.source,node:release.descriptor.node,sha512:release.package.sha512}};let tools;if(fullMedia){const explicitMissing=call.tools?.ffmpeg&&!ffmpeg||call.tools?.ffprobe&&!ffprobe;const mediaSource=ffmpeg&&ffprobe?"INSTALLED":!explicitMissing&&release.tools?"SIGNED_CHANNEL":"MISSING";const canReuseCaptions=localCaptions&&(!call.tools?.captionAssetsDirectory||mediaSource==="INSTALLED");const captionSource=canReuseCaptions?"INSTALLED":release.resources?.captions?"SIGNED_CHANNEL":"MISSING";const dependencies={mediaSource,captionSource,missingTools:mediaSource==="MISSING"?missingTools:[]};if(mediaSource==="MISSING"||captionSource==="MISSING")return blocked("MEDIA_DEPENDENCIES_REQUIRED",{surface:"HOST_OWNER",action:"PROVIDE_MATCHING_DEPENDENCIES"},{...facts,dependencies});try{tools=ffmpeg&&ffprobe?await captureInstalledTools({mode:"INSTALLED",ffmpeg,ffprobe,...call.tools?.captionAssetsDirectory&&{captionAssetsDirectory:captionPath}}):{mode:"MANAGED"}}catch(error){return blocked(reason(error,"TOOL_IDENTITY_UNAVAILABLE"),{surface:"HOST_OWNER",action:"CHECK_INSTALLED_TOOLS"},{...facts,dependencies})}if(pinned&&(tools.mode!=="INSTALLED"||tools.ffmpeg.digest!==pinned.ffmpeg.digest||tools.ffprobe.digest!==pinned.ffprobe.digest))return blocked("INSTALLED_TOOL_IDENTITY_CHANGED",{surface:"HOST_OWNER",action:"CHECK_INSTALLED_TOOLS"},{...facts,dependencies});Object.assign(facts,{dependencies})}if(!manager||!configured&&!!trust.catalogueUrl)return status({...facts,state:"INITIALIZATION_REQUIRED",reasonCode:manager?"DEPENDENCY_CHANNEL_CONFIGURATION_REQUIRED":"COMPONENT_NOT_INITIALIZED",nextAction:{surface:"HOST_COMPONENT",call:{action:"initialize"},includeOriginalChannel:!!trust.catalogueUrl}});if(!active||active.descriptor.version!==release.descriptor.version||fullMedia&&(!active.toolsConfigPath||!localCaptions||!!call.tools))return status({...facts,state:"INSTALL_PLAN_REQUIRED",reasonCode:"PIN_CURRENT_INSTALLATION_PLAN",nextAction:{surface:"HOST_COMPONENT",call:{action:"install-plan",version:release.descriptor.version,source:call.source,...tools&&{tools}}}});const device=await componentDevice(home,scope);const component=await observeComponent(home,scope,manager,receipts);if(device&&component.liveness.state==="STOPPED")return status({...facts,component,state:"START_REQUIRED",reasonCode:"OWNED_RUNTIME_STOPPED",nextAction:{surface:"HOST_COMPONENT",action:"start",expectedRevision:component.installationRevision}});return status({...facts,component,state:device?"VERIFY_DEVICE":"ENROLLMENT_REQUIRED",reasonCode:device?"CHECK_DEVICE_HEARTBEAT_AND_TASK":"INSPECT_ORIGINAL_ENROLLMENT",nextAction:device?{surface:"MCP",tool:"studio_capability_query",arguments:{tenantId:scope.tenantId,tool:"device_status",arguments:{tenantId:scope.tenantId,deviceId:device.deviceId}}}:{surface:"HOST_ENROLLMENT",call:{action:"inspect"}}})}export{componentPreflight};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{profileAuthorization}from"./chunk-3TOXIJ7K.js";import{readCredential,readInput}from"./chunk-QGK6G6YS.js";import{connectRemoteMcp}from"./chunk-GLAF74UU.js";import"./chunk-2UYKJ6YN.js";import"./chunk-APNZQZFB.js";import{defaultConnection,tenantConnection}from"./chunk-27KI24GK.js";import"./chunk-7I7ARCY7.js";import"./chunk-DLW42PJ6.js";import{CapabilityVersionSchema}from"./chunk-WTJVS2VS.js";import"./chunk-KOCUZ3AE.js";import{NativeStudioSdkError}from"./chunk-TT7IA5HB.js";var operations={status:"device.status",enroll:"device.enroll","enrollment-issue":"device.enrollment.issue","enrollment-lookup":"device.enrollment.lookup",revoke:"device.revoke",receipt:"device.management-receipt"};async function deviceManagementCommand(action,args,env,stdin){if(!action||!Object.hasOwn(operations,action))throw Error();const flags=new Map;for(let i=0;i<args.length;i+=2){const key=args[i],value=args[i+1];if(!key||!["--input","--profile","--mcp-url","--token-file","--token-env","--capability-version"].includes(key)||!value||value.startsWith("--")||flags.has(key))throw Error();flags.set(key,value)}if(!flags.has("--input"))throw Error();const capabilityVersion=CapabilityVersionSchema.optional().parse(flags.get("--capability-version"));await defaultConnection(flags,env,true);const profile=flags.get("--profile");if(profile&&["--mcp-url","--token-file","--token-env"].some(k=>flags.has(k)))throw Error();const token=profile?await profileAuthorization(profile):null;const resource=token?.resource??flags.get("--mcp-url");if(!resource)throw Error();const scope=tenantConnection(resource);const raw=await readInput(flags.get("--input"),stdin);const nested=action==="receipt"?raw.input:raw;if(nested?.tenantId!==void 0&&String(nested.tenantId).toLowerCase()!==scope.tenantId.toLowerCase())throw new NativeStudioSdkError("FORBIDDEN","BLOCKED","NO_WRITE");const authorization=token?.authorization??await readCredential(flags,env);const connection=await connectRemoteMcp(scope.resource,authorization,scope.tenantId);try{const key=operations[action];const input=action==="receipt"?{command:raw}:{...raw,tenantId:scope.tenantId};const command=input;const output=capabilityVersion?await connection.studio.call(key,command,{capabilityVersion}):await connection.studio.call(key,command);return{exitCode:0,output}}finally{await connection.close().catch(()=>{})}}export{deviceManagementCommand};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{callerOriginMatches,workspaceCaller}from"./chunk-
|
|
1
|
+
import{callerOriginMatches,workspaceCaller}from"./chunk-NG4BDFEY.js";import{renderConnection}from"./chunk-OSO6KRE2.js";import"./chunk-UYKCN5DU.js";import{LocalInstallationManager,ownerClient,probeLocalLibrary,probeReferenceThumbnail,probeTenantComposition,probeTenantMediaProcessing,probeTenantMediaValidation,probeTenantQwenGeneration,probeTenantSpeech,probeTenantTranscription,verifySlot}from"./chunk-ELUJ44BO.js";import{DesktopDeviceRecords}from"./chunk-AFNJRZLJ.js";import"./chunk-IYDHDLTR.js";import{LocalToolSelectionSchema}from"./chunk-6EZX2TRX.js";import"./chunk-3TOXIJ7K.js";import"./chunk-QGK6G6YS.js";import"./chunk-GLAF74UU.js";import"./chunk-2UYKJ6YN.js";import{DeviceDiscoveryInputSchema,LocalDeviceTransportConfigurationSchema}from"./chunk-APNZQZFB.js";import"./chunk-7P2NA6TH.js";import"./chunk-27KI24GK.js";import"./chunk-7I7ARCY7.js";import{LocalClientError,read}from"./chunk-DLW42PJ6.js";import"./chunk-WTJVS2VS.js";import"./chunk-KOCUZ3AE.js";import{NativeStudioSdkError}from"./chunk-TT7IA5HB.js";import{z}from"zod";var transportSchema=LocalDeviceTransportConfigurationSchema.safeExtend({tools:LocalToolSelectionSchema.optional()});var nextSteps={ACCOUNT_LOGIN_REQUIRED:"nvs login --server <Studio-origin>",TENANT_CONNECTION_REQUIRED:"nvs connect --mcp-url <tenant-connection-url>",ACCOUNT_REVOCATION_UNCONFIRMED:"nvs logout",PROJECT_SELECTION_REQUIRED:"Run nvs workspaces, nvs projects, then nvs project --id <project-id>",INSTALL_REQUIRED:"Configure the Runtime, check signed releases, then prepare nvs local install --version <exact>",INSTALLATION_RECOVERY_REQUIRED:"Inspect nvs local status, then reconcile the original installation plan",CONFIGURATION_REQUIRED:"nvs local configure --input <private-json>",DEVICE_ENROLLMENT_REQUIRED:"nvs local cloud --action enroll with the approved owner input",DEVICE_RECEIPT_REQUIRED:"nvs local cloud --action receipt with the original management command",PROJECT_CONNECTION_REQUIRED:"nvs connect",DEVICE_AUTHORITY_UNCONFIRMED:"Check the current workspace membership, device proof and revocation",DEVICE_CONNECTION_REQUIRED:"nvs local connect --input <private-device-config>",DEVICE_CONNECTION_RECOVERY_REQUIRED:"Inspect the original device connection and Runtime status",DEVICE_OFFLINE:"Inspect nvs local status, then start the configured Runtime if stopped",DEVICE_BUSY:"Wait for available capacity, then recheck this device",RUNTIME_QUALIFICATION_REQUIRED:"Check the signed Runtime slot and the approved tools",DEVICE_CAPABILITY_UNCONFIRMED:"Check the configured action, tool or provider prerequisites and the current heartbeat",PROJECT_QUERY_UNAVAILABLE:"Check the selected Project connection, then retry this read"};async function qualified(kind,root,slot,validator){if(kind==="library")return true;if(kind==="preview"||kind==="final")return validator?probeTenantMediaValidation(root,slot):true;if(!await probeTenantMediaProcessing(root,slot))return false;switch(kind){case"REFERENCE_PREVIEW":return probeReferenceThumbnail(root,slot);case"LOCAL_MEDIA_INSPECT":case"LOCAL_MEDIA_PUBLISH":return probeLocalLibrary(root,slot);case"COMPOSITION_RENDER":return probeTenantComposition(root,slot);case"SPEECH_SYNTHESIZE":return probeTenantSpeech(root,slot);case"TRANSCRIBE_AUDIO":return probeTenantTranscription(root,slot);case"KEYFRAME_GENERATE":return probeTenantQwenGeneration(root,slot,"keyframe");case"VIDEO_GENERATE":return probeTenantQwenGeneration(root,slot,"video");case"SPEECH_EXTERNAL_QWEN":return probeTenantQwenGeneration(root,slot,"speech");case"TRANSCRIBE_EXTERNAL_QWEN":return probeTenantQwenGeneration(root,slot,"asr");default:return true}}async function devicePreflight(raw,env,explicitProject){const kind=DeviceDiscoveryInputSchema.shape.kind.parse(raw);const context={};const blocked=reason=>({exitCode:4,output:{semanticStatus:"BLOCKED",kind,...context,error:{code:reason,outcome:"NO_WRITE"},nextStep:nextSteps[reason]}});let caller;try{caller=await workspaceCaller(env)}catch(error){if(error.code==="ENOENT")return blocked("ACCOUNT_LOGIN_REQUIRED");if(error instanceof NativeStudioSdkError){if(error.code==="TENANT_CONNECTION_REQUIRED")return blocked("TENANT_CONNECTION_REQUIRED");if(error.code==="ACCOUNT_LOGIN_REQUIRED")return blocked("ACCOUNT_LOGIN_REQUIRED");if(error.code==="ACCOUNT_LOGOUT_OUTCOME_UNKNOWN")return blocked("ACCOUNT_REVOCATION_UNCONFIRMED");if(error.code==="PROJECT_SELECTION_REQUIRED")return blocked("PROJECT_SELECTION_REQUIRED")}throw error}if(!caller)return blocked("ACCOUNT_LOGIN_REQUIRED");const{home,tenantId,principalId,serverOrigin}=caller;const projectId=explicitProject?z.uuid().parse(explicitProject):void 0;Object.assign(context,{tenantId,projectId});const manager=await LocalInstallationManager.openExisting(home);if(!manager)return blocked("INSTALL_REQUIRED");const{active,transition}=(await manager.ledger.current()).value;if(transition)return blocked("INSTALLATION_RECOVERY_REQUIRED");if(!active)return blocked("INSTALL_REQUIRED");const slotRoot=manager.ledger.slotPath(active);await verifySlot(slotRoot,active);const records=await DesktopDeviceRecords.inspect(home,{origin:serverOrigin,tenantId,principalId});const pending=records?.pending?.command;if(records?.pending?.phase==="SENDING"&&(pending?.kind==="ENROLL"||pending?.kind==="REVOKE_DEVICE"))return blocked("DEVICE_RECEIPT_REQUIRED");if(records?.connection?.phase==="CONNECTING")return blocked("DEVICE_CONNECTION_RECOVERY_REQUIRED");const config=await manager.configuration().catch(error=>{if(error instanceof LocalClientError&&error.code==="CONFIGURATION_REQUIRED")return null;throw error});if(!config)return blocked("CONFIGURATION_REQUIRED");let transport=null;try{if(config.cloudConfigFile)transport=transportSchema.parse(JSON.parse((await read(config.cloudConfigFile,32768)).toString()))}catch(error){if(error.code==="ENOENT")return blocked("DEVICE_CONNECTION_REQUIRED");if(error instanceof SyntaxError||error instanceof z.ZodError)return blocked("DEVICE_CONNECTION_RECOVERY_REQUIRED");throw error}const endpoint=transport?new URL(transport.endpoint):null;const current=endpoint&&await callerOriginMatches(endpoint.origin,caller)&&!endpoint.username&&!endpoint.password&&transport?.tenantId===tenantId?transport:null;const deviceId=records?.device?.deviceId??current?.deviceId;if(!deviceId)return blocked("DEVICE_ENROLLMENT_REQUIRED");context.deviceId=deviceId;const configured=current?.deviceId===deviceId&¤t.tenantId===tenantId;if(!configured||!current)return blocked("DEVICE_CONNECTION_REQUIRED");if(!projectId){const local=await ownerClient(config.stateDirectory);const status=await local.status(void 0,true).catch(()=>null);if(!status)return blocked("DEVICE_OFFLINE");if(status.deviceAuthority?.tenantId!==tenantId||status.deviceAuthority.deviceId!==deviceId)return blocked("DEVICE_AUTHORITY_UNCONFIRMED");if(status.state==="DRAINING")return blocked("DEVICE_BUSY");if(status.state==="RECOVERY_REQUIRED")return blocked("DEVICE_CONNECTION_RECOVERY_REQUIRED");const capabilities=status.deviceCapabilities;if(!capabilities)return blocked("DEVICE_CAPABILITY_UNCONFIRMED");if(capabilities.deviceRevision!==current.deviceRevision)return blocked("DEVICE_CONNECTION_RECOVERY_REQUIRED");if(kind==="preview"||kind==="final"){const doctor=await local.doctor().catch(()=>null);if(!doctor?.nativeExecutionReady||!doctor.executionProfiles?.includes("STUDIO_MEDIA_V2"))return blocked("RUNTIME_QUALIFICATION_REQUIRED");if(current.tenantMediaValidation&&!capabilities.tenantMediaValidation)return blocked("DEVICE_CAPABILITY_UNCONFIRMED")}if(kind!=="preview"&&kind!=="final"&&kind!=="library"){const configuredKinds=current.processorCapabilities??[];if(!current.tenantMediaProcessing||!configuredKinds.includes(kind)||!capabilities.tenantMediaProcessing||!capabilities.processorCapabilities.includes(kind))return blocked("DEVICE_CAPABILITY_UNCONFIRMED")}if(!await qualified(kind,slotRoot,active,!!current?.tenantMediaValidation))return blocked("RUNTIME_QUALIFICATION_REQUIRED");await caller.assertCurrent();return{exitCode:0,output:{semanticStatus:"SUCCESS",kind,tenantId,deviceId,availability:status.state==="EXECUTING"?"BUSY":"AVAILABLE"}}}const conn=await renderConnection(env,void 0,false,projectId).catch(error=>{if(error instanceof NativeStudioSdkError&&error.code==="AUTHORIZATION_REQUIRED")return null;throw error});if(!conn)return blocked("PROJECT_CONNECTION_REQUIRED");try{if(conn.scope.tenantId!==tenantId||conn.scope.projectId!==projectId||(caller.resource?conn.scope.resource!==caller.resource:new URL(conn.scope.resource).origin!==serverOrigin))return blocked("PROJECT_CONNECTION_REQUIRED");const page=await conn.studio.deviceRenders.list({kind,projectId,deviceId}).catch(error=>{if(error instanceof NativeStudioSdkError)return null;throw error});await caller.assertCurrent();if(!page||page.truncated)return blocked("PROJECT_QUERY_UNAVAILABLE");const candidate=page.items[0];if(!candidate)return blocked("DEVICE_AUTHORITY_UNCONFIRMED");if(!configured)return blocked("DEVICE_CONNECTION_REQUIRED");if(candidate.availability==="OFFLINE")return blocked("DEVICE_OFFLINE");if(candidate.availability==="BUSY")return blocked("DEVICE_BUSY");if(candidate.availability==="UNQUALIFIED")return blocked(await qualified(kind,slotRoot,active,!!page.validationMode)?"DEVICE_CAPABILITY_UNCONFIRMED":"RUNTIME_QUALIFICATION_REQUIRED");return{exitCode:0,output:{semanticStatus:"SUCCESS",kind,tenantId,projectId,deviceId,availability:candidate.availability,validationMode:page.validationMode}}}finally{await conn.close().catch(()=>{})}}export{devicePreflight};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{profileAuthorization}from"./chunk-3TOXIJ7K.js";import{readCredential}from"./chunk-QGK6G6YS.js";import{connectRemoteMcp}from"./chunk-
|
|
1
|
+
import{profileAuthorization}from"./chunk-3TOXIJ7K.js";import{readCredential}from"./chunk-QGK6G6YS.js";import{connectRemoteMcp}from"./chunk-GLAF74UU.js";import"./chunk-2UYKJ6YN.js";import{WorkspaceDeviceListInputSchema}from"./chunk-APNZQZFB.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";var query=WorkspaceDeviceListInputSchema.omit({tenantId:true});async function deviceInventoryCommand(args,env){const flags=new Map;for(let i=0;i<args.length;i+=2){const key=args[i],value=args[i+1];if(!key||!["--device","--after","--limit","--profile","--mcp-url","--token-file","--token-env"].includes(key)||!value||value.startsWith("--")||flags.has(key))throw Error();flags.set(key,value)}const input=query.parse({...flags.has("--device")&&{deviceId:flags.get("--device")},...flags.has("--after")&&{after:flags.get("--after")},...flags.has("--limit")&&{limit:Number(flags.get("--limit"))}});await defaultConnection(flags,env,true);const profile=flags.get("--profile");if(profile&&["--mcp-url","--token-file","--token-env"].some(key=>flags.has(key)))throw Error();const token=profile?await profileAuthorization(profile):null;const resource=token?.resource??flags.get("--mcp-url");if(!resource)throw Error();const scope=tenantConnection(resource);const authorization=token?.authorization??await readCredential(flags,env);const connection=await connectRemoteMcp(scope.resource,authorization,scope.tenantId);try{const output=await connection.studio.call("workspace.devices.list",{...input,tenantId:scope.tenantId});return{exitCode:0,output}}finally{await connection.close().catch(()=>{})}}export{deviceInventoryCommand};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{callerRenderConnection}from"./chunk-
|
|
1
|
+
import{callerRenderConnection}from"./chunk-OSO6KRE2.js";import"./chunk-UYKCN5DU.js";import"./chunk-3TOXIJ7K.js";import"./chunk-QGK6G6YS.js";import"./chunk-GLAF74UU.js";import"./chunk-2UYKJ6YN.js";import{DeviceDiscoveryInputSchema}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"./chunk-TT7IA5HB.js";var query=DeviceDiscoveryInputSchema.pick({kind:true,deviceId:true});async function devicesCommand(argv,env,stdin=process.stdin){const[action,...args]=argv;if(action==="inventory")return(await import("./devices-inventory-BZF53UAU.js")).deviceInventoryCommand(args,env);if(action!=="list")return(await import("./device-management-TLRUMZL5.js")).deviceManagementCommand(action,args,env,stdin);const flags=new Map;for(let i=0;i<args.length;i+=2){const name=args[i],value=args[i+1];if(!name||!["--kind","--device","--project","--mcp-url","--token-file"].includes(name)||!value||value.startsWith("--")||flags.has(name))throw Error();flags.set(name,value)}const input=query.parse({kind:flags.get("--kind"),...flags.has("--device")&&{deviceId:flags.get("--device")}});const conn=await callerRenderConnection(env,flags,false);try{const output=await conn.studio.deviceRenders.list({...input,projectId:conn.scope.projectId});return{exitCode:0,output}}finally{await conn.close().catch(()=>{})}}export{devicesCommand};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{ComponentReceipts,componentHome,initializeComponent,observeComponent,observeLoginService,withComponentLock}from"./chunk-LBK42NHW.js";import{runLoginService}from"./chunk-D74NHT4I.js";import"./chunk-QE7O57PQ.js";import"./chunk-4PAVWOPA.js";import"./chunk-4M2SOMSN.js";import"./chunk-L3QA7FLZ.js";import"./chunk-MLZ3ZPGU.js";import{InstalledToolPathsSchema,LocalInstallationManager,captureInstalledTools}from"./chunk-ELUJ44BO.js";import"./chunk-AFNJRZLJ.js";import"./chunk-IYDHDLTR.js";import"./chunk-6EZX2TRX.js";import"./chunk-APNZQZFB.js";import"./chunk-7I7ARCY7.js";import{LocalClientError,fail}from"./chunk-DLW42PJ6.js";import"./chunk-WTJVS2VS.js";import"./chunk-KOCUZ3AE.js";import"./chunk-TT7IA5HB.js";var ok=output=>({exitCode:0,output});var acknowledged=output=>({exitCode:output.phase==="COMPLETE"?0:2,output});async function serviceFingerprint(home){const service=await observeLoginService(home);if(!("fingerprint"in service)||!service.fingerprint||!("supervision"in service)||service.supervision!=="EXPLICIT_RECOVERY")fail("COMPONENT_SERVICE_UNCONFIRMED");return service.fingerprint}async function applyComponentCommand(manager,command,before){const home=manager.ledger.root;switch(command.action){case"apply":case"rollback":{if(command.action==="rollback"){const plan=await manager.plan(command.planId),version=plan.release.descriptor.version;if(version===before.installedVersion||!await manager.ledger.hadCompletedVersion(version))fail("COMPONENT_ROLLBACK_VERSION_UNAVAILABLE")}await manager.apply(command.planId,command.fingerprint);return"COMPONENT_VERSION_ACTIVATED"}case"reconcile-install":await manager.reconcile(command.planId,command.fingerprint);return"COMPONENT_INSTALLATION_RECONCILED";case"service-enable":await runLoginService("service-enable",home,command.fingerprint,"EXPLICIT_RECOVERY");return"COMPONENT_SERVICE_REGISTERED";case"start":if(before.loginService==="REGISTERED")await runLoginService("service-start",home,await serviceFingerprint(home));else await manager.start();return"COMPONENT_STARTED";case"stop":if(before.loginService!=="NONE")await runLoginService("service-disable",home,await serviceFingerprint(home));if((await manager.status()).running)await manager.stop();return"COMPONENT_STOPPED";case"recover":if(before.readiness.state==="READY")return"COMPONENT_HEALTHY";if(before.loginService==="REGISTERED")await runLoginService("service-restart",home,await serviceFingerprint(home));else{if(before.liveness.state==="ALIVE")await manager.stop();await manager.start()}return"COMPONENT_RECOVERED"}}function outcomeObserved(command,current){switch(command.action){case"stop":return current.liveness.state==="STOPPED"&¤t.loginService==="NONE";case"service-enable":return current.loginService==="REGISTERED";case"reconcile-install":return true;default:return current.readiness.state==="READY"}}function reason(error){return error instanceof LocalClientError&&/^[A-Z][A-Z0-9_]{0,79}$/.test(error.code)?error.code:"COMPONENT_ACTION_UNAVAILABLE"}async function runHostComponent(parent,{scope,call}){const target=await componentHome(parent,scope,call.action==="initialize"),home=target.home,receipts=new ComponentReceipts(home);if(call.action==="initialize")return withComponentLock(home,async()=>{const manager2=await initializeComponent(home,scope,call.channel);return ok(await observeComponent(home,scope,manager2,receipts))});if(call.action==="receipt")return ok({receipt:target.claimed?await receipts.find(call.requestId):null});const manager=target.claimed?await LocalInstallationManager.openExisting(home):null;const observe=()=>observeComponent(home,scope,manager,receipts);if(call.action==="status")return ok(await observe());if(call.action==="preflight")return(await import("./component-preflight-WECLCZLF.js")).componentPreflight(home,scope,call,manager,receipts);if(!manager)fail("COMPONENT_INITIALIZATION_REQUIRED","NO_WRITE");if(call.action==="service-plan"){await observe();return ok(await runLoginService("service-plan",home,void 0,"EXPLICIT_RECOVERY"))}if(call.action==="install-plan"||call.action==="rollback-plan"){if(call.source==="SIGNED_CHANNEL"&&call.version==="latest")fail("EXACT_RELEASE_VERSION_REQUIRED","NO_WRITE");return withComponentLock(home,async()=>{const before=await observe();if(call.action==="rollback-plan"&&(call.version===before.installedVersion||!await manager.ledger.hadCompletedVersion(call.version)))fail("COMPONENT_ROLLBACK_VERSION_UNAVAILABLE","NO_WRITE");const paths=InstalledToolPathsSchema.safeParse(call.tools);const tools=paths.success?await captureInstalledTools(paths.data):call.tools;return ok(call.source==="SIGNED_CHANNEL"?await manager.prepare(call.version,tools):await manager.prepareBundled(call.version,tools))})}if(call.action==="observe-original")return withComponentLock(home,async()=>{const original=await receipts.find(call.requestId);if(!original)fail("COMPONENT_RECEIPT_NOT_FOUND");if(original.phase!=="SENDING")return ok(original);const current=await observe();const command=original.command;const observed=command.expectedRevision===current.installationRevision&&["start","stop","recover","service-enable"].includes(command.action)&&outcomeObserved(command,current);return ok(await receipts.finish(original,{phase:observed?"COMPLETE":"DEGRADED",outcome:observed?"OBSERVED":"UNKNOWN",reasonCode:observed?"COMPONENT_STATE_OBSERVED":"COMPONENT_ORIGINAL_OUTCOME_UNKNOWN",installationRevision:current.installationRevision,runningVersion:current.runningVersion}))});return withComponentLock(home,async()=>{const replay=await receipts.original(call);if(replay)return acknowledged(replay);const before=await observe();if(call.expectedRevision!==before.installationRevision)fail("REVISION_CONFLICT","NO_WRITE");if(call.action==="recover"&&before.capabilityMismatch)return{exitCode:2,output:{semanticStatus:"CAPABILITY_UNAVAILABLE",error:{code:"CAPABILITY_VERSION_MISMATCH",outcome:"NO_WRITE",details:before.capabilityMismatch}}};if(before.liveness.state==="UNKNOWN"||before.loginService==="UNKNOWN")fail("COMPONENT_OWNERSHIP_UNCONFIRMED","NO_WRITE");if(before.loginService==="INCOMPLETE"&&call.action!=="stop")fail("COMPONENT_SERVICE_NEEDS_STOP","NO_WRITE");const{latest}=await receipts.snapshot();if(call.action==="recover"&&before.readiness.state!=="READY"&&latest?.command.action==="recover"&&latest.phase==="DEGRADED")fail("COMPONENT_RECOVERY_EXHAUSTED","NO_WRITE");const original=await receipts.begin(call,before.runningVersion);let reasonCode,after,phase="DEGRADED";try{reasonCode=await applyComponentCommand(manager,call,before);after=await observe();if(outcomeObserved(call,after))phase="COMPLETE";else reasonCode=call.action==="recover"?"COMPONENT_RESTART_INEFFECTIVE":"COMPONENT_RESULT_UNCONFIRMED"}catch(error){reasonCode=reason(error);after=await observe().catch(()=>before)}return acknowledged(await receipts.finish(original,{phase,outcome:phase==="COMPLETE"?"SUCCESS":"UNKNOWN",reasonCode,installationRevision:after.installationRevision,runningVersion:after.runningVersion}))})}export{runHostComponent};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{HostComponentRequestSchema}from"./chunk-QE7O57PQ.js";import{HostEnrollmentRequestSchema}from"./chunk-K35CWLDH.js";import"./chunk-4M2SOMSN.js";import"./chunk-L3QA7FLZ.js";import"./chunk-ROGOASYF.js";import"./chunk-HBDPYWMI.js";import"./chunk-MLZ3ZPGU.js";import"./chunk-ELUJ44BO.js";import"./chunk-AFNJRZLJ.js";import"./chunk-IYDHDLTR.js";import"./chunk-6EZX2TRX.js";import"./chunk-APNZQZFB.js";import"./chunk-DLW42PJ6.js";import"./chunk-WTJVS2VS.js";import"./chunk-TT7IA5HB.js";import{z}from"zod";var protocol="NVS_EXTERNAL_HOST_V1";var requests={component:HostComponentRequestSchema,enrollment:HostEnrollmentRequestSchema};function hostOverview(deviceActions){return{exitCode:0,output:{protocol,agentRuntime:"EXTERNAL",commands:["host component --input <private-json|-> [--home <private-parent-home>]","host enrollment --input <private-json|-> [--home <component-home>]","host device --input <json|-> [--home <private-client-home>]"],actions:[...deviceActions],help:["host component help [<action>]","host enrollment help [<action>]"],guidance:"Use workspace_caller and workspace_status on your tenant MCP for component scope. Use host component help preflight for the read-only host check for library, preview or final. Prepare enrollment with authority OAUTH_AGENT and send its invoke on the same MCP. Pass the ticket by private input and read the original lookup after an interrupted reply."}}}function hostActionHelp(command,action){const request=requests[command],options=request.shape.call.options;const actions=options.map(option=>option.shape.action.value);const selected=action&&options.find(option=>option.shape.action.value===action);const invalid=action!==void 0&&!selected;return{exitCode:invalid?2:0,output:{protocol,command:"host "+command,actions,help:"host "+command+" help <action>",...invalid&&{semanticStatus:"INVALID_INPUT",error:{code:"INVALID_INPUT",outcome:"NO_WRITE"}},...selected&&{action,inputSchema:z.toJSONSchema(z.strictObject({scope:request.shape.scope,call:selected}),{io:"input"})}}}}export{hostActionHelp,hostOverview};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{HostEnrollmentRequestSchema,runHostEnrollment}from"./chunk-K35CWLDH.js";import{runDesktopDeviceRequest}from"./chunk-ROGOASYF.js";import"./chunk-HBDPYWMI.js";import"./chunk-MLZ3ZPGU.js";import"./chunk-ELUJ44BO.js";import"./chunk-AFNJRZLJ.js";import{DesktopDeviceRequestSchema}from"./chunk-IYDHDLTR.js";import"./chunk-6EZX2TRX.js";import{readInput}from"./chunk-QGK6G6YS.js";import"./chunk-APNZQZFB.js";import{LocalClientError}from"./chunk-DLW42PJ6.js";import"./chunk-WTJVS2VS.js";import"./chunk-TT7IA5HB.js";import{homedir}from"node:os";import{join,resolve}from"node:path";var actions=new Set(["inspect","enroll","revoke","dispatch","record","refused","prove","connect","connection-recover","media-validation-capability","media-processing-capability"]);var helpFlags=["help","--help"];async function runHostCli(argv,stdin=process.stdin){let entered=false;let mutation=false;try{if(!argv.length||argv.length===1&&helpFlags.includes(argv[0]))return(await import("./host-help-7BGYR4ET.js")).hostOverview(actions);const[command,...rest]=argv,options=new Map;if(command!=="device"&&command!=="enrollment"&&command!=="component")throw Error();if(command!=="device"&&rest.length<=2&&helpFlags.includes(rest[0]??""))return(await import("./host-help-7BGYR4ET.js")).hostActionHelp(command,rest[1]);for(let i=0;i<rest.length;i+=2){const key=rest[i],value=rest[i+1];if(!key||!["--input","--home"].includes(key)||!value||value.startsWith("--")||options.has(key))throw Error();options.set(key,value)}const file=options.get("--input");if(!file)throw Error();const home=resolve(options.get("--home")??process.env.NATIVESTUDIO_CLIENT_HOME??join(homedir(),".nativestudio/client"));const raw=await readInput(file,stdin,command!=="device");if(command==="component"){const{HostComponentRequestSchema}=await import("./component-contract-KXK7WIUI.js");const request2=HostComponentRequestSchema.parse(raw);entered=true;mutation=!["status","preflight","receipt","service-plan"].includes(request2.call.action);return await(await import("./host-component-Q5IHRHRI.js")).runHostComponent(home,request2)}if(command==="enrollment"){const request2=HostEnrollmentRequestSchema.parse(raw);entered=true;mutation=request2.call.action!=="inspect";return{exitCode:0,output:await runHostEnrollment(home,request2)}}const request=DesktopDeviceRequestSchema.parse(raw);if(!actions.has(request.call.action))throw Error();mutation=!["inspect","media-validation-capability","media-processing-capability"].includes(request.call.action);entered=true;const output=await runDesktopDeviceRequest(home,request,{allowedPendingKinds:["ENROLL","REVOKE_DEVICE"]});return{exitCode:0,output}}catch(error){const code=error instanceof LocalClientError?error.code:!entered?"INVALID_INPUT":"INTERNAL_OPERATIONAL_FAILURE";const knownRefusal=error instanceof LocalClientError&&error.outcome==="NO_WRITE";const uncertain=!knownRefusal&&(entered&&mutation&&code!=="DEVICE_COMMAND_UNSUPPORTED"||/(?:UNKNOWN|RECOVERY_REQUIRED|PROOF_UNAVAILABLE)/.test(code)||code==="INTERNAL_OPERATIONAL_FAILURE");return{exitCode:2,output:{semanticStatus:!uncertain&&["INVALID_INPUT","REVISION_CONFLICT"].includes(code)?code:"BLOCKED",error:{code,outcome:uncertain?"UNKNOWN":"NO_WRITE"}}}}}export{runHostCli};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{localCaller}from"./chunk-
|
|
1
|
+
import{localCaller}from"./chunk-NG4BDFEY.js";import{renderConnection}from"./chunk-OSO6KRE2.js";import"./chunk-UYKCN5DU.js";import{DesktopLibraryImportSeedSchema,prepareDesktopLibraryImport,runDesktopLibraryImport,runDesktopLibraryRequest}from"./chunk-L3QA7FLZ.js";import"./chunk-MLZ3ZPGU.js";import"./chunk-ELUJ44BO.js";import{DesktopDeviceRecords}from"./chunk-AFNJRZLJ.js";import"./chunk-IYDHDLTR.js";import"./chunk-6EZX2TRX.js";import"./chunk-3TOXIJ7K.js";import{readInput}from"./chunk-QGK6G6YS.js";import"./chunk-GLAF74UU.js";import"./chunk-2UYKJ6YN.js";import{LocalDeviceViewSchema,LocalManagementCommandSchema}from"./chunk-APNZQZFB.js";import"./chunk-7P2NA6TH.js";import"./chunk-27KI24GK.js";import"./chunk-7I7ARCY7.js";import{fail,sha256}from"./chunk-DLW42PJ6.js";import"./chunk-WTJVS2VS.js";import"./chunk-KOCUZ3AE.js";import{NativeStudioSdkError}from"./chunk-TT7IA5HB.js";import{homedir}from"node:os";import{join,resolve,basename}from"node:path";async function libraryImportContext(home,raw,enrollment){const caller=await localCaller({...process.env,NATIVESTUDIO_CLIENT_HOME:home},typeof raw.projectId==="string"?raw.projectId:void 0);if(!caller){if(!["tenantId","projectId","deviceId","ownerKey"].every(key=>raw[key]))fail("ACCOUNT_LOGIN_REQUIRED");return{}}const{serverOrigin,tenantId,principalId,projectId}=caller;const ownerKey=sha256(JSON.stringify([serverOrigin,tenantId,principalId]));const denied=()=>{throw new NativeStudioSdkError("FORBIDDEN","BLOCKED","NO_WRITE")};if(raw.tenantId!==void 0&&raw.tenantId!==tenantId||raw.projectId!==void 0&&raw.projectId!==projectId||raw.ownerKey!==void 0&&raw.ownerKey!==ownerKey)denied();const record=await DesktopDeviceRecords.inspect(home,{origin:serverOrigin,tenantId,principalId});if(record?.device&&(record.device.enrolledByPrincipalId!==principalId||record.device.tenantId!==tenantId))denied();if(record?.pending?.phase==="SENDING")fail("DEVICE_RECEIPT_REQUIRED");let deviceId=record?.device?.deviceId;if(!deviceId&&enrollment!==void 0){const command=LocalManagementCommandSchema.parse(enrollment);if(command.kind!=="ENROLL"||command.input.tenantId!==tenantId)denied();const env={...process.env,NATIVESTUDIO_CLIENT_HOME:home};const c=await renderConnection(env,void 0,false,projectId);try{if(c.scope.profile!==caller.profile||c.scope.resource!==caller.resource)denied();const receipt=await c.studio.call("device.management-receipt",{command});if(!receipt.result)fail("DEVICE_RECEIPT_REQUIRED");const device=LocalDeviceViewSchema.parse(receipt.result);if(device.enrolledByPrincipalId!==principalId||device.tenantId!==tenantId)denied();deviceId=device.deviceId}finally{await c.close().catch(()=>{})}}if(!deviceId)fail("DEVICE_SETUP_REQUIRED");if(raw.deviceId!==void 0&&raw.deviceId!==deviceId)denied();await caller.assertCurrent();return{tenantId,projectId,deviceId,ownerKey,assertCurrent:caller.assertCurrent}}async function runLocalLibrary(argv,stdin){const[action,...args]=argv,flags=new Map;for(let i=0;i<args.length;i+=2){const name=args[i],value=args[i+1];if(!name||!["--home","--input","--file","--enrollment"].includes(name)||!value||value.startsWith("--")||flags.has(name))throw Error();flags.set(name,value)}if(!action||!["import","list","get","read","access","sync","resume-access","import-receipt","usage"].includes(action)||!flags.has("--input")||flags.get("--input")==="-"&&flags.get("--enrollment")==="-"||action!=="import"&&(flags.has("--file")||flags.has("--enrollment")))throw Error();const home=resolve(flags.get("--home")??process.env.NATIVESTUDIO_CLIENT_HOME??join(homedir(),".nativestudio/client"));const raw=await readInput(flags.get("--input"),stdin);if(action!=="import")return{exitCode:0,output:await runDesktopLibraryRequest(home,{operation:"library",call:{...raw,action}})};const file=flags.get("--file");if(!file)throw Error();const enrollment=flags.has("--enrollment")?await readInput(flags.get("--enrollment"),stdin):void 0;const{assertCurrent,...defaults}=await libraryImportContext(home,raw,enrollment);const seed=DesktopLibraryImportSeedSchema.parse({...defaults,title:basename(file),contentType:"application/octet-stream",...raw});const request=await prepareDesktopLibraryImport({operation:"library-import-prepare",file:resolve(file),seed});await assertCurrent?.();return{exitCode:0,output:await runDesktopLibraryImport(home,request)}}export{runLocalLibrary};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{loginCommand,runLoginService}from"./chunk-UITIQHVU.js";import{prepareInstalledCpuSpeech}from"./chunk-AIR7YOFU.js";import{connectDevice,generateDeviceKey}from"./chunk-GQ32ZQTM.js";import{LocalInstallationManager,captureInstalledTools,ownerClient}from"./chunk-IF6AUKH3.js";import{LocalAgentGrantSchema,NativeStudioLocalDeviceClient,localAgentMediaProposal,localAgentMediaSnapshot,localAgentSnapshotFromContext}from"./chunk-CTCEGOC7.js";import{readCredential,readInput}from"./chunk-QGK6G6YS.js";import{localCliVersion}from"./chunk-2UYKJ6YN.js";import{EnrollLocalDeviceSchema,LocalManagementCommandSchema,NativeStudioAgentClient,RevokeLocalDeviceSchema,StartLocalFinalRenderSchema,StartLocalPreviewSchema,canonicalLocalJson}from"./chunk-LZPPTW2K.js";import"./chunk-7I7ARCY7.js";import{LocalClientError}from"./chunk-DLW42PJ6.js";import"./chunk-WTJVS2VS.js";import"./chunk-KOCUZ3AE.js";import{NativeStudioSdkError}from"./chunk-TT7IA5HB.js";import{homedir as homedir2}from"node:os";import{join as join2,resolve as resolve2}from"node:path";function preparationGuidance(code){const steps={DEPENDENCY_CHANNEL_REQUIRED:["Read workspace_caller.hostReleases (CLI: call workspace.caller); use its exact configured URL, not an inferred path.","Configure the advertised catalogueUrl/publicKey through local configure; never accept an unsigned catalogue or invent a trust key."],MANAGED_TOOLS_UNAVAILABLE:["This exact signed release has no qualified managed media executables. Install the required tools using the host's authorized package manager or official vendor.","Use local tools-prepare --version <resolved-runtime-version> --input <private-json> with mode INSTALLED and absolute ffmpeg/ffprobe paths. Missing fonts/browser remain separate capabilities."],RELEASE_NOT_PUBLISHED:["Ask the release operator to publish matching exact-version dependencies. Preserve this CLI/Runtime identity; do not substitute another version's bytes."],RELEASE_METADATA_INVALID:["Reject malformed release metadata; ask the operator to check the exact signed catalogue URL. Do not treat a discovery page as a catalogue."],RELEASE_ACCESS_DENIED:["The public download edge denied access. Inspect its safe status; for Cloudflare 1010, identify your actual application with a descriptive User-Agent. Do not disable TLS or copy a browser session."],RELEASE_TIMEOUT:["The read deadline ended. An unknown installation apply must be reconciled from its original plan, never replayed blindly."],RELEASE_SIGNATURE_INVALID:["Reject these bytes. Verify the configured operator URL/public key; do not rotate trust to make verification pass."],RELEASE_EXPIRED:["Ask the operator to renew the approved inventory; never ignore expiry or alter the host clock."],BUNDLED_COMPONENT_RELEASE_MISMATCH:["The catalogue does not match the code/resources inside this CLI. Keep the original installation plan; ask the operator for its matching release."],LOGIN_SERVICE_RUNTIME_UPDATE_REQUIRED:["Activate a Runtime with login startup support through the existing exact-version installation plan."],LOGIN_SERVICE_REPLACE_REQUIRED:["Read local service-status and disable the existing registration using its original fingerprint. Then approve the current service plan."],LOGIN_SERVICE_OS_UNCONFIRMED:["Read local service-status and check the current user's native service manager. Keep the original approval fingerprint for reconciliation."],LOGIN_SERVICE_DISABLE_PENDING:["Read local service-status and complete service-disable using the original fingerprint."]};return steps[code]}import{homedir}from"node:os";import{join,resolve}from"node:path";import{createHash}from"node:crypto";async function runLocalAgentCli(argv,stdin){try{const[command,...rest]=argv,flags=new Map;for(let n=0;n<rest.length;n+=2){const k=rest[n],v=rest[n+1];if(!k||!["--home","--input","--approve","--id","--revision","--evidence","--origin","--token-file"].includes(k)||!v||v.startsWith("--")||flags.has(k))throw Error();flags.set(k,v)}const need=k=>{const v=flags.get(k);if(!v)throw Error();return v};if(command==="agent-grant-plan"){const grant=LocalAgentGrantSchema.parse(await readInput(need("--input"),stdin));const disclosures=["review metadata",...grant.imageDisclosureApproved?["original image pixels"]:[],...grant.mediaDisclosureApproved?["normalized image pixels or sampled video frames and technical audio statistics"]:[]];return{exitCode:0,output:{grant,fingerprint:createHash("sha256").update(canonicalLocalJson(grant)).digest("hex"),note:`Approving this fingerprint permits remote OpenAI inference for these Projects until expiry and allows disclosure of ${disclosures.join(", ")}. Preview does not invoke a model.`}}}const evidence=flags.get("--evidence");if(evidence&&!["IMAGE_PIXELS","METADATA_ONLY","MEDIA"].includes(evidence))throw Error();const manager=await LocalInstallationManager.open(resolve(flags.get("--home")??join(homedir(),".nativestudio","client")));const client=await ownerClient((await manager.configuration()).stateDirectory);const studioFor=tenantId=>new NativeStudioAgentClient({baseUrl:need("--origin"),tenantId,authorization:()=>readCredential(flags,process.env)});let output;switch(command){case"agent-grant":output=await client.grantAgent(await readInput(need("--input"),stdin),need("--approve"));break;case"agent-revoke":output=await client.revokeAgent(need("--approve"));break;case"agent-probe":output=await client.probeAgent();break;case"review-prepare":{const context=await readInput(need("--input"),stdin);output=await client.prepareAgentReview(evidence==="MEDIA"?localAgentMediaSnapshot(context):localAgentSnapshotFromContext(context,evidence==="IMAGE_PIXELS"));break}case"review-image-fetch":{const view=await client.inspectAgentReview(need("--id")),snapshot=view.plan.snapshot;if(!snapshot.image||snapshot.basis.target.kind!=="IMAGE")throw Error();const studio=studioFor(snapshot.basis.scope.tenantId);const media=await studio.keyframeMedia({productionId:snapshot.basis.scope.productionId,generationId:snapshot.basis.target.generationId},{checksumSha256:snapshot.media.checksumSha256,byteSize:snapshot.image.byteSize});if(media.contentType!==snapshot.image.contentType)throw Error();output=await client.stageAgentImage(view.plan.id,media.bytes);break}case"review-media-fetch":{const view=await client.inspectAgentReview(need("--id"));const{basis,evidence:expected,media}=view.plan.snapshot;if(!expected)throw Error();if(view.evidenceReceipt){output=view;break}if(view.phase!=="PREPARED")throw Error();const source=await studioFor(basis.scope.tenantId).immutableMedia({projectId:basis.scope.projectId,representationId:media.representationId,checksumSha256:media.checksumSha256,byteSize:expected.byteSize});output=await client.stageAgentImage(view.plan.id,source.bytes);break}case"review-start":output=await client.startAgentReview(need("--id"),Number(need("--revision")),need("--approve"));break;case"review-inspect":output=await client.inspectAgentReview(need("--id"));break;case"review-proposal":output=localAgentMediaProposal(await client.inspectAgentReview(need("--id")));break;default:throw Error()}return{exitCode:0,output}}catch(e){const known=e instanceof NativeStudioSdkError;return{exitCode:2,output:{semanticStatus:"BLOCKED",error:{code:known?e.code:"INVALID_INPUT",outcome:known?e.outcome:"NO_WRITE"}}}}}async function runLocalCli(argv,stdin=process.stdin){let mutation=false;try{const[command,...rest]=argv,options=new Map;if(command==="library"){mutation=["import","access","resume-access"].includes(rest[0]??"");return await(await import("./library-main-4BQ2J73H.js")).runLocalLibrary(rest,stdin)}if(command==="device-preflight"){for(let i=0;i<rest.length;i+=2){const name=rest[i],value=rest[i+1];if(!name||!["--kind","--home","--project"].includes(name)||!value||value.startsWith("--")||options.has(name))throw Error();options.set(name,value)}return(await import("./device-preflight-QAPMMHWK.js")).devicePreflight(options.get("--kind"),{...process.env,...options.has("--home")&&{NATIVESTUDIO_CLIENT_HOME:resolve2(options.get("--home"))}},options.get("--project"))}if(command?.startsWith("agent-")||command?.startsWith("review-"))return runLocalAgentCli(argv,stdin);const allowed=["--home","--input","--version","--plan","--approve","--output","--origin","--token-file","--action"];for(let i=0;i<rest.length;i+=2){const k=rest[i],v=rest[i+1];if(!k||!allowed.includes(k)||!v||v.startsWith("--")||options.has(k))throw Error();options.set(k,v)}if(command==="help"||!command)return{exitCode:0,output:{namespace:"nvs local",commands:["configure --input <private-json>","keygen --output <new-private-device-key>","cloud --action enroll|revoke-device|preview|final|receipt --origin <cloud-origin> --token-file <member-token> --input <json>","connect --input <private-device-config>","version","install|update-prepare --version <exact|latest> \u2014 uses this CLI's bundled code; update CLI first for newer code; latest resolves once into an exact saved plan","speech-prepare --input <json with optional voiceIds> \u2014 prepare pinned CPU speech resources and return the original tools update plan","tools-prepare --version <exact|latest> --input <private-json with mode MANAGED or INSTALLED, exact ffmpeg/ffprobe paths, optional compositionBrowser and captionAssetsDirectory>","update-check","update-reject --version <exact>","update-apply --plan <uuid> --approve <fingerprint>","update-reconcile --plan <uuid> --approve <fingerprint>","start","status","service-plan|service-status [--home <private-client-home>] \u2014 inspect optional user-login startup without changing it","service-enable|service-start|service-disable --approve <service-fingerprint> [--home <private-client-home>] \u2014 register, start or remove this installation's user-login service","device-preflight --kind preview|final|<processor-kind> [--project <uuid>] [--home <private-client-home>] \u2014 read current setup and action qualification","doctor","stop","grant --input <scopes-expiry-json> --output <new-private-connector>","mcp [--connector <private-file>] [--with-library]","library import|list|get|read|access|sync|resume-access|import-receipt|usage --input <json|-> [--file <exact-media>] [--home <client-home>] \u2014 private Owner library; import never uploads","agent-grant-plan|agent-probe|agent-grant|agent-revoke \u2014 installed Codex CLI with explicitly authorized remote OpenAI inference","review-prepare --input <private-context> [--evidence METADATA_ONLY|IMAGE_PIXELS|MEDIA]","review-media-fetch --id <draft> --origin <cloud-origin> --token-file <member-token> \u2014 read exact stored bytes for a MEDIA draft","review-image-fetch|review-inspect|review-proposal \u2014 use --id <draft>","review-start --id <draft> --revision <current> --approve <plan-fingerprint>"],note:"Release check and update planning only inspect metadata. speech-prepare explicitly fetches optional CPU resources. Apply uses the exact saved fingerprint. MCP disconnect does not stop Runtime."}};if(command==="version")return{exitCode:0,output:await localCliVersion()};const required=key=>{const v=options.get(key);if(!v)throw Error();return v};if(command==="keygen")return{exitCode:0,output:await generateDeviceKey(resolve2(required("--output")))};if(command==="cloud"){const input=await readInput(required("--input"),stdin);const action=required("--action");const tenantId=action==="receipt"?LocalManagementCommandSchema.parse(input).input.tenantId:input.tenantId;if(typeof tenantId!=="string")throw Error();const client=new NativeStudioLocalDeviceClient({baseUrl:required("--origin"),tenantId,authorization:()=>readCredential(new Map([["--token-file",required("--token-file")]]),process.env)});const output2=action==="enroll"?await client.enroll(EnrollLocalDeviceSchema.parse(input)):action==="revoke-device"?await client.revokeDevice(RevokeLocalDeviceSchema.parse(input)):action==="preview"?await client.startPreview(StartLocalPreviewSchema.parse(input)):action==="final"?await client.startFinal(StartLocalFinalRenderSchema.parse(input)):action==="receipt"?await client.managementReceipt(LocalManagementCommandSchema.parse(input)):void 0;if(!output2)throw Error();return{exitCode:0,output:output2}}const home=resolve2(options.get("--home")??process.env.NATIVESTUDIO_CLIENT_HOME??join2(homedir2(),".nativestudio","client"));if(loginCommand(command)){mutation=["service-enable","service-start","service-disable"].includes(command);if([...options.keys()].some(key=>key!=="--home"&&(!mutation||key!=="--approve")))throw Error();return{exitCode:0,output:await runLoginService(command,home,options.get("--approve"))}}const manager=await LocalInstallationManager.open(home);let output;mutation=["configure","speech-prepare","connect","start","stop","grant","update-apply","update-reconcile","update-reject"].includes(command??"");switch(command){case"connect":output=await connectDevice(manager,await readInput(required("--input"),stdin));break;case"configure":output=await manager.configure(await readInput(required("--input"),stdin));break;case"status":output=await manager.status();break;case"update-reject":output=await manager.reject(required("--version"));break;case"update-check":output=await manager.check();break;case"install":case"update-prepare":output=await manager.prepareBundled(required("--version"));break;case"speech-prepare":output=await prepareInstalledCpuSpeech(manager,await readInput(required("--input"),stdin));break;case"tools-prepare":{const raw=await readInput(required("--input"),stdin);const choice=raw.mode==="INSTALLED"?await captureInstalledTools(raw):raw;output=await manager.prepareBundled(required("--version"),choice)}break;case"update-apply":output=await manager.apply(required("--plan"),required("--approve"));break;case"update-reconcile":output=await manager.reconcile(required("--plan"),required("--approve"));break;case"start":output=await manager.start();break;case"stop":output=await manager.stop();break;case"doctor":output=await(await ownerClient((await manager.configuration()).stateDirectory)).doctor();break;case"grant":output=await manager.grant(await readInput(required("--input"),stdin),resolve2(required("--output")));break;default:throw Error()}return{exitCode:0,output}}catch(e){const known=e instanceof LocalClientError?e.code:e instanceof NativeStudioSdkError?e.code:"INVALID_INPUT";return{exitCode:2,output:{semanticStatus:"BLOCKED",...preparationGuidance(known)?{nextSteps:preparationGuidance(known)}:{},error:{code:known,outcome:e instanceof NativeStudioSdkError?e.outcome:mutation&&!["USER_APPROVAL_REQUIRED","PLAN_CHANGED","REVISION_CONFLICT","INSTALL_REQUIRED","CONFIGURATION_REQUIRED","DEVICE_CONNECTION_REQUIRED","LOGIN_SERVICE_PLAN_CHANGED","LOGIN_SERVICE_REPLACE_REQUIRED","LOGIN_SERVICE_DISABLE_PENDING","LOGIN_SERVICE_RUNTIME_UPDATE_REQUIRED","LOGIN_SERVICE_PLATFORM_UNSUPPORTED","LOGIN_SERVICE_USER_REQUIRED"].includes(known)?"UNKNOWN":"NO_WRITE"}}}}}export{runLocalCli};
|
|
1
|
+
import{loginCommand,runLoginService}from"./chunk-D74NHT4I.js";import{prepareInstalledCpuSpeech}from"./chunk-FVY3PLG7.js";import{connectDevice,generateDeviceKey}from"./chunk-HBDPYWMI.js";import{LocalInstallationManager,captureInstalledTools,ownerClient}from"./chunk-ELUJ44BO.js";import{LocalAgentGrantSchema,NativeStudioLocalDeviceClient,localAgentMediaProposal,localAgentMediaSnapshot,localAgentSnapshotFromContext}from"./chunk-6EZX2TRX.js";import{readCredential,readInput}from"./chunk-QGK6G6YS.js";import{localCliVersion}from"./chunk-2UYKJ6YN.js";import{EnrollLocalDeviceSchema,LocalManagementCommandSchema,NativeStudioAgentClient,RevokeLocalDeviceSchema,StartLocalFinalRenderSchema,StartLocalPreviewSchema,canonicalLocalJson}from"./chunk-APNZQZFB.js";import"./chunk-7I7ARCY7.js";import{LocalClientError}from"./chunk-DLW42PJ6.js";import"./chunk-WTJVS2VS.js";import"./chunk-KOCUZ3AE.js";import{NativeStudioSdkError}from"./chunk-TT7IA5HB.js";import{homedir as homedir2}from"node:os";import{join as join2,resolve as resolve2}from"node:path";function preparationGuidance(code){const steps={DEPENDENCY_CHANNEL_REQUIRED:["Read workspace_caller.hostReleases (CLI: call workspace.caller); use its exact configured URL, not an inferred path.","Configure the advertised catalogueUrl/publicKey through local configure; never accept an unsigned catalogue or invent a trust key."],MANAGED_TOOLS_UNAVAILABLE:["This exact signed release has no qualified managed media executables. Install the required tools using the host's authorized package manager or official vendor.","Use local tools-prepare --version <resolved-runtime-version> --input <private-json> with mode INSTALLED and absolute ffmpeg/ffprobe paths. Missing fonts/browser remain separate capabilities."],RELEASE_NOT_PUBLISHED:["Ask the release operator to publish matching exact-version dependencies. Preserve this CLI/Runtime identity; do not substitute another version's bytes."],RELEASE_METADATA_INVALID:["Reject malformed release metadata; ask the operator to check the exact signed catalogue URL. Do not treat a discovery page as a catalogue."],RELEASE_ACCESS_DENIED:["The public download edge denied access. Inspect its safe status; for Cloudflare 1010, identify your actual application with a descriptive User-Agent. Do not disable TLS or copy a browser session."],RELEASE_TIMEOUT:["The read deadline ended. An unknown installation apply must be reconciled from its original plan, never replayed blindly."],RELEASE_SIGNATURE_INVALID:["Reject these bytes. Verify the configured operator URL/public key; do not rotate trust to make verification pass."],RELEASE_EXPIRED:["Ask the operator to renew the approved inventory; never ignore expiry or alter the host clock."],BUNDLED_COMPONENT_RELEASE_MISMATCH:["The catalogue does not match the code/resources inside this CLI. Keep the original installation plan; ask the operator for its matching release."],LOGIN_SERVICE_RUNTIME_UPDATE_REQUIRED:["Activate a Runtime with login startup support through the existing exact-version installation plan."],LOGIN_SERVICE_REPLACE_REQUIRED:["Read local service-status and disable the existing registration using its original fingerprint. Then approve the current service plan."],LOGIN_SERVICE_OS_UNCONFIRMED:["Read local service-status and check the current user's native service manager. Keep the original approval fingerprint for reconciliation."],LOGIN_SERVICE_DISABLE_PENDING:["Read local service-status and complete service-disable using the original fingerprint."]};return steps[code]}import{homedir}from"node:os";import{join,resolve}from"node:path";import{createHash}from"node:crypto";async function runLocalAgentCli(argv,stdin){try{const[command,...rest]=argv,flags=new Map;for(let n=0;n<rest.length;n+=2){const k=rest[n],v=rest[n+1];if(!k||!["--home","--input","--approve","--id","--revision","--evidence","--origin","--token-file"].includes(k)||!v||v.startsWith("--")||flags.has(k))throw Error();flags.set(k,v)}const need=k=>{const v=flags.get(k);if(!v)throw Error();return v};if(command==="agent-grant-plan"){const grant=LocalAgentGrantSchema.parse(await readInput(need("--input"),stdin));const disclosures=["review metadata",...grant.imageDisclosureApproved?["original image pixels"]:[],...grant.mediaDisclosureApproved?["normalized image pixels or sampled video frames and technical audio statistics"]:[]];return{exitCode:0,output:{grant,fingerprint:createHash("sha256").update(canonicalLocalJson(grant)).digest("hex"),note:`Approving this fingerprint permits remote OpenAI inference for these Projects until expiry and allows disclosure of ${disclosures.join(", ")}. Preview does not invoke a model.`}}}const evidence=flags.get("--evidence");if(evidence&&!["IMAGE_PIXELS","METADATA_ONLY","MEDIA"].includes(evidence))throw Error();const manager=await LocalInstallationManager.open(resolve(flags.get("--home")??join(homedir(),".nativestudio","client")));const client=await ownerClient((await manager.configuration()).stateDirectory);const studioFor=tenantId=>new NativeStudioAgentClient({baseUrl:need("--origin"),tenantId,authorization:()=>readCredential(flags,process.env)});let output;switch(command){case"agent-grant":output=await client.grantAgent(await readInput(need("--input"),stdin),need("--approve"));break;case"agent-revoke":output=await client.revokeAgent(need("--approve"));break;case"agent-probe":output=await client.probeAgent();break;case"review-prepare":{const context=await readInput(need("--input"),stdin);output=await client.prepareAgentReview(evidence==="MEDIA"?localAgentMediaSnapshot(context):localAgentSnapshotFromContext(context,evidence==="IMAGE_PIXELS"));break}case"review-image-fetch":{const view=await client.inspectAgentReview(need("--id")),snapshot=view.plan.snapshot;if(!snapshot.image||snapshot.basis.target.kind!=="IMAGE")throw Error();const studio=studioFor(snapshot.basis.scope.tenantId);const media=await studio.keyframeMedia({productionId:snapshot.basis.scope.productionId,generationId:snapshot.basis.target.generationId},{checksumSha256:snapshot.media.checksumSha256,byteSize:snapshot.image.byteSize});if(media.contentType!==snapshot.image.contentType)throw Error();output=await client.stageAgentImage(view.plan.id,media.bytes);break}case"review-media-fetch":{const view=await client.inspectAgentReview(need("--id"));const{basis,evidence:expected,media}=view.plan.snapshot;if(!expected)throw Error();if(view.evidenceReceipt){output=view;break}if(view.phase!=="PREPARED")throw Error();const source=await studioFor(basis.scope.tenantId).immutableMedia({projectId:basis.scope.projectId,representationId:media.representationId,checksumSha256:media.checksumSha256,byteSize:expected.byteSize});output=await client.stageAgentImage(view.plan.id,source.bytes);break}case"review-start":output=await client.startAgentReview(need("--id"),Number(need("--revision")),need("--approve"));break;case"review-inspect":output=await client.inspectAgentReview(need("--id"));break;case"review-proposal":output=localAgentMediaProposal(await client.inspectAgentReview(need("--id")));break;default:throw Error()}return{exitCode:0,output}}catch(e){const known=e instanceof NativeStudioSdkError;return{exitCode:2,output:{semanticStatus:"BLOCKED",error:{code:known?e.code:"INVALID_INPUT",outcome:known?e.outcome:"NO_WRITE"}}}}}async function runLocalCli(argv,stdin=process.stdin){let mutation=false;try{const[command,...rest]=argv,options=new Map;if(command==="library"){mutation=["import","access","resume-access"].includes(rest[0]??"");return await(await import("./library-main-ATRFEAVN.js")).runLocalLibrary(rest,stdin)}if(command==="device-preflight"){for(let i=0;i<rest.length;i+=2){const name=rest[i],value=rest[i+1];if(!name||!["--kind","--home","--project"].includes(name)||!value||value.startsWith("--")||options.has(name))throw Error();options.set(name,value)}return(await import("./device-preflight-C7FFUXI2.js")).devicePreflight(options.get("--kind"),{...process.env,...options.has("--home")&&{NATIVESTUDIO_CLIENT_HOME:resolve2(options.get("--home"))}},options.get("--project"))}if(command?.startsWith("agent-")||command?.startsWith("review-"))return runLocalAgentCli(argv,stdin);const allowed=["--home","--input","--version","--plan","--approve","--output","--origin","--token-file","--action"];for(let i=0;i<rest.length;i+=2){const k=rest[i],v=rest[i+1];if(!k||!allowed.includes(k)||!v||v.startsWith("--")||options.has(k))throw Error();options.set(k,v)}if(command==="help"||!command)return{exitCode:0,output:{namespace:"nvs local",commands:["configure --input <private-json>","keygen --output <new-private-device-key>","cloud --action enroll|revoke-device|preview|final|receipt --origin <cloud-origin> --token-file <member-token> --input <json>","connect --input <private-device-config>","version","install|update-prepare --version <exact|latest> \u2014 uses this CLI's bundled code; update CLI first for newer code; latest resolves once into an exact saved plan","speech-prepare --input <json with optional voiceIds> \u2014 prepare pinned CPU speech resources and return the original tools update plan","tools-prepare --version <exact|latest> --input <private-json with mode MANAGED or INSTALLED, exact ffmpeg/ffprobe paths, optional compositionBrowser and captionAssetsDirectory>","update-check","update-reject --version <exact>","update-apply --plan <uuid> --approve <fingerprint>","update-reconcile --plan <uuid> --approve <fingerprint>","start","status","service-plan|service-status [--home <private-client-home>] \u2014 inspect optional user-login startup without changing it","service-enable|service-start|service-disable --approve <service-fingerprint> [--home <private-client-home>] \u2014 register, start or remove this installation's user-login service","device-preflight --kind preview|final|<processor-kind> [--project <uuid>] [--home <private-client-home>] \u2014 read current setup and action qualification","doctor","stop","grant --input <scopes-expiry-json> --output <new-private-connector>","mcp [--connector <private-file>] [--with-library]","library import|list|get|read|access|sync|resume-access|import-receipt|usage --input <json|-> [--file <exact-media>] [--home <client-home>] \u2014 private Owner library; import never uploads","agent-grant-plan|agent-probe|agent-grant|agent-revoke \u2014 installed Codex CLI with explicitly authorized remote OpenAI inference","review-prepare --input <private-context> [--evidence METADATA_ONLY|IMAGE_PIXELS|MEDIA]","review-media-fetch --id <draft> --origin <cloud-origin> --token-file <member-token> \u2014 read exact stored bytes for a MEDIA draft","review-image-fetch|review-inspect|review-proposal \u2014 use --id <draft>","review-start --id <draft> --revision <current> --approve <plan-fingerprint>"],note:"Release check and update planning only inspect metadata. speech-prepare explicitly fetches optional CPU resources. Apply uses the exact saved fingerprint. MCP disconnect does not stop Runtime."}};if(command==="version")return{exitCode:0,output:await localCliVersion()};const required=key=>{const v=options.get(key);if(!v)throw Error();return v};if(command==="keygen")return{exitCode:0,output:await generateDeviceKey(resolve2(required("--output")))};if(command==="cloud"){const input=await readInput(required("--input"),stdin);const action=required("--action");const tenantId=action==="receipt"?LocalManagementCommandSchema.parse(input).input.tenantId:input.tenantId;if(typeof tenantId!=="string")throw Error();const client=new NativeStudioLocalDeviceClient({baseUrl:required("--origin"),tenantId,authorization:()=>readCredential(new Map([["--token-file",required("--token-file")]]),process.env)});const output2=action==="enroll"?await client.enroll(EnrollLocalDeviceSchema.parse(input)):action==="revoke-device"?await client.revokeDevice(RevokeLocalDeviceSchema.parse(input)):action==="preview"?await client.startPreview(StartLocalPreviewSchema.parse(input)):action==="final"?await client.startFinal(StartLocalFinalRenderSchema.parse(input)):action==="receipt"?await client.managementReceipt(LocalManagementCommandSchema.parse(input)):void 0;if(!output2)throw Error();return{exitCode:0,output:output2}}const home=resolve2(options.get("--home")??process.env.NATIVESTUDIO_CLIENT_HOME??join2(homedir2(),".nativestudio","client"));if(loginCommand(command)){mutation=["service-enable","service-start","service-disable"].includes(command);if([...options.keys()].some(key=>key!=="--home"&&(!mutation||key!=="--approve")))throw Error();return{exitCode:0,output:await runLoginService(command,home,options.get("--approve"))}}const manager=await LocalInstallationManager.open(home);let output;mutation=["configure","speech-prepare","connect","start","stop","grant","update-apply","update-reconcile","update-reject"].includes(command??"");switch(command){case"connect":output=await connectDevice(manager,await readInput(required("--input"),stdin));break;case"configure":output=await manager.configure(await readInput(required("--input"),stdin));break;case"status":output=await manager.status();break;case"update-reject":output=await manager.reject(required("--version"));break;case"update-check":output=await manager.check();break;case"install":case"update-prepare":output=await manager.prepareBundled(required("--version"));break;case"speech-prepare":output=await prepareInstalledCpuSpeech(manager,await readInput(required("--input"),stdin));break;case"tools-prepare":{const raw=await readInput(required("--input"),stdin);const choice=raw.mode==="INSTALLED"?await captureInstalledTools(raw):raw;output=await manager.prepareBundled(required("--version"),choice)}break;case"update-apply":output=await manager.apply(required("--plan"),required("--approve"));break;case"update-reconcile":output=await manager.reconcile(required("--plan"),required("--approve"));break;case"start":output=await manager.start();break;case"stop":output=await manager.stop();break;case"doctor":output=await(await ownerClient((await manager.configuration()).stateDirectory)).doctor();break;case"grant":output=await manager.grant(await readInput(required("--input"),stdin),resolve2(required("--output")));break;default:throw Error()}return{exitCode:0,output}}catch(e){const known=e instanceof LocalClientError?e.code:e instanceof NativeStudioSdkError?e.code:"INVALID_INPUT";return{exitCode:2,output:{semanticStatus:"BLOCKED",...preparationGuidance(known)?{nextSteps:preparationGuidance(known)}:{},error:{code:known,outcome:e instanceof NativeStudioSdkError?e.outcome:mutation&&!["USER_APPROVAL_REQUIRED","PLAN_CHANGED","REVISION_CONFLICT","INSTALL_REQUIRED","CONFIGURATION_REQUIRED","DEVICE_CONNECTION_REQUIRED","LOGIN_SERVICE_PLAN_CHANGED","LOGIN_SERVICE_REPLACE_REQUIRED","LOGIN_SERVICE_DISABLE_PENDING","LOGIN_SERVICE_RUNTIME_UPDATE_REQUIRED","LOGIN_SERVICE_PLATFORM_UNSUPPORTED","LOGIN_SERVICE_USER_REQUIRED"].includes(known)?"UNKNOWN":"NO_WRITE"}}}}}export{runLocalCli};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{workspaceCaller}from"./chunk-
|
|
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,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-KMP4SMK7.js")).renderCommand(argv.slice(1),environment);if(argv[0]==="devices")return await(await import("./devices-main-XKRRLX5B.js")).devicesCommand(argv.slice(1),environment,stdin);if(argv[0]==="import")return await(await import("./source-import-YYRII5FQ.js")).importSourceCommand(argv.slice(1),environment,stdin);if(AccountCommands.has(argv[0]??"")){const business=await(await import("./workspace-main-LD56MMI6.js")).workspaceCommand(argv,environment);return business??await runAccountCommand(argv,environment)}if(argv.length===1&&argv[0]==="status")return await connectionStatus(environment);if(NavigationCliCommands.has(argv[0]??""))return await runNavigationCli(argv,stdin,(args2,input2)=>runRemoteCli(args2,environment,input2));if(["auth-start","auth-complete"].includes(argv[0]??""))return await(await import("./oauth-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>","capabilities [groups | search --query <text> --group <group> | describe --tool <name>]","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 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{sdkOperations,sdkMcpTools,sdkCarrierDifferences,assertCarrierCoverage}=await import("./src-IX5ZVGZS.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"];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 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-TIFVZEGG.js")).withRemoteClient(options,environment,sdkMcpTools[key]===null,studio=>studio.call(key,input));const status=output?.semanticStatus;return{exitCode:status?exits[status]??1:0,output}}catch(error){const e=error instanceof NativeStudioSdkError?error:null;const accountRecovery={ACCOUNT_LOGIN_OUTCOME_UNKNOWN:["Start a fresh nvs login --server <Studio-origin>; never replay the old exchange."],ACCOUNT_LOGOUT_OUTCOME_UNKNOWN:["Retry nvs logout explicitly; local account use remains locked."],ACCOUNT_LOGIN_REQUIRED:["nvs login --server <Studio-origin>"],ACCOUNT_SESSION_EXPIRED_OR_REVOKED:["nvs login --server <Studio-origin>"],WORKSPACE_SELECTION_REQUIRED:["nvs workspaces","nvs workspace --id <workspace-id>"],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-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};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{connectRemoteMcp}from"./chunk-GLAF74UU.js";import"./chunk-2UYKJ6YN.js";import"./chunk-APNZQZFB.js";import"./chunk-WTJVS2VS.js";import"./chunk-KOCUZ3AE.js";import"./chunk-TT7IA5HB.js";export{connectRemoteMcp};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{withRemoteClient}from"./chunk-
|
|
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 +1 @@
|
|
|
1
|
-
import{withRemoteClient}from"./chunk-
|
|
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};
|
|
@@ -0,0 +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};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var actions={list:{command:"series.list",fields:{"--project":"projectId","--after":"after","--limit":"limit"}},get:{command:"series.get",fields:{"--project":"projectId","--series":"seriesId","--version":"version"}},binding:{command:"series.binding",fields:{"--project":"projectId","--production":"productionId","--revision":"productionRevision","--at-revision":"atRevision"}},publish:{command:"series.publish",fields:{}},bind:{command:"series.bind",fields:{}},receipt:{command:"series.receipt",fields:{}},"brand-command":{command:"series.brand.command",fields:{}},"brand-get":{command:"series.brand.get",fields:{}},"brand-receipt":{command:"series.brand.receipt",fields:{}},"canon-record":{command:"series.canon.record",fields:{}},"canon-get":{command:"series.canon.get",fields:{}},"canon-receipt":{command:"series.canon.receipt",fields:{}},"improvement-command":{command:"series.improvement.command",fields:{}},"improvement-query":{command:"series.improvement.query",fields:{}},"improvement-receipt":{command:"series.improvement.receipt",fields:{}}};var connectionOptions=new Set(["--tenant","--origin","--mcp-url","--profile","--token-env","--token-file","--transport","--capability-version"]);var numericFields=new Set(["limit","version","productionRevision","atRevision"]);var receiptCommands={publish:"receipt",bind:"receipt","brand-command":"brand-receipt","canon-record":"canon-receipt","improvement-command":"improvement-receipt"};var seriesHelp={commands:["nvs series list --project <uuid> [--after <uuid>] [--limit <1..40>]","nvs series get --project <uuid> --series <uuid> [--version <n>]","nvs series publish --input <json|->","nvs series bind --input <json|->","nvs series binding --project <uuid> --production <uuid> [--revision <n> | --at-revision <n>]","nvs series receipt --input <json|->","nvs series brand-command|brand-get|brand-receipt --input <json|->","nvs series canon-record|canon-get|canon-receipt --input <json|->","nvs series improvement-command|improvement-query|improvement-receipt --input <json|->"],connection:"Uses the saved tenant OAuth connection. Explicit connection flags match nvs call.",capabilityVersion:"Optional on member MCP. Pass --capability-version with the version from capabilities describe.",continuation:"List and read a series, bind its exact version, then use the returned production and profile revisions in production operations.",json:{publish:["projectId","seriesId","expectedVersion","content","reason","idempotencyKey"],bind:["projectId","productionId","seriesId","version","expectedProductionRevision","expectedProfileVersion","reason","idempotencyKey"],receipt:["projectId","idempotencyKey"],characterVariants:"Optionally pass characterVariantIds when binding; read approved choices through series get.",binding:"Use --at-revision with a native media receipt's productionRevision to read the series version in effect for that output.",brandCommand:"Use action PUBLISH, GRANT or REVOKE in the brand owner project. Use brand-receipt with projectId and idempotencyKey to recover."}};async function runSeriesCli([verb,...args],stdin,call){if((!verb||verb==="help"||verb==="--help")&&!args.length)return{exitCode:0,output:seriesHelp};if(!verb||!Object.hasOwn(actions,verb))throw Error("INVALID_INPUT");const action=actions[verb];const fields=action.fields;const argv=["call",action.command];const seen=new Set;const data={};let input;for(let index=0;index<args.length;index+=2){const flag=args[index],value=args[index+1];if(!value||value.startsWith("--")||seen.has(flag))throw Error("INVALID_INPUT");seen.add(flag);if(connectionOptions.has(flag))argv.push(flag,value);else if(flag==="--input")input=value;else{const field=fields[flag];if(!Object.hasOwn(fields,flag)||!field)throw Error("INVALID_INPUT");if(numericFields.has(field)&&!/^[1-9]\d{0,15}$/.test(value))throw Error("INVALID_INPUT");data[field]=numericFields.has(field)?Number(value):value}}if(input?Object.keys(data).length:!Object.keys(fields).length||!data.projectId)throw Error("INVALID_INPUT");async function*generatedInput(){yield Buffer.from(JSON.stringify(data))}const result=await call([...argv,"--input",input??"-"],input?stdin:generatedInput());const output=result.output;const recovery=receiptCommands[verb];return output?.error?.outcome==="UNKNOWN"&&recovery?{...result,output:{...output,nextSteps:[`nvs series ${recovery} --input <original-project-and-request-key-json|->`]}}:result}export{runSeriesCli,seriesHelp};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{profileAuthorization}from"./chunk-3TOXIJ7K.js";import{readCredential,readInput}from"./chunk-QGK6G6YS.js";import{NativeStudioAgentClient}from"./chunk-
|
|
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};
|
|
@@ -0,0 +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 +1 @@
|
|
|
1
|
-
import{workspaceCommand,workspaceProject}from"./chunk-
|
|
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};
|
|
@@ -1393,7 +1393,7 @@ export declare class LocalInstallationManager {
|
|
|
1393
1393
|
expectedRuntimeRevision: number;
|
|
1394
1394
|
};
|
|
1395
1395
|
availability: "AVAILABLE" | "BLOCKED";
|
|
1396
|
-
reason: "READY" | "
|
|
1396
|
+
reason: "READY" | "AUTHORIZATION_REQUIRED" | "INSTALL_REQUIRED" | "VERSION_INCOMPATIBLE" | "UPDATE_AVAILABLE" | "RECOVERY_REQUIRED";
|
|
1397
1397
|
}[];
|
|
1398
1398
|
deviceAuthority?: {
|
|
1399
1399
|
tenantId: string;
|
|
@@ -239,8 +239,8 @@ export declare class LocalMcpTools {
|
|
|
239
239
|
reason: z.ZodEnum<{
|
|
240
240
|
UNAVAILABLE: "UNAVAILABLE";
|
|
241
241
|
READY: "READY";
|
|
242
|
-
INSTALL_REQUIRED: "INSTALL_REQUIRED";
|
|
243
242
|
AUTHORIZATION_REQUIRED: "AUTHORIZATION_REQUIRED";
|
|
243
|
+
INSTALL_REQUIRED: "INSTALL_REQUIRED";
|
|
244
244
|
VERSION_INCOMPATIBLE: "VERSION_INCOMPATIBLE";
|
|
245
245
|
UPDATE_AVAILABLE: "UPDATE_AVAILABLE";
|
|
246
246
|
RECOVERY_REQUIRED: "RECOVERY_REQUIRED";
|
|
@@ -469,8 +469,8 @@ export declare class LocalMcpTools {
|
|
|
469
469
|
reason: z.ZodEnum<{
|
|
470
470
|
UNAVAILABLE: "UNAVAILABLE";
|
|
471
471
|
READY: "READY";
|
|
472
|
-
INSTALL_REQUIRED: "INSTALL_REQUIRED";
|
|
473
472
|
AUTHORIZATION_REQUIRED: "AUTHORIZATION_REQUIRED";
|
|
473
|
+
INSTALL_REQUIRED: "INSTALL_REQUIRED";
|
|
474
474
|
VERSION_INCOMPATIBLE: "VERSION_INCOMPATIBLE";
|
|
475
475
|
UPDATE_AVAILABLE: "UPDATE_AVAILABLE";
|
|
476
476
|
RECOVERY_REQUIRED: "RECOVERY_REQUIRED";
|
|
@@ -4,6 +4,7 @@ export declare function fetchBytes(raw: string, maximum: number, origin: string,
|
|
|
4
4
|
export interface ReleaseTrust {
|
|
5
5
|
catalogueUrl?: string | null;
|
|
6
6
|
publicKeyFile?: string | null;
|
|
7
|
+
publicKey?: string;
|
|
7
8
|
}
|
|
8
9
|
export declare function catalogue(trust: ReleaseTrust, signal?: AbortSignal): Promise<{
|
|
9
10
|
signed: {
|