@nativestudio/cli 0.3.0-rc.4 → 0.3.0-rc.6
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 +7 -7
- package/components/runtime.json +3 -3
- package/components/runtime.tgz +0 -0
- package/dist/_chunks/{chunk-XZP6RNGC.js → chunk-HKD6F6M6.js} +1 -1
- package/dist/_chunks/{chunk-RNOIRNC3.js → chunk-INLSOHAK.js} +1 -1
- package/dist/_chunks/{chunk-VDQOSVZY.js → chunk-N6S6HCWE.js} +1 -1
- package/dist/_chunks/{chunk-JLOHTDP6.js → chunk-RVGDXRPK.js} +1 -1
- package/dist/_chunks/{local-main-GSL2FQOG.js → local-main-J2G7OU5E.js} +1 -1
- package/dist/_chunks/{local-mcp-VYHO4ZE3.js → local-mcp-LCHXL2IE.js} +1 -1
- package/dist/_chunks/{main-KLXOK7QK.js → main-PPA76ARV.js} +1 -1
- package/dist/_chunks/project-connect-7L2HRJUN.js +1 -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/project-connect-W7V3OALV.js +0 -1
package/COMPATIBILITY.json
CHANGED
|
@@ -1,20 +1,20 @@
|
|
|
1
1
|
{
|
|
2
2
|
"protocol": "NVS_PRODUCT_COMPATIBILITY_V1",
|
|
3
3
|
"product": "@nativestudio/cli",
|
|
4
|
-
"version": "0.3.0-rc.
|
|
4
|
+
"version": "0.3.0-rc.6",
|
|
5
5
|
"source": {
|
|
6
|
-
"head": "
|
|
7
|
-
"fileDigest": "
|
|
6
|
+
"head": "a13fb75ba28a524ae5347f03659646762354efe3",
|
|
7
|
+
"fileDigest": "9ef45b8f1850b520586d878981e71c4a8cc6bb6eecc91f046030c84c386bb794",
|
|
8
8
|
"dirty": false,
|
|
9
|
-
"remoteMainHead": "
|
|
9
|
+
"remoteMainHead": "a13fb75ba28a524ae5347f03659646762354efe3"
|
|
10
10
|
},
|
|
11
11
|
"node": ">=24.12 <25",
|
|
12
12
|
"discoveryProfile": "contextual-v1",
|
|
13
13
|
"accountProtocol": "NVS_CLI_ACCOUNT_V1",
|
|
14
14
|
"component": {
|
|
15
15
|
"protocol": "NVS_PRODUCT_COMPONENT_V1",
|
|
16
|
-
"version": "0.3.0-rc.
|
|
17
|
-
"byteSize":
|
|
18
|
-
"sha512": "
|
|
16
|
+
"version": "0.3.0-rc.6",
|
|
17
|
+
"byteSize": 17920972,
|
|
18
|
+
"sha512": "5fd414f1cfb8bd52cff7d969a5898a02c1ccad9dd9129e9eb628d725c654596886a185a1cdd37ce480ea4fe979df591db5de9ede84a48777e31db997eb500eff"
|
|
19
19
|
}
|
|
20
20
|
}
|
package/components/runtime.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"protocol": "NVS_PRODUCT_COMPONENT_V1",
|
|
3
|
-
"version": "0.3.0-rc.
|
|
4
|
-
"byteSize":
|
|
5
|
-
"sha512": "
|
|
3
|
+
"version": "0.3.0-rc.6",
|
|
4
|
+
"byteSize": 17920972,
|
|
5
|
+
"sha512": "5fd414f1cfb8bd52cff7d969a5898a02c1ccad9dd9129e9eb628d725c654596886a185a1cdd37ce480ea4fe979df591db5de9ede84a48777e31db997eb500eff"
|
|
6
6
|
}
|
package/components/runtime.tgz
CHANGED
|
Binary file
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LocalDeviceTransportConfigurationSchema,LocalDoctorReportSchema,LocalManagementInventorySchema,LocalRuntimeDescriptorSchema,LocalToolChoiceSchema,LocalToolSelectionSchema,LocalUpdatePlanSchema,NativeStudioLocalRuntimeClient,asset,canonicalLocalJson,catalogue,select}from"./chunk-JLOHTDP6.js";import{assertExecutable,directory,entries,fail,localSocketPath,optional,read,sha256,sha512,verifyBackup,write}from"./chunk-KB2GVAN7.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"}}async function captureInstalledTools(paths){paths=z.strictObject({mode:z.literal("INSTALLED").optional(),ffmpeg:z.string().min(1).max(4096),ffprobe:z.string().min(1).max(4096)}).parse(paths);const selected={};for(const name of["ffmpeg","ffprobe"]){if(!isAbsolute(paths[name]))fail("TOOL_PATH_INVALID");const path=await realpath(paths[name]);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");selected[name]={path,digest:h.digest("hex")}}finally{await file.close()}}return LocalToolChoiceSchema.parse({mode:"INSTALLED",...selected})}import{generateKeyPairSync}from"node:crypto";import{dirname,join,sep}from"node:path";async function generateDeviceKey(output){await directory(dirname(output));const key=generateKeyPairSync("ec",{namedCurve:"prime256v1"});await write(output,JSON.stringify(key.privateKey.export({format:"jwk"})),true);return{publicKey:key.publicKey.export({format:"jwk"}),privateKeyFile:output}}async function connectDevice(manager,raw){const schema=LocalDeviceTransportConfigurationSchema.extend({tools:LocalToolSelectionSchema.optional()});const input=schema.parse(raw),c=await manager.configuration();await read(input.privateKeyFile,16384);const active=(await manager.ledger.current()).value.active;const actual=active?.toolsConfigPath?LocalToolSelectionSchema.parse(JSON.parse((await read(active.toolsConfigPath,32768)).toString())):c.cloudConfigFile?LocalToolSelectionSchema.parse(JSON.parse((await read(c.cloudConfigFile,32768)).toString()).tools):null;if(input.tools&&active&&(!actual||canonicalLocalJson(input.tools)!==canonicalLocalJson(actual)))fail("TOOL_SELECTION_PLAN_REQUIRED");let tools=input.tools;if(!tools){const selected=(await manager.ledger.current()).value.active?.toolsConfigPath;if(!selected)fail("MANAGED_TOOLS_REQUIRED");tools=LocalToolSelectionSchema.parse(JSON.parse((await read(selected,32768)).toString()))}if(tools.mode==="MANAGED"&&!tools.ffmpeg.path.startsWith(join(c.stateDirectory,"tools")+sep))fail("MANAGED_TOOLS_REQUIRED");const file=join(c.stateDirectory,"cloud-device.json");await write(file,canonicalLocalJson({...input,tools}));await manager.configure({...c,cloudConfigFile:file});return{connected:true,deviceId:input.deviceId,projects:input.projects,nextActions:[{surface:"CLI",operation:"local.stop",availability:"AVAILABLE",reason:"READY"},{surface:"CLI",operation:"local.start",availability:"AVAILABLE",reason:"READY"}]}}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/captions/NotoSansSC.ttf","dist/captions/NativeStudioSC-Regular.ttf","dist/captions/OFL.txt",...["Bootstrap.ps1","NativeMain.cs","PrivateAccess.cs","PipeBridge.cs","JobNative.cs","JobRunner.cs"].map(name=>"dist/native/"+name)]);import{spawn}from"node:child_process";import{open as open2}from"node:fs/promises";import{dirname as dirname2,join as join2,delimiter}from"node:path";import{z as z2}from"zod";var environment=()=>({...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:dirname2(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(join2(root,name),64*1024*1024))!==hash)fail("SLOT_INTEGRITY_INVALID")}}async function probe(root,expected){const bytes=await new Promise((resolve,reject)=>{const child=spawn(process.execPath,["--max-old-space-size=256",join2(root,"dist/entry.js"),"--describe"],{env:environment(),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))})});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(join2(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!==join2(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(join2(stateDirectory,"runtime-process.log"),"a",384);const child=spawn(process.execPath,["--max-old-space-size=256",join2(root,"dist/entry.js"),"serve","--state-dir",stateDirectory,...cloudConfig?["--cloud-config",cloudConfig]:[],...toolsConfig?["--tools-config",toolsConfig]:[]],{env:environment(),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:lstat2}=await import("node:fs/promises");try{if(process.platform!=="win32")await lstat2(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",join2(root,"dist/entry.js"),"--qualify-tools","--state-dir",stateDirectory,"--tools-config",selection],{env:environment(),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(join2(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")}import{randomUUID}from"node:crypto";import{lstat}from"node:fs/promises";import{join as join3}from"node:path";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 tools.ffmpeg.digest+":"+tools.ffprobe.digest}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(join3(state,"journal.sqlite"+suffix))}catch(e){if(e.code==="ENOENT")continue;throw e}fail("RUNTIME_STATUS_REQUIRED")}}async function prepareInstallation(manager,version,raw){const c=await manager.configuration(),current=(await manager.ledger.current()).value;if(current.transition)fail("ACTIVATION_IN_PROGRESS");const trusted=await catalogue(c),release=select(trusted.signed,version),explicit=raw===void 0?void 0:LocalToolChoiceSchema.parse(raw),preference=await toolPreference(current.active?.toolsConfigPath??null,c.cloudConfigFile,explicit),toolSelection=explicit||preference.mode==="INSTALLED"||release.tools?preference:void 0;if(toolSelection?.mode==="MANAGED"&&!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:release.tools;if(desired)await assertPendingToolIdentity(inventory,previous,c.cloudConfigFile,preference.mode==="INSTALLED"?preference.ffmpeg.digest+":"+preference.ffprobe.digest:release.tools.ffmpeg.sha256+":"+release.tools.ffprobe.sha256)}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:trusted.fingerprint,trustFingerprint:trusted.trustFingerprint,release,...toolSelection?{toolSelection}:{},createdAt:new Date().toISOString(),expiresAt:new Date(Math.min(Date.now()+18e5,Date.parse(trusted.signed.catalogue.expiresAt))).toISOString()};const plan=LocalUpdatePlanSchema.parse({...body,fingerprint:sha256(canonicalLocalJson(body))});await write(join3(manager.ledger.root,"plans",plan.planId+".json"),canonicalLocalJson(plan),true);return plan}function newerVersion(candidate,current){const parse=v=>{const core=v.split("+")[0],i=core.indexOf("-");return{parts:(i<0?core:core.slice(0,i)).split(".").map(BigInt),pre:i<0?null:core.slice(i+1).split(".")}};const a=parse(candidate),b=parse(current);for(let i=0;i<3;i++){if(a.parts[i]!==b.parts[i])return a.parts[i]>b.parts[i]}if(!a.pre||!b.pre)return!a.pre&&!!b.pre;for(let i=0;i<Math.max(a.pre.length,b.pre.length);i++){const x=a.pre[i],y=b.pre[i];if(x===y)continue;if(x===void 0||y===void 0)return y===void 0;const xn=/^\d+$/.test(x),yn=/^\d+$/.test(y);if(xn&&yn)return BigInt(x)>BigInt(y);if(xn!==yn)return!xn;return x>y}return false}import{randomUUID as randomUUID2}from"node:crypto";import{join as join4,dirname as dirname3}from"node:path";import{z as z3}from"zod";async function grant(manager,raw,output){const i=z3.strictObject({projects:z3.array(z3.strictObject({tenantId:z3.uuid(),projectId:z3.uuid()})).min(1).max(100),expiresAt:z3.iso.datetime({offset:true})}).parse(raw);const c=await manager.configuration(),client=await ownerClient(c.stateDirectory);await directory(dirname3(output));const connector=await client.call({operation:"session.issue",...i});await write(output,canonicalLocalJson(connector),true);await write(join4(manager.ledger.root,"grants",randomUUID2()+".json"),canonicalLocalJson({...i,output}),true);return{granted:true,projects:i.projects,expiresAt:i.expiresAt}}async function reconnect(manager){const{entries:entries2}=await import("./files-TTIQ7LYJ.js"),c=await manager.configuration(),client=await ownerClient(c.stateDirectory);let renewed=0,blocked=0;for(const name of await entries2(join4(manager.ledger.root,"grants"))){if(!/^[0-9a-f-]{36}\.json$/.test(name))continue;try{const g=z3.strictObject({projects:z3.array(z3.strictObject({tenantId:z3.uuid(),projectId:z3.uuid()})).max(100),expiresAt:z3.iso.datetime({offset:true}),output:z3.string().min(1)}).parse(await optional(join4(manager.ledger.root,"grants",name)));if(Date.parse(g.expiresAt)<=Date.now())continue;const connector=await client.call({operation:"session.issue",projects:g.projects,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 join8}from"node:path";import{z as z6}from"zod";import{z as z4}from"zod";import{join as join5}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(join5(root,name));return new _InstallationLedger(root)}async current(){const names=(await entries(join5(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 names.entries()){const raw=JSON.parse((await read(join5(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(join5(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 join5(this.root,"slots",slot.id)}};import{randomUUID as randomUUID3}from"node:crypto";import{chmod as chmod2}from"node:fs/promises";import{join as join7}from"node:path";import{constants as constants2}from"node:fs";import{open as open3}from"node:fs/promises";import{z as z5}from"zod";var metadataSchema=z5.strictObject({protocol:z5.literal("NVS_PRODUCT_COMPONENT_V1"),version:z5.string().min(1).max(120),byteSize:z5.int().positive().max(64*1024*1024),sha512:z5.string().regex(/^[a-f0-9]{128}$/)});async function regularBytes(url,maximum){const file=await open3(url,constants2.O_RDONLY|constants2.O_NOFOLLOW);try{const stat=await file.stat();if(!stat.isFile()||stat.size>maximum)fail("EMBEDDED_COMPONENT_INVALID");const bytes=Buffer.alloc(stat.size+1);let size=0;while(size<bytes.length){const result=await file.read(bytes,size,bytes.length-size,null);if(!result.bytesRead)break;size+=result.bytesRead}if(size!==stat.size)fail("EMBEDDED_COMPONENT_INVALID");return bytes.subarray(0,size)}finally{await file.close()}}async function verifiedEmbeddedAsset(base,release){try{const info=metadataSchema.parse(JSON.parse((await regularBytes(new URL("runtime.json",base),4096)).toString()));if(info.version!==release.descriptor.version)fail("EMBEDDED_RELEASE_MISMATCH");if(info.byteSize!==release.package.byteSize||info.sha512!==release.package.sha512)fail("EMBEDDED_RELEASE_MISMATCH");const bytes=await regularBytes(new URL("runtime.tgz",base),info.byteSize);if(bytes.length!==release.package.byteSize||sha512(bytes)!==release.package.sha512)fail("EMBEDDED_COMPONENT_INVALID");return bytes}catch(error){if(error instanceof Error&&error.message.includes("EMBEDDED_RELEASE_MISMATCH"))throw error;fail("EMBEDDED_COMPONENT_INVALID")}}async function embeddedAsset(release){if(false)return null;if(release.descriptor.version!=="0.3.0-rc.4")return null;if(false)fail("EMBEDDED_COMPONENT_INVALID");const base=new URL("./components/",import.meta.resolve("@nativestudio/cli/package.json"));return verifiedEmbeddedAsset(base,release)}import{gunzipSync}from"node:zlib";import{chmod}from"node:fs/promises";import{join as join6}from"node:path";async function unpack(bytes,root,expectedVersion){const data=gunzipSync(bytes,{maxOutputLength:64*1024*1024}),files=new Map;let offset=0;while(offset+512<=data.length){const header=data.subarray(offset,offset+512);if(header.every(b=>b===0))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 name=text(0,100),prefix=text(345,500),path=(prefix?prefix+"/":"")+name,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(!/^package(?:\/dist(?:\/(?:native|captions))?)?\/?$/.test(path))fail("PACKAGE_PATH_INVALID")}else{if(kind!=="0"&&kind!=="")fail("PACKAGE_LINK_OR_METADATA_REFUSED");if(!path.startsWith("package/")||!allowedRuntimeFiles.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}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 chmod(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 bytes=await embeddedAsset(release)??await asset(release.package,origin),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){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 chmod2(path2,320)}result[name]={path:path2,digest:a.sha256}}const selection={mode:"MANAGED",ffmpeg:result.ffmpeg,ffprobe:result.ffprobe};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");await write(path,JSON.stringify(preference),true);return path}if(explicit?.mode==="MANAGED"&&!release.tools)fail("MANAGED_TOOLS_UNAVAILABLE");return await managedTools(release,origin,state,slotId)??previousSelection}var configurationSchema=z6.strictObject({stateDirectory:z6.string().min(1).max(4096),catalogueUrl:z6.string().url(),publicKeyFile:z6.string().min(1).max(4096),cloudConfigFile:z6.string().nullable().default(null),notifications:z6.boolean().default(true),rejectedVersions:z6.array(LocalRuntimeDescriptorSchema.shape.version).max(64).default([])});var LocalInstallationManager=class _LocalInstallationManager{constructor(ledger){this.ledger=ledger}ledger;static async open(root){return new _LocalInstallationManager(await InstallationLedger.open(root))}async configure(raw,options={}){const c=configurationSchema.parse(raw);c.stateDirectory=await directory(c.stateDirectory);await write(join8(this.ledger.root,"configuration.json"),canonicalLocalJson(c),options.ifAbsent);return{configured:true}}async configuration(){const value=await optional(join8(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?join8(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(),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)}async plan(id){if(!z6.uuid().safeParse(id).success)fail("PLAN_INVALID");const p=LocalUpdatePlanSchema.parse(JSON.parse((await read(join8(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 trusted=await catalogue(c);if(Date.parse(plan.expiresAt)<=Date.now()||plan.trustFingerprint!==trusted.trustFingerprint||canonicalLocalJson(select(trusted.signed,plan.release.descriptor.version))!==canonicalLocalJson(plan.release))fail("PLAN_CHANGED");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,trusted.origin);const tools=await selectedTools(plan.release,trusted.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);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")}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){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){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){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{}}await waitStopped(c.stateDirectory);const previous=s.transition.previous;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,generateDeviceKey,connectDevice,ownerClient,waitStopped,socketAbsent,newerVersion,LocalInstallationManager};
|
|
1
|
+
import{LocalDeviceTransportConfigurationSchema,LocalDoctorReportSchema,LocalManagementInventorySchema,LocalRuntimeDescriptorSchema,LocalToolChoiceSchema,LocalToolSelectionSchema,LocalUpdatePlanSchema,NativeStudioLocalRuntimeClient,asset,canonicalLocalJson,catalogue,select}from"./chunk-RVGDXRPK.js";import{assertExecutable,directory,entries,fail,localSocketPath,optional,read,sha256,sha512,verifyBackup,write}from"./chunk-KB2GVAN7.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"}}async function captureInstalledTools(paths){paths=z.strictObject({mode:z.literal("INSTALLED").optional(),ffmpeg:z.string().min(1).max(4096),ffprobe:z.string().min(1).max(4096)}).parse(paths);const selected={};for(const name of["ffmpeg","ffprobe"]){if(!isAbsolute(paths[name]))fail("TOOL_PATH_INVALID");const path=await realpath(paths[name]);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");selected[name]={path,digest:h.digest("hex")}}finally{await file.close()}}return LocalToolChoiceSchema.parse({mode:"INSTALLED",...selected})}import{generateKeyPairSync}from"node:crypto";import{dirname,join,sep}from"node:path";async function generateDeviceKey(output){await directory(dirname(output));const key=generateKeyPairSync("ec",{namedCurve:"prime256v1"});await write(output,JSON.stringify(key.privateKey.export({format:"jwk"})),true);return{publicKey:key.publicKey.export({format:"jwk"}),privateKeyFile:output}}async function connectDevice(manager,raw){const schema=LocalDeviceTransportConfigurationSchema.extend({tools:LocalToolSelectionSchema.optional()});const input=schema.parse(raw),c=await manager.configuration();await read(input.privateKeyFile,16384);const active=(await manager.ledger.current()).value.active;const actual=active?.toolsConfigPath?LocalToolSelectionSchema.parse(JSON.parse((await read(active.toolsConfigPath,32768)).toString())):c.cloudConfigFile?LocalToolSelectionSchema.parse(JSON.parse((await read(c.cloudConfigFile,32768)).toString()).tools):null;if(input.tools&&active&&(!actual||canonicalLocalJson(input.tools)!==canonicalLocalJson(actual)))fail("TOOL_SELECTION_PLAN_REQUIRED");let tools=input.tools;if(!tools){const selected=(await manager.ledger.current()).value.active?.toolsConfigPath;if(!selected)fail("MANAGED_TOOLS_REQUIRED");tools=LocalToolSelectionSchema.parse(JSON.parse((await read(selected,32768)).toString()))}if(tools.mode==="MANAGED"&&!tools.ffmpeg.path.startsWith(join(c.stateDirectory,"tools")+sep))fail("MANAGED_TOOLS_REQUIRED");const file=join(c.stateDirectory,"cloud-device.json");await write(file,canonicalLocalJson({...input,tools}));await manager.configure({...c,cloudConfigFile:file});return{connected:true,deviceId:input.deviceId,projects:input.projects,nextActions:[{surface:"CLI",operation:"local.stop",availability:"AVAILABLE",reason:"READY"},{surface:"CLI",operation:"local.start",availability:"AVAILABLE",reason:"READY"}]}}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/captions/NotoSansSC.ttf","dist/captions/NativeStudioSC-Regular.ttf","dist/captions/OFL.txt",...["Bootstrap.ps1","NativeMain.cs","PrivateAccess.cs","PipeBridge.cs","JobNative.cs","JobRunner.cs"].map(name=>"dist/native/"+name)]);import{spawn}from"node:child_process";import{open as open2}from"node:fs/promises";import{dirname as dirname2,join as join2,delimiter}from"node:path";import{z as z2}from"zod";var environment=()=>({...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:dirname2(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(join2(root,name),64*1024*1024))!==hash)fail("SLOT_INTEGRITY_INVALID")}}async function probe(root,expected){const bytes=await new Promise((resolve,reject)=>{const child=spawn(process.execPath,["--max-old-space-size=256",join2(root,"dist/entry.js"),"--describe"],{env:environment(),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))})});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(join2(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!==join2(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(join2(stateDirectory,"runtime-process.log"),"a",384);const child=spawn(process.execPath,["--max-old-space-size=256",join2(root,"dist/entry.js"),"serve","--state-dir",stateDirectory,...cloudConfig?["--cloud-config",cloudConfig]:[],...toolsConfig?["--tools-config",toolsConfig]:[]],{env:environment(),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:lstat2}=await import("node:fs/promises");try{if(process.platform!=="win32")await lstat2(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",join2(root,"dist/entry.js"),"--qualify-tools","--state-dir",stateDirectory,"--tools-config",selection],{env:environment(),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(join2(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")}import{randomUUID}from"node:crypto";import{lstat}from"node:fs/promises";import{join as join3}from"node:path";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 tools.ffmpeg.digest+":"+tools.ffprobe.digest}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(join3(state,"journal.sqlite"+suffix))}catch(e){if(e.code==="ENOENT")continue;throw e}fail("RUNTIME_STATUS_REQUIRED")}}async function prepareInstallation(manager,version,raw){const c=await manager.configuration(),current=(await manager.ledger.current()).value;if(current.transition)fail("ACTIVATION_IN_PROGRESS");const trusted=await catalogue(c),release=select(trusted.signed,version),explicit=raw===void 0?void 0:LocalToolChoiceSchema.parse(raw),preference=await toolPreference(current.active?.toolsConfigPath??null,c.cloudConfigFile,explicit),toolSelection=explicit||preference.mode==="INSTALLED"||release.tools?preference:void 0;if(toolSelection?.mode==="MANAGED"&&!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:release.tools;if(desired)await assertPendingToolIdentity(inventory,previous,c.cloudConfigFile,preference.mode==="INSTALLED"?preference.ffmpeg.digest+":"+preference.ffprobe.digest:release.tools.ffmpeg.sha256+":"+release.tools.ffprobe.sha256)}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:trusted.fingerprint,trustFingerprint:trusted.trustFingerprint,release,...toolSelection?{toolSelection}:{},createdAt:new Date().toISOString(),expiresAt:new Date(Math.min(Date.now()+18e5,Date.parse(trusted.signed.catalogue.expiresAt))).toISOString()};const plan=LocalUpdatePlanSchema.parse({...body,fingerprint:sha256(canonicalLocalJson(body))});await write(join3(manager.ledger.root,"plans",plan.planId+".json"),canonicalLocalJson(plan),true);return plan}function newerVersion(candidate,current){const parse=v=>{const core=v.split("+")[0],i=core.indexOf("-");return{parts:(i<0?core:core.slice(0,i)).split(".").map(BigInt),pre:i<0?null:core.slice(i+1).split(".")}};const a=parse(candidate),b=parse(current);for(let i=0;i<3;i++){if(a.parts[i]!==b.parts[i])return a.parts[i]>b.parts[i]}if(!a.pre||!b.pre)return!a.pre&&!!b.pre;for(let i=0;i<Math.max(a.pre.length,b.pre.length);i++){const x=a.pre[i],y=b.pre[i];if(x===y)continue;if(x===void 0||y===void 0)return y===void 0;const xn=/^\d+$/.test(x),yn=/^\d+$/.test(y);if(xn&&yn)return BigInt(x)>BigInt(y);if(xn!==yn)return!xn;return x>y}return false}import{randomUUID as randomUUID2}from"node:crypto";import{join as join4,dirname as dirname3}from"node:path";import{z as z3}from"zod";async function grant(manager,raw,output){const i=z3.strictObject({projects:z3.array(z3.strictObject({tenantId:z3.uuid(),projectId:z3.uuid()})).min(1).max(100),expiresAt:z3.iso.datetime({offset:true})}).parse(raw);const c=await manager.configuration(),client=await ownerClient(c.stateDirectory);await directory(dirname3(output));const connector=await client.call({operation:"session.issue",...i});await write(output,canonicalLocalJson(connector),true);await write(join4(manager.ledger.root,"grants",randomUUID2()+".json"),canonicalLocalJson({...i,output}),true);return{granted:true,projects:i.projects,expiresAt:i.expiresAt}}async function reconnect(manager){const{entries:entries2}=await import("./files-TTIQ7LYJ.js"),c=await manager.configuration(),client=await ownerClient(c.stateDirectory);let renewed=0,blocked=0;for(const name of await entries2(join4(manager.ledger.root,"grants"))){if(!/^[0-9a-f-]{36}\.json$/.test(name))continue;try{const g=z3.strictObject({projects:z3.array(z3.strictObject({tenantId:z3.uuid(),projectId:z3.uuid()})).max(100),expiresAt:z3.iso.datetime({offset:true}),output:z3.string().min(1)}).parse(await optional(join4(manager.ledger.root,"grants",name)));if(Date.parse(g.expiresAt)<=Date.now())continue;const connector=await client.call({operation:"session.issue",projects:g.projects,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 join8}from"node:path";import{z as z6}from"zod";import{z as z4}from"zod";import{join as join5}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(join5(root,name));return new _InstallationLedger(root)}async current(){const names=(await entries(join5(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 names.entries()){const raw=JSON.parse((await read(join5(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(join5(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 join5(this.root,"slots",slot.id)}};import{randomUUID as randomUUID3}from"node:crypto";import{chmod as chmod2}from"node:fs/promises";import{join as join7}from"node:path";import{constants as constants2}from"node:fs";import{open as open3}from"node:fs/promises";import{z as z5}from"zod";var metadataSchema=z5.strictObject({protocol:z5.literal("NVS_PRODUCT_COMPONENT_V1"),version:z5.string().min(1).max(120),byteSize:z5.int().positive().max(64*1024*1024),sha512:z5.string().regex(/^[a-f0-9]{128}$/)});async function regularBytes(url,maximum){const file=await open3(url,constants2.O_RDONLY|constants2.O_NOFOLLOW);try{const stat=await file.stat();if(!stat.isFile()||stat.size>maximum)fail("EMBEDDED_COMPONENT_INVALID");const bytes=Buffer.alloc(stat.size+1);let size=0;while(size<bytes.length){const result=await file.read(bytes,size,bytes.length-size,null);if(!result.bytesRead)break;size+=result.bytesRead}if(size!==stat.size)fail("EMBEDDED_COMPONENT_INVALID");return bytes.subarray(0,size)}finally{await file.close()}}async function verifiedEmbeddedAsset(base,release){try{const info=metadataSchema.parse(JSON.parse((await regularBytes(new URL("runtime.json",base),4096)).toString()));if(info.version!==release.descriptor.version)fail("EMBEDDED_RELEASE_MISMATCH");if(info.byteSize!==release.package.byteSize||info.sha512!==release.package.sha512)fail("EMBEDDED_RELEASE_MISMATCH");const bytes=await regularBytes(new URL("runtime.tgz",base),info.byteSize);if(bytes.length!==release.package.byteSize||sha512(bytes)!==release.package.sha512)fail("EMBEDDED_COMPONENT_INVALID");return bytes}catch(error){if(error instanceof Error&&error.message.includes("EMBEDDED_RELEASE_MISMATCH"))throw error;fail("EMBEDDED_COMPONENT_INVALID")}}async function embeddedAsset(release){if(false)return null;if(release.descriptor.version!=="0.3.0-rc.6")return null;if(false)fail("EMBEDDED_COMPONENT_INVALID");const base=new URL("./components/",import.meta.resolve("@nativestudio/cli/package.json"));return verifiedEmbeddedAsset(base,release)}import{gunzipSync}from"node:zlib";import{chmod}from"node:fs/promises";import{join as join6}from"node:path";async function unpack(bytes,root,expectedVersion){const data=gunzipSync(bytes,{maxOutputLength:64*1024*1024}),files=new Map;let offset=0;while(offset+512<=data.length){const header=data.subarray(offset,offset+512);if(header.every(b=>b===0))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 name=text(0,100),prefix=text(345,500),path=(prefix?prefix+"/":"")+name,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(!/^package(?:\/dist(?:\/(?:native|captions))?)?\/?$/.test(path))fail("PACKAGE_PATH_INVALID")}else{if(kind!=="0"&&kind!=="")fail("PACKAGE_LINK_OR_METADATA_REFUSED");if(!path.startsWith("package/")||!allowedRuntimeFiles.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}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 chmod(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 bytes=await embeddedAsset(release)??await asset(release.package,origin),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){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 chmod2(path2,320)}result[name]={path:path2,digest:a.sha256}}const selection={mode:"MANAGED",ffmpeg:result.ffmpeg,ffprobe:result.ffprobe};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");await write(path,JSON.stringify(preference),true);return path}if(explicit?.mode==="MANAGED"&&!release.tools)fail("MANAGED_TOOLS_UNAVAILABLE");return await managedTools(release,origin,state,slotId)??previousSelection}var configurationSchema=z6.strictObject({stateDirectory:z6.string().min(1).max(4096),catalogueUrl:z6.string().url(),publicKeyFile:z6.string().min(1).max(4096),cloudConfigFile:z6.string().nullable().default(null),notifications:z6.boolean().default(true),rejectedVersions:z6.array(LocalRuntimeDescriptorSchema.shape.version).max(64).default([])});var LocalInstallationManager=class _LocalInstallationManager{constructor(ledger){this.ledger=ledger}ledger;static async open(root){return new _LocalInstallationManager(await InstallationLedger.open(root))}async configure(raw,options={}){const c=configurationSchema.parse(raw);c.stateDirectory=await directory(c.stateDirectory);await write(join8(this.ledger.root,"configuration.json"),canonicalLocalJson(c),options.ifAbsent);return{configured:true}}async configuration(){const value=await optional(join8(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?join8(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(),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)}async plan(id){if(!z6.uuid().safeParse(id).success)fail("PLAN_INVALID");const p=LocalUpdatePlanSchema.parse(JSON.parse((await read(join8(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 trusted=await catalogue(c);if(Date.parse(plan.expiresAt)<=Date.now()||plan.trustFingerprint!==trusted.trustFingerprint||canonicalLocalJson(select(trusted.signed,plan.release.descriptor.version))!==canonicalLocalJson(plan.release))fail("PLAN_CHANGED");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,trusted.origin);const tools=await selectedTools(plan.release,trusted.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);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")}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){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){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){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{}}await waitStopped(c.stateDirectory);const previous=s.transition.previous;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,generateDeviceKey,connectDevice,ownerClient,waitStopped,socketAbsent,newerVersion,LocalInstallationManager};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LocalExecutionInspectInputSchema,LocalExecutionListInputSchema,LocalMcpOutputSchemas,NativeStudioLocalRuntimeClient,catalogue}from"./chunk-
|
|
1
|
+
import{LocalExecutionInspectInputSchema,LocalExecutionListInputSchema,LocalMcpOutputSchemas,NativeStudioLocalRuntimeClient,catalogue}from"./chunk-RVGDXRPK.js";import{fail,optional}from"./chunk-KB2GVAN7.js";import{NativeStudioSdkError}from"./chunk-6NVIN2NI.js";import{z}from"zod";import{join}from"node:path";var localTools={local_navigate:{description:"Local execution entry. Discover Project-scoped Runtime progress, recovery and updates. Native writes remain with the cloud owner.",input:z.strictObject({intent:z.string().max(500).optional()})},local_capability_describe:{description:"Inspect the exact public schema for a local capability. Standard discovery stays stable; each call validates current Runtime authority.",input:z.strictObject({tool:z.enum(["local_runtime_status","local_execution_list","local_execution_inspect","local_update_check"])})},local_runtime_status:{description:"Read current authorized local Runtime status. Does not start, stop or mutate native work.",input:z.strictObject({})},local_execution_list:{description:"List a bounded page of pending local execution identities in one authorized Project, then inspect an exact native Job.",input:LocalExecutionListInputSchema},local_execution_inspect:{description:"Inspect one exact native Job in the authorized Project. Native Job/Attempt identity remains authoritative.",input:LocalExecutionInspectInputSchema},local_update_check:{description:"Read signed compatible release metadata only. No executable download, approval, installation or restart.",input:z.strictObject({})}};var LocalMcpTools=class _LocalMcpTools{constructor(client,home,renders){this.client=client;this.home=home;this.renders=renders}client;home;renders;static async open(connector,home,renderTools){const client=await NativeStudioLocalRuntimeClient.fromConnector(connector);return new _LocalMcpTools(client,home,renderTools?await renderTools(client):void 0)}schema(name){return{name,description:localTools[name].description,inputSchema:z.toJSONSchema(localTools[name].input,{io:"input"}),outputSchema:z.toJSONSchema(LocalMcpOutputSchemas[name],{io:"input"}),annotations:{readOnlyHint:true,destructiveHint:false,openWorldHint:name==="local_update_check"}}}async call(name,raw,signal){return LocalMcpOutputSchemas[name].parse(await this.invoke(name,raw,signal))}async invoke(name,raw,signal){const input=localTools[name].input.parse(raw);if(name==="local_capability_describe")return{location:"LOCAL",tool:input.tool,schema:this.schema(input.tool)};if(name==="local_navigate"){let status;try{status=await this.client.status(signal)}catch{return{location:"LOCAL",state:"UNAVAILABLE",groups:[],nextActions:[{surface:"CLI",operation:"local.grant",availability:"BLOCKED",reason:"AUTHORIZATION_REQUIRED"}]}}return{location:"LOCAL",state:status.state,authorizedProjects:status.authorizedProjects,groups:[{id:"execution",label:"Local execution and recovery",tools:["local_runtime_status","local_execution_list","local_execution_inspect"]},{id:"versions",label:"Versions and updates",tools:["local_update_check"]}],nextActions:[{tool:"local_capability_describe",arguments:{tool:"local_execution_list"},availability:"AVAILABLE",reason:"READY"},...status.state==="RECOVERY_REQUIRED"?[{surface:"CLI",operation:"local.status",availability:"AVAILABLE",reason:"RECOVERY_REQUIRED"}]:[]]}}if(name==="local_runtime_status")return{...await this.client.status(signal),nextActions:[{tool:"local_capability_describe",arguments:{tool:"local_execution_list"}}]};if(name==="local_execution_list"){const page=await this.client.executions(LocalExecutionListInputSchema.parse(input),signal);return{...page,nextActions:page.items.map(item=>({tool:"local_execution_inspect",arguments:{tenantId:item.binding.tenantId,projectId:item.binding.projectId,productionId:item.binding.productionId,runtimeJobId:item.binding.runtimeJobId}}))}}if(name==="local_execution_inspect")return{location:"LOCAL",execution:await this.client.inspect(LocalExecutionInspectInputSchema.parse(input),signal),nextActions:[]};if(name==="local_update_check"){const current=await this.client.status(signal);if(!current.authorizedProjects.length)throw new NativeStudioSdkError("AUTHORIZATION_REQUIRED","BLOCKED","NO_WRITE");const raw2=await optional(join(this.home,"configuration.json"));const config=z.object({catalogueUrl:z.string().url(),publicKeyFile:z.string()}).parse(raw2);const v=await catalogue(config,signal);return{location:"LOCAL",running:current.versions,available:v.signed.catalogue.releases.filter(r=>r.descriptor.platform.os===process.platform&&r.descriptor.platform.architecture===process.arch).map(r=>r.descriptor),nextActions:[{surface:"CLI",operation:"local.update.prepare",availability:"BLOCKED",reason:"USER_APPROVAL_REQUIRED"}]}}fail("CAPABILITY_UNAVAILABLE")}};export{localTools,LocalMcpTools};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LocalDeviceGrantSchema,LocalDeviceViewSchema,LocalFinalRenderAdmissionSchema,LocalManagementCommandSchema,LocalManagementResultSchema,LocalPreviewAdmissionSchema,StartLocalFinalRenderSchema,StartLocalPreviewSchema,canonicalLocalJson}from"./chunk-
|
|
1
|
+
import{LocalDeviceGrantSchema,LocalDeviceViewSchema,LocalFinalRenderAdmissionSchema,LocalManagementCommandSchema,LocalManagementResultSchema,LocalPreviewAdmissionSchema,StartLocalFinalRenderSchema,StartLocalPreviewSchema,canonicalLocalJson}from"./chunk-RVGDXRPK.js";import{directory,entries,fail,read,sha256,write}from"./chunk-KB2GVAN7.js";import{z}from"zod";var DesktopDeviceScopeSchema=z.strictObject({origin:z.url().refine(value=>{const u=new URL(value);return u.origin===value&&(u.protocol==="https:"||u.protocol==="http:"&&["127.0.0.1","localhost","[::1]"].includes(u.hostname))}),tenantId:z.uuid(),principalId:z.uuid()});var digest=z.string().regex(/^[a-f0-9]{64}$/);var DesktopDeviceCallSchema=z.discriminatedUnion("action",[z.strictObject({action:z.literal("inspect")}),z.strictObject({action:z.literal("prove")}),z.strictObject({action:z.literal("connect"),expectedRevision:z.int().nonnegative(),installationFingerprint:digest.optional()}),z.strictObject({action:z.literal("remember-enable"),expectedRevision:z.int().nonnegative(),installationFingerprint:digest,projectIds:z.array(z.uuid()).min(1).max(20)}),z.strictObject({action:z.literal("connection-recover")}),z.strictObject({action:z.literal("enroll"),label:z.string().trim().min(1).max(120)}),z.strictObject({action:z.literal("grant"),projectId:z.uuid(),expiresAt:z.iso.datetime(),executionPolicy:z.literal("DEVICE_ONLY").optional(),capability:z.enum(["ROUGH_CUT_PREVIEW_V1","STUDIO_MEDIA_V2"]).optional()}),z.strictObject({action:z.literal("revoke"),projectId:z.uuid()}),z.strictObject({action:z.literal("preview"),input:StartLocalPreviewSchema.omit({tenantId:true,placement:true,idempotencyKey:true}),mode:z.enum(["local-only","local-preferred"])}),z.strictObject({action:z.literal("final"),input:StartLocalFinalRenderSchema.omit({tenantId:true,placement:true,idempotencyKey:true}),mode:z.enum(["local-only","local-preferred"])}),z.strictObject({action:z.literal("dispatch"),fingerprint:digest}),z.strictObject({action:z.literal("record"),fingerprint:digest,result:LocalManagementResultSchema}),z.strictObject({action:z.literal("refused"),fingerprint:digest})]);var DesktopDeviceRequestSchema=z.strictObject({operation:z.literal("device"),scope:DesktopDeviceScopeSchema,call:DesktopDeviceCallSchema});var DesktopDeviceStateSchema=z.strictObject({revision:z.int().nonnegative(),scope:DesktopDeviceScopeSchema,enrollment:LocalManagementCommandSchema.options[0].shape.input.nullable(),device:LocalDeviceViewSchema.nullable(),grants:z.array(LocalDeviceGrantSchema).max(20),previews:z.array(z.union([LocalPreviewAdmissionSchema,LocalFinalRenderAdmissionSchema])).max(20),connectorId:z.uuid().nullable(),connection:z.strictObject({phase:z.enum(["CONNECTING","READY","CONNECTED"]),expiresAt:z.iso.datetime(),projects:z.array(z.strictObject({tenantId:z.uuid(),projectId:z.uuid()})).min(1).max(20)}).nullable().default(null),pending:z.strictObject({command:LocalManagementCommandSchema,fingerprint:digest,phase:z.enum(["PREPARED","SENDING","REFUSED"])}).nullable()});var DesktopDeviceViewSchema=DesktopDeviceStateSchema.omit({scope:true,enrollment:true,connectorId:true,pending:true,device:true}).extend({installation:z.strictObject({version:z.string().min(1).max(100),fingerprint:digest,workProtocol:z.enum(["NVS_LOCAL_WORK_V1","NVS_LOCAL_WORK_V2"]).optional()}).nullable().optional(),automaticConnection:z.boolean().optional(),device:z.strictObject({deviceId:z.uuid(),label:z.string().max(120)}).nullable(),pending:z.strictObject({kind:z.enum(["ENROLL","GRANT","REVOKE_GRANT","PREVIEW","FINAL_RENDER"]),phase:z.enum(["PREPARED","SENDING","REFUSED"]),fingerprint:digest}).nullable()});var DesktopDeviceReplySchema=z.strictObject({view:DesktopDeviceViewSchema,command:LocalManagementCommandSchema.optional()});import{join}from"node:path";var DesktopDeviceRecords=class _DesktopDeviceRecords{constructor(root,scope){this.root=root;this.scope=scope}root;scope;static async open(home,raw){const scope=DesktopDeviceScopeSchema.parse(raw);return new _DesktopDeviceRecords(await directory(join(home,"devices",sha256(canonicalLocalJson(scope)))),scope)}async current(){const names=(await entries(this.root)).filter(n=>/^\d{12}\.json$/.test(n)).sort();let state={revision:0,scope:this.scope,enrollment:null,device:null,grants:[],previews:[],connectorId:null,connection:null,pending:null};for(const[index,name]of names.entries()){const next=DesktopDeviceStateSchema.parse(JSON.parse((await read(join(this.root,name),262144,true)).toString()));if(next.revision!==index+1||canonicalLocalJson(next.scope)!==canonicalLocalJson(this.scope))fail("DEVICE_HISTORY_INVALID");state=next}return state}async save(before,fields){if((await this.current()).revision!==before.revision)fail("REVISION_CONFLICT");const next=DesktopDeviceStateSchema.parse({...before,...fields,revision:before.revision+1});try{await write(join(this.root,String(next.revision).padStart(12,"0")+".json"),canonicalLocalJson(next),true)}catch(e){if(e.code==="EEXIST")fail("REVISION_CONFLICT");throw e}return next}keyPath(){return join(this.root,"device-key.json")}connectorPath(id){return join(this.root,id+".connector.json")}};async function desktopDeviceConnector(home,scope){const records=await DesktopDeviceRecords.open(home,scope),state=await records.current();if(!state.connectorId)fail("LOCAL_AUTHORIZATION_REQUIRED");return records.connectorPath(state.connectorId)}export{DesktopDeviceScopeSchema,DesktopDeviceRequestSchema,DesktopDeviceReplySchema,DesktopDeviceRecords,desktopDeviceConnector};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{fail,localSocketPath,privateAccess,privateDirectory,read,sha256,sha512}from"./chunk-KB2GVAN7.js";import{CaptionRenderStyleSchema,FinalRenderAdmissionSchema,FinalRenderManifestReaderSchema,FinalRenderStartSchema,KeyframeObservationSchema,NativeRuntimePublicKeySchema,ReviewEvidenceMediaSchema,ReviewIntelligenceBasisSchema,ReviewIntelligenceContextResultSchema,RoughCutAdmissionSchema,RoughCutManifestReaderSchema,RoughCutRequirementSchema,RoughCutStartSchema,RoughCutTechnicalSchema,ValidateReviewIntelligenceSchema,VideoReviewRequirementSchema,VideoTechnicalMetadataSchema,VisualLayerCompositionSchema,VisualRequirementSchema}from"./chunk-PBEHCYR7.js";import{OperationIdSchema}from"./chunk-VPYAXWXY.js";import{NativeStudioSdkError}from"./chunk-6NVIN2NI.js";import{z as z2}from"zod";import{z}from"zod";var LocalIdSchema=z.uuid().transform(v=>v.toLowerCase());var LocalDigestSchema=z.string().length(64).regex(/^[0-9a-f]{64}$/);var LocalRevisionSchema=z.int().positive();var LocalTimeSchema=z.iso.datetime({offset:true});var LocalPackageVersionSchema=z.string().max(120).regex(/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-(?:0|[1-9]\d*|\d*[A-Za-z-][0-9A-Za-z-]*)(?:\.(?:0|[1-9]\d*|\d*[A-Za-z-][0-9A-Za-z-]*))*)?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/).refine(v=>v===v.trim());var LocalProjectScopeSchema=z.strictObject({tenantId:LocalIdSchema,projectId:LocalIdSchema});var LocalWorkScopeSchema=LocalProjectScopeSchema.extend({productionId:LocalIdSchema,runtimeJobId:LocalIdSchema});var LocalPlacementPolicySchema=z.discriminatedUnion("mode",[z.strictObject({mode:z.literal("local-only"),deviceId:LocalIdSchema}),z.strictObject({mode:z.literal("local-preferred"),deviceId:LocalIdSchema}),z.strictObject({mode:z.literal("cloud-only")})]);var LocalPlacementAvailabilitySchema=z.discriminatedUnion("status",[z.strictObject({status:z.literal("AVAILABLE"),deviceId:LocalIdSchema}),z.strictObject({status:z.literal("UNAVAILABLE"),deviceId:LocalIdSchema,reason:z.enum(["OFFLINE","UNQUALIFIED","BUSY"])}),z.strictObject({status:z.literal("DENIED"),reason:z.enum(["FORBIDDEN","APPROVAL_REQUIRED","INVALID_INPUT"])})]);var LocalDevicePlatformSchema=z2.strictObject({os:z2.enum(["darwin","linux","win32"]),architecture:z2.enum(["x64","arm64"])});var EnrollLocalDeviceSchema=z2.strictObject({tenantId:LocalIdSchema,requestId:LocalIdSchema,label:z2.string().trim().min(1).max(120),platform:LocalDevicePlatformSchema,runtimeVersion:LocalPackageVersionSchema,publicKey:NativeRuntimePublicKeySchema});var LocalDeviceViewSchema=EnrollLocalDeviceSchema.omit({requestId:true}).extend({deviceId:LocalIdSchema,revision:LocalRevisionSchema,enrolledByPrincipalId:LocalIdSchema,createdAt:LocalTimeSchema,verifiedAt:LocalTimeSchema.nullable(),revokedAt:LocalTimeSchema.nullable()}).refine(v=>[v.verifiedAt,v.revokedAt].every(time=>time===null||Date.parse(time)>=Date.parse(v.createdAt)));var LocalDeviceChallengeSchema=z2.strictObject({tenantId:LocalIdSchema,deviceId:LocalIdSchema,deviceRevision:LocalRevisionSchema,challengeId:LocalIdSchema,audience:z2.string().min(1).max(2048),issuedAt:LocalTimeSchema,expiresAt:LocalTimeSchema}).refine(v=>{const ttl=Date.parse(v.expiresAt)-Date.parse(v.issuedAt);return ttl>0&&ttl<=3e5});var LocalDeviceProofClaimsSchema=z2.strictObject({protocol:z2.literal("NVS_LOCAL_DEVICE_PROOF_V1"),tenantId:LocalIdSchema,deviceId:LocalIdSchema,deviceRevision:LocalRevisionSchema,challengeId:LocalIdSchema,audience:z2.string().min(1).max(2048),jti:LocalIdSchema,iat:z2.int().nonnegative(),exp:z2.int().positive()}).refine(v=>v.exp>v.iat&&v.exp-v.iat<=60);var ProveLocalDeviceSchema=z2.strictObject({tenantId:LocalIdSchema,deviceId:LocalIdSchema,deviceRevision:LocalRevisionSchema,challengeId:LocalIdSchema,assertion:z2.string().max(4096).regex(/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/).meta({writeOnly:true})});var GrantLocalDeviceSchema=LocalProjectScopeSchema.extend({requestId:LocalIdSchema,executionPolicy:z2.literal("DEVICE_ONLY").optional(),deviceId:LocalIdSchema,deviceRevision:LocalRevisionSchema,expectedRevision:z2.int().nonnegative(),expiresAt:LocalTimeSchema,capability:z2.enum(["ROUGH_CUT_PREVIEW_V1","STUDIO_MEDIA_V2"])});var LocalDeviceGrantSchema=GrantLocalDeviceSchema.omit({requestId:true,expectedRevision:true}).extend({grantId:LocalIdSchema,revision:LocalRevisionSchema,approvedByPrincipalId:LocalIdSchema,createdAt:LocalTimeSchema,revokedAt:LocalTimeSchema.nullable()}).refine(v=>Date.parse(v.expiresAt)>Date.parse(v.createdAt));var RevokeLocalDeviceGrantSchema=LocalProjectScopeSchema.extend({grantId:LocalIdSchema,requestId:LocalIdSchema,expectedRevision:LocalRevisionSchema});var RevokeLocalDeviceSchema=z2.strictObject({tenantId:LocalIdSchema,deviceId:LocalIdSchema,requestId:LocalIdSchema,expectedRevision:LocalRevisionSchema});import{z as z5}from"zod";import{z as z4}from"zod";import{z as z3}from"zod";var pixel=z3.int().nonnegative().max(4096);var dimension=z3.int().positive().max(4096);var frame=z3.int().nonnegative().max(1800);var sample=z3.int().nonnegative().max(288e4);var rectangle=z3.strictObject({x:pixel,y:pixel,width:dimension,height:dimension});var window=z3.strictObject({start:sample,count:sample});var source=z3.strictObject({representationId:z3.uuid(),checksum:LocalDigestSchema,byteSize:z3.int().positive().max(134217728)});var LocalMediaRecipeSchema=z3.strictObject({protocol:z3.literal("NVS_RESOLVED_MEDIA_RECIPE_V2"),family:z3.enum(["ROUGH_CUT_RENDER","FINAL_RENDER"]),width:dimension,height:dimension,totalFrames:z3.int().min(900).max(1800),crf:z3.union([z3.literal(18),z3.literal(23)]),algorithm:z3.enum(["ORDERED_TRIM_CUT_V1","ORDERED_COMPOSE_V2"]),clips:z3.array(z3.strictObject({representationId:z3.uuid(),technical:VideoTechnicalMetadataSchema,sourceInMs:z3.int().nonnegative().max(6e4),sourceOutMs:z3.int().positive().max(6e4),startFrame:frame,frameCount:z3.int().positive().max(1800),overlapFrames:frame,crop:rectangle.nullable(),viewport:rectangle})).min(1).max(32),caption:z3.strictObject({style:CaptionRenderStyleSchema,references:z3.array(z3.strictObject({representationId:z3.uuid(),expectedUtf8:z3.string().max(65536)})).length(2),cues:z3.array(z3.strictObject({ordinal:z3.int().nonnegative().max(512),startFrame:frame,endFrame:frame,fontSize:z3.int().min(16).max(256),margin:pixel,text:z3.string().min(1).max(2e3)})).min(1).max(512)}).nullable(),audio:z3.strictObject({algorithm:z3.literal("PCM_WINDOW_MIX_AAC_V1"),tracks:z3.array(source.extend({channels:z3.union([z3.literal(1),z3.literal(2)]),sampleCount:z3.int().positive().max(288e4),sourceIn:sample,sourceOut:sample,start:sample,count:sample,gain:z3.int().nonnegative().max(1e3),duck:z3.int().nonnegative().max(1e3),duckWindows:z3.array(window).max(512)})).min(1).max(266)}).nullable(),graphics:z3.array(source.extend({contentType:z3.enum(["image/png","image/webp"]),sourceWidth:dimension,sourceHeight:dimension,width:dimension,height:dimension,x:pixel,y:pixel,startFrame:frame,endFrame:frame,opacity:z3.number().min(.1).max(1)})).max(8),visual:z3.strictObject({composition:VisualLayerCompositionSchema,plans:z3.array(z3.strictObject({id:z3.uuid(),startFrame:frame,endFrame:frame,width:dimension,height:dimension,x:pixel,y:pixel,opacityPermille:z3.int().min(0).max(1e3)})).max(8)}).nullable()}).superRefine((r,ctx)=>{if(r.width%2||r.height%2||r.clips.some(c=>c.viewport.x+c.viewport.width>r.width||c.viewport.y+c.viewport.height>r.height||c.sourceOutMs<=c.sourceInMs)||r.audio?.tracks.some(t=>t.sourceIn>=t.sourceOut||t.sourceOut>t.sampleCount||t.start+t.count>r.totalFrames*1600))ctx.addIssue({code:"custom",message:"Invalid bounded execution geometry or sample window"})});var previewProfile=z4.strictObject({kind:z4.literal("ROUGH_CUT_PREVIEW_V1"),profileId:z4.literal("PREVIEW_H264_480P_V1"),contractDigest:LocalDigestSchema});var studioProfile=z4.strictObject({kind:z4.literal("STUDIO_MEDIA_V2"),profileId:z4.literal("STUDIO_MEDIA_V2"),contractDigest:LocalDigestSchema});var LocalExecutionProfileSchema=z4.discriminatedUnion("kind",[previewProfile,studioProfile]);var LocalToolchainSchema=z4.strictObject({platform:LocalDevicePlatformSchema,rendererVersion:LocalPackageVersionSchema,rendererDigest:LocalDigestSchema,ffmpeg:z4.strictObject({version:z4.string().min(1).max(160),binaryDigest:LocalDigestSchema}),ffprobe:z4.strictObject({version:z4.string().min(1).max(160),binaryDigest:LocalDigestSchema}),profile:LocalExecutionProfileSchema,supported:z4.array(z4.strictObject({profile:LocalExecutionProfileSchema,rendererVersion:LocalPackageVersionSchema,rendererDigest:LocalDigestSchema})).max(4).optional()});var frozen=LocalWorkScopeSchema.extend({protocol:z4.literal("NVS_LOCAL_WORK_V1"),operationId:OperationIdSchema,renderId:LocalIdSchema,productionRevision:LocalRevisionSchema,executionClass:z4.enum(["LIVE","TEST_ONLY"]),policy:LocalPlacementPolicySchema,profile:previewProfile,manifest:RoughCutManifestReaderSchema,manifestFingerprint:LocalDigestSchema,sources:z4.array(z4.strictObject({artifactId:LocalIdSchema,representationId:LocalIdSchema,checksumSha256:LocalDigestSchema,byteSize:z4.int().positive(),contentType:z4.string().min(1).max(100)})).min(1).max(512)});var studio=frozen.extend({protocol:z4.literal("NVS_LOCAL_WORK_V2"),profile:studioProfile,manifest:z4.union([RoughCutManifestReaderSchema,FinalRenderManifestReaderSchema]),recipe:LocalMediaRecipeSchema,recipeFingerprint:LocalDigestSchema});var LocalFrozenWorkSchema=z4.discriminatedUnion("protocol",[frozen,studio]).superRefine((v,ctx)=>{const t=v.manifest.timeline;if(t.tenantId!==v.tenantId||t.projectId!==v.projectId||t.productionId!==v.productionId||t.executionClass!==v.executionClass)ctx.addIssue({code:"custom",message:"Frozen manifest scope/class mismatch"});if(new Set(v.sources.map(s=>s.representationId)).size!==v.sources.length)ctx.addIssue({code:"custom",message:"Duplicate source representation"});if(v.protocol==="NVS_LOCAL_WORK_V2"&&(v.recipe.width!==v.manifest.profile.width||v.recipe.height!==v.manifest.profile.height||v.recipe.totalFrames!==v.manifest.totalFrames||v.recipe.family==="FINAL_RENDER"!=="selection"in v.manifest))ctx.addIssue({code:"custom",message:"Recipe must match its native render family and geometry"})});var LocalLeaseBindingSchema=LocalWorkScopeSchema.extend({attemptId:LocalIdSchema,assignmentRevision:LocalRevisionSchema,workerId:z4.string().min(1).max(200),workFingerprint:LocalDigestSchema,toolchainFingerprint:LocalDigestSchema});var target=z4.discriminatedUnion("kind",[z4.strictObject({kind:z4.literal("DEVICE"),deviceId:LocalIdSchema,deviceRevision:LocalRevisionSchema,grantId:LocalIdSchema,grantRevision:LocalRevisionSchema}),z4.strictObject({kind:z4.literal("SERVER")})]);var LocalExecutionLeaseSchema=LocalLeaseBindingSchema.extend({target,issuedAt:LocalTimeSchema,expiresAt:LocalTimeSchema}).refine(v=>Date.parse(v.expiresAt)>Date.parse(v.issuedAt));var LocalWorkAssignmentSchema=z4.strictObject({work:LocalFrozenWorkSchema,lease:LocalExecutionLeaseSchema,toolchain:LocalToolchainSchema}).superRefine(({work,lease,toolchain},ctx)=>{if(["tenantId","projectId","productionId","runtimeJobId"].some(k=>work[k]!==lease[k]))ctx.addIssue({code:"custom",message:"Assignment work scope mismatch"});const p=work.policy,t=lease.target;if(p.mode==="cloud-only"&&t.kind!=="SERVER"||p.mode==="local-only"&&t.kind!=="DEVICE"||t.kind==="DEVICE"&&(p.mode==="cloud-only"||p.deviceId!==t.deviceId))ctx.addIssue({code:"custom",message:"Assignment contradicts placement policy"});if(work.profile.contractDigest!==toolchain.profile.contractDigest)ctx.addIssue({code:"custom",message:"Unqualified execution profile"})});var StartLocalPreviewSchema=RoughCutStartSchema.omit({deviceExecution:true}).extend({placement:LocalPlacementPolicySchema,localProfile:z5.literal("STUDIO_MEDIA_V2").optional()});var LocalDeviceScopeSchema=z5.strictObject({tenantId:LocalIdSchema,deviceId:LocalIdSchema});var LocalDeviceSessionSchema=z5.strictObject({...LocalDeviceScopeSchema.shape,expiresAt:LocalTimeSchema,credential:z5.string().length(43).regex(/^[A-Za-z0-9_-]+$/).meta({writeOnly:true})});var LocalDeviceHeartbeatSchema=LocalDeviceScopeSchema.extend({toolchain:LocalToolchainSchema,available:z5.boolean(),maxConcurrentJobs:z5.int().min(1).max(2).optional()});var ClaimLocalPreviewSchema=LocalProjectScopeSchema.extend({requestId:LocalIdSchema,deviceId:LocalIdSchema});var LocalOutputStageSchema=LocalLeaseBindingSchema.extend({uploadRequestId:LocalIdSchema,role:z5.enum(["VIDEO","POSTER"]),checksumSha256:LocalDigestSchema,byteSize:z5.int().positive().max(128*1024*1024)});var LocalOutputTicketSchema=z5.strictObject({receiptId:LocalIdSchema,role:z5.enum(["VIDEO","POSTER"]),checksumSha256:LocalDigestSchema,byteSize:z5.int().positive(),uploaded:z5.boolean()});var LocalSourceRequestSchema=LocalLeaseBindingSchema.extend({representationId:LocalIdSchema});var LocalProofChallengeRequestSchema=LocalDeviceScopeSchema.extend({deviceRevision:z5.int().positive()});var LocalPreviewPlacementViewSchema=z5.strictObject({target:z5.enum(["DEVICE","SERVER"]),reason:z5.enum(["LOCAL_AVAILABLE","CLOUD_ONLY","OFFLINE","UNQUALIFIED","BUSY","LEASE_RECOVERY"]),policy:LocalPlacementPolicySchema});var LocalDeviceTransportConfigurationSchema=z5.strictObject({endpoint:z5.string().url().max(2048),tenantId:LocalIdSchema,deviceId:LocalIdSchema,deviceRevision:z5.int().positive(),projects:z5.array(LocalProjectScopeSchema).min(1).max(20),privateKeyFile:z5.string().min(1).max(4096),platform:LocalDevicePlatformSchema});var LocalPreviewAdmissionSchema=RoughCutAdmissionSchema.extend({placement:LocalPreviewPlacementViewSchema});var StartLocalFinalRenderSchema=FinalRenderStartSchema.omit({deviceExecution:true}).extend({placement:LocalPlacementPolicySchema});var LocalFinalRenderAdmissionSchema=FinalRenderAdmissionSchema.extend({placement:LocalPreviewPlacementViewSchema});var LocalClaimReceiptSchema=z5.strictObject({found:z5.boolean(),assignment:LocalWorkAssignmentSchema.nullable()});var LocalWorkStateSchema=z5.strictObject({binding:LocalLeaseBindingSchema,status:z5.enum(["ACTIVE","FENCED","OUTCOME_UNKNOWN"]),assignment:LocalWorkAssignmentSchema.nullable()});import{z as z14}from"zod";import{z as z7}from"zod";import{z as z6}from"zod";var executable=z6.strictObject({path:z6.string().min(1).max(4096),digest:LocalDigestSchema});var LocalToolSelectionSchema=z6.strictObject({mode:z6.enum(["MANAGED","INSTALLED"]),ffmpeg:executable,ffprobe:executable});var LocalRuntimeDescriptorSchema=z7.strictObject({protocol:z7.literal("NVS_RUNTIME_DESCRIPTOR_V1"),version:LocalPackageVersionSchema,node:z7.strictObject({major:z7.literal(24),minMinor:z7.literal(12)}),platform:LocalDevicePlatformSchema,ipcProtocol:z7.literal("NVS_LOCAL_IPC_V1"),workProtocol:z7.enum(["NVS_LOCAL_WORK_V1","NVS_LOCAL_WORK_V2"]),journalSchema:z7.literal(1),rendererDigest:LocalDigestSchema,profileDigest:LocalDigestSchema,compatibleRenderers:z7.array(z7.strictObject({rendererDigest:LocalDigestSchema,profileDigest:LocalDigestSchema})).max(4).optional()});var LocalSessionConnectorSchema=z7.strictObject({protocol:z7.literal("NVS_LOCAL_CONNECTOR_V1"),stateDirectory:z7.string().min(1).max(4096),credential:z7.string().length(43).regex(/^[A-Za-z0-9_-]{43}$/),expiresAt:LocalTimeSchema,projects:z7.array(LocalProjectScopeSchema).min(1).max(100)});var LocalManagementInventorySchema=z7.strictObject({runtimeRevision:z7.int().positive(),descriptor:LocalRuntimeDescriptorSchema,activeProcesses:z7.int().nonnegative(),pendingExecutions:z7.int().nonnegative(),pendingRequests:z7.int().nonnegative(),pendingRenderers:z7.array(LocalDigestSchema).max(64)});var LocalReleaseAssetSchema=z7.strictObject({url:z7.string().url().max(2048),byteSize:z7.int().positive().max(256*1024*1024),sha512:z7.string().length(128).regex(/^[0-9a-f]{128}$/)});var LocalReleaseSchema=z7.strictObject({descriptor:LocalRuntimeDescriptorSchema,package:LocalReleaseAssetSchema,tools:z7.strictObject({ffmpeg:LocalReleaseAssetSchema.extend({sha256:LocalDigestSchema}),ffprobe:LocalReleaseAssetSchema.extend({sha256:LocalDigestSchema})}).nullable()});var LocalReleaseCatalogueSchema=z7.strictObject({protocol:z7.literal("NVS_LOCAL_RELEASE_CATALOGUE_V1"),issuedAt:LocalTimeSchema,expiresAt:LocalTimeSchema,releases:z7.array(LocalReleaseSchema).min(1).max(32)}).refine(v=>Date.parse(v.expiresAt)>Date.parse(v.issuedAt)&&Date.parse(v.expiresAt)-Date.parse(v.issuedAt)<=7*864e5&&new Set(v.releases.map(r=>[r.descriptor.version,r.descriptor.platform.os,r.descriptor.platform.architecture].join(":"))).size===v.releases.length);var LocalSignedCatalogueSchema=z7.strictObject({catalogue:LocalReleaseCatalogueSchema,signature:z7.string().length(86).regex(/^[A-Za-z0-9_-]{85}[AQgw]$/)});var LocalToolChoiceSchema=z7.discriminatedUnion("mode",[z7.strictObject({mode:z7.literal("MANAGED")}),LocalToolSelectionSchema.extend({mode:z7.literal("INSTALLED")})]);var LocalUpdatePlanSchema=z7.strictObject({protocol:z7.literal("NVS_LOCAL_UPDATE_PLAN_V1"),planId:LocalIdSchema,installationRevision:z7.int().nonnegative(),runtimeRevision:z7.int().positive().nullable(),catalogueFingerprint:LocalDigestSchema,trustFingerprint:LocalDigestSchema.optional(),release:LocalReleaseSchema,toolSelection:LocalToolChoiceSchema.optional(),fingerprint:LocalDigestSchema,createdAt:LocalTimeSchema,expiresAt:LocalTimeSchema});var LocalClientNextActionSchema=z7.strictObject({surface:z7.enum(["CLI","LOCAL_IPC","REMOTE"]),operation:z7.enum(["runtime.status","local.configure","local.install","local.start","local.connect","local.grant","local.status","local.doctor","local.stop","local.update.check","local.update.prepare","local.update.apply","local.update.reconcile","execution.inspect","rough_cut_get","operation_get"]),availability:z7.enum(["AVAILABLE","BLOCKED"]),reason:z7.enum(["READY","INSTALL_REQUIRED","AUTHORIZATION_REQUIRED","VERSION_INCOMPATIBLE","UPDATE_AVAILABLE","RECOVERY_REQUIRED","USER_APPROVAL_REQUIRED","TRUST_REQUIRED","UNAVAILABLE"])});import{z as z13}from"zod";import{z as z8}from"zod";var LocalOfflineSnapshotSchema=z8.strictObject({projectId:z8.uuid(),title:z8.string().min(1).max(200),savedAt:LocalTimeSchema,expiresAt:LocalTimeSchema,productions:z8.array(z8.strictObject({id:z8.uuid(),title:z8.string().max(200)})).max(40),possiblyTruncated:z8.boolean()}).refine(v=>new TextEncoder().encode(JSON.stringify(v)).length<=8192);var text=z8.string().max(4e3).refine(v=>new TextEncoder().encode(JSON.stringify(v)).length<=8192);var LocalOfflineCallSchema=z8.discriminatedUnion("action",[z8.strictObject({action:z8.enum(["list","forget"]),key:LocalDigestSchema}),z8.strictObject({action:z8.literal("retain"),key:LocalDigestSchema,snapshot:LocalOfflineSnapshotSchema}),z8.strictObject({action:z8.literal("draft"),key:LocalDigestSchema,projectId:z8.uuid(),text,expectedRevision:z8.int().nonnegative()})]);var LocalOfflinePageSchema=z8.strictObject({historical:z8.literal(true),items:z8.array(z8.strictObject({snapshot:LocalOfflineSnapshotSchema,draft:z8.strictObject({text,revision:z8.int().nonnegative()})})).max(3)});import{z as z10}from"zod";import{z as z9}from"zod";var QualifiedLocalAgentVersionSchema=z9.enum(["0.164.0","0.165.0"]);var LocalAgentGrantSchema=z9.strictObject({protocol:z9.literal("NVS_CODEX_REVIEW_GRANT_V1"),binary:z9.string().min(1).max(4096).refine(v=>/^(?:\/|[A-Za-z]:[\\/])/.test(v)),binaryDigest:z9.string().regex(/^[a-f0-9]{64}$/),version:QualifiedLocalAgentVersionSchema,model:z9.string().regex(/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,99}$/),reasoningEffort:z9.enum(["low","medium","high","xhigh"]).optional(),reviewerLabel:z9.string().trim().min(1).max(100),inference:z9.literal("REMOTE_OPENAI"),remoteUseApproved:z9.literal(true),imageDisclosureApproved:z9.literal(true).optional(),mediaDisclosureApproved:z9.literal(true).optional(),projects:z9.array(LocalProjectScopeSchema).min(1).max(100),expiresAt:z9.iso.datetime({offset:true})});var LocalAgentMediaInputSchema=z10.strictObject({profile:z10.literal("NVS_AGENT_DERIVED_EVIDENCE_V1"),contentType:z10.enum(["image/png","image/jpeg","image/webp","video/mp4"]),byteSize:z10.int().positive().max(134217728),width:z10.int().positive().max(4096),height:z10.int().positive().max(4096),durationMs:z10.int().positive().max(6e4).optional(),frameRate:z10.union([z10.literal(24),z10.literal(30)]).optional(),hasAudio:z10.boolean().optional()}).refine(v=>v.contentType==="video/mp4"?!!v.durationMs&&!!v.frameRate:!v.durationMs&&!v.frameRate&&v.hasAudio===void 0);var sha=z10.string().regex(/^[a-f0-9]{64}$/);var LocalAgentEvidenceReceiptSchema=z10.strictObject({protocol:z10.literal("NVS_AGENT_DERIVED_EVIDENCE_V1"),draftId:z10.uuid(),media:ReviewEvidenceMediaSchema,ffmpegDigest:sha,ffprobeDigest:sha,attachment:z10.strictObject({checksumSha256:sha,byteSize:z10.int().positive().max(8388608),width:z10.int().positive().max(4096),height:z10.int().positive().max(4096)}),timestampsMs:z10.array(z10.number().nonnegative().max(6e4)).max(6),audio:z10.strictObject({sampleRateHz:z10.literal(48e3),channels:z10.literal(1),samples:z10.int().positive().max(2881024),peak:z10.number().min(0).max(1),rms:z10.number().min(0).max(1),clippedSamples:z10.int().nonnegative().max(2881024)}).nullable(),limitations:z10.tuple([z10.literal("SAMPLED_FRAMES_ARE_NOT_FULL_PLAYBACK"),z10.literal("AUDIO_STATISTICS_ARE_NOT_LISTENING_OR_TRANSCRIPTION")])});var LocalAgentDiscoverySchema=z10.strictObject({candidate:z10.strictObject({binary:z10.string().min(1).max(4096),binaryDigest:sha,version:z10.string().regex(/^\d+\.\d+\.\d+$/),qualified:z10.boolean()}).nullable(),configured:LocalAgentGrantSchema.nullable()});import{z as z11}from"zod";var LocalResourcePolicySchema=z11.strictObject({mode:z11.enum(["CONTINUOUS","IDLE_ONLY"]).default("CONTINUOUS"),idleAfterSeconds:z11.int().min(30).max(3600).default(300),maxConcurrentJobs:z11.int().min(1).max(2).default(1),cpuCores:z11.union([z11.literal(1),z11.literal(2)]).default(2),memoryMiB:z11.int().min(512).max(4096).default(4096),cacheQuotaBytes:z11.int().min(512*1024*1024).max(32*1024*1024*1024).default(1024*1024*1024)});var LocalResourceSettingsSchema=z11.strictObject({revision:z11.int().nonnegative(),policy:LocalResourcePolicySchema});var LocalExecutionProgressSchema=z11.strictObject({stage:z11.enum(["WAITING","DOWNLOADING","EXECUTING","UPLOADING","AWAITING_ACCEPTANCE","COMPLETE","RECOVERY_REQUIRED","FENCED"]),downloadedBytes:z11.int().nonnegative(),sourceBytes:z11.int().nonnegative(),uploadedBytes:z11.int().nonnegative(),outputBytes:z11.int().nonnegative(),lastError:z11.strictObject({code:z11.string().regex(/^[A-Z][A-Z0-9_]{0,79}$/),observedAt:LocalTimeSchema}).nullable()});var LocalStorageInspectionSchema=z11.strictObject({cacheBytes:z11.int().nonnegative(),protectedBytes:z11.int().nonnegative(),reclaimableBytes:z11.int().nonnegative(),transferBytes:z11.int().nonnegative(),journalBytes:z11.int().nonnegative(),reviewBytes:z11.int().nonnegative().optional(),ownerStagingBytes:z11.int().nonnegative().optional(),availableDiskBytes:z11.int().nonnegative(),quotaBytes:z11.int().positive(),overQuota:z11.boolean()});var LocalWorkspaceInspectionSchema=z11.strictObject({settings:LocalResourceSettingsSchema,storage:LocalStorageInspectionSchema,scheduling:z11.strictObject({state:z11.enum(["READY","WAITING_FOR_IDLE","AT_CAPACITY","DRAINING"]),activeJobs:z11.int().nonnegative(),idleObservationCurrent:z11.boolean()})});var LocalDiagnosticsSchema=z11.strictObject({protocol:z11.literal("NVS_LOCAL_DIAGNOSTICS_V1"),createdAt:LocalTimeSchema,runtimeVersion:z11.string().min(1).max(80),runtimeRevision:LocalRevisionSchema,settings:LocalResourceSettingsSchema,storage:LocalStorageInspectionSchema,recordCounts:z11.record(z11.string().regex(/^[A-Z_]{1,40}$/),z11.int().nonnegative()),failures:z11.array(z11.strictObject({taskFingerprint:z11.string().regex(/^[a-f0-9]{64}$/),code:z11.string().regex(/^[A-Z][A-Z0-9_]{0,79}$/),observedAt:LocalTimeSchema})).max(32)});import{z as z12}from"zod";function canonicalLocalJson(value){if(value===null||typeof value==="string"||typeof value==="boolean")return JSON.stringify(value);if(typeof value==="number"&&Number.isFinite(value))return JSON.stringify(value);if(Array.isArray(value))return"["+value.map(canonicalLocalJson).join(",")+"]";if(typeof value==="object")return"{"+Object.entries(value).filter(([,v])=>v!==void 0).sort(([a],[b])=>a<b?-1:a>b?1:0).map(([k,v])=>JSON.stringify(k)+":"+canonicalLocalJson(v)).join(",")+"}";throw new Error("Fingerprint input must be finite JSON data")}var sha2=z12.string().regex(/^[a-f0-9]{64}$/);var qualifiedVersion=QualifiedLocalAgentVersionSchema;var LocalAgentSnapshotSchema=z12.strictObject({basis:ReviewIntelligenceBasisSchema,productionRevision:z12.int().positive(),reviewVersion:z12.int().nonnegative(),executionClass:z12.enum(["LIVE","TEST_ONLY"]),media:ReviewEvidenceMediaSchema,requirements:z12.array(z12.union([VisualRequirementSchema,VideoReviewRequirementSchema,RoughCutRequirementSchema])).min(1).max(64),evidence:LocalAgentMediaInputSchema.optional(),image:z12.strictObject({contentType:z12.literal("image/png"),byteSize:z12.int().positive().max(8388608),width:z12.int().positive().max(4096),height:z12.int().positive().max(4096)}).optional()}).refine(v=>!v.image||!v.evidence&&v.basis.target.kind==="IMAGE").refine(v=>v.basis.target.kind==="IMAGE"||!v.evidence||v.evidence.contentType==="video/mp4").refine(v=>new TextEncoder().encode(JSON.stringify(v)).length<=32768).refine(v=>new Set(v.requirements.map(r=>r.key)).size===v.requirements.length);var LocalAgentProbeSchema=z12.strictObject({configured:z12.boolean(),available:z12.boolean(),reason:z12.enum(["GRANT_REQUIRED","READY","RUNTIME_UNAVAILABLE","GRANT_EXPIRED"]),grantFingerprint:sha2.nullable(),inference:z12.literal("REMOTE_OPENAI")});var LocalAgentPlanSchema=z12.strictObject({protocol:z12.enum(["NVS_LOCAL_AGENT_REVIEW_V1","NVS_LOCAL_AGENT_REVIEW_V2"]),id:z12.uuid(),grantFingerprint:sha2,snapshot:LocalAgentSnapshotSchema,expiresAt:z12.iso.datetime({offset:true}),fingerprint:sha2});var LocalAgentMetadataAnswerSchema=z12.strictObject({summary:z12.string().trim().min(1).max(1500),observations:z12.array(z12.strictObject({key:z12.string().min(1).max(220),observed:z12.string().trim().min(1).max(1e3)})).min(1).max(64)});var LocalAgentPixelAnswerSchema=z12.strictObject({summary:z12.string().trim().min(1).max(1500),imageReadback:z12.string().trim().min(1).max(800),observations:z12.array(KeyframeObservationSchema.omit({region:true}).extend({key:z12.string().min(1).max(220)})).min(1).max(64)});var LocalAgentAnswerSchema=z12.union([LocalAgentMetadataAnswerSchema,LocalAgentPixelAnswerSchema]).refine(v=>new TextEncoder().encode(JSON.stringify(v)).length<=96*1024);var LocalAgentImageReceiptSchema=z12.strictObject({protocol:z12.literal("NVS_LOCAL_AGENT_IMAGE_V1"),draftId:z12.uuid(),media:ReviewEvidenceMediaSchema,byteSize:z12.int().positive().max(8388608),contentType:z12.literal("image/png"),width:z12.int().positive().max(4096),height:z12.int().positive().max(4096)});var LocalAgentReviewViewSchema=z12.strictObject({plan:LocalAgentPlanSchema,revision:z12.int().positive(),phase:z12.enum(["PREPARED","RUNNING","RESULT_PENDING","UNKNOWN"]),answer:LocalAgentAnswerSchema.nullable(),imageReceipt:LocalAgentImageReceiptSchema.optional(),evidenceReceipt:LocalAgentEvidenceReceiptSchema.optional(),provenance:z12.strictObject({adapter:z12.enum(["CODEX_METADATA_V1","CODEX_MEDIA_V2"]),binaryDigest:sha2,version:qualifiedVersion,model:z12.string().max(100),reasoningEffort:z12.enum(["low","medium","high","xhigh"]).optional(),reviewerLabel:z12.string().max(100),inference:z12.literal("REMOTE_OPENAI"),evidence:z12.enum(["METADATA_ONLY","IMAGE_PIXELS","VIDEO_FRAMES"])})}).refine(v=>{const image=v.plan.snapshot.image,receipt=v.imageReceipt;if(receipt&&(!image||receipt.draftId!==v.plan.id||canonicalLocalJson(receipt.media)!==canonicalLocalJson(v.plan.snapshot.media)||canonicalLocalJson({contentType:receipt.contentType,byteSize:receipt.byteSize,width:receipt.width,height:receipt.height})!==canonicalLocalJson(image)))return false;if(v.phase==="RESULT_PENDING"!==!!v.answer)return false;const derived=v.plan.snapshot.evidence,receipt2=v.evidenceReceipt;if(v.provenance.adapter!==(derived?"CODEX_MEDIA_V2":"CODEX_METADATA_V1"))return false;if(receipt2&&(!derived||receipt2.draftId!==v.plan.id||canonicalLocalJson(receipt2.media)!==canonicalLocalJson(v.plan.snapshot.media)))return false;if(v.answer&&!!(image||derived)!=="imageReadback"in v.answer)return false;const pixels=v.phase==="RESULT_PENDING"&&!!(image||derived);return v.provenance.evidence===(pixels?derived?.contentType==="video/mp4"?"VIDEO_FRAMES":"IMAGE_PIXELS":"METADATA_ONLY")&&(!pixels||(derived?!!receipt2:!!receipt))});function localAgentSnapshotFromContext(raw,includeImage=false){const c=ReviewIntelligenceContextResultSchema.parse(raw);if(c.reviewTarget.kind!=="IMAGE"||c.basis.target.kind!=="IMAGE"||c.ownerContext.semanticStatus!=="SUCCESS")throw Error("LOCAL_AGENT_CONTEXT_UNAVAILABLE");const t=c.reviewTarget.target,scope=c.basis.scope;if(!t.runtimeSucceeded||t.candidate.availability!=="AVAILABLE"||t.candidate.freshness!=="CURRENT_BASIS"||!t.productionRunnable||t.freshness!=="CURRENT_BASIS"||t.generationId!==c.basis.target.generationId||t.tenantId!==scope.tenantId||t.projectId!==scope.projectId||t.productionId!==scope.productionId||c.ownerContext.basis.tenantId!==scope.tenantId||c.ownerContext.basis.projectId!==scope.projectId||c.ownerContext.basis.productionId!==scope.productionId)throw Error("LOCAL_AGENT_CONTEXT_UNAVAILABLE");return LocalAgentSnapshotSchema.parse({basis:c.basis,productionRevision:c.ownerContext.basis.productionRevision,reviewVersion:t.reviewVersion,executionClass:t.executionClass,media:{artifactId:t.candidate.artifactId,representationId:t.candidate.representationId,checksumSha256:t.candidate.checksumSha256},requirements:t.requirements,...includeImage?{image:{contentType:t.candidate.contentType,byteSize:t.candidate.byteSize,width:t.candidate.width,height:t.candidate.height}}:{}})}function localAgentNativeProposal(raw){const v=LocalAgentReviewViewSchema.parse(raw);if(v.plan.snapshot.basis.target.kind!=="IMAGE"||v.plan.snapshot.evidence)throw Error("LOCAL_AGENT_MEDIA_PROPOSAL_REQUIRED");if(v.phase!=="RESULT_PENDING"||!v.answer)throw Error("LOCAL_AGENT_RESULT_UNAVAILABLE");const keys=new Set(v.answer.observations.map(o=>o.key));if(keys.size!==v.answer.observations.length||keys.size!==v.plan.snapshot.requirements.length||v.plan.snapshot.requirements.some(r=>!keys.has(r.key)))throw Error("LOCAL_AGENT_RESULT_UNAVAILABLE");const p=v.provenance;const pixels=p.evidence==="IMAGE_PIXELS";return ValidateReviewIntelligenceSchema.parse({basis:v.plan.snapshot.basis,proposal:{origin:{kind:"EXTERNAL_AGENT_HOST",label:p.reviewerLabel},summary:`${pixels?"IMAGE_PIXELS":"METADATA_ONLY; no visual inspection"}. Codex ${p.version}; model ${p.model}; effort ${p.reasoningEffort??"DEFAULT"}; binary ${p.binaryDigest}; draft ${v.plan.id}; plan ${v.plan.fingerprint}. ${v.answer.summary}`,evidence:pixels?[{id:"original_image",label:"Verified ORIGINAL PNG attachment",producer:"EXTERNAL_AGENT_HOST",kind:"IMAGE_PIXELS",media:v.plan.snapshot.media}]:[],review:{kind:"IMAGE",observations:v.answer.observations.map(o=>({...o,status:pixels&&"status"in o?o.status:"NOT_OBSERVABLE",confidence:pixels&&"confidence"in o?o.confidence:"UNCERTAIN",evidenceIds:pixels?["original_image"]:[]}))}}})}var projectInput=LocalProjectScopeSchema;var LocalExecutionListInputSchema=LocalProjectScopeSchema.extend({after:z13.string().length(64).regex(/^[0-9a-f]{64}$/).nullable().default(null),limit:z13.int().min(1).max(16).default(8),includeCompleted:z13.boolean().optional(),includeProgress:z13.boolean().optional()});var LocalExecutionInspectInputSchema=LocalWorkScopeSchema.extend({includeProgress:z13.boolean().optional()});var LocalIpcCallSchema=z13.discriminatedUnion("operation",[z13.strictObject({operation:z13.literal("agent.discover"),binary:z13.string().min(1).max(4096).optional()}),z13.strictObject({operation:z13.literal("offline.workspace"),input:LocalOfflineCallSchema}),z13.strictObject({operation:z13.literal("workspace.inspect")}),z13.strictObject({operation:z13.literal("workspace.configure"),policy:LocalResourcePolicySchema,expectedRevision:z13.int().nonnegative()}),z13.strictObject({operation:z13.literal("workspace.activity"),idleSeconds:z13.int().min(0).max(86400),observedAt:z13.iso.datetime()}),z13.strictObject({operation:z13.literal("storage.clean")}),z13.strictObject({operation:z13.literal("diagnostics.read")}),z13.strictObject({operation:z13.literal("agent.grant"),grant:LocalAgentGrantSchema,approval:z13.string().regex(/^[a-f0-9]{64}$/)}),z13.strictObject({operation:z13.literal("agent.probe")}),z13.strictObject({operation:z13.literal("agent.revoke"),approval:z13.string().regex(/^[a-f0-9]{64}$/)}),z13.strictObject({operation:z13.literal("agent.prepare"),snapshot:LocalAgentSnapshotSchema}),z13.strictObject({operation:z13.literal("agent.start"),id:z13.uuid(),expectedRevision:LocalRevisionSchema,approval:z13.string().regex(/^[a-f0-9]{64}$/)}),z13.strictObject({operation:z13.literal("agent.inspect"),id:z13.uuid()}),z13.strictObject({operation:z13.literal("runtime.status"),includeDevice:z13.literal(true).optional()}),z13.strictObject({operation:z13.literal("runtime.doctor")}),z13.strictObject({operation:z13.literal("runtime.inventory")}),z13.strictObject({operation:z13.literal("session.issue"),projects:z13.array(projectInput).min(1).max(100),expiresAt:z13.iso.datetime({offset:true})}),z13.strictObject({operation:z13.literal("runtime.stop"),expectedRuntimeRevision:LocalRevisionSchema}),z13.strictObject({operation:z13.literal("execution.inspect"),input:LocalExecutionInspectInputSchema}),z13.strictObject({operation:z13.literal("execution.list"),input:LocalExecutionListInputSchema}),z13.strictObject({operation:z13.literal("update.check")}),z13.strictObject({operation:z13.literal("update.prepare"),targetVersion:LocalPackageVersionSchema,expectedRuntimeRevision:LocalRevisionSchema}),z13.strictObject({operation:z13.literal("update.apply"),planId:LocalIdSchema,targetVersion:LocalPackageVersionSchema,expectedRuntimeRevision:LocalRevisionSchema})]);var LocalNextActionSchema=z13.strictObject({call:LocalIpcCallSchema,availability:z13.enum(["AVAILABLE","BLOCKED"]),reason:z13.enum(["READY","INSTALL_REQUIRED","AUTHORIZATION_REQUIRED","VERSION_INCOMPATIBLE","UPDATE_AVAILABLE","RECOVERY_REQUIRED"])});var LocalIpcRequestSchema=z13.strictObject({protocol:z13.literal("NVS_LOCAL_IPC_V1"),requestId:LocalIdSchema,call:LocalIpcCallSchema});var LocalVersionReportSchema=z13.strictObject({component:z13.enum(["CLI","SDK","MCP","RUNTIME","MEDIA_TOOLS"]),installedVersion:LocalPackageVersionSchema.nullable(),runningVersion:LocalPackageVersionSchema.nullable(),availableVersion:LocalPackageVersionSchema.nullable(),executablePath:z13.string().min(1).max(4096).nullable(),installOwner:z13.enum(["NPM_GLOBAL","PROJECT","NPX","MANAGED","TARBALL","UNKNOWN"])});var LocalRuntimeStatusSchema=z13.strictObject({protocol:z13.literal("NVS_LOCAL_IPC_V1"),runtimeRevision:LocalRevisionSchema,state:z13.enum(["IDLE","EXECUTING","DRAINING","RECOVERY_REQUIRED"]),journalSchemaVersion:z13.literal(1),workProtocols:z13.array(z13.enum(["NVS_LOCAL_WORK_V1","NVS_LOCAL_WORK_V2"])).min(1).max(2),versions:z13.array(LocalVersionReportSchema).max(8),authorizedProjects:z13.array(projectInput).max(100),deviceAuthority:z13.strictObject({tenantId:z13.uuid(),deviceId:z13.uuid(),origin:z13.url()}).optional(),nextActions:z13.array(LocalNextActionSchema).max(8)});var LocalDoctorReportSchema=z13.strictObject({mode:z13.enum(["MANAGED","INSTALLED"]),availability:z13.enum(["AVAILABLE","UNAVAILABLE"]),reason:z13.enum(["QUALIFIED_PROCESS_TOOLS","MANAGED_TOOLS_MISSING","TOOL_QUALIFICATION_FAILED"]),nativeExecutionReady:z13.boolean(),executionProfiles:z13.array(z13.enum(["ROUGH_CUT_PREVIEW_V1","STUDIO_MEDIA_V2"])).max(2).optional(),tools:z13.array(z13.strictObject({name:z13.enum(["FFMPEG","FFPROBE"]),path:z13.string().min(1).max(4096),version:z13.string().min(1).max(200),digest:z13.string().regex(/^[0-9a-f]{64}$/)})).max(2)});var LocalExecutionInspectionSchema=z13.strictObject({binding:LocalLeaseBindingSchema,revision:LocalRevisionSchema,phase:z13.enum(["STAGED","RUNNING","RECOVERY_REQUIRED","OUTPUT_PENDING","RECEIPT_RECORDED","FENCED"]),checkpoint:z13.enum(["ADOPTED","SOURCES_READY","PROCESS_STARTED","OUTPUT_STAGED"]),progress:LocalExecutionProgressSchema.optional()});var LocalExecutionPageSchema=z13.strictObject({items:z13.array(LocalExecutionInspectionSchema).max(16),nextCursor:z13.string().length(64).regex(/^[0-9a-f]{64}$/).nullable()});var LocalIpcErrorCodeSchema=z13.enum(["FORBIDDEN","INVALID_INPUT","FRAME_LIMIT","BUSY","AUTHORIZATION_REQUIRED","REVISION_CONFLICT","CAPABILITY_UNAVAILABLE","INTERNAL_OPERATIONAL_FAILURE","AGENT_APPROVAL_REQUIRED","AGENT_RUNTIME_UNAVAILABLE","AGENT_LOGIN_REQUIRED","AGENT_VERSION_UNQUALIFIED","AGENT_GRANT_REQUIRED","AGENT_OUTCOME_UNKNOWN","AGENT_IMAGE_REQUIRED","AGENT_IMAGE_INVALID","AGENT_IMAGE_BUDGET_EXCEEDED","AGENT_IMAGE_AUTHORIZATION_REQUIRED","CACHE_QUOTA_EXCEEDED"]);var LocalIpcResponseSchema=z13.discriminatedUnion("semanticStatus",[z13.strictObject({protocol:z13.literal("NVS_LOCAL_IPC_V1"),requestId:LocalIdSchema,semanticStatus:z13.literal("SUCCESS"),data:z13.union([LocalWorkspaceInspectionSchema,LocalDiagnosticsSchema,LocalOfflinePageSchema,LocalRuntimeStatusSchema,LocalDoctorReportSchema,LocalExecutionInspectionSchema.nullable(),z13.strictObject({state:z13.literal("DRAINING"),inventory:LocalManagementInventorySchema.optional(),backupPath:z13.string().min(1).max(4096).optional()}),LocalSessionConnectorSchema,LocalManagementInventorySchema,LocalExecutionPageSchema,LocalAgentProbeSchema,LocalAgentDiscoverySchema,LocalAgentReviewViewSchema])}),z13.strictObject({protocol:z13.literal("NVS_LOCAL_IPC_V1"),requestId:LocalIdSchema.nullable(),semanticStatus:z13.enum(["BLOCKED","INVALID_INPUT"]),error:z13.strictObject({code:LocalIpcErrorCodeSchema})})]);var LocalMcpToolNameSchema=z14.enum(["local_navigate","local_capability_describe","local_runtime_status","local_execution_list","local_execution_inspect","local_update_check"]);var LocalMcpActionSchema=z14.strictObject({tool:LocalMcpToolNameSchema,arguments:z14.record(z14.string(),z14.unknown()),availability:z14.enum(["AVAILABLE","BLOCKED"]).optional(),reason:z14.string().max(100).optional()});var LocalMcpNavigationSchema=z14.strictObject({location:z14.literal("LOCAL"),state:z14.enum(["UNAVAILABLE","IDLE","EXECUTING","DRAINING","RECOVERY_REQUIRED"]),authorizedProjects:z14.array(LocalProjectScopeSchema).max(100).optional(),groups:z14.array(z14.strictObject({id:z14.string().max(40),label:z14.string().max(100),tools:z14.array(LocalMcpToolNameSchema).max(6)})).max(4),nextActions:z14.array(z14.union([LocalMcpActionSchema,LocalClientNextActionSchema])).max(16)});var LocalMcpExecutionPageSchema=LocalExecutionPageSchema.extend({nextActions:z14.array(LocalMcpActionSchema).max(16)});var LocalMcpInspectionSchema=z14.strictObject({location:z14.literal("LOCAL"),execution:LocalExecutionInspectionSchema.nullable(),nextActions:z14.array(LocalMcpActionSchema).max(4)});var LocalMcpUpdateSchema=z14.strictObject({location:z14.literal("LOCAL"),running:z14.array(LocalVersionReportSchema).max(8),available:z14.array(LocalRuntimeDescriptorSchema).max(32),nextActions:z14.array(LocalClientNextActionSchema).max(4)});var LocalMcpDescriptionSchema=z14.strictObject({location:z14.literal("LOCAL"),tool:LocalMcpToolNameSchema,schema:z14.object({name:LocalMcpToolNameSchema,description:z14.string(),inputSchema:z14.record(z14.string(),z14.unknown())}).passthrough()});var LocalMcpFailureSchema=z14.strictObject({semanticStatus:z14.enum(["BLOCKED","INVALID_INPUT"]),error:z14.strictObject({code:z14.enum(["AUTHORIZATION_REQUIRED","FORBIDDEN","LOCAL_RUNTIME_UNAVAILABLE","RELEASE_UNAVAILABLE","VERSION_INCOMPATIBLE","INVALID_INPUT","LOCAL_CAPABILITY_UNAVAILABLE"]),outcome:z14.literal("NO_WRITE")}),nextActions:z14.array(LocalClientNextActionSchema).max(4)});var LocalMcpOutputSchemas={local_navigate:LocalMcpNavigationSchema,local_capability_describe:LocalMcpDescriptionSchema,local_runtime_status:LocalRuntimeStatusSchema.omit({nextActions:true}).extend({nextActions:z14.array(LocalMcpActionSchema).max(8)}),local_execution_list:LocalMcpExecutionPageSchema,local_execution_inspect:LocalMcpInspectionSchema,local_update_check:LocalMcpUpdateSchema};import{z as z15}from"zod";var LocalManagementCommandSchema=z15.discriminatedUnion("kind",[z15.strictObject({kind:z15.literal("ENROLL"),input:EnrollLocalDeviceSchema}),z15.strictObject({kind:z15.literal("GRANT"),input:GrantLocalDeviceSchema}),z15.strictObject({kind:z15.literal("REVOKE_GRANT"),input:RevokeLocalDeviceGrantSchema}),z15.strictObject({kind:z15.literal("PREVIEW"),input:StartLocalPreviewSchema}),z15.strictObject({kind:z15.literal("FINAL_RENDER"),input:StartLocalFinalRenderSchema})]);var LocalManagementResultSchema=z15.union([LocalDeviceViewSchema,LocalDeviceGrantSchema,LocalPreviewAdmissionSchema,LocalFinalRenderAdmissionSchema,z15.strictObject({semanticStatus:z15.literal("SUCCESS")})]);var LocalManagementReceiptSchema=z15.strictObject({fingerprint:z15.string().regex(/^[a-f0-9]{64}$/),result:LocalManagementResultSchema.nullable()});import{z as z17}from"zod";import{createHash}from"node:crypto";function localBudget(timeoutMs,parent,ceiling=6e4){if(!Number.isInteger(timeoutMs)||timeoutMs<1||timeoutMs>ceiling)throw Error("LOCAL_DEADLINE_INVALID");const controller=new AbortController,timer=setTimeout(()=>controller.abort(),timeoutMs);return{signal:parent?AbortSignal.any([parent,controller.signal]):controller.signal,close:()=>clearTimeout(timer)}}async function localAbortable(work,signal){if(signal.aborted)void work.catch(()=>{});signal.throwIfAborted();return new Promise((resolve,reject)=>{const abort=()=>reject(Error("LOCAL_DEADLINE"));signal.addEventListener("abort",abort,{once:true});work.then(v=>{signal.removeEventListener("abort",abort);resolve(v)},e=>{signal.removeEventListener("abort",abort);reject(e)});if(signal.aborted)abort()})}import{z as z16}from"zod";var output=z16.discriminatedUnion("role",[z16.strictObject({role:z16.literal("VIDEO"),receiptId:LocalIdSchema,checksumSha256:LocalDigestSchema,byteSize:z16.int().positive().max(128*1024*1024),contentType:z16.literal("video/mp4")}),z16.strictObject({role:z16.literal("POSTER"),receiptId:LocalIdSchema,checksumSha256:LocalDigestSchema,byteSize:z16.int().positive().max(2*1024*1024),contentType:z16.literal("image/png")})]);var LocalCompletionSubmissionSchema=LocalLeaseBindingSchema.extend({requestId:LocalIdSchema,outputs:z16.array(output).length(2),technical:RoughCutTechnicalSchema}).superRefine((v,ctx)=>{const video=v.outputs.find(o=>o.role==="VIDEO");if(new Set(v.outputs.map(o=>o.role)).size!==2||new Set(v.outputs.map(o=>o.receiptId)).size!==2||!video||video.checksumSha256!==v.technical.checksumSha256||video.byteSize!==v.technical.byteSize)ctx.addIssue({code:"custom",message:"Exact video/poster receipts required"})});var LocalVerifiedUploadSchema=z16.strictObject({binding:LocalLeaseBindingSchema,output,verifiedAt:LocalTimeSchema});var LocalCompletionReceiptSchema=LocalLeaseBindingSchema.extend({submissionFingerprint:LocalDigestSchema.optional(),semanticStatus:z16.literal("SUCCESS"),requestId:LocalIdSchema,renderId:LocalIdSchema,operationId:OperationIdSchema,artifactId:LocalIdSchema,videoRepresentationId:LocalIdSchema,posterRepresentationId:LocalIdSchema,checksumSha256:LocalDigestSchema,acceptedAt:LocalTimeSchema});var GetLocalCompletionReceiptSchema=LocalLeaseBindingSchema.pick({tenantId:true,projectId:true,productionId:true,runtimeJobId:true}).extend({requestId:LocalIdSchema});var NativeStudioLocalDeviceClient=class{constructor(options){this.options=options;const u=new URL(options.baseUrl);if(u.username||u.password||u.search||u.hash||u.pathname!=="/"||u.protocol!=="https:"&&!(u.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(u.hostname)))throw new NativeStudioSdkError("INVALID_INPUT","INVALID_INPUT","NO_WRITE");this.origin=u.origin}options;origin;async command(route,raw,input,output2,signal,readOnly=false){let started=false;const budget=localBudget(15e3,signal);try{const i=input.parse(raw);if((i.tenantId??i.input?.tenantId)!==this.options.tenantId)throw Error();budget.signal.throwIfAborted();const authorization=await localAbortable(Promise.resolve().then(()=>this.options.authorization()),budget.signal);if(authorization!==authorization.trim()||!/^Bearer [A-Za-z0-9._~-]{1,8192}$/.test(authorization))throw Error();const body=JSON.stringify(i);if(Buffer.byteLength(body)>65536)throw Error();budget.signal.throwIfAborted();started=true;const r=await fetch(this.origin+"/v1/local-execution/"+route,{method:"POST",headers:{authorization,"content-type":"application/json"},body,redirect:"error",signal:budget.signal});if(!r.ok){await r.body?.cancel();throw new NativeStudioSdkError(r.status===403||r.status===401?"FORBIDDEN":"LOCAL_COMMAND_REFUSED","BLOCKED",readOnly?"NO_WRITE":r.status>=500?"UNKNOWN":"REJECTED",r.status)}const parts=[];let size=0;for await(const b of r.body??[]){size+=b.length;if(size>262144)throw Error();parts.push(b)}const value=output2.parse(JSON.parse(Buffer.concat(parts).toString()));if(value&&typeof value==="object"){const result=value,request3=i;for(const key of["tenantId","projectId","deviceId"])if(key in result&&key in request3&&result[key]!==request3[key])throw Error()}return value}catch(e){if(e instanceof NativeStudioSdkError)throw e;throw new NativeStudioSdkError(started?readOnly?"LOCAL_QUERY_UNAVAILABLE":"LOCAL_COMMAND_UNKNOWN":"INVALID_INPUT",started?"BLOCKED":"INVALID_INPUT",started&&!readOnly?"UNKNOWN":"NO_WRITE")}finally{budget.close()}}enroll(input,signal){return this.command("devices/enroll",input,EnrollLocalDeviceSchema,LocalDeviceViewSchema,signal)}async managementReceipt(input,signal){const parsedInput=LocalManagementCommandSchema.safeParse(input);if(!parsedInput.success)throw new NativeStudioSdkError("INVALID_INPUT","INVALID_INPUT","NO_WRITE");const parsed=parsedInput.data;const value=await this.command("management-receipt",input,LocalManagementCommandSchema,LocalManagementReceiptSchema,signal,true);if(value.fingerprint!==createHash("sha256").update(canonicalLocalJson(parsed)).digest("hex"))throw new NativeStudioSdkError("LOCAL_RECEIPT_INVALID","BLOCKED","NO_WRITE");if(value.result){const result=value.result,original=parsed.input;for(const key of["tenantId","projectId","deviceId","productionId","timelineVersionId"])if(key in original&&key in result&&result[key]!==original[key])throw new NativeStudioSdkError("LOCAL_RECEIPT_INVALID","BLOCKED","NO_WRITE")}return value}grant(input,signal){return this.command("devices/grant",input,GrantLocalDeviceSchema,LocalDeviceGrantSchema,signal)}revokeDevice(input,signal){return this.command("devices/revoke",input,RevokeLocalDeviceSchema,z17.strictObject({semanticStatus:z17.literal("SUCCESS")}),signal)}revokeGrant(input,signal){return this.command("devices/revoke-grant",input,RevokeLocalDeviceGrantSchema,z17.strictObject({semanticStatus:z17.literal("SUCCESS")}),signal)}startPreview(input,signal){return this.command("previews",input,StartLocalPreviewSchema,LocalPreviewAdmissionSchema,signal)}startFinal(input,signal){return this.command("final-renders",input,StartLocalFinalRenderSchema,LocalFinalRenderAdmissionSchema,signal)}};import{randomUUID,createHash as createHash2}from"node:crypto";import{request}from"node:http";import{z as z18}from"zod";import{constants}from"node:fs";import{open,realpath}from"node:fs/promises";async function checkedLocalDirectory(path){await privateDirectory(path);return realpath(path)}async function readLocalCredential(path,maximum=32768){await privateAccess(path,"file");const file=await open(path,constants.O_RDONLY|constants.O_NOFOLLOW);try{const stat=await file.stat();if(!stat.isFile()||stat.nlink!==1||process.platform!=="win32"&&(stat.uid!==process.getuid?.()||stat.mode&63)||stat.size>maximum)throw Error("LOCAL_CREDENTIAL_INVALID");const bytes=Buffer.alloc(Math.min(maximum+1,stat.size+1));let used=0;while(used<bytes.length){const part=await file.read(bytes,used,bytes.length-used,null);if(!part.bytesRead)break;used+=part.bytesRead}if(used>stat.size)throw Error("LOCAL_CREDENTIAL_INVALID");if(used>maximum)throw Error("LOCAL_CREDENTIAL_INVALID");return bytes.subarray(0,used)}finally{await file.close()}}async function stageAgentImage(options,view,input,signal){const budget=localBudget(view.plan.snapshot.evidence?18e4:options.timeoutMs??1e4,signal,view.plan.snapshot.evidence?18e4:6e4);let dispatched=false;try{budget.signal.throwIfAborted();if(input.byteLength>134217728)throw Error();const bytes=Buffer.from(input),snapshot=view.plan.snapshot,id=z18.uuid().parse(view.plan.id),requestId=randomUUID();if(!snapshot.image&&!snapshot.evidence||bytes.length!==(snapshot.evidence??snapshot.image).byteSize||bytes.length>(snapshot.evidence?134217728:8388608)||createHash2("sha256").update(bytes).digest("hex")!==snapshot.media.checksumSha256)throw Error();const root=await checkedLocalDirectory(options.stateDirectory),path=localSocketPath(root);await privateAccess(path,"pipe");const auth=await localAbortable(Promise.resolve().then(options.authorization),budget.signal);budget.signal.throwIfAborted();if(!/^Bearer [A-Za-z0-9_-]{43}$/.test(auth))throw Error();const reply=await new Promise((resolve,reject)=>{const req=request({socketPath:path,path:"/ipc/v1/agent-images/"+id,method:"PUT",signal:budget.signal,headers:{authorization:auth,"content-type":snapshot.evidence?"application/octet-stream":"image/png","content-length":bytes.length,"x-nvs-request-id":requestId}},res=>{let size=0;const chunks=[];res.on("error",reject);res.on("aborted",()=>reject(Error()));res.on("data",b=>{size+=b.length;if(size>262144)req.destroy(Error());else chunks.push(b)});res.on("end",()=>{try{resolve(JSON.parse(Buffer.concat(chunks).toString()))}catch{reject(Error())}})});req.on("error",reject);dispatched=true;req.end(bytes)});const response=LocalIpcResponseSchema.parse(reply);if(response.requestId!==requestId&&!(response.requestId===null&&response.semanticStatus!=="SUCCESS"&&["BUSY","FORBIDDEN"].includes(response.error.code)))throw Error();if(response.semanticStatus!=="SUCCESS")throw new NativeStudioSdkError(response.error.code,response.semanticStatus,response.error.code==="INTERNAL_OPERATIONAL_FAILURE"?"UNKNOWN":"REJECTED");const v=LocalAgentReviewViewSchema.parse(response.data),receipt=v.evidenceReceipt??v.imageReceipt;if(v.plan.id!==id||canonicalLocalJson(v.plan)!==canonicalLocalJson(view.plan)||v.revision<view.revision||v.phase!=="PREPARED"||!receipt||receipt.draftId!==id||canonicalLocalJson(receipt.media)!==canonicalLocalJson(snapshot.media)||!snapshot.evidence&&canonicalLocalJson({contentType:v.imageReceipt?.contentType,byteSize:v.imageReceipt?.byteSize,width:v.imageReceipt?.width,height:v.imageReceipt?.height})!==canonicalLocalJson(snapshot.image))throw Error();return v}catch(e){if(e instanceof NativeStudioSdkError)throw e;throw new NativeStudioSdkError("LOCAL_AGENT_IMAGE_TRANSFER_FAILED","BLOCKED",dispatched?"UNKNOWN":"NO_WRITE")}finally{budget.close()}}var NativeStudioLocalWorkspaceClient=class{constructor(client){this.client=client}client;async offline(raw,signal){return LocalOfflinePageSchema.parse(await this.client.call({operation:"offline.workspace",input:LocalOfflineCallSchema.parse(raw)},signal))}async inspect(signal){return LocalWorkspaceInspectionSchema.parse(await this.client.call({operation:"workspace.inspect"},signal))}async configure(raw,expectedRevision,signal){const policy=LocalResourcePolicySchema.parse(raw);return LocalWorkspaceInspectionSchema.parse(await this.client.call({operation:"workspace.configure",policy,expectedRevision},signal))}async observeActivity(idleSeconds,observedAt,signal){return LocalWorkspaceInspectionSchema.parse(await this.client.call({operation:"workspace.activity",idleSeconds,observedAt},signal))}async clean(signal){return LocalWorkspaceInspectionSchema.parse(await this.client.call({operation:"storage.clean"},signal))}async diagnostics(signal){return LocalDiagnosticsSchema.parse(await this.client.call({operation:"diagnostics.read"},signal))}};import{randomUUID as randomUUID2}from"node:crypto";import{request as request2}from"node:http";var NativeStudioLocalRuntimeClient=class _NativeStudioLocalRuntimeClient{constructor(options){this.options=options}options;workspace=new NativeStudioLocalWorkspaceClient(this);static async fromConnector(path){const initial=LocalSessionConnectorSchema.parse(JSON.parse((await readLocalCredential(path)).toString()));return new _NativeStudioLocalRuntimeClient({stateDirectory:initial.stateDirectory,projects:initial.projects,authorization:async()=>{const current=LocalSessionConnectorSchema.parse(JSON.parse((await readLocalCredential(path)).toString()));if(current.stateDirectory!==initial.stateDirectory||canonicalLocalJson(current.projects)!==canonicalLocalJson(initial.projects)||Date.parse(current.expiresAt)>Date.parse(initial.expiresAt)||Date.parse(current.expiresAt)<=Date.now())throw Error("LOCAL_AUTHORIZATION_REQUIRED");return"Bearer "+current.credential}})}async call(call,signal){let started=false;const budget=localBudget(this.options.timeoutMs??(["runtime.doctor","agent.probe","agent.grant","agent.start"].includes(call.operation)?6e4:1e4),signal);const readOnly=["runtime.status","runtime.doctor","runtime.inventory","execution.inspect","execution.list","update.check","agent.probe","agent.discover","agent.inspect","workspace.inspect","diagnostics.read"].includes(call.operation);try{const input=LocalIpcRequestSchema.parse({protocol:"NVS_LOCAL_IPC_V1",requestId:randomUUID2(),call});const root=await checkedLocalDirectory(this.options.stateDirectory);const path=localSocketPath(root);await privateAccess(path,"pipe");budget.signal.throwIfAborted();const auth=await localAbortable(Promise.resolve().then(()=>this.options.authorization()),budget.signal);budget.signal.throwIfAborted();if(auth.length!==50||!/^Bearer [A-Za-z0-9_-]{43}$/.test(auth))throw Error();const body=JSON.stringify(input);const reply=await new Promise((resolve,reject)=>{const abort=budget.signal;const req=request2({socketPath:path,method:"POST",path:"/ipc/v1",signal:abort,headers:{authorization:auth,"content-type":"application/json","content-length":Buffer.byteLength(body)}},res=>{const chunks=[];let length=0;res.on("error",reject);res.on("aborted",()=>reject(Error()));res.on("data",b=>{length+=b.length;if(length>256*1024)req.destroy(Error());else chunks.push(b)});res.on("end",()=>{try{resolve(JSON.parse(Buffer.concat(chunks).toString()))}catch{reject(Error())}})});req.on("error",reject);started=true;req.end(body)});const value=LocalIpcResponseSchema.parse(reply);if(value.requestId!==input.requestId&&!(value.requestId===null&&value.semanticStatus!=="SUCCESS"&&["FORBIDDEN","BUSY","INVALID_INPUT"].includes(value.error.code)))throw Error();if(value.semanticStatus!=="SUCCESS")throw new NativeStudioSdkError(value.error.code,value.semanticStatus,readOnly?"NO_WRITE":value.error.code==="INTERNAL_OPERATIONAL_FAILURE"?"UNKNOWN":"REJECTED");if(value.requestId!==input.requestId)throw Error();return value.data}catch(error){if(error instanceof NativeStudioSdkError)throw error;throw new NativeStudioSdkError("LOCAL_RUNTIME_UNAVAILABLE","BLOCKED",started&&!readOnly?"UNKNOWN":"NO_WRITE")}finally{budget.close()}}response(schema,raw){const result=schema.safeParse(raw);if(!result.success)throw new NativeStudioSdkError("LOCAL_RESPONSE_INVALID","BLOCKED","NO_WRITE");return result.data}async status(signal,includeDevice=false){const value=this.response(LocalRuntimeStatusSchema,await this.call({operation:"runtime.status",...includeDevice?{includeDevice:true}:{}},signal));if(this.options.projects&&value.authorizedProjects.some(p=>!this.options.projects.some(q=>q.tenantId===p.tenantId&&q.projectId===p.projectId)))throw new NativeStudioSdkError("LOCAL_SCOPE_INVALID","BLOCKED","NO_WRITE");return value}async doctor(signal){return this.response(LocalDoctorReportSchema,await this.call({operation:"runtime.doctor"},signal))}async inventory(signal){return this.response(LocalManagementInventorySchema,await this.call({operation:"runtime.inventory"},signal))}async grantAgent(raw,approval){return this.response(LocalAgentProbeSchema,await this.call({operation:"agent.grant",grant:LocalAgentGrantSchema.parse(raw),approval}))}async revokeAgent(approval){return this.response(LocalAgentProbeSchema,await this.call({operation:"agent.revoke",approval}))}async probeAgent(){return this.response(LocalAgentProbeSchema,await this.call({operation:"agent.probe"}))}async discoverAgent(binary){return this.response(LocalAgentDiscoverySchema,await this.call({operation:"agent.discover",...binary?{binary}:{}}))}async prepareAgentReview(snapshot){const input=LocalAgentSnapshotSchema.parse(snapshot);const v=this.response(LocalAgentReviewViewSchema,await this.call({operation:"agent.prepare",snapshot:input}));if(canonicalLocalJson(v.plan.snapshot)!==canonicalLocalJson(input))throw new NativeStudioSdkError("LOCAL_RESPONSE_INVALID","BLOCKED","UNKNOWN");return v}async startAgentReview(id,expectedRevision,approval){const v=this.response(LocalAgentReviewViewSchema,await this.call({operation:"agent.start",id,expectedRevision,approval}));if(v.plan.id!==id||v.plan.fingerprint!==approval)throw new NativeStudioSdkError("LOCAL_RESPONSE_INVALID","BLOCKED","UNKNOWN");return v}async stageAgentImage(id,bytes,signal){const budget=localBudget(18e4,signal,18e4);try{return await stageAgentImage(this.options,await this.inspectAgentReview(id,budget.signal),bytes,budget.signal)}finally{budget.close()}}async inspectAgentReview(id,signal){const v=this.response(LocalAgentReviewViewSchema,await this.call({operation:"agent.inspect",id},signal));if(v.plan.id!==id)throw new NativeStudioSdkError("LOCAL_RESPONSE_INVALID","BLOCKED","NO_WRITE");return v}async executions(input,signal){const i=LocalExecutionListInputSchema.parse(input);if(this.options.projects&&!this.options.projects.some(p=>p.tenantId===i.tenantId&&p.projectId===i.projectId))throw new NativeStudioSdkError("FORBIDDEN","BLOCKED","NO_WRITE");const page=this.response(LocalExecutionPageSchema,await this.call({operation:"execution.list",input:i},signal));if(page.items.some(e=>e.binding.tenantId!==i.tenantId||e.binding.projectId!==i.projectId))throw new NativeStudioSdkError("LOCAL_SCOPE_INVALID","BLOCKED","NO_WRITE");return page}async inspect(raw,signal){const input=LocalExecutionInspectInputSchema.parse(raw);if(this.options.projects&&!this.options.projects.some(p=>p.tenantId===input.tenantId&&p.projectId===input.projectId))throw new NativeStudioSdkError("FORBIDDEN","BLOCKED","NO_WRITE");const value=this.response(LocalExecutionInspectionSchema.nullable(),await this.call({operation:"execution.inspect",input},signal));if(value&&["tenantId","projectId","productionId","runtimeJobId"].some(k=>value.binding[k]!==input[k]))throw new NativeStudioSdkError("LOCAL_SCOPE_INVALID","BLOCKED","NO_WRITE");return value}};import{createPublicKey,verify}from"node:crypto";function endpoint(raw){const u=new URL(raw);if(u.username||u.password||u.search||u.hash||u.protocol!=="https:"&&!(u.protocol==="http:"&&["127.0.0.1","localhost","[::1]"].includes(u.hostname)))fail("RELEASE_ORIGIN_INVALID");return u}async function fetchBytes(raw,maximum,origin,signal=AbortSignal.timeout(3e4)){const u=endpoint(raw);if(u.origin!==origin)fail("RELEASE_ORIGIN_INVALID");const r=await fetch(u,{redirect:"error",signal,headers:{accept:"application/octet-stream"}});if(!r.ok||Number(r.headers.get("content-length"))>maximum){await r.body?.cancel();fail("RELEASE_UNAVAILABLE")}const parts=[];let size=0;for await(const part of r.body??[]){size+=part.byteLength;if(size>maximum){await r.body?.cancel().catch(()=>{});fail("RELEASE_LIMIT")}parts.push(part)}return Buffer.concat(parts)}async function catalogue(trust,signal){const origin=endpoint(trust.catalogueUrl).origin;const bytes=await fetchBytes(trust.catalogueUrl,65536,origin,signal??AbortSignal.timeout(3e4));const signed=LocalSignedCatalogueSchema.parse(JSON.parse(bytes.toString()));const key=createPublicKey((await read(trust.publicKeyFile,16384)).toString());if(key.asymmetricKeyType!=="ed25519"||!verify(null,Buffer.from(canonicalLocalJson(signed.catalogue)),key,Buffer.from(signed.signature,"base64url")))fail("RELEASE_SIGNATURE_INVALID");const now=Date.now();if(Date.parse(signed.catalogue.issuedAt)>now||Date.parse(signed.catalogue.expiresAt)<=now)fail("RELEASE_EXPIRED");for(const release of signed.catalogue.releases){for(const a of[release.package,...release.tools?Object.values(release.tools):[]])if(endpoint(a.url).origin!==origin)fail("RELEASE_ORIGIN_INVALID")}return{signed,fingerprint:sha256(canonicalLocalJson(signed.catalogue)),origin,trustFingerprint:sha256(canonicalLocalJson({catalogueUrl:endpoint(trust.catalogueUrl).href,publicKey:key.export({type:"spki",format:"der"}).toString("base64")}))}}function select(signed,version){const r=signed.catalogue.releases.find(r2=>r2.descriptor.version===version&&r2.descriptor.platform.os===process.platform&&r2.descriptor.platform.architecture===process.arch);if(!r)fail("VERSION_INCOMPATIBLE");const[major,minor]=process.versions.node.split(".").map(Number);if(major!==r.descriptor.node.major||minor<r.descriptor.node.minMinor)fail("NODE_VERSION_INCOMPATIBLE");return r}async function asset(a,origin){const bytes=await fetchBytes(a.url,a.byteSize,origin,AbortSignal.timeout(12e4));if(bytes.length!==a.byteSize||sha512(bytes)!==a.sha512)fail("RELEASE_INTEGRITY_INVALID");return bytes}export{EnrollLocalDeviceSchema,LocalDeviceViewSchema,LocalDeviceChallengeSchema,GrantLocalDeviceSchema,LocalDeviceGrantSchema,RevokeLocalDeviceGrantSchema,RevokeLocalDeviceSchema,LocalOfflineCallSchema,LocalOfflinePageSchema,LocalAgentGrantSchema,LocalAgentDiscoverySchema,LocalToolSelectionSchema,LocalRuntimeDescriptorSchema,LocalManagementInventorySchema,LocalReleaseSchema,LocalToolChoiceSchema,LocalUpdatePlanSchema,LocalResourcePolicySchema,LocalWorkspaceInspectionSchema,LocalDiagnosticsSchema,canonicalLocalJson,LocalAgentSnapshotSchema,LocalAgentProbeSchema,LocalAgentReviewViewSchema,localAgentSnapshotFromContext,localAgentNativeProposal,LocalExecutionListInputSchema,LocalExecutionInspectInputSchema,LocalDoctorReportSchema,StartLocalPreviewSchema,LocalDeviceSessionSchema,LocalDeviceTransportConfigurationSchema,LocalPreviewAdmissionSchema,StartLocalFinalRenderSchema,LocalFinalRenderAdmissionSchema,LocalMcpFailureSchema,LocalMcpOutputSchemas,LocalManagementCommandSchema,LocalManagementResultSchema,NativeStudioLocalDeviceClient,NativeStudioLocalRuntimeClient,endpoint,catalogue,select,asset};
|
|
1
|
+
import{fail,localSocketPath,privateAccess,privateDirectory,read,sha256,sha512}from"./chunk-KB2GVAN7.js";import{CaptionRenderStyleSchema,FinalRenderAdmissionSchema,FinalRenderManifestReaderSchema,FinalRenderStartSchema,KeyframeObservationSchema,NativeRuntimePublicKeySchema,ReviewEvidenceMediaSchema,ReviewIntelligenceBasisSchema,ReviewIntelligenceContextResultSchema,RoughCutAdmissionSchema,RoughCutManifestReaderSchema,RoughCutRequirementSchema,RoughCutStartSchema,RoughCutTechnicalSchema,ValidateReviewIntelligenceSchema,VideoReviewRequirementSchema,VideoTechnicalMetadataSchema,VisualLayerCompositionSchema,VisualRequirementSchema}from"./chunk-PBEHCYR7.js";import{OperationIdSchema}from"./chunk-VPYAXWXY.js";import{NativeStudioSdkError}from"./chunk-6NVIN2NI.js";import{z as z2}from"zod";import{z}from"zod";var LocalIdSchema=z.uuid().transform(v=>v.toLowerCase());var LocalDigestSchema=z.string().length(64).regex(/^[0-9a-f]{64}$/);var LocalRevisionSchema=z.int().positive();var LocalTimeSchema=z.iso.datetime({offset:true});var LocalPackageVersionSchema=z.string().max(120).regex(/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-(?:0|[1-9]\d*|\d*[A-Za-z-][0-9A-Za-z-]*)(?:\.(?:0|[1-9]\d*|\d*[A-Za-z-][0-9A-Za-z-]*))*)?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/).refine(v=>v===v.trim());var LocalProjectScopeSchema=z.strictObject({tenantId:LocalIdSchema,projectId:LocalIdSchema});var LocalWorkScopeSchema=LocalProjectScopeSchema.extend({productionId:LocalIdSchema,runtimeJobId:LocalIdSchema});var LocalPlacementPolicySchema=z.discriminatedUnion("mode",[z.strictObject({mode:z.literal("local-only"),deviceId:LocalIdSchema}),z.strictObject({mode:z.literal("local-preferred"),deviceId:LocalIdSchema}),z.strictObject({mode:z.literal("cloud-only")})]);var LocalPlacementAvailabilitySchema=z.discriminatedUnion("status",[z.strictObject({status:z.literal("AVAILABLE"),deviceId:LocalIdSchema}),z.strictObject({status:z.literal("UNAVAILABLE"),deviceId:LocalIdSchema,reason:z.enum(["OFFLINE","UNQUALIFIED","BUSY"])}),z.strictObject({status:z.literal("DENIED"),reason:z.enum(["FORBIDDEN","APPROVAL_REQUIRED","INVALID_INPUT"])})]);var LocalDevicePlatformSchema=z2.strictObject({os:z2.enum(["darwin","linux","win32"]),architecture:z2.enum(["x64","arm64"])});var EnrollLocalDeviceSchema=z2.strictObject({tenantId:LocalIdSchema,requestId:LocalIdSchema,label:z2.string().trim().min(1).max(120),platform:LocalDevicePlatformSchema,runtimeVersion:LocalPackageVersionSchema,publicKey:NativeRuntimePublicKeySchema});var LocalDeviceViewSchema=EnrollLocalDeviceSchema.omit({requestId:true}).extend({deviceId:LocalIdSchema,revision:LocalRevisionSchema,enrolledByPrincipalId:LocalIdSchema,createdAt:LocalTimeSchema,verifiedAt:LocalTimeSchema.nullable(),revokedAt:LocalTimeSchema.nullable()}).refine(v=>[v.verifiedAt,v.revokedAt].every(time=>time===null||Date.parse(time)>=Date.parse(v.createdAt)));var LocalDeviceChallengeSchema=z2.strictObject({tenantId:LocalIdSchema,deviceId:LocalIdSchema,deviceRevision:LocalRevisionSchema,challengeId:LocalIdSchema,audience:z2.string().min(1).max(2048),issuedAt:LocalTimeSchema,expiresAt:LocalTimeSchema}).refine(v=>{const ttl=Date.parse(v.expiresAt)-Date.parse(v.issuedAt);return ttl>0&&ttl<=3e5});var LocalDeviceProofClaimsSchema=z2.strictObject({protocol:z2.literal("NVS_LOCAL_DEVICE_PROOF_V1"),tenantId:LocalIdSchema,deviceId:LocalIdSchema,deviceRevision:LocalRevisionSchema,challengeId:LocalIdSchema,audience:z2.string().min(1).max(2048),jti:LocalIdSchema,iat:z2.int().nonnegative(),exp:z2.int().positive()}).refine(v=>v.exp>v.iat&&v.exp-v.iat<=60);var ProveLocalDeviceSchema=z2.strictObject({tenantId:LocalIdSchema,deviceId:LocalIdSchema,deviceRevision:LocalRevisionSchema,challengeId:LocalIdSchema,assertion:z2.string().max(4096).regex(/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/).meta({writeOnly:true})});var GrantLocalDeviceSchema=LocalProjectScopeSchema.extend({requestId:LocalIdSchema,executionPolicy:z2.literal("DEVICE_ONLY").optional(),deviceId:LocalIdSchema,deviceRevision:LocalRevisionSchema,expectedRevision:z2.int().nonnegative(),expiresAt:LocalTimeSchema,capability:z2.enum(["ROUGH_CUT_PREVIEW_V1","STUDIO_MEDIA_V2"])});var LocalDeviceGrantSchema=GrantLocalDeviceSchema.omit({requestId:true,expectedRevision:true}).extend({grantId:LocalIdSchema,revision:LocalRevisionSchema,approvedByPrincipalId:LocalIdSchema,createdAt:LocalTimeSchema,revokedAt:LocalTimeSchema.nullable()}).refine(v=>Date.parse(v.expiresAt)>Date.parse(v.createdAt));var RevokeLocalDeviceGrantSchema=LocalProjectScopeSchema.extend({grantId:LocalIdSchema,requestId:LocalIdSchema,expectedRevision:LocalRevisionSchema});var RevokeLocalDeviceSchema=z2.strictObject({tenantId:LocalIdSchema,deviceId:LocalIdSchema,requestId:LocalIdSchema,expectedRevision:LocalRevisionSchema});import{z as z5}from"zod";import{z as z4}from"zod";import{z as z3}from"zod";var pixel=z3.int().nonnegative().max(4096);var dimension=z3.int().positive().max(4096);var frame=z3.int().nonnegative().max(1800);var sample=z3.int().nonnegative().max(288e4);var rectangle=z3.strictObject({x:pixel,y:pixel,width:dimension,height:dimension});var window=z3.strictObject({start:sample,count:sample});var source=z3.strictObject({representationId:z3.uuid(),checksum:LocalDigestSchema,byteSize:z3.int().positive().max(134217728)});var LocalMediaRecipeSchema=z3.strictObject({protocol:z3.literal("NVS_RESOLVED_MEDIA_RECIPE_V2"),family:z3.enum(["ROUGH_CUT_RENDER","FINAL_RENDER"]),width:dimension,height:dimension,totalFrames:z3.int().min(900).max(1800),crf:z3.union([z3.literal(18),z3.literal(23)]),algorithm:z3.enum(["ORDERED_TRIM_CUT_V1","ORDERED_COMPOSE_V2"]),clips:z3.array(z3.strictObject({representationId:z3.uuid(),technical:VideoTechnicalMetadataSchema,sourceInMs:z3.int().nonnegative().max(6e4),sourceOutMs:z3.int().positive().max(6e4),startFrame:frame,frameCount:z3.int().positive().max(1800),overlapFrames:frame,crop:rectangle.nullable(),viewport:rectangle})).min(1).max(32),caption:z3.strictObject({style:CaptionRenderStyleSchema,references:z3.array(z3.strictObject({representationId:z3.uuid(),expectedUtf8:z3.string().max(65536)})).length(2),cues:z3.array(z3.strictObject({ordinal:z3.int().nonnegative().max(512),startFrame:frame,endFrame:frame,fontSize:z3.int().min(16).max(256),margin:pixel,text:z3.string().min(1).max(2e3)})).min(1).max(512)}).nullable(),audio:z3.strictObject({algorithm:z3.literal("PCM_WINDOW_MIX_AAC_V1"),tracks:z3.array(source.extend({channels:z3.union([z3.literal(1),z3.literal(2)]),sampleCount:z3.int().positive().max(288e4),sourceIn:sample,sourceOut:sample,start:sample,count:sample,gain:z3.int().nonnegative().max(1e3),duck:z3.int().nonnegative().max(1e3),duckWindows:z3.array(window).max(512)})).min(1).max(266)}).nullable(),graphics:z3.array(source.extend({contentType:z3.enum(["image/png","image/webp"]),sourceWidth:dimension,sourceHeight:dimension,width:dimension,height:dimension,x:pixel,y:pixel,startFrame:frame,endFrame:frame,opacity:z3.number().min(.1).max(1)})).max(8),visual:z3.strictObject({composition:VisualLayerCompositionSchema,plans:z3.array(z3.strictObject({id:z3.uuid(),startFrame:frame,endFrame:frame,width:dimension,height:dimension,x:pixel,y:pixel,opacityPermille:z3.int().min(0).max(1e3)})).max(8)}).nullable()}).superRefine((r,ctx)=>{if(r.width%2||r.height%2||r.clips.some(c=>c.viewport.x+c.viewport.width>r.width||c.viewport.y+c.viewport.height>r.height||c.sourceOutMs<=c.sourceInMs)||r.audio?.tracks.some(t=>t.sourceIn>=t.sourceOut||t.sourceOut>t.sampleCount||t.start+t.count>r.totalFrames*1600))ctx.addIssue({code:"custom",message:"Invalid bounded execution geometry or sample window"})});var previewProfile=z4.strictObject({kind:z4.literal("ROUGH_CUT_PREVIEW_V1"),profileId:z4.literal("PREVIEW_H264_480P_V1"),contractDigest:LocalDigestSchema});var studioProfile=z4.strictObject({kind:z4.literal("STUDIO_MEDIA_V2"),profileId:z4.literal("STUDIO_MEDIA_V2"),contractDigest:LocalDigestSchema});var LocalExecutionProfileSchema=z4.discriminatedUnion("kind",[previewProfile,studioProfile]);var LocalToolchainSchema=z4.strictObject({platform:LocalDevicePlatformSchema,rendererVersion:LocalPackageVersionSchema,rendererDigest:LocalDigestSchema,ffmpeg:z4.strictObject({version:z4.string().min(1).max(160),binaryDigest:LocalDigestSchema}),ffprobe:z4.strictObject({version:z4.string().min(1).max(160),binaryDigest:LocalDigestSchema}),profile:LocalExecutionProfileSchema,supported:z4.array(z4.strictObject({profile:LocalExecutionProfileSchema,rendererVersion:LocalPackageVersionSchema,rendererDigest:LocalDigestSchema})).max(4).optional()});var frozen=LocalWorkScopeSchema.extend({protocol:z4.literal("NVS_LOCAL_WORK_V1"),operationId:OperationIdSchema,renderId:LocalIdSchema,productionRevision:LocalRevisionSchema,executionClass:z4.enum(["LIVE","TEST_ONLY"]),policy:LocalPlacementPolicySchema,profile:previewProfile,manifest:RoughCutManifestReaderSchema,manifestFingerprint:LocalDigestSchema,sources:z4.array(z4.strictObject({artifactId:LocalIdSchema,representationId:LocalIdSchema,checksumSha256:LocalDigestSchema,byteSize:z4.int().positive(),contentType:z4.string().min(1).max(100)})).min(1).max(512)});var studio=frozen.extend({protocol:z4.literal("NVS_LOCAL_WORK_V2"),profile:studioProfile,manifest:z4.union([RoughCutManifestReaderSchema,FinalRenderManifestReaderSchema]),recipe:LocalMediaRecipeSchema,recipeFingerprint:LocalDigestSchema});var LocalFrozenWorkSchema=z4.discriminatedUnion("protocol",[frozen,studio]).superRefine((v,ctx)=>{const t=v.manifest.timeline;if(t.tenantId!==v.tenantId||t.projectId!==v.projectId||t.productionId!==v.productionId||t.executionClass!==v.executionClass)ctx.addIssue({code:"custom",message:"Frozen manifest scope/class mismatch"});if(new Set(v.sources.map(s=>s.representationId)).size!==v.sources.length)ctx.addIssue({code:"custom",message:"Duplicate source representation"});if(v.protocol==="NVS_LOCAL_WORK_V2"&&(v.recipe.width!==v.manifest.profile.width||v.recipe.height!==v.manifest.profile.height||v.recipe.totalFrames!==v.manifest.totalFrames||v.recipe.family==="FINAL_RENDER"!=="selection"in v.manifest))ctx.addIssue({code:"custom",message:"Recipe must match its native render family and geometry"})});var LocalLeaseBindingSchema=LocalWorkScopeSchema.extend({attemptId:LocalIdSchema,assignmentRevision:LocalRevisionSchema,workerId:z4.string().min(1).max(200),workFingerprint:LocalDigestSchema,toolchainFingerprint:LocalDigestSchema});var target=z4.discriminatedUnion("kind",[z4.strictObject({kind:z4.literal("DEVICE"),deviceId:LocalIdSchema,deviceRevision:LocalRevisionSchema,grantId:LocalIdSchema,grantRevision:LocalRevisionSchema}),z4.strictObject({kind:z4.literal("SERVER")})]);var LocalExecutionLeaseSchema=LocalLeaseBindingSchema.extend({target,issuedAt:LocalTimeSchema,expiresAt:LocalTimeSchema}).refine(v=>Date.parse(v.expiresAt)>Date.parse(v.issuedAt));var LocalWorkAssignmentSchema=z4.strictObject({work:LocalFrozenWorkSchema,lease:LocalExecutionLeaseSchema,toolchain:LocalToolchainSchema}).superRefine(({work,lease,toolchain},ctx)=>{if(["tenantId","projectId","productionId","runtimeJobId"].some(k=>work[k]!==lease[k]))ctx.addIssue({code:"custom",message:"Assignment work scope mismatch"});const p=work.policy,t=lease.target;if(p.mode==="cloud-only"&&t.kind!=="SERVER"||p.mode==="local-only"&&t.kind!=="DEVICE"||t.kind==="DEVICE"&&(p.mode==="cloud-only"||p.deviceId!==t.deviceId))ctx.addIssue({code:"custom",message:"Assignment contradicts placement policy"});if(work.profile.contractDigest!==toolchain.profile.contractDigest)ctx.addIssue({code:"custom",message:"Unqualified execution profile"})});var StartLocalPreviewSchema=RoughCutStartSchema.omit({deviceExecution:true}).extend({placement:LocalPlacementPolicySchema,localProfile:z5.literal("STUDIO_MEDIA_V2").optional()});var LocalDeviceScopeSchema=z5.strictObject({tenantId:LocalIdSchema,deviceId:LocalIdSchema});var LocalDeviceSessionSchema=z5.strictObject({...LocalDeviceScopeSchema.shape,expiresAt:LocalTimeSchema,credential:z5.string().length(43).regex(/^[A-Za-z0-9_-]+$/).meta({writeOnly:true})});var LocalDeviceHeartbeatSchema=LocalDeviceScopeSchema.extend({toolchain:LocalToolchainSchema,available:z5.boolean(),maxConcurrentJobs:z5.int().min(1).max(2).optional()});var ClaimLocalPreviewSchema=LocalProjectScopeSchema.extend({requestId:LocalIdSchema,deviceId:LocalIdSchema});var LocalOutputStageSchema=LocalLeaseBindingSchema.extend({uploadRequestId:LocalIdSchema,role:z5.enum(["VIDEO","POSTER"]),checksumSha256:LocalDigestSchema,byteSize:z5.int().positive().max(128*1024*1024)});var LocalOutputTicketSchema=z5.strictObject({receiptId:LocalIdSchema,role:z5.enum(["VIDEO","POSTER"]),checksumSha256:LocalDigestSchema,byteSize:z5.int().positive(),uploaded:z5.boolean()});var LocalSourceRequestSchema=LocalLeaseBindingSchema.extend({representationId:LocalIdSchema});var LocalProofChallengeRequestSchema=LocalDeviceScopeSchema.extend({deviceRevision:z5.int().positive()});var LocalPreviewPlacementViewSchema=z5.strictObject({target:z5.enum(["DEVICE","SERVER"]),reason:z5.enum(["LOCAL_AVAILABLE","CLOUD_ONLY","OFFLINE","UNQUALIFIED","BUSY","LEASE_RECOVERY"]),policy:LocalPlacementPolicySchema});var LocalDeviceTransportConfigurationSchema=z5.strictObject({endpoint:z5.string().url().max(2048),tenantId:LocalIdSchema,deviceId:LocalIdSchema,deviceRevision:z5.int().positive(),projects:z5.array(LocalProjectScopeSchema).min(1).max(20),privateKeyFile:z5.string().min(1).max(4096),platform:LocalDevicePlatformSchema});var LocalPreviewAdmissionSchema=RoughCutAdmissionSchema.extend({placement:LocalPreviewPlacementViewSchema});var StartLocalFinalRenderSchema=FinalRenderStartSchema.omit({deviceExecution:true}).extend({placement:LocalPlacementPolicySchema});var LocalFinalRenderAdmissionSchema=FinalRenderAdmissionSchema.extend({placement:LocalPreviewPlacementViewSchema});var LocalClaimReceiptSchema=z5.strictObject({found:z5.boolean(),assignment:LocalWorkAssignmentSchema.nullable()});var LocalWorkStateSchema=z5.strictObject({binding:LocalLeaseBindingSchema,status:z5.enum(["ACTIVE","FENCED","OUTCOME_UNKNOWN"]),assignment:LocalWorkAssignmentSchema.nullable()});import{z as z14}from"zod";import{z as z7}from"zod";import{z as z6}from"zod";var executable=z6.strictObject({path:z6.string().min(1).max(4096),digest:LocalDigestSchema});var LocalToolSelectionSchema=z6.strictObject({mode:z6.enum(["MANAGED","INSTALLED"]),ffmpeg:executable,ffprobe:executable});var LocalRuntimeDescriptorSchema=z7.strictObject({protocol:z7.literal("NVS_RUNTIME_DESCRIPTOR_V1"),version:LocalPackageVersionSchema,node:z7.strictObject({major:z7.literal(24),minMinor:z7.literal(12)}),platform:LocalDevicePlatformSchema,ipcProtocol:z7.literal("NVS_LOCAL_IPC_V1"),workProtocol:z7.enum(["NVS_LOCAL_WORK_V1","NVS_LOCAL_WORK_V2"]),journalSchema:z7.literal(1),rendererDigest:LocalDigestSchema,profileDigest:LocalDigestSchema,compatibleRenderers:z7.array(z7.strictObject({rendererDigest:LocalDigestSchema,profileDigest:LocalDigestSchema})).max(4).optional()});var LocalSessionConnectorSchema=z7.strictObject({protocol:z7.literal("NVS_LOCAL_CONNECTOR_V1"),stateDirectory:z7.string().min(1).max(4096),credential:z7.string().length(43).regex(/^[A-Za-z0-9_-]{43}$/),expiresAt:LocalTimeSchema,projects:z7.array(LocalProjectScopeSchema).min(1).max(100)});var LocalManagementInventorySchema=z7.strictObject({runtimeRevision:z7.int().positive(),descriptor:LocalRuntimeDescriptorSchema,activeProcesses:z7.int().nonnegative(),pendingExecutions:z7.int().nonnegative(),pendingRequests:z7.int().nonnegative(),pendingRenderers:z7.array(LocalDigestSchema).max(64)});var LocalReleaseAssetSchema=z7.strictObject({url:z7.string().url().max(2048),byteSize:z7.int().positive().max(256*1024*1024),sha512:z7.string().length(128).regex(/^[0-9a-f]{128}$/)});var LocalReleaseSchema=z7.strictObject({descriptor:LocalRuntimeDescriptorSchema,package:LocalReleaseAssetSchema,tools:z7.strictObject({ffmpeg:LocalReleaseAssetSchema.extend({sha256:LocalDigestSchema}),ffprobe:LocalReleaseAssetSchema.extend({sha256:LocalDigestSchema})}).nullable()});var LocalReleaseCatalogueSchema=z7.strictObject({protocol:z7.literal("NVS_LOCAL_RELEASE_CATALOGUE_V1"),issuedAt:LocalTimeSchema,expiresAt:LocalTimeSchema,releases:z7.array(LocalReleaseSchema).min(1).max(32)}).refine(v=>Date.parse(v.expiresAt)>Date.parse(v.issuedAt)&&Date.parse(v.expiresAt)-Date.parse(v.issuedAt)<=7*864e5&&new Set(v.releases.map(r=>[r.descriptor.version,r.descriptor.platform.os,r.descriptor.platform.architecture].join(":"))).size===v.releases.length);var LocalSignedCatalogueSchema=z7.strictObject({catalogue:LocalReleaseCatalogueSchema,signature:z7.string().length(86).regex(/^[A-Za-z0-9_-]{85}[AQgw]$/)});var LocalToolChoiceSchema=z7.discriminatedUnion("mode",[z7.strictObject({mode:z7.literal("MANAGED")}),LocalToolSelectionSchema.extend({mode:z7.literal("INSTALLED")})]);var LocalUpdatePlanSchema=z7.strictObject({protocol:z7.literal("NVS_LOCAL_UPDATE_PLAN_V1"),planId:LocalIdSchema,installationRevision:z7.int().nonnegative(),runtimeRevision:z7.int().positive().nullable(),catalogueFingerprint:LocalDigestSchema,trustFingerprint:LocalDigestSchema.optional(),release:LocalReleaseSchema,toolSelection:LocalToolChoiceSchema.optional(),fingerprint:LocalDigestSchema,createdAt:LocalTimeSchema,expiresAt:LocalTimeSchema});var LocalClientNextActionSchema=z7.strictObject({surface:z7.enum(["CLI","LOCAL_IPC","REMOTE"]),operation:z7.enum(["runtime.status","local.configure","local.install","local.start","local.connect","local.grant","local.status","local.doctor","local.stop","local.update.check","local.update.prepare","local.update.apply","local.update.reconcile","execution.inspect","rough_cut_get","operation_get"]),availability:z7.enum(["AVAILABLE","BLOCKED"]),reason:z7.enum(["READY","INSTALL_REQUIRED","AUTHORIZATION_REQUIRED","VERSION_INCOMPATIBLE","UPDATE_AVAILABLE","RECOVERY_REQUIRED","USER_APPROVAL_REQUIRED","TRUST_REQUIRED","UNAVAILABLE"])});import{z as z13}from"zod";import{z as z8}from"zod";var LocalOfflineSnapshotSchema=z8.strictObject({projectId:z8.uuid(),title:z8.string().min(1).max(200),savedAt:LocalTimeSchema,expiresAt:LocalTimeSchema,productions:z8.array(z8.strictObject({id:z8.uuid(),title:z8.string().max(200)})).max(40),possiblyTruncated:z8.boolean()}).refine(v=>new TextEncoder().encode(JSON.stringify(v)).length<=8192);var text=z8.string().max(4e3).refine(v=>new TextEncoder().encode(JSON.stringify(v)).length<=8192);var LocalOfflineCallSchema=z8.discriminatedUnion("action",[z8.strictObject({action:z8.enum(["list","forget"]),key:LocalDigestSchema}),z8.strictObject({action:z8.literal("retain"),key:LocalDigestSchema,snapshot:LocalOfflineSnapshotSchema}),z8.strictObject({action:z8.literal("draft"),key:LocalDigestSchema,projectId:z8.uuid(),text,expectedRevision:z8.int().nonnegative()})]);var LocalOfflinePageSchema=z8.strictObject({historical:z8.literal(true),items:z8.array(z8.strictObject({snapshot:LocalOfflineSnapshotSchema,draft:z8.strictObject({text,revision:z8.int().nonnegative()})})).max(3)});import{z as z10}from"zod";import{z as z9}from"zod";var QualifiedLocalAgentVersionSchema=z9.enum(["0.164.0","0.165.0"]);var LocalAgentGrantSchema=z9.strictObject({protocol:z9.literal("NVS_CODEX_REVIEW_GRANT_V1"),binary:z9.string().min(1).max(4096).refine(v=>/^(?:\/|[A-Za-z]:[\\/])/.test(v)),binaryDigest:z9.string().regex(/^[a-f0-9]{64}$/),version:QualifiedLocalAgentVersionSchema,model:z9.string().regex(/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,99}$/),reasoningEffort:z9.enum(["low","medium","high","xhigh"]).optional(),reviewerLabel:z9.string().trim().min(1).max(100),inference:z9.literal("REMOTE_OPENAI"),remoteUseApproved:z9.literal(true),imageDisclosureApproved:z9.literal(true).optional(),mediaDisclosureApproved:z9.literal(true).optional(),projects:z9.array(LocalProjectScopeSchema).min(1).max(100),expiresAt:z9.iso.datetime({offset:true})});var LocalAgentMediaInputSchema=z10.strictObject({profile:z10.literal("NVS_AGENT_DERIVED_EVIDENCE_V1"),contentType:z10.enum(["image/png","image/jpeg","image/webp","video/mp4"]),byteSize:z10.int().positive().max(134217728),width:z10.int().positive().max(4096),height:z10.int().positive().max(4096),durationMs:z10.int().positive().max(6e4).optional(),frameRate:z10.union([z10.literal(24),z10.literal(30)]).optional(),hasAudio:z10.boolean().optional()}).refine(v=>v.contentType==="video/mp4"?!!v.durationMs&&!!v.frameRate:!v.durationMs&&!v.frameRate&&v.hasAudio===void 0);var sha=z10.string().regex(/^[a-f0-9]{64}$/);var LocalAgentEvidenceReceiptSchema=z10.strictObject({protocol:z10.literal("NVS_AGENT_DERIVED_EVIDENCE_V1"),draftId:z10.uuid(),media:ReviewEvidenceMediaSchema,ffmpegDigest:sha,ffprobeDigest:sha,attachment:z10.strictObject({checksumSha256:sha,byteSize:z10.int().positive().max(8388608),width:z10.int().positive().max(4096),height:z10.int().positive().max(4096)}),timestampsMs:z10.array(z10.number().nonnegative().max(6e4)).max(6),audio:z10.strictObject({sampleRateHz:z10.literal(48e3),channels:z10.literal(1),samples:z10.int().positive().max(2881024),peak:z10.number().min(0).max(1),rms:z10.number().min(0).max(1),clippedSamples:z10.int().nonnegative().max(2881024)}).nullable(),limitations:z10.tuple([z10.literal("SAMPLED_FRAMES_ARE_NOT_FULL_PLAYBACK"),z10.literal("AUDIO_STATISTICS_ARE_NOT_LISTENING_OR_TRANSCRIPTION")])});var LocalAgentDiscoverySchema=z10.strictObject({candidate:z10.strictObject({binary:z10.string().min(1).max(4096),binaryDigest:sha,version:z10.string().regex(/^\d+\.\d+\.\d+$/),qualified:z10.boolean()}).nullable(),configured:LocalAgentGrantSchema.nullable()});import{z as z11}from"zod";var LocalResourcePolicySchema=z11.strictObject({mode:z11.enum(["CONTINUOUS","IDLE_ONLY"]).default("CONTINUOUS"),idleAfterSeconds:z11.int().min(30).max(3600).default(300),maxConcurrentJobs:z11.int().min(1).max(2).default(1),cpuCores:z11.union([z11.literal(1),z11.literal(2)]).default(2),memoryMiB:z11.int().min(512).max(4096).default(4096),cacheQuotaBytes:z11.int().min(512*1024*1024).max(32*1024*1024*1024).default(1024*1024*1024)});var LocalResourceSettingsSchema=z11.strictObject({revision:z11.int().nonnegative(),policy:LocalResourcePolicySchema});var LocalExecutionProgressSchema=z11.strictObject({stage:z11.enum(["WAITING","DOWNLOADING","EXECUTING","UPLOADING","AWAITING_ACCEPTANCE","COMPLETE","RECOVERY_REQUIRED","FENCED"]),downloadedBytes:z11.int().nonnegative(),sourceBytes:z11.int().nonnegative(),uploadedBytes:z11.int().nonnegative(),outputBytes:z11.int().nonnegative(),lastError:z11.strictObject({code:z11.string().regex(/^[A-Z][A-Z0-9_]{0,79}$/),observedAt:LocalTimeSchema}).nullable()});var LocalStorageInspectionSchema=z11.strictObject({cacheBytes:z11.int().nonnegative(),protectedBytes:z11.int().nonnegative(),reclaimableBytes:z11.int().nonnegative(),transferBytes:z11.int().nonnegative(),journalBytes:z11.int().nonnegative(),reviewBytes:z11.int().nonnegative().optional(),ownerStagingBytes:z11.int().nonnegative().optional(),availableDiskBytes:z11.int().nonnegative(),quotaBytes:z11.int().positive(),overQuota:z11.boolean()});var LocalWorkspaceInspectionSchema=z11.strictObject({settings:LocalResourceSettingsSchema,storage:LocalStorageInspectionSchema,scheduling:z11.strictObject({state:z11.enum(["READY","WAITING_FOR_IDLE","AT_CAPACITY","DRAINING"]),activeJobs:z11.int().nonnegative(),idleObservationCurrent:z11.boolean()})});var LocalDiagnosticsSchema=z11.strictObject({protocol:z11.literal("NVS_LOCAL_DIAGNOSTICS_V1"),createdAt:LocalTimeSchema,runtimeVersion:z11.string().min(1).max(80),runtimeRevision:LocalRevisionSchema,settings:LocalResourceSettingsSchema,storage:LocalStorageInspectionSchema,recordCounts:z11.record(z11.string().regex(/^[A-Z_]{1,40}$/),z11.int().nonnegative()),failures:z11.array(z11.strictObject({taskFingerprint:z11.string().regex(/^[a-f0-9]{64}$/),code:z11.string().regex(/^[A-Z][A-Z0-9_]{0,79}$/),observedAt:LocalTimeSchema})).max(32)});import{z as z12}from"zod";function canonicalLocalJson(value){if(value===null||typeof value==="string"||typeof value==="boolean")return JSON.stringify(value);if(typeof value==="number"&&Number.isFinite(value))return JSON.stringify(value);if(Array.isArray(value))return"["+value.map(canonicalLocalJson).join(",")+"]";if(typeof value==="object")return"{"+Object.entries(value).filter(([,v])=>v!==void 0).sort(([a],[b])=>a<b?-1:a>b?1:0).map(([k,v])=>JSON.stringify(k)+":"+canonicalLocalJson(v)).join(",")+"}";throw new Error("Fingerprint input must be finite JSON data")}var sha2=z12.string().regex(/^[a-f0-9]{64}$/);var qualifiedVersion=QualifiedLocalAgentVersionSchema;var LocalAgentSnapshotSchema=z12.strictObject({basis:ReviewIntelligenceBasisSchema,productionRevision:z12.int().positive(),reviewVersion:z12.int().nonnegative(),executionClass:z12.enum(["LIVE","TEST_ONLY"]),media:ReviewEvidenceMediaSchema,requirements:z12.array(z12.union([VisualRequirementSchema,VideoReviewRequirementSchema,RoughCutRequirementSchema])).min(1).max(64),evidence:LocalAgentMediaInputSchema.optional(),image:z12.strictObject({contentType:z12.literal("image/png"),byteSize:z12.int().positive().max(8388608),width:z12.int().positive().max(4096),height:z12.int().positive().max(4096)}).optional()}).refine(v=>!v.image||!v.evidence&&v.basis.target.kind==="IMAGE").refine(v=>v.basis.target.kind==="IMAGE"||!v.evidence||v.evidence.contentType==="video/mp4").refine(v=>new TextEncoder().encode(JSON.stringify(v)).length<=32768).refine(v=>new Set(v.requirements.map(r=>r.key)).size===v.requirements.length);var LocalAgentProbeSchema=z12.strictObject({configured:z12.boolean(),available:z12.boolean(),reason:z12.enum(["GRANT_REQUIRED","READY","RUNTIME_UNAVAILABLE","GRANT_EXPIRED"]),grantFingerprint:sha2.nullable(),inference:z12.literal("REMOTE_OPENAI")});var LocalAgentPlanSchema=z12.strictObject({protocol:z12.enum(["NVS_LOCAL_AGENT_REVIEW_V1","NVS_LOCAL_AGENT_REVIEW_V2"]),id:z12.uuid(),grantFingerprint:sha2,snapshot:LocalAgentSnapshotSchema,expiresAt:z12.iso.datetime({offset:true}),fingerprint:sha2});var LocalAgentMetadataAnswerSchema=z12.strictObject({summary:z12.string().trim().min(1).max(1500),observations:z12.array(z12.strictObject({key:z12.string().min(1).max(220),observed:z12.string().trim().min(1).max(1e3)})).min(1).max(64)});var LocalAgentPixelAnswerSchema=z12.strictObject({summary:z12.string().trim().min(1).max(1500),imageReadback:z12.string().trim().min(1).max(800),observations:z12.array(KeyframeObservationSchema.omit({region:true}).extend({key:z12.string().min(1).max(220)})).min(1).max(64)});var LocalAgentAnswerSchema=z12.union([LocalAgentMetadataAnswerSchema,LocalAgentPixelAnswerSchema]).refine(v=>new TextEncoder().encode(JSON.stringify(v)).length<=96*1024);var LocalAgentImageReceiptSchema=z12.strictObject({protocol:z12.literal("NVS_LOCAL_AGENT_IMAGE_V1"),draftId:z12.uuid(),media:ReviewEvidenceMediaSchema,byteSize:z12.int().positive().max(8388608),contentType:z12.literal("image/png"),width:z12.int().positive().max(4096),height:z12.int().positive().max(4096)});var LocalAgentReviewViewSchema=z12.strictObject({plan:LocalAgentPlanSchema,revision:z12.int().positive(),phase:z12.enum(["PREPARED","RUNNING","RESULT_PENDING","UNKNOWN"]),answer:LocalAgentAnswerSchema.nullable(),imageReceipt:LocalAgentImageReceiptSchema.optional(),evidenceReceipt:LocalAgentEvidenceReceiptSchema.optional(),provenance:z12.strictObject({adapter:z12.enum(["CODEX_METADATA_V1","CODEX_MEDIA_V2"]),binaryDigest:sha2,version:qualifiedVersion,model:z12.string().max(100),reasoningEffort:z12.enum(["low","medium","high","xhigh"]).optional(),reviewerLabel:z12.string().max(100),inference:z12.literal("REMOTE_OPENAI"),evidence:z12.enum(["METADATA_ONLY","IMAGE_PIXELS","VIDEO_FRAMES"])})}).refine(v=>{const image=v.plan.snapshot.image,receipt=v.imageReceipt;if(receipt&&(!image||receipt.draftId!==v.plan.id||canonicalLocalJson(receipt.media)!==canonicalLocalJson(v.plan.snapshot.media)||canonicalLocalJson({contentType:receipt.contentType,byteSize:receipt.byteSize,width:receipt.width,height:receipt.height})!==canonicalLocalJson(image)))return false;if(v.phase==="RESULT_PENDING"!==!!v.answer)return false;const derived=v.plan.snapshot.evidence,receipt2=v.evidenceReceipt;if(v.provenance.adapter!==(derived?"CODEX_MEDIA_V2":"CODEX_METADATA_V1"))return false;if(receipt2&&(!derived||receipt2.draftId!==v.plan.id||canonicalLocalJson(receipt2.media)!==canonicalLocalJson(v.plan.snapshot.media)))return false;if(v.answer&&!!(image||derived)!=="imageReadback"in v.answer)return false;const pixels=v.phase==="RESULT_PENDING"&&!!(image||derived);return v.provenance.evidence===(pixels?derived?.contentType==="video/mp4"?"VIDEO_FRAMES":"IMAGE_PIXELS":"METADATA_ONLY")&&(!pixels||(derived?!!receipt2:!!receipt))});function localAgentSnapshotFromContext(raw,includeImage=false){const c=ReviewIntelligenceContextResultSchema.parse(raw);if(c.reviewTarget.kind!=="IMAGE"||c.basis.target.kind!=="IMAGE"||c.ownerContext.semanticStatus!=="SUCCESS")throw Error("LOCAL_AGENT_CONTEXT_UNAVAILABLE");const t=c.reviewTarget.target,scope=c.basis.scope;if(!t.runtimeSucceeded||t.candidate.availability!=="AVAILABLE"||t.candidate.freshness!=="CURRENT_BASIS"||!t.productionRunnable||t.freshness!=="CURRENT_BASIS"||t.generationId!==c.basis.target.generationId||t.tenantId!==scope.tenantId||t.projectId!==scope.projectId||t.productionId!==scope.productionId||c.ownerContext.basis.tenantId!==scope.tenantId||c.ownerContext.basis.projectId!==scope.projectId||c.ownerContext.basis.productionId!==scope.productionId)throw Error("LOCAL_AGENT_CONTEXT_UNAVAILABLE");return LocalAgentSnapshotSchema.parse({basis:c.basis,productionRevision:c.ownerContext.basis.productionRevision,reviewVersion:t.reviewVersion,executionClass:t.executionClass,media:{artifactId:t.candidate.artifactId,representationId:t.candidate.representationId,checksumSha256:t.candidate.checksumSha256},requirements:t.requirements,...includeImage?{image:{contentType:t.candidate.contentType,byteSize:t.candidate.byteSize,width:t.candidate.width,height:t.candidate.height}}:{}})}function localAgentNativeProposal(raw){const v=LocalAgentReviewViewSchema.parse(raw);if(v.plan.snapshot.basis.target.kind!=="IMAGE"||v.plan.snapshot.evidence)throw Error("LOCAL_AGENT_MEDIA_PROPOSAL_REQUIRED");if(v.phase!=="RESULT_PENDING"||!v.answer)throw Error("LOCAL_AGENT_RESULT_UNAVAILABLE");const keys=new Set(v.answer.observations.map(o=>o.key));if(keys.size!==v.answer.observations.length||keys.size!==v.plan.snapshot.requirements.length||v.plan.snapshot.requirements.some(r=>!keys.has(r.key)))throw Error("LOCAL_AGENT_RESULT_UNAVAILABLE");const p=v.provenance;const pixels=p.evidence==="IMAGE_PIXELS";return ValidateReviewIntelligenceSchema.parse({basis:v.plan.snapshot.basis,proposal:{origin:{kind:"EXTERNAL_AGENT_HOST",label:p.reviewerLabel},summary:`${pixels?"IMAGE_PIXELS":"METADATA_ONLY; no visual inspection"}. Codex ${p.version}; model ${p.model}; effort ${p.reasoningEffort??"DEFAULT"}; binary ${p.binaryDigest}; draft ${v.plan.id}; plan ${v.plan.fingerprint}. ${v.answer.summary}`,evidence:pixels?[{id:"original_image",label:"Verified ORIGINAL PNG attachment",producer:"EXTERNAL_AGENT_HOST",kind:"IMAGE_PIXELS",media:v.plan.snapshot.media}]:[],review:{kind:"IMAGE",observations:v.answer.observations.map(o=>({...o,status:pixels&&"status"in o?o.status:"NOT_OBSERVABLE",confidence:pixels&&"confidence"in o?o.confidence:"UNCERTAIN",evidenceIds:pixels?["original_image"]:[]}))}}})}var projectInput=LocalProjectScopeSchema;var LocalExecutionListInputSchema=LocalProjectScopeSchema.extend({after:z13.string().length(64).regex(/^[0-9a-f]{64}$/).nullable().default(null),limit:z13.int().min(1).max(16).default(8),includeCompleted:z13.boolean().optional(),includeProgress:z13.boolean().optional()});var LocalExecutionInspectInputSchema=LocalWorkScopeSchema.extend({includeProgress:z13.boolean().optional()});var LocalIpcCallSchema=z13.discriminatedUnion("operation",[z13.strictObject({operation:z13.literal("agent.discover"),binary:z13.string().min(1).max(4096).optional()}),z13.strictObject({operation:z13.literal("offline.workspace"),input:LocalOfflineCallSchema}),z13.strictObject({operation:z13.literal("workspace.inspect")}),z13.strictObject({operation:z13.literal("workspace.configure"),policy:LocalResourcePolicySchema,expectedRevision:z13.int().nonnegative()}),z13.strictObject({operation:z13.literal("workspace.activity"),idleSeconds:z13.int().min(0).max(86400),observedAt:z13.iso.datetime()}),z13.strictObject({operation:z13.literal("storage.clean")}),z13.strictObject({operation:z13.literal("diagnostics.read")}),z13.strictObject({operation:z13.literal("agent.grant"),grant:LocalAgentGrantSchema,approval:z13.string().regex(/^[a-f0-9]{64}$/)}),z13.strictObject({operation:z13.literal("agent.probe")}),z13.strictObject({operation:z13.literal("agent.revoke"),approval:z13.string().regex(/^[a-f0-9]{64}$/)}),z13.strictObject({operation:z13.literal("agent.prepare"),snapshot:LocalAgentSnapshotSchema}),z13.strictObject({operation:z13.literal("agent.start"),id:z13.uuid(),expectedRevision:LocalRevisionSchema,approval:z13.string().regex(/^[a-f0-9]{64}$/)}),z13.strictObject({operation:z13.literal("agent.inspect"),id:z13.uuid()}),z13.strictObject({operation:z13.literal("runtime.status"),includeDevice:z13.literal(true).optional()}),z13.strictObject({operation:z13.literal("runtime.doctor")}),z13.strictObject({operation:z13.literal("runtime.inventory")}),z13.strictObject({operation:z13.literal("session.issue"),projects:z13.array(projectInput).min(1).max(100),expiresAt:z13.iso.datetime({offset:true})}),z13.strictObject({operation:z13.literal("runtime.stop"),expectedRuntimeRevision:LocalRevisionSchema}),z13.strictObject({operation:z13.literal("execution.inspect"),input:LocalExecutionInspectInputSchema}),z13.strictObject({operation:z13.literal("execution.list"),input:LocalExecutionListInputSchema}),z13.strictObject({operation:z13.literal("update.check")}),z13.strictObject({operation:z13.literal("update.prepare"),targetVersion:LocalPackageVersionSchema,expectedRuntimeRevision:LocalRevisionSchema}),z13.strictObject({operation:z13.literal("update.apply"),planId:LocalIdSchema,targetVersion:LocalPackageVersionSchema,expectedRuntimeRevision:LocalRevisionSchema})]);var LocalNextActionSchema=z13.strictObject({call:LocalIpcCallSchema,availability:z13.enum(["AVAILABLE","BLOCKED"]),reason:z13.enum(["READY","INSTALL_REQUIRED","AUTHORIZATION_REQUIRED","VERSION_INCOMPATIBLE","UPDATE_AVAILABLE","RECOVERY_REQUIRED"])});var LocalIpcRequestSchema=z13.strictObject({protocol:z13.literal("NVS_LOCAL_IPC_V1"),requestId:LocalIdSchema,call:LocalIpcCallSchema});var LocalVersionReportSchema=z13.strictObject({component:z13.enum(["CLI","SDK","MCP","RUNTIME","MEDIA_TOOLS"]),installedVersion:LocalPackageVersionSchema.nullable(),runningVersion:LocalPackageVersionSchema.nullable(),availableVersion:LocalPackageVersionSchema.nullable(),executablePath:z13.string().min(1).max(4096).nullable(),installOwner:z13.enum(["NPM_GLOBAL","PROJECT","NPX","MANAGED","TARBALL","UNKNOWN"])});var LocalRuntimeStatusSchema=z13.strictObject({protocol:z13.literal("NVS_LOCAL_IPC_V1"),runtimeRevision:LocalRevisionSchema,state:z13.enum(["IDLE","EXECUTING","DRAINING","RECOVERY_REQUIRED"]),journalSchemaVersion:z13.literal(1),workProtocols:z13.array(z13.enum(["NVS_LOCAL_WORK_V1","NVS_LOCAL_WORK_V2"])).min(1).max(2),versions:z13.array(LocalVersionReportSchema).max(8),authorizedProjects:z13.array(projectInput).max(100),deviceAuthority:z13.strictObject({tenantId:z13.uuid(),deviceId:z13.uuid(),origin:z13.url()}).optional(),nextActions:z13.array(LocalNextActionSchema).max(8)});var LocalDoctorReportSchema=z13.strictObject({mode:z13.enum(["MANAGED","INSTALLED"]),availability:z13.enum(["AVAILABLE","UNAVAILABLE"]),reason:z13.enum(["QUALIFIED_PROCESS_TOOLS","MANAGED_TOOLS_MISSING","TOOL_QUALIFICATION_FAILED"]),nativeExecutionReady:z13.boolean(),executionProfiles:z13.array(z13.enum(["ROUGH_CUT_PREVIEW_V1","STUDIO_MEDIA_V2"])).max(2).optional(),tools:z13.array(z13.strictObject({name:z13.enum(["FFMPEG","FFPROBE"]),path:z13.string().min(1).max(4096),version:z13.string().min(1).max(200),digest:z13.string().regex(/^[0-9a-f]{64}$/)})).max(2)});var LocalExecutionInspectionSchema=z13.strictObject({binding:LocalLeaseBindingSchema,revision:LocalRevisionSchema,phase:z13.enum(["STAGED","RUNNING","RECOVERY_REQUIRED","OUTPUT_PENDING","RECEIPT_RECORDED","FENCED"]),checkpoint:z13.enum(["ADOPTED","SOURCES_READY","PROCESS_STARTED","OUTPUT_STAGED"]),progress:LocalExecutionProgressSchema.optional()});var LocalExecutionPageSchema=z13.strictObject({items:z13.array(LocalExecutionInspectionSchema).max(16),nextCursor:z13.string().length(64).regex(/^[0-9a-f]{64}$/).nullable()});var LocalIpcErrorCodeSchema=z13.enum(["FORBIDDEN","INVALID_INPUT","FRAME_LIMIT","BUSY","AUTHORIZATION_REQUIRED","REVISION_CONFLICT","CAPABILITY_UNAVAILABLE","INTERNAL_OPERATIONAL_FAILURE","AGENT_APPROVAL_REQUIRED","AGENT_RUNTIME_UNAVAILABLE","AGENT_LOGIN_REQUIRED","AGENT_VERSION_UNQUALIFIED","AGENT_GRANT_REQUIRED","AGENT_OUTCOME_UNKNOWN","AGENT_IMAGE_REQUIRED","AGENT_IMAGE_INVALID","AGENT_IMAGE_BUDGET_EXCEEDED","AGENT_IMAGE_AUTHORIZATION_REQUIRED","CACHE_QUOTA_EXCEEDED"]);var LocalIpcResponseSchema=z13.discriminatedUnion("semanticStatus",[z13.strictObject({protocol:z13.literal("NVS_LOCAL_IPC_V1"),requestId:LocalIdSchema,semanticStatus:z13.literal("SUCCESS"),data:z13.union([LocalWorkspaceInspectionSchema,LocalDiagnosticsSchema,LocalOfflinePageSchema,LocalRuntimeStatusSchema,LocalDoctorReportSchema,LocalExecutionInspectionSchema.nullable(),z13.strictObject({state:z13.literal("DRAINING"),inventory:LocalManagementInventorySchema.optional(),backupPath:z13.string().min(1).max(4096).optional()}),LocalSessionConnectorSchema,LocalManagementInventorySchema,LocalExecutionPageSchema,LocalAgentProbeSchema,LocalAgentDiscoverySchema,LocalAgentReviewViewSchema])}),z13.strictObject({protocol:z13.literal("NVS_LOCAL_IPC_V1"),requestId:LocalIdSchema.nullable(),semanticStatus:z13.enum(["BLOCKED","INVALID_INPUT"]),error:z13.strictObject({code:LocalIpcErrorCodeSchema})})]);var LocalMcpToolNameSchema=z14.enum(["local_navigate","local_capability_describe","local_runtime_status","local_execution_list","local_execution_inspect","local_update_check"]);var LocalMcpActionSchema=z14.strictObject({tool:LocalMcpToolNameSchema,arguments:z14.record(z14.string(),z14.unknown()),availability:z14.enum(["AVAILABLE","BLOCKED"]).optional(),reason:z14.string().max(100).optional()});var LocalMcpNavigationSchema=z14.strictObject({location:z14.literal("LOCAL"),state:z14.enum(["UNAVAILABLE","IDLE","EXECUTING","DRAINING","RECOVERY_REQUIRED"]),authorizedProjects:z14.array(LocalProjectScopeSchema).max(100).optional(),groups:z14.array(z14.strictObject({id:z14.string().max(40),label:z14.string().max(100),tools:z14.array(LocalMcpToolNameSchema).max(6)})).max(4),nextActions:z14.array(z14.union([LocalMcpActionSchema,LocalClientNextActionSchema])).max(16)});var LocalMcpExecutionPageSchema=LocalExecutionPageSchema.extend({nextActions:z14.array(LocalMcpActionSchema).max(16)});var LocalMcpInspectionSchema=z14.strictObject({location:z14.literal("LOCAL"),execution:LocalExecutionInspectionSchema.nullable(),nextActions:z14.array(LocalMcpActionSchema).max(4)});var LocalMcpUpdateSchema=z14.strictObject({location:z14.literal("LOCAL"),running:z14.array(LocalVersionReportSchema).max(8),available:z14.array(LocalRuntimeDescriptorSchema).max(32),nextActions:z14.array(LocalClientNextActionSchema).max(4)});var LocalMcpDescriptionSchema=z14.strictObject({location:z14.literal("LOCAL"),tool:LocalMcpToolNameSchema,schema:z14.object({name:LocalMcpToolNameSchema,description:z14.string(),inputSchema:z14.record(z14.string(),z14.unknown())}).passthrough()});var LocalMcpFailureSchema=z14.strictObject({semanticStatus:z14.enum(["BLOCKED","INVALID_INPUT"]),error:z14.strictObject({code:z14.enum(["AUTHORIZATION_REQUIRED","FORBIDDEN","LOCAL_RUNTIME_UNAVAILABLE","RELEASE_UNAVAILABLE","VERSION_INCOMPATIBLE","INVALID_INPUT","LOCAL_CAPABILITY_UNAVAILABLE"]),outcome:z14.literal("NO_WRITE")}),nextActions:z14.array(LocalClientNextActionSchema).max(4)});var LocalMcpOutputSchemas={local_navigate:LocalMcpNavigationSchema,local_capability_describe:LocalMcpDescriptionSchema,local_runtime_status:LocalRuntimeStatusSchema.omit({nextActions:true}).extend({nextActions:z14.array(LocalMcpActionSchema).max(8)}),local_execution_list:LocalMcpExecutionPageSchema,local_execution_inspect:LocalMcpInspectionSchema,local_update_check:LocalMcpUpdateSchema};import{z as z15}from"zod";var LocalManagementCommandSchema=z15.discriminatedUnion("kind",[z15.strictObject({kind:z15.literal("ENROLL"),input:EnrollLocalDeviceSchema}),z15.strictObject({kind:z15.literal("GRANT"),input:GrantLocalDeviceSchema}),z15.strictObject({kind:z15.literal("REVOKE_GRANT"),input:RevokeLocalDeviceGrantSchema}),z15.strictObject({kind:z15.literal("PREVIEW"),input:StartLocalPreviewSchema}),z15.strictObject({kind:z15.literal("FINAL_RENDER"),input:StartLocalFinalRenderSchema})]);var LocalManagementResultSchema=z15.union([LocalDeviceViewSchema,LocalDeviceGrantSchema,LocalPreviewAdmissionSchema,LocalFinalRenderAdmissionSchema,z15.strictObject({semanticStatus:z15.literal("SUCCESS")})]);var LocalManagementReceiptSchema=z15.strictObject({fingerprint:z15.string().regex(/^[a-f0-9]{64}$/),result:LocalManagementResultSchema.nullable()});import{z as z17}from"zod";import{createHash}from"node:crypto";function localBudget(timeoutMs,parent,ceiling=6e4){if(!Number.isInteger(timeoutMs)||timeoutMs<1||timeoutMs>ceiling)throw Error("LOCAL_DEADLINE_INVALID");const controller=new AbortController,timer=setTimeout(()=>controller.abort(),timeoutMs);return{signal:parent?AbortSignal.any([parent,controller.signal]):controller.signal,close:()=>clearTimeout(timer)}}async function localAbortable(work,signal){if(signal.aborted)void work.catch(()=>{});signal.throwIfAborted();return new Promise((resolve,reject)=>{const abort=()=>reject(Error("LOCAL_DEADLINE"));signal.addEventListener("abort",abort,{once:true});work.then(v=>{signal.removeEventListener("abort",abort);resolve(v)},e=>{signal.removeEventListener("abort",abort);reject(e)});if(signal.aborted)abort()})}import{z as z16}from"zod";var output=z16.discriminatedUnion("role",[z16.strictObject({role:z16.literal("VIDEO"),receiptId:LocalIdSchema,checksumSha256:LocalDigestSchema,byteSize:z16.int().positive().max(128*1024*1024),contentType:z16.literal("video/mp4")}),z16.strictObject({role:z16.literal("POSTER"),receiptId:LocalIdSchema,checksumSha256:LocalDigestSchema,byteSize:z16.int().positive().max(2*1024*1024),contentType:z16.literal("image/png")})]);var LocalCompletionSubmissionSchema=LocalLeaseBindingSchema.extend({requestId:LocalIdSchema,outputs:z16.array(output).length(2),technical:RoughCutTechnicalSchema}).superRefine((v,ctx)=>{const video=v.outputs.find(o=>o.role==="VIDEO");if(new Set(v.outputs.map(o=>o.role)).size!==2||new Set(v.outputs.map(o=>o.receiptId)).size!==2||!video||video.checksumSha256!==v.technical.checksumSha256||video.byteSize!==v.technical.byteSize)ctx.addIssue({code:"custom",message:"Exact video/poster receipts required"})});var LocalVerifiedUploadSchema=z16.strictObject({binding:LocalLeaseBindingSchema,output,verifiedAt:LocalTimeSchema});var LocalCompletionReceiptSchema=LocalLeaseBindingSchema.extend({submissionFingerprint:LocalDigestSchema.optional(),semanticStatus:z16.literal("SUCCESS"),requestId:LocalIdSchema,renderId:LocalIdSchema,operationId:OperationIdSchema,artifactId:LocalIdSchema,videoRepresentationId:LocalIdSchema,posterRepresentationId:LocalIdSchema,checksumSha256:LocalDigestSchema,acceptedAt:LocalTimeSchema});var GetLocalCompletionReceiptSchema=LocalLeaseBindingSchema.pick({tenantId:true,projectId:true,productionId:true,runtimeJobId:true}).extend({requestId:LocalIdSchema});var NativeStudioLocalDeviceClient=class{constructor(options){this.options=options;const u=new URL(options.baseUrl);if(u.username||u.password||u.search||u.hash||u.pathname!=="/"||u.protocol!=="https:"&&!(u.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(u.hostname)))throw new NativeStudioSdkError("INVALID_INPUT","INVALID_INPUT","NO_WRITE");this.origin=u.origin}options;origin;async command(route,raw,input,output2,signal,readOnly=false){let started=false;const budget=localBudget(15e3,signal);try{const i=input.parse(raw);if((i.tenantId??i.input?.tenantId)!==this.options.tenantId)throw Error();budget.signal.throwIfAborted();const authorization=await localAbortable(Promise.resolve().then(()=>this.options.authorization()),budget.signal);if(authorization!==authorization.trim()||!/^Bearer [A-Za-z0-9._~-]{1,8192}$/.test(authorization))throw Error();const body=JSON.stringify(i);if(Buffer.byteLength(body)>65536)throw Error();budget.signal.throwIfAborted();started=true;const r=await fetch(this.origin+"/v1/local-execution/"+route,{method:"POST",headers:{authorization,"content-type":"application/json"},body,redirect:"error",signal:budget.signal});if(!r.ok){await r.body?.cancel();throw new NativeStudioSdkError(r.status===403||r.status===401?"FORBIDDEN":"LOCAL_COMMAND_REFUSED","BLOCKED",readOnly?"NO_WRITE":r.status>=500?"UNKNOWN":"REJECTED",r.status)}const parts=[];let size=0;for await(const b of r.body??[]){size+=b.length;if(size>262144)throw Error();parts.push(b)}const value=output2.parse(JSON.parse(Buffer.concat(parts).toString()));if(value&&typeof value==="object"){const result=value,request3=i;for(const key of["tenantId","projectId","deviceId"])if(key in result&&key in request3&&result[key]!==request3[key])throw Error()}return value}catch(e){if(e instanceof NativeStudioSdkError)throw e;throw new NativeStudioSdkError(started?readOnly?"LOCAL_QUERY_UNAVAILABLE":"LOCAL_COMMAND_UNKNOWN":"INVALID_INPUT",started?"BLOCKED":"INVALID_INPUT",started&&!readOnly?"UNKNOWN":"NO_WRITE")}finally{budget.close()}}enroll(input,signal){return this.command("devices/enroll",input,EnrollLocalDeviceSchema,LocalDeviceViewSchema,signal)}async managementReceipt(input,signal){const parsedInput=LocalManagementCommandSchema.safeParse(input);if(!parsedInput.success)throw new NativeStudioSdkError("INVALID_INPUT","INVALID_INPUT","NO_WRITE");const parsed=parsedInput.data;const value=await this.command("management-receipt",input,LocalManagementCommandSchema,LocalManagementReceiptSchema,signal,true);if(value.fingerprint!==createHash("sha256").update(canonicalLocalJson(parsed)).digest("hex"))throw new NativeStudioSdkError("LOCAL_RECEIPT_INVALID","BLOCKED","NO_WRITE");if(value.result){const result=value.result,original=parsed.input;for(const key of["tenantId","projectId","deviceId","productionId","timelineVersionId"])if(key in original&&key in result&&result[key]!==original[key])throw new NativeStudioSdkError("LOCAL_RECEIPT_INVALID","BLOCKED","NO_WRITE")}return value}grant(input,signal){return this.command("devices/grant",input,GrantLocalDeviceSchema,LocalDeviceGrantSchema,signal)}revokeDevice(input,signal){return this.command("devices/revoke",input,RevokeLocalDeviceSchema,z17.strictObject({semanticStatus:z17.literal("SUCCESS")}),signal)}revokeGrant(input,signal){return this.command("devices/revoke-grant",input,RevokeLocalDeviceGrantSchema,z17.strictObject({semanticStatus:z17.literal("SUCCESS")}),signal)}startPreview(input,signal){return this.command("previews",input,StartLocalPreviewSchema,LocalPreviewAdmissionSchema,signal)}startFinal(input,signal){return this.command("final-renders",input,StartLocalFinalRenderSchema,LocalFinalRenderAdmissionSchema,signal)}};import{randomUUID,createHash as createHash2}from"node:crypto";import{request}from"node:http";import{z as z18}from"zod";import{constants}from"node:fs";import{open,realpath}from"node:fs/promises";async function checkedLocalDirectory(path){await privateDirectory(path);return realpath(path)}async function readLocalCredential(path,maximum=32768){await privateAccess(path,"file");const file=await open(path,constants.O_RDONLY|constants.O_NOFOLLOW);try{const stat=await file.stat();if(!stat.isFile()||stat.nlink!==1||process.platform!=="win32"&&(stat.uid!==process.getuid?.()||stat.mode&63)||stat.size>maximum)throw Error("LOCAL_CREDENTIAL_INVALID");const bytes=Buffer.alloc(Math.min(maximum+1,stat.size+1));let used=0;while(used<bytes.length){const part=await file.read(bytes,used,bytes.length-used,null);if(!part.bytesRead)break;used+=part.bytesRead}if(used>stat.size)throw Error("LOCAL_CREDENTIAL_INVALID");if(used>maximum)throw Error("LOCAL_CREDENTIAL_INVALID");return bytes.subarray(0,used)}finally{await file.close()}}async function stageAgentImage(options,view,input,signal){const budget=localBudget(view.plan.snapshot.evidence?18e4:options.timeoutMs??1e4,signal,view.plan.snapshot.evidence?18e4:6e4);let dispatched=false;try{budget.signal.throwIfAborted();if(input.byteLength>134217728)throw Error();const bytes=Buffer.from(input),snapshot=view.plan.snapshot,id=z18.uuid().parse(view.plan.id),requestId=randomUUID();if(!snapshot.image&&!snapshot.evidence||bytes.length!==(snapshot.evidence??snapshot.image).byteSize||bytes.length>(snapshot.evidence?134217728:8388608)||createHash2("sha256").update(bytes).digest("hex")!==snapshot.media.checksumSha256)throw Error();const root=await checkedLocalDirectory(options.stateDirectory),path=localSocketPath(root);await privateAccess(path,"pipe");const auth=await localAbortable(Promise.resolve().then(options.authorization),budget.signal);budget.signal.throwIfAborted();if(!/^Bearer [A-Za-z0-9_-]{43}$/.test(auth))throw Error();const reply=await new Promise((resolve,reject)=>{const req=request({socketPath:path,path:"/ipc/v1/agent-images/"+id,method:"PUT",signal:budget.signal,headers:{authorization:auth,"content-type":snapshot.evidence?"application/octet-stream":"image/png","content-length":bytes.length,"x-nvs-request-id":requestId}},res=>{let size=0;const chunks=[];res.on("error",reject);res.on("aborted",()=>reject(Error()));res.on("data",b=>{size+=b.length;if(size>262144)req.destroy(Error());else chunks.push(b)});res.on("end",()=>{try{resolve(JSON.parse(Buffer.concat(chunks).toString()))}catch{reject(Error())}})});req.on("error",reject);dispatched=true;req.end(bytes)});const response=LocalIpcResponseSchema.parse(reply);if(response.requestId!==requestId&&!(response.requestId===null&&response.semanticStatus!=="SUCCESS"&&["BUSY","FORBIDDEN"].includes(response.error.code)))throw Error();if(response.semanticStatus!=="SUCCESS")throw new NativeStudioSdkError(response.error.code,response.semanticStatus,response.error.code==="INTERNAL_OPERATIONAL_FAILURE"?"UNKNOWN":"REJECTED");const v=LocalAgentReviewViewSchema.parse(response.data),receipt=v.evidenceReceipt??v.imageReceipt;if(v.plan.id!==id||canonicalLocalJson(v.plan)!==canonicalLocalJson(view.plan)||v.revision<view.revision||v.phase!=="PREPARED"||!receipt||receipt.draftId!==id||canonicalLocalJson(receipt.media)!==canonicalLocalJson(snapshot.media)||!snapshot.evidence&&canonicalLocalJson({contentType:v.imageReceipt?.contentType,byteSize:v.imageReceipt?.byteSize,width:v.imageReceipt?.width,height:v.imageReceipt?.height})!==canonicalLocalJson(snapshot.image))throw Error();return v}catch(e){if(e instanceof NativeStudioSdkError)throw e;throw new NativeStudioSdkError("LOCAL_AGENT_IMAGE_TRANSFER_FAILED","BLOCKED",dispatched?"UNKNOWN":"NO_WRITE")}finally{budget.close()}}var NativeStudioLocalWorkspaceClient=class{constructor(client){this.client=client}client;async offline(raw,signal){return LocalOfflinePageSchema.parse(await this.client.call({operation:"offline.workspace",input:LocalOfflineCallSchema.parse(raw)},signal))}async inspect(signal){return LocalWorkspaceInspectionSchema.parse(await this.client.call({operation:"workspace.inspect"},signal))}async configure(raw,expectedRevision,signal){const policy=LocalResourcePolicySchema.parse(raw);return LocalWorkspaceInspectionSchema.parse(await this.client.call({operation:"workspace.configure",policy,expectedRevision},signal))}async observeActivity(idleSeconds,observedAt,signal){return LocalWorkspaceInspectionSchema.parse(await this.client.call({operation:"workspace.activity",idleSeconds,observedAt},signal))}async clean(signal){return LocalWorkspaceInspectionSchema.parse(await this.client.call({operation:"storage.clean"},signal))}async diagnostics(signal){return LocalDiagnosticsSchema.parse(await this.client.call({operation:"diagnostics.read"},signal))}};import{randomUUID as randomUUID2}from"node:crypto";import{request as request2}from"node:http";var NativeStudioLocalRuntimeClient=class _NativeStudioLocalRuntimeClient{constructor(options){this.options=options}options;workspace=new NativeStudioLocalWorkspaceClient(this);static async fromConnector(path){const initial=LocalSessionConnectorSchema.parse(JSON.parse((await readLocalCredential(path)).toString()));return new _NativeStudioLocalRuntimeClient({stateDirectory:initial.stateDirectory,projects:initial.projects,authorization:async()=>{const current=LocalSessionConnectorSchema.parse(JSON.parse((await readLocalCredential(path)).toString()));if(current.stateDirectory!==initial.stateDirectory||canonicalLocalJson(current.projects)!==canonicalLocalJson(initial.projects)||Date.parse(current.expiresAt)>Date.parse(initial.expiresAt)||Date.parse(current.expiresAt)<=Date.now())throw Error("LOCAL_AUTHORIZATION_REQUIRED");return"Bearer "+current.credential}})}async call(call,signal){let started=false;const budget=localBudget(this.options.timeoutMs??(["runtime.doctor","agent.probe","agent.grant","agent.start"].includes(call.operation)?6e4:3e4),signal);const readOnly=["runtime.status","runtime.doctor","runtime.inventory","execution.inspect","execution.list","update.check","agent.probe","agent.discover","agent.inspect","workspace.inspect","diagnostics.read"].includes(call.operation);try{const input=LocalIpcRequestSchema.parse({protocol:"NVS_LOCAL_IPC_V1",requestId:randomUUID2(),call});const root=await checkedLocalDirectory(this.options.stateDirectory);const path=localSocketPath(root);await privateAccess(path,"pipe");budget.signal.throwIfAborted();const auth=await localAbortable(Promise.resolve().then(()=>this.options.authorization()),budget.signal);budget.signal.throwIfAborted();if(auth.length!==50||!/^Bearer [A-Za-z0-9_-]{43}$/.test(auth))throw Error();const body=JSON.stringify(input);const reply=await new Promise((resolve,reject)=>{const abort=budget.signal;const req=request2({socketPath:path,method:"POST",path:"/ipc/v1",signal:abort,headers:{authorization:auth,"content-type":"application/json","content-length":Buffer.byteLength(body)}},res=>{const chunks=[];let length=0;res.on("error",reject);res.on("aborted",()=>reject(Error()));res.on("data",b=>{length+=b.length;if(length>256*1024)req.destroy(Error());else chunks.push(b)});res.on("end",()=>{try{resolve(JSON.parse(Buffer.concat(chunks).toString()))}catch{reject(Error())}})});req.on("error",reject);started=true;req.end(body)});const value=LocalIpcResponseSchema.parse(reply);if(value.requestId!==input.requestId&&!(value.requestId===null&&value.semanticStatus!=="SUCCESS"&&["FORBIDDEN","BUSY","INVALID_INPUT"].includes(value.error.code)))throw Error();if(value.semanticStatus!=="SUCCESS")throw new NativeStudioSdkError(value.error.code,value.semanticStatus,readOnly?"NO_WRITE":value.error.code==="INTERNAL_OPERATIONAL_FAILURE"?"UNKNOWN":"REJECTED");if(value.requestId!==input.requestId)throw Error();return value.data}catch(error){if(error instanceof NativeStudioSdkError)throw error;throw new NativeStudioSdkError("LOCAL_RUNTIME_UNAVAILABLE","BLOCKED",started&&!readOnly?"UNKNOWN":"NO_WRITE")}finally{budget.close()}}response(schema,raw){const result=schema.safeParse(raw);if(!result.success)throw new NativeStudioSdkError("LOCAL_RESPONSE_INVALID","BLOCKED","NO_WRITE");return result.data}async status(signal,includeDevice=false){const value=this.response(LocalRuntimeStatusSchema,await this.call({operation:"runtime.status",...includeDevice?{includeDevice:true}:{}},signal));if(this.options.projects&&value.authorizedProjects.some(p=>!this.options.projects.some(q=>q.tenantId===p.tenantId&&q.projectId===p.projectId)))throw new NativeStudioSdkError("LOCAL_SCOPE_INVALID","BLOCKED","NO_WRITE");return value}async doctor(signal){return this.response(LocalDoctorReportSchema,await this.call({operation:"runtime.doctor"},signal))}async inventory(signal){return this.response(LocalManagementInventorySchema,await this.call({operation:"runtime.inventory"},signal))}async grantAgent(raw,approval){return this.response(LocalAgentProbeSchema,await this.call({operation:"agent.grant",grant:LocalAgentGrantSchema.parse(raw),approval}))}async revokeAgent(approval){return this.response(LocalAgentProbeSchema,await this.call({operation:"agent.revoke",approval}))}async probeAgent(){return this.response(LocalAgentProbeSchema,await this.call({operation:"agent.probe"}))}async discoverAgent(binary){return this.response(LocalAgentDiscoverySchema,await this.call({operation:"agent.discover",...binary?{binary}:{}}))}async prepareAgentReview(snapshot){const input=LocalAgentSnapshotSchema.parse(snapshot);const v=this.response(LocalAgentReviewViewSchema,await this.call({operation:"agent.prepare",snapshot:input}));if(canonicalLocalJson(v.plan.snapshot)!==canonicalLocalJson(input))throw new NativeStudioSdkError("LOCAL_RESPONSE_INVALID","BLOCKED","UNKNOWN");return v}async startAgentReview(id,expectedRevision,approval){const v=this.response(LocalAgentReviewViewSchema,await this.call({operation:"agent.start",id,expectedRevision,approval}));if(v.plan.id!==id||v.plan.fingerprint!==approval)throw new NativeStudioSdkError("LOCAL_RESPONSE_INVALID","BLOCKED","UNKNOWN");return v}async stageAgentImage(id,bytes,signal){const budget=localBudget(18e4,signal,18e4);try{return await stageAgentImage(this.options,await this.inspectAgentReview(id,budget.signal),bytes,budget.signal)}finally{budget.close()}}async inspectAgentReview(id,signal){const v=this.response(LocalAgentReviewViewSchema,await this.call({operation:"agent.inspect",id},signal));if(v.plan.id!==id)throw new NativeStudioSdkError("LOCAL_RESPONSE_INVALID","BLOCKED","NO_WRITE");return v}async executions(input,signal){const i=LocalExecutionListInputSchema.parse(input);if(this.options.projects&&!this.options.projects.some(p=>p.tenantId===i.tenantId&&p.projectId===i.projectId))throw new NativeStudioSdkError("FORBIDDEN","BLOCKED","NO_WRITE");const page=this.response(LocalExecutionPageSchema,await this.call({operation:"execution.list",input:i},signal));if(page.items.some(e=>e.binding.tenantId!==i.tenantId||e.binding.projectId!==i.projectId))throw new NativeStudioSdkError("LOCAL_SCOPE_INVALID","BLOCKED","NO_WRITE");return page}async inspect(raw,signal){const input=LocalExecutionInspectInputSchema.parse(raw);if(this.options.projects&&!this.options.projects.some(p=>p.tenantId===input.tenantId&&p.projectId===input.projectId))throw new NativeStudioSdkError("FORBIDDEN","BLOCKED","NO_WRITE");const value=this.response(LocalExecutionInspectionSchema.nullable(),await this.call({operation:"execution.inspect",input},signal));if(value&&["tenantId","projectId","productionId","runtimeJobId"].some(k=>value.binding[k]!==input[k]))throw new NativeStudioSdkError("LOCAL_SCOPE_INVALID","BLOCKED","NO_WRITE");return value}};import{createPublicKey,verify}from"node:crypto";function endpoint(raw){const u=new URL(raw);if(u.username||u.password||u.search||u.hash||u.protocol!=="https:"&&!(u.protocol==="http:"&&["127.0.0.1","localhost","[::1]"].includes(u.hostname)))fail("RELEASE_ORIGIN_INVALID");return u}async function fetchBytes(raw,maximum,origin,signal=AbortSignal.timeout(3e4)){const u=endpoint(raw);if(u.origin!==origin)fail("RELEASE_ORIGIN_INVALID");const r=await fetch(u,{redirect:"error",signal,headers:{accept:"application/octet-stream"}});if(!r.ok||Number(r.headers.get("content-length"))>maximum){await r.body?.cancel();fail("RELEASE_UNAVAILABLE")}const parts=[];let size=0;for await(const part of r.body??[]){size+=part.byteLength;if(size>maximum){await r.body?.cancel().catch(()=>{});fail("RELEASE_LIMIT")}parts.push(part)}return Buffer.concat(parts)}async function catalogue(trust,signal){const origin=endpoint(trust.catalogueUrl).origin;const bytes=await fetchBytes(trust.catalogueUrl,65536,origin,signal??AbortSignal.timeout(3e4));const signed=LocalSignedCatalogueSchema.parse(JSON.parse(bytes.toString()));const key=createPublicKey((await read(trust.publicKeyFile,16384)).toString());if(key.asymmetricKeyType!=="ed25519"||!verify(null,Buffer.from(canonicalLocalJson(signed.catalogue)),key,Buffer.from(signed.signature,"base64url")))fail("RELEASE_SIGNATURE_INVALID");const now=Date.now();if(Date.parse(signed.catalogue.issuedAt)>now||Date.parse(signed.catalogue.expiresAt)<=now)fail("RELEASE_EXPIRED");for(const release of signed.catalogue.releases){for(const a of[release.package,...release.tools?Object.values(release.tools):[]])if(endpoint(a.url).origin!==origin)fail("RELEASE_ORIGIN_INVALID")}return{signed,fingerprint:sha256(canonicalLocalJson(signed.catalogue)),origin,trustFingerprint:sha256(canonicalLocalJson({catalogueUrl:endpoint(trust.catalogueUrl).href,publicKey:key.export({type:"spki",format:"der"}).toString("base64")}))}}function select(signed,version){const r=signed.catalogue.releases.find(r2=>r2.descriptor.version===version&&r2.descriptor.platform.os===process.platform&&r2.descriptor.platform.architecture===process.arch);if(!r)fail("VERSION_INCOMPATIBLE");const[major,minor]=process.versions.node.split(".").map(Number);if(major!==r.descriptor.node.major||minor<r.descriptor.node.minMinor)fail("NODE_VERSION_INCOMPATIBLE");return r}async function asset(a,origin){const bytes=await fetchBytes(a.url,a.byteSize,origin,AbortSignal.timeout(12e4));if(bytes.length!==a.byteSize||sha512(bytes)!==a.sha512)fail("RELEASE_INTEGRITY_INVALID");return bytes}export{EnrollLocalDeviceSchema,LocalDeviceViewSchema,LocalDeviceChallengeSchema,GrantLocalDeviceSchema,LocalDeviceGrantSchema,RevokeLocalDeviceGrantSchema,RevokeLocalDeviceSchema,LocalOfflineCallSchema,LocalOfflinePageSchema,LocalAgentGrantSchema,LocalAgentDiscoverySchema,LocalToolSelectionSchema,LocalRuntimeDescriptorSchema,LocalManagementInventorySchema,LocalReleaseSchema,LocalToolChoiceSchema,LocalUpdatePlanSchema,LocalResourcePolicySchema,LocalWorkspaceInspectionSchema,LocalDiagnosticsSchema,canonicalLocalJson,LocalAgentSnapshotSchema,LocalAgentProbeSchema,LocalAgentReviewViewSchema,localAgentSnapshotFromContext,localAgentNativeProposal,LocalExecutionListInputSchema,LocalExecutionInspectInputSchema,LocalDoctorReportSchema,StartLocalPreviewSchema,LocalDeviceSessionSchema,LocalDeviceTransportConfigurationSchema,LocalPreviewAdmissionSchema,StartLocalFinalRenderSchema,LocalFinalRenderAdmissionSchema,LocalMcpFailureSchema,LocalMcpOutputSchemas,LocalManagementCommandSchema,LocalManagementResultSchema,NativeStudioLocalDeviceClient,NativeStudioLocalRuntimeClient,endpoint,catalogue,select,asset};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LocalInstallationManager,captureInstalledTools,connectDevice,generateDeviceKey,ownerClient}from"./chunk-
|
|
1
|
+
import{LocalInstallationManager,captureInstalledTools,connectDevice,generateDeviceKey,ownerClient}from"./chunk-HKD6F6M6.js";import{EnrollLocalDeviceSchema,GrantLocalDeviceSchema,LocalAgentGrantSchema,LocalManagementCommandSchema,NativeStudioLocalDeviceClient,RevokeLocalDeviceGrantSchema,RevokeLocalDeviceSchema,StartLocalFinalRenderSchema,StartLocalPreviewSchema,canonicalLocalJson,localAgentNativeProposal,localAgentSnapshotFromContext}from"./chunk-RVGDXRPK.js";import{readCredential,readInput}from"./chunk-6LU6GJKW.js";import{LocalClientError}from"./chunk-KB2GVAN7.js";import{localCliVersion}from"./chunk-2UYKJ6YN.js";import{NativeStudioAgentClient}from"./chunk-YKOJPJZR.js";import"./chunk-GJ7BZJLW.js";import"./chunk-PBEHCYR7.js";import"./chunk-VPYAXWXY.js";import{NativeStudioSdkError}from"./chunk-6NVIN2NI.js";import{homedir as homedir2}from"node:os";import{join as join2,resolve as resolve2}from"node:path";import{homedir}from"node:os";import{join,resolve}from"node:path";import{createHash}from"node:crypto";async function runLocalAgentCli(argv,stdin){try{const[command,...rest]=argv,flags=new Map;for(let n=0;n<rest.length;n+=2){const k=rest[n],v=rest[n+1];if(!k||!["--home","--input","--approve","--id","--revision","--evidence","--origin","--token-file"].includes(k)||!v||v.startsWith("--")||flags.has(k))throw Error();flags.set(k,v)}const need=k=>{const v=flags.get(k);if(!v)throw Error();return v};if(command==="agent-grant-plan"){const grant=LocalAgentGrantSchema.parse(await readInput(need("--input"),stdin));return{exitCode:0,output:{grant,fingerprint:createHash("sha256").update(canonicalLocalJson(grant)).digest("hex"),note:"Explicitly approves remote OpenAI inference/use for these Projects until expiry. Does not invoke a model."}}}if(flags.has("--evidence")&&!["IMAGE_PIXELS","METADATA_ONLY"].includes(need("--evidence")))throw Error();const manager=await LocalInstallationManager.open(resolve(flags.get("--home")??join(homedir(),".nativestudio","client")));const client=await ownerClient((await manager.configuration()).stateDirectory);let output;switch(command){case"agent-grant":output=await client.grantAgent(await readInput(need("--input"),stdin),need("--approve"));break;case"agent-revoke":output=await client.revokeAgent(need("--approve"));break;case"agent-probe":output=await client.probeAgent();break;case"review-prepare":output=await client.prepareAgentReview(localAgentSnapshotFromContext(await readInput(need("--input"),stdin),flags.get("--evidence")==="IMAGE_PIXELS"));break;case"review-image-fetch":{const view=await client.inspectAgentReview(need("--id")),snapshot=view.plan.snapshot;if(!snapshot.image||snapshot.basis.target.kind!=="IMAGE")throw Error();const studio=new NativeStudioAgentClient({baseUrl:need("--origin"),tenantId:snapshot.basis.scope.tenantId,authorization:()=>readCredential(flags,process.env)});const media=await studio.keyframeMedia({productionId:snapshot.basis.scope.productionId,generationId:snapshot.basis.target.generationId},{checksumSha256:snapshot.media.checksumSha256,byteSize:snapshot.image.byteSize});if(media.contentType!==snapshot.image.contentType)throw Error();output=await client.stageAgentImage(view.plan.id,media.bytes);break}case"review-start":output=await client.startAgentReview(need("--id"),Number(need("--revision")),need("--approve"));break;case"review-inspect":output=await client.inspectAgentReview(need("--id"));break;case"review-proposal":output=localAgentNativeProposal(await client.inspectAgentReview(need("--id")));break;default:throw Error()}return{exitCode:0,output}}catch(e){const known=e instanceof NativeStudioSdkError;return{exitCode:2,output:{semanticStatus:"BLOCKED",error:{code:known?e.code:"INVALID_INPUT",outcome:known?e.outcome:"NO_WRITE"}}}}}async function runLocalCli(argv,stdin=process.stdin){let mutation=false;try{const[command,...rest]=argv,options=new Map;if(command?.startsWith("agent-")||command?.startsWith("review-"))return runLocalAgentCli(argv,stdin);const allowed=["--home","--input","--version","--plan","--approve","--output","--origin","--token-file","--action"];for(let i=0;i<rest.length;i+=2){const k=rest[i],v=rest[i+1];if(!k||!allowed.includes(k)||!v||v.startsWith("--")||options.has(k))throw Error();options.set(k,v)}if(command==="help"||!command)return{exitCode:0,output:{namespace:"nvs local",commands:["configure --input <private-json>","keygen --output <new-private-device-key>","cloud --action enroll|grant|revoke-device|revoke-grant|preview|final|receipt --origin <cloud-origin> --token-file <member-token> --input <json>","connect --input <private-device-config>","version","install|update-prepare --version <exact>","tools-prepare --version <exact> --input <private-json with mode MANAGED or INSTALLED and exact ffmpeg/ffprobe paths>","update-check","update-reject --version <exact>","update-apply --plan <uuid> --approve <fingerprint>","update-reconcile --plan <uuid> --approve <fingerprint>","start","status","doctor","stop","grant --input <scopes-expiry-json> --output <new-private-connector>","mcp [--connector <private-file>] [--with-project-renders]","agent-grant-plan|agent-probe|agent-grant|agent-revoke|review-prepare|review-image-fetch|review-start|review-inspect|review-proposal \u2014 see --input private JSON and exact --approve"],note:"Check/prepare do not download executables. Apply requires exact approval. MCP disconnect does not stop Runtime."}};if(command==="version")return{exitCode:0,output:await localCliVersion()};const required=key=>{const v=options.get(key);if(!v)throw Error();return v};if(command==="keygen")return{exitCode:0,output:await generateDeviceKey(resolve2(required("--output")))};if(command==="cloud"){const input=await readInput(required("--input"),stdin);const action=required("--action");const tenantId=action==="receipt"?LocalManagementCommandSchema.parse(input).input.tenantId:input.tenantId;if(typeof tenantId!=="string")throw Error();const client=new NativeStudioLocalDeviceClient({baseUrl:required("--origin"),tenantId,authorization:()=>readCredential(new Map([["--token-file",required("--token-file")]]),process.env)});const output2=action==="enroll"?await client.enroll(EnrollLocalDeviceSchema.parse(input)):action==="grant"?await client.grant(GrantLocalDeviceSchema.parse(input)):action==="revoke-device"?await client.revokeDevice(RevokeLocalDeviceSchema.parse(input)):action==="revoke-grant"?await client.revokeGrant(RevokeLocalDeviceGrantSchema.parse(input)):action==="preview"?await client.startPreview(StartLocalPreviewSchema.parse(input)):action==="final"?await client.startFinal(StartLocalFinalRenderSchema.parse(input)):action==="receipt"?await client.managementReceipt(LocalManagementCommandSchema.parse(input)):void 0;if(!output2)throw Error();return{exitCode:0,output:output2}}const manager=await LocalInstallationManager.open(resolve2(options.get("--home")??join2(homedir2(),".nativestudio","client")));let output;mutation=["configure","connect","start","stop","grant","update-apply","update-reconcile","update-reject"].includes(command??"");switch(command){case"connect":output=await connectDevice(manager,await readInput(required("--input"),stdin));break;case"configure":output=await manager.configure(await readInput(required("--input"),stdin));break;case"status":output=await manager.status();break;case"update-reject":output=await manager.reject(required("--version"));break;case"update-check":output=await manager.check();break;case"install":case"update-prepare":output=await manager.prepare(required("--version"));break;case"tools-prepare":{const raw=await readInput(required("--input"),stdin);const choice=raw.mode==="INSTALLED"?await captureInstalledTools(raw):raw;output=await manager.prepare(required("--version"),choice)}break;case"update-apply":output=await manager.apply(required("--plan"),required("--approve"));break;case"update-reconcile":output=await manager.reconcile(required("--plan"),required("--approve"));break;case"start":output=await manager.start();break;case"stop":output=await manager.stop();break;case"doctor":output=await(await ownerClient((await manager.configuration()).stateDirectory)).doctor();break;case"grant":output=await manager.grant(await readInput(required("--input"),stdin),resolve2(required("--output")));break;default:throw Error()}return{exitCode:0,output}}catch(e){const known=e instanceof LocalClientError?e.code:e instanceof NativeStudioSdkError?e.code:"INVALID_INPUT";return{exitCode:2,output:{semanticStatus:"BLOCKED",error:{code:known,outcome:e instanceof NativeStudioSdkError?e.outcome:mutation&&!["USER_APPROVAL_REQUIRED","PLAN_CHANGED","REVISION_CONFLICT","INSTALL_REQUIRED","CONFIGURATION_REQUIRED"].includes(known)?"UNKNOWN":"NO_WRITE"}}}}}export{runLocalCli};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{StdioLines}from"./chunk-JFC6ZIGA.js";import{renderConnection}from"./chunk-D533YC7J.js";import{clientHome,loadConnection,readAccount,requireAccount}from"./chunk-KNFUMWDY.js";import{LocalMcpTools,localTools}from"./chunk-
|
|
1
|
+
import{StdioLines}from"./chunk-JFC6ZIGA.js";import{renderConnection}from"./chunk-D533YC7J.js";import{clientHome,loadConnection,readAccount,requireAccount}from"./chunk-KNFUMWDY.js";import{LocalMcpTools,localTools}from"./chunk-INLSOHAK.js";import{desktopDeviceConnector}from"./chunk-N6S6HCWE.js";import{LocalMcpFailureSchema}from"./chunk-RVGDXRPK.js";import"./chunk-DXJQWTLG.js";import"./chunk-FU3524Z6.js";import"./chunk-6LU6GJKW.js";import"./chunk-KB2GVAN7.js";import"./chunk-CA54SKBO.js";import{localCliVersion}from"./chunk-2UYKJ6YN.js";import{DeviceRenderAdmissionSchema,DeviceRenderIntentSchema,PreparedDeviceRenderSchema}from"./chunk-YKOJPJZR.js";import"./chunk-GJ7BZJLW.js";import"./chunk-PBEHCYR7.js";import"./chunk-VPYAXWXY.js";import"./chunk-PUNG4ND7.js";import{NativeStudioSdkError}from"./chunk-6NVIN2NI.js";import{z as z2}from"zod";import{homedir}from"node:os";import{join,resolve}from"node:path";import{deserializeMessage,SUPPORTED_PROTOCOL_VERSIONS,LATEST_PROTOCOL_VERSION,serializeMessage,isJSONRPCRequest,isJSONRPCNotification}from"@modelcontextprotocol/client";import{z}from"zod";var templates={local_render_prepare:{description:"Read the selected Project's exact current preview/final basis for this computer. Preserve this command for submission and reconciliation.",input:DeviceRenderIntentSchema,output:PreparedDeviceRenderSchema},local_render_start:{description:"Submit an exact prepared preview/final to this authorized tenant computer only. Offline means unavailable. Keep the operation and job identities; never resubmit an unknown write.",input:PreparedDeviceRenderSchema,output:DeviceRenderAdmissionSchema}};var renderNames=Object.keys(templates);function denied(){throw new NativeStudioSdkError("FORBIDDEN","BLOCKED","NO_WRITE")}async function selectedConnector(home,env){const account=requireAccount(await readAccount(await clientHome(env)));if(!account.workspaceId||!account.projectId)denied();return desktopDeviceConnector(home,{origin:account.serverOrigin,tenantId:account.workspaceId,principalId:account.principalId})}var ProjectRenderTools=class _ProjectRenderTools{constructor(runtime,env,binding,deviceId){this.runtime=runtime;this.env=env;this.binding=binding;this.deviceId=deviceId}runtime;env;binding;deviceId;static async open(runtime,env){const c=await loadConnection(env,true);if(!c?.scope.split(/\s+/).includes("nvs:write"))denied();const status=await runtime.status(void 0,true);const authority=status.deviceAuthority;if(!authority||authority.origin!==new URL(c.resource).origin||authority.tenantId!==c.tenantId||!status.authorizedProjects.some(p=>p.tenantId===c.tenantId&&p.projectId===c.projectId))denied();return new _ProjectRenderTools(runtime,env,c,authority.deviceId)}schema(n){const t=templates[n];return{name:n,description:t.description,inputSchema:{...z.toJSONSchema(t.input,{io:"input"}),type:"object"},outputSchema:{...z.toJSONSchema(t.output,{io:"input"}),type:"object"},annotations:{readOnlyHint:n==="local_render_prepare",destructiveHint:false,idempotentHint:true,openWorldHint:true}}}async call(n,raw,signal){const c=await renderConnection(this.env,signal);try{if(c.scope.resource!==this.binding.resource||c.scope.profile!==this.binding.profile)denied();const s=await this.runtime.status(signal,true);if(s.deviceAuthority?.tenantId!==c.scope.tenantId||s.deviceAuthority.deviceId!==this.deviceId||s.deviceAuthority.origin!==new URL(c.scope.resource).origin||!s.authorizedProjects.some(p=>p.tenantId===c.scope.tenantId&&p.projectId===c.scope.projectId))denied();if(n==="local_render_prepare"){const input=DeviceRenderIntentSchema.parse(raw);if(input.deviceId&&input.deviceId!==this.deviceId)denied();return await c.studio.deviceRenders.prepare({...input,deviceId:this.deviceId},{signal})}const prepared=PreparedDeviceRenderSchema.parse(raw);if(prepared.command.tenantId!==c.scope.tenantId||prepared.command.deviceExecution.deviceId!==this.deviceId)denied();const response=await c.studio.deviceRenders.start(prepared,{signal});const parsed=DeviceRenderAdmissionSchema.safeParse(response);if(!parsed.success)throw new NativeStudioSdkError("RESPONSE_INVALID","BLOCKED","UNKNOWN");return parsed.data}finally{await c.close().catch(()=>{})}}};async function serveLocalMcp(tools,input,output){const identity=await localCliVersion();const visible=[...Object.keys(localTools),...tools.renders?renderNames:[]].sort(),pending=new Map;let initialized=false,closed=false;const frames=new StdioLines(65536);let finish;const ended=new Promise(resolve2=>{finish=resolve2});const send=message=>{if(closed)return;if(output.writableLength>512*1024){close(1);return}output.write(serializeMessage(message))};const error=(id,code,message)=>send({jsonrpc:"2.0",id,error:{code,message}});async function dispatch(r){if(pending.has(r.id)||pending.size>=8){error(r.id,-32e3,"Local request capacity unavailable");return}const abort=new AbortController;const timer=setTimeout(()=>abort.abort(),3e4);pending.set(r.id,abort);try{let result;if(r.method==="initialize"){if(initialized)throw Error();const v=r.params?.protocolVersion;if(typeof v!=="string")throw Error();const protocol=SUPPORTED_PROTOCOL_VERSIONS.includes(v)?v:LATEST_PROTOCOL_VERSION;initialized=true;result={protocolVersion:protocol,serverInfo:{name:"native-studio-local",version:identity.version},capabilities:{tools:{}},instructions:"Use local_navigate and local_capability_describe for scoped guidance. The standard tool list stays stable. Local tools inspect scoped mechanics. Optional local render tools require a separate writable Project connection and only dispatch to this device. Cloud owns native admission. Updates require a human CLI approval; MCP cannot stop or replace Runtime."}}else if(!initialized)throw Error();else if(r.method==="ping")result={};else if(r.method==="tools/list"){if(r.params?.cursor!==void 0)throw Error();result={tools:visible.map(n=>renderNames.includes(n)?tools.renders.schema(n):tools.schema(n))}}else if(r.method==="tools/call"){const name=r.params?.name;if(typeof name!=="string"||!visible.includes(name))throw Error();const render=renderNames.includes(name)&&tools.renders;let data;try{data=render?await render.call(name,r.params?.arguments??{},abort.signal):await tools.call(name,r.params?.arguments??{},abort.signal)}catch(cause){const code=cause instanceof z2.ZodError?"INVALID_INPUT":cause instanceof NativeStudioSdkError&&["AUTHORIZATION_REQUIRED","FORBIDDEN","LOCAL_RUNTIME_UNAVAILABLE"].includes(cause.code)?cause.code:"LOCAL_CAPABILITY_UNAVAILABLE";const failure=render?{semanticStatus:cause instanceof NativeStudioSdkError?cause.semanticStatus:code==="INVALID_INPUT"?code:"BLOCKED",error:{code:cause instanceof NativeStudioSdkError?cause.code:code,outcome:cause instanceof NativeStudioSdkError?cause.outcome:"NO_WRITE"},nextActions:[]}:LocalMcpFailureSchema.parse({semanticStatus:code==="INVALID_INPUT"?"INVALID_INPUT":"BLOCKED",error:{code,outcome:"NO_WRITE"},nextActions:[{surface:"CLI",operation:"local.status",availability:"AVAILABLE",reason:code==="FORBIDDEN"||code==="AUTHORIZATION_REQUIRED"?"AUTHORIZATION_REQUIRED":"UNAVAILABLE"}]});send({jsonrpc:"2.0",id:r.id,result:{isError:true,content:[{type:"text",text:JSON.stringify(failure)}],structuredContent:failure}});return}result={content:[{type:"text",text:JSON.stringify(data)}],structuredContent:data}}else{error(r.id,-32601,"Local method unavailable");return}send({jsonrpc:"2.0",id:r.id,result})}catch{error(r.id,-32602,"Local capability unavailable or authorization required")}finally{clearTimeout(timer);pending.delete(r.id)}}function onData(b){try{frames.push(b,line=>{const message=deserializeMessage(line.toString());if(isJSONRPCRequest(message))void dispatch(message);else if(isJSONRPCNotification(message)){if(message.method==="notifications/cancelled"){const id=message.params?.requestId;if(typeof id==="string"||typeof id==="number")pending.get(id)?.abort()}}else throw Error();return!closed})}catch{close(1)}}function close(code=0){if(closed)return;closed=true;for(const abort of pending.values())abort.abort();input.off("data",onData);finish(code)}input.on("data",onData);input.once("end",()=>close(frames.incomplete?1:0));input.once("error",()=>close(1));output.once("error",()=>close(1));return{closed:ended,close:async()=>close()}}async function runLocalMcp(argv){try{const flags=new Map;const projectRenders=argv.includes("--with-project-renders");if(argv.filter(k=>k==="--with-project-renders").length>1)throw Error();argv=argv.filter(k=>k!=="--with-project-renders");for(let i=0;i<argv.length;i+=2){const k=argv[i],v=argv[i+1];if(!k||!["--connector","--home"].includes(k)||!v||flags.has(k))throw Error();flags.set(k,v)}const home=resolve(flags.get("--home")??process.env.NATIVESTUDIO_CLIENT_HOME??join(homedir(),".nativestudio","client"));const env={...process.env,NATIVESTUDIO_CLIENT_HOME:home};const connector=flags.get("--connector")??await selectedConnector(home,env);const tools=await LocalMcpTools.open(resolve(connector),home,projectRenders?client=>ProjectRenderTools.open(client,env):void 0);const service=await serveLocalMcp(tools,process.stdin,process.stdout);return await service.closed}catch{process.stderr.write("Local MCP needs a current scoped connector. Project renders also require a writable connection to the same Project.\n");return 2}}export{runLocalMcp,serveLocalMcp};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
import{loginLink,openLoginBrowser}from"./chunk-VDNNFVTZ.js";import{NativeStudioAccountClient,accountError,accountServerOrigin,clientHome,connectionStatus,defaultConnection,readAccount,requireAccount,saveAccount,withAccountLock}from"./chunk-KNFUMWDY.js";import"./chunk-FU3524Z6.js";import{readCredential,readInput}from"./chunk-6LU6GJKW.js";import{write}from"./chunk-KB2GVAN7.js";import"./chunk-GJ7BZJLW.js";import"./chunk-VPYAXWXY.js";import"./chunk-PUNG4ND7.js";import{NativeStudioSdkError}from"./chunk-6NVIN2NI.js";var aliases={find:"studio.start",overview:"studio.navigate",next:"studio.navigate",resume:"operation.get"};var auth=new Set(["--tenant","--origin","--mcp-url","--profile","--token-env","--token-file"]);var fields={find:{"--query":"search","--project":"projectId","--limit":"limit","--next":"next","--attention":"attention"},overview:{"--production":"productionId","--project":"projectId","--goal":"goal","--limit":"actionLimit","--next":"actionNext"},next:{"--production":"productionId","--project":"projectId","--goal":"goal","--limit":"actionLimit","--next":"actionNext"},resume:{"--production":"productionId","--operation":"operationId"},search:{"--query":"query","--project":"projectId","--group":"group","--family":"family","--limit":"limit","--next":"next"},describe:{"--tool":"tool","--project":"projectId","--reference":"schemaCursor"},groups:{"--project":"projectId"}};var NavigationCliCommands=new Set([...Object.keys(aliases),"capabilities"]);async function runNavigationCli(argv,stdin,call){const kind=argv[0]==="capabilities"?argv[1]?.startsWith("--")||!argv[1]?"groups":argv[1]:argv[0];const operation=argv[0]==="capabilities"?{groups:"studio.capability.groups",search:"studio.capability.search",describe:"studio.capability.describe"}[kind]:aliases[kind];const offset=argv[0]==="capabilities"&&argv[1]===kind?2:1;if(!operation||!fields[kind])throw Error("INVALID_INPUT");const forwarded=["call",operation],body={},seen=new Set;let input;for(let i=offset;i<argv.length;i+=2){const flag=argv[i],value=argv[i+1];if(!value||value.startsWith("--")||seen.has(flag))throw Error("INVALID_INPUT");seen.add(flag);if(auth.has(flag))forwarded.push(flag,value);else if(flag==="--input")input=value;else{const key=fields[kind][flag];if(!key)throw Error("INVALID_INPUT");body[key]=flag==="--limit"?Number(value):value}}if(input&&Object.keys(body).length)throw Error("INVALID_INPUT");forwarded.push("--input",input??"-");const generated=async function*(){yield Buffer.from(JSON.stringify(body))};return call(forwarded,input?stdin:generated())}import{randomBytes,randomUUID,createHash,timingSafeEqual}from"node:crypto";import{createServer}from"node:http";import{join}from"node:path";async function accountSignals(timeout,run){const cancelled=new AbortController,signal=AbortSignal.any([AbortSignal.timeout(timeout),cancelled.signal]);const stop=()=>cancelled.abort();process.once("SIGINT",stop);process.once("SIGTERM",stop);try{return await run(signal)}finally{process.off("SIGINT",stop);process.off("SIGTERM",stop)}}async function runAccountLogin(argv,environment,hooks={}){const options=new Map;for(let i=1;i<argv.length;i+=2){const key=argv[i],value=argv[i+1];if(!key||!["--server","--browser","--timeout-ms"].includes(key)||!value||value.startsWith("--")||options.has(key))accountError("ACCOUNT_LOGIN_INPUT_INVALID");options.set(key,value)}const configured=options.get("--server")??environment.NATIVESTUDIO_STUDIO_ORIGIN;if(!configured)return{exitCode:2,output:{semanticStatus:"NEEDS_INPUT",error:{code:"ACCOUNT_SERVER_REQUIRED",outcome:"NO_WRITE"},nextSteps:["nvs login --server <Studio-origin> (no Project required)"]}};const origin=accountServerOrigin(configured),browser=options.get("--browser")??"auto",timeout=options.get("--timeout-ms")??"180000";if(!["auto","manual"].includes(browser)||!/^\d+$/.test(timeout)||Number(timeout)<1e3||Number(timeout)>3e5)accountError("ACCOUNT_LOGIN_INPUT_INVALID");const root=await clientHome(environment,true);return withAccountLock(root,()=>accountSignals(Number(timeout),async signal=>{if((await readAccount(root))?.state==="REVOKE_PENDING")accountError("ACCOUNT_LOGOUT_OUTCOME_UNKNOWN","UNKNOWN");const client=new NativeStudioAccountClient({serverOrigin:origin});await client.metadata(signal);const verifier=randomBytes(32).toString("base64url"),state=randomBytes(32).toString("base64url"),path="/account-callback/"+randomUUID();let finish,receiving=false,sent=false;const callback=new Promise(done=>{finish=done});const server=createServer({maxHeaderSize:8192,headersTimeout:5e3,requestTimeout:5e3},(req,res)=>{res.setHeader("cache-control","no-store");res.setHeader("content-type","text/plain; charset=utf-8");res.setHeader("x-content-type-options","nosniff");const address=server.address(),host=address&&typeof address!=="string"?`127.0.0.1:${address.port}`:"";if(receiving||req.method!=="GET"||req.headers.host!==host||req.headers.origin||!req.url||!req.url.startsWith(path+"?")||req.url.length>2048){res.writeHead(400).end("Invalid account callback.");return}const url=new URL(req.url,`http://${host}`),received=url.searchParams.get("state");const keys=[...url.searchParams.keys()];if(url.pathname!==path||new Set(keys).size!==keys.length||keys.some(k=>!["state","iss","code","error"].includes(k))||!received||Buffer.byteLength(received)!==Buffer.byteLength(state)||!timingSafeEqual(Buffer.from(received),Buffer.from(state))||url.searchParams.get("iss")!==origin||(url.searchParams.has("error")?url.searchParams.get("error")!=="access_denied"||url.searchParams.has("code"):!/^[A-Za-z0-9_-]{43}$/.test(url.searchParams.get("code")??""))){res.writeHead(400).end("Invalid account callback.");return}receiving=true;res.end("Account confirmation received. Return to NativeStudio CLI.");finish(url.searchParams.get("code"))});server.maxConnections=8;const expired=()=>finish(null);signal.addEventListener("abort",expired,{once:true});const attempt=join(root,"account-login-attempt.json");let attemptFile;try{await new Promise((done,fail)=>{server.once("error",fail);server.listen(0,"127.0.0.1",done)});const address=server.address();if(!address||typeof address==="string")throw Error();const redirectUri=`http://127.0.0.1:${address.port}${path}`;const started=await client.start({redirectUri,state,codeChallenge:createHash("sha256").update(verifier).digest("base64url")},signal);const url=`${origin}/cli-authorize?requestId=${started.requestId}`;signal.throwIfAborted();if(hooks.authorize)await hooks.authorize(url,signal);else{process.stderr.write(`CLI account login request: ${started.requestId}
|
|
2
|
-
`);if(browser==="manual")loginLink(url);else await openLoginBrowser(url,signal)}const code=await callback;if(!code)accountError(signal.aborted?signal.reason?.name==="TimeoutError"?"ACCOUNT_LOGIN_TIMED_OUT":"ACCOUNT_LOGIN_CANCELLED":"ACCOUNT_LOGIN_DENIED");const marker={version:1,serverOrigin:origin,requestId:started.requestId,state:"EXCHANGE_UNRESOLVED"};attemptFile=join(root,`account-login-attempt-${started.requestId}.json`);await write(attemptFile,JSON.stringify(marker),true);await write(attempt,JSON.stringify(marker));signal.throwIfAborted();sent=true;const session=await client.exchange({requestId:started.requestId,redirectUri,code,codeVerifier:verifier},signal);if(Date.parse(session.expiresAt)<=Date.now()||Date.parse(session.expiresAt)>Date.now()+36e5+3e4)accountError("ACCOUNT_SESSION_INVALID","UNKNOWN");await saveAccount(root,{version:1,epoch:randomUUID(),state:"ACTIVE",serverOrigin:origin,accessToken:session.accessToken,expiresAt:session.expiresAt,principalId:session.account.principalId,workspaceId:null,projectId:null});await write(attempt,JSON.stringify({...marker,state:"COMPLETED"}));await write(attemptFile,JSON.stringify({...marker,state:"COMPLETED"}));return{exitCode:0,output:{semanticStatus:"SUCCESS",authenticated:true,credentialPurpose:"CLI_ACCOUNT",serverOrigin:origin,expiresAt:session.expiresAt,account:session.account,nextSteps:["nvs workspaces","nvs workspace --id <workspace-id>","nvs projects"]}}}catch(error){if(sent){if(error instanceof NativeStudioSdkError&&error.outcome!=="UNKNOWN"){await write(attempt,JSON.stringify({version:1,state:"REJECTED"}));if(attemptFile)await write(attemptFile,JSON.stringify({version:1,state:"REJECTED"}));throw error}accountError("ACCOUNT_LOGIN_OUTCOME_UNKNOWN","UNKNOWN")}if(error instanceof NativeStudioSdkError&&error.outcome==="UNKNOWN")accountError("ACCOUNT_LOGIN_OUTCOME_UNKNOWN","UNKNOWN");if(signal.aborted)accountError(signal.reason?.name==="TimeoutError"?"ACCOUNT_LOGIN_TIMED_OUT":"ACCOUNT_LOGIN_CANCELLED");throw error}finally{signal.removeEventListener("abort",expired);server.closeAllConnections();await new Promise(done=>server.close(()=>done()))}}))}import{randomUUID as randomUUID2}from"node:crypto";import{z}from"zod";var AccountCommands=new Set(["whoami","workspaces","workspace","projects","project","logout"]);async function runAccountCommand(argv,environment){const command=argv[0],options=new Map;for(let i=1;i<argv.length;i+=2){const key=argv[i],value=argv[i+1];if(!key||!["--id","--limit","--next"].includes(key)||!value||value.startsWith("--")||options.has(key))accountError("ACCOUNT_COMMAND_INPUT_INVALID");options.set(key,value)}if(["workspace","project"].includes(command??"")?options.size!==1||!options.has("--id"):command==="projects"?options.has("--id"):options.size!==0)accountError("ACCOUNT_COMMAND_INPUT_INVALID");const root=await clientHome(environment,true);return withAccountLock(root,()=>accountSignals(15e3,async signal=>{const stored=await readAccount(root);if(command==="logout"){if(!stored||stored.state==="SIGNED_OUT")return{exitCode:0,output:{semanticStatus:"SUCCESS",authenticated:false,changed:false}};const client2=new NativeStudioAccountClient({serverOrigin:stored.serverOrigin,accessToken:stored.accessToken});const pending={...stored,state:"REVOKE_PENDING",workspaceId:null,projectId:null};await saveAccount(root,pending);try{await client2.logout(signal);await saveAccount(root,{...pending,state:"SIGNED_OUT",accessToken:null})}catch{accountError("ACCOUNT_LOGOUT_OUTCOME_UNKNOWN","UNKNOWN")}return{exitCode:0,output:{semanticStatus:"SUCCESS",authenticated:false,changed:true,nextSteps:["nvs login --server <Studio-origin>"]}}}const account=requireAccount(stored),client=new NativeStudioAccountClient({serverOrigin:account.serverOrigin,accessToken:account.accessToken});if(command==="whoami"||command==="workspaces"||command==="workspace"){const value2=await client.me(signal);if(value2.account.principalId!==account.principalId)accountError("ACCOUNT_IDENTITY_MISMATCH");if(command==="workspace"){const id=z.uuid().parse(options.get("--id"));if(!value2.account.tenants.some(t=>t.id===id))accountError("WORKSPACE_NOT_AUTHORIZED");await saveAccount(root,{...account,workspaceId:id,projectId:null,epoch:randomUUID2()});return{exitCode:0,output:{semanticStatus:"SUCCESS",workspaceId:id,nextSteps:["nvs projects"]}}}return{exitCode:0,output:{semanticStatus:"SUCCESS",authenticated:true,credentialPurpose:"CLI_ACCOUNT",verification:"LIVE_NATIVE_ACCOUNT",...command==="workspaces"?{workspaces:value2.account.tenants}:{account:value2.account,workspaceId:account.workspaceId,projectId:account.projectId,expiresAt:account.expiresAt},nextSteps:["nvs workspace --id <workspace-id>"]}}}if(!account.workspaceId)accountError("WORKSPACE_SELECTION_REQUIRED");if(command==="projects"){const limit=options.has("--limit")?z.coerce.number().int().min(1).max(100).parse(options.get("--limit")):void 0;const value2=await client.projects({tenantId:account.workspaceId,limit,next:options.get("--next")},signal);if(value2.items.some(p=>p.tenantId!==account.workspaceId))accountError("ACCOUNT_RESPONSE_SCOPE_MISMATCH");return{exitCode:0,output:{semanticStatus:"SUCCESS",...value2,nextSteps:["nvs project --id <project-id>"]}}}if(command!=="project")accountError("ACCOUNT_COMMAND_INPUT_INVALID");const projectId=z.uuid().parse(options.get("--id")),value=await client.project({tenantId:account.workspaceId,projectId},signal);if(value.project.id!==projectId||value.project.tenantId!==account.workspaceId)accountError("ACCOUNT_RESPONSE_SCOPE_MISMATCH");if(value.project.lifecycle!=="ACTIVE")accountError("PROJECT_ARCHIVED");await saveAccount(root,{...account,projectId,epoch:randomUUID2()});return{exitCode:0,output:{semanticStatus:"SUCCESS",project:value.project,connectionPage:`${account.serverOrigin}/projects/${projectId}/settings`,nextSteps:["Open connectionPage, then explicitly authorize this Project using nvs connect.","nvs status"]}}}))}var exits={SUCCESS:0,ACCEPTED:0,INVALID_INPUT:2,NOT_FOUND:3,BLOCKED:4,CAPABILITY_UNAVAILABLE:4,REVISION_CONFLICT:5};async function runRemoteCli(argv,environment=process.env,stdin=process.stdin){try{if(argv[0]==="connect")return await(await import("./project-connect-W7V3OALV.js")).runProjectConnect(argv,environment);if(argv[0]==="login"){if(argv.includes("--mcp-url")){const{runProjectConnect}=await import("./project-connect-W7V3OALV.js");const result=await runProjectConnect(["connect",...argv.slice(1)],environment);return{...result,output:{...result.output,deprecated:{code:"PROJECT_AUTH_IS_CONNECT",replacement:"nvs connect --mcp-url <project-connection-url>",note:"This legacy spelling authorizes one project; it does not establish a CLI account session."}}}}return await runAccountLogin(argv,environment)}if(argv[0]==="render")return await(await import("./render-main-ZW6UJHGN.js")).renderCommand(argv.slice(1),environment);if(AccountCommands.has(argv[0]??""))return await runAccountCommand(argv,environment);if(argv.length===1&&argv[0]==="status")return await connectionStatus(environment);if(NavigationCliCommands.has(argv[0]??""))return await runNavigationCli(argv,stdin,(args2,input2)=>runRemoteCli(args2,environment,input2));if(["auth-start","auth-complete"].includes(argv[0]??""))return await(await import("./oauth-WJ36KWAC.js")).runOAuthCommand(argv,stdin);if(!argv.length||argv.length===1&&["help","--help"].includes(argv[0]))return{exitCode:0,output:{product:"NativeStudio CLI",start:["nvs login --server <Studio-origin> \u2014 sign in/register your account in the browser; no project required.","nvs workspaces; nvs workspace --id <id>; nvs projects; nvs project --id <id>","nvs connect (uses the selected Project; read-only by default)","nvs status","nvs find --query <intent>"],navigation:["nvs capabilities","nvs overview --production <uuid>","nvs next --production <uuid>","nvs resume --production <uuid> --operation <op_original>"],agentConnection:{command:"nvs",args:["mcp"],note:"Uses the private saved connection; no token in Agent configuration."},commands:["login --server <Studio-origin> | whoami | logout \u2014 independent account session","workspaces | workspace --id <id> | projects [--limit <n>] [--next <cursor>] | project --id <id>","connect [--mcp-url <project-connection-url>] \u2014 reuses the selected Project and current authorization","status","find --query <text> [--project <uuid>]","overview | next --production <uuid> [--goal <text>]","resume --production <uuid> --operation <op_original>","capabilities [groups | search --query <text> --group <group> | describe --tool <name>]","render preview|final --production <uuid> --request <stable-uuid> [--device <uuid>] \u2014 tenant device only; saves original receipt","mcp \u2014 connect the Agent using the private saved connection","local help \u2014 installed Runtime, scoped local MCP, explicit exact-version updates"],advanced:["operations","mcp --profile <private-file> | --mcp-url <endpoint> --token-env <NAME>|--token-file <private-file>","call <operation> --input <file|-> --tenant <uuid> --token-env <NAME> --origin <https-origin>","call <operation> --input <file|-> --tenant <uuid> --token-file <private-file> --mcp-url <https-endpoint>","auth-start --profile <new-private-file> --mcp-url <resource> --callback <receiver-url>","auth-complete --profile <private-file> --input <callback-json-file|->","call <operation> --profile <private-file> --tenant <uuid> --input <file|->"],note:"No automatic write retry. Transport abort does not cancel native Jobs."}};const{NativeStudioAgentClient,sdkOperations}=await import("./src-BXLFLNRG.js");if(argv.length===1&&argv[0]==="operations")return{exitCode:0,output:{operations:Object.entries(sdkOperations).map(([name2,spec])=>({name:name2,readOnly:spec.readOnly??null,http:spec.request!==null}))}};const[command,name,...args]=argv;if(command!=="call"||!name||!Object.hasOwn(sdkOperations,name))throw Error();const options=new Map;const allowed=["--input","--tenant","--origin","--mcp-url","--token-env","--token-file","--profile"];for(let i=0;i<args.length;i+=2){const key2=args[i],value=args[i+1];if(!key2||!allowed.includes(key2)||!value||value.startsWith("--")||options.has(key2))throw Error();options.set(key2,value)}await defaultConnection(options,environment,true);if(!options.has("--input")||!options.has("--tenant")||(options.has("--profile")?options.has("--origin")||options.has("--mcp-url")||options.has("--token-file")||options.has("--token-env"):options.has("--origin")===options.has("--mcp-url")))throw Error();const key=name;const input=await readInput(options.get("--input"),stdin);const profile=options.has("--profile")?await(await import("./oauth-WJ36KWAC.js")).profileAuthorization(options.get("--profile")):null;const authorization=profile?.authorization??await readCredential(options,environment);const tenantId=options.get("--tenant");let output;if(profile||options.has("--mcp-url")){const{connectRemoteMcp}=await import("./mcp-P7W623FE.js");const connection=await connectRemoteMcp(profile?.resource??options.get("--mcp-url"),authorization,tenantId);try{output=await connection.studio.call(key,input)}finally{await connection.close()}}else{const studio=new NativeStudioAgentClient({tenantId,baseUrl:options.get("--origin"),authorization:()=>authorization});output=await studio.call(key,input)}const status=output?.semanticStatus;return{exitCode:status?exits[status]??1:0,output}}catch(error){const e=error instanceof NativeStudioSdkError?error:null;const accountRecovery={ACCOUNT_LOGIN_OUTCOME_UNKNOWN:["Start a fresh nvs login --server <Studio-origin>; never replay the old exchange."],ACCOUNT_LOGOUT_OUTCOME_UNKNOWN:["Retry nvs logout explicitly; local account use remains locked."],ACCOUNT_LOGIN_REQUIRED:["nvs login --server <Studio-origin>"],ACCOUNT_SESSION_EXPIRED_OR_REVOKED:["nvs login --server <Studio-origin>"],WORKSPACE_SELECTION_REQUIRED:["nvs workspaces","nvs workspace --id <workspace-id>"],PROJECT_CONNECTION_ACCOUNT_MISMATCH:["nvs whoami","nvs workspaces","nvs project --id <project-id>","nvs connect --mcp-url <project-connection-url>"],ACCOUNT_PROJECT_SELECTION_REQUIRED:["nvs whoami","nvs workspace --id <workspace-id>","nvs project --id <project-id>"],PROJECT_AUTHORIZED_CONNECTION_NOT_SELECTED:["Authorization may exist. Inspect Web grants; select the intended account/project before creating a fresh connection."]};return{exitCode:e?exits[e.semanticStatus]??1:2,output:{semanticStatus:e?.semanticStatus??"INVALID_INPUT",error:{code:e?.code??"INVALID_INPUT",outcome:e?.outcome??"NO_WRITE"},...e&&accountRecovery[e.code]?{nextSteps:accountRecovery[e.code]}:{},...["PROJECT_CONNECTION_REQUIRED","OAUTH_OUTCOME_UNKNOWN"].includes(e?.code??"")?{nextSteps:["nvs connect --mcp-url <project-connection-url>","nvs help"]}:{}}}}}export{runRemoteCli};
|
|
2
|
+
`);if(browser==="manual")loginLink(url);else await openLoginBrowser(url,signal)}const code=await callback;if(!code)accountError(signal.aborted?signal.reason?.name==="TimeoutError"?"ACCOUNT_LOGIN_TIMED_OUT":"ACCOUNT_LOGIN_CANCELLED":"ACCOUNT_LOGIN_DENIED");const marker={version:1,serverOrigin:origin,requestId:started.requestId,state:"EXCHANGE_UNRESOLVED"};attemptFile=join(root,`account-login-attempt-${started.requestId}.json`);await write(attemptFile,JSON.stringify(marker),true);await write(attempt,JSON.stringify(marker));signal.throwIfAborted();sent=true;const session=await client.exchange({requestId:started.requestId,redirectUri,code,codeVerifier:verifier},signal);if(Date.parse(session.expiresAt)<=Date.now()||Date.parse(session.expiresAt)>Date.now()+36e5+3e4)accountError("ACCOUNT_SESSION_INVALID","UNKNOWN");await saveAccount(root,{version:1,epoch:randomUUID(),state:"ACTIVE",serverOrigin:origin,accessToken:session.accessToken,expiresAt:session.expiresAt,principalId:session.account.principalId,workspaceId:null,projectId:null});await write(attempt,JSON.stringify({...marker,state:"COMPLETED"}));await write(attemptFile,JSON.stringify({...marker,state:"COMPLETED"}));return{exitCode:0,output:{semanticStatus:"SUCCESS",authenticated:true,credentialPurpose:"CLI_ACCOUNT",serverOrigin:origin,expiresAt:session.expiresAt,account:session.account,nextSteps:["nvs workspaces","nvs workspace --id <workspace-id>","nvs projects"]}}}catch(error){if(sent){if(error instanceof NativeStudioSdkError&&error.outcome!=="UNKNOWN"){await write(attempt,JSON.stringify({version:1,state:"REJECTED"}));if(attemptFile)await write(attemptFile,JSON.stringify({version:1,state:"REJECTED"}));throw error}accountError("ACCOUNT_LOGIN_OUTCOME_UNKNOWN","UNKNOWN")}if(error instanceof NativeStudioSdkError&&error.outcome==="UNKNOWN")accountError("ACCOUNT_LOGIN_OUTCOME_UNKNOWN","UNKNOWN");if(signal.aborted)accountError(signal.reason?.name==="TimeoutError"?"ACCOUNT_LOGIN_TIMED_OUT":"ACCOUNT_LOGIN_CANCELLED");throw error}finally{signal.removeEventListener("abort",expired);server.closeAllConnections();await new Promise(done=>server.close(()=>done()))}}))}import{randomUUID as randomUUID2}from"node:crypto";import{z}from"zod";var AccountCommands=new Set(["whoami","workspaces","workspace","projects","project","logout"]);async function runAccountCommand(argv,environment){const command=argv[0],options=new Map;for(let i=1;i<argv.length;i+=2){const key=argv[i],value=argv[i+1];if(!key||!["--id","--limit","--next"].includes(key)||!value||value.startsWith("--")||options.has(key))accountError("ACCOUNT_COMMAND_INPUT_INVALID");options.set(key,value)}if(["workspace","project"].includes(command??"")?options.size!==1||!options.has("--id"):command==="projects"?options.has("--id"):options.size!==0)accountError("ACCOUNT_COMMAND_INPUT_INVALID");const root=await clientHome(environment,true);return withAccountLock(root,()=>accountSignals(15e3,async signal=>{const stored=await readAccount(root);if(command==="logout"){if(!stored||stored.state==="SIGNED_OUT")return{exitCode:0,output:{semanticStatus:"SUCCESS",authenticated:false,changed:false}};const client2=new NativeStudioAccountClient({serverOrigin:stored.serverOrigin,accessToken:stored.accessToken});const pending={...stored,state:"REVOKE_PENDING",workspaceId:null,projectId:null};await saveAccount(root,pending);try{await client2.logout(signal);await saveAccount(root,{...pending,state:"SIGNED_OUT",accessToken:null})}catch{accountError("ACCOUNT_LOGOUT_OUTCOME_UNKNOWN","UNKNOWN")}return{exitCode:0,output:{semanticStatus:"SUCCESS",authenticated:false,changed:true,nextSteps:["nvs login --server <Studio-origin>"]}}}const account=requireAccount(stored),client=new NativeStudioAccountClient({serverOrigin:account.serverOrigin,accessToken:account.accessToken});if(command==="whoami"||command==="workspaces"||command==="workspace"){const value2=await client.me(signal);if(value2.account.principalId!==account.principalId)accountError("ACCOUNT_IDENTITY_MISMATCH");if(command==="workspace"){const id=z.uuid().parse(options.get("--id"));if(!value2.account.tenants.some(t=>t.id===id))accountError("WORKSPACE_NOT_AUTHORIZED");await saveAccount(root,{...account,workspaceId:id,projectId:null,epoch:randomUUID2()});return{exitCode:0,output:{semanticStatus:"SUCCESS",workspaceId:id,nextSteps:["nvs projects"]}}}return{exitCode:0,output:{semanticStatus:"SUCCESS",authenticated:true,credentialPurpose:"CLI_ACCOUNT",verification:"LIVE_NATIVE_ACCOUNT",...command==="workspaces"?{workspaces:value2.account.tenants}:{account:value2.account,workspaceId:account.workspaceId,projectId:account.projectId,expiresAt:account.expiresAt},nextSteps:["nvs workspace --id <workspace-id>"]}}}if(!account.workspaceId)accountError("WORKSPACE_SELECTION_REQUIRED");if(command==="projects"){const limit=options.has("--limit")?z.coerce.number().int().min(1).max(100).parse(options.get("--limit")):void 0;const value2=await client.projects({tenantId:account.workspaceId,limit,next:options.get("--next")},signal);if(value2.items.some(p=>p.tenantId!==account.workspaceId))accountError("ACCOUNT_RESPONSE_SCOPE_MISMATCH");return{exitCode:0,output:{semanticStatus:"SUCCESS",...value2,nextSteps:["nvs project --id <project-id>"]}}}if(command!=="project")accountError("ACCOUNT_COMMAND_INPUT_INVALID");const projectId=z.uuid().parse(options.get("--id")),value=await client.project({tenantId:account.workspaceId,projectId},signal);if(value.project.id!==projectId||value.project.tenantId!==account.workspaceId)accountError("ACCOUNT_RESPONSE_SCOPE_MISMATCH");if(value.project.lifecycle!=="ACTIVE")accountError("PROJECT_ARCHIVED");await saveAccount(root,{...account,projectId,epoch:randomUUID2()});return{exitCode:0,output:{semanticStatus:"SUCCESS",project:value.project,connectionPage:`${account.serverOrigin}/projects/${projectId}/settings`,nextSteps:["Open connectionPage, then explicitly authorize this Project using nvs connect.","nvs status"]}}}))}var exits={SUCCESS:0,ACCEPTED:0,INVALID_INPUT:2,NOT_FOUND:3,BLOCKED:4,CAPABILITY_UNAVAILABLE:4,REVISION_CONFLICT:5};async function runRemoteCli(argv,environment=process.env,stdin=process.stdin){try{if(argv[0]==="connect")return await(await import("./project-connect-7L2HRJUN.js")).runProjectConnect(argv,environment);if(argv[0]==="login"){if(argv.includes("--mcp-url")){const{runProjectConnect}=await import("./project-connect-7L2HRJUN.js");const result=await runProjectConnect(["connect",...argv.slice(1)],environment);return{...result,output:{...result.output,deprecated:{code:"PROJECT_AUTH_IS_CONNECT",replacement:"nvs connect --mcp-url <project-connection-url>",note:"This legacy spelling authorizes one project; it does not establish a CLI account session."}}}}return await runAccountLogin(argv,environment)}if(argv[0]==="render")return await(await import("./render-main-ZW6UJHGN.js")).renderCommand(argv.slice(1),environment);if(AccountCommands.has(argv[0]??""))return await runAccountCommand(argv,environment);if(argv.length===1&&argv[0]==="status")return await connectionStatus(environment);if(NavigationCliCommands.has(argv[0]??""))return await runNavigationCli(argv,stdin,(args2,input2)=>runRemoteCli(args2,environment,input2));if(["auth-start","auth-complete"].includes(argv[0]??""))return await(await import("./oauth-WJ36KWAC.js")).runOAuthCommand(argv,stdin);if(!argv.length||argv.length===1&&["help","--help"].includes(argv[0]))return{exitCode:0,output:{product:"NativeStudio CLI",start:["nvs login --server <Studio-origin> \u2014 sign in/register your account in the browser; no project required.","nvs workspaces; nvs workspace --id <id>; nvs projects; nvs project --id <id>","nvs connect (uses the selected Project; read-only by default)","nvs status","nvs find --query <intent>"],navigation:["nvs capabilities","nvs overview --production <uuid>","nvs next --production <uuid>","nvs resume --production <uuid> --operation <op_original>"],agentConnection:{command:"nvs",args:["mcp"],note:"Uses the private saved connection; no token in Agent configuration."},commands:["login --server <Studio-origin> | whoami | logout \u2014 independent account session","workspaces | workspace --id <id> | projects [--limit <n>] [--next <cursor>] | project --id <id>","connect [--mcp-url <project-connection-url>] \u2014 reuses the selected Project and current authorization","status","find --query <text> [--project <uuid>]","overview | next --production <uuid> [--goal <text>]","resume --production <uuid> --operation <op_original>","capabilities [groups | search --query <text> --group <group> | describe --tool <name>]","render preview|final --production <uuid> --request <stable-uuid> [--device <uuid>] \u2014 tenant device only; saves original receipt","mcp \u2014 connect the Agent using the private saved connection","local help \u2014 installed Runtime, scoped local MCP, explicit exact-version updates"],advanced:["operations","mcp --profile <private-file> | --mcp-url <endpoint> --token-env <NAME>|--token-file <private-file>","call <operation> --input <file|-> --tenant <uuid> --token-env <NAME> --origin <https-origin>","call <operation> --input <file|-> --tenant <uuid> --token-file <private-file> --mcp-url <https-endpoint>","auth-start --profile <new-private-file> --mcp-url <resource> --callback <receiver-url>","auth-complete --profile <private-file> --input <callback-json-file|->","call <operation> --profile <private-file> --tenant <uuid> --input <file|->"],note:"No automatic write retry. Transport abort does not cancel native Jobs."}};const{NativeStudioAgentClient,sdkOperations}=await import("./src-BXLFLNRG.js");if(argv.length===1&&argv[0]==="operations")return{exitCode:0,output:{operations:Object.entries(sdkOperations).map(([name2,spec])=>({name:name2,readOnly:spec.readOnly??null,http:spec.request!==null}))}};const[command,name,...args]=argv;if(command!=="call"||!name||!Object.hasOwn(sdkOperations,name))throw Error();const options=new Map;const allowed=["--input","--tenant","--origin","--mcp-url","--token-env","--token-file","--profile"];for(let i=0;i<args.length;i+=2){const key2=args[i],value=args[i+1];if(!key2||!allowed.includes(key2)||!value||value.startsWith("--")||options.has(key2))throw Error();options.set(key2,value)}await defaultConnection(options,environment,true);if(!options.has("--input")||!options.has("--tenant")||(options.has("--profile")?options.has("--origin")||options.has("--mcp-url")||options.has("--token-file")||options.has("--token-env"):options.has("--origin")===options.has("--mcp-url")))throw Error();const key=name;const input=await readInput(options.get("--input"),stdin);const profile=options.has("--profile")?await(await import("./oauth-WJ36KWAC.js")).profileAuthorization(options.get("--profile")):null;const authorization=profile?.authorization??await readCredential(options,environment);const tenantId=options.get("--tenant");let output;if(profile||options.has("--mcp-url")){const{connectRemoteMcp}=await import("./mcp-P7W623FE.js");const connection=await connectRemoteMcp(profile?.resource??options.get("--mcp-url"),authorization,tenantId);try{output=await connection.studio.call(key,input)}finally{await connection.close()}}else{const studio=new NativeStudioAgentClient({tenantId,baseUrl:options.get("--origin"),authorization:()=>authorization});output=await studio.call(key,input)}const status=output?.semanticStatus;return{exitCode:status?exits[status]??1:0,output}}catch(error){const e=error instanceof NativeStudioSdkError?error:null;const accountRecovery={ACCOUNT_LOGIN_OUTCOME_UNKNOWN:["Start a fresh nvs login --server <Studio-origin>; never replay the old exchange."],ACCOUNT_LOGOUT_OUTCOME_UNKNOWN:["Retry nvs logout explicitly; local account use remains locked."],ACCOUNT_LOGIN_REQUIRED:["nvs login --server <Studio-origin>"],ACCOUNT_SESSION_EXPIRED_OR_REVOKED:["nvs login --server <Studio-origin>"],WORKSPACE_SELECTION_REQUIRED:["nvs workspaces","nvs workspace --id <workspace-id>"],PROJECT_CONNECTION_ACCOUNT_MISMATCH:["nvs whoami","nvs workspaces","nvs project --id <project-id>","nvs connect --mcp-url <project-connection-url>"],ACCOUNT_PROJECT_SELECTION_REQUIRED:["nvs whoami","nvs workspace --id <workspace-id>","nvs project --id <project-id>"],PROJECT_AUTHORIZED_CONNECTION_NOT_SELECTED:["Authorization may exist. Inspect Web grants; select the intended account/project before creating a fresh connection."]};return{exitCode:e?exits[e.semanticStatus]??1:2,output:{semanticStatus:e?.semanticStatus??"INVALID_INPUT",error:{code:e?.code??"INVALID_INPUT",outcome:e?.outcome??"NO_WRITE"},...e&&accountRecovery[e.code]?{nextSteps:accountRecovery[e.code]}:{},...["PROJECT_CONNECTION_REQUIRED","OAUTH_OUTCOME_UNKNOWN"].includes(e?.code??"")?{nextSteps:["nvs connect --mcp-url <project-connection-url>","nvs help"]}:{}}}}}export{runRemoteCli};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{loginLink,openLoginBrowser}from"./chunk-VDNNFVTZ.js";import{clientHome,connectionError,loadConnection,projectConnection,readAccount,saveConnection}from"./chunk-KNFUMWDY.js";import{profileAuthorization,runOAuthCommand}from"./chunk-DXJQWTLG.js";import{FileOAuthProvider}from"./chunk-FU3524Z6.js";import"./chunk-6LU6GJKW.js";import"./chunk-KB2GVAN7.js";import"./chunk-GJ7BZJLW.js";import"./chunk-VPYAXWXY.js";import"./chunk-PUNG4ND7.js";import{NativeStudioSdkError}from"./chunk-6NVIN2NI.js";import{randomUUID,timingSafeEqual}from"node:crypto";import{createServer}from"node:http";import{join}from"node:path";async function runProjectConnect(argv,environment,hooks={}){if(argv[0]!=="connect")throw Error();const options=new Map;for(let i=1;i<argv.length;i+=2){const key=argv[i],value=argv[i+1];if(!key||!["--mcp-url","--scope","--timeout-ms","--browser"].includes(key)||!value||value.startsWith("--")||options.has(key))throw Error();options.set(key,value)}const root=await clientHome(environment,true),account=await readAccount(root);const explicit=options.get("--mcp-url");if(!explicit&&(!account?.workspaceId||!account.projectId))connectionError("ACCOUNT_PROJECT_SELECTION_REQUIRED");const resource=projectConnection(explicit??new URL("/mcp/external/v1/tenants/"+account.workspaceId+"/projects/"+account.projectId,account.serverOrigin).href);const scope=options.get("--scope")??"nvs:read";if(!["nvs:read","nvs:read nvs:write"].includes(scope))throw Error();const browser=options.get("--browser")??"auto";if(!["auto","manual"].includes(browser))throw Error();const timeout=options.get("--timeout-ms")??"180000";if(!/^\d+$/.test(timeout)||Number(timeout)<1e3||Number(timeout)>3e5)throw Error();const signal=AbortSignal.timeout(Number(timeout));const profile=`profile-${randomUUID()}.json`;const path=join(root,profile),callbackPath=`/callback/${randomUUID()}`;if(account&&(account.state!=="ACTIVE"||Date.parse(account.expiresAt)<=Date.now()||account.workspaceId!==resource.tenantId||account.projectId!==resource.projectId))connectionError("ACCOUNT_PROJECT_SELECTION_REQUIRED");if(!explicit){let saved=null;try{saved=await loadConnection(environment,true)}catch(error){if(!(error instanceof NativeStudioSdkError)||error.code!=="PROJECT_CONNECTION_ACCOUNT_MISMATCH")throw error}if(saved?.resource===resource.resource&&saved.scope===scope&&!saved.exchangeUnresolved){await profileAuthorization(saved.profile,signal);return{exitCode:0,output:{semanticStatus:"SUCCESS",connected:true,resource:saved.resource,tenantId:saved.tenantId,projectId:saved.projectId,scope,reused:true}}}}let provider,receiving=false,redeeming=false;let finish;const callback=new Promise(resolve=>{finish=resolve});const server=createServer({maxHeaderSize:8192,requestTimeout:5e3,headersTimeout:5e3},(req,res)=>{res.setHeader("cache-control","no-store");res.setHeader("content-type","text/plain; charset=utf-8");res.setHeader("x-content-type-options","nosniff");const address=server.address();const host=address&&typeof address!=="string"?`127.0.0.1:${address.port}`:"";if(req.method!=="GET"||req.headers.host!==host||req.headers.origin||!req.url||req.url.length>4096||!req.url.startsWith(callbackPath+"?")||!provider||receiving){res.writeHead(400).end("Invalid authorization callback.");return}const url=new URL(req.url,`http://${host}`),state=url.searchParams.get("state");const expected=provider.data.state;const issuer=provider.data.discovery?.authorizationServerMetadata?.issuer??provider.data.discovery?.authorizationServerUrl;if(!state||Buffer.byteLength(state)!==Buffer.byteLength(expected)||!timingSafeEqual(Buffer.from(state),Buffer.from(expected))||url.searchParams.getAll("state").length!==1||url.pathname!==callbackPath||url.searchParams.getAll("iss").length!==1||url.searchParams.get("iss")!==issuer||(url.searchParams.has("error")?url.searchParams.has("code"):url.searchParams.getAll("code").length!==1||!url.searchParams.get("code"))){res.writeHead(400).end("Invalid authorization callback.");return}receiving=true;res.end("Authorization received. Return to NativeStudio CLI for the result.");finish(url.searchParams.has("error")?null:url.href)});server.maxConnections=8;const expired=()=>finish(null);signal.addEventListener("abort",expired,{once:true});try{await new Promise((resolve,reject)=>{server.once("error",reject);server.listen(0,"127.0.0.1",resolve)});const address=server.address();if(!address||typeof address==="string")throw Error();const redirect=`http://127.0.0.1:${address.port}${callbackPath}`;await runOAuthCommand(["auth-start","--profile",path,"--mcp-url",resource.resource,"--callback",redirect,"--scope",scope],empty(),signal);provider=await FileOAuthProvider.load(path);if(!provider.data.authorizationUrl)throw Error();signal.throwIfAborted();if(hooks.authorize)await hooks.authorize(provider.data.authorizationUrl,signal);else if(browser==="manual")loginLink(provider.data.authorizationUrl);else await openLoginBrowser(provider.data.authorizationUrl,signal);const received=await callback;if(!received)connectionError(signal.aborted?"LOGIN_TIMED_OUT":"LOGIN_DENIED");async function*input(){yield Buffer.from(JSON.stringify({callbackUrl:received}))}redeeming=true;await runOAuthCommand(["auth-complete","--profile",path,"--input","-"],input(),signal);const credentials=await saveConnection(root,profile,account?.epoch).catch(()=>{throw new NativeStudioSdkError("PROJECT_AUTHORIZED_CONNECTION_NOT_SELECTED","INTERNAL_OPERATIONAL_FAILURE","UNKNOWN")});return{exitCode:0,output:{semanticStatus:"SUCCESS",connected:true,credentialPurpose:"PROJECT_MCP",...resource,scope:credentials.scope,requestedScope:scope,nextSteps:["nvs status","nvs find --query <intent>","nvs mcp"]}}}catch(error){if(!redeeming&&signal.aborted)connectionError("LOGIN_TIMED_OUT");throw error}finally{signal.removeEventListener("abort",expired);server.closeAllConnections();await new Promise(resolve=>server.close(()=>resolve()))}}async function*empty(){}export{runProjectConnect};
|
package/dist/entry.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
if(process.argv[2]==="local"){if(process.argv[3]==="mcp"){const{runLocalMcp}=await import("./_chunks/local-mcp-
|
|
2
|
+
if(process.argv[2]==="local"){if(process.argv[3]==="mcp"){const{runLocalMcp}=await import("./_chunks/local-mcp-LCHXL2IE.js");process.exitCode=await runLocalMcp(process.argv.slice(4))}else{const{runLocalCli}=await import("./_chunks/local-main-J2G7OU5E.js");const result=await runLocalCli(process.argv.slice(3));process.stdout.write(JSON.stringify(result.output)+"\n");process.exitCode=result.exitCode}}else if(process.argv[2]==="mcp"){const{runMcpStdio}=await import("./_chunks/stdio-main-4Z2JVCMO.js");process.exitCode=await runMcpStdio(process.argv.slice(3),process.env)}else{const{runRemoteCli}=await import("./_chunks/main-PPA76ARV.js");const result=await runRemoteCli(process.argv.slice(2));process.stdout.write(JSON.stringify(result.output)+"\n");process.exitCode=result.exitCode}
|
package/dist/local-management.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LocalInstallationManager,captureInstalledTools,connectDevice,generateDeviceKey,newerVersion,ownerClient,socketAbsent,toolPreference,waitStopped}from"./_chunks/chunk-XZP6RNGC.js";import{DesktopDeviceRecords,DesktopDeviceReplySchema,DesktopDeviceRequestSchema,DesktopDeviceScopeSchema,desktopDeviceConnector}from"./_chunks/chunk-VDQOSVZY.js";import{LocalAgentDiscoverySchema,LocalAgentGrantSchema,LocalAgentProbeSchema,LocalAgentReviewViewSchema,LocalAgentSnapshotSchema,LocalDeviceChallengeSchema,LocalDeviceGrantSchema,LocalDeviceSessionSchema,LocalDeviceViewSchema,LocalDiagnosticsSchema,LocalFinalRenderAdmissionSchema,LocalManagementCommandSchema,LocalOfflineCallSchema,LocalOfflinePageSchema,LocalPreviewAdmissionSchema,LocalReleaseSchema,LocalResourcePolicySchema,LocalRuntimeDescriptorSchema,LocalToolSelectionSchema,LocalWorkspaceInspectionSchema,canonicalLocalJson,catalogue,endpoint}from"./_chunks/chunk-JLOHTDP6.js";import{LocalClientError,atomicMove,directory,entries,fail,optional,read,sha256,write}from"./_chunks/chunk-KB2GVAN7.js";import"./_chunks/chunk-PBEHCYR7.js";import"./_chunks/chunk-VPYAXWXY.js";import{NativeStudioSdkError}from"./_chunks/chunk-6NVIN2NI.js";import{z as z8}from"zod";import{z}from"zod";import{join,sep}from"node:path";var StoragePlanSchema=z.strictObject({id:z.uuid(),mode:z.enum(["BACKUP","MIGRATE"]),source:z.string().min(1),destination:z.string().min(1),installationRevision:z.int().nonnegative(),installationFingerprint:z.string().regex(/^[a-f0-9]{64}$/),runtimeRevision:z.int().positive(),revision:z.int().nonnegative().default(0),phase:z.enum(["PREPARED","DRAINING","COPYING","COPIED","VERIFYING","COMPLETE","CANCELLED"]),fingerprint:z.string().regex(/^[a-f0-9]{64}$/),expiresAt:z.iso.datetime(),bytes:z.int().nonnegative().default(0)});var recordSchema=z.strictObject({plan:StoragePlanSchema,previous:z.string().regex(/^[a-f0-9]{64}$/).nullable(),digest:z.string().regex(/^[a-f0-9]{64}$/)});var phases=["PREPARED","DRAINING","COPYING","COPIED","VERIFYING","COMPLETE"];var terminal=phase=>["COMPLETE","CANCELLED"].includes(phase);var advances=(before,after)=>before===after||!terminal(before)&&(after==="CANCELLED"||phases.indexOf(after)===phases.indexOf(before)+1);async function storageInstallationIdentity(slot,source,destination){const tools=slot.toolsConfigPath?LocalToolSelectionSchema.parse(JSON.parse((await read(slot.toolsConfigPath,32768)).toString())):null;if(tools?.mode==="MANAGED"){for(const name of["ffmpeg","ffprobe"])for(const root of[source,destination])if(tools[name].path.startsWith(root+sep)){tools[name].path="{state}"+tools[name].path.slice(root.length);break}}return sha256(canonicalLocalJson({descriptor:slot.descriptor,files:slot.files,tools}))}function intent(p){return{id:p.id,mode:p.mode,source:p.source,destination:p.destination,installationRevision:p.installationRevision,installationFingerprint:p.installationFingerprint,runtimeRevision:p.runtimeRevision,expiresAt:p.expiresAt}}async function history(root,id2){const path=await directory(join(root,z.uuid().parse(id2)));let plan=null;let digest5=null;const names=(await entries(path)).filter(n=>/^\d{8}\.json$/.test(n)).sort();for(const[index,name]of names.entries()){const record=recordSchema.parse(JSON.parse((await read(join(path,name))).toString())),next=record.plan;if(next.id!==id2||next.revision!==index+1||next.fingerprint!==sha256(canonicalLocalJson(intent(next)))||record.previous!==digest5||record.digest!==sha256(canonicalLocalJson({plan:next,previous:digest5}))||!plan&&next.phase!=="PREPARED"||plan&&(plan.fingerprint!==next.fingerprint||!advances(plan.phase,next.phase)))fail("STORAGE_HISTORY_INVALID");plan=next;digest5=record.digest}return{plan,digest:digest5}}async function readStoragePlan(root,id2){return(await history(root,id2)).plan}async function saveStoragePlan(root,expected,phase,extra={}){const current=await history(root,expected.id),actual=current.plan;if((actual?.revision??0)!==expected.revision)fail("REVISION_CONFLICT");if(actual&&canonicalLocalJson(actual)!==canonicalLocalJson(expected))fail("PLAN_CHANGED");const next=StoragePlanSchema.parse({...expected,...extra,phase,revision:expected.revision+1});if(next.fingerprint!==sha256(canonicalLocalJson(intent(next))))fail("PLAN_CHANGED");if(!actual&&phase!=="PREPARED"||actual&&!advances(actual.phase,phase))fail("PLAN_CHANGED");const file=join(root,next.id,String(next.revision).padStart(8,"0")+".json");try{const body={plan:next,previous:current.digest};await write(file,canonicalLocalJson({...body,digest:sha256(canonicalLocalJson(body))}),true)}catch(e){if(e.code==="EEXIST")fail("REVISION_CONFLICT");throw e}return next}import{z as z3}from"zod";import{lstat as lstat2,realpath}from"node:fs/promises";import{randomUUID}from"node:crypto";import{join as join4,resolve,sep as sep3}from"node:path";import{constants,createReadStream}from"node:fs";import{open,readdir,lstat,statfs,chmod,unlink}from"node:fs/promises";import{join as join2,relative,sep as sep2}from"node:path";import{createHash}from"node:crypto";async function digestFile(path){const file=await open(path,constants.O_RDONLY|constants.O_NOFOLLOW);try{const before=await file.stat(),hash=createHash("sha256");if(!before.isFile()||before.nlink!==1||before.size>512*1024**2||process.platform!=="win32"&&(before.uid!==process.getuid?.()||before.mode&63))fail("STORAGE_FILE_INVALID");let bytes=0;for await(const chunk of createReadStream(path,{fd:file.fd,autoClose:false})){bytes+=chunk.length;if(bytes>before.size)fail("STORAGE_FILE_CHANGED");hash.update(chunk)}const after=await file.stat();if(bytes!==before.size||before.mtimeMs!==after.mtimeMs||before.ino!==after.ino)fail("STORAGE_FILE_CHANGED");return{bytes,sha256:hash.digest("hex"),mode:before.mode&448}}finally{await file.close()}}async function storageFiles(root){const files=[];async function walk(path,depth){if(depth>8)fail("STORAGE_FILE_LIMIT");for(const item of await readdir(path,{withFileTypes:true})){const source=join2(path,item.name),name=relative(root,source);if(path===root&&!["journal.sqlite","journal.sqlite-wal","cache","staging","tools","agent-images","agent-evidence","agent-reviews"].includes(item.name))continue;const info=await lstat(source);if(info.isSymbolicLink()||!info.isFile()&&!info.isDirectory())fail("STORAGE_FILE_INVALID");if(info.isDirectory())await walk(source,depth+1);else{if(files.length>=5e4)fail("STORAGE_FILE_LIMIT");const value=await digestFile(source);files.push({name,bytes:value.bytes,sha256:value.sha256})}}}await walk(root,0);return files.sort((a,b)=>a.name.localeCompare(b.name))}async function copyStorage(source,destination){if(destination===source||destination.startsWith(source+sep2)||source.startsWith(destination+sep2))fail("STORAGE_LOCATION_INVALID");await directory(destination);const files=await storageFiles(source),total=files.reduce((n,f)=>n+f.bytes,0);const fs=await statfs(destination);if(fs.bavail*fs.bsize<total+256*1024**2)fail("STORAGE_SPACE_REQUIRED");for(const item of files){const original=join2(source,item.name),target=join2(destination,item.name);const parent=target.slice(0,target.lastIndexOf(sep2));await directory(parent);try{const existing=await digestFile(target);if(existing.sha256!==item.sha256||existing.bytes!==item.bytes)fail("STORAGE_COPY_CONFLICT");continue}catch(error){if(error.code!=="ENOENT")throw error}const temporary=target+".copy-part";try{await digestFile(temporary);await unlink(temporary)}catch(error){if(error.code!=="ENOENT")throw error}const input=await open(original,constants.O_RDONLY|constants.O_NOFOLLOW),output=await open(temporary,"wx",384);try{for await(const bytes of createReadStream(original,{fd:input.fd,autoClose:false}))await output.writeFile(bytes);await output.sync()}finally{await input.close();await output.close()}const copied=await digestFile(temporary),before=await digestFile(original);if(copied.sha256!==item.sha256||before.sha256!==item.sha256||copied.bytes!==item.bytes)fail("STORAGE_COPY_INVALID");await chmod(temporary,before.mode);await atomicMove(temporary,target,true)}return{files,total}}import{join as join3}from"node:path";import{z as z2}from"zod";var digest=z2.string().regex(/^[a-f0-9]{64}$/);var DesktopAutomationSchema=z2.strictObject({enabled:z2.boolean(),scope:DesktopDeviceScopeSchema,deviceId:z2.uuid(),deviceRevision:z2.int().positive(),installationFingerprint:digest,projects:z2.array(z2.strictObject({projectId:z2.uuid(),grantId:z2.uuid(),revision:z2.int().positive(),expiresAt:z2.iso.datetime()})).min(1).max(20)});async function desktopInstallationIdentity(manager){const active=(await manager.ledger.current()).value.active;if(!active)return null;const tools=active.toolsConfigPath?JSON.parse((await read(active.toolsConfigPath,32768)).toString()):null;return{version:active.descriptor.version,workProtocol:active.descriptor.workProtocol,fingerprint:sha256(canonicalLocalJson({descriptor:active.descriptor,files:active.files,tools}))}}async function desktopAutomation(home){const value=await optional(join3(home,"desktop-execution-policy.json"));return value?DesktopAutomationSchema.parse(value):null}function canResumeDesktop(policy,state,installation){if(!policy?.enabled||!installation||!state.device||policy.installationFingerprint!==installation.fingerprint||canonicalLocalJson(policy.scope)!==canonicalLocalJson(state.scope)||policy.deviceId!==state.device.deviceId||policy.deviceRevision!==state.device.revision)return false;const grants=state.grants.filter(g=>!g.revokedAt&&Date.parse(g.expiresAt)>Date.now());return grants.length>0&&grants.every(g=>policy.projects.some(p=>p.projectId===g.projectId&&p.grantId===g.grantId&&p.revision===g.revision&&p.expiresAt===g.expiresAt))}async function rememberDesktopAutomation(home,state,installation,expectedFingerprint,projectIds){if(!installation||installation.fingerprint!==expectedFingerprint||!state.device)fail("DEVICE_PLAN_CHANGED");const grants=state.grants.filter(g=>!g.revokedAt&&Date.parse(g.expiresAt)>Date.now());if(!grants.length||grants.some(g=>!projectIds.includes(g.projectId)))fail("DEVICE_PLAN_CHANGED");const value=DesktopAutomationSchema.parse({enabled:true,scope:state.scope,deviceId:state.device.deviceId,deviceRevision:state.device.revision,installationFingerprint:expectedFingerprint,projects:grants.map(g=>({projectId:g.projectId,grantId:g.grantId,revision:g.revision,expiresAt:g.expiresAt}))});await write(join3(home,"desktop-execution-policy.json"),canonicalLocalJson(value));return value}async function disableDesktopAutomation(home){const policy=await desktopAutomation(home);if(policy)await write(join3(home,"desktop-execution-policy.json"),canonicalLocalJson({...policy,enabled:false}))}var id=z3.uuid();var digest2=z3.string().regex(/^[a-f0-9]{64}$/);var planSchema=StoragePlanSchema;var DesktopStorageRequestSchema=z3.strictObject({operation:z3.literal("storage"),call:z3.discriminatedUnion("action",[z3.strictObject({action:z3.literal("status")}),z3.strictObject({action:z3.literal("prepare"),mode:z3.enum(["BACKUP","MIGRATE"]),destination:z3.string().min(1).max(4096)}),z3.strictObject({action:z3.enum(["execute","recover","abandon"]),id,fingerprint:digest2})])});var viewSchema=planSchema.omit({source:true,destination:true,runtimeRevision:true,installationRevision:true});var DesktopStorageReplySchema=viewSchema.nullable();function present(plan){if(!plan)return null;const{source,destination,runtimeRevision,installationRevision,...view2}=plan;void source;void destination;void runtimeRevision;void installationRevision;return DesktopStorageReplySchema.parse(view2)}async function runDesktopStorageRequest(home,raw){const{call}=DesktopStorageRequestSchema.parse(raw),manager=await LocalInstallationManager.open(home);const root=await directory(join4(home,"storage-plans"));const pointer=await optional(join4(root,"current.json"));const prior=pointer?await readStoragePlan(root,id.parse(pointer)):null;if(call.action==="status")return present(prior);let config=await manager.configuration(),installation=(await manager.ledger.current()).value;let plan;const save=async(phase,extra={})=>{plan=await saveStoragePlan(root,plan,phase,extra)};if(call.action==="prepare"){if(!installation.active||installation.transition)fail("RECOVERY_REQUIRED");if(prior&&!["COMPLETE","CANCELLED"].includes(prior.phase))fail("RECOVERY_REQUIRED");const selected=resolve(call.destination),info=await lstat2(selected);if(!info.isDirectory()||info.isSymbolicLink()||process.platform!=="win32"&&info.uid!==process.getuid?.())fail("STORAGE_LOCATION_INVALID");const destination=await realpath(selected);if(destination===config.stateDirectory||destination.startsWith(config.stateDirectory+sep3))fail("STORAGE_LOCATION_INVALID");const inventory=await(await ownerClient(config.stateDirectory)).inventory();const body={id:randomUUID(),mode:call.mode,source:config.stateDirectory,destination:join4(destination,"NVS-"+randomUUID().replaceAll("-","").slice(0,16)),installationRevision:installation.revision,runtimeRevision:inventory.runtimeRevision,expiresAt:new Date(Date.now()+18e5).toISOString()};if(call.mode==="MIGRATE"&&process.platform!=="win32"&&Buffer.byteLength(join4(body.destination,"runtime.sock"))>100)fail("SOCKET_PATH_TOO_LONG");const frozen={...body,installationFingerprint:await storageInstallationIdentity(installation.active,body.source,body.destination)};plan=planSchema.parse({...frozen,fingerprint:sha256(canonicalLocalJson(frozen)),phase:"PREPARED"});await save("PREPARED");await write(join4(root,"current.json"),canonicalLocalJson(plan.id));return present(plan)}plan=await readStoragePlan(root,call.id);if(!plan||plan.fingerprint!==call.fingerprint)fail("PLAN_CHANGED");if(["COMPLETE","CANCELLED"].includes(plan.phase))return present(plan);if(call.action==="abandon"){await save("CANCELLED");return present(plan)}if(!installation.active||installation.transition)fail("RECOVERY_REQUIRED");if(await storageInstallationIdentity(installation.active,plan.source,plan.destination)!==plan.installationFingerprint)fail("PLAN_CHANGED");if(config.stateDirectory!==plan.source&&!(plan.mode==="MIGRATE"&&config.stateDirectory===plan.destination))fail("PLAN_CHANGED");if(plan.phase==="PREPARED"){if(Date.parse(plan.expiresAt)<=Date.now()||installation.revision!==plan.installationRevision)fail("PLAN_CHANGED");const client=await ownerClient(plan.source),inventory=await client.inventory();if(inventory.runtimeRevision!==plan.runtimeRevision)fail("REVISION_CONFLICT");await save("DRAINING");await manager.stop()}if(plan.phase==="DRAINING"){await waitStopped(plan.source);if(!await socketAbsent(plan.source))fail("RECOVERY_REQUIRED");await save("COPYING")}if(plan.phase==="COPYING"){if(!await socketAbsent(plan.source))fail("RECOVERY_REQUIRED");const copied=await copyStorage(plan.source,plan.destination);await write(join4(plan.destination,"backup-manifest.json"),canonicalLocalJson({protocol:"NVS_STORAGE_COPY_V1",planId:plan.id,...copied}));await save("COPIED",{bytes:copied.total})}if(plan.phase==="COPIED"){if(plan.mode==="MIGRATE"){if(installation.active.toolsConfigPath){const tools=LocalToolSelectionSchema.parse(JSON.parse((await read(installation.active.toolsConfigPath,32768)).toString()));if(tools.mode==="MANAGED"){for(const name of["ffmpeg","ffprobe"]){if(tools[name].path.startsWith(plan.source+sep3))tools[name].path=plan.destination+tools[name].path.slice(plan.source.length);else if(!tools[name].path.startsWith(plan.destination+sep3)||installation.active.toolsConfigPath!==join4(root,plan.id+"-tools.json"))fail("PLAN_CHANGED")}const toolsConfigPath=join4(root,plan.id+"-tools.json");await write(toolsConfigPath,canonicalLocalJson(tools));if(installation.active.toolsConfigPath!==toolsConfigPath)await manager.ledger.commit(installation,{active:{...installation.active,toolsConfigPath},transition:null})}}await manager.configure({...config,stateDirectory:plan.destination});await disableDesktopAutomation(home)}await save("VERIFYING")}if(plan.phase==="VERIFYING"){await manager.start();config=await manager.configuration();const inventory=await(await ownerClient(config.stateDirectory)).inventory();installation=(await manager.ledger.current()).value;if(canonicalLocalJson(inventory.descriptor)!==canonicalLocalJson(installation.active.descriptor))fail("STORAGE_COPY_INVALID");await save("COMPLETE")}return present(plan)}import{z as z4}from"zod";var DesktopOfflineRequestSchema=z4.strictObject({operation:z4.literal("offline"),call:LocalOfflineCallSchema});var DesktopOfflineReplySchema=LocalOfflinePageSchema;async function runDesktopOfflineRequest(home,raw){const{call}=DesktopOfflineRequestSchema.parse(raw),manager=await LocalInstallationManager.open(home),c=await manager.configuration();if(!(await manager.status()).running){const policy=await desktopAutomation(home),installation=await desktopInstallationIdentity(manager);if(!policy?.enabled||policy.installationFingerprint!==installation?.fingerprint||!policy.projects.some(p=>Date.parse(p.expiresAt)>Date.now())||!await socketAbsent(c.stateDirectory))fail("RUNTIME_STATUS_REQUIRED");await manager.start()}const client=await ownerClient(c.stateDirectory);return LocalOfflinePageSchema.parse(await client.call({operation:"offline.workspace",input:call}))}import{z as z5}from"zod";import{join as join5}from"node:path";import{unlink as unlink2}from"node:fs/promises";var sha=z5.string().regex(/^[a-f0-9]{64}$/);var historyItem=z5.strictObject({id:z5.uuid(),projectId:z5.uuid(),productionId:z5.uuid(),kind:z5.enum(["IMAGE","VIDEO","ROUGH_CUT","PROGRAMMATIC"]),mediaFileId:z5.uuid().optional()});var stateSchema=z5.strictObject({grantFingerprint:sha.nullable(),pendingGrant:sha.nullable(),history:z5.array(historyItem).max(200)});var DesktopAgentRequestSchema=z5.strictObject({operation:z5.literal("agent"),scope:DesktopDeviceScopeSchema,call:z5.discriminatedUnion("action",[z5.strictObject({action:z5.literal("discover"),binary:z5.string().min(1).max(4096).optional()}),z5.strictObject({action:z5.literal("probe")}),z5.strictObject({action:z5.literal("grant"),grant:LocalAgentGrantSchema,approval:sha}),z5.strictObject({action:z5.literal("revoke")}),z5.strictObject({action:z5.literal("prepare"),snapshot:LocalAgentSnapshotSchema}),z5.strictObject({action:z5.literal("stage"),id:z5.uuid(),mediaFileId:z5.uuid().optional()}),z5.strictObject({action:z5.literal("start"),id:z5.uuid(),expectedRevision:z5.int().positive(),approval:sha}),z5.strictObject({action:z5.literal("inspect"),id:z5.uuid()})])});var DesktopAgentReplySchema=z5.strictObject({probe:LocalAgentProbeSchema.optional(),discovery:LocalAgentDiscoverySchema.optional(),review:LocalAgentReviewViewSchema.optional(),history:z5.array(historyItem.omit({mediaFileId:true}).extend({pendingMedia:z5.boolean()})).max(200),pendingGrant:z5.boolean()});async function runDesktopAgentRequest(home,raw){const{scope,call}=DesktopAgentRequestSchema.parse(raw),root=await directory(join5(home,"agent-owner",sha256(canonicalLocalJson(scope)))),path=join5(root,"current.json");let state=stateSchema.parse(await optional(path)??{grantFingerprint:null,pendingGrant:null,history:[]});const manager=await LocalInstallationManager.open(home),client=await ownerClient((await manager.configuration()).stateDirectory);const save=async value=>{state=stateSchema.parse({...state,...value});await write(path,canonicalLocalJson(state))};const result=fields=>DesktopAgentReplySchema.parse({...fields,history:state.history.map(({mediaFileId,...r})=>{return{...r,pendingMedia:!!mediaFileId}}),pendingGrant:!!state.pendingGrant});if(call.action==="discover"){const discovery=await client.discoverAgent(call.binary);const fp=discovery.configured?sha256(canonicalLocalJson(discovery.configured)):null;if(state.pendingGrant&&state.pendingGrant===fp)await save({grantFingerprint:fp,pendingGrant:null});return result({discovery:{...discovery,configured:fp===state.grantFingerprint?discovery.configured:null}})}if(call.action==="probe"){const probe=await client.probeAgent();if(state.pendingGrant&&probe.grantFingerprint===state.pendingGrant)await save({grantFingerprint:state.pendingGrant,pendingGrant:null});return result({probe:probe.grantFingerprint===state.grantFingerprint?probe:{...probe,available:false,configured:false,reason:"GRANT_REQUIRED",grantFingerprint:null}})}if(call.action==="grant"){if(state.pendingGrant)fail("AGENT_OUTCOME_UNKNOWN");if(call.grant.projects.some(p=>p.tenantId!==scope.tenantId)||sha256(canonicalLocalJson(call.grant))!==call.approval)fail("AGENT_APPROVAL_REQUIRED");await save({pendingGrant:call.approval});let probe;try{probe=await client.grantAgent(call.grant,call.approval)}catch(e){if(e instanceof NativeStudioSdkError&&["NO_WRITE","REJECTED"].includes(e.outcome))await save({pendingGrant:null});throw e}await save({pendingGrant:null,grantFingerprint:call.approval});return result({probe})}if(call.action==="revoke"){const probe=await client.probeAgent();if(!state.grantFingerprint||probe.grantFingerprint!==state.grantFingerprint)fail("AGENT_APPROVAL_REQUIRED");const revoked=await client.revokeAgent(state.grantFingerprint);await save({grantFingerprint:null,pendingGrant:null});return result({probe:revoked})}if(call.action==="prepare"){if(state.history.length>=200)fail("QUERY_LIMIT");if(state.pendingGrant||!state.grantFingerprint||call.snapshot.basis.scope.tenantId!==scope.tenantId)fail("AGENT_APPROVAL_REQUIRED");const review=await client.prepareAgentReview(call.snapshot);if(review.plan.grantFingerprint!==state.grantFingerprint)fail("AGENT_APPROVAL_REQUIRED");const s2=review.plan.snapshot.basis.scope;await save({history:[{id:review.plan.id,projectId:s2.projectId,productionId:s2.productionId,kind:review.plan.snapshot.basis.target.kind},...state.history]});return result({review})}const entry=state.history.find(h=>h.id===call.id);if(!entry)fail("AGENT_APPROVAL_REQUIRED");const original=await client.inspectAgentReview(call.id),s=original.plan.snapshot.basis.scope;if(s.tenantId!==scope.tenantId||s.projectId!==entry.projectId||s.productionId!==entry.productionId)fail("AGENT_APPROVAL_REQUIRED");const staged=!!(original.imageReceipt||original.evidenceReceipt);if(staged&&entry.mediaFileId){const file=join5(home,"agent-import",entry.mediaFileId+".bin");try{const bytes=await read(file,134217728);if(sha256(bytes)!==original.plan.snapshot.media.checksumSha256)fail("AGENT_IMAGE_INVALID");await unlink2(file)}catch(e){if(e.code!=="ENOENT")throw e}await save({history:state.history.map(h=>{if(h.id!==call.id)return h;const{mediaFileId,...item}=h;void mediaFileId;return item})})}if(call.action==="inspect"||call.action==="stage"&&staged)return result({review:original});if(call.action==="stage"){const mediaFileId=call.mediaFileId??entry.mediaFileId;if(!mediaFileId)fail("AGENT_IMAGE_REQUIRED");await save({history:state.history.map(h=>h.id===call.id?{...h,mediaFileId}:h)});const file=join5(home,"agent-import",mediaFileId+".bin"),bytes=await read(file,134217728);const review=await client.stageAgentImage(call.id,bytes);await unlink2(file);await save({history:state.history.map(h=>{if(h.id!==call.id)return h;const{mediaFileId:_id,...rest}=h;void _id;return rest})});return result({review})}if(state.pendingGrant||original.plan.grantFingerprint!==state.grantFingerprint)fail("AGENT_APPROVAL_REQUIRED");return result({review:await client.startAgentReview(call.id,call.expectedRevision,call.approval)})}import{z as z6}from"zod";var digest3=z6.string().regex(/^[a-f0-9]{64}$/);var DesktopBootstrapRequestSchema=z6.strictObject({operation:z6.literal("bootstrap"),call:z6.discriminatedUnion("action",[z6.strictObject({action:z6.literal("prepare")}),z6.strictObject({action:z6.literal("apply"),id:z6.uuid(),fingerprint:digest3})])});var DesktopBootstrapReplySchema=z6.strictObject({id:z6.uuid(),fingerprint:digest3,version:z6.string().min(1).max(80),host:z6.string().min(1).max(512),bytes:z6.int().positive(),expiresAt:z6.iso.datetime(),installed:z6.boolean()});import{z as z7}from"zod";var DesktopWorkspaceRequestSchema=z7.strictObject({operation:z7.literal("workspace"),call:z7.discriminatedUnion("action",[z7.strictObject({action:z7.enum(["inspect","clean","diagnostics"])}),z7.strictObject({action:z7.literal("configure"),policy:LocalResourcePolicySchema,expectedRevision:z7.int().nonnegative()}),z7.strictObject({action:z7.literal("activity"),idleSeconds:z7.int().min(0).max(86400),observedAt:z7.iso.datetime()})])});var DesktopWorkspaceReplySchema=z7.union([LocalWorkspaceInspectionSchema,LocalDiagnosticsSchema]);async function runDesktopWorkspaceRequest(home,raw){const request=DesktopWorkspaceRequestSchema.parse(raw);const manager=await LocalInstallationManager.open(home);const config=await manager.configuration();const client=await ownerClient(config.stateDirectory);const input=request.call;switch(input.action){case"inspect":return client.workspace.inspect();case"clean":return client.workspace.clean();case"diagnostics":return client.workspace.diagnostics();case"configure":return client.workspace.configure(input.policy,input.expectedRevision);case"activity":return client.workspace.observeActivity(input.idleSeconds,input.observedAt)}}var version=LocalRuntimeDescriptorSchema.shape.version;var fingerprint=z8.string().regex(/^[a-f0-9]{64}$/);var DesktopRuntimeChannelSchema=z8.strictObject({protocol:z8.literal("NVS_DESKTOP_RUNTIME_CHANNEL_V1"),catalogueUrl:z8.string().url().max(4096),publicKey:z8.string().min(32).max(16384)});var DesktopOwnerRequestSchema=z8.discriminatedUnion("operation",[DesktopDeviceRequestSchema,DesktopWorkspaceRequestSchema,DesktopStorageRequestSchema,DesktopOfflineRequestSchema,DesktopAgentRequestSchema,DesktopBootstrapRequestSchema,z8.strictObject({operation:z8.enum(["status","start","stop","check","configuration","recovery"])}),z8.strictObject({operation:z8.enum(["prepare","reject"]),version}),z8.strictObject({operation:z8.literal("tools-prepare"),version,choice:z8.discriminatedUnion("mode",[z8.strictObject({mode:z8.literal("MANAGED")}),z8.strictObject({mode:z8.literal("INSTALLED"),ffmpeg:z8.string().min(1).max(4096),ffprobe:z8.string().min(1).max(4096)})])}),z8.strictObject({operation:z8.literal("configure"),channelFingerprint:fingerprint}),z8.strictObject({operation:z8.enum(["apply","recover"]),planId:z8.uuid(),fingerprint})]);var DesktopRuntimeStatusSchema=z8.strictObject({protocol:z8.literal("NVS_DESKTOP_RUNTIME_STATUS_V1"),state:z8.enum(["RUNNING","STOPPED","UNAVAILABLE","INSTALL_REQUIRED"]),activeVersion:version.nullable(),phase:z8.string().regex(/^[A-Z_]{1,64}$/),toolMode:z8.enum(["MANAGED","INSTALLED"]).nullable().optional()});var DesktopUpdateCheckSchema=z8.strictObject({protocol:z8.literal("NVS_DESKTOP_RUNTIME_UPDATES_V1"),activeVersion:version.nullable(),versions:z8.array(z8.strictObject({version,rejected:z8.boolean()})).max(128),notifications:z8.boolean()});var DesktopOwnerPlanSchema=z8.strictObject({protocol:z8.literal("NVS_DESKTOP_OWNER_PLAN_V1"),plan:z8.strictObject({kind:z8.enum(["APPLY","RECOVER"]),toolMode:z8.enum(["MANAGED","INSTALLED"]).optional(),planId:z8.uuid(),fingerprint,version,previousVersion:version.nullable(),expiresAt:z8.iso.datetime(),phase:z8.string().regex(/^[A-Z_]{1,64}$/)}).nullable()});var DesktopChannelInfoSchema=z8.strictObject({protocol:z8.literal("NVS_DESKTOP_CHANNEL_INFO_V1"),configured:z8.boolean(),source:z8.enum(["EXISTING","BUNDLED","UNAVAILABLE"]),host:z8.string().max(512).nullable(),channelFingerprint:fingerprint.nullable()});var desktopOwnerResponses={device:DesktopDeviceReplySchema,workspace:DesktopWorkspaceReplySchema,storage:DesktopStorageReplySchema,offline:DesktopOfflineReplySchema,agent:DesktopAgentReplySchema,bootstrap:DesktopBootstrapReplySchema,status:DesktopRuntimeStatusSchema,start:DesktopRuntimeStatusSchema,stop:DesktopRuntimeStatusSchema,configure:DesktopRuntimeStatusSchema,apply:DesktopRuntimeStatusSchema,recover:DesktopRuntimeStatusSchema,reject:DesktopRuntimeStatusSchema,check:DesktopUpdateCheckSchema,configuration:DesktopChannelInfoSchema,prepare:DesktopOwnerPlanSchema,"tools-prepare":DesktopOwnerPlanSchema,recovery:DesktopOwnerPlanSchema};async function desktopRuntimeStatus(manager){const status=await manager.status();const stopped=!status.running&&status.activeVersion?await socketAbsent((await manager.configuration()).stateDirectory):false;const active=(await manager.ledger.current()).value.active;const toolMode=active?.toolsConfigPath?(await toolPreference(active.toolsConfigPath,null)).mode:null;return DesktopRuntimeStatusSchema.parse({protocol:"NVS_DESKTOP_RUNTIME_STATUS_V1",state:status.running?"RUNNING":stopped?"STOPPED":status.activeVersion?"UNAVAILABLE":"INSTALL_REQUIRED",activeVersion:status.activeVersion,phase:status.phase,toolMode})}import{createPublicKey}from"node:crypto";import{join as join6}from"node:path";function desktopRuntimeChannel(raw){const channel=DesktopRuntimeChannelSchema.parse(raw);const url=endpoint(channel.catalogueUrl),key=createPublicKey(channel.publicKey);if(key.asymmetricKeyType!=="ed25519"||channel.publicKey.replace(/\r\n/g,"\n").trim()!==key.export({type:"spki",format:"pem"}).toString().trim())fail("RELEASE_SIGNATURE_INVALID");const value={...channel,catalogueUrl:url.href,publicKey:key.export({type:"spki",format:"pem"}).toString()};return{value,host:url.host,fingerprint:sha256(canonicalLocalJson(value))}}async function desktopChannelInfo(manager,bundled){let channel,configured=false;try{const config=await manager.configuration();channel=desktopRuntimeChannel({protocol:"NVS_DESKTOP_RUNTIME_CHANNEL_V1",catalogueUrl:config.catalogueUrl,publicKey:(await read(config.publicKeyFile,16384)).toString()});configured=true}catch(error){if(!(error instanceof LocalClientError&&error.code==="CONFIGURATION_REQUIRED"))throw error;if(bundled!==void 0)channel=desktopRuntimeChannel(bundled)}return DesktopChannelInfoSchema.parse({protocol:"NVS_DESKTOP_CHANNEL_INFO_V1",configured,source:configured?"EXISTING":channel?"BUNDLED":"UNAVAILABLE",host:channel?.host??null,channelFingerprint:channel?.fingerprint??null})}async function configureDesktopChannel(manager,expectedFingerprint,bundled){const info=await desktopChannelInfo(manager,bundled);if(!info.channelFingerprint)fail("DESKTOP_CHANNEL_REQUIRED");if(info.channelFingerprint!==expectedFingerprint)fail("DESKTOP_CHANNEL_CHANGED");if(info.configured)return;const stateDirectory=join6(manager.ledger.root,"runtime-state");if(process.platform!=="win32"&&Buffer.byteLength(join6(stateDirectory,"runtime.sock"))>100)fail("SOCKET_PATH_TOO_LONG");const channel=desktopRuntimeChannel(bundled),publicKeyFile=join6(manager.ledger.root,"desktop-release-"+channel.fingerprint+".pem");try{await write(publicKeyFile,channel.value.publicKey,true)}catch(error){if(error.code!=="EEXIST")throw error;if((await read(publicKeyFile,16384)).toString()!==channel.value.publicKey)fail("DESKTOP_CHANNEL_CHANGED")}try{await manager.configure({stateDirectory,catalogueUrl:channel.value.catalogueUrl,publicKeyFile,notifications:true},{ifAbsent:true})}catch(error){if(error.code==="EEXIST")fail("DESKTOP_CHANNEL_CHANGED");throw error}}import{createPrivateKey as createPrivateKey2,createPublicKey as createPublicKey2,randomUUID as randomUUID4}from"node:crypto";import{randomUUID as randomUUID2}from"node:crypto";async function connectDesktopDevice(records,manager,s,expectedRevision){if(s.revision!==expectedRevision)fail("DEVICE_PLAN_CHANGED");if(s.connection?.phase==="CONNECTING")fail("DEVICE_CONNECTION_RECOVERY_REQUIRED");if(!s.device)fail("DEVICE_ENROLLMENT_REQUIRED");const valid=s.grants.filter(g=>!g.revokedAt&&Date.parse(g.expiresAt)>Date.now());if(!valid.length)fail("LOCAL_AUTHORIZATION_REQUIRED");const projects=valid.map(g=>({tenantId:g.tenantId,projectId:g.projectId}));const c=await manager.configuration();const previous=c.cloudConfigFile?JSON.parse((await read(c.cloudConfigFile,32768)).toString()):null;if(previous&&(previous.endpoint!==s.scope.origin||previous.tenantId!==s.scope.tenantId||previous.deviceId!==s.device.deviceId))fail("DEVICE_CONNECTION_CONFLICT");const running=(await manager.status()).running;if(!running&&!await socketAbsent(c.stateDirectory))fail("DEVICE_CONNECTION_RECOVERY_REQUIRED");const reuse=running&&previous&&canonicalLocalJson(previous.projects)===canonicalLocalJson(projects);const expiresAt=new Date(Math.min(Date.now()+24*36e5,...valid.map(g=>Date.parse(g.expiresAt)))).toISOString();s=await records.save(s,{connection:{phase:"CONNECTING",projects,expiresAt}});if(!reuse){if(running)await manager.stop();await connectDevice(manager,{endpoint:s.scope.origin,tenantId:s.scope.tenantId,deviceId:s.device.deviceId,deviceRevision:s.device.revision,privateKeyFile:records.keyPath(),platform:s.device.platform,projects});await manager.start()}const id2=randomUUID2();await manager.grant({projects,expiresAt},records.connectorPath(id2));return records.save(s,{connectorId:id2,connection:{...s.connection,phase:"CONNECTED"}})}async function recoverDesktopConnection(records,manager,s){if(s.connection?.phase!=="CONNECTING")return s;const c=await manager.configuration(),running=(await manager.status()).running;if(!running){if(!await socketAbsent(c.stateDirectory))fail("DEVICE_CONNECTION_RECOVERY_REQUIRED");return records.save(s,{connection:null,connectorId:null})}if(!c.cloudConfigFile||!s.device)fail("DEVICE_CONNECTION_RECOVERY_REQUIRED");const actual=JSON.parse((await read(c.cloudConfigFile,32768)).toString());if(actual.endpoint!==s.scope.origin||actual.deviceId!==s.device.deviceId||actual.tenantId!==s.scope.tenantId||canonicalLocalJson(actual.projects)!==canonicalLocalJson(s.connection.projects))fail("DEVICE_CONNECTION_RECOVERY_REQUIRED");return records.save(s,{connection:{...s.connection,phase:"READY"},connectorId:null})}import{createPrivateKey,sign,randomUUID as randomUUID3}from"node:crypto";async function proveDesktopDevice(records){const state=await records.current(),d=state.device;if(!d)fail("DEVICE_ENROLLMENT_REQUIRED");async function request(action,input){const response=await fetch(state.scope.origin+"/v1/local-execution/devices/"+action,{method:"POST",redirect:"error",headers:{"content-type":"application/json"},body:JSON.stringify(input),signal:AbortSignal.timeout(15e3)});if(!response.ok){await response.body?.cancel();fail("DEVICE_PROOF_UNAVAILABLE")}const chunks=[];let size=0;for await(const bytes of response.body??[]){size+=bytes.length;if(size>16384)fail("DEVICE_PROOF_INVALID");chunks.push(bytes)}return JSON.parse(Buffer.concat(chunks).toString())}const scope={tenantId:d.tenantId,deviceId:d.deviceId,deviceRevision:d.revision};const challenge=LocalDeviceChallengeSchema.parse(await request("challenge",scope));if(challenge.tenantId!==d.tenantId||challenge.deviceId!==d.deviceId||challenge.deviceRevision!==d.revision||Date.parse(challenge.expiresAt)<=Date.now())fail("DEVICE_PROOF_INVALID");const key=createPrivateKey({key:JSON.parse((await read(records.keyPath(),16384)).toString()),format:"jwk"});const header=Buffer.from(JSON.stringify({alg:"ES256",typ:"nvs-local-device+jwt"})).toString("base64url");const iat=Math.floor(Date.now()/1e3),claims=Buffer.from(JSON.stringify({protocol:"NVS_LOCAL_DEVICE_PROOF_V1",...scope,challengeId:challenge.challengeId,audience:challenge.audience,jti:randomUUID3(),iat,exp:iat+30})).toString("base64url");const unsigned=header+"."+claims;const assertion=unsigned+"."+sign("sha256",Buffer.from(unsigned),{key,dsaEncoding:"ieee-p1363"}).toString("base64url");const result=LocalDeviceSessionSchema.parse(await request("prove",{...scope,challengeId:challenge.challengeId,assertion}));if(result.tenantId!==d.tenantId||result.deviceId!==d.deviceId)fail("DEVICE_PROOF_INVALID")}var fingerprint2=v=>sha256(canonicalLocalJson(v));function view(s){return{revision:s.revision,device:s.device?{deviceId:s.device.deviceId,label:s.device.label}:null,grants:s.grants,previews:s.previews,connection:s.connection,pending:s.pending?{kind:s.pending.command.kind,phase:s.pending.phase,fingerprint:s.pending.fingerprint}:null}}function accepted(s,result){const command=s.pending.command,i=command.input;if(command.kind==="ENROLL"){const d=LocalDeviceViewSchema.parse(result);if(d.tenantId!==i.tenantId||d.enrolledByPrincipalId!==s.scope.principalId||d.label!==command.input.label||d.runtimeVersion!==command.input.runtimeVersion||canonicalLocalJson(d.publicKey)!==canonicalLocalJson(command.input.publicKey)||canonicalLocalJson(d.platform)!==canonicalLocalJson(command.input.platform)||d.revokedAt)fail("DEVICE_RESULT_INVALID");return{device:d}}if(command.kind==="GRANT"){const g=LocalDeviceGrantSchema.parse(result),input2=command.input;if(g.tenantId!==input2.tenantId||g.projectId!==input2.projectId||g.deviceId!==input2.deviceId||g.deviceRevision!==input2.deviceRevision||g.revision!==input2.expectedRevision+1||g.expiresAt!==input2.expiresAt||g.capability!==input2.capability||g.executionPolicy!==input2.executionPolicy||g.approvedByPrincipalId!==s.scope.principalId||g.revokedAt)fail("DEVICE_RESULT_INVALID");return{grants:[...s.grants.filter(v=>v.projectId!==g.projectId),g]}}if(command.kind==="REVOKE_GRANT"){if(result?.semanticStatus!=="SUCCESS")fail("DEVICE_RESULT_INVALID");return{grants:s.grants.map(g=>g.projectId===command.input.projectId?{...g,revision:g.revision+1,revokedAt:new Date().toISOString()}:g),connectorId:null}}const p=(command.kind==="FINAL_RENDER"?LocalFinalRenderAdmissionSchema:LocalPreviewAdmissionSchema).parse(result),input=command.input;if(p.productionId!==input.productionId||p.timelineVersionId!==input.timelineVersionId||p.timelineFingerprint!==input.timelineFingerprint||canonicalLocalJson(p.placement.policy)!==canonicalLocalJson(input.placement))fail("DEVICE_RESULT_INVALID");return{previews:[p,...s.previews.filter(v=>v.renderId!==p.renderId)].slice(0,20)}}async function runDesktopDeviceRequest(home,raw){const request=DesktopDeviceRequestSchema.parse(raw),call=request.call;const records=await DesktopDeviceRecords.open(home,request.scope),manager=await LocalInstallationManager.open(home);let s=await records.current();const installation=await desktopInstallationIdentity(manager);let automatic=await desktopAutomation(home);const publicView=()=>({...view(s),installation,automaticConnection:canResumeDesktop(automatic,s,installation)});if(call.action==="inspect")return DesktopDeviceReplySchema.parse({view:publicView(),...s.pending?{command:s.pending.command}:{}});if(call.action==="dispatch"||call.action==="record"||call.action==="refused"){if(!s.pending||s.pending.fingerprint!==call.fingerprint)fail("DEVICE_PLAN_CHANGED");if(call.action==="dispatch"){if(s.pending.phase!=="PREPARED")fail("DEVICE_OUTCOME_UNKNOWN");const command2=s.pending.command;s=await records.save(s,{pending:{...s.pending,phase:"SENDING"}});return DesktopDeviceReplySchema.parse({view:publicView(),command:command2})}if(s.pending.phase!=="SENDING")fail("DEVICE_PLAN_CHANGED");s=await records.save(s,call.action==="record"?{...accepted(s,call.result),pending:null}:{pending:{...s.pending,phase:"REFUSED"}});return DesktopDeviceReplySchema.parse({view:publicView()})}if(s.pending?.phase==="SENDING")fail("DEVICE_OUTCOME_UNKNOWN");if(call.action==="remember-enable"){if(s.revision!==call.expectedRevision)fail("DEVICE_PLAN_CHANGED");automatic=await rememberDesktopAutomation(home,s,installation,call.installationFingerprint,call.projectIds);return DesktopDeviceReplySchema.parse({view:publicView()})}if(call.action==="prove"){await proveDesktopDevice(records);return DesktopDeviceReplySchema.parse({view:publicView()})}if(call.action==="connect"){if(call.installationFingerprint&&call.installationFingerprint!==installation?.fingerprint)fail("DEVICE_PLAN_CHANGED");s=await connectDesktopDevice(records,manager,s,call.expectedRevision);return DesktopDeviceReplySchema.parse({view:publicView()})}if(call.action==="connection-recover"){s=await recoverDesktopConnection(records,manager,s);return DesktopDeviceReplySchema.parse({view:publicView()})}let command;if(call.action==="enroll"){if(s.device)fail("DEVICE_ALREADY_ENROLLED");const active=(await manager.ledger.current()).value.active;if(!active)fail("INSTALL_REQUIRED");let publicKey;try{const key=createPrivateKey2({key:JSON.parse((await read(records.keyPath(),16384)).toString()),format:"jwk"});publicKey=createPublicKey2(key).export({format:"jwk"})}catch(e){if(e.code!=="ENOENT")throw e;publicKey=(await generateDeviceKey(records.keyPath())).publicKey}command={kind:"ENROLL",input:{tenantId:s.scope.tenantId,requestId:randomUUID4(),label:call.label,platform:active.descriptor.platform,runtimeVersion:active.descriptor.version,publicKey}}}else{const d=s.device;if(!d)fail("DEVICE_ENROLLMENT_REQUIRED");if(call.action==="preview"||call.action==="final"){if(!s.grants.some(g=>!g.revokedAt&&Date.parse(g.expiresAt)>Date.now()))fail("LOCAL_AUTHORIZATION_REQUIRED");command={kind:call.action==="final"?"FINAL_RENDER":"PREVIEW",input:{...call.input,tenantId:s.scope.tenantId,placement:{mode:call.mode,deviceId:d.deviceId},idempotencyKey:"desktop:"+randomUUID4()}}}else{const grant=s.grants.find(g=>g.projectId===call.projectId);if(call.action==="grant"){const ttl=Date.parse(call.expiresAt)-Date.now();if(ttl<=0||ttl>24*36e5||s.grants.length>=20&&!grant)fail("INVALID_INPUT");command={kind:"GRANT",input:{tenantId:s.scope.tenantId,projectId:call.projectId,requestId:randomUUID4(),deviceId:d.deviceId,deviceRevision:d.revision,expectedRevision:grant?.revision??0,expiresAt:call.expiresAt,...call.executionPolicy?{executionPolicy:call.executionPolicy}:{},capability:call.capability??"ROUGH_CUT_PREVIEW_V1"}}}else{if(!grant||grant.revokedAt)fail("LOCAL_AUTHORIZATION_REQUIRED");command={kind:"REVOKE_GRANT",input:{tenantId:s.scope.tenantId,projectId:call.projectId,requestId:randomUUID4(),grantId:grant.grantId,expectedRevision:grant.revision}}}}}const parsed=LocalManagementCommandSchema.parse(command);s=await records.save(s,{...parsed.kind==="ENROLL"?{enrollment:parsed.input}:{},pending:{command:parsed,fingerprint:fingerprint2(parsed),phase:"PREPARED"}});return DesktopDeviceReplySchema.parse({view:publicView(),command:parsed})}async function desktopDevicePending(home,scope){return(await(await DesktopDeviceRecords.open(home,scope)).current()).pending?.command??null}import{z as z9}from"zod";import{join as join7}from"node:path";import{randomUUID as randomUUID5}from"node:crypto";var digest4=z9.string().regex(/^[a-f0-9]{64}$/);var intentSchema=z9.strictObject({id:z9.uuid(),channel:z9.strictObject({protocol:z9.literal("NVS_DESKTOP_RUNTIME_CHANNEL_V1"),catalogueUrl:z9.string().url(),publicKey:z9.string()}),release:LocalReleaseSchema,installationRevision:z9.int().nonnegative(),expiresAt:z9.iso.datetime()});async function runDesktopBootstrap(home,raw,bundled){const{call}=DesktopBootstrapRequestSchema.parse(raw),manager=await LocalInstallationManager.open(home),root=await directory(join7(home,"bootstrap-plans"));let intent2,fingerprint3;if(call.action==="prepare"){const info=await desktopChannelInfo(manager,bundled);if(!info.channelFingerprint)fail("DESKTOP_CHANNEL_REQUIRED");const configuration=info.configured?await manager.configuration():null;const channel=desktopRuntimeChannel(configuration?{protocol:"NVS_DESKTOP_RUNTIME_CHANNEL_V1",catalogueUrl:configuration.catalogueUrl,publicKey:(await read(configuration.publicKeyFile,16384)).toString()}:bundled);const publicKeyFile=join7(root,channel.fingerprint+".pem");try{await write(publicKeyFile,channel.value.publicKey,true)}catch(e){if(e.code!=="EEXIST"||(await read(publicKeyFile,16384)).toString()!==channel.value.publicKey)throw e}const trusted=await catalogue({catalogueUrl:channel.value.catalogueUrl,publicKeyFile});const candidates=trusted.signed.catalogue.releases.filter(r=>r.descriptor.workProtocol==="NVS_LOCAL_WORK_V2"&&r.descriptor.platform.os===process.platform&&r.descriptor.platform.architecture===process.arch&&!!r.tools);const release=candidates.reduce((a,b)=>!a||newerVersion(b.descriptor.version,a.descriptor.version)?b:a,null);if(!release)fail("LOCAL_PROFILE_UNAVAILABLE");intent2=intentSchema.parse({id:randomUUID5(),channel:channel.value,release,installationRevision:(await manager.ledger.current()).value.revision,expiresAt:new Date(Math.min(Date.now()+18e5,Date.parse(trusted.signed.catalogue.expiresAt))).toISOString()});fingerprint3=sha256(canonicalLocalJson(intent2));await write(join7(root,intent2.id+".json"),canonicalLocalJson({intent:intent2,fingerprint:fingerprint3}),true)}else{const saved=z9.strictObject({intent:intentSchema,fingerprint:digest4}).parse(JSON.parse((await read(join7(root,call.id+".json"),131072)).toString()));intent2=saved.intent;fingerprint3=saved.fingerprint;if(fingerprint3!==call.fingerprint||fingerprint3!==sha256(canonicalLocalJson(intent2))||intent2.id!==call.id)fail("PLAN_CHANGED");const receiptFile=join7(root,intent2.id+".installation.json");const receipt=z9.strictObject({id:z9.uuid(),fingerprint:digest4}).nullable().parse(await optional(receiptFile));if(receipt){const state=(await manager.ledger.current()).value;if(state.transition){if(state.transition.planId!==receipt.id)fail("RECOVERY_REQUIRED");await manager.reconcile(receipt.id,receipt.fingerprint)}}else{if(Date.parse(intent2.expiresAt)<=Date.now()||(await manager.ledger.current()).value.revision!==intent2.installationRevision)fail("PLAN_CHANGED");const trust=desktopRuntimeChannel(intent2.channel);await configureDesktopChannel(manager,trust.fingerprint,intent2.channel);const plan=await manager.prepare(intent2.release.descriptor.version,{mode:"MANAGED"});if(canonicalLocalJson(plan.release)!==canonicalLocalJson(intent2.release))fail("PLAN_CHANGED");await write(receiptFile,canonicalLocalJson({id:plan.planId,fingerprint:plan.fingerprint}),true);await manager.apply(plan.planId,plan.fingerprint)}const installed=(await manager.ledger.current()).value;if(installed.transition||canonicalLocalJson(installed.active?.descriptor)!==canonicalLocalJson(intent2.release.descriptor))fail("RECOVERY_REQUIRED");const configuration=await manager.configuration(),report=await(await ownerClient(configuration.stateDirectory)).doctor();if(!report.executionProfiles?.includes("STUDIO_MEDIA_V2"))fail("LOCAL_PROFILE_UNAVAILABLE");if((await desktopRuntimeStatus(manager)).state!=="RUNNING")fail("RECOVERY_REQUIRED")}return DesktopBootstrapReplySchema.parse({id:intent2.id,fingerprint:fingerprint3,version:intent2.release.descriptor.version,host:new URL(intent2.channel.catalogueUrl).host,bytes:intent2.release.package.byteSize+Object.values(intent2.release.tools??{}).reduce((sum,a)=>sum+a.byteSize,0),expiresAt:intent2.expiresAt,installed:call.action==="apply"})}async function runDesktopOwnerRequest(home,raw,bundledChannel){const request=DesktopOwnerRequestSchema.parse(raw),manager=await LocalInstallationManager.open(home);let result;switch(request.operation){case"bootstrap":result=await runDesktopBootstrap(home,request,bundledChannel);break;case"agent":result=await runDesktopAgentRequest(home,request);break;case"offline":result=await runDesktopOfflineRequest(home,request);break;case"storage":result=await runDesktopStorageRequest(home,request);break;case"workspace":result=await runDesktopWorkspaceRequest(home,request);break;case"device":result=await runDesktopDeviceRequest(home,request);break;case"status":case"start":case"stop":if(request.operation==="start")await manager.start();if(request.operation==="stop"){await disableDesktopAutomation(home);await manager.stop()}result=await desktopRuntimeStatus(manager);break;case"configuration":result=await desktopChannelInfo(manager,bundledChannel);break;case"configure":await configureDesktopChannel(manager,request.channelFingerprint,bundledChannel);result=await desktopRuntimeStatus(manager);break;case"check":{const checked=await manager.check();result={protocol:"NVS_DESKTOP_RUNTIME_UPDATES_V1",activeVersion:checked.installation.activeVersion,versions:checked.available.map(v=>({version:v.version,rejected:checked.rejectedVersions.includes(v.version)})),notifications:checked.notifications};break}case"prepare":case"tools-prepare":{const choice=request.operation==="tools-prepare"?request.choice.mode==="MANAGED"?request.choice:await captureInstalledTools(request.choice):void 0;const plan=await manager.prepare(request.version,choice);result={protocol:"NVS_DESKTOP_OWNER_PLAN_V1",plan:{kind:"APPLY",...choice?{toolMode:choice.mode}:{},planId:plan.planId,fingerprint:plan.fingerprint,version:plan.release.descriptor.version,previousVersion:(await manager.status()).activeVersion,expiresAt:plan.expiresAt,phase:"PREPARED"}};break}case"recovery":{const current=(await manager.ledger.current()).value,transition=current.transition;let plan=null;if(transition){const original=await manager.plan(transition.planId);if(original.fingerprint!==transition.fingerprint)fail("PLAN_CHANGED");plan={kind:"RECOVER",planId:original.planId,fingerprint:original.fingerprint,version:original.release.descriptor.version,previousVersion:transition.previous?.descriptor.version??null,expiresAt:original.expiresAt,phase:transition.phase}}result={protocol:"NVS_DESKTOP_OWNER_PLAN_V1",plan};break}case"apply":case"recover":if(request.operation==="apply")await manager.apply(request.planId,request.fingerprint);else await manager.reconcile(request.planId,request.fingerprint);result=await desktopRuntimeStatus(manager);break;case"reject":await manager.reject(request.version);result=await desktopRuntimeStatus(manager);break}return desktopOwnerResponses[request.operation].parse(result)}import{lstat as lstat3,readFile,chmod as chmod2}from"node:fs/promises";import{join as join8,isAbsolute,dirname}from"node:path";async function verifiedSource(source,expected,limit){if(!isAbsolute(source)||!/^[a-f0-9]{64}$/.test(expected))fail("DESKTOP_DISTRIBUTION_INVALID");const stat=await lstat3(source);if(!stat.isFile()||stat.isSymbolicLink()||stat.size>limit)fail("DESKTOP_DISTRIBUTION_INVALID");const bytes=await readFile(source);if(bytes.length>limit||sha256(bytes)!==expected)fail("DESKTOP_DISTRIBUTION_INVALID");return bytes}async function retain(target,bytes,expected,limit,mode){try{if(sha256(await read(target,limit))!==expected)fail("DESKTOP_DISTRIBUTION_INVALID")}catch(error){if(error.code!=="ENOENT")throw error;try{await write(target,bytes,true)}catch(error2){if(error2.code!=="EEXIST")throw error2}if(sha256(await read(target,limit))!==expected)fail("DESKTOP_DISTRIBUTION_INVALID")}await chmod2(target,mode)}async function materializeDesktopNode(home,source,expected,licenseDigest){const bytes=await verifiedSource(source,expected,160*1024*1024);const license=licenseDigest?await verifiedSource(join8(dirname(source),"LICENSE.txt"),licenseDigest,2*1024*1024):null;const base=await directory(join8(await directory(home),"nodes",expected)),target=join8(base,process.platform==="win32"?"node.exe":"node");if(license)await retain(join8(base,"LICENSE.txt"),license,licenseDigest,2*1024*1024,256);await retain(target,bytes,expected,160*1024*1024,320);return target}async function runLocalManagement(home,operation){if(!["status","start","stop"].includes(operation))throw Error("INVALID_INPUT");const manager=await LocalInstallationManager.open(home);if(operation==="start")await manager.start();if(operation==="stop")await manager.stop();return desktopRuntimeStatus(manager)}export{DesktopDeviceReplySchema,DesktopDeviceScopeSchema,DesktopOwnerRequestSchema,desktopDeviceConnector,desktopDevicePending,desktopOwnerResponses,desktopRuntimeChannel,materializeDesktopNode,runDesktopOwnerRequest,runLocalManagement};
|
|
1
|
+
import{LocalInstallationManager,captureInstalledTools,connectDevice,generateDeviceKey,newerVersion,ownerClient,socketAbsent,toolPreference,waitStopped}from"./_chunks/chunk-HKD6F6M6.js";import{DesktopDeviceRecords,DesktopDeviceReplySchema,DesktopDeviceRequestSchema,DesktopDeviceScopeSchema,desktopDeviceConnector}from"./_chunks/chunk-N6S6HCWE.js";import{LocalAgentDiscoverySchema,LocalAgentGrantSchema,LocalAgentProbeSchema,LocalAgentReviewViewSchema,LocalAgentSnapshotSchema,LocalDeviceChallengeSchema,LocalDeviceGrantSchema,LocalDeviceSessionSchema,LocalDeviceViewSchema,LocalDiagnosticsSchema,LocalFinalRenderAdmissionSchema,LocalManagementCommandSchema,LocalOfflineCallSchema,LocalOfflinePageSchema,LocalPreviewAdmissionSchema,LocalReleaseSchema,LocalResourcePolicySchema,LocalRuntimeDescriptorSchema,LocalToolSelectionSchema,LocalWorkspaceInspectionSchema,canonicalLocalJson,catalogue,endpoint}from"./_chunks/chunk-RVGDXRPK.js";import{LocalClientError,atomicMove,directory,entries,fail,optional,read,sha256,write}from"./_chunks/chunk-KB2GVAN7.js";import"./_chunks/chunk-PBEHCYR7.js";import"./_chunks/chunk-VPYAXWXY.js";import{NativeStudioSdkError}from"./_chunks/chunk-6NVIN2NI.js";import{z as z8}from"zod";import{z}from"zod";import{join,sep}from"node:path";var StoragePlanSchema=z.strictObject({id:z.uuid(),mode:z.enum(["BACKUP","MIGRATE"]),source:z.string().min(1),destination:z.string().min(1),installationRevision:z.int().nonnegative(),installationFingerprint:z.string().regex(/^[a-f0-9]{64}$/),runtimeRevision:z.int().positive(),revision:z.int().nonnegative().default(0),phase:z.enum(["PREPARED","DRAINING","COPYING","COPIED","VERIFYING","COMPLETE","CANCELLED"]),fingerprint:z.string().regex(/^[a-f0-9]{64}$/),expiresAt:z.iso.datetime(),bytes:z.int().nonnegative().default(0)});var recordSchema=z.strictObject({plan:StoragePlanSchema,previous:z.string().regex(/^[a-f0-9]{64}$/).nullable(),digest:z.string().regex(/^[a-f0-9]{64}$/)});var phases=["PREPARED","DRAINING","COPYING","COPIED","VERIFYING","COMPLETE"];var terminal=phase=>["COMPLETE","CANCELLED"].includes(phase);var advances=(before,after)=>before===after||!terminal(before)&&(after==="CANCELLED"||phases.indexOf(after)===phases.indexOf(before)+1);async function storageInstallationIdentity(slot,source,destination){const tools=slot.toolsConfigPath?LocalToolSelectionSchema.parse(JSON.parse((await read(slot.toolsConfigPath,32768)).toString())):null;if(tools?.mode==="MANAGED"){for(const name of["ffmpeg","ffprobe"])for(const root of[source,destination])if(tools[name].path.startsWith(root+sep)){tools[name].path="{state}"+tools[name].path.slice(root.length);break}}return sha256(canonicalLocalJson({descriptor:slot.descriptor,files:slot.files,tools}))}function intent(p){return{id:p.id,mode:p.mode,source:p.source,destination:p.destination,installationRevision:p.installationRevision,installationFingerprint:p.installationFingerprint,runtimeRevision:p.runtimeRevision,expiresAt:p.expiresAt}}async function history(root,id2){const path=await directory(join(root,z.uuid().parse(id2)));let plan=null;let digest5=null;const names=(await entries(path)).filter(n=>/^\d{8}\.json$/.test(n)).sort();for(const[index,name]of names.entries()){const record=recordSchema.parse(JSON.parse((await read(join(path,name))).toString())),next=record.plan;if(next.id!==id2||next.revision!==index+1||next.fingerprint!==sha256(canonicalLocalJson(intent(next)))||record.previous!==digest5||record.digest!==sha256(canonicalLocalJson({plan:next,previous:digest5}))||!plan&&next.phase!=="PREPARED"||plan&&(plan.fingerprint!==next.fingerprint||!advances(plan.phase,next.phase)))fail("STORAGE_HISTORY_INVALID");plan=next;digest5=record.digest}return{plan,digest:digest5}}async function readStoragePlan(root,id2){return(await history(root,id2)).plan}async function saveStoragePlan(root,expected,phase,extra={}){const current=await history(root,expected.id),actual=current.plan;if((actual?.revision??0)!==expected.revision)fail("REVISION_CONFLICT");if(actual&&canonicalLocalJson(actual)!==canonicalLocalJson(expected))fail("PLAN_CHANGED");const next=StoragePlanSchema.parse({...expected,...extra,phase,revision:expected.revision+1});if(next.fingerprint!==sha256(canonicalLocalJson(intent(next))))fail("PLAN_CHANGED");if(!actual&&phase!=="PREPARED"||actual&&!advances(actual.phase,phase))fail("PLAN_CHANGED");const file=join(root,next.id,String(next.revision).padStart(8,"0")+".json");try{const body={plan:next,previous:current.digest};await write(file,canonicalLocalJson({...body,digest:sha256(canonicalLocalJson(body))}),true)}catch(e){if(e.code==="EEXIST")fail("REVISION_CONFLICT");throw e}return next}import{z as z3}from"zod";import{lstat as lstat2,realpath}from"node:fs/promises";import{randomUUID}from"node:crypto";import{join as join4,resolve,sep as sep3}from"node:path";import{constants,createReadStream}from"node:fs";import{open,readdir,lstat,statfs,chmod,unlink}from"node:fs/promises";import{join as join2,relative,sep as sep2}from"node:path";import{createHash}from"node:crypto";async function digestFile(path){const file=await open(path,constants.O_RDONLY|constants.O_NOFOLLOW);try{const before=await file.stat(),hash=createHash("sha256");if(!before.isFile()||before.nlink!==1||before.size>512*1024**2||process.platform!=="win32"&&(before.uid!==process.getuid?.()||before.mode&63))fail("STORAGE_FILE_INVALID");let bytes=0;for await(const chunk of createReadStream(path,{fd:file.fd,autoClose:false})){bytes+=chunk.length;if(bytes>before.size)fail("STORAGE_FILE_CHANGED");hash.update(chunk)}const after=await file.stat();if(bytes!==before.size||before.mtimeMs!==after.mtimeMs||before.ino!==after.ino)fail("STORAGE_FILE_CHANGED");return{bytes,sha256:hash.digest("hex"),mode:before.mode&448}}finally{await file.close()}}async function storageFiles(root){const files=[];async function walk(path,depth){if(depth>8)fail("STORAGE_FILE_LIMIT");for(const item of await readdir(path,{withFileTypes:true})){const source=join2(path,item.name),name=relative(root,source);if(path===root&&!["journal.sqlite","journal.sqlite-wal","cache","staging","tools","agent-images","agent-evidence","agent-reviews"].includes(item.name))continue;const info=await lstat(source);if(info.isSymbolicLink()||!info.isFile()&&!info.isDirectory())fail("STORAGE_FILE_INVALID");if(info.isDirectory())await walk(source,depth+1);else{if(files.length>=5e4)fail("STORAGE_FILE_LIMIT");const value=await digestFile(source);files.push({name,bytes:value.bytes,sha256:value.sha256})}}}await walk(root,0);return files.sort((a,b)=>a.name.localeCompare(b.name))}async function copyStorage(source,destination){if(destination===source||destination.startsWith(source+sep2)||source.startsWith(destination+sep2))fail("STORAGE_LOCATION_INVALID");await directory(destination);const files=await storageFiles(source),total=files.reduce((n,f)=>n+f.bytes,0);const fs=await statfs(destination);if(fs.bavail*fs.bsize<total+256*1024**2)fail("STORAGE_SPACE_REQUIRED");for(const item of files){const original=join2(source,item.name),target=join2(destination,item.name);const parent=target.slice(0,target.lastIndexOf(sep2));await directory(parent);try{const existing=await digestFile(target);if(existing.sha256!==item.sha256||existing.bytes!==item.bytes)fail("STORAGE_COPY_CONFLICT");continue}catch(error){if(error.code!=="ENOENT")throw error}const temporary=target+".copy-part";try{await digestFile(temporary);await unlink(temporary)}catch(error){if(error.code!=="ENOENT")throw error}const input=await open(original,constants.O_RDONLY|constants.O_NOFOLLOW),output=await open(temporary,"wx",384);try{for await(const bytes of createReadStream(original,{fd:input.fd,autoClose:false}))await output.writeFile(bytes);await output.sync()}finally{await input.close();await output.close()}const copied=await digestFile(temporary),before=await digestFile(original);if(copied.sha256!==item.sha256||before.sha256!==item.sha256||copied.bytes!==item.bytes)fail("STORAGE_COPY_INVALID");await chmod(temporary,before.mode);await atomicMove(temporary,target,true)}return{files,total}}import{join as join3}from"node:path";import{z as z2}from"zod";var digest=z2.string().regex(/^[a-f0-9]{64}$/);var DesktopAutomationSchema=z2.strictObject({enabled:z2.boolean(),scope:DesktopDeviceScopeSchema,deviceId:z2.uuid(),deviceRevision:z2.int().positive(),installationFingerprint:digest,projects:z2.array(z2.strictObject({projectId:z2.uuid(),grantId:z2.uuid(),revision:z2.int().positive(),expiresAt:z2.iso.datetime()})).min(1).max(20)});async function desktopInstallationIdentity(manager){const active=(await manager.ledger.current()).value.active;if(!active)return null;const tools=active.toolsConfigPath?JSON.parse((await read(active.toolsConfigPath,32768)).toString()):null;return{version:active.descriptor.version,workProtocol:active.descriptor.workProtocol,fingerprint:sha256(canonicalLocalJson({descriptor:active.descriptor,files:active.files,tools}))}}async function desktopAutomation(home){const value=await optional(join3(home,"desktop-execution-policy.json"));return value?DesktopAutomationSchema.parse(value):null}function canResumeDesktop(policy,state,installation){if(!policy?.enabled||!installation||!state.device||policy.installationFingerprint!==installation.fingerprint||canonicalLocalJson(policy.scope)!==canonicalLocalJson(state.scope)||policy.deviceId!==state.device.deviceId||policy.deviceRevision!==state.device.revision)return false;const grants=state.grants.filter(g=>!g.revokedAt&&Date.parse(g.expiresAt)>Date.now());return grants.length>0&&grants.every(g=>policy.projects.some(p=>p.projectId===g.projectId&&p.grantId===g.grantId&&p.revision===g.revision&&p.expiresAt===g.expiresAt))}async function rememberDesktopAutomation(home,state,installation,expectedFingerprint,projectIds){if(!installation||installation.fingerprint!==expectedFingerprint||!state.device)fail("DEVICE_PLAN_CHANGED");const grants=state.grants.filter(g=>!g.revokedAt&&Date.parse(g.expiresAt)>Date.now());if(!grants.length||grants.some(g=>!projectIds.includes(g.projectId)))fail("DEVICE_PLAN_CHANGED");const value=DesktopAutomationSchema.parse({enabled:true,scope:state.scope,deviceId:state.device.deviceId,deviceRevision:state.device.revision,installationFingerprint:expectedFingerprint,projects:grants.map(g=>({projectId:g.projectId,grantId:g.grantId,revision:g.revision,expiresAt:g.expiresAt}))});await write(join3(home,"desktop-execution-policy.json"),canonicalLocalJson(value));return value}async function disableDesktopAutomation(home){const policy=await desktopAutomation(home);if(policy)await write(join3(home,"desktop-execution-policy.json"),canonicalLocalJson({...policy,enabled:false}))}var id=z3.uuid();var digest2=z3.string().regex(/^[a-f0-9]{64}$/);var planSchema=StoragePlanSchema;var DesktopStorageRequestSchema=z3.strictObject({operation:z3.literal("storage"),call:z3.discriminatedUnion("action",[z3.strictObject({action:z3.literal("status")}),z3.strictObject({action:z3.literal("prepare"),mode:z3.enum(["BACKUP","MIGRATE"]),destination:z3.string().min(1).max(4096)}),z3.strictObject({action:z3.enum(["execute","recover","abandon"]),id,fingerprint:digest2})])});var viewSchema=planSchema.omit({source:true,destination:true,runtimeRevision:true,installationRevision:true});var DesktopStorageReplySchema=viewSchema.nullable();function present(plan){if(!plan)return null;const{source,destination,runtimeRevision,installationRevision,...view2}=plan;void source;void destination;void runtimeRevision;void installationRevision;return DesktopStorageReplySchema.parse(view2)}async function runDesktopStorageRequest(home,raw){const{call}=DesktopStorageRequestSchema.parse(raw),manager=await LocalInstallationManager.open(home);const root=await directory(join4(home,"storage-plans"));const pointer=await optional(join4(root,"current.json"));const prior=pointer?await readStoragePlan(root,id.parse(pointer)):null;if(call.action==="status")return present(prior);let config=await manager.configuration(),installation=(await manager.ledger.current()).value;let plan;const save=async(phase,extra={})=>{plan=await saveStoragePlan(root,plan,phase,extra)};if(call.action==="prepare"){if(!installation.active||installation.transition)fail("RECOVERY_REQUIRED");if(prior&&!["COMPLETE","CANCELLED"].includes(prior.phase))fail("RECOVERY_REQUIRED");const selected=resolve(call.destination),info=await lstat2(selected);if(!info.isDirectory()||info.isSymbolicLink()||process.platform!=="win32"&&info.uid!==process.getuid?.())fail("STORAGE_LOCATION_INVALID");const destination=await realpath(selected);if(destination===config.stateDirectory||destination.startsWith(config.stateDirectory+sep3))fail("STORAGE_LOCATION_INVALID");const inventory=await(await ownerClient(config.stateDirectory)).inventory();const body={id:randomUUID(),mode:call.mode,source:config.stateDirectory,destination:join4(destination,"NVS-"+randomUUID().replaceAll("-","").slice(0,16)),installationRevision:installation.revision,runtimeRevision:inventory.runtimeRevision,expiresAt:new Date(Date.now()+18e5).toISOString()};if(call.mode==="MIGRATE"&&process.platform!=="win32"&&Buffer.byteLength(join4(body.destination,"runtime.sock"))>100)fail("SOCKET_PATH_TOO_LONG");const frozen={...body,installationFingerprint:await storageInstallationIdentity(installation.active,body.source,body.destination)};plan=planSchema.parse({...frozen,fingerprint:sha256(canonicalLocalJson(frozen)),phase:"PREPARED"});await save("PREPARED");await write(join4(root,"current.json"),canonicalLocalJson(plan.id));return present(plan)}plan=await readStoragePlan(root,call.id);if(!plan||plan.fingerprint!==call.fingerprint)fail("PLAN_CHANGED");if(["COMPLETE","CANCELLED"].includes(plan.phase))return present(plan);if(call.action==="abandon"){await save("CANCELLED");return present(plan)}if(!installation.active||installation.transition)fail("RECOVERY_REQUIRED");if(await storageInstallationIdentity(installation.active,plan.source,plan.destination)!==plan.installationFingerprint)fail("PLAN_CHANGED");if(config.stateDirectory!==plan.source&&!(plan.mode==="MIGRATE"&&config.stateDirectory===plan.destination))fail("PLAN_CHANGED");if(plan.phase==="PREPARED"){if(Date.parse(plan.expiresAt)<=Date.now()||installation.revision!==plan.installationRevision)fail("PLAN_CHANGED");const client=await ownerClient(plan.source),inventory=await client.inventory();if(inventory.runtimeRevision!==plan.runtimeRevision)fail("REVISION_CONFLICT");await save("DRAINING");await manager.stop()}if(plan.phase==="DRAINING"){await waitStopped(plan.source);if(!await socketAbsent(plan.source))fail("RECOVERY_REQUIRED");await save("COPYING")}if(plan.phase==="COPYING"){if(!await socketAbsent(plan.source))fail("RECOVERY_REQUIRED");const copied=await copyStorage(plan.source,plan.destination);await write(join4(plan.destination,"backup-manifest.json"),canonicalLocalJson({protocol:"NVS_STORAGE_COPY_V1",planId:plan.id,...copied}));await save("COPIED",{bytes:copied.total})}if(plan.phase==="COPIED"){if(plan.mode==="MIGRATE"){if(installation.active.toolsConfigPath){const tools=LocalToolSelectionSchema.parse(JSON.parse((await read(installation.active.toolsConfigPath,32768)).toString()));if(tools.mode==="MANAGED"){for(const name of["ffmpeg","ffprobe"]){if(tools[name].path.startsWith(plan.source+sep3))tools[name].path=plan.destination+tools[name].path.slice(plan.source.length);else if(!tools[name].path.startsWith(plan.destination+sep3)||installation.active.toolsConfigPath!==join4(root,plan.id+"-tools.json"))fail("PLAN_CHANGED")}const toolsConfigPath=join4(root,plan.id+"-tools.json");await write(toolsConfigPath,canonicalLocalJson(tools));if(installation.active.toolsConfigPath!==toolsConfigPath)await manager.ledger.commit(installation,{active:{...installation.active,toolsConfigPath},transition:null})}}await manager.configure({...config,stateDirectory:plan.destination});await disableDesktopAutomation(home)}await save("VERIFYING")}if(plan.phase==="VERIFYING"){await manager.start();config=await manager.configuration();const inventory=await(await ownerClient(config.stateDirectory)).inventory();installation=(await manager.ledger.current()).value;if(canonicalLocalJson(inventory.descriptor)!==canonicalLocalJson(installation.active.descriptor))fail("STORAGE_COPY_INVALID");await save("COMPLETE")}return present(plan)}import{z as z4}from"zod";var DesktopOfflineRequestSchema=z4.strictObject({operation:z4.literal("offline"),call:LocalOfflineCallSchema});var DesktopOfflineReplySchema=LocalOfflinePageSchema;async function runDesktopOfflineRequest(home,raw){const{call}=DesktopOfflineRequestSchema.parse(raw),manager=await LocalInstallationManager.open(home),c=await manager.configuration();if(!(await manager.status()).running){const policy=await desktopAutomation(home),installation=await desktopInstallationIdentity(manager);if(!policy?.enabled||policy.installationFingerprint!==installation?.fingerprint||!policy.projects.some(p=>Date.parse(p.expiresAt)>Date.now())||!await socketAbsent(c.stateDirectory))fail("RUNTIME_STATUS_REQUIRED");await manager.start()}const client=await ownerClient(c.stateDirectory);return LocalOfflinePageSchema.parse(await client.call({operation:"offline.workspace",input:call}))}import{z as z5}from"zod";import{join as join5}from"node:path";import{unlink as unlink2}from"node:fs/promises";var sha=z5.string().regex(/^[a-f0-9]{64}$/);var historyItem=z5.strictObject({id:z5.uuid(),projectId:z5.uuid(),productionId:z5.uuid(),kind:z5.enum(["IMAGE","VIDEO","ROUGH_CUT","PROGRAMMATIC"]),mediaFileId:z5.uuid().optional()});var stateSchema=z5.strictObject({grantFingerprint:sha.nullable(),pendingGrant:sha.nullable(),history:z5.array(historyItem).max(200)});var DesktopAgentRequestSchema=z5.strictObject({operation:z5.literal("agent"),scope:DesktopDeviceScopeSchema,call:z5.discriminatedUnion("action",[z5.strictObject({action:z5.literal("discover"),binary:z5.string().min(1).max(4096).optional()}),z5.strictObject({action:z5.literal("probe")}),z5.strictObject({action:z5.literal("grant"),grant:LocalAgentGrantSchema,approval:sha}),z5.strictObject({action:z5.literal("revoke")}),z5.strictObject({action:z5.literal("prepare"),snapshot:LocalAgentSnapshotSchema}),z5.strictObject({action:z5.literal("stage"),id:z5.uuid(),mediaFileId:z5.uuid().optional()}),z5.strictObject({action:z5.literal("start"),id:z5.uuid(),expectedRevision:z5.int().positive(),approval:sha}),z5.strictObject({action:z5.literal("inspect"),id:z5.uuid()})])});var DesktopAgentReplySchema=z5.strictObject({probe:LocalAgentProbeSchema.optional(),discovery:LocalAgentDiscoverySchema.optional(),review:LocalAgentReviewViewSchema.optional(),history:z5.array(historyItem.omit({mediaFileId:true}).extend({pendingMedia:z5.boolean()})).max(200),pendingGrant:z5.boolean()});async function runDesktopAgentRequest(home,raw){const{scope,call}=DesktopAgentRequestSchema.parse(raw),root=await directory(join5(home,"agent-owner",sha256(canonicalLocalJson(scope)))),path=join5(root,"current.json");let state=stateSchema.parse(await optional(path)??{grantFingerprint:null,pendingGrant:null,history:[]});const manager=await LocalInstallationManager.open(home),client=await ownerClient((await manager.configuration()).stateDirectory);const save=async value=>{state=stateSchema.parse({...state,...value});await write(path,canonicalLocalJson(state))};const result=fields=>DesktopAgentReplySchema.parse({...fields,history:state.history.map(({mediaFileId,...r})=>{return{...r,pendingMedia:!!mediaFileId}}),pendingGrant:!!state.pendingGrant});if(call.action==="discover"){const discovery=await client.discoverAgent(call.binary);const fp=discovery.configured?sha256(canonicalLocalJson(discovery.configured)):null;if(state.pendingGrant&&state.pendingGrant===fp)await save({grantFingerprint:fp,pendingGrant:null});return result({discovery:{...discovery,configured:fp===state.grantFingerprint?discovery.configured:null}})}if(call.action==="probe"){const probe=await client.probeAgent();if(state.pendingGrant&&probe.grantFingerprint===state.pendingGrant)await save({grantFingerprint:state.pendingGrant,pendingGrant:null});return result({probe:probe.grantFingerprint===state.grantFingerprint?probe:{...probe,available:false,configured:false,reason:"GRANT_REQUIRED",grantFingerprint:null}})}if(call.action==="grant"){if(state.pendingGrant)fail("AGENT_OUTCOME_UNKNOWN");if(call.grant.projects.some(p=>p.tenantId!==scope.tenantId)||sha256(canonicalLocalJson(call.grant))!==call.approval)fail("AGENT_APPROVAL_REQUIRED");await save({pendingGrant:call.approval});let probe;try{probe=await client.grantAgent(call.grant,call.approval)}catch(e){if(e instanceof NativeStudioSdkError&&["NO_WRITE","REJECTED"].includes(e.outcome))await save({pendingGrant:null});throw e}await save({pendingGrant:null,grantFingerprint:call.approval});return result({probe})}if(call.action==="revoke"){const probe=await client.probeAgent();if(!state.grantFingerprint||probe.grantFingerprint!==state.grantFingerprint)fail("AGENT_APPROVAL_REQUIRED");const revoked=await client.revokeAgent(state.grantFingerprint);await save({grantFingerprint:null,pendingGrant:null});return result({probe:revoked})}if(call.action==="prepare"){if(state.history.length>=200)fail("QUERY_LIMIT");if(state.pendingGrant||!state.grantFingerprint||call.snapshot.basis.scope.tenantId!==scope.tenantId)fail("AGENT_APPROVAL_REQUIRED");const review=await client.prepareAgentReview(call.snapshot);if(review.plan.grantFingerprint!==state.grantFingerprint)fail("AGENT_APPROVAL_REQUIRED");const s2=review.plan.snapshot.basis.scope;await save({history:[{id:review.plan.id,projectId:s2.projectId,productionId:s2.productionId,kind:review.plan.snapshot.basis.target.kind},...state.history]});return result({review})}const entry=state.history.find(h=>h.id===call.id);if(!entry)fail("AGENT_APPROVAL_REQUIRED");const original=await client.inspectAgentReview(call.id),s=original.plan.snapshot.basis.scope;if(s.tenantId!==scope.tenantId||s.projectId!==entry.projectId||s.productionId!==entry.productionId)fail("AGENT_APPROVAL_REQUIRED");const staged=!!(original.imageReceipt||original.evidenceReceipt);if(staged&&entry.mediaFileId){const file=join5(home,"agent-import",entry.mediaFileId+".bin");try{const bytes=await read(file,134217728);if(sha256(bytes)!==original.plan.snapshot.media.checksumSha256)fail("AGENT_IMAGE_INVALID");await unlink2(file)}catch(e){if(e.code!=="ENOENT")throw e}await save({history:state.history.map(h=>{if(h.id!==call.id)return h;const{mediaFileId,...item}=h;void mediaFileId;return item})})}if(call.action==="inspect"||call.action==="stage"&&staged)return result({review:original});if(call.action==="stage"){const mediaFileId=call.mediaFileId??entry.mediaFileId;if(!mediaFileId)fail("AGENT_IMAGE_REQUIRED");await save({history:state.history.map(h=>h.id===call.id?{...h,mediaFileId}:h)});const file=join5(home,"agent-import",mediaFileId+".bin"),bytes=await read(file,134217728);const review=await client.stageAgentImage(call.id,bytes);await unlink2(file);await save({history:state.history.map(h=>{if(h.id!==call.id)return h;const{mediaFileId:_id,...rest}=h;void _id;return rest})});return result({review})}if(state.pendingGrant||original.plan.grantFingerprint!==state.grantFingerprint)fail("AGENT_APPROVAL_REQUIRED");return result({review:await client.startAgentReview(call.id,call.expectedRevision,call.approval)})}import{z as z6}from"zod";var digest3=z6.string().regex(/^[a-f0-9]{64}$/);var DesktopBootstrapRequestSchema=z6.strictObject({operation:z6.literal("bootstrap"),call:z6.discriminatedUnion("action",[z6.strictObject({action:z6.literal("prepare")}),z6.strictObject({action:z6.literal("apply"),id:z6.uuid(),fingerprint:digest3})])});var DesktopBootstrapReplySchema=z6.strictObject({id:z6.uuid(),fingerprint:digest3,version:z6.string().min(1).max(80),host:z6.string().min(1).max(512),bytes:z6.int().positive(),expiresAt:z6.iso.datetime(),installed:z6.boolean()});import{z as z7}from"zod";var DesktopWorkspaceRequestSchema=z7.strictObject({operation:z7.literal("workspace"),call:z7.discriminatedUnion("action",[z7.strictObject({action:z7.enum(["inspect","clean","diagnostics"])}),z7.strictObject({action:z7.literal("configure"),policy:LocalResourcePolicySchema,expectedRevision:z7.int().nonnegative()}),z7.strictObject({action:z7.literal("activity"),idleSeconds:z7.int().min(0).max(86400),observedAt:z7.iso.datetime()})])});var DesktopWorkspaceReplySchema=z7.union([LocalWorkspaceInspectionSchema,LocalDiagnosticsSchema]);async function runDesktopWorkspaceRequest(home,raw){const request=DesktopWorkspaceRequestSchema.parse(raw);const manager=await LocalInstallationManager.open(home);const config=await manager.configuration();const client=await ownerClient(config.stateDirectory);const input=request.call;switch(input.action){case"inspect":return client.workspace.inspect();case"clean":return client.workspace.clean();case"diagnostics":return client.workspace.diagnostics();case"configure":return client.workspace.configure(input.policy,input.expectedRevision);case"activity":return client.workspace.observeActivity(input.idleSeconds,input.observedAt)}}var version=LocalRuntimeDescriptorSchema.shape.version;var fingerprint=z8.string().regex(/^[a-f0-9]{64}$/);var DesktopRuntimeChannelSchema=z8.strictObject({protocol:z8.literal("NVS_DESKTOP_RUNTIME_CHANNEL_V1"),catalogueUrl:z8.string().url().max(4096),publicKey:z8.string().min(32).max(16384)});var DesktopOwnerRequestSchema=z8.discriminatedUnion("operation",[DesktopDeviceRequestSchema,DesktopWorkspaceRequestSchema,DesktopStorageRequestSchema,DesktopOfflineRequestSchema,DesktopAgentRequestSchema,DesktopBootstrapRequestSchema,z8.strictObject({operation:z8.enum(["status","start","stop","check","configuration","recovery"])}),z8.strictObject({operation:z8.enum(["prepare","reject"]),version}),z8.strictObject({operation:z8.literal("tools-prepare"),version,choice:z8.discriminatedUnion("mode",[z8.strictObject({mode:z8.literal("MANAGED")}),z8.strictObject({mode:z8.literal("INSTALLED"),ffmpeg:z8.string().min(1).max(4096),ffprobe:z8.string().min(1).max(4096)})])}),z8.strictObject({operation:z8.literal("configure"),channelFingerprint:fingerprint}),z8.strictObject({operation:z8.enum(["apply","recover"]),planId:z8.uuid(),fingerprint})]);var DesktopRuntimeStatusSchema=z8.strictObject({protocol:z8.literal("NVS_DESKTOP_RUNTIME_STATUS_V1"),state:z8.enum(["RUNNING","STOPPED","UNAVAILABLE","INSTALL_REQUIRED"]),activeVersion:version.nullable(),phase:z8.string().regex(/^[A-Z_]{1,64}$/),toolMode:z8.enum(["MANAGED","INSTALLED"]).nullable().optional()});var DesktopUpdateCheckSchema=z8.strictObject({protocol:z8.literal("NVS_DESKTOP_RUNTIME_UPDATES_V1"),activeVersion:version.nullable(),versions:z8.array(z8.strictObject({version,rejected:z8.boolean()})).max(128),notifications:z8.boolean()});var DesktopOwnerPlanSchema=z8.strictObject({protocol:z8.literal("NVS_DESKTOP_OWNER_PLAN_V1"),plan:z8.strictObject({kind:z8.enum(["APPLY","RECOVER"]),toolMode:z8.enum(["MANAGED","INSTALLED"]).optional(),planId:z8.uuid(),fingerprint,version,previousVersion:version.nullable(),expiresAt:z8.iso.datetime(),phase:z8.string().regex(/^[A-Z_]{1,64}$/)}).nullable()});var DesktopChannelInfoSchema=z8.strictObject({protocol:z8.literal("NVS_DESKTOP_CHANNEL_INFO_V1"),configured:z8.boolean(),source:z8.enum(["EXISTING","BUNDLED","UNAVAILABLE"]),host:z8.string().max(512).nullable(),channelFingerprint:fingerprint.nullable()});var desktopOwnerResponses={device:DesktopDeviceReplySchema,workspace:DesktopWorkspaceReplySchema,storage:DesktopStorageReplySchema,offline:DesktopOfflineReplySchema,agent:DesktopAgentReplySchema,bootstrap:DesktopBootstrapReplySchema,status:DesktopRuntimeStatusSchema,start:DesktopRuntimeStatusSchema,stop:DesktopRuntimeStatusSchema,configure:DesktopRuntimeStatusSchema,apply:DesktopRuntimeStatusSchema,recover:DesktopRuntimeStatusSchema,reject:DesktopRuntimeStatusSchema,check:DesktopUpdateCheckSchema,configuration:DesktopChannelInfoSchema,prepare:DesktopOwnerPlanSchema,"tools-prepare":DesktopOwnerPlanSchema,recovery:DesktopOwnerPlanSchema};async function desktopRuntimeStatus(manager){const status=await manager.status();const stopped=!status.running&&status.activeVersion?await socketAbsent((await manager.configuration()).stateDirectory):false;const active=(await manager.ledger.current()).value.active;const toolMode=active?.toolsConfigPath?(await toolPreference(active.toolsConfigPath,null)).mode:null;return DesktopRuntimeStatusSchema.parse({protocol:"NVS_DESKTOP_RUNTIME_STATUS_V1",state:status.running?"RUNNING":stopped?"STOPPED":status.activeVersion?"UNAVAILABLE":"INSTALL_REQUIRED",activeVersion:status.activeVersion,phase:status.phase,toolMode})}import{createPublicKey}from"node:crypto";import{join as join6}from"node:path";function desktopRuntimeChannel(raw){const channel=DesktopRuntimeChannelSchema.parse(raw);const url=endpoint(channel.catalogueUrl),key=createPublicKey(channel.publicKey);if(key.asymmetricKeyType!=="ed25519"||channel.publicKey.replace(/\r\n/g,"\n").trim()!==key.export({type:"spki",format:"pem"}).toString().trim())fail("RELEASE_SIGNATURE_INVALID");const value={...channel,catalogueUrl:url.href,publicKey:key.export({type:"spki",format:"pem"}).toString()};return{value,host:url.host,fingerprint:sha256(canonicalLocalJson(value))}}async function desktopChannelInfo(manager,bundled){let channel,configured=false;try{const config=await manager.configuration();channel=desktopRuntimeChannel({protocol:"NVS_DESKTOP_RUNTIME_CHANNEL_V1",catalogueUrl:config.catalogueUrl,publicKey:(await read(config.publicKeyFile,16384)).toString()});configured=true}catch(error){if(!(error instanceof LocalClientError&&error.code==="CONFIGURATION_REQUIRED"))throw error;if(bundled!==void 0)channel=desktopRuntimeChannel(bundled)}return DesktopChannelInfoSchema.parse({protocol:"NVS_DESKTOP_CHANNEL_INFO_V1",configured,source:configured?"EXISTING":channel?"BUNDLED":"UNAVAILABLE",host:channel?.host??null,channelFingerprint:channel?.fingerprint??null})}async function configureDesktopChannel(manager,expectedFingerprint,bundled){const info=await desktopChannelInfo(manager,bundled);if(!info.channelFingerprint)fail("DESKTOP_CHANNEL_REQUIRED");if(info.channelFingerprint!==expectedFingerprint)fail("DESKTOP_CHANNEL_CHANGED");if(info.configured)return;const stateDirectory=join6(manager.ledger.root,"runtime-state");if(process.platform!=="win32"&&Buffer.byteLength(join6(stateDirectory,"runtime.sock"))>100)fail("SOCKET_PATH_TOO_LONG");const channel=desktopRuntimeChannel(bundled),publicKeyFile=join6(manager.ledger.root,"desktop-release-"+channel.fingerprint+".pem");try{await write(publicKeyFile,channel.value.publicKey,true)}catch(error){if(error.code!=="EEXIST")throw error;if((await read(publicKeyFile,16384)).toString()!==channel.value.publicKey)fail("DESKTOP_CHANNEL_CHANGED")}try{await manager.configure({stateDirectory,catalogueUrl:channel.value.catalogueUrl,publicKeyFile,notifications:true},{ifAbsent:true})}catch(error){if(error.code==="EEXIST")fail("DESKTOP_CHANNEL_CHANGED");throw error}}import{createPrivateKey as createPrivateKey2,createPublicKey as createPublicKey2,randomUUID as randomUUID4}from"node:crypto";import{randomUUID as randomUUID2}from"node:crypto";async function connectDesktopDevice(records,manager,s,expectedRevision){if(s.revision!==expectedRevision)fail("DEVICE_PLAN_CHANGED");if(s.connection?.phase==="CONNECTING")fail("DEVICE_CONNECTION_RECOVERY_REQUIRED");if(!s.device)fail("DEVICE_ENROLLMENT_REQUIRED");const valid=s.grants.filter(g=>!g.revokedAt&&Date.parse(g.expiresAt)>Date.now());if(!valid.length)fail("LOCAL_AUTHORIZATION_REQUIRED");const projects=valid.map(g=>({tenantId:g.tenantId,projectId:g.projectId}));const c=await manager.configuration();const previous=c.cloudConfigFile?JSON.parse((await read(c.cloudConfigFile,32768)).toString()):null;if(previous&&(previous.endpoint!==s.scope.origin||previous.tenantId!==s.scope.tenantId||previous.deviceId!==s.device.deviceId))fail("DEVICE_CONNECTION_CONFLICT");const running=(await manager.status()).running;if(!running&&!await socketAbsent(c.stateDirectory))fail("DEVICE_CONNECTION_RECOVERY_REQUIRED");const reuse=running&&previous&&canonicalLocalJson(previous.projects)===canonicalLocalJson(projects);const expiresAt=new Date(Math.min(Date.now()+24*36e5,...valid.map(g=>Date.parse(g.expiresAt)))).toISOString();s=await records.save(s,{connection:{phase:"CONNECTING",projects,expiresAt}});if(!reuse){if(running)await manager.stop();await connectDevice(manager,{endpoint:s.scope.origin,tenantId:s.scope.tenantId,deviceId:s.device.deviceId,deviceRevision:s.device.revision,privateKeyFile:records.keyPath(),platform:s.device.platform,projects});await manager.start()}const id2=randomUUID2();await manager.grant({projects,expiresAt},records.connectorPath(id2));return records.save(s,{connectorId:id2,connection:{...s.connection,phase:"CONNECTED"}})}async function recoverDesktopConnection(records,manager,s){if(s.connection?.phase!=="CONNECTING")return s;const c=await manager.configuration(),running=(await manager.status()).running;if(!running){if(!await socketAbsent(c.stateDirectory))fail("DEVICE_CONNECTION_RECOVERY_REQUIRED");return records.save(s,{connection:null,connectorId:null})}if(!c.cloudConfigFile||!s.device)fail("DEVICE_CONNECTION_RECOVERY_REQUIRED");const actual=JSON.parse((await read(c.cloudConfigFile,32768)).toString());if(actual.endpoint!==s.scope.origin||actual.deviceId!==s.device.deviceId||actual.tenantId!==s.scope.tenantId||canonicalLocalJson(actual.projects)!==canonicalLocalJson(s.connection.projects))fail("DEVICE_CONNECTION_RECOVERY_REQUIRED");return records.save(s,{connection:{...s.connection,phase:"READY"},connectorId:null})}import{createPrivateKey,sign,randomUUID as randomUUID3}from"node:crypto";async function proveDesktopDevice(records){const state=await records.current(),d=state.device;if(!d)fail("DEVICE_ENROLLMENT_REQUIRED");async function request(action,input){const response=await fetch(state.scope.origin+"/v1/local-execution/devices/"+action,{method:"POST",redirect:"error",headers:{"content-type":"application/json"},body:JSON.stringify(input),signal:AbortSignal.timeout(15e3)});if(!response.ok){await response.body?.cancel();fail("DEVICE_PROOF_UNAVAILABLE")}const chunks=[];let size=0;for await(const bytes of response.body??[]){size+=bytes.length;if(size>16384)fail("DEVICE_PROOF_INVALID");chunks.push(bytes)}return JSON.parse(Buffer.concat(chunks).toString())}const scope={tenantId:d.tenantId,deviceId:d.deviceId,deviceRevision:d.revision};const started=performance.now();const challenge=LocalDeviceChallengeSchema.parse(await request("challenge",scope));if(challenge.tenantId!==d.tenantId||challenge.deviceId!==d.deviceId||challenge.deviceRevision!==d.revision||Date.parse(challenge.expiresAt)-Date.parse(challenge.issuedAt)<=performance.now()-started)fail("DEVICE_PROOF_INVALID");const key=createPrivateKey({key:JSON.parse((await read(records.keyPath(),16384)).toString()),format:"jwk"});const header=Buffer.from(JSON.stringify({alg:"ES256",typ:"nvs-local-device+jwt"})).toString("base64url");const iat=Math.floor(Date.parse(challenge.issuedAt)/1e3),claims=Buffer.from(JSON.stringify({protocol:"NVS_LOCAL_DEVICE_PROOF_V1",...scope,challengeId:challenge.challengeId,audience:challenge.audience,jti:randomUUID3(),iat,exp:iat+30})).toString("base64url");const unsigned=header+"."+claims;const assertion=unsigned+"."+sign("sha256",Buffer.from(unsigned),{key,dsaEncoding:"ieee-p1363"}).toString("base64url");const result=LocalDeviceSessionSchema.parse(await request("prove",{...scope,challengeId:challenge.challengeId,assertion}));if(result.tenantId!==d.tenantId||result.deviceId!==d.deviceId)fail("DEVICE_PROOF_INVALID")}var fingerprint2=v=>sha256(canonicalLocalJson(v));function view(s){return{revision:s.revision,device:s.device?{deviceId:s.device.deviceId,label:s.device.label}:null,grants:s.grants,previews:s.previews,connection:s.connection,pending:s.pending?{kind:s.pending.command.kind,phase:s.pending.phase,fingerprint:s.pending.fingerprint}:null}}function accepted(s,result){const command=s.pending.command,i=command.input;if(command.kind==="ENROLL"){const d=LocalDeviceViewSchema.parse(result);if(d.tenantId!==i.tenantId||d.enrolledByPrincipalId!==s.scope.principalId||d.label!==command.input.label||d.runtimeVersion!==command.input.runtimeVersion||canonicalLocalJson(d.publicKey)!==canonicalLocalJson(command.input.publicKey)||canonicalLocalJson(d.platform)!==canonicalLocalJson(command.input.platform)||d.revokedAt)fail("DEVICE_RESULT_INVALID");return{device:d}}if(command.kind==="GRANT"){const g=LocalDeviceGrantSchema.parse(result),input2=command.input;if(g.tenantId!==input2.tenantId||g.projectId!==input2.projectId||g.deviceId!==input2.deviceId||g.deviceRevision!==input2.deviceRevision||g.revision!==input2.expectedRevision+1||g.expiresAt!==input2.expiresAt||g.capability!==input2.capability||g.executionPolicy!==input2.executionPolicy||g.approvedByPrincipalId!==s.scope.principalId||g.revokedAt)fail("DEVICE_RESULT_INVALID");return{grants:[...s.grants.filter(v=>v.projectId!==g.projectId),g]}}if(command.kind==="REVOKE_GRANT"){if(result?.semanticStatus!=="SUCCESS")fail("DEVICE_RESULT_INVALID");return{grants:s.grants.map(g=>g.projectId===command.input.projectId?{...g,revision:g.revision+1,revokedAt:new Date().toISOString()}:g),connectorId:null}}const p=(command.kind==="FINAL_RENDER"?LocalFinalRenderAdmissionSchema:LocalPreviewAdmissionSchema).parse(result),input=command.input;if(p.productionId!==input.productionId||p.timelineVersionId!==input.timelineVersionId||p.timelineFingerprint!==input.timelineFingerprint||canonicalLocalJson(p.placement.policy)!==canonicalLocalJson(input.placement))fail("DEVICE_RESULT_INVALID");return{previews:[p,...s.previews.filter(v=>v.renderId!==p.renderId)].slice(0,20)}}async function runDesktopDeviceRequest(home,raw){const request=DesktopDeviceRequestSchema.parse(raw),call=request.call;const records=await DesktopDeviceRecords.open(home,request.scope),manager=await LocalInstallationManager.open(home);let s=await records.current();const installation=await desktopInstallationIdentity(manager);let automatic=await desktopAutomation(home);const publicView=()=>({...view(s),installation,automaticConnection:canResumeDesktop(automatic,s,installation)});if(call.action==="inspect")return DesktopDeviceReplySchema.parse({view:publicView(),...s.pending?{command:s.pending.command}:{}});if(call.action==="dispatch"||call.action==="record"||call.action==="refused"){if(!s.pending||s.pending.fingerprint!==call.fingerprint)fail("DEVICE_PLAN_CHANGED");if(call.action==="dispatch"){if(s.pending.phase!=="PREPARED")fail("DEVICE_OUTCOME_UNKNOWN");const command2=s.pending.command;s=await records.save(s,{pending:{...s.pending,phase:"SENDING"}});return DesktopDeviceReplySchema.parse({view:publicView(),command:command2})}if(s.pending.phase!=="SENDING")fail("DEVICE_PLAN_CHANGED");s=await records.save(s,call.action==="record"?{...accepted(s,call.result),pending:null}:{pending:{...s.pending,phase:"REFUSED"}});return DesktopDeviceReplySchema.parse({view:publicView()})}if(s.pending?.phase==="SENDING")fail("DEVICE_OUTCOME_UNKNOWN");if(call.action==="remember-enable"){if(s.revision!==call.expectedRevision)fail("DEVICE_PLAN_CHANGED");automatic=await rememberDesktopAutomation(home,s,installation,call.installationFingerprint,call.projectIds);return DesktopDeviceReplySchema.parse({view:publicView()})}if(call.action==="prove"){await proveDesktopDevice(records);return DesktopDeviceReplySchema.parse({view:publicView()})}if(call.action==="connect"){if(call.installationFingerprint&&call.installationFingerprint!==installation?.fingerprint)fail("DEVICE_PLAN_CHANGED");s=await connectDesktopDevice(records,manager,s,call.expectedRevision);return DesktopDeviceReplySchema.parse({view:publicView()})}if(call.action==="connection-recover"){s=await recoverDesktopConnection(records,manager,s);return DesktopDeviceReplySchema.parse({view:publicView()})}let command;if(call.action==="enroll"){if(s.device)fail("DEVICE_ALREADY_ENROLLED");const active=(await manager.ledger.current()).value.active;if(!active)fail("INSTALL_REQUIRED");let publicKey;try{const key=createPrivateKey2({key:JSON.parse((await read(records.keyPath(),16384)).toString()),format:"jwk"});publicKey=createPublicKey2(key).export({format:"jwk"})}catch(e){if(e.code!=="ENOENT")throw e;publicKey=(await generateDeviceKey(records.keyPath())).publicKey}command={kind:"ENROLL",input:{tenantId:s.scope.tenantId,requestId:randomUUID4(),label:call.label,platform:active.descriptor.platform,runtimeVersion:active.descriptor.version,publicKey}}}else{const d=s.device;if(!d)fail("DEVICE_ENROLLMENT_REQUIRED");if(call.action==="preview"||call.action==="final"){if(!s.grants.some(g=>!g.revokedAt&&Date.parse(g.expiresAt)>Date.now()))fail("LOCAL_AUTHORIZATION_REQUIRED");command={kind:call.action==="final"?"FINAL_RENDER":"PREVIEW",input:{...call.input,tenantId:s.scope.tenantId,placement:{mode:call.mode,deviceId:d.deviceId},idempotencyKey:"desktop:"+randomUUID4()}}}else{const grant=s.grants.find(g=>g.projectId===call.projectId);if(call.action==="grant"){const ttl=Date.parse(call.expiresAt)-Date.now();if(ttl<=0||ttl>24*36e5||s.grants.length>=20&&!grant)fail("INVALID_INPUT");command={kind:"GRANT",input:{tenantId:s.scope.tenantId,projectId:call.projectId,requestId:randomUUID4(),deviceId:d.deviceId,deviceRevision:d.revision,expectedRevision:grant?.revision??0,expiresAt:call.expiresAt,...call.executionPolicy?{executionPolicy:call.executionPolicy}:{},capability:call.capability??"ROUGH_CUT_PREVIEW_V1"}}}else{if(!grant||grant.revokedAt)fail("LOCAL_AUTHORIZATION_REQUIRED");command={kind:"REVOKE_GRANT",input:{tenantId:s.scope.tenantId,projectId:call.projectId,requestId:randomUUID4(),grantId:grant.grantId,expectedRevision:grant.revision}}}}}const parsed=LocalManagementCommandSchema.parse(command);s=await records.save(s,{...parsed.kind==="ENROLL"?{enrollment:parsed.input}:{},pending:{command:parsed,fingerprint:fingerprint2(parsed),phase:"PREPARED"}});return DesktopDeviceReplySchema.parse({view:publicView(),command:parsed})}async function desktopDevicePending(home,scope){return(await(await DesktopDeviceRecords.open(home,scope)).current()).pending?.command??null}import{z as z9}from"zod";import{join as join7}from"node:path";import{randomUUID as randomUUID5}from"node:crypto";var digest4=z9.string().regex(/^[a-f0-9]{64}$/);var intentSchema=z9.strictObject({id:z9.uuid(),channel:z9.strictObject({protocol:z9.literal("NVS_DESKTOP_RUNTIME_CHANNEL_V1"),catalogueUrl:z9.string().url(),publicKey:z9.string()}),release:LocalReleaseSchema,installationRevision:z9.int().nonnegative(),expiresAt:z9.iso.datetime()});async function runDesktopBootstrap(home,raw,bundled){const{call}=DesktopBootstrapRequestSchema.parse(raw),manager=await LocalInstallationManager.open(home),root=await directory(join7(home,"bootstrap-plans"));let intent2,fingerprint3;if(call.action==="prepare"){const info=await desktopChannelInfo(manager,bundled);if(!info.channelFingerprint)fail("DESKTOP_CHANNEL_REQUIRED");const configuration=info.configured?await manager.configuration():null;const channel=desktopRuntimeChannel(configuration?{protocol:"NVS_DESKTOP_RUNTIME_CHANNEL_V1",catalogueUrl:configuration.catalogueUrl,publicKey:(await read(configuration.publicKeyFile,16384)).toString()}:bundled);const publicKeyFile=join7(root,channel.fingerprint+".pem");try{await write(publicKeyFile,channel.value.publicKey,true)}catch(e){if(e.code!=="EEXIST"||(await read(publicKeyFile,16384)).toString()!==channel.value.publicKey)throw e}const trusted=await catalogue({catalogueUrl:channel.value.catalogueUrl,publicKeyFile});const candidates=trusted.signed.catalogue.releases.filter(r=>r.descriptor.workProtocol==="NVS_LOCAL_WORK_V2"&&r.descriptor.platform.os===process.platform&&r.descriptor.platform.architecture===process.arch&&!!r.tools);const release=candidates.reduce((a,b)=>!a||newerVersion(b.descriptor.version,a.descriptor.version)?b:a,null);if(!release)fail("LOCAL_PROFILE_UNAVAILABLE");intent2=intentSchema.parse({id:randomUUID5(),channel:channel.value,release,installationRevision:(await manager.ledger.current()).value.revision,expiresAt:new Date(Math.min(Date.now()+18e5,Date.parse(trusted.signed.catalogue.expiresAt))).toISOString()});fingerprint3=sha256(canonicalLocalJson(intent2));await write(join7(root,intent2.id+".json"),canonicalLocalJson({intent:intent2,fingerprint:fingerprint3}),true)}else{const saved=z9.strictObject({intent:intentSchema,fingerprint:digest4}).parse(JSON.parse((await read(join7(root,call.id+".json"),131072)).toString()));intent2=saved.intent;fingerprint3=saved.fingerprint;if(fingerprint3!==call.fingerprint||fingerprint3!==sha256(canonicalLocalJson(intent2))||intent2.id!==call.id)fail("PLAN_CHANGED");const receiptFile=join7(root,intent2.id+".installation.json");const receipt=z9.strictObject({id:z9.uuid(),fingerprint:digest4}).nullable().parse(await optional(receiptFile));if(receipt){const state=(await manager.ledger.current()).value;if(state.transition){if(state.transition.planId!==receipt.id)fail("RECOVERY_REQUIRED");await manager.reconcile(receipt.id,receipt.fingerprint)}}else{if(Date.parse(intent2.expiresAt)<=Date.now()||(await manager.ledger.current()).value.revision!==intent2.installationRevision)fail("PLAN_CHANGED");const trust=desktopRuntimeChannel(intent2.channel);await configureDesktopChannel(manager,trust.fingerprint,intent2.channel);const plan=await manager.prepare(intent2.release.descriptor.version,{mode:"MANAGED"});if(canonicalLocalJson(plan.release)!==canonicalLocalJson(intent2.release))fail("PLAN_CHANGED");await write(receiptFile,canonicalLocalJson({id:plan.planId,fingerprint:plan.fingerprint}),true);await manager.apply(plan.planId,plan.fingerprint)}const installed=(await manager.ledger.current()).value;if(installed.transition||canonicalLocalJson(installed.active?.descriptor)!==canonicalLocalJson(intent2.release.descriptor))fail("RECOVERY_REQUIRED");const configuration=await manager.configuration(),report=await(await ownerClient(configuration.stateDirectory)).doctor();if(!report.executionProfiles?.includes("STUDIO_MEDIA_V2"))fail("LOCAL_PROFILE_UNAVAILABLE");if((await desktopRuntimeStatus(manager)).state!=="RUNNING")fail("RECOVERY_REQUIRED")}return DesktopBootstrapReplySchema.parse({id:intent2.id,fingerprint:fingerprint3,version:intent2.release.descriptor.version,host:new URL(intent2.channel.catalogueUrl).host,bytes:intent2.release.package.byteSize+Object.values(intent2.release.tools??{}).reduce((sum,a)=>sum+a.byteSize,0),expiresAt:intent2.expiresAt,installed:call.action==="apply"})}async function runDesktopOwnerRequest(home,raw,bundledChannel){const request=DesktopOwnerRequestSchema.parse(raw),manager=await LocalInstallationManager.open(home);let result;switch(request.operation){case"bootstrap":result=await runDesktopBootstrap(home,request,bundledChannel);break;case"agent":result=await runDesktopAgentRequest(home,request);break;case"offline":result=await runDesktopOfflineRequest(home,request);break;case"storage":result=await runDesktopStorageRequest(home,request);break;case"workspace":result=await runDesktopWorkspaceRequest(home,request);break;case"device":result=await runDesktopDeviceRequest(home,request);break;case"status":case"start":case"stop":if(request.operation==="start")await manager.start();if(request.operation==="stop"){await disableDesktopAutomation(home);await manager.stop()}result=await desktopRuntimeStatus(manager);break;case"configuration":result=await desktopChannelInfo(manager,bundledChannel);break;case"configure":await configureDesktopChannel(manager,request.channelFingerprint,bundledChannel);result=await desktopRuntimeStatus(manager);break;case"check":{const checked=await manager.check();result={protocol:"NVS_DESKTOP_RUNTIME_UPDATES_V1",activeVersion:checked.installation.activeVersion,versions:checked.available.map(v=>({version:v.version,rejected:checked.rejectedVersions.includes(v.version)})),notifications:checked.notifications};break}case"prepare":case"tools-prepare":{const choice=request.operation==="tools-prepare"?request.choice.mode==="MANAGED"?request.choice:await captureInstalledTools(request.choice):void 0;const plan=await manager.prepare(request.version,choice);result={protocol:"NVS_DESKTOP_OWNER_PLAN_V1",plan:{kind:"APPLY",...choice?{toolMode:choice.mode}:{},planId:plan.planId,fingerprint:plan.fingerprint,version:plan.release.descriptor.version,previousVersion:(await manager.status()).activeVersion,expiresAt:plan.expiresAt,phase:"PREPARED"}};break}case"recovery":{const current=(await manager.ledger.current()).value,transition=current.transition;let plan=null;if(transition){const original=await manager.plan(transition.planId);if(original.fingerprint!==transition.fingerprint)fail("PLAN_CHANGED");plan={kind:"RECOVER",planId:original.planId,fingerprint:original.fingerprint,version:original.release.descriptor.version,previousVersion:transition.previous?.descriptor.version??null,expiresAt:original.expiresAt,phase:transition.phase}}result={protocol:"NVS_DESKTOP_OWNER_PLAN_V1",plan};break}case"apply":case"recover":if(request.operation==="apply")await manager.apply(request.planId,request.fingerprint);else await manager.reconcile(request.planId,request.fingerprint);result=await desktopRuntimeStatus(manager);break;case"reject":await manager.reject(request.version);result=await desktopRuntimeStatus(manager);break}return desktopOwnerResponses[request.operation].parse(result)}import{lstat as lstat3,readFile,chmod as chmod2}from"node:fs/promises";import{join as join8,isAbsolute,dirname}from"node:path";async function verifiedSource(source,expected,limit){if(!isAbsolute(source)||!/^[a-f0-9]{64}$/.test(expected))fail("DESKTOP_DISTRIBUTION_INVALID");const stat=await lstat3(source);if(!stat.isFile()||stat.isSymbolicLink()||stat.size>limit)fail("DESKTOP_DISTRIBUTION_INVALID");const bytes=await readFile(source);if(bytes.length>limit||sha256(bytes)!==expected)fail("DESKTOP_DISTRIBUTION_INVALID");return bytes}async function retain(target,bytes,expected,limit,mode){try{if(sha256(await read(target,limit))!==expected)fail("DESKTOP_DISTRIBUTION_INVALID")}catch(error){if(error.code!=="ENOENT")throw error;try{await write(target,bytes,true)}catch(error2){if(error2.code!=="EEXIST")throw error2}if(sha256(await read(target,limit))!==expected)fail("DESKTOP_DISTRIBUTION_INVALID")}await chmod2(target,mode)}async function materializeDesktopNode(home,source,expected,licenseDigest){const bytes=await verifiedSource(source,expected,160*1024*1024);const license=licenseDigest?await verifiedSource(join8(dirname(source),"LICENSE.txt"),licenseDigest,2*1024*1024):null;const base=await directory(join8(await directory(home),"nodes",expected)),target=join8(base,process.platform==="win32"?"node.exe":"node");if(license)await retain(join8(base,"LICENSE.txt"),license,licenseDigest,2*1024*1024,256);await retain(target,bytes,expected,160*1024*1024,320);return target}async function runLocalManagement(home,operation){if(!["status","start","stop"].includes(operation))throw Error("INVALID_INPUT");const manager=await LocalInstallationManager.open(home);if(operation==="start")await manager.start();if(operation==="stop")await manager.stop();return desktopRuntimeStatus(manager)}export{DesktopDeviceReplySchema,DesktopDeviceScopeSchema,DesktopOwnerRequestSchema,desktopDeviceConnector,desktopDevicePending,desktopOwnerResponses,desktopRuntimeChannel,materializeDesktopNode,runDesktopOwnerRequest,runLocalManagement};
|
package/dist/local-navigation.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LocalMcpTools}from"./_chunks/chunk-
|
|
1
|
+
import{LocalMcpTools}from"./_chunks/chunk-INLSOHAK.js";import{DesktopDeviceScopeSchema,desktopDeviceConnector}from"./_chunks/chunk-N6S6HCWE.js";import"./_chunks/chunk-RVGDXRPK.js";import"./_chunks/chunk-KB2GVAN7.js";import"./_chunks/chunk-PBEHCYR7.js";import"./_chunks/chunk-VPYAXWXY.js";import"./_chunks/chunk-6NVIN2NI.js";async function openDesktopDeviceTools(raw,home){const scope=DesktopDeviceScopeSchema.parse(raw);return LocalMcpTools.open(await desktopDeviceConnector(home,scope),home)}export{LocalMcpTools,openDesktopDeviceTools};
|
package/package.json
CHANGED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{loginLink,openLoginBrowser}from"./chunk-VDNNFVTZ.js";import{clientHome,connectionError,loadConnection,projectConnection,readAccount,saveConnection}from"./chunk-KNFUMWDY.js";import{profileAuthorization,runOAuthCommand}from"./chunk-DXJQWTLG.js";import{FileOAuthProvider}from"./chunk-FU3524Z6.js";import"./chunk-6LU6GJKW.js";import"./chunk-KB2GVAN7.js";import"./chunk-GJ7BZJLW.js";import"./chunk-VPYAXWXY.js";import"./chunk-PUNG4ND7.js";import{NativeStudioSdkError}from"./chunk-6NVIN2NI.js";import{randomUUID,timingSafeEqual}from"node:crypto";import{createServer}from"node:http";import{join}from"node:path";async function runProjectConnect(argv,environment,hooks={}){if(argv[0]!=="connect")throw Error();const options=new Map;for(let i=1;i<argv.length;i+=2){const key=argv[i],value=argv[i+1];if(!key||!["--mcp-url","--scope","--timeout-ms","--browser"].includes(key)||!value||value.startsWith("--")||options.has(key))throw Error();options.set(key,value)}const root=await clientHome(environment,true),account=await readAccount(root);const explicit=options.get("--mcp-url");if(!explicit&&(!account?.workspaceId||!account.projectId))connectionError("ACCOUNT_PROJECT_SELECTION_REQUIRED");const resource=projectConnection(explicit??new URL("/mcp/external/v1/tenants/"+account.workspaceId+"/projects/"+account.projectId,account.serverOrigin).href);const scope=options.get("--scope")??"nvs:read";if(!["nvs:read","nvs:read nvs:write"].includes(scope))throw Error();const browser=options.get("--browser")??"auto";if(!["auto","manual"].includes(browser))throw Error();const timeout=options.get("--timeout-ms")??"180000";if(!/^\d+$/.test(timeout)||Number(timeout)<1e3||Number(timeout)>3e5)throw Error();const signal=AbortSignal.timeout(Number(timeout));const profile=`profile-${randomUUID()}.json`;const path=join(root,profile),callbackPath=`/callback/${randomUUID()}`;if(account&&(account.state!=="ACTIVE"||Date.parse(account.expiresAt)<=Date.now()||account.workspaceId!==resource.tenantId||account.projectId!==resource.projectId))connectionError("ACCOUNT_PROJECT_SELECTION_REQUIRED");if(!explicit){const saved=await loadConnection(environment,true);if(saved?.resource===resource.resource&&saved.scope===scope&&!saved.exchangeUnresolved){await profileAuthorization(saved.profile,signal);return{exitCode:0,output:{semanticStatus:"SUCCESS",connected:true,resource:saved.resource,tenantId:saved.tenantId,projectId:saved.projectId,scope,reused:true}}}}let provider,receiving=false,redeeming=false;let finish;const callback=new Promise(resolve=>{finish=resolve});const server=createServer({maxHeaderSize:8192,requestTimeout:5e3,headersTimeout:5e3},(req,res)=>{res.setHeader("cache-control","no-store");res.setHeader("content-type","text/plain; charset=utf-8");res.setHeader("x-content-type-options","nosniff");const address=server.address();const host=address&&typeof address!=="string"?`127.0.0.1:${address.port}`:"";if(req.method!=="GET"||req.headers.host!==host||req.headers.origin||!req.url||req.url.length>4096||!req.url.startsWith(callbackPath+"?")||!provider||receiving){res.writeHead(400).end("Invalid authorization callback.");return}const url=new URL(req.url,`http://${host}`),state=url.searchParams.get("state");const expected=provider.data.state;const issuer=provider.data.discovery?.authorizationServerMetadata?.issuer??provider.data.discovery?.authorizationServerUrl;if(!state||Buffer.byteLength(state)!==Buffer.byteLength(expected)||!timingSafeEqual(Buffer.from(state),Buffer.from(expected))||url.searchParams.getAll("state").length!==1||url.pathname!==callbackPath||url.searchParams.getAll("iss").length!==1||url.searchParams.get("iss")!==issuer||(url.searchParams.has("error")?url.searchParams.has("code"):url.searchParams.getAll("code").length!==1||!url.searchParams.get("code"))){res.writeHead(400).end("Invalid authorization callback.");return}receiving=true;res.end("Authorization received. Return to NativeStudio CLI for the result.");finish(url.searchParams.has("error")?null:url.href)});server.maxConnections=8;const expired=()=>finish(null);signal.addEventListener("abort",expired,{once:true});try{await new Promise((resolve,reject)=>{server.once("error",reject);server.listen(0,"127.0.0.1",resolve)});const address=server.address();if(!address||typeof address==="string")throw Error();const redirect=`http://127.0.0.1:${address.port}${callbackPath}`;await runOAuthCommand(["auth-start","--profile",path,"--mcp-url",resource.resource,"--callback",redirect,"--scope",scope],empty(),signal);provider=await FileOAuthProvider.load(path);if(!provider.data.authorizationUrl)throw Error();signal.throwIfAborted();if(hooks.authorize)await hooks.authorize(provider.data.authorizationUrl,signal);else if(browser==="manual")loginLink(provider.data.authorizationUrl);else await openLoginBrowser(provider.data.authorizationUrl,signal);const received=await callback;if(!received)connectionError(signal.aborted?"LOGIN_TIMED_OUT":"LOGIN_DENIED");async function*input(){yield Buffer.from(JSON.stringify({callbackUrl:received}))}redeeming=true;await runOAuthCommand(["auth-complete","--profile",path,"--input","-"],input(),signal);const credentials=await saveConnection(root,profile,account?.epoch).catch(()=>{throw new NativeStudioSdkError("PROJECT_AUTHORIZED_CONNECTION_NOT_SELECTED","INTERNAL_OPERATIONAL_FAILURE","UNKNOWN")});return{exitCode:0,output:{semanticStatus:"SUCCESS",connected:true,credentialPurpose:"PROJECT_MCP",...resource,scope:credentials.scope,requestedScope:scope,nextSteps:["nvs status","nvs find --query <intent>","nvs mcp"]}}}catch(error){if(!redeeming&&signal.aborted)connectionError("LOGIN_TIMED_OUT");throw error}finally{signal.removeEventListener("abort",expired);server.closeAllConnections();await new Promise(resolve=>server.close(()=>resolve()))}}async function*empty(){}export{runProjectConnect};
|