@nativestudio/cli 0.3.0-rc.14 → 0.3.0-rc.16
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 +11 -11
- package/components/runtime.json +7 -7
- package/components/runtime.tgz +0 -0
- package/dist/_chunks/{chunk-C62JAWRQ.js → chunk-35XQP7RY.js} +1 -1
- package/dist/_chunks/{chunk-RDIMORUT.js → chunk-5LSB6HDP.js} +1 -1
- package/dist/_chunks/{chunk-W6C63ZN7.js → chunk-B7BQERMR.js} +1 -1
- package/dist/_chunks/{chunk-S74X4KIC.js → chunk-BGH3Y5UX.js} +1 -1
- package/dist/_chunks/chunk-CW67UB2I.js +1 -0
- package/dist/_chunks/chunk-EML7OS3I.js +1 -0
- package/dist/_chunks/{chunk-3AVC742O.js → chunk-FX5UVDTH.js} +1 -1
- package/dist/_chunks/{chunk-6UYY5KHI.js → chunk-HAOCQVMU.js} +1 -1
- package/dist/_chunks/{chunk-VD3OQ743.js → chunk-JLQCUXCT.js} +1 -1
- package/dist/_chunks/chunk-KOCUZ3AE.js +1 -0
- package/dist/_chunks/chunk-LOYAGAAN.js +1 -0
- package/dist/_chunks/chunk-MT5XZ67U.js +1 -0
- package/dist/_chunks/{chunk-VDNNFVTZ.js → chunk-OW6R4MAQ.js} +1 -1
- package/dist/_chunks/{chunk-6LY4JYSG.js → chunk-PYUYK3FV.js} +1 -1
- package/dist/_chunks/chunk-RT77PT3A.js +1 -0
- package/dist/_chunks/chunk-RUPH3HZ2.js +1 -0
- package/dist/_chunks/chunk-SKAVQ4UW.js +1 -0
- package/dist/_chunks/{chunk-ROBBF33U.js → chunk-SRB5ZFKO.js} +1 -1
- package/dist/_chunks/chunk-TQIJBUSP.js +1 -0
- package/dist/_chunks/chunk-TWC3NXFA.js +1 -0
- package/dist/_chunks/chunk-U5FT4VBR.js +1 -0
- package/dist/_chunks/chunk-U6ZG2G7W.js +1 -0
- package/dist/_chunks/chunk-UMCOLDHH.js +1 -0
- package/dist/_chunks/chunk-VLEWCWYF.js +1 -0
- package/dist/_chunks/chunk-WAADGZEV.js +1 -0
- package/dist/_chunks/{chunk-VKLS4QK5.js → chunk-XVQWVJWD.js} +1 -1
- package/dist/_chunks/{connect-6UH7ZFAC.js → connect-OY623MMA.js} +1 -1
- package/dist/_chunks/{device-management-H3NIDIPY.js → device-management-ELAPFWM2.js} +1 -1
- package/dist/_chunks/device-preflight-27RDJVBU.js +1 -0
- package/dist/_chunks/{devices-inventory-I2E3Q4DA.js → devices-inventory-2XEJPPO5.js} +1 -1
- package/dist/_chunks/{devices-main-VV2VYU4T.js → devices-main-UMF3ZBHA.js} +1 -1
- package/dist/_chunks/{files-TTIQ7LYJ.js → files-72BEXD7E.js} +1 -1
- package/dist/_chunks/{host-main-3JFGVU5P.js → host-main-WYTVTQ4Z.js} +1 -1
- package/dist/_chunks/http-profile-D65WSTZU.js +1 -0
- package/dist/_chunks/{library-main-CTBW7DAI.js → library-main-L7SY7V7L.js} +1 -1
- package/dist/_chunks/local-main-7FONRY6F.js +1 -0
- package/dist/_chunks/{local-mcp-XB6E3V2W.js → local-mcp-ELFJBJG6.js} +1 -1
- package/dist/_chunks/main-XWUYQQ32.js +2 -0
- package/dist/_chunks/mcp-ACNG635V.js +1 -0
- package/dist/_chunks/oauth-QBJ62PIA.js +1 -0
- package/dist/_chunks/observe-entry-3CHBX74Y.js +1 -0
- package/dist/_chunks/remote-client-WIZVKP3O.js +1 -0
- package/dist/_chunks/{render-main-VTM6WGFP.js → render-main-ZXYQ7EV5.js} +1 -1
- package/dist/_chunks/{source-import-KKV2UWJO.js → source-import-ZWR26CMU.js} +1 -1
- package/dist/_chunks/src-TR4JNPGI.js +1 -0
- package/dist/_chunks/{stdio-main-Y7N4NVKU.js → stdio-main-QQLYSRD4.js} +1 -1
- package/dist/_chunks/workspace-main-NYDAQGB4.js +1 -0
- package/dist/_types/cli/local/desktop-contract.d.ts +14 -14
- package/dist/_types/cli/local/desktop-device-contract.d.ts +5 -5
- package/dist/_types/cli/local/desktop-device-owner.d.ts +2 -2
- package/dist/_types/cli/local/desktop-device-state.d.ts +2 -2
- package/dist/_types/cli/local/desktop-library.d.ts +1 -1
- package/dist/_types/cli/local/desktop-owner.d.ts +4 -4
- package/dist/_types/cli/local/manager.d.ts +2 -2
- package/dist/_types/cli/local/mcp-tools.d.ts +2 -2
- package/dist/_types/cli/local-management.d.ts +1 -1
- package/dist/_types/contracts/agent-execution-lifecycle.d.ts +55 -43
- package/dist/_types/contracts/agent-execution-oauth.d.ts +2 -2
- package/dist/_types/contracts/agent-execution-registration.d.ts +59 -15
- package/dist/_types/contracts/agent-execution-selection.d.ts +7 -7
- package/dist/_types/contracts/agent-host-contract.d.ts +189 -0
- package/dist/_types/contracts/agent-host-execution.d.ts +92 -61
- package/dist/_types/contracts/agent-host-generic-transport.d.ts +4 -4
- package/dist/_types/contracts/agent-host-legacy-release.d.ts +31 -0
- package/dist/_types/contracts/agent-host-protocol.d.ts +71 -0
- package/dist/_types/contracts/agent-host-wire.d.ts +263 -0
- package/dist/_types/contracts/agent-host.d.ts +126 -65
- package/dist/_types/contracts/artifact-discovery.d.ts +16 -16
- package/dist/_types/contracts/composition-observation.d.ts +1 -1
- package/dist/_types/contracts/delivery-operations.d.ts +1 -1
- package/dist/_types/contracts/delivery-summary.d.ts +1 -1
- package/dist/_types/contracts/device-onboarding.d.ts +29 -0
- package/dist/_types/contracts/device-render.d.ts +26 -0
- package/dist/_types/contracts/exploration-recommendation.d.ts +2 -2
- package/dist/_types/contracts/federation-result.d.ts +239 -0
- package/dist/_types/contracts/final-ready.d.ts +2 -2
- package/dist/_types/contracts/final-render.d.ts +2 -2
- package/dist/_types/contracts/index.d.ts +6 -0
- package/dist/_types/contracts/interface/execution-output.d.ts +9 -6
- package/dist/_types/contracts/interface/production-snapshot.d.ts +5 -5
- package/dist/_types/contracts/keyframe-generation.d.ts +2 -2
- package/dist/_types/contracts/keyframe-review.d.ts +1 -1
- package/dist/_types/contracts/lifecycle-event-projections.d.ts +17 -2
- package/dist/_types/contracts/lifecycle-events.d.ts +54 -2
- package/dist/_types/contracts/local-execution/device-inventory.d.ts +28 -2
- package/dist/_types/contracts/local-execution/index.d.ts +1 -0
- package/dist/_types/contracts/local-execution/ipc.d.ts +6 -6
- package/dist/_types/contracts/local-execution/library.d.ts +2 -2
- package/dist/_types/contracts/local-execution/processor.d.ts +7 -7
- package/dist/_types/contracts/local-execution/workspace.d.ts +1 -1
- package/dist/_types/contracts/media-observation.d.ts +3 -3
- package/dist/_types/contracts/native-tool-authority.d.ts +25 -21
- package/dist/_types/contracts/native-tool-execution.d.ts +60 -39
- package/dist/_types/contracts/navigation-context.d.ts +4 -4
- package/dist/_types/contracts/navigation-groups.d.ts +1 -1
- package/dist/_types/contracts/navigation.d.ts +5 -5
- package/dist/_types/contracts/production-feedback.d.ts +452 -0
- package/dist/_types/contracts/repair-strategy.d.ts +1 -1
- package/dist/_types/contracts/review-intelligence-final-output.d.ts +1 -1
- package/dist/_types/contracts/rough-cut.d.ts +1 -1
- package/dist/_types/contracts/shares.d.ts +135 -0
- package/dist/_types/contracts/speech.d.ts +5 -5
- package/dist/_types/contracts/temporal-evidence-operation.d.ts +1 -1
- package/dist/_types/contracts/video-generation.d.ts +2 -2
- package/dist/_types/contracts/video-review.d.ts +1 -1
- package/dist/_types/contracts/visual-exploration.d.ts +2 -2
- package/dist/_types/contracts/voice-profile/contracts.d.ts +4 -4
- package/dist/_types/contracts/workspace.d.ts +21 -0
- package/dist/_types/sdk/local-runtime/workspace.d.ts +4 -4
- package/dist/_types/sdk/local-runtime-client.d.ts +3 -3
- package/dist/entry.js +1 -1
- package/dist/local-management.js +1 -1
- package/dist/local-navigation.js +1 -1
- package/dist/native/helper.exe +0 -0
- package/dist/native/helper.json +1 -0
- package/package.json +1 -1
- package/dist/_chunks/chunk-2AI3WF2O.js +0 -1
- package/dist/_chunks/chunk-5DY7LSZZ.js +0 -1
- package/dist/_chunks/chunk-6LU6GJKW.js +0 -1
- package/dist/_chunks/chunk-77IAHNM2.js +0 -1
- package/dist/_chunks/chunk-FU3524Z6.js +0 -1
- package/dist/_chunks/chunk-HY7NXJYX.js +0 -1
- package/dist/_chunks/chunk-KB2GVAN7.js +0 -1
- package/dist/_chunks/chunk-PDQYFIQQ.js +0 -1
- package/dist/_chunks/chunk-PUNG4ND7.js +0 -1
- package/dist/_chunks/chunk-RK2P3UVF.js +0 -1
- package/dist/_chunks/chunk-SV3NF7GO.js +0 -1
- package/dist/_chunks/chunk-TLPI6P7L.js +0 -1
- package/dist/_chunks/chunk-U7ECMITP.js +0 -1
- package/dist/_chunks/chunk-ZRSYOFMX.js +0 -1
- package/dist/_chunks/device-preflight-LHFLPVAB.js +0 -1
- package/dist/_chunks/http-profile-NIQDCFPU.js +0 -1
- package/dist/_chunks/local-main-227MNGEC.js +0 -1
- package/dist/_chunks/main-W6NNZFLK.js +0 -2
- package/dist/_chunks/mcp-EXQ5UAHB.js +0 -1
- package/dist/_chunks/oauth-HC6TI7HB.js +0 -1
- package/dist/_chunks/src-OIY5TBQT.js +0 -1
- package/dist/_chunks/workspace-main-Y7ZVBRJJ.js +0 -1
- package/dist/native/Bootstrap.ps1 +0 -90
- package/dist/native/JobNative.cs +0 -137
- package/dist/native/JobRunner.cs +0 -381
- package/dist/native/NativeMain.cs +0 -161
- package/dist/native/PipeBridge.cs +0 -260
- package/dist/native/PrivateAccess.cs +0 -152
|
@@ -1 +0,0 @@
|
|
|
1
|
-
function secureEndpoint(endpoint){const url=new URL(endpoint);if(url.username||url.password||url.search||url.hash||!(url.protocol==="https:"||url.protocol==="http:"&&["127.0.0.1","localhost","[::1]"].includes(url.hostname)))throw Error();return url}var remoteResponse=(input,init)=>fetch(input,{...init,redirect:"error",signal:init?.signal?AbortSignal.any([init.signal,AbortSignal.timeout(3e4)]):AbortSignal.timeout(3e4)});var remoteFetch=async(input,init)=>{const response=await remoteResponse(input,init);if(!response.body)return response;const reader=response.body.getReader(),chunks=[];let size=0;try{while(true){const part=await reader.read();if(part.done)break;size+=part.value.byteLength;if(size>32*1024*1024){await reader.cancel();throw Error()}chunks.push(part.value)}}finally{reader.releaseLock()}return new Response(Buffer.concat(chunks),{status:response.status,headers:response.headers})};export{secureEndpoint,remoteResponse,remoteFetch};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{probeLocalLibrary,probeTenantQwenGeneration,probeTenantSpeech,probeTenantTranscription}from"./chunk-ZRSYOFMX.js";import{directory,fail,read,write}from"./chunk-KB2GVAN7.js";import{LocalDeviceTransportConfigurationSchema,LocalToolSelectionSchema,canonicalLocalJson}from"./chunk-PDQYFIQQ.js";import{generateKeyPairSync}from"node:crypto";import{dirname,join,sep}from"node:path";import{z}from"zod";async function generateDeviceKey(output){await directory(dirname(output));const key=generateKeyPairSync("ec",{namedCurve:"prime256v1"});await write(output,JSON.stringify(key.privateKey.export({format:"jwk"})),true);return{publicKey:key.publicKey.export({format:"jwk"}),privateKeyFile:output}}async function connectDevice(manager,raw){const schema=LocalDeviceTransportConfigurationSchema.safeExtend({compositionBrowser:z.never().optional(),macSpeechIdentity:z.never().optional(),whisperIdentity:z.never().optional(),whisperTools:z.never().optional(),qwenIdentities:z.never().optional(),tools:LocalToolSelectionSchema.optional()});const input=schema.parse(raw),c=await manager.configuration();await read(input.privateKeyFile,16384);const active=(await manager.ledger.current()).value.active;if(input.processorCapabilities?.some(kind=>kind==="LOCAL_MEDIA_INSPECT"||kind==="LOCAL_MEDIA_PUBLISH")&&(!active||!await probeLocalLibrary(manager.ledger.slotPath(active),active)))fail("LOCAL_PROFILE_UNAVAILABLE");if(input.processorCapabilities?.includes("SPEECH_SYNTHESIZE")&&(!active||!await probeTenantSpeech(manager.ledger.slotPath(active),active)))fail("LOCAL_PROFILE_UNAVAILABLE");if(input.processorCapabilities?.includes("TRANSCRIBE_AUDIO")&&(!active||!await probeTenantTranscription(manager.ledger.slotPath(active),active)))fail("LOCAL_PROFILE_UNAVAILABLE");const qwenProcessors=[["KEYFRAME_GENERATE","keyframe"],["VIDEO_GENERATE","video"],["SPEECH_EXTERNAL_QWEN","speech"],["TRANSCRIBE_EXTERNAL_QWEN","asr"]];const selectedQwen=qwenProcessors.filter(([processor])=>input.processorCapabilities?.includes(processor));if(selectedQwen.some(([,kind])=>kind!=="speech")!==Boolean(input.qwenDeviceCredentials?.length))fail("LOCAL_PROFILE_UNAVAILABLE");for(const[,kind]of selectedQwen){if(!active||!await probeTenantQwenGeneration(manager.ledger.slotPath(active),active,kind))fail("LOCAL_PROFILE_UNAVAILABLE")}for(const credential of input.qwenDeviceCredentials??[]){if(credential.tenantId!==input.tenantId)fail("LOCAL_PROFILE_UNAVAILABLE");(await read(credential.privateKeyFile,4096)).fill(0)}const actual=active?.toolsConfigPath?LocalToolSelectionSchema.parse(JSON.parse((await read(active.toolsConfigPath,32768)).toString())):c.cloudConfigFile?LocalToolSelectionSchema.parse(JSON.parse((await read(c.cloudConfigFile,32768)).toString()).tools):null;if(input.tools&&active&&(!actual||canonicalLocalJson(input.tools)!==canonicalLocalJson(actual)))fail("TOOL_SELECTION_PLAN_REQUIRED");let tools=input.tools;if(!tools){const selected=(await manager.ledger.current()).value.active?.toolsConfigPath;if(!selected)fail("MANAGED_TOOLS_REQUIRED");tools=LocalToolSelectionSchema.parse(JSON.parse((await read(selected,32768)).toString()))}if(tools.mode==="MANAGED"&&!tools.ffmpeg.path.startsWith(join(c.stateDirectory,"tools")+sep))fail("MANAGED_TOOLS_REQUIRED");const file=join(c.stateDirectory,"cloud-device.json");const cloudTools=active?{mode:tools.mode,ffmpeg:tools.ffmpeg,ffprobe:tools.ffprobe}:tools;await write(file,canonicalLocalJson({...input,tools:cloudTools}));await manager.configure({...c,cloudConfigFile:file});return{connected:true,deviceId:input.deviceId,tenantId:input.tenantId,nextActions:[{surface:"CLI",operation:"local.stop",availability:"AVAILABLE",reason:"READY"},{surface:"CLI",operation:"local.start",availability:"AVAILABLE",reason:"READY"}]}}export{generateDeviceKey,connectDevice};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{FileOAuthProvider,withProfileLock}from"./chunk-FU3524Z6.js";import{directory,optional,privateDirectory,write}from"./chunk-KB2GVAN7.js";import{CliAccountExchangeSchema,CliAccountIdentitySchema,CliAccountSessionSchema,CliAccountStartSchema,CliAccountStartedSchema,ProjectLibraryPageSchema,ProjectWorkspaceSchema}from"./chunk-TLPI6P7L.js";import{secureEndpoint}from"./chunk-PUNG4ND7.js";import{NativeStudioSdkError}from"./chunk-HTUTYIRU.js";import{join}from"node:path";import{z as z2}from"zod";import{z}from"zod";function accountServerOrigin(value){const url=new URL(value);if(url.pathname!=="/"||url.search||url.hash||url.username||url.password||!(url.protocol==="https:"||url.protocol==="http:"&&["127.0.0.1","localhost","[::1]"].includes(url.hostname)))throw new NativeStudioSdkError("ACCOUNT_SERVER_ORIGIN_REQUIRED","INVALID_INPUT","NO_WRITE");return url.origin}var NativeStudioAccountClient=class{constructor(options){this.options=options;this.serverOrigin=accountServerOrigin(options.serverOrigin);if(options.accessToken&&!/^nvsh_[A-Za-z0-9_-]{43}$/.test(options.accessToken))throw new NativeStudioSdkError("INVALID_ACCOUNT_CREDENTIAL","INVALID_INPUT","NO_WRITE")}options;serverOrigin;async request(action,schema,options={}){if(options.credential&&!this.options.accessToken)throw new NativeStudioSdkError("ACCOUNT_LOGIN_REQUIRED","INVALID_INPUT","NO_WRITE");const write2=options.body!==void 0;let response;try{response=await(this.options.fetch??fetch)(`${this.serverOrigin}/api/cli-account/${action}${options.query?"?"+options.query:""}`,{method:write2?"POST":"GET",cache:"no-store",redirect:"error",credentials:"omit",signal:AbortSignal.any([AbortSignal.timeout(15e3),...options.signal?[options.signal]:[]]),headers:{...write2?{"content-type":"application/json"}:{},...options.credential?{authorization:"Bearer "+this.options.accessToken}:{}},...write2?{body:JSON.stringify(options.body)}:{}})}catch{throw new NativeStudioSdkError("ACCOUNT_TRANSPORT_FAILED","BLOCKED",write2?"UNKNOWN":"NO_WRITE")}if(!response.ok){await response.body?.cancel();throw new NativeStudioSdkError(response.status===401?"ACCOUNT_SESSION_EXPIRED_OR_REVOKED":"ACCOUNT_REQUEST_REJECTED","BLOCKED",write2&&response.status>=500?"UNKNOWN":"REJECTED",response.status)}try{if(!(response.headers.get("content-type")??"").startsWith("application/json"))throw Error();const reader=response.body?.getReader();if(!reader)throw Error();const chunks=[];let size=0;try{while(true){const part=await reader.read();if(part.done)break;size+=part.value.byteLength;if(size>1024*1024){await reader.cancel();throw Error()}chunks.push(part.value)}}finally{reader.releaseLock()}const bytes=new Uint8Array(size);let offset=0;for(const part of chunks){bytes.set(part,offset);offset+=part.length}return schema.parse(JSON.parse(new TextDecoder().decode(bytes)))}catch{throw new NativeStudioSdkError("ACCOUNT_RESPONSE_INVALID","BLOCKED",write2?"UNKNOWN":"NO_WRITE")}}async metadata(signal){return this.request("metadata",z.strictObject({protocol:z.literal("NVS_CLI_ACCOUNT_V1"),serverOrigin:z.literal(this.serverOrigin)}),{signal})}start(input,signal){return this.request("start",CliAccountStartedSchema,{body:CliAccountStartSchema.parse(input),signal})}exchange(input,signal){return this.request("exchange",CliAccountSessionSchema,{body:CliAccountExchangeSchema.parse(input),signal})}me(signal){return this.request("me",CliAccountIdentitySchema,{credential:true,signal})}logout(signal){return this.request("logout",z.strictObject({changed:z.literal(true)}),{credential:true,body:{},signal})}async projects(input,signal){const value=z.strictObject({tenantId:z.uuid(),limit:z.number().int().min(1).max(100).optional(),next:z.string().min(1).max(8192).optional()}).parse(input);const result=await this.request("projects",ProjectLibraryPageSchema,{credential:true,signal,query:new URLSearchParams({tenantId:value.tenantId,...value.limit?{limit:String(value.limit)}:{},...value.next?{next:value.next}:{}})});if(result.items.some(p=>p.tenantId!==value.tenantId))throw new NativeStudioSdkError("ACCOUNT_RESPONSE_SCOPE_MISMATCH","BLOCKED","NO_WRITE");return result}async project(input,signal){const value=z.strictObject({tenantId:z.uuid(),projectId:z.uuid()}).parse(input);const result=await this.request("project",ProjectWorkspaceSchema,{credential:true,signal,query:new URLSearchParams(value)});if(result.project.id!==value.projectId||result.project.tenantId!==value.tenantId)throw new NativeStudioSdkError("ACCOUNT_RESPONSE_SCOPE_MISMATCH","BLOCKED","NO_WRITE");return result}};var AccountStateSchema=z2.strictObject({version:z2.literal(1),epoch:z2.uuid(),serverOrigin:z2.string().refine(v=>{try{return accountServerOrigin(v)===v}catch{return false}}),principalId:z2.uuid(),expiresAt:z2.iso.datetime(),workspaceId:z2.uuid().nullable(),projectId:z2.uuid().nullable(),state:z2.enum(["ACTIVE","REVOKE_PENDING","SIGNED_OUT"]),accessToken:z2.string().regex(/^nvsh_[A-Za-z0-9_-]{43}$/).nullable()}).refine(v=>v.state==="SIGNED_OUT"===(v.accessToken===null)&&(!v.projectId||Boolean(v.workspaceId)));function accountError(code,outcome="NO_WRITE"){throw new NativeStudioSdkError(code,outcome==="UNKNOWN"?"INTERNAL_OPERATIONAL_FAILURE":["ACCOUNT_LOGIN_INPUT_INVALID","ACCOUNT_COMMAND_INPUT_INVALID"].includes(code)?"INVALID_INPUT":"BLOCKED",outcome)}async function readAccount(root){const value=await optional(join(root,"account.json"));if(value===null)return null;const parsed=AccountStateSchema.safeParse(value);if(!parsed.success)accountError("ACCOUNT_STATE_INVALID");return parsed.data}async function saveAccount(root,value){const account=AccountStateSchema.parse(value);await write(join(root,"account.json"),JSON.stringify(account))}async function withAccountLock(root,action){try{return await withProfileLock(join(root,"account.json"),action)}catch(error){if(error.code==="EEXIST")accountError("ACCOUNT_COMMAND_BUSY");throw error}}function requireAccount(value){if(!value)accountError("ACCOUNT_LOGIN_REQUIRED");if(value.state==="REVOKE_PENDING")accountError("ACCOUNT_LOGOUT_OUTCOME_UNKNOWN","UNKNOWN");if(value.state!=="ACTIVE"||Date.parse(value.expiresAt)<=Date.now())accountError("ACCOUNT_LOGIN_REQUIRED");return value}import{homedir}from"node:os";import{isAbsolute,join as join2}from"node:path";import{realpath}from"node:fs/promises";function connectionError(code){throw new NativeStudioSdkError(code,"INVALID_INPUT","NO_WRITE")}async function clientHome(environment,create=false){const path=environment.NATIVESTUDIO_CLIENT_HOME??join2(homedir(),".nativestudio","client");if(!isAbsolute(path))connectionError("CLIENT_HOME_ABSOLUTE_REQUIRED");if(create)return directory(path);await privateDirectory(path);const root=await realpath(path);if(/(?:^|[\\/])(?:node_modules|_npx)(?:[\\/]|$)/.test(root))connectionError("CLIENT_HOME_PRIVATE_REQUIRED");return root}import{join as join3}from"node:path";var uuid="[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}";var tenantPath=new RegExp(`^/mcp/external/v1/tenants/(${uuid})$`,"i");function tenantConnection(resource){const url=secureEndpoint(resource),match=tenantPath.exec(url.pathname);if(!match)connectionError("TENANT_MCP_URL_REQUIRED");return{resource:url.href,tenantId:match[1].toLowerCase()}}async function saveConnection(root,profile,expectedEpoch){return withAccountLock(root,()=>saveConnectionLocked(root,profile,expectedEpoch))}async function saveConnectionLocked(root,profile,expectedEpoch){if(!/^profile-[0-9a-f-]{36}\.json$/.test(profile))throw Error();const provider=await FileOAuthProvider.load(join3(root,profile));const scope=tenantConnection(provider.data.resource);if(!provider.data.token?.access_token||provider.data.pendingExchange)throw Error();const account=await readAccount(root);if(account?.epoch!==expectedEpoch)connectionError("ACCOUNT_CHANGED_DURING_CONNECTION");if(account&&(account.state!=="ACTIVE"||account.workspaceId!==scope.tenantId))connectionError("ACCOUNT_WORKSPACE_SELECTION_REQUIRED");await write(join3(root,"connection.json"),JSON.stringify({version:3,profile,...scope,...account?{accountEpoch:account.epoch}:{}}));return{scope:provider.data.token.scope??provider.data.scope,expiresAt:provider.data.expiresAt}}async function loadConnection(environment){let root;try{root=await clientHome(environment)}catch(e){if(e.code==="ENOENT")return null;throw e}const value=await optional(join3(root,"connection.json"));if(value===null)return null;if(value.version!==3||typeof value.profile!=="string"||!/^profile-[0-9a-f-]{36}\.json$/.test(value.profile)||typeof value.resource!=="string")connectionError("CONNECTION_INVALID");const scope=tenantConnection(value.resource);if(scope.tenantId!==value.tenantId||value.projectId!==void 0)connectionError("CONNECTION_SCOPE_MISMATCH");const account=await readAccount(root);if(value.accountEpoch!==void 0&&(!account||typeof value.accountEpoch!=="string"))connectionError("CONNECTION_ACCOUNT_MISMATCH");if(account&&(account.state!=="ACTIVE"||value.accountEpoch!==account.epoch||scope.tenantId!==account.workspaceId))connectionError("CONNECTION_ACCOUNT_MISMATCH");const profile=join3(root,value.profile),provider=await FileOAuthProvider.load(profile);if(provider.data.resource!==scope.resource||!provider.data.token?.access_token)connectionError("CONNECTION_PROFILE_MISMATCH");return{...scope,profile,scope:provider.data.token.scope??provider.data.scope,requestedScope:provider.data.scope,expiresAt:provider.data.expiresAt,exchangeUnresolved:Boolean(provider.data.pendingExchange)}}var authentication=["--profile","--origin","--mcp-url","--token-env","--token-file"];async function defaultConnection(options,environment,tenant){if(authentication.some(key=>options.has(key)))return;const connection=await loadConnection(environment);if(!connection)connectionError("TENANT_CONNECTION_REQUIRED");if(options.has("--tenant")&&options.get("--tenant")!==connection.tenantId)connectionError("CONNECTION_SCOPE_MISMATCH");options.set("--profile",connection.profile);if(tenant)options.set("--tenant",connection.tenantId)}async function connectionStatus(environment){const value=await loadConnection(environment);return{exitCode:0,output:value?{semanticStatus:"SUCCESS",connected:true,credentialPurpose:"TENANT_MCP",accountSessionVerified:false,verification:"LOCAL_METADATA_ONLY",resource:value.resource,tenantId:value.tenantId,scope:value.scope,requestedScope:value.requestedScope,expiresAt:value.expiresAt,credentialState:value.exchangeUnresolved?"EXCHANGE_UNRESOLVED":typeof value.expiresAt==="number"&&value.expiresAt>Date.now()+3e4?"CACHED":"REFRESH_REQUIRED",nextSteps:value.exchangeUnresolved?["Wait for the active authorization command. If it returned OAUTH_OUTCOME_UNKNOWN, run nvs connect --mcp-url <workspace-connection-url>."]:["nvs find --query <intent>","nvs capabilities","nvs mcp"]}:{semanticStatus:"NEEDS_INPUT",connected:false,credentialPurpose:"TENANT_MCP",accountSessionVerified:false,nextSteps:["Open Agent access in the workspace settings, then authorize the workspace once.","nvs connect --mcp-url <workspace-connection-url>"]}}}export{accountServerOrigin,NativeStudioAccountClient,accountError,readAccount,saveAccount,withAccountLock,requireAccount,connectionError,clientHome,tenantConnection,saveConnection,loadConnection,defaultConnection,connectionStatus};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{ContinuationSchema,DeliveryOutputProfileSchema,HumanLinksSchema,PrincipalIdSchema,ProductionIdSchema,ProjectIdSchema,QueryLimitSchema,QueryPageInfoSchema,TenantIdSchema}from"./chunk-6UYY5KHI.js";import{z}from"zod";var HumanEmailSchema=z.string().trim().max(254).toLowerCase().pipe(z.email()).refine(v=>/^[\x21-\x7e]+$/.test(v),"Use an ASCII email address");var HumanPasswordSchema=z.string().max(512).superRefine((v,c)=>{const points=[...v];const control=points.some(c2=>c2.codePointAt(0)<32||c2.codePointAt(0)===127);if(points.length<15||points.length>128||control)c.addIssue({code:"custom",message:"Password must contain 15\u2013128 characters"})});var HumanCodePurposeSchema=z.enum(["REGISTER","RESET_PASSWORD","LINK_EMAIL"]);var HumanCodeRequestSchema=z.strictObject({email:HumanEmailSchema,purpose:HumanCodePurposeSchema});var HumanCodeRequestedSchema=z.strictObject({accepted:z.literal(true),challengeId:z.uuid(),retryAfterSeconds:z.literal(60),expiresInSeconds:z.literal(600)});var proof={challengeId:z.uuid(),email:HumanEmailSchema,code:z.string().regex(/^\d{6}$/),password:HumanPasswordSchema};var HumanRegisterSchema=z.strictObject({...proof,displayName:z.string().trim().min(1).max(80)});var HumanResetSchema=z.strictObject(proof);var HumanLoginSchema=z.strictObject({email:HumanEmailSchema,password:z.string().max(512),rememberMe:z.boolean().optional()});var HumanTenantSchema=z.strictObject({id:z.uuid(),displayName:z.string().max(200)});var HumanAccountSchema=z.strictObject({principalId:z.uuid(),displayName:z.string().max(200),email:HumanEmailSchema.nullable(),tenants:z.array(HumanTenantSchema).max(100)});var HumanDesktopSessionSchema=z.strictObject({tenantId:z.uuid(),scopeKey:z.string().regex(/^[a-f0-9]{64}$/),expiresAt:z.int().positive(),sessionExpiresAt:z.int().positive().optional(),rememberMe:z.boolean(),account:HumanAccountSchema.omit({tenants:true})}).refine(({rememberMe,expiresAt,sessionExpiresAt})=>sessionExpiresAt===void 0||rememberMe&&sessionExpiresAt>=expiresAt,"Desktop persistence requires consent and the session deadline");var ShortHumanSessionSchema=z.strictObject({accessToken:z.string().regex(/^nvsh_[A-Za-z0-9_-]{43}$/),expiresAt:z.iso.datetime(),account:HumanAccountSchema});var HumanRefreshTokenSchema=z.string().regex(/^nvshr_[A-Za-z0-9_-]{43}$/);var HumanRefreshSchema=z.strictObject({refreshToken:HumanRefreshTokenSchema});var HumanSessionSchema=ShortHumanSessionSchema.extend({refreshToken:HumanRefreshTokenSchema.optional(),sessionId:z.uuid().optional(),sessionExpiresAt:z.iso.datetime().optional()}).refine(session=>{const{refreshToken,sessionId,sessionExpiresAt,expiresAt}=session;if(!refreshToken)return sessionId===void 0&&sessionExpiresAt===void 0;return!!sessionId&&!!sessionExpiresAt&&Date.parse(expiresAt)<=Date.parse(sessionExpiresAt)},"Persistent session requires its exact identity and absolute expiry");var HumanIdentityAvailabilitySchema=z.strictObject({passwordLogin:z.boolean(),emailVerification:z.boolean()});var HumanIdentityFailureSchema=z.strictObject({code:z.enum(["INVALID_INPUT","INVALID_CREDENTIALS","INVALID_CODE","RATE_LIMITED","MAIL_UNAVAILABLE","UNAVAILABLE","UNAUTHENTICATED","CONFLICT"])});var CliAccountRedirectSchema=z.string().max(256).refine(value=>{try{const url=new URL(value);return url.protocol==="http:"&&url.hostname==="127.0.0.1"&&Number(url.port)>0&&!url.username&&!url.password&&!url.search&&!url.hash&&/^\/account-callback\/[a-f0-9-]{36}$/.test(url.pathname)&&url.href===value}catch{return false}},"Owned loopback account callback required");var proofKey=z.string().regex(/^[A-Za-z0-9_-]{43}$/);var CliAccountRequestIdSchema=z.uuid();var CliAccountStartSchema=z.strictObject({redirectUri:CliAccountRedirectSchema,state:proofKey,codeChallenge:proofKey});var CliAccountStartedSchema=z.strictObject({requestId:z.uuid(),expiresAt:z.iso.datetime()});var CliAccountPreviewSchema=CliAccountStartedSchema.extend({redirectUri:CliAccountRedirectSchema});var CliAccountDecisionSchema=z.strictObject({requestId:z.uuid(),approved:z.boolean(),expectedPrincipalId:z.uuid()});var CliAccountExchangeSchema=z.strictObject({requestId:z.uuid(),code:proofKey,codeVerifier:proofKey,redirectUri:CliAccountRedirectSchema});var CliAccountSessionSchema=ShortHumanSessionSchema.extend({credentialPurpose:z.literal("CLI_ACCOUNT")});var CliAccountIdentitySchema=z.strictObject({credentialPurpose:z.literal("CLI_ACCOUNT"),account:HumanAccountSchema});import{z as z2}from"zod";var ProductionLifecycleSchema=z2.enum(["ACTIVE","COMPLETED","FAILED","CANCELLED"]);var ProductionPhaseSchema=z2.enum(["INTAKE","PLANNING","PREPARING_GENERATION","GENERATING","SHOT_REVIEW","ASSEMBLING","ROUGH_CUT_REVIEW","FINAL_READY","FINAL_RENDERING","DELIVERY_VALIDATION"]);var ProductionConditionSchema=z2.enum(["RUNNABLE","RUNNING","WAITING_PROVIDER","WAITING_HUMAN","BLOCKED","RETRYING"]);var CreateProductionInputSchema=z2.object({tenantId:TenantIdSchema,projectId:ProjectIdSchema,principalId:PrincipalIdSchema});var ProductionStateSchema=z2.object({lifecycle:ProductionLifecycleSchema,phase:ProductionPhaseSchema,condition:ProductionConditionSchema,revision:z2.int().positive(),blockingReason:z2.string().min(1).nullable(),waitingReason:z2.string().min(1).nullable()});var ProductionSchema=z2.object({humanLinks:HumanLinksSchema.optional(),id:ProductionIdSchema,tenantId:TenantIdSchema,projectId:ProjectIdSchema,state:ProductionStateSchema,activeBriefVersion:z2.int().positive().nullable().default(null),activeStoryVersion:z2.int().positive().nullable().default(null),activeSceneShotPlanVersion:z2.int().positive().nullable().default(null),createdByPrincipalId:PrincipalIdSchema,createdAt:z2.iso.datetime({offset:true}),updatedAt:z2.iso.datetime({offset:true})});import{z as z3}from"zod";var ProjectLifecycleSchema=z3.enum(["ACTIVE","ARCHIVED"]);var CreateProjectInputSchema=z3.object({tenantId:TenantIdSchema,principalId:PrincipalIdSchema,idempotencyKey:z3.string().trim().min(1).max(200),name:z3.string().trim().min(1).max(200)});var CreateProjectRequestSchema=CreateProjectInputSchema.omit({principalId:true}).strict();var ProjectSchema=z3.object({id:ProjectIdSchema,tenantId:TenantIdSchema,name:z3.string().min(1),lifecycle:ProjectLifecycleSchema,defaultActiveProductionId:ProductionIdSchema.nullable(),revision:z3.int().positive(),createdByPrincipalId:PrincipalIdSchema,createdAt:z3.iso.datetime({offset:true}),updatedAt:z3.iso.datetime({offset:true})});var CreatedProjectResultSchema=z3.object({project:ProjectSchema,production:ProductionSchema});import{z as z4}from"zod";var ProjectLibraryQuerySchema=z4.strictObject({tenantId:TenantIdSchema,limit:QueryLimitSchema,next:ContinuationSchema.optional()});var ProjectLibraryScopeSchema=z4.strictObject({tenantId:TenantIdSchema,projectId:ProjectIdSchema});var ProjectLibraryPageSchema=z4.strictObject({items:z4.array(ProjectSchema).max(100),page:QueryPageInfoSchema});var ProjectWorkspaceSchema=z4.strictObject({project:ProjectSchema,productions:z4.array(ProductionSchema).max(100),possiblyTruncated:z4.boolean()});var SourceLibraryQuerySchema=ProjectLibraryQuerySchema.extend({projectId:ProjectIdSchema.optional()});var SourceLibraryItemSchema=z4.strictObject({artifactId:z4.uuid(),representationId:z4.uuid(),projectId:ProjectIdSchema,kind:z4.enum(["REFERENCE_IMAGE","REFERENCE_VIDEO","PRODUCT_INFORMATION"]),originalName:z4.string().max(255),checksumSha256:z4.string().regex(/^[0-9a-f]{64}$/),contentType:z4.enum(["image/png","image/jpeg","image/webp","text/plain","application/json","video/mp4"]),byteSize:z4.int().positive().max(8388608),width:z4.int().positive().nullable(),height:z4.int().positive().nullable(),createdAt:z4.iso.datetime({offset:true})});var SourceLibraryPageSchema=z4.strictObject({items:z4.array(SourceLibraryItemSchema).max(100),page:QueryPageInfoSchema});var SourceLibraryMediaSchema=ProjectLibraryScopeSchema.extend({artifactId:z4.uuid()});var StudioInputContentSchema=z4.strictObject({schemaVersion:z4.literal(1),productionId:z4.uuid(),projectTitle:z4.string().trim().min(1).max(200),name:z4.string().trim().max(300),intent:z4.string().trim().min(1).max(2e3),aspectRatio:z4.enum(["16:9","9:16"]),targetDurationSeconds:z4.int().min(30).max(60),outputProfile:DeliveryOutputProfileSchema,sourceArtifactIds:z4.array(z4.uuid()).max(12)});export{HumanTenantSchema,CliAccountStartSchema,CliAccountStartedSchema,CliAccountExchangeSchema,CliAccountSessionSchema,CliAccountIdentitySchema,ProductionStateSchema,ProductionSchema,CreateProjectRequestSchema,ProjectSchema,CreatedProjectResultSchema,ProjectLibraryQuerySchema,ProjectLibraryScopeSchema,ProjectLibraryPageSchema,ProjectWorkspaceSchema,SourceLibraryQuerySchema,SourceLibraryItemSchema,SourceLibraryPageSchema,SourceLibraryMediaSchema,StudioInputContentSchema};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{fail,localSocketPath,privateAccess,privateDirectory,read,sha256,sha512}from"./chunk-KB2GVAN7.js";import{EnrollLocalDeviceSchema,LocalAgentDiscoverySchema,LocalAgentGrantSchema,LocalAgentProbeSchema,LocalAgentReviewViewSchema,LocalAgentSnapshotSchema,LocalDeviceManagementCommandSchema,LocalDeviceViewSchema,LocalDiagnosticsSchema,LocalDoctorReportSchema,LocalExecutionInspectInputSchema,LocalExecutionInspectionSchema,LocalExecutionListInputSchema,LocalExecutionPageSchema,LocalFinalRenderAdmissionSchema,LocalIpcRequestSchema,LocalIpcResponseSchema,LocalLibraryCallSchema,LocalLibraryCapabilitySchema,LocalLibraryGetSchema,LocalLibraryImportSchema,LocalLibraryItemSchema,LocalLibraryPageSchema,LocalLibraryProjectionPageSchema,LocalLibraryProjectionSchema,LocalLibraryReadReplySchema,LocalLibraryUsageSchema,LocalManagementInventorySchema,LocalManagementReceiptSchema,LocalOfflineCallSchema,LocalOfflinePageSchema,LocalPreviewAdmissionSchema,LocalResourcePolicySchema,LocalRuntimeStatusSchema,LocalSessionConnectorSchema,LocalSignedCatalogueSchema,LocalWorkspaceInspectionSchema,RevokeLocalDeviceSchema,StartLocalFinalRenderSchema,StartLocalPreviewSchema,assertManagementReceipt,canonicalLocalJson,checkedManagementReceipt,mediaCategoryOf}from"./chunk-PDQYFIQQ.js";import{NativeStudioSdkError}from"./chunk-HTUTYIRU.js";import{z}from"zod";function localBudget(timeoutMs,parent,ceiling=6e4){if(!Number.isInteger(timeoutMs)||timeoutMs<1||timeoutMs>ceiling)throw Error("LOCAL_DEADLINE_INVALID");const controller=new AbortController,timer=setTimeout(()=>controller.abort(),timeoutMs);return{signal:parent?AbortSignal.any([parent,controller.signal]):controller.signal,close:()=>clearTimeout(timer)}}async function localAbortable(work,signal){if(signal.aborted)void work.catch(()=>{});signal.throwIfAborted();return new Promise((resolve,reject)=>{const abort=()=>reject(Error("LOCAL_DEADLINE"));signal.addEventListener("abort",abort,{once:true});work.then(v=>{signal.removeEventListener("abort",abort);resolve(v)},e=>{signal.removeEventListener("abort",abort);reject(e)});if(signal.aborted)abort()})}var NativeStudioLocalDeviceClient=class{constructor(options){this.options=options;const u=new URL(options.baseUrl);if(u.username||u.password||u.search||u.hash||u.pathname!=="/"||u.protocol!=="https:"&&!(u.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(u.hostname)))throw new NativeStudioSdkError("INVALID_INPUT","INVALID_INPUT","NO_WRITE");this.origin=u.origin}options;origin;async command(route,raw,input,output,signal,readOnly=false,validate){let started=false;const budget=localBudget(15e3,signal);try{const i=input.parse(raw);if((i.tenantId??i.input?.tenantId)!==this.options.tenantId)throw Error();budget.signal.throwIfAborted();const authorization=await localAbortable(Promise.resolve().then(()=>this.options.authorization()),budget.signal);if(authorization!==authorization.trim()||!/^Bearer [A-Za-z0-9._~-]{1,8192}$/.test(authorization))throw Error();const body=JSON.stringify(i);if(Buffer.byteLength(body)>65536)throw Error();budget.signal.throwIfAborted();started=true;const r=await fetch(this.origin+"/v1/local-execution/"+route,{method:"POST",headers:{authorization,"content-type":"application/json","x-native-tenant-id":this.options.tenantId},body,redirect:"error",signal:budget.signal});if(!r.ok){await r.body?.cancel();throw new NativeStudioSdkError(r.status===403||r.status===401?"FORBIDDEN":"LOCAL_COMMAND_REFUSED","BLOCKED",readOnly?"NO_WRITE":r.status>=500?"UNKNOWN":"REJECTED",r.status)}const parts=[];let size=0;for await(const b of r.body??[]){size+=b.length;if(size>262144)throw Error();parts.push(b)}const value=output.parse(JSON.parse(Buffer.concat(parts).toString()));validate?.(i,value);if(value&&typeof value==="object"){const result=value,request4=i;for(const key of["tenantId","projectId","deviceId"])if(key in result&&key in request4&&result[key]!==request4[key])throw Error()}return value}catch(e){if(e instanceof NativeStudioSdkError)throw e;throw new NativeStudioSdkError(started?readOnly?"LOCAL_QUERY_UNAVAILABLE":"LOCAL_COMMAND_UNKNOWN":"INVALID_INPUT",started?"BLOCKED":"INVALID_INPUT",started&&!readOnly?"UNKNOWN":"NO_WRITE")}finally{budget.close()}}enroll(input,signal){return this.command("devices/enroll",input,EnrollLocalDeviceSchema,LocalDeviceViewSchema,signal,false,(original,result)=>assertManagementReceipt("device.enroll",original,result))}async managementReceipt(input,signal){const parsedInput=LocalDeviceManagementCommandSchema.safeParse(input);if(!parsedInput.success)throw new NativeStudioSdkError("INVALID_INPUT","INVALID_INPUT","NO_WRITE");const parsed=parsedInput.data;const value=await this.command("management-receipt",input,LocalDeviceManagementCommandSchema,LocalManagementReceiptSchema,signal,true);return checkedManagementReceipt(parsed,value)}revokeDevice(input,signal){return this.command("devices/revoke",input,RevokeLocalDeviceSchema,z.strictObject({semanticStatus:z.literal("SUCCESS")}),signal)}startPreview(input,signal){return this.command("previews",input,StartLocalPreviewSchema,LocalPreviewAdmissionSchema,signal)}startFinal(input,signal){return this.command("final-renders",input,StartLocalFinalRenderSchema,LocalFinalRenderAdmissionSchema,signal)}};import{randomUUID,createHash}from"node:crypto";import{request}from"node:http";import{z as z2}from"zod";import{constants}from"node:fs";import{open,realpath}from"node:fs/promises";async function checkedLocalDirectory(path){await privateDirectory(path);return realpath(path)}async function readLocalCredential(path,maximum=32768){await privateAccess(path,"file");const file=await open(path,constants.O_RDONLY|constants.O_NOFOLLOW);try{const stat=await file.stat();if(!stat.isFile()||stat.nlink!==1||process.platform!=="win32"&&(stat.uid!==process.getuid?.()||stat.mode&63)||stat.size>maximum)throw Error("LOCAL_CREDENTIAL_INVALID");const bytes=Buffer.alloc(Math.min(maximum+1,stat.size+1));let used=0;while(used<bytes.length){const part=await file.read(bytes,used,bytes.length-used,null);if(!part.bytesRead)break;used+=part.bytesRead}if(used>stat.size)throw Error("LOCAL_CREDENTIAL_INVALID");if(used>maximum)throw Error("LOCAL_CREDENTIAL_INVALID");return bytes.subarray(0,used)}finally{await file.close()}}async function stageAgentImage(options,view,input,signal){const budget=localBudget(view.plan.snapshot.evidence?18e4:options.timeoutMs??1e4,signal,view.plan.snapshot.evidence?18e4:6e4);let dispatched=false;try{budget.signal.throwIfAborted();if(input.byteLength>134217728)throw Error();const bytes=Buffer.from(input),snapshot=view.plan.snapshot,id=z2.uuid().parse(view.plan.id),requestId=randomUUID();if(!snapshot.image&&!snapshot.evidence||bytes.length!==(snapshot.evidence??snapshot.image).byteSize||bytes.length>(snapshot.evidence?134217728:8388608)||createHash("sha256").update(bytes).digest("hex")!==snapshot.media.checksumSha256)throw Error();const root=await checkedLocalDirectory(options.stateDirectory),path=localSocketPath(root);await privateAccess(path,"pipe");const auth=await localAbortable(Promise.resolve().then(options.authorization),budget.signal);budget.signal.throwIfAborted();if(!/^Bearer [A-Za-z0-9_-]{43}$/.test(auth))throw Error();const reply=await new Promise((resolve,reject)=>{const req=request({socketPath:path,path:"/ipc/v1/agent-images/"+id,method:"PUT",signal:budget.signal,headers:{authorization:auth,"content-type":snapshot.evidence?"application/octet-stream":"image/png","content-length":bytes.length,"x-nvs-request-id":requestId}},res=>{let size=0;const chunks=[];res.on("error",reject);res.on("aborted",()=>reject(Error()));res.on("data",b=>{size+=b.length;if(size>262144)req.destroy(Error());else chunks.push(b)});res.on("end",()=>{try{resolve(JSON.parse(Buffer.concat(chunks).toString()))}catch{reject(Error())}})});req.on("error",reject);dispatched=true;req.end(bytes)});const response=LocalIpcResponseSchema.parse(reply);if(response.requestId!==requestId&&!(response.requestId===null&&response.semanticStatus!=="SUCCESS"&&["BUSY","FORBIDDEN"].includes(response.error.code)))throw Error();if(response.semanticStatus!=="SUCCESS")throw new NativeStudioSdkError(response.error.code,response.semanticStatus,response.error.code==="INTERNAL_OPERATIONAL_FAILURE"?"UNKNOWN":"REJECTED");const v=LocalAgentReviewViewSchema.parse(response.data),receipt=v.evidenceReceipt??v.imageReceipt;if(v.plan.id!==id||canonicalLocalJson(v.plan)!==canonicalLocalJson(view.plan)||v.revision<view.revision||v.phase!=="PREPARED"||!receipt||receipt.draftId!==id||canonicalLocalJson(receipt.media)!==canonicalLocalJson(snapshot.media)||!snapshot.evidence&&canonicalLocalJson({contentType:v.imageReceipt?.contentType,byteSize:v.imageReceipt?.byteSize,width:v.imageReceipt?.width,height:v.imageReceipt?.height})!==canonicalLocalJson(snapshot.image))throw Error();return v}catch(e){if(e instanceof NativeStudioSdkError)throw e;throw new NativeStudioSdkError("LOCAL_AGENT_IMAGE_TRANSFER_FAILED","BLOCKED",dispatched?"UNKNOWN":"NO_WRITE")}finally{budget.close()}}var NativeStudioLocalWorkspaceClient=class{constructor(client){this.client=client}client;async offline(raw,signal){return LocalOfflinePageSchema.parse(await this.client.call({operation:"offline.workspace",input:LocalOfflineCallSchema.parse(raw)},signal))}async inspect(signal){return LocalWorkspaceInspectionSchema.parse(await this.client.call({operation:"workspace.inspect"},signal))}async configure(raw,expectedRevision,signal){const policy=LocalResourcePolicySchema.parse(raw);return LocalWorkspaceInspectionSchema.parse(await this.client.call({operation:"workspace.configure",policy,expectedRevision},signal))}async observeActivity(idleSeconds,observedAt,signal){return LocalWorkspaceInspectionSchema.parse(await this.client.call({operation:"workspace.activity",idleSeconds,observedAt},signal))}async clean(signal){return LocalWorkspaceInspectionSchema.parse(await this.client.call({operation:"storage.clean"},signal))}async diagnostics(signal){return LocalDiagnosticsSchema.parse(await this.client.call({operation:"diagnostics.read"},signal))}};import{Readable as Readable2}from"node:stream";import{createHash as createHash2}from"node:crypto";import{request as request2}from"node:http";async function libraryTransport(options,input,signal){const budget=localBudget(18e4,signal,18e4);let started=false;try{const root=await checkedLocalDirectory(options.stateDirectory),socketPath=localSocketPath(root);await privateAccess(socketPath,"pipe");const authorization=await localAbortable(Promise.resolve().then(()=>options.authorization()),budget.signal);if(!/^Bearer [A-Za-z0-9_-]{43}$/.test(authorization))throw Error();budget.signal.throwIfAborted();const response=await new Promise((resolve,reject)=>{const req=request2({socketPath,method:input.method,path:input.path,signal:budget.signal,headers:{authorization,...input.headers}},resolve);req.on("error",reject);started=true;if(input.body){input.body.once("error",error=>req.destroy(error));input.body.pipe(req)}else req.end()});return{response,close:()=>{budget.close();response.destroy();input.body?.destroy()}}}catch(error){budget.close();input.body?.destroy();if(error instanceof NativeStudioSdkError)throw error;throw new NativeStudioSdkError("LOCAL_RUNTIME_UNAVAILABLE","BLOCKED",started&&input.method==="PUT"?"UNKNOWN":"NO_WRITE")}}import{Readable}from"node:stream";var libraryRange=/^bytes=(?:[0-9]+-[0-9]*|-[0-9]+)$/;function expectedRange(range,total){if(!range)return{length:total,header:void 0};const match=/^bytes=(\d*)-(\d*)$/.exec(range);if(!match||!total)throw new NativeStudioSdkError("LIBRARY_RANGE_INVALID","INVALID_INPUT","NO_WRITE",416);const start=match[1]?Number(match[1]):Math.max(0,total-Number(match[2]));const end=match[1]&&match[2]?Math.min(total-1,Number(match[2])):total-1;if(!Number.isSafeInteger(start)||!Number.isSafeInteger(end)||start<0||start>=total||end<start)throw new NativeStudioSdkError("LIBRARY_RANGE_INVALID","INVALID_INPUT","NO_WRITE",416);return{length:end-start+1,header:`bytes ${start}-${end}/${total}`}}async function readLibraryMedia(options,raw,input={},signal){const value=LocalLibraryGetSchema.parse(raw),method=input.method??"GET";if(method!=="GET"&&method!=="HEAD")throw new NativeStudioSdkError("INVALID_INPUT","INVALID_INPUT","NO_WRITE");if(input.range!==void 0&&(input.range.length>100||!libraryRange.test(input.range)))throw new NativeStudioSdkError("LIBRARY_RANGE_INVALID","INVALID_INPUT","NO_WRITE",416);const expected=expectedRange(input.range,value.reference.byteSize);const header=Buffer.from(JSON.stringify(value)).toString("base64url");if(header.length>3072)throw new NativeStudioSdkError("INVALID_INPUT","INVALID_INPUT","NO_WRITE");const transfer=await libraryTransport(options,{method,path:"/ipc/v1/library/read",headers:{"x-nvs-library-read":header,...input.range?{range:input.range}:{}}},signal);const{response}=transfer;try{if(response.statusCode===416)throw new NativeStudioSdkError("LIBRARY_RANGE_INVALID","INVALID_INPUT","NO_WRITE",416);const status=response.statusCode,contentLength=Number(response.headers["content-length"]);if(![200,206].includes(status??0)||!Number.isSafeInteger(contentLength)||contentLength<0||contentLength>value.reference.byteSize||response.headers["content-type"]!==value.reference.contentType)throw Error();const contentRange=response.headers["content-range"];if(status===206){if(!input.range||contentRange!==expected.header||contentLength!==expected.length)throw Error()}else if(input.range||contentRange||contentLength!==value.reference.byteSize)throw Error();const stream=Readable.from((async function*(){let size=0;try{for await(const bytes of response){size+=bytes.length;if(size>contentLength||method==="HEAD")throw Error();yield bytes}if(method!=="HEAD"&&size!==contentLength)throw Error()}finally{transfer.close()}})());stream.once("close",transfer.close);return{stream,contentType:value.reference.contentType,byteSize:value.reference.byteSize,contentLength,httpStatus:status,...contentRange?{contentRange:String(contentRange)}:{}}}catch(error){transfer.close();if(error instanceof NativeStudioSdkError)throw error;throw new NativeStudioSdkError("LOCAL_LIBRARY_MEDIA_INVALID","BLOCKED","NO_WRITE")}}var NativeStudioLocalLibraryClient=class{constructor(client){this.client=client}client;async capability(signal){return LocalLibraryCapabilitySchema.parse(await this.client.call({operation:"library.capability"},signal))}async call(raw,signal){const input=LocalLibraryCallSchema.parse(raw),data=await this.client.call({operation:"library.call",input},signal);const schema=input.action==="list"?LocalLibraryPageSchema:input.action==="scoped-list"?LocalLibraryProjectionPageSchema:input.action==="scoped-get"?LocalLibraryProjectionSchema.nullable():input.action==="usage"?LocalLibraryUsageSchema:input.action==="read"?LocalLibraryReadReplySchema:["get","import-receipt"].includes(input.action)?LocalLibraryItemSchema.nullable():LocalLibraryItemSchema;const result=schema.parse(data);if(result&&"items"in result&&"limit"in input&&result.items.length>input.limit)throw new NativeStudioSdkError("LOCAL_SCOPE_INVALID","BLOCKED","NO_WRITE");if((input.action==="list"||input.action==="scoped-list")&&result&&"items"in result){for(const item of result.items){const label=input.action==="list"&&"title"in item?item.title:"metadata"in item?item.metadata?.label:void 0;if(input.mediaCategory&&mediaCategoryOf(item.reference.contentType)!==input.mediaCategory||input.search&&!label?.toLowerCase().includes(input.search.toLowerCase()))throw new NativeStudioSdkError("LOCAL_SCOPE_INVALID","BLOCKED","NO_WRITE")}}if(input.action==="read"){const value=LocalLibraryReadReplySchema.parse(result),bytes=Buffer.from(value.contentBase64,"base64");const length=Math.min(input.length,Math.max(0,input.reference.byteSize-input.offset));if(value.offset!==input.offset||bytes.toString("base64")!==value.contentBase64||bytes.length!==length||value.complete!==input.offset+length>=input.reference.byteSize)throw new NativeStudioSdkError("LOCAL_LIBRARY_MEDIA_INVALID","BLOCKED","NO_WRITE")}const refs=result&&typeof result==="object"&&"items"in result?result.items.map(item=>item.reference):result&&typeof result==="object"&&"reference"in result?[result.reference]:[];for(const ref of refs){if("reference"in input&&canonicalLocalJson(ref)!==canonicalLocalJson(input.reference)||"tenantId"in input&&(ref.tenantId!==input.tenantId||input.projectId!==void 0&&ref.projectId!==input.projectId||ref.deviceId!==input.deviceId))throw new NativeStudioSdkError("LOCAL_SCOPE_INVALID","BLOCKED","NO_WRITE")}if("ownerKey"in input&&input.ownerKey&&result&&typeof result==="object"){const owned="items"in result?result.items:"ownerKey"in result?[result]:[];if(owned.some(item=>"ownerKey"in item&&item.ownerKey!==input.ownerKey))throw new NativeStudioSdkError("LOCAL_SCOPE_INVALID","BLOCKED","NO_WRITE")}return result}async import(raw,bytes,signal){const input=LocalLibraryImportSchema.parse(raw),header=Buffer.from(JSON.stringify(input)).toString("base64url");if(header.length>3072)throw new NativeStudioSdkError("INVALID_INPUT","INVALID_INPUT","NO_WRITE");const body=Readable2.from((async function*(){let count=0;const hash=createHash2("sha256");for await(const chunk of bytes){const part=Buffer.from(chunk);count+=part.length;if(count>input.reference.byteSize)throw Error("LOCAL_FILE_CHANGED");hash.update(part);yield part}if(count!==input.reference.byteSize||hash.digest("hex")!==input.reference.checksumSha256)throw Error("LOCAL_FILE_CHANGED")})());const transfer=await libraryTransport(this.client.options,{method:"PUT",path:"/ipc/v1/library/import",body,headers:{"x-nvs-request-id":input.requestId,"x-nvs-library-import":header,"content-type":"application/octet-stream","content-length":input.reference.byteSize}},signal);try{let size=0;const parts=[];for await(const part of transfer.response){size+=part.length;if(size>262144)throw Error();parts.push(part)}const reply=LocalIpcResponseSchema.parse(JSON.parse(Buffer.concat(parts).toString()));if(reply.semanticStatus!=="SUCCESS")throw new NativeStudioSdkError(reply.error.code,reply.semanticStatus,reply.error.code==="INTERNAL_OPERATIONAL_FAILURE"?"UNKNOWN":"REJECTED");const item=LocalLibraryItemSchema.parse(reply.data);if(reply.requestId!==input.requestId||canonicalLocalJson(item.reference)!==canonicalLocalJson(input.reference)||item.ownerKey!==input.ownerKey||item.title!==input.title)throw Error();return item}catch(error){if(error instanceof NativeStudioSdkError)throw error;throw new NativeStudioSdkError("LOCAL_LIBRARY_IMPORT_UNKNOWN","BLOCKED","UNKNOWN")}finally{transfer.close()}}media(raw,input={},signal){return readLibraryMedia(this.client.options,raw,input,signal)}};import{randomUUID as randomUUID2}from"node:crypto";import{request as request3}from"node:http";var NativeStudioLocalRuntimeClient=class _NativeStudioLocalRuntimeClient{constructor(options){this.options=options}options;workspace=new NativeStudioLocalWorkspaceClient(this);library=new NativeStudioLocalLibraryClient(this);static async fromConnector(path){const initial=LocalSessionConnectorSchema.parse(JSON.parse((await readLocalCredential(path)).toString()));return new _NativeStudioLocalRuntimeClient({stateDirectory:initial.stateDirectory,device:{tenantId:initial.tenantId,deviceId:initial.deviceId},authorization:async()=>{const current=LocalSessionConnectorSchema.parse(JSON.parse((await readLocalCredential(path)).toString()));if(current.stateDirectory!==initial.stateDirectory||current.tenantId!==initial.tenantId||current.deviceId!==initial.deviceId||Date.parse(current.expiresAt)>Date.parse(initial.expiresAt)||Date.parse(current.expiresAt)<=Date.now())throw Error("LOCAL_AUTHORIZATION_REQUIRED");return"Bearer "+current.credential}})}async call(call,signal){let started=false;const budget=localBudget(this.options.timeoutMs??(["runtime.doctor","agent.probe","agent.grant","agent.start"].includes(call.operation)?6e4:3e4),signal);const readOnly=["runtime.status","runtime.doctor","runtime.inventory","execution.inspect","execution.list","update.check","agent.probe","agent.discover","agent.inspect","workspace.inspect","diagnostics.read","library.capability"].includes(call.operation)||call.operation==="library.call"&&["list","get","usage","read","import-receipt","scoped-list","scoped-get","sync"].includes(call.input.action);try{const input=LocalIpcRequestSchema.parse({protocol:"NVS_LOCAL_IPC_V1",requestId:randomUUID2(),call});const root=await checkedLocalDirectory(this.options.stateDirectory);const path=localSocketPath(root);await privateAccess(path,"pipe");budget.signal.throwIfAborted();const auth=await localAbortable(Promise.resolve().then(()=>this.options.authorization()),budget.signal);budget.signal.throwIfAborted();if(auth.length!==50||!/^Bearer [A-Za-z0-9_-]{43}$/.test(auth))throw Error();const body=JSON.stringify(input);const reply=await new Promise((resolve,reject)=>{const abort=budget.signal;const req=request3({socketPath:path,method:"POST",path:"/ipc/v1",signal:abort,headers:{authorization:auth,"content-type":"application/json","content-length":Buffer.byteLength(body)}},res=>{const chunks=[];let length=0;res.on("error",reject);res.on("aborted",()=>reject(Error()));res.on("data",b=>{length+=b.length;if(length>256*1024)req.destroy(Error());else chunks.push(b)});res.on("end",()=>{try{resolve(JSON.parse(Buffer.concat(chunks).toString()))}catch{reject(Error())}})});req.on("error",reject);started=true;req.end(body)});const value=LocalIpcResponseSchema.parse(reply);if(value.requestId!==input.requestId&&!(value.requestId===null&&value.semanticStatus!=="SUCCESS"&&["FORBIDDEN","BUSY","INVALID_INPUT"].includes(value.error.code)))throw Error();if(value.semanticStatus!=="SUCCESS")throw new NativeStudioSdkError(value.error.code,value.semanticStatus,readOnly?"NO_WRITE":value.error.code==="INTERNAL_OPERATIONAL_FAILURE"?"UNKNOWN":"REJECTED");if(value.requestId!==input.requestId)throw Error();return value.data}catch(error){if(error instanceof NativeStudioSdkError)throw error;throw new NativeStudioSdkError("LOCAL_RUNTIME_UNAVAILABLE","BLOCKED",started&&!readOnly?"UNKNOWN":"NO_WRITE")}finally{budget.close()}}response(schema,raw){const result=schema.safeParse(raw);if(!result.success)throw new NativeStudioSdkError("LOCAL_RESPONSE_INVALID","BLOCKED","NO_WRITE");return result.data}async status(signal,includeDevice=false){const value=this.response(LocalRuntimeStatusSchema,await this.call({operation:"runtime.status",...includeDevice||this.options.device?{includeDevice:true}:{}},signal));if(this.options.device&&(value.deviceAuthority?.tenantId!==this.options.device.tenantId||value.deviceAuthority.deviceId!==this.options.device.deviceId))throw new NativeStudioSdkError("LOCAL_SCOPE_INVALID","BLOCKED","NO_WRITE");return value}async doctor(signal){return this.response(LocalDoctorReportSchema,await this.call({operation:"runtime.doctor"},signal))}async inventory(signal){return this.response(LocalManagementInventorySchema,await this.call({operation:"runtime.inventory"},signal))}async grantAgent(raw,approval){return this.response(LocalAgentProbeSchema,await this.call({operation:"agent.grant",grant:LocalAgentGrantSchema.parse(raw),approval}))}async revokeAgent(approval){return this.response(LocalAgentProbeSchema,await this.call({operation:"agent.revoke",approval}))}async probeAgent(){return this.response(LocalAgentProbeSchema,await this.call({operation:"agent.probe"}))}async discoverAgent(binary){return this.response(LocalAgentDiscoverySchema,await this.call({operation:"agent.discover",...binary?{binary}:{}}))}async prepareAgentReview(snapshot){const input=LocalAgentSnapshotSchema.parse(snapshot);const v=this.response(LocalAgentReviewViewSchema,await this.call({operation:"agent.prepare",snapshot:input}));if(canonicalLocalJson(v.plan.snapshot)!==canonicalLocalJson(input))throw new NativeStudioSdkError("LOCAL_RESPONSE_INVALID","BLOCKED","UNKNOWN");return v}async startAgentReview(id,expectedRevision,approval){const v=this.response(LocalAgentReviewViewSchema,await this.call({operation:"agent.start",id,expectedRevision,approval}));if(v.plan.id!==id||v.plan.fingerprint!==approval)throw new NativeStudioSdkError("LOCAL_RESPONSE_INVALID","BLOCKED","UNKNOWN");return v}async stageAgentImage(id,bytes,signal){const budget=localBudget(18e4,signal,18e4);try{return await stageAgentImage(this.options,await this.inspectAgentReview(id,budget.signal),bytes,budget.signal)}finally{budget.close()}}async inspectAgentReview(id,signal){const v=this.response(LocalAgentReviewViewSchema,await this.call({operation:"agent.inspect",id},signal));if(v.plan.id!==id)throw new NativeStudioSdkError("LOCAL_RESPONSE_INVALID","BLOCKED","NO_WRITE");return v}async executions(input,signal){const i=LocalExecutionListInputSchema.parse(input);if(this.options.device&&this.options.device.tenantId!==i.tenantId)throw new NativeStudioSdkError("FORBIDDEN","BLOCKED","NO_WRITE");const page=this.response(LocalExecutionPageSchema,await this.call({operation:"execution.list",input:i},signal));if(page.items.some(e=>e.binding.tenantId!==i.tenantId||e.binding.projectId!==i.projectId))throw new NativeStudioSdkError("LOCAL_SCOPE_INVALID","BLOCKED","NO_WRITE");return page}async inspect(raw,signal){const input=LocalExecutionInspectInputSchema.parse(raw);if(this.options.device&&this.options.device.tenantId!==input.tenantId)throw new NativeStudioSdkError("FORBIDDEN","BLOCKED","NO_WRITE");const value=this.response(LocalExecutionInspectionSchema.nullable(),await this.call({operation:"execution.inspect",input},signal));if(value&&["tenantId","projectId","productionId","runtimeJobId"].some(k=>value.binding[k]!==input[k]))throw new NativeStudioSdkError("LOCAL_SCOPE_INVALID","BLOCKED","NO_WRITE");return value}};function newerVersion(candidate,current){const parse=v=>{const core=v.split("+")[0],i=core.indexOf("-");return{parts:(i<0?core:core.slice(0,i)).split(".").map(BigInt),pre:i<0?null:core.slice(i+1).split(".")}};const a=parse(candidate),b=parse(current);for(let i=0;i<3;i++){if(a.parts[i]!==b.parts[i])return a.parts[i]>b.parts[i]}if(!a.pre||!b.pre)return!a.pre&&!!b.pre;for(let i=0;i<Math.max(a.pre.length,b.pre.length);i++){const x=a.pre[i],y=b.pre[i];if(x===y)continue;if(x===void 0||y===void 0)return y===void 0;const xn=/^\d+$/.test(x),yn=/^\d+$/.test(y);if(xn&&yn)return BigInt(x)>BigInt(y);if(xn!==yn)return!xn;return x>y}return false}import{createPublicKey,verify}from"node:crypto";function endpoint(raw){const u=new URL(raw);if(u.username||u.password||u.search||u.hash||u.protocol!=="https:"&&!(u.protocol==="http:"&&["127.0.0.1","localhost","[::1]"].includes(u.hostname)))fail("RELEASE_ORIGIN_INVALID");return u}async function fetchBytes(raw,maximum,origin,signal=AbortSignal.timeout(3e4)){const u=endpoint(raw);if(u.origin!==origin)fail("RELEASE_ORIGIN_INVALID");const r=await fetch(u,{redirect:"error",signal,headers:{accept:"application/octet-stream"}});if(!r.ok||Number(r.headers.get("content-length"))>maximum){await r.body?.cancel();fail("RELEASE_UNAVAILABLE")}const parts=[];let size=0;for await(const part of r.body??[]){size+=part.byteLength;if(size>maximum){await r.body?.cancel().catch(()=>{});fail("RELEASE_LIMIT")}parts.push(part)}return Buffer.concat(parts)}async function catalogue(trust,signal){if(!trust.catalogueUrl||!trust.publicKeyFile)fail("DEPENDENCY_CHANNEL_REQUIRED");const origin=endpoint(trust.catalogueUrl).origin;const bytes=await fetchBytes(trust.catalogueUrl,65536,origin,signal??AbortSignal.timeout(3e4));const signed=LocalSignedCatalogueSchema.parse(JSON.parse(bytes.toString()));const key=createPublicKey((await read(trust.publicKeyFile,16384)).toString());if(key.asymmetricKeyType!=="ed25519"||!verify(null,Buffer.from(canonicalLocalJson(signed.catalogue)),key,Buffer.from(signed.signature,"base64url")))fail("RELEASE_SIGNATURE_INVALID");const now=Date.now();if(Date.parse(signed.catalogue.issuedAt)>now||Date.parse(signed.catalogue.expiresAt)<=now)fail("RELEASE_EXPIRED");for(const release of signed.catalogue.releases){for(const a of[release.package,...release.tools?Object.values(release.tools):[],...release.resources?Object.values(release.resources):[]])if(endpoint(a.url).origin!==origin)fail("RELEASE_ORIGIN_INVALID")}return{signed,fingerprint:sha256(canonicalLocalJson(signed.catalogue)),origin,trustFingerprint:sha256(canonicalLocalJson({catalogueUrl:endpoint(trust.catalogueUrl).href,publicKey:key.export({type:"spki",format:"der"}).toString("base64")}))}}function select(signed,version,rejected=[]){if(version==="latest"){const candidates=signed.catalogue.releases.filter(r2=>!rejected.includes(r2.descriptor.version)&&r2.descriptor.platform.os===process.platform&&r2.descriptor.platform.architecture===process.arch&&Number(process.versions.node.split(".")[0])===r2.descriptor.node.major&&Number(process.versions.node.split(".")[1])>=r2.descriptor.node.minMinor);const latest=candidates.reduce((a,b)=>!a||newerVersion(b.descriptor.version,a.descriptor.version)?b:a,void 0);if(!latest)fail("VERSION_INCOMPATIBLE");version=latest.descriptor.version}const r=signed.catalogue.releases.find(r2=>r2.descriptor.version===version&&r2.descriptor.platform.os===process.platform&&r2.descriptor.platform.architecture===process.arch);if(!r)fail("VERSION_INCOMPATIBLE");const[major,minor]=process.versions.node.split(".").map(Number);if(major!==r.descriptor.node.major||minor<r.descriptor.node.minMinor)fail("NODE_VERSION_INCOMPATIBLE");return r}async function asset(a,origin){const bytes=await fetchBytes(a.url,a.byteSize,origin,AbortSignal.timeout(12e4));if(bytes.length!==a.byteSize||sha512(bytes)!==a.sha512)fail("RELEASE_INTEGRITY_INVALID");return bytes}export{NativeStudioLocalDeviceClient,NativeStudioLocalRuntimeClient,newerVersion,endpoint,catalogue,select,asset};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{NativeStudioLocalRuntimeClient,asset,catalogue,newerVersion,select}from"./chunk-U7ECMITP.js";import{assertExecutable,directory,entries,fail,localSocketPath,optional,privateAccess,read,sha256,sha512,verifyBackup,write}from"./chunk-KB2GVAN7.js";import{LocalCompositionBrowserSelectionSchema,LocalDoctorReportSchema,LocalManagementInventorySchema,LocalRuntimeComponentSchema,LocalRuntimeDescriptorSchema,LocalToolChoiceSchema,LocalToolSelectionSchema,LocalUpdatePlanSchema,RuntimeCaptionAssets,canonicalLocalJson,importedNormalizationValidationProfile,localLibraryProfile,tenantRenderValidationProfile,whisperCppRecognitionProfile}from"./chunk-PDQYFIQQ.js";import{z}from"zod";import{constants,createReadStream}from"node:fs";import{open,realpath}from"node:fs/promises";import{isAbsolute}from"node:path";import{createHash}from"node:crypto";async function toolPreference(previous,cloud,explicit){if(explicit)return LocalToolChoiceSchema.parse(explicit);const raw=previous?JSON.parse((await read(previous,32768)).toString()):cloud?JSON.parse((await read(cloud,32768)).toString()).tools:null;const selected=raw?LocalToolSelectionSchema.parse(raw):null;return selected?.mode==="INSTALLED"?{...selected,mode:"INSTALLED"}:{mode:"MANAGED",...selected?.cpuSpeech?{cpuSpeech:selected.cpuSpeech}:{}}}async function captureInstalledTools(input,host=process){const paths=z.strictObject({mode:z.literal("INSTALLED").optional(),ffmpeg:z.string().min(1).max(4096),ffprobe:z.string().min(1).max(4096),compositionBrowser:z.string().min(1).max(4096).optional(),captionAssetsDirectory:z.string().min(1).max(4096).optional(),whisper:z.strictObject({binary:z.string().min(1).max(4096),model:z.string().min(1).max(4096)}).optional()}).parse(input);if(paths.compositionBrowser&&(host.platform!=="linux"||host.arch!=="x64"))fail("COMPOSITION_BROWSER_PLATFORM_UNAVAILABLE");if(paths.whisper&&(host.platform!=="darwin"||host.arch!=="arm64"))fail("LOCAL_PROFILE_UNAVAILABLE");async function capture(candidate,executable=true){if(!isAbsolute(candidate))fail("TOOL_PATH_INVALID");const path=await realpath(candidate);if(executable)await assertExecutable(path);const file=await open(path,constants.O_RDONLY|constants.O_NOFOLLOW|constants.O_NONBLOCK);try{const before=await file.stat();if(!before.isFile()||before.size<1||before.size>256*1024*1024)fail("TOOL_PATH_INVALID");const h=createHash("sha256");let count=0;for await(const chunk of createReadStream(path,{fd:file.fd,autoClose:false})){count+=chunk.length;if(count>before.size)fail("TOOL_CHANGED");h.update(chunk)}const after=await file.stat();if(count!==before.size||after.size!==before.size||after.mtimeMs!==before.mtimeMs)fail("TOOL_CHANGED");return{path,digest:h.digest("hex")}}finally{await file.close()}}const compositionBrowser=paths.compositionBrowser?await capture(paths.compositionBrowser):void 0;if(compositionBrowser&&!LocalCompositionBrowserSelectionSchema.safeParse(compositionBrowser).success)fail("COMPOSITION_BROWSER_INTEGRITY_INVALID");const model=paths.whisper?await capture(paths.whisper.model,false):void 0;if(model&&model.digest!==whisperCppRecognitionProfile.modelSha256)fail("LOCAL_ASR_IDENTITY_MISMATCH");const binary=paths.whisper?await capture(paths.whisper.binary):void 0;if(paths.captionAssetsDirectory&&!isAbsolute(paths.captionAssetsDirectory))fail("CAPTION_ASSET_LOCATION_INVALID");return LocalToolChoiceSchema.parse({mode:"INSTALLED",ffmpeg:await capture(paths.ffmpeg),ffprobe:await capture(paths.ffprobe),...compositionBrowser?{compositionBrowser}:{},...paths.captionAssetsDirectory?{captionAssetsDirectory:await realpath(paths.captionAssetsDirectory)}:{},...binary&&model?{whisper:{binaryPath:binary.path,binarySha256:binary.digest,modelPath:model.path}}:{}})}var requiredRuntimeFiles=["package.json","dist/entry.js","dist/supervisor.mjs","dist/parent-lifetime.mjs","dist/execution-identity.json"];var allowedRuntimeFiles=new Set([...requiredRuntimeFiles,"README.md","LICENSE","dist/THIRD_PARTY_NOTICES.md","dist/BUNDLED_DEPENDENCIES.json","dist/agent-supervisor.mjs","dist/kokoro-worker.mjs","dist/capture.mjs","dist/hyperframe.manifest.json","dist/hyperframe.runtime.iife.js","dist/hyperframe-gsap.js","dist/hyperframe-dependencies.json","dist/hyperframe-notices.txt","dist/captions/NotoSansSC.ttf","dist/captions/NativeStudioSC-Regular.ttf","dist/captions/OFL.txt",...["Bootstrap.ps1","NativeMain.cs","PrivateAccess.cs","PipeBridge.cs","JobNative.cs","JobRunner.cs"].map(name=>"dist/native/"+name)]);import{spawn}from"node:child_process";import{open as open2}from"node:fs/promises";import{dirname,join,delimiter}from"node:path";import{z as z2}from"zod";var runtimeEnvironment=()=>({...Object.fromEntries(["HOME","USER","LOGNAME","TMPDIR","CODEX_HOME","SystemRoot","SYSTEMROOT","USERPROFILE","LOCALAPPDATA","APPDATA","TEMP","TMP"].flatMap(k=>process.env[k]?[[k,process.env[k]]]:[])),PATH:dirname(process.execPath)+(process.platform==="win32"?"":delimiter+["/usr/bin","/bin"].join(delimiter)),LANG:"C",LC_ALL:"C",UV_THREADPOOL_SIZE:"2",NVS_INSTALL_OWNER:"MANAGED"});async function verifySlot(root,slot){if(requiredRuntimeFiles.some(name=>!Object.hasOwn(slot.files,name)))fail("SLOT_FILES_MISSING");for(const[name,hash]of Object.entries(slot.files)){if(!allowedRuntimeFiles.has(name))fail("SLOT_PATH_INVALID");if(sha256(await read(join(root,name),64*1024*1024))!==hash)fail("SLOT_INTEGRITY_INVALID")}}async function probeEntry(root,option,args=[]){return new Promise((resolve,reject)=>{const child=spawn(process.execPath,["--max-old-space-size=256",join(root,"dist/entry.js"),option,...args],{env:runtimeEnvironment(),stdio:["ignore","pipe","ignore"],shell:false});const parts=[];let size=0;const timer=setTimeout(()=>child.kill("SIGKILL"),1e4);child.stdout.on("data",b=>{size+=b.length;if(size>65536)child.kill("SIGKILL");else parts.push(b)});child.on("error",reject);child.on("close",code=>{clearTimeout(timer);if(code!==0||size>65536)reject(Error("Runtime descriptor unavailable"));else resolve(Buffer.concat(parts))})})}async function probeProfile(root,slot,option,profile){await verifySlot(root,slot);try{const digest=(await probeEntry(root,option)).toString().trim();return digest===sha256(canonicalLocalJson(profile))}catch{return false}}function probeTenantMediaValidation(root,slot){return probeProfile(root,slot,"--tenant-media-validation-profile",tenantRenderValidationProfile)}function probeTenantMediaProcessing(root,slot){return probeProfile(root,slot,"--tenant-media-processing-profile",importedNormalizationValidationProfile)}async function probeLocalLibrary(root,slot){await verifySlot(root,slot);try{return(await probeEntry(root,"--local-library-profile")).toString().trim()===sha256(canonicalLocalJson(localLibraryProfile))}catch{return false}}async function probeTenantComposition(root,slot){if(process.platform!=="linux"||process.arch!=="x64"||!slot.toolsConfigPath)return false;const selected=LocalToolSelectionSchema.parse(JSON.parse((await read(slot.toolsConfigPath,32768)).toString()));if(selected.mode!=="INSTALLED"||!selected.compositionBrowser)return false;await verifySlot(root,slot);try{const result=await probeEntry(root,"--tenant-composition-capability",["--tools-config",slot.toolsConfigPath]);return result.toString().trim()===selected.compositionBrowser.digest}catch{return false}}async function probeTenantSpeech(root,slot){if(process.platform!=="darwin")return false;await verifySlot(root,slot);try{return/^[a-f0-9]{64}$/.test((await probeEntry(root,"--tenant-speech-capability")).toString().trim())}catch{return false}}async function probeTenantTranscription(root,slot){if(process.platform!=="darwin"||process.arch!=="arm64"||!slot.toolsConfigPath)return false;await verifySlot(root,slot);try{return/^[a-f0-9]{64}$/.test((await probeEntry(root,"--tenant-transcription-capability",["--tools-config",slot.toolsConfigPath])).toString().trim())}catch{return false}}async function probeTenantQwenGeneration(root,slot,kind){await verifySlot(root,slot);return probeEntry(root,`--tenant-qwen-${kind}-capability`).then(value=>value.toString().trim()==="QWEN_"+kind.toUpperCase()+"_V1",()=>false)}async function probe(root,expected){const bytes=await probeEntry(root,"--describe");const descriptor=LocalRuntimeDescriptorSchema.parse(JSON.parse(bytes.toString()));if(canonicalLocalJson(descriptor)!==canonicalLocalJson(expected))fail("RUNTIME_DESCRIPTOR_MISMATCH");return descriptor}async function ownerClient(stateDirectory){await directory(stateDirectory);return new NativeStudioLocalRuntimeClient({stateDirectory,authorization:async()=>"Bearer "+(await read(join(stateDirectory,"control-token"),128)).toString()})}async function runningInventory(client,root,slot){const inventory=await client.inventory(),status=await client.status();if(canonicalLocalJson(inventory.descriptor)!==canonicalLocalJson(slot.descriptor)||status.versions.find(v=>v.component==="RUNTIME")?.executablePath!==join(root,"dist/entry.js"))fail("RUNTIME_ALREADY_RUNNING");return inventory}async function launch(root,slot,stateDirectory,cloudConfig,toolsConfig){await verifySlot(root,slot);await probe(root,slot.descriptor);await directory(stateDirectory);const existing=await ownerClient(stateDirectory);try{return await runningInventory(existing,root,slot)}catch(e){if(e instanceof Error&&e.message.includes("RUNTIME_ALREADY_RUNNING"))throw e}const log=await open2(join(stateDirectory,"runtime-process.log"),"a",384);const child=spawn(process.execPath,["--max-old-space-size=256",join(root,"dist/entry.js"),"serve","--state-dir",stateDirectory,...cloudConfig?["--cloud-config",cloudConfig]:[],...toolsConfig?["--tools-config",toolsConfig]:[]],{env:runtimeEnvironment(),detached:true,windowsHide:true,stdio:["ignore",log.fd,log.fd],shell:false});let spawnError=false;child.once("error",()=>{spawnError=true});child.unref();await log.close();const deadline=Date.now()+15e3;while(Date.now()<deadline){if(spawnError||child.exitCode!==null)fail("RUNTIME_START_FAILED");try{return await runningInventory(existing,root,slot)}catch{}await new Promise(r=>setTimeout(r,100))}child.kill("SIGTERM");fail("RUNTIME_START_UNCONFIRMED")}async function waitStopped(stateDirectory){const client=await ownerClient(stateDirectory),deadline=Date.now()+1e4;while(Date.now()<deadline){try{await client.inventory()}catch{const{lstat:lstat3}=await import("node:fs/promises");try{if(process.platform!=="win32")await lstat3(localSocketPath(stateDirectory))}catch(e){if(e.code==="ENOENT")return}const{createConnection}=await import("node:net");const closed=await new Promise(resolve=>{const s=createConnection(localSocketPath(stateDirectory));s.once("connect",()=>{s.destroy();resolve(false)});s.once("error",e=>resolve(["ECONNREFUSED","ENOENT"].includes(e.code??"")));s.setTimeout(300,()=>{s.destroy();resolve(false)})});if(closed)return}await new Promise(r=>setTimeout(r,100))}fail("RUNTIME_STOP_UNCONFIRMED")}async function socketAbsent(stateDirectory){const{createConnection}=await import("node:net");return new Promise(resolve=>{const socket=createConnection(localSocketPath(stateDirectory));socket.once("connect",()=>{socket.destroy();resolve(false)});socket.once("error",error=>resolve(["ECONNREFUSED","ENOENT"].includes(error.code??"")));socket.setTimeout(500,()=>{socket.destroy();resolve(false)})})}async function probeTools(root,stateDirectory,selection){const{execFile}=await import("node:child_process");const diagnostic=z2.strictObject({tool:z2.enum(["FFMPEG","FFPROBE"]),stage:z2.enum(["IDENTITY","VERSION","ENCODERS","DECODERS","FILTERS","DEMUXERS","MUXERS","FINAL_IDENTITY"]),cause:z2.enum(["IDENTITY_INVALID","VERSION_INVALID","CAPABILITY_MISSING","PROCESS_FAILED","TIMEOUT","CANCELLED"])});const failures=[];for(let attempt=0;attempt<2;attempt++){const result=await new Promise((resolve,reject)=>execFile(process.execPath,["--max-old-space-size=256",join(root,"dist/entry.js"),"--qualify-tools","--state-dir",stateDirectory,"--tools-config",selection],{env:runtimeEnvironment(),timeout:5e4,maxBuffer:65536},(error,stdout,stderr)=>error?reject(Error("Tool probe failed")):resolve({stdout,stderr})));const report=LocalDoctorReportSchema.parse(JSON.parse(result.stdout));let failure;for(const line of result.stderr.split("\n")){try{const parsed=diagnostic.safeParse(JSON.parse(line).toolProbe);if(parsed.success)failure=parsed.data}catch{}}if(failure)failures.push(failure);if(failures.length)await write(join(stateDirectory,"tool-qualification.json"),JSON.stringify({checkedAt:new Date().toISOString(),availability:report.availability,failures}));if(report.availability==="AVAILABLE")return report;if(!failure||!["TIMEOUT","PROCESS_FAILED"].includes(failure.cause))break}fail("TOOL_QUALIFICATION_FAILED")}async function verifyManagedMedia(previous,reuse){if(!previous)fail("MANAGED_TOOLS_UNAVAILABLE");const current=LocalToolSelectionSchema.parse(JSON.parse((await read(previous,32768)).toString()));if(current.mode!=="MANAGED"||canonicalLocalJson({schemaVersion:1,ffmpeg:current.ffmpeg,ffprobe:current.ffprobe})!==canonicalLocalJson(reuse))fail("MANAGED_TOOLS_CHANGED");const files=await captureInstalledTools({ffmpeg:reuse.ffmpeg.path,ffprobe:reuse.ffprobe.path});if(files.mode!=="INSTALLED"||canonicalLocalJson(files.ffmpeg)!==canonicalLocalJson(reuse.ffmpeg)||canonicalLocalJson(files.ffprobe)!==canonicalLocalJson(reuse.ffprobe))fail("MANAGED_TOOLS_CHANGED");return{mode:"MANAGED",ffmpeg:current.ffmpeg,ffprobe:current.ffprobe}}import{randomUUID}from"node:crypto";import{lstat}from"node:fs/promises";import{join as join2}from"node:path";import{constants as constants2}from"node:fs";import{open as open3}from"node:fs/promises";import{createHash as createHash2}from"node:crypto";async function bytesAt(base,name,maximum){const f=await open3(new URL(name,base),constants2.O_RDONLY|constants2.O_NOFOLLOW|constants2.O_NONBLOCK);try{const stat=await f.stat();if(!stat.isFile()||stat.size<1||stat.size>maximum)fail("BUNDLED_COMPONENT_INVALID");const bytes=Buffer.alloc(stat.size+1);let used=0;while(used<bytes.length){const{bytesRead}=await f.read(bytes,used,bytes.length-used,null);if(!bytesRead)break;used+=bytesRead}if(used!==stat.size)fail("BUNDLED_COMPONENT_CHANGED");return bytes.subarray(0,used)}finally{await f.close()}}async function readEmbeddedRuntime(base,manifestDigest){const raw=await bytesAt(base,"components/runtime.json",32768);if(sha256(raw)!==manifestDigest)fail("BUNDLED_COMPONENT_CHANGED");const component=LocalRuntimeComponentSchema.parse(JSON.parse(raw.toString()));const product=JSON.parse((await bytesAt(base,"package.json",32768)).toString());if(product.name!=="@nativestudio/cli"||product.version!==component.version)fail("BUNDLED_COMPONENT_IDENTITY_INVALID");const bytes=await bytesAt(base,"components/runtime.tgz",64*1024*1024);if(bytes.length!==component.byteSize||createHash2("sha512").update(bytes).digest("hex")!==component.sha512)fail("BUNDLED_COMPONENT_INTEGRITY_INVALID");const descriptor=LocalRuntimeDescriptorSchema.parse({...component.descriptor,platform:{os:process.platform,architecture:process.arch}});return{component,bytes,descriptor,trustFingerprint:manifestDigest}}async function embeddedRuntime(version){if(false)return null;const base=new URL(".",import.meta.resolve("@nativestudio/cli/package.json"));const value=await readEmbeddedRuntime(base,"3d1ab069c88c9fc8c9c353cc6e5e46010eadc82708550e4d5041cde545ad5a00");return version&&version!=="latest"&&version!==value.component.version?null:value}async function installationSource(c,version,bundled,dependencies){if(!bundled){const trusted2=await catalogue(c);return{release:select(trusted2.signed,version,c.rejectedVersions),origin:trusted2.origin,catalogueFingerprint:trusted2.fingerprint,trustFingerprint:trusted2.trustFingerprint,expiresAt:trusted2.signed.catalogue.expiresAt}}const core=await embeddedRuntime(version);if(!core||c.rejectedVersions.includes(core.descriptor.version))fail("BUNDLED_VERSION_UNAVAILABLE");const[major,minor]=process.versions.node.split(".").map(Number);if(major!==core.descriptor.node.major||minor<core.descriptor.node.minMinor)fail("NODE_VERSION_INCOMPATIBLE");const trusted=dependencies?await catalogue(c):null;const remote=trusted?select(trusted.signed,core.descriptor.version):null;if(remote&&(remote.package.sha512!==core.component.sha512||remote.package.byteSize!==core.component.byteSize||canonicalLocalJson(remote.descriptor)!==canonicalLocalJson(core.descriptor)||remote.resources&&(remote.resources.captions.sha512!==core.component.resources.captions.sha512||remote.resources.captions.byteSize!==core.component.resources.captions.byteSize)))fail("BUNDLED_COMPONENT_RELEASE_MISMATCH");return{release:{descriptor:core.descriptor,package:{source:"CLI",byteSize:core.component.byteSize,sha512:core.component.sha512},tools:remote?.tools??null,...remote?.resources?{resources:remote.resources}:{}},origin:trusted?.origin??"",catalogueFingerprint:trusted?.fingerprint??null,trustFingerprint:trusted?sha256(canonicalLocalJson([core.trustFingerprint,trusted.trustFingerprint])):core.trustFingerprint,expiresAt:trusted?.signed.catalogue.expiresAt??new Date(Date.now()+18e5).toISOString()}}async function approvedSource(c,plan){const source=await installationSource(c,plan.release.descriptor.version,"source"in plan.release.package,plan.catalogueFingerprint!==null);if(Date.parse(plan.expiresAt)<=Date.now()||source.trustFingerprint!==plan.trustFingerprint||canonicalLocalJson(source.release)!==canonicalLocalJson(plan.release))fail("PLAN_CHANGED");return source}function needsDependencyChannel(c,choice,haveCaptions=false){return!!choice&&(choice.mode==="MANAGED"&&!choice.reuseMedia||choice.mode==="INSTALLED"&&!choice.captionAssetsDirectory&&!haveCaptions&&!!c.catalogueUrl&&!!c.publicKeyFile)}function toolIdentity(tools){return[tools.ffmpeg.digest,tools.ffprobe.digest,...tools.cpuSpeech?[canonicalLocalJson({...tools.cpuSpeech,voiceIds:[...tools.cpuSpeech.voiceIds].sort((a,b)=>a-b)})]:[],...tools.mode==="INSTALLED"&&tools.compositionBrowser?[tools.compositionBrowser.digest]:[],...tools.mode==="INSTALLED"&&tools.whisper?[tools.whisper.binarySha256,whisperCppRecognitionProfile.modelSha256]:[]].join(":")}async function identity(path,cloud){if(!path)return null;const raw=JSON.parse((await read(path,32768)).toString());const tools=LocalToolSelectionSchema.parse(cloud?raw.tools:raw);return toolIdentity(tools)}async function effective(path,cloud){return path?identity(path,false):identity(cloud,true)}function supportedRenderer(expected,digest){return expected.rendererDigest===digest||!!expected.compatibleRenderers?.some(r=>r.rendererDigest===digest)}async function assertPendingCompatible(raw,expected,previous,next,cloud){const i=LocalManagementInventorySchema.parse(raw);if(i.pendingRenderers.some(d=>!supportedRenderer(expected,d)))fail("NATIVE_RECOVERY_REQUIRED");if(i.pendingExecutions+i.pendingRequests===0)return;if(i.descriptor.profileDigest!==expected.profileDigest&&!expected.compatibleRenderers?.some(r=>r.profileDigest===i.descriptor.profileDigest))fail("NATIVE_RECOVERY_REQUIRED");const before=await effective(previous,cloud);const after=await effective(next,cloud);if(!before||before!==after)fail("NATIVE_RECOVERY_REQUIRED")}async function assertPendingToolIdentity(raw,previous,cloud,next){const i=LocalManagementInventorySchema.parse(raw);if(i.pendingExecutions+i.pendingRequests>0&&await effective(previous,cloud)!==next)fail("NATIVE_RECOVERY_REQUIRED")}async function assertNoStoppedJournal(state){for(const suffix of["","-wal","-shm","-journal"]){try{await lstat(join2(state,"journal.sqlite"+suffix))}catch(e){if(e.code==="ENOENT")continue;throw e}fail("RUNTIME_STATUS_REQUIRED")}}async function prepareInstallation(manager,version,raw,bundled=false){const c=await manager.configuration(),current=(await manager.ledger.current()).value;if(current.transition)fail("ACTIVATION_IN_PROGRESS");const explicit=raw===void 0?void 0:LocalToolChoiceSchema.parse(raw),source=await installationSource(c,version,bundled,needsDependencyChannel(c,explicit,Object.entries(RuntimeCaptionAssets).every(([name,hash])=>current.active?.files["dist/captions/"+name]===hash))),release=source.release,preference=await toolPreference(current.active?.toolsConfigPath??null,c.cloudConfigFile,explicit),toolSelection=explicit||preference.mode==="INSTALLED"||release.tools?preference:void 0;if(toolSelection?.mode==="MANAGED"){if(toolSelection.reuseMedia)await verifyManagedMedia(current.active?.toolsConfigPath??null,toolSelection.reuseMedia);else if(!release.tools)fail("MANAGED_TOOLS_UNAVAILABLE")}let runtimeRevision=null;try{const inventory=await(await ownerClient(c.stateDirectory)).inventory();runtimeRevision=inventory.runtimeRevision;const previous=current.active?.toolsConfigPath??null;await assertPendingCompatible(inventory,release.descriptor,previous,previous,c.cloudConfigFile);const desired=preference.mode==="INSTALLED"?preference:preference.reuseMedia??release.tools;if(desired)await assertPendingToolIdentity(inventory,previous,c.cloudConfigFile,preference.mode==="INSTALLED"?toolIdentity(preference):preference.reuseMedia?toolIdentity({mode:"MANAGED",ffmpeg:preference.reuseMedia.ffmpeg,ffprobe:preference.reuseMedia.ffprobe,...preference.cpuSpeech?{cpuSpeech:preference.cpuSpeech}:{}}):release.tools.ffmpeg.sha256+":"+release.tools.ffprobe.sha256+(preference.cpuSpeech?":"+canonicalLocalJson({...preference.cpuSpeech,voiceIds:[...preference.cpuSpeech.voiceIds].sort((a,b)=>a-b)}):""))}catch(e){if(e instanceof Error&&e.message.includes("NATIVE_RECOVERY_REQUIRED"))throw e;if(!await socketAbsent(c.stateDirectory))fail("RUNTIME_STATUS_REQUIRED");await assertNoStoppedJournal(c.stateDirectory)}const body={protocol:"NVS_LOCAL_UPDATE_PLAN_V1",planId:randomUUID(),installationRevision:current.revision,runtimeRevision,catalogueFingerprint:source.catalogueFingerprint,trustFingerprint:source.trustFingerprint,release,...toolSelection?{toolSelection}:{},createdAt:new Date().toISOString(),expiresAt:new Date(Math.min(Date.now()+18e5,Date.parse(source.expiresAt))).toISOString()};const plan=LocalUpdatePlanSchema.parse({...body,fingerprint:sha256(canonicalLocalJson(body))});await write(join2(manager.ledger.root,"plans",plan.planId+".json"),canonicalLocalJson(plan),true);return plan}import{randomUUID as randomUUID2}from"node:crypto";import{join as join3,dirname as dirname2}from"node:path";import{z as z3}from"zod";async function grant(manager,raw,output){const i=z3.strictObject({tenantId:z3.uuid(),deviceId:z3.uuid(),expiresAt:z3.iso.datetime({offset:true})}).parse(raw);const c=await manager.configuration(),client=await ownerClient(c.stateDirectory);await directory(dirname2(output));const connector=await client.call({operation:"session.issue",...i});await write(output,canonicalLocalJson(connector),true);await write(join3(manager.ledger.root,"grants",randomUUID2()+".json"),canonicalLocalJson({...i,output}),true);return{granted:true,tenantId:i.tenantId,deviceId:i.deviceId,expiresAt:i.expiresAt}}async function reconnect(manager){const{entries:entries2}=await import("./files-TTIQ7LYJ.js"),c=await manager.configuration(),client=await ownerClient(c.stateDirectory);let renewed=0,blocked=0;for(const name of await entries2(join3(manager.ledger.root,"grants"))){if(!/^[0-9a-f-]{36}\.json$/.test(name))continue;try{const g=z3.strictObject({tenantId:z3.uuid(),deviceId:z3.uuid(),expiresAt:z3.iso.datetime({offset:true}),output:z3.string().min(1)}).parse(await optional(join3(manager.ledger.root,"grants",name)));if(Date.parse(g.expiresAt)<=Date.now())continue;const connector=await client.call({operation:"session.issue",tenantId:g.tenantId,deviceId:g.deviceId,expiresAt:g.expiresAt});await write(g.output,canonicalLocalJson(connector));renewed++}catch{blocked++}}return{renewed,blocked}}import{randomUUID as randomUUID4}from"node:crypto";import{join as join9}from"node:path";import{z as z5}from"zod";import{z as z4}from"zod";import{join as join4}from"node:path";var slotSchema=z4.strictObject({id:z4.uuid(),descriptor:LocalRuntimeDescriptorSchema,toolsConfigPath:z4.string().nullable().default(null),files:z4.record(z4.string().min(1).max(100),z4.string().regex(/^[0-9a-f]{64}$/))});var transitionSchema=z4.strictObject({id:z4.uuid(),planId:z4.uuid(),fingerprint:z4.string().regex(/^[0-9a-f]{64}$/),phase:z4.enum(["STAGING","STAGED","DRAINING","ACTIVATING","VERIFYING","ROLLBACK_REQUIRED"]),previous:slotSchema.nullable(),candidate:slotSchema.nullable(),backupPath:z4.string().nullable(),failedPhase:z4.enum(["STAGING","STAGED","DRAINING","ACTIVATING","VERIFYING","ROLLBACK_REQUIRED"]).nullable().default(null)});var installationSchema=z4.strictObject({revision:z4.int().nonnegative(),active:slotSchema.nullable(),transition:transitionSchema.nullable()});var recordSchema=z4.strictObject({previous:z4.string().nullable(),value:installationSchema,digest:z4.string().regex(/^[0-9a-f]{64}$/)});var InstallationLedger=class _InstallationLedger{constructor(root){this.root=root}root;static async open(path){const root=await directory(path);for(const name of["revisions","plans","slots","grants"])await directory(join4(root,name));return new _InstallationLedger(root)}static async openExisting(root){try{await privateAccess(root,"directory");await privateAccess(join4(root,"revisions"),"directory")}catch(error){if(error.code==="ENOENT")return null;throw error}return new _InstallationLedger(root)}async current(){const names2=(await entries(join4(this.root,"revisions"))).filter(n=>/^\d{12}\.json$/.test(n)).sort();let previous=null,value={revision:0,active:null,transition:null};for(const[i,name]of names2.entries()){const raw=JSON.parse((await read(join4(this.root,"revisions",name),262144,true)).toString());const r=recordSchema.parse(raw);const expected=sha256(canonicalLocalJson({previous:raw.previous,value:raw.value}));if(r.value.revision!==i+1||r.previous!==previous||r.digest!==expected)fail("INSTALLATION_HISTORY_INVALID");previous=r.digest;value=r.value}return{value,digest:previous}}async commit(expected,next){const current=await this.current();if(current.value.revision!==expected.revision)fail("REVISION_CONFLICT");const value=installationSchema.parse({...next,revision:expected.revision+1});const record={previous:current.digest,value,digest:sha256(canonicalLocalJson({previous:current.digest,value}))};try{await write(join4(this.root,"revisions",String(value.revision).padStart(12,"0")+".json"),canonicalLocalJson(record),true)}catch(e){if(e.code==="EEXIST")fail("REVISION_CONFLICT");throw e}return value}slotPath(slot){return join4(this.root,"slots",slot.id)}};import{constants as constants3}from"node:fs";import{open as open4,chmod}from"node:fs/promises";import{join as join5,isAbsolute as isAbsolute2}from"node:path";import{gunzipSync}from"node:zlib";function packageFiles(bytes,allowed2,directories){const data=gunzipSync(bytes,{maxOutputLength:64*1024*1024});const files=new Map;let offset=0;while(offset+512<=data.length){const header=data.subarray(offset,offset+512);if(header.every(b=>b===0)){if(!data.subarray(offset).every(b=>b===0))fail("PACKAGE_FORMAT_INVALID");break}const text=(a,b)=>header.subarray(a,b).toString().replace(/\0.*$/s,"");const number=(a,b)=>{const v=text(a,b).trim();if(!/^[0-7]+$/.test(v))fail("PACKAGE_FORMAT_INVALID");return parseInt(v,8)};const sum=number(148,156);let actual=0;for(let i=0;i<512;i++)actual+=i>=148&&i<156?32:header[i];if(actual!==sum||!text(257,263).startsWith("ustar"))fail("PACKAGE_FORMAT_INVALID");const prefix=text(345,500),path=(prefix?prefix+"/":"")+text(0,100),size=number(124,136),kind=text(156,157);if(!Number.isSafeInteger(size)||size<0||offset+512+size>data.length)fail("PACKAGE_FORMAT_INVALID");if(kind==="5"){if(!directories.test(path)||size!==0)fail("PACKAGE_PATH_INVALID")}else{if(kind!=="0"&&kind!=="")fail("PACKAGE_LINK_OR_METADATA_REFUSED");if(!path.startsWith("package/")||!allowed2.has(path.slice(8))||files.has(path.slice(8)))fail("PACKAGE_PATH_INVALID");files.set(path.slice(8),data.subarray(offset+512,offset+512+size))}offset+=512+Math.ceil(size/512)*512}return files}var names=Object.keys(RuntimeCaptionAssets);var allowed=new Set(names.map(n=>"dist/captions/"+n));async function captionDirectory(path){if(!isAbsolute2(path))fail("CAPTION_ASSET_LOCATION_INVALID");const files=new Map;for(const name of names){const f=await open4(join5(path,name),constants3.O_RDONLY|constants3.O_NOFOLLOW|constants3.O_NONBLOCK);try{const s=await f.stat();if(!s.isFile()||s.size<1||s.size>20*1024*1024)fail("CAPTION_ASSET_INVALID");const bytes=Buffer.alloc(s.size+1);let used=0;while(used<bytes.length){const part=await f.read(bytes,used,bytes.length-used,null);if(!part.bytesRead)break;used+=part.bytesRead}if(used!==s.size||sha256(bytes.subarray(0,used))!==RuntimeCaptionAssets[name])fail("CAPTION_ASSET_INVALID");files.set("dist/captions/"+name,bytes.subarray(0,used))}finally{await f.close()}}return files}async function managedCaptions(ledger,resource,origin){const path=join5(await directory(join5(ledger.root,"resources")),resource.sha512+".tgz");let bytes;let downloaded=false;try{bytes=await read(path,resource.byteSize)}catch(e){if(e.code!=="ENOENT")throw e;bytes=await asset(resource,origin);downloaded=true}if(bytes.length!==resource.byteSize||sha512(bytes)!==resource.sha512)fail("CAPTION_RESOURCE_INTEGRITY_INVALID");const files=packageFiles(bytes,allowed,/^package(?:\/dist(?:\/captions)?)?\/?$/);if(files.size!==names.length)fail("CAPTION_ASSET_INVALID");for(const name of names)if(sha256(files.get("dist/captions/"+name))!==RuntimeCaptionAssets[name])fail("CAPTION_ASSET_INVALID");if(downloaded){try{await write(path,bytes,true)}catch(e){if(e.code!=="EEXIST")throw e;const existing=await read(path,resource.byteSize);if(existing.length!==resource.byteSize||sha512(existing)!==resource.sha512)fail("CAPTION_RESOURCE_INTEGRITY_INVALID")}}return files}async function stageResources(ledger,candidate,previous,plan,origin){const root=ledger.slotPath(candidate);const present=[...allowed].filter(p=>candidate.files[p]);if(present.length){await captionDirectory(join5(root,"dist/captions"));return candidate}const choice=plan.toolSelection;let files;if(choice?.mode==="INSTALLED"&&choice.captionAssetsDirectory)files=await captionDirectory(choice.captionAssetsDirectory);else if(previous&&[...allowed].some(p=>previous.files[p]))files=await captionDirectory(join5(ledger.slotPath(previous),"dist/captions"));else if(plan.release.resources)files=await managedCaptions(ledger,plan.release.resources.captions,origin);if(!files)return candidate;await directory(join5(root,"dist/captions"));const hashes={...candidate.files};for(const[path,bytes]of files){await write(join5(root,path),bytes,true);await chmod(join5(root,path),256);hashes[path]=sha256(bytes)}return{...candidate,files:hashes}}import{randomUUID as randomUUID3}from"node:crypto";import{chmod as chmod3}from"node:fs/promises";import{join as join7}from"node:path";import{chmod as chmod2}from"node:fs/promises";import{join as join6}from"node:path";async function unpack(bytes,root,expectedVersion){const files=packageFiles(bytes,allowedRuntimeFiles,/^package(?:\/dist(?:\/(?:native|captions))?)?\/?$/);if(!requiredRuntimeFiles.every(p=>files.has(p)))fail("PACKAGE_FILES_MISSING");const manifest=JSON.parse(files.get("package.json").toString());const deps=manifest.dependencies;if(manifest.name!=="@nativestudio/local-runtime"||manifest.version!==expectedVersion||manifest.type!=="module"||Object.keys(deps??{}).length||Object.keys(manifest.optionalDependencies??{}).length||["preinstall","install","postinstall","prepare"].some(name=>Object.hasOwn(manifest.scripts??{},name))||!["dist/entry.js","./dist/entry.js"].includes(manifest.bin?.["nvs-runtime"]??"")||Object.keys(manifest.bin??{}).length!==1)fail("PACKAGE_IDENTITY_INVALID");const hashes={};await directory(join6(root,"dist"));if([...files.keys()].some(p=>p.startsWith("dist/native/")))await directory(join6(root,"dist/native"));if([...files.keys()].some(p=>p.startsWith("dist/captions/")))await directory(join6(root,"dist/captions"));for(const[path,contents]of files){await write(join6(root,path),contents,true);await chmod2(join6(root,path),path.endsWith("entry.js")?320:256);hashes[path]=sha256(contents)}return hashes}async function stage(ledger,release,origin){const id=randomUUID3(),root=await directory(join7(ledger.root,"slots",id));const bundled=await embeddedRuntime(release.descriptor.version);if(bundled&&(bundled.component.byteSize!==release.package.byteSize||bundled.component.sha512!==release.package.sha512))fail("BUNDLED_COMPONENT_RELEASE_MISMATCH");if("source"in release.package&&!bundled)fail("BUNDLED_VERSION_UNAVAILABLE");const bytes=bundled?.bytes??("url"in release.package?await asset(release.package,origin):fail("BUNDLED_VERSION_UNAVAILABLE")),files=await unpack(bytes,root,release.descriptor.version);const slot={id,files,descriptor:release.descriptor,toolsConfigPath:null};await probe(root,slot.descriptor);return slot}async function managedTools(release,origin,stateDirectory,selectionId,cpuSpeech){if(!release.tools)return null;const result={};for(const name of["ffmpeg","ffprobe"]){const a=release.tools[name],dir=await directory(join7(stateDirectory,"tools",a.sha256)),path2=join7(dir,name+(process.platform==="win32"?".exe":""));try{if(sha256(await read(path2,256*1024*1024))!==a.sha256)fail("TOOL_INTEGRITY_INVALID")}catch(e){if(e.code!=="ENOENT")throw e;const bytes=await asset(a,origin);if(sha256(bytes)!==a.sha256)fail("TOOL_INTEGRITY_INVALID");await write(path2,bytes,true);await chmod3(path2,320)}result[name]={path:path2,digest:a.sha256}}const selection={mode:"MANAGED",ffmpeg:result.ffmpeg,ffprobe:result.ffprobe,...cpuSpeech?{cpuSpeech}:{}};const path=join7(await directory(join7(stateDirectory,"tool-selections")),selectionId+".json");await write(path,JSON.stringify(selection));return path}async function selectedTools(release,origin,state,slotId,cloudConfig,previousSelection,explicit){const preference=await toolPreference(previousSelection,cloudConfig,explicit);if(preference.mode==="INSTALLED"){const path=join7(await directory(join7(state,"tool-selections")),slotId+".json");const selection={...preference};delete selection.captionAssetsDirectory;await write(path,JSON.stringify(selection),true);return path}if(preference.mode==="MANAGED"&&preference.reuseMedia){const media=await verifyManagedMedia(previousSelection,preference.reuseMedia);const path=join7(await directory(join7(state,"tool-selections")),slotId+".json");await write(path,JSON.stringify({...media,...preference.cpuSpeech?{cpuSpeech:preference.cpuSpeech}:{}}),true);return path}if(explicit?.mode==="MANAGED"&&!release.tools)fail("MANAGED_TOOLS_UNAVAILABLE");return await managedTools(release,origin,state,slotId,preference.cpuSpeech)??previousSelection}import{lstat as lstat2,opendir}from"node:fs/promises";import{join as join8}from"node:path";async function containsLibraryFiles(root){let visited=0;async function walk(path,depth){if(depth>8||++visited>1e4)fail("NATIVE_RECOVERY_REQUIRED");const info=await lstat2(path);if(info.isFile()){await privateAccess(path,"file");return true}if(!info.isDirectory()||info.isSymbolicLink())fail("NATIVE_RECOVERY_REQUIRED");await privateAccess(path,"directory");const directory2=await opendir(path,{bufferSize:16});for await(const entry of directory2)if(await walk(join8(path,entry.name),depth+1))return true;return false}const library=join8(root,"library");try{await lstat2(library)}catch(error){if(error.code==="ENOENT")return false;throw error}try{return await walk(library,0)}catch(error){if(error.code==="ENOENT")fail("NATIVE_RECOVERY_REQUIRED");throw error}}async function assertLibraryCompatible(configuration,root,slot){let configured=false;if(configuration.cloudConfigFile){try{const value=JSON.parse((await read(configuration.cloudConfigFile,32768)).toString());if(!value||typeof value!=="object"||Array.isArray(value))fail("NATIVE_RECOVERY_REQUIRED");const capabilities=value.processorCapabilities;if(capabilities!==void 0&&!Array.isArray(capabilities))fail("NATIVE_RECOVERY_REQUIRED");configured=Array.isArray(capabilities)&&capabilities.some(kind=>kind==="LOCAL_MEDIA_INSPECT"||kind==="LOCAL_MEDIA_PUBLISH")}catch(error){if(error instanceof SyntaxError)fail("NATIVE_RECOVERY_REQUIRED");throw error}}if(!configured&&!await containsLibraryFiles(configuration.stateDirectory))return;if(!await probeLocalLibrary(root,slot))fail("NATIVE_RECOVERY_REQUIRED")}var configurationSchema=z5.strictObject({stateDirectory:z5.string().min(1).max(4096),catalogueUrl:z5.string().url().nullable().default(null),publicKeyFile:z5.string().min(1).max(4096).nullable().default(null),cloudConfigFile:z5.string().nullable().default(null),notifications:z5.boolean().default(true),rejectedVersions:z5.array(LocalRuntimeDescriptorSchema.shape.version).max(64).default([])}).refine(c=>!!c.catalogueUrl===!!c.publicKeyFile,"Release channel requires URL and key together");var LocalInstallationManager=class _LocalInstallationManager{constructor(ledger){this.ledger=ledger}ledger;static async open(root){return new _LocalInstallationManager(await InstallationLedger.open(root))}static async openExisting(root){const ledger=await InstallationLedger.openExisting(root);return ledger?new _LocalInstallationManager(ledger):null}async configure(raw,options={}){const c=configurationSchema.parse(raw);c.stateDirectory=await directory(c.stateDirectory);await write(join9(this.ledger.root,"configuration.json"),canonicalLocalJson(c),options.ifAbsent);return{configured:true}}async configuration(){const value=await optional(join9(this.ledger.root,"configuration.json"));if(!value)fail("CONFIGURATION_REQUIRED");return configurationSchema.parse(value)}async status(){const s=(await this.ledger.current()).value;let c;try{c=await this.configuration()}catch(error){if(error instanceof Error&&error.message.includes("CONFIGURATION_REQUIRED"))return{protocol:"NVS_LOCAL_INSTALLATION_STATUS_V1",revision:s.revision,activeVersion:s.active?.descriptor.version??null,running:null,phase:s.transition?.phase??"IDLE",nextActions:[{surface:"CLI",operation:"local.configure",availability:"AVAILABLE",reason:"INSTALL_REQUIRED"}]};throw error}let running=null;try{running=await(await ownerClient(c.stateDirectory)).status()}catch{}return{protocol:"NVS_LOCAL_INSTALLATION_STATUS_V1",revision:s.revision,activeVersion:s.active?.descriptor.version??null,entryPath:s.active?join9(this.ledger.slotPath(s.active),"dist/entry.js"):null,installOwner:"MANAGED",phase:s.transition?.phase??"IDLE",running,nextActions:[{surface:"CLI",operation:s.transition?"local.update.reconcile":s.active?"local.start":"local.install",availability:"AVAILABLE",reason:s.transition?"RECOVERY_REQUIRED":s.active?"READY":"INSTALL_REQUIRED"}]}}async reject(version){LocalRuntimeDescriptorSchema.shape.version.parse(version);const c=await this.configuration();await this.configure({...c,rejectedVersions:[...new Set([...c.rejectedVersions,version])]});return{rejected:true,version,selectedVersion:(await this.ledger.current()).value.active?.descriptor.version??null}}async check(){const c=await this.configuration();if(!c.catalogueUrl)return{installation:await this.status(),channel:"UNCONFIGURED",available:[],notifications:c.notifications,rejectedVersions:c.rejectedVersions};const v=await catalogue(c);return{installation:await this.status(),catalogueFingerprint:v.fingerprint,available:v.signed.catalogue.releases.filter(r=>r.descriptor.platform.os===process.platform&&r.descriptor.platform.architecture===process.arch).map(r=>r.descriptor),notifications:c.notifications,rejectedVersions:c.rejectedVersions}}prepare(version,choice){return prepareInstallation(this,version,choice)}prepareBundled(version,choice){return prepareInstallation(this,version,choice,true)}async plan(id){if(!z5.uuid().safeParse(id).success)fail("PLAN_INVALID");const p=LocalUpdatePlanSchema.parse(JSON.parse((await read(join9(this.ledger.root,"plans",id+".json"))).toString()));const{fingerprint,...body}=p;if(sha256(canonicalLocalJson(body))!==fingerprint)fail("PLAN_CHANGED");return p}async transition(s,phase,patch={}){if(!s.transition)fail("TRANSITION_REQUIRED");return this.ledger.commit(s,{active:s.active,transition:{...s.transition,...patch,phase}})}async apply(id,approval){const plan=await this.plan(id),c=await this.configuration();if(approval!==plan.fingerprint)fail("USER_APPROVAL_REQUIRED");const source=await approvedSource(c,plan);let s=(await this.ledger.current()).value;if(s.revision!==plan.installationRevision||s.transition)fail("REVISION_CONFLICT");if(plan.runtimeRevision!==null){const i=await(await ownerClient(c.stateDirectory)).inventory();if(i.runtimeRevision!==plan.runtimeRevision||i.pendingRenderers.some(d=>!supportedRenderer(plan.release.descriptor,d)))fail("REVISION_CONFLICT")}if(plan.runtimeRevision===null){if(!await socketAbsent(c.stateDirectory))fail("REVISION_CONFLICT");await assertNoStoppedJournal(c.stateDirectory)}s=await this.ledger.commit(s,{active:s.active,transition:{id:randomUUID4(),planId:id,fingerprint:approval,phase:"STAGING",previous:s.active,candidate:null,backupPath:null,failedPhase:null}});try{let candidate=await stage(this.ledger,plan.release,source.origin);candidate=await stageResources(this.ledger,candidate,s.active,plan,source.origin);await assertLibraryCompatible(c,this.ledger.slotPath(candidate),candidate);const tools=await selectedTools(plan.release,source.origin,c.stateDirectory,candidate.id,c.cloudConfigFile,s.active?.toolsConfigPath??null,plan.toolSelection);candidate={...candidate,toolsConfigPath:tools};if(tools)await probeTools(this.ledger.slotPath(candidate),c.stateDirectory,tools);s=await this.transition(s,"STAGED",{candidate});if(plan.runtimeRevision!==null){const client=await ownerClient(c.stateDirectory),i=await client.inventory();if(i.runtimeRevision!==plan.runtimeRevision||i.pendingRenderers.some(d=>!supportedRenderer(candidate.descriptor,d)))fail("REVISION_CONFLICT");await assertPendingCompatible(i,candidate.descriptor,s.active?.toolsConfigPath??null,tools,c.cloudConfigFile);await assertLibraryCompatible(c,this.ledger.slotPath(candidate),candidate);s=await this.transition(s,"DRAINING");const result=await client.call({operation:"runtime.stop",expectedRuntimeRevision:plan.runtimeRevision});if(!result||typeof result!=="object"||!("backupPath"in result)||typeof result.backupPath!=="string")fail("JOURNAL_BACKUP_REQUIRED");await verifyBackup(result.backupPath,c.stateDirectory);s=await this.transition(s,"ACTIVATING",{backupPath:result.backupPath});await waitStopped(c.stateDirectory);await assertPendingCompatible("inventory"in result?result.inventory:null,candidate.descriptor,s.active?.toolsConfigPath??null,tools,c.cloudConfigFile)}else{if(!await socketAbsent(c.stateDirectory))fail("REVISION_CONFLICT");await assertNoStoppedJournal(c.stateDirectory);s=await this.transition(s,"ACTIVATING")}await assertLibraryCompatible(c,this.ledger.slotPath(candidate),candidate);s=await this.ledger.commit(s,{active:candidate,transition:{...s.transition,phase:"VERIFYING"}});await this.startSlot(candidate,c);s=await this.ledger.commit(s,{active:candidate,transition:null});await this.reconnect();return{activated:true,revision:s.revision,version:candidate.descriptor.version}}catch(error){const actual=(await this.ledger.current()).value;if(actual.transition?.planId===id)await this.transition(actual,"ROLLBACK_REQUIRED",{failedPhase:actual.transition.phase});throw error}}async startSlot(slot,c){await assertLibraryCompatible(c,this.ledger.slotPath(slot),slot);return launch(this.ledger.slotPath(slot),slot,c.stateDirectory,c.cloudConfigFile??void 0,slot.toolsConfigPath??void 0)}async start(){const s=(await this.ledger.current()).value;if(s.transition)fail("ACTIVATION_IN_PROGRESS");if(!s.active)fail("INSTALL_REQUIRED");const c=await this.configuration(),inventory=await this.startSlot(s.active,c);const clients=await this.reconnect();let updateNotice={status:"DISABLED"};if(c.notifications&&c.catalogueUrl){try{const v=await catalogue(c,AbortSignal.timeout(1500));updateNotice={status:"CHECKED",versions:v.signed.catalogue.releases.filter(r=>r.descriptor.platform.os===process.platform&&r.descriptor.platform.architecture===process.arch&&newerVersion(r.descriptor.version,s.active.descriptor.version)&&!c.rejectedVersions.includes(r.descriptor.version)).map(r=>r.descriptor.version)}}catch{updateNotice={status:"UNAVAILABLE"}}}return{...inventory,clients,updateNotice}}async stop(){const c=await this.configuration(),client=await ownerClient(c.stateDirectory),i=await client.inventory();const result=await client.call({operation:"runtime.stop",expectedRuntimeRevision:i.runtimeRevision});await waitStopped(c.stateDirectory);return result}async reconcile(id,approval){const s=(await this.ledger.current()).value,c=await this.configuration();if(!s.transition||s.transition.planId!==id||s.transition.fingerprint!==approval)fail("USER_APPROVAL_REQUIRED");if(s.active?.id===s.transition.previous?.id&&["STAGING","STAGED"].includes(s.transition.failedPhase??s.transition.phase)){const next2=await this.ledger.commit(s,{active:s.transition.previous,transition:null});return{rolledBack:true,revision:next2.revision,version:next2.active?.descriptor.version??null}}const candidate=s.transition.candidate;if(candidate){await assertLibraryCompatible(c,this.ledger.slotPath(candidate),candidate);try{const i=await runningInventory(await ownerClient(c.stateDirectory),this.ledger.slotPath(candidate),candidate);if(canonicalLocalJson(i.descriptor)===canonicalLocalJson(candidate.descriptor)){await verifySlot(this.ledger.slotPath(candidate),candidate);const next2=await this.ledger.commit(s,{active:candidate,transition:null});await this.reconnect();return{recovered:true,revision:next2.revision,version:candidate.descriptor.version}}}catch{}}const previous=s.transition.previous;if(previous)await assertLibraryCompatible(c,this.ledger.slotPath(previous),previous);await waitStopped(c.stateDirectory);const next=await this.ledger.commit(s,{active:previous,transition:null});if(previous)await this.startSlot(previous,c);await this.reconnect();return{rolledBack:true,revision:next.revision,version:previous?.descriptor.version??null}}grant(raw,output){return grant(this,raw,output)}reconnect(){return reconnect(this)}};export{toolPreference,captureInstalledTools,embeddedRuntime,runtimeEnvironment,verifySlot,probeTenantMediaValidation,probeTenantMediaProcessing,probeLocalLibrary,probeTenantComposition,probeTenantSpeech,probeTenantTranscription,probeTenantQwenGeneration,ownerClient,waitStopped,socketAbsent,LocalInstallationManager};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{callerOriginMatches,workspaceCaller}from"./chunk-RDIMORUT.js";import{renderConnection}from"./chunk-ROBBF33U.js";import"./chunk-S74X4KIC.js";import"./chunk-HY7NXJYX.js";import"./chunk-SV3NF7GO.js";import{LocalInstallationManager,ownerClient,probeLocalLibrary,probeTenantComposition,probeTenantMediaProcessing,probeTenantMediaValidation,probeTenantQwenGeneration,probeTenantSpeech,probeTenantTranscription,verifySlot}from"./chunk-ZRSYOFMX.js";import{DesktopDeviceRecords}from"./chunk-VD3OQ743.js";import"./chunk-U7ECMITP.js";import"./chunk-3AVC742O.js";import"./chunk-FU3524Z6.js";import"./chunk-6LU6GJKW.js";import{LocalClientError,read}from"./chunk-KB2GVAN7.js";import"./chunk-77IAHNM2.js";import"./chunk-2UYKJ6YN.js";import{DeviceDiscoveryInputSchema}from"./chunk-5DY7LSZZ.js";import"./chunk-TLPI6P7L.js";import{LocalDeviceTransportConfigurationSchema,LocalToolSelectionSchema}from"./chunk-PDQYFIQQ.js";import"./chunk-6UYY5KHI.js";import"./chunk-PUNG4ND7.js";import{NativeStudioSdkError}from"./chunk-HTUTYIRU.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"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"&&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 +0,0 @@
|
|
|
1
|
-
import{profileHttpOrigin}from"./chunk-HY7NXJYX.js";import"./chunk-SV3NF7GO.js";import"./chunk-FU3524Z6.js";import"./chunk-KB2GVAN7.js";import"./chunk-TLPI6P7L.js";import"./chunk-6UYY5KHI.js";import"./chunk-PUNG4ND7.js";import"./chunk-HTUTYIRU.js";export{profileHttpOrigin};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{prepareInstalledCpuSpeech}from"./chunk-2AI3WF2O.js";import{connectDevice,generateDeviceKey}from"./chunk-RK2P3UVF.js";import{LocalInstallationManager,captureInstalledTools,ownerClient}from"./chunk-ZRSYOFMX.js";import{NativeStudioLocalDeviceClient}from"./chunk-U7ECMITP.js";import{readCredential,readInput}from"./chunk-6LU6GJKW.js";import{LocalClientError}from"./chunk-KB2GVAN7.js";import{localCliVersion}from"./chunk-2UYKJ6YN.js";import{NativeStudioAgentClient}from"./chunk-5DY7LSZZ.js";import"./chunk-TLPI6P7L.js";import{EnrollLocalDeviceSchema,LocalAgentGrantSchema,LocalManagementCommandSchema,RevokeLocalDeviceSchema,StartLocalFinalRenderSchema,StartLocalPreviewSchema,canonicalLocalJson,localAgentMediaProposal,localAgentMediaSnapshot,localAgentSnapshotFromContext}from"./chunk-PDQYFIQQ.js";import"./chunk-6UYY5KHI.js";import{NativeStudioSdkError}from"./chunk-HTUTYIRU.js";import{homedir as homedir2}from"node:os";import{join as join2,resolve as resolve2}from"node:path";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-CTBW7DAI.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-LHFLPVAB.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","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 manager=await LocalInstallationManager.open(resolve2(options.get("--home")??process.env.NATIVESTUDIO_CLIENT_HOME??join2(homedir2(),".nativestudio","client")));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",error:{code:known,outcome:e instanceof NativeStudioSdkError?e.outcome:mutation&&!["USER_APPROVAL_REQUIRED","PLAN_CHANGED","REVISION_CONFLICT","INSTALL_REQUIRED","CONFIGURATION_REQUIRED"].includes(known)?"UNKNOWN":"NO_WRITE"}}}}}export{runLocalCli};
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import{loginLink,openLoginBrowser}from"./chunk-VDNNFVTZ.js";import{NativeStudioAccountClient,accountError,accountServerOrigin,clientHome,connectionStatus,defaultConnection,readAccount,requireAccount,saveAccount,withAccountLock}from"./chunk-SV3NF7GO.js";import"./chunk-FU3524Z6.js";import{readCredential,readInput}from"./chunk-6LU6GJKW.js";import{write}from"./chunk-KB2GVAN7.js";import"./chunk-TLPI6P7L.js";import"./chunk-6UYY5KHI.js";import"./chunk-PUNG4ND7.js";import{NativeStudioSdkError}from"./chunk-HTUTYIRU.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-6UH7ZFAC.js")).runConnect(argv,environment);if(argv[0]==="login")return await runAccountLogin(argv,environment);if(argv[0]==="render")return await(await import("./render-main-VTM6WGFP.js")).renderCommand(argv.slice(1),environment);if(argv[0]==="devices")return await(await import("./devices-main-VV2VYU4T.js")).devicesCommand(argv.slice(1),environment,stdin);if(argv[0]==="import")return await(await import("./source-import-KKV2UWJO.js")).importSourceCommand(argv.slice(1),environment,stdin);if(AccountCommands.has(argv[0]??"")){const business=await(await import("./workspace-main-Y7ZVBRJJ.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-HC6TI7HB.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","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 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 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 enroll/prove/connect an execution device using the external Agent's existing MCP session; discover the separate SKILL URL with nvs skill or workspace_caller.skill"],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{NativeStudioAgentClient,sdkOperations,sdkMcpTools,sdkCarrierDifferences,assertCarrierCoverage}=await import("./src-OIY5TBQT.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)}await defaultConnection(options,environment,true);if(!options.has("--input")||!options.has("--tenant")||(options.has("--profile")?options.has("--origin")||options.has("--mcp-url")||options.has("--token-file")||options.has("--token-env"):options.has("--origin")===options.has("--mcp-url")))throw Error();const key=name;const 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 input=await readInput(options.get("--input"),stdin);const profile=options.has("--profile")?await(await import("./oauth-HC6TI7HB.js")).profileAuthorization(options.get("--profile")):null;const authorization=profile?.authorization??await readCredential(options,environment);const tenantId=options.get("--tenant");let output;const profileHttp=profile&&(transport==="http"||!transport&&sdkMcpTools[key]===null);if(!profileHttp&&(profile||options.has("--mcp-url"))){const{connectRemoteMcp}=await import("./mcp-EXQ5UAHB.js");const connection=await connectRemoteMcp(profile?.resource??options.get("--mcp-url"),authorization,tenantId);try{output=await connection.studio.call(key,input)}finally{await connection.close()}}else{const studio=new NativeStudioAgentClient({tenantId,baseUrl:profileHttp?await(await import("./http-profile-NIQDCFPU.js")).profileHttpOrigin(options.get("--profile"),profile.resource):options.get("--origin"),authorization:()=>authorization});output=await studio.call(key,input)}const status=output?.semanticStatus;return{exitCode:status?exits[status]??1:0,output}}catch(error){const e=error instanceof NativeStudioSdkError?error:null;const accountRecovery={ACCOUNT_LOGIN_OUTCOME_UNKNOWN:["Start a fresh nvs login --server <Studio-origin>; never replay the old exchange."],ACCOUNT_LOGOUT_OUTCOME_UNKNOWN:["Retry nvs logout explicitly; local account use remains locked."],ACCOUNT_LOGIN_REQUIRED:["nvs login --server <Studio-origin>"],ACCOUNT_SESSION_EXPIRED_OR_REVOKED:["nvs login --server <Studio-origin>"],WORKSPACE_SELECTION_REQUIRED:["nvs workspaces","nvs workspace --id <workspace-id>"],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/project before creating a fresh connection."]};return{exitCode:e?exits[e.semanticStatus]??1:2,output:{semanticStatus:e?.semanticStatus??"INVALID_INPUT",error:{code:e?.code??"INVALID_INPUT",outcome:e?.outcome??"NO_WRITE",...e?.issues.length?{issues:e.issues}:{}},...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};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{connectRemoteMcp}from"./chunk-77IAHNM2.js";import"./chunk-2UYKJ6YN.js";import"./chunk-5DY7LSZZ.js";import"./chunk-TLPI6P7L.js";import"./chunk-PDQYFIQQ.js";import"./chunk-6UYY5KHI.js";import"./chunk-PUNG4ND7.js";import"./chunk-HTUTYIRU.js";export{connectRemoteMcp};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{profileAuthorization,runOAuthCommand}from"./chunk-3AVC742O.js";import"./chunk-FU3524Z6.js";import"./chunk-6LU6GJKW.js";import"./chunk-KB2GVAN7.js";import"./chunk-PUNG4ND7.js";import"./chunk-HTUTYIRU.js";export{profileAuthorization,runOAuthCommand};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{CapabilityDescribeSchema,CapabilityGroupsSchema,DeviceDiscoveryInputSchema,DeviceRenderAdmissionSchema,DeviceRenderDownloadSchema,DeviceRenderIntentSchema,DeviceRenderReadSchema,NativeStudioAgentClient,NativeStudioDeviceRenders,NativeStudioMcpClient,NativeStudioNavigationClient,NativeStudioNavigationFacade,NativeStudioRuntimeAuthorityClient,NavigationGroupIdSchema,NavigationGroups,NavigationProfile,NavigationProfileKey,NavigationToolNames,PreparedDeviceRenderSchema,assertCarrierCoverage,navigationGroup,queryPages,sdkCarrierDifferences,sdkImageMediaTools,sdkMcpTools,sdkOperations,waitForOperation}from"./chunk-5DY7LSZZ.js";import"./chunk-TLPI6P7L.js";import{FinalRenderViewSchema,LocalLibraryAdmissionSchema,LocalLibraryCommandQuerySchema,LocalLibraryCommandSchema,LocalLibraryCommandStatusSchema,LocalLibraryProjectionPageSchema,LocalLibraryProjectionQuerySchema,LocalLibraryReferenceSchema,ProjectDeviceListSchema,RoughCutViewSchema,TenantRenderMediaTicketSchema,WorkspaceDeviceListInputSchema,WorkspaceDeviceListSchema}from"./chunk-PDQYFIQQ.js";import"./chunk-6UYY5KHI.js";import{NativeStudioSdkError,sdkInputError}from"./chunk-HTUTYIRU.js";export{CapabilityDescribeSchema,CapabilityGroupsSchema,DeviceDiscoveryInputSchema,DeviceRenderAdmissionSchema,DeviceRenderDownloadSchema,DeviceRenderIntentSchema,DeviceRenderReadSchema,FinalRenderViewSchema,LocalLibraryAdmissionSchema,LocalLibraryCommandQuerySchema,LocalLibraryCommandSchema,LocalLibraryCommandStatusSchema,LocalLibraryProjectionPageSchema,LocalLibraryProjectionQuerySchema,LocalLibraryReferenceSchema,NativeStudioAgentClient,NativeStudioDeviceRenders,NativeStudioMcpClient,NativeStudioNavigationClient,NativeStudioNavigationFacade,NativeStudioRuntimeAuthorityClient,NativeStudioSdkError,NavigationGroupIdSchema,NavigationGroups,NavigationProfile,NavigationProfileKey,NavigationToolNames,PreparedDeviceRenderSchema,ProjectDeviceListSchema,RoughCutViewSchema,TenantRenderMediaTicketSchema,WorkspaceDeviceListInputSchema,WorkspaceDeviceListSchema,assertCarrierCoverage,navigationGroup,queryPages,sdkCarrierDifferences,sdkImageMediaTools,sdkInputError,sdkMcpTools,sdkOperations,waitForOperation};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{workspaceCommand,workspaceProject}from"./chunk-S74X4KIC.js";import"./chunk-SV3NF7GO.js";import"./chunk-3AVC742O.js";import"./chunk-FU3524Z6.js";import"./chunk-6LU6GJKW.js";import"./chunk-KB2GVAN7.js";import"./chunk-77IAHNM2.js";import"./chunk-2UYKJ6YN.js";import"./chunk-5DY7LSZZ.js";import"./chunk-TLPI6P7L.js";import"./chunk-PDQYFIQQ.js";import"./chunk-6UYY5KHI.js";import"./chunk-PUNG4ND7.js";import"./chunk-HTUTYIRU.js";export{workspaceCommand,workspaceProject};
|
|
@@ -1,90 +0,0 @@
|
|
|
1
|
-
$ErrorActionPreference = 'Stop'
|
|
2
|
-
[Console]::InputEncoding = New-Object Text.UTF8Encoding($false)
|
|
3
|
-
[Console]::OutputEncoding = New-Object Text.UTF8Encoding($false)
|
|
4
|
-
try {
|
|
5
|
-
$raw = [Console]::In.ReadToEnd()
|
|
6
|
-
if ($raw.Length -gt 32768) { throw 'INPUT_LIMIT' }
|
|
7
|
-
$request = $raw | ConvertFrom-Json
|
|
8
|
-
$names = @('Bootstrap.ps1','NativeMain.cs','PrivateAccess.cs','PipeBridge.cs','JobNative.cs','JobRunner.cs')
|
|
9
|
-
$directory = [IO.Path]::GetFullPath($request.directory)
|
|
10
|
-
$hash = [Security.Cryptography.SHA256]::Create()
|
|
11
|
-
foreach ($name in $names) {
|
|
12
|
-
$file = Join-Path $directory $name
|
|
13
|
-
if (([IO.File]::GetAttributes($file) -band [IO.FileAttributes]::ReparsePoint) -ne 0) { throw 'REPARSE' }
|
|
14
|
-
$prefix = [Text.Encoding]::UTF8.GetBytes($name + "`n")
|
|
15
|
-
[void]$hash.TransformBlock($prefix,0,$prefix.Length,$prefix,0)
|
|
16
|
-
$bytes = [IO.File]::ReadAllBytes($file)
|
|
17
|
-
if ($bytes.Length -gt 262144) { throw 'SOURCE_LIMIT' }
|
|
18
|
-
[void]$hash.TransformBlock($bytes,0,$bytes.Length,$bytes,0)
|
|
19
|
-
}
|
|
20
|
-
[void]$hash.TransformFinalBlock([byte[]]@(),0,0)
|
|
21
|
-
$digest = ([BitConverter]::ToString($hash.Hash)).Replace('-','').ToLowerInvariant()
|
|
22
|
-
if ($digest -ne $request.sourceDigest) { throw 'SOURCE_CHANGED' }
|
|
23
|
-
$sid = [Security.Principal.WindowsIdentity]::GetCurrent().User
|
|
24
|
-
function Check-Private([string]$path) {
|
|
25
|
-
$item = Get-Item -LiteralPath $path -Force
|
|
26
|
-
if (($item.Attributes -band [IO.FileAttributes]::ReparsePoint) -ne 0) { throw 'REPARSE' }
|
|
27
|
-
$acl = $item.GetAccessControl()
|
|
28
|
-
if ($acl.GetOwner([Security.Principal.SecurityIdentifier]).Value -ne $sid.Value) { throw 'OWNER' }
|
|
29
|
-
foreach ($rule in $acl.GetAccessRules($true,$true,[Security.Principal.SecurityIdentifier])) {
|
|
30
|
-
if ($rule.AccessControlType -eq [Security.AccessControl.AccessControlType]::Allow -and
|
|
31
|
-
$rule.IdentityReference.Value -notin @($sid.Value,'S-1-5-18','S-1-5-32-544')) { throw 'ACL' }
|
|
32
|
-
}
|
|
33
|
-
}
|
|
34
|
-
function Private-Directory([string]$path) {
|
|
35
|
-
if ([IO.Directory]::Exists($path)) { Check-Private $path; return }
|
|
36
|
-
$acl = New-Object Security.AccessControl.DirectorySecurity
|
|
37
|
-
$acl.SetOwner($sid)
|
|
38
|
-
$acl.SetAccessRuleProtection($true,$false)
|
|
39
|
-
$rule = New-Object Security.AccessControl.FileSystemAccessRule($sid,'FullControl','ContainerInherit,ObjectInherit','None','Allow')
|
|
40
|
-
$acl.AddAccessRule($rule)
|
|
41
|
-
[void][IO.Directory]::CreateDirectory($path,$acl)
|
|
42
|
-
Check-Private $path
|
|
43
|
-
}
|
|
44
|
-
$base = Join-Path ([Environment]::GetFolderPath('LocalApplicationData')) 'NativeStudio-platform'
|
|
45
|
-
Private-Directory $base
|
|
46
|
-
$cache = Join-Path $base $digest
|
|
47
|
-
Private-Directory $cache
|
|
48
|
-
$mutex = New-Object Threading.Mutex($false,('Local\NVS-compile-' + $sid.Value + '-' + $digest))
|
|
49
|
-
$locked = $false
|
|
50
|
-
try {
|
|
51
|
-
try { $locked = $mutex.WaitOne(10000) } catch [Threading.AbandonedMutexException] { $locked = $true }
|
|
52
|
-
if (-not $locked) { throw 'BUSY' }
|
|
53
|
-
$record = Join-Path $cache 'helper.json'
|
|
54
|
-
if ([IO.File]::Exists($record)) {
|
|
55
|
-
Check-Private $record
|
|
56
|
-
$value = [IO.File]::ReadAllText($record) | ConvertFrom-Json
|
|
57
|
-
if ($value.sourceDigest -ne $digest -or $value.file -notmatch '^helper-[0-9a-f-]{36}\.exe$') { throw 'CACHE' }
|
|
58
|
-
$executable = Join-Path $cache $value.file
|
|
59
|
-
Check-Private $executable
|
|
60
|
-
$actual = (Get-FileHash -LiteralPath $executable -Algorithm SHA256).Hash.ToLowerInvariant()
|
|
61
|
-
if ($actual -ne $value.sha256) { throw 'CACHE_CHANGED' }
|
|
62
|
-
} else {
|
|
63
|
-
$file = 'helper-' + [Guid]::NewGuid().ToString() + '.exe'
|
|
64
|
-
$executable = Join-Path $cache $file
|
|
65
|
-
$sources = @($names | Where-Object { $_.EndsWith('.cs') } | ForEach-Object { Join-Path $directory $_ })
|
|
66
|
-
$compiler = New-Object CodeDom.Compiler.CompilerParameters
|
|
67
|
-
$compiler.GenerateExecutable = $true
|
|
68
|
-
$compiler.OutputAssembly = $executable
|
|
69
|
-
$compiler.CompilerOptions = '/platform:x64 /optimize+ /langversion:5'
|
|
70
|
-
$compiler.ReferencedAssemblies.AddRange(@('System.dll','System.Core.dll','System.Web.dll','System.Web.Extensions.dll','System.Security.dll'))
|
|
71
|
-
Add-Type -Path $sources -CompilerParameters $compiler
|
|
72
|
-
Check-Private $executable
|
|
73
|
-
$actual = (Get-FileHash -LiteralPath $executable -Algorithm SHA256).Hash.ToLowerInvariant()
|
|
74
|
-
$value = @{ sourceDigest=$digest; file=$file; sha256=$actual }
|
|
75
|
-
$temporary = Join-Path $cache ([Guid]::NewGuid().ToString() + '.json')
|
|
76
|
-
$bytes = [Text.Encoding]::UTF8.GetBytes(($value | ConvertTo-Json -Compress))
|
|
77
|
-
$stream = New-Object IO.FileStream($temporary,[IO.FileMode]::CreateNew,[IO.FileAccess]::Write,[IO.FileShare]::None)
|
|
78
|
-
try { $stream.Write($bytes,0,$bytes.Length); $stream.Flush($true) } finally { $stream.Dispose() }
|
|
79
|
-
[IO.File]::Move($temporary,$record)
|
|
80
|
-
Check-Private $record
|
|
81
|
-
}
|
|
82
|
-
@{ path=$executable; sha256=$actual; sourceDigest=$digest } | ConvertTo-Json -Compress
|
|
83
|
-
} finally {
|
|
84
|
-
if ($locked) { $mutex.ReleaseMutex() }
|
|
85
|
-
$mutex.Dispose()
|
|
86
|
-
}
|
|
87
|
-
} catch {
|
|
88
|
-
[Console]::Error.WriteLine('WINDOWS_HELPER_UNAVAILABLE')
|
|
89
|
-
exit 1
|
|
90
|
-
}
|