@nativestudio/cli 0.3.0-rc.16 → 0.3.0-rc.17
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/COMPATIBILITY.json +8 -8
- package/components/runtime.json +4 -4
- package/components/runtime.tgz +0 -0
- package/dist/_chunks/{chunk-VLEWCWYF.js → chunk-3KBIDTXT.js} +1 -1
- package/dist/_chunks/{chunk-B7BQERMR.js → chunk-4IFMG2ZS.js} +1 -1
- package/dist/_chunks/chunk-4NJIT52T.js +1 -0
- package/dist/_chunks/{chunk-5LSB6HDP.js → chunk-53EULX5D.js} +1 -1
- package/dist/_chunks/{chunk-RT77PT3A.js → chunk-65X56WAQ.js} +1 -1
- package/dist/_chunks/{chunk-U6ZG2G7W.js → chunk-744IEPTK.js} +1 -1
- package/dist/_chunks/{chunk-EML7OS3I.js → chunk-BR26X3ZF.js} +1 -1
- package/dist/_chunks/chunk-C7CSZFV6.js +1 -0
- package/dist/_chunks/{chunk-JLQCUXCT.js → chunk-GKDGSAI5.js} +1 -1
- package/dist/_chunks/{chunk-SRB5ZFKO.js → chunk-HI5SIUX7.js} +1 -1
- package/dist/_chunks/{chunk-PYUYK3FV.js → chunk-IHTF6VEC.js} +1 -1
- package/dist/_chunks/{chunk-LOYAGAAN.js → chunk-K25YVVTT.js} +1 -1
- package/dist/_chunks/{chunk-BGH3Y5UX.js → chunk-KYNC2BSW.js} +1 -1
- package/dist/_chunks/{chunk-35XQP7RY.js → chunk-ORFGJBJA.js} +1 -1
- package/dist/_chunks/{chunk-MT5XZ67U.js → chunk-SDTAJ7FI.js} +1 -1
- package/dist/_chunks/{chunk-XVQWVJWD.js → chunk-UGOXJEDU.js} +1 -1
- package/dist/_chunks/{device-management-ELAPFWM2.js → device-management-CXSZFF53.js} +1 -1
- package/dist/_chunks/{device-preflight-27RDJVBU.js → device-preflight-6HKPPZ5L.js} +1 -1
- package/dist/_chunks/{devices-inventory-2XEJPPO5.js → devices-inventory-K553HAF3.js} +1 -1
- package/dist/_chunks/{devices-main-UMF3ZBHA.js → devices-main-LBDRDV2M.js} +1 -1
- package/dist/_chunks/host-main-ZMBFHY55.js +1 -0
- package/dist/_chunks/{library-main-L7SY7V7L.js → library-main-RNDPNKYK.js} +1 -1
- package/dist/_chunks/{local-main-7FONRY6F.js → local-main-RC4RM3OB.js} +1 -1
- package/dist/_chunks/{local-mcp-ELFJBJG6.js → local-mcp-LQCQ3WLF.js} +1 -1
- package/dist/_chunks/{main-XWUYQQ32.js → main-CPIMF4PS.js} +2 -2
- package/dist/_chunks/mcp-HQQJCKHS.js +1 -0
- package/dist/_chunks/{observe-entry-3CHBX74Y.js → observe-entry-4GPGZ3NJ.js} +1 -1
- package/dist/_chunks/remote-client-6XHMNMXK.js +1 -0
- package/dist/_chunks/{render-main-ZXYQ7EV5.js → render-main-ATCEBECW.js} +1 -1
- package/dist/_chunks/{source-import-ZWR26CMU.js → source-import-HIL7NW3L.js} +1 -1
- package/dist/_chunks/src-MRFJOTKK.js +1 -0
- package/dist/_chunks/stdio-main-T4ORVLSX.js +1 -0
- package/dist/_chunks/{workspace-main-NYDAQGB4.js → workspace-main-44ECTGHC.js} +1 -1
- package/dist/_types/contracts/device-onboarding.d.ts +12 -6
- package/dist/_types/contracts/device-render.d.ts +12 -6
- package/dist/_types/contracts/federation-event-link-receiver.d.ts +200 -0
- package/dist/_types/contracts/federation-event-link.d.ts +485 -0
- package/dist/_types/contracts/index.d.ts +3 -0
- package/dist/_types/contracts/local-execution/device-inventory.d.ts +12 -6
- package/dist/_types/contracts/mcp-capabilities.d.ts +15 -0
- package/dist/_types/contracts/navigation-context.d.ts +21 -2
- package/dist/_types/contracts/navigation.d.ts +12 -0
- package/dist/entry.js +1 -1
- package/dist/local-management.js +1 -1
- package/dist/local-navigation.js +1 -1
- package/package.json +1 -1
- package/dist/_chunks/chunk-TQIJBUSP.js +0 -1
- package/dist/_chunks/chunk-WAADGZEV.js +0 -1
- package/dist/_chunks/host-main-WYTVTQ4Z.js +0 -1
- package/dist/_chunks/mcp-ACNG635V.js +0 -1
- package/dist/_chunks/remote-client-WIZVKP3O.js +0 -1
- package/dist/_chunks/src-TR4JNPGI.js +0 -1
- package/dist/_chunks/stdio-main-QQLYSRD4.js +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
import{selectedProject}from"./chunk-
|
|
1
|
+
import{selectedProject}from"./chunk-HI5SIUX7.js";import{profileAuthorization}from"./chunk-FX5UVDTH.js";import{connectRemoteMcp}from"./chunk-65X56WAQ.js";import{profileHttpOrigin}from"./chunk-UMCOLDHH.js";import{clientHome,loadConnection,readAccount,requireAccount}from"./chunk-TWC3NXFA.js";import{NativeStudioSdkError}from"./chunk-HTUTYIRU.js";import{z}from"zod";async function resolveCaller(env,explicitProject,workspaceOnly=false){const home=await clientHome(env),account=await readAccount(home);const saved=await loadConnection(env);const assertCurrent=async()=>{const latest=await loadConnection(env),current=await readAccount(home);if(latest?.profile!==saved?.profile||latest?.resource!==saved?.resource||account?.epoch!==current?.epoch||account?.state!==current?.state||account?.principalId!==current?.principalId||account?.workspaceId!==current?.workspaceId||account?.serverOrigin!==current?.serverOrigin)throw new NativeStudioSdkError("FORBIDDEN","BLOCKED","NO_WRITE");if(latest?.exchangeUnresolved)throw new NativeStudioSdkError("OAUTH_OUTCOME_UNKNOWN","BLOCKED","UNKNOWN");if(account&&!saved)requireAccount(current)};if(saved){const auth=await profileAuthorization(saved.profile);if(auth.resource!==saved.resource)throw new NativeStudioSdkError("FORBIDDEN","BLOCKED","NO_WRITE");const projectId=workspaceOnly?void 0:await selectedProject(saved,env,explicitProject);const c=await connectRemoteMcp(saved.resource,auth.authorization,saved.tenantId);try{const caller=await c.studio.call("workspace.caller",{});if(caller.tenantId!==saved.tenantId||account&&(account.principalId!==caller.principalId||account.serverOrigin!==caller.serverOrigin))throw new NativeStudioSdkError("FORBIDDEN","BLOCKED","NO_WRITE");if(projectId){const selected=await c.studio.call("project.get",{projectId});if(selected.project.id!==projectId||selected.project.tenantId!==caller.tenantId)throw new NativeStudioSdkError("FORBIDDEN","BLOCKED","NO_WRITE")}await assertCurrent();return{tenantId:caller.tenantId,principalId:caller.principalId,serverOrigin:caller.serverOrigin,home,projectId,resource:saved.resource,profile:saved.profile,assertCurrent}}finally{await c.close().catch(()=>{})}}if(!account)return null;const human=requireAccount(account);if(!human.workspaceId||!workspaceOnly&&!(explicitProject??human.projectId))throw new NativeStudioSdkError("PROJECT_SELECTION_REQUIRED","BLOCKED","NO_WRITE");return{home,tenantId:human.workspaceId,projectId:workspaceOnly?void 0:z.uuid().parse(explicitProject??human.projectId),principalId:human.principalId,serverOrigin:human.serverOrigin,resource:void 0,profile:void 0,assertCurrent}}async function localCaller(env,explicitProject){const caller=await resolveCaller(env,explicitProject);if(!caller)return null;if(!caller.projectId)throw new NativeStudioSdkError("PROJECT_SELECTION_REQUIRED","BLOCKED","NO_WRITE");return{...caller,projectId:caller.projectId}}function workspaceCaller(env){return resolveCaller(env,void 0,true)}async function callerOriginMatches(origin,caller){if(origin===caller.serverOrigin)return true;if(!caller.resource||!caller.profile)return false;return origin===new URL(caller.resource).origin||origin===await profileHttpOrigin(caller.profile,caller.resource)}export{localCaller,workspaceCaller,callerOriginMatches};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{localCliVersion}from"./chunk-2UYKJ6YN.js";import{NativeStudioMcpClient}from"./chunk-
|
|
1
|
+
import{localCliVersion}from"./chunk-2UYKJ6YN.js";import{NativeStudioMcpClient}from"./chunk-4NJIT52T.js";import{boundedRemoteFetch,secureEndpoint}from"./chunk-KOCUZ3AE.js";import{NativeStudioSdkError}from"./chunk-HTUTYIRU.js";import{Client,StreamableHTTPClientTransport}from"@modelcontextprotocol/client";async function connectRemoteMcp(endpoint,authorization,tenantId,options={}){const url=secureEndpoint(endpoint);const client=new Client({name:"native-studio-remote-cli",version:(await localCliVersion()).version},{versionNegotiation:{mode:"auto"}});const stop=()=>{void client.close().catch(()=>{})};options.signal?.throwIfAborted();options.signal?.addEventListener("abort",stop,{once:true});try{const transport=new StreamableHTTPClientTransport(url,{requestInit:{headers:{authorization}},fetch:boundedRemoteFetch(options.maxJsonBytes??32*1024*1024,options.signal)});await client.connect(transport);return{studio:new NativeStudioMcpClient({tenantId,client,...options.maxJsonBytes?{maxJsonBytes:options.maxJsonBytes}:{}}),close:()=>{options.signal?.removeEventListener("abort",stop);return client.close()}}}catch{options.signal?.removeEventListener("abort",stop);await client.close();throw new NativeStudioSdkError("TRANSPORT_UNAVAILABLE","INTERNAL_OPERATIONAL_FAILURE","NO_WRITE")}}export{connectRemoteMcp};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LocalCompositionBrowserSelectionSchema,LocalDoctorReportSchema,LocalManagementInventorySchema,LocalRuntimeComponentSchema,LocalRuntimeDescriptorSchema,LocalToolChoiceSchema,LocalToolSelectionSchema,LocalUpdatePlanSchema,NativeStudioLocalRuntimeClient,RuntimeCaptionAssets,asset,catalogue,newerVersion,select}from"./chunk-VLEWCWYF.js";import{canonicalLocalJson,importedNormalizationValidationProfile,localLibraryProfile,tenantRenderValidationProfile,whisperCppRecognitionProfile}from"./chunk-WAADGZEV.js";import{assertExecutable,directory,entries,fail,localSocketPath,optional,privateAccess,read,sha256,sha512,verifyBackup,write}from"./chunk-RUPH3HZ2.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",...["helper.exe","helper.json"].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,"f7f26c5df6c4b248b28f83baeea2e165d55f2c5456101cd091e4a30c5f10bfbf");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-72BEXD7E.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
|
+
import{LocalCompositionBrowserSelectionSchema,LocalDoctorReportSchema,LocalManagementInventorySchema,LocalRuntimeComponentSchema,LocalRuntimeDescriptorSchema,LocalToolChoiceSchema,LocalToolSelectionSchema,LocalUpdatePlanSchema,NativeStudioLocalRuntimeClient,RuntimeCaptionAssets,asset,catalogue,newerVersion,select}from"./chunk-3KBIDTXT.js";import{canonicalLocalJson,importedNormalizationValidationProfile,localLibraryProfile,tenantRenderValidationProfile,whisperCppRecognitionProfile}from"./chunk-C7CSZFV6.js";import{assertExecutable,directory,entries,fail,localSocketPath,optional,privateAccess,read,sha256,sha512,verifyBackup,write}from"./chunk-RUPH3HZ2.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",...["helper.exe","helper.json"].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,"25202d8514a9ba89b32013ddc716b808b19026d707f7e93e987866ef6a065ba9");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-72BEXD7E.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 +1 @@
|
|
|
1
|
-
import{readCredential}from"./chunk-U5FT4VBR.js";import{NativeStudioAgentClient}from"./chunk-
|
|
1
|
+
import{readCredential}from"./chunk-U5FT4VBR.js";import{NativeStudioAgentClient}from"./chunk-4NJIT52T.js";import{defaultConnection}from"./chunk-TWC3NXFA.js";async function withRemoteClient(options,environment,httpOnly,action,budgets={}){budgets.signal?.throwIfAborted();await defaultConnection(options,environment,true);budgets.signal?.throwIfAborted();if(!options.has("--tenant")||(options.has("--profile")?["--origin","--mcp-url","--token-file","--token-env"].some(k=>options.has(k)):options.has("--origin")===options.has("--mcp-url")))throw Error();const transport=options.get("--transport");if(transport&&!["http","mcp"].includes(transport))throw Error();if(!options.has("--profile")&&transport&&transport!==(options.has("--origin")?"http":"mcp"))throw Error();const profile=options.has("--profile")?await(await import("./oauth-QBJ62PIA.js")).profileAuthorization(options.get("--profile"),budgets.signal):null;const authorization=profile?.authorization??await readCredential(options,environment);budgets.signal?.throwIfAborted();const profileHttp=profile&&(transport==="http"||!transport&&httpOnly);if(!profileHttp&&(profile||options.has("--mcp-url"))){if(httpOnly)throw Error();const connection=await(await import("./mcp-HQQJCKHS.js")).connectRemoteMcp(profile?.resource??options.get("--mcp-url"),authorization,options.get("--tenant"),budgets);try{budgets.signal?.throwIfAborted();return await action(connection.studio)}finally{await connection.close()}}const baseUrl=profileHttp?await(await import("./http-profile-D65WSTZU.js")).profileHttpOrigin(options.get("--profile"),profile.resource,budgets.signal):options.get("--origin");budgets.signal?.throwIfAborted();return action(new NativeStudioAgentClient({tenantId:options.get("--tenant"),baseUrl,authorization:()=>authorization,...budgets.maxJsonBytes?{maxJsonBytes:budgets.maxJsonBytes}:{}}))}export{withRemoteClient};
|