@nativestudio/sdk 0.3.0-rc.1 → 0.3.0-rc.2
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/dist/_types/contracts/local-execution/ipc.d.ts +3 -3
- package/dist/_types/contracts/local-execution/lifecycle.d.ts +28 -0
- package/dist/_types/contracts/local-execution/local-navigation.d.ts +3 -3
- package/dist/_types/sdk/local-runtime-client.d.ts +4 -4
- package/dist/local-runtime.js +1 -1
- package/package.json +1 -1
package/COMPATIBILITY.json
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
{
|
|
2
2
|
"protocol": "NVS_PRODUCT_COMPATIBILITY_V1",
|
|
3
3
|
"product": "@nativestudio/sdk",
|
|
4
|
-
"version": "0.3.0-rc.
|
|
4
|
+
"version": "0.3.0-rc.2",
|
|
5
5
|
"source": {
|
|
6
|
-
"head": "
|
|
7
|
-
"fileDigest": "
|
|
6
|
+
"head": "367934225a30676f9bab1ac294c427289cf80f89",
|
|
7
|
+
"fileDigest": "4c2a660f49c5c7368a05f8a896be2b5dfd8fb4c521da76e0278c5ab212bb3187",
|
|
8
8
|
"dirty": false,
|
|
9
|
-
"remoteMainHead": "
|
|
9
|
+
"remoteMainHead": "367934225a30676f9bab1ac294c427289cf80f89"
|
|
10
10
|
},
|
|
11
11
|
"node": ">=24.12 <25",
|
|
12
12
|
"discoveryProfile": "contextual-v1",
|
|
@@ -422,9 +422,9 @@ export declare const LocalVersionReportSchema: z.ZodObject<{
|
|
|
422
422
|
installOwner: z.ZodEnum<{
|
|
423
423
|
UNKNOWN: "UNKNOWN";
|
|
424
424
|
PROJECT: "PROJECT";
|
|
425
|
+
MANAGED: "MANAGED";
|
|
425
426
|
NPM_GLOBAL: "NPM_GLOBAL";
|
|
426
427
|
NPX: "NPX";
|
|
427
|
-
MANAGED: "MANAGED";
|
|
428
428
|
TARBALL: "TARBALL";
|
|
429
429
|
}>;
|
|
430
430
|
}, z.core.$strict>;
|
|
@@ -454,9 +454,9 @@ export declare const LocalRuntimeStatusSchema: z.ZodObject<{
|
|
|
454
454
|
installOwner: z.ZodEnum<{
|
|
455
455
|
UNKNOWN: "UNKNOWN";
|
|
456
456
|
PROJECT: "PROJECT";
|
|
457
|
+
MANAGED: "MANAGED";
|
|
457
458
|
NPM_GLOBAL: "NPM_GLOBAL";
|
|
458
459
|
NPX: "NPX";
|
|
459
|
-
MANAGED: "MANAGED";
|
|
460
460
|
TARBALL: "TARBALL";
|
|
461
461
|
}>;
|
|
462
462
|
}, z.core.$strict>>;
|
|
@@ -740,9 +740,9 @@ export declare const LocalIpcResponseSchema: z.ZodDiscriminatedUnion<[z.ZodObjec
|
|
|
740
740
|
installOwner: z.ZodEnum<{
|
|
741
741
|
UNKNOWN: "UNKNOWN";
|
|
742
742
|
PROJECT: "PROJECT";
|
|
743
|
+
MANAGED: "MANAGED";
|
|
743
744
|
NPM_GLOBAL: "NPM_GLOBAL";
|
|
744
745
|
NPX: "NPX";
|
|
745
|
-
MANAGED: "MANAGED";
|
|
746
746
|
TARBALL: "TARBALL";
|
|
747
747
|
}>;
|
|
748
748
|
}, z.core.$strict>>;
|
|
@@ -217,12 +217,26 @@ export declare const LocalSignedCatalogueSchema: z.ZodObject<{
|
|
|
217
217
|
}, z.core.$strict>;
|
|
218
218
|
signature: z.ZodString;
|
|
219
219
|
}, z.core.$strict>;
|
|
220
|
+
export declare const LocalToolChoiceSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{
|
|
221
|
+
mode: z.ZodLiteral<"MANAGED">;
|
|
222
|
+
}, z.core.$strict>, z.ZodObject<{
|
|
223
|
+
ffmpeg: z.ZodObject<{
|
|
224
|
+
path: z.ZodString;
|
|
225
|
+
digest: z.ZodString;
|
|
226
|
+
}, z.core.$strict>;
|
|
227
|
+
ffprobe: z.ZodObject<{
|
|
228
|
+
path: z.ZodString;
|
|
229
|
+
digest: z.ZodString;
|
|
230
|
+
}, z.core.$strict>;
|
|
231
|
+
mode: z.ZodLiteral<"INSTALLED">;
|
|
232
|
+
}, z.core.$strict>], "mode">;
|
|
220
233
|
export declare const LocalUpdatePlanSchema: z.ZodObject<{
|
|
221
234
|
protocol: z.ZodLiteral<"NVS_LOCAL_UPDATE_PLAN_V1">;
|
|
222
235
|
planId: z.ZodPipe<z.ZodUUID, z.ZodTransform<string, string>>;
|
|
223
236
|
installationRevision: z.ZodInt;
|
|
224
237
|
runtimeRevision: z.ZodNullable<z.ZodInt>;
|
|
225
238
|
catalogueFingerprint: z.ZodString;
|
|
239
|
+
trustFingerprint: z.ZodOptional<z.ZodString>;
|
|
226
240
|
release: z.ZodObject<{
|
|
227
241
|
descriptor: z.ZodObject<{
|
|
228
242
|
protocol: z.ZodLiteral<"NVS_RUNTIME_DESCRIPTOR_V1">;
|
|
@@ -268,6 +282,19 @@ export declare const LocalUpdatePlanSchema: z.ZodObject<{
|
|
|
268
282
|
}, z.core.$strict>;
|
|
269
283
|
}, z.core.$strict>>;
|
|
270
284
|
}, z.core.$strict>;
|
|
285
|
+
toolSelection: z.ZodOptional<z.ZodDiscriminatedUnion<[z.ZodObject<{
|
|
286
|
+
mode: z.ZodLiteral<"MANAGED">;
|
|
287
|
+
}, z.core.$strict>, z.ZodObject<{
|
|
288
|
+
ffmpeg: z.ZodObject<{
|
|
289
|
+
path: z.ZodString;
|
|
290
|
+
digest: z.ZodString;
|
|
291
|
+
}, z.core.$strict>;
|
|
292
|
+
ffprobe: z.ZodObject<{
|
|
293
|
+
path: z.ZodString;
|
|
294
|
+
digest: z.ZodString;
|
|
295
|
+
}, z.core.$strict>;
|
|
296
|
+
mode: z.ZodLiteral<"INSTALLED">;
|
|
297
|
+
}, z.core.$strict>], "mode">>;
|
|
271
298
|
fingerprint: z.ZodString;
|
|
272
299
|
createdAt: z.ZodISODateTime;
|
|
273
300
|
expiresAt: z.ZodISODateTime;
|
|
@@ -317,3 +344,4 @@ export type LocalSessionConnector = z.infer<typeof LocalSessionConnectorSchema>;
|
|
|
317
344
|
export type LocalRelease = z.infer<typeof LocalReleaseSchema>;
|
|
318
345
|
export type LocalSignedCatalogue = z.infer<typeof LocalSignedCatalogueSchema>;
|
|
319
346
|
export type LocalUpdatePlan = z.infer<typeof LocalUpdatePlanSchema>;
|
|
347
|
+
export type LocalToolChoice = z.infer<typeof LocalToolChoiceSchema>;
|
|
@@ -215,9 +215,9 @@ export declare const LocalMcpUpdateSchema: z.ZodObject<{
|
|
|
215
215
|
installOwner: z.ZodEnum<{
|
|
216
216
|
UNKNOWN: "UNKNOWN";
|
|
217
217
|
PROJECT: "PROJECT";
|
|
218
|
+
MANAGED: "MANAGED";
|
|
218
219
|
NPM_GLOBAL: "NPM_GLOBAL";
|
|
219
220
|
NPX: "NPX";
|
|
220
|
-
MANAGED: "MANAGED";
|
|
221
221
|
TARBALL: "TARBALL";
|
|
222
222
|
}>;
|
|
223
223
|
}, z.core.$strict>>;
|
|
@@ -498,9 +498,9 @@ export declare const LocalMcpOutputSchemas: {
|
|
|
498
498
|
installOwner: z.ZodEnum<{
|
|
499
499
|
UNKNOWN: "UNKNOWN";
|
|
500
500
|
PROJECT: "PROJECT";
|
|
501
|
+
MANAGED: "MANAGED";
|
|
501
502
|
NPM_GLOBAL: "NPM_GLOBAL";
|
|
502
503
|
NPX: "NPX";
|
|
503
|
-
MANAGED: "MANAGED";
|
|
504
504
|
TARBALL: "TARBALL";
|
|
505
505
|
}>;
|
|
506
506
|
}, z.core.$strict>>;
|
|
@@ -636,9 +636,9 @@ export declare const LocalMcpOutputSchemas: {
|
|
|
636
636
|
installOwner: z.ZodEnum<{
|
|
637
637
|
UNKNOWN: "UNKNOWN";
|
|
638
638
|
PROJECT: "PROJECT";
|
|
639
|
+
MANAGED: "MANAGED";
|
|
639
640
|
NPM_GLOBAL: "NPM_GLOBAL";
|
|
640
641
|
NPX: "NPX";
|
|
641
|
-
MANAGED: "MANAGED";
|
|
642
642
|
TARBALL: "TARBALL";
|
|
643
643
|
}>;
|
|
644
644
|
}, z.core.$strict>>;
|
|
@@ -124,7 +124,7 @@ export declare class NativeStudioLocalRuntimeClient {
|
|
|
124
124
|
runningVersion: string | null;
|
|
125
125
|
availableVersion: string | null;
|
|
126
126
|
executablePath: string | null;
|
|
127
|
-
installOwner: "UNKNOWN" | "PROJECT" | "
|
|
127
|
+
installOwner: "UNKNOWN" | "PROJECT" | "MANAGED" | "NPM_GLOBAL" | "NPX" | "TARBALL";
|
|
128
128
|
}[];
|
|
129
129
|
authorizedProjects: {
|
|
130
130
|
tenantId: string;
|
|
@@ -361,7 +361,7 @@ export declare class NativeStudioLocalRuntimeClient {
|
|
|
361
361
|
runningVersion: string | null;
|
|
362
362
|
availableVersion: string | null;
|
|
363
363
|
executablePath: string | null;
|
|
364
|
-
installOwner: "UNKNOWN" | "PROJECT" | "
|
|
364
|
+
installOwner: "UNKNOWN" | "PROJECT" | "MANAGED" | "NPM_GLOBAL" | "NPX" | "TARBALL";
|
|
365
365
|
}[];
|
|
366
366
|
authorizedProjects: {
|
|
367
367
|
tenantId: string;
|
|
@@ -921,8 +921,8 @@ export declare class NativeStudioLocalRuntimeClient {
|
|
|
921
921
|
}
|
|
922
922
|
export { LocalSessionConnectorSchema } from "../contracts/local-execution/index.js";
|
|
923
923
|
export { NativeStudioSdkError } from "./errors.js";
|
|
924
|
-
export { LocalRuntimeDescriptorSchema, LocalManagementInventorySchema, LocalSignedCatalogueSchema, LocalReleaseSchema, LocalUpdatePlanSchema, LocalClientNextActionSchema, canonicalLocalJson, LocalSessionConnectorSchema as LocalConnectorSchema, } from "../contracts/local-execution/index.js";
|
|
925
|
-
export type { LocalRelease, LocalSignedCatalogue, LocalUpdatePlan, LocalRuntimeDescriptor, LocalSessionConnector, } from "../contracts/local-execution/index.js";
|
|
924
|
+
export { LocalRuntimeDescriptorSchema, LocalManagementInventorySchema, LocalSignedCatalogueSchema, LocalReleaseSchema, LocalUpdatePlanSchema, LocalToolChoiceSchema, LocalClientNextActionSchema, canonicalLocalJson, LocalSessionConnectorSchema as LocalConnectorSchema, } from "../contracts/local-execution/index.js";
|
|
925
|
+
export type { LocalRelease, LocalSignedCatalogue, LocalUpdatePlan, LocalToolChoice, LocalRuntimeDescriptor, LocalSessionConnector, } from "../contracts/local-execution/index.js";
|
|
926
926
|
export { NativeStudioLocalDeviceClient } from "./local-runtime/device-client.js";
|
|
927
927
|
export { EnrollLocalDeviceSchema, GrantLocalDeviceSchema, RevokeLocalDeviceSchema, RevokeLocalDeviceGrantSchema, StartLocalPreviewSchema, LocalDeviceTransportConfigurationSchema, } from "../contracts/local-execution/index.js";
|
|
928
928
|
export { LocalToolSelectionSchema, LocalWorkScopeSchema, } from "../contracts/local-execution/index.js";
|
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 z7}from"zod";import{z as z5}from"zod";var LocalRuntimeDescriptorSchema=z5.strictObject({protocol:z5.literal("NVS_RUNTIME_DESCRIPTOR_V1"),version:LocalPackageVersionSchema,node:z5.strictObject({major:z5.literal(24),minMinor:z5.literal(12)}),platform:LocalDevicePlatformSchema,ipcProtocol:z5.literal("NVS_LOCAL_IPC_V1"),workProtocol:z5.literal("NVS_LOCAL_WORK_V1"),journalSchema:z5.literal(1),rendererDigest:LocalDigestSchema,profileDigest:LocalDigestSchema});var LocalSessionConnectorSchema=z5.strictObject({protocol:z5.literal("NVS_LOCAL_CONNECTOR_V1"),stateDirectory:z5.string().min(1).max(4096),credential:z5.string().length(43).regex(/^[A-Za-z0-9_-]{43}$/),expiresAt:LocalTimeSchema,projects:z5.array(LocalProjectScopeSchema).min(1).max(100)});var LocalManagementInventorySchema=z5.strictObject({runtimeRevision:z5.int().positive(),descriptor:LocalRuntimeDescriptorSchema,activeProcesses:z5.int().nonnegative(),pendingExecutions:z5.int().nonnegative(),pendingRequests:z5.int().nonnegative(),pendingRenderers:z5.array(LocalDigestSchema).max(64)});var LocalReleaseAssetSchema=z5.strictObject({url:z5.string().url().max(2048),byteSize:z5.int().positive().max(256*1024*1024),sha512:z5.string().length(128).regex(/^[0-9a-f]{128}$/)});var LocalReleaseSchema=z5.strictObject({descriptor:LocalRuntimeDescriptorSchema,package:LocalReleaseAssetSchema,tools:z5.strictObject({ffmpeg:LocalReleaseAssetSchema.extend({sha256:LocalDigestSchema}),ffprobe:LocalReleaseAssetSchema.extend({sha256:LocalDigestSchema})}).nullable()});var LocalReleaseCatalogueSchema=z5.strictObject({protocol:z5.literal("NVS_LOCAL_RELEASE_CATALOGUE_V1"),issuedAt:LocalTimeSchema,expiresAt:LocalTimeSchema,releases:z5.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=z5.strictObject({catalogue:LocalReleaseCatalogueSchema,signature:z5.string().length(86).regex(/^[A-Za-z0-9_-]{85}[AQgw]$/)});var LocalUpdatePlanSchema=z5.strictObject({protocol:z5.literal("NVS_LOCAL_UPDATE_PLAN_V1"),planId:LocalIdSchema,installationRevision:z5.int().nonnegative(),runtimeRevision:z5.int().positive().nullable(),catalogueFingerprint:LocalDigestSchema,release:LocalReleaseSchema,fingerprint:LocalDigestSchema,createdAt:LocalTimeSchema,expiresAt:LocalTimeSchema});var LocalClientNextActionSchema=z5.strictObject({surface:z5.enum(["CLI","LOCAL_IPC","REMOTE"]),operation:z5.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:z5.enum(["AVAILABLE","BLOCKED"]),reason:z5.enum(["READY","INSTALL_REQUIRED","AUTHORIZATION_REQUIRED","VERSION_INCOMPATIBLE","UPDATE_AVAILABLE","RECOVERY_REQUIRED","USER_APPROVAL_REQUIRED","TRUST_REQUIRED","UNAVAILABLE"])});import{z as z6}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=z6.string().regex(/^[a-f0-9]{64}$/);var qualifiedVersion=z6.enum(["0.164.0","0.165.0"]);var LocalAgentGrantSchema=z6.strictObject({protocol:z6.literal("NVS_CODEX_REVIEW_GRANT_V1"),binary:z6.string().min(1).max(4096).startsWith("/"),binaryDigest:sha,version:qualifiedVersion,model:z6.string().regex(/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,99}$/),reasoningEffort:z6.enum(["low","medium","high","xhigh"]).optional(),reviewerLabel:z6.string().trim().min(1).max(100),inference:z6.literal("REMOTE_OPENAI"),remoteUseApproved:z6.literal(true),imageDisclosureApproved:z6.literal(true).optional(),projects:z6.array(LocalProjectScopeSchema).min(1).max(100),expiresAt:z6.iso.datetime({offset:true})});var LocalAgentSnapshotSchema=z6.strictObject({basis:ReviewIntelligenceBasisSchema.extend({target:z6.strictObject({kind:z6.literal("IMAGE"),generationId:z6.uuid()})}),productionRevision:z6.int().positive(),reviewVersion:z6.int().nonnegative(),executionClass:z6.enum(["LIVE","TEST_ONLY"]),media:ReviewEvidenceMediaSchema,requirements:z6.array(VisualRequirementSchema).min(1).max(64),image:z6.strictObject({contentType:z6.literal("image/png"),byteSize:z6.int().positive().max(8388608),width:z6.int().positive().max(4096),height:z6.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=z6.strictObject({configured:z6.boolean(),available:z6.boolean(),reason:z6.enum(["GRANT_REQUIRED","READY","RUNTIME_UNAVAILABLE","GRANT_EXPIRED"]),grantFingerprint:sha.nullable(),inference:z6.literal("REMOTE_OPENAI")});var LocalAgentPlanSchema=z6.strictObject({protocol:z6.literal("NVS_LOCAL_AGENT_REVIEW_V1"),id:z6.uuid(),grantFingerprint:sha,snapshot:LocalAgentSnapshotSchema,expiresAt:z6.iso.datetime({offset:true}),fingerprint:sha});var LocalAgentMetadataAnswerSchema=z6.strictObject({summary:z6.string().trim().min(1).max(1500),observations:z6.array(z6.strictObject({key:z6.string().min(1).max(200),observed:z6.string().trim().min(1).max(1e3)})).min(1).max(64)});var LocalAgentPixelAnswerSchema=z6.strictObject({summary:z6.string().trim().min(1).max(1500),imageReadback:z6.string().trim().min(1).max(800),observations:z6.array(KeyframeObservationSchema.omit({region:true})).min(1).max(64)});var LocalAgentAnswerSchema=z6.union([LocalAgentMetadataAnswerSchema,LocalAgentPixelAnswerSchema]).refine(v=>new TextEncoder().encode(JSON.stringify(v)).length<=96*1024);var LocalAgentImageReceiptSchema=z6.strictObject({protocol:z6.literal("NVS_LOCAL_AGENT_IMAGE_V1"),draftId:z6.uuid(),media:ReviewEvidenceMediaSchema,byteSize:z6.int().positive().max(8388608),contentType:z6.literal("image/png"),width:z6.int().positive().max(4096),height:z6.int().positive().max(4096)});var LocalAgentReviewViewSchema=z6.strictObject({plan:LocalAgentPlanSchema,revision:z6.int().positive(),phase:z6.enum(["PREPARED","RUNNING","RESULT_PENDING","UNKNOWN"]),answer:LocalAgentAnswerSchema.nullable(),imageReceipt:LocalAgentImageReceiptSchema.optional(),provenance:z6.strictObject({adapter:z6.literal("CODEX_METADATA_V1"),binaryDigest:sha,version:qualifiedVersion,model:z6.string().max(100),reasoningEffort:z6.enum(["low","medium","high","xhigh"]).optional(),reviewerLabel:z6.string().max(100),inference:z6.literal("REMOTE_OPENAI"),evidence:z6.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:z7.string().length(64).regex(/^[0-9a-f]{64}$/).nullable().default(null),limit:z7.int().min(1).max(16).default(8)});var LocalIpcCallSchema=z7.discriminatedUnion("operation",[z7.strictObject({operation:z7.literal("agent.grant"),grant:LocalAgentGrantSchema,approval:z7.string().regex(/^[a-f0-9]{64}$/)}),z7.strictObject({operation:z7.literal("agent.probe")}),z7.strictObject({operation:z7.literal("agent.revoke"),approval:z7.string().regex(/^[a-f0-9]{64}$/)}),z7.strictObject({operation:z7.literal("agent.prepare"),snapshot:LocalAgentSnapshotSchema}),z7.strictObject({operation:z7.literal("agent.start"),id:z7.uuid(),expectedRevision:LocalRevisionSchema,approval:z7.string().regex(/^[a-f0-9]{64}$/)}),z7.strictObject({operation:z7.literal("agent.inspect"),id:z7.uuid()}),z7.strictObject({operation:z7.literal("runtime.status")}),z7.strictObject({operation:z7.literal("runtime.doctor")}),z7.strictObject({operation:z7.literal("runtime.inventory")}),z7.strictObject({operation:z7.literal("session.issue"),projects:z7.array(projectInput).min(1).max(100),expiresAt:z7.iso.datetime({offset:true})}),z7.strictObject({operation:z7.literal("runtime.stop"),expectedRuntimeRevision:LocalRevisionSchema}),z7.strictObject({operation:z7.literal("execution.inspect"),input:LocalWorkScopeSchema}),z7.strictObject({operation:z7.literal("execution.list"),input:LocalExecutionListInputSchema}),z7.strictObject({operation:z7.literal("update.check")}),z7.strictObject({operation:z7.literal("update.prepare"),targetVersion:LocalPackageVersionSchema,expectedRuntimeRevision:LocalRevisionSchema}),z7.strictObject({operation:z7.literal("update.apply"),planId:LocalIdSchema,targetVersion:LocalPackageVersionSchema,expectedRuntimeRevision:LocalRevisionSchema})]);var LocalNextActionSchema=z7.strictObject({call:LocalIpcCallSchema,availability:z7.enum(["AVAILABLE","BLOCKED"]),reason:z7.enum(["READY","INSTALL_REQUIRED","AUTHORIZATION_REQUIRED","VERSION_INCOMPATIBLE","UPDATE_AVAILABLE","RECOVERY_REQUIRED"])});var LocalIpcRequestSchema=z7.strictObject({protocol:z7.literal("NVS_LOCAL_IPC_V1"),requestId:LocalIdSchema,call:LocalIpcCallSchema});var LocalVersionReportSchema=z7.strictObject({component:z7.enum(["CLI","SDK","MCP","RUNTIME","MEDIA_TOOLS"]),installedVersion:LocalPackageVersionSchema.nullable(),runningVersion:LocalPackageVersionSchema.nullable(),availableVersion:LocalPackageVersionSchema.nullable(),executablePath:z7.string().min(1).max(4096).nullable(),installOwner:z7.enum(["NPM_GLOBAL","PROJECT","NPX","MANAGED","TARBALL","UNKNOWN"])});var LocalRuntimeStatusSchema=z7.strictObject({protocol:z7.literal("NVS_LOCAL_IPC_V1"),runtimeRevision:LocalRevisionSchema,state:z7.enum(["IDLE","EXECUTING","DRAINING","RECOVERY_REQUIRED"]),journalSchemaVersion:z7.literal(1),workProtocols:z7.array(z7.literal("NVS_LOCAL_WORK_V1")).min(1).max(1),versions:z7.array(LocalVersionReportSchema).max(8),authorizedProjects:z7.array(projectInput).max(100),nextActions:z7.array(LocalNextActionSchema).max(8)});var LocalDoctorReportSchema=z7.strictObject({mode:z7.enum(["MANAGED","INSTALLED"]),availability:z7.enum(["AVAILABLE","UNAVAILABLE"]),reason:z7.enum(["QUALIFIED_PROCESS_TOOLS","MANAGED_TOOLS_MISSING","TOOL_QUALIFICATION_FAILED"]),nativeExecutionReady:z7.boolean(),tools:z7.array(z7.strictObject({name:z7.enum(["FFMPEG","FFPROBE"]),path:z7.string().min(1).max(4096),version:z7.string().min(1).max(200),digest:z7.string().regex(/^[0-9a-f]{64}$/)})).max(2)});var LocalExecutionInspectionSchema=z7.strictObject({binding:LocalLeaseBindingSchema,revision:LocalRevisionSchema,phase:z7.enum(["STAGED","RUNNING","RECOVERY_REQUIRED","OUTPUT_PENDING","RECEIPT_RECORDED","FENCED"]),checkpoint:z7.enum(["ADOPTED","SOURCES_READY","PROCESS_STARTED","OUTPUT_STAGED"])});var LocalExecutionPageSchema=z7.strictObject({items:z7.array(LocalExecutionInspectionSchema).max(16),nextCursor:z7.string().length(64).regex(/^[0-9a-f]{64}$/).nullable()});var LocalIpcErrorCodeSchema=z7.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=z7.discriminatedUnion("semanticStatus",[z7.strictObject({protocol:z7.literal("NVS_LOCAL_IPC_V1"),requestId:LocalIdSchema,semanticStatus:z7.literal("SUCCESS"),data:z7.union([LocalRuntimeStatusSchema,LocalDoctorReportSchema,LocalExecutionInspectionSchema.nullable(),z7.strictObject({state:z7.literal("DRAINING"),inventory:LocalManagementInventorySchema.optional(),backupPath:z7.string().min(1).max(4096).optional()}),LocalSessionConnectorSchema,LocalManagementInventorySchema,LocalExecutionPageSchema,LocalAgentProbeSchema,LocalAgentReviewViewSchema])}),z7.strictObject({protocol:z7.literal("NVS_LOCAL_IPC_V1"),requestId:LocalIdSchema.nullable(),semanticStatus:z7.enum(["BLOCKED","INVALID_INPUT"]),error:z7.strictObject({code:LocalIpcErrorCodeSchema})})]);import{z as z8}from"zod";var StartLocalPreviewSchema=RoughCutStartSchema.extend({placement:LocalPlacementPolicySchema});var LocalDeviceScopeSchema=z8.strictObject({tenantId:LocalIdSchema,deviceId:LocalIdSchema});var LocalDeviceSessionSchema=z8.strictObject({...LocalDeviceScopeSchema.shape,expiresAt:LocalTimeSchema,credential:z8.string().length(43).regex(/^[A-Za-z0-9_-]+$/).meta({writeOnly:true})});var LocalDeviceHeartbeatSchema=LocalDeviceScopeSchema.extend({toolchain:LocalToolchainSchema,available:z8.boolean()});var ClaimLocalPreviewSchema=LocalProjectScopeSchema.extend({requestId:LocalIdSchema,deviceId:LocalIdSchema});var LocalOutputStageSchema=LocalLeaseBindingSchema.extend({uploadRequestId:LocalIdSchema,role:z8.enum(["VIDEO","POSTER"]),checksumSha256:LocalDigestSchema,byteSize:z8.int().positive().max(128*1024*1024)});var LocalOutputTicketSchema=z8.strictObject({receiptId:LocalIdSchema,role:z8.enum(["VIDEO","POSTER"]),checksumSha256:LocalDigestSchema,byteSize:z8.int().positive(),uploaded:z8.boolean()});var LocalSourceRequestSchema=LocalLeaseBindingSchema.extend({representationId:LocalIdSchema});var LocalProofChallengeRequestSchema=LocalDeviceScopeSchema.extend({deviceRevision:z8.int().positive()});var LocalPreviewPlacementViewSchema=z8.strictObject({target:z8.enum(["DEVICE","SERVER"]),reason:z8.enum(["LOCAL_AVAILABLE","CLOUD_ONLY","OFFLINE","UNQUALIFIED","BUSY","LEASE_RECOVERY"]),policy:LocalPlacementPolicySchema});var LocalDeviceTransportConfigurationSchema=z8.strictObject({endpoint:z8.string().url().max(2048),tenantId:LocalIdSchema,deviceId:LocalIdSchema,deviceRevision:z8.int().positive(),projects:z8.array(LocalProjectScopeSchema).min(1).max(20),privateKeyFile:z8.string().min(1).max(4096),platform:LocalDevicePlatformSchema});var LocalPreviewAdmissionSchema=RoughCutAdmissionSchema.extend({placement:LocalPreviewPlacementViewSchema});var LocalClaimReceiptSchema=z8.strictObject({found:z8.boolean(),assignment:LocalWorkAssignmentSchema.nullable()});var LocalWorkStateSchema=z8.strictObject({binding:LocalLeaseBindingSchema,status:z8.enum(["ACTIVE","FENCED","OUTCOME_UNKNOWN"]),assignment:LocalWorkAssignmentSchema.nullable()});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});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,LocalToolSelectionSchema,LocalUpdatePlanSchema,LocalWorkScopeSchema,NativeStudioLocalDeviceClient,NativeStudioLocalRuntimeClient,NativeStudioSdkError,RevokeLocalDeviceGrantSchema,RevokeLocalDeviceSchema,StartLocalPreviewSchema,canonicalLocalJson,localAgentNativeProposal,localAgentSnapshotFromContext};
|
|
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};
|