@nativestudio/sdk 0.3.0-rc.2 → 0.3.0-rc.5
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 +4 -4
- package/README.md +20 -0
- package/dist/_chunks/chunk-GLD5WP6Z.js +1 -0
- package/dist/_chunks/chunk-NSS2BKVM.js +1 -0
- package/dist/_types/contracts/delivery-manifest.d.ts +63 -27
- package/dist/_types/contracts/delivery-operations.d.ts +21 -9
- package/dist/_types/contracts/device-render.d.ts +10 -0
- package/dist/_types/contracts/exploration-recommendation.d.ts +84 -36
- package/dist/_types/contracts/final-render.d.ts +9 -0
- package/dist/_types/contracts/index.d.ts +1 -0
- package/dist/_types/contracts/local-execution/agent-context.d.ts +365 -0
- package/dist/_types/contracts/local-execution/agent-evidence.d.ts +79 -0
- package/dist/_types/contracts/local-execution/agent-grant.d.ts +31 -0
- package/dist/_types/contracts/local-execution/agent-review.d.ts +733 -46
- package/dist/_types/contracts/local-execution/device.d.ts +10 -2
- package/dist/_types/contracts/local-execution/index.d.ts +6 -0
- package/dist/_types/contracts/local-execution/ipc.d.ts +1759 -37
- package/dist/_types/contracts/local-execution/lifecycle.d.ts +48 -6
- package/dist/_types/contracts/local-execution/local-navigation.d.ts +112 -10
- package/dist/_types/contracts/local-execution/management.d.ts +394 -0
- package/dist/_types/contracts/local-execution/media-recipe.d.ts +203 -0
- package/dist/_types/contracts/local-execution/offline.d.ts +59 -0
- package/dist/_types/contracts/local-execution/preview.d.ts +7607 -159
- package/dist/_types/contracts/local-execution/work.d.ts +7674 -294
- package/dist/_types/contracts/local-execution/workspace.d.ts +136 -0
- package/dist/_types/contracts/programmatic-exploration.d.ts +42 -18
- package/dist/_types/contracts/repair-strategy.d.ts +42 -18
- package/dist/_types/contracts/review-intelligence-final-output.d.ts +42 -18
- package/dist/_types/contracts/review-intelligence.d.ts +84 -36
- package/dist/_types/contracts/rough-cut-manifest.d.ts +7 -3
- package/dist/_types/contracts/rough-cut-profile.d.ts +12 -3
- package/dist/_types/contracts/rough-cut-review.d.ts +126 -54
- package/dist/_types/contracts/rough-cut.d.ts +85 -32
- package/dist/_types/contracts/visual-layer-render.d.ts +21 -9
- package/dist/_types/sdk/catalog/assembly.d.ts +146 -110
- package/dist/_types/sdk/catalog/delivery.d.ts +36 -36
- package/dist/_types/sdk/catalog/programmatic-exploration.d.ts +36 -36
- package/dist/_types/sdk/catalog/repair-strategy.d.ts +36 -36
- package/dist/_types/sdk/catalog/reviewer.d.ts +72 -72
- package/dist/_types/sdk/catalog/visual-exploration.d.ts +36 -36
- package/dist/_types/sdk/client.d.ts +2 -0
- package/dist/_types/sdk/device-renders.d.ts +138 -0
- package/dist/_types/sdk/index.d.ts +1 -0
- package/dist/_types/sdk/local-runtime/device-client.d.ts +138 -2
- package/dist/_types/sdk/local-runtime/workspace.d.ts +181 -0
- package/dist/_types/sdk/local-runtime-client.d.ts +1294 -56
- package/dist/_types/sdk/mcp-client.d.ts +2 -0
- package/dist/index.d.ts +1 -1
- package/dist/index.js +1 -1
- package/dist/local-runtime.js +1 -1
- package/dist/native/JobNative.cs +10 -0
- package/dist/native/JobRunner.cs +24 -3
- package/dist/native/NativeMain.cs +15 -0
- package/dist/runtime-authority.js +1 -1
- package/package.json +1 -1
- package/dist/_chunks/chunk-34KSWLCI.js +0 -1
- package/dist/_chunks/chunk-4IOFVNFG.js +0 -1
package/dist/local-runtime.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{KeyframeObservationSchema,NativeRuntimePublicKeySchema,ReviewEvidenceMediaSchema,ReviewIntelligenceBasisSchema,ReviewIntelligenceContextResultSchema,RoughCutAdmissionSchema,RoughCutManifestReaderSchema,RoughCutStartSchema,RoughCutTechnicalSchema,ValidateReviewIntelligenceSchema,VisualRequirementSchema}from"./_chunks/chunk-4IOFVNFG.js";import{OperationIdSchema}from"./_chunks/chunk-4M3AGNTZ.js";import{NativeStudioSdkError}from"./_chunks/chunk-6NVIN2NI.js";import{lstat as lstat2,mkdir,open,rename,link,unlink}from"node:fs/promises";import{dirname,isAbsolute as isAbsolute2,join as join2}from"node:path";import{createHash as createHash2}from"node:crypto";import{execFile,spawn}from"node:child_process";import{once}from"node:events";import{readFile,realpath,lstat}from"node:fs/promises";import{createHash,randomUUID}from"node:crypto";import{fileURLToPath}from"node:url";import{join,win32,isAbsolute}from"node:path";var nativeAssetNames=["Bootstrap.ps1","NativeMain.cs","PrivateAccess.cs","PipeBridge.cs","JobNative.cs","JobRunner.cs"];var executable;var assetDirectory;async function windowsHelper(){if(process.platform!=="win32"||process.arch!=="x64")throw Error("WINDOWS_PLATFORM_REQUIRED");return executable??=bootstrap().catch(error=>{executable=void 0;throw error})}async function bootstrap(){const directory=assetDirectory??fileURLToPath(new URL("./dist/native/",import.meta.resolve("@nativestudio/sdk/package.json")));const hash=createHash("sha256");for(const name of nativeAssetNames){hash.update(name+"\n");hash.update(await readFile(join(directory,name)))}const sourceDigest=hash.digest("hex"),system=process.env.SystemRoot??process.env.SYSTEMROOT;if(!system||!win32.isAbsolute(system)||system.startsWith("\\\\"))throw Error("WINDOWS_SYSTEM_UNAVAILABLE");const shell=join(system,"System32/WindowsPowerShell/v1.0/powershell.exe"),script=(await readFile(join(directory,"Bootstrap.ps1"))).toString("utf8");const result=await new Promise((resolve,reject)=>{const child=execFile(shell,["-NoLogo","-NoProfile","-NonInteractive","-EncodedCommand",Buffer.from(script,"utf16le").toString("base64")],{timeout:15e3,maxBuffer:32768,windowsHide:true},(error,stdout)=>error?reject(Error("WINDOWS_HELPER_UNAVAILABLE")):resolve(stdout));child.stdin.on("error",()=>{});child.stdin.end(JSON.stringify({directory,sourceDigest}))});const value=JSON.parse(result);if(value.sourceDigest!==sourceDigest||!/^[a-f0-9]{64}$/.test(value.sha256)||!win32.isAbsolute(value.path))throw Error("WINDOWS_HELPER_INVALID");const path=await realpath(value.path),stat=await lstat(path);if(!stat.isFile()||stat.isSymbolicLink()||stat.nlink!==1||stat.size>2*1024*1024||createHash("sha256").update(await readFile(path)).digest("hex")!==value.sha256)throw Error("WINDOWS_HELPER_INVALID");return path}var service;async function connection(){return service??=(async()=>{const child=spawn(await windowsHelper(),["service",String(process.pid)],{shell:false,windowsHide:true,stdio:["pipe","pipe","pipe"]});const pending=new Map;let bytes=Buffer.alloc(0),stderr=0;const close=()=>{for(const item of pending.values()){clearTimeout(item.timer);item.reject(Error("WINDOWS_HELPER_UNAVAILABLE"))}pending.clear();service=void 0};child.stdout.on("data",part=>{bytes=Buffer.concat([bytes,part]);if(bytes.length>2*1024*1024)return child.kill();for(;;){const end=bytes.indexOf(10);if(end<0)break;const line=bytes.subarray(0,end);bytes=bytes.subarray(end+1);try{const value=JSON.parse(line.toString());const item=pending.get(value.id);if(!item)continue;pending.delete(value.id);clearTimeout(item.timer);if(value.ok)item.resolve(value.data);else item.reject(Error(value.error==="EXISTS"?"EXISTS":"WINDOWS_ACCESS_DENIED"))}catch{child.kill()}}});child.stderr.on("data",b=>{if((stderr+=b.length)>65536)child.kill()});child.on("error",close);child.on("close",close);child.stdin.on("error",close);await once(child,"spawn");child.unref();child.stdout.unref();child.stderr.unref();child.stdin.unref();return{child,pending}})().catch(error=>{service=void 0;throw error})}async function windowsRequest(request3,timeoutMs=1e4,signal){signal?.throwIfAborted();const{child,pending}=await connection();signal?.throwIfAborted();if(child.exitCode!==null||child.signalCode!==null||child.stdin.destroyed)throw Error("WINDOWS_HELPER_UNAVAILABLE");if(pending.size>=32)throw Error("WINDOWS_HELPER_BUSY");const id=randomUUID(),data=JSON.stringify({...request3,id});if(Buffer.byteLength(data)>1024*1024)throw Error("WINDOWS_HELPER_INPUT_LIMIT");return new Promise((resolve,reject)=>{const abort=()=>{child.stdin.write(JSON.stringify({operation:"cancel",target:id})+"\n")};const timer=setTimeout(()=>{abort();pending.delete(id);signal?.removeEventListener("abort",abort);reject(Error("WINDOWS_HELPER_TIMEOUT"))},timeoutMs);pending.set(id,{timer,resolve:v=>{signal?.removeEventListener("abort",abort);resolve(v)},reject:e=>{signal?.removeEventListener("abort",abort);reject(e)}});signal?.addEventListener("abort",abort,{once:true});child.stdin.write(data+"\n");if(signal?.aborted)abort()})}function localSocketPath(root,platform=process.platform){if(platform!=="win32")return join2(root,"runtime.sock");return"\\\\.\\pipe\\nvs-"+createHash2("sha256").update(root.toLowerCase()).digest("hex")}async function privateAccess(path,kind){if(process.platform==="win32"){if(kind!=="pipe")await lstat2(path);await windowsRequest({operation:"check",path,kind});return}const s=await lstat2(path);if(s.isSymbolicLink()||s.uid!==process.getuid?.()||s.mode&63||(kind==="directory"?!s.isDirectory():kind==="pipe"?!s.isSocket():!s.isFile()))throw Error("LOCAL_PERMISSIONS_INVALID")}async function privateDirectory(path,create=false){if(!isAbsolute2(path)||!["win32","darwin","linux"].includes(process.platform))throw Error("LOCAL_LOCATION_INVALID");if(process.platform==="win32")await windowsRequest({operation:create?"directory":"check",path,kind:"directory"});else{if(create)await mkdir(path,{recursive:true,mode:448});await privateAccess(path,"directory")}}import{spawn as spawn2}from"node:child_process";import{Duplex}from"node:stream";import{randomUUID as randomUUID2,createHash as createHash3}from"node:crypto";import{request}from"node:http";import{z as z11}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"])})]);import{z as z2}from"zod";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,deviceId:LocalIdSchema,deviceRevision:LocalRevisionSchema,expectedRevision:z2.int().nonnegative(),expiresAt:LocalTimeSchema,capability:z2.literal("ROUGH_CUT_PREVIEW_V1")});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 z3}from"zod";var LocalExecutionProfileSchema=z3.strictObject({kind:z3.literal("ROUGH_CUT_PREVIEW_V1"),profileId:z3.literal("PREVIEW_H264_480P_V1"),contractDigest:LocalDigestSchema});var LocalToolchainSchema=z3.strictObject({platform:LocalDevicePlatformSchema,rendererVersion:LocalPackageVersionSchema,rendererDigest:LocalDigestSchema,ffmpeg:z3.strictObject({version:z3.string().min(1).max(160),binaryDigest:LocalDigestSchema}),ffprobe:z3.strictObject({version:z3.string().min(1).max(160),binaryDigest:LocalDigestSchema}),profile:LocalExecutionProfileSchema});var LocalFrozenWorkSchema=LocalWorkScopeSchema.extend({protocol:z3.literal("NVS_LOCAL_WORK_V1"),operationId:OperationIdSchema,renderId:LocalIdSchema,productionRevision:LocalRevisionSchema,executionClass:z3.enum(["LIVE","TEST_ONLY"]),policy:LocalPlacementPolicySchema,profile:LocalExecutionProfileSchema,manifest:RoughCutManifestReaderSchema,manifestFingerprint:LocalDigestSchema,sources:z3.array(z3.strictObject({artifactId:LocalIdSchema,representationId:LocalIdSchema,checksumSha256:LocalDigestSchema,byteSize:z3.int().positive(),contentType:z3.string().min(1).max(100)})).min(1).max(512)}).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"})});var LocalLeaseBindingSchema=LocalWorkScopeSchema.extend({attemptId:LocalIdSchema,assignmentRevision:LocalRevisionSchema,workerId:z3.string().min(1).max(200),workFingerprint:LocalDigestSchema,toolchainFingerprint:LocalDigestSchema});var target=z3.discriminatedUnion("kind",[z3.strictObject({kind:z3.literal("DEVICE"),deviceId:LocalIdSchema,deviceRevision:LocalRevisionSchema,grantId:LocalIdSchema,grantRevision:LocalRevisionSchema}),z3.strictObject({kind:z3.literal("SERVER")})]);var LocalExecutionLeaseSchema=LocalLeaseBindingSchema.extend({target,issuedAt:LocalTimeSchema,expiresAt:LocalTimeSchema}).refine(v=>Date.parse(v.expiresAt)>Date.parse(v.issuedAt));var LocalWorkAssignmentSchema=z3.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"})});import{z as z4}from"zod";var output=z4.discriminatedUnion("role",[z4.strictObject({role:z4.literal("VIDEO"),receiptId:LocalIdSchema,checksumSha256:LocalDigestSchema,byteSize:z4.int().positive().max(128*1024*1024),contentType:z4.literal("video/mp4")}),z4.strictObject({role:z4.literal("POSTER"),receiptId:LocalIdSchema,checksumSha256:LocalDigestSchema,byteSize:z4.int().positive().max(2*1024*1024),contentType:z4.literal("image/png")})]);var LocalCompletionSubmissionSchema=LocalLeaseBindingSchema.extend({requestId:LocalIdSchema,outputs:z4.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=z4.strictObject({binding:LocalLeaseBindingSchema,output,verifiedAt:LocalTimeSchema});var LocalCompletionReceiptSchema=LocalLeaseBindingSchema.extend({submissionFingerprint:LocalDigestSchema.optional(),semanticStatus:z4.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});import{z as z8}from"zod";import{z as z6}from"zod";import{z as z5}from"zod";var executable2=z5.strictObject({path:z5.string().min(1).max(4096),digest:LocalDigestSchema});var LocalToolSelectionSchema=z5.strictObject({mode:z5.enum(["MANAGED","INSTALLED"]),ffmpeg:executable2,ffprobe:executable2});var LocalRuntimeDescriptorSchema=z6.strictObject({protocol:z6.literal("NVS_RUNTIME_DESCRIPTOR_V1"),version:LocalPackageVersionSchema,node:z6.strictObject({major:z6.literal(24),minMinor:z6.literal(12)}),platform:LocalDevicePlatformSchema,ipcProtocol:z6.literal("NVS_LOCAL_IPC_V1"),workProtocol:z6.literal("NVS_LOCAL_WORK_V1"),journalSchema:z6.literal(1),rendererDigest:LocalDigestSchema,profileDigest:LocalDigestSchema});var LocalSessionConnectorSchema=z6.strictObject({protocol:z6.literal("NVS_LOCAL_CONNECTOR_V1"),stateDirectory:z6.string().min(1).max(4096),credential:z6.string().length(43).regex(/^[A-Za-z0-9_-]{43}$/),expiresAt:LocalTimeSchema,projects:z6.array(LocalProjectScopeSchema).min(1).max(100)});var LocalManagementInventorySchema=z6.strictObject({runtimeRevision:z6.int().positive(),descriptor:LocalRuntimeDescriptorSchema,activeProcesses:z6.int().nonnegative(),pendingExecutions:z6.int().nonnegative(),pendingRequests:z6.int().nonnegative(),pendingRenderers:z6.array(LocalDigestSchema).max(64)});var LocalReleaseAssetSchema=z6.strictObject({url:z6.string().url().max(2048),byteSize:z6.int().positive().max(256*1024*1024),sha512:z6.string().length(128).regex(/^[0-9a-f]{128}$/)});var LocalReleaseSchema=z6.strictObject({descriptor:LocalRuntimeDescriptorSchema,package:LocalReleaseAssetSchema,tools:z6.strictObject({ffmpeg:LocalReleaseAssetSchema.extend({sha256:LocalDigestSchema}),ffprobe:LocalReleaseAssetSchema.extend({sha256:LocalDigestSchema})}).nullable()});var LocalReleaseCatalogueSchema=z6.strictObject({protocol:z6.literal("NVS_LOCAL_RELEASE_CATALOGUE_V1"),issuedAt:LocalTimeSchema,expiresAt:LocalTimeSchema,releases:z6.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=z6.strictObject({catalogue:LocalReleaseCatalogueSchema,signature:z6.string().length(86).regex(/^[A-Za-z0-9_-]{85}[AQgw]$/)});var LocalToolChoiceSchema=z6.discriminatedUnion("mode",[z6.strictObject({mode:z6.literal("MANAGED")}),LocalToolSelectionSchema.extend({mode:z6.literal("INSTALLED")})]);var LocalUpdatePlanSchema=z6.strictObject({protocol:z6.literal("NVS_LOCAL_UPDATE_PLAN_V1"),planId:LocalIdSchema,installationRevision:z6.int().nonnegative(),runtimeRevision:z6.int().positive().nullable(),catalogueFingerprint:LocalDigestSchema,trustFingerprint:LocalDigestSchema.optional(),release:LocalReleaseSchema,toolSelection:LocalToolChoiceSchema.optional(),fingerprint:LocalDigestSchema,createdAt:LocalTimeSchema,expiresAt:LocalTimeSchema});var LocalClientNextActionSchema=z6.strictObject({surface:z6.enum(["CLI","LOCAL_IPC","REMOTE"]),operation:z6.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:z6.enum(["AVAILABLE","BLOCKED"]),reason:z6.enum(["READY","INSTALL_REQUIRED","AUTHORIZATION_REQUIRED","VERSION_INCOMPATIBLE","UPDATE_AVAILABLE","RECOVERY_REQUIRED","USER_APPROVAL_REQUIRED","TRUST_REQUIRED","UNAVAILABLE"])});import{z as z7}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 sha=z7.string().regex(/^[a-f0-9]{64}$/);var qualifiedVersion=z7.enum(["0.164.0","0.165.0"]);var LocalAgentGrantSchema=z7.strictObject({protocol:z7.literal("NVS_CODEX_REVIEW_GRANT_V1"),binary:z7.string().min(1).max(4096).startsWith("/"),binaryDigest:sha,version:qualifiedVersion,model:z7.string().regex(/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,99}$/),reasoningEffort:z7.enum(["low","medium","high","xhigh"]).optional(),reviewerLabel:z7.string().trim().min(1).max(100),inference:z7.literal("REMOTE_OPENAI"),remoteUseApproved:z7.literal(true),imageDisclosureApproved:z7.literal(true).optional(),projects:z7.array(LocalProjectScopeSchema).min(1).max(100),expiresAt:z7.iso.datetime({offset:true})});var LocalAgentSnapshotSchema=z7.strictObject({basis:ReviewIntelligenceBasisSchema.extend({target:z7.strictObject({kind:z7.literal("IMAGE"),generationId:z7.uuid()})}),productionRevision:z7.int().positive(),reviewVersion:z7.int().nonnegative(),executionClass:z7.enum(["LIVE","TEST_ONLY"]),media:ReviewEvidenceMediaSchema,requirements:z7.array(VisualRequirementSchema).min(1).max(64),image:z7.strictObject({contentType:z7.literal("image/png"),byteSize:z7.int().positive().max(8388608),width:z7.int().positive().max(4096),height:z7.int().positive().max(4096)}).optional()}).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=z7.strictObject({configured:z7.boolean(),available:z7.boolean(),reason:z7.enum(["GRANT_REQUIRED","READY","RUNTIME_UNAVAILABLE","GRANT_EXPIRED"]),grantFingerprint:sha.nullable(),inference:z7.literal("REMOTE_OPENAI")});var LocalAgentPlanSchema=z7.strictObject({protocol:z7.literal("NVS_LOCAL_AGENT_REVIEW_V1"),id:z7.uuid(),grantFingerprint:sha,snapshot:LocalAgentSnapshotSchema,expiresAt:z7.iso.datetime({offset:true}),fingerprint:sha});var LocalAgentMetadataAnswerSchema=z7.strictObject({summary:z7.string().trim().min(1).max(1500),observations:z7.array(z7.strictObject({key:z7.string().min(1).max(200),observed:z7.string().trim().min(1).max(1e3)})).min(1).max(64)});var LocalAgentPixelAnswerSchema=z7.strictObject({summary:z7.string().trim().min(1).max(1500),imageReadback:z7.string().trim().min(1).max(800),observations:z7.array(KeyframeObservationSchema.omit({region:true})).min(1).max(64)});var LocalAgentAnswerSchema=z7.union([LocalAgentMetadataAnswerSchema,LocalAgentPixelAnswerSchema]).refine(v=>new TextEncoder().encode(JSON.stringify(v)).length<=96*1024);var LocalAgentImageReceiptSchema=z7.strictObject({protocol:z7.literal("NVS_LOCAL_AGENT_IMAGE_V1"),draftId:z7.uuid(),media:ReviewEvidenceMediaSchema,byteSize:z7.int().positive().max(8388608),contentType:z7.literal("image/png"),width:z7.int().positive().max(4096),height:z7.int().positive().max(4096)});var LocalAgentReviewViewSchema=z7.strictObject({plan:LocalAgentPlanSchema,revision:z7.int().positive(),phase:z7.enum(["PREPARED","RUNNING","RESULT_PENDING","UNKNOWN"]),answer:LocalAgentAnswerSchema.nullable(),imageReceipt:LocalAgentImageReceiptSchema.optional(),provenance:z7.strictObject({adapter:z7.literal("CODEX_METADATA_V1"),binaryDigest:sha,version:qualifiedVersion,model:z7.string().max(100),reasoningEffort:z7.enum(["low","medium","high","xhigh"]).optional(),reviewerLabel:z7.string().max(100),inference:z7.literal("REMOTE_OPENAI"),evidence:z7.enum(["METADATA_ONLY","IMAGE_PIXELS"])})}).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;if(v.answer&&!!image!=="imageReadback"in v.answer)return false;const pixels=v.phase==="RESULT_PENDING"&&!!image;return v.provenance.evidence===(pixels?"IMAGE_PIXELS":"METADATA_ONLY")&&(!pixels||!!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.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:z8.string().length(64).regex(/^[0-9a-f]{64}$/).nullable().default(null),limit:z8.int().min(1).max(16).default(8)});var LocalIpcCallSchema=z8.discriminatedUnion("operation",[z8.strictObject({operation:z8.literal("agent.grant"),grant:LocalAgentGrantSchema,approval:z8.string().regex(/^[a-f0-9]{64}$/)}),z8.strictObject({operation:z8.literal("agent.probe")}),z8.strictObject({operation:z8.literal("agent.revoke"),approval:z8.string().regex(/^[a-f0-9]{64}$/)}),z8.strictObject({operation:z8.literal("agent.prepare"),snapshot:LocalAgentSnapshotSchema}),z8.strictObject({operation:z8.literal("agent.start"),id:z8.uuid(),expectedRevision:LocalRevisionSchema,approval:z8.string().regex(/^[a-f0-9]{64}$/)}),z8.strictObject({operation:z8.literal("agent.inspect"),id:z8.uuid()}),z8.strictObject({operation:z8.literal("runtime.status")}),z8.strictObject({operation:z8.literal("runtime.doctor")}),z8.strictObject({operation:z8.literal("runtime.inventory")}),z8.strictObject({operation:z8.literal("session.issue"),projects:z8.array(projectInput).min(1).max(100),expiresAt:z8.iso.datetime({offset:true})}),z8.strictObject({operation:z8.literal("runtime.stop"),expectedRuntimeRevision:LocalRevisionSchema}),z8.strictObject({operation:z8.literal("execution.inspect"),input:LocalWorkScopeSchema}),z8.strictObject({operation:z8.literal("execution.list"),input:LocalExecutionListInputSchema}),z8.strictObject({operation:z8.literal("update.check")}),z8.strictObject({operation:z8.literal("update.prepare"),targetVersion:LocalPackageVersionSchema,expectedRuntimeRevision:LocalRevisionSchema}),z8.strictObject({operation:z8.literal("update.apply"),planId:LocalIdSchema,targetVersion:LocalPackageVersionSchema,expectedRuntimeRevision:LocalRevisionSchema})]);var LocalNextActionSchema=z8.strictObject({call:LocalIpcCallSchema,availability:z8.enum(["AVAILABLE","BLOCKED"]),reason:z8.enum(["READY","INSTALL_REQUIRED","AUTHORIZATION_REQUIRED","VERSION_INCOMPATIBLE","UPDATE_AVAILABLE","RECOVERY_REQUIRED"])});var LocalIpcRequestSchema=z8.strictObject({protocol:z8.literal("NVS_LOCAL_IPC_V1"),requestId:LocalIdSchema,call:LocalIpcCallSchema});var LocalVersionReportSchema=z8.strictObject({component:z8.enum(["CLI","SDK","MCP","RUNTIME","MEDIA_TOOLS"]),installedVersion:LocalPackageVersionSchema.nullable(),runningVersion:LocalPackageVersionSchema.nullable(),availableVersion:LocalPackageVersionSchema.nullable(),executablePath:z8.string().min(1).max(4096).nullable(),installOwner:z8.enum(["NPM_GLOBAL","PROJECT","NPX","MANAGED","TARBALL","UNKNOWN"])});var LocalRuntimeStatusSchema=z8.strictObject({protocol:z8.literal("NVS_LOCAL_IPC_V1"),runtimeRevision:LocalRevisionSchema,state:z8.enum(["IDLE","EXECUTING","DRAINING","RECOVERY_REQUIRED"]),journalSchemaVersion:z8.literal(1),workProtocols:z8.array(z8.literal("NVS_LOCAL_WORK_V1")).min(1).max(1),versions:z8.array(LocalVersionReportSchema).max(8),authorizedProjects:z8.array(projectInput).max(100),nextActions:z8.array(LocalNextActionSchema).max(8)});var LocalDoctorReportSchema=z8.strictObject({mode:z8.enum(["MANAGED","INSTALLED"]),availability:z8.enum(["AVAILABLE","UNAVAILABLE"]),reason:z8.enum(["QUALIFIED_PROCESS_TOOLS","MANAGED_TOOLS_MISSING","TOOL_QUALIFICATION_FAILED"]),nativeExecutionReady:z8.boolean(),tools:z8.array(z8.strictObject({name:z8.enum(["FFMPEG","FFPROBE"]),path:z8.string().min(1).max(4096),version:z8.string().min(1).max(200),digest:z8.string().regex(/^[0-9a-f]{64}$/)})).max(2)});var LocalExecutionInspectionSchema=z8.strictObject({binding:LocalLeaseBindingSchema,revision:LocalRevisionSchema,phase:z8.enum(["STAGED","RUNNING","RECOVERY_REQUIRED","OUTPUT_PENDING","RECEIPT_RECORDED","FENCED"]),checkpoint:z8.enum(["ADOPTED","SOURCES_READY","PROCESS_STARTED","OUTPUT_STAGED"])});var LocalExecutionPageSchema=z8.strictObject({items:z8.array(LocalExecutionInspectionSchema).max(16),nextCursor:z8.string().length(64).regex(/^[0-9a-f]{64}$/).nullable()});var LocalIpcErrorCodeSchema=z8.enum(["FORBIDDEN","INVALID_INPUT","FRAME_LIMIT","BUSY","AUTHORIZATION_REQUIRED","REVISION_CONFLICT","CAPABILITY_UNAVAILABLE","INTERNAL_OPERATIONAL_FAILURE","AGENT_APPROVAL_REQUIRED","AGENT_GRANT_REQUIRED","AGENT_OUTCOME_UNKNOWN","AGENT_IMAGE_REQUIRED","AGENT_IMAGE_INVALID","AGENT_IMAGE_BUDGET_EXCEEDED","AGENT_IMAGE_AUTHORIZATION_REQUIRED"]);var LocalIpcResponseSchema=z8.discriminatedUnion("semanticStatus",[z8.strictObject({protocol:z8.literal("NVS_LOCAL_IPC_V1"),requestId:LocalIdSchema,semanticStatus:z8.literal("SUCCESS"),data:z8.union([LocalRuntimeStatusSchema,LocalDoctorReportSchema,LocalExecutionInspectionSchema.nullable(),z8.strictObject({state:z8.literal("DRAINING"),inventory:LocalManagementInventorySchema.optional(),backupPath:z8.string().min(1).max(4096).optional()}),LocalSessionConnectorSchema,LocalManagementInventorySchema,LocalExecutionPageSchema,LocalAgentProbeSchema,LocalAgentReviewViewSchema])}),z8.strictObject({protocol:z8.literal("NVS_LOCAL_IPC_V1"),requestId:LocalIdSchema.nullable(),semanticStatus:z8.enum(["BLOCKED","INVALID_INPUT"]),error:z8.strictObject({code:LocalIpcErrorCodeSchema})})]);import{z as z9}from"zod";var StartLocalPreviewSchema=RoughCutStartSchema.extend({placement:LocalPlacementPolicySchema});var LocalDeviceScopeSchema=z9.strictObject({tenantId:LocalIdSchema,deviceId:LocalIdSchema});var LocalDeviceSessionSchema=z9.strictObject({...LocalDeviceScopeSchema.shape,expiresAt:LocalTimeSchema,credential:z9.string().length(43).regex(/^[A-Za-z0-9_-]+$/).meta({writeOnly:true})});var LocalDeviceHeartbeatSchema=LocalDeviceScopeSchema.extend({toolchain:LocalToolchainSchema,available:z9.boolean()});var ClaimLocalPreviewSchema=LocalProjectScopeSchema.extend({requestId:LocalIdSchema,deviceId:LocalIdSchema});var LocalOutputStageSchema=LocalLeaseBindingSchema.extend({uploadRequestId:LocalIdSchema,role:z9.enum(["VIDEO","POSTER"]),checksumSha256:LocalDigestSchema,byteSize:z9.int().positive().max(128*1024*1024)});var LocalOutputTicketSchema=z9.strictObject({receiptId:LocalIdSchema,role:z9.enum(["VIDEO","POSTER"]),checksumSha256:LocalDigestSchema,byteSize:z9.int().positive(),uploaded:z9.boolean()});var LocalSourceRequestSchema=LocalLeaseBindingSchema.extend({representationId:LocalIdSchema});var LocalProofChallengeRequestSchema=LocalDeviceScopeSchema.extend({deviceRevision:z9.int().positive()});var LocalPreviewPlacementViewSchema=z9.strictObject({target:z9.enum(["DEVICE","SERVER"]),reason:z9.enum(["LOCAL_AVAILABLE","CLOUD_ONLY","OFFLINE","UNQUALIFIED","BUSY","LEASE_RECOVERY"]),policy:LocalPlacementPolicySchema});var LocalDeviceTransportConfigurationSchema=z9.strictObject({endpoint:z9.string().url().max(2048),tenantId:LocalIdSchema,deviceId:LocalIdSchema,deviceRevision:z9.int().positive(),projects:z9.array(LocalProjectScopeSchema).min(1).max(20),privateKeyFile:z9.string().min(1).max(4096),platform:LocalDevicePlatformSchema});var LocalPreviewAdmissionSchema=RoughCutAdmissionSchema.extend({placement:LocalPreviewPlacementViewSchema});var LocalClaimReceiptSchema=z9.strictObject({found:z9.boolean(),assignment:LocalWorkAssignmentSchema.nullable()});var LocalWorkStateSchema=z9.strictObject({binding:LocalLeaseBindingSchema,status:z9.enum(["ACTIVE","FENCED","OUTCOME_UNKNOWN"]),assignment:LocalWorkAssignmentSchema.nullable()});import{z as z10}from"zod";var LocalMcpToolNameSchema=z10.enum(["local_navigate","local_capability_describe","local_runtime_status","local_execution_list","local_execution_inspect","local_update_check"]);var LocalMcpActionSchema=z10.strictObject({tool:LocalMcpToolNameSchema,arguments:z10.record(z10.string(),z10.unknown()),availability:z10.enum(["AVAILABLE","BLOCKED"]).optional(),reason:z10.string().max(100).optional()});var LocalMcpNavigationSchema=z10.strictObject({location:z10.literal("LOCAL"),state:z10.enum(["UNAVAILABLE","IDLE","EXECUTING","DRAINING","RECOVERY_REQUIRED"]),authorizedProjects:z10.array(LocalProjectScopeSchema).max(100).optional(),groups:z10.array(z10.strictObject({id:z10.string().max(40),label:z10.string().max(100),tools:z10.array(LocalMcpToolNameSchema).max(6)})).max(4),nextActions:z10.array(z10.union([LocalMcpActionSchema,LocalClientNextActionSchema])).max(16)});var LocalMcpExecutionPageSchema=LocalExecutionPageSchema.extend({nextActions:z10.array(LocalMcpActionSchema).max(16)});var LocalMcpInspectionSchema=z10.strictObject({location:z10.literal("LOCAL"),execution:LocalExecutionInspectionSchema.nullable(),nextActions:z10.array(LocalMcpActionSchema).max(4)});var LocalMcpUpdateSchema=z10.strictObject({location:z10.literal("LOCAL"),running:z10.array(LocalVersionReportSchema).max(8),available:z10.array(LocalRuntimeDescriptorSchema).max(32),nextActions:z10.array(LocalClientNextActionSchema).max(4)});var LocalMcpDescriptionSchema=z10.strictObject({location:z10.literal("LOCAL"),tool:LocalMcpToolNameSchema,schema:z10.object({name:LocalMcpToolNameSchema,description:z10.string(),inputSchema:z10.record(z10.string(),z10.unknown())}).passthrough()});var LocalMcpFailureSchema=z10.strictObject({semanticStatus:z10.enum(["BLOCKED","INVALID_INPUT"]),error:z10.strictObject({code:z10.enum(["AUTHORIZATION_REQUIRED","FORBIDDEN","LOCAL_RUNTIME_UNAVAILABLE","RELEASE_UNAVAILABLE","VERSION_INCOMPATIBLE","INVALID_INPUT","LOCAL_CAPABILITY_UNAVAILABLE"]),outcome:z10.literal("NO_WRITE")}),nextActions:z10.array(LocalClientNextActionSchema).max(4)});var LocalMcpOutputSchemas={local_navigate:LocalMcpNavigationSchema,local_capability_describe:LocalMcpDescriptionSchema,local_runtime_status:LocalRuntimeStatusSchema.omit({nextActions:true}).extend({nextActions:z10.array(LocalMcpActionSchema).max(8)}),local_execution_list:LocalMcpExecutionPageSchema,local_execution_inspect:LocalMcpInspectionSchema,local_update_check:LocalMcpUpdateSchema};import{constants}from"node:fs";import{open as open2,realpath as realpath2}from"node:fs/promises";async function checkedLocalDirectory(path){await privateDirectory(path);return realpath2(path)}async function readLocalCredential(path,maximum=32768){await privateAccess(path,"file");const file=await open2(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()}}function localBudget(timeoutMs,parent){if(!Number.isInteger(timeoutMs)||timeoutMs<1||timeoutMs>6e4)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()})}async function stageAgentImage(options,view,input,signal){const budget=localBudget(options.timeoutMs??1e4,signal);let dispatched=false;try{budget.signal.throwIfAborted();if(input.byteLength>8388608)throw Error();const bytes=Buffer.from(input),snapshot=view.plan.snapshot,id=z11.uuid().parse(view.plan.id),requestId=randomUUID2();if(!snapshot.image||bytes.length!==snapshot.image.byteSize||bytes.length>8388608||createHash3("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":"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.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)||canonicalLocalJson({contentType:receipt.contentType,byteSize:receipt.byteSize,width:receipt.width,height:receipt.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()}}import{randomUUID as randomUUID3}from"node:crypto";import{request as request2}from"node:http";import{z as z12}from"zod";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){let started=false;const budget=localBudget(15e3,signal);try{const i=input.parse(raw);if(i.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",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?"LOCAL_COMMAND_UNKNOWN":"INVALID_INPUT",started?"BLOCKED":"INVALID_INPUT",started?"UNKNOWN":"NO_WRITE")}finally{budget.close()}}enroll(input,signal){return this.command("devices/enroll",input,EnrollLocalDeviceSchema,LocalDeviceViewSchema,signal)}grant(input,signal){return this.command("devices/grant",input,GrantLocalDeviceSchema,LocalDeviceGrantSchema,signal)}revokeDevice(input,signal){return this.command("devices/revoke",input,RevokeLocalDeviceSchema,z12.strictObject({semanticStatus:z12.literal("SUCCESS")}),signal)}revokeGrant(input,signal){return this.command("devices/revoke-grant",input,RevokeLocalDeviceGrantSchema,z12.strictObject({semanticStatus:z12.literal("SUCCESS")}),signal)}startPreview(input,signal){return this.command("previews",input,StartLocalPreviewSchema,LocalPreviewAdmissionSchema,signal)}};var NativeStudioLocalRuntimeClient=class _NativeStudioLocalRuntimeClient{constructor(options){this.options=options}options;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.inspect"].includes(call.operation);try{const input=LocalIpcRequestSchema.parse({protocol:"NVS_LOCAL_IPC_V1",requestId:randomUUID3(),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){const value=this.response(LocalRuntimeStatusSchema,await this.call({operation:"runtime.status"},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 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(this.options.timeoutMs??1e4,signal);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=LocalWorkScopeSchema.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}};export{EnrollLocalDeviceSchema,GrantLocalDeviceSchema,LocalAgentGrantSchema,LocalAgentSnapshotSchema,LocalClientNextActionSchema,LocalSessionConnectorSchema as LocalConnectorSchema,LocalDeviceTransportConfigurationSchema,LocalDoctorReportSchema,LocalExecutionListInputSchema,LocalExecutionPageSchema,LocalManagementInventorySchema,LocalMcpFailureSchema,LocalMcpOutputSchemas,LocalReleaseSchema,LocalRuntimeDescriptorSchema,LocalSessionConnectorSchema,LocalSignedCatalogueSchema,LocalToolChoiceSchema,LocalToolSelectionSchema,LocalUpdatePlanSchema,LocalWorkScopeSchema,NativeStudioLocalDeviceClient,NativeStudioLocalRuntimeClient,NativeStudioSdkError,RevokeLocalDeviceGrantSchema,RevokeLocalDeviceSchema,StartLocalPreviewSchema,canonicalLocalJson,localAgentNativeProposal,localAgentSnapshotFromContext};
|
|
1
|
+
import{CaptionRenderStyleSchema,FinalRenderAdmissionSchema,FinalRenderManifestReaderSchema,FinalRenderStartSchema,KeyframeObservationSchema,NativeRuntimePublicKeySchema,ReviewEvidenceMediaSchema,ReviewIntelligenceBasisSchema,ReviewIntelligenceContextResultSchema,RoughCutAdmissionSchema,RoughCutManifestReaderSchema,RoughCutRequirementSchema,RoughCutStartSchema,RoughCutTechnicalSchema,ValidateReviewIntelligenceSchema,VideoReviewRequirementSchema,VideoTechnicalMetadataSchema,VisualLayerCompositionSchema,VisualRequirementSchema}from"./_chunks/chunk-NSS2BKVM.js";import{OperationIdSchema}from"./_chunks/chunk-4M3AGNTZ.js";import{NativeStudioSdkError}from"./_chunks/chunk-6NVIN2NI.js";import{lstat as lstat2,mkdir,open,rename,link,unlink}from"node:fs/promises";import{dirname,isAbsolute as isAbsolute2,join as join2}from"node:path";import{createHash as createHash2}from"node:crypto";import{execFile,spawn}from"node:child_process";import{once}from"node:events";import{readFile,realpath,lstat}from"node:fs/promises";import{createHash,randomUUID}from"node:crypto";import{fileURLToPath}from"node:url";import{join,win32,isAbsolute}from"node:path";var nativeAssetNames=["Bootstrap.ps1","NativeMain.cs","PrivateAccess.cs","PipeBridge.cs","JobNative.cs","JobRunner.cs"];var executable;var assetDirectory;async function windowsHelper(){if(process.platform!=="win32"||process.arch!=="x64")throw Error("WINDOWS_PLATFORM_REQUIRED");return executable??=bootstrap().catch(error=>{executable=void 0;throw error})}async function bootstrap(){const directory=assetDirectory??fileURLToPath(new URL("./dist/native/",import.meta.resolve("@nativestudio/sdk/package.json")));const hash=createHash("sha256");for(const name of nativeAssetNames){hash.update(name+"\n");hash.update(await readFile(join(directory,name)))}const sourceDigest=hash.digest("hex"),system=process.env.SystemRoot??process.env.SYSTEMROOT;if(!system||!win32.isAbsolute(system)||system.startsWith("\\\\"))throw Error("WINDOWS_SYSTEM_UNAVAILABLE");const shell=join(system,"System32/WindowsPowerShell/v1.0/powershell.exe"),script=(await readFile(join(directory,"Bootstrap.ps1"))).toString("utf8");const result=await new Promise((resolve,reject)=>{const child=execFile(shell,["-NoLogo","-NoProfile","-NonInteractive","-EncodedCommand",Buffer.from(script,"utf16le").toString("base64")],{timeout:15e3,maxBuffer:32768,windowsHide:true},(error,stdout)=>error?reject(Error("WINDOWS_HELPER_UNAVAILABLE")):resolve(stdout));child.stdin.on("error",()=>{});child.stdin.end(JSON.stringify({directory,sourceDigest}))});const value=JSON.parse(result);if(value.sourceDigest!==sourceDigest||!/^[a-f0-9]{64}$/.test(value.sha256)||!win32.isAbsolute(value.path))throw Error("WINDOWS_HELPER_INVALID");const path=await realpath(value.path),stat=await lstat(path);if(!stat.isFile()||stat.isSymbolicLink()||stat.nlink!==1||stat.size>2*1024*1024||createHash("sha256").update(await readFile(path)).digest("hex")!==value.sha256)throw Error("WINDOWS_HELPER_INVALID");return path}var service;async function connection(){return service??=(async()=>{const child=spawn(await windowsHelper(),["service",String(process.pid)],{shell:false,windowsHide:true,stdio:["pipe","pipe","pipe"]});const pending=new Map;let bytes=Buffer.alloc(0),stderr=0;const close=()=>{for(const item of pending.values()){clearTimeout(item.timer);item.reject(Error("WINDOWS_HELPER_UNAVAILABLE"))}pending.clear();service=void 0};child.stdout.on("data",part=>{bytes=Buffer.concat([bytes,part]);if(bytes.length>2*1024*1024)return child.kill();for(;;){const end=bytes.indexOf(10);if(end<0)break;const line=bytes.subarray(0,end);bytes=bytes.subarray(end+1);try{const value=JSON.parse(line.toString());const item=pending.get(value.id);if(!item)continue;pending.delete(value.id);clearTimeout(item.timer);if(value.ok)item.resolve(value.data);else item.reject(Error(["EXISTS","RESOURCE_BUDGET_EXCEEDED"].includes(value.error??"")?value.error:"WINDOWS_ACCESS_DENIED"))}catch{child.kill()}}});child.stderr.on("data",b=>{if((stderr+=b.length)>65536)child.kill()});child.on("error",close);child.on("close",close);child.stdin.on("error",close);await once(child,"spawn");child.unref();child.stdout.unref();child.stderr.unref();child.stdin.unref();return{child,pending}})().catch(error=>{service=void 0;throw error})}async function windowsRequest(request3,timeoutMs=1e4,signal){signal?.throwIfAborted();const{child,pending}=await connection();signal?.throwIfAborted();if(child.exitCode!==null||child.signalCode!==null||child.stdin.destroyed)throw Error("WINDOWS_HELPER_UNAVAILABLE");if(pending.size>=32)throw Error("WINDOWS_HELPER_BUSY");const id=randomUUID(),data=JSON.stringify({...request3,id});if(Buffer.byteLength(data)>1024*1024)throw Error("WINDOWS_HELPER_INPUT_LIMIT");return new Promise((resolve,reject)=>{const abort=()=>{child.stdin.write(JSON.stringify({operation:"cancel",target:id})+"\n")};const timer=setTimeout(()=>{abort();pending.delete(id);signal?.removeEventListener("abort",abort);reject(Error("WINDOWS_HELPER_TIMEOUT"))},timeoutMs);pending.set(id,{timer,resolve:v=>{signal?.removeEventListener("abort",abort);resolve(v)},reject:e=>{signal?.removeEventListener("abort",abort);reject(e)}});signal?.addEventListener("abort",abort,{once:true});child.stdin.write(data+"\n");if(signal?.aborted)abort()})}function localSocketPath(root,platform=process.platform){if(platform!=="win32")return join2(root,"runtime.sock");return"\\\\.\\pipe\\nvs-"+createHash2("sha256").update(root.toLowerCase()).digest("hex")}async function privateAccess(path,kind){if(process.platform==="win32"){if(kind!=="pipe")await lstat2(path);await windowsRequest({operation:"check",path,kind});return}const s=await lstat2(path);if(s.isSymbolicLink()||s.uid!==process.getuid?.()||s.mode&63||(kind==="directory"?!s.isDirectory():kind==="pipe"?!s.isSocket():!s.isFile()))throw Error("LOCAL_PERMISSIONS_INVALID")}async function privateDirectory(path,create=false){if(!isAbsolute2(path)||!["win32","darwin","linux"].includes(process.platform))throw Error("LOCAL_LOCATION_INVALID");if(process.platform==="win32")await windowsRequest({operation:create?"directory":"check",path,kind:"directory"});else{if(create)await mkdir(path,{recursive:true,mode:448});await privateAccess(path,"directory")}}import{spawn as spawn2}from"node:child_process";import{Duplex}from"node:stream";import{randomUUID as randomUUID2,createHash as createHash3}from"node:crypto";import{request}from"node:http";import{z as z17}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"])})]);import{z as z2}from"zod";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 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"})});import{z as z5}from"zod";var output=z5.discriminatedUnion("role",[z5.strictObject({role:z5.literal("VIDEO"),receiptId:LocalIdSchema,checksumSha256:LocalDigestSchema,byteSize:z5.int().positive().max(128*1024*1024),contentType:z5.literal("video/mp4")}),z5.strictObject({role:z5.literal("POSTER"),receiptId:LocalIdSchema,checksumSha256:LocalDigestSchema,byteSize:z5.int().positive().max(2*1024*1024),contentType:z5.literal("image/png")})]);var LocalCompletionSubmissionSchema=LocalLeaseBindingSchema.extend({requestId:LocalIdSchema,outputs:z5.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=z5.strictObject({binding:LocalLeaseBindingSchema,output,verifiedAt:LocalTimeSchema});var LocalCompletionReceiptSchema=LocalLeaseBindingSchema.extend({submissionFingerprint:LocalDigestSchema.optional(),semanticStatus:z5.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});import{z as z13}from"zod";import{z as z6}from"zod";var LocalOfflineSnapshotSchema=z6.strictObject({projectId:z6.uuid(),title:z6.string().min(1).max(200),savedAt:LocalTimeSchema,expiresAt:LocalTimeSchema,productions:z6.array(z6.strictObject({id:z6.uuid(),title:z6.string().max(200)})).max(40),possiblyTruncated:z6.boolean()}).refine(v=>new TextEncoder().encode(JSON.stringify(v)).length<=8192);var text=z6.string().max(4e3).refine(v=>new TextEncoder().encode(JSON.stringify(v)).length<=8192);var LocalOfflineCallSchema=z6.discriminatedUnion("action",[z6.strictObject({action:z6.enum(["list","forget"]),key:LocalDigestSchema}),z6.strictObject({action:z6.literal("retain"),key:LocalDigestSchema,snapshot:LocalOfflineSnapshotSchema}),z6.strictObject({action:z6.literal("draft"),key:LocalDigestSchema,projectId:z6.uuid(),text,expectedRevision:z6.int().nonnegative()})]);var LocalOfflinePageSchema=z6.strictObject({historical:z6.literal(true),items:z6.array(z6.strictObject({snapshot:LocalOfflineSnapshotSchema,draft:z6.strictObject({text,revision:z6.int().nonnegative()})})).max(3)});import{z as z8}from"zod";import{z as z7}from"zod";var QualifiedLocalAgentVersionSchema=z7.enum(["0.164.0","0.165.0"]);var LocalAgentGrantSchema=z7.strictObject({protocol:z7.literal("NVS_CODEX_REVIEW_GRANT_V1"),binary:z7.string().min(1).max(4096).refine(v=>/^(?:\/|[A-Za-z]:[\\/])/.test(v)),binaryDigest:z7.string().regex(/^[a-f0-9]{64}$/),version:QualifiedLocalAgentVersionSchema,model:z7.string().regex(/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,99}$/),reasoningEffort:z7.enum(["low","medium","high","xhigh"]).optional(),reviewerLabel:z7.string().trim().min(1).max(100),inference:z7.literal("REMOTE_OPENAI"),remoteUseApproved:z7.literal(true),imageDisclosureApproved:z7.literal(true).optional(),mediaDisclosureApproved:z7.literal(true).optional(),projects:z7.array(LocalProjectScopeSchema).min(1).max(100),expiresAt:z7.iso.datetime({offset:true})});var LocalAgentMediaInputSchema=z8.strictObject({profile:z8.literal("NVS_AGENT_DERIVED_EVIDENCE_V1"),contentType:z8.enum(["image/png","image/jpeg","image/webp","video/mp4"]),byteSize:z8.int().positive().max(134217728),width:z8.int().positive().max(4096),height:z8.int().positive().max(4096),durationMs:z8.int().positive().max(6e4).optional(),frameRate:z8.union([z8.literal(24),z8.literal(30)]).optional(),hasAudio:z8.boolean().optional()}).refine(v=>v.contentType==="video/mp4"?!!v.durationMs&&!!v.frameRate:!v.durationMs&&!v.frameRate&&v.hasAudio===void 0);var sha=z8.string().regex(/^[a-f0-9]{64}$/);var LocalAgentEvidenceReceiptSchema=z8.strictObject({protocol:z8.literal("NVS_AGENT_DERIVED_EVIDENCE_V1"),draftId:z8.uuid(),media:ReviewEvidenceMediaSchema,ffmpegDigest:sha,ffprobeDigest:sha,attachment:z8.strictObject({checksumSha256:sha,byteSize:z8.int().positive().max(8388608),width:z8.int().positive().max(4096),height:z8.int().positive().max(4096)}),timestampsMs:z8.array(z8.number().nonnegative().max(6e4)).max(6),audio:z8.strictObject({sampleRateHz:z8.literal(48e3),channels:z8.literal(1),samples:z8.int().positive().max(2881024),peak:z8.number().min(0).max(1),rms:z8.number().min(0).max(1),clippedSamples:z8.int().nonnegative().max(2881024)}).nullable(),limitations:z8.tuple([z8.literal("SAMPLED_FRAMES_ARE_NOT_FULL_PLAYBACK"),z8.literal("AUDIO_STATISTICS_ARE_NOT_LISTENING_OR_TRANSCRIPTION")])});var LocalAgentDiscoverySchema=z8.strictObject({candidate:z8.strictObject({binary:z8.string().min(1).max(4096),binaryDigest:sha,version:z8.string().regex(/^\d+\.\d+\.\d+$/),qualified:z8.boolean()}).nullable(),configured:LocalAgentGrantSchema.nullable()});import{z as z10}from"zod";import{z as z9}from"zod";var executable2=z9.strictObject({path:z9.string().min(1).max(4096),digest:LocalDigestSchema});var LocalToolSelectionSchema=z9.strictObject({mode:z9.enum(["MANAGED","INSTALLED"]),ffmpeg:executable2,ffprobe:executable2});var LocalRuntimeDescriptorSchema=z10.strictObject({protocol:z10.literal("NVS_RUNTIME_DESCRIPTOR_V1"),version:LocalPackageVersionSchema,node:z10.strictObject({major:z10.literal(24),minMinor:z10.literal(12)}),platform:LocalDevicePlatformSchema,ipcProtocol:z10.literal("NVS_LOCAL_IPC_V1"),workProtocol:z10.enum(["NVS_LOCAL_WORK_V1","NVS_LOCAL_WORK_V2"]),journalSchema:z10.literal(1),rendererDigest:LocalDigestSchema,profileDigest:LocalDigestSchema,compatibleRenderers:z10.array(z10.strictObject({rendererDigest:LocalDigestSchema,profileDigest:LocalDigestSchema})).max(4).optional()});var LocalSessionConnectorSchema=z10.strictObject({protocol:z10.literal("NVS_LOCAL_CONNECTOR_V1"),stateDirectory:z10.string().min(1).max(4096),credential:z10.string().length(43).regex(/^[A-Za-z0-9_-]{43}$/),expiresAt:LocalTimeSchema,projects:z10.array(LocalProjectScopeSchema).min(1).max(100)});var LocalManagementInventorySchema=z10.strictObject({runtimeRevision:z10.int().positive(),descriptor:LocalRuntimeDescriptorSchema,activeProcesses:z10.int().nonnegative(),pendingExecutions:z10.int().nonnegative(),pendingRequests:z10.int().nonnegative(),pendingRenderers:z10.array(LocalDigestSchema).max(64)});var LocalReleaseAssetSchema=z10.strictObject({url:z10.string().url().max(2048),byteSize:z10.int().positive().max(256*1024*1024),sha512:z10.string().length(128).regex(/^[0-9a-f]{128}$/)});var LocalReleaseSchema=z10.strictObject({descriptor:LocalRuntimeDescriptorSchema,package:LocalReleaseAssetSchema,tools:z10.strictObject({ffmpeg:LocalReleaseAssetSchema.extend({sha256:LocalDigestSchema}),ffprobe:LocalReleaseAssetSchema.extend({sha256:LocalDigestSchema})}).nullable()});var LocalReleaseCatalogueSchema=z10.strictObject({protocol:z10.literal("NVS_LOCAL_RELEASE_CATALOGUE_V1"),issuedAt:LocalTimeSchema,expiresAt:LocalTimeSchema,releases:z10.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=z10.strictObject({catalogue:LocalReleaseCatalogueSchema,signature:z10.string().length(86).regex(/^[A-Za-z0-9_-]{85}[AQgw]$/)});var LocalToolChoiceSchema=z10.discriminatedUnion("mode",[z10.strictObject({mode:z10.literal("MANAGED")}),LocalToolSelectionSchema.extend({mode:z10.literal("INSTALLED")})]);var LocalUpdatePlanSchema=z10.strictObject({protocol:z10.literal("NVS_LOCAL_UPDATE_PLAN_V1"),planId:LocalIdSchema,installationRevision:z10.int().nonnegative(),runtimeRevision:z10.int().positive().nullable(),catalogueFingerprint:LocalDigestSchema,trustFingerprint:LocalDigestSchema.optional(),release:LocalReleaseSchema,toolSelection:LocalToolChoiceSchema.optional(),fingerprint:LocalDigestSchema,createdAt:LocalTimeSchema,expiresAt:LocalTimeSchema});var LocalClientNextActionSchema=z10.strictObject({surface:z10.enum(["CLI","LOCAL_IPC","REMOTE"]),operation:z10.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:z10.enum(["AVAILABLE","BLOCKED"]),reason:z10.enum(["READY","INSTALL_REQUIRED","AUTHORIZATION_REQUIRED","VERSION_INCOMPATIBLE","UPDATE_AVAILABLE","RECOVERY_REQUIRED","USER_APPROVAL_REQUIRED","TRUST_REQUIRED","UNAVAILABLE"])});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})})]);import{z as z14}from"zod";var StartLocalPreviewSchema=RoughCutStartSchema.omit({deviceExecution:true}).extend({placement:LocalPlacementPolicySchema,localProfile:z14.literal("STUDIO_MEDIA_V2").optional()});var LocalDeviceScopeSchema=z14.strictObject({tenantId:LocalIdSchema,deviceId:LocalIdSchema});var LocalDeviceSessionSchema=z14.strictObject({...LocalDeviceScopeSchema.shape,expiresAt:LocalTimeSchema,credential:z14.string().length(43).regex(/^[A-Za-z0-9_-]+$/).meta({writeOnly:true})});var LocalDeviceHeartbeatSchema=LocalDeviceScopeSchema.extend({toolchain:LocalToolchainSchema,available:z14.boolean(),maxConcurrentJobs:z14.int().min(1).max(2).optional()});var ClaimLocalPreviewSchema=LocalProjectScopeSchema.extend({requestId:LocalIdSchema,deviceId:LocalIdSchema});var LocalOutputStageSchema=LocalLeaseBindingSchema.extend({uploadRequestId:LocalIdSchema,role:z14.enum(["VIDEO","POSTER"]),checksumSha256:LocalDigestSchema,byteSize:z14.int().positive().max(128*1024*1024)});var LocalOutputTicketSchema=z14.strictObject({receiptId:LocalIdSchema,role:z14.enum(["VIDEO","POSTER"]),checksumSha256:LocalDigestSchema,byteSize:z14.int().positive(),uploaded:z14.boolean()});var LocalSourceRequestSchema=LocalLeaseBindingSchema.extend({representationId:LocalIdSchema});var LocalProofChallengeRequestSchema=LocalDeviceScopeSchema.extend({deviceRevision:z14.int().positive()});var LocalPreviewPlacementViewSchema=z14.strictObject({target:z14.enum(["DEVICE","SERVER"]),reason:z14.enum(["LOCAL_AVAILABLE","CLOUD_ONLY","OFFLINE","UNQUALIFIED","BUSY","LEASE_RECOVERY"]),policy:LocalPlacementPolicySchema});var LocalDeviceTransportConfigurationSchema=z14.strictObject({endpoint:z14.string().url().max(2048),tenantId:LocalIdSchema,deviceId:LocalIdSchema,deviceRevision:z14.int().positive(),projects:z14.array(LocalProjectScopeSchema).min(1).max(20),privateKeyFile:z14.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=z14.strictObject({found:z14.boolean(),assignment:LocalWorkAssignmentSchema.nullable()});var LocalWorkStateSchema=z14.strictObject({binding:LocalLeaseBindingSchema,status:z14.enum(["ACTIVE","FENCED","OUTCOME_UNKNOWN"]),assignment:LocalWorkAssignmentSchema.nullable()});import{z as z15}from"zod";var LocalMcpToolNameSchema=z15.enum(["local_navigate","local_capability_describe","local_runtime_status","local_execution_list","local_execution_inspect","local_update_check"]);var LocalMcpActionSchema=z15.strictObject({tool:LocalMcpToolNameSchema,arguments:z15.record(z15.string(),z15.unknown()),availability:z15.enum(["AVAILABLE","BLOCKED"]).optional(),reason:z15.string().max(100).optional()});var LocalMcpNavigationSchema=z15.strictObject({location:z15.literal("LOCAL"),state:z15.enum(["UNAVAILABLE","IDLE","EXECUTING","DRAINING","RECOVERY_REQUIRED"]),authorizedProjects:z15.array(LocalProjectScopeSchema).max(100).optional(),groups:z15.array(z15.strictObject({id:z15.string().max(40),label:z15.string().max(100),tools:z15.array(LocalMcpToolNameSchema).max(6)})).max(4),nextActions:z15.array(z15.union([LocalMcpActionSchema,LocalClientNextActionSchema])).max(16)});var LocalMcpExecutionPageSchema=LocalExecutionPageSchema.extend({nextActions:z15.array(LocalMcpActionSchema).max(16)});var LocalMcpInspectionSchema=z15.strictObject({location:z15.literal("LOCAL"),execution:LocalExecutionInspectionSchema.nullable(),nextActions:z15.array(LocalMcpActionSchema).max(4)});var LocalMcpUpdateSchema=z15.strictObject({location:z15.literal("LOCAL"),running:z15.array(LocalVersionReportSchema).max(8),available:z15.array(LocalRuntimeDescriptorSchema).max(32),nextActions:z15.array(LocalClientNextActionSchema).max(4)});var LocalMcpDescriptionSchema=z15.strictObject({location:z15.literal("LOCAL"),tool:LocalMcpToolNameSchema,schema:z15.object({name:LocalMcpToolNameSchema,description:z15.string(),inputSchema:z15.record(z15.string(),z15.unknown())}).passthrough()});var LocalMcpFailureSchema=z15.strictObject({semanticStatus:z15.enum(["BLOCKED","INVALID_INPUT"]),error:z15.strictObject({code:z15.enum(["AUTHORIZATION_REQUIRED","FORBIDDEN","LOCAL_RUNTIME_UNAVAILABLE","RELEASE_UNAVAILABLE","VERSION_INCOMPATIBLE","INVALID_INPUT","LOCAL_CAPABILITY_UNAVAILABLE"]),outcome:z15.literal("NO_WRITE")}),nextActions:z15.array(LocalClientNextActionSchema).max(4)});var LocalMcpOutputSchemas={local_navigate:LocalMcpNavigationSchema,local_capability_describe:LocalMcpDescriptionSchema,local_runtime_status:LocalRuntimeStatusSchema.omit({nextActions:true}).extend({nextActions:z15.array(LocalMcpActionSchema).max(8)}),local_execution_list:LocalMcpExecutionPageSchema,local_execution_inspect:LocalMcpInspectionSchema,local_update_check:LocalMcpUpdateSchema};function localAgentMediaSnapshot(raw){const c=ReviewIntelligenceContextResultSchema.parse(raw),r=c.reviewTarget,t=r.target,scope=c.basis.scope;if(c.ownerContext.semanticStatus!=="SUCCESS"||!t.productionRunnable||t.freshness!=="CURRENT_BASIS"||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||r.kind!==c.basis.target.kind)throw Error("LOCAL_AGENT_CONTEXT_UNAVAILABLE");let media,descriptor;if(r.kind==="ROUGH_CUT"){if(!r.target.inspectable||c.basis.target.kind!=="ROUGH_CUT"||r.target.renderId!==c.basis.target.renderId)throw Error("LOCAL_AGENT_CONTEXT_UNAVAILABLE");media=r.target.basis;descriptor={...r.target.technical,contentType:"video/mp4"}}else if(r.kind==="PROGRAMMATIC"){if(!r.target.runtimeSucceeded||r.target.media.availability!=="AVAILABLE"||c.basis.target.kind!=="PROGRAMMATIC"||r.target.renderId!==c.basis.target.renderId)throw Error("LOCAL_AGENT_CONTEXT_UNAVAILABLE");media=r.target.media;descriptor=r.target.media}else{if(!r.target.runtimeSucceeded||r.target.candidate.availability!=="AVAILABLE"||r.target.candidate.freshness!=="CURRENT_BASIS"||!("generationId"in c.basis.target)||r.target.generationId!==c.basis.target.generationId)throw Error("LOCAL_AGENT_CONTEXT_UNAVAILABLE");media=r.target.candidate;descriptor=r.target.candidate}const video=descriptor.contentType==="video/mp4";return LocalAgentSnapshotSchema.parse({basis:c.basis,productionRevision:c.ownerContext.basis.productionRevision,reviewVersion:t.reviewVersion,executionClass:t.executionClass,media:{artifactId:media.artifactId,representationId:media.representationId,checksumSha256:media.checksumSha256},requirements:t.requirements,evidence:{profile:"NVS_AGENT_DERIVED_EVIDENCE_V1",contentType:descriptor.contentType,byteSize:descriptor.byteSize,width:descriptor.width,height:descriptor.height,...video&&"durationMs"in descriptor?{durationMs:descriptor.durationMs,frameRate:descriptor.frameRate,hasAudio:descriptor.hasAudio}:{}}})}function localAgentMediaProposal(raw){const v=LocalAgentReviewViewSchema.parse(raw),s=v.plan.snapshot;if(!s.evidence)return localAgentNativeProposal(v);if(v.phase!=="RESULT_PENDING"||!v.answer||!v.evidenceReceipt||s.basis.target.kind==="ROUGH_CUT")throw Error("LOCAL_AGENT_FULL_TEMPORAL_INSPECTION_REQUIRED");const video=s.evidence.contentType==="video/mp4",id=video?"sampled_frames":"normalized_image";return ValidateReviewIntelligenceSchema.parse({basis:s.basis,proposal:{origin:{kind:"EXTERNAL_AGENT_HOST",label:v.provenance.reviewerLabel},summary:`Advisory ${video?"six sampled frames; no full playback, listening or transcription":"normalized original image"}. Source ${s.media.checksumSha256}; attachment ${v.evidenceReceipt.attachment.checksumSha256}; draft ${v.plan.id}. ${v.answer.summary}`,evidence:[{id,label:video?"Six ordered verified source frame samples":"Verified normalized source image",producer:"EXTERNAL_AGENT_HOST",media:s.media,...video?{kind:"VIDEO_FRAMES",timestampsMs:v.evidenceReceipt.timestampsMs}:{kind:"IMAGE_PIXELS"}}],review:{kind:s.basis.target.kind,observations:v.answer.observations.map(o=>{const requirement=s.requirements.find(r=>r.key===o.key);const unsupported="family"in requirement&&requirement.family==="SOUND"||"continuity"in requirement&&!!requirement.continuity;return{...o,status:unsupported?"NOT_OBSERVABLE":"status"in o?o.status:"NOT_OBSERVABLE",confidence:unsupported?"UNCERTAIN":"confidence"in o?o.confidence:"UNCERTAIN",evidenceIds:unsupported?[]:[id],..."interval"in requirement&&requirement.interval?{interval:requirement.interval}:{}}})}}})}import{z as z16}from"zod";var LocalManagementCommandSchema=z16.discriminatedUnion("kind",[z16.strictObject({kind:z16.literal("ENROLL"),input:EnrollLocalDeviceSchema}),z16.strictObject({kind:z16.literal("GRANT"),input:GrantLocalDeviceSchema}),z16.strictObject({kind:z16.literal("REVOKE_GRANT"),input:RevokeLocalDeviceGrantSchema}),z16.strictObject({kind:z16.literal("PREVIEW"),input:StartLocalPreviewSchema}),z16.strictObject({kind:z16.literal("FINAL_RENDER"),input:StartLocalFinalRenderSchema})]);var LocalManagementResultSchema=z16.union([LocalDeviceViewSchema,LocalDeviceGrantSchema,LocalPreviewAdmissionSchema,LocalFinalRenderAdmissionSchema,z16.strictObject({semanticStatus:z16.literal("SUCCESS")})]);var LocalManagementReceiptSchema=z16.strictObject({fingerprint:z16.string().regex(/^[a-f0-9]{64}$/),result:LocalManagementResultSchema.nullable()});var localManagementRoutes={ENROLL:"devices/enroll",GRANT:"devices/grant",REVOKE_GRANT:"devices/revoke-grant",PREVIEW:"previews",FINAL_RENDER:"final-renders"};import{constants}from"node:fs";import{open as open2,realpath as realpath2}from"node:fs/promises";async function checkedLocalDirectory(path){await privateDirectory(path);return realpath2(path)}async function readLocalCredential(path,maximum=32768){await privateAccess(path,"file");const file=await open2(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()}}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()})}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=z17.uuid().parse(view.plan.id),requestId=randomUUID2();if(!snapshot.image&&!snapshot.evidence||bytes.length!==(snapshot.evidence??snapshot.image).byteSize||bytes.length>(snapshot.evidence?134217728:8388608)||createHash3("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 randomUUID3}from"node:crypto";import{request as request2}from"node:http";import{z as z18}from"zod";import{createHash as createHash4}from"node:crypto";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!==createHash4("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,z18.strictObject({semanticStatus:z18.literal("SUCCESS")}),signal)}revokeGrant(input,signal){return this.command("devices/revoke-grant",input,RevokeLocalDeviceGrantSchema,z18.strictObject({semanticStatus:z18.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)}};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:randomUUID3(),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}};export{EnrollLocalDeviceSchema,GrantLocalDeviceSchema,LocalAgentDiscoverySchema,LocalAgentGrantSchema,LocalAgentProbeSchema,LocalAgentReviewViewSchema,LocalAgentSnapshotSchema,LocalClientNextActionSchema,LocalSessionConnectorSchema as LocalConnectorSchema,LocalDeviceChallengeSchema,LocalDeviceGrantSchema,LocalDeviceSessionSchema,LocalDeviceTransportConfigurationSchema,LocalDeviceViewSchema,LocalDiagnosticsSchema,LocalDoctorReportSchema,LocalExecutionInspectInputSchema,LocalExecutionListInputSchema,LocalExecutionPageSchema,LocalExecutionProgressSchema,LocalFinalRenderAdmissionSchema,LocalManagementCommandSchema,LocalManagementInventorySchema,LocalManagementReceiptSchema,LocalManagementResultSchema,LocalMcpFailureSchema,LocalMcpOutputSchemas,LocalOfflineCallSchema,LocalOfflinePageSchema,LocalPreviewAdmissionSchema,LocalReleaseSchema,LocalResourcePolicySchema,LocalResourceSettingsSchema,LocalRuntimeDescriptorSchema,LocalSessionConnectorSchema,LocalSignedCatalogueSchema,LocalStorageInspectionSchema,LocalToolChoiceSchema,LocalToolSelectionSchema,LocalUpdatePlanSchema,LocalWorkScopeSchema,LocalWorkspaceInspectionSchema,NativeStudioLocalDeviceClient,NativeStudioLocalRuntimeClient,NativeStudioLocalWorkspaceClient,NativeStudioSdkError,RevokeLocalDeviceGrantSchema,RevokeLocalDeviceSchema,StartLocalFinalRenderSchema,StartLocalPreviewSchema,canonicalLocalJson,localAgentMediaProposal,localAgentMediaSnapshot,localAgentNativeProposal,localAgentSnapshotFromContext,localManagementRoutes};
|
package/dist/native/JobNative.cs
CHANGED
|
@@ -104,6 +104,16 @@ namespace NativeStudio.Platform
|
|
|
104
104
|
}
|
|
105
105
|
catch { CloseHandle(job); throw; }
|
|
106
106
|
}
|
|
107
|
+
public static void Budget(IntPtr job, double cores, ulong memory)
|
|
108
|
+
{
|
|
109
|
+
var limits = new ExtendedLimits();
|
|
110
|
+
limits.basic.flags = 0x2000 | 0x200 | 8 | 0x20;
|
|
111
|
+
limits.jobMemory = new UIntPtr(memory);
|
|
112
|
+
limits.basic.active = 64;
|
|
113
|
+
limits.basic.priority = 0x4000;
|
|
114
|
+
Set(job, 9, limits);
|
|
115
|
+
Set(job, 15, new CpuLimits { flags = 5, rate = (uint)Math.Min(10000, Math.Max(1, cores * 10000 / Environment.ProcessorCount)) });
|
|
116
|
+
}
|
|
107
117
|
public static uint[] Processes(IntPtr job)
|
|
108
118
|
{
|
|
109
119
|
int size = 8 + 64 * IntPtr.Size;
|
package/dist/native/JobRunner.cs
CHANGED
|
@@ -15,6 +15,10 @@ namespace NativeStudio.Platform
|
|
|
15
15
|
static readonly object Sync = new object();
|
|
16
16
|
static readonly Dictionary<string, IntPtr> Jobs = new Dictionary<string, IntPtr>();
|
|
17
17
|
static readonly HashSet<string> Cancelled = new HashSet<string>();
|
|
18
|
+
static readonly Dictionary<string, double> Cpus = new Dictionary<string, double>();
|
|
19
|
+
static readonly Dictionary<string, ulong> Memories = new Dictionary<string, ulong>();
|
|
20
|
+
static readonly HashSet<string> Exceeded = new HashSet<string>();
|
|
21
|
+
static ulong memoryBudget = 4294967296UL;
|
|
18
22
|
static IntPtr aggregate;
|
|
19
23
|
static Process parent;
|
|
20
24
|
static bool closed;
|
|
@@ -40,8 +44,18 @@ namespace NativeStudio.Platform
|
|
|
40
44
|
{
|
|
41
45
|
Jobs.Remove(id);
|
|
42
46
|
Cancelled.Remove(id);
|
|
47
|
+
Exceeded.Remove(id);
|
|
48
|
+
Cpus.Remove(id);
|
|
49
|
+
Memories.Remove(id);
|
|
50
|
+
ApplyBudget();
|
|
43
51
|
}
|
|
44
52
|
}
|
|
53
|
+
static void ApplyBudget()
|
|
54
|
+
{
|
|
55
|
+
memoryBudget = Memories.Count == 0 ? 4294967296UL : Memories.Values.Min();
|
|
56
|
+
if (aggregate != IntPtr.Zero && !closed)
|
|
57
|
+
JobNative.Budget(aggregate, Cpus.Count == 0 ? 2 : Cpus.Values.Min(), memoryBudget);
|
|
58
|
+
}
|
|
45
59
|
public static void Cancel(string id)
|
|
46
60
|
{
|
|
47
61
|
lock (Sync)
|
|
@@ -105,10 +119,10 @@ namespace NativeStudio.Platform
|
|
|
105
119
|
}
|
|
106
120
|
catch (ArgumentException) { } // A command already exited.
|
|
107
121
|
}
|
|
108
|
-
if (rss >
|
|
122
|
+
if ((ulong)rss > memoryBudget)
|
|
109
123
|
{
|
|
110
|
-
|
|
111
|
-
|
|
124
|
+
foreach (var id in Cpus.Keys) Exceeded.Add(id);
|
|
125
|
+
JobNative.TerminateJobObject(aggregate, 1);
|
|
112
126
|
}
|
|
113
127
|
}
|
|
114
128
|
Thread.Sleep(100);
|
|
@@ -199,6 +213,11 @@ namespace NativeStudio.Platform
|
|
|
199
213
|
throw new Exception("INPUT_LIMIT");
|
|
200
214
|
int maximum = Convert.ToInt32(r["maxOutputBytes"]);
|
|
201
215
|
long expires = Convert.ToInt64(r["expiresAt"]);
|
|
216
|
+
var budget = r.ContainsKey("limits") ? (IDictionary<string, object>)r["limits"] : null;
|
|
217
|
+
double cpu = budget == null ? 2 : Convert.ToDouble(budget["cpuCores"]);
|
|
218
|
+
ulong memory = budget == null ? 4294967296UL : Convert.ToUInt64(budget["memoryBytes"]);
|
|
219
|
+
if (Double.IsNaN(cpu) || Double.IsInfinity(cpu) || cpu < 0.25 || cpu > 2 || memory < 1048576UL || memory > 4294967296UL)
|
|
220
|
+
throw new Exception("LIMIT");
|
|
202
221
|
if (maximum < 1 || maximum > 524288 || expires <= DateTimeOffset.UtcNow.ToUnixTimeMilliseconds())
|
|
203
222
|
throw new Exception("LIMIT");
|
|
204
223
|
string cwd = r.ContainsKey("cwd") && r["cwd"] != null ? PrivateAccess.PathOf(NativeMain.Text(r, "cwd")) : null;
|
|
@@ -209,6 +228,7 @@ namespace NativeStudio.Platform
|
|
|
209
228
|
try
|
|
210
229
|
{
|
|
211
230
|
var root = Aggregate();
|
|
231
|
+
lock (Sync) { Cpus[id] = cpu; Memories[id] = memory; ApplyBudget(); }
|
|
212
232
|
job = JobNative.Job(false);
|
|
213
233
|
ownedJob = new SafeFileHandle(job, true);
|
|
214
234
|
lock (Sync)
|
|
@@ -307,6 +327,7 @@ namespace NativeStudio.Platform
|
|
|
307
327
|
}
|
|
308
328
|
}
|
|
309
329
|
uint code;
|
|
330
|
+
lock (Sync) { if (Exceeded.Contains(id)) throw new Exception("RESOURCE_BUDGET_EXCEEDED"); }
|
|
310
331
|
if (!JobNative.GetExitCodeProcess(info.process, out code))
|
|
311
332
|
throw new Exception("EXIT");
|
|
312
333
|
JobNative.Kill(ownedJob); // Dispose every descendant even if it closed its streams.
|
|
@@ -7,6 +7,16 @@ namespace NativeStudio.Platform
|
|
|
7
7
|
{
|
|
8
8
|
public static class NativeMain
|
|
9
9
|
{
|
|
10
|
+
[System.Runtime.InteropServices.StructLayout(System.Runtime.InteropServices.LayoutKind.Sequential)]
|
|
11
|
+
struct LastInput { public uint size; public uint tick; }
|
|
12
|
+
[System.Runtime.InteropServices.DllImport("user32.dll", SetLastError = true)]
|
|
13
|
+
static extern bool GetLastInputInfo(ref LastInput input);
|
|
14
|
+
static int IdleSeconds()
|
|
15
|
+
{
|
|
16
|
+
var input = new LastInput { size = 8 };
|
|
17
|
+
if (!GetLastInputInfo(ref input)) throw new Exception("IDLE_UNAVAILABLE");
|
|
18
|
+
return (int)Math.Min(86400U, unchecked((uint)Environment.TickCount - input.tick) / 1000U);
|
|
19
|
+
}
|
|
10
20
|
static readonly object Output = new object();
|
|
11
21
|
public static readonly JavaScriptSerializer Json = new JavaScriptSerializer { MaxJsonLength = 2097152, RecursionLimit = 32 };
|
|
12
22
|
public static string Text(IDictionary<string, object> r, string key)
|
|
@@ -49,6 +59,11 @@ namespace NativeStudio.Platform
|
|
|
49
59
|
try
|
|
50
60
|
{
|
|
51
61
|
var operation = Text(r, "operation");
|
|
62
|
+
if (operation == "idle")
|
|
63
|
+
{
|
|
64
|
+
Send(new { id = id, ok = true, data = new { seconds = IdleSeconds() } });
|
|
65
|
+
return;
|
|
66
|
+
}
|
|
52
67
|
if (operation == "directory")
|
|
53
68
|
PrivateAccess.Directory(Text(r, "path"));
|
|
54
69
|
else if (operation == "check")
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{NativeStudioRuntimeAuthorityClient}from"./_chunks/chunk-
|
|
1
|
+
import{NativeStudioRuntimeAuthorityClient}from"./_chunks/chunk-GLD5WP6Z.js";import"./_chunks/chunk-7YCEMDNZ.js";import"./_chunks/chunk-NSS2BKVM.js";import"./_chunks/chunk-4M3AGNTZ.js";import"./_chunks/chunk-6NVIN2NI.js";export{NativeStudioRuntimeAuthorityClient};
|