@nativestudio/cli 0.3.0-rc.20 → 0.3.0-rc.21
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/COMPATIBILITY.json +8 -8
- package/components/runtime.json +4 -4
- package/components/runtime.tgz +0 -0
- package/dist/_chunks/{chunk-APNZQZFB.js → chunk-2S7FI3HF.js} +1 -1
- package/dist/_chunks/{chunk-OSO6KRE2.js → chunk-3RNDOAQI.js} +1 -1
- package/dist/_chunks/{chunk-QK4XPVKT.js → chunk-4AD4PNUX.js} +1 -1
- package/dist/_chunks/{chunk-D74NHT4I.js → chunk-5Y7J2OYL.js} +1 -1
- package/dist/_chunks/{chunk-GLAF74UU.js → chunk-76E5R3OC.js} +1 -1
- package/dist/_chunks/{chunk-4PAVWOPA.js → chunk-7IVAYDU3.js} +1 -1
- package/dist/_chunks/{chunk-L3QA7FLZ.js → chunk-DMA53YVU.js} +1 -1
- package/dist/_chunks/{chunk-AFNJRZLJ.js → chunk-ETK7GYCB.js} +1 -1
- package/dist/_chunks/{chunk-ELUJ44BO.js → chunk-FFXSXE3G.js} +1 -1
- package/dist/_chunks/{chunk-HBDPYWMI.js → chunk-H4FH6STZ.js} +1 -1
- package/dist/_chunks/{chunk-6EZX2TRX.js → chunk-LDBXGRCQ.js} +1 -1
- package/dist/_chunks/{chunk-K35CWLDH.js → chunk-LTNJ45JP.js} +1 -1
- package/dist/_chunks/{chunk-MLZ3ZPGU.js → chunk-MZWEFYHE.js} +1 -1
- package/dist/_chunks/{chunk-ROGOASYF.js → chunk-PQCA4X5H.js} +1 -1
- package/dist/_chunks/{chunk-IYDHDLTR.js → chunk-SM2I7TJ3.js} +1 -1
- package/dist/_chunks/{chunk-FVY3PLG7.js → chunk-VXYZCCCQ.js} +1 -1
- package/dist/_chunks/{chunk-UYKCN5DU.js → chunk-VYCNG6TR.js} +1 -1
- package/dist/_chunks/{chunk-4M2SOMSN.js → chunk-WLQMICJN.js} +1 -1
- package/dist/_chunks/{chunk-NG4BDFEY.js → chunk-X5MVC46N.js} +1 -1
- package/dist/_chunks/{chunk-XUSVNPR5.js → chunk-X5PBZTKX.js} +1 -1
- package/dist/_chunks/{chunk-LBK42NHW.js → chunk-ZMJYBUS3.js} +1 -1
- package/dist/_chunks/{chunk-QE7O57PQ.js → chunk-ZYXHPTT2.js} +1 -1
- package/dist/_chunks/component-contract-2JHTRTOB.js +1 -0
- package/dist/_chunks/{component-preflight-WECLCZLF.js → component-preflight-6OWDQAZT.js} +1 -1
- package/dist/_chunks/{device-management-TLRUMZL5.js → device-management-JPS4HG34.js} +1 -1
- package/dist/_chunks/{device-preflight-C7FFUXI2.js → device-preflight-GTQ67H7C.js} +1 -1
- package/dist/_chunks/{devices-inventory-BZF53UAU.js → devices-inventory-E6ZLXCVR.js} +1 -1
- package/dist/_chunks/{devices-main-V3YHCB2C.js → devices-main-2BMCANKU.js} +1 -1
- package/dist/_chunks/{host-component-Q5IHRHRI.js → host-component-ZYQ5ETVL.js} +1 -1
- package/dist/_chunks/{host-help-7BGYR4ET.js → host-help-VNLA3YOV.js} +1 -1
- package/dist/_chunks/{host-main-JLIBRHC2.js → host-main-KLWW7R47.js} +1 -1
- package/dist/_chunks/{library-main-ATRFEAVN.js → library-main-3WWH7UYV.js} +1 -1
- package/dist/_chunks/{local-main-KTYCLHDA.js → local-main-5BW63USP.js} +1 -1
- package/dist/_chunks/{local-mcp-ISMU6ADI.js → local-mcp-AARKBDU5.js} +1 -1
- package/dist/_chunks/{main-MOZS2EK3.js → main-LGYJ3ZCN.js} +1 -1
- package/dist/_chunks/mcp-BLSK636Q.js +1 -0
- package/dist/_chunks/{observe-entry-E6DFHIMW.js → observe-entry-JVZAMB7N.js} +1 -1
- package/dist/_chunks/{remote-client-T75C45JO.js → remote-client-25Z65VJU.js} +1 -1
- package/dist/_chunks/{render-main-OGCO2LX4.js → render-main-6Z3DKCWL.js} +1 -1
- package/dist/_chunks/{source-import-55JJ26AA.js → source-import-PNMCMTK7.js} +1 -1
- package/dist/_chunks/{src-V2K52JDH.js → src-7HSJFRVQ.js} +1 -1
- package/dist/_chunks/{workspace-main-3P56DSEQ.js → workspace-main-QX5JGEMR.js} +1 -1
- package/dist/_types/contracts/interface/operation.d.ts +59 -0
- package/dist/_types/contracts/interface/production-snapshot.d.ts +25 -0
- package/dist/_types/contracts/interface/query.d.ts +25 -0
- package/dist/_types/contracts/lifecycle-event-projections.d.ts +2 -2
- package/dist/_types/contracts/navigation-context.d.ts +49 -1
- package/dist/_types/contracts/navigation.d.ts +1 -1
- package/dist/entry.js +1 -1
- package/dist/local-management.js +1 -1
- package/dist/local-navigation.js +1 -1
- package/package.json +1 -1
- package/dist/_chunks/component-contract-KXK7WIUI.js +0 -1
- package/dist/_chunks/mcp-M2SO3J2H.js +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
import{ArtifactIdSchema,ArtifactRelationIdSchema,ArtifactRepresentationIdSchema,BriefIdSchema,BriefVersionIdSchema,CapabilityVersionMismatchSchema,CapabilityVersionSchema,ContinuationSchema,ContinuityEdgeIdSchema,CreateProjectRequestSchema,CreatedProjectResultSchema,DeliveryOutputProfileSchema,HumanLinksSchema,HumanTenantSchema,InterfaceSemanticStatusSchema,NextActionSchema,OperationIdSchema,PrincipalIdSchema,ProductionIdSchema,ProductionSchema,ProductionStateSchema,ProjectIdSchema,ProjectLibraryPageSchema,ProjectLibraryQuerySchema,ProjectLibraryScopeSchema,ProjectSchema,ProjectWorkspaceSchema,QueryLimitSchema,QueryPageInfoSchema,SceneIdSchema,SceneShotPlanIdSchema,SceneShotPlanVersionIdSchema,ShotIdSchema,SourceLibraryItemSchema,SourceLibraryMediaSchema,SourceLibraryPageSchema,SourceLibraryQuerySchema,StoryIdSchema,StoryVersionIdSchema,StudioInputContentSchema,TenantIdSchema,WorkSummarySchema,finalProfileIds}from"./chunk-WTJVS2VS.js";import{NativeStudioSdkError,sdkInputError}from"./chunk-TT7IA5HB.js";import{createHash}from"node:crypto";import{z}from"zod";var LocalIdSchema=z.uuid().overwrite(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 z5}from"zod";import{z as z4}from"zod";import{z as z3}from"zod";import{z as z2}from"zod";var HOST_PROTOCOL="NVS_AGENT_HOST_V1";var HostProtocolDigest="c4b254f091c364e0fab8d43ad551f296a3bce2996bdb2c5349307c62295c1769";var HostDelegationDigest="03e0bad50c7c6ecf7979db72c0927fa43904d8fbad67ae02447a87a9263f2730";var HostReferenceSchema=z2.string().min(1).max(256).refine(v=>Array.from(v).every(c=>{const n=c.codePointAt(0);return n>=32&&(n<127||n>159)&&(n<55296||n>57343)}));var HostScopeSchema=z2.strictObject({namespace:HostReferenceSchema,ref:HostReferenceSchema});var HostChoiceSchema=z2.strictObject({agentKey:HostReferenceSchema,agentVersion:HostReferenceSchema,modelOptionKey:HostReferenceSchema});var CurrentHostSelectionSchema=HostChoiceSchema.extend({contractVersion:z2.literal(2),hostKey:z2.string().regex(/^[a-z0-9][a-z0-9_-]{0,63}$/),hostScope:HostScopeSchema}).strict();var HistoricalHostSelectionSchema=z2.object({hostKey:z2.string().min(1).max(64)}).catchall(z2.union([HostReferenceSchema,z2.number().int().nonnegative()])).refine(v=>!Object.hasOwn(v,"contractVersion")&&Object.keys(v).length<=32);var HostBearerSchema=z2.string().min(16).max(4096).regex(/^[A-Za-z0-9._~+/-]+={0,2}$/).meta({writeOnly:true});var CurrentHostInstallationTransportSchema=z2.strictObject({protocol:z2.literal(HOST_PROTOCOL),hostContractDigest:z2.literal(HostProtocolDigest),installationId:z2.string().regex(/^[A-Za-z0-9_-]{1,160}$/),installationRevisionId:z2.string().regex(/^[A-Za-z0-9_-]{1,160}$/),slotKey:z2.string().regex(/^[a-z0-9_-]{1,64}$/),contractDigest:z2.literal(HostDelegationDigest),capabilityDigest:z2.string().regex(/^[a-f0-9]{64}$/)});var HistoricalHostTransportSchema=z2.strictObject({protocol:HostReferenceSchema.refine(v=>v!==HOST_PROTOCOL),installationId:HostReferenceSchema,installationRevisionId:HostReferenceSchema,slotKey:HostReferenceSchema,contractDigest:z2.string().regex(/^[a-f0-9]{64}$/).optional(),capabilityDigest:z2.string().regex(/^[a-f0-9]{64}$/).optional()});var Id=z3.uuid().toLowerCase();var ReadId=z3.uuid().regex(/^[0-9a-f-]{36}$/);var Key=z3.string().regex(/^[a-z0-9][a-z0-9_-]{0,63}$/);var Revision=z3.int().min(0).max(999999999);var AgentHostScopeSchema=z3.strictObject({tenantId:Id,projectId:Id});var ReadScope=z3.strictObject({tenantId:ReadId,projectId:ReadId});var AgentHostSelectionSchema=CurrentHostSelectionSchema;var AgentHostReadSelectionSchema=z3.union([CurrentHostSelectionSchema,HistoricalHostSelectionSchema]);var ConfigureAgentHostSchema=AgentHostScopeSchema.extend({requestId:Id,bindingId:Id,expectedRevision:z3.int().min(0).max(999999998),selection:AgentHostSelectionSchema,apiCredential:HostBearerSchema});var RevokeAgentHostSchema=AgentHostScopeSchema.extend({requestId:Id,bindingId:Id,expectedRevision:z3.int().min(1).max(999999998)});var AgentHostBindingSchema=ReadScope.extend({bindingId:ReadId,revision:Revision.refine(value2=>value2>0),configurationVersion:Revision.refine(value2=>value2>0),enabled:z3.boolean(),selection:AgentHostReadSelectionSchema,updatedAt:z3.iso.datetime({offset:true})}).refine(value2=>value2.configurationVersion<=value2.revision);var CurrentAgentHostBindingSchema=AgentHostBindingSchema.safeExtend({selection:CurrentHostSelectionSchema});var UpdateAgentHostSelectionSchema=ConfigureAgentHostSchema.omit({apiCredential:true}).extend({expectedRevision:z3.int().min(1).max(999999998),expectedConfigurationVersion:z3.int().positive().max(999999998)});var AgentHostCurrentSchema=z3.strictObject({binding:AgentHostBindingSchema.nullable()});var AgentHostHistoryQuerySchema=AgentHostScopeSchema.extend({limit:z3.int().min(1).max(100).default(20),beforeVersion:z3.int().positive().max(999999999).optional()});var AgentHostConfigurationVersionSchema=ReadScope.extend({bindingId:ReadId,version:z3.int().positive().max(999999999),selection:AgentHostReadSelectionSchema,createdByPrincipalId:ReadId,createdAt:z3.iso.datetime({offset:true}),revokedAt:z3.iso.datetime({offset:true}).nullable()});var AgentHostHistoryPageSchema=z3.strictObject({items:z3.array(AgentHostConfigurationVersionSchema).max(100),hasMore:z3.boolean(),nextBeforeVersion:z3.int().positive().max(999999999).nullable()}).refine(page5=>page5.hasMore===(page5.nextBeforeVersion!==null)&&(!page5.hasMore||page5.items.length>0));var AgentHostReadinessSchema=ReadScope.extend({binding:AgentHostBindingSchema.nullable(),registeredHostKeys:z3.array(Key).max(16),configurationStatus:z3.enum(["NOT_CONFIGURED","REVOKED","HOST_UNAVAILABLE","CREDENTIAL_UNAVAILABLE","CONFIGURATION_CHANGED","CONFIGURED"]),remoteCredentialVerification:z3.enum(["NOT_CHECKED","VERIFIED"]),nativeToolAuthority:z3.enum(["NOT_CONNECTED","UNVERIFIED","VERIFIED"]),executionAvailability:z3.enum(["UNAVAILABLE","AVAILABLE"]),reason:z3.enum(["NATIVE_TOOL_AUTHORITY_NOT_CONNECTED","NATIVE_TOOL_AUTHORITY_NOT_QUALIFIED","CONFIGURATION_CHANGED"]).nullable(),checkedAt:z3.iso.datetime({offset:true})}).refine(v=>{const verified=v.nativeToolAuthority==="VERIFIED";return(v.binding===null||v.binding.tenantId===v.tenantId&&v.binding.projectId===v.projectId)&&verified===(v.remoteCredentialVerification==="VERIFIED")&&verified===(v.executionAvailability==="AVAILABLE")&&verified===(v.reason===null)&&(!verified||v.configurationStatus==="CONFIGURED"&&v.binding?.enabled===true)});var AgentHostFailureSchema=z3.strictObject({semanticStatus:z3.enum(["INVALID_INPUT","NOT_FOUND","BLOCKED","REVISION_CONFLICT","CAPABILITY_UNAVAILABLE","INTERNAL_OPERATIONAL_FAILURE"]),error:z3.strictObject({code:z3.enum(["INVALID_INPUT","UNAUTHENTICATED","FORBIDDEN","NOT_FOUND","REVISION_CONFLICT","REQUEST_CONFLICT","HOST_UNAVAILABLE","CREDENTIAL_UNAVAILABLE","CREDENTIAL_SCOPE_MISMATCH","BINDING_REVOKED","INTERNAL_OPERATIONAL_FAILURE"]),message:z3.literal("Agent Host operation did not complete")})});var id=z4.uuid().regex(/^[0-9a-f-]{36}$/);var requestId=z4.uuid().toLowerCase();var key=z4.string().regex(/^[A-Za-z0-9_-]{1,160}$/);var NativeRuntimePublicKeySchema=z4.strictObject({kty:z4.literal("EC"),crv:z4.literal("P-256"),x:z4.string().regex(/^[A-Za-z0-9_-]{43}$/),y:z4.string().regex(/^[A-Za-z0-9_-]{43}$/)});var ConfigureNativeToolGrantSchema=AgentHostScopeSchema.extend({requestId,bindingId:requestId,expectedBindingRevision:z4.int().positive(),expectedConfigurationVersion:z4.int().positive(),runtimeKey:key,installationId:key,installationRevisionId:key,publicKey:NativeRuntimePublicKeySchema,expiresAt:z4.iso.datetime({offset:true})});var NativeToolGrantGetSchema=AgentHostScopeSchema.extend({grantId:requestId});var RevokeNativeToolGrantSchema=NativeToolGrantGetSchema.extend({requestId,expectedRevision:z4.int().positive()});var NativeRuntimeProofRequestSchema=NativeToolGrantGetSchema.extend({assertion:z4.string().regex(/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/).max(4096).meta({writeOnly:true})});var NativeRuntimeStatusClaimsSchema=z4.strictObject({iss:key,sub:key,aud:z4.url().max(2048),grantId:id,installationRevisionId:key,jti:id,iat:z4.int().nonnegative(),exp:z4.int().positive()}).refine(v=>v.exp>v.iat&&v.exp-v.iat<=60);var NativeRuntimeProofClaimsSchema=z4.strictObject({iss:key,sub:key,aud:z4.url().max(2048),grantId:id,grantRevision:z4.int().positive(),installationRevisionId:key,challengeId:id,jti:id,iat:z4.int().nonnegative(),exp:z4.int().positive()}).refine(v=>v.exp>v.iat&&v.exp-v.iat<=60);var NativeToolGrantViewSchema=z4.strictObject({tenantId:id,projectId:id}).extend({protocol:z4.literal("NATIVESTUDIO_RUNTIME_REGISTRATION_V1"),grantId:id,bindingId:id,bindingRevision:z4.int().positive(),configurationVersion:z4.int().positive(),selection:AgentHostReadSelectionSchema,runtimeKey:key,installationId:key,installationRevisionId:key,publicKey:NativeRuntimePublicKeySchema,resource:z4.url().max(2048),revision:z4.int().positive(),enabled:z4.boolean(),createdByPrincipalId:id,runtimePrincipalId:id,createdAt:z4.iso.datetime({offset:true}),expiresAt:z4.iso.datetime({offset:true}),challengeId:id,challengeExpiresAt:z4.iso.datetime({offset:true}),verifiedAt:z4.iso.datetime({offset:true}).nullable(),revokedAt:z4.iso.datetime({offset:true}).nullable()}).refine(v=>{const resource=new URL(v.resource);return resource.protocol==="https:"&&!resource.username&&!resource.password&&!resource.search&&!resource.hash&&resource.pathname===`/mcp/native/v1/projects/${v.projectId}`&&v.enabled===(v.revokedAt===null)&&Date.parse(v.challengeExpiresAt)<=Date.parse(v.expiresAt)});var LocalDevicePlatformSchema=z5.strictObject({os:z5.enum(["darwin","linux","win32"]),architecture:z5.enum(["x64","arm64"])});var EnrollLocalDeviceSchema=z5.strictObject({tenantId:LocalIdSchema,requestId:LocalIdSchema,expectedPrincipalId:LocalIdSchema.optional(),label:z5.string().trim().min(1).max(120),platform:LocalDevicePlatformSchema,runtimeVersion:LocalPackageVersionSchema,publicKey:NativeRuntimePublicKeySchema});var LocalDeviceViewSchema=EnrollLocalDeviceSchema.omit({requestId:true,expectedPrincipalId:true}).extend({deviceId:LocalIdSchema,revision:LocalRevisionSchema,enrolledByPrincipalId:LocalIdSchema,createdAt:LocalTimeSchema,verifiedAt:LocalTimeSchema.nullable(),revokedAt:LocalTimeSchema.nullable()}).refine(v=>[v.verifiedAt,v.revokedAt].every(time2=>time2===null||Date.parse(time2)>=Date.parse(v.createdAt)));var LocalDeviceChallengeSchema=z5.strictObject({tenantId:LocalIdSchema,deviceId:LocalIdSchema,deviceRevision:LocalRevisionSchema,challengeId:LocalIdSchema,audience:z5.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=z5.strictObject({protocol:z5.literal("NVS_LOCAL_DEVICE_PROOF_V1"),tenantId:LocalIdSchema,deviceId:LocalIdSchema,deviceRevision:LocalRevisionSchema,challengeId:LocalIdSchema,audience:z5.string().min(1).max(2048),jti:LocalIdSchema,iat:z5.int().nonnegative(),exp:z5.int().positive()}).refine(v=>v.exp>v.iat&&v.exp-v.iat<=60);var ProveLocalDeviceSchema=z5.strictObject({tenantId:LocalIdSchema,deviceId:LocalIdSchema,deviceRevision:LocalRevisionSchema,challengeId:LocalIdSchema,assertion:z5.string().max(4096).regex(/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/).meta({writeOnly:true})});var RevokeLocalDeviceSchema=z5.strictObject({tenantId:LocalIdSchema,deviceId:LocalIdSchema,requestId:LocalIdSchema,expectedRevision:LocalRevisionSchema});import{z as z7}from"zod";import{z as z6}from"zod";var InventoryArguments=z6.strictObject({tenantId:z6.uuid()});var DeviceSetupRecoverySchema=z6.strictObject({reason:z6.enum(["NO_REGISTERED_DEVICE","NO_SUITABLE_DEVICE","CAPABILITY_MISSING","DEVICE_DISCONNECTED","DEVICE_BUSY","INCOMPLETE_INVENTORY"]),action:z6.enum(["PREPARE_OR_REPAIR_HOST","RECONNECT_EXISTING_HOST","WAIT","INSPECT_EXISTING"]),inspect:z6.discriminatedUnion("tool",[z6.strictObject({tool:z6.literal("workspace_caller"),arguments:InventoryArguments}),z6.strictObject({tool:z6.literal("studio_capability_query"),arguments:z6.strictObject({tenantId:z6.uuid(),tool:z6.literal("workspace_devices_list"),arguments:InventoryArguments})})]),guidance:z6.string().min(1).max(1e3)}).superRefine((value2,ctx)=>{const action=value2.reason==="DEVICE_BUSY"?"WAIT":value2.reason==="INCOMPLETE_INVENTORY"||value2.reason==="NO_SUITABLE_DEVICE"?"INSPECT_EXISTING":value2.reason==="DEVICE_DISCONNECTED"?"RECONNECT_EXISTING_HOST":"PREPARE_OR_REPAIR_HOST";const tool=action==="WAIT"||action==="INSPECT_EXISTING"?"studio_capability_query":"workspace_caller";if(value2.action!==action||value2.inspect.tool!==tool)ctx.addIssue({code:"custom",message:"Recovery must match the observed device condition"});if(value2.inspect.tool==="studio_capability_query"&&value2.inspect.arguments.tenantId.toLowerCase()!==value2.inspect.arguments.arguments.tenantId.toLowerCase())ctx.addIssue({code:"custom",message:"Recovery scope must match the inventory target"})});var WorkspaceDeviceListInputSchema=z7.strictObject({tenantId:LocalIdSchema,deviceId:LocalIdSchema.optional(),after:LocalIdSchema.optional(),limit:z7.int().min(1).max(50).default(25)});var WorkspaceDeviceInventoryItemSchema=z7.strictObject({deviceId:LocalIdSchema,label:z7.string().trim().min(1).max(120),platform:LocalDevicePlatformSchema,runtimeVersion:LocalPackageVersionSchema.nullable(),runtimeVersionObservedAt:LocalTimeSchema.nullable(),revision:LocalRevisionSchema,createdAt:LocalTimeSchema,verifiedAt:LocalTimeSchema.nullable(),revokedAt:LocalTimeSchema.nullable(),lastSeenAt:LocalTimeSchema.nullable(),connection:z7.enum(["UNVERIFIED","REVOKED","OWNER_UNAVAILABLE","CONNECTED","DISCONNECTED"])}).refine(value2=>value2.runtimeVersion===null===(value2.runtimeVersionObservedAt===null),{message:"Runtime version and observation time must be present together"});var WorkspaceDeviceListSchema=z7.strictObject({tenantId:LocalIdSchema,observedAt:LocalTimeSchema,items:z7.array(WorkspaceDeviceInventoryItemSchema).max(50),nextCursor:LocalIdSchema.nullable(),recovery:DeviceSetupRecoverySchema.optional()});import{z as z8}from"zod";var identity={deviceId:LocalIdSchema,deviceRevision:LocalRevisionSchema};var WorkspaceDeviceAuthoritySchema=z8.strictObject({...identity,authority:z8.literal("WORKSPACE_DEVICE_V1")});var LocalDeviceExecutionTargetSchema=z8.discriminatedUnion("kind",[WorkspaceDeviceAuthoritySchema.extend({kind:z8.literal("DEVICE")}),z8.strictObject({kind:z8.literal("SERVER")})]);var TenantDeviceTargetSchema=WorkspaceDeviceAuthoritySchema.extend({keyFingerprint:LocalDigestSchema});function sameDeviceAuthority(a,b){return a.deviceId===b.deviceId&&a.deviceRevision===b.deviceRevision&&a.authority===b.authority}import{z as z65}from"zod";import{z as z28}from"zod";import{z as z26}from"zod";import{z as z9}from"zod";var offset=z9.int().min(0).max(4094).multipleOf(2);var dimension=z9.int().min(2).max(4096).multipleOf(2);var ClipFramingSchema=z9.strictObject({algorithm:z9.literal("CROP_PAD_V1"),crop:z9.strictObject({x:offset,y:offset,width:dimension,height:dimension}),anchorXPermille:z9.int().min(0).max(1e3),anchorYPermille:z9.int().min(0).max(1e3)});var PicturePolicySchema=z9.literal("CROP_PAD_V1");import{z as z10}from"zod";var ClipTransitionSchema=z10.union([z10.literal("CUT"),z10.strictObject({kind:z10.literal("CROSS_DISSOLVE_V1"),durationFrames:z10.int().min(2).max(30)})]);import{z as z11}from"zod";var sha=z11.string().regex(/^[0-9a-f]{64}$/);var GraphicPlacementSchema=z11.strictObject({startFrame:z11.int().nonnegative().max(1800),endFrame:z11.int().positive().max(1800),anchor:z11.enum(["TOP_LEFT","TOP_RIGHT","BOTTOM_LEFT","BOTTOM_RIGHT"]),widthPermille:z11.int().min(50).max(400),marginXPermille:z11.int().min(0).max(100),marginYPermille:z11.int().min(0).max(100),opacityPermille:z11.int().min(100).max(1e3)}).refine(v=>v.endFrame>v.startFrame,"Graphic frame interval must advance");var TimelineGraphicInputSchema=z11.strictObject({artifactId:ArtifactIdSchema,placement:GraphicPlacementSchema});var TimelineGraphicSourceSchema=z11.strictObject({tenantId:TenantIdSchema,projectId:ProjectIdSchema,productionId:ProductionIdSchema.nullable(),artifactId:ArtifactIdSchema,representationId:ArtifactRepresentationIdSchema,checksumSha256:sha,contentType:z11.enum(["image/png","image/webp"]),byteSize:z11.int().positive().max(16*1024*1024),width:z11.int().positive().max(8192),height:z11.int().positive().max(8192)});var TimelineGraphicSchema=z11.strictObject({source:TimelineGraphicSourceSchema,placement:GraphicPlacementSchema});import{z as z13}from"zod";import{z as z12}from"zod";var id2=z12.uuid().toLowerCase();var hash=z12.string().regex(/^[0-9a-f]{64}$/);var CaptionTranscriptPlacementSchema=z12.discriminatedUnion("kind",[z12.strictObject({kind:z12.literal("AUDIO_TRACK"),purpose:z12.enum(["VOICEOVER","MUSIC"])}),z12.strictObject({kind:z12.literal("SPEECH_CUE"),cueId:z12.string().regex(/^[a-z][a-z0-9_-]{0,63}$/)}),z12.strictObject({kind:z12.literal("TIMELINE_OUTPUT")})]);var CaptionTranscriptPlanSchema=z12.strictObject({tenantId:TenantIdSchema,productionId:ProductionIdSchema,timelineVersionId:id2,language:z12.string().regex(/^[A-Za-z]{2,8}(?:-[A-Za-z0-9]{1,8})*$/).max(60),sources:z12.array(z12.strictObject({observationId:id2,placement:CaptionTranscriptPlacementSchema,granularity:z12.enum(["word","segment"])})).min(1).max(64)});var AuthorTranscriptCaptionsSchema=CaptionTranscriptPlanSchema.extend({expectedProductionRevision:z12.int().positive(),expectedCaptionVersion:z12.int().nonnegative(),idempotencyKey:z12.string().trim().min(1).max(200)});var CaptionTranscriptProvenanceSchema=z12.strictObject({schemaVersion:z12.literal(1),advisory:z12.literal(true),timing:z12.literal("PROVIDER_REPORTED"),timelineVersionId:id2,timingFingerprint:hash,sources:z12.array(z12.strictObject({observationId:id2,artifactId:id2,representationId:id2,checksumSha256:hash,placement:CaptionTranscriptPlacementSchema,granularity:z12.enum(["word","segment"]),sourceInMs:z12.int().nonnegative(),sourceOutMs:z12.int().positive(),startMs:z12.int().nonnegative(),spanIndices:z12.array(z12.int().nonnegative().max(1199)).min(1).max(120),excludedSpans:z12.int().nonnegative().max(1200)})).min(1).max(64)});var sha2=z13.string().regex(/^[0-9a-f]{64}$/);var CaptionContentSchema=z13.strictObject({language:z13.string().regex(/^[A-Za-z]{2,8}(?:-[A-Za-z0-9]{1,8})*$/).max(60),durationMs:z13.int().min(3e4).max(6e4),cues:z13.array(z13.strictObject({startMs:z13.int().nonnegative().max(59999),endMs:z13.int().positive().max(6e4),text:z13.string().min(1).max(240)})).min(1).max(120)});var CaptionScopeSchema=z13.strictObject({tenantId:TenantIdSchema,productionId:ProductionIdSchema});var AuthorCaptionsSchema=CaptionScopeSchema.extend({expectedProductionRevision:z13.int().positive(),expectedCaptionVersion:z13.int().nonnegative(),idempotencyKey:z13.string().trim().min(1).max(200),content:CaptionContentSchema});var CaptionGetSchema=CaptionScopeSchema.extend({versionId:z13.uuid()});var CaptionQuerySchema=CaptionScopeSchema.extend({limit:QueryLimitSchema,next:ContinuationSchema.optional()});var CaptionRepresentationSchema=z13.strictObject({id:z13.uuid(),checksumSha256:sha2,byteSize:z13.int().positive().max(131072)});var CaptionVersionSchema=CaptionScopeSchema.extend({transcriptProvenance:CaptionTranscriptProvenanceSchema.optional(),id:z13.uuid(),captionId:z13.uuid(),projectId:z13.uuid(),version:z13.int().positive(),artifactId:z13.uuid(),content:CaptionContentSchema,fingerprint:sha2,original:CaptionRepresentationSchema,subtitle:CaptionRepresentationSchema,previousVersionId:z13.uuid().nullable(),createdByPrincipalId:z13.uuid(),createdAt:z13.iso.datetime({offset:true})});var CaptionViewSchema=z13.strictObject({version:CaptionVersionSchema,isCurrent:z13.boolean(),availability:z13.enum(["AVAILABLE","UNAVAILABLE"])});var CaptionReceiptSchema=z13.strictObject({semanticStatus:z13.literal("SUCCESS"),version:CaptionVersionSchema,productionRevision:z13.int().positive()});var CaptionBasisSchema=CaptionScopeSchema.extend({productionRevision:z13.int().positive(),currentVersion:z13.int().nonnegative(),currentVersionId:z13.uuid().nullable(),authorable:z13.boolean()});var CaptionPageSchema=z13.strictObject({items:z13.array(CaptionViewSchema).max(200),page:QueryPageInfoSchema});var CaptionExportSchema=CaptionGetSchema.extend({format:z13.enum(["JSON","SRT"])});var CaptionSnapshotSchema=z13.strictObject({currentVersion:z13.int().positive().nullable(),currentVersionId:z13.uuid().nullable(),artifactId:z13.uuid().nullable(),availability:z13.enum(["NONE","AVAILABLE","UNAVAILABLE"]),cueCount:z13.int().nonnegative().max(120),durationMs:z13.int().min(3e4).max(6e4).nullable(),attachedToTimeline:z13.boolean(),attachedCaptionVersionId:z13.uuid().nullable().optional(),attachedTimelineVersionId:z13.uuid().nullable().optional()});var CaptionTranscriptDraftSchema=z13.strictObject({content:CaptionContentSchema,provenance:CaptionTranscriptProvenanceSchema});import{z as z14}from"zod";var LegacyCaptionRenderStyleSchema=z14.strictObject({id:z14.literal("PLAIN_TEXT_NOTO_SANS_SC_V1"),fontSha256:z14.literal("a3041811a78c361b1de50f953c805e0244951c21c5bd412f7232ef0d899af0da"),framePolicy:z14.literal("PTS_HALF_OPEN_CEIL_V1")});var RegularCaptionRenderStyleSchema=z14.strictObject({id:z14.literal("PLAIN_TEXT_NATIVE_SC_REGULAR_V2"),fontSha256:z14.literal("e5a51f41fc1b827da651afee3975e07a182ff4f8e04d9dfc0a3cecd6177a52b6"),framePolicy:z14.literal("PTS_HALF_OPEN_CEIL_V1")});var CaptionRenderStyleSchema=z14.discriminatedUnion("id",[LegacyCaptionRenderStyleSchema,RegularCaptionRenderStyleSchema]);import{z as z17}from"zod";import{z as z16}from"zod";import{z as z15}from"zod";var VoiceProfileRefSchema=z15.strictObject({ownerSystem:z15.string().regex(/^[a-z][a-z0-9-]{1,79}$/),ownerTenantRef:z15.string().trim().min(1).max(160),voiceProfileRef:z15.string().trim().min(1).max(160),version:z15.int().positive(),digest:z15.string().regex(/^[a-f0-9]{64}$/)});var VoiceLocaleSchema=z15.string().min(2).max(35).refine(value2=>{try{return value2.toLowerCase()!=="auto"&&Intl.getCanonicalLocales(value2).length===1}catch{return false}},"A concrete BCP 47 language is required").describe("Concrete BCP 47 tag, for example zh or en-US; auto is not a language");var VoiceProfileUseSchema=z15.strictObject({ref:VoiceProfileRefSchema,bindingKey:z15.string().regex(/^[a-z][a-z0-9_-]{0,63}$/),language:VoiceLocaleSchema,usage:z15.enum(["AUDITION","PRODUCTION"])});var sha3=z16.string().regex(/^[0-9a-f]{64}$/);var AudioPurposeSchema=z16.enum(["VOICEOVER","MUSIC"]);var AudioProductionScopeSchema=z16.strictObject({tenantId:TenantIdSchema,productionId:ProductionIdSchema});var AudioScopeSchema=AudioProductionScopeSchema.extend({purpose:AudioPurposeSchema});var AudioMaterialPurposeSchema=z16.enum(["VOICEOVER","MUSIC","VOICE_SAMPLE"]);var AudioReadScopeSchema=AudioScopeSchema.extend({purpose:AudioMaterialPurposeSchema});var AudioMediaSchema=z16.strictObject({profile:z16.literal("PCM_S16LE_48000_V1"),audioCodec:z16.literal("pcm_s16le"),sampleRateHz:z16.literal(48e3),audioChannels:z16.union([z16.literal(1),z16.literal(2)]),sampleCount:z16.int().min(4800).max(288e4),durationMs:z16.int().min(100).max(6e4)}).refine(m=>m.sampleCount*1e3===m.durationMs*m.sampleRateHz,{message:"Exact PCM sample count must match duration"});var AudioImportSchema=AudioScopeSchema.extend({expectedProductionRevision:z16.int().positive(),expectedAudioVersion:z16.int().nonnegative(),idempotencyKey:z16.string().trim().min(1).max(200),contentType:z16.literal("audio/wav"),originalName:z16.string().trim().min(1).max(255).regex(/^[^\p{Cc}]*$/u).optional()});var AudioImportRequestSchema=AudioImportSchema.extend({contentBase64:z16.string().min(60).max(16777216).regex(/^[A-Za-z0-9+/]*={0,2}$/)});var AudioPublicationSchema=AudioImportSchema.extend({purpose:AudioMaterialPurposeSchema});var AudioGetSchema=AudioReadScopeSchema.extend({versionId:z16.uuid()});var AudioQuerySchema=AudioReadScopeSchema.extend({limit:QueryLimitSchema,next:ContinuationSchema.optional()});var AudioRepresentationSchema=z16.strictObject({id:z16.uuid(),checksumSha256:sha3,byteSize:z16.int().min(44).max(12582912)});var AudioVersionSchema=AudioReadScopeSchema.extend({id:z16.uuid(),audioId:z16.uuid(),projectId:z16.uuid(),version:z16.int().positive(),artifactId:z16.uuid(),original:AudioRepresentationSchema,media:AudioMediaSchema,originalName:z16.string().trim().min(1).max(255).regex(/^[^\p{Cc}]*$/u).nullable(),previousVersionId:z16.uuid().nullable(),createdByPrincipalId:z16.uuid(),createdAt:z16.iso.datetime({offset:true}),generation:z16.strictObject({generationId:z16.uuid(),voiceProfile:VoiceProfileUseSchema.optional(),executionClass:z16.enum(["LIVE","TEST_ONLY"]),executionTarget:z16.literal("TENANT_DEVICE").optional(),sourceArtifactId:z16.uuid(),sourceRepresentationId:z16.uuid(),sourceChecksumSha256:sha3,sourceByteSize:z16.int().min(44).max(12582912),sourceMedia:z16.strictObject({sampleRateHz:z16.int().positive().max(48e3),audioChannels:z16.union([z16.literal(1),z16.literal(2)]),sampleCount:z16.int().positive()}),normalizationVersion:z16.literal("SPEECH_PCM_V1"),padSamples:z16.int().min(0).max(47)}).optional()}).refine(v=>v.version===1===(v.previousVersionId===null),{message:"Audio replacement history must preserve exact preceding version"});var AudioViewSchema=z16.strictObject({version:AudioVersionSchema,isCurrent:z16.boolean(),availability:z16.enum(["AVAILABLE","UNAVAILABLE"])});var ProductionAudioVersionSchema=AudioVersionSchema.safeExtend({purpose:AudioPurposeSchema});var AudioReceiptSchema=z16.strictObject({semanticStatus:z16.literal("SUCCESS"),version:AudioVersionSchema,productionRevision:z16.int().positive()});var AudioBasisSchema=AudioReadScopeSchema.extend({productionRevision:z16.int().positive(),currentVersion:z16.int().nonnegative(),currentVersionId:z16.uuid().nullable(),importable:z16.boolean()});var AudioPageSchema=z16.strictObject({items:z16.array(AudioViewSchema).max(200),page:QueryPageInfoSchema});var AudioSnapshotSchema=z16.strictObject({tracks:z16.array(z16.strictObject({purpose:AudioPurposeSchema,currentVersion:z16.int().positive().nullable(),currentVersionId:z16.uuid().nullable(),artifactId:z16.uuid().nullable(),availability:z16.enum(["NONE","AVAILABLE","UNAVAILABLE"]),durationMs:z16.int().min(100).max(6e4).nullable(),audioChannels:z16.union([z16.literal(1),z16.literal(2)]).nullable(),attachedToTimeline:z16.boolean()})).length(2)});var placement={sourceInMs:z17.int().nonnegative().max(6e4),sourceOutMs:z17.int().positive().max(6e4),startMs:z17.int().nonnegative().max(6e4),gainPermille:z17.int().nonnegative().max(1e3)};var TimelineAudioInputSchema=z17.strictObject({tracks:z17.array(z17.strictObject({purpose:AudioPurposeSchema,versionId:z17.uuid(),...placement})).min(1).max(2),duckingMusicPermille:z17.int().nonnegative().max(1e3).default(1e3)}).superRefine((audio2,ctx)=>{if(new Set(audio2.tracks.map(t=>t.purpose)).size!==audio2.tracks.length||audio2.tracks.some(t=>t.sourceOutMs<=t.sourceInMs)||audio2.duckingMusicPermille<1e3&&audio2.tracks.length!==2)ctx.addIssue({code:"custom",message:"Distinct purposes, advancing trims and explicit ducking pair required"})});var AudioMixProfileSchema=z17.strictObject({id:z17.literal("PCM_WINDOW_MIX_AAC_V1"),sampleRateHz:z17.literal(48e3),audioChannels:z17.literal(2),audioCodec:z17.literal("aac"),bitrate:z17.literal(192e3),peakPermille:z17.literal(950),duckingMusicPermille:z17.int().nonnegative().max(1e3)});var TimelineAudioCompositionSchema=z17.strictObject({mix:AudioMixProfileSchema,tracks:z17.array(z17.strictObject({source:ProductionAudioVersionSchema,...placement})).min(1).max(2)}).superRefine((audio2,ctx)=>{if(new Set(audio2.tracks.map(t=>t.source.purpose)).size!==audio2.tracks.length||audio2.tracks.some(t=>t.sourceOutMs<=t.sourceInMs||t.sourceOutMs>t.source.media.durationMs)||audio2.mix.duckingMusicPermille<1e3&&audio2.tracks.length!==2)ctx.addIssue({code:"custom",message:"Invalid exact audio composition"})});var RenderedAudioSchema=z17.strictObject({audioCodec:z17.literal("aac"),sampleRateHz:z17.literal(48e3),audioChannels:z17.literal(2),sampleCount:z17.int().positive().max(288e4)});import{z as z18}from"zod";var Fingerprint=z18.string().regex(/^[0-9a-f]{64}$/);var AcceptedShotReferenceSchema=z18.strictObject({acceptanceId:z18.uuid(),reviewId:z18.uuid(),generationId:z18.uuid(),candidateId:z18.uuid(),shotId:ShotIdSchema,artifactId:ArtifactIdSchema,representationId:ArtifactRepresentationIdSchema,checksumSha256:Fingerprint,artifactChecksumSha256:Fingerprint,preparationId:z18.uuid(),contractId:z18.uuid(),contractFingerprint:Fingerprint,planVersionId:SceneShotPlanVersionIdSchema,planVersion:z18.int().positive(),shotPlanningRevision:z18.int().positive(),executionClass:z18.enum(["LIVE","TEST_ONLY"]),reviewResult:z18.enum(["PASS","WARNING"])});import{z as z20}from"zod";import{z as z19}from"zod";var ProviderIdSchema=z19.enum(["QWEN_CN","VOLCENGINE_CN","GEMINI","OPENAI","XAI"]);var ProviderConnectionIdSchema=z19.uuid().brand();var ModelProfileIdSchema=z19.string().regex(/^[a-z][a-z0-9-]{1,79}$/);var GeometryPolicySchema=z19.enum(["STRICT","PAD_TO_ASPECT"]);var ProviderSelectionSchema=z19.strictObject({connectionId:ProviderConnectionIdSchema,modelProfileId:ModelProfileIdSchema});var TenantProviderExecutionGrantSchema=z19.strictObject({projectId:z19.uuid(),modelProfileId:ModelProfileIdSchema,modelProfileVersion:z19.int().positive(),workload:z19.enum(["KEYFRAME_GENERATE","VIDEO_GENERATE","SPEECH_SYNTHESIS","TRANSCRIPTION","AUDIO_OBSERVATION","VIDEO_OBSERVATION"]),disclosure:z19.enum(["TEXT_ONLY","IMMUTABLE_PROJECT_INPUTS"]),expiresAt:z19.iso.datetime({offset:true}),maxPerRequestMicros:z19.int().min(0).max(1e9),maxTotalMicros:z19.int().min(0).max(1e9),maxSubmissions:z19.int().min(1).max(1e4)}).refine(v=>v.maxPerRequestMicros<=v.maxTotalMicros);var providerConfigurationFields={providerId:ProviderIdSchema,label:z19.string().trim().min(1).max(100),allowedModelProfileIds:z19.array(ModelProfileIdSchema).min(1).max(16),qwenEndpoint:z19.literal("QIANWEN_PLATFORM").optional(),credentialService:z19.enum(["ARK","DOUBAO_SPEECH"]).optional(),qwenWorkspaceId:z19.string().regex(/^[a-z0-9][a-z0-9-]{0,63}$/).optional(),geometryPolicy:GeometryPolicySchema.default("STRICT")};var ProviderConfigurationSchema=z19.strictObject({...providerConfigurationFields,tenantExecution:z19.array(TenantProviderExecutionGrantSchema).min(1).max(64).optional()}).superRefine((v,c)=>{if(new Set(v.allowedModelProfileIds).size!==v.allowedModelProfileIds.length)c.addIssue({code:"custom",message:"Duplicate model profile"});const grants=v.tenantExecution??[];const keys=new Set(grants.map(g=>[g.projectId.toLowerCase(),g.modelProfileId,g.workload].join(":")));if(keys.size!==grants.length||grants.some(g=>!v.allowedModelProfileIds.includes(g.modelProfileId)))c.addIssue({code:"custom",message:"Invalid tenant execution scope",path:["tenantExecution"]});if(v.qwenWorkspaceId&&v.providerId!=="QWEN_CN")c.addIssue({code:"custom",message:"Workspace only applies to Qwen China"});if(v.credentialService&&v.providerId!=="VOLCENGINE_CN")c.addIssue({code:"custom",message:"Credential service applies to Volcengine"});if(v.qwenEndpoint&&(v.providerId!=="QWEN_CN"||v.qwenWorkspaceId))c.addIssue({code:"custom",message:"Qianwen platform requires an exact Qwen route without a workspace"})});var ConfigureProviderInputSchema=z19.strictObject({tenantId:TenantIdSchema,connectionId:ProviderConnectionIdSchema,expectedVersion:z19.int().nonnegative(),configuration:ProviderConfigurationSchema,apiKey:z19.string().min(8).max(4096).regex(/^[!-~]+$/)});var ProviderConnectionViewSchema=z19.strictObject({tenantId:TenantIdSchema,connectionId:ProviderConnectionIdSchema,version:z19.int().positive(),enabled:z19.boolean(),credentialConfigured:z19.boolean(),configuration:z19.object(providerConfigurationFields),createdByPrincipalId:PrincipalIdSchema,updatedAt:z19.iso.datetime({offset:true})});var ProviderConnectionCommandSchema=z19.strictObject({tenantId:TenantIdSchema,connectionId:ProviderConnectionIdSchema,expectedVersion:z19.int().positive()});var ProviderCredentialRevokeSchema=z19.strictObject({tenantId:TenantIdSchema,connectionId:ProviderConnectionIdSchema,version:z19.int().positive()});var SetKeyframeDefaultSchema=z19.strictObject({tenantId:TenantIdSchema,selection:ProviderSelectionSchema,expectedRevision:z19.int().nonnegative()});var ProviderExecutionBindingSchema=z19.strictObject({tenantId:TenantIdSchema,connectionId:ProviderConnectionIdSchema,connectionVersion:z19.int().positive(),providerId:ProviderIdSchema,modelProfileId:ModelProfileIdSchema,modelProfileVersion:z19.int().positive(),modelId:z19.string().min(1).max(160),credentialRef:z19.uuid(),credentialVersion:z19.int().positive(),geometryPolicy:GeometryPolicySchema,qwenEndpoint:z19.literal("QIANWEN_PLATFORM").optional()}).refine(binding=>!binding.qwenEndpoint||binding.providerId==="QWEN_CN",{message:"Qianwen platform binding requires Qwen China"});var GenerationCostVariantSchema=z20.strictObject({mode:z20.enum(["REFERENCE_TO_IMAGE","REFERENCE_TO_VIDEO","FIRST_FRAME_TO_VIDEO","FIRST_LAST_FRAME_TO_VIDEO"]),aspectRatio:z20.enum(["16:9","9:16"]),workingWidth:z20.int().min(0).max(4096),workingHeight:z20.int().min(0).max(4096),hasAudio:z20.boolean(),references:z20.int().min(0).max(24),durationSeconds:z20.number().finite().min(0).max(30)});var GenerationCostPolicySchema=z20.strictObject({currency:z20.literal("USD"),sourceUrl:z20.url({protocol:/^https$/}).max(2e3),rationale:z20.string().trim().min(1).max(2e3),validUntil:z20.iso.datetime({offset:true}),rules:z20.array(z20.strictObject({id:z20.string().regex(/^[a-zA-Z0-9_-]{1,80}$/),variant:GenerationCostVariantSchema,upperBoundMicros:z20.int().nonnegative().max(1e9)})).min(1).max(64)}).refine(p=>new Set(p.rules.map(r=>r.id)).size===p.rules.length,"Duplicate cost rule");var ExpectedGenerationExecutionSchema=z20.strictObject({connectionVersion:z20.int().positive(),modelProfileVersion:z20.int().positive(),quoteValidUntil:z20.iso.datetime({offset:true})});var GenerationCostQuoteSchema=z20.strictObject({currency:z20.literal("USD"),upperBoundMicros:z20.int().nonnegative().max(1e9),selection:ProviderSelectionSchema,expectedExecution:ExpectedGenerationExecutionSchema,sourceUrl:z20.url({protocol:/^https$/}).max(2e3),ruleIds:z20.array(z20.string()).min(1).max(64),preparationId:z20.uuid(),contractFingerprint:z20.string().regex(/^[a-f0-9]{64}$/)});import{z as z25}from"zod";import{z as z21}from"zod";var id3=z21.uuid().toLowerCase();var hash2=z21.string().regex(/^[0-9a-f]{64}$/);var NativeVideoAudioMetadataSchema=z21.strictObject({normalizationVersion:z21.literal("VIDEO_AUDIO_PCM_V1"),sourceCodec:z21.literal("aac"),sourceSampleRateHz:z21.int().min(8e3).max(96e3),sourceChannels:z21.union([z21.literal(1),z21.literal(2)]),sourceFrameRateHz:z21.union([z21.literal(24),z21.literal(30)]),sourceFrameCount:z21.int().positive().max(905),sourceStartOffsetMs:z21.number().finite().min(-500).max(5e3),sourceDeclaredDurationMs:z21.number().positive().max(31e3),alignment:z21.literal("TRIM_PAD_PCM_TO_VIDEO_ZERO_V1"),media:z21.strictObject({profile:z21.literal("PCM_S16LE_48000_NATIVE_VIDEO_V1"),audioCodec:z21.literal("pcm_s16le"),sampleRateHz:z21.literal(48e3),audioChannels:z21.union([z21.literal(1),z21.literal(2)]),sampleCount:z21.int().positive().max(1448e3),durationMs:z21.number().positive().max(30200)}).refine(m=>m.durationMs===m.sampleCount/48),checksumSha256:hash2}).superRefine((v,ctx)=>{if(v.media.sampleCount!==v.sourceFrameCount*(48e3/v.sourceFrameRateHz)||v.media.audioChannels!==v.sourceChannels)ctx.addIssue({code:"custom",message:"Native PCM must follow the exact source video frame clock"})});var NativeVideoSoundReferenceSchema=z21.strictObject({id:id3,tenantId:id3,projectId:id3,productionId:id3,shotId:id3,generationId:id3,videoArtifactId:id3,videoRepresentationId:id3,videoChecksumSha256:hash2,artifactId:id3,representationId:id3,checksumSha256:hash2,byteSize:z21.int().min(44).max(12582912),metadata:NativeVideoAudioMetadataSchema,executionClass:z21.enum(["LIVE","TEST_ONLY"])});import{z as z22}from"zod";var KeyframePurposeSchema=z22.enum(["START_FRAME","END_FRAME","SUBJECT_REFERENCE"]);var AcceptedKeyframeReferenceSchema=z22.strictObject({acceptanceId:z22.uuid(),reviewId:z22.uuid(),generationId:z22.uuid(),candidateId:z22.uuid(),shotId:ShotIdSchema,framePurpose:KeyframePurposeSchema,artifactId:ArtifactIdSchema,representationId:ArtifactRepresentationIdSchema,checksumSha256:z22.string().regex(/^[0-9a-f]{64}$/),artifactChecksumSha256:z22.string().regex(/^[0-9a-f]{64}$/),planVersionId:SceneShotPlanVersionIdSchema,planVersion:z22.int().positive(),shotPlanningRevision:z22.int().positive(),executionClass:z22.enum(["LIVE","TEST_ONLY"])});import{z as z24}from"zod";import{z as z23}from"zod";var ConsistencyReviewScaleSchema=z23.enum(["INTRA_SHOT","INTER_SHOT","PRODUCTION"]);var State=z23.string().trim().min(1).max(300);var StoryTime=z23.int().nonnegative().max(31536e8);var position=z23.int().min(1).max(999);var StateChange=z23.strictObject({atPermille:position,from:State,to:State,reason:State});var TimeJump=z23.strictObject({atPermille:position,fromMs:StoryTime,toMs:StoryTime,reason:State});var ContinuityExpectationSchema=z23.discriminatedUnion("kind",[z23.strictObject({kind:z23.literal("STATE"),mode:z23.enum(["PRESERVE","PLANNED_TRANSITIONS"]),entry:State,exit:State,changes:z23.array(StateChange).min(1).max(16).optional()}).superRefine((v,c)=>{const changes=v.changes??[];if(v.mode==="PLANNED_TRANSITIONS"!==!!changes.length||!changes.length&&v.entry!==v.exit||changes.length&&(changes[0].from!==v.entry||changes.at(-1).to!==v.exit)||changes.some((x,i)=>x.from===x.to||i>0&&(x.atPermille<=changes[i-1].atPermille||x.from!==changes[i-1].to)))c.addIssue({code:"custom",message:"State changes require an ordered explicit plan with exact entry and exit"})}),z23.strictObject({kind:z23.literal("TIME"),mode:z23.enum(["MONOTONIC","PLANNED_JUMPS"]),entryMs:StoryTime,exitMs:StoryTime,jumps:z23.array(TimeJump).min(1).max(16).optional()}).superRefine((v,c)=>{const jumps=v.jumps??[];if(v.mode==="PLANNED_JUMPS"!==!!jumps.length||!jumps.length&&v.exitMs<v.entryMs||jumps.length&&(jumps[0].fromMs<v.entryMs||jumps.at(-1).toMs>v.exitMs)||jumps.some((x,i)=>x.fromMs===x.toMs||i>0&&(x.atPermille<=jumps[i-1].atPermille||x.fromMs<jumps[i-1].toMs)))c.addIssue({code:"custom",message:"Story time requires monotonic segments separated by exact planned jumps"})})]);var ContinuitySampleSchema=z23.strictObject({atMs:z23.int().nonnegative().max(6e4),state:State.optional(),storyTimeMs:StoryTime.optional()}).superRefine((v,c)=>{if(v.state!==void 0===(v.storyTimeMs!==void 0))c.addIssue({code:"custom",message:"A sample observes exactly one state or story-time value"})});var ContinuitySamplesSchema=z23.array(ContinuitySampleSchema).min(3).max(64);var PreparationIdSchema=z24.uuid().brand();var GenerationContractIdSchema=z24.uuid().brand();var ContentFingerprintSchema=z24.string().regex(/^[0-9a-f]{64}$/);var PreparationTargetSchema=z24.discriminatedUnion("mediaType",[z24.strictObject({mediaType:z24.literal("IMAGE"),purpose:z24.enum(["KEYFRAME","REFERENCE_FRAME"]),framePurpose:z24.enum(["START_FRAME","END_FRAME","SUBJECT_REFERENCE"])}),z24.strictObject({mediaType:z24.literal("VIDEO"),purpose:z24.literal("SHOT_CANDIDATE")})]);var PreparationBasisSchema=z24.strictObject({tenantId:TenantIdSchema,projectId:ProjectIdSchema,productionId:ProductionIdSchema,sceneId:SceneIdSchema,shotId:ShotIdSchema,productionRevision:z24.int().positive(),briefVersionId:BriefVersionIdSchema,briefVersion:z24.int().positive(),storyVersionId:StoryVersionIdSchema,storyVersion:z24.int().positive(),planVersionId:SceneShotPlanVersionIdSchema,planVersion:z24.int().positive(),shotPlanningRevision:z24.int().positive(),resolverVersion:z24.literal("w7-product-preflight-v1"),consistencyProfile:z24.strictObject({id:z24.uuid(),version:z24.int().positive(),effectiveFingerprint:ContentFingerprintSchema}).optional()});var ReferenceRoleSchema=z24.enum(["PRODUCT_IDENTITY","PRODUCT_PACKSHOT","CHARACTER_IDENTITY","WARDROBE","LOCATION","STYLE","START_FRAME_ANCHOR","END_FRAME_ANCHOR"]);var ReferenceBindingInputSchema=z24.strictObject({keyframeAcceptanceId:z24.uuid().optional(),role:ReferenceRoleSchema,artifactId:ArtifactIdSchema,representationId:ArtifactRepresentationIdSchema,checksumSha256:ContentFingerprintSchema,reason:z24.string().trim().min(1).max(500)});var ExactEvidenceReferenceSchema=z24.strictObject({artifactId:ArtifactIdSchema,representationId:ArtifactRepresentationIdSchema,checksumSha256:ContentFingerprintSchema,artifactChecksumSha256:ContentFingerprintSchema});var ResolvedReferenceSchema=ReferenceBindingInputSchema.extend({artifactChecksumSha256:ContentFingerprintSchema,contentType:z24.enum(["image/png","image/jpeg","image/webp"]),acceptedKeyframe:AcceptedKeyframeReferenceSchema.optional(),consistencyRuleId:z24.uuid().optional(),subjectId:z24.uuid().optional(),authority:z24.enum(["BRIEF_SOURCE_AND_EXPLICIT_BINDING","EXPLICIT_SHOT_BINDING","CANONICAL_PROFILE_MASTER","ACCEPTED_KEYFRAME_AND_EXPLICIT_BINDING"])});var ResolvedConstraintSchema=z24.strictObject({continuity:ContinuityExpectationSchema.optional(),reviewScales:z24.array(ConsistencyReviewScaleSchema).min(1).max(3).optional(),key:z24.string().min(1).max(200),family:z24.enum(["PRODUCT_IDENTITY","CHARACTER_IDENTITY","WARDROBE","LOCATION","STYLE","SHOT_INTENT","BOUNDARY_CONTINUITY"]),scope:z24.enum(["PROJECT","PRODUCTION","SCENE","SHOT","CONTINUITY_EDGE"]),subjectId:z24.uuid().optional(),dimension:z24.string().regex(/^[A-Z][A-Z0-9_]{0,63}$/).optional(),enforcement:z24.enum(["LOCKED","REQUIRED","PREFERRED"]),expected:z24.string().min(1).max(1e3),source:z24.strictObject({kind:z24.enum(["BRIEF","SCENE","SHOT","CONTINUITY_EDGE","CONSISTENCY_PROFILE"]),id:z24.uuid(),version:z24.int().positive()})});var PreparationBlockerSchema=z24.strictObject({code:z24.enum(["MISSING_PRODUCT_REFERENCE","CANONICAL_SOURCE_UNAVAILABLE","CONSTRAINT_CONFLICT","PREVIOUS_SHOT_EVIDENCE_UNAVAILABLE","GENERATED_KEYFRAME_REQUIRED"]),summary:z24.string().min(1).max(1e3),relatedShotId:ShotIdSchema.optional(),edgeId:ContinuityEdgeIdSchema.optional()});var ConstraintSetSchema=z24.strictObject({preparationId:PreparationIdSchema,version:z24.int().positive(),fingerprint:ContentFingerprintSchema,items:z24.array(ResolvedConstraintSchema).max(2048)});var ReferenceSetSchema=z24.strictObject({preparationId:PreparationIdSchema,version:z24.int().positive(),fingerprint:ContentFingerprintSchema,bindings:z24.array(ResolvedReferenceSchema).max(12)});var VideoGenerationIdSchema=z25.uuid().brand();var VideoProviderProfileSchema=z25.strictObject({id:z25.string().regex(/^[a-z][a-z0-9-]{1,79}$/),adapterVersion:z25.string().min(1).max(80),model:z25.string().min(1).max(160),executionClass:z25.enum(["LIVE","TEST_ONLY"]),mediaType:z25.literal("VIDEO"),modes:z25.array(z25.enum(["REFERENCE_TO_VIDEO","FIRST_FRAME_TO_VIDEO","FIRST_LAST_FRAME_TO_VIDEO"])).min(1).max(3),referenceRoles:z25.array(ReferenceRoleSchema).min(1).max(8),aspectRatios:z25.array(z25.enum(["16:9","9:16"])).min(1).max(2),minDurationSeconds:z25.int().min(1),maxDurationSeconds:z25.int().max(30),maxReferences:z25.int().min(1).max(10),combineAnchorsAndReferences:z25.boolean(),workingWidth:z25.int().positive().max(4096),workingHeight:z25.int().positive().max(4096),frameRate:z25.union([z25.literal(24),z25.literal(30)]),sourceFormat:z25.strictObject({videoCodec:z25.literal("hevc"),pixelFormat:z25.literal("yuv420p10le")}).optional(),hasAudio:z25.boolean(),nativeAudioChannels:z25.union([z25.literal(1),z25.literal(2)]).optional(),correlationStrategy:z25.literal("PROVIDER_TASK_ID")});var VideoOptionsInputSchema=z25.strictObject({tenantId:TenantIdSchema});var VideoStartInputSchema=z25.strictObject({expectedExecution:ExpectedGenerationExecutionSchema.optional(),tenantId:TenantIdSchema,projectId:ProjectIdSchema,productionId:ProductionIdSchema,shotId:ShotIdSchema,preparationId:PreparationIdSchema,contractId:GenerationContractIdSchema,contractFingerprint:ContentFingerprintSchema,selection:ProviderSelectionSchema,idempotencyKey:z25.string().trim().min(1).max(200)});var VideoDeviceStartInputSchema=VideoStartInputSchema.omit({selection:true,expectedExecution:true}).extend({deviceId:z25.uuid(),approvedQuote:GenerationCostQuoteSchema});var VideoGetInputSchema=z25.strictObject({tenantId:TenantIdSchema,productionId:ProductionIdSchema,generationId:VideoGenerationIdSchema});var VideoQueryInputSchema=z25.strictObject({tenantId:TenantIdSchema,productionId:ProductionIdSchema,shotId:ShotIdSchema.optional(),limit:QueryLimitSchema,next:ContinuationSchema.optional()});var VideoAdmissionSchema=z25.strictObject({semanticStatus:z25.literal("ACCEPTED"),generationId:VideoGenerationIdSchema,operationId:OperationIdSchema,productionId:ProductionIdSchema,contractId:GenerationContractIdSchema,executionClass:z25.enum(["LIVE","TEST_ONLY"])});var VideoTechnicalMetadataSchema=z25.strictObject({contentType:z25.literal("video/mp4"),checksumSha256:ContentFingerprintSchema,byteSize:z25.int().positive().max(128*1024*1024),width:z25.int().positive().max(4096),height:z25.int().positive().max(4096),durationMs:z25.int().min(1).max(30150),frameRate:z25.number().positive().max(120),videoCodec:z25.enum(["h264","hevc"]),pixelFormat:z25.literal("yuv420p10le").optional(),hasAudio:z25.boolean(),nativeAudio:NativeVideoAudioMetadataSchema.optional()});var VideoPosterSchema=z25.strictObject({representationId:ArtifactRepresentationIdSchema,contentType:z25.literal("image/png"),checksumSha256:ContentFingerprintSchema,byteSize:z25.int().positive().max(2*1024*1024),width:z25.int().positive().max(320),height:z25.int().positive().max(320)});var VideoCandidateSchema=VideoTechnicalMetadataSchema.extend({nativeSound:NativeVideoSoundReferenceSchema.optional(),id:z25.uuid(),artifactId:ArtifactIdSchema,representationId:ArtifactRepresentationIdSchema,poster:VideoPosterSchema,availability:z25.enum(["AVAILABLE","INVALID"]),observation:z25.enum(["NOT_OBSERVED","OBSERVED"]),evaluation:z25.enum(["UNREVIEWED","PASS","WARNING","FAIL"]),accepted:z25.boolean(),reviewId:z25.uuid().optional(),reviewVersion:z25.int().positive().optional(),acceptanceDecisionId:z25.uuid().optional(),freshness:z25.enum(["CURRENT_BASIS","STALE_BASIS"])});var VideoGenerationViewSchema=z25.strictObject({generationId:VideoGenerationIdSchema,tenantId:TenantIdSchema,projectId:ProjectIdSchema,productionId:ProductionIdSchema,shotId:ShotIdSchema,preparationId:PreparationIdSchema,contractId:GenerationContractIdSchema,contractFingerprint:ContentFingerprintSchema,connection:z25.strictObject({connectionId:z25.uuid(),connectionVersion:z25.int().positive(),modelProfileId:z25.string(),modelProfileVersion:z25.int().positive()}),operationId:OperationIdSchema,provider:VideoProviderProfileSchema,runtimeStatus:z25.enum(["PENDING","READY","RUNNING","WAITING","SUCCEEDED","FAILED","CANCELLED","SUPERSEDED"]),providerStatus:z25.enum(["NOT_SUBMITTED","SUBMITTING","PENDING","UNKNOWN","SUCCEEDED","FAILED"]),freshness:z25.enum(["CURRENT_BASIS","STALE_BASIS"]),cancellationRequested:z25.boolean(),candidate:VideoCandidateSchema.nullable(),createdByPrincipalId:PrincipalIdSchema,createdAt:z25.iso.datetime({offset:true})});var VideoQueryPageSchema=z25.strictObject({items:z25.array(VideoGenerationViewSchema),page:QueryPageInfoSchema});var VideoSummarySchema=z25.strictObject({generations:z25.int().nonnegative(),running:z25.int().nonnegative(),waiting:z25.int().nonnegative(),registeredCandidates:z25.int().nonnegative(),testCandidates:z25.int().nonnegative(),liveCandidates:z25.int().nonnegative()});var TimelineDurationSchema=z26.strictObject({totalMs:z26.int().positive().max(603e4),targetMs:z26.int().min(3e4).max(6e4),minMs:z26.literal(3e4),maxMs:z26.literal(6e4),deltaTargetMs:z26.int(),classification:z26.enum(["TOO_SHORT","WITHIN_TARGET","TOO_LONG"])});var TimelineClipSchema=z26.strictObject({ordinal:z26.int().positive().max(200),source:AcceptedShotReferenceSchema,technical:VideoTechnicalMetadataSchema,sourceInMs:z26.int().nonnegative(),sourceOutMs:z26.int().positive(),startMs:z26.int().nonnegative(),durationMs:z26.int().positive(),transition:ClipTransitionSchema,framing:ClipFramingSchema.optional()});var TimelineManifestSchema=z26.strictObject({schemaVersion:z26.literal(1),caption:CaptionVersionSchema.optional(),captionStyle:CaptionRenderStyleSchema.optional(),audio:TimelineAudioCompositionSchema.optional(),graphics:z26.array(TimelineGraphicSchema).max(8).optional(),basis:z26.strictObject({briefVersionId:BriefVersionIdSchema,briefVersion:z26.int().positive(),storyVersion:z26.int().positive(),planVersionId:SceneShotPlanVersionIdSchema,planVersion:z26.int().positive()}),output:z26.strictObject({aspectRatio:z26.enum(["16:9","9:16"]),profile:DeliveryOutputProfileSchema}),clips:z26.array(TimelineClipSchema).min(1).max(200),duration:TimelineDurationSchema,missingPlannedShotIds:z26.array(ShotIdSchema).max(200),executionClass:z26.enum(["LIVE","TEST_ONLY"])});var TimelineVersionIdentityShape={id:z26.uuid(),timelineId:z26.uuid(),tenantId:TenantIdSchema,projectId:ProjectIdSchema,productionId:ProductionIdSchema,version:z26.int().positive(),fingerprint:z26.string().regex(/^[0-9a-f]{64}$/),createdByPrincipalId:PrincipalIdSchema,createdAt:z26.iso.datetime({offset:true})};function validateTimelineAttachments(timeline,context){if(timeline.audio?.tracks.some(t=>t.source.tenantId!==timeline.tenantId||t.source.projectId!==timeline.projectId||t.source.productionId!==timeline.productionId||t.startMs+t.sourceOutMs-t.sourceInMs>timeline.duration.totalMs||(t.startMs+t.sourceOutMs-t.sourceInMs)*48>Math.round(timeline.duration.totalMs*30/1e3)*1600))context.addIssue({code:"custom",message:"Timeline audio ownership or physical placement mismatch"});const caption=timeline.caption;if(timeline.captionStyle&&!caption)context.addIssue({code:"custom",message:"Timeline caption style requires an exact caption"});if(caption&&(caption.tenantId!==timeline.tenantId||caption.projectId!==timeline.projectId||caption.productionId!==timeline.productionId||caption.content.durationMs!==timeline.duration.totalMs))context.addIssue({code:"custom",message:"Timeline caption ownership or duration mismatch"})}var TimelineVersionSchema=TimelineManifestSchema.extend(TimelineVersionIdentityShape).superRefine(validateTimelineAttachments);import{z as z27}from"zod";var RoughCutProfileIdSchema=z27.enum(["PREVIEW_H264_480P_V1","PREVIEW_H264_720P_V1","PREVIEW_H264_1080P_V1"]);var RoughCutProfileSchema=z27.strictObject({captionPolicy:z27.literal("BURN_IN").optional(),captionStyle:CaptionRenderStyleSchema.optional(),graphicsPolicy:z27.literal("OVERLAY_V1").optional(),id:RoughCutProfileIdSchema,algorithm:z27.enum(["ORDERED_TRIM_CUT_V1","ORDERED_COMPOSE_V2"]),picturePolicy:PicturePolicySchema.optional(),width:z27.union([z27.literal(854),z27.literal(480),z27.literal(1280),z27.literal(720),z27.literal(1920),z27.literal(1080)]),height:z27.union([z27.literal(854),z27.literal(480),z27.literal(1280),z27.literal(720),z27.literal(1920),z27.literal(1080)]),frameRate:z27.literal(30),codec:z27.literal("h264"),pixelFormat:z27.literal("yuv420p"),fit:z27.literal("PAD"),hasAudio:z27.boolean(),audioMix:AudioMixProfileSchema.optional(),framePolicy:z27.literal("CUMULATIVE_NEAREST_FRAME")}).superRefine((profile,context)=>{const pair=profile.id==="PREVIEW_H264_480P_V1"?[854,480]:profile.id==="PREVIEW_H264_720P_V1"?[1280,720]:[1920,1080];if(!(profile.width===pair[0]&&profile.height===pair[1]||profile.width===pair[1]&&profile.height===pair[0]))context.addIssue({code:"custom",message:"Exact preview profile geometry required"});if(profile.hasAudio!==!!profile.audioMix)context.addIssue({code:"custom",message:"Audio policy requires exact native mix"});if(!!profile.captionStyle!==!!profile.captionPolicy)context.addIssue({code:"custom",message:"Caption policy and style must agree"})});var RoughCutManifestSchema=z28.strictObject({schemaVersion:z28.literal(1),timeline:TimelineVersionSchema,profile:RoughCutProfileSchema,frames:z28.array(z28.strictObject({ordinal:z28.int().positive().max(200),startFrame:z28.int().nonnegative().max(1800),frameCount:z28.int().positive().max(1800),overlapFrames:z28.int().nonnegative().max(30).default(0)})).min(1).max(200),totalFrames:z28.int().min(900).max(1800)});import{z as z54}from"zod";import{z as z52}from"zod";import{z as z50}from"zod";import{z as z29}from"zod";var Fingerprint2=z29.string().regex(/^[0-9a-f]{64}$/);var ProgrammaticAcceptedVisualSourceReferenceSchema=z29.strictObject({sourceKind:z29.literal("PROGRAMMATIC"),acceptanceId:z29.uuid(),reviewId:z29.uuid(),renderId:z29.uuid(),compositionId:z29.uuid(),compositionVersionId:z29.uuid(),compositionVersion:z29.int().positive(),compositionFingerprint:Fingerprint2,renderManifestFingerprint:Fingerprint2,shotId:ShotIdSchema,artifactId:ArtifactIdSchema,representationId:ArtifactRepresentationIdSchema,checksumSha256:Fingerprint2,artifactChecksumSha256:Fingerprint2,planVersionId:SceneShotPlanVersionIdSchema,planVersion:z29.int().positive(),shotPlanningRevision:z29.int().positive(),executionClass:z29.enum(["LIVE","TEST_ONLY"]),reviewResult:z29.enum(["PASS","WARNING"])});var ImportedAcceptedVisualSourceReferenceSchema=z29.strictObject({sourceKind:z29.literal("IMPORTED"),acceptanceId:z29.uuid(),reviewId:z29.uuid(),normalizationId:z29.uuid(),sourceId:z29.uuid(),sourceVersionId:z29.uuid(),shotId:ShotIdSchema,artifactId:ArtifactIdSchema,representationId:ArtifactRepresentationIdSchema,checksumSha256:Fingerprint2,executionClass:z29.enum(["LIVE","TEST_ONLY"]),reviewResult:z29.enum(["PASS","WARNING"])});var AcceptedVisualSourceReferenceSchema=z29.union([AcceptedShotReferenceSchema,ProgrammaticAcceptedVisualSourceReferenceSchema,ImportedAcceptedVisualSourceReferenceSchema]);import{z as z49}from"zod";import{z as z31}from"zod";import{z as z30}from"zod";var id4=z30.uuid().toLowerCase();var hash3=z30.string().regex(/^[0-9a-f]{64}$/);var ImportedSynchronousAudioPurposeSchema=z30.literal("SOURCE_SYNC");var SourceSyncPcmMediaSchema=z30.strictObject({profile:z30.literal("PCM_S16LE_48000_SOURCE_SYNC_V1"),audioCodec:z30.literal("pcm_s16le"),sampleRateHz:z30.literal(48e3),audioChannels:z30.union([z30.literal(1),z30.literal(2)]),sampleCount:z30.int().min(1600).max(576e3),durationMs:z30.number().positive().max(12e3)}).refine(m=>m.sampleCount%1600===0&&m.durationMs===m.sampleCount/48);var ImportedSynchronousAudioExtractionSchema=z30.strictObject({schemaVersion:z30.literal(1),purpose:ImportedSynchronousAudioPurposeSchema,tenantId:id4,projectId:id4,productionId:id4,shotId:id4,sourceId:id4,sourceVersionId:id4,normalizationId:id4,originalArtifactId:id4,originalRepresentationId:id4,originalChecksumSha256:hash3,sourceRange:z30.strictObject({clock:z30.literal("SOURCE_ZERO_BASED_CFR30"),startFrame:z30.int().nonnegative().max(1799),endFrame:z30.int().positive().max(1800)}),destinationStartSample:z30.literal(0)}).refine(v=>v.sourceRange.endFrame>v.sourceRange.startFrame&&v.sourceRange.endFrame-v.sourceRange.startFrame<=360);var ImportedSynchronousAudioSourceSchema=z30.strictObject({schemaVersion:z30.literal(1),purpose:ImportedSynchronousAudioPurposeSchema,tenantId:id4,projectId:id4,productionId:id4,shotId:id4,sourceId:id4,sourceVersionId:id4,normalizationId:id4,originalArtifactId:id4,originalRepresentationId:id4,originalChecksumSha256:hash3,sourceRange:z30.strictObject({clock:z30.literal("SOURCE_ZERO_BASED_CFR30"),startFrame:z30.int().nonnegative(),endFrame:z30.int().positive()}),destinationStartSample:z30.int().nonnegative(),media:z30.union([AudioMediaSchema,SourceSyncPcmMediaSchema]),wavChecksumSha256:hash3,wavByteSize:z30.int().min(44).max(12582912)}).superRefine((v,ctx)=>{if(v.sourceRange.endFrame<=v.sourceRange.startFrame||(v.sourceRange.endFrame-v.sourceRange.startFrame)*1600!==v.media.sampleCount)ctx.addIssue({code:"custom",message:"Exact CFR30 interval and PCM48k sample mapping required"})});var id5=z31.uuid().toLowerCase();var key2=z31.string().trim().min(1).max(200);var SourceSyncAudioStartSchema=z31.strictObject({tenantId:id5,productionId:id5,normalizationId:id5,expectedProductionRevision:z31.int().positive(),expectedVersion:z31.int().nonnegative(),idempotencyKey:key2});var SourceSyncAudioGetSchema=z31.strictObject({tenantId:id5,productionId:id5,shotId:id5,versionId:id5});var SourceSyncAudioVersionSchema=z31.strictObject({schemaVersion:z31.literal(1),purpose:z31.literal("SOURCE_SYNC"),id:id5,audioId:id5,version:z31.int().positive(),tenantId:id5,projectId:id5,productionId:id5,shotId:id5,normalizationId:id5,artifactId:id5,representationId:id5,provenance:ImportedSynchronousAudioSourceSchema,previousVersionId:id5.nullable(),executionClass:z31.enum(["LIVE","TEST_ONLY"]),createdByPrincipalId:id5,createdAt:z31.iso.datetime({offset:true})});var SourceSyncAudioReceiptSchema=z31.strictObject({semanticStatus:z31.literal("SUCCESS"),version:SourceSyncAudioVersionSchema,productionRevision:z31.int().positive()});var SourceSyncAudioViewSchema=z31.strictObject({version:SourceSyncAudioVersionSchema,status:z31.enum(["CURRENT","STALE"]),availability:z31.enum(["AVAILABLE","UNAVAILABLE"])});import{z as z32}from"zod";var SourceSoundTreatmentSchema=z32.strictObject({policy:z32.enum(["KEEP","MUTE","DUCK"]),gainPermille:z32.int().min(0).max(1e3),duckingPermille:z32.int().min(0).max(1e3)}).superRefine((v,c)=>{if(v.policy==="MUTE"&&v.gainPermille!==0||v.policy!=="DUCK"&&v.duckingPermille!==1e3)c.addIssue({code:"custom",message:"Mute requires zero gain; ducking requires explicit DUCK"})});import{z as z35}from"zod";import{z as z33}from"zod";var SpeechParameterValueSchema=z33.union([z33.string().max(4096),z33.number().finite(),z33.boolean(),z33.array(z33.string().max(4096)).max(100),z33.record(z33.string().min(1).max(100),z33.string().max(4096)).refine(v=>Object.keys(v).length<=100)]);var SpeechParameterRuleSchema=z33.strictObject({label:z33.string().trim().min(1).max(100).regex(/^[^\p{Cc}]*$/u),type:z33.enum(["NUMBER","INTEGER","STRING","BOOLEAN","STRING_ARRAY","STRING_MAP"]),required:z33.boolean().default(false),min:z33.number().optional(),max:z33.number().optional(),maxLength:z33.int().positive().max(4096).optional(),options:z33.array(z33.string().min(1).max(100)).max(100).optional(),default:SpeechParameterValueSchema.optional(),unit:z33.string().max(40).optional(),description:z33.string().max(500).optional(),maxItems:z33.int().positive().max(100).optional(),maxKeyLength:z33.int().positive().max(100).optional()});var SpeechParametersSchema=z33.record(z33.string().regex(/^[a-z][a-z0-9_]{0,49}$/),SpeechParameterValueSchema).refine(p=>Object.keys(p).length<=24);var SpeechVoiceSchema=z33.strictObject({id:z33.string().min(1).max(100),label:z33.string().min(1).max(100),languages:z33.array(z33.string().min(2).max(20)).min(1).max(32).optional(),parameterDefaults:SpeechParametersSchema.optional(),parameterOptions:z33.record(z33.string(),z33.array(z33.string().min(1).max(100)).min(1).max(100)).optional(),unsupportedParameters:z33.array(z33.string()).max(24).optional()});import{z as z34}from"zod";var cpuSpeechResources={schemaVersion:1,wrapper:{name:"sherpa-onnx-node",url:"https://registry.npmjs.org/sherpa-onnx-node/-/sherpa-onnx-node-1.12.33.tgz",byteSize:10289,sha256:"c56a08c884dcd3ec4b4d815edea4aabbff62fbcd1b0176e88480b5d9b920fa03"},engines:[{platform:"linux-x64",package:"sherpa-onnx-linux-x64",url:"https://registry.npmjs.org/sherpa-onnx-linux-x64/-/sherpa-onnx-linux-x64-1.12.33.tgz",byteSize:10137208,sha256:"651f529869249628c3e304744ab21d658f880be3684e8ead93702f2055bfb5d1",engineDigest:"dbc8c7bcdcd9dc24183894eabb945001ae001fe69cd16c427f01cf41e598c33a",fileCount:25,unpackedBytes:30623890},{platform:"linux-arm64",package:"sherpa-onnx-linux-arm64",url:"https://registry.npmjs.org/sherpa-onnx-linux-arm64/-/sherpa-onnx-linux-arm64-1.12.33.tgz",byteSize:12826691,sha256:"fec1be880a3e6a79e30db4075690759218a28923fafda51983649bcae3efdfbf",engineDigest:"447387941363150362e034f0e8bceb11922b95f11d8553882b7386ad24f1e92f",fileCount:25,unpackedBytes:37679333},{platform:"darwin-x64",package:"sherpa-onnx-darwin-x64",url:"https://registry.npmjs.org/sherpa-onnx-darwin-x64/-/sherpa-onnx-darwin-x64-1.12.33.tgz",byteSize:25289549,sha256:"137082336fa9bf721385c85828b29766dd0d8e0ce67dcc8691d9a5daa7171ce9",engineDigest:"a298b1bd79b690a7cc26eed975980ff69262967627340525a9ef66a8ca45b091",fileCount:26,unpackedBytes:85413811},{platform:"darwin-arm64",package:"sherpa-onnx-darwin-arm64",url:"https://registry.npmjs.org/sherpa-onnx-darwin-arm64/-/sherpa-onnx-darwin-arm64-1.12.33.tgz",byteSize:22164444,sha256:"c5d96d89deadb042f603a83dd0b93b9f147ca635ae3316e83718cd5566c0b61a",engineDigest:"f409d0ef9b864983c784b27369b40a20a988347ecfdbc27a34ea8a8533ccb589",fileCount:26,unpackedBytes:75969095}],model:{url:"https://github.com/k2-fsa/sherpa-onnx/releases/download/tts-models/kokoro-int8-multi-lang-v1_1.tar.bz2",byteSize:147052523,sha256:"259c9c8bc906d6078e4e0570421885dabb68b539c2f970fcbb890a58eeaf3e9c",directory:"kokoro-int8-multi-lang-v1_1",treeDigest:"ebd0959580940e20dbb10a55775ec94e47229c7c503f65932403fe0764667126",fileCount:377,unpackedBytes:215227172}};var kokoroCpuProfile=Object.freeze({id:"KOKORO_INT8_ZH_EN_V1",adapter:"KOKORO_ONNX_CPU_V1",engineVersion:"1.12.33",engineDigest:"f409d0ef9b864983c784b27369b40a20a988347ecfdbc27a34ea8a8533ccb589",modelDigest:"ebd0959580940e20dbb10a55775ec94e47229c7c503f65932403fe0764667126",modelArchiveSha256:"259c9c8bc906d6078e4e0570421885dabb68b539c2f970fcbb890a58eeaf3e9c",sampleRateHz:24e3,speakerCount:103,maxCharacters:600,maxDurationMs:6e4});var CpuSpeechToolSelectionSchema=z34.strictObject({engineDirectory:z34.string().min(1).max(4096),modelDirectory:z34.string().min(1).max(4096)});var CpuSpeechInputSchema=z34.strictObject({text:z34.string().min(1).max(kokoroCpuProfile.maxCharacters).refine(s=>s.trim().length>0&&!new RegExp("\\p{Cc}","u").test(s.replace(/[\t\n]/g,""))&&new TextEncoder().encode(s).length<=2400),voiceId:z34.int().min(0).max(kokoroCpuProfile.speakerCount-1),language:z34.enum(["zh","en"]),speed:z34.number().min(.5).max(2).default(1)});var SpeechDeliverySchema=z34.discriminatedUnion("mode",[z34.strictObject({mode:z34.literal("NON_STREAMING"),output:z34.literal("COMPLETE_AUDIO")}),z34.strictObject({mode:z34.literal("SENTENCE_CHUNKED"),output:z34.literal("ORDERED_SENTENCES")}),z34.strictObject({mode:z34.literal("TRUE_STREAMING"),output:z34.literal("CONTINUOUS_AUDIO")})]);var CpuSpeechIdentitySchema=z34.strictObject({profileId:z34.literal(kokoroCpuProfile.id),adapter:z34.literal(kokoroCpuProfile.adapter),platform:z34.strictObject({os:z34.enum(["darwin","linux"]),architecture:z34.enum(["arm64","x64"])}),engineVersion:z34.literal(kokoroCpuProfile.engineVersion),engineDigest:LocalDigestSchema,modelDigest:z34.literal(kokoroCpuProfile.modelDigest),bridgeSha256:LocalDigestSchema,nodeSha256:LocalDigestSchema}).refine(v=>cpuSpeechResources.engines.some(e=>e.platform===v.platform.os+"-"+v.platform.architecture&&e.engineDigest===v.engineDigest));var CpuSpeechObservationSchema=z34.strictObject({inputSha256:LocalDigestSchema,voiceId:CpuSpeechInputSchema.shape.voiceId,language:CpuSpeechInputSchema.shape.language,outputSha256:LocalDigestSchema,outputBytes:z34.int().min(4844).max(2880044),sampleRateHz:z34.literal(kokoroCpuProfile.sampleRateHz),sampleCount:z34.int().min(2400).max(144e4),durationMs:z34.number().min(100).max(kokoroCpuProfile.maxDurationMs),modelLoadMs:z34.number().nonnegative(),synthesisMs:z34.number().nonnegative(),outputReadyMs:z34.number().positive(),realTimeFactor:z34.number().nonnegative(),cpuMs:z34.number().nonnegative(),peakRssBytes:z34.int().positive()});var CpuSpeechQualificationSchema=z34.strictObject({identity:CpuSpeechIdentitySchema,delivery:z34.strictObject({mode:z34.literal("NON_STREAMING"),output:z34.literal("COMPLETE_AUDIO")}),cancellation:z34.literal("OWNED_PROCESS"),technicalStatus:z34.literal("TECHNICALLY_OBSERVED"),listeningStatus:z34.literal("NOT_PROVEN"),observations:z34.array(CpuSpeechObservationSchema).min(3).max(24),observedAt:z34.iso.datetime({offset:true})});var CpuSpeechCapabilitySchema=z34.strictObject({identity:CpuSpeechIdentitySchema,voices:z34.array(z34.strictObject({voiceId:CpuSpeechInputSchema.shape.voiceId,languages:z34.array(CpuSpeechInputSchema.shape.language).min(1).max(2).refine(v=>new Set(v).size===v.length)})).min(1).max(8).refine(v=>new Set(v.map(s=>s.voiceId)).size===v.length)});var CpuSpeechInstallationSchema=CpuSpeechToolSelectionSchema.extend({voiceIds:z34.array(CpuSpeechInputSchema.shape.voiceId).min(1).max(8).refine(v=>new Set(v).size===v.length)});var NativeSpeechExecutionSchema=z35.strictObject({schemaVersion:z35.literal(1),profileId:z35.literal(kokoroCpuProfile.id),modelDigest:z35.literal(kokoroCpuProfile.modelDigest)});var speed=SpeechParameterRuleSchema.safeExtend({type:z35.literal("NUMBER"),min:z35.number().min(.5).max(2),max:z35.number().min(.5).max(2),default:z35.number().min(.5).max(2).default(1)}).refine(r=>r.min<=r.max&&r.default>=r.min&&r.default<=r.max);var voice=SpeechVoiceSchema.safeExtend({id:z35.string().regex(/^(?:[0-9]|[1-9][0-9]|10[0-2])$/),languages:z35.array(z35.enum(["zh","en"])).min(1).max(2).optional()});var NativeSpeechModelProfileSchema=z35.strictObject({id:ModelProfileIdSchema,version:z35.int().positive(),label:z35.string().trim().min(1).max(100).regex(/^[^\p{Cc}]*$/u),protocol:z35.literal(kokoroCpuProfile.adapter),execution:NativeSpeechExecutionSchema,textMaxCharacters:z35.int().min(1).max(kokoroCpuProfile.maxCharacters),languages:z35.array(z35.enum(["zh","en"])).min(1).max(2).refine(v=>new Set(v).size===v.length),voices:z35.array(voice).min(1).max(kokoroCpuProfile.speakerCount).refine(v=>new Set(v.map(voice2=>voice2.id)).size===v.length),parameters:z35.strictObject({speed}),sourceUrl:z35.literal("https://k2-fsa.github.io/sherpa/onnx/tts/pretrained_models/kokoro.html"),output:z35.literal("PCM_S16LE_48000_V1"),normalizationVersion:z35.literal("SPEECH_PCM_V1")});import{z as z48}from"zod";import{z as z39}from"zod";import{z as z37}from"zod";import{z as z36}from"zod";var receiptId=z36.string().regex(/^[A-Za-z0-9_.:-]{1,500}$/);var resultHost="dashscope-result-bj.oss-cn-beijing.aliyuncs.com";var maxQwenTtsAudioBytes=12*1024*1024;var QwenTtsReceiptSchema=z36.strictObject({providerRequestId:receiptId,audioId:receiptId,audioUrl:z36.url().max(8192).meta({writeOnly:true}),expiresAt:z36.iso.datetime(),usage:z36.strictObject({characters:z36.int().min(0).max(6e3)}).optional()}).refine(({audioUrl,expiresAt})=>{try{const url=new URL(audioUrl);const expires=url.searchParams.getAll("Expires");return url.href===audioUrl&&url.protocol==="https:"&&url.hostname===resultHost&&!url.username&&!url.password&&!url.port&&!url.hash&&url.pathname.endsWith(".wav")&&(expires.length===0||expires.length===1&&/^\d{1,12}$/.test(expires[0])&&Number(expires[0])*1e3===Date.parse(expiresAt))}catch{return false}},"Invalid Qwen TTS audio receipt");var QwenSpeechProviderStateSchema=z36.discriminatedUnion("state",[z36.strictObject({state:z36.literal("RECEIVED"),receipt:QwenTtsReceiptSchema}),z36.strictObject({state:z36.literal("UNKNOWN")}),z36.strictObject({state:z36.literal("REJECTED")})]);var MacSpeechIdentitySchema=z37.strictObject({adapter:z37.literal("MACOS_SAY_V1"),voiceId:z37.literal("com.apple.speech.synthesis.voice.Albert"),locale:z37.literal("en-US"),systemBuild:z37.string().regex(/^[A-Za-z0-9]{1,40}$/),saySha256:LocalDigestSchema,sandboxSha256:LocalDigestSchema,synthesizerSha256:LocalDigestSchema,voiceCatalogSha256:LocalDigestSchema,voiceProbeSha256:LocalDigestSchema});var MacSpeechInputSchema=z37.strictObject({text:z37.string().min(1).max(2e3).refine(text6=>text6.trim().length>0&&!text6.includes("[[")&&!new RegExp("\\p{Cc}","u").test(text6)&&new TextEncoder().encode(text6).length<=4096),rateWordsPerMinute:z37.int().min(80).max(240)});var SpeechSynthesisRecipeSchema=MacSpeechInputSchema.extend({processor:z37.literal("SPEECH_SYNTHESIZE"),identity:MacSpeechIdentitySchema});var audioObject=z37.strictObject({checksumSha256:LocalDigestSchema,byteSize:z37.int().min(44).max(12*1024*1024)});var SpeechSynthesisEvidenceSchema=z37.strictObject({processor:z37.literal("SPEECH_SYNTHESIZE"),source:audioObject,normalized:audioObject,sourceMedia:z37.strictObject({sampleRateHz:z37.literal(22050),audioChannels:z37.literal(1),sampleCount:z37.int().min(2205).max(1323e3)}),media:AudioMediaSchema.refine(value2=>value2.audioChannels===1),padSamples:z37.int().min(0).max(47)});var QwenSpeechRecipeSchema=z37.strictObject({processor:z37.literal("SPEECH_EXTERNAL_QWEN"),generationId:LocalIdSchema,quoteFingerprint:LocalDigestSchema});var QwenSpeechEvidenceSchema=SpeechSynthesisEvidenceSchema.extend({processor:z37.literal("SPEECH_EXTERNAL_QWEN"),providerRequestId:QwenTtsReceiptSchema.shape.providerRequestId,audioId:QwenTtsReceiptSchema.shape.audioId,sourceMedia:z37.strictObject({sampleRateHz:z37.literal([8e3,12e3,16e3,22050,24e3,32e3,44100,48e3]),audioChannels:z37.union([z37.literal(1),z37.literal(2)]),sampleCount:z37.int().min(800).max(288e4)}).refine(({sampleRateHz,sampleCount})=>sampleCount>=sampleRateHz/10&&sampleCount<=sampleRateHz*60)});import{z as z38}from"zod";var NativeSpeechOptionsSchema=z38.strictObject({schemaVersion:z38.literal(1),models:z38.array(z38.strictObject({modelProfileId:ModelProfileIdSchema,modelProfileVersion:z38.int().positive(),label:z38.string().min(1).max(100),profileId:z38.literal(kokoroCpuProfile.id),textMaxCharacters:z38.int().min(1).max(kokoroCpuProfile.maxCharacters)})).max(20),devices:z38.array(z38.strictObject({deviceId:z38.uuid(),label:z38.string().min(1).max(120),profileId:z38.literal(kokoroCpuProfile.id),voices:CpuSpeechCapabilitySchema.shape.voices})).max(50),possiblyTruncated:z38.boolean()});var SpeechModelProfileSchema=z39.strictObject({id:ModelProfileIdSchema,version:z39.int().positive(),providerId:ProviderIdSchema,modelId:z39.string().min(1).max(160).nullable(),protocol:z39.enum(["QWEN_TTS","QWEN_AUDIO_TTS","OPENAI_TTS","XAI_TTS","GEMINI_INTERACTIONS_TTS","VOLCENGINE_TTS"]),label:z39.string().trim().min(1).max(100).regex(/^[^\p{Cc}]*$/u),textMaxCharacters:z39.int().positive().max(6e3),requestTimeoutMs:z39.int().positive().max(3e5),workspaceRequired:z39.boolean(),voices:z39.array(SpeechVoiceSchema).min(1).max(100),languages:z39.array(z39.string().min(2).max(20)).min(1).max(32),parameters:z39.record(z39.string().regex(/^[a-z][a-z0-9_]{0,49}$/),SpeechParameterRuleSchema),sourceUrl:z39.url().max(2048),verifiedAt:z39.iso.date(),providerTextMaxCharacters:z39.int().positive().nullable(),resourceId:z39.string().min(1).max(100).nullable(),output:z39.literal("PCM_S16LE_48000_V1"),normalizationVersion:z39.literal("SPEECH_PCM_V1")});var SpeechScopeSchema=z39.strictObject({tenantId:TenantIdSchema,productionId:ProductionIdSchema});var SpeechExecutionBindingSchema=z39.strictObject({tenantId:TenantIdSchema,connectionId:z39.uuid(),connectionVersion:z39.int().positive(),credentialRef:z39.uuid(),credentialVersion:z39.int().positive(),profile:SpeechModelProfileSchema,executionClass:z39.enum(["LIVE","TEST_ONLY"])});var SpeechStartSchema=SpeechScopeSchema.extend({voiceProfile:VoiceProfileUseSchema.optional(),soundCue:z39.strictObject({soundPlanVersionId:z39.uuid(),cueId:z39.string().regex(/^[a-z][a-z0-9_-]{0,63}$/)}).optional(),expectedProductionRevision:z39.int().positive(),expectedAudioVersion:z39.int().nonnegative(),expectedModelProfileVersion:z39.int().positive(),idempotencyKey:z39.string().trim().min(1).max(200),selection:ProviderSelectionSchema,text:z39.string().min(1).max(6e3).refine(s=>s.trim().length>0&&!s.includes("\0")),voice:z39.string().min(1).max(100),parameters:SpeechParametersSchema.default({})});var SpeechGetSchema=SpeechScopeSchema.extend({generationId:z39.uuid()});var SpeechAdmissionSchema=z39.strictObject({humanLinks:HumanLinksSchema.optional(),semanticStatus:z39.literal("ACCEPTED"),generationId:z39.uuid(),runtimeJobId:z39.uuid(),productionRevision:z39.int().positive(),executionClass:z39.enum(["LIVE","TEST_ONLY"])});var SpeechGenerationViewSchema=SpeechAdmissionSchema.omit({semanticStatus:true}).extend({tenantId:TenantIdSchema,productionId:ProductionIdSchema,soundCue:SpeechStartSchema.shape.soundCue,voiceProfile:VoiceProfileUseSchema.optional(),text:z39.string().min(1).max(6e3),voice:z39.string().min(1).max(100),parameters:SpeechParametersSchema,profile:SpeechModelProfileSchema,connectionId:z39.uuid(),connectionVersion:z39.int().positive(),runtimeStatus:z39.enum(["PENDING","READY","RUNNING","WAITING","SUCCEEDED","FAILED","CANCELLED","SUPERSEDED"]),providerStatus:z39.enum(["NOT_SUBMITTED","SUBMITTING","UNKNOWN","SUCCEEDED","REJECTED"]),cancellationRequested:z39.boolean(),result:AudioReceiptSchema.nullable(),createdAt:z39.iso.datetime({offset:true})});var localSpeechBody=z39.strictObject({expectedProductionRevision:SpeechStartSchema.shape.expectedProductionRevision,expectedAudioVersion:SpeechStartSchema.shape.expectedAudioVersion,idempotencyKey:SpeechStartSchema.shape.idempotencyKey,text:SpeechStartSchema.shape.text,rateWordsPerMinute:MacSpeechInputSchema.shape.rateWordsPerMinute.optional(),voiceProfile:VoiceProfileUseSchema.optional(),soundCue:SpeechStartSchema.shape.soundCue,deviceExecution:z39.strictObject({deviceId:z39.uuid().optional()})});function refineLocalSpeech(v,ctx){const valid=v.voiceProfile?v.rateWordsPerMinute===void 0&&CpuSpeechInputSchema.shape.text.safeParse(v.text).success&&(v.voiceProfile.usage!=="AUDITION"||!v.soundCue):false;const systemValid=!v.voiceProfile&&!v.soundCue&&MacSpeechInputSchema.safeParse({text:v.text,rateWordsPerMinute:v.rateWordsPerMinute}).success;if(!(v.voiceProfile?valid:systemValid))ctx.addIssue({code:"custom",message:"Exact saved CPU voice or anonymous system voice required"})}var LocalSpeechBodySchema=localSpeechBody.superRefine(refineLocalSpeech);var LocalSpeechStartSchema=SpeechScopeSchema.extend(localSpeechBody.shape).superRefine(refineLocalSpeech);var NativeSpeechBindingSchema=z39.strictObject({profile:NativeSpeechModelProfileSchema,voice:z39.string().min(1).max(100),parameters:SpeechParametersSchema});var NativeSpeechBasisSchema=z39.strictObject({schemaVersion:z39.literal(1),modelProfileId:ModelProfileIdSchema,modelProfileVersion:z39.int().positive(),label:z39.string().min(1).max(100),voice:z39.string().min(1).max(100),parameters:SpeechParametersSchema,execution:NativeSpeechExecutionSchema});var LocalSpeechBindingSchema=z39.strictObject({target:z39.literal("TENANT_DEVICE"),tenantId:TenantIdSchema,deviceId:z39.uuid(),identity:z39.union([MacSpeechIdentitySchema,CpuSpeechIdentitySchema]),native:NativeSpeechBindingSchema.optional(),executionClass:z39.literal("LIVE")}).refine(v=>v.identity.adapter==="KOKORO_ONNX_CPU_V1"===!!v.native);var localSpeechExecution=z39.strictObject({target:z39.literal("TENANT_DEVICE"),deviceId:z39.uuid(),identity:LocalSpeechBindingSchema.shape.identity});var LocalSpeechAdmissionSchema=SpeechAdmissionSchema.extend({executionClass:z39.literal("LIVE"),deviceExecution:localSpeechExecution});var LocalSpeechGenerationViewSchema=SpeechGenerationViewSchema.omit({voiceProfile:true,soundCue:true,parameters:true,profile:true,voice:true,connectionId:true,connectionVersion:true,providerStatus:true}).extend({executionClass:z39.literal("LIVE"),deviceExecution:localSpeechExecution,rateWordsPerMinute:MacSpeechInputSchema.shape.rateWordsPerMinute.optional(),voiceProfile:VoiceProfileUseSchema.optional(),soundCue:SpeechStartSchema.shape.soundCue,nativeBasis:NativeSpeechBasisSchema.optional()});var SpeechOptionsSchema=SpeechScopeSchema.extend({native:NativeSpeechOptionsSchema.optional(),options:z39.array(z39.strictObject({selection:ProviderSelectionSchema,profile:SpeechModelProfileSchema,connectionLabel:z39.string().min(1).max(100),connectionVersion:z39.int().positive(),executionTarget:z39.literal("TENANT_DEVICE").optional()})).max(100),possiblyTruncated:z39.boolean()});import{z as z47}from"zod";import{z as z44}from"zod";import{z as z40}from"zod";var KeyframeGenerationIdSchema=z40.uuid().brand();var KeyframeProviderProfileSchema=z40.strictObject({id:z40.string().regex(/^[a-zA-Z0-9][a-zA-Z0-9_.-]{0,79}$/),adapterVersion:z40.string().min(1).max(80),model:z40.string().min(1).max(120),executionClass:z40.enum(["LIVE","TEST_ONLY"]),mediaType:z40.literal("IMAGE"),mode:z40.literal("REFERENCE_TO_IMAGE"),referenceRoles:z40.array(ReferenceRoleSchema).min(1).max(6),aspectRatios:z40.array(z40.enum(["16:9","9:16"])).min(1).max(2),maxReferences:z40.int().min(1).max(12),correlationLookup:z40.boolean()});var KeyframeStartInputSchema=z40.strictObject({expectedExecution:ExpectedGenerationExecutionSchema.optional(),selection:ProviderSelectionSchema.optional(),tenantId:TenantIdSchema,projectId:ProjectIdSchema,productionId:ProductionIdSchema,shotId:ShotIdSchema,preparationId:PreparationIdSchema,contractId:GenerationContractIdSchema,contractFingerprint:ContentFingerprintSchema,idempotencyKey:z40.string().trim().min(1).max(200)});var KeyframeDeviceStartInputSchema=KeyframeStartInputSchema.omit({selection:true,expectedExecution:true}).extend({deviceId:z40.uuid(),approvedQuote:GenerationCostQuoteSchema});var KeyframeGetInputSchema=z40.strictObject({tenantId:TenantIdSchema,productionId:ProductionIdSchema,generationId:KeyframeGenerationIdSchema});var KeyframeQueryInputSchema=z40.strictObject({tenantId:TenantIdSchema,productionId:ProductionIdSchema,shotId:ShotIdSchema.optional(),limit:QueryLimitSchema,next:ContinuationSchema.optional()});var KeyframeAdmissionSchema=z40.strictObject({semanticStatus:z40.literal("ACCEPTED"),generationId:KeyframeGenerationIdSchema,operationId:OperationIdSchema,productionId:ProductionIdSchema,contractId:GenerationContractIdSchema,executionClass:z40.enum(["LIVE","TEST_ONLY"])});var KeyframeCandidateSchema=z40.strictObject({id:z40.uuid(),artifactId:ArtifactIdSchema,representationId:ArtifactRepresentationIdSchema,availability:z40.enum(["AVAILABLE","INVALID"]),observation:z40.enum(["NOT_OBSERVED","OBSERVED"]),evaluation:z40.enum(["UNREVIEWED","PASS","WARNING","FAIL"]),accepted:z40.boolean(),reviewId:z40.uuid().optional(),reviewVersion:z40.int().positive().optional(),acceptanceDecisionId:z40.uuid().optional(),freshness:z40.enum(["CURRENT_BASIS","STALE_BASIS"]),checksumSha256:ContentFingerprintSchema,contentType:z40.enum(["image/png","image/jpeg","image/webp"]),byteSize:z40.int().positive(),width:z40.int().positive(),height:z40.int().positive()});var KeyframeGenerationViewSchema=z40.strictObject({connection:z40.strictObject({connectionId:z40.uuid(),connectionVersion:z40.int().positive(),modelProfileId:z40.string(),modelProfileVersion:z40.int().positive()}).optional(),generationId:KeyframeGenerationIdSchema,tenantId:TenantIdSchema,projectId:ProjectIdSchema,productionId:ProductionIdSchema,shotId:ShotIdSchema,preparationId:PreparationIdSchema,contractId:GenerationContractIdSchema,contractFingerprint:ContentFingerprintSchema,operationId:OperationIdSchema,provider:KeyframeProviderProfileSchema,runtimeStatus:z40.enum(["PENDING","READY","RUNNING","WAITING","SUCCEEDED","FAILED","CANCELLED","SUPERSEDED"]),providerStatus:z40.enum(["NOT_SUBMITTED","SUBMITTING","PENDING","UNKNOWN","SUCCEEDED","FAILED"]),freshness:z40.enum(["CURRENT_BASIS","STALE_BASIS"]),cancellationRequested:z40.boolean(),candidate:KeyframeCandidateSchema.nullable(),createdByPrincipalId:PrincipalIdSchema,createdAt:z40.iso.datetime({offset:true})});var KeyframeQueryPageSchema=z40.strictObject({items:z40.array(KeyframeGenerationViewSchema),page:QueryPageInfoSchema});var KeyframeMediaSchema=z40.strictObject({contentType:z40.enum(["image/png","image/jpeg","image/webp"]),checksumSha256:ContentFingerprintSchema,byteSize:z40.int().positive().max(8*1024*1024),contentBase64:z40.string().min(4).max(4*Math.ceil(8*1024*1024/3))});var KeyframeSummarySchema=z40.strictObject({generations:z40.int().nonnegative(),running:z40.int().nonnegative(),waiting:z40.int().nonnegative(),registeredCandidates:z40.int().nonnegative(),testCandidates:z40.int().nonnegative(),liveCandidates:z40.int().nonnegative()});import{z as z43}from"zod";import{z as z42}from"zod";import{z as z41}from"zod";var MatrixParameterRuleSchema=SpeechParameterRuleSchema.extend({numberOptions:z41.array(z41.number().finite()).min(1).max(32).optional()}).superRefine((r,ctx)=>{const numeric=r.type==="NUMBER"||r.type==="INTEGER";const stringValid=v=>typeof v==="string"&&v.length<=(r.maxLength??4096)&&(!r.options||r.options.includes(v));const valid=v=>numeric?typeof v==="number"&&Number.isFinite(v)&&(r.type!=="INTEGER"||Number.isInteger(v))&&(r.min===void 0||v>=r.min)&&(r.max===void 0||v<=r.max)&&(!r.numberOptions||r.numberOptions.includes(v)):r.type==="BOOLEAN"?typeof v==="boolean":r.type==="STRING"?stringValid(v):r.type==="STRING_ARRAY"?Array.isArray(v)&&v.length<=(r.maxItems??100)&&v.every(stringValid):!!v&&typeof v==="object"&&!Array.isArray(v)&&Object.keys(v).length<=(r.maxItems??100)&&Object.entries(v).every(([k,item])=>k.length>0&&k.length<=(r.maxKeyLength??100)&&stringValid(item));if(r.min!==void 0&&r.max!==void 0&&r.min>r.max||r.numberOptions&&(!numeric||new Set(r.numberOptions).size!==r.numberOptions.length||r.numberOptions.some(v=>!valid(v)))||r.default!==void 0&&!valid(r.default))ctx.addIssue({code:"custom",message:"Typed parameter range, choices and default must agree"})});var AsrProfileSchema=z42.strictObject({id:ModelProfileIdSchema,version:z42.int().positive(),providerId:ProviderIdSchema,sourceUrl:z42.url().max(2048),verifiedAt:z42.iso.date(),modelId:z42.string().min(1).max(160),label:z42.string().min(1).max(100),protocol:z42.enum(["OPENAI_TRANSCRIPTION_V1","OPENAI_WHISPER_TRANSCRIPTION_V1","QWEN_ASR_V1"]),modes:z42.tuple([z42.literal("TRANSCRIPTION")]),inputKinds:z42.array(z42.enum(["AUDIO","VIDEO"])).min(1).max(2),requestTimeoutMs:z42.int().min(1e3).max(18e4),maxBytes:z42.int().positive().max(12582912),maxDurationMs:z42.int().positive().max(6e4),parameters:z42.record(z42.string().regex(/^[a-z][a-z0-9_]{0,49}$/),MatrixParameterRuleSchema)}).superRefine((p,c)=>{const openai=p.providerId==="OPENAI";const whisper=p.protocol==="OPENAI_WHISPER_TRANSCRIPTION_V1";const fields=openai?whisper?{prompt:"STRING",language:"STRING",temperature:"NUMBER",timestamp_granularities:"STRING_ARRAY"}:{prompt:"STRING",languages:"STRING_ARRAY",keywords:"STRING_ARRAY"}:{context:"STRING",language:"STRING",enable_itn:"BOOLEAN"};if(p.providerId!==(p.protocol==="QWEN_ASR_V1"?"QWEN_CN":"OPENAI")||new Set(p.inputKinds).size!==p.inputKinds.length||!openai&&(p.maxBytes>7340032||p.inputKinds.includes("VIDEO"))||Object.entries(p.parameters).some(([key10,rule])=>fields[key10]!==rule.type))c.addIssue({code:"custom",message:"ASR protocol capability mismatch"});if(whisper){const rule=p.parameters.timestamp_granularities;if(!rule?.required||!rule.options?.length||rule.options.some(v=>!["word","segment"].includes(v)))c.addIssue({code:"custom",message:"Timed ASR requires explicit supported granularities"});const temperature=p.parameters.temperature;if(temperature&&(temperature.min===void 0||temperature.min<0||temperature.max===void 0||temperature.max>1))c.addIssue({code:"custom",message:"Whisper temperature must stay within 0\u20131"})}});var TranscriptText={schemaVersion:z42.literal(1),text:z42.string().max(6e4),languages:z42.array(z42.string().min(2).max(40)).max(32)};var TimedText=z42.strictObject({text:z42.string().min(1).max(2500),startMs:z42.int().nonnegative().max(6e4),endMs:z42.int().positive().max(6e4)}).refine(v=>v.endMs>v.startMs,"Transcript interval must advance");var TranscriptSchema=z42.discriminatedUnion("timing",[z42.strictObject({...TranscriptText,timing:z42.literal("UNAVAILABLE")}),z42.strictObject({...TranscriptText,timing:z42.literal("PROVIDER_REPORTED"),timeBase:z42.literal("ORIGINAL_MEDIA_MS"),granularities:z42.array(z42.enum(["word","segment"])).min(1).max(2),words:z42.array(TimedText).max(1200),segments:z42.array(TimedText).max(240)}).superRefine((v,c)=>{if(new Set(v.granularities).size!==v.granularities.length)c.addIssue({code:"custom",message:"Duplicate timing granularity"});for(const[kind,items]of[["word",v.words],["segment",v.segments]]){if(!v.granularities.includes(kind)&&items.length>0||v.granularities.includes(kind)&&v.text.trim()&&!items.length||items.some((item,i)=>i>0&&item.startMs<items[i-1].endMs))c.addIssue({code:"custom",message:"Missing, unordered or overlapping Provider timing"})}})]);var ObservationModeSchema=z43.enum(["AUDIO","AUDIOVISUAL","VIDEO","VIDEO_ALL_FRAMES","TRANSCRIPTION"]);var ObservationParametersSchema=SpeechParametersSchema;var VisualObservationProfileSchema=z43.strictObject({id:ModelProfileIdSchema,version:z43.int().positive(),providerId:ProviderIdSchema,sourceUrl:z43.url().max(2048),modelId:z43.string().min(1).max(160),label:z43.string().min(1).max(100),protocol:z43.enum(["GEMINI_INTERACTIONS_V1","QIANWEN_VIDEO_V1"]),modes:z43.array(z43.enum(["AUDIO","AUDIOVISUAL","VIDEO","VIDEO_ALL_FRAMES"])).min(1).max(4),requestTimeoutMs:z43.int().min(1e3).max(18e4),maxBytes:z43.int().positive().max(12582912),maxDurationMs:z43.int().positive().max(6e4),parameters:z43.record(z43.string(),z43.strictObject({type:z43.enum(["NUMBER","INTEGER","BOOLEAN","STRING"]),min:z43.number().optional(),max:z43.number().optional(),options:z43.array(z43.string()).max(20).optional(),default:z43.union([z43.number().finite(),z43.boolean(),z43.string().max(200)])}))}).superRefine((p,c)=>{if(new Set(p.modes).size!==p.modes.length)c.addIssue({code:"custom",message:"Duplicate observation mode"});if((p.protocol==="QIANWEN_VIDEO_V1"||p.modes.includes("AUDIOVISUAL"))&&p.maxBytes>8388608)c.addIssue({code:"custom",message:"Video observation input exceeds supported bound"});const gemini=p.protocol==="GEMINI_INTERACTIONS_V1";const allowed=gemini?["max_output_tokens"]:["fps","max_tokens"];if(p.providerId!==(gemini?"GEMINI":"QWEN_CN")||p.modes.some(m=>!(gemini?["AUDIO","AUDIOVISUAL"]:["VIDEO","VIDEO_ALL_FRAMES"]).includes(m))||Object.keys(p.parameters).some(k=>!allowed.includes(k))||allowed.some(k=>!p.parameters[k]))c.addIssue({code:"custom",message:"Observation protocol/profile mismatch"});for(const[k,r]of Object.entries(p.parameters)){const n=r.default;const lo=k==="fps"?1:256,hi=k==="fps"?10:4096;if(typeof n!=="number"||!["NUMBER","INTEGER"].includes(r.type)||k!=="fps"&&r.type!=="INTEGER"||r.min===void 0||r.max===void 0||r.min<lo||r.max>hi||r.min>r.max||n<r.min||n>r.max||r.type==="INTEGER"&&!Number.isSafeInteger(n))c.addIssue({code:"custom",message:"Unsupported observation parameter rule"})}});var ObservationProfileSchema=z43.union([VisualObservationProfileSchema,AsrProfileSchema]);var ProviderTenantInputSchema=z44.strictObject({tenantId:TenantIdSchema});var ImageModelProfileSchema=z44.strictObject({referenceRoles:z44.array(ReferenceRoleSchema.exclude(["START_FRAME_ANCHOR","END_FRAME_ANCHOR"])).min(1).max(6).optional(),id:ModelProfileIdSchema,version:z44.int().positive(),providerId:ProviderIdSchema,modelId:z44.string().min(1).max(160),protocol:z44.enum(["QWEN_EDIT","ARK_IMAGE","GEMINI_IMAGE","OPENAI_IMAGE","XAI_IMAGE"]),maxReferences:z44.int().positive(),promptMaxUtf8Bytes:z44.int().positive(),requestTimeoutMs:z44.int().positive(),workingWidth:z44.int().nonnegative(),workingHeight:z44.int().nonnegative()});var VideoModelProfileSchema=z44.strictObject({id:ModelProfileIdSchema,version:z44.int().positive(),providerId:ProviderIdSchema,modelId:z44.string().min(1).max(160),protocol:z44.enum(["QWEN_VIDEO","VOLCENGINE_VIDEO"]),requestTimeoutMs:z44.int().positive(),promptMaxCharacters:z44.int().positive(),resolution:z44.enum(["720P","1080P"]),adapterVersion:z44.string().min(1).max(80),capabilities:VideoProviderProfileSchema.omit({id:true,adapterVersion:true,model:true,executionClass:true})});var ProviderDefaultViewSchema=z44.strictObject({selection:ProviderSelectionSchema,revision:z44.int().positive()});var scan=z44.strictObject({limit:z44.literal(100),possiblyTruncated:z44.boolean()});var ProviderConnectionPageSchema=scan.extend({items:z44.array(ProviderConnectionViewSchema).max(100)});var ProviderModelsViewSchema=z44.strictObject({catalog:z44.array(ImageModelProfileSchema).max(100),videoCatalog:z44.array(VideoModelProfileSchema).max(100),speechCatalog:z44.array(SpeechModelProfileSchema).max(100).default([]),observationCatalog:z44.array(ObservationProfileSchema).max(100).default([]),available:z44.array(z44.strictObject({selection:ProviderSelectionSchema,profile:KeyframeProviderProfileSchema})).max(1600),defaultSelection:ProviderDefaultViewSchema.nullable(),connectionScan:scan});import{z as z45}from"zod";var key3=z45.string().regex(/^[A-Za-z][A-Za-z0-9_.-]{0,99}$/);var value=z45.union([z45.string().max(160),z45.number().finite(),z45.boolean()]);var ModelAudioCapabilitySchema=z45.enum(["SYNCHRONIZED_AUDIO","SPEECH_GENERATION","SPEECH_RECOGNITION","TRANSCRIPT_TIMESTAMPS","VOICE_REFERENCE","AUDIO_REFERENCE","AUDIO_DRIVEN_VIDEO","LIP_SYNCHRONIZATION","AUDIO_EDITING","SEPARATE_STEMS"]);var ModelCapabilityMatrixSchema=z45.strictObject({schemaVersion:z45.literal(1),service:key3,lifecycle:z45.enum(["ACTIVE","DEPRECATED","RETIRED"]),sources:z45.array(z45.strictObject({url:z45.url().max(2048),checkedAt:z45.iso.date()})).min(1).max(8),modes:z45.array(key3).min(1).max(16),claims:z45.array(z45.strictObject({capability:ModelAudioCapabilitySchema,modes:z45.array(key3).min(1).max(16),support:z45.enum(["SUPPORTED","UNSUPPORTED","UNKNOWN"]),control:z45.enum(["PARAMETER","PROMPT","ALWAYS_ON","MEDIA_INPUT","NONE"]),parameterPath:key3.optional(),access:z45.enum(["PUBLIC","QUALIFIED_ACCOUNT"]).default("PUBLIC"),description:z45.string().max(600).optional()})).max(64),parameters:z45.record(key3,MatrixParameterRuleSchema),constraints:z45.array(z45.strictObject({modes:z45.array(key3).min(1).max(16),when:z45.strictObject({parameter:key3,equals:value}).optional(),require:z45.array(key3).max(16).default([]),forbid:z45.array(key3).max(16).default([]),requireValues:z45.record(key3,value).default({}),reason:z45.string().min(1).max(300)})).max(32),references:z45.array(z45.strictObject({kind:z45.enum(["VOICE_ID","AUDIO_REFERENCE","DRIVING_AUDIO"]),modes:z45.array(key3).min(1).max(16),parameterPath:key3,maxItems:z45.int().min(1).max(10),minDurationMs:z45.int().positive().optional(),maxDurationMs:z45.int().positive().max(6e4).optional(),maxTotalDurationMs:z45.int().positive().max(6e4).optional(),maxBytes:z45.int().positive().max(67108864).optional(),formats:z45.array(z45.enum(["WAV","MP3"])).max(2),requiresVisual:z45.boolean(),access:z45.enum(["PUBLIC","QUALIFIED_ACCOUNT"])})).max(16),outputAudioChannels:z45.union([z45.literal(1),z45.literal(2)]).optional()}).superRefine((m,ctx)=>{const modes=new Set(m.modes);const claims=m.claims.flatMap(c=>c.modes.map(mode=>`${c.capability}:${mode}:${c.access}`));if(modes.size!==m.modes.length||new Set(claims).size!==claims.length||Object.keys(m.parameters).length>48||[...m.claims,...m.constraints,...m.references].some(r=>r.modes.some(mode=>!modes.has(mode)))||m.claims.some(r=>r.control==="PARAMETER"&&(!r.parameterPath||!Object.hasOwn(m.parameters,r.parameterPath)))||m.constraints.some(r=>r.when&&!Object.hasOwn(m.parameters,r.when.parameter)))ctx.addIssue({code:"custom",message:"Matrix modes and parameter references must resolve"});for(const rule of Object.values(m.parameters))if(rule.min!==void 0&&rule.max!==void 0&&rule.min>rule.max)ctx.addIssue({code:"custom",message:"Matrix parameter range must advance"})});import{z as z46}from"zod";var rate=z46.int().positive().max(1e9);var ruleId=z46.string().regex(/^[a-zA-Z0-9_-]{1,80}$/);var sourceUrl=z46.url({protocol:/^https$/}).max(2e3).refine(value2=>{const url=new URL(value2);return!url.username&&!url.password&&!url.search});function speechCostUpperBoundMicros(characters,microsPerMillion){return Math.ceil(characters*microsPerMillion/1e6)}var SpeechCostPolicySchema=z46.strictObject({currency:z46.literal("USD"),unit:z46.literal("INPUT_CHARACTER"),ruleId,upperBoundMicrosPerMillionCharacters:rate,sourceUrl,validUntil:z46.iso.datetime({offset:true})});var SpeechCostQuoteSchema=z46.strictObject({workload:z46.literal("SPEECH_SYNTHESIS"),currency:z46.literal("USD"),projectId:ProjectIdSchema,selection:ProviderSelectionSchema,expectedExecution:ExpectedGenerationExecutionSchema.extend({credentialVersion:z46.int().positive()}),intentFingerprint:z46.string().regex(/^[a-f0-9]{64}$/),textCharacters:z46.int().min(1).max(600),billableCharactersUpperBound:z46.int().min(1).max(2400),upperBoundMicros:z46.int().positive().max(1e9),upperBoundMicrosPerMillionCharacters:rate,ruleId,sourceUrl}).refine(value2=>value2.billableCharactersUpperBound>=value2.textCharacters&&value2.billableCharactersUpperBound<=value2.textCharacters*4&&value2.upperBoundMicros===speechCostUpperBoundMicros(value2.billableCharactersUpperBound,value2.upperBoundMicrosPerMillionCharacters),"Speech quote must match its exact character bound and rate");var SpeechDeviceStartSchema=SpeechStartSchema.extend({deviceId:z46.uuid().optional(),approvedQuote:SpeechCostQuoteSchema});var cost={costPolicy:GenerationCostPolicySchema.optional()};var matrix={matrix:ModelCapabilityMatrixSchema.optional()};var ProviderModelDefinitionSchema=z47.discriminatedUnion("family",[z47.strictObject({family:z47.literal("NATIVE_SPEECH"),profile:NativeSpeechModelProfileSchema}),z47.strictObject({family:z47.literal("IMAGE"),profile:ImageModelProfileSchema,...matrix,...cost}),z47.strictObject({family:z47.literal("VIDEO"),profile:VideoModelProfileSchema,...matrix,...cost}),z47.strictObject({family:z47.literal("SPEECH"),profile:SpeechModelProfileSchema,...matrix}),z47.strictObject({family:z47.literal("OBSERVATION"),profile:ObservationProfileSchema,...matrix}),z47.strictObject({family:z47.literal("DECLARED"),profile:z47.strictObject({id:ModelProfileIdSchema,version:z47.int().positive(),providerId:ProviderIdSchema,modelId:z47.string().min(1).max(160),protocol:z47.literal("DOCUMENTED_ONLY")}),matrix:ModelCapabilityMatrixSchema})]);var ProviderModelViewSchema=z47.strictObject({tenantId:TenantIdSchema,id:ModelProfileIdSchema,version:z47.int().positive(),enabled:z47.boolean(),definition:ProviderModelDefinitionSchema}).refine(v=>v.id===v.definition.profile.id&&v.version===v.definition.profile.version,{message:"Model version identity mismatch"});var ConfigureProviderModelSchema=z47.strictObject({tenantId:TenantIdSchema,expectedVersion:z47.int().nonnegative(),definition:ProviderModelDefinitionSchema,speechCostPolicy:SpeechCostPolicySchema.optional()}).refine(v=>!v.speechCostPolicy||v.definition.family==="SPEECH",{message:"Speech cost policy requires a speech model"}).refine(v=>v.definition.profile.version===v.expectedVersion+1,{message:"Next model version required"}).refine(v=>new TextEncoder().encode(JSON.stringify(v.definition)).length<=65536,{message:"Model definition too large"});var DisableProviderModelSchema=z47.strictObject({tenantId:TenantIdSchema,id:ModelProfileIdSchema,expectedVersion:z47.int().positive()});var ProviderModelPageSchema=z47.strictObject({items:z47.array(ProviderModelViewSchema).max(100),possiblyTruncated:z47.boolean()});var ProviderModelGetSchema=z47.strictObject({tenantId:TenantIdSchema,id:ModelProfileIdSchema,version:z47.int().positive().optional()});var id6=z48.uuid().toLowerCase();var SoundPlanScopeSchema=z48.strictObject({tenantId:id6,productionId:id6});var SoundPlanBasisSchema=z48.strictObject({briefVersionId:id6,briefVersion:z48.int().positive(),storyVersionId:id6,storyVersion:z48.int().positive(),planVersionId:id6,planVersion:z48.int().positive()});var SoundPlanModelSchema=z48.strictObject({modelProfileId:z48.string().regex(/^[a-z][a-z0-9-]{1,79}$/),modelProfileVersion:z48.int().positive(),connectionId:id6});var SoundPlanNativeSpeechSchema=SoundPlanModelSchema.omit({connectionId:true}).extend({schemaVersion:z48.literal(1),execution:NativeSpeechExecutionSchema});var SoundMakingPlanContentSchema=z48.strictObject({visuals:z48.array(z48.strictObject({shotId:id6,method:z48.enum(["CODE","GENERATED","IMPORTED"]),model:SoundPlanModelSchema.optional(),nativeAudio:z48.boolean().optional(),sourceSound:SourceSoundTreatmentSchema,rationale:z48.string().trim().min(1).max(600)})).min(1).max(200),cues:z48.array(z48.strictObject({id:z48.string().regex(/^[a-z][a-z0-9_-]{0,63}$/),role:z48.enum(["NARRATION","DIALOGUE","MUSIC","AMBIENCE","SOUND_EFFECT"]),source:z48.enum(["TTS","NATIVE_VIDEO","IMPORTED_AUDIO","EXISTING_AUDIO"]),shotIds:z48.array(id6).min(1).max(200),startMs:z48.int().min(0).max(6e4),endMs:z48.int().positive().max(6e4),text:z48.string().trim().min(1).max(6e3).optional(),voice:z48.string().min(1).max(100).optional(),voiceProfile:VoiceProfileUseSchema.extend({usage:z48.literal("PRODUCTION")}).optional(),model:SoundPlanModelSchema.optional(),nativeModel:SoundPlanNativeSpeechSchema.optional(),parameters:SpeechParametersSchema.optional(),audio:z48.strictObject({purpose:z48.enum(["VOICEOVER","MUSIC"]),versionId:z48.uuid()}).optional(),lipSync:z48.enum(["REQUIRED","NONE"]),exactSpeech:z48.boolean()})).max(64),unknowns:z48.array(z48.string().trim().min(1).max(300)).max(16)}).superRefine((v,c)=>{if(new Set(v.visuals.map(s=>s.shotId)).size!==v.visuals.length||new Set(v.cues.map(s=>s.id)).size!==v.cues.length)c.addIssue({code:"custom",message:"Visual Shot and cue identities must be unique"});for(const s of v.visuals)if(s.method==="GENERATED"!==!!s.model||s.method==="GENERATED"&&s.nativeAudio===void 0||s.method!=="GENERATED"&&s.nativeAudio!==void 0||s.method==="CODE"&&s.sourceSound.policy!=="MUTE")c.addIssue({code:"custom",message:"Generated visuals require a model; CODE has no native sound"});for(const cue of v.cues)if(cue.endMs<=cue.startMs||new Set(cue.shotIds).size!==cue.shotIds.length||cue.source==="TTS"&&(!cue.text||!cue.voice||!!cue.model===!!cue.nativeModel||cue.nativeModel&&!cue.voiceProfile||!["NARRATION","DIALOGUE"].includes(cue.role))||cue.exactSpeech&&!cue.text||["NARRATION","DIALOGUE"].includes(cue.role)&&!cue.text||["IMPORTED_AUDIO","EXISTING_AUDIO"].includes(cue.source)!==!!cue.audio||cue.audio&&((["NARRATION","DIALOGUE"].includes(cue.role)?"VOICEOVER":"MUSIC")!==cue.audio.purpose||!["NARRATION","DIALOGUE","MUSIC"].includes(cue.role))||cue.source!=="TTS"&&(!!cue.voice||!!cue.model||!!cue.nativeModel||!!cue.parameters||!!cue.voiceProfile)||cue.source==="NATIVE_VIDEO"&&["NARRATION","DIALOGUE"].includes(cue.role)&&cue.shotIds.length!==1||cue.lipSync==="REQUIRED"&&(cue.source!=="NATIVE_VIDEO"||cue.shotIds.length!==1))c.addIssue({code:"custom",message:"Invalid speech, cue timing or synchronization intent"})});var SoundPlanVersionSchema=SoundPlanScopeSchema.extend({id:id6,soundPlanId:id6,projectId:id6,version:z48.int().positive(),basis:SoundPlanBasisSchema,content:SoundMakingPlanContentSchema,createdByPrincipalId:id6,createdAt:z48.iso.datetime({offset:true})});var SoundPlanValidateSchema=SoundPlanScopeSchema.extend({expectedProductionRevision:z48.int().positive(),basis:SoundPlanBasisSchema,content:SoundMakingPlanContentSchema});var SoundPlanAcceptSchema=SoundPlanValidateSchema.extend({expectedVersion:z48.int().nonnegative(),idempotencyKey:z48.string().trim().min(1).max(200)});var SoundPlanGetSchema=SoundPlanScopeSchema.extend({versionId:id6.optional()});var SoundPlanDiagnosticSchema=z48.strictObject({severity:z48.enum(["ERROR","WARNING"]),code:z48.string().regex(/^[A-Z][A-Z0-9_]{0,79}$/),shotId:id6.optional(),cueId:z48.string().max(64).optional(),message:z48.string().max(500)});var SoundPlanValidationSchema=z48.strictObject({executable:z48.boolean(),diagnostics:z48.array(SoundPlanDiagnosticSchema).max(256),semantics:z48.literal("PLAN_VALIDATION_NOT_CREATIVE_OR_LISTENING_APPROVAL")});var SoundPlanViewSchema=z48.strictObject({version:SoundPlanVersionSchema,current:z48.boolean(),freshness:z48.enum(["CURRENT_BASIS","STALE_BASIS"])});var SoundPlanReceiptSchema=z48.strictObject({semanticStatus:z48.literal("SUCCESS"),version:SoundPlanVersionSchema,productionRevision:z48.int().positive()});var SoundPlanContextSchema=SoundPlanScopeSchema.extend({projectId:id6,productionRevision:z48.int().positive(),runnable:z48.boolean(),basis:SoundPlanBasisSchema.nullable(),targetDurationMs:z48.int().positive().nullable(),shots:z48.array(z48.strictObject({shotId:id6,durationMs:z48.int().positive()})).max(200),currentVersion:z48.int().nonnegative(),currentVersionId:id6.nullable(),capabilities:z48.strictObject({models:z48.array(ProviderModelViewSchema).max(100),video:z48.array(z48.strictObject({selection:ProviderSelectionSchema,profile:VideoProviderProfileSchema})).max(1600),speech:SpeechOptionsSchema.shape.options,audio:z48.array(AudioViewSchema).max(64)})});var TimelineSourceSoundInputSchema=z49.strictObject({duckingMusicPermille:z49.int().nonnegative().max(1e3).optional(),soundPlanVersionId:z49.uuid(),clips:z49.array(z49.strictObject({ordinal:z49.int().min(1).max(200),treatment:SourceSoundTreatmentSchema,importedAudioVersionId:z49.uuid().optional()})).min(1).max(200),speechCues:z49.array(z49.strictObject({cueId:z49.string().regex(/^[a-z][a-z0-9_-]{0,63}$/),audioVersionId:z49.uuid()})).max(64)});var TimelineSourceSoundSourceSchema=z49.discriminatedUnion("kind",[z49.strictObject({kind:z49.literal("NATIVE_GENERATED"),version:NativeVideoSoundReferenceSchema}),z49.strictObject({kind:z49.literal("IMPORTED_SYNC"),version:SourceSyncAudioVersionSchema})]);var TimelineSourceSoundCompositionSchema=z49.strictObject({schemaVersion:z49.literal(1),soundPlanVersionId:z49.uuid(),soundPlanFingerprint:z49.string().regex(/^[0-9a-f]{64}$/),plannedCues:SoundMakingPlanContentSchema.shape.cues,mix:AudioMixProfileSchema,clips:z49.array(z49.strictObject({ordinal:z49.int().min(1).max(200),treatment:SourceSoundTreatmentSchema,source:TimelineSourceSoundSourceSchema.optional(),sourceInSample:z49.int().nonnegative().max(288e4),sourceOutSample:z49.int().nonnegative().max(288e4),startSample:z49.int().nonnegative().max(288e4),outputSampleCount:z49.int().positive().max(288e4)})).min(1).max(200),speechCues:z49.array(z49.strictObject({cueId:z49.string().regex(/^[a-z][a-z0-9_-]{0,63}$/),source:ProductionAudioVersionSchema,sourceInMs:z49.literal(0),sourceOutMs:z49.int().positive().max(6e4),startMs:z49.int().nonnegative().max(6e4),gainPermille:z49.literal(1e3)})).max(64)}).superRefine((v,ctx)=>{if(new Set(v.clips.map(c=>c.ordinal)).size!==v.clips.length||new Set(v.speechCues.map(c=>c.cueId)).size!==v.speechCues.length||v.speechCues.some(c=>c.source.purpose!=="VOICEOVER"||c.sourceOutMs!==c.source.media.durationMs)||v.clips.some(c=>c.treatment.policy!=="MUTE"!==!!c.source||c.source&&c.sourceOutSample<=c.sourceInSample))ctx.addIssue({code:"custom",message:"Explicit distinct clip sound decisions and exact source required"})});var TimelineV2ClipSchema=TimelineManifestSchema.shape.clips.element.extend({source:AcceptedVisualSourceReferenceSchema});var TimelineV2ManifestSchema=TimelineManifestSchema.extend({schemaVersion:z50.literal(2),clips:z50.array(TimelineV2ClipSchema).min(1).max(200),sourceSound:TimelineSourceSoundCompositionSchema.optional()});var TimelineV2VersionSchema=TimelineV2ManifestSchema.extend(TimelineVersionIdentityShape).superRefine(validateTimelineAttachments);import{z as z51}from"zod";var sha4=z51.string().regex(/^[0-9a-f]{64}$/);var VisualFrameSequenceSchema=z51.strictObject({schemaVersion:z51.literal(1),profileId:z51.literal("RGBA_PNG_SEQUENCE_30_V1"),tenantId:TenantIdSchema,projectId:ProjectIdSchema,productionId:ProductionIdSchema.nullable(),artifactId:ArtifactIdSchema,representationId:ArtifactRepresentationIdSchema,checksumSha256:sha4,width:z51.int().min(1).max(1920),height:z51.int().min(1).max(1920),frameRate:z51.literal(30),frameCount:z51.int().min(1).max(360),alpha:z51.literal("STRAIGHT_RGBA"),frames:z51.array(z51.strictObject({ordinal:z51.int().min(0).max(359),artifactId:ArtifactIdSchema,representationId:ArtifactRepresentationIdSchema,checksumSha256:sha4,byteSize:z51.int().min(1).max(16*1024*1024)})).min(1).max(360)}).superRefine((v,context)=>{if(v.width*v.height>1920*1080||v.frames.length!==v.frameCount||v.frames.some((f,i)=>f.ordinal!==i)||new Set(v.frames.map(f=>f.representationId)).size!==v.frames.length||v.frames.reduce((n,f)=>n+f.byteSize,0)>64*1024*1024)context.addIssue({code:"custom",message:"Frame sequence geometry/order/identity/byte budget mismatch"})});var VisualLayerPlacementSchema=z51.strictObject({xPermille:z51.int().min(0).max(1e3),yPermille:z51.int().min(0).max(1e3),widthPermille:z51.int().min(1).max(1e3),heightPermille:z51.int().min(1).max(1e3)}).refine(v=>v.xPermille+v.widthPermille<=1e3&&v.yPermille+v.heightPermille<=1e3,"Layer rectangle must fit the canvas");var VisualLayerSchema=z51.strictObject({id:z51.uuid(),source:VisualFrameSequenceSchema,sourceInFrame:z51.int().min(0).max(359),sourceOutFrame:z51.int().min(1).max(360),startFrame:z51.int().min(0).max(1799),zIndex:z51.int().min(0).max(7),opacityPermille:z51.int().min(0).max(1e3),placement:VisualLayerPlacementSchema}).superRefine((v,context)=>{if(v.sourceOutFrame<=v.sourceInFrame||v.sourceOutFrame>v.source.frameCount||v.startFrame+v.sourceOutFrame-v.sourceInFrame>1800)context.addIssue({code:"custom",message:"Layer source/output frame interval mismatch"})});var VisualLayerCompositionSchema=z51.strictObject({schemaVersion:z51.literal(1),profileId:z51.literal("STRAIGHT_ALPHA_FRAME_OVERLAY_30_V1"),tenantId:TenantIdSchema,projectId:ProjectIdSchema,productionId:ProductionIdSchema,totalFrames:z51.int().min(1).max(1800),layers:z51.array(VisualLayerSchema).min(1).max(8)}).superRefine((v,context)=>{const sources=new Map;const frames=new Map;let bytes=0;for(const layer of v.layers){const source6=layer.source;const body=JSON.stringify(source6);for(const frame2 of source6.frames){const identity6=JSON.stringify({artifactId:frame2.artifactId,checksumSha256:frame2.checksumSha256,byteSize:frame2.byteSize,width:source6.width,height:source6.height});if(frames.has(frame2.representationId)&&frames.get(frame2.representationId)!==identity6)context.addIssue({code:"custom",message:"Shared frame representation has inconsistent facts"});frames.set(frame2.representationId,identity6)}if(source6.tenantId!==v.tenantId||source6.projectId!==v.projectId||source6.productionId!==null&&source6.productionId!==v.productionId||layer.startFrame+layer.sourceOutFrame-layer.sourceInFrame>v.totalFrames||sources.has(source6.representationId)&&sources.get(source6.representationId)!==body)context.addIssue({code:"custom",message:"Layer source scope/identity/output bounds mismatch"});if(!sources.has(source6.representationId))bytes+=source6.frames.reduce((n,f)=>n+f.byteSize,0);sources.set(source6.representationId,body)}if(new Set(v.layers.map(l=>l.id)).size!==v.layers.length||new Set(v.layers.map(l=>l.zIndex)).size!==v.layers.length||bytes>256*1024*1024)context.addIssue({code:"custom",message:"Layer instance/z-order/byte budget mismatch"})});var TimelineVisualLayerInputSchema=z52.strictObject({id:z52.uuid(),artifactId:ArtifactIdSchema,sourceInFrame:z52.int().min(0).max(359),sourceOutFrame:z52.int().min(1).max(360),startFrame:z52.int().min(0).max(1799),zIndex:z52.int().min(0).max(7),opacityPermille:z52.int().min(0).max(1e3),placement:VisualLayerPlacementSchema}).refine(layer=>layer.sourceOutFrame>layer.sourceInFrame&&layer.startFrame+layer.sourceOutFrame-layer.sourceInFrame<=1800,"Dynamic layer interval must advance and fit the output clock");var TimelineV3ManifestSchema=TimelineV2ManifestSchema.extend({schemaVersion:z52.literal(3),visualLayers:VisualLayerCompositionSchema});var TimelineV3VersionSchema=TimelineV3ManifestSchema.extend(TimelineVersionIdentityShape).superRefine((timeline,context)=>{validateTimelineAttachments(timeline,context);validateTimelineVisualLayerClock(timeline,context)});function validateTimelineVisualLayerClock(timeline,context){const composition2=timeline.visualLayers;let sourceMs=0;let totalFrames=0;let previousFrames=0;for(const[index,clip]of timeline.clips.entries()){const previousBoundary=Math.round(sourceMs*30/1e3);sourceMs+=clip.durationMs;const frames=Math.round(sourceMs*30/1e3)-previousBoundary;const overlap=clip.transition==="CUT"?0:clip.transition.durationFrames;if(clip.ordinal!==index+1||frames<1||overlap>0&&(index===0||overlap>=frames||overlap>=previousFrames))context.addIssue({code:"custom",message:"Dynamic Timeline clip frame plan mismatch"});totalFrames+=frames-overlap;previousFrames=frames}if(timeline.tenantId!==void 0&&composition2.tenantId!==timeline.tenantId||timeline.projectId!==void 0&&composition2.projectId!==timeline.projectId||timeline.productionId!==void 0&&composition2.productionId!==timeline.productionId||composition2.totalFrames!==totalFrames||Math.abs(totalFrames*1e3/30-timeline.duration.totalMs)>1e3/60+.001)context.addIssue({code:"custom",message:"Dynamic Timeline ownership or physical output clock mismatch"})}import{z as z53}from"zod";var FinalRenderProfileIdSchema=z53.enum(["FINAL_H264_720P_V1","FINAL_H264_1080P_V1","FINAL_H264_480P_V1"]);var FinalRenderProfileSchema=z53.strictObject({id:FinalRenderProfileIdSchema,algorithm:z53.enum(["ORDERED_TRIM_CUT_V1","ORDERED_COMPOSE_V2"]),picturePolicy:PicturePolicySchema.optional(),width:z53.union([z53.literal(1280),z53.literal(720),z53.literal(1920),z53.literal(1080),z53.literal(854),z53.literal(480)]),height:z53.union([z53.literal(1280),z53.literal(720),z53.literal(1920),z53.literal(1080),z53.literal(854),z53.literal(480)]),frameRate:z53.literal(30),codec:z53.literal("h264"),pixelFormat:z53.literal("yuv420p"),fit:z53.literal("PAD"),hasAudio:z53.boolean(),audioMix:AudioMixProfileSchema.optional(),framePolicy:z53.literal("CUMULATIVE_NEAREST_FRAME"),encoder:z53.literal("libx264"),crf:z53.literal(18),preset:z53.literal("veryfast"),gopFrames:z53.literal(30),bFrames:z53.literal(0),audioPolicy:z53.enum(["SILENT","MIXED"]),captionPolicy:z53.enum(["NONE","BURN_IN"]),sourceQualityPolicy:z53.literal("NO_UPSCALE_V1"),captionStyle:CaptionRenderStyleSchema.optional(),graphicsPolicy:z53.literal("OVERLAY_V1").optional()}).superRefine((profile,context)=>{if(profile.hasAudio!==!!profile.audioMix||profile.hasAudio!==(profile.audioPolicy==="MIXED"))context.addIssue({code:"custom",message:"Exact native audio policy and mix must agree"});if(!!profile.captionStyle!==(profile.captionPolicy==="BURN_IN"))context.addIssue({code:"custom",message:"Caption burn-in requires exact native style"});const pair=profile.id==="FINAL_H264_720P_V1"?[1280,720]:profile.id==="FINAL_H264_480P_V1"?[854,480]:[1920,1080];if(!(profile.width===pair[0]&&profile.height===pair[1]||profile.width===pair[1]&&profile.height===pair[0]))context.addIssue({code:"custom",message:"Final profile geometry mismatch"})});var VisualLayerPolicySchema=z54.enum(["STRAIGHT_ALPHA_FRAME_OVERLAY_30_V1","STRAIGHT_ALPHA_FRAME_OVERLAY_30_V2"]);var VisualLayerPreviewProfileSchema=RoughCutProfileSchema.safeExtend({visualLayerPolicy:VisualLayerPolicySchema});var VisualLayerFinalProfileSchema=FinalRenderProfileSchema.safeExtend({visualLayerPolicy:VisualLayerPolicySchema,visualLayerSourceQualityPolicy:z54.literal("NO_UPSCALE_V1")});var shape={schemaVersion:z54.literal(3),timeline:TimelineV3VersionSchema};var preview=RoughCutManifestSchema.extend({...shape,profile:VisualLayerPreviewProfileSchema});var final=RoughCutManifestSchema.extend({...shape,profile:VisualLayerFinalProfileSchema});function validateClock(value2,context){if(value2.totalFrames!==value2.timeline.visualLayers.totalFrames)context.addIssue({code:"custom",message:"Dynamic render must use the frozen layer clock"})}var VisualLayerPreviewManifestSchema=preview.superRefine(validateClock);var VisualLayerFinalManifestSchema=final.superRefine(validateClock);var VisualLayerRenderManifestSchema=z54.union([VisualLayerPreviewManifestSchema,VisualLayerFinalManifestSchema]);import{z as z59}from"zod";import{z as z56}from"zod";import{z as z55}from"zod";var processorFamilies={IMPORTED_VISUAL_NORMALIZE:"ARTIFACT_INGEST",SOURCE_SYNC_AUDIO:"ARTIFACT_INGEST",TEMPORAL_SAMPLE:"TEMPORAL_SAMPLE",DELIVERY_VALIDATE:"DELIVERY_VALIDATE",COMPOSITION_RENDER:"COMPOSITION_RENDER",IMPORT_ORIGINAL:"ARTIFACT_INGEST",LOCAL_MEDIA_INSPECT:"OBSERVE",LOCAL_MEDIA_PUBLISH:"ARTIFACT_INGEST",IMPORT_PROJECT_SOURCE:"ARTIFACT_INGEST",REGISTER_VISUAL_SEQUENCE:"ARTIFACT_INGEST",REFERENCE_PREVIEW:"PLANNING_MATERIALIZE",SPEECH_SYNTHESIZE:"AUDIO_GENERATE",SPEECH_SYNTHESIZE_CPU:"AUDIO_GENERATE",SPEECH_EXTERNAL_QWEN:"AUDIO_GENERATE",TRANSCRIBE_AUDIO:"OBSERVE",TRANSCRIBE_EXTERNAL_QWEN:"OBSERVE",KEYFRAME_GENERATE:"KEYFRAME_GENERATE",VIDEO_GENERATE:"VIDEO_GENERATE"};var TenantProcessorKindSchema=z55.enum(Object.keys(processorFamilies));var referenceThumbnailProfile={processor:"REFERENCE_PREVIEW",format:"PNG_480_INSIDE_V1",maxDimension:480,maxBytes:1024*1024};var validationMode=z56.literal("TENANT_TRUSTED_VALIDATOR").optional();var DeviceRenderTargetSchema=z56.strictObject({mode:z56.literal("tenant-device-only"),deviceId:z56.uuid().optional(),validationMode});var DeviceRenderReceiptSchema=z56.strictObject({mode:z56.literal("tenant-device-only"),deviceId:z56.uuid(),runtimeJobId:z56.uuid(),validationMode});var projectDeviceScope=z56.strictObject({tenantId:z56.uuid(),projectId:z56.uuid(),kind:z56.enum(["preview","final","library",...TenantProcessorKindSchema.options])});var ProjectDeviceListInputSchema=projectDeviceScope.extend({deviceId:z56.uuid().optional()});var ProjectDeviceListSchema=projectDeviceScope.extend({items:z56.array(z56.strictObject({deviceId:z56.uuid(),label:z56.string().trim().min(1).max(120),availability:z56.enum(["AVAILABLE","BUSY","OFFLINE","UNQUALIFIED"])})).max(50),truncated:z56.boolean(),validationMode:z56.literal("TENANT_TRUSTED_VALIDATOR").nullable(),recovery:DeviceSetupRecoverySchema.optional()});import{z as z58}from"zod";import{z as z57}from"zod";var TimelineVersionReaderSchema=z57.discriminatedUnion("schemaVersion",[TimelineVersionSchema,TimelineV2VersionSchema,TimelineV3VersionSchema]);var TimelineManifestReaderSchema=z57.discriminatedUnion("schemaVersion",[TimelineManifestSchema,TimelineV2ManifestSchema,TimelineV3ManifestSchema.superRefine(validateTimelineVisualLayerClock)]);var TimelineScopeSchema=z58.strictObject({tenantId:TenantIdSchema,productionId:ProductionIdSchema});var TimelineClipInputSchema=z58.strictObject({shotId:ShotIdSchema,acceptanceId:z58.uuid(),framing:ClipFramingSchema.optional(),transition:ClipTransitionSchema.optional(),sourceInMs:z58.int().nonnegative().max(30150),sourceOutMs:z58.int().positive().max(30150)}).refine(v=>v.sourceOutMs>v.sourceInMs,"Clip source range must advance");var BuildTimelineShapeSchema=TimelineScopeSchema.extend({schemaVersion:z58.union([z58.literal(2),z58.literal(3)]).optional(),expectedProductionRevision:z58.int().positive(),expectedTimelineVersion:z58.int().nonnegative(),idempotencyKey:z58.string().trim().min(1).max(200),clips:z58.array(TimelineClipInputSchema).min(1).max(200),captionVersionId:z58.uuid().optional(),audio:TimelineAudioInputSchema.optional(),sourceSound:TimelineSourceSoundInputSchema.optional(),graphics:z58.array(TimelineGraphicInputSchema).max(8).optional(),visualLayers:z58.array(TimelineVisualLayerInputSchema).min(1).max(8).optional()});var BuildTimelineSchema=BuildTimelineShapeSchema.superRefine((input,context)=>{if(input.sourceSound&&!input.schemaVersion)context.addIssue({code:"custom",message:"Source sound requires explicit Timeline2/3"});if(input.schemaVersion===3!==!!input.visualLayers?.length)context.addIssue({code:"custom",message:"Dynamic layers require explicit Timeline3"});if(input.visualLayers&&(new Set(input.visualLayers.map(layer=>layer.id)).size!==input.visualLayers.length||new Set(input.visualLayers.map(layer=>layer.zIndex)).size!==input.visualLayers.length))context.addIssue({code:"custom",message:"Dynamic layer IDs and z-order must be unique"})});var TimelineStaleReasonSchema=z58.enum(["BRIEF_CHANGED","STORY_CHANGED","PLAN_CHANGED","SHOT_ACCEPTANCE_CHANGED","PRODUCTION_UNAVAILABLE","CAPTION_VERSION_CHANGED","CAPTION_UNAVAILABLE","AUDIO_VERSION_CHANGED","AUDIO_UNAVAILABLE","GRAPHIC_UNAVAILABLE","VISUAL_LAYER_UNAVAILABLE","SOUND_PLAN_CHANGED","SOURCE_SOUND_UNAVAILABLE"]);var TimelineViewSchema=z58.strictObject({version:TimelineVersionReaderSchema,isCurrent:z58.boolean(),freshness:z58.enum(["CURRENT_BASIS","STALE_BASIS"]),staleReasons:z58.array(TimelineStaleReasonSchema).max(13),assemblyStatus:z58.enum(["DRAFT","ASSEMBLY_READY"])});var TimelineGetSchema=TimelineScopeSchema.extend({versionId:z58.uuid()});var TimelineQuerySchema=TimelineScopeSchema.extend({limit:QueryLimitSchema,next:ContinuationSchema.optional()});var TimelinePageSchema=z58.strictObject({items:z58.array(TimelineViewSchema),page:QueryPageInfoSchema});var TimelineBuildReceiptSchema=z58.strictObject({semanticStatus:z58.literal("SUCCESS"),version:TimelineVersionReaderSchema,productionRevision:z58.int().positive()});var TimelineBasisSchema=TimelineScopeSchema.extend({productionRevision:z58.int().positive(),currentTimelineVersion:z58.int().nonnegative(),runnable:z58.boolean(),planningReady:z58.boolean(),output:TimelineManifestSchema.shape.output.nullable(),targetDurationMs:z58.int().positive().nullable(),shots:z58.array(z58.strictObject({shotId:ShotIdSchema,ordinal:z58.int().positive(),acceptanceStatus:z58.enum(["NONE","CURRENT","STALE"]),source:AcceptedVisualSourceReferenceSchema.nullable(),technical:VideoTechnicalMetadataSchema.nullable()})).max(200)});var TimelineSnapshotSchema=z58.strictObject({currentVersion:z58.int().positive().nullable(),stale:z58.boolean(),timelineId:z58.uuid().nullable(),versionId:z58.uuid().nullable(),assemblyStatus:z58.enum(["DRAFT","ASSEMBLY_READY"]).nullable(),totalDurationMs:z58.int().positive().nullable(),durationClassification:TimelineDurationSchema.shape.classification.nullable(),missingPlannedShots:z58.int().nonnegative(),staleReasons:z58.array(TimelineStaleReasonSchema).max(13)});var sha5=z59.string().regex(/^[0-9a-f]{64}$/);var RoughCutStartSchema=TimelineScopeSchema.extend({deviceExecution:DeviceRenderTargetSchema.optional(),timelineVersionId:z59.uuid(),timelineFingerprint:sha5,expectedProductionRevision:z59.int().positive(),profileId:RoughCutProfileIdSchema,idempotencyKey:z59.string().trim().min(1).max(200)});var RoughCutGetSchema=TimelineScopeSchema.extend({renderId:z59.uuid()});var RoughCutQuerySchema=TimelineScopeSchema.extend({limit:QueryLimitSchema,next:ContinuationSchema.optional()});var RoughCutV2ManifestSchema=RoughCutManifestSchema.extend({schemaVersion:z59.literal(2),timeline:TimelineV2VersionSchema});var RoughCutManifestReaderSchema=z59.discriminatedUnion("schemaVersion",[RoughCutManifestSchema,RoughCutV2ManifestSchema,VisualLayerPreviewManifestSchema]);var RoughCutTechnicalSchema=VideoTechnicalMetadataSchema.extend({hasAudio:z59.boolean(),audio:RenderedAudioSchema.optional(),durationMs:z59.int().min(29983).max(60017),frameRate:z59.literal(30),frameCount:z59.int().min(900).max(1800),engineVersion:z59.string().min(1).max(200)}).superRefine((v,ctx)=>{if(v.hasAudio!==!!v.audio||v.audio&&v.audio.sampleCount!==v.frameCount*1600)ctx.addIssue({code:"custom",message:"Actual audio stream must match physical output samples"})});var RoughCutArtifactSchema=RoughCutTechnicalSchema.safeExtend({artifactId:z59.uuid(),representationId:z59.uuid(),version:z59.int().positive(),poster:VideoPosterSchema,availability:z59.enum(["AVAILABLE","INVALID"]),reviewState:z59.enum(["UNREVIEWED","PASS","WARNING","FAIL"])});var RoughCutAdmissionSchema=z59.strictObject({humanLinks:HumanLinksSchema.optional(),deviceExecution:DeviceRenderReceiptSchema.optional(),semanticStatus:z59.literal("ACCEPTED"),renderId:z59.uuid(),operationId:OperationIdSchema,productionId:z59.uuid(),timelineVersionId:z59.uuid(),timelineFingerprint:sha5,executionClass:z59.enum(["LIVE","TEST_ONLY"]),manifestFingerprint:sha5,productionRevision:z59.int().positive()});var RoughCutViewSchema=TimelineScopeSchema.extend({humanLinks:HumanLinksSchema.optional(),renderId:z59.uuid(),projectId:ProjectIdSchema,runtimeJobId:z59.uuid(),operationId:OperationIdSchema,manifest:RoughCutManifestReaderSchema,manifestFingerprint:sha5,runtimeStatus:VideoGenerationViewSchema.shape.runtimeStatus,cancellationRequested:z59.boolean(),isCurrentTimeline:z59.boolean(),freshness:z59.enum(["CURRENT_BASIS","STALE_BASIS"]),staleReasons:z59.array(z59.string().min(1).max(120)).max(16),executionClass:z59.enum(["LIVE","TEST_ONLY"]),roughCut:RoughCutArtifactSchema.nullable(),createdByPrincipalId:PrincipalIdSchema,createdAt:z59.iso.datetime({offset:true})});var RoughCutPageSchema=z59.strictObject({items:z59.array(RoughCutViewSchema),page:QueryPageInfoSchema});var RoughCutSnapshotSchema=z59.strictObject({latestVersion:z59.int().positive().nullable(),reviewState:z59.enum(["UNREVIEWED","PASS","WARNING","FAIL"]).nullable(),latestRenderId:z59.uuid().nullable(),runtimeStatus:VideoGenerationViewSchema.shape.runtimeStatus.nullable(),currentRenderId:z59.uuid().nullable(),currentArtifactId:z59.uuid().nullable(),currentTimelineVersionId:z59.uuid().nullable(),stale:z59.boolean()});import{z as z63}from"zod";import{z as z61}from"zod";import{z as z60}from"zod";var sha6=z60.string().regex(/^[0-9a-f]{64}$/);var DeliveryPolicySchema=z60.strictObject({schemaVersion:z60.literal(1),requiredAudio:z60.boolean(),requiredCaptions:z60.boolean(),requiredGraphics:z60.boolean(),finalApproval:z60.enum(["AUTOMATIC","HUMAN"])});var DeliveryPolicyInputSchema=DeliveryPolicySchema.extend({requiredAudio:z60.boolean().default(false),requiredCaptions:z60.boolean().default(false),requiredGraphics:z60.boolean().default(false),finalApproval:z60.enum(["AUTOMATIC","HUMAN"]).default("AUTOMATIC")});var DeliveryCompositionSchema=z60.strictObject({hasAudio:z60.boolean(),hasCaptions:z60.boolean(),hasGraphics:z60.boolean()});var DeliveryTargetSchema=z60.strictObject({tenantId:z60.uuid(),projectId:z60.uuid(),productionId:z60.uuid(),renderId:z60.uuid(),timelineVersionId:z60.uuid(),timelineFingerprint:sha6,selectionId:z60.uuid(),selectionVersion:z60.int().positive(),renderManifestFingerprint:sha6,artifactId:z60.uuid(),representationId:z60.uuid(),checksumSha256:sha6,byteSize:z60.int().positive().max(128*1024*1024),executionClass:z60.enum(["LIVE","TEST_ONLY"])});var deliveryPhysicalCheckKeys=["FILE_READABLE","CHECKSUM","CONTAINER_PROFILE","DURATION","VIDEO_DECODE","AUDIO_DECODE","REQUIRED_AUDIO","REQUIRED_CAPTIONS","REQUIRED_GRAPHICS","MISSING_MEDIA","BLACK_FRAMES"];var DeliveryCheckKeySchema=z60.enum([...deliveryPhysicalCheckKeys,"ARTIFACT_REGISTRATION","PROVENANCE","MANIFEST_INTEGRITY","EXACT_BASIS","BLOCKING_FINDINGS"]);var DeliveryCheckSchema=z60.strictObject({key:DeliveryCheckKeySchema,status:z60.enum(["PASS","FAIL","UNVERIFIED","NOT_APPLICABLE"]),detail:z60.string().trim().min(1).max(1e3)});var DeliveryPhysicalChecksSchema=z60.array(DeliveryCheckSchema.extend({key:z60.enum(deliveryPhysicalCheckKeys)})).length(deliveryPhysicalCheckKeys.length).refine(checks=>new Set(checks.map(check=>check.key)).size===deliveryPhysicalCheckKeys.length,"Exact physical media checks required");var DeliveryValidationReviewSchema=z60.strictObject({id:z60.uuid(),target:DeliveryTargetSchema,policy:DeliveryPolicySchema,policyFingerprint:sha6,composition:DeliveryCompositionSchema,checks:z60.array(DeliveryCheckSchema).length(DeliveryCheckKeySchema.options.length),result:z60.enum(["PASS","FAIL"]),blockingChecks:z60.array(DeliveryCheckKeySchema).max(DeliveryCheckKeySchema.options.length),createdAt:z60.iso.datetime({offset:true})}).superRefine((review2,ctx)=>{const seen=new Set;const blocked=new Set;const{policy,composition:composition2}=review2;for(const check of review2.checks){if(seen.has(check.key))ctx.addIssue({code:"custom",message:"Duplicate deterministic delivery check"});seen.add(check.key);const mayOmit=check.key==="AUDIO_DECODE"&&!composition2.hasAudio||check.key==="REQUIRED_AUDIO"&&!policy.requiredAudio||check.key==="REQUIRED_CAPTIONS"&&!policy.requiredCaptions||check.key==="REQUIRED_GRAPHICS"&&!policy.requiredGraphics;if(check.status==="NOT_APPLICABLE"&&!mayOmit)ctx.addIssue({code:"custom",message:"Required delivery evidence cannot be omitted"});if(check.status==="FAIL"||check.status==="UNVERIFIED")blocked.add(check.key)}if(policy.requiredAudio&&!composition2.hasAudio)blocked.add("REQUIRED_AUDIO");if(policy.requiredCaptions&&!composition2.hasCaptions)blocked.add("REQUIRED_CAPTIONS");if(policy.requiredGraphics&&!composition2.hasGraphics)blocked.add("REQUIRED_GRAPHICS");const expected=DeliveryCheckKeySchema.options.filter(key10=>blocked.has(key10));if(review2.result!==(expected.length?"FAIL":"PASS")||JSON.stringify(review2.blockingChecks)!==JSON.stringify(expected))ctx.addIssue({code:"custom",message:"Review result and blockers must match complete owned evidence"})});var sha7=z61.string().regex(/^[0-9a-f]{64}$/);function sameTarget(a,b){return Object.keys(DeliveryTargetSchema.shape).every(key10=>a[key10]===b[key10])}var DeliveryApprovalSchema=z61.strictObject({id:z61.uuid(),reviewId:z61.uuid(),target:DeliveryTargetSchema,policyFingerprint:sha7,authority:z61.literal("HUMAN"),action:z61.enum(["APPROVE","REJECT"]),principalId:z61.uuid(),createdAt:z61.iso.datetime({offset:true})});var DeliveryManifestLinkSchema=z61.strictObject({id:z61.uuid(),checksumSha256:sha7,target:DeliveryTargetSchema,policyFingerprint:sha7,reviewId:z61.uuid()});var FinalDeliveryReceiptSchema=z61.strictObject({id:z61.uuid(),deliveryRole:z61.literal("FINAL_ARTIFACT"),review:DeliveryValidationReviewSchema,manifest:DeliveryManifestLinkSchema,approval:DeliveryApprovalSchema.nullable(),productionRevision:z61.int().positive(),completedAt:z61.iso.datetime({offset:true})}).superRefine((receipt,ctx)=>{const{review:review2,manifest,approval}=receipt;if(review2.result!=="PASS"||!sameTarget(manifest.target,review2.target)||manifest.reviewId!==review2.id||manifest.policyFingerprint!==review2.policyFingerprint)ctx.addIssue({code:"custom",message:"Final delivery requires an exact PASS Review and Manifest"});if(review2.policy.finalApproval==="HUMAN"){if(!approval||approval.action!=="APPROVE"||approval.reviewId!==review2.id||approval.policyFingerprint!==review2.policyFingerprint||!sameTarget(approval.target,review2.target))ctx.addIssue({code:"custom",message:"Configured Human gate requires exact Human approval"})}else if(approval){ctx.addIssue({code:"custom",message:"Automatic delivery does not carry an unconfigured approval"})}});import{z as z62}from"zod";var sha8=z62.string().regex(/^[0-9a-f]{64}$/);var DecideFinalReadySchema=TimelineScopeSchema.extend({renderId:z62.uuid(),reviewId:z62.uuid(),basisFingerprint:sha8,action:z62.enum(["SELECT","REJECT"]),acknowledgeWarnings:z62.boolean().default(false),expectedProductionRevision:z62.int().positive(),expectedFinalReadyVersion:z62.int().nonnegative(),reason:z62.string().trim().min(1).max(2500),idempotencyKey:z62.string().trim().min(1).max(200)});var RevokeFinalReadySchema=TimelineScopeSchema.extend({selectionId:z62.uuid(),expectedFinalReadyVersion:z62.int().positive(),expectedProductionRevision:z62.int().positive(),reason:z62.string().trim().min(1).max(2500),idempotencyKey:z62.string().trim().min(1).max(200)});var FinalReadyDecisionSchema=TimelineScopeSchema.extend({id:z62.uuid(),projectId:ProjectIdSchema,version:z62.int().positive(),action:z62.enum(["SELECT","REJECT","REVOKE"]),renderId:z62.uuid(),reviewId:z62.uuid(),basisFingerprint:sha8,timelineVersionId:z62.uuid(),timelineFingerprint:sha8,artifactId:z62.uuid(),representationId:z62.uuid(),checksumSha256:sha8,outputProfile:DeliveryOutputProfileSchema,executionClass:z62.enum(["LIVE","TEST_ONLY"]),previousSelectionId:z62.uuid().nullable(),acknowledgeWarnings:z62.boolean(),warningKeys:z62.array(z62.string()).max(300),reason:z62.string().min(1).max(2500),createdByPrincipalId:PrincipalIdSchema,createdAt:z62.iso.datetime({offset:true})});var FinalReadyViewSchema=TimelineScopeSchema.extend({version:z62.int().nonnegative(),status:z62.enum(["NONE","CURRENT","STALE"]),selection:FinalReadyDecisionSchema.nullable(),staleReasons:z62.array(z62.string()).max(24)});var FinalReadyQuerySchema=TimelineScopeSchema.extend({limit:QueryLimitSchema,next:ContinuationSchema.optional()});var FinalReadyPageSchema=z62.strictObject({items:z62.array(FinalReadyDecisionSchema),page:QueryPageInfoSchema});var FinalReadyReceiptSchema=z62.strictObject({semanticStatus:z62.literal("SUCCESS"),decision:FinalReadyDecisionSchema,productionRevision:z62.int().positive()});var RoughCutReviewSnapshotSchema=z62.strictObject({currentRenderId:z62.uuid().nullable(),latestReviewId:z62.uuid().nullable(),reviewVersion:z62.int().nonnegative(),result:z62.enum(["PASS","WARNING","FAIL"]).nullable(),current:z62.boolean(),inspectable:z62.boolean(),executionClass:z62.enum(["LIVE","TEST_ONLY"]).nullable(),findings:z62.strictObject({open:z62.int().nonnegative(),blocking:z62.int().nonnegative(),warnings:z62.int().nonnegative()}),finalReady:FinalReadyViewSchema,latestDecision:FinalReadyDecisionSchema.nullable()});var sha9=z63.string().regex(/^[0-9a-f]{64}$/);function hasTimelineAudio(timeline){return!!timeline.audio||!!timeline.sourceSound&&(timeline.sourceSound.clips.some(c=>!!c.source)||timeline.sourceSound.speechCues.length>0)}var FinalRenderStartSchema=TimelineScopeSchema.extend({deviceExecution:DeviceRenderTargetSchema.optional(),selectionId:z63.uuid(),expectedFinalReadyVersion:z63.int().positive(),timelineVersionId:z63.uuid(),timelineFingerprint:sha9,expectedProductionRevision:z63.int().positive(),profileId:FinalRenderProfileIdSchema,audioPolicy:z63.enum(["SILENT","MIXED"]),captionPolicy:z63.enum(["NONE","BURN_IN"]),idempotencyKey:z63.string().trim().min(1).max(200)});var FinalRenderGetSchema=RoughCutGetSchema;var FinalRenderQuerySchema=RoughCutQuerySchema;var finalManifestShape={selection:FinalReadyDecisionSchema.refine(v=>v.action==="SELECT"),selectionVersion:z63.int().positive(),profile:FinalRenderProfileSchema};var finalV1=RoughCutManifestSchema.extend(finalManifestShape);var finalV2=RoughCutV2ManifestSchema.extend(finalManifestShape);var finalV3=VisualLayerFinalManifestSchema.safeExtend({...finalManifestShape,profile:VisualLayerFinalProfileSchema});function validateFinalManifest(manifest,context){const{selection:selected,timeline,profile}=manifest;const expectedProfile=finalProfileIds[timeline.output.profile];const landscape=timeline.output.aspectRatio==="16:9";if(!!profile.picturePolicy!==timeline.clips.some(c=>!!c.framing)||profile.audioPolicy!==(hasTimelineAudio(timeline)?"MIXED":"SILENT")||!!profile.audioMix!==hasTimelineAudio(timeline)||profile.captionPolicy!==(timeline.caption?"BURN_IN":"NONE")||!!profile.captionStyle!==!!timeline.caption||!!profile.graphicsPolicy!==!!timeline.graphics?.length||selected.tenantId!==timeline.tenantId||selected.projectId!==timeline.projectId||selected.productionId!==timeline.productionId||selected.timelineVersionId!==timeline.id||selected.timelineFingerprint!==timeline.fingerprint||selected.version>manifest.selectionVersion||selected.outputProfile!==timeline.output.profile||selected.executionClass!==timeline.executionClass||profile.id!==expectedProfile||profile.width>profile.height!==landscape)context.addIssue({code:"custom",message:"Final selection, Timeline and profile mismatch"})}var FinalRenderManifestSchema=finalV1.superRefine(validateFinalManifest);var FinalRenderV2ManifestSchema=finalV2.superRefine(validateFinalManifest);var FinalRenderV3ManifestSchema=finalV3.superRefine(validateFinalManifest);var FinalRenderManifestReaderSchema=z63.discriminatedUnion("schemaVersion",[FinalRenderManifestSchema,FinalRenderV2ManifestSchema,FinalRenderV3ManifestSchema]);var FinalRenderTechnicalSchema=RoughCutTechnicalSchema;var FinalRenderArtifactSchema=RoughCutArtifactSchema.safeExtend({reviewState:z63.literal("UNREVIEWED"),deliveryRole:z63.literal("NONE")});var FinalRenderAdmissionSchema=RoughCutAdmissionSchema.extend({selectionId:z63.uuid(),selectionVersion:z63.int().positive(),profileId:FinalRenderProfileIdSchema});var FinalRenderViewSchema=RoughCutViewSchema.omit({roughCut:true,manifest:true,staleReasons:true}).extend({manifest:FinalRenderManifestReaderSchema,finalOutput:FinalRenderArtifactSchema.nullable(),finalDelivery:FinalDeliveryReceiptSchema.nullable().default(null),staleReasons:z63.array(z63.string().min(1).max(120)).max(24)});var FinalRenderPageSchema=z63.strictObject({items:z63.array(FinalRenderViewSchema).max(200),page:QueryPageInfoSchema});var FinalRenderSourceBlockerSchema=z63.strictObject({code:z63.enum(["SOURCE_RESOLUTION_INSUFFICIENT","SOURCE_MEDIA_UNSUPPORTED"]),shotId:z63.uuid(),ordinal:z63.int().positive().max(200),actualWidth:z63.int().positive().max(4096),actualHeight:z63.int().positive().max(4096),requiredWidth:z63.int().positive().max(4096),requiredHeight:z63.int().positive().max(4096)});var FinalRenderEligibilitySchema=TimelineScopeSchema.extend({productionRevision:z63.int().positive(),finalReady:FinalReadyViewSchema,profile:z63.union([FinalRenderProfileSchema,VisualLayerFinalProfileSchema]).nullable(),renderable:z63.boolean(),blockers:z63.array(z63.string().min(1).max(120)).max(24),sourceBlockers:z63.array(FinalRenderSourceBlockerSchema).max(200),supportedAudioPolicy:z63.enum(["SILENT","MIXED"]),supportedCaptionPolicy:z63.enum(["NONE","BURN_IN"])});var FinalRenderSnapshotSchema=z63.strictObject({latestRenderId:z63.uuid().nullable(),runtimeStatus:RoughCutViewSchema.shape.runtimeStatus.nullable(),currentRenderId:z63.uuid().nullable(),currentArtifactId:z63.uuid().nullable(),stale:z63.boolean(),eligibility:FinalRenderEligibilitySchema});import{z as z64}from"zod";var pixel=z64.int().nonnegative().max(4096);var dimension2=z64.int().positive().max(4096);var frame=z64.int().nonnegative().max(1800);var sample=z64.int().nonnegative().max(288e4);var rectangle=z64.strictObject({x:pixel,y:pixel,width:dimension2,height:dimension2});var window=z64.strictObject({start:sample,count:sample});var source=z64.strictObject({representationId:z64.uuid(),checksum:LocalDigestSchema,byteSize:z64.int().positive().max(134217728)});var LocalMediaRecipeSchema=z64.strictObject({protocol:z64.literal("NVS_RESOLVED_MEDIA_RECIPE_V2"),family:z64.enum(["ROUGH_CUT_RENDER","FINAL_RENDER"]),width:dimension2,height:dimension2,totalFrames:z64.int().min(900).max(1800),crf:z64.union([z64.literal(18),z64.literal(23)]),algorithm:z64.enum(["ORDERED_TRIM_CUT_V1","ORDERED_COMPOSE_V2"]),clips:z64.array(z64.strictObject({representationId:z64.uuid(),technical:VideoTechnicalMetadataSchema,sourceInMs:z64.int().nonnegative().max(6e4),sourceOutMs:z64.int().positive().max(6e4),startFrame:frame,frameCount:z64.int().positive().max(1800),overlapFrames:frame,crop:rectangle.nullable(),viewport:rectangle})).min(1).max(32),caption:z64.strictObject({style:CaptionRenderStyleSchema,references:z64.array(z64.strictObject({representationId:z64.uuid(),expectedUtf8:z64.string().max(65536)})).length(2),cues:z64.array(z64.strictObject({ordinal:z64.int().nonnegative().max(512),startFrame:frame,endFrame:frame,fontSize:z64.int().min(16).max(256),margin:pixel,text:z64.string().min(1).max(2e3)})).min(1).max(512)}).nullable(),audio:z64.strictObject({algorithm:z64.literal("PCM_WINDOW_MIX_AAC_V1"),tracks:z64.array(source.extend({channels:z64.union([z64.literal(1),z64.literal(2)]),sampleCount:z64.int().positive().max(288e4),sourceIn:sample,sourceOut:sample,start:sample,count:sample,gain:z64.int().nonnegative().max(1e3),duck:z64.int().nonnegative().max(1e3),duckWindows:z64.array(window).max(512)})).min(1).max(266)}).nullable(),graphics:z64.array(source.extend({contentType:z64.enum(["image/png","image/webp"]),sourceWidth:dimension2,sourceHeight:dimension2,width:dimension2,height:dimension2,x:pixel,y:pixel,startFrame:frame,endFrame:frame,opacity:z64.number().min(.1).max(1)})).max(8),visual:z64.strictObject({policy:VisualLayerPolicySchema.optional(),composition:VisualLayerCompositionSchema,plans:z64.array(z64.strictObject({id:z64.uuid(),startFrame:frame,endFrame:frame,width:dimension2,height:dimension2,x:pixel,y:pixel,opacityPermille:z64.int().min(0).max(1e3)})).max(8)}).nullable()}).superRefine((r,ctx)=>{if(r.width%2||r.height%2||r.clips.some(c=>c.viewport.x+c.viewport.width>r.width||c.viewport.y+c.viewport.height>r.height||c.sourceOutMs<=c.sourceInMs)||r.audio?.tracks.some(t=>t.sourceIn>=t.sourceOut||t.sourceOut>t.sampleCount||t.start+t.count>r.totalFrames*1600))ctx.addIssue({code:"custom",message:"Invalid bounded execution geometry or sample window"})});var previewProfile=z65.strictObject({kind:z65.literal("ROUGH_CUT_PREVIEW_V1"),profileId:z65.literal("PREVIEW_H264_480P_V1"),contractDigest:LocalDigestSchema});var studioProfile=z65.strictObject({kind:z65.literal("STUDIO_MEDIA_V2"),profileId:z65.literal("STUDIO_MEDIA_V2"),contractDigest:LocalDigestSchema});var audioProfile=z65.strictObject({kind:z65.literal("AUDIO_MEDIA_V1"),profileId:z65.literal("AUDIO_MEDIA_V1"),contractDigest:LocalDigestSchema});var LocalExecutionProfileSchema=z65.discriminatedUnion("kind",[previewProfile,studioProfile,audioProfile]);var LocalToolchainSchema=z65.strictObject({platform:LocalDevicePlatformSchema,rendererVersion:LocalPackageVersionSchema,rendererDigest:LocalDigestSchema,ffmpeg:z65.strictObject({version:z65.string().min(1).max(160),binaryDigest:LocalDigestSchema}),ffprobe:z65.strictObject({version:z65.string().min(1).max(160),binaryDigest:LocalDigestSchema}),profile:LocalExecutionProfileSchema,supported:z65.array(z65.strictObject({profile:LocalExecutionProfileSchema,rendererVersion:LocalPackageVersionSchema,rendererDigest:LocalDigestSchema})).max(4).optional()});function selectLocalToolchain(raw,contractDigest){const parsed=LocalToolchainSchema.safeParse(raw);if(!parsed.success)return null;const value2=parsed.data;if(value2.profile.contractDigest===contractDigest){return value2.supported&&value2.profile.kind!=="AUDIO_MEDIA_V1"?{...value2,supported:value2.supported.filter(s=>s.profile.kind!=="AUDIO_MEDIA_V1")}:value2}const selected=value2.supported?.find(s=>s.profile.contractDigest===contractDigest);if(!selected)return null;const{supported,...base3}=value2;void supported;return LocalToolchainSchema.parse({...base3,...selected})}var frozen=LocalWorkScopeSchema.extend({protocol:z65.literal("NVS_LOCAL_WORK_V1"),operationId:OperationIdSchema,renderId:LocalIdSchema,productionRevision:LocalRevisionSchema,executionClass:z65.enum(["LIVE","TEST_ONLY"]),policy:LocalPlacementPolicySchema,profile:previewProfile,manifest:RoughCutManifestReaderSchema,manifestFingerprint:LocalDigestSchema,sources:z65.array(z65.strictObject({artifactId:LocalIdSchema,representationId:LocalIdSchema,checksumSha256:LocalDigestSchema,byteSize:z65.int().positive(),contentType:z65.string().min(1).max(100)})).min(1).max(512)});var studio=frozen.extend({protocol:z65.literal("NVS_LOCAL_WORK_V2"),profile:studioProfile,manifest:z65.union([RoughCutManifestReaderSchema,FinalRenderManifestReaderSchema]),recipe:LocalMediaRecipeSchema,recipeFingerprint:LocalDigestSchema});var LocalFrozenWorkSchema=z65.discriminatedUnion("protocol",[frozen,studio]).superRefine((v,ctx)=>{const t=v.manifest.timeline;if(t.tenantId!==v.tenantId||t.projectId!==v.projectId||t.productionId!==v.productionId||t.executionClass!==v.executionClass)ctx.addIssue({code:"custom",message:"Frozen manifest scope/class mismatch"});if(v.protocol==="NVS_LOCAL_WORK_V2"&&(v.manifest.schemaVersion===3!==!!v.recipe.visual||v.manifest.schemaVersion===3&&v.manifest.profile.visualLayerPolicy!==(v.recipe.visual?.policy??"STRAIGHT_ALPHA_FRAME_OVERLAY_30_V1")))ctx.addIssue({code:"custom",message:"Recipe must preserve the frozen visual policy"});if(new Set(v.sources.map(s=>s.representationId)).size!==v.sources.length)ctx.addIssue({code:"custom",message:"Duplicate source representation"});if(v.protocol==="NVS_LOCAL_WORK_V2"&&(v.recipe.width!==v.manifest.profile.width||v.recipe.height!==v.manifest.profile.height||v.recipe.totalFrames!==v.manifest.totalFrames||v.recipe.family==="FINAL_RENDER"!=="selection"in v.manifest))ctx.addIssue({code:"custom",message:"Recipe must match its native render family and geometry"})});var LocalLeaseBindingSchema=LocalWorkScopeSchema.extend({attemptId:LocalIdSchema,assignmentRevision:LocalRevisionSchema,workerId:z65.string().min(1).max(200),workFingerprint:LocalDigestSchema,toolchainFingerprint:LocalDigestSchema});var target=LocalDeviceExecutionTargetSchema;var LocalExecutionLeaseSchema=LocalLeaseBindingSchema.extend({target,issuedAt:LocalTimeSchema,expiresAt:LocalTimeSchema}).refine(v=>Date.parse(v.expiresAt)>Date.parse(v.issuedAt));var LocalWorkAssignmentSchema=z65.strictObject({work:LocalFrozenWorkSchema,lease:LocalExecutionLeaseSchema,toolchain:LocalToolchainSchema,tenantMediaValidation:z65.literal(true).optional()}).superRefine(({work,lease,toolchain,tenantMediaValidation},ctx)=>{if(["tenantId","projectId","productionId","runtimeJobId"].some(k=>work[k]!==lease[k]))ctx.addIssue({code:"custom",message:"Assignment work scope mismatch"});if(tenantMediaValidation&&(work.protocol!=="NVS_LOCAL_WORK_V2"||work.policy.mode!=="local-only"))ctx.addIssue({code:"custom",message:"Invalid tenant validation assignment"});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 z67}from"zod";import{z as z66}from"zod";var MediaCategorySchema=z66.enum(["IMAGE","VIDEO","AUDIO","DOCUMENT"]);function mediaCategoryOf(contentType){if(contentType.startsWith("image/"))return"IMAGE";if(contentType.startsWith("video/"))return"VIDEO";if(contentType.startsWith("audio/"))return"AUDIO";return"DOCUMENT"}var localLibraryProfile={protocol:"NVS_LOCAL_LIBRARY_V1",inspection:"LOCAL_FILE_DECODE_V1",publication:"COMMITTED_SOURCE_READBACK_V1"};var LocalLibraryContentTypeSchema=z67.enum(["video/mp4","image/png","image/jpeg","image/webp","audio/wav","text/plain","application/json","application/pdf","application/octet-stream"]);var LocalLibraryVersionSchema=z67.strictObject({fileId:LocalIdSchema,versionId:LocalIdSchema,checksumSha256:LocalDigestSchema,byteSize:z67.int().nonnegative().max(128*1024*1024),contentType:LocalLibraryContentTypeSchema});var LocalLibraryReferenceSchema=LocalProjectScopeSchema.extend({deviceId:LocalIdSchema,...LocalLibraryVersionSchema.shape});var LocalLibraryMetadataSchema=z67.strictObject({label:z67.string().trim().min(1).max(255)});var LocalLibraryAccessCommandSchema=z67.strictObject({reference:LocalLibraryReferenceSchema,requestId:LocalIdSchema,expectedRevision:z67.int().nonnegative(),metadata:LocalLibraryMetadataSchema.nullable(),allowInspect:z67.boolean(),allowPublish:z67.boolean(),expiresAt:LocalTimeSchema});var LocalLibraryAccessReceiptSchema=LocalLibraryAccessCommandSchema.extend({revision:z67.int().positive(),recordedAt:LocalTimeSchema});var LocalLibraryAccessQuerySchema=z67.strictObject({reference:LocalLibraryReferenceSchema,requestId:LocalIdSchema});var LocalLibraryAccessCurrentSchema=z67.strictObject({reference:LocalLibraryReferenceSchema});var LocalLibraryAccessStateSchema=z67.strictObject({state:z67.enum(["LOCAL_ONLY","PENDING","SYNCED","UNKNOWN","REJECTED"]),desired:LocalLibraryAccessCommandSchema.nullable(),confirmed:LocalLibraryAccessReceiptSchema.nullable()});var LocalLibraryItemSchema=z67.strictObject({reference:LocalLibraryReferenceSchema,ownerKey:LocalDigestSchema,title:z67.string().trim().min(1).max(255),createdAt:LocalTimeSchema,revision:z67.int().positive(),access:LocalLibraryAccessStateSchema});var pageFields={after:LocalDigestSchema.nullable().default(null),limit:z67.int().min(1).max(16).default(16)};var LocalLibraryQuerySchema=LocalProjectScopeSchema.extend({projectId:LocalIdSchema.optional(),deviceId:LocalIdSchema,ownerKey:LocalDigestSchema.optional(),search:z67.string().trim().min(1).max(200).optional(),mediaCategory:MediaCategorySchema.optional(),...pageFields});var LocalLibraryPageSchema=z67.strictObject({items:z67.array(LocalLibraryItemSchema).max(16),nextCursor:LocalDigestSchema.nullable()});var LocalLibraryProjectionSchema=z67.strictObject({reference:LocalLibraryReferenceSchema,metadata:LocalLibraryMetadataSchema.nullable(),accessRevision:z67.int().positive(),allowInspect:z67.boolean(),allowPublish:z67.boolean(),expiresAt:LocalTimeSchema});var LocalLibraryProjectionPageSchema=z67.strictObject({items:z67.array(LocalLibraryProjectionSchema).max(16),nextCursor:LocalDigestSchema.nullable()});var LocalLibraryProjectionQuerySchema=LocalLibraryQuerySchema.omit({ownerKey:true}).extend({projectId:LocalIdSchema});var LocalLibraryImportSchema=z67.strictObject({requestId:LocalIdSchema,reference:LocalLibraryReferenceSchema,ownerKey:LocalDigestSchema,title:z67.string().trim().min(1).max(255)});var LocalLibraryImportReceiptQuerySchema=LocalProjectScopeSchema.extend({deviceId:LocalIdSchema,requestId:LocalIdSchema,ownerKey:LocalDigestSchema.optional()});var LocalLibraryReadSchema=z67.strictObject({reference:LocalLibraryReferenceSchema,ownerKey:LocalDigestSchema.optional(),offset:z67.int().nonnegative(),length:z67.int().min(1).max(128*1024)});var LocalLibraryReadReplySchema=z67.strictObject({reference:LocalLibraryReferenceSchema,offset:z67.int().nonnegative(),contentBase64:z67.string().max(174764).regex(/^[A-Za-z0-9+/]*={0,2}$/),complete:z67.boolean()});var LocalLibraryGetSchema=z67.strictObject({reference:LocalLibraryReferenceSchema,ownerKey:LocalDigestSchema.optional()});var LocalLibraryAccessInputSchema=z67.strictObject({command:LocalLibraryAccessCommandSchema,expectedLocalRevision:z67.int().positive(),ownerKey:LocalDigestSchema.optional()});var LocalLibraryCallSchema=z67.discriminatedUnion("action",[LocalLibraryQuerySchema.extend({action:z67.literal("list")}),LocalLibraryGetSchema.extend({action:z67.literal("get")}),LocalLibraryProjectionQuerySchema.extend({action:z67.literal("scoped-list")}),z67.strictObject({action:z67.literal("scoped-get"),reference:LocalLibraryReferenceSchema}),z67.strictObject({action:z67.literal("usage"),ownerKey:LocalDigestSchema.optional()}),LocalLibraryReadSchema.extend({action:z67.literal("read")}),LocalLibraryAccessInputSchema.extend({action:z67.literal("access")}),LocalLibraryAccessQuerySchema.extend({action:z67.literal("sync"),ownerKey:LocalDigestSchema.optional()}),LocalLibraryAccessQuerySchema.extend({action:z67.literal("resume-access"),ownerKey:LocalDigestSchema.optional()}),LocalLibraryImportReceiptQuerySchema.extend({action:z67.literal("import-receipt")})]);var LocalLibraryCapabilitySchema=z67.strictObject({protocol:z67.literal("NVS_LOCAL_LIBRARY_V1"),available:z67.boolean(),profileDigest:LocalDigestSchema});var LocalLibraryUsageSchema=z67.strictObject({fileCount:z67.int().nonnegative(),totalBytes:z67.int().nonnegative(),quotaBytes:z67.int().positive(),availableDiskBytes:z67.int().nonnegative()});import{z as z76}from"zod";import{z as z68}from"zod";var TemporalEvidenceReferenceSchema=z68.strictObject({evidenceId:z68.uuid(),frameSetArtifactId:z68.uuid(),contactSheetArtifactId:z68.uuid(),manifestRepresentationId:z68.uuid(),sheetRepresentationId:z68.uuid(),planFingerprint:z68.string().regex(/^[0-9a-f]{64}$/),sourceArtifactId:z68.uuid(),sourceRepresentationId:z68.uuid(),sourceChecksumSha256:z68.string().regex(/^[0-9a-f]{64}$/),timestampsMs:z68.array(z68.number().nonnegative().max(6e4)).min(1).max(64),executionClass:z68.enum(["LIVE","TEST_ONLY"])});var TemporalEvidenceIdsSchema=z68.array(z68.uuid()).min(1).max(8).refine(v=>new Set(v).size===v.length,"Evidence references must be unique");import{z as z75}from"zod";import{z as z70}from"zod";import{z as z69}from"zod";var ListeningEvidenceIdsSchema=z69.array(z69.string().min(1).max(100)).max(64);var ListeningEvidenceSchema=z69.strictObject({id:z69.string().trim().min(1).max(100),kind:z69.enum(["AUDIO_LISTENING","VIDEO_WITH_AUDIO_PLAYBACK"]),media:z69.strictObject({artifactId:z69.uuid(),representationId:z69.uuid(),checksumSha256:z69.string().regex(/^[0-9a-f]{64}$/)}),coverage:z69.array(z69.strictObject({startMs:z69.int().nonnegative().max(6e4),endMs:z69.int().positive().max(6e4)}).refine(v=>v.endMs>v.startMs)).min(1).max(200),producer:z69.string().trim().min(1).max(200)});var ListeningEvidenceSetSchema=z69.array(ListeningEvidenceSchema).max(64).refine(v=>new Set(v.map(e=>e.id)).size===v.length);var sha10=z70.string().regex(/^[a-f0-9]{64}$/);var VoiceListeningIntervalSchema=ListeningEvidenceSchema.shape.coverage.element;var VoiceExpectationSchema=z70.strictObject({voiceProfile:VoiceProfileRefSchema,referenceId:z70.uuid()});var VoiceRuleTargetsSchema=z70.discriminatedUnion("kind",[z70.strictObject({kind:z70.literal("VOICEOVER")}),z70.strictObject({kind:z70.literal("SOUND_CUES"),cueIds:z70.array(z70.string().regex(/^[a-z][a-z0-9_-]{0,63}$/)).min(1).max(64).refine(ids=>new Set(ids).size===ids.length)})]);var VoiceConsistencyReasonSchema=z70.enum(["NO_SOURCE","VOICE_UNAVAILABLE","REFERENCE_CHANGED","AUDIO_UNAVAILABLE","IDENTITY_MISMATCH","NO_COMPARISON","COMPARISON_NOT_MATCHED","COMPARISON_STALE","TEST_ONLY"]);var VoiceRequirementGateSchema=z70.strictObject({qualified:z70.boolean(),evidenceFingerprint:sha10,listeningIntervals:z70.array(VoiceListeningIntervalSchema).min(1).max(264),sourceAudioVersionIds:z70.array(z70.uuid()).max(65),reasons:z70.array(VoiceConsistencyReasonSchema).max(9)}).refine(v=>v.qualified===(v.reasons.length===0)&&(!v.qualified||v.sourceAudioVersionIds.length>0));var VoiceSourceEvidenceSchema=z70.strictObject({audioVersionId:z70.uuid(),voiceProfile:VoiceProfileRefSchema.nullable(),referenceId:z70.uuid().nullable(),comparisonId:z70.uuid().nullable(),comparisonVersion:z70.int().nonnegative(),comparisonFingerprint:sha10.nullable(),identityResult:z70.enum(["MATCH","DIFFERENT","UNDETERMINED"]).nullable(),current:z70.boolean(),executionClass:z70.enum(["LIVE","TEST_ONLY"]).nullable(),reasons:z70.array(VoiceConsistencyReasonSchema).max(9)});var VoiceExpectationEvidenceSchema=VoiceExpectationSchema.extend({current:z70.boolean(),executionClass:z70.enum(["LIVE","TEST_ONLY"]).nullable(),reasons:z70.array(VoiceConsistencyReasonSchema).max(9)});var ProductionVoiceEvidenceSchema=z70.strictObject({expectations:z70.array(VoiceExpectationEvidenceSchema).max(16),sources:z70.array(VoiceSourceEvidenceSchema).max(65)});import{z as z71}from"zod";var sha11=z71.string().regex(/^[0-9a-f]{64}$/);var CompositionFindingLocalitySchema=z71.strictObject({schemaVersion:z71.literal(1),sourceKind:z71.literal("CODE"),role:z71.enum(["PRIMARY_VISUAL","VISUAL_LAYER"]),compositionId:z71.uuid(),compositionVersionId:z71.uuid(),compositionVersion:z71.int().positive(),compositionFingerprint:sha11,renderId:z71.uuid(),renderManifestFingerprint:sha11,artifactId:z71.uuid(),representationId:z71.uuid(),checksumSha256:sha11,clipOrdinal:z71.int().min(1).max(200).nullable(),visualLayerId:z71.uuid().nullable(),sourceInFrame:z71.int().min(0).max(359),sourceOutFrame:z71.int().min(1).max(360),mapping:z71.literal("INTERSECTING_NATIVE_30FPS_FRAME_CELLS")}).superRefine((v,ctx)=>{if(v.sourceOutFrame<=v.sourceInFrame||(v.role==="PRIMARY_VISUAL"?v.clipOrdinal===null||v.visualLayerId!==null:v.visualLayerId===null||v.clipOrdinal!==null))ctx.addIssue({code:"custom",message:"CODE locality requires an exact occurrence and advancing local frame interval"})});import{z as z72}from"zod";var CanonicalFactSchema=z72.strictObject({key:z72.string().regex(/^[A-Z][A-Z0-9_]{1,59}$/),value:z72.string().trim().min(1).max(300),sourceArtifactId:ArtifactIdSchema,evidence:z72.discriminatedUnion("kind",[z72.strictObject({kind:z72.literal("JSON_POINTER"),pointer:z72.string().startsWith("/").max(200)}),z72.strictObject({kind:z72.literal("EXACT_TEXT_LINE")})])});var BriefContentSchema=z72.strictObject({objective:z72.string().trim().min(1).max(1e3),productPresentationGoal:z72.string().trim().min(1).max(1e3),audience:z72.string().trim().min(1).max(300).optional(),styleTone:z72.string().trim().min(1).max(300).optional(),callToAction:z72.string().trim().min(1).max(300).optional(),targetDurationSeconds:z72.int().min(30).max(60),aspectRatio:z72.enum(["16:9","9:16"]),outputProfile:DeliveryOutputProfileSchema,canonicalFacts:z72.array(CanonicalFactSchema).max(32).default([])});var AcceptBriefRequestSchema=z72.strictObject({tenantId:TenantIdSchema,expectedProductionRevision:z72.int().positive(),revisionReason:z72.string().trim().min(1).max(1e3).optional(),sourceArtifactIds:z72.array(ArtifactIdSchema).max(20).default([]),content:BriefContentSchema});var BriefSourceReferenceSchema=z72.strictObject({artifactId:ArtifactIdSchema,checksumSha256:z72.string().regex(/^[0-9a-f]{64}$/)});var BriefVersionSchema=z72.strictObject({id:BriefVersionIdSchema,briefId:BriefIdSchema,tenantId:TenantIdSchema,projectId:ProjectIdSchema,productionId:ProductionIdSchema,version:z72.int().positive(),content:BriefContentSchema,sources:z72.array(BriefSourceReferenceSchema).min(1).max(20),createdByPrincipalId:PrincipalIdSchema,createdAt:z72.iso.datetime({offset:true})});var AcceptBriefResultSchema=z72.discriminatedUnion("semanticStatus",[z72.strictObject({semanticStatus:z72.literal("SUCCESS"),briefVersion:BriefVersionSchema,productionRevision:z72.int().positive(),activeBriefVersion:z72.int().positive()}),z72.strictObject({semanticStatus:z72.literal("NEEDS_INPUT"),missingFacts:z72.array(z72.enum(["PRODUCT_INFORMATION_SOURCE","PRODUCT_NAME"])).min(1)})]);import{z as z73}from"zod";var StoryFactKeySchema=z73.string().regex(/^[A-Z][A-Z0-9_]{1,59}$/);var StoryFactClaimSchema=z73.strictObject({key:StoryFactKeySchema,value:z73.string().trim().min(1).max(300)});var StoryBeatSchema=z73.strictObject({summary:z73.string().trim().min(1).max(600),sceneRequirements:z73.array(z73.string().trim().min(1).max(300)).max(8).default([])});var StoryContentSchema=z73.strictObject({narrativeIntent:z73.string().trim().min(1).max(2e3),beats:z73.array(StoryBeatSchema).min(1).max(24),factualClaims:z73.array(StoryFactClaimSchema).max(32).default([])});var AcceptStoryRequestSchema=z73.strictObject({tenantId:TenantIdSchema,expectedProductionRevision:z73.int().positive(),expectedBriefVersion:z73.int().positive(),revisionReason:z73.string().trim().min(1).max(1e3).optional(),idempotencyKey:z73.string().trim().min(1).max(200),content:StoryContentSchema});var StoryVersionSchema=z73.strictObject({id:StoryVersionIdSchema,storyId:StoryIdSchema,tenantId:TenantIdSchema,projectId:ProjectIdSchema,productionId:ProductionIdSchema,version:z73.int().positive(),briefVersionId:BriefVersionIdSchema,briefVersion:z73.int().positive(),content:StoryContentSchema,createdByPrincipalId:PrincipalIdSchema,createdAt:z73.iso.datetime({offset:true})});var AcceptStoryResultSchema=z73.discriminatedUnion("semanticStatus",[z73.strictObject({semanticStatus:z73.literal("SUCCESS"),storyVersion:StoryVersionSchema,productionRevision:z73.int().positive(),activeStoryVersion:z73.int().positive()}),z73.strictObject({semanticStatus:z73.literal("NEEDS_INPUT"),missingPrerequisites:z73.array(z73.literal("ACTIVE_BRIEF")).min(1)})]);import{z as z74}from"zod";var ConsistencyFamilySchema=z74.enum(["PRODUCT_IDENTITY","CHARACTER_IDENTITY","WARDROBE","LOCATION","BOUNDARY_CONTINUITY","STYLE","VOICE_IDENTITY"]);var ConsistencyEnforcementSchema=z74.enum(["LOCKED","REQUIRED","PREFERRED","FREE"]);var ConsistencyMasterReferenceSchema=z74.strictObject({artifactId:ArtifactIdSchema,representationId:ArtifactRepresentationIdSchema,checksumSha256:z74.string().regex(/^[0-9a-f]{64}$/),artifactChecksumSha256:z74.string().regex(/^[0-9a-f]{64}$/),contentType:z74.enum(["image/png","image/jpeg","image/webp","audio/wav"])});var Fact=z74.strictObject({dimension:z74.string().regex(/^[A-Z][A-Z0-9_]{0,63}$/),value:z74.string().trim().min(1).max(1e3)});var ConsistencySubjectSchema=z74.strictObject({id:z74.uuid(),kind:z74.enum(["CHARACTER","VOICE"]),displayName:z74.string().trim().min(1).max(200),facts:z74.array(Fact).min(1).max(32),master:ConsistencyMasterReferenceSchema,voiceExpectation:VoiceExpectationSchema.optional()}).superRefine((s,c)=>{if(new Set(s.facts.map(f=>f.dimension)).size!==s.facts.length)c.addIssue({code:"custom",message:"Canonical subject dimensions must be unique"});if(s.kind==="VOICE"!==(s.master.contentType==="audio/wav"))c.addIssue({code:"custom",message:"Character requires an image master; Voice requires audio"});if(s.voiceExpectation&&s.kind!=="VOICE")c.addIssue({code:"custom",message:"Only Voice subjects carry a voice expectation"})});var ConsistencyRuleScopeSchema=z74.discriminatedUnion("kind",[z74.strictObject({kind:z74.literal("PROJECT")}),z74.strictObject({kind:z74.literal("PRODUCTION")}),z74.strictObject({kind:z74.literal("SCENE"),id:z74.uuid()}),z74.strictObject({kind:z74.literal("SHOT"),id:z74.uuid()}),z74.strictObject({kind:z74.literal("CONTINUITY_EDGE"),id:z74.uuid()})]);var ConsistencyRuleSchema=z74.strictObject({voiceTargets:VoiceRuleTargetsSchema.optional(),reviewScales:z74.array(ConsistencyReviewScaleSchema).min(1).max(3).refine(s=>new Set(s).size===s.length,"Review scales must be unique").optional(),continuity:ContinuityExpectationSchema.optional(),id:z74.uuid(),family:ConsistencyFamilySchema,subjectId:z74.uuid().nullable(),dimension:z74.string().regex(/^[A-Z][A-Z0-9_]{0,63}$/),scope:ConsistencyRuleScopeSchema,enforcement:ConsistencyEnforcementSchema,expected:z74.string().trim().min(1).max(1e3).nullable(),referenceMode:z74.enum(["NONE","SUBJECT_MASTER","EXACT"]),reference:ConsistencyMasterReferenceSchema.optional(),override:z74.strictObject({priorRuleId:z74.uuid(),reason:z74.string().trim().min(1).max(1e3)}).optional(),transition:z74.strictObject({edgeId:z74.uuid(),from:z74.string().trim().min(1).max(1e3),to:z74.string().trim().min(1).max(1e3),reason:z74.string().trim().min(1).max(1e3)}).optional()}).superRefine((r,c)=>{const invalid=message=>c.addIssue({code:"custom",message});if(r.continuity&&(r.enforcement==="FREE"||r.family==="VOICE_IDENTITY"))invalid("FREE/Voice rules cannot create visual state/time obligations");if(r.family==="VOICE_IDENTITY"&&r.enforcement!=="FREE"&&(!r.voiceTargets||r.referenceMode!=="SUBJECT_MASTER"||r.reviewScales?.length!==1||r.reviewScales[0]!=="PRODUCTION"))invalid("Active Voice identity requires explicit audio targets, subject reference and full-production review");if(r.voiceTargets&&(r.family!=="VOICE_IDENTITY"||r.enforcement==="FREE"))invalid("Only active Voice rules select audio targets");if(r.enforcement==="FREE"!==(r.expected===null))invalid("FREE has no expected obligation; other enforcement requires an expectation");if(r.enforcement==="FREE"&&r.referenceMode!=="NONE")invalid("FREE cannot require reference conditioning");if(r.referenceMode==="EXACT"!==(r.reference!==void 0))invalid("Only EXACT reference mode carries an exact reference");if(r.referenceMode==="SUBJECT_MASTER"&&!r.subjectId)invalid("SUBJECT_MASTER requires an exact canonical subject");if(["CHARACTER_IDENTITY","WARDROBE","VOICE_IDENTITY"].includes(r.family)&&!r.subjectId)invalid("Character, Wardrobe and Voice obligations require an exact subject");if(r.family==="CHARACTER_IDENTITY"&&["LOCKED","REQUIRED"].includes(r.enforcement)&&r.referenceMode==="NONE")invalid("Mandatory Character identity requires concrete identity evidence");if(r.transition&&(r.family!=="WARDROBE"||r.transition.to!==r.expected||!r.override))invalid("A planned Wardrobe transition must name the changed inherited rule and new expectation")});var ConsistencyProfileContentSchema=z74.strictObject({subjects:z74.array(ConsistencySubjectSchema).max(32),rules:z74.array(ConsistencyRuleSchema).max(256)}).superRefine((p,c)=>{const invalid=message=>c.addIssue({code:"custom",message});if(new Set(p.subjects.map(s=>s.id)).size!==p.subjects.length||new Set(p.rules.map(r=>r.id)).size!==p.rules.length)invalid("Consistency subjects and rules require distinct stable IDs");if(p.rules.filter(r=>r.family==="VOICE_IDENTITY"&&r.enforcement!=="FREE").length>16)invalid("Voice obligations exceed their bounded rule budget");for(const r of p.rules){const s=p.subjects.find(s2=>s2.id===r.subjectId);if(r.subjectId&&!s)invalid("Rule names an unknown canonical subject");if(r.family==="VOICE_IDENTITY"&&r.enforcement!=="FREE"&&!s?.voiceExpectation)invalid("Active Voice identity requires an exact approved voice expectation");if(s&&r.family==="VOICE_IDENTITY"!==(s.kind==="VOICE")&&["CHARACTER_IDENTITY","WARDROBE","VOICE_IDENTITY"].includes(r.family))invalid("Rule family and canonical subject kind disagree");if(r.override&&!p.rules.some(prior=>prior.id===r.override.priorRuleId))invalid("An override must name an existing inherited rule");if(r.reference&&r.family==="VOICE_IDENTITY"!==(r.reference.contentType==="audio/wav"))invalid("Visual obligations cannot use audio and Voice obligations cannot use images")}});var ConsistencyProfileScopeSchema=z74.strictObject({tenantId:TenantIdSchema,productionId:ProductionIdSchema});var ConsistencyProfileVersionQuerySchema=ConsistencyProfileScopeSchema.extend({profileId:z74.uuid()});var ConfigureConsistencyProfileSchema=ConsistencyProfileScopeSchema.extend({expectedProductionRevision:z74.int().positive(),expectedProfileVersion:z74.int().nonnegative(),content:ConsistencyProfileContentSchema,reason:z74.string().trim().min(1).max(2e3),idempotencyKey:z74.string().trim().min(1).max(200)});var ConsistencyProfileVersionSchema=ConsistencyProfileScopeSchema.extend({id:z74.uuid(),projectId:ProjectIdSchema,version:z74.int().positive(),previousVersionId:z74.uuid().nullable(),content:ConsistencyProfileContentSchema,fingerprint:z74.string().regex(/^[0-9a-f]{64}$/),reason:z74.string().trim().min(1).max(2e3),createdByPrincipalId:PrincipalIdSchema,createdAt:z74.iso.datetime({offset:true})});var ConsistencyProfileViewSchema=ConsistencyProfileScopeSchema.extend({productionRevision:z74.int().positive(),current:ConsistencyProfileVersionSchema.nullable()});var ConsistencyProfileReceiptSchema=z74.strictObject({semanticStatus:z74.literal("SUCCESS"),profile:ConsistencyProfileVersionSchema,productionRevision:z74.int().positive()});var sha12=z75.string().regex(/^[0-9a-f]{64}$/);var RoughCutReviewScopeSchema=TimelineScopeSchema.extend({renderId:z75.uuid()});var ReviewIntervalSchema=z75.strictObject({startMs:z75.int().nonnegative().max(6e4),endMs:z75.int().positive().max(6e4)}).refine(v=>v.endMs>v.startMs,"Review interval must advance");var RoughCutRequirementSchema=z75.strictObject({voiceIdentity:VoiceRequirementGateSchema.optional(),continuity:ContinuityExpectationSchema.optional(),consistencyScale:ConsistencyReviewScaleSchema.optional(),consistencyFamily:z75.enum(["PRODUCT_IDENTITY","CHARACTER_IDENTITY","WARDROBE","LOCATION","STYLE","BOUNDARY_CONTINUITY","VOICE_IDENTITY"]).optional(),consistencySubject:ConsistencySubjectSchema.optional(),consistencyReference:ConsistencyMasterReferenceSchema.optional(),key:z75.string().min(1).max(220),dimension:z75.enum(["PRODUCT_PRESENTATION","CANONICAL_FACT","NARRATIVE","PACING","REPETITION","STYLE","TECHNICAL","TRANSITION"]),expected:z75.string().min(1).max(4e3),enforcement:z75.enum(["LOCKED","REQUIRED","PREFERRED"]),scope:z75.enum(["PRODUCTION","TRANSITION"]),interval:ReviewIntervalSchema,shotIds:z75.array(z75.uuid()).min(1).max(200)});var RoughCutObservationSchema=z75.strictObject({listeningEvidenceIds:ListeningEvidenceIdsSchema.optional(),continuitySamples:ContinuitySamplesSchema.optional(),temporalEvidenceIds:TemporalEvidenceIdsSchema.optional(),key:z75.string().min(1).max(220),status:z75.enum(["SATISFIED","VIOLATED","NOT_OBSERVABLE","NOT_APPLICABLE"]),confidence:z75.enum(["CLEAR","UNCERTAIN"]),observed:z75.string().trim().min(1).max(1800),interval:ReviewIntervalSchema,location:z75.strictObject({interval:ReviewIntervalSchema,shotIds:z75.array(z75.uuid()).min(1).max(200)}).optional()});var RoughCutInspectionSchema=z75.strictObject({actor:z75.enum(["HUMAN","EXTERNAL_AGENT"]),method:z75.literal("FULL_TEMPORAL_INSPECTION"),coverage:z75.array(ReviewIntervalSchema).min(1).max(200)});var RoughCutReviewBasisSchema=z75.strictObject({voiceEvidence:ProductionVoiceEvidenceSchema.optional(),consistencyRequirements:z75.array(RoughCutRequirementSchema).max(256).optional(),artifactId:z75.uuid(),representationId:z75.uuid(),checksumSha256:sha12,manifestFingerprint:sha12,manifest:RoughCutManifestReaderSchema,brief:BriefVersionSchema,story:StoryVersionSchema});var RecordRoughCutReviewSchema=RoughCutReviewScopeSchema.extend({listeningEvidence:ListeningEvidenceSetSchema.optional(),artifactId:z75.uuid(),representationId:z75.uuid(),checksumSha256:sha12,basisFingerprint:sha12,expectedProductionRevision:z75.int().positive(),expectedReviewVersion:z75.int().nonnegative(),idempotencyKey:z75.string().trim().min(1).max(200),inspection:RoughCutInspectionSchema,observations:z75.array(RoughCutObservationSchema).min(1).max(300),summary:z75.string().trim().min(1).max(2500)});var RoughCutReviewRecordSchema=RoughCutReviewScopeSchema.extend({listeningEvidence:ListeningEvidenceSetSchema.optional(),id:z75.uuid(),projectId:ProjectIdSchema,version:z75.int().positive(),kind:z75.literal("PRODUCTION_REVIEW_2"),lifecycle:z75.literal("COMPLETED"),evaluatorVersion:z75.literal("production-review-v1"),basis:RoughCutReviewBasisSchema,basisFingerprint:sha12,executionClass:z75.enum(["LIVE","TEST_ONLY"]),technical:RoughCutTechnicalSchema,durationMs:z75.int().min(3e4).max(6e4),requirements:z75.array(RoughCutRequirementSchema).min(1).max(300),inspection:RoughCutInspectionSchema,observations:z75.array(RoughCutObservationSchema).min(1).max(300),result:z75.enum(["PASS","WARNING","FAIL"]),blockingKeys:z75.array(z75.string()).max(300),warningKeys:z75.array(z75.string()).max(300),summary:z75.string().min(1).max(2500),createdByPrincipalId:PrincipalIdSchema,createdAt:z75.iso.datetime({offset:true})});var RoughCutReviewTargetSchema=RoughCutReviewScopeSchema.extend({temporalEvidence:z75.array(TemporalEvidenceReferenceSchema).max(8).optional(),projectId:ProjectIdSchema,productionRevision:z75.int().positive(),productionRunnable:z75.boolean(),executionClass:z75.enum(["LIVE","TEST_ONLY"]),freshness:z75.enum(["CURRENT_BASIS","STALE_BASIS"]),staleReasons:z75.array(z75.string()).max(18),inspectable:z75.boolean(),durationMs:z75.int().min(3e4).max(6e4),basis:RoughCutReviewBasisSchema,basisFingerprint:sha12,technical:RoughCutTechnicalSchema,requirements:z75.array(RoughCutRequirementSchema).min(1).max(300),latestReview:RoughCutReviewRecordSchema.nullable(),reviewVersion:z75.int().nonnegative(),finalReadyVersion:z75.int().nonnegative()});var RoughCutFindingSchema=RoughCutReviewScopeSchema.extend({compositionLocality:z75.array(CompositionFindingLocalitySchema).min(1).max(208).optional(),id:z75.uuid(),projectId:ProjectIdSchema,reviewId:z75.uuid(),reviewVersion:z75.int().positive(),basisFingerprint:sha12,artifactId:z75.uuid(),timelineVersionId:z75.uuid(),requirement:RoughCutRequirementSchema,observation:RoughCutObservationSchema,blocking:z75.boolean(),severity:z75.enum(["BLOCKING","WARNING"]),remediation:z75.enum(["REVISE_PRODUCTION","REVISE_TRANSITION","CORRECT_CANONICAL_CONTRADICTION"]),affectedScope:z75.strictObject({kind:z75.enum(["PRODUCTION","SHOT","TRANSITION","TIMELINE_REGION"]),interval:ReviewIntervalSchema,shotIds:z75.array(z75.uuid()).min(1).max(200)}),initialLifecycle:z75.literal("OPEN"),createdAt:z75.iso.datetime({offset:true})});var RoughCutFindingViewSchema=RoughCutFindingSchema.extend({lifecycle:z75.enum(["OPEN","REMEDIATION_PLANNED","RESOLVED","WAIVED","SUPERSEDED"]),proofReviewId:z75.uuid().nullable(),proofDecisionId:z75.uuid().nullable()});var RoughCutReviewQuerySchema=RoughCutReviewScopeSchema.extend({limit:QueryLimitSchema,next:ContinuationSchema.optional()});var RoughCutReviewPageSchema=z75.strictObject({items:z75.array(RoughCutReviewRecordSchema),page:QueryPageInfoSchema});var RoughCutFindingQuerySchema=TimelineScopeSchema.extend({renderId:z75.uuid().optional(),limit:QueryLimitSchema,next:ContinuationSchema.optional()});var RoughCutFindingGetSchema=TimelineScopeSchema.extend({findingId:z75.uuid()});var RoughCutFindingPageSchema=z75.strictObject({items:z75.array(RoughCutFindingViewSchema),page:QueryPageInfoSchema});var RoughCutReviewReceiptSchema=z75.strictObject({semanticStatus:z75.literal("SUCCESS"),review:RoughCutReviewRecordSchema,findingIds:z75.array(z75.uuid()).max(300),productionRevision:z75.int().positive()});var ReviewEvidenceKeySchema=z76.string().regex(/^[a-z][a-z0-9_-]{0,39}$/);var ReviewEvidenceMediaSchema=z76.strictObject({artifactId:z76.uuid(),representationId:z76.uuid(),checksumSha256:z76.string().regex(/^[0-9a-f]{64}$/)});var common={id:ReviewEvidenceKeySchema,label:z76.string().trim().min(1).max(200),producer:z76.enum(["EXTERNAL_AGENT_HOST","HUMAN","VLM"]),media:ReviewEvidenceMediaSchema};var ReviewIntelligenceEvidenceSchema=z76.discriminatedUnion("kind",[z76.strictObject({...common,kind:z76.literal("METADATA")}),z76.strictObject({...common,kind:z76.literal("IMAGE_PIXELS")}),z76.strictObject({...common,kind:z76.literal("REGISTERED_TEMPORAL_FRAMES"),reference:TemporalEvidenceReferenceSchema}),z76.strictObject({...common,kind:z76.literal("VIDEO_PLAYBACK"),coverage:z76.array(ReviewIntervalSchema).min(1).max(200)}),z76.strictObject({...common,kind:z76.literal("AUDIO_LISTENING"),coverage:z76.array(ReviewIntervalSchema).min(1).max(200)}),z76.strictObject({...common,kind:z76.literal("VIDEO_WITH_AUDIO_PLAYBACK"),coverage:z76.array(ReviewIntervalSchema).min(1).max(200)}),z76.strictObject({...common,kind:z76.literal("VIDEO_FRAMES"),timestampsMs:z76.array(z76.number().nonnegative().max(6e4)).min(1).max(64)})]);import{z as z77}from"zod";var whisperCppRecognitionProfile=Object.freeze({id:"WHISPER_CPP_TINY_EN_Q5_1_PCM16K_V1",sourceRevision:"2eeeba56e9edd762b4b38467bab96c2517163158",modelSha256:"c77c5766f1cef09b6b7d47f21b546cbddd4157886b3b5d6d4f709e91e66c7c2b",language:"en",sampleRateHz:16e3,maxDurationMs:6e4});var LocalWhisperIdentitySchema=z77.strictObject({profileId:z77.literal(whisperCppRecognitionProfile.id),binarySha256:LocalDigestSchema,modelSha256:z77.literal(whisperCppRecognitionProfile.modelSha256)});var LocalWhisperToolSelectionSchema=z77.strictObject({binaryPath:z77.string().min(1).max(4096),binarySha256:LocalDigestSchema,modelPath:z77.string().min(1).max(4096)});function canonicalLocalJson(value2){if(value2===null||typeof value2==="string"||typeof value2==="boolean")return JSON.stringify(value2);if(typeof value2==="number"&&Number.isFinite(value2))return JSON.stringify(value2);if(Array.isArray(value2))return"["+value2.map(canonicalLocalJson).join(",")+"]";if(typeof value2==="object")return"{"+Object.entries(value2).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 MAX_SHOT_REVIEW_REQUIREMENTS=2200;import{z as z78}from"zod";var ObservationScopeSchema=z78.strictObject({tenantId:z78.uuid(),productionId:z78.uuid()});var audioSourceRequest=z78.strictObject({kind:z78.literal("AUDIO"),media:ReviewEvidenceMediaSchema,versionId:z78.uuid(),purpose:z78.enum(["VOICEOVER","MUSIC"])});var ObservationSourceRequestSchema=z78.discriminatedUnion("kind",[audioSourceRequest,z78.strictObject({kind:z78.literal("VIDEO"),media:ReviewEvidenceMediaSchema})]);var ObservationStartSchema=ObservationScopeSchema.extend({expectedProductionRevision:z78.int().positive(),idempotencyKey:z78.string().min(1).max(200),source:ObservationSourceRequestSchema,mode:ObservationModeSchema,selection:ProviderSelectionSchema,expectedModelProfileVersion:z78.int().positive(),parameters:ObservationParametersSchema.default({})}).refine(q=>q.mode==="TRANSCRIPTION"||q.mode==="AUDIO"===(q.source.kind==="AUDIO"),{message:"Observation input/mode mismatch"});var ObservationGetSchema=ObservationScopeSchema.extend({observationId:z78.uuid()});var ObservationBindingSchema=z78.strictObject({tenantId:z78.uuid(),connectionId:z78.uuid(),connectionVersion:z78.int().positive(),credentialRef:z78.string(),credentialVersion:z78.int().positive(),profile:ObservationProfileSchema,matrix:ModelCapabilityMatrixSchema.optional(),executionClass:z78.enum(["LIVE","TEST_ONLY"])}).refine(v=>!v.profile.modes.some(m=>m==="TRANSCRIPTION")||!!v.matrix,{message:"ASR requires its frozen capability matrix"});var ObservationSourceSchema=ReviewEvidenceMediaSchema.extend({tenantId:z78.uuid(),projectId:z78.uuid(),productionId:z78.uuid(),byteSize:z78.int().positive().max(12582912),durationMs:z78.number().positive().max(6e4),frameRate:z78.number().positive().max(60).optional(),executionClass:z78.enum(["LIVE","TEST_ONLY"])});var json=z78.record(z78.string(),z78.unknown());var ObservationResultSchema=z78.strictObject({schemaVersion:z78.int().positive(),advisory:z78.literal(true),producer:z78.enum(["VLM","ASR"]).optional(),source:ObservationSourceSchema,input:json,provider:json,observedAt:z78.iso.datetime(),report:json,transcript:TranscriptSchema.optional(),evidence:ReviewIntelligenceEvidenceSchema.optional(),limitations:z78.array(z78.string().max(200)).max(20)}).refine(v=>v.producer==="ASR"===!!v.transcript&&!(v.producer==="ASR"&&v.evidence),{message:"ASR transcript cannot provide listening or visual Review evidence"}).refine(v=>new TextEncoder().encode(JSON.stringify(v)).length<=131072,{message:"Observation report too large"}).refine(v=>v.transcript?.timing!=="PROVIDER_REPORTED"||v.provider.protocol==="OPENAI_WHISPER_TRANSCRIPTION_V1"&&[...v.transcript.words,...v.transcript.segments].every(item=>item.endMs<=v.source.durationMs),{message:"Transcript timing requires the exact supported protocol and media duration"});var ObservationAdmissionSchema=z78.strictObject({semanticStatus:z78.literal("ACCEPTED"),observationId:z78.uuid(),runtimeJobId:z78.uuid(),productionRevision:z78.int().positive(),executionClass:z78.enum(["LIVE","TEST_ONLY"])});var ObservationViewSchema=ObservationScopeSchema.extend({observationId:z78.uuid(),runtimeJobId:z78.uuid(),request:ObservationStartSchema,profile:ObservationProfileSchema,matrix:ModelCapabilityMatrixSchema.optional(),parameters:ObservationParametersSchema,executionClass:z78.enum(["LIVE","TEST_ONLY"]),runtimeStatus:z78.enum(["PENDING","READY","RUNNING","WAITING","SUCCEEDED","FAILED","CANCELLED","SUPERSEDED"]),providerStatus:z78.enum(["NOT_SUBMITTED","SUBMITTING","UNKNOWN","SUCCEEDED","REJECTED"]),cancellationRequested:z78.boolean(),failure:z78.strictObject({classification:z78.string().min(1).max(100),summary:z78.string().min(1).max(1e3)}).nullable(),result:ObservationResultSchema.nullable(),createdAt:z78.iso.datetime()});var ObservationOptionsSchema=ObservationScopeSchema.extend({options:z78.array(z78.strictObject({selection:ProviderSelectionSchema,profile:ObservationProfileSchema,matrix:ModelCapabilityMatrixSchema.optional(),connectionLabel:z78.string(),connectionVersion:z78.int().positive()})).max(100),possiblyTruncated:z78.boolean()});var LocalObservationStartSchema=ObservationScopeSchema.extend({expectedProductionRevision:ObservationStartSchema.shape.expectedProductionRevision,idempotencyKey:ObservationStartSchema.shape.idempotencyKey,source:audioSourceRequest,mode:z78.literal("TRANSCRIPTION"),deviceExecution:z78.strictObject({deviceId:z78.uuid().optional()})});var localObservationExecution=z78.strictObject({target:z78.literal("TENANT_DEVICE"),deviceId:z78.uuid(),identity:LocalWhisperIdentitySchema});var LocalObservationBindingSchema=localObservationExecution.extend({tenantId:z78.uuid(),executionClass:z78.literal("LIVE"),source:ObservationSourceSchema});var LocalObservationAdmissionSchema=ObservationAdmissionSchema.extend({executionClass:z78.literal("LIVE"),deviceExecution:localObservationExecution});var LocalObservationResultSchema=z78.strictObject({schemaVersion:z78.literal(1),advisory:z78.literal(true),producer:z78.literal("ASR"),source:ObservationSourceSchema,deviceExecution:localObservationExecution,observedAt:z78.iso.datetime(),transcript:TranscriptSchema.options[0],inputPcmSha256:z78.string().regex(/^[0-9a-f]{64}$/),inputPcmByteSize:z78.int().min(44).max(1920044)}).refine(v=>new TextEncoder().encode(JSON.stringify(v)).length<=131072,{message:"Observation report too large"});var LocalObservationViewSchema=ObservationViewSchema.omit({profile:true,matrix:true,parameters:true,providerStatus:true}).extend({request:LocalObservationStartSchema,executionClass:z78.literal("LIVE"),deviceExecution:localObservationExecution,result:LocalObservationResultSchema.nullable()});var qwenAsrModelId="qwen3-asr-flash-2026-02-10";var QwenAsrDeviceQuoteInputSchema=ObservationScopeSchema.extend({expectedProductionRevision:ObservationStartSchema.shape.expectedProductionRevision,idempotencyKey:ObservationStartSchema.shape.idempotencyKey,source:audioSourceRequest,mode:z78.literal("TRANSCRIPTION"),selection:ProviderSelectionSchema.extend({modelProfileId:z78.literal(qwenAsrModelId)}),expectedModelProfileVersion:z78.literal(1),parameters:ObservationParametersSchema.default({}),deviceId:z78.uuid()});var QwenAsrCostQuoteSchema=z78.strictObject({protocol:z78.literal("NVS_QWEN_ASR_COST_QUOTE_V1"),currency:z78.literal("USD"),ruleId:z78.string().min(1).max(100),sourceUrl:z78.url().max(2048),selection:QwenAsrDeviceQuoteInputSchema.shape.selection,connectionVersion:z78.int().positive(),modelProfileVersion:z78.literal(1),deviceId:z78.uuid(),intentFingerprint:z78.string().regex(/^[0-9a-f]{64}$/),inputDurationMs:z78.number().positive().max(6e4),reservedSeconds:z78.int().min(1).max(60),upperBoundMicrosPerSecond:z78.int().positive().max(1e6),upperBoundMicros:z78.int().positive().max(6e7),validUntil:z78.iso.datetime()});var QwenAsrDeviceStartSchema=QwenAsrDeviceQuoteInputSchema.extend({approvedQuote:QwenAsrCostQuoteSchema});var qwenAsrDeviceExecution=z78.strictObject({target:z78.literal("TENANT_EXTERNAL_PROVIDER"),deviceId:z78.uuid()});var QwenAsrDeviceAdmissionSchema=ObservationAdmissionSchema.extend({executionClass:z78.literal("LIVE"),deviceExecution:qwenAsrDeviceExecution});var qwenAsrTokenCount=z78.int().min(0).max(1e7).optional();var QwenAsrDeviceResultSchema=ObservationResultSchema.safeExtend({producer:z78.literal("ASR"),transcript:TranscriptSchema.options[0],input:z78.strictObject({kind:z78.literal("ORIGINAL_PCM_WAV_TRANSCRIPTION"),checksumSha256:ObservationSourceSchema.shape.checksumSha256,byteSize:ObservationSourceSchema.shape.byteSize,timeScaleFactor:z78.literal(1)}),provider:z78.strictObject({protocol:z78.literal("QWEN_ASR_V1"),requestedModel:z78.literal(qwenAsrModelId),model:z78.literal(qwenAsrModelId),requestId:z78.string().regex(/^[A-Za-z0-9_.:-]{1,500}$/),usage:z78.strictObject({seconds:z78.int().min(0).max(60).optional(),prompt_tokens:qwenAsrTokenCount,completion_tokens:qwenAsrTokenCount,total_tokens:qwenAsrTokenCount})}),report:z78.strictObject({task:z78.literal("SPEECH_RECOGNITION")})});var QwenAsrDeviceViewSchema=ObservationViewSchema.extend({request:QwenAsrDeviceQuoteInputSchema,executionClass:z78.literal("LIVE"),deviceExecution:qwenAsrDeviceExecution,result:QwenAsrDeviceResultSchema.nullable()});var ProductionGuidanceSchema=z78.strictObject({version:z78.enum(["NVS_PRODUCTION_GUIDANCE_V1","NVS_PRODUCTION_GUIDANCE_V2"]),instructions:z78.string().min(1).max(16e3)});var ProductionGuidanceContextSchema=ObservationScopeSchema.extend({projectId:z78.uuid(),revision:z78.int().positive(),guidance:ProductionGuidanceSchema});import{z as z86}from"zod";import{z as z80}from"zod";import{z as z79}from"zod";var Fingerprint3=z79.string().regex(/^[0-9a-f]{64}$/);var VideoReviewScopeSchema=z79.strictObject({tenantId:TenantIdSchema,productionId:ProductionIdSchema,generationId:z79.uuid()});var VideoReviewRequirementSchema=z79.strictObject({intentPath:z79.string().min(1).max(220).optional(),continuity:ContinuityExpectationSchema.optional(),interval:z79.strictObject({startMs:z79.int().nonnegative().max(6e4),endMs:z79.int().positive().max(6e4)}).refine(v=>v.endMs>v.startMs,"Requirement interval must advance").optional(),key:z79.string().min(1).max(220),family:z79.enum(["PRODUCT_IDENTITY","CHARACTER_IDENTITY","WARDROBE","LOCATION","STYLE","SHOT_INTENT","BOUNDARY_CONTINUITY","SOUND"]),expected:z79.string().min(1).max(2500),enforcement:z79.enum(["LOCKED","REQUIRED","PREFERRED"]),evidenceWindow:z79.enum(["WHOLE_VIDEO","START","END","TEMPORAL"])});var VideoObservationSchema=z79.strictObject({listeningEvidenceIds:ListeningEvidenceIdsSchema.optional(),continuitySamples:ContinuitySamplesSchema.optional(),temporalEvidenceIds:TemporalEvidenceIdsSchema.optional(),key:z79.string().min(1).max(220),status:z79.enum(["SATISFIED","VIOLATED","NOT_OBSERVABLE","NOT_APPLICABLE"]),confidence:z79.enum(["CLEAR","UNCERTAIN"]),observed:z79.string().trim().min(1).max(1800),interval:z79.strictObject({startMs:z79.int().nonnegative(),endMs:z79.int().positive()}).refine(v=>v.endMs>v.startMs,"Observation interval must advance").optional()});var RecordVideoReviewSchema=VideoReviewScopeSchema.extend({listeningEvidence:ListeningEvidenceSetSchema.optional(),candidateId:z79.uuid(),representationId:ArtifactRepresentationIdSchema,checksumSha256:Fingerprint3,expectedReviewVersion:z79.int().nonnegative(),idempotencyKey:z79.string().trim().min(1).max(200),observations:z79.array(VideoObservationSchema).min(1).max(MAX_SHOT_REVIEW_REQUIREMENTS),summary:z79.string().trim().min(1).max(2500)});var VideoReviewRecordSchema=z79.strictObject({listeningEvidence:ListeningEvidenceSetSchema.optional(),id:z79.uuid(),tenantId:TenantIdSchema,projectId:ProjectIdSchema,productionId:ProductionIdSchema,generationId:z79.uuid(),candidateId:z79.uuid(),artifactId:ArtifactIdSchema,representationId:ArtifactRepresentationIdSchema,checksumSha256:Fingerprint3,shotId:ShotIdSchema,version:z79.int().positive(),preparationId:z79.uuid(),contractId:z79.uuid(),contractFingerprint:Fingerprint3,executionClass:z79.enum(["LIVE","TEST_ONLY"]),kind:z79.literal("SHOT_REVIEW_1"),lifecycle:z79.literal("COMPLETED"),evaluatorVersion:z79.literal("shot-review-v1"),source:z79.literal("EXPLICIT_MEDIA_INSPECTION"),technical:VideoTechnicalMetadataSchema,requirements:z79.array(VideoReviewRequirementSchema).min(1).max(MAX_SHOT_REVIEW_REQUIREMENTS),observations:z79.array(VideoObservationSchema).min(1).max(MAX_SHOT_REVIEW_REQUIREMENTS),result:z79.enum(["PASS","WARNING","FAIL"]),blockingKeys:z79.array(z79.string()).max(MAX_SHOT_REVIEW_REQUIREMENTS),warningKeys:z79.array(z79.string()).max(MAX_SHOT_REVIEW_REQUIREMENTS),summary:z79.string().min(1).max(2500),createdByPrincipalId:PrincipalIdSchema,createdAt:z79.iso.datetime({offset:true})});var DecideVideoShotSchema=VideoReviewScopeSchema.extend({candidateId:z79.uuid(),reviewId:z79.uuid(),expectedAcceptanceVersion:z79.int().nonnegative(),action:z79.enum(["ACCEPT","REJECT"]),acknowledgeWarnings:z79.boolean().default(false),reason:z79.string().trim().min(1).max(2500),idempotencyKey:z79.string().trim().min(1).max(200)});var ShotAcceptanceScopeSchema=z79.strictObject({tenantId:TenantIdSchema,productionId:ProductionIdSchema,shotId:ShotIdSchema});var RevokeShotAcceptanceSchema=ShotAcceptanceScopeSchema.extend({acceptanceId:z79.uuid(),expectedAcceptanceVersion:z79.int().positive(),reason:z79.string().trim().min(1).max(2500),idempotencyKey:z79.string().trim().min(1).max(200)});var GeneratedShotAcceptanceDecisionSchema=z79.strictObject({id:z79.uuid(),tenantId:TenantIdSchema,projectId:ProjectIdSchema,productionId:ProductionIdSchema,shotId:ShotIdSchema,acceptanceVersion:z79.int().positive(),generationId:z79.uuid(),candidateId:z79.uuid(),artifactId:ArtifactIdSchema,representationId:ArtifactRepresentationIdSchema,reviewId:z79.uuid(),action:z79.enum(["ACCEPT","REJECT","REVOKE"]),reference:AcceptedShotReferenceSchema.nullable(),previousAcceptanceId:z79.uuid().nullable(),warningKeys:z79.array(z79.string()).max(MAX_SHOT_REVIEW_REQUIREMENTS),acknowledgeWarnings:z79.boolean(),reason:z79.string().min(1).max(2500),createdByPrincipalId:PrincipalIdSchema,createdAt:z79.iso.datetime({offset:true})});var ProgrammaticShotAcceptanceDecisionSchema=z79.strictObject({sourceKind:z79.literal("PROGRAMMATIC"),id:z79.uuid(),tenantId:TenantIdSchema,projectId:ProjectIdSchema,productionId:ProductionIdSchema,shotId:ShotIdSchema,acceptanceVersion:z79.int().positive(),renderId:z79.uuid(),compositionId:z79.uuid(),compositionVersionId:z79.uuid(),artifactId:ArtifactIdSchema,representationId:ArtifactRepresentationIdSchema,reviewId:z79.uuid(),action:z79.enum(["ACCEPT","REJECT","REVOKE"]),reference:ProgrammaticAcceptedVisualSourceReferenceSchema.nullable(),previousAcceptanceId:z79.uuid().nullable(),warningKeys:z79.array(z79.string()).max(MAX_SHOT_REVIEW_REQUIREMENTS),acknowledgeWarnings:z79.boolean(),reason:z79.string().min(1).max(2500),createdByPrincipalId:PrincipalIdSchema,createdAt:z79.iso.datetime({offset:true})});var ShotAcceptanceDecisionSchema=z79.union([GeneratedShotAcceptanceDecisionSchema,ProgrammaticShotAcceptanceDecisionSchema,z79.strictObject({sourceKind:z79.literal("IMPORTED"),id:z79.uuid(),tenantId:TenantIdSchema,projectId:ProjectIdSchema,productionId:ProductionIdSchema,shotId:ShotIdSchema,acceptanceVersion:z79.int().positive(),normalizationId:z79.uuid(),sourceId:z79.uuid(),sourceVersionId:z79.uuid(),artifactId:ArtifactIdSchema,representationId:ArtifactRepresentationIdSchema,reviewId:z79.uuid(),action:z79.enum(["ACCEPT","REJECT","REVOKE"]),reference:ImportedAcceptedVisualSourceReferenceSchema.nullable(),previousAcceptanceId:z79.uuid().nullable(),warningKeys:z79.array(z79.string()).max(MAX_SHOT_REVIEW_REQUIREMENTS),acknowledgeWarnings:z79.boolean(),reason:z79.string().min(1).max(2500),createdByPrincipalId:PrincipalIdSchema,createdAt:z79.iso.datetime({offset:true})})]);var VideoReviewTargetSchema=VideoReviewScopeSchema.extend({temporalEvidence:z79.array(TemporalEvidenceReferenceSchema).max(8).optional(),projectId:ProjectIdSchema,shotId:ShotIdSchema,preparationId:z79.uuid(),contractId:z79.uuid(),contractFingerprint:Fingerprint3,executionClass:z79.enum(["LIVE","TEST_ONLY"]),freshness:z79.enum(["CURRENT_BASIS","STALE_BASIS"]),runtimeSucceeded:z79.boolean(),productionRunnable:z79.boolean(),candidate:VideoCandidateSchema,requirements:z79.array(VideoReviewRequirementSchema).min(1).max(MAX_SHOT_REVIEW_REQUIREMENTS),latestReview:VideoReviewRecordSchema.nullable(),reviewVersion:z79.int().nonnegative(),acceptanceVersion:z79.int().nonnegative(),activeAcceptanceId:z79.uuid().nullable()});var ShotAcceptanceViewSchema=ShotAcceptanceScopeSchema.extend({acceptanceVersion:z79.int().nonnegative(),status:z79.enum(["NONE","CURRENT","STALE"]),acceptance:ShotAcceptanceDecisionSchema.nullable(),reference:AcceptedVisualSourceReferenceSchema.nullable()});var VideoReviewQuerySchema=VideoReviewScopeSchema.extend({limit:QueryLimitSchema,next:ContinuationSchema.optional()});var VideoReviewPageSchema=z79.strictObject({items:z79.array(VideoReviewRecordSchema),page:QueryPageInfoSchema});var ShotDecisionQuerySchema=ShotAcceptanceScopeSchema.extend({limit:QueryLimitSchema,next:ContinuationSchema.optional()});var ShotDecisionPageSchema=z79.strictObject({items:z79.array(ShotAcceptanceDecisionSchema),page:QueryPageInfoSchema});var VideoReviewReceiptSchema=z79.strictObject({semanticStatus:z79.literal("SUCCESS"),review:VideoReviewRecordSchema,productionRevision:z79.int().positive()});var ShotDecisionReceiptSchema=z79.strictObject({semanticStatus:z79.literal("SUCCESS"),decision:ShotAcceptanceDecisionSchema,productionRevision:z79.int().positive()});var Fingerprint4=z80.string().regex(/^[0-9a-f]{64}$/);var ProgrammaticVideoReviewScopeSchema=z80.strictObject({tenantId:TenantIdSchema,productionId:ProductionIdSchema,renderId:z80.uuid()});var ProgrammaticReviewMediaSchema=VideoTechnicalMetadataSchema.extend({artifactId:ArtifactIdSchema,representationId:ArtifactRepresentationIdSchema,availability:z80.enum(["AVAILABLE","INVALID"])});var ProgrammaticVideoReviewRecordSchema=z80.strictObject({sourceKind:z80.literal("PROGRAMMATIC"),id:z80.uuid(),tenantId:TenantIdSchema,projectId:ProjectIdSchema,productionId:ProductionIdSchema,shotId:ShotIdSchema,renderId:z80.uuid(),compositionId:z80.uuid(),compositionVersionId:z80.uuid(),compositionVersion:z80.int().positive(),compositionFingerprint:Fingerprint4,renderManifestFingerprint:Fingerprint4,artifactId:ArtifactIdSchema,representationId:ArtifactRepresentationIdSchema,checksumSha256:Fingerprint4,version:z80.int().positive(),planVersionId:z80.uuid(),planVersion:z80.int().positive(),shotPlanningRevision:z80.int().positive(),executionClass:z80.enum(["LIVE","TEST_ONLY"]),kind:z80.literal("SHOT_REVIEW_1"),lifecycle:z80.literal("COMPLETED"),evaluatorVersion:z80.literal("shot-review-v1"),source:z80.literal("EXPLICIT_MEDIA_INSPECTION"),technical:VideoTechnicalMetadataSchema,requirements:z80.array(VideoReviewRequirementSchema).min(1).max(MAX_SHOT_REVIEW_REQUIREMENTS),observations:z80.array(VideoObservationSchema).min(1).max(MAX_SHOT_REVIEW_REQUIREMENTS),result:z80.enum(["PASS","WARNING","FAIL"]),blockingKeys:z80.array(z80.string()).max(MAX_SHOT_REVIEW_REQUIREMENTS),warningKeys:z80.array(z80.string()).max(MAX_SHOT_REVIEW_REQUIREMENTS),summary:z80.string().min(1).max(2500),createdByPrincipalId:PrincipalIdSchema,createdAt:z80.iso.datetime({offset:true})});var ProgrammaticVideoReviewTargetSchema=ProgrammaticVideoReviewScopeSchema.extend({sourceKind:z80.literal("PROGRAMMATIC"),temporalEvidence:z80.array(TemporalEvidenceReferenceSchema).max(8).optional(),projectId:ProjectIdSchema,shotId:ShotIdSchema,compositionId:z80.uuid(),compositionVersionId:z80.uuid(),compositionVersion:z80.int().positive(),compositionFingerprint:Fingerprint4,renderManifestFingerprint:Fingerprint4,executionClass:z80.enum(["LIVE","TEST_ONLY"]),freshness:z80.enum(["CURRENT_BASIS","STALE_BASIS"]),runtimeSucceeded:z80.boolean(),productionRunnable:z80.boolean(),media:ProgrammaticReviewMediaSchema,requirements:z80.array(VideoReviewRequirementSchema).min(1).max(MAX_SHOT_REVIEW_REQUIREMENTS),latestReview:ProgrammaticVideoReviewRecordSchema.nullable(),reviewVersion:z80.int().nonnegative(),acceptanceVersion:z80.int().nonnegative(),activeAcceptanceId:z80.uuid().nullable()});var RecordProgrammaticVideoReviewSchema=ProgrammaticVideoReviewScopeSchema.extend({representationId:ArtifactRepresentationIdSchema,checksumSha256:Fingerprint4,expectedReviewVersion:z80.int().nonnegative(),idempotencyKey:z80.string().trim().min(1).max(200),observations:z80.array(VideoObservationSchema).min(1).max(MAX_SHOT_REVIEW_REQUIREMENTS),summary:z80.string().trim().min(1).max(2500)});var DecideProgrammaticShotSchema=ProgrammaticVideoReviewScopeSchema.extend({reviewId:z80.uuid(),expectedAcceptanceVersion:z80.int().nonnegative(),action:z80.enum(["ACCEPT","REJECT"]),acknowledgeWarnings:z80.boolean().default(false),reason:z80.string().trim().min(1).max(2500),idempotencyKey:z80.string().trim().min(1).max(200)});var ProgrammaticVideoReviewQuerySchema=ProgrammaticVideoReviewScopeSchema.extend({limit:QueryLimitSchema,next:ContinuationSchema.optional()});var ProgrammaticVideoReviewPageSchema=z80.strictObject({items:z80.array(ProgrammaticVideoReviewRecordSchema),page:QueryPageInfoSchema});var ProgrammaticVideoReviewReceiptSchema=z80.strictObject({semanticStatus:z80.literal("SUCCESS"),review:ProgrammaticVideoReviewRecordSchema,productionRevision:z80.int().positive()});import{z as z84}from"zod";import{z as z82}from"zod";import{z as z81}from"zod";var Intent=z81.string().trim().min(1).max(300);var CameraIntentSchema=z81.strictObject({scale:z81.enum(["EXTREME_CLOSE_UP","CLOSE_UP","MEDIUM","WIDE","EXTREME_WIDE"]),framing:z81.enum(["CENTERED","OFF_CENTER","SYMMETRICAL","OVER_SHOULDER"]),angle:z81.enum(["EYE_LEVEL","HIGH","LOW","TOP_DOWN"]),movement:z81.enum(["STATIC","PAN","TILT","DOLLY","TRACK","ORBIT","CRANE","ZOOM"]),stability:z81.enum(["LOCKED","STABILIZED","HANDHELD"]),direction:z81.enum(["LEFT","RIGHT","UP","DOWN","FORWARD","BACKWARD","CLOCKWISE","COUNTERCLOCKWISE"]).optional(),lensIntent:z81.string().trim().min(1).max(120).optional()});var ShotTemporalBeatSchema=z81.strictObject({startSeconds:z81.number().min(0).max(30),endSeconds:z81.number().positive().max(30),action:Intent});var ShotDirectionSchema=z81.strictObject({camera:CameraIntentSchema,temporalBeats:z81.array(ShotTemporalBeatSchema).min(1).max(8),environmentIntent:Intent.optional(),lightingIntent:Intent.optional(),styleIntent:Intent.optional(),audioIntent:Intent.optional()});function checkShotDirectionTiming(direction,duration){let cursor=0;for(const beat of direction.temporalBeats){if(Math.abs(beat.startSeconds-cursor)>1e-6||beat.endSeconds<=beat.startSeconds)return false;cursor=beat.endSeconds}return Math.abs(cursor-duration)<=1e-6}var PlanningClientKeySchema=z82.string().regex(/^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/);var BoundaryRequirementSchema=z82.strictObject({attribute:z82.string().regex(/^[A-Za-z][A-Za-z0-9_.-]{0,59}$/),value:z82.string().trim().min(1).max(300)});var ShotIntentSchema=z82.strictObject({narrativePurpose:z82.string().trim().min(1).max(600),subjectAction:z82.string().trim().min(1).max(600),targetDurationSeconds:z82.number().min(.5).max(30),subjectRequirements:z82.array(z82.string().trim().min(1).max(300)).max(16).default([]),cameraComposition:z82.string().trim().min(1).max(500).optional(),factualClaims:z82.array(StoryFactClaimSchema).max(16).default([]),requiresGeneratedKeyframe:z82.boolean().default(false),sourceMediaAllowed:z82.boolean().default(false),direction:ShotDirectionSchema.optional()}).superRefine((value2,context)=>{if(value2.direction&&!checkShotDirectionTiming(value2.direction,value2.targetDurationSeconds))context.addIssue({code:"custom",path:["direction","temporalBeats"],message:"Temporal beats must be contiguous from zero and cover exactly the Shot duration"})});var ShotPlanInputSchema=z82.strictObject({clientKey:PlanningClientKeySchema,shotId:ShotIdSchema.optional(),intent:ShotIntentSchema,entryBoundary:z82.array(BoundaryRequirementSchema).max(24).default([]),exitBoundary:z82.array(BoundaryRequirementSchema).max(24).default([])});var ScenePlanInputSchema=z82.strictObject({clientKey:PlanningClientKeySchema,sceneId:SceneIdSchema.optional(),purpose:z82.string().trim().min(1).max(800),locationContext:z82.string().trim().min(1).max(300).optional(),timeContext:z82.string().trim().min(1).max(300).optional(),entryBoundary:z82.array(BoundaryRequirementSchema).max(24).default([]),exitBoundary:z82.array(BoundaryRequirementSchema).max(24).default([]),shots:z82.array(ShotPlanInputSchema).min(1).max(24)});var ContinuityRequirementSchema=z82.strictObject({mode:z82.enum(["PERSIST","TRANSITION","REESTABLISH","REVIEW"]),attribute:z82.string().regex(/^[A-Za-z][A-Za-z0-9_.-]{0,59}$/),description:z82.string().trim().min(1).max(500)});var ContinuityEdgeInputSchema=z82.strictObject({fromShotKey:PlanningClientKeySchema,toShotKey:PlanningClientKeySchema,requirements:z82.array(ContinuityRequirementSchema).min(1).max(24)});var AcceptSceneShotPlanRequestSchema=z82.strictObject({tenantId:TenantIdSchema,expectedProductionRevision:z82.int().positive(),expectedStoryVersion:z82.int().positive(),revisionReason:z82.string().trim().min(1).max(1e3).optional(),idempotencyKey:z82.string().trim().min(1).max(200),scenes:z82.array(ScenePlanInputSchema).min(1).max(12),continuityEdges:z82.array(ContinuityEdgeInputSchema).max(64).default([])});var ShotPlanEntrySchema=z82.strictObject({shotId:ShotIdSchema,clientKey:PlanningClientKeySchema,ordinal:z82.int().positive(),planningRevision:z82.int().positive(),intent:ShotIntentSchema,entryBoundary:z82.array(BoundaryRequirementSchema).max(24),exitBoundary:z82.array(BoundaryRequirementSchema).max(24)});var ScenePlanEntrySchema=z82.strictObject({sceneId:SceneIdSchema,clientKey:PlanningClientKeySchema,ordinal:z82.int().positive(),purpose:z82.string().trim().min(1).max(800),locationContext:z82.string().trim().min(1).max(300).optional(),timeContext:z82.string().trim().min(1).max(300).optional(),entryBoundary:z82.array(BoundaryRequirementSchema).max(24),exitBoundary:z82.array(BoundaryRequirementSchema).max(24),shots:z82.array(ShotPlanEntrySchema).min(1).max(24)});var ContinuityEdgeSchema=z82.strictObject({id:ContinuityEdgeIdSchema,fromShotId:ShotIdSchema,toShotId:ShotIdSchema,requirements:z82.array(ContinuityRequirementSchema).min(1).max(24)});var SceneShotPlanVersionSchema=z82.strictObject({id:SceneShotPlanVersionIdSchema,planId:SceneShotPlanIdSchema,tenantId:TenantIdSchema,projectId:ProjectIdSchema,productionId:ProductionIdSchema,version:z82.int().positive(),storyVersionId:StoryVersionIdSchema,storyVersion:z82.int().positive(),briefVersionId:BriefVersionIdSchema,briefVersion:z82.int().positive(),scenes:z82.array(ScenePlanEntrySchema).min(1).max(12),continuityEdges:z82.array(ContinuityEdgeSchema).max(64),createdByPrincipalId:PrincipalIdSchema,createdAt:z82.iso.datetime({offset:true})});var AcceptSceneShotPlanResultSchema=z82.discriminatedUnion("semanticStatus",[z82.strictObject({semanticStatus:z82.literal("SUCCESS"),planVersion:SceneShotPlanVersionSchema,productionRevision:z82.int().positive(),activeSceneShotPlanVersion:z82.int().positive()}),z82.strictObject({semanticStatus:z82.literal("NEEDS_INPUT"),missingPrerequisites:z82.array(z82.literal("ACTIVE_STORY")).min(1)})]);import{z as z83}from"zod";var WriterScopeSchema=z83.strictObject({tenantId:TenantIdSchema,projectId:ProjectIdSchema,productionId:ProductionIdSchema});var WriterBasisSchema=WriterScopeSchema.extend({productionRevision:z83.int().positive(),briefVersionId:BriefVersionIdSchema,briefVersion:z83.int().positive()});var IntentSchema=z83.string().trim().min(1).max(600);var WriterAlternativeSchema=z83.strictObject({alternativeId:z83.string().regex(/^[a-z][a-z0-9_-]{0,39}$/),title:z83.string().trim().min(1).max(120),story:StoryContentSchema,rationale:z83.strictObject({coreMessage:IntentSchema,hook:IntentSchema,audienceFit:IntentSchema,pacingIntent:IntentSchema,endingIntent:IntentSchema,tradeoffs:z83.array(IntentSchema).max(6)}),beatDurationsSeconds:z83.array(z83.int().positive().max(60)).min(1).max(24)});var WriterProposalSchema=z83.strictObject({origin:z83.strictObject({kind:z83.literal("EXTERNAL_AGENT_HOST"),label:z83.string().trim().min(1).max(100)}),unknowns:z83.array(z83.string().trim().min(1).max(300)).max(8),alternatives:z83.array(WriterAlternativeSchema).min(1).max(3)});var ValidateWriterProposalSchema=z83.strictObject({basis:WriterBasisSchema,revisionReason:AcceptStoryRequestSchema.shape.revisionReason,proposal:WriterProposalSchema});var MissingBriefSchema=z83.strictObject({semanticStatus:z83.literal("NEEDS_INPUT"),missingPrerequisites:z83.array(z83.literal("ACTIVE_BRIEF")).min(1).max(1)});var WriterBriefResultSchema=z83.discriminatedUnion("semanticStatus",[z83.strictObject({semanticStatus:z83.literal("SUCCESS"),basis:WriterBasisSchema,briefVersion:BriefVersionSchema}),MissingBriefSchema]);var WriterAcceptanceDraftSchema=z83.strictObject({alternativeId:WriterAlternativeSchema.shape.alternativeId,projectId:ProjectIdSchema,productionId:ProductionIdSchema,request:AcceptStoryRequestSchema.omit({idempotencyKey:true})});var WriterValidationResultSchema=z83.discriminatedUnion("semanticStatus",[z83.strictObject({semanticStatus:z83.literal("SUCCESS"),advisory:z83.literal(true),basis:WriterBasisSchema,proposal:WriterProposalSchema,acceptanceDrafts:z83.array(WriterAcceptanceDraftSchema).min(1).max(3),limitations:z83.array(z83.enum(["PROSE_IS_CREATIVE_INTENT_NOT_FACT_VERIFIED","PACING_IS_ADVISORY_NOT_TIMELINE_TRUTH","ACCEPTANCE_RECHECKS_CURRENT_BASIS"])).length(3)}),MissingBriefSchema]);var DirectorScopeSchema=WriterScopeSchema;var DirectorBasisSchema=WriterBasisSchema.extend({storyVersionId:StoryVersionIdSchema,storyVersion:z84.int().positive(),sceneShotPlanVersionId:SceneShotPlanVersionIdSchema.nullable(),sceneShotPlanVersion:z84.int().positive().nullable()}).refine(value2=>value2.sceneShotPlanVersionId===null===(value2.sceneShotPlanVersion===null),"Current plan ID and version must both be present or null");var Intent2=z84.string().trim().min(1).max(600);var Plan=AcceptSceneShotPlanRequestSchema.pick({scenes:true,continuityEdges:true});var DirectorAlternativeSchema=z84.strictObject({alternativeId:z84.string().regex(/^[a-z][a-z0-9_-]{0,39}$/),title:z84.string().trim().min(1).max(120),plan:Plan,rationale:z84.strictObject({storyInterpretation:Intent2,visualApproach:Intent2,pacingIntent:Intent2,tradeoffs:z84.array(Intent2).max(6)}),shotStoryBeats:z84.array(z84.strictObject({shotKey:PlanningClientKeySchema,beatOrdinals:z84.array(z84.int().positive().max(24)).min(1).max(4)})).min(1).max(48)}).refine(value2=>value2.plan.scenes.reduce((n,scene)=>n+scene.shots.length,0)<=48,"Director alternatives contain at most 48 Shots");var DirectorProposalSchema=z84.strictObject({origin:z84.strictObject({kind:z84.literal("EXTERNAL_AGENT_HOST"),label:z84.string().trim().min(1).max(100)}),unknowns:z84.array(z84.string().trim().min(1).max(300)).max(8),alternatives:z84.array(DirectorAlternativeSchema).min(1).max(3)});var ValidateDirectorProposalSchema=z84.strictObject({basis:DirectorBasisSchema,revisionReason:AcceptSceneShotPlanRequestSchema.shape.revisionReason,proposal:DirectorProposalSchema}).refine(value2=>new TextEncoder().encode(JSON.stringify(value2)).byteLength<=1024*1024,"Director validation input exceeds the 1 MiB JSON budget");var Missing=z84.strictObject({semanticStatus:z84.literal("NEEDS_INPUT"),missingPrerequisites:z84.array(z84.enum(["ACTIVE_BRIEF","ACTIVE_STORY"])).min(1).max(2)});var DirectorContextResultSchema=z84.discriminatedUnion("semanticStatus",[z84.strictObject({semanticStatus:z84.literal("SUCCESS"),basis:DirectorBasisSchema,briefVersion:BriefVersionSchema,storyVersion:StoryVersionSchema,sceneShotPlanVersion:SceneShotPlanVersionSchema.nullable(),stalePrerequisites:z84.array(z84.enum(["CURRENT_STORY","CURRENT_SCENE_SHOT_PLAN"])).min(1).max(2).optional()}),Missing]);var DirectorAcceptanceDraftSchema=z84.strictObject({alternativeId:DirectorAlternativeSchema.shape.alternativeId,projectId:DirectorScopeSchema.shape.projectId,productionId:DirectorScopeSchema.shape.productionId,request:AcceptSceneShotPlanRequestSchema.omit({idempotencyKey:true})});var DirectorValidationResultSchema=z84.discriminatedUnion("semanticStatus",[z84.strictObject({semanticStatus:z84.literal("SUCCESS"),advisory:z84.literal(true),basis:DirectorBasisSchema,proposal:DirectorProposalSchema,acceptanceDrafts:z84.array(DirectorAcceptanceDraftSchema).min(1).max(3),limitations:z84.array(z84.enum(["PROSE_IS_CREATIVE_INTENT_NOT_FACT_VERIFIED","DIRECTION_IS_INTENT_NOT_OBSERVED_MEDIA","ACCEPTANCE_RECHECKS_CURRENT_BASIS","PREPARATION_AND_GENERATION_REMAIN_SEPARATE"])).length(4)}),Missing]);import{z as z85}from"zod";var Fingerprint5=z85.string().regex(/^[0-9a-f]{64}$/);var KeyframeReviewScopeSchema=z85.strictObject({tenantId:TenantIdSchema,productionId:ProductionIdSchema,generationId:z85.uuid()});var VisualRequirementSchema=z85.strictObject({intentPath:z85.string().min(1).max(220).optional(),key:z85.string().min(1).max(200),expected:z85.string().min(1).max(2500),enforcement:z85.enum(["LOCKED","REQUIRED","PREFERRED"])});var Region=z85.strictObject({x:z85.number().min(0).max(1),y:z85.number().min(0).max(1),width:z85.number().positive().max(1),height:z85.number().positive().max(1)}).refine(r=>r.x+r.width<=1&&r.y+r.height<=1,"Evidence region must fit within the image");var KeyframeObservationSchema=z85.strictObject({key:z85.string().min(1).max(200),status:z85.enum(["SATISFIED","VIOLATED","NOT_OBSERVABLE","NOT_APPLICABLE"]),confidence:z85.enum(["CLEAR","UNCERTAIN"]),observed:z85.string().trim().min(1).max(1500),region:Region.optional()});var RecordKeyframeReviewSchema=KeyframeReviewScopeSchema.extend({candidateId:z85.uuid(),representationId:z85.uuid(),checksumSha256:Fingerprint5,expectedReviewVersion:z85.int().nonnegative(),idempotencyKey:z85.string().trim().min(1).max(200),observations:z85.array(KeyframeObservationSchema).min(1).max(MAX_SHOT_REVIEW_REQUIREMENTS),summary:z85.string().trim().min(1).max(2e3)});var KeyframeReviewRecordSchema=z85.strictObject({id:z85.uuid(),tenantId:TenantIdSchema,projectId:ProjectIdSchema,productionId:ProductionIdSchema,generationId:z85.uuid(),candidateId:z85.uuid(),artifactId:z85.uuid(),representationId:z85.uuid(),checksumSha256:Fingerprint5,shotId:ShotIdSchema,framePurpose:KeyframePurposeSchema,version:z85.int().positive(),preparationId:z85.uuid(),contractId:z85.uuid(),contractFingerprint:Fingerprint5,executionClass:z85.enum(["LIVE","TEST_ONLY"]),kind:z85.literal("KEYFRAME_REFERENCE"),lifecycle:z85.literal("COMPLETED"),evaluatorVersion:z85.literal("keyframe-reference-v1"),source:z85.literal("EXPLICIT_VISUAL_INSPECTION"),requirements:z85.array(VisualRequirementSchema).min(1).max(MAX_SHOT_REVIEW_REQUIREMENTS),observations:z85.array(KeyframeObservationSchema).min(1).max(MAX_SHOT_REVIEW_REQUIREMENTS),result:z85.enum(["PASS","WARNING","FAIL"]),blockingKeys:z85.array(z85.string()).max(MAX_SHOT_REVIEW_REQUIREMENTS),warningKeys:z85.array(z85.string()).max(MAX_SHOT_REVIEW_REQUIREMENTS),summary:z85.string().min(1).max(2e3),createdByPrincipalId:PrincipalIdSchema,createdAt:z85.iso.datetime({offset:true})});var DecideKeyframeSchema=KeyframeReviewScopeSchema.extend({candidateId:z85.uuid(),reviewId:z85.uuid(),expectedSelectionVersion:z85.int().nonnegative(),action:z85.enum(["ACCEPT","REJECT"]),acknowledgeWarnings:z85.boolean().default(false),reason:z85.string().trim().min(1).max(2e3),idempotencyKey:z85.string().trim().min(1).max(200)});var KeyframeReferenceScopeSchema=z85.strictObject({tenantId:TenantIdSchema,productionId:ProductionIdSchema,shotId:ShotIdSchema,framePurpose:KeyframePurposeSchema});var RevokeKeyframeSchema=KeyframeReferenceScopeSchema.extend({acceptanceId:z85.uuid(),expectedSelectionVersion:z85.int().positive(),reason:z85.string().trim().min(1).max(2e3),idempotencyKey:z85.string().trim().min(1).max(200)});var KeyframeDecisionRecordSchema=z85.strictObject({id:z85.uuid(),tenantId:TenantIdSchema,projectId:ProjectIdSchema,productionId:ProductionIdSchema,shotId:ShotIdSchema,framePurpose:KeyframePurposeSchema,selectionVersion:z85.int().positive(),generationId:z85.uuid(),candidateId:z85.uuid(),reviewId:z85.uuid(),action:z85.enum(["ACCEPT","REJECT","REVOKE"]),reference:AcceptedKeyframeReferenceSchema.nullable(),previousAcceptanceId:z85.uuid().nullable(),warningKeys:z85.array(z85.string()).max(MAX_SHOT_REVIEW_REQUIREMENTS),acknowledgeWarnings:z85.boolean(),reason:z85.string().min(1).max(2e3),createdByPrincipalId:PrincipalIdSchema,createdAt:z85.iso.datetime({offset:true})});var KeyframeReviewTargetSchema=KeyframeReviewScopeSchema.extend({projectId:ProjectIdSchema,shotId:ShotIdSchema,framePurpose:KeyframePurposeSchema,preparationId:z85.uuid(),contractId:z85.uuid(),contractFingerprint:Fingerprint5,executionClass:z85.enum(["LIVE","TEST_ONLY"]),freshness:z85.enum(["CURRENT_BASIS","STALE_BASIS"]),runtimeSucceeded:z85.boolean(),productionRunnable:z85.boolean(),candidate:KeyframeCandidateSchema,requirements:z85.array(VisualRequirementSchema).min(1).max(MAX_SHOT_REVIEW_REQUIREMENTS),latestReview:KeyframeReviewRecordSchema.nullable(),reviewVersion:z85.int().nonnegative(),selectionVersion:z85.int().nonnegative(),activeAcceptanceId:z85.uuid().nullable()});var KeyframeReferenceViewSchema=KeyframeReferenceScopeSchema.extend({selectionVersion:z85.int().nonnegative(),status:z85.enum(["NONE","CURRENT","STALE"]),acceptance:KeyframeDecisionRecordSchema.nullable(),reference:AcceptedKeyframeReferenceSchema.nullable()});var KeyframeReviewQuerySchema=KeyframeReviewScopeSchema.extend({limit:QueryLimitSchema,next:ContinuationSchema.optional()});var KeyframeReviewPageSchema=z85.strictObject({items:z85.array(KeyframeReviewRecordSchema),page:QueryPageInfoSchema});var KeyframeReviewReceiptSchema=z85.strictObject({semanticStatus:z85.literal("SUCCESS"),review:KeyframeReviewRecordSchema,productionRevision:z85.int().positive()});var KeyframeDecisionReceiptSchema=z85.strictObject({semanticStatus:z85.literal("SUCCESS"),decision:KeyframeDecisionRecordSchema,productionRevision:z85.int().positive()});var KeyframeDecisionQuerySchema=KeyframeReferenceScopeSchema.extend({limit:QueryLimitSchema,next:ContinuationSchema.optional()});var KeyframeDecisionPageSchema=z85.strictObject({items:z85.array(KeyframeDecisionRecordSchema),page:QueryPageInfoSchema});var KeyframeReviewSummarySchema=z85.strictObject({reviewedCandidates:z85.int().nonnegative(),unreviewedCandidates:z85.int().nonnegative(),decisionCount:z85.int().nonnegative()});var sha13=z86.string().regex(/^[0-9a-f]{64}$/);var evidenceIds=z86.array(ReviewEvidenceKeySchema).max(16);var ReviewIntelligenceTargetSchema=z86.discriminatedUnion("kind",[z86.strictObject({kind:z86.literal("IMAGE"),generationId:z86.uuid()}),z86.strictObject({kind:z86.literal("VIDEO"),generationId:z86.uuid()}),z86.strictObject({kind:z86.literal("ROUGH_CUT"),renderId:z86.uuid()}),z86.strictObject({kind:z86.literal("PROGRAMMATIC"),renderId:z86.uuid()})]);var ReviewIntelligenceContextInputSchema=z86.strictObject({scope:DirectorScopeSchema,target:ReviewIntelligenceTargetSchema});var ReviewIntelligenceBasisSchema=ReviewIntelligenceContextInputSchema.extend({contextFingerprint:sha13});var ReviewIntelligenceOwnerTargetSchema=z86.discriminatedUnion("kind",[z86.strictObject({kind:z86.literal("IMAGE"),target:KeyframeReviewTargetSchema}),z86.strictObject({kind:z86.literal("VIDEO"),target:VideoReviewTargetSchema}),z86.strictObject({kind:z86.literal("ROUGH_CUT"),target:RoughCutReviewTargetSchema}),z86.strictObject({kind:z86.literal("PROGRAMMATIC"),target:ProgrammaticVideoReviewTargetSchema})]);var review=z86.discriminatedUnion("kind",[z86.strictObject({kind:z86.literal("IMAGE"),observations:z86.array(KeyframeObservationSchema.extend({evidenceIds})).min(1).max(MAX_SHOT_REVIEW_REQUIREMENTS)}),z86.strictObject({kind:z86.literal("VIDEO"),observations:z86.array(VideoObservationSchema.extend({evidenceIds})).min(1).max(MAX_SHOT_REVIEW_REQUIREMENTS)}),z86.strictObject({kind:z86.literal("PROGRAMMATIC"),observations:z86.array(VideoObservationSchema.extend({evidenceIds})).min(1).max(MAX_SHOT_REVIEW_REQUIREMENTS)}),z86.strictObject({kind:z86.literal("ROUGH_CUT"),observations:z86.array(RoughCutObservationSchema.extend({evidenceIds})).min(1).max(300),inspection:RoughCutInspectionSchema})]);var ValidateReviewIntelligenceSchema=z86.strictObject({basis:ReviewIntelligenceBasisSchema,proposal:z86.strictObject({origin:z86.strictObject({kind:z86.literal("EXTERNAL_AGENT_HOST"),label:z86.string().trim().min(1).max(100)}),summary:z86.string().trim().min(1).max(2e3),evidence:z86.array(ReviewIntelligenceEvidenceSchema).max(256),review})}).refine(input=>new TextEncoder().encode(JSON.stringify(input)).byteLength<=1024*1024,"Review Intelligence input exceeds the 1 MiB JSON budget");var ReviewIntelligenceContextResultSchema=z86.strictObject({semanticStatus:z86.literal("SUCCESS"),advisory:z86.literal(true),basis:ReviewIntelligenceBasisSchema,productionGuidance:ProductionGuidanceSchema.optional(),ownerContext:DirectorContextResultSchema,reviewTarget:ReviewIntelligenceOwnerTargetSchema,limitations:z86.array(z86.enum(["NO_IMPLICIT_MEDIA_OR_MODEL_CALL","READS_ARE_NOT_ATOMIC_OR_RESERVED"])).length(2)});var ReviewIntelligenceRecordDraftSchema=z86.discriminatedUnion("kind",[z86.strictObject({kind:z86.literal("PROGRAMMATIC"),input:RecordProgrammaticVideoReviewSchema.omit({idempotencyKey:true})}),z86.strictObject({kind:z86.literal("IMAGE"),input:RecordKeyframeReviewSchema.omit({idempotencyKey:true})}),z86.strictObject({kind:z86.literal("VIDEO"),input:RecordVideoReviewSchema.omit({idempotencyKey:true})}),z86.strictObject({kind:z86.literal("ROUGH_CUT"),input:RecordRoughCutReviewSchema.omit({idempotencyKey:true})})]);var ReviewIntelligenceIssueSchema=z86.strictObject({requirement:z86.union([VisualRequirementSchema,VideoReviewRequirementSchema,RoughCutRequirementSchema]),observation:z86.union([KeyframeObservationSchema,VideoObservationSchema,RoughCutObservationSchema]),evidenceIds,blocking:z86.boolean(),severity:z86.enum(["BLOCKING","WARNING"]),affectedScope:z86.strictObject({kind:z86.enum(["PRODUCTION","SHOT","TRANSITION","TIMELINE_REGION"]),interval:ReviewIntervalSchema,shotIds:z86.array(z86.uuid()).min(1).max(200)}).optional()});var ReviewIntelligenceValidationResultSchema=z86.strictObject({semanticStatus:z86.literal("SUCCESS"),advisory:z86.literal(true),basis:ReviewIntelligenceBasisSchema,proposal:ValidateReviewIntelligenceSchema.shape.proposal,canonicalRulePreview:z86.strictObject({source:z86.literal("EXISTING_CANONICAL_DOMAIN_RULES"),authoritative:z86.literal(false),evaluatorVersion:z86.enum(["keyframe-reference-v1","shot-review-v1","production-review-v1"]),result:z86.enum(["PASS","WARNING","FAIL"]),blockingKeys:z86.array(z86.string()).max(MAX_SHOT_REVIEW_REQUIREMENTS),warningKeys:z86.array(z86.string()).max(MAX_SHOT_REVIEW_REQUIREMENTS)}),issueProposals:z86.array(ReviewIntelligenceIssueSchema).max(MAX_SHOT_REVIEW_REQUIREMENTS),recordDraft:ReviewIntelligenceRecordDraftSchema,limitations:z86.array(z86.enum(["EVIDENCE_DECLARATIONS_ARE_NOT_ATTESTED_PIXEL_READS","RULE_PREVIEW_IS_NOT_A_CANONICAL_REVIEW","RECORD_RECHECKS_CURRENTNESS_CAS_AND_EXECUTION_CLASS","ACCEPTANCE_REMAINS_A_SEPARATE_OWNER_DECISION"])).length(4)});import{z as z89}from"zod";import{z as z88}from"zod";import{z as z87}from"zod";var maxMediaObjectBytes=128*1024*1024;var mediaObjectTransferPath="/v1/object-transfers";var mediaBrowserReadPath=mediaObjectTransferPath+"/browser-read";var MediaBrowserContentTypeSchema=z87.enum(["image/png","image/jpeg","image/webp","video/mp4","audio/wav","audio/mpeg","application/json","text/plain","application/x-subrip"]);var MediaObjectVersionSchema=LocalProjectScopeSchema.extend({versionId:LocalIdSchema,role:z87.enum(["SOURCE","VIDEO","POSTER","AUDIO","FRAME","SHEET","MANIFEST"]),byteSize:z87.int().min(1).max(maxMediaObjectBytes),checksumSha256:LocalDigestSchema});var MediaTransferGrantSchema=z87.strictObject({protocol:z87.literal("NVS_MEDIA_TRANSFER_V1"),storageId:z87.string().regex(/^[A-Za-z0-9_-]{1,100}$/),method:z87.enum(["GET","PUT","HEAD"]),object:MediaObjectVersionSchema,issuedAt:LocalTimeSchema,expiresAt:LocalTimeSchema});var MediaObjectTicketSchema=z87.strictObject({endpoint:z87.url().max(2048),credential:z87.string().regex(/^[A-Za-z0-9_-]{1,2048}\.[A-Za-z0-9_-]{43}$/).meta({writeOnly:true}),method:z87.enum(["GET","PUT"]),object:MediaObjectVersionSchema});var MediaBrowserReadGrantSchema=z87.strictObject({protocol:z87.literal("NVS_MEDIA_BROWSER_READ_V1"),storageId:z87.string().regex(/^[A-Za-z0-9_-]{1,100}$/),object:MediaObjectVersionSchema,contentType:MediaBrowserContentTypeSchema,representationId:LocalIdSchema,attachment:z87.boolean(),issuedAt:LocalTimeSchema,expiresAt:LocalTimeSchema});var MediaBrowserReadTicketSchema=z87.strictObject({url:z87.url().max(4096).refine(value2=>{const url=new URL(value2);return(url.protocol==="https:"||url.protocol==="http:"&&url.hostname==="127.0.0.1")&&!url.username&&!url.password&&!url.hash&&url.pathname===mediaBrowserReadPath&&url.searchParams.size===1&&/^[A-Za-z0-9_-]{1,3072}\.[A-Za-z0-9_-]{43}$/.test(url.searchParams.get("ticket")??"")}),expiresAt:LocalTimeSchema,object:MediaObjectVersionSchema,contentType:MediaBrowserContentTypeSchema});var QwenDeviceCredentialScopeSchema=z88.strictObject({tenantId:LocalIdSchema,connectionId:LocalIdSchema,connectionVersion:z88.int().positive(),workspace:z88.string().regex(/^[a-z0-9][a-z0-9-]{0,63}$/)});var QwenDeviceCredentialIdentitySchema=QwenDeviceCredentialScopeSchema.extend({proofSha256:LocalDigestSchema});var QwenDeviceCredentialSelectionSchema=QwenDeviceCredentialScopeSchema.extend({privateKeyFile:z88.string().min(1).max(4096)});var qwenSource=ResolvedReferenceSchema.pick({artifactId:true,representationId:true,checksumSha256:true,contentType:true,role:true}).extend({byteSize:MediaObjectVersionSchema.shape.byteSize.max(8*1024*1024)});var keyframeBytes=z88.strictObject({checksumSha256:LocalDigestSchema,byteSize:MediaObjectVersionSchema.shape.byteSize.max(8*1024*1024),width:z88.int().positive().max(4096),height:z88.int().positive().max(4096)});var externalKeyframe=z88.literal("KEYFRAME_GENERATE");var QwenKeyframeRecipeSchema=z88.strictObject({processor:externalKeyframe,generationId:LocalIdSchema,credential:QwenDeviceCredentialIdentitySchema,quoteFingerprint:LocalDigestSchema,prompt:z88.string().trim().min(1).refine(value2=>new TextEncoder().encode(value2).length<=1300),aspectRatio:z88.enum(["16:9","9:16"]),sources:z88.array(qwenSource).min(1).max(3)});var QwenKeyframeEvidenceSchema=z88.strictObject({processor:externalKeyframe,providerExecutionId:z88.string().regex(/^[A-Za-z0-9_.:-]{1,500}$/),providerResultId:LocalDigestSchema,image:keyframeBytes});var QwenVideoRecipeSchema=QwenKeyframeRecipeSchema.extend({processor:z88.literal("VIDEO_GENERATE"),prompt:z88.string().trim().min(1).max(2e4),mode:z88.enum(["REFERENCE_TO_VIDEO","FIRST_FRAME_TO_VIDEO","FIRST_LAST_FRAME_TO_VIDEO"]),durationSeconds:z88.int().min(2).max(30),sources:z88.array(qwenSource).min(1).max(10)});var QwenVideoTaskIdSchema=z88.string().regex(/^[A-Za-z0-9_-]{1,160}$/);var QwenVideoEvidenceSchema=z88.strictObject({processor:z88.literal("VIDEO_GENERATE"),providerExecutionId:QwenVideoTaskIdSchema,providerResultId:QwenVideoTaskIdSchema,video:VideoTechnicalMetadataSchema.extend({videoCodec:z88.literal("h264"),frameRate:z88.literal(30),hasAudio:z88.literal(false),frameCount:z88.int().positive().max(902)}),poster:keyframeBytes});var ExternalGenerationReservationMarkerSchema=z88.strictObject({protocol:z88.literal("NVS_TENANT_EXTERNAL_GENERATION_V1"),tenantId:LocalIdSchema,projectId:LocalIdSchema,productionId:LocalIdSchema,runtimeJobId:LocalIdSchema,shotId:LocalIdSchema,preparationId:LocalIdSchema,contractId:LocalIdSchema,workload:z88.enum(["KEYFRAME_GENERATE","VIDEO_GENERATE"]),policyRevision:z88.int().positive(),contractFingerprint:LocalDigestSchema,originRequestFingerprint:LocalDigestSchema,bindingFingerprint:LocalDigestSchema,inputsFingerprint:LocalDigestSchema,quoteFingerprint:LocalDigestSchema});function checkProcessorDeclaration(enabled,kinds,context){if(enabled!==!!kinds?.length||kinds&&new Set(kinds).size!==kinds.length)context.addIssue({code:"custom",path:["processorCapabilities"],message:"Explicit unique processor capabilities must match processing enablement"})}var StartLocalPreviewSchema=RoughCutStartSchema.omit({deviceExecution:true}).extend({placement:LocalPlacementPolicySchema,localProfile:z89.literal("STUDIO_MEDIA_V2").optional()});var LocalDeviceScopeSchema=z89.strictObject({tenantId:LocalIdSchema,deviceId:LocalIdSchema});var LocalDeviceSessionSchema=z89.strictObject({...LocalDeviceScopeSchema.shape,expiresAt:LocalTimeSchema,credential:z89.string().length(43).regex(/^[A-Za-z0-9_-]+$/).meta({writeOnly:true})});var LocalDeviceHeartbeatSchema=LocalDeviceScopeSchema.extend({runtimeVersion:LocalPackageVersionSchema,toolchain:LocalToolchainSchema,available:z89.boolean(),maxConcurrentJobs:z89.int().min(1).max(2).optional(),validationProfileDigest:LocalDigestSchema.optional(),processorProfileDigest:LocalDigestSchema.optional(),localLibraryProfileDigest:LocalDigestSchema.optional(),macSpeechIdentity:MacSpeechIdentitySchema.optional(),cpuSpeech:CpuSpeechCapabilitySchema.optional(),whisperIdentity:LocalWhisperIdentitySchema.optional(),qwenIdentities:z89.array(QwenDeviceCredentialIdentitySchema).min(1).max(16).optional(),processorCapabilities:z89.array(TenantProcessorKindSchema).min(1).max(TenantProcessorKindSchema.options.length).optional()}).superRefine((value2,context)=>checkProcessorDeclaration(!!value2.processorProfileDigest,value2.processorCapabilities,context));var ClaimLocalPreviewSchema=LocalProjectScopeSchema.extend({requestId:LocalIdSchema,deviceId:LocalIdSchema,tenantMediaValidation:z89.literal(true).optional()});var LocalOutputStageSchema=LocalLeaseBindingSchema.extend({uploadRequestId:LocalIdSchema,role:z89.enum(["VIDEO","POSTER"]),checksumSha256:LocalDigestSchema,byteSize:z89.int().positive().max(128*1024*1024)});var LocalOutputTicketSchema=z89.strictObject({receiptId:LocalIdSchema,role:z89.enum(["VIDEO","POSTER"]),checksumSha256:LocalDigestSchema,byteSize:z89.int().positive(),uploaded:z89.boolean()});var LocalSourceRequestSchema=LocalLeaseBindingSchema.extend({representationId:LocalIdSchema});var LocalProofChallengeRequestSchema=LocalDeviceScopeSchema.extend({deviceRevision:z89.int().positive()});var LocalPreviewPlacementViewSchema=z89.strictObject({target:z89.enum(["DEVICE","SERVER"]),reason:z89.enum(["LOCAL_AVAILABLE","CLOUD_ONLY","OFFLINE","UNQUALIFIED","BUSY","LEASE_RECOVERY"]),policy:LocalPlacementPolicySchema});var LocalDeviceTransportConfigurationSchema=z89.strictObject({endpoint:z89.string().url().max(2048),tenantId:LocalIdSchema,deviceId:LocalIdSchema,deviceRevision:z89.int().positive(),privateKeyFile:z89.string().min(1).max(4096),platform:LocalDevicePlatformSchema,tenantMediaValidation:z89.literal(true).optional(),tenantMediaProcessing:z89.literal(true).optional(),processorCapabilities:z89.array(TenantProcessorKindSchema).min(1).max(TenantProcessorKindSchema.options.length).optional(),compositionBrowser:z89.string().min(1).max(4096).optional(),macSpeechIdentity:MacSpeechIdentitySchema.optional(),cpuSpeech:CpuSpeechCapabilitySchema.optional(),cpuSpeechTools:CpuSpeechToolSelectionSchema.optional(),whisperIdentity:LocalWhisperIdentitySchema.optional(),whisperTools:LocalWhisperToolSelectionSchema.optional(),qwenDeviceCredentials:z89.array(QwenDeviceCredentialSelectionSchema).max(16).optional(),qwenIdentities:LocalDeviceHeartbeatSchema.shape.qwenIdentities}).superRefine((value2,context)=>checkProcessorDeclaration(value2.tenantMediaProcessing===true,value2.processorCapabilities,context));var LocalPreviewAdmissionSchema=RoughCutAdmissionSchema.extend({placement:LocalPreviewPlacementViewSchema});var StartLocalFinalRenderSchema=FinalRenderStartSchema.omit({deviceExecution:true}).extend({placement:LocalPlacementPolicySchema});var LocalFinalRenderAdmissionSchema=FinalRenderAdmissionSchema.extend({placement:LocalPreviewPlacementViewSchema});var LocalClaimReceiptSchema=z89.strictObject({found:z89.boolean(),assignment:LocalWorkAssignmentSchema.nullable()});var LocalWorkStateSchema=z89.strictObject({binding:LocalLeaseBindingSchema,status:z89.enum(["ACTIVE","FENCED","OUTCOME_UNKNOWN"]),assignment:LocalWorkAssignmentSchema.nullable()});import{z as z90}from"zod";var LocalManagementCommandSchema=z90.discriminatedUnion("kind",[z90.strictObject({kind:z90.literal("ENROLL"),input:EnrollLocalDeviceSchema}),z90.strictObject({kind:z90.literal("REVOKE_DEVICE"),input:RevokeLocalDeviceSchema}),z90.strictObject({kind:z90.literal("PREVIEW"),input:StartLocalPreviewSchema}),z90.strictObject({kind:z90.literal("FINAL_RENDER"),input:StartLocalFinalRenderSchema})]);var LocalManagementResultSchema=z90.union([LocalDeviceViewSchema,LocalPreviewAdmissionSchema,LocalFinalRenderAdmissionSchema,z90.strictObject({semanticStatus:z90.literal("SUCCESS")})]);var LocalManagementReceiptSchema=z90.strictObject({fingerprint:z90.string().regex(/^[a-f0-9]{64}$/),result:LocalManagementResultSchema.nullable()});var LocalDeviceManagementCommandSchema=LocalManagementCommandSchema;var ScopedLocalManagementReceiptSchema=z90.strictObject({tenantId:LocalIdSchema,command:LocalDeviceManagementCommandSchema}).refine(value2=>value2.tenantId.toLowerCase()===value2.command.input.tenantId.toLowerCase(),{message:"Management receipt must use the authorized tenant"});import{z as z92}from"zod";import{z as z91}from"zod";var WorkspaceScopeSchema=z91.strictObject({tenantId:TenantIdSchema});var WorkspaceViewSchema=HumanTenantSchema;var skillUrl=z91.url().max(4096).refine(value2=>{try{const u=new URL(value2);return value2===value2.trim()&&![...value2].some(c=>c.charCodeAt(0)<=32||c.charCodeAt(0)===127)&&!u.username&&!u.password&&!/[?#]/.test(value2)&&(u.protocol==="https:"||u.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(u.hostname))}catch{return false}});var PublicDownloadDescriptorSchema=z91.discriminatedUnion("status",[z91.strictObject({status:z91.literal("AVAILABLE"),url:skillUrl}),z91.strictObject({status:z91.enum(["UNCONFIGURED","UNAVAILABLE"]),url:z91.null()})]);var WorkspaceCallerSchema=z91.strictObject({humanLinks:HumanLinksSchema.optional(),tenantId:z91.uuid(),principalId:z91.uuid(),serverOrigin:z91.url().refine(value2=>{const u=new URL(value2);return u.origin===value2&&!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))}),skill:PublicDownloadDescriptorSchema,hostReleases:PublicDownloadDescriptorSchema});var WorkspacePageSchema=z91.strictObject({items:z91.array(WorkspaceViewSchema).max(100),possiblyTruncated:z91.boolean()});var DeviceEnrollmentScopeSchema=z92.strictObject({origin:WorkspaceCallerSchema.shape.serverOrigin,tenantId:z92.uuid(),principalId:z92.uuid()});var DeviceEnrollmentHandoffSchema=z92.strictObject({protocol:z92.literal("NVS_DEVICE_ENROLLMENT_HANDOFF_V1"),scope:DeviceEnrollmentScopeSchema,command:LocalManagementCommandSchema.options[0],fingerprint:z92.string().regex(/^[a-f0-9]{64}$/)}).refine(({scope:scope8,command:command4})=>scope8.tenantId.toLowerCase()===command4.input.tenantId.toLowerCase()&&scope8.principalId.toLowerCase()===command4.input.expectedPrincipalId?.toLowerCase(),{message:"Enrollment must match the target workspace and member"});import{z as z93}from"zod";var fingerprint=z93.string().regex(/^[a-f0-9]{64}$/);var scope={tenantId:z93.uuid(),requestId:z93.uuid()};var DeviceEnrollmentIssueSchema=EnrollLocalDeviceSchema.extend({expectedPrincipalId:z93.uuid()});var DeviceEnrollmentLookupSchema=z93.strictObject(scope);var DeviceEnrollmentTicketSchema=z93.strictObject({...scope,protocol:z93.literal("NVS_DEVICE_ENROLLMENT_V1"),enrollmentId:z93.uuid(),deviceId:z93.uuid(),fingerprint,issuedAt:z93.iso.datetime(),expiresAt:z93.iso.datetime()}).refine(({issuedAt,expiresAt})=>{const ttl=Date.parse(expiresAt)-Date.parse(issuedAt);return ttl>0&&ttl<=3e5});var DeviceEnrollmentRedeemSchema=z93.strictObject({tenantId:z93.uuid(),enrollmentId:z93.uuid(),signature:z93.string().regex(/^[A-Za-z0-9_-]{86}$/).meta({writeOnly:true})});var DeviceEnrollmentReceiptSchema=z93.strictObject({fingerprint,result:LocalDeviceViewSchema});var DeviceEnrollmentObservationSchema=z93.discriminatedUnion("state",[z93.strictObject({...scope,state:z93.literal("NOT_FOUND")}),z93.strictObject({...scope,state:z93.literal("ISSUED"),ticket:DeviceEnrollmentTicketSchema}),z93.strictObject({...scope,state:z93.literal("EXPIRED"),fingerprint}),z93.strictObject({...scope,state:z93.literal("ENROLLED"),receipt:DeviceEnrollmentReceiptSchema})]);function deviceEnrollmentSigningInput(ticket){return canonicalLocalJson(DeviceEnrollmentTicketSchema.parse(ticket))}import{z as z94}from"zod";var timestamp=z94.iso.datetime();var reason=z94.string().regex(/^[A-Z][A-Z0-9_]{0,79}$/);var absent=z94.strictObject({state:z94.enum(["NONE","UNKNOWN","NOT_APPLICABLE"])});var occurrence=z94.strictObject({state:z94.literal("OBSERVED"),at:timestamp,reasonCode:reason});var event=z94.union([occurrence,absent]);var count=z94.int().nonnegative();var depth=z94.union([z94.strictObject({state:z94.literal("OBSERVED"),ready:count,pending:count,running:count,waiting:count}),absent.extend({state:z94.enum(["UNKNOWN","NOT_APPLICABLE"])})]);var health=z94.strictObject({at:timestamp.nullable(),reasonCode:reason});var ComponentStatusSchema=z94.strictObject({protocol:z94.literal("NVS_COMPONENT_STATUS_V1"),observedAt:timestamp,liveness:health.extend({state:z94.enum(["ALIVE","STOPPED","STALE","UNKNOWN"])}),readiness:health.extend({state:z94.enum(["READY","BLOCKED","UNKNOWN"])}),lastSuccess:event,lastFailure:event,queueDepth:depth,nextRetry:event});var WorkspaceStatusSchema=ComponentStatusSchema.extend({component:z94.enum(["STUDIO_API","STUDIO_MCP"]),source:z94.literal("AUTHORIZED_WORKSPACE_READ"),tenantId:z94.uuid(),agentGrantId:z94.uuid().optional()});var DeviceStatusInputSchema=z94.strictObject({tenantId:z94.uuid(),deviceId:z94.uuid()});var DeviceStatusSchema=ComponentStatusSchema.extend({component:z94.literal("EXECUTION_NODE"),source:z94.literal("DEVICE_HEARTBEAT_AND_NATIVE_WORK"),tenantId:z94.uuid(),deviceId:z94.uuid(),deviceRevision:z94.int().positive(),runtimeVersion:z94.string().min(1).max(120).nullable(),runtimeVersionObservedAt:timestamp.nullable(),capabilityMismatch:CapabilityVersionMismatchSchema.optional()});import{z as z95}from"zod";var TenantMediaComputeModeSchema=z95.enum(["STAGE_ONE","TENANT_TRUSTED_VALIDATOR"]);var tenantRenderValidationProfile={protocol:"NVS_TENANT_MEDIA_REPORT_V1",inspection:"STUDIO_DECODE_READBACK_V1"};var TenantMediaWorkSchema=LocalWorkScopeSchema.extend({protocol:z95.literal("NVS_TENANT_MEDIA_WORK_V1"),family:z95.enum(["ROUGH_CUT_RENDER","FINAL_RENDER"]),validationMode:z95.literal("TENANT_TRUSTED_VALIDATOR"),operationId:OperationIdSchema,originRequestFingerprint:LocalDigestSchema,basisFingerprint:LocalDigestSchema,policyRevision:LocalRevisionSchema,target:TenantDeviceTargetSchema,renderProfileDigest:LocalDigestSchema,validationProfileDigest:LocalDigestSchema,audioRequired:z95.boolean()});var renderChecks=["CONTAINER_PROFILE","DURATION","VIDEO_DECODE","AUDIO_DECODE","POSTER_DECODE"];var renderCheck=z95.strictObject({key:z95.enum(renderChecks),result:z95.enum(["PASS","FAIL","UNVERIFIED","NOT_APPLICABLE"])});var TenantMediaValidationBodySchema=LocalLeaseBindingSchema.extend({schemaVersion:z95.literal(1),work:TenantMediaWorkSchema,originRequestFingerprint:LocalDigestSchema,requestId:LocalIdSchema,validationRequestId:LocalIdSchema,outputs:z95.array(MediaObjectVersionSchema).length(2),checks:z95.array(renderCheck).length(renderChecks.length),technical:RoughCutTechnicalSchema.nullable()}).superRefine((report,ctx)=>{const{work,outputs,checks}=report;if(work.tenantId!==report.tenantId||work.projectId!==report.projectId||work.productionId!==report.productionId||work.runtimeJobId!==report.runtimeJobId||work.originRequestFingerprint!==report.originRequestFingerprint)ctx.addIssue({code:"custom",path:["work"],message:"Work scope mismatch"});if(!outputs.some(output=>output.role==="VIDEO")||!outputs.some(output=>output.role==="POSTER")||new Set(outputs.map(output=>output.versionId)).size!==2||outputs.some(output=>output.tenantId!==report.tenantId||output.projectId!==report.projectId))ctx.addIssue({code:"custom",path:["outputs"],message:"Exact video and poster versions required"});if(new Set(checks.map(check=>check.key)).size!==renderChecks.length||checks.some(check=>check.result==="NOT_APPLICABLE"!==(check.key==="AUDIO_DECODE"&&!work.audioRequired)))ctx.addIssue({code:"custom",path:["checks"],message:"Exact applicable checks required"});const video=outputs.find(output=>output.role==="VIDEO");if(checks.every(check=>check.result==="PASS"||check.result==="NOT_APPLICABLE")&&!report.technical||report.technical&&(report.technical.checksumSha256!==video?.checksumSha256||report.technical.byteSize!==video?.byteSize||report.technical.hasAudio!==work.audioRequired))ctx.addIssue({code:"custom",path:["technical"],message:"Exact inspected video required"})});var TenantMediaValidationReportSchema=TenantMediaValidationBodySchema.safeExtend({reportFingerprint:LocalDigestSchema,signature:z95.string().regex(/^[A-Za-z0-9_-]{86}$/)});import{z as z96}from"zod";var PrepareTenantMediaValidationSchema=LocalLeaseBindingSchema.extend({requestId:LocalIdSchema,outputReceiptIds:z96.array(LocalIdSchema).length(2).refine(ids=>new Set(ids).size===2)});var TenantMediaValidationRequestSchema=LocalLeaseBindingSchema.extend({requestId:LocalIdSchema,validationRequestId:LocalIdSchema,work:TenantMediaWorkSchema,outputs:z96.array(MediaObjectVersionSchema).length(2)});var TenantMediaValidationReadbackSchema=z96.strictObject({request:TenantMediaValidationRequestSchema,tickets:z96.array(MediaObjectTicketSchema).length(2)});var TenantMediaDownloadSchema=LocalProjectScopeSchema.extend({representationId:LocalIdSchema});var TenantMediaOutputStageSchema=z96.strictObject({ticket:MediaObjectTicketSchema,uploaded:z96.boolean()});var TenantRenderMediaInputSchema=TimelineScopeSchema.extend({renderId:z96.uuid(),role:z96.enum(["VIDEO","POSTER"])});var TenantRenderMediaTicketSchema=TenantRenderMediaInputSchema.extend({representationId:z96.uuid(),ticket:MediaObjectTicketSchema.extend({object:MediaObjectVersionSchema.extend({tenantId:z96.uuid(),projectId:z96.uuid(),versionId:z96.uuid()})})});var TenantMediaCapabilitySchema=z96.strictObject({tenantId:LocalIdSchema,validationMode:z96.literal("TENANT_TRUSTED_VALIDATOR")});import{z as z119}from"zod";import{z as z108}from"zod";import{z as z97}from"zod";var IMPORTED_VISUAL_PROFILE_ID="IMPORTED_H264_SDR_CFR30_VISUAL_V1";var IMPORTED_VISUAL_MAX_BYTES=128*1024*1024;var Hash=z97.string().regex(/^[0-9a-f]{64}$/);var PositiveInteger=z97.int().positive().max(1e9);var ImportedVisualRationalSchema=z97.strictObject({numerator:PositiveInteger,denominator:PositiveInteger});var geometry=limit=>z97.strictObject({width:z97.int().min(2).max(limit).multipleOf(2),height:z97.int().min(2).max(limit).multipleOf(2)}).refine(({width,height})=>width*9===height*16||width*16===height*9,"Only exact 16:9 or 9:16 geometry is supported");var ImportedVisualToolchainSchema=z97.strictObject({ffmpegVersion:z97.string().startsWith("ffmpeg version ").max(512),ffprobeVersion:z97.string().startsWith("ffprobe version ").max(512)});var ImportedVisualSourceInputSchema=z97.strictObject({contentType:z97.literal("video/mp4"),checksumSha256:Hash,byteSize:z97.int().min(32).max(IMPORTED_VISUAL_MAX_BYTES),executionClass:z97.enum(["LIVE","TEST_ONLY"])});var ImportedVisualSourceRangeSchema=z97.strictObject({clock:z97.literal("SOURCE_ZERO_BASED_CFR30"),startFrame:z97.int().min(0).max(1799),endFrame:z97.int().min(1).max(1800)}).refine(v=>v.endFrame>v.startFrame&&v.endFrame-v.startFrame<=360,"The half-open interval must contain 1 to 360 frames");var ImportedVisualNormalizationRequestSchema=z97.strictObject({schemaVersion:z97.literal(1),profileId:z97.literal(IMPORTED_VISUAL_PROFILE_ID),source:ImportedVisualSourceInputSchema,sourceRange:ImportedVisualSourceRangeSchema,output:geometry(1920),audioPolicy:z97.enum(["REQUIRE_NO_AUDIO","SILENT_DERIVATIVE"]),expectedToolchain:ImportedVisualToolchainSchema});var ImportedVisualSourceMetadataSchema=z97.strictObject({...ImportedVisualSourceInputSchema.shape,geometry:geometry(3840),videoCodec:z97.literal("h264"),pixelFormat:z97.literal("yuv420p"),sampleAspectRatio:z97.literal("1:1"),rotationDegrees:z97.literal(0),startPts:z97.literal(0),timeBase:ImportedVisualRationalSchema,frameRate:ImportedVisualRationalSchema,frameCount:z97.int().min(1).max(3600),durationTicks:z97.int().positive().max(6e10),availableCfr30Frames:z97.int().min(0).max(1800),color:z97.strictObject({range:z97.enum(["tv","unknown"]),space:z97.enum(["bt709","unknown"]),transfer:z97.enum(["bt709","unknown"]),primaries:z97.enum(["bt709","unknown"])}),audio:z97.strictObject({codec:z97.literal("aac"),sampleRateHz:z97.union([z97.literal(44100),z97.literal(48e3)]),channels:z97.union([z97.literal(1),z97.literal(2)]),startPts:z97.int(),timeBase:ImportedVisualRationalSchema,durationTicks:z97.int().positive().max(6e10)}).nullable(),fullDecode:z97.literal(true),cfrTimestampsVerified:z97.literal(true)}).superRefine((v,ctx)=>{if(![v.durationTicks,v.timeBase.numerator,v.timeBase.denominator,v.frameRate.numerator,v.frameRate.denominator,v.frameCount,v.availableCfr30Frames].every(Number.isSafeInteger)||v.timeBase.denominator<=0||v.frameRate.numerator<=0||v.frameRate.denominator<=0)return;const ticks=BigInt(v.durationTicks)*BigInt(v.timeBase.numerator);const base3=BigInt(v.timeBase.denominator);const declaredFrames=ticks*BigInt(v.frameRate.numerator);const expectedFrames=BigInt(v.frameCount)*base3*BigInt(v.frameRate.denominator);if(ticks>60n*base3||declaredFrames!==expectedFrames||BigInt(v.availableCfr30Frames)!==ticks*30n/base3||v.audio&&BigInt(v.audio.durationTicks)*BigInt(v.audio.timeBase.numerator)>60n*BigInt(v.audio.timeBase.denominator))ctx.addIssue({code:"custom",message:"Media clock/count/duration metadata is inconsistent"})});var ImportedVisualInspectionSchema=z97.strictObject({profileId:z97.literal(IMPORTED_VISUAL_PROFILE_ID),source:ImportedVisualSourceMetadataSchema,toolchain:ImportedVisualToolchainSchema,evidenceScope:z97.literal("TECHNICAL_MEDIA_ONLY")});var ImportedVisualNormalizationReceiptSchema=z97.strictObject({schemaVersion:z97.literal(1),request:ImportedVisualNormalizationRequestSchema,original:ImportedVisualSourceMetadataSchema,output:ImportedVisualSourceMetadataSchema,toolchain:ImportedVisualToolchainSchema,frameMap:z97.array(z97.strictObject({outputFrame:z97.int().min(0).max(359),sourceFrame:z97.int().min(0).max(3599),sourcePts:z97.int().min(0).max(6e10)})).min(1).max(360),audioDisposition:z97.enum(["NO_AUDIO_PRESENT","REMOVED_FROM_DERIVATIVE_ONLY"]),evidenceScope:z97.literal("TECHNICAL_MEDIA_ONLY")}).superRefine((v,ctx)=>{const count2=v.request.sourceRange.endFrame-v.request.sourceRange.startFrame;const source6=v.original;if(![source6.frameRate.numerator,source6.frameRate.denominator,source6.timeBase.numerator,source6.timeBase.denominator,v.request.sourceRange.startFrame].every(Number.isSafeInteger)||source6.frameRate.numerator<=0||source6.frameRate.denominator<=0)return;const rounded=i=>(2n*BigInt(i)*30n*BigInt(source6.frameRate.denominator)+BigInt(source6.frameRate.numerator))/(2n*BigInt(source6.frameRate.numerator));const exactFrameMap=v.frameMap.every((m,i)=>{if(!Number.isSafeInteger(m.sourcePts)||!Number.isSafeInteger(m.sourceFrame))return false;const absoluteFrame=BigInt(v.request.sourceRange.startFrame+i);return BigInt(m.sourcePts)*BigInt(source6.timeBase.numerator)*BigInt(source6.frameRate.numerator)===BigInt(m.sourceFrame)*BigInt(source6.timeBase.denominator)*BigInt(source6.frameRate.denominator)&&rounded(m.sourceFrame)<=absoluteFrame&&(m.sourceFrame+1===source6.frameCount||rounded(m.sourceFrame+1)>absoluteFrame)});if(!exactFrameMap||v.request.sourceRange.endFrame>source6.availableCfr30Frames||v.output.geometry.width>source6.geometry.width||v.output.geometry.height>source6.geometry.height||v.output.geometry.width*source6.geometry.height!==v.output.geometry.height*source6.geometry.width)ctx.addIssue({code:"custom",message:"Receipt frame mapping or geometry violates the pinned profile"});if(v.output.frameCount!==count2||v.frameMap.length!==count2||v.frameMap.some((m,i)=>m.outputFrame!==i||m.sourceFrame>=v.original.frameCount)||v.output.frameRate.numerator!==30||v.output.frameRate.denominator!==1||v.output.audio||v.original.checksumSha256!==v.request.source.checksumSha256||v.original.byteSize!==v.request.source.byteSize||v.original.executionClass!==v.request.source.executionClass||v.output.executionClass!==v.original.executionClass||v.output.geometry.width!==v.request.output.width||v.output.geometry.height!==v.request.output.height||v.toolchain.ffmpegVersion!==v.request.expectedToolchain.ffmpegVersion||v.toolchain.ffprobeVersion!==v.request.expectedToolchain.ffprobeVersion||v.audioDisposition!==(v.original.audio?"REMOVED_FROM_DERIVATIVE_ONLY":"NO_AUDIO_PRESENT")||v.original.audio&&v.request.audioPolicy!=="SILENT_DERIVATIVE"){ctx.addIssue({code:"custom",message:"Normalization receipt does not match its exact request/source/output"})}});import{z as z98}from"zod";var Uuid=z98.uuid();var Hash2=z98.string().regex(/^[0-9a-f]{64}$/);var ImportedVisualOriginalRegisterSchema=z98.strictObject({deviceId:z98.uuid().toLowerCase().optional(),projectSourceArtifactId:z98.uuid().optional(),tenantId:Uuid,projectId:Uuid,productionId:Uuid,shotId:Uuid,expectedProductionRevision:z98.int().nonnegative(),source:z98.strictObject({contentType:z98.literal("video/mp4"),checksumSha256:Hash2,byteSize:z98.int().min(32).max(128*1024*1024),executionClass:z98.enum(["LIVE","TEST_ONLY"])}),declaredProvenance:z98.strictObject({originalName:z98.string().trim().min(1).max(255).optional(),authorship:z98.string().trim().min(1).max(500).optional(),license:z98.string().trim().min(1).max(500).optional()}),idempotencyKey:z98.string().trim().min(1).max(200)});var ImportedVisualFromProjectSourceSchema=ImportedVisualOriginalRegisterSchema.omit({source:true,projectSourceArtifactId:true}).extend({projectSourceArtifactId:Uuid});var ImportedVisualOriginalReviseSchema=ImportedVisualOriginalRegisterSchema.extend({sourceId:Uuid,expectedVersion:z98.int().positive()});var ImportedVisualNormalizeStartSchema=z98.strictObject({deviceExecution:DeviceRenderTargetSchema.optional(),tenantId:Uuid,projectId:Uuid,productionId:Uuid,shotId:Uuid,sourceId:Uuid,sourceVersionId:Uuid,expectedProductionRevision:z98.int().nonnegative(),request:ImportedVisualNormalizationRequestSchema,idempotencyKey:z98.string().trim().min(1).max(200)});var ImportedVisualGetSchema=z98.strictObject({tenantId:Uuid,productionId:Uuid,normalizationId:Uuid});var ImportedVisualReviewSchema=z98.strictObject({tenantId:Uuid,productionId:Uuid,normalizationId:Uuid,representationId:Uuid,checksumSha256:Hash2,expectedReviewVersion:z98.int().nonnegative(),observations:z98.array(VideoObservationSchema).min(1).max(MAX_SHOT_REVIEW_REQUIREMENTS),summary:z98.string().trim().min(1).max(2500),idempotencyKey:z98.string().trim().min(1).max(200)});var ImportedVisualDecisionSchema=z98.strictObject({tenantId:Uuid,productionId:Uuid,normalizationId:Uuid,reviewId:Uuid,expectedAcceptanceVersion:z98.int().nonnegative(),action:z98.enum(["ACCEPT","REJECT"]),acknowledgeWarnings:z98.boolean().default(false),reason:z98.string().trim().min(1).max(2500),idempotencyKey:z98.string().trim().min(1).max(200)});var ImportedVisualOriginalViewSchema=z98.strictObject({sourceId:Uuid,versionId:Uuid,version:z98.int().positive(),tenantId:Uuid,projectId:Uuid,productionId:Uuid,shotId:Uuid,artifactId:Uuid,representationId:Uuid,metadata:ImportedVisualSourceMetadataSchema,declaredProvenance:ImportedVisualOriginalRegisterSchema.shape.declaredProvenance.optional(),executionClass:z98.enum(["LIVE","TEST_ONLY"]),current:z98.boolean(),createdAt:z98.iso.datetime({offset:true})});var ImportedVisualNormalizationViewSchema=z98.strictObject({normalizationId:Uuid,runtimeJobId:Uuid,sourceId:Uuid,sourceVersionId:Uuid,lifecycle:z98.string(),cancellationRequested:z98.boolean(),receipt:ImportedVisualNormalizationReceiptSchema.nullable(),output:z98.strictObject({artifactId:Uuid,representationId:Uuid,posterArtifactId:Uuid,posterRepresentationId:Uuid}).nullable()});import{z as z99}from"zod";var id7=z99.uuid().toLowerCase();var SourceSyncRuntimeStartSchema=SourceSyncAudioStartSchema.extend({deviceId:id7.optional()});var SourceSyncRuntimePublicationSchema=SourceSyncRuntimeStartSchema.transform(({deviceId,...publication})=>{void deviceId;return publication});var SourceSyncRuntimeScopeSchema=z99.strictObject({tenantId:id7,productionId:id7,requestId:id7});var SourceSyncRuntimeAdmissionSchema=z99.strictObject({requestId:id7,runtimeJobId:id7,productionRevision:z99.int().positive()});var SourceSyncRuntimeViewSchema=SourceSyncRuntimeAdmissionSchema.extend({normalizationId:id7,lifecycle:z99.enum(["PENDING","READY","RUNNING","WAITING","SUCCEEDED","FAILED","CANCELLED","SUPERSEDED"]),cancellationRequested:z99.boolean(),output:SourceSyncAudioReceiptSchema.nullable()});import{z as z100}from"zod";var id8=z100.uuid().toLowerCase();var hash4=z100.string().regex(/^[0-9a-f]{64}$/);var SourceSyncMediaIdentitySchema=z100.strictObject({artifactId:id8,representationId:id8,checksumSha256:hash4});var sampleRange=z100.strictObject({startSample:z100.int().nonnegative(),endSample:z100.int().positive()}).refine(v=>v.endSample>v.startSample);var frameRange=z100.strictObject({startFrame:z100.int().nonnegative(),endFrame:z100.int().positive()}).refine(v=>v.endFrame>v.startFrame);var SourceSyncListeningEvidenceSchema=z100.discriminatedUnion("kind",[z100.strictObject({id:z100.string().trim().min(1).max(100),kind:z100.literal("AUDIO_LISTENING"),media:SourceSyncMediaIdentitySchema,coverage:z100.array(sampleRange).min(1).max(64),producer:z100.string().trim().min(1).max(200)}),z100.strictObject({id:z100.string().trim().min(1).max(100),kind:z100.literal("VIDEO_PLAYBACK"),media:SourceSyncMediaIdentitySchema,coverage:z100.array(frameRange).min(1).max(64),producer:z100.string().trim().min(1).max(200)})]);var SourceSyncObservationSchema=z100.strictObject({key:z100.enum(["AUDIBILITY","AUDIO_VISUAL_ALIGNMENT"]),status:z100.enum(["SATISFIED","VIOLATED","NOT_OBSERVABLE"]),confidence:z100.enum(["CLEAR","UNCERTAIN"]),observed:z100.string().trim().min(1).max(2e3),evidenceIds:z100.array(z100.string().trim().min(1).max(100)).max(64)});var SourceSyncReviewTargetSchema=z100.strictObject({version:SourceSyncAudioVersionSchema,audio:SourceSyncMediaIdentitySchema,visual:SourceSyncMediaIdentitySchema,sampleCount:z100.int().positive(),frameCount:z100.int().positive().max(360),currentReviewVersion:z100.int().nonnegative(),declarationScope:z100.literal("ATTRIBUTED_OBSERVATIONS_NOT_LISTENING_ATTESTATION")});var SourceSyncReviewInputSchema=SourceSyncAudioGetSchema.extend({tenantId:id8,productionId:id8,shotId:id8,versionId:id8,expectedReviewVersion:z100.int().nonnegative(),audio:SourceSyncMediaIdentitySchema,visual:SourceSyncMediaIdentitySchema,evidence:z100.array(SourceSyncListeningEvidenceSchema).max(64),observations:z100.array(SourceSyncObservationSchema).length(2),summary:z100.string().trim().min(1).max(4e3),idempotencyKey:z100.string().trim().min(1).max(200)});var SourceSyncReviewRecordSchema=z100.strictObject({id:id8,versionId:id8,reviewVersion:z100.int().positive(),tenantId:id8,productionId:id8,shotId:id8,audio:SourceSyncMediaIdentitySchema,visual:SourceSyncMediaIdentitySchema,evidence:z100.array(SourceSyncListeningEvidenceSchema).max(64),observations:z100.array(SourceSyncObservationSchema).length(2),outcome:z100.enum(["PASS","FAIL","NEEDS_REVIEW"]),summary:z100.string(),createdByPrincipalId:id8,executionClass:z100.enum(["LIVE","TEST_ONLY"]),createdAt:z100.iso.datetime({offset:true})});var SourceSyncReviewGetSchema=SourceSyncAudioGetSchema.extend({tenantId:id8,productionId:id8,shotId:id8,versionId:id8,reviewId:id8});import{z as z101}from"zod";var ImportedVideoReviewRecordSchema=VideoReviewRecordSchema.omit({generationId:true,candidateId:true,preparationId:true,contractId:true,contractFingerprint:true}).extend({sourceKind:z101.literal("IMPORTED"),normalizationId:z101.uuid(),sourceId:z101.uuid(),sourceVersionId:z101.uuid(),planVersionId:z101.uuid(),shotPlanningRevision:z101.int().positive()});var ImportedVideoReviewReceiptSchema=z101.strictObject({semanticStatus:z101.literal("SUCCESS"),review:ImportedVideoReviewRecordSchema,productionRevision:z101.int().positive()});import{z as z102}from"zod";var ImportedVisualCancellationSchema=z102.strictObject({cancellationRequested:z102.boolean()});var ImportedVisualAdmissionSchema=z102.strictObject({semanticStatus:z102.literal("ACCEPTED"),normalizationId:z102.uuid(),runtimeJobId:z102.uuid(),sourceId:z102.uuid(),sourceVersionId:z102.uuid(),productionRevision:z102.int().positive(),deviceExecution:DeviceRenderReceiptSchema.optional()});var ImportedVisualReviewTargetSchema=ProgrammaticVideoReviewTargetSchema.omit({renderId:true,compositionId:true,compositionVersionId:true,compositionVersion:true,compositionFingerprint:true,renderManifestFingerprint:true}).extend({sourceKind:z102.literal("IMPORTED"),normalizationId:z102.uuid(),sourceId:z102.uuid(),sourceVersionId:z102.uuid(),latestReview:ImportedVideoReviewRecordSchema.nullable()});import{z as z103}from"zod";var ImportedVisualOriginalGetSchema=z103.strictObject({tenantId:z103.uuid(),productionId:z103.uuid(),sourceId:z103.uuid(),version:z103.int().positive().optional()});var ImportedVisualOriginalHistoryQuerySchema=z103.strictObject({tenantId:z103.uuid(),productionId:z103.uuid(),sourceId:z103.uuid(),beforeVersion:z103.int().positive().optional(),limit:z103.int().min(1).max(50).default(20)});var ImportedVisualOriginalHistorySchema=z103.strictObject({sourceId:z103.uuid(),items:z103.array(ImportedVisualOriginalViewSchema).max(50),nextBeforeVersion:z103.int().positive().nullable()});var ImportedVisualOriginalQuerySchema=z103.strictObject({tenantId:z103.uuid().toLowerCase(),productionId:z103.uuid().toLowerCase(),shotId:z103.uuid().toLowerCase().optional(),afterSourceId:z103.uuid().toLowerCase().optional(),limit:z103.int().min(1).max(50).default(20)});var ImportedVisualOriginalPageSchema=z103.strictObject({tenantId:z103.uuid(),productionId:z103.uuid(),items:z103.array(ImportedVisualOriginalViewSchema).max(50),nextAfterSourceId:z103.uuid().nullable()}).refine(p=>p.nextAfterSourceId===null||p.items.at(-1)?.sourceId===p.nextAfterSourceId);import{z as z104}from"zod";var Content=z104.string().min(44).max(178956972).refine(value2=>{if(value2.length%4||/[^A-Za-z0-9+/=]/.test(value2))return false;const padding=value2.endsWith("==")?2:value2.endsWith("=")?1:0;return value2.indexOf("=")===(padding?value2.length-padding:-1)},"Invalid base64").refine(value2=>{const alphabet="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";return value2.endsWith("==")?alphabet.indexOf(value2.at(-3))%16===0:value2.endsWith("=")?alphabet.indexOf(value2.at(-2))%4===0:true},"Noncanonical base64");var ImportedVisualOriginalUploadSchema=ImportedVisualOriginalRegisterSchema.extend({contentBase64:Content});var ImportedVisualOriginalRevisionUploadSchema=ImportedVisualOriginalReviseSchema.extend({contentBase64:Content});var LegacyImportedVisualUploadSchema=ImportedVisualOriginalUploadSchema.omit({deviceId:true});var LegacyImportedVisualRevisionSchema=ImportedVisualOriginalRevisionUploadSchema.omit({deviceId:true});var LegacyImportedVisualProjectSourceSchema=ImportedVisualFromProjectSourceSchema.omit({deviceId:true});import{z as z105}from"zod";var DirectOriginalCommandSchema=z105.discriminatedUnion("operation",[z105.strictObject({operation:z105.literal("REGISTER"),input:ImportedVisualOriginalRegisterSchema}),z105.strictObject({operation:z105.literal("REVISE"),input:ImportedVisualOriginalReviseSchema})]);var DirectOriginalKeySchema=LocalWorkScopeSchema.omit({runtimeJobId:true}).extend({intakeId:LocalIdSchema});var DirectOriginalAdmissionSchema=z105.strictObject({state:z105.literal("SUBMITTED"),tenantId:z105.uuid(),projectId:z105.uuid(),productionId:z105.uuid(),intakeId:z105.uuid(),runtimeJobId:z105.uuid(),operationId:OperationIdSchema});var accepted=z105.strictObject({state:z105.literal("ACCEPTED"),original:ImportedVisualOriginalViewSchema});var DirectOriginalStageSchema=z105.discriminatedUnion("state",[accepted,DirectOriginalAdmissionSchema,DirectOriginalKeySchema.extend({state:z105.literal("UPLOAD"),ticket:MediaObjectTicketSchema,uploaded:z105.boolean()})]);var DirectOriginalSubmitSchema=z105.discriminatedUnion("state",[accepted,DirectOriginalAdmissionSchema]);import{z as z107}from"zod";import{z as z106}from"zod";var ArtifactLifecycleSchema=z106.enum(["CREATING","PROCESSING","READY","INVALID","ARCHIVED"]);var ArtifactMetadataSchema=z106.object({id:ArtifactIdSchema,tenantId:TenantIdSchema,projectId:ProjectIdSchema,productionId:ProductionIdSchema.nullable(),family:z106.string().trim().min(1),origin:z106.string().trim().min(1),lifecycle:ArtifactLifecycleSchema,createdByPrincipalId:PrincipalIdSchema,checksumSha256:z106.string().regex(/^[0-9a-f]{64}$/).nullable(),contentType:z106.string().trim().min(1).nullable(),primaryRepresentationId:ArtifactRepresentationIdSchema.nullable(),mediaMetadata:z106.record(z106.string(),z106.unknown()),createdAt:z106.iso.datetime({offset:true}),readyAt:z106.iso.datetime({offset:true}).nullable()});var ArtifactRepresentationSchema=z106.object({id:ArtifactRepresentationIdSchema,tenantId:TenantIdSchema,artifactId:ArtifactIdSchema,role:z106.string().trim().min(1),storageDriver:z106.string().trim().min(1),storageLocator:z106.record(z106.string(),z106.unknown()),checksumSha256:z106.string().regex(/^[0-9a-f]{64}$/),contentType:z106.string().trim().min(1),byteSize:z106.string().regex(/^\d+$/),width:z106.int().positive().nullable(),height:z106.int().positive().nullable(),durationMs:z106.string().regex(/^\d+$/).nullable(),frameRate:z106.string().nullable(),videoCodec:z106.string().nullable(),audioCodec:z106.string().nullable(),hasAudio:z106.boolean().nullable(),sampleRateHz:z106.int().positive().nullable(),audioChannels:z106.int().positive().nullable(),createdAt:z106.iso.datetime({offset:true})});var ArtifactRelationSchema=z106.object({id:ArtifactRelationIdSchema,tenantId:TenantIdSchema,sourceArtifactId:ArtifactIdSchema,targetArtifactId:ArtifactIdSchema,relationType:z106.string().trim().min(1),createdByPrincipalId:PrincipalIdSchema,createdAt:z106.iso.datetime({offset:true})});var RegisterReadyArtifactInputSchema=z106.object({tenantId:TenantIdSchema,projectId:ProjectIdSchema,productionId:ProductionIdSchema.nullable(),principalId:PrincipalIdSchema,family:z106.string().trim().min(1),origin:z106.string().trim().min(1),representation:z106.object({role:z106.string().trim().min(1),storageDriver:z106.string().trim().min(1),storageLocator:z106.record(z106.string(),z106.unknown()),checksumSha256:z106.string().regex(/^[0-9a-f]{64}$/),contentType:z106.string().trim().min(1),byteSize:z106.string().regex(/^\d+$/),width:z106.int().positive().nullable(),height:z106.int().positive().nullable(),durationMs:z106.string().regex(/^\d+$/).nullable(),frameRate:z106.string().nullable(),videoCodec:z106.string().nullable(),audioCodec:z106.string().nullable(),hasAudio:z106.boolean().nullable(),sampleRateHz:z106.int().positive().nullable(),audioChannels:z106.int().positive().nullable()}),mediaMetadata:z106.record(z106.string(),z106.unknown()).default({}),provenance:z106.array(z106.object({targetArtifactId:ArtifactIdSchema,relationType:z106.string().trim().min(1)})).default([])});var ReadyArtifactRegistrationSchema=z106.object({artifact:ArtifactMetadataSchema,primaryRepresentation:ArtifactRepresentationSchema,relations:z106.array(ArtifactRelationSchema)});var SourceInputMetadataSchema=z106.strictObject({idempotencyKey:z106.string().trim().min(1).max(200).optional(),tenantId:TenantIdSchema,kind:z106.enum(["PRODUCT_INFORMATION","REFERENCE_IMAGE","REFERENCE_VIDEO"]),contentType:z106.enum(["text/plain","application/json","image/png","image/jpeg","image/webp","video/mp4"]),originalName:z106.string().trim().min(1).max(255).optional()});var UploadSourceInputRequestSchema=SourceInputMetadataSchema.extend({contentBase64:z106.string().min(4).max(11184812).regex(/^[A-Za-z0-9+/]*={0,2}$/)});var DirectProjectSourceCommandSchema=z107.strictObject({projectId:LocalIdSchema,metadata:SourceInputMetadataSchema.extend({tenantId:LocalIdSchema.pipe(TenantIdSchema),idempotencyKey:z107.string().trim().min(1).max(200)}),checksumSha256:LocalDigestSchema,byteSize:z107.int().positive().max(8*1024*1024),requestedDeviceId:LocalIdSchema.optional()}).refine(({metadata})=>metadata.kind==="REFERENCE_VIDEO"?metadata.contentType==="video/mp4":metadata.kind==="REFERENCE_IMAGE"&&["image/png","image/jpeg","image/webp"].includes(metadata.contentType));var DirectProjectSourceKeySchema=LocalProjectScopeSchema.extend({intakeId:LocalIdSchema});var DirectProjectSourceAdmissionSchema=DirectProjectSourceKeySchema.extend({state:z107.literal("SUBMITTED"),productionId:LocalIdSchema,runtimeJobId:LocalIdSchema,operationId:OperationIdSchema});var accepted2=z107.strictObject({state:z107.literal("ACCEPTED"),registration:ReadyArtifactRegistrationSchema});var DirectProjectSourceStageSchema=z107.discriminatedUnion("state",[accepted2,DirectProjectSourceAdmissionSchema,DirectProjectSourceKeySchema.extend({state:z107.literal("UPLOAD"),ticket:MediaObjectTicketSchema,uploaded:z107.boolean()})]);var DirectProjectSourceSubmitSchema=z107.discriminatedUnion("state",[accepted2,DirectProjectSourceAdmissionSchema]);var LocalLibraryDestinationSchema=z108.discriminatedUnion("kind",[z108.strictObject({kind:z108.literal("ORIGINAL"),command:DirectOriginalCommandSchema}),z108.strictObject({kind:z108.literal("PROJECT_SOURCE"),command:DirectProjectSourceCommandSchema})]);function localLibraryInspectable(reference3){if(reference3.contentType==="video/mp4")return reference3.byteSize>=32;return["image/png","image/jpeg","image/webp"].includes(reference3.contentType)&&reference3.byteSize>0&&reference3.byteSize<=8*1024*1024}var sameId=(left,right)=>left.toLowerCase()===right.toLowerCase();function destinationMatches(destination,reference3){if(destination.kind==="ORIGINAL"){const{input}=destination.command;return sameId(input.tenantId,reference3.tenantId)&&sameId(input.projectId,reference3.projectId)&&(!input.deviceId||sameId(input.deviceId,reference3.deviceId))&&input.source.contentType===reference3.contentType&&input.source.byteSize===reference3.byteSize&&input.source.checksumSha256===reference3.checksumSha256}const{command:command4}=destination;return sameId(command4.metadata.tenantId,reference3.tenantId)&&sameId(command4.projectId,reference3.projectId)&&(!command4.requestedDeviceId||sameId(command4.requestedDeviceId,reference3.deviceId))&&command4.metadata.contentType===reference3.contentType&&command4.byteSize===reference3.byteSize&&command4.checksumSha256===reference3.checksumSha256}var command=LocalWorkScopeSchema.omit({runtimeJobId:true}).extend({requestId:LocalIdSchema,reference:LocalLibraryReferenceSchema,accessRevision:z108.int().positive()});var LocalLibraryCommandSchema=z108.discriminatedUnion("action",[command.extend({action:z108.literal("INSPECT")}),command.extend({action:z108.literal("PUBLISH"),destination:LocalLibraryDestinationSchema})]).superRefine((value2,ctx)=>{if(value2.reference.tenantId!==value2.tenantId||value2.reference.projectId!==value2.projectId)ctx.addIssue({code:"custom",message:"Exact local file project required"});if(!localLibraryInspectable(value2.reference))ctx.addIssue({code:"custom",message:"A qualified media file version is required"});if(value2.action!=="PUBLISH")return;const d=value2.destination;if(d.kind==="ORIGINAL"){const input=d.command.input;if(!sameId(input.tenantId,value2.tenantId)||!sameId(input.projectId,value2.projectId)||!sameId(input.productionId,value2.productionId)||input.deviceId&&!sameId(input.deviceId,value2.reference.deviceId)||input.source.byteSize!==value2.reference.byteSize||input.source.checksumSha256!==value2.reference.checksumSha256||input.source.contentType!==value2.reference.contentType)ctx.addIssue({code:"custom",message:"Original must bind exact local file and native Production"})}else if(!sameId(d.command.metadata.tenantId,value2.tenantId)||!sameId(d.command.projectId,value2.projectId)||d.command.requestedDeviceId&&!sameId(d.command.requestedDeviceId,value2.reference.deviceId)||d.command.byteSize!==value2.reference.byteSize||d.command.checksumSha256!==value2.reference.checksumSha256||d.command.metadata.contentType!==value2.reference.contentType)ctx.addIssue({code:"custom",message:"Project SOURCE must bind exact local file"})});var LocalLibraryCommandQuerySchema=LocalWorkScopeSchema.omit({runtimeJobId:true}).extend({requestId:LocalIdSchema});var LocalLibraryAdmissionSchema=LocalWorkScopeSchema.extend({state:z108.literal("SUBMITTED"),requestId:LocalIdSchema,operationId:OperationIdSchema,reference:LocalLibraryReferenceSchema,accessRevision:z108.int().positive()});var LocalLibraryInspectionSchema=z108.discriminatedUnion("kind",[z108.strictObject({kind:z108.literal("VIDEO"),metadata:ImportedVisualSourceMetadataSchema}),z108.strictObject({kind:z108.literal("IMAGE"),checksumSha256:LocalDigestSchema,byteSize:z108.int().positive().max(8*1024*1024),width:z108.int().positive().max(4096),height:z108.int().positive().max(4096)})]);var LocalLibraryInspectRecipeSchema=z108.strictObject({processor:z108.literal("LOCAL_MEDIA_INSPECT"),reference:LocalLibraryReferenceSchema,accessRevision:z108.int().positive(),libraryProfileDigest:LocalDigestSchema}).refine(({reference:reference3})=>localLibraryInspectable(reference3),"Qualified local inspection required");var LocalLibraryPublishRecipeSchema=z108.strictObject({processor:z108.literal("LOCAL_MEDIA_PUBLISH"),reference:LocalLibraryReferenceSchema,accessRevision:z108.int().positive(),libraryProfileDigest:LocalDigestSchema,destination:LocalLibraryDestinationSchema,object:MediaObjectVersionSchema.extend({role:z108.literal("SOURCE")})}).refine(({reference:reference3,object,destination})=>localLibraryInspectable(reference3)&&destinationMatches(destination,reference3)&&object.tenantId===reference3.tenantId&&object.projectId===reference3.projectId&&object.checksumSha256===reference3.checksumSha256&&object.byteSize===reference3.byteSize,"Publication must use the exact local file version and native destination");var LocalLibraryInspectEvidenceSchema=z108.strictObject({processor:z108.literal("LOCAL_MEDIA_INSPECT"),inspection:LocalLibraryInspectionSchema});var LocalLibraryPublishEvidenceSchema=z108.strictObject({processor:z108.literal("LOCAL_MEDIA_PUBLISH"),inspection:LocalLibraryInspectionSchema});import{z as z109}from"zod";var sha14=z109.string().regex(/^[0-9a-f]{64}$/);var TemporalEvidenceSourceSchema=z109.strictObject({tenantId:z109.uuid(),projectId:z109.uuid(),productionId:z109.uuid(),artifactId:z109.uuid(),representationId:z109.uuid(),checksumSha256:sha14,byteSize:z109.int().positive().max(128*1024*1024),width:z109.int().min(16).max(4096),height:z109.int().min(16).max(4096),durationMs:z109.int().positive().max(6e4),frameRate:z109.number().min(1).max(60),frameCount:z109.int().positive().max(3600),videoCodec:z109.literal("h264"),executionClass:z109.enum(["LIVE","TEST_ONLY"])}).refine(v=>Math.abs(v.frameCount/v.frameRate*1e3-v.durationMs)<=150,"Exact frame count, duration and rate must agree");var TemporalRiskWindowSchema=z109.strictObject({startMs:z109.int().nonnegative().max(6e4),endMs:z109.int().positive().max(6e4),reason:z109.enum(["TEMPORAL_BEAT","PRIOR_FINDING","SUSPICIOUS_DRIFT","SCENE_CHANGE"])}).refine(v=>v.endMs>v.startMs,"Risk window must advance");var TemporalSamplingProfileSchema=z109.strictObject({id:z109.literal("ADAPTIVE_TEMPORAL_V1"),motion:z109.enum(["NORMAL","HIGH"]),lockedIdentity:z109.boolean(),windows:z109.array(TemporalRiskWindowSchema).max(32)});var TemporalSampleSchema=z109.strictObject({ordinal:z109.int().nonnegative().max(63),frameIndex:z109.int().nonnegative().max(3599),timestampMs:z109.number().nonnegative().max(6e4),reasons:z109.array(z109.enum(["START","END","INTERIOR","HIGH_MOTION","LOCKED_IDENTITY","TEMPORAL_BEAT","PRIOR_FINDING","SUSPICIOUS_DRIFT","SCENE_CHANGE"])).min(1).max(9)});var TemporalSamplingPlanSchema=z109.strictObject({schemaVersion:z109.literal(1),source:TemporalEvidenceSourceSchema,profile:TemporalSamplingProfileSchema,samples:z109.array(TemporalSampleSchema).min(1).max(64),frameWidth:z109.int().min(16).max(320),frameHeight:z109.int().min(16).max(320),columns:z109.int().min(1).max(4),rows:z109.int().min(1).max(16),gutterPx:z109.literal(8)}).superRefine((p,ctx)=>{const s=p.samples;if(s[0]?.frameIndex!==0||s.at(-1)?.frameIndex!==p.source.frameCount-1||p.rows!==Math.ceil(s.length/p.columns)||p.columns!==Math.min(4,s.length)||s.some((v,i)=>v.ordinal!==i||v.frameIndex>=p.source.frameCount||Math.abs(v.timestampMs-v.frameIndex*1e3/p.source.frameRate)>.001||i>0&&v.frameIndex<=s[i-1].frameIndex||new Set(v.reasons).size!==v.reasons.length)||p.profile.windows.some(w=>w.endMs>p.source.durationMs))ctx.addIssue({code:"custom",message:"Temporal samples must preserve exact bounded source order, time and layout"})});var ExtractedTemporalFrameSchema=z109.strictObject({sample:TemporalSampleSchema,checksumSha256:sha14,byteSize:z109.int().positive().max(2*1024*1024),width:z109.int().positive().max(320),height:z109.int().positive().max(320),contentType:z109.literal("image/png")});var TemporalEvidenceManifestSchema=z109.strictObject({schemaVersion:z109.literal(1),plan:TemporalSamplingPlanSchema,engineVersion:z109.string().min(1).max(200),frames:z109.array(ExtractedTemporalFrameSchema).min(1).max(64),sheet:z109.strictObject({checksumSha256:sha14,byteSize:z109.int().positive().max(16*1024*1024),width:z109.int().positive().max(1320),height:z109.int().positive().max(5256),contentType:z109.literal("image/png")})}).superRefine((m,ctx)=>{const p=m.plan;if(m.frames.length!==p.samples.length||m.frames.some((f,i)=>JSON.stringify(f.sample)!==JSON.stringify(p.samples[i])||f.width!==p.frameWidth||f.height!==p.frameHeight)||m.sheet.width!==p.columns*p.frameWidth+(p.columns+1)*p.gutterPx||m.sheet.height!==p.rows*p.frameHeight+(p.rows+1)*p.gutterPx)ctx.addIssue({code:"custom",message:"Evidence frames and sheet must match the exact sampling plan"})});function processorToolchain(raw,processor){const parsed=LocalToolchainSchema.safeParse(raw);if(!parsed.success)return null;const value2=parsed.data;if(processor!=="SPEECH_SYNTHESIZE_CPU"){if(value2.profile.kind!=="STUDIO_MEDIA_V2")return null;return selectLocalToolchain(value2,value2.profile.contractDigest)}const selected=value2.profile.kind==="AUDIO_MEDIA_V1"?value2:value2.supported?.find(s=>s.profile.kind==="AUDIO_MEDIA_V1");if(!selected)return null;const{supported,...base3}=value2;void supported;return LocalToolchainSchema.parse({...base3,profile:selected.profile,rendererVersion:selected.rendererVersion,rendererDigest:selected.rendererDigest})}import{z as z114}from"zod";import{z as z113}from"zod";import{z as z111}from"zod";import{z as z110}from"zod";var sha15=z110.string().regex(/^[0-9a-f]{64}$/);var name=z110.string().regex(/^[A-Za-z][A-Za-z0-9_.-]{0,63}$/);var CompositionPathSchema=z110.string().max(240).regex(/^[A-Za-z0-9_-][A-Za-z0-9_.-]*(?:\/[A-Za-z0-9_.-]+)*$/).refine(v=>!v.split("/").some(p=>p==="."||p===".."));var CompositionScopeSchema=z110.strictObject({tenantId:z110.uuid(),productionId:z110.uuid()});var CompositionBasisPinSchema=z110.strictObject({briefVersionId:z110.uuid(),storyVersionId:z110.uuid(),planVersionId:z110.uuid(),shotId:z110.uuid().nullable()});var CompositionBindingSchema=z110.strictObject({name,purpose:z110.enum(["SOURCE","DEPENDENCY_MANIFEST","DEPENDENCY_LOCK","DATA","FONT","IMAGE","VIDEO"]),artifactId:z110.uuid(),representationId:z110.uuid(),checksumSha256:sha15,declaredOrigin:z110.enum(["CODE","AI","HUMAN","IMPORTED","UNKNOWN"])});var parameter=z110.discriminatedUnion("type",[z110.strictObject({name,type:z110.literal("STRING"),value:z110.string().max(4e3),maxLength:z110.int().min(0).max(4e3)}).refine(v=>v.value.length<=v.maxLength),z110.strictObject({name,type:z110.literal("NUMBER"),value:z110.number().finite(),minimum:z110.number().finite(),maximum:z110.number().finite()}).refine(v=>v.minimum<=v.value&&v.value<=v.maximum),z110.strictObject({name,type:z110.literal("BOOLEAN"),value:z110.boolean()})]);var CompositionContentSchema=z110.strictObject({schemaVersion:z110.literal(1),provider:z110.literal("HYPERFRAME"),dialect:z110.literal("HYPERFRAME_HTML_GSAP_V1"),role:z110.enum(["PRIMARY_VISUAL","VISUAL_LAYER"]),executionClass:z110.enum(["LIVE","TEST_ONLY"]),intent:z110.string().trim().min(1).max(2e3),viewport:z110.strictObject({width:z110.int().min(1).max(8192),height:z110.int().min(1).max(8192)}),clock:z110.strictObject({numerator:z110.int().positive(),denominator:z110.int().positive(),frameCount:z110.int().positive().max(2147483647)}),entrypoint:CompositionPathSchema,parameterSchemaVersion:z110.literal(1),parameters:z110.array(parameter).max(64),bindings:z110.array(CompositionBindingSchema).min(3).max(64),dependencies:z110.array(z110.strictObject({name:z110.string().regex(/^(?:@[a-z0-9._-]+\/)?[a-z0-9._-]+$/),version:z110.string().regex(/^\d+\.\d+\.\d+(?:-[A-Za-z0-9.-]+)?$/),integrity:z110.string().regex(/^sha(?:256|384|512)-[A-Za-z0-9+/]+={0,2}$/)})).min(1).max(64),randomSeed:z110.int().nonnegative().max(4294967295).nullable()}).superRefine((c,ctx)=>{for(const list of[c.parameters,c.bindings,c.dependencies])if(new Set(list.map(x=>x.name)).size!==list.length)ctx.addIssue({code:"custom",message:"Names must be unique within each input group"});for(const purpose of["SOURCE","DEPENDENCY_MANIFEST","DEPENDENCY_LOCK"])if(c.bindings.filter(x=>x.purpose===purpose).length!==1)ctx.addIssue({code:"custom",path:["bindings"],message:"Exactly one "+purpose+" binding is required"});if(c.bindings.find(x=>x.purpose==="SOURCE")?.declaredOrigin!=="CODE")ctx.addIssue({code:"custom",path:["bindings"],message:"Programmatic source must retain CODE provenance"});for(const p of["@hyperframes/engine","@hyperframes/producer","gsap"])if(!c.dependencies.some(x=>x.name===p))ctx.addIssue({code:"custom",path:["dependencies"],message:"Missing authoring dependency: "+p})});var CompositionSourceBundleSchema=z110.strictObject({schemaVersion:z110.literal(1),entrypoint:CompositionPathSchema,files:z110.array(z110.strictObject({path:CompositionPathSchema,contentType:z110.enum(["text/html","text/css","text/javascript","image/svg+xml","application/json"]),content:z110.string().max(1048576)})).min(1).max(128)}).superRefine((b,ctx)=>{if(new Set(b.files.map(x=>x.path)).size!==b.files.length)ctx.addIssue({code:"custom",message:"Source paths must be unique"});if(!b.files.some(x=>x.path===b.entrypoint&&x.contentType==="text/html"))ctx.addIssue({code:"custom",message:"Entrypoint must resolve to a declared HTML file"})});var SubmitCompositionSchema=CompositionScopeSchema.extend({compositionId:z110.uuid().nullable(),expectedVersion:z110.int().nonnegative(),previousVersionId:z110.uuid().nullable(),expectedProductionRevision:z110.int().positive(),basis:CompositionBasisPinSchema,content:CompositionContentSchema,idempotencyKey:z110.string().trim().min(1).max(200)}).superRefine((i,ctx)=>{if(i.expectedVersion===0!==(i.compositionId===null&&i.previousVersionId===null)||i.expectedVersion>0&&(!i.compositionId||!i.previousVersionId))ctx.addIssue({code:"custom",message:"Create and exact-version revision identities must not be mixed"});if(i.content.role==="PRIMARY_VISUAL"&&!i.basis.shotId)ctx.addIssue({code:"custom",message:"Primary visual must bind a planned Shot"})});var CompositionGetSchema=CompositionScopeSchema.extend({compositionId:z110.uuid(),versionId:z110.uuid().optional()});var CompositionHistorySchema=CompositionScopeSchema.extend({compositionId:z110.uuid(),limit:z110.int().min(1).max(100).default(20),beforeVersion:z110.int().positive().optional()});var CompositionInputFactSchema=CompositionBindingSchema.extend({contentType:z110.string().min(1),byteSize:z110.int().positive().max(67108864),registeredOrigin:z110.string().min(1),executionClass:z110.enum(["LIVE","TEST_ONLY"]).nullable()});var CompositionVersionSchema=CompositionScopeSchema.extend({id:z110.uuid(),compositionId:z110.uuid(),projectId:z110.uuid(),version:z110.int().positive(),previousVersionId:z110.uuid().nullable(),basis:CompositionBasisPinSchema,content:CompositionContentSchema,inputs:z110.array(CompositionInputFactSchema).min(3).max(64),fingerprint:sha15,createdByPrincipalId:z110.uuid(),createdAt:z110.iso.datetime({offset:true})}).refine(v=>v.version===1===(v.previousVersionId===null));var CompositionReceiptSchema=z110.strictObject({semanticStatus:z110.literal("SUCCESS"),version:CompositionVersionSchema,productionRevision:z110.int().positive()});var CompositionViewSchema=z110.strictObject({version:CompositionVersionSchema,isCurrent:z110.boolean(),basisStatus:z110.enum(["CURRENT","STALE"]),inputStatus:z110.enum(["AVAILABLE","UNAVAILABLE"]),byteReadback:z110.literal("NOT_CHECKED")});var CompositionPageSchema=z110.strictObject({items:z110.array(CompositionViewSchema).max(100),hasMore:z110.boolean(),nextBeforeVersion:z110.int().positive().nullable()});var CompositionDependencyManifestSchema=z110.object({dependencies:z110.record(z110.string(),z110.string())});var CompositionDependencyLockSchema=z110.object({lockfileVersion:z110.literal(3),packages:z110.record(z110.string(),z110.object({version:z110.string().optional(),integrity:z110.string().optional(),dependencies:z110.record(z110.string(),z110.string()).optional()}))});var HyperframeLegacyRenderProfileSchema=z111.strictObject({id:z111.literal("HYPERFRAME_1080P30_FULL_PAINT_V1"),adapter:z111.literal("native-hyperframe-v1"),engine:z111.literal("0.8.134"),producer:z111.literal("0.8.134"),gsap:z111.literal("3.15.0"),node:z111.string().min(1).max(80),browser:z111.string().min(1).max(160),browserSha256:z111.string().regex(/^[0-9a-f]{64}$/),ffmpeg:z111.string().min(1).max(240),maxFrames:z111.literal(360),timeoutMs:z111.literal(6e5),maxRssBytes:z111.literal(3221225472),maxScratchBytes:z111.literal(3221225472),maxOutputBytes:z111.literal(134217728),maxCpuMs:z111.literal(6e5),capture:z111.literal("PNG_SOFTWARE_SCREENSHOT_FULL_PAINT"),encode:z111.literal("H264_YUV420P_CRF18_THREADS2_NO_AUDIO")});var HyperframeCachedRenderProfileSchema=HyperframeLegacyRenderProfileSchema.extend({id:z111.literal("HYPERFRAME_1080P30_FRAME_CACHE_V2"),adapter:z111.literal("native-hyperframe-cache-v2"),encode:z111.literal("H264_YUV420P_CRF18_VERYFAST_THREADS2_NO_AUDIO")});var HyperframeRenderProfileSchema=z111.discriminatedUnion("id",[HyperframeLegacyRenderProfileSchema,HyperframeCachedRenderProfileSchema]);var CompositionRenderStartSchema=CompositionGetSchema.extend({versionId:z111.uuid(),fingerprint:z111.string().regex(/^[0-9a-f]{64}$/),expectedProductionRevision:z111.int().positive(),profileId:z111.enum(["HYPERFRAME_1080P30_FULL_PAINT_V1","HYPERFRAME_1080P30_FRAME_CACHE_V2","HYPERFRAME_RGBA_PNG30_FULL_PAINT_V1"]),idempotencyKey:z111.string().trim().min(1).max(200),deviceId:z111.uuid().toLowerCase().optional()});var CompositionRenderGetSchema=CompositionScopeSchema.extend({renderId:z111.uuid()});var CompositionRenderManifestSchema=z111.strictObject({schemaVersion:z111.literal(1),version:CompositionVersionSchema,profile:HyperframeRenderProfileSchema,firstFrame:z111.literal(0),frameCount:z111.int().min(1).max(360)}).superRefine((m,ctx)=>{if(m.frameCount!==m.version.content.clock.frameCount||m.version.inputs.reduce((n,i)=>n+i.byteSize,0)>134217728)ctx.addIssue({code:"custom",message:"Exact frame count and aggregate input budget required"})});var CompositionRenderReceiptSchema=z111.strictObject({semanticStatus:z111.literal("ACCEPTED"),renderId:z111.uuid(),runtimeJobId:z111.uuid(),compositionVersionId:z111.uuid(),manifestFingerprint:z111.string().regex(/^[0-9a-f]{64}$/),productionRevision:z111.int().positive()});var CompositionRenderTechnicalSchema=z111.strictObject({width:z111.literal(1920),height:z111.literal(1080),frameRate:z111.literal(30),frameCount:z111.int().min(1).max(360),durationMs:z111.number().positive(),contentType:z111.literal("video/mp4"),videoCodec:z111.literal("h264"),pixelFormat:z111.literal("yuv420p"),hasAudio:z111.literal(false),fullDecode:z111.literal(true),checksumSha256:z111.string().regex(/^[0-9a-f]{64}$/),byteSize:z111.int().min(1).max(134217728),decodedFramesSha256:z111.string().regex(/^[0-9a-f]{64}$/)});var CompositionRenderResourcesSchema=z111.strictObject({sampleIntervalMs:z111.literal(100),sampledTreePeakRssBytes:z111.int().nonnegative(),sampledTreeCpuMs:z111.number().nonnegative(),observedPids:z111.int().nonnegative(),scratchPeakBytes:z111.int().nonnegative(),wallMs:z111.number().nonnegative(),processGroupCleaned:z111.literal(true)});import{z as z112}from"zod";var HyperframeAlphaRenderProfileSchema=HyperframeLegacyRenderProfileSchema.extend({id:z112.literal("HYPERFRAME_RGBA_PNG30_FULL_PAINT_V1"),adapter:z112.literal("native-hyperframe-alpha-v1"),encode:z112.literal("RGBA_PNG_SEQUENCE_30_V1"),maxOutputBytes:z112.literal(67108864),maxDecodedBytes:z112.literal(536870912)});var CompositionFrameRenderManifestSchema=z112.strictObject({...CompositionRenderManifestSchema.shape,schemaVersion:z112.literal(2),profile:HyperframeAlphaRenderProfileSchema}).superRefine((m,context)=>{const c=m.version.content;if(m.frameCount!==c.clock.frameCount||m.version.inputs.reduce((n,i)=>n+i.byteSize,0)>134217728||c.role!=="VISUAL_LAYER"||c.viewport.width>1920||c.viewport.height>1920||c.viewport.width*c.viewport.height>1920*1080||c.viewport.width*c.viewport.height*m.frameCount*4>m.profile.maxDecodedBytes||c.clock.numerator!==30||c.clock.denominator!==1)context.addIssue({code:"custom",message:"Qualified CODE alpha geometry/role/clock/decoded budget mismatch"})});var CompositionFrameTechnicalSchema=z112.strictObject({profileId:z112.literal("RGBA_PNG_SEQUENCE_30_V1"),width:z112.int().min(1).max(1920),height:z112.int().min(1).max(1920),frameRate:z112.literal(30),frameCount:z112.int().min(1).max(360),alpha:z112.literal("STRAIGHT_RGBA"),fullDecode:z112.literal(true),frames:z112.array(z112.strictObject({ordinal:z112.int().min(0).max(359),checksumSha256:z112.string().regex(/^[0-9a-f]{64}$/),byteSize:z112.int().min(1).max(16777216)})).min(1).max(360)}).superRefine((value2,context)=>{if(value2.frames.length!==value2.frameCount||value2.frames.some((f,i)=>f.ordinal!==i)||value2.width*value2.height>1920*1080||value2.width*value2.height*value2.frameCount*4>536870912||value2.frames.reduce((n,f)=>n+f.byteSize,0)>67108864)context.addIssue({code:"custom",message:"CODE frame order/geometry/byte budget mismatch"})});var CompositionFrameRenderOutputSchema=z112.strictObject({sequence:VisualFrameSequenceSchema,technical:CompositionFrameTechnicalSchema,resources:CompositionRenderResourcesSchema}).superRefine((output,context)=>{if(output.sequence.width!==output.technical.width||output.sequence.height!==output.technical.height||output.sequence.frameCount!==output.technical.frameCount||output.sequence.frames.some((frame2,i)=>frame2.ordinal!==output.technical.frames[i]?.ordinal||frame2.checksumSha256!==output.technical.frames[i]?.checksumSha256||frame2.byteSize!==output.technical.frames[i]?.byteSize))context.addIssue({code:"custom",message:"CODE frame output must identify the exact native sequence"})});var CompositionRenderManifestReaderSchema=z113.discriminatedUnion("schemaVersion",[CompositionRenderManifestSchema,CompositionFrameRenderManifestSchema]);var CompositionRenderViewSchema=z113.strictObject({sourceIdentity:z113.strictObject({tenantId:z113.uuid(),projectId:z113.uuid(),productionId:z113.uuid(),compositionId:z113.uuid(),versionId:z113.uuid(),fingerprint:z113.string().regex(/^[0-9a-f]{64}$/),shotId:z113.uuid().nullable(),role:z113.enum(["PRIMARY_VISUAL","VISUAL_LAYER"])}).optional(),frameOutput:CompositionFrameRenderOutputSchema.optional(),receipt:CompositionRenderReceiptSchema,lifecycle:z113.string().min(1).max(80),cancellationRequested:z113.boolean(),failureClassification:z113.string().min(1).max(80).nullable(),output:z113.strictObject({artifactId:z113.uuid(),representationId:z113.uuid(),technical:CompositionRenderTechnicalSchema,resources:CompositionRenderResourcesSchema}).nullable()}).superRefine((view,context)=>{if(view.sourceIdentity&&view.sourceIdentity.versionId!==view.receipt.compositionVersionId)context.addIssue({code:"custom",message:"Render source identity must bind the admitted exact version"});if(view.frameOutput&&view.output!==null)context.addIssue({code:"custom",message:"CODE frame output must match its render Production and exclude an MP4 output"})});var CompositionRenderCancellationSchema=z113.strictObject({cancellationRequested:z113.boolean()});var identity2=z114.strictObject({artifactId:LocalIdSchema,representationId:LocalIdSchema});var ProcessorCompositionAllocationSchema=z114.strictObject({sequence:identity2,frames:z114.array(identity2).min(1).max(360)}).refine(({sequence,frames})=>{const entries=[sequence,...frames];return new Set(entries.map(entry=>entry.artifactId)).size===entries.length&&new Set(entries.map(entry=>entry.representationId)).size===entries.length});var processorCompositionFields={manifest:CompositionRenderManifestReaderSchema,allocation:ProcessorCompositionAllocationSchema.nullable()};var base={processor:z114.literal("COMPOSITION_RENDER"),resources:CompositionRenderResourcesSchema};var ProcessorCompositionVideoEvidenceSchema=z114.strictObject({...base,format:z114.literal("MP4"),technical:CompositionRenderTechnicalSchema});var ProcessorCompositionSequenceEvidenceSchema=z114.strictObject({...base,format:z114.literal("RGBA_SEQUENCE"),technical:CompositionFrameTechnicalSchema,sequence:VisualFrameSequenceSchema});var ProcessorCompositionEvidenceSchema=z114.discriminatedUnion("format",[ProcessorCompositionVideoEvidenceSchema,ProcessorCompositionSequenceEvidenceSchema]);import{z as z118}from"zod";import{z as z115}from"zod";var VisualSequenceScopeSchema=z115.strictObject({tenantId:TenantIdSchema,projectId:ProjectIdSchema});var RegisterVisualSequenceSchema=VisualSequenceScopeSchema.extend({deviceId:z115.uuid().toLowerCase().optional(),productionId:ProductionIdSchema.nullable(),idempotencyKey:z115.string().trim().min(1).max(200),width:z115.int().min(1).max(1920),height:z115.int().min(1).max(1920),frameArtifactIds:z115.array(ArtifactIdSchema).min(1).max(360)}).refine(v=>v.width*v.height<=1920*1080&&new Set(v.frameArtifactIds).size===v.frameArtifactIds.length,"Sequence requires bounded geometry and unique ordered frame Artifacts");var VisualSequenceGetSchema=VisualSequenceScopeSchema.extend({artifactId:ArtifactIdSchema});var LegacyVisualSequenceRegistrationSchema=z115.strictObject(RegisterVisualSequenceSchema.shape).omit({deviceId:true}).refine(input=>RegisterVisualSequenceSchema.safeParse(input).success);var VisualSequenceRegistrationAdmissionSchema=z115.strictObject({semanticStatus:z115.literal("ACCEPTED"),requestId:z115.uuid(),runtimeJobId:z115.uuid(),runtimeProductionId:ProductionIdSchema,operationId:OperationIdSchema,artifactId:ArtifactIdSchema,representationId:z115.uuid()});var VisualSequenceViewSchema=z115.strictObject({sequence:VisualFrameSequenceSchema,freshness:z115.enum(["CURRENT_BASIS","STALE_BASIS"]),staleReasons:z115.array(z115.enum(["SEQUENCE_UNAVAILABLE","FRAME_UNAVAILABLE"])).max(2),createdAt:z115.iso.datetime({offset:true})});var VisualSequenceQuerySchema=VisualSequenceScopeSchema.extend({limit:QueryLimitSchema,next:ContinuationSchema.optional()});var VisualSequencePageSchema=z115.strictObject({items:z115.array(VisualSequenceViewSchema).max(100),page:QueryPageInfoSchema});var{checksumSha256:_checksum,...manifestShape}=VisualFrameSequenceSchema.shape;var VisualSequenceManifestSchema=z115.strictObject(manifestShape).superRefine((value2,context)=>{if(!VisualFrameSequenceSchema.safeParse({...value2,checksumSha256:"0".repeat(64)}).success)context.addIssue({code:"custom",message:"Invalid canonical frame sequence manifest"})});import{z as z116}from"zod";var TranscribeAudioRecipeSchema=z116.strictObject({processor:z116.literal("TRANSCRIBE_AUDIO"),source:ObservationSourceSchema.extend({contentType:z116.literal("audio/wav")}),identity:LocalWhisperIdentitySchema});var TranscribeAudioEvidenceSchema=z116.strictObject({processor:z116.literal("TRANSCRIBE_AUDIO"),identity:LocalWhisperIdentitySchema,transcript:TranscriptSchema.refine(transcript=>transcript.timing==="UNAVAILABLE"),inputPcmSha256:LocalDigestSchema,inputPcmByteSize:z116.int().min(44).max(1920044)});var QwenAsrRecipeSchema=z116.strictObject({processor:z116.literal("TRANSCRIBE_EXTERNAL_QWEN"),observationId:LocalIdSchema,quoteFingerprint:LocalDigestSchema,credential:QwenDeviceCredentialIdentitySchema,source:TranscribeAudioRecipeSchema.shape.source,parameters:z116.strictObject({context:z116.string().max(2e3).refine(value2=>!value2.includes("\0")).optional(),language:z116.string().regex(/^[a-zA-Z][a-zA-Z0-9-]{1,19}$/).optional(),enable_itn:z116.boolean().optional()})});var asrTokens=z116.int().min(0).max(1e7).optional();var QwenAsrEvidenceSchema=z116.strictObject({processor:z116.literal("TRANSCRIBE_EXTERNAL_QWEN"),providerRequestId:z116.string().regex(/^[A-Za-z0-9_.:-]{1,500}$/),model:z116.literal("qwen3-asr-flash-2026-02-10"),usage:z116.strictObject({seconds:z116.int().min(0).max(60).optional(),prompt_tokens:asrTokens,completion_tokens:asrTokens,total_tokens:asrTokens}),transcript:TranscriptSchema.options[0]});import{z as z117}from"zod";var CpuSpeechRecipeSchema=CpuSpeechInputSchema.extend({processor:z117.literal("SPEECH_SYNTHESIZE_CPU"),identity:CpuSpeechIdentitySchema,voiceProfile:VoiceProfileUseSchema}).refine(v=>v.voiceProfile.language===v.language);var CpuSpeechEvidenceSchema=SpeechSynthesisEvidenceSchema.extend({processor:z117.literal("SPEECH_SYNTHESIZE_CPU"),sourceMedia:z117.strictObject({sampleRateHz:z117.literal(24e3),audioChannels:z117.literal(1),sampleCount:z117.int().min(2400).max(144e4)})});var sourceReference=z118.strictObject({artifactId:LocalIdSchema,representationId:LocalIdSchema,byteSize:MediaObjectVersionSchema.shape.byteSize,checksumSha256:LocalDigestSchema,contentType:z118.string().min(1).max(100)});var source2=sourceReference.extend({contentType:z118.literal("video/mp4")});var ReferencePreviewRecipeSchema=z118.strictObject({processor:z118.literal("REFERENCE_PREVIEW"),briefVersionId:LocalIdSchema,source:sourceReference.extend({contentType:z118.enum(["image/png","image/jpeg","image/webp"]),byteSize:z118.int().positive().max(8*1024*1024)})});var normalize=z118.strictObject({processor:z118.literal("IMPORTED_VISUAL_NORMALIZE"),source:source2,request:ImportedVisualNormalizationRequestSchema}).refine(({request,source:source6})=>request.source.byteSize===source6.byteSize&&request.source.checksumSha256===source6.checksumSha256,"Original representation must match the normalization request");var audio=z118.strictObject({processor:z118.literal("SOURCE_SYNC_AUDIO"),source:source2,input:ImportedVisualSourceInputSchema,extraction:ImportedSynchronousAudioExtractionSchema}).refine(value2=>value2.source.checksumSha256===value2.input.checksumSha256&&value2.source.checksumSha256===value2.extraction.originalChecksumSha256&&value2.source.representationId===value2.extraction.originalRepresentationId&&value2.source.artifactId===value2.extraction.originalArtifactId&&value2.source.byteSize===value2.input.byteSize);var temporal=z118.strictObject({processor:z118.literal("TEMPORAL_SAMPLE"),source:source2,plan:TemporalSamplingPlanSchema}).refine(value2=>value2.source.checksumSha256===value2.plan.source.checksumSha256&&value2.source.representationId===value2.plan.source.representationId&&value2.source.artifactId===value2.plan.source.artifactId&&value2.source.byteSize===value2.plan.source.byteSize);var delivery=z118.strictObject({processor:z118.literal("DELIVERY_VALIDATE"),recipe:LocalMediaRecipeSchema.refine(value2=>value2.family==="FINAL_RENDER"),target:DeliveryTargetSchema.pick({representationId:true,checksumSha256:true,byteSize:true,artifactId:true}).extend({contentType:z118.literal("video/mp4")}),policy:z118.strictObject({requiredAudio:z118.boolean(),requiredCaptions:z118.boolean(),requiredGraphics:z118.boolean()}),engineVersion:z118.string().min(1).max(200),sources:z118.array(sourceReference).min(1).max(512),manifestBasisFingerprint:LocalDigestSchema}).refine(({sources,target:target3})=>new Set([target3.representationId,...sources.map(v=>v.representationId)]).size===sources.length+1);var composition=z118.strictObject({processor:z118.literal("COMPOSITION_RENDER"),...processorCompositionFields,sources:z118.array(sourceReference).min(1).max(64)}).refine(({manifest,allocation,sources})=>{const inputs=manifest.version.inputs;return(manifest.schemaVersion===1?allocation===null:allocation?.frames.length===manifest.frameCount)&&new Set(inputs.map(input=>input.representationId)).size===sources.length&&new Set(sources.map(source6=>source6.representationId)).size===sources.length&&inputs.every(input=>sources.some(source6=>source6.representationId===input.representationId&&source6.artifactId===input.artifactId&&source6.checksumSha256===input.checksumSha256&&source6.byteSize===input.byteSize&&source6.contentType===input.contentType))});var directOriginal=z118.strictObject({processor:z118.literal("IMPORT_ORIGINAL"),command:DirectOriginalCommandSchema,object:MediaObjectVersionSchema.extend({role:z118.literal("SOURCE")})}).refine(({command:{input},object})=>input.tenantId===object.tenantId&&input.projectId===object.projectId&&input.source.checksumSha256===object.checksumSha256&&input.source.byteSize===object.byteSize);var projectSource=z118.strictObject({processor:z118.literal("IMPORT_PROJECT_SOURCE"),metadata:SourceInputMetadataSchema.extend({idempotencyKey:z118.string().trim().min(1).max(200)}),projectId:LocalIdSchema,object:MediaObjectVersionSchema.extend({role:z118.literal("SOURCE")})}).refine(({metadata,projectId,object})=>metadata.tenantId===object.tenantId&&projectId===object.projectId&&object.byteSize<=8*1024*1024&&(metadata.kind==="REFERENCE_VIDEO"?metadata.contentType==="video/mp4":metadata.kind==="REFERENCE_IMAGE"&&["image/png","image/jpeg","image/webp"].includes(metadata.contentType)));var visualSequence=z118.strictObject({processor:z118.literal("REGISTER_VISUAL_SEQUENCE"),input:RegisterVisualSequenceSchema,manifest:VisualSequenceManifestSchema,sources:z118.array(sourceReference).min(1).max(360)}).refine(({input,manifest,sources})=>input.tenantId===manifest.tenantId&&input.projectId===manifest.projectId&&input.productionId===manifest.productionId&&new Set(sources.map(source6=>source6.representationId)).size===sources.length&&manifest.frames.every(frame2=>sources.some(source6=>source6.artifactId===frame2.artifactId&&source6.representationId===frame2.representationId&&source6.byteSize===frame2.byteSize&&source6.checksumSha256===frame2.checksumSha256&&source6.contentType==="image/png")));var TenantProcessorRecipeSchema=z118.discriminatedUnion("processor",[normalize,audio,temporal,delivery,composition,directOriginal,projectSource,ReferencePreviewRecipeSchema,LocalLibraryInspectRecipeSchema,LocalLibraryPublishRecipeSchema,visualSequence,SpeechSynthesisRecipeSchema,CpuSpeechRecipeSchema,QwenSpeechRecipeSchema,TranscribeAudioRecipeSchema,QwenAsrRecipeSchema,QwenKeyframeRecipeSchema,QwenVideoRecipeSchema]);var TenantProcessorWorkSchema=TenantMediaWorkSchema.omit({audioRequired:true,renderProfileDigest:true}).extend({protocol:z119.literal("NVS_TENANT_PROCESSOR_V1"),family:z119.enum(["ARTIFACT_INGEST","PLANNING_MATERIALIZE","TEMPORAL_SAMPLE","DELIVERY_VALIDATE","COMPOSITION_RENDER","AUDIO_GENERATE","OBSERVE","KEYFRAME_GENERATE","VIDEO_GENERATE"]),processor:TenantProcessorKindSchema,recipeFingerprint:LocalDigestSchema,toolchainFingerprint:LocalDigestSchema,externalGeneration:ExternalGenerationReservationMarkerSchema.optional()}).refine(value2=>processorFamilies[value2.processor]===value2.family&&(value2.processor==="KEYFRAME_GENERATE"||value2.processor==="VIDEO_GENERATE")===!!value2.externalGeneration);var TenantComputeWorkSchema=z119.discriminatedUnion("protocol",[TenantMediaWorkSchema,TenantProcessorWorkSchema]);var importedNormalizationValidationProfile={processor:"IMPORTED_VISUAL_NORMALIZE",protocol:"NVS_TENANT_PROCESSOR_REPORT_V1",inspection:"IMPORTED_MP4_AND_POSTER_READBACK_V1"};var ClaimTenantProcessorSchema=LocalProjectScopeSchema.extend({requestId:LocalIdSchema});var TenantProcessorAssignmentSchema=z119.strictObject({work:TenantProcessorWorkSchema,recipe:TenantProcessorRecipeSchema,lease:LocalExecutionLeaseSchema,toolchain:LocalToolchainSchema}).superRefine(({work,recipe,lease,toolchain},ctx)=>{const selected=work.processor==="SPEECH_SYNTHESIZE_CPU"?processorToolchain(toolchain,work.processor):toolchain;if(!selected||toolchain.profile.kind==="AUDIO_MEDIA_V1"&&work.processor!=="SPEECH_SYNTHESIZE_CPU"||canonicalLocalJson(selected)!==canonicalLocalJson(toolchain))ctx.addIssue({code:"custom",message:"Exact processor media profile required"});const target3=lease.target;if((recipe.processor==="LOCAL_MEDIA_INSPECT"||recipe.processor==="LOCAL_MEDIA_PUBLISH")&&(recipe.reference.tenantId!==work.tenantId||recipe.reference.projectId!==work.projectId||recipe.reference.deviceId!==work.target.deviceId||recipe.processor==="LOCAL_MEDIA_PUBLISH"&&recipe.destination.kind==="ORIGINAL"&&recipe.destination.command.input.productionId.toLowerCase()!==work.productionId))ctx.addIssue({code:"custom",message:"Local file reference must match native target and scope"});if(recipe.processor!==work.processor||lease.tenantId!==work.tenantId||lease.projectId!==work.projectId||lease.productionId!==work.productionId||lease.runtimeJobId!==work.runtimeJobId||lease.toolchainFingerprint!==work.toolchainFingerprint||target3.kind!=="DEVICE"||!sameDeviceAuthority(target3,work.target))ctx.addIssue({code:"custom",message:"Assignment must match the frozen device work"})});var TenantProcessorClaimReceiptSchema=z119.strictObject({found:z119.boolean(),assignment:TenantProcessorAssignmentSchema.nullable()});var StageTenantProcessorOutputSchema=LocalLeaseBindingSchema.extend({requestId:LocalIdSchema,role:z119.enum(["VIDEO","POSTER","AUDIO","FRAME","SHEET","MANIFEST"]),ordinal:z119.int().nonnegative().max(359).default(0),checksumSha256:LocalDigestSchema,byteSize:MediaObjectVersionSchema.shape.byteSize});var PrepareTenantProcessorReportSchema=LocalLeaseBindingSchema.extend({requestId:LocalIdSchema,outputVersionIds:z119.array(LocalIdSchema).max(362).refine(ids=>ids.length===new Set(ids).size)});var TenantProcessorReportRequestSchema=LocalLeaseBindingSchema.extend({requestId:LocalIdSchema,validationRequestId:LocalIdSchema,work:TenantProcessorWorkSchema,outputs:z119.array(MediaObjectVersionSchema).max(362)});var poster=z119.strictObject({checksumSha256:LocalDigestSchema,byteSize:z119.int().min(1).max(2*1024*1024),width:z119.int().min(1).max(320),height:z119.int().min(1).max(320)});var TenantProcessorEvidenceSchema=z119.discriminatedUnion("processor",[LocalLibraryInspectEvidenceSchema,LocalLibraryPublishEvidenceSchema,z119.strictObject({processor:z119.literal("IMPORTED_VISUAL_NORMALIZE"),receipt:ImportedVisualNormalizationReceiptSchema,posterEvidence:poster}),z119.strictObject({processor:z119.literal("SOURCE_SYNC_AUDIO"),provenance:ImportedSynchronousAudioSourceSchema}),z119.strictObject({processor:z119.literal("TEMPORAL_SAMPLE"),manifest:TemporalEvidenceManifestSchema}),z119.strictObject({processor:z119.literal("DELIVERY_VALIDATE"),checks:DeliveryPhysicalChecksSchema,technical:FinalRenderTechnicalSchema.nullable()}),ProcessorCompositionEvidenceSchema,SpeechSynthesisEvidenceSchema,CpuSpeechEvidenceSchema,QwenSpeechEvidenceSchema,TranscribeAudioEvidenceSchema,QwenAsrEvidenceSchema,QwenKeyframeEvidenceSchema,QwenVideoEvidenceSchema,z119.strictObject({processor:z119.literal("REFERENCE_PREVIEW"),image:z119.strictObject({checksumSha256:LocalDigestSchema,byteSize:z119.int().positive().max(referenceThumbnailProfile.maxBytes),width:z119.int().positive().max(referenceThumbnailProfile.maxDimension),height:z119.int().positive().max(referenceThumbnailProfile.maxDimension)})}),z119.strictObject({processor:z119.literal("IMPORT_ORIGINAL"),metadata:ImportedVisualSourceMetadataSchema}),z119.strictObject({processor:z119.literal("IMPORT_PROJECT_SOURCE"),validated:z119.strictObject({checksumSha256:LocalDigestSchema,byteSize:z119.int().positive().max(8*1024*1024),width:z119.int().positive().max(4096),height:z119.int().positive().max(4096),video:ImportedVisualSourceMetadataSchema.optional()})}),z119.strictObject({processor:z119.literal("REGISTER_VISUAL_SEQUENCE"),evidence:z119.strictObject({checksumSha256:VisualFrameSequenceSchema.shape.checksumSha256,width:VisualFrameSequenceSchema.shape.width,height:VisualFrameSequenceSchema.shape.height,frames:VisualFrameSequenceSchema.shape.frames,byteSize:z119.int().positive().max(2*1024*1024)})})]);var TenantProcessorReportBodySchema=TenantProcessorReportRequestSchema.extend({schemaVersion:z119.literal(1),evidence:TenantProcessorEvidenceSchema}).superRefine(({work,outputs,evidence:evidence2,...binding},ctx)=>{if(work.tenantId!==binding.tenantId||work.projectId!==binding.projectId||work.productionId!==binding.productionId||work.runtimeJobId!==binding.runtimeJobId||work.toolchainFingerprint!==binding.toolchainFingerprint||evidence2.processor!==work.processor||new Set(outputs.map(value2=>value2.versionId)).size!==outputs.length||outputs.some(object=>object.tenantId!==work.tenantId||object.projectId!==work.projectId)||!matchesEvidence(outputs,evidence2))ctx.addIssue({code:"custom",message:"Report must bind the exact processor and committed media versions"})});function matchesEvidence(outputs,evidence2){const matches=(index,role,expected)=>{const output=outputs[index];return output?.role===role&&output.checksumSha256===expected.checksumSha256&&output.byteSize===expected.byteSize};switch(evidence2.processor){case"REFERENCE_PREVIEW":return outputs.length===1&&matches(0,"POSTER",evidence2.image);case"IMPORTED_VISUAL_NORMALIZE":return outputs.length===2&&matches(0,"VIDEO",evidence2.receipt.output)&&matches(1,"POSTER",evidence2.posterEvidence);case"SOURCE_SYNC_AUDIO":return outputs.length===1&&matches(0,"AUDIO",{checksumSha256:evidence2.provenance.wavChecksumSha256,byteSize:evidence2.provenance.wavByteSize});case"SPEECH_SYNTHESIZE":case"SPEECH_SYNTHESIZE_CPU":case"SPEECH_EXTERNAL_QWEN":return outputs.length===2&&matches(0,"AUDIO",evidence2.source)&&matches(1,"AUDIO",evidence2.normalized);case"TEMPORAL_SAMPLE":{const frames=evidence2.manifest.frames;return outputs.length===frames.length+2&&frames.every((value2,index)=>matches(index,"FRAME",value2))&&matches(frames.length,"SHEET",evidence2.manifest.sheet)&&outputs.at(-1)?.role==="MANIFEST"}case"DELIVERY_VALIDATE":case"TRANSCRIBE_AUDIO":case"TRANSCRIBE_EXTERNAL_QWEN":case"LOCAL_MEDIA_INSPECT":case"LOCAL_MEDIA_PUBLISH":case"IMPORT_ORIGINAL":case"IMPORT_PROJECT_SOURCE":return outputs.length===0;case"REGISTER_VISUAL_SEQUENCE":return outputs.length===1&&matches(0,"MANIFEST",evidence2.evidence);case"KEYFRAME_GENERATE":return outputs.length===1&&matches(0,"FRAME",evidence2.image);case"VIDEO_GENERATE":return outputs.length===2&&matches(0,"VIDEO",evidence2.video)&&matches(1,"POSTER",evidence2.poster);case"COMPOSITION_RENDER":if(evidence2.format==="MP4")return outputs.length===1&&matches(0,"VIDEO",evidence2.technical);return outputs.length===evidence2.technical.frames.length+1&&evidence2.technical.frames.every((value2,index)=>matches(index,"FRAME",value2))&&outputs.at(-1)?.role==="MANIFEST"&&outputs.at(-1)?.checksumSha256===evidence2.sequence.checksumSha256}}var TenantProcessorReportSchema=TenantProcessorReportBodySchema.safeExtend({reportFingerprint:LocalDigestSchema,signature:z119.string().regex(/^[A-Za-z0-9_-]{86}$/)});var TenantProcessorReceiptQuerySchema=LocalLeaseBindingSchema.extend({requestId:LocalIdSchema});var TenantProcessorStateSchema=z119.strictObject({binding:LocalLeaseBindingSchema,state:z119.enum(["FENCED","PENDING"])});var TenantProcessorFailureSchema=LocalLeaseBindingSchema.extend({code:z119.literal("INVALID_SOURCE")});var TenantProcessorProviderOutcomeSchema=LocalLeaseBindingSchema.extend({outcome:z119.enum(["UNKNOWN","REJECTED","WAITING","INVALID_RESULT"]),providerExecutionId:QwenVideoTaskIdSchema.optional()}).refine(value2=>!["WAITING","INVALID_RESULT"].includes(value2.outcome)||!!value2.providerExecutionId);var TenantProcessorProviderTaskSchema=LocalLeaseBindingSchema.extend({providerExecutionId:QwenVideoTaskIdSchema.optional()});var TenantProcessorInvalidSpeechSchema=LocalLeaseBindingSchema.extend(QwenSpeechEvidenceSchema.pick({providerRequestId:true,audioId:true}).shape);var TenantProcessorReceiptSchema=TenantProcessorReceiptQuerySchema.extend({operationId:TenantProcessorWorkSchema.shape.operationId,reportFingerprint:LocalDigestSchema,result:z119.union([z119.strictObject({sourceArtifactId:LocalIdSchema,representationId:LocalIdSchema,reusedExisting:z119.boolean()}),z119.strictObject({localMediaInspectionId:LocalIdSchema}),z119.strictObject({normalizationId:LocalIdSchema,artifactId:LocalIdSchema,representationId:LocalIdSchema,posterArtifactId:LocalIdSchema,posterRepresentationId:LocalIdSchema}),SourceSyncAudioReceiptSchema,z119.strictObject({generationId:LocalIdSchema,audio:AudioReceiptSchema}),z119.strictObject({observationId:LocalIdSchema}),z119.strictObject({generationId:LocalIdSchema,candidateId:LocalIdSchema,artifactId:LocalIdSchema,representationId:LocalIdSchema}),z119.strictObject({evidenceId:LocalIdSchema,frameSetArtifactId:LocalIdSchema,contactSheetArtifactId:LocalIdSchema}),z119.strictObject({deliveryValidationId:LocalIdSchema,reviewId:LocalIdSchema}),z119.strictObject({renderId:LocalIdSchema,artifactId:LocalIdSchema,representationId:LocalIdSchema}),ImportedVisualOriginalViewSchema,ReadyArtifactRegistrationSchema,z119.strictObject({requestId:LocalIdSchema,artifactId:LocalIdSchema,representationId:LocalIdSchema})])});import{z as z120}from"zod";var LocalLibraryCommandStatusSchema=z120.strictObject({admission:LocalLibraryAdmissionSchema,lifecycle:z120.enum(["READY","WAITING","RUNNING","SUCCEEDED","FAILED","CANCELLED","SUPERSEDED"]),receipt:TenantProcessorReceiptSchema.nullable(),inspection:LocalLibraryInspectionSchema.nullable(),failureSummary:z120.string().max(500).nullable()}).superRefine(({admission,receipt},ctx)=>{if(receipt&&(receipt.tenantId!==admission.tenantId||receipt.projectId!==admission.projectId||receipt.productionId!==admission.productionId||receipt.runtimeJobId!==admission.runtimeJobId||receipt.operationId!==admission.operationId))ctx.addIssue({code:"custom",message:"Original native receipt must match admitted local file work"})});function abortable(promise,signal){if(signal.aborted){void promise.catch(()=>{});return Promise.reject(signal.reason)}return new Promise((resolve,reject)=>{const abort=()=>reject(signal.reason);signal.addEventListener("abort",abort,{once:true});promise.then(resolve,reject).finally(()=>signal.removeEventListener("abort",abort))})}async function boundedResponseBytes(response,limit,signal){const length=response.headers.get("content-length");if(length!==null&&(!/^\d+$/.test(length)||Number(length)>limit)){void response.body?.cancel().catch(()=>{});throw new NativeStudioSdkError("RESPONSE_TOO_LARGE","INTERNAL_OPERATIONAL_FAILURE","UNKNOWN")}if(!response.body)return new Uint8Array;const reader=response.body.getReader();const chunks=[];let size=0;try{while(true){const next=await abortable(reader.read(),signal);if(next.done)break;size+=next.value.byteLength;if(size>limit)throw new NativeStudioSdkError("RESPONSE_TOO_LARGE","INTERNAL_OPERATIONAL_FAILURE","UNKNOWN");chunks.push(next.value)}const result=new Uint8Array(size);let offset2=0;for(const chunk of chunks){result.set(chunk,offset2);offset2+=chunk.byteLength}return result}finally{void reader.cancel().catch(()=>{});reader.releaseLock()}}var failed=()=>new NativeStudioSdkError("MEDIA_IDENTITY_MISMATCH","INTERNAL_OPERATIONAL_FAILURE","NO_WRITE");async function downloadImmutableObject(ticket,options={}){const object=MediaObjectVersionSchema.parse(ticket.object),url=new URL(ticket.endpoint);if(ticket.method!=="GET"||url.pathname!==mediaObjectTransferPath||url.username||url.password||url.search||url.hash||url.protocol!=="https:"&&!(url.protocol==="http:"&&url.hostname==="127.0.0.1"))throw failed();const timeout=AbortSignal.timeout(12e4);const signal=options.signal?AbortSignal.any([options.signal,timeout]):timeout;try{const response=await fetch(url,{headers:{authorization:"Bearer "+ticket.credential},credentials:"omit",redirect:"error",signal});if(response.status!==200||response.headers.get("x-media-object-version")!==object.versionId||response.headers.get("x-content-sha256")!==object.checksumSha256||response.headers.get("content-length")!==String(object.byteSize)){await response.body?.cancel();throw failed()}const bytes=await boundedResponseBytes(response,object.byteSize,signal);if(bytes.byteLength!==object.byteSize||createHash("sha256").update(bytes).digest("hex")!==object.checksumSha256)throw failed();return{bytes,object}}catch{throw failed()}}async function downloadRenderObject(ticket,options){if(ticket.object.role==="SOURCE")throw failed();const result=await downloadImmutableObject(ticket,options);return{...result,contentType:result.object.role==="VIDEO"?"video/mp4":"image/png"}}import{z as z186}from"zod";import{z as z121}from"zod";var OperationTargetSchema=z121.object({type:z121.string().min(1).max(120),id:z121.string().min(1).max(2048),version:z121.int().positive().nullable()});var OperationSummarySchema=z121.object({humanLinks:HumanLinksSchema.optional(),id:OperationIdSchema,productionId:ProductionIdSchema,semanticStatus:InterfaceSemanticStatusSchema,targets:z121.array(OperationTargetSchema).max(100),work:WorkSummarySchema,blockers:z121.array(z121.string().min(1).max(1e3)).max(100),nextActions:z121.array(NextActionSchema).max(50),startedAt:z121.iso.datetime({offset:true}),updatedAt:z121.iso.datetime({offset:true})});import{z as z124}from"zod";import{z as z123}from"zod";import{z as z122}from"zod";var sha16=z122.string().regex(/^[0-9a-f]{64}$/);var DeliveryManifestBasisSchema=z122.strictObject({schemaVersion:z122.literal(1),evaluatorVersion:z122.literal("DELIVERY_V1"),target:DeliveryTargetSchema,policyVersionId:z122.uuid(),policyVersion:z122.int().positive(),policy:DeliveryPolicySchema,policyFingerprint:sha16,finalRenderRuntimeJobId:z122.uuid(),finalRenderManifest:FinalRenderManifestReaderSchema,finalRenderTechnical:FinalRenderTechnicalSchema,roughCutReview:RoughCutReviewRecordSchema,artifacts:z122.array(z122.strictObject({artifactId:z122.uuid(),family:z122.string().min(1).max(100),origin:z122.string().min(1).max(100),checksumSha256:sha16})).min(1).max(2e3),relations:z122.array(z122.strictObject({id:z122.uuid(),sourceArtifactId:z122.uuid(),targetArtifactId:z122.uuid(),relationType:z122.string().min(1).max(100)})).max(4e3)}).superRefine((basis,ctx)=>{const t=basis.target,m=basis.finalRenderManifest;if(t.selectionId!==m.selection.id||t.selectionVersion!==m.selectionVersion||t.timelineVersionId!==m.timeline.id||t.timelineFingerprint!==m.timeline.fingerprint||t.tenantId!==m.timeline.tenantId||t.projectId!==m.timeline.projectId||t.productionId!==m.timeline.productionId||t.executionClass!==m.timeline.executionClass||t.checksumSha256!==basis.finalRenderTechnical.checksumSha256||t.byteSize!==basis.finalRenderTechnical.byteSize||basis.finalRenderTechnical.hasAudio!==m.profile.hasAudio||basis.roughCutReview.id!==m.selection.reviewId||basis.roughCutReview.basisFingerprint!==m.selection.basisFingerprint||!basis.artifacts.some(a=>a.artifactId===t.artifactId&&a.checksumSha256===t.checksumSha256)||new Set(basis.artifacts.map(a=>a.artifactId)).size!==basis.artifacts.length||new Set(basis.relations.map(r=>r.id)).size!==basis.relations.length||basis.relations.some(r=>!basis.artifacts.some(a=>a.artifactId===r.sourceArtifactId)||!basis.artifacts.some(a=>a.artifactId===r.targetArtifactId)))ctx.addIssue({code:"custom",message:"Manifest must identify exact render, Review-2 and provenance"})});var ProductionDeliveryManifestSchema=DeliveryManifestBasisSchema.safeExtend({reviewId:z122.uuid(),productionRevision:z122.int().positive(),completedAt:z122.iso.datetime({offset:true})});var DeliveryManifestGetSchema=TimelineScopeSchema.extend({manifestId:z122.uuid()});var RegisteredDeliveryManifestSchema=z122.strictObject({link:DeliveryManifestLinkSchema,body:ProductionDeliveryManifestSchema}).refine(v=>v.link.reviewId===v.body.reviewId&&v.link.policyFingerprint===v.body.policyFingerprint&&Object.keys(DeliveryTargetSchema.shape).every(key10=>v.link.target[key10]===v.body.target[key10]),"Manifest registration must match exact body");var sha17=z123.string().regex(/^[0-9a-f]{64}$/);var mutation=TimelineScopeSchema.extend({expectedProductionRevision:z123.int().positive(),idempotencyKey:z123.string().trim().min(1).max(200)});var ConfigureDeliveryPolicySchema=mutation.extend({expectedPolicyVersion:z123.int().nonnegative(),policy:DeliveryPolicyInputSchema});var DeliveryPolicyVersionSchema=TimelineScopeSchema.extend({id:z123.uuid(),projectId:z123.uuid(),version:z123.int().positive(),policy:DeliveryPolicySchema,policyFingerprint:sha17,createdByPrincipalId:z123.uuid(),createdAt:z123.iso.datetime({offset:true})});var DeliveryPolicyReceiptSchema=z123.strictObject({policy:DeliveryPolicyVersionSchema,productionRevision:z123.int().positive()});var LegacyStartDeliveryValidationSchema=mutation.extend({target:DeliveryTargetSchema,expectedPolicyVersion:z123.int().nonnegative()}).refine(v=>v.target.tenantId===v.tenantId&&v.target.productionId===v.productionId,"Exact delivery target must match command scope");var StartDeliveryValidationSchema=LegacyStartDeliveryValidationSchema.safeExtend({deviceId:z123.uuid().toLowerCase().optional()});var DeliveryValidationGetSchema=TimelineScopeSchema.extend({validationId:z123.uuid()});var DecideDeliveryApprovalSchema=mutation.extend({validationId:z123.uuid(),reviewId:z123.uuid(),target:DeliveryTargetSchema,policyFingerprint:sha17,action:z123.enum(["APPROVE","REJECT"])}).refine(v=>v.target.tenantId===v.tenantId&&v.target.productionId===v.productionId,"Exact approval target must match command scope");var DeliveryAdmissionSchema=z123.strictObject({humanLinks:HumanLinksSchema.optional(),semanticStatus:z123.literal("ACCEPTED"),validationId:z123.uuid(),runtimeJobId:z123.uuid(),operationId:z123.string().min(1),target:DeliveryTargetSchema,policyVersionId:z123.uuid(),policyVersion:z123.int().positive(),policyFingerprint:sha17,manifestBasisFingerprint:sha17,evaluatorVersion:z123.literal("DELIVERY_V1"),productionRevision:z123.int().positive()});var DeliveryFindingSchema=z123.strictObject({id:z123.uuid(),reviewId:z123.uuid(),target:DeliveryTargetSchema,key:DeliveryCheckKeySchema,detail:z123.string().trim().min(1).max(1e3),blocking:z123.literal(true),createdAt:z123.iso.datetime({offset:true})});var DeliveryCompletionBlockerSchema=z123.enum(["VALIDATION_FAILED","EXACT_OUTPUT_CHANGED","DELIVERY_POLICY_CHANGED","FINAL_READY_STALE","ARTIFACT_UNAVAILABLE","PROVENANCE_INCOMPLETE","MANIFEST_NOT_REGISTERED","MANIFEST_BINDING_MISMATCH","BLOCKING_FINDINGS","TEST_EVIDENCE_DISABLED","APPROVAL_BINDING_MISMATCH","APPROVAL_REJECTED"]);var DeliveryReviewReceiptSchema=z123.strictObject({review:DeliveryValidationReviewSchema,action:z123.enum(["COMPLETE","WAITING_HUMAN","BLOCK"]),blockers:z123.array(DeliveryCompletionBlockerSchema).max(12),productionRevision:z123.int().positive()});var DeliveryDecisionReceiptSchema=z123.strictObject({humanLinks:HumanLinksSchema.optional(),approval:DeliveryApprovalSchema,finalDelivery:FinalDeliveryReceiptSchema.nullable(),productionRevision:z123.int().positive(),condition:z123.enum(["RUNNABLE","BLOCKED"])});var DeliveryValidationViewSchema=z123.strictObject({humanLinks:HumanLinksSchema.optional(),admission:DeliveryAdmissionSchema,policy:DeliveryPolicyVersionSchema,manifestBasis:DeliveryManifestBasisSchema,runtimeStatus:z123.enum(["PENDING","READY","RUNNING","WAITING","SUCCEEDED","FAILED","CANCELLED","SUPERSEDED"]),current:z123.boolean(),reviewReceipt:DeliveryReviewReceiptSchema.nullable(),findings:z123.array(DeliveryFindingSchema).max(16),approval:DeliveryApprovalSchema.nullable(),finalDelivery:FinalDeliveryReceiptSchema.nullable()});var DeliverySnapshotSchema=TimelineScopeSchema.extend({humanLinks:HumanLinksSchema.optional(),productionRevision:z123.int().positive(),policy:DeliveryPolicyVersionSchema.nullable(),currentValidationId:z123.uuid().nullable(),finalDelivery:FinalDeliveryReceiptSchema.nullable()});var DeliverySummarySchema=z124.strictObject({policy:DeliveryPolicyVersionSchema.nullable(),validation:z124.strictObject({id:z124.uuid(),runtimeStatus:DeliveryValidationViewSchema.shape.runtimeStatus,current:z124.boolean(),reviewId:z124.uuid().nullable(),result:z124.enum(["PASS","FAIL"]).nullable(),action:z124.enum(["COMPLETE","WAITING_HUMAN","BLOCK"]).nullable(),blockingChecks:z124.array(DeliveryCheckKeySchema).max(16),approvalAction:z124.enum(["APPROVE","REJECT"]).nullable()}).nullable(),finalDelivery:FinalDeliveryReceiptSchema.nullable()});import{z as z128}from"zod";import{z as z127}from"zod";import{z as z126}from"zod";import{z as z125}from"zod";var ShotSoundContentSchema=z125.strictObject({model:z125.strictObject({modelProfileId:z125.string().regex(/^[a-z][a-z0-9-]{1,79}$/),modelProfileVersion:z125.int().positive(),connectionId:z125.uuid()}).optional(),nativeAudio:z125.boolean(),cues:z125.array(z125.strictObject({id:z125.string().regex(/^[a-z][a-z0-9_-]{0,63}$/),role:z125.enum(["DIALOGUE","MUSIC","AMBIENCE","SOUND_EFFECT","NARRATION"]),startMs:z125.int().nonnegative().max(3e4),endMs:z125.int().positive().max(3e4),text:z125.string().trim().min(1).max(6e3).optional(),exactSpeech:z125.boolean(),lipSync:z125.enum(["REQUIRED","NONE"])}).refine(v=>v.endMs>v.startMs)).max(64)});var ShotSoundInstructionSchema=z125.strictObject({soundPlanVersionId:z125.uuid().toLowerCase(),fingerprint:z125.string().regex(/^[0-9a-f]{64}$/),content:ShotSoundContentSchema});var GenerationContractSchema=z126.strictObject({id:GenerationContractIdSchema,schemaVersion:z126.literal(1),preparationId:PreparationIdSchema,target:PreparationTargetSchema,basis:PreparationBasisSchema,mode:z126.enum(["REFERENCE_TO_IMAGE","REFERENCE_TO_VIDEO","FIRST_FRAME_TO_VIDEO","FIRST_LAST_FRAME_TO_VIDEO"]),creativeInstruction:z126.strictObject({sound:ShotSoundInstructionSchema.optional(),shot:ShotIntentSchema,scenePurpose:z126.string().min(1).max(800),locationContext:z126.string().max(300).optional(),timeContext:z126.string().max(300).optional(),productPresentationGoal:z126.string().min(1).max(1e3),styleTone:z126.string().max(300).optional(),entryBoundary:z126.array(BoundaryRequirementSchema).max(48),exitBoundary:z126.array(BoundaryRequirementSchema).max(48)}),acceptedShotReferences:z126.array(AcceptedVisualSourceReferenceSchema).max(24).default([]),constraintSetFingerprint:ContentFingerprintSchema,referenceSetFingerprint:ContentFingerprintSchema,output:z126.strictObject({aspectRatio:z126.enum(["16:9","9:16"]),targetDurationSeconds:z126.number().min(.5).max(30).nullable(),workingResolution:z126.null(),frameRate:z126.null(),finalDeliveryProfile:DeliveryOutputProfileSchema}),requiredCapabilities:z126.strictObject({referenceConditioning:z126.literal(true),referenceRoles:z126.array(ReferenceRoleSchema).min(1).max(8),startFrameControl:z126.boolean(),endFrameControl:z126.boolean(),nativeAudio:z126.boolean().optional()}),fingerprint:ContentFingerprintSchema}).superRefine((value2,context)=>{const invalid=message=>context.addIssue({code:"custom",message});if(value2.target.mediaType==="IMAGE"&&value2.acceptedShotReferences.length)invalid("Image generation cannot depend on accepted video Shots");if(value2.target.mediaType==="IMAGE"&&(value2.mode!=="REFERENCE_TO_IMAGE"||value2.output.targetDurationSeconds!==null||value2.requiredCapabilities.startFrameControl||value2.requiredCapabilities.endFrameControl))invalid("Image generation cannot claim video duration or frame-control semantics");if(value2.target.mediaType==="VIDEO"&&(value2.mode==="REFERENCE_TO_IMAGE"||value2.output.targetDurationSeconds===null))invalid("Video generation requires video mode and duration");const roles=value2.requiredCapabilities.referenceRoles;if(!roles.some(role=>role==="PRODUCT_IDENTITY"||role==="PRODUCT_PACKSHOT"))invalid("Product identity requires concrete reference conditioning");if(value2.requiredCapabilities.startFrameControl&&!roles.includes("START_FRAME_ANCHOR"))invalid("Start-frame control requires an exact anchor role");if(value2.requiredCapabilities.endFrameControl&&!roles.includes("END_FRAME_ANCHOR"))invalid("End-frame control requires an exact anchor role");if(value2.mode==="FIRST_LAST_FRAME_TO_VIDEO"&&(!value2.requiredCapabilities.startFrameControl||!value2.requiredCapabilities.endFrameControl))invalid("First/last mode requires both anchor capabilities")});var PrepareShotRequestSchema=z127.strictObject({tenantId:TenantIdSchema,expectedProductionRevision:z127.int().positive(),expectedPlanVersionId:SceneShotPlanVersionIdSchema,expectedPlanVersion:z127.int().positive(),expectedShotPlanningRevision:z127.int().positive(),expectedPreparationVersion:z127.int().nonnegative(),idempotencyKey:z127.string().trim().min(1).max(200),target:PreparationTargetSchema,referenceBindings:z127.array(ReferenceBindingInputSchema).max(12).default([])});var PreparationVersionSchema=z127.strictObject({id:PreparationIdSchema,version:z127.int().positive(),basis:PreparationBasisSchema,target:PreparationTargetSchema,constraints:ConstraintSetSchema,referenceSet:ReferenceSetSchema,canonicalSources:z127.array(ExactEvidenceReferenceSchema).max(64),acceptedShotReferences:z127.array(AcceptedVisualSourceReferenceSchema).max(24).default([]),blockers:z127.array(PreparationBlockerSchema).max(2048),contract:GenerationContractSchema.nullable(),createdByPrincipalId:PrincipalIdSchema,createdAt:z127.iso.datetime({offset:true})}).superRefine((value2,context)=>{const invalid=message=>context.addIssue({code:"custom",message});if(value2.constraints.preparationId!==value2.id||value2.referenceSet.preparationId!==value2.id||value2.constraints.version!==value2.version||value2.referenceSet.version!==value2.version)invalid("Resolved snapshot identity must match preparation");if(value2.contract!==null!==(value2.blockers.length===0))invalid("A preparation contract exists only for an unblocked preflight");if(value2.contract&&(value2.contract.preparationId!==value2.id||JSON.stringify(value2.contract.basis)!==JSON.stringify(value2.basis)||JSON.stringify(value2.contract.target)!==JSON.stringify(value2.target)||value2.contract.constraintSetFingerprint!==value2.constraints.fingerprint||value2.contract.referenceSetFingerprint!==value2.referenceSet.fingerprint||JSON.stringify(value2.contract.acceptedShotReferences)!==JSON.stringify(value2.acceptedShotReferences)))invalid("Generation Contract must freeze the exact preparation basis and snapshots")});var PrepareShotResultSchema=z127.strictObject({semanticStatus:z127.literal("SUCCESS"),preparation:PreparationVersionSchema,productionRevision:z127.int().positive()});var PreparationViewSchema=z127.strictObject({preparation:PreparationVersionSchema,freshness:z127.enum(["CURRENT_BASIS","STALE_BASIS"]),superseded:z127.boolean(),freshnessReasons:z127.array(z127.enum(["PLAN_CHANGED","SHOT_CHANGED","REFERENCE_UNAVAILABLE","CONSISTENCY_PROFILE_CHANGED","SOUND_PLAN_CHANGED","SUPERSEDED","KEYFRAME_SELECTION_CHANGED","PREDECESSOR_ACCEPTANCE_CHANGED"])).max(8),execution:z127.strictObject({eligibleVideoSelections:z127.array(ProviderSelectionSchema).max(1600).optional(),available:z127.boolean(),reasons:z127.array(z127.enum(["STALE_BASIS","PREPARATION_BLOCKED","PRODUCTION_NOT_RUNNABLE","PROVIDER_CAPABILITY_UNAVAILABLE","VIDEO_SELECTION_REQUIRED"])).min(0).max(4)})});var PreparationQueryInputSchema=z127.strictObject({tenantId:TenantIdSchema,productionId:ProductionIdSchema,shotId:ShotIdSchema.optional(),mediaType:z127.enum(["IMAGE","VIDEO"]).optional(),limit:QueryLimitSchema,next:ContinuationSchema.optional()});var PreparationQueryPageSchema=z127.strictObject({items:z127.array(PreparationViewSchema),page:QueryPageInfoSchema});var PreparationGetInputSchema=z127.strictObject({tenantId:TenantIdSchema,productionId:ProductionIdSchema,preparationId:PreparationIdSchema});var PreparationActiveInputSchema=z127.strictObject({tenantId:TenantIdSchema,productionId:ProductionIdSchema,shotId:ShotIdSchema,mediaType:z127.enum(["IMAGE","VIDEO"])});var PreparationSummarySchema=z127.strictObject({latest:z127.int().nonnegative(),current:z127.int().nonnegative(),stale:z127.int().nonnegative(),contractValid:z127.int().nonnegative(),preflightBlocked:z127.int().nonnegative(),executionAvailable:z127.int().nonnegative()});var NullableVersionSchema=z128.int().positive().nullable();var ProductionBlockerSchema=z128.object({code:z128.string().min(1).max(120),summary:z128.string().min(1).max(1e3),targetType:z128.string().min(1).max(80),targetId:z128.string().min(1).max(2048)});var ProductionSnapshotSchema=z128.object({humanLinks:HumanLinksSchema.optional(),tenantId:TenantIdSchema,projectId:ProjectIdSchema,productionId:ProductionIdSchema,state:ProductionStateSchema,planning:z128.object({activeBriefVersion:NullableVersionSchema,activeStoryVersion:NullableVersionSchema,activeSceneShotPlanVersion:NullableVersionSchema}),preparation:PreparationSummarySchema.optional(),keyframes:KeyframeSummarySchema.optional(),keyframeReview:KeyframeReviewSummarySchema.optional(),videos:VideoSummarySchema.optional(),captions:CaptionSnapshotSchema.optional(),audio:AudioSnapshotSchema.optional(),shots:z128.object({planned:z128.int().nonnegative(),ready:z128.int().nonnegative(),generating:z128.int().nonnegative(),candidates:z128.int().nonnegative(),accepted:z128.int().nonnegative(),blocked:z128.int().nonnegative(),stale:z128.int().nonnegative()}),findings:z128.object({open:z128.int().nonnegative(),blocking:z128.int().nonnegative(),warnings:z128.int().nonnegative()}),timeline:z128.object({currentVersion:NullableVersionSchema,stale:z128.boolean(),...TimelineSnapshotSchema.omit({currentVersion:true,stale:true}).partial().shape}),roughCut:RoughCutSnapshotSchema.partial().required({latestVersion:true,reviewState:true}),review2:RoughCutReviewSnapshotSchema.optional(),final:z128.object({ready:FinalReadyViewSchema.optional(),render:FinalRenderSnapshotSchema.optional(),renderState:z128.string().min(1).max(120).nullable(),delivery:DeliverySummarySchema.optional(),deliveryValidationState:z128.string().min(1).max(120).nullable()}),work:WorkSummarySchema,activeOperations:z128.array(OperationSummarySchema).max(20),blockers:z128.array(ProductionBlockerSchema).max(100),latestDecisions:z128.array(z128.string().min(1).max(1e3)).max(50),nextActions:z128.array(NextActionSchema).max(50),generatedAt:z128.iso.datetime({offset:true})});import{z as z129}from"zod";var ProductionQueryInputSchema=z129.object({tenantId:TenantIdSchema,projectId:ProjectIdSchema.optional(),search:z129.string().trim().min(1).max(200).optional(),attention:z129.enum(["NEEDS_YOU","WORKING","FINISHED"]).optional(),limit:QueryLimitSchema,next:ContinuationSchema.optional()});var ProductionQueryPageSchema=z129.object({items:z129.array(ProductionSchema),page:QueryPageInfoSchema});var OperationQueryInputSchema=z129.object({tenantId:TenantIdSchema,productionId:ProductionIdSchema,limit:QueryLimitSchema,next:ContinuationSchema.optional()});var OperationQueryPageSchema=z129.object({items:z129.array(OperationSummarySchema),page:QueryPageInfoSchema});var StoryQueryInputSchema=z129.object({tenantId:TenantIdSchema,productionId:ProductionIdSchema,limit:QueryLimitSchema,next:ContinuationSchema.optional()});var StoryQueryPageSchema=z129.object({items:z129.array(StoryVersionSchema),page:QueryPageInfoSchema});var SceneShotPlanQueryInputSchema=z129.object({tenantId:TenantIdSchema,productionId:ProductionIdSchema,limit:QueryLimitSchema,next:ContinuationSchema.optional()});var SceneShotPlanQueryPageSchema=z129.object({items:z129.array(SceneShotPlanVersionSchema),page:QueryPageInfoSchema});import{z as z130}from"zod";var InterfaceCancellationDataSchema=z130.strictObject({cancellationAccepted:z130.boolean()});var InterfaceCancellationReceiptSchema=InterfaceCancellationDataSchema.extend({semanticStatus:z130.literal("SUCCESS")});import{z as z131}from"zod";var id9=z131.uuid();var sha18=z131.string().regex(/^[0-9a-f]{64}$/);var AgentHostExecutionScopeSchema=z131.strictObject({tenantId:id9,projectId:id9,productionId:id9});var StartAgentHostExecutionSchema=AgentHostExecutionScopeSchema.extend({requestId:id9,studioInputArtifactId:id9,bindingId:id9,expectedProductionRevision:z131.int().positive(),expectedBindingRevision:z131.int().positive(),expectedConfigurationVersion:z131.int().positive()});var AgentHostExecutionGetSchema=AgentHostExecutionScopeSchema.extend({executionId:id9});var AgentHostExecutionQuerySchema=AgentHostExecutionScopeSchema.extend({limit:z131.int().min(1).max(100).default(20),beforeId:id9.optional()});var AgentHostExecutionSourceSchema=z131.strictObject({artifactId:id9,representationId:id9,checksumSha256:sha18,byteSize:z131.int().positive().max(8388608),contentType:z131.string().min(1).max(100),kind:z131.enum(["PRODUCT_INFORMATION","REFERENCE_IMAGE","REFERENCE_VIDEO"])});var AgentHostExecutionInputSchema=AgentHostExecutionScopeSchema.extend({protocol:z131.literal("NATIVESTUDIO_PRODUCTION_V1"),executionId:id9,hostRequestId:id9,productionRevision:z131.int().positive(),studioInput:StudioInputContentSchema,intake:AgentHostExecutionSourceSchema,sources:z131.array(AgentHostExecutionSourceSchema).max(12)}).refine(v=>v.studioInput.productionId===v.productionId&&v.studioInput.sourceArtifactIds.length===v.sources.length&&new Set(v.sources.map(s=>s.artifactId)).size===v.sources.length&&v.sources.every((s,index)=>s.artifactId===v.studioInput.sourceArtifactIds[index])&&!v.sources.some(s=>s.artifactId===v.intake.artifactId));var AgentHostInstallationTransportSchema=z131.union([CurrentHostInstallationTransportSchema,HistoricalHostTransportSchema]);var AgentHostNativeToolAuthoritySchema=AgentHostExecutionScopeSchema.extend({protocol:z131.literal("NATIVESTUDIO_AGENT_TOOLS_V1"),authorityRef:id9,executionId:id9,hostRequestId:id9,bindingId:id9,configurationVersion:z131.int().positive(),inputFingerprint:sha18,capabilityDigest:sha18,expiresAt:z131.iso.datetime({offset:true}),executionClass:z131.enum(["LIVE","TEST_ONLY"]),transport:AgentHostInstallationTransportSchema.optional()});var AgentHostExecutionSnapshotSchema=z131.strictObject({binding:AgentHostBindingSchema,input:AgentHostExecutionInputSchema,authority:AgentHostNativeToolAuthoritySchema}).refine(v=>v.binding.tenantId===v.input.tenantId&&v.binding.projectId===v.input.projectId&&v.binding.enabled&&v.authority.tenantId===v.input.tenantId&&v.authority.projectId===v.input.projectId&&v.authority.productionId===v.input.productionId&&v.authority.executionId===v.input.executionId&&v.authority.hostRequestId===v.input.hostRequestId&&v.authority.bindingId===v.binding.bindingId&&v.authority.configurationVersion===v.binding.configurationVersion);var AgentHostTaskObservationSchema=z131.strictObject({requestId:id9,runKey:z131.string().regex(/^[A-Za-z0-9_-]{1,160}$/),status:z131.enum(["accepted","running","succeeded","failed","cancelled","unknown"]),agentKey:HostReferenceSchema,agentVersion:z131.union([HostReferenceSchema,z131.int().positive()]),modelOptionKey:HostReferenceSchema,cancelRequested:z131.boolean(),createdAt:z131.iso.datetime({offset:true}),updatedAt:z131.iso.datetime({offset:true}),timing:z131.strictObject({acceptedAt:z131.iso.datetime({offset:true}),deadlineAt:z131.iso.datetime({offset:true}),limitSource:z131.literal("TASK_POLICY")}).nullable()});var AgentHostDispatchPhaseSchema=z131.enum(["ADMITTED","SENDING","OUTCOME_UNKNOWN","OBSERVING","REJECTED","CANCELLED_BEFORE_SUBMISSION"]);var AgentHostExecutionViewSchema=AgentHostExecutionScopeSchema.extend({executionId:id9,requestId:id9,requestedByPrincipalId:id9,hostRequestId:id9,revision:z131.int().positive(),contractVersion:z131.union([z131.literal(1),z131.literal(2)]).optional(),legacyDispatchFenceReleased:z131.boolean().optional(),snapshotFingerprint:sha18,snapshot:AgentHostExecutionSnapshotSchema,dispatchPhase:AgentHostDispatchPhaseSchema,active:z131.boolean(),observation:AgentHostTaskObservationSchema.nullable(),cancelRequestId:id9.nullable(),errorCode:z131.string().regex(/^[A-Z_]{1,80}$/).nullable(),createdAt:z131.iso.datetime({offset:true}),updatedAt:z131.iso.datetime({offset:true})}).refine(v=>(!v.legacyDispatchFenceReleased||v.contractVersion===1)&&v.snapshot.input.executionId===v.executionId&&v.snapshot.input.hostRequestId===v.hostRequestId&&v.snapshot.input.tenantId===v.tenantId&&v.snapshot.input.projectId===v.projectId&&v.snapshot.input.productionId===v.productionId&&(!v.observation||v.observation.requestId===v.hostRequestId&&v.observation.agentKey===v.snapshot.binding.selection.agentKey&&v.observation.agentVersion===v.snapshot.binding.selection.agentVersion&&v.observation.modelOptionKey===v.snapshot.binding.selection.modelOptionKey));var AgentHostExecutionPageSchema=z131.strictObject({items:z131.array(AgentHostExecutionViewSchema).max(100),hasMore:z131.boolean(),nextBeforeId:id9.nullable()}).refine(v=>v.hasMore===(v.nextBeforeId!==null)&&(!v.hasMore||v.nextBeforeId===v.items.at(-1)?.executionId)&&new Set(v.items.map(item=>item.executionId)).size===v.items.length);var AgentHostExecutionEventSchema=z131.strictObject({id:id9,executionId:id9,revision:z131.int().positive(),action:z131.enum(["ADMIT","CLAIM","RECOVER_UNKNOWN","OBSERVE","REJECT","CANCEL_REQUEST","CANCEL_UNSENT"]),createdByPrincipalId:id9,observation:AgentHostTaskObservationSchema.nullable(),errorCode:z131.string().regex(/^[A-Z_]{1,80}$/).nullable(),createdAt:z131.iso.datetime({offset:true})});var AgentHostExecutionEventQuerySchema=AgentHostExecutionGetSchema.extend({limit:z131.int().min(1).max(100).default(20),beforeRevision:z131.int().positive().optional()});var AgentHostExecutionEventPageSchema=z131.strictObject({items:z131.array(AgentHostExecutionEventSchema).max(100),hasMore:z131.boolean(),nextBeforeRevision:z131.int().positive().nullable()}).refine(v=>v.hasMore===(v.nextBeforeRevision!==null)&&(!v.hasMore||v.nextBeforeRevision===v.items.at(-1)?.revision)&&v.items.every((item,index)=>!index||item.revision<v.items[index-1].revision));var AgentHostExecutionFailureSchema=z131.strictObject({semanticStatus:z131.enum(["INVALID_INPUT","NOT_FOUND","BLOCKED","REVISION_CONFLICT","CAPABILITY_UNAVAILABLE","INTERNAL_OPERATIONAL_FAILURE"]),error:z131.strictObject({code:z131.enum(["INVALID_INPUT","UNAUTHENTICATED","FORBIDDEN","NOT_FOUND","REVISION_CONFLICT","REQUEST_CONFLICT","SOURCE_UNAVAILABLE","TOOL_AUTHORITY_UNAVAILABLE","ACTIVE_EXECUTION_EXISTS","LEASE_LOST","BINDING_UNAVAILABLE","INTERNAL_OPERATIONAL_FAILURE"]),message:z131.literal("Agent Host execution did not complete")})});import{z as z133}from"zod";import{z as z132}from"zod";var key4=z132.string().trim().min(1).max(200);var ScopedSourceInputSchema=SourceInputMetadataSchema.extend({projectId:ProjectIdSchema,idempotencyKey:key4});var ScopedSourceUploadSchema=UploadSourceInputRequestSchema.extend({projectId:ProjectIdSchema,idempotencyKey:key4});var SourceReadSchema=SourceLibraryMediaSchema.extend({offsetBytes:z132.int().min(0).max(8388608).default(0),maxTextBytes:z132.int().min(4).max(65536).default(16384)});var SourceTextWindowSchema=SourceLibraryMediaSchema.extend({contentType:z132.enum(["text/plain","application/json"]),checksumSha256:z132.string().regex(/^[0-9a-f]{64}$/),totalBytes:z132.int().positive().max(8388608),offsetBytes:z132.int().nonnegative(),byteLength:z132.int().nonnegative().max(65536),nextOffsetBytes:z132.int().nonnegative().nullable(),text:z132.string().max(65536)});var InterfaceImageMetadataSchema=KeyframeMediaSchema.omit({contentBase64:true});var InterfacePosterMetadataSchema=InterfaceImageMetadataSchema.extend({contentType:z133.literal("image/png")});var InterfaceDownloadDescriptorSchema=z133.strictObject({humanLinks:HumanLinksSchema.optional(),method:z133.literal("GET"),path:z133.string().min(1).max(2048),tenantId:TenantIdSchema,authentication:z133.literal("BEARER_AND_TENANT_HEADER"),contentType:z133.enum(["video/mp4","image/png","application/json"]),checksumSha256:z133.string().regex(/^[0-9a-f]{64}$/),byteSize:z133.int().positive().max(128*1024*1024)});var tenantMediaDownloadPath="/v1/local-execution/tenant-media/download";var InterfaceDeliveryDownloadDescriptorSchema=z133.discriminatedUnion("method",[InterfaceDownloadDescriptorSchema,InterfaceDownloadDescriptorSchema.extend({method:z133.literal("POST"),path:z133.literal(tenantMediaDownloadPath),productionId:ProductionIdSchema,contentType:z133.literal("video/mp4"),body:z133.strictObject({tenantId:TenantIdSchema,projectId:ProjectIdSchema,representationId:ArtifactRepresentationIdSchema})})]);var SourceReadResultSchema=z133.union([SourceTextWindowSchema,SourceLibraryMediaSchema.extend(InterfaceImageMetadataSchema.shape).strict(),SourceLibraryMediaSchema.extend({contentType:z133.literal("video/mp4"),checksumSha256:z133.string().regex(/^[0-9a-f]{64}$/),byteSize:z133.int().positive().max(8388608),importOperation:z133.literal("imported-visual.register-source")}).strict()]);import{z as z134}from"zod";var StartReferencePreviewSchema=z134.strictObject({tenantId:TenantIdSchema,projectId:ProjectIdSchema,productionId:ProductionIdSchema,sourceArtifactId:ArtifactIdSchema,expectedBriefVersion:z134.int().positive(),idempotencyKey:z134.string().regex(/^[A-Za-z0-9_-]{8,80}$/),deviceId:z134.uuid().optional()});var ReferencePreviewAdmissionSchema=z134.strictObject({semanticStatus:z134.literal("ACCEPTED"),operationId:OperationIdSchema,productionId:ProductionIdSchema,sourceArtifactId:ArtifactIdSchema,briefVersion:z134.int().positive()});var ReferencePreviewResultSchema=z134.strictObject({semanticStatus:z134.literal("SUCCESS"),sourceArtifactId:ArtifactIdSchema,representationId:ArtifactRepresentationIdSchema,contentType:z134.literal("image/png"),checksumSha256:z134.string().regex(/^[0-9a-f]{64}$/),width:z134.int().positive(),height:z134.int().positive(),byteSize:z134.int().positive(),contentBase64:z134.string().min(4)});var ReferencePreviewOperationInputSchema=z134.strictObject({tenantId:TenantIdSchema,projectId:ProjectIdSchema,productionId:ProductionIdSchema,operationId:OperationIdSchema});var ReferencePreviewReadResultSchema=z134.union([ReferencePreviewResultSchema,z134.strictObject({semanticStatus:z134.literal("ACCEPTED")})]);var ReferencePreviewCancelResultSchema=z134.union([z134.strictObject({semanticStatus:z134.literal("ACCEPTED")}),z134.strictObject({semanticStatus:z134.literal("NOT_FOUND")})]);import{z as z135}from"zod";var StudioCapabilitiesInputSchema=z135.strictObject({tenantId:TenantIdSchema,productionId:ProductionIdSchema.optional()});var StudioCapabilitiesSchema=z135.strictObject({semanticStatus:z135.literal("SUCCESS"),capabilities:z135.array(z135.strictObject({capability:z135.string().min(1).max(120),tool:z135.string().min(1).max(120).optional(),availability:z135.enum(["AVAILABLE","UNAVAILABLE"]),reason:z135.string().min(1).max(1e3).nullable()})).max(512)});var VideoOptionsSchema=z135.array(z135.strictObject({selection:ProviderSelectionSchema,profile:VideoProviderProfileSchema})).max(1600);import{z as z136}from"zod";var RenderReadinessInputSchema=z136.strictObject({tenantId:z136.uuid(),projectId:z136.uuid().optional(),productionId:z136.uuid().optional(),kind:z136.enum(["preview","final"]),deviceId:z136.uuid().optional(),hostAccess:z136.enum(["MCP_ONLY","AUTHORIZED_HOST"]).optional()});var RenderReadinessSchema=RenderReadinessInputSchema.omit({hostAccess:true}).extend({protocol:z136.literal("NVS_RENDER_READINESS_V1"),observedAt:z136.iso.datetime(),state:z136.enum(["SELECT_PROJECT","SELECT_PRODUCTION","BUSINESS_BLOCKED","AUTHORIZATION_REQUIRED","CHECK_DEVICE_INVENTORY","DEVICE_QUALIFICATION_UNKNOWN","WAIT_FOR_DEVICE","PREPARE_HOST","HOST_HANDOFF_REQUIRED","DEVICE_UNAVAILABLE","READY"]),reasonCode:z136.string().regex(/^[A-Z][A-Z0-9_]{0,79}$/),writeAuthorization:z136.enum(["READ_ONLY","WRITE_SCOPE_PRESENT","CHECK_AT_ADMISSION"]),blockers:FinalRenderEligibilitySchema.shape.blockers.optional(),sourceBlockers:FinalRenderEligibilitySchema.shape.sourceBlockers.optional(),candidates:ProjectDeviceListSchema.optional(),executionTarget:DeviceRenderTargetSchema.optional(),nextAction:z136.strictObject({owner:z136.enum(["AGENT","HOST_OWNER","AUTHORIZED_MEMBER","TENANT_OPERATOR"]),inspect:z136.strictObject({tool:z136.enum(["studio_capability_query","studio_capability_describe","workspace_caller"]),arguments:z136.record(z136.string(),z136.unknown())}).optional(),hostRequirements:z136.strictObject({packageName:z136.literal("@nativestudio/cli"),nodeMajor:z136.literal(24),permission:z136.literal("AUTHORIZED_USER_SHELL")}).optional()})});function renderDeviceSelection(candidates,requestedDeviceId){const fixed=requestedDeviceId?.toLowerCase();const available=candidates.items.filter(item=>item.availability==="AVAILABLE"&&(!fixed||item.deviceId.toLowerCase()===fixed));if(available.length>1)return{state:"DEVICE_SELECTION_REQUIRED"};if(available[0]&&(fixed||!candidates.truncated))return{state:"AVAILABLE",deviceId:available[0].deviceId};return{state:candidates.truncated?"INCOMPLETE_INVENTORY":"UNAVAILABLE"}}function currentPreviewRenderBasis(basis,current){if(!current||!current.isCurrent||current.assemblyStatus!=="ASSEMBLY_READY"||current.freshness!=="CURRENT_BASIS"||basis.currentTimelineVersion!==current.version.version)return null;return{timelineVersionId:current.version.id,timelineFingerprint:current.version.fingerprint,expectedProductionRevision:basis.productionRevision}}import{z as z139}from"zod";import{z as z137}from"zod";var uuid=z137.uuid().toLowerCase();var timestamp2=z137.iso.datetime();var version=z137.int().positive();var digest=z137.string().regex(/^[a-f0-9]{64}$/);var requestKey=z137.string().trim().min(1).max(200);var reason2=z137.string().trim().min(1).max(2e3);var scope2=z137.strictObject({tenantId:TenantIdSchema,projectId:ProjectIdSchema});var commandBase=scope2.extend({idempotencyKey:requestKey,reason:reason2});var claim=z137.strictObject({id:uuid,statement:z137.string().trim().min(1).max(1e3),evidenceArtifactId:ArtifactIdSchema,evidenceChecksumSha256:digest});var variant=z137.strictObject({id:uuid,market:z137.string().regex(/^(?:[A-Z]{2}|GLOBAL)$/),locale:z137.string().regex(/^[a-z]{2,3}(?:-[a-zA-Z0-9]{2,8}){0,4}$/),channel:z137.enum(["WEB","SOCIAL","PAID_AD","INTERNAL","EVENT","COMMERCE"]),allowedClaimIds:z137.array(uuid).max(20),requiredGraphicsSha256:z137.array(digest).max(4)});var brandContent=z137.strictObject({name:z137.string().trim().min(1).max(200),validFrom:timestamp2,validUntil:timestamp2,claims:z137.array(claim).max(40),variants:z137.array(variant).min(1).max(30)}).superRefine((value2,ctx)=>{const claimIds=new Set(value2.claims.map(item=>item.id));if(Date.parse(value2.validFrom)>=Date.parse(value2.validUntil))ctx.addIssue({code:"custom",path:["validUntil"],message:"End of brand validity must follow its start"});if(claimIds.size!==value2.claims.length||new Set(value2.variants.map(item=>item.id)).size!==value2.variants.length)ctx.addIssue({code:"custom",message:"Brand claims and variants require unique identities"});for(const[index,item]of value2.variants.entries()){if(new Set(item.allowedClaimIds).size!==item.allowedClaimIds.length||item.allowedClaimIds.some(id15=>!claimIds.has(id15)))ctx.addIssue({code:"custom",path:["variants",index,"allowedClaimIds"],message:"Every approved claim must appear once in this brand release"});if(new Set(item.requiredGraphicsSha256).size!==item.requiredGraphicsSha256.length)ctx.addIssue({code:"custom",path:["variants",index,"requiredGraphicsSha256"],message:"Required graphics must have distinct checksums"})}});var BrandPublicationSchema=scope2.extend({brandId:uuid,version,content:brandContent,fingerprint:digest,reason:reason2,createdByPrincipalId:PrincipalIdSchema,createdAt:timestamp2});var grantFields={grantId:uuid,brandId:uuid,version,consumerProjectId:ProjectIdSchema,variantIds:z137.array(uuid).min(1).max(30).refine(ids=>new Set(ids).size===ids.length),expiresAt:timestamp2};var BrandGrantSchema=scope2.extend({...grantFields,reason:reason2,createdByPrincipalId:PrincipalIdSchema,createdAt:timestamp2,revokedAt:timestamp2.nullable(),revokedByPrincipalId:PrincipalIdSchema.nullable(),revocationReason:reason2.nullable()});var EnterpriseBrandCommandSchema=z137.discriminatedUnion("action",[commandBase.extend({action:z137.literal("PUBLISH"),brandId:uuid,expectedVersion:z137.int().nonnegative(),content:brandContent}),commandBase.extend({action:z137.literal("GRANT"),...grantFields}),commandBase.extend({action:z137.literal("REVOKE"),grantId:uuid})]);var EnterpriseBrandReceiptSchema=z137.discriminatedUnion("action",[scope2.extend({action:z137.literal("PUBLISH"),idempotencyKey:requestKey,publication:BrandPublicationSchema}),scope2.extend({action:z137.enum(["GRANT","REVOKE"]),idempotencyKey:requestKey,grant:BrandGrantSchema})]);var BrandSelectionSchema=z137.strictObject({ownerProjectId:ProjectIdSchema,brandId:uuid,version,grantId:uuid,variantId:uuid,selectedClaimIds:z137.array(uuid).max(20).refine(ids=>new Set(ids).size===ids.length)});var BoundBrandVariantSchema=BrandSelectionSchema.extend({variant,selectedClaims:z137.array(claim).max(20),releaseFingerprint:digest});var EnterpriseBrandQuerySchema=z137.discriminatedUnion("action",[scope2.extend({action:z137.literal("PUBLICATION"),ownerProjectId:ProjectIdSchema,brandId:uuid,version,grantId:uuid.optional()}),scope2.extend({action:z137.literal("GRANT"),ownerProjectId:ProjectIdSchema,grantId:uuid})]);var EnterpriseBrandViewSchema=z137.discriminatedUnion("action",[scope2.extend({action:z137.literal("PUBLICATION"),grantId:uuid.optional(),publication:BrandPublicationSchema}),scope2.extend({action:z137.literal("GRANT"),grant:BrandGrantSchema})]);var EnterpriseBrandReceiptQuerySchema=scope2.extend({idempotencyKey:requestKey});import{z as z138}from"zod";var uuid2=z138.uuid().toLowerCase();var change=z138.strictObject({ruleId:uuid2,expected:z138.string().trim().min(1).max(1e3)});var SeriesCharacterVariantSchema=z138.strictObject({id:uuid2,subjectId:uuid2,name:z138.string().trim().min(1).max(200),wardrobe:z138.array(change).min(1).max(8).refine(rules=>new Set(rules.map(rule=>rule.ruleId)).size===rules.length),voiceSubjectId:uuid2.optional()});var SeriesCharacterVariantsSchema=z138.array(SeriesCharacterVariantSchema).min(1).max(16).refine(variants=>new Set(variants.map(variant2=>variant2.id)).size===variants.length);var SeriesCharacterVariantIdsSchema=z138.array(uuid2).min(1).max(16).refine(ids=>new Set(ids).size===ids.length);var digest2=z139.string().regex(/^[a-f0-9]{64}$/);var revision=z139.int().positive();var requestKey2=z139.string().trim().min(1).max(200);var reason3=z139.string().trim().min(1).max(2e3);var SeriesProjectScopeSchema=z139.strictObject({tenantId:TenantIdSchema,projectId:ProjectIdSchema});var identity3=SeriesProjectScopeSchema.extend({seriesId:z139.uuid()});var SeriesStandardQuerySchema=identity3.extend({version:revision.optional()});var SeriesStandardListSchema=SeriesProjectScopeSchema.extend({after:z139.uuid().optional(),limit:z139.int().positive().max(40).default(10)});var standard=z139.strictObject({name:z139.string().trim().min(1).max(200),consistency:ConsistencyProfileContentSchema,characterVariants:SeriesCharacterVariantsSchema.optional()});var PublishSeriesStandardSchema=identity3.extend({expectedVersion:z139.int().nonnegative(),brand:BrandSelectionSchema.optional(),content:standard.extend({graphics:z139.array(TimelineGraphicInputSchema).max(4)}).superRefine(({consistency,graphics},ctx)=>{if(!consistency.rules.length&&!graphics.length)ctx.addIssue({code:"custom",message:"A series standard needs a rule or a graphic"});for(const[index,rule]of consistency.rules.entries()){if(rule.scope.kind!=="PROJECT"||rule.transition||rule.voiceTargets?.kind==="SOUND_CUES")ctx.addIssue({code:"custom",path:["consistency","rules",index],message:"Reusable rules require project scope and cannot name episode-specific cues or transitions"})}if(new Set(graphics.map(g=>g.artifactId.toLowerCase())).size!==graphics.length)ctx.addIssue({code:"custom",path:["graphics"],message:"Duplicate required graphic"})}),reason:reason3,idempotencyKey:requestKey2});var SeriesStandardVersionSchema=identity3.extend({version:revision,brand:BoundBrandVariantSchema.optional(),content:standard.extend({graphics:z139.array(TimelineGraphicSchema).max(4)}),fingerprint:digest2,reason:reason3,createdByPrincipalId:PrincipalIdSchema,createdAt:z139.iso.datetime()});var SeriesStandardPageSchema=SeriesProjectScopeSchema.extend({items:z139.array(SeriesStandardVersionSchema.omit({content:true,brand:true}).extend({name:standard.shape.name})).max(40),next:z139.uuid().nullable()});var ProductionSeriesScopeSchema=SeriesProjectScopeSchema.extend({productionId:ProductionIdSchema});var ProductionSeriesQuerySchema=ProductionSeriesScopeSchema.extend({productionRevision:revision.optional(),atRevision:revision.optional()}).refine(query=>query.productionRevision===void 0||query.atRevision===void 0,"Use either the binding revision or a production receipt revision");var BindSeriesStandardSchema=ProductionSeriesScopeSchema.extend({seriesId:z139.uuid(),version:revision,expectedProductionRevision:revision,expectedProfileVersion:z139.int().nonnegative(),characterVariantIds:SeriesCharacterVariantIdsSchema.optional(),reason:reason3,idempotencyKey:requestKey2});var ProductionSeriesBindingSchema=ProductionSeriesScopeSchema.extend({standard:SeriesStandardVersionSchema,characterVariantIds:SeriesCharacterVariantIdsSchema.optional(),profileId:z139.uuid(),profileVersion:revision,productionRevision:revision,reason:reason3,createdByPrincipalId:PrincipalIdSchema,createdAt:z139.iso.datetime()});var PublishSeriesStandardReceiptSchema=z139.strictObject({action:z139.literal("PUBLISH"),idempotencyKey:requestKey2,standard:SeriesStandardVersionSchema});var BindSeriesStandardReceiptSchema=z139.strictObject({action:z139.literal("BIND"),idempotencyKey:requestKey2,binding:ProductionSeriesBindingSchema});var SeriesStandardReceiptSchema=z139.discriminatedUnion("action",[PublishSeriesStandardReceiptSchema,BindSeriesStandardReceiptSchema]);var SeriesStandardReceiptQuerySchema=SeriesProjectScopeSchema.extend({idempotencyKey:requestKey2});import{z as z140}from"zod";var id10=z140.uuid().toLowerCase();var ordinal=z140.int().positive();var scope3=z140.strictObject({tenantId:TenantIdSchema,projectId:ProjectIdSchema});var branch=scope3.extend({seriesId:id10,branchId:id10});var reference=z140.strictObject({branchId:id10,ordinal});var state=z140.record(z140.string().regex(/^[A-Z][A-Z0-9_.-]{0,63}$/),z140.string().trim().min(1).max(1e3)).refine(value2=>Object.keys(value2).length<=48,"Up to 48 canonical facts");var time=z140.strictObject({startTick:z140.int().nonnegative(),endTick:z140.int().positive()}).refine(range=>range.endTick>range.startTick,"Story time must have a positive duration");var relation=z140.discriminatedUnion("kind",[z140.strictObject({kind:z140.literal("CONTINUE")}),z140.strictObject({kind:z140.literal("FLASHBACK"),anchor:reference}),z140.strictObject({kind:z140.literal("FORK"),anchor:reference})]);var episode={productionId:ProductionIdSchema,storyTime:time,entryState:state,exitState:state,relation,reason:z140.string().trim().min(1).max(2e3),idempotencyKey:z140.string().trim().min(1).max(200)};var RecordSeriesCanonSchema=branch.extend({...episode,expectedHeadOrdinal:z140.int().nonnegative(),bindingRevision:ordinal,seriesVersion:ordinal});var SeriesCanonSchema=branch.extend({...episode,ordinal,bindingRevision:ordinal,seriesVersion:ordinal,basis:reference.nullable(),continuation:z140.strictObject({head:reference,endTick:z140.int().positive(),state}),createdAt:z140.iso.datetime(),createdByPrincipalId:PrincipalIdSchema});var SeriesCanonQuerySchema=branch.extend({ordinal:ordinal.optional()});var SeriesCanonReceiptQuerySchema=scope3.extend({idempotencyKey:episode.idempotencyKey});import{z as z141}from"zod";var id11=z141.uuid().toLowerCase();var version2=z141.int().positive();var scope4=z141.strictObject({tenantId:TenantIdSchema,projectId:ProjectIdSchema});var series=scope4.extend({seriesId:id11});var identity4=series.extend({proposalId:id11});var requestKey3=z141.string().trim().min(1).max(200);var reason4=z141.string().trim().min(1).max(2e3);var command2=identity4.extend({reason:reason4,idempotencyKey:requestKey3});var finding=z141.strictObject({kind:z141.literal("FINDING"),productionId:ProductionIdSchema,bindingRevision:version2,findingId:id11});var canon=z141.strictObject({kind:z141.literal("CANON"),branchId:id11,ordinal:version2});var source3=z141.discriminatedUnion("kind",[finding,canon]);var evidence=z141.discriminatedUnion("kind",[finding.extend({renderId:id11,reviewId:id11,timelineVersionId:id11,seriesVersion:version2,manifestFingerprint:z141.string().regex(/^[a-f0-9]{64}$/)}),canon.extend({productionId:ProductionIdSchema,bindingRevision:version2,seriesVersion:version2})]);var draft=z141.strictObject({content:PublishSeriesStandardSchema.shape.content,brand:BrandSelectionSchema.optional()});var SeriesImprovementCommandSchema=z141.discriminatedUnion("action",[command2.extend({action:z141.literal("PROPOSE"),baseVersion:version2,source:source3,draft}),command2.extend({action:z141.literal("APPROVE")}),command2.extend({action:z141.literal("DECLINE")})]);var actor={createdAt:z141.iso.datetime(),createdByPrincipalId:PrincipalIdSchema,reason:reason4};var SeriesImprovementProposalSchema=identity4.extend({baseVersion:version2,evidence,draft,...actor});var SeriesImprovementDecisionSchema=z141.discriminatedUnion("action",[identity4.extend({action:z141.literal("APPROVE"),published:SeriesStandardVersionSchema,...actor}),identity4.extend({action:z141.literal("DECLINE"),...actor})]);var SeriesImprovementReceiptSchema=identity4.extend({action:z141.enum(["PROPOSE","APPROVE","DECLINE"]),idempotencyKey:requestKey3,proposal:SeriesImprovementProposalSchema,decision:SeriesImprovementDecisionSchema.nullable()});var SeriesImprovementQuerySchema=z141.discriminatedUnion("action",[identity4.extend({action:z141.literal("GET")}),series.extend({action:z141.literal("LIST"),after:id11.optional(),limit:z141.int().min(1).max(20).default(10)})]);var SeriesImprovementViewSchema=z141.discriminatedUnion("action",[identity4.extend({action:z141.literal("GET"),proposal:SeriesImprovementProposalSchema,decision:SeriesImprovementDecisionSchema.nullable()}),series.extend({action:z141.literal("LIST"),items:z141.array(SeriesImprovementProposalSchema.omit({draft:true}).extend({disposition:z141.enum(["PENDING","APPROVED","DECLINED"])})).max(20),next:id11.nullable()})]);var SeriesImprovementReceiptQuerySchema=scope4.extend({idempotencyKey:requestKey3});import{z as z142}from"zod";var Key2=z142.string().regex(/^[a-z][a-z0-9_-]{0,39}$/);var Intent3=z142.string().trim().min(1).max(600);var ExplorationScopeSchema=DirectorScopeSchema.extend({shotId:ShotIdSchema});var ExplorationBasisSchema=DirectorBasisSchema.safeExtend({shotId:ShotIdSchema,shotPlanningRevision:z142.int().positive()});var ExplorationContextInputSchema=z142.strictObject({scope:ExplorationScopeSchema,preparationIds:z142.array(PreparationIdSchema).max(6).default([])}).refine(v=>new Set(v.preparationIds).size===v.preparationIds.length,"Preparation IDs must be distinct");var ExplorationProfileIdentitySchema=KeyframeProviderProfileSchema.pick({id:true,adapterVersion:true,model:true,executionClass:true});var ExplorationOptionSchema=z142.strictObject({selection:ProviderSelectionSchema.nullable(),profile:z142.discriminatedUnion("mediaType",[KeyframeProviderProfileSchema,VideoProviderProfileSchema])});var Missing2=z142.strictObject({semanticStatus:z142.literal("NEEDS_INPUT"),missingPrerequisites:z142.array(z142.enum(["ACTIVE_BRIEF","ACTIVE_STORY","ACTIVE_SCENE_SHOT_PLAN"])).min(1).max(3)});var ExplorationContextResultSchema=z142.discriminatedUnion("semanticStatus",[z142.strictObject({semanticStatus:z142.literal("SUCCESS"),advisory:z142.literal(true),basis:ExplorationBasisSchema,owner:DirectorContextResultSchema.options[0],preparations:z142.array(z142.strictObject({view:PreparationViewSchema,eligibleOptions:z142.array(ExplorationOptionSchema).max(24),eligibleOptionCount:z142.int().nonnegative(),optionsTruncated:z142.boolean()})).max(6)}),Missing2]);var ImageDraft=KeyframeStartInputSchema.omit({idempotencyKey:true});var VideoDraft=VideoStartInputSchema.omit({idempotencyKey:true});var ExplorationCommandSchema=z142.strictObject({commandKey:Key2,purpose:Intent3,mediaType:z142.enum(["IMAGE","VIDEO"]),preparationId:PreparationIdSchema,contractId:ImageDraft.shape.contractId,contractFingerprint:ImageDraft.shape.contractFingerprint,selection:ProviderSelectionSchema.nullable(),profile:ExplorationProfileIdentitySchema});var ValidateExplorationPlanSchema=z142.strictObject({basis:ExplorationBasisSchema,plan:z142.strictObject({origin:z142.strictObject({kind:z142.literal("EXTERNAL_AGENT_HOST"),label:z142.string().trim().min(1).max(100)}),objective:Intent3,comparisonCriteria:z142.array(Intent3).min(1).max(8),unknowns:z142.array(z142.string().trim().min(1).max(300)).max(8),maximumGenerationCommands:z142.int().min(1).max(6),commands:z142.array(ExplorationCommandSchema).min(1).max(6)})}).refine(v=>new TextEncoder().encode(JSON.stringify(v)).byteLength<=1024*1024,"Exploration input exceeds the 1 MiB JSON budget");var ExplorationDraftSchema=z142.discriminatedUnion("mediaType",[z142.strictObject({commandKey:Key2,mediaType:z142.literal("IMAGE"),request:ImageDraft}),z142.strictObject({commandKey:Key2,mediaType:z142.literal("VIDEO"),request:VideoDraft})]);var ExplorationValidationResultSchema=z142.discriminatedUnion("semanticStatus",[z142.strictObject({semanticStatus:z142.literal("SUCCESS"),advisory:z142.literal(true),basis:ExplorationBasisSchema,plan:ValidateExplorationPlanSchema.shape.plan,generationDrafts:z142.array(ExplorationDraftSchema).min(1).max(6),limitations:z142.array(z142.enum(["ADMISSION_RECHECKS_BASIS_AND_PROVIDER","COMMAND_COUNT_IS_NOT_MONETARY_BUDGET","NO_AUTOMATIC_EXECUTION_OR_ACCEPTANCE","QUALITY_REQUIRES_EXACT_MEDIA_INSPECTION"])).length(4)}),Missing2]);var ExplorationCompareInputSchema=z142.strictObject({scope:ExplorationScopeSchema,items:z142.array(z142.strictObject({label:Key2,mediaType:z142.enum(["IMAGE","VIDEO"]),generationId:z142.uuid()})).min(2).max(6)});var ExplorationComparisonResultSchema=z142.strictObject({semanticStatus:z142.literal("SUCCESS"),advisory:z142.literal(true),scope:ExplorationScopeSchema,items:z142.array(z142.discriminatedUnion("mediaType",[z142.strictObject({label:Key2,mediaType:z142.literal("IMAGE"),generation:KeyframeGenerationViewSchema,handoff:z142.strictObject({mediaRead:KeyframeReviewScopeSchema,reviewTarget:KeyframeReviewScopeSchema}).nullable()}),z142.strictObject({label:Key2,mediaType:z142.literal("VIDEO"),generation:VideoGenerationViewSchema,handoff:z142.strictObject({mediaRead:VideoReviewScopeSchema,reviewTarget:VideoReviewScopeSchema}).nullable()})])).min(2).max(6),limitations:z142.tuple([z142.literal("OWNER_STATES_ARE_NOT_VISUAL_SCORES"),z142.literal("REVIEW_AND_ACCEPTANCE_REMAIN_EXPLICIT")])});import{z as z143}from"zod";var sha19=z143.string().regex(/^[0-9a-f]{64}$/);var FinalOutputReviewContextInputSchema=z143.strictObject({scope:DirectorScopeSchema,renderId:z143.uuid()});var FinalOutputReviewBasisSchema=FinalOutputReviewContextInputSchema.extend({contextFingerprint:sha19});var FinalOutputReviewContextResultSchema=z143.strictObject({semanticStatus:z143.literal("SUCCESS"),advisory:z143.literal(true),basis:FinalOutputReviewBasisSchema,ownerContext:DirectorContextResultSchema,deliveryTarget:DeliveryTargetSchema,deliverySnapshot:DeliverySnapshotSchema,validation:DeliveryValidationViewSchema.nullable(),manifest:RegisteredDeliveryManifestSchema.nullable(),limitations:z143.array(z143.enum(["OWNER_REVIEW_3_REMAINS_AUTHORITATIVE","NO_CALLER_SUPPLIED_DELIVERY_CHECKS","NO_IMPLICIT_MEDIA_OR_MODEL_CALL","READS_ARE_NOT_ATOMIC_OR_RESERVED"])).length(4)});import{z as z148}from"zod";import{z as z147}from"zod";import{z as z146}from"zod";import{z as z144}from"zod";var Text=z144.string().trim().min(1).max(600);var Method=z144.enum(["HUMAN","AI","CODE"]);var Key3=z144.string().regex(/^[a-z][a-z0-9_.:-]{0,99}$/);var CompositionAuthoringObligationsSchema=z144.strictObject({schemaVersion:z144.literal(1),basis:CompositionBasisPinSchema,productionRevision:z144.int().positive(),output:BriefContentSchema.pick({targetDurationSeconds:true,aspectRatio:true,outputProfile:true}),objective:BriefContentSchema.shape.objective,productPresentationGoal:BriefContentSchema.shape.productPresentationGoal,audience:BriefContentSchema.shape.audience,styleTone:BriefContentSchema.shape.styleTone,callToAction:BriefContentSchema.shape.callToAction,narrativeIntent:StoryContentSchema.shape.narrativeIntent,canonicalFacts:BriefContentSchema.shape.canonicalFacts,storyBeats:StoryContentSchema.shape.beats,storyFactualClaims:StoryContentSchema.shape.factualClaims,shot:ShotPlanEntrySchema.nullable(),obligationKeys:z144.array(Key3).min(1).max(384).refine(v=>new Set(v).size===v.length,"Obligation keys must be unique"),semantics:z144.literal("ACCEPTED_INTENT_NOT_OBSERVED_MEDIA")}).refine(v=>v.basis.shotId===null===(v.shot===null)&&(!v.shot||v.shot.shotId===v.basis.shotId),"Authoring Shot must match the exact planning basis");var MakingAlternativeSchema=z144.strictObject({alternativeId:z144.string().regex(/^[a-z][a-z0-9_-]{0,39}$/),title:z144.string().trim().min(1).max(120),method:z144.enum(["HUMAN","AI","CODE","HYBRID"]),contributions:z144.array(z144.strictObject({method:Method,role:z144.enum(["PRIMARY_VISUAL","VISUAL_LAYER"]),intent:Text})).min(1).max(6),rationale:Text,tradeoffs:z144.array(Text).max(6),obligationKeys:z144.array(Key3).min(1).max(384)}).superRefine((v,ctx)=>{const methods=new Set(v.contributions.map(c=>c.method));if(v.method==="HYBRID"?methods.size<2:methods.size!==1||!methods.has(v.method))ctx.addIssue({code:"custom",path:["contributions"],message:"Contributions must match the advisory making method"});if(new Set(v.contributions.map(c=>c.method+":"+c.role)).size!==v.contributions.length)ctx.addIssue({code:"custom",path:["contributions"],message:"Method/role contributions must be unique"});if(new Set(v.obligationKeys).size!==v.obligationKeys.length)ctx.addIssue({code:"custom",path:["obligationKeys"],message:"Obligation references must be unique"})});var ValidateCompositionMakingSchema=CompositionScopeSchema.extend({projectId:z144.uuid(),expectedProductionRevision:z144.int().positive(),basis:CompositionBasisPinSchema,proposal:z144.strictObject({origin:z144.strictObject({kind:z144.literal("EXTERNAL_AGENT_HOST"),label:z144.string().trim().min(1).max(100)}),makingIntent:z144.enum(["REAL_WORLD_CAPTURE","GENERATED_SCENE","PROGRAMMATIC_EXPLANATION"]),unknowns:z144.array(z144.string().trim().min(1).max(300)).max(8),alternatives:z144.array(MakingAlternativeSchema).min(1).max(3)})}).superRefine((v,ctx)=>{if(new Set(v.proposal.alternatives.map(a=>a.alternativeId)).size!==v.proposal.alternatives.length)ctx.addIssue({code:"custom",message:"Alternative IDs must be unique"});if(new TextEncoder().encode(JSON.stringify(v)).byteLength>131072)ctx.addIssue({code:"custom",message:"Making proposal exceeds the 128 KiB UTF-8 JSON budget"})});var CompositionMakingValidationSchema=CompositionScopeSchema.extend({semanticStatus:z144.literal("SUCCESS"),advisory:z144.literal(true),projectId:z144.uuid(),authoring:CompositionAuthoringObligationsSchema,proposal:ValidateCompositionMakingSchema.shape.proposal,limitations:z144.tuple([z144.literal("STRATEGY_IS_AGENT_ADVICE_NOT_CANONICAL_SELECTION"),z144.literal("SOURCE_METHOD_IS_NOT_PROVENANCE_OR_PROVIDER_ELIGIBILITY"),z144.literal("AUTHORING_AND_RENDER_RECHECK_CURRENT_BASIS"),z144.literal("INDEPENDENT_REVIEW_AND_DELIVERY_REMAIN_REQUIRED")])}).superRefine((v,ctx)=>{const required=new Set(v.authoring.obligationKeys);if(new Set(v.proposal.alternatives.map(a=>a.alternativeId)).size!==v.proposal.alternatives.length||v.proposal.alternatives.some(a=>a.obligationKeys.length!==required.size||a.obligationKeys.some(k=>!required.has(k))))ctx.addIssue({code:"custom",message:"Making result must retain unique alternatives and exact native obligation coverage"})});import{z as z145}from"zod";var CompositionAuthoringRequirementsSchema=z145.strictObject({videoFrameCache:z145.strictObject({profileId:z145.literal("HYPERFRAME_1080P30_FRAME_CACHE_V2"),media:z145.literal("MANAGED_MP4_H264_CFR30_SDR_YUV420P"),maxVideos:z145.literal(4),maxDimension:z145.literal(1920),maxPixels:z145.literal(2073600),maxSourceSeconds:z145.literal(60),playbackRate:z145.literal(1),loop:z145.literal(false),sourceOffset:z145.literal("ZERO_BASED_FRAME_ALIGNED"),srcPattern:z145.literal("/inputs/{inputName}.mp4"),attributes:z145.tuple([z145.literal("id"),z145.literal("src"),z145.literal("data-start"),z145.literal("data-duration")]),dynamicVideoSupported:z145.literal(false),nativePlaybackAndCanvasSamplingSupported:z145.literal(false)}).optional(),semantics:z145.literal("REQUIREMENTS_NOT_RUNTIME_OR_REVIEW_EVIDENCE"),dependencies:CompositionContentSchema.shape.dependencies,html:z145.strictObject({entrypoint:z145.literal("index.html"),stageSelector:z145.literal("#stage"),timelineRegistry:z145.literal("window.__timelines"),readinessPromise:z145.literal("window.__nativeReady"),gsapScript:z145.literal("/_native/gsap.min.js"),managedInputsScript:z145.literal("/native-inputs.js"),rootAttributes:z145.tuple([z145.literal("data-composition-id"),z145.literal("data-width"),z145.literal("data-height"),z145.literal("data-duration")]),timing:z145.literal("PAUSED_GSAP_TIMELINE_WITH_DURATION_MATCHING_LOCAL_CLOCK")})});var jsonSchema=z145.record(z145.string().max(120),z145.json());var CompositionAuthoringGuideSchema=z145.strictObject({inputTool:z145.literal("composition_put_input"),inputField:z145.literal("contentUtf8"),encoding:z145.literal("UTF8_JSON"),schemas:z145.strictObject({SOURCE:jsonSchema,DEPENDENCY_MANIFEST:jsonSchema,DEPENDENCY_LOCK:jsonSchema}),rendererRequirements:CompositionAuthoringRequirementsSchema.nullable(),dependencyInputs:z145.strictObject({dependencies:CompositionContentSchema.shape.dependencies,manifest:CompositionDependencyManifestSchema,lock:CompositionDependencyLockSchema}).nullable().optional(),validation:z145.literal("NATIVE_OWNER_RECHECKS_BYTES_BASIS_AND_SEMANTIC_REFINEMENTS")}).refine(v=>new TextEncoder().encode(JSON.stringify(v)).byteLength<=65536);var CreateCompositionSchema=SubmitCompositionSchema.safeExtend({compositionId:z146.null(),expectedVersion:z146.literal(0),previousVersionId:z146.null()});var ReviseCompositionSchema=SubmitCompositionSchema.safeExtend({compositionId:z146.uuid(),expectedVersion:z146.int().positive(),previousVersionId:z146.uuid()});var CompositionBriefQuerySchema=CompositionScopeSchema.extend({shotId:z146.uuid().nullable().default(null)});var CompositionAuthoringBriefSchema=CompositionScopeSchema.extend({projectId:z146.uuid(),productionRevision:z146.int().positive(),planningStatus:z146.enum(["READY","MISSING_PLANNING","STALE_PLANNING","INACTIVE"]),basis:CompositionBasisPinSchema.nullable(),briefContent:BriefContentSchema.nullable(),storyContent:StoryContentSchema.nullable(),shot:ShotPlanEntrySchema.nullable(),authoring:CompositionAuthoringObligationsSchema.nullable().optional()});var ValidateCompositionSchema=CompositionScopeSchema.extend({expectedProductionRevision:z146.int().positive(),basis:CompositionBasisPinSchema,content:CompositionContentSchema}).superRefine((v,ctx)=>{if(v.content.role==="PRIMARY_VISUAL"&&!v.basis.shotId)ctx.addIssue({code:"custom",path:["basis","shotId"],message:"Primary visual requires a planned Shot"})});var CompositionValidationReceiptSchema=z146.strictObject({authoringValidation:z146.literal("PASS"),basis:CompositionBasisPinSchema,productionRevision:z146.int().positive(),contentFingerprint:z146.string().regex(/^[0-9a-f]{64}$/),inputCount:z146.int().min(3).max(64),byteReadback:z146.literal("VERIFIED"),rendererValidation:z146.literal("NOT_EXECUTED"),renderAvailability:z146.enum(["AVAILABLE","UNAVAILABLE"]),nextActions:z146.array(z146.enum(["CREATE_COMPOSITION","REVISE_COMPOSITION"])).max(2)});var PutCompositionInputSchema=CompositionScopeSchema.extend({name:CompositionBindingSchema.shape.name,purpose:z146.enum(["SOURCE","DEPENDENCY_MANIFEST","DEPENDENCY_LOCK","DATA"]),declaredOrigin:CompositionBindingSchema.shape.declaredOrigin,executionClass:z146.enum(["LIVE","TEST_ONLY"]),contentUtf8:z146.string().min(1).max(8388608),idempotencyKey:z146.string().trim().min(1).max(200)}).superRefine((v,ctx)=>{if(v.purpose==="SOURCE"&&v.declaredOrigin!=="CODE")ctx.addIssue({code:"custom",path:["declaredOrigin"],message:"Programmatic source must retain CODE provenance"})});var CompositionInputReceiptSchema=z146.strictObject({binding:CompositionBindingSchema,projectId:z146.uuid(),contentType:z146.literal("application/json"),byteSize:z146.int().positive().max(8388608),executionClass:z146.enum(["LIVE","TEST_ONLY"]),inputStatus:z146.enum(["AVAILABLE","UNAVAILABLE"]),byteReadback:z146.literal("VERIFIED_AT_REGISTRATION")});var CompositionCapabilitySchema=z146.strictObject({capability:z146.string().min(1).max(80),tool:z146.string().nullable(),availability:z146.enum(["AVAILABLE","UNAVAILABLE"]),reason:z146.string().nullable()});var CompositionCapabilitiesSchema=z146.strictObject({provider:z146.literal("HYPERFRAME"),dialect:z146.literal("HYPERFRAME_HTML_GSAP_V1"),planningStatus:CompositionAuthoringBriefSchema.shape.planningStatus,capabilities:z146.array(CompositionCapabilitySchema).max(18),inputLimitsMiB:z146.strictObject({SOURCE:z146.literal(8),DEPENDENCY_MANIFEST:z146.literal(8),DEPENDENCY_LOCK:z146.literal(8),DATA:z146.literal(8),FONT:z146.literal(32),IMAGE:z146.literal(8),VIDEO:z146.literal(64)}),clockSemantics:z146.literal("RATIONAL_FPS_HALF_OPEN_FRAMES"),rendererValidation:z146.enum(["C3_PENDING","PER_REQUEST_CONFORMANCE"]),authoringGuide:CompositionAuthoringGuideSchema.optional()});var CompositionFailureSchema=z146.strictObject({semanticStatus:z146.enum(["INVALID_INPUT","NOT_FOUND","REVISION_CONFLICT","STALE_BASIS","BLOCKED","CAPABILITY_UNAVAILABLE","INTERNAL_OPERATIONAL_FAILURE"]),error:z146.strictObject({code:z146.string().max(80),message:z146.string().max(2e3)}),retryable:z146.boolean(),nextActions:z146.array(z146.string().max(80)).max(4),diagnostics:z146.array(z146.strictObject({code:z146.string().max(80),message:z146.string().max(2e3)})).max(32)});var ParameterValue=z147.strictObject({kind:z147.literal("PARAMETER_VALUE"),name:CompositionBindingSchema.shape.name,value:z147.union([z147.string().max(4e3),z147.number().finite(),z147.boolean()])});var Binding=CompositionBindingSchema.extend({purpose:z147.enum(["SOURCE","DATA","FONT","IMAGE","VIDEO"])});var CompositionRepairConsumerSchema=z147.discriminatedUnion("role",[z147.strictObject({role:z147.literal("PRIMARY_VISUAL"),clipOrdinal:z147.int().min(1).max(200)}),z147.strictObject({role:z147.literal("VISUAL_LAYER"),visualLayerId:z147.uuid()})]);var Consumers=z147.array(CompositionRepairConsumerSchema).min(1).max(208).refine(items=>new Set(items.map(i=>i.role==="PRIMARY_VISUAL"?i.role+i.clipOrdinal:i.role+i.visualLayerId)).size===items.length,"Coordinated consumers must be unique exact occurrences");var CompositionRepairPatchSchema=z147.discriminatedUnion("kind",[ParameterValue,z147.strictObject({kind:z147.literal("BINDING_REPLACE"),binding:Binding})]);var ReviseCompositionRepairActionSchema=z147.strictObject({kind:z147.literal("REVISE_COMPOSITION"),localityIndex:z147.int().min(0).max(207),patches:z147.array(CompositionRepairPatchSchema).min(1).max(16),coordinatedConsumers:Consumers.optional()}).superRefine((v,ctx)=>{const names=v.patches.map(p=>p.kind+":"+(p.kind==="PARAMETER_VALUE"?p.name:p.binding.name));if(new Set(names).size!==names.length)ctx.addIssue({code:"custom",message:"Local Composition patch targets must be unique"})});var CompositionRepairSubjectSchema=z147.strictObject({locality:CompositionFindingLocalitySchema,composition:CompositionViewSchema,render:CompositionRenderViewSchema});var{idempotencyKey,...revisionShape}=ReviseCompositionSchema.shape;var RevisionDraft=z147.strictObject(revisionShape).refine(v=>v.content.role!=="PRIMARY_VISUAL"||v.basis.shotId!==null,"Primary repair retains an exact planned Shot");var CompositionRepairHandoffSchema=z147.strictObject({kind:z147.literal("COMPOSITION_REVISE"),locality:CompositionFindingLocalitySchema,input:RevisionDraft,renderProfileId:z147.enum(["HYPERFRAME_1080P30_FULL_PAINT_V1","HYPERFRAME_1080P30_FRAME_CACHE_V2","HYPERFRAME_RGBA_PNG30_FULL_PAINT_V1"]),sourceReviewRequired:z147.boolean(),coordinatedConsumers:Consumers.optional()}).superRefine((v,ctx)=>{if(v.input.compositionId!==v.locality.compositionId||v.input.previousVersionId!==v.locality.compositionVersionId||v.input.expectedVersion!==v.locality.compositionVersion||v.input.content.role!==v.locality.role||v.coordinatedConsumers?.some(i=>i.role!==v.locality.role)||v.sourceReviewRequired!==(v.locality.role==="PRIMARY_VISUAL")||!(v.locality.role==="PRIMARY_VISUAL"?["HYPERFRAME_1080P30_FULL_PAINT_V1","HYPERFRAME_1080P30_FRAME_CACHE_V2"].includes(v.renderProfileId):v.renderProfileId==="HYPERFRAME_RGBA_PNG30_FULL_PAINT_V1"))ctx.addIssue({code:"custom",message:"Composition repair handoff must retain exact locality identity, role and original output profile"})});var text=z148.string().trim().min(1).max(2e3);var key5=z148.string().regex(/^[a-z][a-z0-9_-]{0,39}$/);var RepairStrategyContextInputSchema=z148.strictObject({scope:DirectorScopeSchema,findingId:z148.uuid()});var RepairStrategyBasisSchema=RepairStrategyContextInputSchema.extend({contextFingerprint:z148.string().regex(/^[0-9a-f]{64}$/)});var RepairStrategyActionSchema=z148.discriminatedUnion("kind",[ReviseCompositionRepairActionSchema,z148.strictObject({kind:z148.literal("TRIM_CLIP"),ordinal:z148.int().min(1).max(200),sourceInMs:z148.int().nonnegative().max(30150),sourceOutMs:z148.int().positive().max(30150)}),z148.strictObject({kind:z148.literal("REVISE_CAPTIONS"),content:CaptionContentSchema}),z148.strictObject({kind:z148.literal("ADJUST_TRANSITION"),ordinal:z148.int().min(2).max(200),transition:ClipTransitionSchema}),z148.strictObject({kind:z148.literal("ADJUST_AUDIO_COMPOSITION"),audio:TimelineAudioInputSchema}),z148.strictObject({kind:z148.literal("ACKNOWLEDGE_WARNINGS"),acknowledgements:z148.array(z148.strictObject({key:z148.string().min(1).max(220),reason:text})).min(1).max(300)}),z148.strictObject({kind:z148.literal("REGENERATE_SHOT"),shotId:z148.uuid()}),z148.strictObject({kind:z148.literal("REQUEST_HUMAN_INPUT"),question:text}),z148.strictObject({kind:z148.literal("REQUEST_CANONICAL_CHANGE"),requestedChange:text})]);var RepairStrategyAlternativeSchema=z148.strictObject({id:key5,rationale:text,whySmallerChangeInsufficient:text,action:RepairStrategyActionSchema});var ValidateRepairStrategySchema=z148.strictObject({basis:RepairStrategyBasisSchema,proposal:z148.strictObject({origin:z148.strictObject({kind:z148.literal("EXTERNAL_AGENT_HOST"),label:z148.string().trim().min(1).max(100)}),summary:text,alternatives:z148.array(RepairStrategyAlternativeSchema).min(1).max(6),selectedAlternativeId:key5})}).refine(v=>new TextEncoder().encode(JSON.stringify(v)).byteLength<=1024*1024,"Repair Strategy input exceeds the 1 MiB JSON budget");var RepairStrategyContextResultSchema=z148.strictObject({compositionRepairAvailable:z148.boolean().optional(),semanticStatus:z148.literal("SUCCESS"),advisory:z148.literal(true),basis:RepairStrategyBasisSchema,ownerContext:DirectorContextResultSchema,finding:RoughCutFindingViewSchema,reviewTarget:RoughCutReviewTargetSchema,finalReady:FinalReadyViewSchema,eligibility:z148.strictObject({ready:z148.boolean(),reasons:z148.array(z148.enum(["FINDING_NOT_OPEN","TARGET_STALE","MEDIA_UNAVAILABLE","PRODUCTION_UNAVAILABLE","REVIEW_CHANGED","FINDING_BASIS_CHANGED"])).max(6)})});var RepairStrategyHandoffSchema=z148.discriminatedUnion("kind",[CompositionRepairHandoffSchema,z148.strictObject({kind:z148.literal("TIMELINE_BUILD"),input:BuildTimelineShapeSchema.omit({idempotencyKey:true})}),z148.strictObject({kind:z148.literal("CAPTION_AUTHOR"),input:AuthorCaptionsSchema.omit({idempotencyKey:true})}),z148.strictObject({kind:z148.literal("FINAL_READY_DECIDE"),input:DecideFinalReadySchema.omit({idempotencyKey:true})}),z148.strictObject({kind:z148.literal("REGENERATION_INTENT"),preparationQuery:PreparationActiveInputSchema,admission:z148.literal("EXPLICIT_NATIVE_PREPARATION_AND_SELECTION_REQUIRED")}),z148.strictObject({kind:z148.literal("HUMAN_INPUT_INTENT"),question:text}),z148.strictObject({kind:z148.literal("CANONICAL_CHANGE_INTENT"),requestedChange:text})]);var RepairStrategyValidationResultSchema=z148.strictObject({semanticStatus:z148.literal("SUCCESS"),advisory:z148.literal(true),basis:RepairStrategyBasisSchema,proposal:ValidateRepairStrategySchema.shape.proposal,finding:RoughCutFindingViewSchema,alternatives:z148.array(z148.strictObject({alternativeId:key5,affectedScope:RoughCutFindingViewSchema.shape.affectedScope,handoff:RepairStrategyHandoffSchema,materialChange:z148.boolean(),preservedAcceptanceIds:z148.array(z148.uuid()).max(200),followUp:z148.array(z148.enum(["REVOKE_FINAL_READY_AND_REFRESH","REFRESH_TIMELINE_BASIS","ATTACH_NEW_CAPTION","REFRESH_AND_PREPARE_SHOT","EXPLICIT_VIDEO_GENERATION","REVIEW_1","SHOT_ACCEPTANCE","REBUILD_TIMELINE","ROUGH_CUT_RENDER","REVIEW_2","FINAL_READY_DECISION","AUTHORIZED_PLANNING_DECISION","COMPOSITION_REVISE","COMPOSITION_RENDER"])).max(10)})).min(1).max(6),selectedAlternativeId:key5,limitations:z148.tuple([z148.literal("NO_CANONICAL_REPAIR_LIFECYCLE_OR_WRITE"),z148.literal("READS_ARE_NOT_ATOMIC_OR_RESERVED"),z148.literal("CREATIVE_RATIONALE_IS_NOT_VERIFIED"),z148.literal("OWNER_RECHECKS_CAS_IDEMPOTENCY_AND_EXECUTION_CLASS"),z148.literal("MATERIAL_REPAIR_REQUIRES_NEW_OBSERVATION_AND_REVIEW")])}).superRefine((v,ctx)=>{const ids=v.alternatives.map(a=>a.alternativeId);const proposed=v.proposal.alternatives.map(a=>a.id);if(v.finding.id!==v.basis.findingId||v.finding.tenantId!==v.basis.scope.tenantId||v.finding.projectId!==v.basis.scope.projectId||v.finding.productionId!==v.basis.scope.productionId||v.selectedAlternativeId!==v.proposal.selectedAlternativeId||!ids.includes(v.selectedAlternativeId)||new Set(ids).size!==ids.length||ids.length!==proposed.length||ids.some(id15=>!proposed.includes(id15)))ctx.addIssue({code:"custom",message:"Repair validation must retain exact Finding and proposal selection"});for(const alternative of v.alternatives){const h=alternative.handoff;if("input"in h&&(h.input.tenantId!==v.basis.scope.tenantId||h.input.productionId!==v.basis.scope.productionId))ctx.addIssue({code:"custom",message:"Repair handoff must retain the exact native Tenant/Production scope"})}});import{z as z149}from"zod";var text2=z149.string().trim().min(1).max(2e3);var key6=z149.string().regex(/^[a-z][a-z0-9_-]{0,39}$/);var EditorContextInputSchema=z149.strictObject({scope:DirectorScopeSchema,timelineVersionId:z149.uuid()});var EditorBasisSchema=EditorContextInputSchema.extend({contextFingerprint:z149.string().regex(/^[0-9a-f]{64}$/)});var EditorAlternativeSchema=z149.strictObject({id:key6,rationale:text2,pacingIntent:text2,action:z149.discriminatedUnion("kind",[z149.strictObject({kind:z149.literal("BUILD_TIMELINE"),clips:BuildTimelineSchema.shape.clips}),z149.strictObject({kind:z149.literal("EDIT_GRAPHICS"),graphics:z149.array(TimelineGraphicInputSchema).min(1).max(8)}),z149.strictObject({kind:z149.literal("EDIT_VISUAL_LAYERS"),visualLayers:z149.array(TimelineVisualLayerInputSchema).min(1).max(8)}),z149.strictObject({kind:z149.literal("EDIT_AUDIO_COMPOSITION"),audio:TimelineAudioInputSchema}),z149.strictObject({kind:z149.literal("REVISE_CAPTIONS"),content:CaptionContentSchema}),z149.strictObject({kind:z149.literal("REQUEST_COMPOSITION_CAPABILITY"),concern:z149.enum(["TRANSITION","AUDIO_VISUAL_ALIGNMENT","VOICE_TIMING","CAPTION_RETIMING"]),requestedChange:text2}),z149.strictObject({kind:z149.literal("REQUEST_HUMAN_INPUT"),question:text2})])});var ValidateEditorProposalSchema=z149.strictObject({basis:EditorBasisSchema,proposal:z149.strictObject({origin:z149.strictObject({kind:z149.literal("EXTERNAL_AGENT_HOST"),label:z149.string().trim().min(1).max(100)}),summary:text2,alternatives:z149.array(EditorAlternativeSchema).min(1).max(6),selectedAlternativeId:key6})}).refine(v=>new TextEncoder().encode(JSON.stringify(v)).byteLength<=1024*1024,"Editor Intelligence input exceeds the 1 MiB JSON budget");var EditorContextResultSchema=z149.strictObject({semanticStatus:z149.literal("SUCCESS"),advisory:z149.literal(true),basis:EditorBasisSchema,ownerContext:DirectorContextResultSchema,timeline:TimelineViewSchema,timelineBasis:TimelineBasisSchema,finalReady:FinalReadyViewSchema,eligibility:z149.strictObject({ready:z149.boolean(),reasons:z149.array(z149.enum(["TIMELINE_NOT_CURRENT","TIMELINE_STALE","PRODUCTION_UNAVAILABLE","PLANNING_NOT_READY","CREATIVE_BASIS_CHANGED","NO_CURRENT_ACCEPTED_MEDIA","COMPOSITION_VERSION_UNSUPPORTED"])).max(7)})});var ReviewScope=z149.strictObject({kind:z149.literal("PRODUCTION"),interval:z149.strictObject({startMs:z149.literal(0),endMs:z149.int().positive().max(603e4)}),shotIds:z149.array(z149.uuid()).min(1).max(200),dimensions:z149.array(z149.enum(["PACING","ORDERING","CUT_CONTINUITY","PRODUCT_PRESENTATION","CAPTION_TIMING_VISIBILITY","AUDIO_VISUAL_ALIGNMENT","BASIC_MIX"])).min(4).max(7),requirement:z149.literal("COMPLETE_NEW_OUTPUT_INSPECTION")});var EditorHandoffSchema=z149.discriminatedUnion("kind",[z149.strictObject({kind:z149.literal("TIMELINE_BUILD"),input:BuildTimelineShapeSchema.omit({idempotencyKey:true}),preview:TimelineManifestReaderSchema,assemblyStatus:z149.enum(["DRAFT","ASSEMBLY_READY"]),changedOrdinals:z149.array(z149.int().positive().max(200)).max(200),changedGraphicArtifactIds:z149.array(z149.uuid()).max(8),changedAudioPurposes:z149.array(z149.enum(["VOICEOVER","MUSIC"])).max(2),preservedAcceptanceIds:z149.array(z149.uuid()).max(200),reviewScope:ReviewScope,followUp:z149.array(z149.enum(["NATIVE_TIMELINE_BUILD","COMPLETE_TIMELINE","ROUGH_CUT_RENDER","REVIEW_2","FINAL_READY_DECISION"])).min(4).max(5)}),z149.strictObject({kind:z149.literal("CAPTION_AUTHOR"),input:AuthorCaptionsSchema.omit({idempotencyKey:true}),attachment:z149.strictObject({expectedTimelineVersion:z149.int().positive(),preserveCurrentComposition:z149.literal(true),composition:z149.strictObject({schemaVersion:BuildTimelineShapeSchema.shape.schemaVersion,clips:BuildTimelineSchema.shape.clips,audio:BuildTimelineSchema.shape.audio.optional(),sourceSound:BuildTimelineShapeSchema.shape.sourceSound,graphics:BuildTimelineSchema.shape.graphics.optional(),visualLayers:BuildTimelineShapeSchema.shape.visualLayers})}),followUp:z149.tuple([z149.literal("NATIVE_CAPTION_AUTHOR"),z149.literal("ATTACH_NEW_CAPTION_TO_TIMELINE"),z149.literal("ROUGH_CUT_RENDER"),z149.literal("REVIEW_2"),z149.literal("FINAL_READY_DECISION")])}),z149.strictObject({kind:z149.literal("COMPOSITION_CAPABILITY_INTENT"),concern:z149.enum(["TRANSITION","AUDIO_VISUAL_ALIGNMENT","VOICE_TIMING","CAPTION_RETIMING"]),requestedChange:text2,admission:z149.literal("EXPLICIT_CANONICAL_CAPABILITY_REQUIRED")}),z149.strictObject({kind:z149.literal("HUMAN_INPUT_INTENT"),question:text2})]);var EditorValidationResultSchema=z149.strictObject({semanticStatus:z149.literal("SUCCESS"),advisory:z149.literal(true),basis:EditorBasisSchema,proposal:ValidateEditorProposalSchema.shape.proposal,alternatives:z149.array(z149.strictObject({alternativeId:key6,handoff:EditorHandoffSchema})).min(1).max(6),selectedAlternativeId:key6,limitations:z149.tuple([z149.literal("NO_TIMELINE_WRITE_RENDER_OR_PROVIDER_CALL"),z149.literal("READS_ARE_NOT_ATOMIC_OR_RESERVED"),z149.literal("CREATIVE_RATIONALE_IS_NOT_VERIFIED"),z149.literal("OWNER_RECHECKS_CAS_IDEMPOTENCY_AND_EXECUTION_CLASS"),z149.literal("EDIT_REQUIRES_NEW_OUTPUT_INSPECTION_AND_REVIEW")])});import{z as z150}from"zod";var scope5={tenantId:z150.uuid(),productionId:z150.uuid()};var TemporalEvidenceTargetSchema=z150.strictObject({...scope5,artifactId:z150.uuid(),representationId:z150.uuid(),checksumSha256:z150.string().regex(/^[0-9a-f]{64}$/)});var OriginalVideoReadSchema=TemporalEvidenceTargetSchema;var OriginalVideoResultSchema=z150.strictObject({source:TemporalEvidenceSourceSchema,contentType:z150.literal("video/mp4"),dataBase64:z150.string().min(4).max(4*Math.ceil(8*1024*1024/3)).regex(/^[A-Za-z0-9+/]+={0,2}$/)}).refine(v=>{const padding=v.dataBase64.endsWith("==")?2:v.dataBase64.endsWith("=")?1:0;return v.dataBase64.length%4===0&&v.source.byteSize<=8*1024*1024&&v.dataBase64.length/4*3-padding===v.source.byteSize},"Original video must match its exact bounded byte size");var TemporalEvidenceStartSchema=TemporalEvidenceTargetSchema.extend({profile:TemporalSamplingProfileSchema,expectedProductionRevision:z150.int().positive(),idempotencyKey:z150.string().trim().min(1).max(128),deviceId:z150.uuid().toLowerCase().optional()});var TemporalEvidenceGetSchema=z150.strictObject({...scope5,evidenceId:z150.uuid()});var TemporalEvidenceAdmissionSchema=z150.strictObject({semanticStatus:z150.literal("ACCEPTED"),evidenceId:z150.uuid(),runtimeJobId:z150.uuid(),operationId:z150.string().min(1),source:TemporalEvidenceSourceSchema,planFingerprint:z150.string().regex(/^[0-9a-f]{64}$/),productionRevision:z150.int().positive()});var TemporalEvidenceOutputSchema=z150.strictObject({frameSetArtifactId:z150.uuid(),manifestRepresentationId:z150.uuid(),frameRepresentationIds:z150.array(z150.uuid()).min(1).max(64),contactSheetArtifactId:z150.uuid(),sheetRepresentationId:z150.uuid(),manifest:TemporalEvidenceManifestSchema,createdAt:z150.iso.datetime({offset:true})}).refine(v=>v.frameRepresentationIds.length===v.manifest.frames.length&&new Set(v.frameRepresentationIds).size===v.frameRepresentationIds.length,"Exact frame representations must be complete and unique");var TemporalEvidenceViewSchema=z150.strictObject({evidenceId:z150.uuid(),runtimeJobId:z150.uuid(),operationId:z150.string().min(1),source:TemporalEvidenceSourceSchema,planFingerprint:z150.string().regex(/^[0-9a-f]{64}$/),runtimeState:z150.enum(["PENDING","READY","RUNNING","WAITING","SUCCEEDED","FAILED","CANCELLED","SUPERSEDED"]),output:TemporalEvidenceOutputSchema.nullable()});var TemporalEvidenceMediaSchema=TemporalEvidenceGetSchema.extend({kind:z150.enum(["FRAME","SHEET","MANIFEST"]),ordinal:z150.int().nonnegative().max(63).optional()}).refine(v=>v.kind==="FRAME"?v.ordinal!==void 0:v.ordinal===void 0,"Only individual frames require an ordinal");var TemporalEvidenceImageSchema=TemporalEvidenceMediaSchema.safeExtend({kind:z150.enum(["FRAME","SHEET"])});var TemporalEvidenceImageMetadataSchema=TemporalEvidenceImageSchema.safeExtend({contentType:z150.literal("image/png"),checksumSha256:z150.string().regex(/^[0-9a-f]{64}$/),byteSize:z150.int().positive().max(16*1024*1024)});import{z as z151}from"zod";var Text2=z151.string().trim().min(1).max(1e3);var bounded=(value2,bytes)=>new TextEncoder().encode(JSON.stringify(value2)).byteLength<=bytes;var ExplorationComparisonCriterionSchema=z151.strictObject({key:ReviewEvidenceKeySchema,description:Text2,modality:z151.enum(["VISUAL","TEMPORAL"])});var ExplorationRecommendationContextInputSchema=ExplorationCompareInputSchema.extend({criteria:z151.array(ExplorationComparisonCriterionSchema).min(1).max(8)}).superRefine((v,c)=>{if(new Set(v.items.map(i=>i.mediaType)).size!==1)c.addIssue({code:"custom",message:"Recommendation compares one media type"});if(new Set(v.items.map(i=>i.label)).size!==v.items.length||new Set(v.items.map(i=>i.generationId.toLowerCase())).size!==v.items.length)c.addIssue({code:"custom",message:"Labels and generation identities must be distinct"});if(new Set(v.criteria.map(i=>i.key)).size!==v.criteria.length)c.addIssue({code:"custom",message:"Comparison criterion keys must be distinct"});if(v.items[0].mediaType==="IMAGE"&&v.criteria.some(i=>i.modality==="TEMPORAL"))c.addIssue({code:"custom",message:"Temporal comparison requires VIDEO"});if(!bounded(v,1024*1024))c.addIssue({code:"custom",message:"Recommendation input exceeds 1 MiB"})});var ExplorationRecommendationBasisSchema=z151.strictObject({input:ExplorationRecommendationContextInputSchema,contextFingerprint:z151.string().regex(/^[0-9a-f]{64}$/)});var ExplorationRecommendationCandidateSchema=z151.strictObject({label:ReviewEvidenceKeySchema,readiness:z151.enum(["REVIEWABLE","UNAVAILABLE"]),reasons:z151.array(z151.enum(["NO_CANDIDATE","STALE_BASIS","PRODUCTION_NOT_RUNNABLE","OUTPUT_NOT_INSPECTABLE"])).max(4),reviewContext:ReviewIntelligenceContextResultSchema.nullable()});var ExplorationRecommendationContextResultSchema=z151.strictObject({semanticStatus:z151.literal("SUCCESS"),advisory:z151.literal(true),basis:ExplorationRecommendationBasisSchema,comparison:ExplorationComparisonResultSchema,candidates:z151.array(ExplorationRecommendationCandidateSchema).min(2).max(6),limitations:z151.tuple([z151.literal("READS_ARE_NOT_ATOMIC_OR_RESERVED"),z151.literal("NO_IMPLICIT_MEDIA_OR_MODEL_CALL")])}).refine(v=>bounded(v,2*1024*1024),"Recommendation context exceeds 2 MiB");var ExplorationComparisonJudgmentSchema=z151.strictObject({label:ReviewEvidenceKeySchema,criterionKey:ReviewEvidenceKeySchema,judgment:z151.enum(["FAVORABLE","UNFAVORABLE","UNCERTAIN","NOT_OBSERVABLE"]),rationale:Text2,evidenceIds:z151.array(ReviewEvidenceKeySchema).max(16)});var ExplorationRecommendationDecisionSchema=z151.discriminatedUnion("kind",[z151.strictObject({kind:z151.literal("RECOMMEND"),label:ReviewEvidenceKeySchema,rationale:Text2,notSelected:z151.array(z151.strictObject({label:ReviewEvidenceKeySchema,reason:Text2})).min(1).max(5)}),z151.strictObject({kind:z151.literal("NO_RECOMMENDATION"),reason:Text2})]);var ValidateExplorationRecommendationSchema=z151.strictObject({basis:ExplorationRecommendationBasisSchema,proposal:z151.strictObject({origin:z151.strictObject({kind:z151.literal("EXTERNAL_AGENT_HOST"),label:z151.string().trim().min(1).max(100)}),summary:z151.string().trim().min(1).max(2e3),assessments:z151.array(z151.strictObject({label:ReviewEvidenceKeySchema,reviewProposal:ValidateReviewIntelligenceSchema.shape.proposal})).max(6),judgments:z151.array(ExplorationComparisonJudgmentSchema).max(48),decision:ExplorationRecommendationDecisionSchema,unknowns:z151.array(z151.string().trim().min(1).max(300)).max(8)})}).refine(v=>bounded(v,1024*1024),"Recommendation input exceeds 1 MiB");var ExplorationRecommendationValidationResultSchema=z151.strictObject({semanticStatus:z151.literal("SUCCESS"),advisory:z151.literal(true),basis:ExplorationRecommendationBasisSchema,origin:ValidateExplorationRecommendationSchema.shape.proposal.shape.origin,summary:z151.string(),judgments:z151.array(ExplorationComparisonJudgmentSchema).max(48),decision:ExplorationRecommendationDecisionSchema,unknowns:z151.array(z151.string()).max(8),reviews:z151.array(z151.strictObject({label:ReviewEvidenceKeySchema,validation:ReviewIntelligenceValidationResultSchema})).max(6),limitations:z151.tuple([z151.literal("HOST_PREFERENCE_IS_NOT_CANONICAL_SELECTION"),z151.literal("EVIDENCE_DECLARATIONS_ARE_NOT_ATTESTED_INSPECTION"),z151.literal("RULE_PREVIEWS_ARE_NOT_CANONICAL_REVIEWS"),z151.literal("EXPLICIT_RECORD_AND_SEPARATE_ACCEPTANCE_REQUIRED"),z151.literal("OWNER_RECHECKS_CURRENTNESS_CAS_AND_EXECUTION_CLASS")])}).refine(v=>bounded(v,4*1024*1024),"Recommendation result exceeds 4 MiB");import{z as z153}from"zod";import{z as z152}from"zod";var Review1FindingSchema=z152.strictObject({id:z152.uuid(),tenantId:TenantIdSchema,projectId:ProjectIdSchema,productionId:ProductionIdSchema,shotId:ShotIdSchema,mediaType:z152.enum(["IMAGE","VIDEO"]),framePurpose:z152.string().max(40).optional(),generationId:z152.uuid(),candidateId:z152.uuid(),reviewId:z152.uuid(),artifactId:z152.uuid(),representationId:z152.uuid(),checksumSha256:z152.string().regex(/^[0-9a-f]{64}$/),preparationId:z152.uuid(),contractId:z152.uuid(),contractFingerprint:z152.string().regex(/^[0-9a-f]{64}$/),executionClass:z152.enum(["LIVE","TEST_ONLY"]),requirement:z152.union([VideoReviewRequirementSchema,VisualRequirementSchema]),observation:z152.union([VideoObservationSchema,KeyframeObservationSchema]),blocking:z152.boolean(),severity:z152.enum(["BLOCKING","WARNING"]),basisFingerprint:z152.string().regex(/^[0-9a-f]{64}$/),createdAt:z152.iso.datetime({offset:true})}).superRefine((v,c)=>{if(v.requirement.key!==v.observation.key||v.blocking!==(v.severity==="BLOCKING"))c.addIssue({code:"custom",message:"Finding must bind its exact native obligation"})});var Review1FindingViewSchema=Review1FindingSchema.safeExtend({lifecycle:z152.enum(["OPEN","REMEDIATION_PLANNED","RESOLVED","SUPERSEDED"]),proofReviewId:z152.uuid().nullable()});var Review1RepairSourceSchema=z152.strictObject(Review1FindingSchema.shape).omit({id:true,createdAt:true}).superRefine((v,c)=>{if(v.requirement.key!==v.observation.key||v.blocking!==(v.severity==="BLOCKING"))c.addIssue({code:"custom",message:"Source must bind its exact native obligation"})});var Review1RepairSourceQuerySchema=z152.strictObject({tenantId:TenantIdSchema,projectId:ProjectIdSchema,productionId:ProductionIdSchema,mediaType:z152.enum(["IMAGE","VIDEO"]),generationId:z152.uuid(),reviewId:z152.uuid(),requirementKey:z152.string().min(1).max(220)});var sha20=z153.string().regex(/^[0-9a-f]{64}$/);var handoffs={REVISE_COMPOSITION:"COMPOSITION_REVISE",TRIM_CLIP:"TIMELINE_BUILD",ADJUST_TRANSITION:"TIMELINE_BUILD",ADJUST_AUDIO_COMPOSITION:"TIMELINE_BUILD",REVISE_CAPTIONS:"CAPTION_AUTHOR",ACKNOWLEDGE_WARNINGS:"FINAL_READY_DECIDE",REGENERATE_SHOT:"REGENERATION_INTENT",REQUEST_HUMAN_INPUT:"HUMAN_INPUT_INTENT",REQUEST_CANONICAL_CHANGE:"CANONICAL_CHANGE_INTENT"};var SemanticRepairBudgetSchema=z153.strictObject({maxSemanticAttempts:z153.int().min(1).max(20),maxElapsedMs:z153.int().min(1).max(864e5),currency:z153.literal("USD"),maxCostMicros:z153.int().min(0).max(1e9),maxConsecutiveNoImprovement:z153.int().min(1).max(20)});var RepairPlanScopeSchema=z153.strictObject({tenantId:TenantIdSchema,productionId:ProductionIdSchema,planId:z153.uuid()});var AuthorRepairPlanSchema=z153.strictObject({strategy:ValidateRepairStrategySchema,expectedProductionRevision:z153.int().positive(),expectedCaseVersion:z153.int().nonnegative(),budget:SemanticRepairBudgetSchema,idempotencyKey:z153.string().trim().min(1).max(200)}).superRefine((v,c)=>{const p=v.strategy.proposal;if(new Set(p.alternatives.map(a=>a.id)).size!==p.alternatives.length||!p.alternatives.some(a=>a.id===p.selectedAlternativeId))c.addIssue({code:"custom",message:"Repair authoring requires unique alternatives and an explicit selection"})});var RepairDecisionSchema=z153.strictObject({id:z153.uuid(),tenantId:TenantIdSchema,projectId:ProjectIdSchema,productionId:ProductionIdSchema,caseId:z153.uuid(),caseVersion:z153.int().positive(),basis:RepairStrategyBasisSchema,sourceReviewId:z153.uuid(),sourceRenderId:z153.uuid().nullable(),review1Source:Review1FindingSchema.optional(),sourceBasisFingerprint:sha20,affectedScopeFingerprint:sha20,obligationFingerprint:sha20,proposal:ValidateRepairStrategySchema.shape.proposal,selectedAlternativeId:z153.string().regex(/^[a-z][a-z0-9_-]{0,39}$/),handoff:RepairStrategyHandoffSchema,budget:SemanticRepairBudgetSchema,createdByPrincipalId:PrincipalIdSchema,createdAt:z153.iso.datetime({offset:true})}).superRefine((d,c)=>{if(d.sourceRenderId===null!==!!d.review1Source||d.review1Source&&(d.review1Source.id!==d.basis.findingId||d.review1Source.reviewId!==d.sourceReviewId||d.review1Source.tenantId!==d.tenantId||d.review1Source.projectId!==d.projectId||d.review1Source.productionId!==d.productionId||d.handoff.kind!=="REGENERATION_INTENT"))c.addIssue({code:"custom",message:"Repair must retain its native Review layer and source"});if(d.basis.scope.tenantId!==d.tenantId||d.basis.scope.productionId!==d.productionId||d.basis.scope.projectId!==d.projectId)c.addIssue({code:"custom",message:"Repair Decision scope must be exactly owned"});if(d.selectedAlternativeId!==d.proposal.selectedAlternativeId||new Set(d.proposal.alternatives.map(a=>a.id)).size!==d.proposal.alternatives.length||!d.proposal.alternatives.some(a=>a.id===d.selectedAlternativeId&&handoffs[a.action.kind]===d.handoff.kind))c.addIssue({code:"custom",message:"Repair Decision must bind the explicit selected alternative"})});var SemanticRepairAttemptSchema=z153.strictObject({id:z153.uuid(),planId:z153.uuid(),caseId:z153.uuid(),ordinal:z153.int().min(1).max(20),executionIdentity:z153.string().trim().min(1).max(200),strategyFingerprint:sha20,startedAt:z153.iso.datetime({offset:true}),reservedCostMicros:z153.int().min(0).max(1e9),chargedCostMicros:z153.int().min(0).max(1e9).nullable(),currency:z153.literal("USD"),outcome:z153.enum(["IN_FLIGHT","AWAITING_REVIEW","IMPROVED","NO_IMPROVEMENT","OPERATIONAL_FAILURE","WAIVED"])});var RecordRepairProofSchema=RepairPlanScopeSchema.extend({attemptId:z153.uuid(),renderId:z153.uuid(),reviewId:z153.uuid(),expectedProductionRevision:z153.int().positive(),idempotencyKey:z153.string().trim().min(1).max(200)});import{z as z154}from"zod";var AuthorReview1RepairSchema=z154.strictObject({tenantId:TenantIdSchema,projectId:ProjectIdSchema,productionId:ProductionIdSchema,mediaType:z154.enum(["IMAGE","VIDEO"]),generationId:z154.uuid(),reviewId:z154.uuid(),requirementKey:z154.string().min(1).max(220),reason:z154.string().trim().min(1).max(2e3),expectedProductionRevision:z154.int().positive(),expectedCaseVersion:z154.int().nonnegative(),budget:SemanticRepairBudgetSchema,idempotencyKey:z154.string().trim().min(1).max(200)});var RecordReview1RepairProofSchema=RepairPlanScopeSchema.extend({attemptId:z154.uuid(),generationId:z154.uuid(),reviewId:z154.uuid(),expectedProductionRevision:z154.int().positive(),idempotencyKey:z154.string().trim().min(1).max(200)});import{z as z155}from"zod";var ExecuteRepairSchema=RepairPlanScopeSchema.extend({expectedProductionRevision:z155.int().positive(),expectedCaseVersion:z155.int().positive(),idempotencyKey:z155.string().trim().min(1).max(200),generation:VideoStartInputSchema.omit({idempotencyKey:true}).optional(),keyframeGeneration:KeyframeStartInputSchema.omit({idempotencyKey:true}).optional()});var RepairAttemptEventSchema=z155.strictObject({id:z155.uuid(),attemptId:z155.uuid(),version:z155.int().positive(),outcome:SemanticRepairAttemptSchema.shape.outcome.exclude(["IN_FLIGHT"]),renderId:z155.uuid().nullable(),reviewId:z155.uuid().nullable(),generationId:z155.uuid().optional(),recordedAt:z155.iso.datetime({offset:true})});var RepairAttemptViewSchema=SemanticRepairAttemptSchema.extend({costQuote:GenerationCostQuoteSchema.optional(),events:z155.array(RepairAttemptEventSchema).max(40)});var RepairCaseViewSchema=z155.strictObject({id:z155.uuid(),version:z155.int().positive(),issueKey:z155.string().regex(/^[0-9a-f]{64}$/),budget:SemanticRepairBudgetSchema,openedAt:z155.iso.datetime({offset:true})});var RepairPlanViewSchema=z155.strictObject({review1Finding:Review1FindingViewSchema.optional(),decision:RepairDecisionSchema,repairCase:RepairCaseViewSchema,attempts:z155.array(RepairAttemptViewSchema).max(20)});var RepairAuthorReceiptSchema=z155.strictObject({semanticStatus:z155.literal("SUCCESS"),decision:RepairDecisionSchema,productionRevision:z155.int().positive()});var RepairExecutionReceiptSchema=z155.strictObject({costQuote:GenerationCostQuoteSchema.optional(),semanticStatus:z155.literal("ACCEPTED"),attempt:SemanticRepairAttemptSchema,decision:RepairDecisionSchema,productionRevision:z155.int().positive(),generation:ExecuteRepairSchema.shape.generation.nullable(),keyframeGeneration:ExecuteRepairSchema.shape.keyframeGeneration.nullable().optional()});var RepairProgressSchema=z155.strictObject({view:RepairPlanViewSchema,stage:z155.enum(["WAITING_INPUT","WAITING_GENERATION","WAITING_COMPOSITION_RENDER","WAITING_SOURCE_ACCEPTANCE","WAITING_RENDER","AWAITING_REVIEW","WAIVED","OPERATIONAL_FAILURE","IMPROVED","NO_IMPROVEMENT"]),renderId:z155.uuid().nullable(),generationId:z155.uuid().nullable()});var RepairProofReceiptSchema=z155.strictObject({semanticStatus:z155.literal("SUCCESS"),event:RepairAttemptEventSchema,productionRevision:z155.int().positive()});import{z as z156}from"zod";var EXTERNAL_EVENT_TYPES=["production.work_changed","production.started","production.failed","production.cancelled","finding.opened","artifact.created","shot.candidate_ready","shot.accepted","review.completed","rough_cut.ready","final_render.ready","approval.required","production.completed","delivery.validation_failed"];var ExternalEventTypeSchema=z156.enum(EXTERNAL_EVENT_TYPES);var LifecycleEventScopeSchema=z156.object({tenantId:TenantIdSchema,productionId:ProductionIdSchema}).strict();var ExternalLifecycleEventSchema=z156.object({schemaVersion:z156.literal(1),eventId:z156.uuid(),tenantId:TenantIdSchema,productionId:ProductionIdSchema,projectId:z156.uuid(),type:ExternalEventTypeSchema,target:z156.object({type:z156.string().min(1).max(60),id:z156.uuid()}).strict(),occurredAt:z156.iso.datetime(),basis:z156.object({productionRevision:z156.number().int().positive()}).strict(),payload:z156.object({sourceEventType:z156.string().min(1).max(100),artifactId:z156.uuid().optional(),candidateId:z156.uuid().optional(),reviewId:z156.uuid().optional(),findingId:z156.uuid().optional(),shotId:z156.uuid().optional(),manifestId:z156.uuid().optional(),validationId:z156.uuid().optional(),action:z156.string().max(40).optional(),result:z156.string().max(40).optional(),executionClass:z156.enum(["LIVE","TEST_ONLY"]).optional()}).strict()}).strict();var WebhookEndpointSchema=z156.url().max(2048).refine(value2=>{const u=new URL(value2);return u.protocol==="https:"&&!u.username&&!u.password&&!u.hash&&(!u.port||u.port==="443")&&!u.hostname.startsWith("[")});var ConfigureWebhookSchema=LifecycleEventScopeSchema.extend({subscriptionId:z156.uuid(),expectedRevision:z156.number().int().nonnegative(),idempotencyKey:z156.string().min(1).max(128),endpoint:WebhookEndpointSchema,eventTypes:z156.array(ExternalEventTypeSchema).min(1).max(EXTERNAL_EVENT_TYPES.length).refine(v=>new Set(v).size===v.length),signingSecret:z156.string().min(32).max(256)}).strict();var PrepareWebhookSecretSchema=LifecycleEventScopeSchema.extend({subscriptionId:z156.uuid(),secretRef:z156.uuid(),signingSecret:z156.string().min(32).max(256)}).strict();var WebhookSecretReferenceSchema=PrepareWebhookSecretSchema.omit({signingSecret:true});var ConfigureWebhookReferenceSchema=ConfigureWebhookSchema.omit({signingSecret:true}).extend({secretRef:z156.uuid()}).strict();var WebhookAvailabilitySchema=z156.discriminatedUnion("status",[z156.strictObject({status:z156.literal("AVAILABLE"),reason:z156.literal("SIGNING_STORAGE_READY")}),z156.strictObject({status:z156.literal("UNCONFIGURED"),reason:z156.literal("SIGNING_STORAGE_NOT_CONFIGURED")}),z156.strictObject({status:z156.literal("UNAVAILABLE"),reason:z156.literal("SIGNING_STORAGE_UNAVAILABLE")})]);var DisableWebhookSchema=LifecycleEventScopeSchema.extend({subscriptionId:z156.uuid(),expectedRevision:z156.number().int().positive(),idempotencyKey:z156.string().min(1).max(128)}).strict();var ReplayWebhookSchema=DisableWebhookSchema.extend({eventId:z156.uuid()}).strict();var QueryLifecycleEventsSchema=LifecycleEventScopeSchema.extend({kind:z156.enum(["subscriptions","events","deliveries","attempts"]),subscriptionId:z156.uuid().optional(),deliveryId:z156.uuid().optional(),after:z156.uuid().optional(),limit:z156.number().int().min(1).max(50).default(20)}).strict().refine(v=>v.kind!=="attempts"||!!v.deliveryId);var WebhookSubscriptionSchema=LifecycleEventScopeSchema.extend({subscriptionId:z156.uuid(),version:z156.number().int().positive(),revision:z156.number().int().positive(),state:z156.enum(["ACTIVE","DISABLED","DEGRADED"]),endpoint:WebhookEndpointSchema,eventTypes:z156.array(ExternalEventTypeSchema),updatedAt:z156.iso.datetime()}).strict();import{z as z157}from"zod";var WebhookReplayReceiptSchema=z157.strictObject({deliveryId:z157.uuid(),eventId:z157.uuid(),runtimeJobId:z157.uuid()});var WebhookDeliveryViewSchema=z157.strictObject({deliveryId:z157.uuid(),eventId:z157.uuid(),subscriptionId:z157.uuid(),subscriptionVersion:z157.int().positive(),replayNumber:z157.int().nonnegative(),runtimeJobId:z157.uuid(),lifecycle:z157.enum(["PENDING","READY","RUNNING","WAITING","SUCCEEDED","FAILED","CANCELLED","SUPERSEDED"]),runtimeAttempts:z157.int().nonnegative(),wakeAt:z157.iso.datetime({offset:true}).nullable()});var WebhookAttemptViewSchema=z157.strictObject({attemptId:z157.uuid(),runtimeAttemptId:z157.uuid(),outcome:z157.enum(["STARTED","ACKNOWLEDGED","TRANSIENT","PERMANENT","SKIPPED"]),responseStatus:z157.int().min(100).max(599).nullable(),startedAt:z157.iso.datetime({offset:true}),endedAt:z157.iso.datetime({offset:true}).nullable()});var page={next:z157.uuid().nullable()};var WebhookSubscriptionPageSchema=z157.strictObject({...page,items:z157.array(WebhookSubscriptionSchema).max(50)});var ExternalLifecycleEventPageSchema=z157.strictObject({...page,items:z157.array(ExternalLifecycleEventSchema).max(50)});var WebhookDeliveryPageSchema=z157.strictObject({...page,items:z157.array(WebhookDeliveryViewSchema).max(50)});var WebhookAttemptPageSchema=z157.strictObject({...page,items:z157.array(WebhookAttemptViewSchema).max(50)});var LifecycleEventCapabilitiesSchema=z157.strictObject({configuration:WebhookAvailabilitySchema,readinessScope:z157.literal("CURRENT_PROCESS_SIGNING_STORAGE"),deliveryConfirmation:z157.literal("READ_NATIVE_DELIVERIES_AND_ATTEMPTS"),eventTypes:z157.array(ExternalEventTypeSchema).max(14),unavailableNativeEvents:z157.array(z157.enum(["production.failed","production.cancelled","finding.opened"])).max(3),delivery:z157.literal("AT_LEAST_ONCE"),payload:z157.literal("QUERY_NOTIFICATION"),scope:z157.literal("PRODUCTION"),automaticOutboundAttempts:z157.literal(3),manualReplaysPerEvent:z157.literal(3),projectOnlyArtifacts:z157.literal("UNAVAILABLE"),orderingGuaranteed:z157.literal(false),signature:z157.literal("HMAC_SHA256_TIMESTAMP_DOT_EXACT_BODY")});import{z as z158}from"zod";var sha21=z158.string().regex(/^[0-9a-f]{64}$/);var CompositionSourceInspectSchema=CompositionGetSchema.extend({versionId:z158.uuid(),fingerprint:sha21,file:CompositionPathSchema.optional(),startLine:z158.int().min(1).max(8388609).default(1),lineLimit:z158.int().min(1).max(200).default(80)});var CompositionSourceInspectionSchema=z158.strictObject({composition:CompositionViewSchema,source:CompositionInputFactSchema,byteReadback:z158.literal("VERIFIED"),selection:z158.strictObject({file:CompositionPathSchema.nullable(),startLine:z158.int().positive(),lineLimit:z158.int().min(1).max(200)}),files:z158.array(z158.strictObject({path:CompositionPathSchema,contentType:z158.string().max(80),byteSize:z158.int().nonnegative().max(8388608),lineCount:z158.int().positive().max(8388609)})).min(1).max(128),window:z158.strictObject({file:CompositionPathSchema,startLine:z158.int().positive(),lines:z158.array(z158.strictObject({number:z158.int().positive(),text:z158.string().max(65536)})).max(200),hasMore:z158.boolean(),nextLine:z158.int().positive().nullable()}).nullable(),limitations:z158.tuple([z158.literal("SOURCE_INSPECTION_IS_NOT_OUTPUT_REVIEW"),z158.literal("READS_ARE_NOT_ATOMIC_OR_RESERVED")])});var SourceReviewContextInputSchema=z158.strictObject({scope:DirectorScopeSchema,source:CompositionSourceInspectSchema,renderId:z158.uuid().optional()}).refine(i=>i.scope.tenantId===i.source.tenantId&&i.scope.productionId===i.source.productionId,"Source Review retains exact Tenant/Production scope");var SourceReviewContextSchema=z158.strictObject({semanticStatus:z158.literal("SUCCESS"),advisory:z158.literal(true),basis:z158.strictObject({input:SourceReviewContextInputSchema,contextFingerprint:sha21}),ownerContext:DirectorContextResultSchema,source:CompositionSourceInspectionSchema,render:CompositionRenderViewSchema.nullable(),outputReviewTarget:ProgrammaticVideoReviewTargetSchema.nullable(),limitations:z158.tuple([z158.literal("SOURCE_REASONING_DOES_NOT_CERTIFY_OUTPUT_QUALITY"),z158.literal("INDEPENDENT_OUTPUT_REVIEW_AND_ACCEPTANCE_REQUIRED"),z158.literal("READS_ARE_NOT_ATOMIC_OR_RESERVED")])});import{z as z159}from"zod";var key7=z159.string().regex(/^[a-z][a-z0-9_-]{0,39}$/);var ProgrammaticCompareSchema=z159.strictObject({scope:ExplorationScopeSchema,items:z159.array(z159.strictObject({label:key7,renderId:z159.uuid()})).min(2).max(6)}).superRefine((i,c)=>{if(new Set(i.items.map(v=>v.label)).size!==i.items.length||new Set(i.items.map(v=>v.renderId.toLowerCase())).size!==i.items.length)c.addIssue({code:"custom",message:"Programmatic labels and exact renders must be distinct"})});var ProgrammaticComparisonSchema=z159.strictObject({semanticStatus:z159.literal("SUCCESS"),advisory:z159.literal(true),scope:ExplorationScopeSchema,selection:ProgrammaticCompareSchema.shape.items,items:z159.array(z159.strictObject({label:key7,sourceKind:z159.literal("PROGRAMMATIC"),composition:CompositionViewSchema,render:CompositionRenderViewSchema,reviewTarget:ProgrammaticVideoReviewTargetSchema.nullable()})).min(2).max(6),limitations:z159.tuple([z159.literal("OWNER_STATES_ARE_NOT_VISUAL_SCORES"),z159.literal("REVIEW_AND_ACCEPTANCE_REMAIN_EXPLICIT")])}).superRefine((v,c)=>{if(v.items.length!==v.selection.length||v.items.some((item,i)=>item.label!==v.selection[i].label||item.render.receipt.renderId!==v.selection[i].renderId))c.addIssue({code:"custom",message:"Programmatic comparison retains every exact selected label/render"});for(const item of v.items){const owner=item.composition.version,target3=item.reviewTarget;if(owner.tenantId!==v.scope.tenantId||owner.projectId!==v.scope.projectId||owner.productionId!==v.scope.productionId||owner.basis.shotId!==v.scope.shotId||owner.content.role!=="PRIMARY_VISUAL"||owner.id!==item.render.receipt.compositionVersionId||target3&&(target3.renderId!==item.render.receipt.renderId||target3.compositionVersionId!==owner.id||target3.tenantId!==v.scope.tenantId||target3.projectId!==v.scope.projectId||target3.productionId!==v.scope.productionId||target3.shotId!==v.scope.shotId))c.addIssue({code:"custom",message:"Programmatic comparison retains exact native source/output scope"})}}).refine(i=>new TextEncoder().encode(JSON.stringify(i)).byteLength<=2*1024*1024,"Programmatic comparison exceeds2MiB");var ProgrammaticRecommendationContextInputSchema=ProgrammaticCompareSchema.safeExtend({criteria:z159.array(ExplorationComparisonCriterionSchema).min(1).max(8)}).refine(i=>new Set(i.criteria.map(v=>v.key)).size===i.criteria.length,"Criteria must be distinct");var ProgrammaticRecommendationBasisSchema=z159.strictObject({input:ProgrammaticRecommendationContextInputSchema,contextFingerprint:z159.string().regex(/^[0-9a-f]{64}$/)});var ProgrammaticRecommendationContextSchema=z159.strictObject({semanticStatus:z159.literal("SUCCESS"),advisory:z159.literal(true),basis:ProgrammaticRecommendationBasisSchema,comparison:ProgrammaticComparisonSchema,candidates:z159.array(ExplorationRecommendationCandidateSchema).min(2).max(6),limitations:z159.tuple([z159.literal("READS_ARE_NOT_ATOMIC_OR_RESERVED"),z159.literal("NO_IMPLICIT_MEDIA_OR_MODEL_CALL")])}).superRefine((v,c)=>{if(JSON.stringify(v.basis.input.scope)!==JSON.stringify(v.comparison.scope)||JSON.stringify(v.basis.input.items)!==JSON.stringify(v.comparison.selection)||v.candidates.length!==v.comparison.items.length||v.candidates.some((candidate,i)=>candidate.label!==v.comparison.items[i].label))c.addIssue({code:"custom",message:"Programmatic Recommendation keeps exact comparison scope/selection"});for(const candidate of v.candidates){const target3=candidate.reviewContext?.reviewTarget;const item=v.comparison.items.find(i=>i.label===candidate.label);if(target3&&(target3.kind!=="PROGRAMMATIC"||target3.target.renderId!==item?.render.receipt.renderId||target3.target.compositionVersionId!==item.composition.version.id))c.addIssue({code:"custom",message:"Candidate assessment binds the exact native CODE output"})}}).refine(i=>new TextEncoder().encode(JSON.stringify(i)).byteLength<=2*1024*1024,"Programmatic recommendation context exceeds2MiB");var ValidateProgrammaticRecommendationSchema=z159.strictObject({basis:ProgrammaticRecommendationBasisSchema,proposal:ValidateExplorationRecommendationSchema.shape.proposal}).refine(i=>new TextEncoder().encode(JSON.stringify(i)).byteLength<=1024*1024,"Programmatic recommendation input exceeds1MiB");var ProgrammaticRecommendationValidationSchema=z159.strictObject({...ExplorationRecommendationValidationResultSchema.shape,basis:ProgrammaticRecommendationBasisSchema}).superRefine((v,c)=>{const s=v.basis.input.scope;for(const assessment of v.reviews){const item=v.basis.input.items.find(i=>i.label===assessment.label),draft2=assessment.validation.recordDraft;if(!item||draft2.kind!=="PROGRAMMATIC"||draft2.input.renderId!==item.renderId||draft2.input.tenantId!==s.tenantId||draft2.input.productionId!==s.productionId||assessment.validation.basis.scope.projectId!==s.projectId)c.addIssue({code:"custom",message:"Recommendation review draft binds exact CODE output and scope"})}}).refine(i=>new TextEncoder().encode(JSON.stringify(i)).byteLength<=4*1024*1024,"Programmatic recommendation result exceeds4MiB");import{z as z160}from"zod";var CompositionRenderQuerySchema=CompositionScopeSchema.extend({limit:z160.int().min(1).max(24).default(12),next:ContinuationSchema.optional(),shotId:z160.uuid().optional(),role:z160.enum(["PRIMARY_VISUAL","VISUAL_LAYER"]).default("PRIMARY_VISUAL")});var CompositionRenderObservationSchema=z160.strictObject({render:CompositionRenderViewSchema,createdAt:z160.iso.datetime({offset:true}),version:z160.int().positive(),executionClass:z160.enum(["LIVE","TEST_ONLY"]),freshness:z160.enum(["CURRENT_BASIS","STALE_BASIS"]),available:z160.boolean(),review:z160.strictObject({result:z160.enum(["UNREVIEWED","PASS","WARNING","FAIL"]),reviewId:z160.uuid().nullable(),acceptanceId:z160.uuid().nullable(),accepted:z160.boolean()})}).superRefine((v,ctx)=>{if(!v.render.sourceIdentity||v.review.result==="UNREVIEWED"!==(v.review.reviewId===null)||v.review.accepted!==(v.review.acceptanceId!==null)||v.review.accepted&&(!v.review.acceptanceId||!v.review.reviewId||!v.available||v.freshness!=="CURRENT_BASIS"||!["PASS","WARNING"].includes(v.review.result)))ctx.addIssue({code:"custom",message:"Observation requires exact native source/Review/acceptance identity"})});var CompositionRenderPageSchema=z160.strictObject({items:z160.array(CompositionRenderObservationSchema).max(24),page:QueryPageInfoSchema}).refine(v=>new TextEncoder().encode(JSON.stringify(v)).byteLength<=4194304,"Render observation page exceeds 4 MiB");var CompositionRenderMediaDescriptorSchema=z160.strictObject({path:z160.string().regex(/^\/v1\/productions\/[0-9a-f-]{36}\/compositions\/renders\/[0-9a-f-]{36}\/media$/i),contentType:z160.literal("video/mp4"),checksumSha256:z160.string().regex(/^[0-9a-f]{64}$/),byteSize:z160.int().positive().max(134217728),authentication:z160.literal("BEARER_AND_TENANT_HEADER")});import{z as z161}from"zod";var CompositionSampleStartSchema=CompositionRenderGetSchema.extend({expectedProductionRevision:z161.int().positive(),profile:TemporalSamplingProfileSchema,idempotencyKey:z161.string().trim().min(1).max(128)});var CompositionObserveGetSchema=CompositionRenderGetSchema.extend({evidenceId:z161.uuid()});var RenderObservationIdentitySchema=z161.strictObject({renderId:z161.uuid(),compositionVersionId:z161.uuid(),artifactId:z161.uuid(),representationId:z161.uuid(),checksumSha256:z161.string().regex(/^[0-9a-f]{64}$/)});var CompositionSampleReceiptSchema=RenderObservationIdentitySchema.extend({evidence:TemporalEvidenceAdmissionSchema,nextActions:z161.tuple([z161.literal("READ_OBSERVATION")])});var CompositionFrameObservationSchema=z161.strictObject({ordinal:z161.int().nonnegative().max(63),frameIndex:z161.int().nonnegative().max(3599),timestampMs:z161.number().nonnegative().max(6e4),checksumSha256:z161.string().regex(/^[0-9a-f]{64}$/),representationId:z161.uuid(),diagnostic:z161.literal("FRAME_EVIDENCE_READY")});var CompositionObservationViewSchema=RenderObservationIdentitySchema.extend({evidence:TemporalEvidenceViewSchema,frames:z161.array(CompositionFrameObservationSchema).max(64),contactSheetArtifactId:z161.uuid().nullable(),nextActions:z161.array(z161.enum(["READ_OBSERVATION","READ_FRAME_MEDIA","REVISE_COMPOSITION","RENDER_REVISION"])).min(1).max(4)});var scope6={projectId:ProjectIdSchema,productionId:ProductionIdSchema};var ScopedAcceptBriefSchema=AcceptBriefRequestSchema.extend(scope6);var ScopedAcceptStorySchema=AcceptStoryRequestSchema.extend(scope6);var ScopedAcceptSceneShotPlanSchema=AcceptSceneShotPlanRequestSchema.extend(scope6);import{z as z162}from"zod";var NativeToolAuthorityFailureSchema=z162.strictObject({semanticStatus:z162.enum(["INVALID_INPUT","NOT_FOUND","BLOCKED","REVISION_CONFLICT","CAPABILITY_UNAVAILABLE","INTERNAL_OPERATIONAL_FAILURE"]),error:z162.strictObject({code:z162.enum(["INVALID_INPUT","UNAUTHENTICATED","FORBIDDEN","NOT_FOUND","BINDING_UNAVAILABLE","REQUEST_CONFLICT","REVISION_CONFLICT","GRANT_CONFLICT","GRANT_EXPIRED","GRANT_REVOKED","PROOF_INVALID","PROOF_REPLAY","CHALLENGE_EXPIRED","PERMIT_UNAVAILABLE","QUALIFICATION_UNAVAILABLE","CREDENTIAL_INVALID","CREDENTIAL_EXPIRED","CREDENTIAL_UNAVAILABLE","CREDENTIAL_LIMIT","HOST_RUN_UNAVAILABLE","INTERNAL_OPERATIONAL_FAILURE"]),message:z162.literal("Native tool authority operation did not complete")})});import{z as z163}from"zod";var id12=z163.uuid().regex(/^[0-9a-f-]{36}$/);var sha22=z163.string().regex(/^[a-f0-9]{64}$/);var key8=z163.string().regex(/^[A-Za-z0-9_-]{1,160}$/);var NativeRuntimeQualificationSchema=z163.strictObject({protocol:z163.literal("NATIVESTUDIO_RUNTIME_TOOLS_V1"),runtimeKey:key8,installationId:key8,installationRevisionId:key8,resource:z163.url().max(2048),publicKeyFingerprint:sha22,bindingId:id12,configurationVersion:z163.int().positive(),selection:AgentHostReadSelectionSchema,capabilityDigest:sha22,executionClass:z163.enum(["LIVE","TEST_ONLY"]),transport:AgentHostInstallationTransportSchema.optional()});var NativeToolPermitSchema=z163.strictObject({proof:AgentHostNativeToolAuthoritySchema,input:AgentHostExecutionInputSchema,grant:NativeToolGrantViewSchema,qualification:NativeRuntimeQualificationSchema,requestedByPrincipalId:id12,createdAt:z163.iso.datetime({offset:true})}).refine(v=>v.proof.tenantId===v.input.tenantId&&v.proof.projectId===v.input.projectId&&v.proof.productionId===v.input.productionId&&v.proof.executionId===v.input.executionId&&v.proof.hostRequestId===v.input.hostRequestId&&v.grant.tenantId===v.input.tenantId&&v.grant.projectId===v.input.projectId&&v.grant.enabled&&v.grant.verifiedAt!==null&&v.proof.bindingId===v.grant.bindingId&&v.proof.configurationVersion===v.grant.configurationVersion&&v.qualification.runtimeKey===v.grant.runtimeKey&&v.qualification.installationId===v.grant.installationId&&v.qualification.installationRevisionId===v.grant.installationRevisionId&&v.qualification.resource===v.grant.resource&&v.qualification.bindingId===v.grant.bindingId&&v.qualification.configurationVersion===v.grant.configurationVersion&&v.qualification.capabilityDigest===v.proof.capabilityDigest&&v.qualification.executionClass===v.proof.executionClass&&(v.proof.transport===void 0?v.qualification.transport===void 0:v.qualification.transport?.protocol===v.proof.transport.protocol&&v.qualification.transport.installationId===v.proof.transport.installationId&&v.qualification.transport.installationRevisionId===v.proof.transport.installationRevisionId&&v.qualification.transport.slotKey===v.proof.transport.slotKey&&(v.proof.transport.protocol!=="NVS_AGENT_HOST_V1"||v.qualification.transport.protocol==="NVS_AGENT_HOST_V1"&&v.qualification.transport.contractDigest===v.proof.transport.contractDigest&&v.qualification.transport.capabilityDigest===v.proof.transport.capabilityDigest)&&v.proof.transport.installationId===v.grant.installationId&&v.proof.transport.installationRevisionId===v.grant.installationRevisionId)&&Date.parse(v.proof.expiresAt)<=Date.parse(v.grant.expiresAt));var NativeToolPermitGetSchema=AgentHostExecutionScopeSchema.extend({authorityRef:id12});var NativeExecutionProofClaimsSchema=AgentHostExecutionScopeSchema.extend({iss:key8,sub:key8,aud:z163.url().max(2048),grantId:id12,grantRevision:z163.int().positive(),installationRevisionId:key8,authorityRef:id12,executionId:id12,hostRequestId:id12,inputFingerprint:sha22,runKey:key8,jti:id12,iat:z163.int().nonnegative(),exp:z163.int().positive()}).refine(v=>v.exp>v.iat&&v.exp-v.iat<=60);var NativeToolCredentialExchangeSchema=NativeToolPermitGetSchema.extend({assertion:z163.string().regex(/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/).max(8192).meta({writeOnly:true})});var NativeToolCredentialMetadataSchema=NativeToolPermitGetSchema.extend({protocol:z163.literal("NATIVESTUDIO_NATIVE_CREDENTIAL_V1"),tokenId:id12,grantId:id12,grantRevision:z163.int().positive(),executionId:id12,hostRequestId:id12,runKey:key8,jti:id12,assertionFingerprint:sha22,tokenFingerprint:sha22,issuedAt:z163.iso.datetime({offset:true}),expiresAt:z163.iso.datetime({offset:true})});var NativeToolCredentialReplySchema=z163.strictObject({tokenType:z163.literal("Bearer"),accessToken:z163.string().regex(/^nvst_[0-9a-f-]{36}\.[A-Za-z0-9_-]{43}$/).meta({readOnly:true}),tokenId:id12,resource:z163.url().max(2048),expiresAt:z163.iso.datetime({offset:true})}).refine(v=>v.accessToken.startsWith(`nvst_${v.tokenId}.`));var NativeToolSessionSchema=NativeToolPermitGetSchema.extend({authorityProtocol:z163.literal("NVS_GENERIC_EXECUTION_V1").optional(),tokenId:id12,executionId:id12,hostRequestId:id12,grantId:id12,grantRevision:z163.int().positive(),runKey:key8,runtimePrincipalId:id12,approvedByPrincipalId:id12,requestedByPrincipalId:id12,capabilityDigest:sha22,resource:z163.url().max(2048),issuer:z163.url().max(2048),subject:z163.string().max(200),executionClass:z163.enum(["LIVE","TEST_ONLY"]),expiresAt:z163.iso.datetime({offset:true})});import{z as z164}from"zod";var CreateProductionRequestSchema=z164.strictObject({tenantId:TenantIdSchema,projectId:ProjectIdSchema,idempotencyKey:z164.string().trim().min(1).max(200)});var CreatedProductionResultSchema=CreatedProjectResultSchema;import{z as z165}from"zod";var sha23=z165.string().regex(/^[0-9a-f]{64}$/);var WavExportResultSchema=z165.strictObject({contentType:z165.literal("audio/wav"),checksumSha256:sha23,byteSize:z165.int().min(44).max(12582912),contentBase64:z165.string().min(60).max(16777216).regex(/^[A-Za-z0-9+/]+={0,2}$/)});var AudioExportResultSchema=WavExportResultSchema.extend({representationId:z165.uuid()});var CaptionExportResultSchema=z165.strictObject({contentType:z165.enum(["application/json","application/x-subrip"]),checksumSha256:sha23,representationId:z165.uuid(),text:z165.string().min(1).max(131072)});import{z as z166}from"zod";var tenant=TenantIdSchema.toLowerCase();var project=ProjectIdSchema.toLowerCase();var production=ProductionIdSchema.toLowerCase();var artifact=ArtifactIdSchema.toLowerCase();var representation=ArtifactRepresentationIdSchema.toLowerCase();var DiscoverableArtifactFamilySchema=z166.enum(["SOURCE","KEYFRAME_CANDIDATE","SHOT_CANDIDATE","COMPOSITION_RENDER_OUTPUT","ROUGH_CUT","FINAL_RENDER_OUTPUT","IMPORTED_VISUAL_ORIGINAL","IMPORTED_VISUAL_NORMALIZED","IMPORTED_VISUAL_POSTER","AUDIO","AUDIO_SOURCE_SYNC","CAPTION","CONTACT_SHEET"]);var DiscoveryContentTypeSchema=MediaBrowserContentTypeSchema;var ArtifactDiscoveryQuerySchema=z166.strictObject({tenantId:tenant,projectId:project.optional(),productionId:production.optional(),artifactId:artifact.optional(),mediaCategory:MediaCategorySchema.optional(),family:DiscoverableArtifactFamilySchema.optional(),search:z166.string().trim().min(1).max(200).optional(),lifecycle:z166.enum(["READY","ARCHIVED"]).default("READY"),limit:QueryLimitSchema,next:ContinuationSchema.optional()});var ArtifactDiscoveryMediaSchema=z166.strictObject({tenantId:tenant,projectId:project,artifactId:artifact,representationId:representation});var ArtifactMediaTicketRequestSchema=ArtifactDiscoveryMediaSchema.extend({download:z166.boolean().optional()});var ArtifactMediaTicketSchema=ArtifactDiscoveryMediaSchema.extend(MediaBrowserReadTicketSchema.shape);var ArtifactDiscoveryItemSchema=z166.strictObject({humanLinks:HumanLinksSchema.optional(),artifactId:ArtifactIdSchema,projectId:ProjectIdSchema,projectName:z166.string().min(1).max(500),projectLifecycle:ProjectSchema.shape.lifecycle.nullable().default(null),productionId:ProductionIdSchema.nullable(),representationId:ArtifactRepresentationIdSchema,family:DiscoverableArtifactFamilySchema,lifecycle:z166.enum(["READY","ARCHIVED"]),origin:z166.string().min(1).max(120),contentType:DiscoveryContentTypeSchema,checksumSha256:z166.string().regex(/^[a-f0-9]{64}$/),byteSize:z166.int().positive(),width:z166.int().positive().nullable(),height:z166.int().positive().nullable(),durationMs:z166.int().nonnegative().nullable(),createdAt:z166.iso.datetime({offset:true}),originalName:z166.string().max(255).nullable(),sourceKind:SourceLibraryItemSchema.shape.kind.nullable().default(null),executionClass:z166.enum(["LIVE","TEST_ONLY","UNKNOWN"]),mediaAvailable:z166.boolean(),sourceVersionId:z166.uuid().nullable(),normalizationId:z166.uuid().nullable()});var ArtifactDiscoveryPageSchema=z166.strictObject({items:z166.array(ArtifactDiscoveryItemSchema).max(100),page:QueryPageInfoSchema});import{z as z167}from"zod";var TerminateProductionSchema=z167.strictObject({tenantId:TenantIdSchema,projectId:ProjectIdSchema,productionId:ProductionIdSchema,outcome:z167.enum(["FAILED","CANCELLED"]),expectedProductionRevision:z167.int().positive(),reason:z167.string().trim().min(1).max(1e3),idempotencyKey:z167.string().trim().min(1).max(200)});var ProductionTerminationReceiptSchema=z167.strictObject({decisionId:z167.uuid(),productionId:ProductionIdSchema,projectId:ProjectIdSchema,state:ProductionStateSchema});import{z as z168}from"zod";var text3=z168.string().trim().min(1).max(600);var key9=z168.string().regex(/^[a-z][a-z0-9_-]{0,39}$/);var Review1RepairSourceResultSchema=z168.strictObject({input:Review1RepairSourceQuerySchema,source:Review1RepairSourceSchema,productionRevision:z168.int().positive(),caseVersion:z168.int().nonnegative(),budget:SemanticRepairBudgetSchema.nullable()}).superRefine((v,c)=>{const fields=["tenantId","projectId","productionId","mediaType","generationId","reviewId"];if(fields.some(key10=>v.input[key10]!==v.source[key10])||v.input.requirementKey!==v.source.requirement.key)c.addIssue({code:"custom",message:"Native source must match the exact scoped Review obligation"})});var Review1RepairStrategyBasisSchema=z168.strictObject({input:Review1RepairSourceQuerySchema,contextFingerprint:z168.string().regex(/^[0-9a-f]{64}$/)});var Review1RepairStrategyContextSchema=z168.strictObject({semanticStatus:z168.literal("SUCCESS"),advisory:z168.literal(true),basis:Review1RepairStrategyBasisSchema,owner:Review1RepairSourceResultSchema});var ValidateReview1RepairStrategySchema=z168.strictObject({basis:Review1RepairStrategyBasisSchema,budget:SemanticRepairBudgetSchema.optional(),proposal:z168.strictObject({origin:z168.strictObject({kind:z168.literal("EXTERNAL_AGENT_HOST"),label:z168.string().trim().min(1).max(100)}),summary:text3,alternatives:z168.array(z168.strictObject({id:key9,rationale:text3,whySmallerChangeInsufficient:text3,action:z168.discriminatedUnion("kind",[z168.strictObject({kind:z168.literal("REGENERATE_SHOT")}),z168.strictObject({kind:z168.literal("REQUEST_HUMAN_INPUT"),question:text3}),z168.strictObject({kind:z168.literal("REQUEST_CANONICAL_CHANGE"),requestedChange:text3})])})).min(1).max(6),selectedAlternativeId:key9})}).refine(v=>new TextEncoder().encode(JSON.stringify(v)).byteLength<=1024*1024,"Review-1 strategy exceeds 1 MiB");var Review1RepairStrategyValidationSchema=z168.strictObject({semanticStatus:z168.literal("SUCCESS"),advisory:z168.literal(true),basis:Review1RepairStrategyBasisSchema,proposal:ValidateReview1RepairStrategySchema.shape.proposal,alternatives:z168.array(z168.strictObject({alternativeId:key9,handoff:z168.discriminatedUnion("kind",[z168.strictObject({kind:z168.literal("AUTHOR_REVIEW1_REPAIR"),input:AuthorReview1RepairSchema.omit({idempotencyKey:true})}),z168.strictObject({kind:z168.literal("HUMAN_INPUT_INTENT"),question:text3}),z168.strictObject({kind:z168.literal("CANONICAL_CHANGE_INTENT"),requestedChange:text3})])})).min(1).max(6),selectedAlternativeId:key9,followUp:z168.union([z168.tuple([]),z168.tuple([z168.literal("EXPLICIT_NATIVE_AUTHORING"),z168.literal("OWNER_BUDGET_AND_COST_ADMISSION"),z168.literal("EXPLICIT_NATIVE_EXECUTION"),z168.literal("INDEPENDENT_REVIEW_1_AND_NATIVE_PROOF")])])});import{z as z170}from"zod";import{z as z169}from"zod";var NavigationGroupIdSchema=z169.enum(["navigation","materials","planning","execution","review","delivery","local","administration","unclassified"]);var NavigationGroups=Object.freeze([{id:"navigation",title:"\u5BFC\u822A\u4E0E\u6062\u590D",description:"Locate Productions, inspect state and reconcile original Operations"},{id:"materials",title:"\u9879\u76EE\u4E0E\u7D20\u6750",description:"Projects, source material, references and Artifact discovery"},{id:"planning",title:"\u521B\u4F5C\u4E0E\u8BA1\u5212",description:"Brief, Story, Scenes, Shots and creative plans"},{id:"execution",title:"\u6267\u884C\u4E0E\u8FDB\u5EA6",description:"Generation, runtime Jobs, observation and cancellation"},{id:"review",title:"\u5BA1\u67E5\u4E0E\u4FEE\u590D",description:"Review targets, Findings, evidence and repair"},{id:"delivery",title:"\u88C5\u914D\u4E0E\u4EA4\u4ED8",description:"Timeline, composition, preview, rendering and delivery"},{id:"local",title:"\u672C\u5730\u6267\u884C",description:"Authorized local Runtime, media tools and Agent connections"},{id:"administration",title:"\u7BA1\u7406\u4E0E\u96C6\u6210",description:"Tenant integration, Providers and native authority configuration"},{id:"unclassified",title:"\u5F85\u5206\u7C7B\u80FD\u529B",description:"Registered capabilities awaiting explicit semantic classification"}]);var namespaces=[["navigation",/^nvs_open_execution$/],["local",/^(?:local_|device_|list_devices$)/],["administration",/^(?:provider_|tenant_|oauth_|credential_|native_tool_|agent_host_|webhook_|federation_)/],["review",/(?:^|_)(?:review|reviewer|finding|repair)(?:_|$)/],["navigation",/^(?:workspace_|studio_|operation_|production_(?:query|snapshot)|job_(?:get|query)|production_guidance_)/],["materials",/^(?:project_|source_|artifact_|reference_|visual_sequence_|imported_visual_|source_sync_)/],["planning",/^(?:brief_|story_|scene_|shot_|writer_|director_|exploration_|consistency_|series_|voice_profile_|making_|sound_plan_|planning_|editor_)/],["delivery",/^(?:share_|timeline_|composition_|rough_cut_|final_|delivery_|caption_|audio_)/],["execution",/^(?:production_|keyframe_|video_|generation_|speech_|media_observation_|temporal_evidence_|lifecycle_)/]];function navigationGroup(tool){return namespaces.find(([,pattern])=>pattern.test(tool))?.[0]??"unclassified"}var NavigationProfile="contextual-v1";var NavigationProfileKey="io.nativestudio/discovery-profile";var NavigationToolNames=["studio_start","studio_capability_search","studio_capability_describe","studio_capability_groups","studio_navigate"];var Scope=z170.object({tenantId:TenantIdSchema,projectId:ProjectIdSchema.optional()});var ToolName=z170.string().regex(/^[a-zA-Z0-9_-]{1,120}$/);var StudioStartInputSchema=ProductionQueryInputSchema.extend({limit:z170.int().min(1).max(5).default(5)}).strict();var StudioStartSchema=z170.object({tenantId:TenantIdSchema,choices:ProductionQueryPageSchema.shape.items.max(5),page:ProductionQueryPageSchema.shape.page,selection:z170.enum(["NONE","ONE","CHOOSE"]),guidance:z170.literal("Select an explicit Production ID, then call studio_navigate. Never infer an ID.")}).strict();var CapabilitySummarySchema=z170.object({tool:ToolName,title:z170.string().max(500),description:z170.string().max(6e3),family:z170.string().min(1).max(120),group:NavigationGroupIdSchema.optional(),readOnly:z170.boolean(),invocationTool:z170.enum(["studio_capability_query","studio_capability_invoke"]).optional(),registration:z170.literal("REGISTERED")}).strict();var CapabilitySearchInputSchema=Scope.extend({query:z170.string().trim().min(1).max(240),family:z170.string().regex(/^[a-z0-9_-]{1,120}$/).optional(),group:NavigationGroupIdSchema.optional(),limit:z170.int().min(1).max(8).default(5),next:z170.string().min(1).max(2048).optional()}).strict();var CapabilitySearchSchema=z170.object({tenantId:TenantIdSchema,catalogVersion:z170.string().regex(/^[a-f0-9]{64}$/),outcome:z170.enum(["MATCHES","AMBIGUOUS","NO_MATCH"]),candidates:z170.array(CapabilitySummarySchema.extend({matchedTerms:z170.array(z170.string().max(120)).max(24)})).max(8),page:z170.object({hasMore:z170.boolean(),next:z170.string().max(2048).nullable()}).strict(),guidance:z170.literal("Registration is not availability or authorization. Inspect the selected schema and native context before invoking its typed command.")}).strict();var CapabilityDescribeInputSchema=Scope.extend({tool:ToolName,schemaCursor:z170.string().min(1).max(2048).optional()}).strict();var JsonSchema=z170.record(z170.string(),z170.unknown());var PublicToolDefinitionSchema=z170.object({name:ToolName,title:z170.string().optional(),description:z170.string().optional(),inputSchema:JsonSchema,outputSchema:JsonSchema.optional(),annotations:JsonSchema.optional(),execution:JsonSchema.optional(),_meta:JsonSchema.optional(),icons:z170.array(JsonSchema).optional()}).strict();var CapabilityGroupsInputSchema=Scope.extend({includeDefinitions:z170.boolean().optional()}).strict();var CapabilityGroupsSchema=z170.object({tenantId:TenantIdSchema,catalogVersion:z170.string().regex(/^[a-f0-9]{64}$/),definitions:z170.array(PublicToolDefinitionSchema).max(6).optional(),groups:z170.array(z170.object({id:NavigationGroupIdSchema,title:z170.string().max(120),description:z170.string().max(500),count:z170.int().nonnegative(),readOnlyCount:z170.int().nonnegative()}).strict()).max(9)}).strict();var CapabilityDescribeSchema=CapabilitySummarySchema.extend({tenantId:TenantIdSchema,catalogVersion:z170.string().regex(/^[a-f0-9]{64}$/),capabilityVersion:CapabilityVersionSchema.optional(),outputContract:z170.enum(["DECLARED","NOT_DECLARED"]),schemaCursor:z170.string().min(1).max(2048),definition:PublicToolDefinitionSchema,guidance:z170.literal("Use this bounded definition as client-local schema metadata. Standard tools/list stays stable; commands revalidate authority and current state.")}).strict();var StudioNavigateInputSchema=Scope.extend({productionId:ProductionIdSchema,goal:z170.string().trim().min(1).max(240).optional(),actionLimit:z170.int().min(1).max(8).default(8).describe("Native action page size: 1\u20138 (default 8). Omit this field unless a smaller page is needed."),actionNext:z170.string().min(1).max(2048).optional().describe("Opaque actions.page.next; keep the same goal and actionLimit. Changed native state requires a fresh first page.")}).strict();import{z as z171}from"zod";var McpEntryToolNames=["workspace_caller","studio_capability_groups","studio_capability_search","studio_capability_describe","studio_capability_query","studio_capability_invoke"];var McpCapabilityGatewayNames=["studio_capability_query","studio_capability_invoke"];var CapabilityInvocationInputSchema=z171.strictObject({tenantId:TenantIdSchema,tool:z171.string().regex(/^[a-zA-Z0-9_-]{1,120}$/),arguments:z171.record(z171.string(),z171.unknown()),capabilityVersion:CapabilityVersionSchema.optional()});var CapabilityInvocationOutputSchema=z171.strictObject({tool:z171.string().regex(/^[a-zA-Z0-9_-]{1,120}$/),result:z171.unknown().optional()});import{z as z172}from"zod";var OperationArguments=z172.strictObject({tenantId:TenantIdSchema,productionId:ProductionIdSchema,operationId:OperationSummarySchema.shape.id});var OperationInspect=z172.discriminatedUnion("tool",[z172.strictObject({tool:z172.literal("operation_get"),arguments:OperationArguments}),z172.strictObject({tool:z172.literal("studio_capability_query"),arguments:CapabilityInvocationInputSchema.extend({tool:z172.literal("operation_get"),arguments:OperationArguments})})]);var Evidence=z172.object({path:z172.string().min(1).max(120)}).strict();var StudioNavigationSchema=z172.object({tenantId:TenantIdSchema,projectId:ProjectIdSchema,productionId:ProductionIdSchema,evidence:z172.object({source:z172.literal("production_snapshot"),revision:z172.int().positive(),generatedAt:z172.iso.datetime({offset:true})}).strict(),state:ProductionSnapshotSchema.shape.state.extend({blockingReason:z172.string().max(1e3).nullable(),waitingReason:z172.string().max(1e3).nullable()}),stateReasonsTruncated:z172.object({blockingReason:z172.boolean(),waitingReason:z172.boolean()}).strict(),planning:ProductionSnapshotSchema.shape.planning,shots:ProductionSnapshotSchema.shape.shots,work:ProductionSnapshotSchema.shape.work,findings:ProductionSnapshotSchema.shape.findings,timeline:ProductionSnapshotSchema.shape.timeline.pick({currentVersion:true,stale:true}),final:ProductionSnapshotSchema.shape.final.pick({renderState:true,deliveryValidationState:true}),blockers:z172.object({total:z172.int().nonnegative(),truncated:z172.boolean(),items:z172.array(ProductionSnapshotSchema.shape.blockers.element.extend({evidence:Evidence})).max(10)}).strict(),actions:z172.object({total:z172.int().nonnegative(),truncated:z172.boolean(),items:z172.array(NextActionSchema.extend({tool:z172.string().min(1).max(120).nullable(),registration:z172.enum(["REGISTERED","NOT_ON_SURFACE"]),readOnly:z172.boolean().nullable(),invocationTool:z172.enum(["studio_capability_query","studio_capability_invoke"]).optional(),purpose:z172.string().max(500).nullable(),group:NavigationGroupIdSchema.nullable(),context:z172.object({tenantId:TenantIdSchema,projectId:ProjectIdSchema,productionId:ProductionIdSchema,revision:z172.int().positive()}).strict(),inputHints:z172.object({knownInputs:z172.partialRecord(z172.enum(["tenantId","projectId","productionId","shotId","sceneId","findingId","operationId","artifactId"]),z172.string().min(1).max(2048)),schemaFingerprint:z172.string().regex(/^[a-f0-9]{64}$/).nullable(),requiredInputs:z172.array(z172.string()).max(128),missingInputs:z172.array(z172.string()).max(128),schemaInspectionRequired:z172.literal(true)}).strict().nullable(),recommendation:z172.array(z172.enum(["NATIVE_AVAILABLE","NATIVE_UNAVAILABLE","GOAL_MATCH","INSPECT_SCHEMA","NOT_ON_SURFACE"])).max(4),inspect:z172.object({tool:z172.literal("studio_capability_describe"),arguments:CapabilityDescribeInputSchema}).strict().nullable(),evidence:Evidence})).max(8),page:z172.object({hasMore:z172.boolean(),next:z172.string().max(2048).nullable()}).strict()}).strict(),operations:z172.object({total:z172.int().nonnegative(),truncated:z172.boolean(),items:z172.array(OperationSummarySchema.pick({id:true,productionId:true,semanticStatus:true,startedAt:true,updatedAt:true}).extend({inspect:OperationInspect.nullable(),targetCount:z172.int().nonnegative(),blockerCount:z172.int().nonnegative(),evidence:Evidence})).max(5)}).strict(),related:CapabilitySearchSchema.nullable(),guidance:z172.literal("Use native IDs and revision from this snapshot. An outstanding or unacknowledged write must be reconciled through its Operation; never replay it automatically. Commands revalidate current authority, prerequisites, revision and idempotency.")}).strict();import{z as z174}from"zod";import{z as z173}from"zod";var VoiceReferenceAudioSchema=z173.strictObject({audioVersionId:z173.uuid(),projectId:z173.uuid(),productionId:z173.uuid(),artifactId:z173.uuid(),representationId:z173.uuid(),checksumSha256:z173.string().regex(/^[a-f0-9]{64}$/),byteSize:z173.int().min(44).max(12582912),durationMs:z173.int().min(100).max(6e4),executionClass:z173.enum(["LIVE","TEST_ONLY"]),voiceProfile:VoiceProfileUseSchema.safeExtend({usage:z173.literal("AUDITION")})});var VoiceReferenceSchema=z173.strictObject({humanLinks:HumanLinksSchema.optional(),id:z173.uuid(),tenantId:TenantIdSchema,voiceProfileId:z173.uuid(),ref:VoiceProfileRefSchema,version:z173.int().positive(),audio:VoiceReferenceAudioSchema.nullable(),createdByPrincipalId:z173.uuid(),createdAt:z173.iso.datetime({offset:true})}).refine(v=>v.ref.ownerSystem==="native-video-studio"&&v.ref.ownerTenantRef===v.tenantId&&v.ref.voiceProfileRef===v.voiceProfileId&&(!v.audio||Object.entries(v.ref).every(([key10,value2])=>v.audio.voiceProfile.ref[key10]===value2)),"Reference selection must preserve its exact workspace voice identity");var VoiceReferenceGetSchema=z173.strictObject({tenantId:TenantIdSchema,voiceProfileId:z173.uuid(),referenceId:z173.uuid()});var VoiceProfileScopeSchema=z174.strictObject({tenantId:TenantIdSchema,voiceProfileId:z174.uuid()});var VoiceProfileBindingSchema=z174.strictObject({key:z174.string().regex(/^[a-z][a-z0-9_-]{0,63}$/),modelProfileId:ModelProfileIdSchema,modelProfileVersion:z174.int().positive(),voice:z174.string().min(1).max(100),languages:z174.array(VoiceLocaleSchema).min(1).max(16).refine(v=>new Set(v.map(s=>s.toLowerCase())).size===v.length),parameters:SpeechParametersSchema.default({}),nativeExecution:NativeSpeechExecutionSchema.optional()});var VoiceProfileContentSchema=z174.strictObject({displayName:z174.string().trim().min(1).max(100).regex(/^[^\p{Cc}]*$/u),description:z174.string().trim().max(1e3).default(""),style:z174.string().trim().max(400).default(""),origin:z174.enum(["PRESET","LICENSED_REFERENCE","CLONED_WITH_CONSENT"]),allowedUses:z174.array(z174.enum(["AUDITION","PRODUCTION"])).min(1).max(2).refine(v=>new Set(v).size===v.length).default(["AUDITION","PRODUCTION"]),expiresAt:z174.iso.datetime({offset:true}).optional(),rightsStatement:z174.string().trim().min(1).max(1e3).optional(),bindings:z174.array(VoiceProfileBindingSchema).min(1).max(8).refine(v=>new Set(v.map(b=>b.key)).size===v.length)});var command3={tenantId:TenantIdSchema,idempotencyKey:z174.string().trim().min(1).max(200)};var revision2={voiceProfileId:z174.uuid(),expectedRevision:z174.int().positive()};var VoiceProfileCommandSchema=z174.discriminatedUnion("action",[z174.strictObject({...command3,action:z174.literal("CREATE"),content:VoiceProfileContentSchema}),z174.strictObject({...command3,...revision2,action:z174.literal("REVISE"),content:VoiceProfileContentSchema}),z174.strictObject({...command3,...revision2,action:z174.literal("PUBLISH")}),z174.strictObject({...command3,...revision2,action:z174.literal("SET_ENABLED"),enabled:z174.boolean()}),z174.strictObject({...command3,...revision2,action:z174.literal("SET_REFERENCE"),voiceProfileVersion:z174.int().positive(),audioVersionId:z174.uuid().nullable()})]);var VoiceProfileVersionQuerySchema=VoiceProfileScopeSchema.extend({version:z174.int().positive()});var VoiceProfileListSchema=z174.strictObject({tenantId:TenantIdSchema,search:z174.string().trim().max(100).optional(),status:z174.enum(["DRAFT","PUBLISHED","DISABLED"]).optional(),limit:z174.int().min(1).max(100).default(25),next:z174.string().min(1).max(4096).optional()});var VoiceProfileReceiptSchema=z174.strictObject({humanLinks:HumanLinksSchema.optional(),reference:VoiceReferenceSchema.optional(),semanticStatus:z174.literal("SUCCESS"),tenantId:TenantIdSchema,voiceProfileId:z174.uuid(),revision:z174.int().positive(),publishedVersion:z174.int().positive().nullable(),enabled:z174.boolean()});var VoiceProfileVersionSchema=z174.strictObject({humanLinks:HumanLinksSchema.optional(),ref:VoiceProfileRefSchema,content:VoiceProfileContentSchema,publishedByPrincipalId:z174.uuid(),publishedAt:z174.iso.datetime({offset:true})});var VoiceProfileSummarySchema=VoiceProfileReceiptSchema.omit({semanticStatus:true}).extend({displayName:z174.string().min(1).max(100),status:z174.enum(["DRAFT","PUBLISHED","DISABLED"]),updatedAt:z174.iso.datetime({offset:true})});var VoiceProfileViewSchema=VoiceProfileSummarySchema.extend({reference:VoiceReferenceSchema.nullable().default(null),draft:VoiceProfileContentSchema,draftDigest:z174.string().regex(/^[a-f0-9]{64}$/),published:VoiceProfileVersionSchema.nullable()});var VoiceProfilePageSchema=z174.strictObject({humanLinks:HumanLinksSchema.optional(),items:z174.array(VoiceProfileSummarySchema).max(100),next:z174.string().max(4096).nullable()});var VoiceProfileCreateSchema=VoiceProfileCommandSchema.options[0].omit({action:true});var VoiceProfileReviseSchema=VoiceProfileCommandSchema.options[1].omit({action:true});var VoiceProfilePublishSchema=VoiceProfileCommandSchema.options[2].omit({action:true});var VoiceProfileSetEnabledSchema=VoiceProfileCommandSchema.options[3].omit({action:true});var VoiceProfileSetReferenceSchema=VoiceProfileCommandSchema.options[4].omit({action:true});import{z as z175}from"zod";var sha24=z175.string().regex(/^[a-f0-9]{64}$/);var VoiceReviewAudioSchema=VoiceReferenceAudioSchema.omit({voiceProfile:true}).extend({voiceProfile:VoiceProfileUseSchema});var VoiceReviewScopeSchema=z175.strictObject({tenantId:TenantIdSchema,voiceProfileId:z175.uuid()});var VoiceReviewTargetQuerySchema=VoiceReviewScopeSchema.extend({audioVersionId:z175.uuid()});var VoiceReviewBasisSchema=z175.strictObject({reference:VoiceReferenceSchema.safeExtend({audio:VoiceReferenceAudioSchema}),candidate:VoiceReviewAudioSchema}).refine(v=>Object.entries(v.reference.ref).every(([key10,value2])=>v.candidate.voiceProfile.ref[key10]===value2),"Comparison must preserve the exact same voice identity");var VoiceIdentityObservationSchema=z175.strictObject({status:z175.enum(["MATCH","DIFFERENT","UNDETERMINED"]),confidence:z175.enum(["CLEAR","UNCERTAIN"]),observed:z175.string().trim().min(1).max(1800)});var VoiceNaturalnessObservationSchema=z175.strictObject({status:z175.enum(["NATURAL","NEEDS_WORK","NOT_ASSESSED"]),observed:z175.string().trim().min(1).max(1800)});var RecordVoiceReviewSchema=VoiceReviewTargetQuerySchema.extend({referenceId:z175.uuid(),basisFingerprint:sha24,expectedReviewVersion:z175.int().nonnegative(),idempotencyKey:z175.string().trim().min(1).max(200),actor:z175.enum(["HUMAN","EXTERNAL_AGENT"]),referenceListening:ListeningEvidenceSchema,candidateListening:ListeningEvidenceSchema,identity:VoiceIdentityObservationSchema,naturalness:VoiceNaturalnessObservationSchema});var VoiceReviewRecordSchema=VoiceReviewTargetQuerySchema.extend({id:z175.uuid(),version:z175.int().positive(),basis:VoiceReviewBasisSchema,basisFingerprint:sha24,actor:z175.enum(["HUMAN","EXTERNAL_AGENT"]),executionClass:z175.enum(["LIVE","TEST_ONLY"]),referenceListening:ListeningEvidenceSchema,candidateListening:ListeningEvidenceSchema,identity:VoiceIdentityObservationSchema,naturalness:VoiceNaturalnessObservationSchema,identityResult:z175.enum(["MATCH","DIFFERENT","UNDETERMINED"]),createdByPrincipalId:z175.uuid(),createdAt:z175.iso.datetime({offset:true})}).refine(v=>v.basis.reference.audio.audioVersionId!==v.basis.candidate.audioVersionId&&v.basis.reference.tenantId===v.tenantId&&v.basis.reference.voiceProfileId===v.voiceProfileId&&v.basis.candidate.audioVersionId===v.audioVersionId&&v.executionClass===([v.basis.reference.audio,v.basis.candidate].some(a=>a.executionClass==="TEST_ONLY")?"TEST_ONLY":"LIVE")&&v.identityResult===(v.identity.confidence==="CLEAR"?v.identity.status:"UNDETERMINED"),"Review must preserve exact comparison scope, execution class and independent result");var VoiceReviewStaleReasonSchema=z175.enum(["NO_REFERENCE","REFERENCE_CHANGED","REVIEW_SUPERSEDED","VOICE_UNAVAILABLE","AUDIO_UNAVAILABLE","IDENTITY_MISMATCH","SAME_AUDIO","TEST_ONLY"]);var VoiceReviewTargetSchema=VoiceReviewTargetQuerySchema.extend({humanLinks:HumanLinksSchema.optional(),basis:VoiceReviewBasisSchema.nullable(),basisFingerprint:sha24.nullable(),reviewVersion:z175.int().nonnegative(),eligible:z175.boolean(),staleReasons:z175.array(VoiceReviewStaleReasonSchema).max(8),latestReview:VoiceReviewRecordSchema.nullable()}).refine(v=>v.eligible===(v.staleReasons.length===0)&&(!v.eligible||!!v.basis&&!!v.basisFingerprint)&&v.basis===null===(v.basisFingerprint===null)&&(!v.basis||v.basis.reference.tenantId===v.tenantId&&v.basis.reference.voiceProfileId===v.voiceProfileId&&v.basis.candidate.audioVersionId===v.audioVersionId)&&v.reviewVersion===(v.latestReview?.version??0)&&(!v.latestReview||v.latestReview.tenantId===v.tenantId&&v.latestReview.voiceProfileId===v.voiceProfileId&&v.latestReview.audioVersionId===v.audioVersionId&&v.latestReview.basis.reference.id===v.basis?.reference.id),"Target projection must preserve exact scope and eligibility");var VoiceReviewGetSchema=VoiceReviewScopeSchema.extend({reviewId:z175.uuid()});var VoiceReviewViewSchema=z175.strictObject({humanLinks:HumanLinksSchema.optional(),review:VoiceReviewRecordSchema,current:z175.boolean(),staleReasons:z175.array(VoiceReviewStaleReasonSchema).max(8)}).refine(v=>v.current===(v.staleReasons.length===0),"Historical applicability must agree with currentness reasons");var VoiceReviewReceiptSchema=z175.strictObject({humanLinks:HumanLinksSchema.optional(),semanticStatus:z175.literal("SUCCESS"),review:VoiceReviewRecordSchema});import{z as z176}from"zod";var ProductionEventCursorSchema=z176.strictObject({v:z176.literal(1),t:z176.uuid(),p:z176.uuid(),e:z176.uuid(),n:z176.string().regex(/^(0|[1-9][0-9]{0,18})$/)});var ProductionFeedbackInputSchema=LifecycleEventScopeSchema.extend({operationId:OperationIdSchema.optional(),ifNoneMatch:z176.string().regex(/^[a-f0-9]{64}$/).optional()}).strict();var ProductionFeedbackSchema=LifecycleEventScopeSchema.extend({projectId:z176.uuid(),operationId:OperationIdSchema.nullable(),productionRevision:z176.int().positive(),state:ProductionStateSchema,semanticStatus:InterfaceSemanticStatusSchema,work:WorkSummarySchema,blockers:z176.array(z176.string().min(1).max(1e3)).max(100),nextActions:z176.array(NextActionSchema).max(50),media:z176.strictObject({previewReady:z176.boolean(),finalRenderReady:z176.boolean(),deliveryComplete:z176.boolean()}),humanLinks:HumanLinksSchema}).strict();var ProductionFeedbackResultSchema=LifecycleEventScopeSchema.extend({condition:z176.enum(["CURRENT","NOT_MODIFIED"]),etag:z176.string().regex(/^[a-f0-9]{64}$/),cursor:z176.string().min(1).max(4096),retryAfterMs:z176.int().min(1e3).max(3e4),feedback:ProductionFeedbackSchema.nullable()}).strict().refine(v=>v.condition==="CURRENT"===(v.feedback!==null));var ReadProductionEventsSchema=ProductionFeedbackInputSchema.extend({after:z176.string().min(1).max(4096).optional(),start:z176.enum(["CURRENT","BEGINNING"]).default("CURRENT"),limit:z176.int().min(1).max(50).default(20)}).strict();var ProductionEventReadSchema=z176.strictObject({items:z176.array(ExternalLifecycleEventSchema).max(50),nextCursor:z176.string().min(1).max(4096),watermark:z176.string().min(1).max(4096),hasMore:z176.boolean(),current:ProductionFeedbackResultSchema});import{z as z177}from"zod";var scope7=z177.strictObject({tenantId:z177.uuid().toLowerCase(),shareId:z177.uuid().toLowerCase()});var ShareCreateSchema=ArtifactDiscoveryMediaSchema.extend({shareId:z177.uuid().toLowerCase(),idempotencyKey:z177.string().min(1).max(128),title:z177.string().trim().min(1).max(160).default("Video"),expiresAt:z177.iso.datetime({offset:true}).optional()}).strict();var ShareGetSchema=scope7;var ShareRevokeSchema=scope7.extend({expectedRevision:z177.int().positive(),idempotencyKey:z177.string().min(1).max(128)}).strict();var ShareListSchema=z177.strictObject({tenantId:z177.uuid().toLowerCase(),projectId:z177.uuid().toLowerCase().optional(),artifactId:z177.uuid().toLowerCase().optional(),after:z177.uuid().toLowerCase().optional(),limit:z177.int().min(1).max(50).default(20)});var ShareViewSchema=ArtifactDiscoveryMediaSchema.extend({shareId:z177.uuid(),productionId:z177.uuid().nullable(),createdByPrincipalId:z177.uuid(),title:z177.string().min(1).max(160),purpose:z177.enum(["PREVIEW","ROUGH_CUT","FINAL_RENDER"]),contentType:z177.literal("video/mp4"),checksumSha256:z177.string().regex(/^[a-f0-9]{64}$/),byteSize:z177.int().positive().max(128*1024*1024),revision:z177.int().positive(),state:z177.enum(["PREPARING","ACTIVE","REVOKED","EXPIRED","AUTHORITY_REVOKED"]),createdAt:z177.iso.datetime({offset:true}),expiresAt:z177.iso.datetime({offset:true})}).strict();var ShareUrlSchema=z177.url().max(2048).refine(value2=>{try{const u=new URL(value2);return!u.username&&!u.password&&!u.search&&/^\/s\/[a-f0-9-]{36}$/.test(u.pathname)&&/^#key=[A-Za-z0-9_-]{43}$/.test(u.hash)&&(u.protocol==="https:"||u.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(u.hostname))}catch{return false}});var ShareLinkResultSchema=z177.strictObject({share:ShareViewSchema,url:ShareUrlSchema.nullable(),linkState:z177.enum(["AVAILABLE","UNCONFIGURED","UNAVAILABLE","NOT_ACTIVE"])}).refine(v=>v.linkState==="AVAILABLE"===(v.url!==null)).refine(v=>!v.url||v.share.state==="ACTIVE"&&new URL(v.url).pathname==="/s/"+v.share.shareId);var SharePageSchema=z177.strictObject({items:z177.array(ShareViewSchema).max(50),next:z177.uuid().nullable()});var SharePublicInputSchema=z177.strictObject({shareId:z177.uuid().toLowerCase(),secret:z177.string().regex(/^[A-Za-z0-9_-]{43}$/)});import{z as z178}from"zod";var sha25=z178.string().regex(/^[a-f0-9]{64}$/);var ReleaseLegacyHostExecutionSchema=AgentHostExecutionGetSchema.extend({requestId:z178.uuid(),expectedRevision:z178.int().positive(),hostRequestId:z178.uuid(),snapshotFingerprint:sha25,evidenceRef:z178.string().min(1).max(512).refine(v=>Array.from(v).every(c=>{const n=c.codePointAt(0);return n>=32&&(n<127||n>159)&&(n<55296||n>57343)})),evidenceSha256:sha25,decision:z178.literal("RELEASE_NATIVE_DISPATCH_FENCE")});var LegacyHostExecutionReleaseSchema=ReleaseLegacyHostExecutionSchema.extend({releasedByPrincipalId:z178.uuid(),releasedAt:z178.iso.datetime({offset:true})});import{z as z183}from"zod";import{z as z182}from"zod";import{z as z179}from"zod";function orderedFederationWindow(value2){return Date.parse(value2.notBefore)<Date.parse(value2.expiresAt)}var FederationFailureCodeSchema=z179.enum(["FEDERATION_FORBIDDEN","FEDERATION_UNCONFIGURED","FEDERATION_INVALID_INPUT","FEDERATION_INVALID_ID","FEDERATION_INVALID_REFERENCE","FEDERATION_INVALID_MODE","FEDERATION_INVALID_GRANT_VERSION","FEDERATION_INVALID_REVISION","FEDERATION_INVALID_STATE","FEDERATION_INVALID_SOURCE","FEDERATION_INVALID_VALIDITY","FEDERATION_REMOTE_SERVICE_REQUIRED","FEDERATION_EVENT_NOT_ALLOWED","FEDERATION_EVENT_NOT_SELECTED","FEDERATION_SCOPE_MISMATCH","FEDERATION_PRODUCTION_NOT_FOUND","FEDERATION_ROUTE_NOT_FOUND","FEDERATION_STREAM_NOT_FOUND","FEDERATION_CONNECTION_CONFLICT","FEDERATION_GRANT_CONFLICT","FEDERATION_GRANT_VERSION_CONFLICT","FEDERATION_ROUTE_IDENTITY_CONFLICT","FEDERATION_REVISION_CONFLICT","FEDERATION_IDEMPOTENCY_CONFLICT","FEDERATION_CONCURRENT_CHANGE","FEDERATION_ROUTE_CAPACITY","FEDERATION_SUBSCRIPTION_CAPACITY","FEDERATION_SUBSCRIPTION_NOT_FOUND","FEDERATION_SUBSCRIBER_IDENTITY_CONFLICT","FEDERATION_SUBSCRIPTION_CANCELLED","FEDERATION_INITIAL_SELECTION_REQUIRED","FEDERATION_SELECTION_EXCEEDS_AUTHORITY","FEDERATION_SELECTION_EXCEEDS_GRANT","FEDERATION_RESYNC_REQUIRED","FEDERATION_GAP_NOT_REPAIRED","FEDERATION_HOLD_REQUIRED","FEDERATION_RECOVERY_EXHAUSTED","FEDERATION_BINDING_NOT_FOUND","FEDERATION_INBOX_NOT_FOUND","FEDERATION_INBOUND_CONFLICT","FEDERATION_INBOX_NOT_QUARANTINED","FEDERATION_RESULT_NOT_FOUND","FEDERATION_RESULT_MISMATCH","FEDERATION_CONTRACT_MISMATCH","FEDERATION_RECEIPT_ROUTE_NOT_FOUND","FEDERATION_RECEIPT_DELIVERY_NOT_FOUND","FEDERATION_RECEIPT_CONFLICT"]);var ref=z179.string().min(1).max(256).refine(v=>Array.from(v).every(c=>{const code=c.codePointAt(0);return code>=32&&code!==127&&(code<55296||code>57343)}));var types=z179.array(ExternalEventTypeSchema).min(1).max(14).refine(v=>new Set(v).size===v.length);var uuid3=z179.uuid().toLowerCase();var FederationScopeSchema=LifecycleEventScopeSchema.extend({tenantId:uuid3.brand(),productionId:uuid3.brand()});var routeInput=FederationScopeSchema.extend({routeId:uuid3,requestId:ref,expectedRevision:z179.int().nonnegative(),remoteService:ref,remoteTenant:ref,grantRef:ref,grantVersion:z179.int().min(1).max(2147483647),grantEventTypes:types,selectedEventTypes:types,notBefore:z179.iso.datetime(),expiresAt:z179.iso.datetime(),state:z179.enum(["ACTIVE","PAUSED"]),publicationMode:z179.enum(["FIXED","ON_DEMAND"]).default("ON_DEMAND")}).strict();var FederationRouteConfigureSchema=routeInput.refine(orderedFederationWindow).refine(v=>v.selectedEventTypes.every(type=>v.grantEventTypes.includes(type)));var FederationRouteSchema=routeInput.omit({requestId:true,expectedRevision:true}).extend({connectionRef:ref,source:z179.string().min(1).max(2048),serviceRef:z179.literal("native-video-studio"),revision:z179.int().positive(),epoch:uuid3,position:z179.string().regex(/^(0|[1-9][0-9]{0,18})$/),gap:z179.boolean(),publicationMode:z179.enum(["FIXED","ON_DEMAND"]).default("FIXED")}).strict();var FederationSubscriptionSetSchema=FederationScopeSchema.extend({subscriptionId:uuid3,routeId:uuid3,requestId:ref,expectedRevision:z179.int().nonnegative(),subscriberKind:z179.enum(["SYSTEM","AGENT_RUNTIME","HOST_BOT"]),subscriberRef:ref,eventTypes:types,expiresAt:z179.iso.datetime(),state:z179.enum(["ACTIVE","PAUSED","CANCELLED"])}).strict();var FederationSubscriptionGetSchema=FederationScopeSchema.extend({subscriptionId:uuid3}).strict();var FederationSubscriptionSchema=FederationSubscriptionSetSchema.omit({requestId:true,expectedRevision:true}).extend({revision:z179.int().positive(),startCursor:z179.string().min(1).max(4096),effective:z179.enum(["ACTIVE","PAUSED","CANCELLED","EXPIRED","BLOCKED"])}).strict();var FederationBootstrapSchema=FederationScopeSchema.extend({cursor:z179.string().min(1).max(4096),feedback:ProductionFeedbackSchema}).strict().refine(v=>v.tenantId===v.feedback.tenantId&&v.productionId===v.feedback.productionId);var FederationSubscriptionResultSchema=FederationScopeSchema.extend({subscription:FederationSubscriptionSchema,bootstrap:FederationBootstrapSchema}).strict().refine(v=>v.tenantId===v.subscription.tenantId&&v.productionId===v.subscription.productionId&&v.bootstrap.tenantId===v.tenantId&&v.bootstrap.productionId===v.productionId);var FederationCatalogSchema=FederationScopeSchema.extend({configuration:z179.enum(["CONFIGURED","UNCONFIGURED"]),transport:z179.literal("NOT_OBSERVED"),profile:z179.literal("eventsdk/1.2"),runtimeSubscription:z179.literal("EXPLICIT_SELECTION"),runtimeWake:z179.literal("RECEIVER_OWNED"),defaultPublication:z179.literal(false),bootstrap:FederationBootstrapSchema,routes:z179.array(FederationRouteSchema).max(32),events:z179.array(z179.strictObject({type:ExternalEventTypeSchema,wireType:ref,dataschema:ref,defaultEnabled:z179.literal(false)})).max(14)}).strict().refine(v=>v.routes.every(r=>r.tenantId===v.tenantId&&r.productionId===v.productionId)&&v.bootstrap.tenantId===v.tenantId&&v.bootstrap.productionId===v.productionId);var FederationQuerySchema=FederationScopeSchema.extend({kind:z179.enum(["routes","subscriptions","deliveries"]),routeId:uuid3.optional(),eventId:uuid3.optional(),deliveryId:z179.string().regex(/^[0-9a-f]{64}$/).optional(),after:z179.string().min(1).max(64).optional(),limit:z179.int().min(1).max(50).default(20)}).strict().refine(v=>!v.after||(v.kind==="deliveries"?/^[0-9a-f]{64}$/.test(v.after):z179.uuid().safeParse(v.after).success)).refine(v=>v.kind==="deliveries"||!v.eventId&&!v.deliveryId);var FederationDeliverySchema=FederationScopeSchema.extend({routeId:uuid3,eventId:uuid3,deliveryId:z179.string().regex(/^[0-9a-f]{64}$/),eventType:ExternalEventTypeSchema,state:z179.enum(["PENDING","UNKNOWN","PUBLISHED","HOLD"]),attempts:z179.int().nonnegative(),acknowledgement:z179.enum(["BROKER_STORED","NOT_CONFIRMED"]),reason:z179.string().max(100).nullable()}).strict();var page2=(kind,item)=>FederationScopeSchema.extend({kind:z179.literal(kind),items:z179.array(item).max(50),next:(kind==="deliveries"?z179.string().regex(/^[0-9a-f]{64}$/):uuid3).nullable()}).strict();var FederationQueryResultSchema=z179.discriminatedUnion("kind",[page2("routes",FederationRouteSchema),page2("subscriptions",FederationSubscriptionSchema),page2("deliveries",FederationDeliverySchema)]).refine(v=>v.items.every(item=>{const r=item;return r.tenantId===v.tenantId&&r.productionId===v.productionId}));var FederationReceiptInputSchema=FederationScopeSchema.extend({requestId:ref}).strict();var FederationRecoverSchema=FederationScopeSchema.extend({kind:z179.enum(["RETRY_HOLD","REPAIR_GAP"]),routeId:uuid3,requestId:ref,expectedRevision:z179.int().positive(),reason:ref,deliveryId:z179.string().regex(/^[0-9a-f]{64}$/).optional(),expectedAttempts:z179.int().nonnegative().optional(),acknowledgeDuplicateRisk:z179.literal(true).optional()}).strict().refine(v=>v.kind==="RETRY_HOLD"?v.deliveryId!==void 0&&v.expectedAttempts!==void 0&&v.acknowledgeDuplicateRisk===true:v.deliveryId===void 0&&v.expectedAttempts===void 0&&v.acknowledgeDuplicateRisk===void 0);var FederationRecoverySchema=FederationScopeSchema.extend({kind:z179.enum(["RETRY_HOLD","REPAIR_GAP"]),requestId:ref,recoveryId:uuid3,routeId:uuid3,revision:z179.int().positive(),epoch:uuid3,position:z179.string().regex(/^(0|[1-9][0-9]{0,18})$/),gap:z179.boolean(),deliveryId:z179.string().regex(/^[0-9a-f]{64}$/).nullable(),attempts:z179.int().nonnegative().nullable(),recoveryCount:z179.int().min(0).max(3).nullable(),effect:z179.literal("TRANSPORT_ONLY")}).strict().refine(v=>v.kind==="RETRY_HOLD"?v.deliveryId!==null&&v.attempts!==null&&v.recoveryCount!==null&&v.recoveryCount>0:v.deliveryId===null&&v.attempts===null&&v.recoveryCount===null&&!v.gap);var FederationObservationSchema=FederationScopeSchema.extend({asOf:z179.iso.datetime(),routes:z179.array(z179.strictObject({routeId:uuid3,state:z179.enum(["ACTIVE","PAUSED"]),gap:z179.boolean(),position:z179.string(),sourceHead:z179.string().nullable(),sourceLag:z179.string().nullable(),pending:z179.int().nonnegative(),unknown:z179.int().nonnegative(),hold:z179.int().nonnegative(),published:z179.int().nonnegative(),demandBlocked:z179.int().nonnegative(),inFlight:z179.int().nonnegative(),oldestUnsettledEventAt:z179.iso.datetime().nullable(),lastTickAt:z179.iso.datetime().nullable(),faultCode:z179.string().regex(/^[A-Z][A-Z0-9_]{0,63}$/).nullable()})).max(32),workers:z179.array(z179.strictObject({source:z179.string().min(1).max(2048),workerRef:ref,instanceId:uuid3,status:z179.enum(["STARTING","CONNECTED","RECONNECTING","DISABLED","SHADOW","CONFIGURATION_ERROR","STOPPED"]),observedAt:z179.iso.datetime(),configurationRevision:z179.string().regex(/^sha256:[a-f0-9]{64}$/).nullable(),fresh:z179.boolean(),connected:z179.boolean()})).max(32),workersTruncated:z179.boolean(),meaning:z179.literal("BROKER_ACK_IS_NOT_APPLIED")}).strict();var FederationReceiptSchema=FederationReceiptInputSchema.extend({result:z179.union([FederationRouteSchema,FederationSubscriptionResultSchema,FederationRecoverySchema]).nullable()}).strict().refine(v=>!v.result||v.result.tenantId===v.tenantId&&v.result.productionId===v.productionId);import{z as z181}from"zod";import{z as z180}from"zod";var clean=v=>Array.from(v).every(c=>{const n=c.codePointAt(0);return n>=32&&n!==127&&(n<55296||n>57343)});var FederationPeerRefSchema=z180.string().min(1).max(256).refine(clean);var FederationOpaqueUriSchema=z180.string().min(1).max(512).refine(v=>clean(v)&&URL.canParse(v)&&!/\s/u.test(v));var RESOURCE_CHANGE_TYPE="com.nativestudio.federation.resource.changed.v1";var RESOURCE_CHANGE_SCHEMA="urn:nativestudio:federation:resource-change:v1";var FederationSourceScopeSchema=z180.strictObject({namespace:FederationPeerRefSchema,ref:FederationPeerRefSchema});var ResourceChangeSchema=z180.strictObject({schemaVersion:z180.literal(1),sourceScope:FederationSourceScopeSchema,resource:z180.strictObject({namespace:FederationPeerRefSchema,ref:FederationOpaqueUriSchema,version:FederationPeerRefSchema}),changeKind:FederationPeerRefSchema,parentRef:FederationOpaqueUriSchema.nullable().optional()});var distinct=a=>new Set(a).size===a.length;var FederationSourceSelectionSchema=z180.strictObject({scope:FederationSourceScopeSchema,resourceNamespace:FederationPeerRefSchema,changeKinds:z180.array(FederationPeerRefSchema).min(1).max(32).refine(distinct),resourcePrefixes:z180.array(FederationOpaqueUriSchema).min(1).max(16).refine(distinct)});var HistoricalSourceScopeSchema=z180.record(FederationPeerRefSchema,FederationPeerRefSchema).refine(v=>Object.keys(v).length<=32);var HistoricalSourceSelectionSchema=z180.record(FederationPeerRefSchema,z180.union([FederationPeerRefSchema,z180.array(z180.string().min(1).max(512).refine(clean)).max(32),HistoricalSourceScopeSchema])).refine(v=>Object.keys(v).length<=32&&JSON.stringify(v).length<=32768);var uuid4=z181.uuid().toLowerCase();var clean2=v=>Array.from(v).every(c=>{const code=c.codePointAt(0);return code>=32&&code!==127&&(code<55296||code>57343)});var ref2=z181.string().min(1).max(256).refine(clean2);var uri=z181.string().min(1).max(2048).refine(v=>URL.canParse(v)&&!/\s/.test(v)&&clean2(v));var bindingInput=FederationScopeSchema.extend({connectionRef:ref2.optional(),bindingId:uuid4,requestId:ref2,expectedRevision:z181.int().nonnegative(),source:uri,contractVersion:z181.literal(2),remoteService:ref2,sourceSelection:FederationSourceSelectionSchema,remoteTenant:ref2,consumerRef:ref2,grantRef:ref2,grantVersion:z181.int().min(1).max(2147483647),notBefore:z181.iso.datetime(),expiresAt:z181.iso.datetime(),state:z181.enum(["ACTIVE","PAUSED","REVOKED"])}).strict();var InboundBindingConfigureSchema=bindingInput.refine(orderedFederationWindow);var bindingView=bindingInput.omit({requestId:true,expectedRevision:true}).extend({revision:z181.int().positive(),installationSource:uri,connectionRef:ref2,direction:z181.literal("INBOUND"),effective:z181.enum(["ACTIVE","PAUSED","REVOKED","EXPIRED","BLOCKED"])}).strict();var CurrentInboundBindingSchema=bindingView.extend({eventType:z181.literal(RESOURCE_CHANGE_TYPE),dataSchema:z181.literal(RESOURCE_CHANGE_SCHEMA)}).refine(orderedFederationWindow);var InboundBindingSchema=z181.union([CurrentInboundBindingSchema,bindingView.extend({contractVersion:z181.literal(1).default(1),sourceSelection:HistoricalSourceSelectionSchema.optional(),eventType:ref2.optional(),dataSchema:uri.optional()})]);var InboundNoticeSchema=z181.strictObject({resourceRef:z181.string().min(1).max(512),resourceVersion:ref2,changeKind:ref2,contractVersion:z181.literal(2).optional(),resourceNamespace:ref2.optional(),sourceService:ref2.optional(),sourceScope:HistoricalSourceScopeSchema.optional(),parentRef:uri.nullable().optional()}).refine(v=>v.contractVersion!==2||v.sourceService!==void 0&&ResourceChangeSchema.safeParse({schemaVersion:1,sourceScope:v.sourceScope,resource:{namespace:v.resourceNamespace,ref:v.resourceRef,version:v.resourceVersion},changeKind:v.changeKind,...v.parentRef!==void 0?{parentRef:v.parentRef}:{}}).success);var InboundInboxViewSchema=FederationScopeSchema.extend({id:uuid4,bindingId:uuid4,source:uri,eventId:ref2,consumerRef:ref2,disposition:z181.enum(["RECEIVED","HOLD","APPLIED","REJECTED","UNKNOWN"]),revision:z181.int().positive(),generation:z181.int().nonnegative(),attempts:z181.int().nonnegative(),recoveryCount:z181.int().min(0).max(3),workState:z181.enum(["READY","QUARANTINED","SETTLED"]),reason:ref2.nullable(),receivedAt:z181.iso.datetime(),resourceRef:z181.string().min(1).max(512).refine(clean2),resourceVersion:ref2}).strict();var signalBase=FederationScopeSchema.extend({inboxId:uuid4,consumerRef:ref2,source:uri,sourceTenant:ref2,effect:z181.literal("REFRESH_HINT"),appliedAt:z181.iso.datetime()}).strict();var InboundSignalSchema=InboundNoticeSchema.safeExtend(signalBase.shape);var InboundReplaySchema=FederationScopeSchema.extend({inboxId:uuid4,requestId:ref2,expectedGeneration:z181.int().nonnegative(),expectedReceiptRevision:z181.int().positive(),reason:ref2,acknowledgeDuplicateRisk:z181.literal(true)}).strict();var InboundReplayResultSchema=FederationScopeSchema.extend({inboxId:uuid4,requestId:ref2,replayId:uuid4,status:z181.literal("QUEUED_FOR_VERIFICATION"),effect:z181.literal("TRANSPORT_ONLY")}).strict();var InboundReplayViewSchema=InboundReplayResultSchema.omit({status:true}).extend({status:z181.enum(["PENDING","REQUEUED","DENIED"]),reasonCode:ref2.nullable()}).strict();var InboundQuarantineViewSchema=FederationScopeSchema.extend({id:uuid4,bindingId:uuid4,deliveryRef:z181.string().min(1).max(2048).refine(clean2),reasonCode:ref2,recordedAt:z181.iso.datetime()}).strict();var InboundQuerySchema=FederationScopeSchema.extend({kind:z181.enum(["bindings","inbox","signals","replays","quarantine"]),after:uuid4.optional(),limit:z181.int().min(1).max(50).default(20)}).strict();var page3=(kind,schema)=>FederationScopeSchema.extend({kind:z181.literal(kind),items:z181.array(schema).max(50),next:uuid4.nullable()}).strict();var InboundQueryResultSchema=z181.discriminatedUnion("kind",[page3("bindings",InboundBindingSchema),page3("inbox",InboundInboxViewSchema),page3("signals",InboundSignalSchema),page3("replays",InboundReplayViewSchema),page3("quarantine",InboundQuarantineViewSchema)]);var InboundReceiptInputSchema=FederationScopeSchema.extend({kind:z181.enum(["EVENT","COMMAND"]),source:uri.optional(),eventId:ref2.optional(),consumerRef:ref2.optional(),requestId:ref2.optional()}).strict().refine(v=>v.kind==="EVENT"?v.source!==void 0&&v.eventId!==void 0&&v.consumerRef!==void 0&&v.requestId===void 0:v.requestId!==void 0&&v.source===void 0&&v.eventId===void 0&&v.consumerRef===void 0);var InboundReceiptSchema=z181.discriminatedUnion("kind",[FederationScopeSchema.extend({kind:z181.literal("EVENT"),source:uri,eventId:ref2,consumerRef:ref2,result:InboundInboxViewSchema.nullable()}).strict(),FederationScopeSchema.extend({kind:z181.literal("COMMAND"),requestId:ref2,result:z181.union([InboundBindingSchema,InboundReplayResultSchema]).nullable()}).strict()]);var InboundCatalogSchema=FederationScopeSchema.extend({defaultReceive:z181.literal(false),configuration:z181.enum(["CONFIGURED","UNCONFIGURED"]),effect:z181.literal("REFRESH_HINT"),bindings:z181.array(CurrentInboundBindingSchema).max(32),events:z181.array(z181.strictObject({sourceService:ref2,type:ref2,dataSchema:uri})).max(32)}).strict().refine(v=>v.bindings.every(b=>b.tenantId===v.tenantId&&b.productionId===v.productionId&&b.effective==="ACTIVE"));var ref3=z182.string().min(1).max(256);var source4=z182.string().min(1).max(2048).refine(v=>URL.canParse(v));var FederationResourceTypeSchema=z182.enum(["nvs.lifecycle-event","nvs.federation.refresh-hint"]);var FederationResultRefSchema=z182.strictObject({sourceSystem:z182.literal("native-video-studio"),resourceType:FederationResourceTypeSchema,resourceId:ref3,revision:z182.string().regex(/^[1-9][0-9]{0,18}$/),digest:z182.string().regex(/^sha256:[a-f0-9]{64}$/),evidenceRef:ref3.optional()});var FederationResultLocatorSchema=FederationScopeSchema.extend({resourceType:FederationResourceTypeSchema,resourceId:z182.uuid().toLowerCase()}).strict();var base2=FederationScopeSchema.extend({schemaVersion:z182.literal(1),source:source4,resourceId:z182.uuid(),revision:ref3});var FederationResultValueSchema=z182.discriminatedUnion("resourceType",[base2.extend({resourceType:z182.literal("nvs.lifecycle-event"),event:ExternalLifecycleEventSchema}).strict(),base2.extend({resourceType:z182.literal("nvs.federation.refresh-hint"),revision:z182.literal("1"),consumerRef:ref3,peerSource:source4,peerTenant:ref3,resourceRef:z182.string().min(1).max(512),resourceVersion:ref3,changeKind:ref3,contractVersion:z182.literal(2).optional(),resourceNamespace:ref3.optional(),sourceService:ref3.optional(),sourceScope:HistoricalSourceScopeSchema.optional(),parentRef:z182.string().min(1).max(512).nullable().optional(),appliedAt:z182.iso.datetime()}).strict().refine(v=>{if(v.sourceService===void 0&&(v.sourceScope!==void 0||v.parentRef!==void 0))return false;return InboundNoticeSchema.safeParse({resourceRef:v.resourceRef,resourceVersion:v.resourceVersion,changeKind:v.changeKind,contractVersion:v.contractVersion,resourceNamespace:v.resourceNamespace,...v.sourceService?{sourceService:v.sourceService,sourceScope:v.sourceScope,parentRef:v.parentRef}:{}}).success})]).refine(v=>v.resourceType!=="nvs.lifecycle-event"||v.event.tenantId===v.tenantId&&v.event.productionId===v.productionId&&v.event.eventId===v.resourceId&&String(v.event.basis.productionRevision)===v.revision);var FederationResultReadSchema=FederationScopeSchema.extend({source:source4,reference:FederationResultRefSchema}).strict();var FederationResultReferenceSchema=FederationScopeSchema.extend({source:source4,reference:FederationResultRefSchema,meaning:z182.literal("IMMUTABLE_FACT")}).strict();var FederationResultSnapshotSchema=FederationResultReferenceSchema.extend({value:FederationResultValueSchema}).strict().refine(v=>v.value.source===v.source&&v.value.tenantId===v.tenantId&&v.value.productionId===v.productionId&&v.reference.resourceType===v.value.resourceType&&v.reference.resourceId===v.value.resourceId&&v.reference.revision===v.value.revision);function canonicalFederationJson(value2){return boundedJson(value2,2048,16,32768)}function canonicalFederationReadJson(value2){return boundedJson(value2,4096,24,65536)}function canonicalFederationCatalogJson(value2){return boundedJson(value2,2e4,32,131072)}function boundedJson(value2,maxNodes,maxDepth,maxBytes){let nodes=0;let bytes=0;const encoder=new TextEncoder;const reserve=size=>{bytes+=size;if(bytes>maxBytes)throw Error("FEDERATION_JSON_SIZE")};const scalar=text6=>{reserve(encoder.encode(text6).byteLength);return text6};const seen=new Set;const encode=(v,depth2)=>{if(++nodes>maxNodes||depth2>maxDepth)throw Error("FEDERATION_JSON_BUDGET");if(v===null||typeof v==="boolean")return scalar(String(v));if(typeof v==="number"&&Number.isFinite(v))return scalar(JSON.stringify(v));if(typeof v==="string"){if(v.length>maxBytes)throw Error("FEDERATION_JSON_SIZE");if(/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/u.test(v))throw Error("FEDERATION_JSON_UNICODE");return scalar(JSON.stringify(v))}if(!v||typeof v!=="object"||seen.has(v))throw Error("FEDERATION_JSON_VALUE");seen.add(v);try{if(Array.isArray(v)){if(v.length>maxNodes-nodes)throw Error("FEDERATION_JSON_BUDGET");if(Reflect.ownKeys(v).length!==v.length+1)throw Error("FEDERATION_JSON_ARRAY");reserve(v.length===0?2:v.length+1);const items=[];for(let index=0;index<v.length;index++){const property=Object.getOwnPropertyDescriptor(v,String(index));if(!property||!("value"in property))throw Error("FEDERATION_JSON_ARRAY");items.push(encode(property.value,depth2+1))}return"["+items.join(",")+"]"}if(Object.getPrototypeOf(v)!==Object.prototype&&Object.getPrototypeOf(v)!==null)throw Error("FEDERATION_JSON_OBJECT");if(Object.getOwnPropertySymbols(v).length)throw Error("FEDERATION_JSON_OBJECT");const keys=Object.keys(v);if(keys.length>maxNodes-nodes)throw Error("FEDERATION_JSON_BUDGET");reserve(keys.length===0?2:keys.length*2+1);return"{"+keys.sort().map(key10=>{const property=Object.getOwnPropertyDescriptor(v,key10);if(!property||!("value"in property))throw Error("FEDERATION_JSON_PROPERTY");return encode(key10,depth2+1)+":"+encode(property.value,depth2+1)}).join(",")+"}"}finally{seen.delete(v)}};return encode(value2,0)}var canonicalHostContractJson=canonicalFederationCatalogJson;var bounded2=z183.unknown().refine(value2=>{try{canonicalHostContractJson(value2);return true}catch{return false}},{abort:true});var digest3=z183.string().regex(/^sha256:[a-f0-9]{64}$/);var jsonSchema2=z183.record(z183.string(),z183.json());var operations={"installation.read":{method:"GET",path:"/nvs-agent-host/v1/installations/{installationId}"},"task.submit":{method:"POST",path:"/nvs-agent-host/v1/tasks"},"task.by-request":{method:"GET",path:"/nvs-agent-host/v1/tasks/by-request"},"task.get":{method:"GET",path:"/nvs-agent-host/v1/tasks/{runKey}"},"task.cancel":{method:"POST",path:"/nvs-agent-host/v1/tasks/{runKey}/cancel"}};var eventing={standard:"EventSDK",notificationProfile:"eventsdk/1.2",receiptProfile:"eventsdk/1.1",requiredForHostExecution:false,defaultReceive:false,subscriberKinds:["SYSTEM","AGENT_RUNTIME","HOST_BOT"],authorization:"INDEPENDENT_CURRENT_AUTHORITY",wake:"RECEIVER_OWNED",adoption:"RECEIVER_OWNER_GOAL_REQUIRED",receiptMeaning:"LOCAL_APPLIED_IS_NOT_AGENT_ADOPTION",operations:{catalog:"federation.catalog",select:"federation.subscription.set",read:"federation.subscription.get",handoff:"federation.subscription.handoff",contract:"federation.subscription.contract",resultReference:"federation.result.reference",resultRead:"federation.result.read",receiptInspection:"federation.delivery.inspect",receiptHandoff:"federation.receipt-inbound.handoff"}};var semanticChecks=["OPAQUE_SCOPE_IS_NOT_NATIVE_TENANT_MAPPING","JSON_SCHEMA_PLUS_SEMANTIC_CHECKS_REQUIRED","I_JSON_FINITE_PLAIN_DENSE_JSON_NO_DUPLICATE_KEYS_OR_LONE_SURROGATES","HOST_REFERENCES_1_TO_256_UNICODE_CODEPOINTS_WITHOUT_C0_C1_CONTROLS","CURRENT_REGISTRATION_CONSENT_GRANT_PERMIT_LEASE_ACCESS_REQUIRED","INSTALLATION_RECHECK_BEFORE_AND_AFTER_NATIVE_MANIFEST","INPUT_SHA256_CANONICAL_COMPLETE_INPUT_INCLUDING_NATIVE_PROOF","EXACT_REQUEST_INPUT_SCOPE_CHOICE_INSTALLATION_AUTHORITY_AND_TASK","RESPONSE_TIME_ORDER_FRESH_AUTHORIZATION_AND_DEADLINES_WITHIN_NATIVE_PROOF","SUBMIT_DEADLINE_INCLUDES_CREDENTIAL_ACCESS_AND_NATIVE_AUTHORITY_EXPIRY","NO_WRITE_BEFORE_DISPATCH_UNKNOWN_AFTER_DISPATCH_NO_AUTOMATIC_RETRY","RECOVERY_OBSERVES_ORIGINAL_REQUEST_WITHOUT_RESUBMISSION","CANCEL_USES_DISTINCT_REQUEST_AND_EXACT_ORIGINAL_TASK","HOST_REPORT_IS_NOT_PRODUCTION_TRUTH_OR_RESULT_ADOPTION","SUBSCRIPTION_EXECUTION_AND_CONTENT_AUTHORITY_ARE_INDEPENDENT"];var route=value2=>z183.strictObject({method:z183.literal(value2.method),path:z183.literal(value2.path)});var AgentHostContractDocumentSchema=bounded2.pipe(z183.strictObject({contract:z183.literal("nvs-agent-host-contract/1"),hostProtocol:z183.literal(HOST_PROTOCOL),hostContractDigest:z183.literal(HostProtocolDigest),delegationContractDigest:z183.literal(HostDelegationDigest),nativeSelectionVersion:z183.literal(2),nativeProfileVersion:z183.literal(2),schemaDialect:z183.literal("https://json-schema.org/draft/2020-12/schema"),origin:z183.literal("DEPLOYMENT_REGISTERED_ONLY"),credential:z183.literal("PRIVATE_BEARER_NEVER_HUMAN_TOKEN"),scopeQuery:z183.tuple([z183.literal("scopeNamespace"),z183.literal("scopeRef")]),requestQuery:z183.literal("requestId"),operations:z183.strictObject({"installation.read":route(operations["installation.read"]),"task.submit":route(operations["task.submit"]),"task.by-request":route(operations["task.by-request"]),"task.get":route(operations["task.get"]),"task.cancel":route(operations["task.cancel"])}),schemas:z183.strictObject({selection:jsonSchema2,installation:jsonSchema2,taskRequest:jsonSchema2,taskResponse:jsonSchema2,taskCancel:jsonSchema2}),semanticChecks:z183.array(z183.enum(semanticChecks)).length(semanticChecks.length).refine(values=>values.every((v,i)=>v===semanticChecks[i])),maxTaskBytes:z183.literal(131072),currentAuthority:z183.literal("NOT_OBSERVED"),eventing:z183.strictObject({standard:z183.literal(eventing.standard),notificationProfile:z183.literal(eventing.notificationProfile),receiptProfile:z183.literal(eventing.receiptProfile),requiredForHostExecution:z183.literal(false),defaultReceive:z183.literal(false),subscriberKinds:z183.tuple([z183.literal("SYSTEM"),z183.literal("AGENT_RUNTIME"),z183.literal("HOST_BOT")]),authorization:z183.literal(eventing.authorization),wake:z183.literal(eventing.wake),adoption:z183.literal(eventing.adoption),receiptMeaning:z183.literal(eventing.receiptMeaning),operations:z183.strictObject({catalog:z183.literal(eventing.operations.catalog),select:z183.literal(eventing.operations.select),read:z183.literal(eventing.operations.read),handoff:z183.literal(eventing.operations.handoff),contract:z183.literal(eventing.operations.contract),resultReference:z183.literal(eventing.operations.resultReference),resultRead:z183.literal(eventing.operations.resultRead),receiptInspection:z183.literal(eventing.operations.receiptInspection),receiptHandoff:z183.literal(eventing.operations.receiptHandoff)})}),qualification:z183.literal("NVS_DECLARATION_ONLY")}));var AgentHostContractInputSchema=AgentHostScopeSchema.extend({expectedDigest:digest3.optional()}).strict();var AgentHostContractSchema=bounded2.pipe(AgentHostScopeSchema.extend({document:AgentHostContractDocumentSchema,digest:digest3,maxReplyBytes:z183.literal(131072)}).strict());import{z as z184}from"zod";var id13=z184.uuid().toLowerCase();var EventLinkScopeSchema=FederationScopeSchema.extend({tenantId:id13.pipe(TenantIdSchema),productionId:id13.pipe(ProductionIdSchema)});var EventLinkContinuationScopeSchema=z184.strictObject({workspace:id13,productionId:id13,eventLink:id13});var EventLinkStateLocatorSchema=z184.string().regex(/^[a-f0-9]{64}[A-Za-z0-9_-]{43}$/).transform(value2=>{const uuid9=v=>[v.slice(0,8),v.slice(8,12),v.slice(12,16),v.slice(16,20),v.slice(20)].join("-");return{requestId:uuid9(value2.slice(0,32)),productionId:uuid9(value2.slice(32,64))}}).pipe(z184.strictObject({requestId:id13,productionId:id13}));var EventLinkRequestInputSchema=EventLinkScopeSchema.extend({requestId:id13});var EventLinkStartInputSchema=EventLinkRequestInputSchema.extend({targetId:z184.string().regex(/^[a-zA-Z0-9_.:-]{1,80}$/),eventType:ExternalEventTypeSchema});var EventLinkConfirmInputSchema=EventLinkRequestInputSchema.extend({expiresAt:z184.iso.datetime().transform(v=>new Date(v).toISOString()),publicationMode:z184.enum(["FIXED","ON_DEMAND"])});var EventLinkCallbackInputSchema=EventLinkRequestInputSchema.extend({callback:z184.string().min(1).max(8192)});var EventLinkTargetsSchema=EventLinkScopeSchema.extend({sdkVersion:z184.literal("0.4.0"),protocol:z184.literal("event-link/1"),role:z184.literal("SENDER"),configuration:z184.enum(["CONFIGURED","UNCONFIGURED"]),targets:z184.array(z184.strictObject({id:z184.string().max(80),displayName:z184.string().min(1).max(160),serviceRef:z184.string().min(1).max(256),eventTypes:z184.array(ExternalEventTypeSchema).min(1).max(14)})).max(32)});var EventLinkViewSchema=EventLinkRequestInputSchema.extend({phase:z184.enum(["LOGIN","EXCHANGING","CONFIRM","CONFIRMED","DENIED","CANCELLED","EXPIRED","UNKNOWN"]),targetId:z184.string().max(80),eventType:ExternalEventTypeSchema,expiresAt:z184.iso.datetime(),peer:z184.strictObject({serviceRef:z184.string().min(1).max(256),tenantRef:z184.string().min(1).max(256),displayName:z184.string().min(1).max(160)}).nullable(),route:FederationRouteSchema.nullable()}).refine(v=>v.phase==="CONFIRMED"?!!v.route&&v.route.tenantId===v.tenantId&&v.route.productionId===v.productionId&&v.route.routeId===v.requestId&&v.route.selectedEventTypes.length===1&&v.route.selectedEventTypes[0]===v.eventType&&v.peer?.tenantRef===v.route.remoteTenant&&v.peer?.serviceRef===v.route.remoteService:v.route===null);var authorizationUrl=z184.url().max(8192).refine(value2=>{try{const u=new URL(value2);return!u.username&&!u.password&&!u.hash&&(u.protocol==="https:"||u.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(u.hostname))&&u.pathname==="/eventsdk/connect/authorize"}catch{return false}});var EventLinkStartSchema=EventLinkViewSchema.safeExtend({authorizationUrl:authorizationUrl.nullable(),continuationUrl:z184.url().max(2048)}).refine(v=>{const human=new URL(v.continuationUrl);if(human.username||human.password||human.hash||human.pathname!=="/settings/events"||human.protocol!=="https:"&&!(human.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(human.hostname))||human.searchParams.size!==3||!EventLinkContinuationScopeSchema.safeParse(Object.fromEntries(human.searchParams)).success||human.searchParams.get("workspace")!==v.tenantId||human.searchParams.get("eventLink")!==v.requestId||human.searchParams.get("productionId")!==v.productionId)return false;if(v.phase!=="LOGIN")return v.authorizationUrl===null;if(!v.authorizationUrl)return false;const p=new URL(v.authorizationUrl).searchParams;return p.get("request_id")===v.requestId&&p.get("profile")==="event-link/1"&&p.get("state")?.startsWith((v.requestId+v.productionId).replaceAll("-",""))===true&&EventLinkStateLocatorSchema.safeParse(p.get("state")).success});var EventLinkConfirmedSchema=EventLinkViewSchema.refine(v=>v.phase==="CONFIRMED");var EventLinkCancelledSchema=EventLinkViewSchema.refine(v=>v.phase==="CANCELLED");import{z as z185}from"zod";var ref4=z185.uuid().toLowerCase();var proof=z185.string().regex(/^[A-Za-z0-9_-]{43}$/);var EventReceiverLocatorSchema=z185.strictObject({ref:ref4,proof});var EventReceiverAccessSchema=EventReceiverLocatorSchema.extend({tenantId:EventLinkScopeSchema.shape.tenantId});var EventReceiverBeginInputSchema=z185.strictObject({authorization:z185.string().min(1).max(8192),resume:EventReceiverLocatorSchema.optional()});var EventReceiverBeginSchema=EventReceiverLocatorSchema.extend({expiresAt:z185.iso.datetime()});var EventReceiverPrepareSchema=EventReceiverAccessSchema.extend({productionId:EventLinkScopeSchema.shape.productionId,sourceSelection:FederationSourceSelectionSchema,expiresAt:z185.iso.datetime().transform(v=>new Date(v).toISOString())});var EventReceiverDecideSchema=EventReceiverAccessSchema.extend({consentBinding:z185.string().regex(/^[a-f0-9]{64}$/).optional(),decision:z185.enum(["allow","deny"])}).refine(v=>v.decision==="deny"||v.consentBinding!==void 0);var EventReceiverChoiceSchema=EventLinkScopeSchema.extend({sourceSelection:FederationSourceSelectionSchema,expiresAt:z185.iso.datetime()});var EventReceiverViewSchema=z185.strictObject({ref:ref4,state:z185.enum(["PENDING","APPROVED","CONSUMED","DENIED","EXPIRED"]),expiresAt:z185.iso.datetime(),source:z185.strictObject({displayName:z185.string().min(1).max(160),serviceRef:FederationPeerRefSchema,tenantRef:FederationPeerRefSchema,installationSource:z185.string().min(1).max(2048)}),eventType:z185.literal(RESOURCE_CHANGE_TYPE),effect:z185.literal("REFRESH_HINT"),choice:EventReceiverChoiceSchema.nullable()});var EventReceiverInspectionSchema=z185.strictObject({view:EventReceiverViewSchema,callback:z185.strictObject({redirectUri:z185.url().max(2048),state:z185.string().max(8192),issuer:z185.url()})});var EventReceiverReviewSchema=z185.strictObject({view:EventReceiverViewSchema,consentBinding:z185.string().regex(/^[a-f0-9]{64}$/)});var EventReceiverDecisionSchema=z185.strictObject({ref:ref4,redirectUri:z185.url().max(16384)});var EventReceiverPortalSchema=EventLinkScopeSchema.extend({role:z185.literal("RECEIVER"),protocol:z185.literal("event-link/1"),sdkVersion:z185.literal("0.4.0"),configuration:z185.enum(["CONFIGURED","UNCONFIGURED"]),authorizationEndpoint:z185.url().nullable(),tokenEndpoint:z185.url().nullable(),eventType:z185.literal(RESOURCE_CHANGE_TYPE),dataSchema:z185.literal(RESOURCE_CHANGE_SCHEMA),effect:z185.literal("REFRESH_HINT"),defaultReceive:z185.literal(false)});var intent=z186.strictObject({productionId:z186.uuid(),idempotencyKey:z186.string().trim().min(1).max(200),deviceId:z186.uuid().optional(),validationMode:DeviceRenderTargetSchema.shape.validationMode});var DeviceDiscoveryInputSchema=ProjectDeviceListInputSchema.omit({tenantId:true});var DeviceRenderIntentSchema=z186.discriminatedUnion("kind",[intent.extend({kind:z186.literal("preview"),profileId:RoughCutProfileIdSchema.optional()}),intent.extend({kind:z186.literal("final")})]);var DeviceRenderReadSchema=z186.strictObject({kind:z186.enum(["preview","final"]),productionId:z186.uuid(),renderId:z186.uuid()});var basisInput=DeviceRenderReadSchema.pick({kind:true,productionId:true});var DeviceRenderDownloadSchema=DeviceRenderReadSchema.extend({role:z186.enum(["VIDEO","POSTER"])});var PreparedDeviceRenderSchema=z186.discriminatedUnion("kind",[z186.strictObject({kind:z186.literal("preview"),command:RoughCutStartSchema.extend({deviceExecution:DeviceRenderTargetSchema})}),z186.strictObject({kind:z186.literal("final"),command:FinalRenderStartSchema.extend({deviceExecution:DeviceRenderTargetSchema})})]);var DeviceRenderReceiptHandoffSchema=z186.strictObject({protocol:z186.literal("NVS_RENDER_RECEIPT_V1"),scope:z186.strictObject({resource:z186.string().min(1).max(2048),tenantId:z186.uuid(),projectId:z186.uuid(),principalId:z186.uuid(),grantId:z186.uuid()}),prepared:PreparedDeviceRenderSchema});var DeviceRenderAdmissionSchema=z186.union([RoughCutAdmissionSchema.extend({deviceExecution:DeviceRenderReceiptSchema}),FinalRenderAdmissionSchema.extend({deviceExecution:DeviceRenderReceiptSchema})]);var NativeStudioDeviceRenders=class{constructor(caller){this.caller=caller}caller;list(raw,options){const input=DeviceDiscoveryInputSchema.parse(raw);return this.caller.call("devices.list",{...input,tenantId:this.caller.tenantId},options)}async basis(raw,options){const{kind,productionId}=basisInput.parse(raw);const scope8={tenantId:this.caller.tenantId,productionId};if(kind==="final"){const e=await this.caller.call("final-render.eligibility",scope8,options);const selection2=e.finalReady.selection;const basis2=e.renderable&&e.profile&&selection2?{selectionId:selection2.id,expectedFinalReadyVersion:e.finalReady.version,timelineVersionId:selection2.timelineVersionId,timelineFingerprint:selection2.timelineFingerprint,expectedProductionRevision:e.productionRevision,profileId:e.profile.id,audioPolicy:e.profile.audioPolicy,captionPolicy:e.profile.captionPolicy}:null;return{kind,basis:basis2,blockers:basis2?[]:e.blockers.length?e.blockers:["FINAL_READY_NOT_CURRENT"],sourceBlockers:e.sourceBlockers}}const basis=await this.caller.call("timeline.basis",scope8,options);if(!basis.runnable||basis.currentTimelineVersion===0)return{kind,basis:null,blockers:["TIMELINE_NOT_RUNNABLE"]};const current=await this.caller.call("timeline.current",scope8,options);const selection=currentPreviewRenderBasis(basis,current);return{kind,basis:selection,blockers:selection?[]:["TIMELINE_NOT_CURRENT"]}}async prepare(raw,options){const input=DeviceRenderIntentSchema.parse(raw);const scope8={tenantId:this.caller.tenantId,productionId:input.productionId};const base3={...scope8,idempotencyKey:input.idempotencyKey,deviceExecution:{mode:"tenant-device-only",...input.deviceId?{deviceId:input.deviceId}:{},...input.validationMode?{validationMode:input.validationMode}:{}}};const{basis}=await this.basis({kind:input.kind,productionId:input.productionId},options);if(!basis)throw new NativeStudioSdkError("STALE_BASIS","STALE_BASIS","NO_WRITE");return PreparedDeviceRenderSchema.parse({kind:input.kind,command:{...base3,...basis,...input.kind==="preview"&&{profileId:input.profileId??"PREVIEW_H264_480P_V1"}}})}get(raw,options){const{kind,...input}=DeviceRenderReadSchema.parse(raw);return kind==="preview"?this.caller.call("rough-cut.get",input,options):this.caller.call("final-render.get",input,options)}async mediaTicket(raw,options){const{kind,...input}=DeviceRenderDownloadSchema.parse(raw);const result=kind==="preview"?await this.caller.call("rough-cut.media-ticket",input,options):await this.caller.call("final-render.media-ticket",input,options);if(result.ticket.object.tenantId!==this.caller.tenantId||result.ticket.method!=="GET"||result.ticket.object.role!==input.role)throw new NativeStudioSdkError("MEDIA_IDENTITY_MISMATCH","INTERNAL_OPERATIONAL_FAILURE","NO_WRITE");return result}async download(raw,options,expectedProjectId){const input=DeviceRenderDownloadSchema.parse(raw);const{role,...scope8}=input;const view=await this.get(scope8,options);const accepted3="roughCut"in view?view.roughCut:view.finalOutput;const expected=role==="POSTER"?accepted3?.poster:accepted3;const failure=()=>new NativeStudioSdkError("MEDIA_IDENTITY_MISMATCH","INTERNAL_OPERATIONAL_FAILURE","NO_WRITE");if(!expected||expectedProjectId&&expectedProjectId!==view.projectId)throw failure();const media=await this.mediaTicket(input,options);if(media.ticket.object.projectId!==view.projectId||media.representationId!==expected.representationId||media.ticket.object.checksumSha256!==expected.checksumSha256||media.ticket.object.byteSize!==expected.byteSize)throw failure();const output=await downloadRenderObject(media.ticket,options);return{...output,representationId:media.representationId,renderId:media.renderId}}receipt(raw,options){const prepared=PreparedDeviceRenderSchema.parse(raw);return prepared.kind==="preview"?this.caller.call("rough-cut.admission-receipt",prepared.command,options):this.caller.call("final-render.admission-receipt",prepared.command,options)}start(raw,options){const prepared=PreparedDeviceRenderSchema.parse(raw);return prepared.kind==="preview"?this.caller.call("rough-cut.start",prepared.command,options):this.caller.call("final-render.start",prepared.command,options)}};import{createHash as createHash5}from"node:crypto";import{createHash as createHash4}from"node:crypto";import{z as z187}from"zod";import{createHash as createHash2}from"node:crypto";function assertFederationExchangeReply(key10,i,r){let valid=true,write2=false;if(key10==="federation.subscription.contract"){valid=r.subscription.revision===i.expectedRevision&&(!i.expectedSource||i.expectedSource===r.source)&&(r.status!=="READY"||(!i.expectedCatalogDigest||i.expectedCatalogDigest===r.catalogDigest)&&r.catalogDigest==="sha256:"+createHash2("sha256").update(canonicalFederationCatalogJson(r.catalog)).digest("hex"))}if(key10==="federation.result.reference"){const ref7=r.reference;valid=i.resourceType===ref7.resourceType&&i.resourceId===ref7.resourceId}if(key10==="federation.result.read")valid=canonicalFederationJson(i.reference)===canonicalFederationJson(r.reference)&&r.reference.digest==="sha256:"+createHash2("sha256").update(canonicalFederationJson(r.value)).digest("hex");if(key10==="federation.receipt-route.configure"){write2=true;valid=["grantRef","grantVersion","state","receiptProfile"].every(k=>i[k]===r[k])&&r.revision===Number(i.expectedRevision)+1&&Date.parse(String(i.notBefore))===Date.parse(String(r.notBefore))&&Date.parse(String(i.expiresAt))===Date.parse(String(r.expiresAt))}if(key10==="federation.receipt.query")valid=r.items.every(v=>(!i.routeId||v.routeId===i.routeId)&&(!i.inboxId||v.inboxId===i.inboxId)&&(!i.originDeliveryId||v.originDelivery?.deliveryId===i.originDeliveryId));if(key10==="federation.receipt.command")valid=i.requestId===r.requestId&&(!r.result||!("requestId"in r.result)||r.result.requestId===i.requestId);if(key10==="federation.receipt.recover"){write2=true;valid=i.requestId===r.requestId&&r.generation===Number(i.expectedGeneration)+1&&r.attempts===i.expectedAttempts}if(key10==="federation.subscription.handoff")valid=i.expectedRevision===void 0||i.expectedRevision===r.subscription.revision;if(!valid)throw new NativeStudioSdkError("RESPONSE_SCOPE_MISMATCH","INTERNAL_OPERATIONAL_FAILURE",write2?"UNKNOWN":"NO_WRITE")}import{createHash as createHash3}from"node:crypto";function validAcceptance(i,r){const b=r.binding;return b.bindingId===i.bindingId&&b.revision===i.expectedRevision&&(!i.expectedSource||i.expectedSource===r.source)&&(!i.expectedDigest||i.expectedDigest===r.digest)&&(r.document===null||r.digest==="sha256:"+createHash3("sha256").update(canonicalFederationReadJson(r.document)).digest("hex"))}function assertReceiptInboundReply(key10,i,r){if(!key10.startsWith("federation.receipt-inbound."))return;let valid=true;const write2=key10.endsWith(".configure");if(key10.endsWith(".contract"))valid=validAcceptance(i,r);if(key10.endsWith(".handoff")){const inspection=r.inspection,delivery2=inspection.delivery;valid=delivery2.digest===i.expectedDeliveryDigest&&validAcceptance({...i,expectedDigest:i.expectedAcceptanceDigest},r.acceptance)}if(write2)valid=["contractVersion","remoteService","source","remoteTenant","peerType","consumerRef","peerConsumerRef","peerTargetScope","grantRef","grantVersion","state"].every(k=>i[k]===r[k])&&r.revision===Number(i.expectedRevision)+1&&Date.parse(String(i.notBefore))===Date.parse(String(r.notBefore))&&Date.parse(String(i.expiresAt))===Date.parse(String(r.expiresAt));if(key10.endsWith(".command"))valid=i.requestId===r.requestId;if(key10.endsWith(".catalog"))valid=r.bindings.every(b=>b.tenantId===i.tenantId&&b.productionId===i.productionId&&b.effective==="ACTIVE");if(key10.endsWith(".query"))valid=r.items.every(v=>(!i.bindingId||v.bindingId===i.bindingId)&&(!i.originalDeliveryId||v.originalDeliveryId===i.originalDeliveryId));if(!valid)throw new NativeStudioSdkError("RESPONSE_SCOPE_MISMATCH","INTERNAL_OPERATIONAL_FAILURE",write2?"UNKNOWN":"NO_WRITE")}function assertDeliveryInspectionReply(key10,i,raw){if(key10!=="federation.delivery.inspect")return;const d=raw.delivery,b=raw.receiptBinding;if(i.expectedSource&&i.expectedSource!==raw.source||i.expectedDigest&&i.expectedDigest!==d.digest||(i.receiptBindingId?b?.bindingId!==i.receiptBindingId:b!==null))throw new NativeStudioSdkError("RESPONSE_SCOPE_MISMATCH","INTERNAL_OPERATIONAL_FAILURE","NO_WRITE")}function assertFederationReply(key10,input,raw){if(!key10.startsWith("federation.")||!raw||typeof raw!=="object")return;const result=raw;assertDeliveryInspectionReply(key10,input,result);assertReceiptInboundReply(key10,input,result);assertFederationExchangeReply(key10,input,result);let valid=true;if(key10==="federation.inbound.configure"){valid=["contractVersion","source","remoteService","remoteTenant","consumerRef","grantRef","grantVersion","state"].every(k=>input[k]===result[k])&&result.revision===Number(input.expectedRevision)+1&&Date.parse(String(input.notBefore))===Date.parse(String(result.notBefore))&&Date.parse(String(input.expiresAt))===Date.parse(String(result.expiresAt))&&(!input.connectionRef||input.connectionRef===result.connectionRef)&&canonicalFederationJson(input.sourceSelection??null)===canonicalFederationJson(result.sourceSelection??null)}if(key10==="federation.inbound.replay")valid=input.requestId===result.requestId;if(key10==="federation.inbound.catalog")valid=result.bindings.every(b=>["tenantId","productionId"].every(k=>input[k]===b[k]));if(key10==="federation.inbound.receipt")valid=input.kind==="COMMAND"?input.requestId===result.requestId&&(!result.result||!("requestId"in result.result)||input.requestId===result.result.requestId):["source","eventId","consumerRef"].every(k=>input[k]===result[k]&&(!result.result||input[k]===result.result[k]));if(key10==="federation.recover"){valid=input.requestId===result.requestId&&result.revision===Number(input.expectedRevision)+1&&(input.deliveryId??null)===result.deliveryId&&(input.kind!=="RETRY_HOLD"||input.expectedAttempts===result.attempts)}if(key10==="federation.receipt")valid=input.requestId===result.requestId;if(key10==="federation.query"){valid=result.items.every(r=>["routeId","eventId","deliveryId"].every(k=>input[k]===void 0||r[k]===input[k]))}if(key10==="federation.route.configure"||key10==="federation.subscription.set"){const route5=key10==="federation.route.configure";const view=route5?result:result.subscription;const refs=route5?["remoteService","remoteTenant","grantRef"]:["subscriberKind","subscriberRef"];const arrays=route5?["grantEventTypes","selectedEventTypes"]:["eventTypes"];valid=refs.every(k=>input[k]===view[k])&&arrays.every(k=>JSON.stringify([...input[k]].sort())===JSON.stringify([...view[k]].sort()))&&view.revision===Number(input.expectedRevision)+1&&view.state===input.state&&Date.parse(String(input.expiresAt))===Date.parse(String(view.expiresAt));if(route5)valid=valid&&input.publicationMode===view.publicationMode&&Date.parse(String(input.notBefore))===Date.parse(String(view.notBefore))}if(!valid)throw new NativeStudioSdkError("RESPONSE_SCOPE_MISMATCH","INTERNAL_OPERATIONAL_FAILURE",key10==="federation.route.configure"||key10==="federation.subscription.set"||key10==="federation.inbound.configure"||key10==="federation.inbound.replay"||key10==="federation.recover"?"UNKNOWN":"NO_WRITE")}var success=z187.strictObject({semanticStatus:z187.literal("SUCCESS")});var same=(a,b)=>canonicalLocalJson(a??null)===canonicalLocalJson(b??null);var commandFingerprint=command4=>createHash4("sha256").update(canonicalLocalJson(command4)).digest("hex");function resultMatches(command4,raw){const schema=command4.kind==="ENROLL"?LocalDeviceViewSchema:command4.kind==="PREVIEW"?LocalPreviewAdmissionSchema:command4.kind==="FINAL_RENDER"?LocalFinalRenderAdmissionSchema:success;const parsed=schema.safeParse(raw);if(!parsed.success)return false;const result=parsed.data,original=command4.input;for(const key10 of["tenantId","projectId","deviceId","productionId","timelineVersionId"])if(key10 in original&&key10 in result&&String(result[key10]).toLowerCase()!==String(original[key10]).toLowerCase())return false;if(command4.kind==="ENROLL")return result.revokedAt===null&&(!command4.input.expectedPrincipalId||String(result.enrolledByPrincipalId).toLowerCase()===command4.input.expectedPrincipalId.toLowerCase())&&["publicKey","label","platform","runtimeVersion"].every(key10=>same(original[key10],result[key10]));if(command4.kind==="PREVIEW"||command4.kind==="FINAL_RENDER")return same(original.timelineFingerprint,result.timelineFingerprint)&&same(command4.input.placement,result.placement.policy);return true}function checkedManagementReceipt(rawCommand,rawReceipt){const command4=LocalDeviceManagementCommandSchema.parse(rawCommand);const receipt=LocalManagementReceiptSchema.parse(rawReceipt);if(receipt.fingerprint!==commandFingerprint(command4)||receipt.result!==null&&!resultMatches(command4,receipt.result))throw new NativeStudioSdkError("LOCAL_RECEIPT_INVALID","BLOCKED","NO_WRITE");return receipt}function checkedEnrollmentObservation(original,observation,write2){const command4="kind"in original?original:void 0;const request="kind"in original?original.input:original;const bound=value2=>value2.tenantId.toLowerCase()===request.tenantId.toLowerCase()&&value2.requestId.toLowerCase()===request.requestId.toLowerCase();const invalid=()=>{throw new NativeStudioSdkError("DEVICE_ENROLLMENT_RESPONSE_INVALID","BLOCKED",write2?"UNKNOWN":"NO_WRITE")};if(!bound(observation))invalid();const fingerprint2=command4&&commandFingerprint(command4);if(observation.state==="ISSUED"&&(!bound(observation.ticket)||fingerprint2&&observation.ticket.fingerprint!==fingerprint2))invalid();if(observation.state==="EXPIRED"&&fingerprint2&&observation.fingerprint!==fingerprint2)invalid();if(observation.state==="ENROLLED"){const{receipt}=observation;if(receipt.result.tenantId.toLowerCase()!==request.tenantId.toLowerCase()||command4&&(receipt.fingerprint!==fingerprint2||!resultMatches(command4,receipt.result)))invalid()}return observation}function assertManagementReceipt(key10,input,result){assertFederationReply(key10,input,result);if(key10==="device.management-receipt")checkedManagementReceipt(input.command,result);else if(key10==="device.enrollment.issue"||key10==="device.enrollment.lookup"){const write2=key10==="device.enrollment.issue";const original=write2?{kind:"ENROLL",input:DeviceEnrollmentIssueSchema.parse(input)}:DeviceEnrollmentLookupSchema.parse(input);checkedEnrollmentObservation(original,DeviceEnrollmentObservationSchema.parse(result),write2)}else if(key10==="device.enroll"){const command4=LocalDeviceManagementCommandSchema.parse({kind:"ENROLL",input});if(!resultMatches(command4,result))throw new NativeStudioSdkError("RESPONSE_SCOPE_MISMATCH","INTERNAL_OPERATIONAL_FAILURE","UNKNOWN")}}function validateDeviceEnrollmentHandoff(raw){const parsed=DeviceEnrollmentHandoffSchema.safeParse(raw);if(!parsed.success||createHash5("sha256").update(canonicalLocalJson(parsed.data.command)).digest("hex")!==parsed.data.fingerprint)throw new NativeStudioSdkError("DEVICE_HANDOFF_INVALID","INVALID_INPUT","NO_WRITE");return parsed.data}async function issueDeviceEnrollment(client,raw,options={}){const handoff=await verifyCaller(client,raw,options);const result=await client.call("device.enrollment.issue",DeviceEnrollmentIssueSchema.parse(handoff.command.input),options);return checkedEnrollmentObservation(handoff.command,result,true)}async function lookupDeviceEnrollment(client,raw,options={}){const handoff=await verifyCaller(client,raw,options);const{tenantId,requestId:requestId2}=handoff.command.input;const result=await client.call("device.enrollment.lookup",{tenantId,requestId:requestId2},options);return checkedEnrollmentObservation(handoff.command,result,false)}async function verifyCaller(client,raw,options){const handoff=validateDeviceEnrollmentHandoff(raw);const{tenantId,principalId,origin}=handoff.scope;if(tenantId.toLowerCase()!==client.tenantId.toLowerCase())throw new NativeStudioSdkError("FORBIDDEN","BLOCKED","NO_WRITE");const caller=await client.call("workspace.caller",{tenantId},options);if(caller.serverOrigin!==origin||caller.tenantId.toLowerCase()!==tenantId.toLowerCase()||caller.principalId.toLowerCase()!==principalId.toLowerCase())throw new NativeStudioSdkError("FORBIDDEN","BLOCKED","NO_WRITE");return handoff}async function submitDeviceEnrollment(client,raw,options={}){const handoff=await verifyCaller(client,raw,options);const result=await client.call("device.enroll",handoff.command.input,options);return{fingerprint:handoff.fingerprint,result}}async function recoverDeviceEnrollment(client,raw,options={}){const handoff=await verifyCaller(client,raw,options);return client.call("device.management-receipt",{tenantId:handoff.scope.tenantId,command:handoff.command},options)}import"zod";function descriptorOperation(input,output,request,expectedPath){return Object.freeze({...operation(input,output,request,[],{readOnly:true}),expectedPath})}function operation(input,output,request,identity6=[],options={}){return Object.freeze({input,output,request,identity:identity6,readOnly:options.readOnly,expectedPath:void 0,identityWhenPresent:options.identityWhenPresent??[]})}function path(...parts){return"/v1/"+parts.map(value2=>encodeURIComponent(value2)).join("/")}function pageQuery(input){return{limit:input.limit,next:input.next}}function mcpOperation(input,output,readOnly,identity6=[],expectedPath){return Object.freeze({input,output,request:null,readOnly,identity:identity6,expectedPath,identityWhenPresent:[]})}var post=(action,input,output,readOnly,identity6=[])=>operation(input,output,i=>({method:"POST",tenantId:i.tenantId,path:path("shares",action),body:i}),identity6,{readOnly});var target2=["shareId","projectId","artifactId","representationId"].map(k=>[k,"share."+k]);var shareOperations={"share.create":post("create",ShareCreateSchema,ShareLinkResultSchema,false,target2),"share.link":post("link",ShareGetSchema,ShareLinkResultSchema,false,[["shareId","share.shareId"]]),"share.get":post("get",ShareGetSchema,ShareViewSchema.nullable(),true,[["shareId","shareId"]]),"share.list":post("list",ShareListSchema,SharePageSchema,true,[["artifactId","items.*.artifactId"]]),"share.revoke":post("revoke",ShareRevokeSchema,ShareViewSchema,false,[["shareId","shareId"]]),"share.receipt":post("receipt",ShareCreateSchema,ShareViewSchema.nullable(),true,[...["shareId","projectId","artifactId","representationId"].map(k=>[k,k])])};import{z as z189}from"zod";function inputIssues(error,schema){const fields=new Set;const collect=node=>{if(node instanceof z189.ZodObject)Object.keys(node.shape).forEach(key10=>fields.add(key10));else if(node instanceof z189.ZodUnion)node.options.forEach(branch2=>collect(branch2))};collect(schema);const result=new Map;for(const issue of error.issues){const first=issue.path[0];const field=typeof first==="string"&&first.length<=120&&fields.has(first)?first:"$";const safe={field,code:issue.code};result.set(`${field}:${safe.code}`,safe);if(result.size>=8)break}return[...result.values()]}import{z as z190}from"zod";var success2=z190.strictObject({semanticStatus:z190.literal("SUCCESS")});var deviceManagementOperations={"device.status":operation(DeviceStatusInputSchema,DeviceStatusSchema,({tenantId,deviceId})=>({method:"GET",path:path("local-execution","devices",deviceId,"status"),tenantId}),[["tenantId","tenantId"],["deviceId","deviceId"]]),"device.enrollment.issue":operation(DeviceEnrollmentIssueSchema,DeviceEnrollmentObservationSchema,body=>({method:"POST",path:path("local-execution","devices","enrollments"),tenantId:body.tenantId,body}),[["tenantId","tenantId"],["requestId","requestId"]]),"device.enrollment.lookup":operation(DeviceEnrollmentLookupSchema,DeviceEnrollmentObservationSchema,({tenantId,requestId:requestId2})=>({method:"GET",path:path("local-execution","devices","enrollments",requestId2),tenantId}),[["tenantId","tenantId"],["requestId","requestId"]]),"workspace.devices.list":operation(WorkspaceDeviceListInputSchema,WorkspaceDeviceListSchema,({tenantId,deviceId,after,limit})=>({method:"GET",tenantId,path:path("local-execution","devices"),query:{deviceId,after,limit}}),[["deviceId","items.*.deviceId"]],{readOnly:true}),"device.enroll":operation(EnrollLocalDeviceSchema,LocalDeviceViewSchema,i=>({method:"POST",tenantId:i.tenantId,path:path("local-execution","devices","enroll"),body:i}),[["tenantId","tenantId"],["publicKey","publicKey"],["label","label"],["platform","platform"],["runtimeVersion","runtimeVersion"]]),"device.revoke":operation(RevokeLocalDeviceSchema,success2,i=>({method:"POST",tenantId:i.tenantId,path:path("local-execution","devices","revoke"),body:i})),"device.management-receipt":operation(ScopedLocalManagementReceiptSchema,LocalManagementReceiptSchema,i=>({method:"POST",tenantId:i.tenantId,path:path("local-execution","management-receipt"),body:i.command}),[],{readOnly:true})};import{createHash as createHash6}from"node:crypto";var identityFailure=()=>new NativeStudioSdkError("MEDIA_IDENTITY_MISMATCH","INTERNAL_OPERATIONAL_FAILURE","UNKNOWN");function checkTicket({endpoint,method,object},expected){const url=new URL(endpoint);if(method!=="PUT"||object.role!=="SOURCE"||object.tenantId!==expected.tenantId||object.projectId!==expected.projectId||object.byteSize!==expected.byteSize||object.checksumSha256!==expected.checksumSha256||url.pathname!==mediaObjectTransferPath||url.username||url.password||url.search||url.hash||url.protocol!=="https:"&&!(url.protocol==="http:"&&url.hostname==="127.0.0.1"))throw identityFailure();return url}async function upload(ticket,url,bytes,options){const timeout=AbortSignal.timeout(12e4);const signal=options.signal?AbortSignal.any([options.signal,timeout]):timeout;try{const result=await fetch(url,{method:"PUT",redirect:"error",headers:{authorization:"Bearer "+ticket.credential},body:new Uint8Array(bytes),signal});await result.body?.cancel();if(result.status===204)return}catch{}throw new NativeStudioSdkError("OBJECT_UPLOAD_UNCONFIRMED","BLOCKED","UNKNOWN")}var NativeStudioDirectSources=class{constructor(tenantId,transport){this.tenantId=tenantId;this.transport=transport}tenantId;transport;async importProjectSource(intent2,input,options={}){if(!(input instanceof Uint8Array)||input.length<1||input.length>8*1024*1024)sdkInputError();const bytes=Buffer.from(input);const result=DirectProjectSourceCommandSchema.safeParse({...intent2,metadata:{...intent2.metadata,tenantId:this.tenantId},byteSize:bytes.length,checksumSha256:createHash6("sha256").update(bytes).digest("hex")});if(!result.success)sdkInputError();const{projectId,...body}=result.data;const scope8={tenantId:this.tenantId,projectId};const endpoint=action=>path("projects",projectId,"source-artifacts","direct",action);const validate=receipt2=>{if(receipt2.state==="ACCEPTED"){const{artifact:artifact2,primaryRepresentation}=receipt2.registration;if(artifact2.tenantId!==scope8.tenantId||artifact2.projectId!==projectId||artifact2.productionId!==null||artifact2.lifecycle!=="READY"||primaryRepresentation.artifactId!==artifact2.id||primaryRepresentation.tenantId!==scope8.tenantId||primaryRepresentation.checksumSha256!==body.checksumSha256||primaryRepresentation.byteSize!==String(body.byteSize))throw identityFailure()}else if(receipt2.tenantId!==scope8.tenantId||receipt2.projectId!==projectId)throw identityFailure();return receipt2};const stage=await this.transport.json({method:"POST",tenantId:scope8.tenantId,path:endpoint("stage"),body},DirectProjectSourceStageSchema,options);if(stage.state!=="UPLOAD")return validate(stage);if(stage.tenantId!==scope8.tenantId||stage.projectId!==projectId)throw identityFailure();const url=checkTicket(stage.ticket,{...scope8,...body});if(!stage.uploaded)await upload(stage.ticket,url,bytes,options);const receipt=await this.transport.json({method:"POST",tenantId:scope8.tenantId,path:endpoint("submit"),body:{tenantId:scope8.tenantId,intakeId:stage.intakeId}},DirectProjectSourceSubmitSchema,options);if(receipt.state==="SUBMITTED"&&receipt.intakeId!==stage.intakeId)throw identityFailure();return validate(receipt)}async importOriginal(raw,input,options={}){const parsed=DirectOriginalCommandSchema.safeParse(raw);if(!parsed.success)sdkInputError();const command4=parsed.data;const{tenantId,projectId,productionId,shotId,source:source6}=command4.input;if(tenantId!==this.tenantId||!(input instanceof Uint8Array)||input.length!==source6.byteSize)sdkInputError();const bytes=Buffer.from(input);if(createHash6("sha256").update(bytes).digest("hex")!==source6.checksumSha256)sdkInputError();const scope8={tenantId,projectId,productionId};const endpoint=action=>path("productions",productionId,"imported-visuals","originals","direct",action);const validate=receipt2=>{const value2=receipt2.state==="ACCEPTED"?receipt2.original:receipt2;if(value2.tenantId!==tenantId||value2.projectId!==projectId||value2.productionId!==productionId)throw identityFailure();if(receipt2.state==="ACCEPTED"){const{original}=receipt2;if(original.shotId!==shotId||original.metadata.checksumSha256!==source6.checksumSha256||original.metadata.byteSize!==source6.byteSize||command4.operation==="REVISE"&&(original.sourceId!==command4.input.sourceId||original.version!==command4.input.expectedVersion+1))throw identityFailure()}return receipt2};const stage=await this.transport.json({method:"POST",tenantId,path:endpoint("stage"),body:command4},DirectOriginalStageSchema,options);if(stage.state!=="UPLOAD")return validate(stage);if(stage.tenantId!==tenantId||stage.projectId!==projectId||stage.productionId!==productionId)throw identityFailure();const url=checkTicket(stage.ticket,{...scope8,...source6});if(!stage.uploaded)await upload(stage.ticket,url,bytes,options);const receipt=await this.transport.json({method:"POST",tenantId,path:endpoint("submit"),body:{...scope8,intakeId:stage.intakeId}},DirectOriginalSubmitSchema,options);if(receipt.state==="SUBMITTED"&&receipt.intakeId!==stage.intakeId)throw identityFailure();return validate(receipt)}};var NativeStudioNavigationFacade=class{constructor(caller){this.caller=caller}caller;find(input,options){return this.caller.call("studio.start",input,options)}overview(input,options){return this.caller.call("studio.navigate",input,options)}next(input,options){return this.overview(input,options)}resume(input,options){return this.caller.call("operation.get",input,options)}groups(input={},options){return this.caller.call("studio.capability.groups",input,options)}search(input,options){return this.caller.call("studio.capability.search",input,options)}describe(input,options){return this.caller.call("studio.capability.describe",input,options)}query(input,options){return this.caller.call("studio.capability.query",input,options)}invoke(input,options){return this.caller.call("studio.capability.invoke",input,options)}};import{createHash as createHash12}from"node:crypto";import{createHash as createHash7}from"node:crypto";function assertExportBytes(value2,captionFormat){const v=value2;const bytes=v.contentBase64!==void 0?Buffer.from(v.contentBase64,"base64"):Buffer.from(v.text,"utf8");if(v.contentBase64!==void 0&&(bytes.toString("base64")!==v.contentBase64||bytes.length!==v.byteSize||bytes.toString("ascii",0,4)!=="RIFF"||bytes.toString("ascii",8,12)!=="WAVE")||bytes.length>(v.contentBase64!==void 0?12582912:131072)||captionFormat!==void 0&&v.contentType!==(captionFormat==="JSON"?"application/json":"application/x-subrip")||createHash7("sha256").update(bytes).digest("hex")!==v.checksumSha256)throw new NativeStudioSdkError("MEDIA_IDENTITY_MISMATCH","INTERNAL_OPERATIONAL_FAILURE","NO_WRITE")}import{createHash as createHash8}from"node:crypto";function assertPreviewBytes(value2){const v=value2;if(v.semanticStatus!=="SUCCESS")return;const data=v.contentBase64;if(typeof data!=="string"||data.length>4*Math.ceil(8*1024*1024/3))throw new NativeStudioSdkError("RESPONSE_INVALID","INTERNAL_OPERATIONAL_FAILURE","NO_WRITE");const bytes=Buffer.from(data,"base64");if(bytes.length!==v.byteSize||bytes.toString("base64")!==data||!bytes.subarray(0,8).equals(Buffer.from([137,80,78,71,13,10,26,10]))||createHash8("sha256").update(bytes).digest("hex")!==v.checksumSha256)throw new NativeStudioSdkError("MEDIA_IDENTITY_MISMATCH","INTERNAL_OPERATIONAL_FAILURE","NO_WRITE")}import{createHash as createHash9}from"node:crypto";function assertOriginalVideoBytes(value2){const v=value2;const bytes=Buffer.from(v.dataBase64,"base64");if(bytes.toString("base64")!==v.dataBase64||bytes.length!==v.source.byteSize||bytes.subarray(4,8).toString("ascii")!=="ftyp"||createHash9("sha256").update(bytes).digest("hex")!==v.source.checksumSha256)throw new NativeStudioSdkError("RESPONSE_INVALID","INTERNAL_OPERATIONAL_FAILURE","NO_WRITE")}import{z as z191}from"zod";var production2=z191.strictObject({tenantId:TenantIdSchema,productionId:ProductionIdSchema});var sourceUpload=UploadSourceInputRequestSchema.extend({projectId:ProjectIdSchema,idempotencyKey:z191.string().trim().min(1).max(200)});var projectProduction=(p,prod,suffix)=>path("projects",p,"productions",prod,suffix);var coreOperations={"workspace.status":operation(WorkspaceScopeSchema,WorkspaceStatusSchema,({tenantId})=>({method:"GET",path:path("workspace","status"),tenantId}),[["tenantId","tenantId"]]),"workspace.get":operation(WorkspaceScopeSchema,WorkspaceViewSchema,i=>({method:"GET",path:path("workspace"),tenantId:i.tenantId})),"workspace.caller":operation(WorkspaceScopeSchema,WorkspaceCallerSchema,i=>({method:"GET",path:path("workspace","caller"),tenantId:i.tenantId}),[["tenantId","tenantId"]]),"workspace.query":operation(WorkspaceScopeSchema,WorkspacePageSchema,i=>({method:"GET",path:path("workspaces"),tenantId:i.tenantId})),"visual-sequence.start-registration":operation(RegisterVisualSequenceSchema,VisualSequenceRegistrationAdmissionSchema,i=>{const{tenantId,projectId,...body}=i;return{method:"POST",path:path("projects",projectId,"visual-sequences","jobs"),tenantId,body}}),"visual-sequence.register":operation(LegacyVisualSequenceRegistrationSchema,VisualSequenceViewSchema,i=>{const{tenantId,projectId,...body}=i;return{method:"POST",path:path("projects",projectId,"visual-sequences"),tenantId,body}},[["projectId","sequence.projectId"]]),"visual-sequence.get":operation(VisualSequenceGetSchema,VisualSequenceViewSchema,i=>({method:"GET",path:path("projects",i.projectId,"visual-sequences",i.artifactId),tenantId:i.tenantId}),[["artifactId","sequence.artifactId"]]),"visual-sequence.query":operation(VisualSequenceQuerySchema,VisualSequencePageSchema,i=>({method:"GET",path:path("projects",i.projectId,"visual-sequences"),tenantId:i.tenantId,query:pageQuery(i)})),"project.create":operation(CreateProjectRequestSchema,CreatedProjectResultSchema,input=>({method:"POST",path:path("projects"),tenantId:input.tenantId,body:input})),"production.create":operation(CreateProductionRequestSchema,CreatedProductionResultSchema,input=>({method:"POST",path:path("projects",input.projectId,"productions"),tenantId:input.tenantId,body:{idempotencyKey:input.idempotencyKey}}),[["projectId","project.id"]]),"production.terminate":operation(TerminateProductionSchema,ProductionTerminationReceiptSchema,input=>({method:"POST",path:path("projects",input.projectId,"productions",input.productionId,"terminate"),tenantId:input.tenantId,body:{outcome:input.outcome,expectedProductionRevision:input.expectedProductionRevision,reason:input.reason,idempotencyKey:input.idempotencyKey}}),[["productionId","productionId"],["projectId","projectId"]]),"project.query":operation(ProjectLibraryQuerySchema,ProjectLibraryPageSchema,input=>({method:"GET",path:path("projects"),tenantId:input.tenantId,query:pageQuery(input)})),"project.get":operation(ProjectLibraryScopeSchema,ProjectWorkspaceSchema,input=>({method:"GET",path:path("projects",input.projectId),tenantId:input.tenantId}),[["projectId","project.id"]]),"devices.list":operation(ProjectDeviceListInputSchema,ProjectDeviceListSchema,({tenantId,projectId,kind,deviceId})=>({method:"GET",path:path("local-execution","projects",projectId,"devices"),tenantId,query:{kind,deviceId}}),[["projectId","projectId"],["kind","kind"],["deviceId","items.*.deviceId"]],{readOnly:true}),"source.query":operation(SourceLibraryQuerySchema,SourceLibraryPageSchema,input=>({method:"GET",path:input.projectId?path("projects",input.projectId,"source-artifacts"):path("source-artifacts"),tenantId:input.tenantId,query:pageQuery(input)})),"source.ingest":operation(sourceUpload,ReadyArtifactRegistrationSchema,input=>{const{projectId,...body}=input;return{method:"POST",path:path("projects",projectId,"source-artifacts"),tenantId:input.tenantId,body}}),"source.text":operation(SourceReadSchema,SourceTextWindowSchema,input=>({method:"GET",path:path("projects",input.projectId,"source-artifacts",input.artifactId,"text"),tenantId:input.tenantId,query:{offsetBytes:input.offsetBytes,maxTextBytes:input.maxTextBytes}}),[["artifactId","artifactId"]]),"production.query":operation(ProductionQueryInputSchema.strict(),ProductionQueryPageSchema,input=>({method:"GET",path:path("productions"),tenantId:input.tenantId,query:{...pageQuery(input),projectId:input.projectId,search:input.search,attention:input.attention}})),"production.snapshot":operation(production2,ProductionSnapshotSchema,input=>({method:"GET",path:path("productions",input.productionId,"snapshot"),tenantId:input.tenantId})),"brief.accept":operation(ScopedAcceptBriefSchema,AcceptBriefResultSchema,input=>{const{projectId,productionId,...body}=input;return{method:"POST",path:projectProduction(projectId,productionId,"brief-versions"),tenantId:input.tenantId,body}}),"story.accept":operation(ScopedAcceptStorySchema,AcceptStoryResultSchema,input=>{const{projectId,productionId,...body}=input;return{method:"POST",path:projectProduction(projectId,productionId,"story-versions"),tenantId:input.tenantId,body}}),"scene-shot-plan.accept":operation(ScopedAcceptSceneShotPlanSchema,AcceptSceneShotPlanResultSchema,input=>{const{projectId,productionId,...body}=input;return{method:"POST",path:projectProduction(projectId,productionId,"scene-shot-plan-versions"),tenantId:input.tenantId,body}}),"story.query":operation(StoryQueryInputSchema.strict(),StoryQueryPageSchema,input=>({method:"GET",path:path("productions",input.productionId,"stories"),tenantId:input.tenantId,query:pageQuery(input)})),"story.active":operation(production2,StoryVersionSchema,input=>({method:"GET",path:path("productions",input.productionId,"stories","active"),tenantId:input.tenantId})),"scene-shot-plan.query":operation(SceneShotPlanQueryInputSchema.strict(),SceneShotPlanQueryPageSchema,input=>({method:"GET",path:path("productions",input.productionId,"scene-shot-plans"),tenantId:input.tenantId,query:pageQuery(input)})),"scene-shot-plan.active":operation(production2,SceneShotPlanVersionSchema,input=>({method:"GET",path:path("productions",input.productionId,"scene-shot-plans","active"),tenantId:input.tenantId})),"operation.query":operation(OperationQueryInputSchema.strict(),OperationQueryPageSchema,input=>({method:"GET",path:path("productions",input.productionId,"operations"),tenantId:input.tenantId,query:pageQuery(input)})),"operation.get":operation(production2.extend({operationId:OperationIdSchema}),OperationSummarySchema,input=>({method:"GET",path:path("productions",input.productionId,"operations",input.operationId),tenantId:input.tenantId}),[["operationId","id"]])};var reference2=["tenantId","projectId","deviceId","fileId","versionId","checksumSha256","byteSize","contentType"];var deviceLibraryOperations={"device-library.query":operation(LocalLibraryProjectionQuerySchema,LocalLibraryProjectionPageSchema,({tenantId,projectId,deviceId,after,limit,search,mediaCategory})=>({method:"GET",tenantId,path:path("local-execution","projects",projectId,"devices",deviceId,"library"),query:{after:after??void 0,limit,search,mediaCategory}}),[["tenantId","items.*.reference.tenantId"],["projectId","items.*.reference.projectId"],["deviceId","items.*.reference.deviceId"]],{readOnly:true}),"device-library.admit":operation(LocalLibraryCommandSchema,LocalLibraryAdmissionSchema,({tenantId,productionId,...body})=>({method:"POST",tenantId,path:path("productions",productionId,"device-library","commands"),body:{tenantId,productionId,...body}}),[["tenantId","tenantId"],["projectId","projectId"],["productionId","productionId"],["requestId","requestId"],["accessRevision","accessRevision"],...reference2.map(field=>[`reference.${field}`,`reference.${field}`])]),"device-library.receipt":operation(LocalLibraryCommandQuerySchema,LocalLibraryCommandStatusSchema.nullable(),({tenantId,projectId,productionId,requestId:requestId2})=>({method:"GET",tenantId,path:path("productions",productionId,"device-library","commands",requestId2),query:{projectId}}),[["tenantId","admission.tenantId"],["projectId","admission.projectId"],["productionId","admission.productionId"],["requestId","admission.requestId"],["tenantId","admission.reference.tenantId"],["projectId","admission.reference.projectId"]],{readOnly:true})};var navigationOperations={"studio.media.readiness":mcpOperation(RenderReadinessInputSchema,RenderReadinessSchema,true,[["tenantId","tenantId"],["projectId","projectId"],["productionId","productionId"],["kind","kind"],["deviceId","deviceId"]]),"studio.capability.query":mcpOperation(CapabilityInvocationInputSchema,CapabilityInvocationOutputSchema,true,[["tool","tool"]]),"studio.capability.invoke":mcpOperation(CapabilityInvocationInputSchema,CapabilityInvocationOutputSchema,false,[["tool","tool"]]),"studio.capability.groups":mcpOperation(CapabilityGroupsInputSchema,CapabilityGroupsSchema,true),"studio.start":mcpOperation(StudioStartInputSchema,StudioStartSchema,true),"studio.capability.search":mcpOperation(CapabilitySearchInputSchema,CapabilitySearchSchema,true),"studio.capability.describe":mcpOperation(CapabilityDescribeInputSchema,CapabilityDescribeSchema,true),"studio.navigate":mcpOperation(StudioNavigateInputSchema,StudioNavigationSchema,true,[["productionId","productionId"],["projectId","projectId"]])};import{createHash as createHash10}from"node:crypto";var verifiedHostContract=AgentHostContractSchema.refine(v=>v.digest==="sha256:"+createHash10("sha256").update(canonicalHostContractJson(v.document)).digest("hex"));function write(input,suffix){return operation(input,AgentHostBindingSchema,value2=>({method:"POST",tenantId:value2.tenantId,path:path("projects",value2.projectId,"agent-host",...suffix),body:Object.fromEntries(Object.entries(value2).filter(([key10])=>!["tenantId","projectId"].includes(key10)))}),[["bindingId","bindingId"]])}var agentHostOperations={"agent-host.contract":operation(AgentHostContractInputSchema,verifiedHostContract,value2=>({method:"GET",tenantId:value2.tenantId,path:path("projects",value2.projectId,"agent-host","contract"),query:{expectedDigest:value2.expectedDigest}}),[["expectedDigest","digest"]],{readOnly:true}),"agent-host.get":operation(AgentHostScopeSchema,AgentHostCurrentSchema,value2=>({method:"GET",tenantId:value2.tenantId,path:path("projects",value2.projectId,"agent-host")})),"agent-host.readiness":operation(AgentHostScopeSchema,AgentHostReadinessSchema,value2=>({method:"GET",tenantId:value2.tenantId,path:path("projects",value2.projectId,"agent-host","readiness")})),"agent-host.history":operation(AgentHostHistoryQuerySchema,AgentHostHistoryPageSchema,value2=>({method:"GET",tenantId:value2.tenantId,path:path("projects",value2.projectId,"agent-host","history"),query:{limit:value2.limit,beforeVersion:value2.beforeVersion}})),"agent-host.configure":write(ConfigureAgentHostSchema,[]),"agent-host.selection.update":write(UpdateAgentHostSelectionSchema,["selection"]),"agent-host.revoke":write(RevokeAgentHostSchema,["revoke"])};var route2=(scope8,...suffix)=>path("projects",scope8.projectId,"productions",scope8.productionId,"agent-host-executions",...suffix);var mutation2=action=>operation(AgentHostExecutionGetSchema,AgentHostExecutionViewSchema,value2=>({method:"POST",tenantId:value2.tenantId,path:route2(value2,value2.executionId,action),body:{}}),[["executionId","executionId"]]);var agentHostExecutionOperations={"agent-host-execution.legacy-release.get":operation(AgentHostExecutionGetSchema,LegacyHostExecutionReleaseSchema,value2=>({method:"GET",tenantId:value2.tenantId,path:route2(value2,value2.executionId,"legacy-release")}),[["executionId","executionId"]]),"agent-host-execution.legacy-release":operation(ReleaseLegacyHostExecutionSchema,LegacyHostExecutionReleaseSchema,value2=>({method:"POST",tenantId:value2.tenantId,path:route2(value2,value2.executionId,"legacy-release"),body:Object.fromEntries(Object.entries(value2).filter(([key10])=>!["tenantId","projectId","productionId","executionId"].includes(key10)))}),[["executionId","executionId"],["requestId","requestId"],["hostRequestId","hostRequestId"],["expectedRevision","expectedRevision"],["snapshotFingerprint","snapshotFingerprint"],["evidenceRef","evidenceRef"],["evidenceSha256","evidenceSha256"]]),"agent-host-execution.start":operation(StartAgentHostExecutionSchema,AgentHostExecutionViewSchema,value2=>({method:"POST",tenantId:value2.tenantId,path:route2(value2),body:Object.fromEntries(Object.entries(value2).filter(([key10])=>!["tenantId","projectId","productionId"].includes(key10)))}),[["requestId","requestId"],["bindingId","snapshot.binding.bindingId"],["studioInputArtifactId","snapshot.input.intake.artifactId"],["expectedProductionRevision","snapshot.input.productionRevision"],["expectedBindingRevision","snapshot.binding.revision"],["expectedConfigurationVersion","snapshot.binding.configurationVersion"]]),"agent-host-execution.get":operation(AgentHostExecutionGetSchema,AgentHostExecutionViewSchema,value2=>({method:"GET",tenantId:value2.tenantId,path:route2(value2,value2.executionId)}),[["executionId","executionId"]]),"agent-host-execution.query":operation(AgentHostExecutionQuerySchema,AgentHostExecutionPageSchema,value2=>({method:"GET",tenantId:value2.tenantId,path:route2(value2),query:{limit:value2.limit,beforeId:value2.beforeId}})),"agent-host-execution.events":operation(AgentHostExecutionEventQuerySchema,AgentHostExecutionEventPageSchema,value2=>({method:"GET",tenantId:value2.tenantId,path:route2(value2,value2.executionId,"events"),query:{limit:value2.limit,beforeRevision:value2.beforeRevision}}),[["executionId","items.*.executionId"]]),"agent-host-execution.dispatch":mutation2("dispatch"),"agent-host-execution.reconcile":mutation2("reconcile"),"agent-host-execution.cancel":mutation2("cancel")};var route3=(v,...suffix)=>path("projects",v.projectId,"native-tool-grants",...suffix);var nativeToolAuthorityOperations={"native-tool-grant.configure":operation(ConfigureNativeToolGrantSchema,NativeToolGrantViewSchema,v=>({method:"POST",tenantId:v.tenantId,path:route3(v),body:Object.fromEntries(Object.entries(v).filter(([k])=>!["tenantId","projectId"].includes(k)))}),[["bindingId","bindingId"],["expectedBindingRevision","bindingRevision"],["expectedConfigurationVersion","configurationVersion"],["runtimeKey","runtimeKey"],["installationId","installationId"],["installationRevisionId","installationRevisionId"],["publicKey.x","publicKey.x"],["publicKey.y","publicKey.y"]]),"native-tool-grant.get":operation(NativeToolGrantGetSchema,NativeToolGrantViewSchema,v=>({method:"GET",tenantId:v.tenantId,path:route3(v,v.grantId)}),[["grantId","grantId"]]),"native-tool-grant.revoke":operation(RevokeNativeToolGrantSchema,NativeToolGrantViewSchema,v=>({method:"POST",tenantId:v.tenantId,path:route3(v,v.grantId,"revoke"),body:{requestId:v.requestId,expectedRevision:v.expectedRevision}}),[["grantId","grantId"]])};function productionRead(input,output,suffix,query=()=>({}),identity6=[]){return operation(input,output,value2=>({method:"GET",tenantId:value2.tenantId,path:path("productions",value2.productionId,...suffix(value2)),query:query(value2)}),identity6)}function productionWrite(input,output,suffix,options={}){return operation(input,output,value2=>({method:"POST",tenantId:value2.tenantId,path:path("productions",value2.productionId,...suffix(value2)),body:Object.fromEntries(Object.entries(value2).filter(([key10])=>key10!=="productionId"&&(options.tenantInBody||key10!=="tenantId")&&!options.pathFields?.includes(key10)))}),options.identity,options.readOnly===void 0?{}:{readOnly:options.readOnly})}var compositionOperations={"composition.render.query":productionRead(CompositionRenderQuerySchema,CompositionRenderPageSchema,()=>["compositions","renders"],i=>({limit:i.limit,next:i.next,shotId:i.shotId,role:i.role}),[["shotId","items.*.render.sourceIdentity.shotId"],["role","items.*.render.sourceIdentity.role"]]),"composition.capabilities":productionRead(CompositionScopeSchema,CompositionCapabilitiesSchema,()=>["compositions","capabilities"]),"composition.brief":productionRead(CompositionBriefQuerySchema,CompositionAuthoringBriefSchema,()=>["compositions","brief"],i=>({...i.shotId?{shotId:i.shotId}:{}})),"composition.put-input":productionWrite(PutCompositionInputSchema,CompositionInputReceiptSchema,()=>["compositions","inputs"]),"composition.making.validate":productionWrite(ValidateCompositionMakingSchema,CompositionMakingValidationSchema,()=>["compositions","making","validate"],{readOnly:true,identity:[["projectId","projectId"],["expectedProductionRevision","authoring.productionRevision"],["basis.briefVersionId","authoring.basis.briefVersionId"],["basis.storyVersionId","authoring.basis.storyVersionId"],["basis.planVersionId","authoring.basis.planVersionId"],["basis.shotId","authoring.basis.shotId"],["proposal.makingIntent","proposal.makingIntent"]]}),"composition.validate":productionWrite(ValidateCompositionSchema,CompositionValidationReceiptSchema,()=>["compositions","validate"],{readOnly:true}),"composition.create":productionWrite(CreateCompositionSchema,CompositionReceiptSchema,()=>["compositions"]),"composition.revise":productionWrite(ReviseCompositionSchema,CompositionReceiptSchema,()=>["compositions","revise"],{identity:[["compositionId","version.compositionId"]]}),"composition.get":productionRead(CompositionGetSchema,CompositionViewSchema,i=>["compositions",i.compositionId],i=>({versionId:i.versionId}),[["compositionId","version.compositionId"],["versionId","version.id"]]),"composition.history":productionRead(CompositionHistorySchema,CompositionPageSchema,i=>["compositions",i.compositionId,"versions"],i=>({limit:i.limit,beforeVersion:i.beforeVersion}),[["compositionId","items.*.version.compositionId"]]),"composition.render":productionWrite(CompositionRenderStartSchema,CompositionRenderReceiptSchema,()=>["compositions","renders"],{identity:[["versionId","compositionVersionId"]]}),"composition.render.get":productionRead(CompositionRenderGetSchema,CompositionRenderViewSchema,i=>["compositions","renders",i.renderId],void 0,[["renderId","receipt.renderId"]]),"composition.render.cancel":productionWrite(CompositionRenderGetSchema,CompositionRenderCancellationSchema,i=>["compositions","renders",i.renderId,"cancel"],{pathFields:["renderId"]}),"composition.sample":productionWrite(CompositionSampleStartSchema,CompositionSampleReceiptSchema,()=>["compositions","samples"],{identity:[["renderId","renderId"]]}),"composition.observe":productionRead(CompositionObserveGetSchema,CompositionObservationViewSchema,i=>["compositions","renders",i.renderId,"observations",i.evidenceId],void 0,[["renderId","renderId"],["evidenceId","evidence.evidenceId"]])};var cancellation=InterfaceCancellationReceiptSchema;var assemblyOperations={"timeline.basis":productionRead(TimelineScopeSchema,TimelineBasisSchema,()=>["timeline","basis"]),"timeline.build":productionWrite(BuildTimelineSchema,TimelineBuildReceiptSchema,()=>["timeline"]),"timeline.current":productionRead(TimelineScopeSchema,TimelineViewSchema,()=>["timeline","current"]),"timeline.get":productionRead(TimelineGetSchema,TimelineViewSchema,i=>["timeline","versions",i.versionId],void 0,[["versionId","version.id"]]),"timeline.query":productionRead(TimelineQuerySchema,TimelinePageSchema,()=>["timeline","versions"],pageQuery),"rough-cut.admission-receipt":productionWrite(RoughCutStartSchema,RoughCutAdmissionSchema,()=>["rough-cuts","admission-receipt"],{tenantInBody:true,readOnly:true,identity:[["timelineVersionId","timelineVersionId"],["timelineFingerprint","timelineFingerprint"]]}),"rough-cut.start":productionWrite(RoughCutStartSchema,RoughCutAdmissionSchema,()=>["rough-cuts"],{tenantInBody:true,identity:[["timelineVersionId","timelineVersionId"],["timelineFingerprint","timelineFingerprint"]]}),"rough-cut.get":productionRead(RoughCutGetSchema,RoughCutViewSchema,i=>["rough-cuts",i.renderId],void 0,[["renderId","renderId"]]),"rough-cut.query":productionRead(RoughCutQuerySchema,RoughCutPageSchema,()=>["rough-cuts"],pageQuery),"rough-cut.cancel":productionWrite(RoughCutGetSchema,cancellation,i=>["rough-cuts",i.renderId,"cancel"],{pathFields:["renderId"]}),"rough-cut.review.target":productionRead(RoughCutReviewScopeSchema,RoughCutReviewTargetSchema,i=>["rough-cut-review",i.renderId],void 0,[["renderId","renderId"]]),"rough-cut.review.record":productionWrite(RecordRoughCutReviewSchema,RoughCutReviewReceiptSchema,i=>["rough-cut-review",i.renderId],{pathFields:["renderId"],identity:[["renderId","review.renderId"]]}),"rough-cut.review.query":productionRead(RoughCutReviewQuerySchema,RoughCutReviewPageSchema,i=>["rough-cut-review",i.renderId,"history"],pageQuery,[["renderId","items.*.renderId"]]),"rough-cut.finding.query":productionRead(RoughCutFindingQuerySchema,RoughCutFindingPageSchema,()=>["rough-cut-review","findings"],i=>({...pageQuery(i),renderId:i.renderId}),[["renderId","items.*.renderId"]]),"final-ready.get":productionRead(TimelineScopeSchema,FinalReadyViewSchema,()=>["final-ready"]),"final-ready.decide":productionWrite(DecideFinalReadySchema,FinalReadyReceiptSchema,()=>["final-ready","decisions"],{identity:[["renderId","decision.renderId"],["reviewId","decision.reviewId"]]}),"final-ready.revoke":productionWrite(RevokeFinalReadySchema,FinalReadyReceiptSchema,()=>["final-ready","revoke"]),"final-ready.query":productionRead(FinalReadyQuerySchema,FinalReadyPageSchema,()=>["final-ready","decisions"],pageQuery),"final-render.eligibility":productionRead(TimelineScopeSchema,FinalRenderEligibilitySchema,()=>["final-renders","eligibility"]),"final-render.admission-receipt":productionWrite(FinalRenderStartSchema,FinalRenderAdmissionSchema,()=>["final-renders","admission-receipt"],{tenantInBody:true,readOnly:true,identity:[["timelineVersionId","timelineVersionId"],["timelineFingerprint","timelineFingerprint"]]}),"final-render.start":productionWrite(FinalRenderStartSchema,FinalRenderAdmissionSchema,()=>["final-renders"],{tenantInBody:true,identity:[["selectionId","selectionId"],["timelineVersionId","timelineVersionId"],["timelineFingerprint","timelineFingerprint"]]}),"final-render.get":productionRead(FinalRenderGetSchema,FinalRenderViewSchema,i=>["final-renders",i.renderId],void 0,[["renderId","renderId"]]),"final-render.query":productionRead(FinalRenderQuerySchema,FinalRenderPageSchema,()=>["final-renders"],pageQuery),"final-render.cancel":productionWrite(FinalRenderGetSchema,cancellation,i=>["final-renders",i.renderId,"cancel"],{pathFields:["renderId"]})};var Context=EditorContextInputSchema.extend({tenantId:TenantIdSchema}).refine(i=>i.tenantId.toLowerCase()===i.scope.tenantId.toLowerCase());var Validate=ValidateEditorProposalSchema.safeExtend({tenantId:TenantIdSchema}).refine(i=>i.tenantId.toLowerCase()===i.basis.scope.tenantId.toLowerCase());var editorOperations={"editor.context":operation(Context,EditorContextResultSchema,i=>({method:"POST",tenantId:i.scope.tenantId,path:path("projects",i.scope.projectId,"productions",i.scope.productionId,"editor-intelligence","context"),body:{scope:i.scope,timelineVersionId:i.timelineVersionId}}),[["scope.tenantId","basis.scope.tenantId"],["scope.projectId","basis.scope.projectId"],["scope.productionId","basis.scope.productionId"],["timelineVersionId","timeline.version.id"]],{readOnly:true}),"editor.validate":operation(Validate,EditorValidationResultSchema,i=>({method:"POST",tenantId:i.basis.scope.tenantId,path:path("projects",i.basis.scope.projectId,"productions",i.basis.scope.productionId,"editor-intelligence","proposals","validate"),body:{basis:i.basis,proposal:i.proposal}}),[["basis.scope.tenantId","basis.scope.tenantId"],["basis.scope.projectId","basis.scope.projectId"],["basis.scope.productionId","basis.scope.productionId"],["basis.timelineVersionId","basis.timelineVersionId"],["basis.contextFingerprint","basis.contextFingerprint"]],{readOnly:true})};var Context2=ReviewIntelligenceContextInputSchema.extend({tenantId:TenantIdSchema}).refine(i=>i.tenantId.toLowerCase()===i.scope.tenantId.toLowerCase());var Validate2=ValidateReviewIntelligenceSchema.safeExtend({tenantId:TenantIdSchema}).refine(i=>i.tenantId.toLowerCase()===i.basis.scope.tenantId.toLowerCase());var FinalContext=FinalOutputReviewContextInputSchema.extend({tenantId:TenantIdSchema}).refine(i=>i.tenantId.toLowerCase()===i.scope.tenantId.toLowerCase());var reviewerOperations={"reviewer.final-output-context":operation(FinalContext,FinalOutputReviewContextResultSchema,i=>({method:"POST",tenantId:i.tenantId,path:path("projects",i.scope.projectId,"productions",i.scope.productionId,"review-intelligence","final-output","context"),body:{scope:i.scope,renderId:i.renderId}}),[["scope","basis.scope"],["renderId","basis.renderId"],["renderId","deliveryTarget.renderId"]],{readOnly:true}),"reviewer.context":operation(Context2,ReviewIntelligenceContextResultSchema,i=>({method:"POST",tenantId:i.scope.tenantId,path:path("projects",i.scope.projectId,"productions",i.scope.productionId,"review-intelligence","context"),body:{scope:i.scope,target:i.target}}),[["scope.tenantId","basis.scope.tenantId"],["scope.projectId","basis.scope.projectId"],["scope.productionId","basis.scope.productionId"],["target.kind","basis.target.kind"],["target.renderId","basis.target.renderId"],["target.generationId","basis.target.generationId"],["scope.tenantId","reviewTarget.target.tenantId"],["scope.projectId","reviewTarget.target.projectId"],["scope.productionId","reviewTarget.target.productionId"],["target.kind","reviewTarget.kind"],["target.renderId","reviewTarget.target.renderId"],["target.generationId","reviewTarget.target.generationId"]],{readOnly:true}),"reviewer.validate":operation(Validate2,ReviewIntelligenceValidationResultSchema,i=>({method:"POST",tenantId:i.basis.scope.tenantId,path:path("projects",i.basis.scope.projectId,"productions",i.basis.scope.productionId,"review-intelligence","proposals","validate"),body:{basis:i.basis,proposal:i.proposal}}),[["basis.scope.tenantId","basis.scope.tenantId"],["basis.scope.projectId","basis.scope.projectId"],["basis.scope.productionId","basis.scope.productionId"],["basis.target.kind","basis.target.kind"],["basis.target.renderId","basis.target.renderId"],["basis.target.generationId","basis.target.generationId"],["basis.contextFingerprint","basis.contextFingerprint"],["basis.scope.tenantId","recordDraft.input.tenantId"],["basis.scope.productionId","recordDraft.input.productionId"],["basis.target.kind","recordDraft.kind"],["basis.target.renderId","recordDraft.input.renderId"],["basis.target.generationId","recordDraft.input.generationId"]],{readOnly:true})};var Context3=RepairStrategyContextInputSchema.extend({tenantId:TenantIdSchema}).refine(i=>i.tenantId.toLowerCase()===i.scope.tenantId.toLowerCase());var Validate3=ValidateRepairStrategySchema.safeExtend({tenantId:TenantIdSchema}).refine(i=>i.tenantId.toLowerCase()===i.basis.scope.tenantId.toLowerCase());var Review1Validate=ValidateReview1RepairStrategySchema.safeExtend({tenantId:TenantIdSchema}).refine(i=>i.tenantId.toLowerCase()===i.basis.input.tenantId.toLowerCase());var repairStrategyOperations={"repair-strategy.review1.context":operation(Review1RepairSourceQuerySchema,Review1RepairStrategyContextSchema,i=>({method:"POST",tenantId:i.tenantId,path:path("projects",i.projectId,"productions",i.productionId,"repair-strategy","review1","context"),body:i}),[["tenantId","basis.input.tenantId"],["projectId","basis.input.projectId"],["productionId","basis.input.productionId"],["generationId","basis.input.generationId"],["reviewId","basis.input.reviewId"],["requirementKey","basis.input.requirementKey"]],{readOnly:true}),"repair-strategy.review1.validate":operation(Review1Validate,Review1RepairStrategyValidationSchema,i=>({method:"POST",tenantId:i.tenantId,path:path("projects",i.basis.input.projectId,"productions",i.basis.input.productionId,"repair-strategy","review1","proposals","validate"),body:{basis:i.basis,proposal:i.proposal,...i.budget?{budget:i.budget}:{}}}),[["basis","basis"],["proposal.selectedAlternativeId","selectedAlternativeId"]],{readOnly:true}),"repair-strategy.context":operation(Context3,RepairStrategyContextResultSchema,i=>({method:"POST",tenantId:i.scope.tenantId,path:path("projects",i.scope.projectId,"productions",i.scope.productionId,"repair-strategy","context"),body:{scope:i.scope,findingId:i.findingId}}),[["scope.tenantId","basis.scope.tenantId"],["scope.projectId","basis.scope.projectId"],["scope.productionId","basis.scope.productionId"],["findingId","finding.id"]],{readOnly:true}),"repair-strategy.validate":operation(Validate3,RepairStrategyValidationResultSchema,i=>({method:"POST",tenantId:i.basis.scope.tenantId,path:path("projects",i.basis.scope.projectId,"productions",i.basis.scope.productionId,"repair-strategy","proposals","validate"),body:{basis:i.basis,proposal:i.proposal}}),[["basis.scope.tenantId","basis.scope.tenantId"],["basis.scope.projectId","basis.scope.projectId"],["basis.scope.productionId","basis.scope.productionId"],["basis.findingId","finding.id"],["basis.contextFingerprint","basis.contextFingerprint"],["proposal.selectedAlternativeId","selectedAlternativeId"]],{readOnly:true})};var ownedRequest=(action,i)=>{const{projectId,...body}=i;return{method:"POST",tenantId:i.tenantId,path:path("projects",projectId,"productions",i.productionId,"repairs",action),body}};var Author=AuthorRepairPlanSchema.safeExtend({tenantId:TenantIdSchema}).refine(i=>i.tenantId.toLowerCase()===i.strategy.basis.scope.tenantId.toLowerCase());var canonicalRepairOperations={"canonical-repair.author-review1":operation(AuthorReview1RepairSchema,RepairAuthorReceiptSchema,i=>({method:"POST",tenantId:i.tenantId,path:path("projects",i.projectId,"productions",i.productionId,"repairs","author-review1"),body:i}),[["reviewId","decision.sourceReviewId"],["generationId","decision.review1Source.generationId"],["mediaType","decision.review1Source.mediaType"],["requirementKey","decision.review1Source.requirement.key"]]),"canonical-repair.proof-review1":operation(RecordReview1RepairProofSchema.extend({projectId:ProjectIdSchema}),RepairProofReceiptSchema,i=>ownedRequest("proof-review1",i),[["attemptId","event.attemptId"],["generationId","event.generationId"],["reviewId","event.reviewId"]]),"canonical-repair.author":operation(Author,RepairAuthorReceiptSchema,i=>{const{tenantId,...body}=i;const s=i.strategy.basis.scope;return{method:"POST",tenantId,path:path("projects",s.projectId,"productions",s.productionId,"repairs","author"),body}},[["strategy.basis.scope.tenantId","decision.tenantId"],["strategy.basis.scope.projectId","decision.projectId"],["strategy.basis.scope.productionId","decision.productionId"],["strategy.basis.findingId","decision.basis.findingId"],["strategy.basis.contextFingerprint","decision.basis.contextFingerprint"],["strategy.proposal.selectedAlternativeId","decision.selectedAlternativeId"]]),"canonical-repair.get":operation(RepairPlanScopeSchema.extend({projectId:ProjectIdSchema}),RepairPlanViewSchema,i=>ownedRequest("get",i),[["planId","decision.id"]],{readOnly:true}),"canonical-repair.execute":operation(ExecuteRepairSchema.extend({projectId:ProjectIdSchema}),RepairProgressSchema,i=>ownedRequest("execute",i),[["planId","view.decision.id"]]),"canonical-repair.proof":operation(RecordRepairProofSchema.extend({projectId:ProjectIdSchema}),RepairProofReceiptSchema,i=>ownedRequest("proof",i),[["attemptId","event.attemptId"],["renderId","event.renderId"],["reviewId","event.reviewId"]])};var programmaticReviewOperations={"programmatic-review.target":productionRead(ProgrammaticVideoReviewScopeSchema,ProgrammaticVideoReviewTargetSchema,i=>["video-review","programmatic",i.renderId],void 0,[["renderId","renderId"]]),"programmatic-review.record":productionWrite(RecordProgrammaticVideoReviewSchema,ProgrammaticVideoReviewReceiptSchema,i=>["video-review","programmatic",i.renderId],{pathFields:["renderId"],identity:[["renderId","review.renderId"],["representationId","review.representationId"],["checksumSha256","review.checksumSha256"]]}),"programmatic-review.query":productionRead(ProgrammaticVideoReviewQuerySchema,ProgrammaticVideoReviewPageSchema,i=>["video-review","programmatic",i.renderId,"history"],pageQuery,[["renderId","items.*.renderId"]]),"programmatic-review.decide":productionWrite(DecideProgrammaticShotSchema,ShotDecisionReceiptSchema.extend({decision:ProgrammaticShotAcceptanceDecisionSchema}),i=>["video-review","programmatic",i.renderId,"decisions"],{pathFields:["renderId"],identity:[["renderId","decision.renderId"],["reviewId","decision.reviewId"],["action","decision.action"]]})};var Context4=SourceReviewContextInputSchema.safeExtend({tenantId:TenantIdSchema}).refine(i=>i.tenantId.toLowerCase()===i.scope.tenantId.toLowerCase());var compositionSourceOperations={"composition.source.inspect":productionWrite(CompositionSourceInspectSchema,CompositionSourceInspectionSchema,()=>["compositions","source","inspect"],{readOnly:true,identity:[["compositionId","composition.version.compositionId"],["versionId","composition.version.id"],["fingerprint","composition.version.fingerprint"],["file","window.file"],["startLine","selection.startLine"]]}),"reviewer.source-context":operation(Context4,SourceReviewContextSchema,i=>({method:"POST",tenantId:i.scope.tenantId,path:path("projects",i.scope.projectId,"productions",i.scope.productionId,"review-intelligence","source","context"),body:{scope:i.scope,source:i.source,...i.renderId?{renderId:i.renderId}:{}}}),[["scope.tenantId","basis.input.scope.tenantId"],["scope.projectId","source.composition.version.projectId"],["scope.productionId","source.composition.version.productionId"],["source.compositionId","source.composition.version.compositionId"],["source.versionId","source.composition.version.id"],["source.fingerprint","source.composition.version.fingerprint"],["source.file","source.window.file"],["source.startLine","source.selection.startLine"],["renderId","render.receipt.renderId"]],{readOnly:true})};var Compare=ProgrammaticCompareSchema.safeExtend({tenantId:TenantIdSchema}).refine(i=>i.tenantId.toLowerCase()===i.scope.tenantId.toLowerCase());var Context5=ProgrammaticRecommendationContextInputSchema.safeExtend({tenantId:TenantIdSchema}).refine(i=>i.tenantId.toLowerCase()===i.scope.tenantId.toLowerCase());var Validate4=ValidateProgrammaticRecommendationSchema.safeExtend({tenantId:TenantIdSchema}).refine(i=>i.tenantId.toLowerCase()===i.basis.input.scope.tenantId.toLowerCase());var programmaticExplorationOperations={"exploration.programmatic.compare":operation(Compare,ProgrammaticComparisonSchema,i=>({method:"POST",tenantId:i.scope.tenantId,path:path("projects",i.scope.projectId,"productions",i.scope.productionId,"visual-exploration","programmatic","compare"),body:{scope:i.scope,items:i.items}}),[["scope.tenantId","scope.tenantId"],["scope.projectId","scope.projectId"],["scope.productionId","scope.productionId"],["scope.shotId","scope.shotId"],["items","selection"]],{readOnly:true}),"exploration.programmatic.recommendation.context":operation(Context5,ProgrammaticRecommendationContextSchema,i=>({method:"POST",tenantId:i.scope.tenantId,path:path("projects",i.scope.projectId,"productions",i.scope.productionId,"exploration-recommendation","programmatic","context"),body:{scope:i.scope,items:i.items,criteria:i.criteria}}),[["scope.tenantId","basis.input.scope.tenantId"],["scope.projectId","basis.input.scope.projectId"],["scope.productionId","basis.input.scope.productionId"],["scope.shotId","basis.input.scope.shotId"],["items","basis.input.items"]],{readOnly:true}),"exploration.programmatic.recommendation.validate":operation(Validate4,ProgrammaticRecommendationValidationSchema,i=>({method:"POST",tenantId:i.basis.input.scope.tenantId,path:path("projects",i.basis.input.scope.projectId,"productions",i.basis.input.scope.productionId,"exploration-recommendation","programmatic","proposals","validate"),body:{basis:i.basis,proposal:i.proposal}}),[["basis.contextFingerprint","basis.contextFingerprint"],["basis.input.scope.tenantId","basis.input.scope.tenantId"],["basis.input.scope.projectId","basis.input.scope.projectId"],["basis.input.scope.productionId","basis.input.scope.productionId"],["basis.input.items","basis.input.items"],["proposal.decision.kind","decision.kind"],["proposal.decision.label","decision.label"]],{readOnly:true})};var targetIdentity=prefix=>Object.keys(DeliveryTargetSchema.shape).map(key10=>["target."+key10,prefix+"."+key10]);var deliveryOperations={"delivery.policy.configure":productionWrite(ConfigureDeliveryPolicySchema,DeliveryPolicyReceiptSchema,()=>["deliveries","policy"],{tenantInBody:true}),"delivery.policy.get":productionRead(TimelineScopeSchema,DeliveryPolicyVersionSchema,()=>["deliveries","policy"]),"delivery.snapshot":productionRead(TimelineScopeSchema,DeliverySnapshotSchema,()=>["deliveries","snapshot"]),"delivery.target":productionRead(RoughCutGetSchema,DeliveryTargetSchema,i=>["deliveries","targets",i.renderId],void 0,[["renderId","renderId"]]),"delivery.start":productionWrite(StartDeliveryValidationSchema,DeliveryAdmissionSchema,()=>["deliveries"],{tenantInBody:true,identity:targetIdentity("target")}),"delivery.get":productionRead(DeliveryValidationGetSchema,DeliveryValidationViewSchema,i=>["deliveries",i.validationId],void 0,[["validationId","admission.validationId"]]),"delivery.approve":productionWrite(DecideDeliveryApprovalSchema,DeliveryDecisionReceiptSchema,i=>["deliveries",i.validationId,"approval"],{tenantInBody:true,pathFields:["validationId"],identity:[...targetIdentity("approval.target"),["reviewId","approval.reviewId"],["policyFingerprint","approval.policyFingerprint"],["action","approval.action"]]}),"delivery.cancel":productionWrite(DeliveryValidationGetSchema,cancellation,i=>["deliveries",i.validationId,"cancel"],{pathFields:["validationId"]}),"delivery.manifest":productionRead(DeliveryManifestGetSchema,RegisteredDeliveryManifestSchema,i=>["deliveries","manifests",i.manifestId],void 0,[["manifestId","link.id"]])};var prepare=PrepareShotRequestSchema.extend({projectId:ProjectIdSchema,productionId:ProductionIdSchema,shotId:ShotIdSchema});var shotPreparationOperations={"shot-preparation.prepare":operation(prepare,PrepareShotResultSchema,i=>({method:"POST",tenantId:i.tenantId,path:path("projects",i.projectId,"productions",i.productionId,"shots",i.shotId,"preparations"),body:Object.fromEntries(Object.entries(i).filter(([k])=>!["projectId","productionId","shotId"].includes(k)))}),[["projectId","preparation.basis.projectId"],["shotId","preparation.basis.shotId"],["expectedPlanVersionId","preparation.basis.planVersionId"],["expectedPlanVersion","preparation.basis.planVersion"],["expectedShotPlanningRevision","preparation.basis.shotPlanningRevision"],["target","preparation.target"]]),"shot-preparation.get":productionRead(PreparationGetInputSchema,PreparationViewSchema,i=>["shot-preparations",i.preparationId],void 0,[["preparationId","preparation.id"]]),"shot-preparation.active":productionRead(PreparationActiveInputSchema,PreparationViewSchema,i=>["shots",i.shotId,"preparations","active"],i=>({mediaType:i.mediaType}),[["shotId","preparation.basis.shotId"],["mediaType","preparation.target.mediaType"]]),"shot-preparation.query":productionRead(PreparationQueryInputSchema,PreparationQueryPageSchema,()=>["shot-preparations"],i=>({...pageQuery(i),shotId:i.shotId,mediaType:i.mediaType}),[["shotId","items.*.preparation.basis.shotId"],["mediaType","items.*.preparation.target.mediaType"]])};var generationOperations={"keyframe.device.quote":productionWrite(KeyframeStartInputSchema,GenerationCostQuoteSchema.nullable(),()=>["keyframe-generations","device","quote"],{tenantInBody:true,readOnly:true}),"keyframe.device.start":productionWrite(KeyframeDeviceStartInputSchema,KeyframeAdmissionSchema,()=>["keyframe-generations","device"],{tenantInBody:true,identity:[["contractId","contractId"]]}),"keyframe.start":productionWrite(KeyframeStartInputSchema,KeyframeAdmissionSchema,()=>["keyframe-generations"],{tenantInBody:true,identity:[["contractId","contractId"]]}),"keyframe.get":productionRead(KeyframeGetInputSchema,KeyframeGenerationViewSchema,i=>["keyframe-generations",i.generationId],void 0,[["generationId","generationId"]]),"keyframe.query":productionRead(KeyframeQueryInputSchema,KeyframeQueryPageSchema,()=>["keyframe-generations"],i=>({...pageQuery(i),shotId:i.shotId}),[["shotId","items.*.shotId"]]),"keyframe.cancel":productionWrite(KeyframeGetInputSchema,InterfaceCancellationReceiptSchema,i=>["keyframe-generations",i.generationId,"cancel"],{pathFields:["generationId"]}),"video.start":productionWrite(VideoStartInputSchema,VideoAdmissionSchema,()=>["video-generations"],{tenantInBody:true,identity:[["contractId","contractId"]]}),"video.device.quote":productionWrite(VideoStartInputSchema,GenerationCostQuoteSchema.nullable(),()=>["video-generations","device","quote"],{tenantInBody:true,readOnly:true}),"video.device.start":productionWrite(VideoDeviceStartInputSchema,VideoAdmissionSchema,()=>["video-generations","device"],{tenantInBody:true,identity:[["contractId","contractId"]]}),"video.get":productionRead(VideoGetInputSchema,VideoGenerationViewSchema,i=>["video-generations",i.generationId],void 0,[["generationId","generationId"]]),"video.query":productionRead(VideoQueryInputSchema,VideoQueryPageSchema,()=>["video-generations"],i=>({...pageQuery(i),shotId:i.shotId}),[["shotId","items.*.shotId"]]),"video.cancel":productionWrite(VideoGetInputSchema,InterfaceCancellationReceiptSchema,i=>["video-generations",i.generationId,"cancel"],{pathFields:["generationId"]})};var keyframeReviewOperations={"keyframe-review.target":productionRead(KeyframeReviewScopeSchema,KeyframeReviewTargetSchema,i=>["keyframe-review",i.generationId],void 0,[["generationId","generationId"]]),"keyframe-review.record":productionWrite(RecordKeyframeReviewSchema,KeyframeReviewReceiptSchema,i=>["keyframe-review",i.generationId],{pathFields:["generationId"],identity:[["generationId","review.generationId"],["candidateId","review.candidateId"],["representationId","review.representationId"],["checksumSha256","review.checksumSha256"]]}),"keyframe-review.query":productionRead(KeyframeReviewQuerySchema,KeyframeReviewPageSchema,i=>["keyframe-review",i.generationId,"history"],pageQuery,[["generationId","items.*.generationId"]]),"keyframe-review.decide":productionWrite(DecideKeyframeSchema,KeyframeDecisionReceiptSchema,i=>["keyframe-review",i.generationId,"decisions"],{pathFields:["generationId"],identity:[["generationId","decision.generationId"],["candidateId","decision.candidateId"],["reviewId","decision.reviewId"],["action","decision.action"]]}),"keyframe-reference.get":productionRead(KeyframeReferenceScopeSchema,KeyframeReferenceViewSchema,i=>["keyframe-review","references",i.shotId,i.framePurpose],void 0,[["shotId","shotId"],["framePurpose","framePurpose"]]),"keyframe-reference.query":productionRead(KeyframeDecisionQuerySchema,KeyframeDecisionPageSchema,i=>["keyframe-review","references",i.shotId,i.framePurpose,"history"],pageQuery,[["shotId","items.*.shotId"],["framePurpose","items.*.framePurpose"]]),"keyframe-reference.revoke":productionWrite(RevokeKeyframeSchema,KeyframeDecisionReceiptSchema,i=>["keyframe-review","references",i.shotId,i.framePurpose,"revoke"],{pathFields:["shotId","framePurpose"],identity:[["shotId","decision.shotId"],["framePurpose","decision.framePurpose"],["acceptanceId","decision.previousAcceptanceId"]]})};var videoReviewOperations={"video-review.target":productionRead(VideoReviewScopeSchema,VideoReviewTargetSchema,i=>["video-review",i.generationId],void 0,[["generationId","generationId"]]),"video-review.record":productionWrite(RecordVideoReviewSchema,VideoReviewReceiptSchema,i=>["video-review",i.generationId],{pathFields:["generationId"],identity:[["generationId","review.generationId"],["candidateId","review.candidateId"],["representationId","review.representationId"],["checksumSha256","review.checksumSha256"]]}),"video-review.query":productionRead(VideoReviewQuerySchema,VideoReviewPageSchema,i=>["video-review",i.generationId,"history"],pageQuery,[["generationId","items.*.generationId"]]),"video-review.decide":productionWrite(DecideVideoShotSchema,ShotDecisionReceiptSchema.extend({decision:GeneratedShotAcceptanceDecisionSchema}),i=>["video-review",i.generationId,"decisions"],{pathFields:["generationId"],identity:[["generationId","decision.generationId"],["candidateId","decision.candidateId"],["reviewId","decision.reviewId"],["action","decision.action"]]}),"shot-acceptance.get":productionRead(ShotAcceptanceScopeSchema,ShotAcceptanceViewSchema,i=>["video-review","shots",i.shotId,"acceptance"],void 0,[["shotId","shotId"]]),"shot-acceptance.query":productionRead(ShotDecisionQuerySchema,ShotDecisionPageSchema,i=>["video-review","shots",i.shotId,"decisions"],pageQuery,[["shotId","items.*.shotId"]]),"shot-acceptance.revoke":productionWrite(RevokeShotAcceptanceSchema,ShotDecisionReceiptSchema,i=>["video-review","shots",i.shotId,"revoke"],{pathFields:["shotId"],identity:[["shotId","decision.shotId"],["acceptanceId","decision.previousAcceptanceId"]]})};import{z as z192}from"zod";var providerOperations={"provider.model.get":operation(ProviderModelGetSchema,ProviderModelViewSchema,i=>({method:"GET",tenantId:i.tenantId,path:path("provider-models",i.id),query:{version:i.version}}),[["id","id"],["version","version"]]),"provider.model.query":operation(ProviderTenantInputSchema,ProviderModelPageSchema,i=>({method:"GET",tenantId:i.tenantId,path:path("provider-models")})),"provider.model.configure":operation(ConfigureProviderModelSchema,ProviderModelViewSchema,i=>({method:"POST",tenantId:i.tenantId,path:path("provider-models","configure"),body:i}),[["definition.profile.id","id"],["definition.profile.version","version"]]),"provider.model.disable":operation(DisableProviderModelSchema,z192.strictObject({disabled:z192.literal(true)}),i=>({method:"POST",tenantId:i.tenantId,path:path("provider-models","disable"),body:i})),"provider.configure":operation(ConfigureProviderInputSchema,ProviderConnectionViewSchema,i=>({method:"POST",tenantId:i.tenantId,path:path("provider-connections","configure"),body:i}),[["connectionId","connectionId"],["configuration","configuration"]]),"provider.query":operation(ProviderTenantInputSchema,ProviderConnectionPageSchema,i=>({method:"GET",tenantId:i.tenantId,path:path("provider-connections")})),"provider.models":operation(ProviderTenantInputSchema,ProviderModelsViewSchema,i=>({method:"GET",tenantId:i.tenantId,path:path("provider-connections","models")})),"provider.keyframe-default.set":operation(SetKeyframeDefaultSchema,ProviderDefaultViewSchema,i=>({method:"POST",tenantId:i.tenantId,path:path("provider-connections","keyframe-default"),body:i}),[["selection","selection"]]),"provider.disable":operation(ProviderConnectionCommandSchema,z192.strictObject({disabled:z192.literal(true)}),i=>({method:"POST",tenantId:i.tenantId,path:path("provider-connections","disable"),body:i})),"provider.revoke":operation(ProviderCredentialRevokeSchema,z192.strictObject({revoked:z192.literal(true)}),i=>({method:"POST",tenantId:i.tenantId,path:path("provider-connections","revoke"),body:i}))};import{z as z193}from"zod";var observationOperations={"media-observation.device.quote":productionWrite(QwenAsrDeviceQuoteInputSchema,QwenAsrCostQuoteSchema,()=>["media-observations","device","quote"],{readOnly:true}),"media-observation.device.start":productionWrite(QwenAsrDeviceStartSchema,QwenAsrDeviceAdmissionSchema,()=>["media-observations","device"]),"media-observation.device.get":productionRead(ObservationGetSchema,QwenAsrDeviceViewSchema,q=>["media-observations","device",q.observationId],void 0,[["observationId","observationId"]]),"media-observation.start-local":productionWrite(LocalObservationStartSchema,LocalObservationAdmissionSchema,()=>["media-observations","local"]),"media-observation.get-local":productionRead(ObservationGetSchema,LocalObservationViewSchema,q=>["media-observations","local",q.observationId],void 0,[["observationId","observationId"]]),"production-guidance.context":productionRead(ObservationScopeSchema,ProductionGuidanceContextSchema,()=>["media-observations","context"]),"media-observation.options":productionRead(ObservationScopeSchema,ObservationOptionsSchema,()=>["media-observations","options"]),"media-observation.start":productionWrite(ObservationStartSchema,ObservationAdmissionSchema,()=>["media-observations"]),"media-observation.get":productionRead(ObservationGetSchema,ObservationViewSchema,q=>["media-observations",q.observationId],void 0,[["observationId","observationId"]]),"media-observation.cancel":productionWrite(ObservationGetSchema,z193.strictObject({cancellationRequested:z193.boolean()}),q=>["media-observations",q.observationId,"cancel"],{pathFields:["observationId"]})};import{z as z194}from"zod";var speechOperations={"speech.device.quote":productionWrite(SpeechStartSchema,SpeechCostQuoteSchema.nullable(),()=>["speech-generations","device","quote"],{readOnly:true}),"speech.device.start":productionWrite(SpeechDeviceStartSchema,SpeechAdmissionSchema,()=>["speech-generations","device"]),"speech.start-local":productionWrite(LocalSpeechStartSchema,LocalSpeechAdmissionSchema,()=>["speech-generations","local"]),"speech.get-local":productionRead(SpeechGetSchema,LocalSpeechGenerationViewSchema,q=>["speech-generations","local",q.generationId],void 0,[["generationId","generationId"]]),"speech.options":productionRead(SpeechScopeSchema,SpeechOptionsSchema,()=>["speech-generations","options"]),"speech.start":productionWrite(SpeechStartSchema,SpeechAdmissionSchema,()=>["speech-generations"]),"speech.get":productionRead(SpeechGetSchema,SpeechGenerationViewSchema,q=>["speech-generations",q.generationId],void 0,[["generationId","generationId"]]),"speech.cancel":productionWrite(SpeechGetSchema,z194.strictObject({cancellationRequested:z194.boolean()}),q=>["speech-generations",q.generationId,"cancel"],{pathFields:["generationId"]})};var voiceProfileOperations={"voice-profile.set-reference":operation(VoiceProfileSetReferenceSchema,VoiceProfileReceiptSchema,({voiceProfileId,...body})=>({method:"POST",tenantId:body.tenantId,path:path("voice-profiles",voiceProfileId,"reference"),body}),[["voiceProfileId","voiceProfileId"]]),"voice-profile.reference":operation(VoiceReferenceGetSchema,VoiceReferenceSchema,i=>({method:"GET",tenantId:i.tenantId,path:path("voice-profiles",i.voiceProfileId,"references",i.referenceId)}),[["voiceProfileId","voiceProfileId"],["referenceId","id"]],{readOnly:true}),"voice-profile.create":operation(VoiceProfileCreateSchema,VoiceProfileReceiptSchema,i=>({method:"POST",tenantId:i.tenantId,path:path("voice-profiles"),body:i})),"voice-profile.revise":operation(VoiceProfileReviseSchema,VoiceProfileReceiptSchema,({voiceProfileId,...body})=>({method:"POST",tenantId:body.tenantId,path:path("voice-profiles",voiceProfileId,"draft"),body}),[["voiceProfileId","voiceProfileId"]]),"voice-profile.publish":operation(VoiceProfilePublishSchema,VoiceProfileReceiptSchema,({voiceProfileId,...body})=>({method:"POST",tenantId:body.tenantId,path:path("voice-profiles",voiceProfileId,"publish"),body}),[["voiceProfileId","voiceProfileId"]]),"voice-profile.set-enabled":operation(VoiceProfileSetEnabledSchema,VoiceProfileReceiptSchema,({voiceProfileId,...body})=>({method:"POST",tenantId:body.tenantId,path:path("voice-profiles",voiceProfileId,"availability"),body}),[["voiceProfileId","voiceProfileId"],["enabled","enabled"]]),"voice-profile.list":operation(VoiceProfileListSchema,VoiceProfilePageSchema,({tenantId,...query})=>({method:"GET",tenantId,path:path("voice-profiles"),query}),[],{readOnly:true}),"voice-profile.get":operation(VoiceProfileScopeSchema,VoiceProfileViewSchema,i=>({method:"GET",tenantId:i.tenantId,path:path("voice-profiles",i.voiceProfileId)}),[["voiceProfileId","voiceProfileId"]],{readOnly:true}),"voice-profile.version":operation(VoiceProfileVersionQuerySchema,VoiceProfileVersionSchema,i=>({method:"GET",tenantId:i.tenantId,path:path("voice-profiles",i.voiceProfileId,"versions",String(i.version))}),[["voiceProfileId","ref.voiceProfileRef"],["tenantId","ref.ownerTenantRef"],["version","ref.version"]],{readOnly:true})};var voiceReviewOperations={"voice-review.target":operation(VoiceReviewTargetQuerySchema,VoiceReviewTargetSchema,({tenantId,voiceProfileId,...query})=>({method:"GET",tenantId,path:path("voice-profiles",voiceProfileId,"review-target"),query}),[["voiceProfileId","voiceProfileId"],["audioVersionId","audioVersionId"]],{readOnly:true}),"voice-review.record":operation(RecordVoiceReviewSchema,VoiceReviewReceiptSchema,({voiceProfileId,...body})=>({method:"POST",tenantId:body.tenantId,path:path("voice-profiles",voiceProfileId,"reviews"),body}),[["voiceProfileId","review.voiceProfileId"],["audioVersionId","review.audioVersionId"],["referenceId","review.basis.reference.id"]]),"voice-review.get":operation(VoiceReviewGetSchema,VoiceReviewViewSchema,i=>({method:"GET",tenantId:i.tenantId,path:path("voice-profiles",i.voiceProfileId,"reviews",i.reviewId)}),[["voiceProfileId","review.voiceProfileId"],["reviewId","review.id"]],{readOnly:true})};var soundMakingPlanOperations={"sound-plan.context":productionRead(SoundPlanScopeSchema,SoundPlanContextSchema,()=>["sound-making-plan","context"],()=>({}),[["tenantId","tenantId"],["productionId","productionId"]]),"sound-plan.get":productionRead(SoundPlanGetSchema,SoundPlanViewSchema,()=>["sound-making-plan"],q=>({versionId:q.versionId}),[["tenantId","version.tenantId"],["productionId","version.productionId"],["versionId","version.id"]]),"sound-plan.validate":productionWrite(SoundPlanValidateSchema,SoundPlanValidationSchema,()=>["sound-making-plan","validate"],{readOnly:true}),"sound-plan.accept":productionWrite(SoundPlanAcceptSchema,SoundPlanReceiptSchema,()=>["sound-making-plan"],{identity:[["tenantId","version.tenantId"],["productionId","version.productionId"]]})};import{z as z195}from"zod";var post2=(input,output,action,identity6=[],readOnly=false)=>operation(input,output,i=>({method:"POST",tenantId:i.tenantId,path:path("lifecycle-events",action),body:i}),identity6,{readOnly});var lifecycleEventOperations={"production.feedback":post2(ProductionFeedbackInputSchema,ProductionFeedbackResultSchema,"feedback",[],true),"production.events.read":post2(ReadProductionEventsSchema,ProductionEventReadSchema,"read",[],true),"webhook.configure":post2(ConfigureWebhookSchema,WebhookSubscriptionSchema,"configure",[["subscriptionId","subscriptionId"]]),"webhook.secret.prepare":post2(PrepareWebhookSecretSchema,WebhookSecretReferenceSchema,"secret-prepare",[["subscriptionId","subscriptionId"],["secretRef","secretRef"]]),"webhook.configure-reference":post2(ConfigureWebhookReferenceSchema,WebhookSubscriptionSchema,"configure-reference",[["subscriptionId","subscriptionId"]]),"webhook.disable":post2(DisableWebhookSchema,WebhookSubscriptionSchema,"disable",[["subscriptionId","subscriptionId"]]),"webhook.replay":post2(ReplayWebhookSchema,WebhookReplayReceiptSchema,"replay",[["eventId","eventId"]]),"lifecycle-event.capabilities":post2(LifecycleEventScopeSchema,LifecycleEventCapabilitiesSchema,"capabilities",[],true),"lifecycle-event.subscriptions":post2(QueryLifecycleEventsSchema.safeExtend({kind:z195.literal("subscriptions")}),WebhookSubscriptionPageSchema,"query",[["subscriptionId","items.*.subscriptionId"]],true),"lifecycle-event.events":post2(QueryLifecycleEventsSchema.safeExtend({kind:z195.literal("events")}),ExternalLifecycleEventPageSchema,"query",[],true),"lifecycle-event.deliveries":post2(QueryLifecycleEventsSchema.safeExtend({kind:z195.literal("deliveries")}),WebhookDeliveryPageSchema,"query",[["subscriptionId","items.*.subscriptionId"],["deliveryId","items.*.deliveryId"]],true),"lifecycle-event.attempts":post2(QueryLifecycleEventsSchema.safeExtend({kind:z195.literal("attempts")}),WebhookAttemptPageSchema,"query",[],true)};var federationPost=(input,output,action,readOnly,bindings=[])=>operation(input,output,i=>({method:"POST",path:path("federation",action),tenantId:i.tenantId,body:i}),[["tenantId","tenantId"],["productionId","productionId"],...bindings],{readOnly});import{z as z197}from"zod";import{z as z196}from"zod";var clean3=v=>Array.from(v).every(char=>{const code=char.codePointAt(0);return code>=32&&code!==127&&(code<55296||code>57343)});var text4=max=>z196.string().min(1).max(max).refine(clean3);var hash5=z196.string().regex(/^[a-f0-9]{64}$/);var FederationReceiptOriginSchema=z196.strictObject({schemaVersion:z196.literal(1),sourceService:text4(256),bindingId:z196.uuid().toLowerCase(),source:text4(2048).refine(v=>URL.canParse(v)&&!/\s/u.test(v)),sourceTenant:text4(256),eventId:text4(256),deliveryId:hash5,digest:hash5,logicalDigest:hash5,connectionRef:text4(256),grantRef:text4(256),grantVersion:z196.int().min(1).max(2147483647),consumerRef:text4(256),targetScope:text4(128),deliveryRef:text4(2048)});var ref5=z197.string().min(1).max(256).refine(v=>Array.from(v).every(c=>{const p=c.codePointAt(0);return p>=32&&p!==127&&(p<55296||p>57343)}));var uuid5=z197.uuid().toLowerCase();var id14=z197.string().regex(/^[a-f0-9]{64}$/);var receiptRouteInput=FederationScopeSchema.extend({routeId:uuid5,bindingId:uuid5,requestId:ref5,expectedRevision:z197.int().nonnegative(),grantRef:ref5,grantVersion:z197.int().min(1).max(2147483647),notBefore:z197.iso.datetime(),expiresAt:z197.iso.datetime(),state:z197.enum(["ACTIVE","PAUSED","REVOKED"]),receiptProfile:z197.literal("eventsdk/1.1")}).strict();var FederationReceiptRouteConfigureSchema=receiptRouteInput.refine(orderedFederationWindow);var FederationReceiptRouteSchema=receiptRouteInput.omit({requestId:true,expectedRevision:true}).extend({revision:z197.int().positive(),source:z197.string().min(1).max(2048),connectionRef:ref5,remoteService:z197.string().min(1).max(256),remoteTenant:ref5,peerSource:z197.string().min(1).max(2048),effective:z197.enum(["ACTIVE","PAUSED","REVOKED","EXPIRED","BLOCKED"])}).strict();var FederationReceiptDeliverySchema=FederationScopeSchema.extend({id:id14,routeId:uuid5,inboxId:uuid5,eventId:ref5,receiptRef:ref5,receiptRevision:z197.int().positive(),grantRef:ref5,grantVersion:z197.int().positive(),state:z197.enum(["PENDING","UNKNOWN","PUBLISHED","HOLD"]),attempts:z197.int().nonnegative(),generation:z197.int().nonnegative(),recoveryCount:z197.int().min(0).max(3),reason:ref5.nullable(),originDelivery:FederationReceiptOriginSchema.optional(),ack:z197.strictObject({stream:ref5,sequence:z197.int().positive(),duplicate:z197.boolean()}).nullable()}).strict().refine(v=>!v.originDelivery||v.originDelivery.targetScope===v.tenantId+"/"+v.productionId);var FederationReceiptQuerySchema=FederationScopeSchema.extend({kind:z197.enum(["routes","deliveries"]),routeId:uuid5.optional(),inboxId:uuid5.optional(),originDeliveryId:id14.optional(),after:ref5.optional(),limit:z197.int().min(1).max(50).default(20)}).strict().refine(v=>v.kind==="deliveries"||!v.inboxId&&!v.originDeliveryId).refine(v=>!v.after||(v.kind==="routes"?z197.uuid().safeParse(v.after).success:id14.safeParse(v.after).success));var FederationReceiptQueryResultSchema=z197.discriminatedUnion("kind",[FederationScopeSchema.extend({kind:z197.literal("routes"),items:z197.array(FederationReceiptRouteSchema).max(50),next:uuid5.nullable()}).strict(),FederationScopeSchema.extend({kind:z197.literal("deliveries"),items:z197.array(FederationReceiptDeliverySchema).max(50),next:id14.nullable()}).strict()]).refine(v=>v.items.every(item=>item.tenantId===v.tenantId&&item.productionId===v.productionId));var FederationReceiptRecoverSchema=FederationScopeSchema.extend({routeId:uuid5,deliveryId:id14,requestId:ref5,expectedGeneration:z197.int().nonnegative(),expectedAttempts:z197.int().positive(),reason:ref5,acknowledgeDuplicateRisk:z197.literal(true)}).strict();var FederationReceiptRecoverySchema=FederationScopeSchema.extend({routeId:uuid5,deliveryId:id14,requestId:ref5,recoveryId:uuid5,attempts:z197.int().positive(),generation:z197.int().positive(),recoveryCount:z197.int().min(1).max(3),effect:z197.literal("TRANSPORT_ONLY")}).strict();var FederationReceiptCommandInputSchema=FederationScopeSchema.extend({requestId:ref5}).strict();var FederationReceiptCommandSchema=FederationReceiptCommandInputSchema.extend({result:z197.union([FederationReceiptRouteSchema,FederationReceiptRecoverySchema]).nullable()}).strict().refine(v=>!v.result||v.result.tenantId===v.tenantId&&v.result.productionId===v.productionId);import{z as z198}from"zod";var FederationHandoffInputSchema=FederationSubscriptionGetSchema.extend({expectedRevision:z198.int().positive().optional()}).strict();var FederationHandoffSchema=FederationSubscriptionResultSchema.safeExtend({contract:z198.literal("nvs-agent-event-handoff/1"),source:z198.string().min(1).max(2048),notificationProfile:z198.literal("eventsdk/1.2"),receiptProfile:z198.literal("eventsdk/1.1"),status:z198.enum(["READY","NOT_ACTIVE"]),defaultReceive:z198.literal(false),wake:z198.literal("RECEIVER_OWNED"),adoption:z198.literal("RECEIVER_OWNER_GOAL_REQUIRED"),cursorMeaning:z198.literal("NVS_SOURCE_COMMIT_POSITION_NOT_RECEIVER_SEQUENCE"),resultReferenceOperation:z198.literal("federation.result.reference"),resultReadOperation:z198.literal("federation.result.read"),receiptMeaning:z198.literal("LOCAL_APPLIED_IS_NOT_AGENT_ADOPTION"),events:z198.array(z198.strictObject({type:ExternalEventTypeSchema,wireType:z198.string(),dataSchema:z198.string()})).max(14)}).strict().refine(v=>v.status==="READY"===(v.subscription.effective==="ACTIVE")).refine(v=>v.status==="NOT_ACTIVE"?v.events.length===0:new Set(v.events.map(e=>e.type)).size===v.events.length&&v.events.length===v.subscription.eventTypes.length&&v.events.every(e=>v.subscription.eventTypes.includes(e.type)&&e.wireType===`com.nativestudio.${e.type}.v1`&&e.dataSchema===`urn:nativestudio:events:${e.type}:v1`));import{z as z199}from"zod";var digest4=z199.string().regex(/^sha256:[a-f0-9]{64}$/);var FederationContractInputSchema=FederationHandoffInputSchema.extend({expectedRevision:z199.int().positive(),expectedSource:z199.string().min(1).max(2048).optional(),expectedCatalogDigest:digest4.optional()}).strict();var event2=z199.strictObject({type:z199.string().min(1).max(256),dataschema:z199.string().min(1).max(2048),description:z199.string().min(1).max(1024),dataSchema:z199.record(z199.string(),z199.json()),resourceAccess:z199.strictObject({providerPath:z199.literal("/v1/federation/result-read"),tools:z199.tuple([z199.literal("federation_result_reference"),z199.literal("federation_result_read")])})});var FederationNativeCatalogSchema=z199.unknown().refine(value2=>{try{canonicalFederationCatalogJson(value2);return true}catch{return false}}).pipe(z199.strictObject({schemaVersion:z199.literal(1),serviceRef:z199.literal("native-video-studio"),events:z199.array(event2).min(1).max(14)}));var FederationContractSchema=FederationHandoffSchema.safeExtend({producerContract:z199.literal("nvs-producer-contract/1"),catalog:FederationNativeCatalogSchema.nullable(),catalogDigest:digest4.nullable(),maxCatalogBytes:z199.literal(131072),maxEventBytes:z199.literal(32768),maxResultValueBytes:z199.literal(32768),qualification:z199.literal("NVS_CONTRACT_ONLY")}).refine(v=>v.status==="NOT_ACTIVE"?v.catalog===null&&v.catalogDigest===null:!!v.catalog&&!!v.catalogDigest&&v.catalog.events.length===v.events.length&&new Set(v.catalog.events.map(e=>e.type)).size===v.events.length&&v.catalog.events.every(entry=>v.events.some(e=>e.wireType===entry.type&&e.dataSchema===entry.dataschema)));var federationExchangeOperations={"federation.subscription.contract":federationPost(FederationContractInputSchema,FederationContractSchema,"subscription-contract",true,[["subscriptionId","subscription.subscriptionId"]]),"federation.result.reference":federationPost(FederationResultLocatorSchema,FederationResultReferenceSchema,"result-reference",true),"federation.result.read":federationPost(FederationResultReadSchema,FederationResultSnapshotSchema,"result-read",true,[["source","source"]]),"federation.receipt-route.configure":federationPost(FederationReceiptRouteConfigureSchema,FederationReceiptRouteSchema,"receipt-route-configure",false,[["routeId","routeId"],["bindingId","bindingId"]]),"federation.receipt.query":federationPost(FederationReceiptQuerySchema,FederationReceiptQueryResultSchema,"receipt-query",true,[["kind","kind"]]),"federation.receipt.command":federationPost(FederationReceiptCommandInputSchema,FederationReceiptCommandSchema,"receipt-command",true),"federation.receipt.recover":federationPost(FederationReceiptRecoverSchema,FederationReceiptRecoverySchema,"receipt-recover",false,[["routeId","routeId"],["deliveryId","deliveryId"]]),"federation.subscription.handoff":federationPost(FederationHandoffInputSchema,FederationHandoffSchema,"subscription-handoff",true,[["subscriptionId","subscription.subscriptionId"]])};var federationEventLinkOperations={"federation.link.receiver":federationPost(EventLinkScopeSchema,EventReceiverPortalSchema,"link-receiver",true),"federation.link.targets":federationPost(EventLinkScopeSchema,EventLinkTargetsSchema,"link-targets",true),"federation.link.start":federationPost(EventLinkStartInputSchema,EventLinkStartSchema,"link-start",false,[["requestId","requestId"],["targetId","targetId"],["eventType","eventType"]]),"federation.link.get":federationPost(EventLinkRequestInputSchema,EventLinkViewSchema,"link-get",true,[["requestId","requestId"]]),"federation.link.confirm":federationPost(EventLinkConfirmInputSchema,EventLinkConfirmedSchema,"link-confirm",false,[["requestId","requestId"],["expiresAt","route.expiresAt"],["publicationMode","route.publicationMode"]]),"federation.link.cancel":federationPost(EventLinkRequestInputSchema,EventLinkCancelledSchema,"link-cancel",false,[["requestId","requestId"]])};import{z as z200}from"zod";var PEER_RECEIPT_SCHEMA="https://eventsdk.dev/schemas/v1/business-receipt.schema.json";var PUBLISHED_DELIVERY_NAMESPACE="native-video-studio";var PUBLISHED_DELIVERY_PREFIX="urn:nativestudio:published-delivery:v1:";var clean4=v=>Array.from(v).every(c=>{const n=c.codePointAt(0);return n>=32&&n!==127&&(n<55296||n>57343)});var text5=n=>z200.string().min(1).max(n).refine(clean4);var ref6=text5(256);var uuid6=z200.uuid().toLowerCase();var uri2=text5(2048).refine(v=>URL.canParse(v)&&!/\s/u.test(v));var hash6=z200.string().regex(/^[a-f0-9]{64}$/);function publishedDeliveryReceiptRef(deliveryId,digest6){return PUBLISHED_DELIVERY_PREFIX+hash6.parse(deliveryId)+":"+hash6.parse(digest6)}var PeerTerminalReceiptSchema=z200.strictObject({receiptRef:ref6,originSource:uri2,originEventId:ref6,deliveryRef:text5(2048),consumerRef:ref6,targetScope:text5(2048),disposition:z200.enum(["APPLIED","REJECTED"]),recordedAt:z200.iso.datetime({offset:true}),revision:z200.int().min(1).max(2147483647),reasonCode:ref6.optional(),resultRef:z200.strictObject({sourceSystem:ref6,resourceType:ref6,resourceId:text5(2048),revision:ref6,digest:ref6,evidenceRef:text5(2048).optional()}).optional()});var receiptInboundInput=FederationScopeSchema.extend({contractVersion:z200.literal(2),remoteService:ref6,bindingId:uuid6,routeId:uuid6,requestId:ref6,expectedRevision:z200.int().min(0),source:uri2,remoteTenant:ref6,peerType:ref6.refine(v=>!/\s/u.test(v)),consumerRef:ref6,peerConsumerRef:ref6,peerTargetScope:text5(2048),grantRef:ref6,grantVersion:z200.int().min(1).max(2147483647),notBefore:z200.iso.datetime({offset:true}),expiresAt:z200.iso.datetime({offset:true}),state:z200.enum(["ACTIVE","PAUSED","REVOKED"])}).strict();var ReceiptInboundConfigureSchema=receiptInboundInput.refine(orderedFederationWindow);var ReceiptInboundBindingSchema=receiptInboundInput.omit({requestId:true,expectedRevision:true}).extend({installationSource:uri2,remoteService:ref6,contractVersion:z200.union([z200.literal(1),z200.literal(2)]).default(1),connectionRef:ref6,direction:z200.literal("INBOUND"),profile:z200.literal("eventsdk/1.1"),revision:z200.int().positive(),effective:z200.enum(["ACTIVE","PAUSED","REVOKED","EXPIRED","BLOCKED"])}).strict().refine(b=>b.state==="ACTIVE"?b.effective!=="PAUSED":b.effective===b.state).refine(orderedFederationWindow);var CurrentReceiptInboundBindingSchema=ReceiptInboundBindingSchema.safeExtend({contractVersion:z200.literal(2)});var ReceiptObservationSchema=FederationScopeSchema.extend({id:uuid6,bindingId:uuid6,routeId:uuid6,originalEventId:uuid6,originalDeliveryId:hash6,originalDigest:hash6,peerSource:uri2,peerTenant:ref6,receiptRef:ref6,receiptRevision:z200.int().positive(),peerConsumerRef:ref6,peerTargetScope:text5(2048),disposition:z200.enum(["APPLIED","REJECTED"]),peerRecordedAt:z200.iso.datetime({offset:true}),receivedAt:z200.iso.datetime(),hasResultRef:z200.boolean(),meaning:z200.literal("PEER_REPORTED_ONLY")}).strict();var ReceiptInboundQuarantineSchema=FederationScopeSchema.extend({id:uuid6,bindingId:uuid6,deliveryRef:text5(2048),reasonCode:ref6,recordedAt:z200.iso.datetime()}).strict();var ReceiptInboundQuerySchema=FederationScopeSchema.extend({kind:z200.enum(["bindings","observations","quarantine"]),bindingId:uuid6.optional(),originalDeliveryId:hash6.optional(),limit:z200.int().min(1).max(50).default(25),after:uuid6.optional()}).strict().refine(v=>!v.originalDeliveryId||v.kind==="observations");var page4=FederationScopeSchema.extend({next:uuid6.nullable()});var ReceiptInboundQueryResultSchema=z200.discriminatedUnion("kind",[page4.extend({kind:z200.literal("bindings"),items:z200.array(ReceiptInboundBindingSchema).max(50)}).strict(),page4.extend({kind:z200.literal("observations"),items:z200.array(ReceiptObservationSchema).max(50)}).strict(),page4.extend({kind:z200.literal("quarantine"),items:z200.array(ReceiptInboundQuarantineSchema).max(50)}).strict()]).refine(v=>v.items.every(item=>item.tenantId===v.tenantId&&item.productionId===v.productionId));var ReceiptInboundCatalogSchema=FederationScopeSchema.extend({defaultReceive:z200.literal(false),meaning:z200.literal("PEER_REPORTED_ONLY"),bindings:z200.array(CurrentReceiptInboundBindingSchema).max(32)}).strict().refine(v=>v.bindings.every(b=>b.tenantId===v.tenantId&&b.productionId===v.productionId&&b.effective==="ACTIVE"));var ReceiptInboundCommandInputSchema=FederationScopeSchema.extend({requestId:ref6}).strict();var ReceiptInboundCommandSchema=ReceiptInboundCommandInputSchema.extend({result:ReceiptInboundBindingSchema.nullable()}).strict().refine(v=>!v.result||v.result.tenantId===v.tenantId&&v.result.productionId===v.productionId);import{z as z203}from"zod";import{z as z201}from"zod";var uuid7=z201.uuid().toLowerCase();var hash7=z201.string().regex(/^[a-f0-9]{64}$/);var source5=ReceiptInboundBindingSchema.shape.installationSource;var FederationDeliveryInspectInputSchema=FederationScopeSchema.extend({routeId:uuid7,eventId:uuid7,deliveryId:hash7,expectedSource:source5.optional(),expectedDigest:hash7.optional(),receiptBindingId:uuid7.optional()}).strict();var FederationInspectedDeliverySchema=FederationDeliverySchema.extend({source:source5,digest:hash7,connectionRef:ReceiptInboundBindingSchema.shape.connectionRef,grantRef:ReceiptInboundBindingSchema.shape.grantRef,grantVersion:ReceiptInboundBindingSchema.shape.grantVersion}).strict().refine(d=>d.acknowledgement===(d.state==="PUBLISHED"?"BROKER_STORED":"NOT_CONFIRMED")).refine(d=>d.state!=="PUBLISHED"||d.attempts>0);var FederationDeliveryInspectionSchema=FederationScopeSchema.extend({contract:z201.literal("nvs-federation-delivery-inspection/1"),asOf:z201.iso.datetime(),source:source5,delivery:FederationInspectedDeliverySchema,receiptBinding:ReceiptInboundBindingSchema.nullable(),receiptObservation:ReceiptObservationSchema.nullable(),receiptStatus:z201.enum(["NOT_REQUESTED","NOT_OBSERVED","PEER_REPORTED"]),meaning:z201.literal("NATIVE_TRANSPORT_AND_PEER_REPORT_ONLY")}).strict().refine(v=>{const d=v.delivery,b=v.receiptBinding,o=v.receiptObservation;if(d.tenantId!==v.tenantId||d.productionId!==v.productionId||d.source!==v.source)return false;if(!b)return!o&&v.receiptStatus==="NOT_REQUESTED";if(b.tenantId!==v.tenantId||b.productionId!==v.productionId||b.routeId!==d.routeId||b.installationSource!==v.source)return false;if(!o)return v.receiptStatus==="NOT_OBSERVED";return v.receiptStatus==="PEER_REPORTED"&&d.attempts>0&&o.tenantId===v.tenantId&&o.productionId===v.productionId&&o.bindingId===b.bindingId&&o.routeId===d.routeId&&o.originalDeliveryId===d.deliveryId&&o.originalEventId===d.eventId&&o.originalDigest===d.digest&&o.peerSource===b.source&&o.peerTenant===b.remoteTenant&&o.peerConsumerRef===b.peerConsumerRef&&o.peerTargetScope===b.peerTargetScope});import{z as z202}from"zod";var digest5=z202.string().regex(/^sha256:[a-f0-9]{64}$/);var ReceiptAcceptanceInputSchema=FederationScopeSchema.extend({bindingId:z202.uuid().toLowerCase(),expectedRevision:z202.int().positive(),expectedSource:ReceiptInboundBindingSchema.shape.installationSource.optional(),expectedDigest:digest5.optional()}).strict();function createReceiptAcceptanceDocument(raw){const b=CurrentReceiptInboundBindingSchema.parse(raw);return{contract:"nvs-receipt-acceptance/1",bindingId:b.bindingId,bindingRevision:b.revision,tenantId:b.tenantId,productionId:b.productionId,routeId:b.routeId,receiver:{serviceRef:"native-video-studio",source:b.installationSource,consumerRef:b.consumerRef},wire:{specversion:"1.0",profile:"eventsdk/1.1",kind:"RECEIPT",source:b.source,serviceorigin:b.remoteService,sourcetenant:b.remoteTenant,audience:"native-video-studio",type:b.peerType,dataschema:PEER_RECEIPT_SCHEMA,datacontenttype:"application/json",connectionref:b.connectionRef,grantref:b.grantRef,grantversion:b.grantVersion},notBefore:b.notBefore,expiresAt:b.expiresAt,dataSchema:z202.record(z202.string(),z202.json()).parse(z202.toJSONSchema(PeerTerminalReceiptSchema.extend({originSource:z202.literal(b.installationSource),consumerRef:z202.literal(b.peerConsumerRef),targetScope:z202.literal(b.peerTargetScope)}),{target:"draft-2020-12",io:"input"})),association:{rule:"EXACT_ATTEMPTED_NATIVE_OUTBOX_DELIVERY",resourcenamespace:PUBLISHED_DELIVERY_NAMESPACE,resourceRefPrefix:PUBLISHED_DELIVERY_PREFIX,resourceRefComponents:["deliveryId","fullEnvelopeSha256"],resourceRefDelimiter:":",resourceRefPattern:"^"+PUBLISHED_DELIVERY_PREFIX+"[a-f0-9]{64}:[a-f0-9]{64}$",digestAlgorithm:"SHA-256",digestEncoding:"LOWERCASE_HEX",correlationid:"ORIGINAL_NATIVE_EVENT_ID",causationid:"ORIGINAL_NATIVE_EVENT_ID",originEventId:"ORIGINAL_NATIVE_EVENT_ID"},sourceProof:{profile:"eventsdk-origin/1",required:true},maxWireBytes:32768,meaning:"PEER_REPORTED_ONLY",qualification:"NVS_RECEIVER_POLICY_ONLY"}}var boundedDocument=z202.unknown().refine(v=>{try{canonicalFederationReadJson(v);return true}catch{return false}}).pipe(z202.record(z202.string(),z202.json()));var ReceiptAcceptanceSchema=FederationScopeSchema.extend({contract:z202.literal("nvs-receipt-acceptance/1"),source:ReceiptInboundBindingSchema.shape.installationSource,binding:ReceiptInboundBindingSchema,status:z202.enum(["POLICY_ACTIVE","NOT_ACTIVE"]),document:boundedDocument.nullable(),digest:digest5.nullable(),maxDocumentBytes:z202.literal(65536),qualification:z202.literal("NVS_RECEIVER_POLICY_ONLY")}).strict().refine(v=>{try{const b=v.binding;if(b.tenantId!==v.tenantId||b.productionId!==v.productionId||b.installationSource!==v.source)return false;if(b.contractVersion!==2||b.effective!=="ACTIVE")return v.status==="NOT_ACTIVE"&&v.document===null&&v.digest===null;return v.status==="POLICY_ACTIVE"&&v.document!==null&&v.digest!==null&&canonicalFederationReadJson(v.document)===canonicalFederationReadJson(createReceiptAcceptanceDocument(b))}catch{return false}});var ReceiptHandoffInputSchema=FederationDeliveryInspectInputSchema.omit({receiptBindingId:true,expectedDigest:true,expectedSource:true}).extend({bindingId:ReceiptAcceptanceInputSchema.shape.bindingId,expectedRevision:ReceiptAcceptanceInputSchema.shape.expectedRevision,expectedSource:ReceiptInboundBindingSchema.shape.installationSource,expectedDeliveryDigest:FederationDeliveryInspectInputSchema.shape.deliveryId,expectedAcceptanceDigest:ReceiptAcceptanceInputSchema.shape.expectedDigest}).strict();function receiptHandoffStatus(i,a){if(i.receiptStatus==="PEER_REPORTED")return"PEER_REPORTED";if(i.delivery.attempts===0)return"ORIGINAL_NOT_ATTEMPTED";if(a.status!=="POLICY_ACTIVE")return"POLICY_NOT_ACTIVE";return"AWAITING_PEER_REPORT"}function receiptBindingInObservedWindow(i){const b=i.receiptBinding,observed=Date.parse(i.asOf);return b!==null&&Date.parse(b.notBefore)<=observed&&observed<Date.parse(b.expiresAt)}function association(i){return{resourcenamespace:PUBLISHED_DELIVERY_NAMESPACE,resourceref:publishedDeliveryReceiptRef(i.delivery.deliveryId,i.delivery.digest),correlationid:i.delivery.eventId,causationid:i.delivery.eventId}}var reply=FederationScopeSchema.extend({contract:z203.literal("nvs-receipt-handoff/1"),source:ReceiptInboundBindingSchema.shape.installationSource,inspection:FederationDeliveryInspectionSchema,acceptance:ReceiptAcceptanceSchema,status:z203.enum(["PEER_REPORTED","ORIGINAL_NOT_ATTEMPTED","POLICY_NOT_ACTIVE","AWAITING_PEER_REPORT"]),association:z203.strictObject({resourcenamespace:z203.literal(PUBLISHED_DELIVERY_NAMESPACE),resourceref:z203.string().min(1).max(256),correlationid:z203.uuid().toLowerCase(),causationid:z203.uuid().toLowerCase()}).nullable(),maxReplyBytes:z203.literal(131072),qualification:z203.literal("NVS_READ_SNAPSHOT_ONLY")}).strict().refine(v=>{try{const i=v.inspection,a=v.acceptance;if(!i.receiptBinding||i.source!==v.source||a.source!==v.source||i.tenantId!==v.tenantId||i.productionId!==v.productionId||a.tenantId!==v.tenantId||a.productionId!==v.productionId||a.status==="POLICY_ACTIVE"&&!receiptBindingInObservedWindow(i)||canonicalFederationReadJson(i.receiptBinding)!==canonicalFederationReadJson(a.binding)||v.status!==receiptHandoffStatus(i,a))return false;return v.status==="AWAITING_PEER_REPORT"?canonicalFederationReadJson(v.association)===canonicalFederationReadJson(association(i)):v.association===null}catch{return false}});var ReceiptHandoffSchema=z203.unknown().refine(v=>{try{canonicalFederationCatalogJson(v);return true}catch{return false}},{abort:true}).pipe(reply);var federationReceiptInboundOperations={"federation.receipt-inbound.handoff":federationPost(ReceiptHandoffInputSchema,ReceiptHandoffSchema,"receipt-inbound-handoff",true,[["bindingId","acceptance.binding.bindingId"],["routeId","inspection.delivery.routeId"],["eventId","inspection.delivery.eventId"],["deliveryId","inspection.delivery.deliveryId"]]),"federation.receipt-inbound.contract":federationPost(ReceiptAcceptanceInputSchema,ReceiptAcceptanceSchema,"receipt-inbound-contract",true,[["bindingId","binding.bindingId"]]),"federation.receipt-inbound.configure":federationPost(ReceiptInboundConfigureSchema,CurrentReceiptInboundBindingSchema,"receipt-inbound-configure",false,[["bindingId","bindingId"],["routeId","routeId"]]),"federation.receipt-inbound.catalog":federationPost(FederationScopeSchema,ReceiptInboundCatalogSchema,"receipt-inbound-catalog",true),"federation.receipt-inbound.query":federationPost(ReceiptInboundQuerySchema,ReceiptInboundQueryResultSchema,"receipt-inbound-query",true,[["kind","kind"]]),"federation.receipt-inbound.command":federationPost(ReceiptInboundCommandInputSchema,ReceiptInboundCommandSchema,"receipt-inbound-command",true)};var federationDeliveryInspectionOperations={"federation.delivery.inspect":federationPost(FederationDeliveryInspectInputSchema,FederationDeliveryInspectionSchema,"delivery-inspect",true,[["routeId","delivery.routeId"],["eventId","delivery.eventId"],["deliveryId","delivery.deliveryId"]])};var federationOperations={...federationEventLinkOperations,...federationDeliveryInspectionOperations,...federationReceiptInboundOperations,...federationExchangeOperations,"federation.inbound.catalog":federationPost(FederationScopeSchema,InboundCatalogSchema,"inbound-catalog",true),"federation.inbound.configure":federationPost(InboundBindingConfigureSchema,CurrentInboundBindingSchema,"inbound-configure",false,[["bindingId","bindingId"],["source","source"]]),"federation.inbound.query":federationPost(InboundQuerySchema,InboundQueryResultSchema,"inbound-query",true,[["kind","kind"]]),"federation.inbound.receipt":federationPost(InboundReceiptInputSchema,InboundReceiptSchema,"inbound-receipt",true,[["kind","kind"]]),"federation.inbound.replay":federationPost(InboundReplaySchema,InboundReplayResultSchema,"inbound-replay",false,[["inboxId","inboxId"],["requestId","requestId"]]),"federation.observe":federationPost(FederationScopeSchema,FederationObservationSchema,"observe",true),"federation.recover":federationPost(FederationRecoverSchema,FederationRecoverySchema,"recover",false,[["routeId","routeId"],["requestId","requestId"],["kind","kind"]]),"federation.catalog":federationPost(FederationScopeSchema,FederationCatalogSchema,"catalog",true),"federation.route.configure":federationPost(FederationRouteConfigureSchema,FederationRouteSchema,"route-configure",false,[["routeId","routeId"],["grantRef","grantRef"],["grantVersion","grantVersion"],["remoteService","remoteService"],["remoteTenant","remoteTenant"]]),"federation.subscription.set":federationPost(FederationSubscriptionSetSchema,FederationSubscriptionResultSchema,"subscription-set",false,[["subscriptionId","subscription.subscriptionId"],["routeId","subscription.routeId"],["subscriberKind","subscription.subscriberKind"],["subscriberRef","subscription.subscriberRef"]]),"federation.subscription.get":federationPost(FederationSubscriptionGetSchema,FederationSubscriptionResultSchema,"subscription-get",true,[["subscriptionId","subscription.subscriptionId"]]),"federation.query":federationPost(FederationQuerySchema,FederationQueryResultSchema,"query",true,[["kind","kind"]]),"federation.receipt":federationPost(FederationReceiptInputSchema,FederationReceiptSchema,"receipt",true,[["requestId","requestId"]])};var renderTicket=resource=>operation(TenantRenderMediaInputSchema,TenantRenderMediaTicketSchema,i=>({method:"GET",tenantId:i.tenantId,path:path("productions",i.productionId,resource,i.renderId,"media-ticket"),query:{role:i.role}}),[["renderId","renderId"],["role","role"],["role","ticket.object.role"]],{readOnly:true});var mediaDescriptorOperations={"rough-cut.media-ticket":renderTicket("rough-cuts"),"final-render.media-ticket":renderTicket("final-renders"),"composition.render.media-target":descriptorOperation(CompositionRenderGetSchema,CompositionRenderMediaDescriptorSchema,i=>({method:"GET",tenantId:i.tenantId,path:path("productions",i.productionId,"compositions","renders",i.renderId,"media-target")}),i=>path("productions",i.productionId,"compositions","renders",i.renderId,"media")),"delivery.download":descriptorOperation(TimelineScopeSchema,InterfaceDeliveryDownloadDescriptorSchema,i=>({method:"GET",tenantId:i.tenantId,path:path("productions",i.productionId,"deliveries","download")}),(i,o)=>o.method==="POST"?tenantMediaDownloadPath:path("productions",i.productionId,"deliveries","media")),"temporal-evidence.download":descriptorOperation(TemporalEvidenceMediaSchema,InterfaceDownloadDescriptorSchema,i=>({method:"GET",tenantId:i.tenantId,path:path("productions",i.productionId,"temporal-evidence",i.evidenceId,"media",i.kind,"descriptor"),query:i.kind==="FRAME"?{ordinal:i.ordinal}:{}}),i=>path("productions",i.productionId,"temporal-evidence",i.evidenceId,"media",i.kind)+(i.kind==="FRAME"?"?ordinal="+i.ordinal:"")),"video.options":operation(VideoOptionsInputSchema,VideoOptionsSchema,i=>({method:"GET",tenantId:i.tenantId,path:path("video-options")}),[],{readOnly:true})};var referencePreviewOperations={"studio.capabilities":mcpOperation(StudioCapabilitiesInputSchema,StudioCapabilitiesSchema,true),"reference-preview.start":operation(StartReferencePreviewSchema,ReferencePreviewAdmissionSchema,i=>{const{tenantId,productionId,...body}=i;return{method:"POST",tenantId,path:path("productions",productionId,"reference-previews"),body}},[["sourceArtifactId","sourceArtifactId"],["expectedBriefVersion","briefVersion"]],{readOnly:false}),"reference-preview.status":operation(ReferencePreviewOperationInputSchema,OperationSummarySchema,i=>({method:"GET",tenantId:i.tenantId,path:path("productions",i.productionId,"reference-previews",i.operationId,"status"),query:{projectId:i.projectId}}),[["operationId","id"]],{readOnly:true}),"reference-preview.get":operation(ReferencePreviewOperationInputSchema,ReferencePreviewReadResultSchema,i=>({method:"GET",tenantId:i.tenantId,path:path("productions",i.productionId,"reference-previews",i.operationId),query:{projectId:i.projectId}}),[],{readOnly:true}),"reference-preview.cancel":operation(ReferencePreviewOperationInputSchema,ReferencePreviewCancelResultSchema,i=>({method:"POST",tenantId:i.tenantId,path:path("productions",i.productionId,"reference-previews",i.operationId,"cancel"),body:{projectId:i.projectId}}),[],{readOnly:false})};var Context6=ExplorationContextInputSchema.safeExtend({tenantId:TenantIdSchema}).refine(i=>i.tenantId.toLowerCase()===i.scope.tenantId.toLowerCase());var Plan2=ValidateExplorationPlanSchema.safeExtend({tenantId:TenantIdSchema}).refine(i=>i.tenantId.toLowerCase()===i.basis.tenantId.toLowerCase());var Compare2=ExplorationCompareInputSchema.extend({tenantId:TenantIdSchema}).refine(i=>i.tenantId.toLowerCase()===i.scope.tenantId.toLowerCase());var Recommendation=ExplorationRecommendationContextInputSchema.safeExtend({tenantId:TenantIdSchema}).refine(i=>i.tenantId.toLowerCase()===i.scope.tenantId.toLowerCase());var Validate5=ValidateExplorationRecommendationSchema.safeExtend({tenantId:TenantIdSchema}).refine(i=>i.tenantId.toLowerCase()===i.basis.input.scope.tenantId.toLowerCase());var route4=(s,family,...suffix)=>path("projects",s.projectId,"productions",s.productionId,family,...suffix);var ownerOperations={"exploration.context":operation(Context6,ExplorationContextResultSchema,i=>({method:"POST",tenantId:i.tenantId,path:route4(i.scope,"visual-exploration","context"),body:{scope:i.scope,preparationIds:i.preparationIds}}),[["scope.tenantId","basis.tenantId","SUCCESS"],["scope.projectId","basis.projectId","SUCCESS"],["scope.productionId","basis.productionId","SUCCESS"],["scope.shotId","basis.shotId","SUCCESS"]],{readOnly:true}),"exploration.plan.validate":operation(Plan2,ExplorationValidationResultSchema,i=>({method:"POST",tenantId:i.tenantId,path:route4(i.basis,"visual-exploration","plans","validate"),body:{basis:i.basis,plan:i.plan}}),[["basis","basis","SUCCESS"]],{readOnly:true}),"exploration.compare":operation(Compare2,ExplorationComparisonResultSchema,i=>({method:"POST",tenantId:i.tenantId,path:route4(i.scope,"visual-exploration","compare"),body:{scope:i.scope,items:i.items}}),[["scope","scope"]],{readOnly:true}),"exploration.recommendation.context":operation(Recommendation,ExplorationRecommendationContextResultSchema,i=>({method:"POST",tenantId:i.tenantId,path:route4(i.scope,"exploration-recommendation","context"),body:{scope:i.scope,items:i.items,criteria:i.criteria}}),[["scope","basis.input.scope"],["items","basis.input.items"],["criteria","basis.input.criteria"]],{readOnly:true}),"exploration.recommendation.validate":operation(Validate5,ExplorationRecommendationValidationResultSchema,i=>({method:"POST",tenantId:i.tenantId,path:route4(i.basis.input.scope,"exploration-recommendation","proposals","validate"),body:{basis:i.basis,proposal:i.proposal}}),[["basis","basis"],["proposal.decision.kind","decision.kind"],["proposal.decision.label","decision.label"]],{readOnly:true})};var visualExplorationOperations=ownerOperations;import{z as z204}from"zod";var ownerOperations2={"imported-visual.query":productionRead(ImportedVisualOriginalQuerySchema,ImportedVisualOriginalPageSchema,()=>["imported-visuals","originals"],i=>({limit:i.limit,afterSourceId:i.afterSourceId,shotId:i.shotId}),[["shotId","items.*.shotId"]]),"imported-visual.register-source":productionWrite(LegacyImportedVisualProjectSourceSchema,ImportedVisualOriginalViewSchema,()=>["imported-visuals","originals","from-source"],{identity:[["projectId","projectId"],["shotId","shotId"]]}),"imported-visual.start-from-source":productionWrite(ImportedVisualFromProjectSourceSchema,DirectOriginalSubmitSchema,()=>["imported-visuals","originals","from-source","v1"]),"imported-visual.register":operation(LegacyImportedVisualUploadSchema,ImportedVisualOriginalViewSchema,i=>{const{contentBase64,tenantId,productionId,...fields}=i;return{method:"POST",tenantId,path:path("productions",productionId,"imported-visuals","originals","bytes"),importedVideo:{bytes:Buffer.from(contentBase64,"base64"),metadata:Buffer.from(JSON.stringify(fields)).toString("base64url")}}},[["shotId","shotId"]]),"imported-visual.revise":productionWrite(LegacyImportedVisualRevisionSchema,ImportedVisualOriginalViewSchema,i=>["imported-visuals","originals",i.sourceId,"revisions"],{pathFields:["sourceId"],identity:[["sourceId","sourceId"],["shotId","shotId"]]}),"imported-visual.original":productionRead(ImportedVisualOriginalGetSchema,ImportedVisualOriginalViewSchema,i=>["imported-visuals","originals",i.sourceId],i=>({version:i.version}),[["sourceId","sourceId"],["version","version"]]),"imported-visual.history":productionRead(ImportedVisualOriginalHistoryQuerySchema,ImportedVisualOriginalHistorySchema,i=>["imported-visuals","originals",i.sourceId,"history"],i=>({limit:i.limit,beforeVersion:i.beforeVersion}),[["sourceId","sourceId"],["sourceId","items.*.sourceId"]]),"imported-visual.normalize":productionWrite(ImportedVisualNormalizeStartSchema,ImportedVisualAdmissionSchema,()=>["imported-visuals","normalizations"],{identity:[["sourceId","sourceId"],["sourceVersionId","sourceVersionId"]]}),"imported-visual.get":productionRead(ImportedVisualGetSchema,ImportedVisualNormalizationViewSchema,i=>["imported-visuals","normalizations",i.normalizationId],void 0,[["normalizationId","normalizationId"]]),"imported-visual.review.target":productionRead(ImportedVisualGetSchema,ImportedVisualReviewTargetSchema,i=>["imported-visuals","normalizations",i.normalizationId,"review-target"],void 0,[["normalizationId","normalizationId"]]),"imported-visual.review.record":productionWrite(ImportedVisualReviewSchema,ImportedVideoReviewReceiptSchema,i=>["imported-visuals","normalizations",i.normalizationId,"reviews"],{pathFields:["normalizationId"],identity:[["normalizationId","review.normalizationId"],["representationId","review.representationId"],["checksumSha256","review.checksumSha256"]]}),"imported-visual.decide":productionWrite(ImportedVisualDecisionSchema,ShotDecisionReceiptSchema,i=>["imported-visuals","normalizations",i.normalizationId,"decisions"],{pathFields:["normalizationId"],identity:[["normalizationId","decision.normalizationId"],["reviewId","decision.reviewId"]]}),"imported-visual.cancel":productionWrite(ImportedVisualGetSchema,z204.strictObject({cancellationRequested:z204.boolean()}),i=>["imported-visuals","normalizations",i.normalizationId,"cancel"],{pathFields:["normalizationId"]})};var importedVisualOperations=ownerOperations2;var versionPath=i=>["source-sync-audios","shots",i.shotId,"versions",i.versionId];var ownerOperations3={"source-sync.start":productionWrite(SourceSyncRuntimeStartSchema,SourceSyncRuntimeAdmissionSchema,()=>["source-sync-audios","requests"]),"source-sync.get":productionRead(SourceSyncRuntimeScopeSchema,SourceSyncRuntimeViewSchema,i=>["source-sync-audios","requests",i.requestId],void 0,[["requestId","requestId"]]),"source-sync.cancel":productionWrite(SourceSyncRuntimeScopeSchema,ImportedVisualCancellationSchema,i=>["source-sync-audios","requests",i.requestId,"cancel"],{pathFields:["requestId"]}),"source-sync.audio":productionRead(SourceSyncAudioGetSchema,WavExportResultSchema,i=>[...versionPath(i),"audio"]),"source-sync.version":productionRead(SourceSyncAudioGetSchema,SourceSyncAudioViewSchema,versionPath,void 0,[["versionId","version.id"],["shotId","version.shotId"]]),"source-sync.review.target":productionRead(SourceSyncAudioGetSchema,SourceSyncReviewTargetSchema,i=>[...versionPath(i),"review-target"],void 0,[["versionId","version.id"],["shotId","version.shotId"]]),"source-sync.review.record":productionWrite(SourceSyncReviewInputSchema,SourceSyncReviewRecordSchema,i=>[...versionPath(i),"reviews"],{pathFields:["shotId","versionId"],identity:[["versionId","versionId"],["shotId","shotId"],["audio","audio"],["visual","visual"]]}),"source-sync.review.get":productionRead(SourceSyncReviewGetSchema,SourceSyncReviewRecordSchema,i=>[...versionPath(i),"reviews",i.reviewId],void 0,[["versionId","versionId"],["shotId","shotId"],["reviewId","id"]])};var sourceSyncOperations=ownerOperations3;var Writer=ValidateWriterProposalSchema.extend({tenantId:TenantIdSchema}).refine(i=>i.tenantId.toLowerCase()===i.basis.tenantId.toLowerCase());var Director=ValidateDirectorProposalSchema.safeExtend({tenantId:TenantIdSchema}).refine(i=>i.tenantId.toLowerCase()===i.basis.tenantId.toLowerCase());var projectProduction2=(scope8,...suffix)=>path("projects",scope8.projectId,"productions",scope8.productionId,...suffix);var planningIntelligenceOperations={"brief.active":operation(WriterScopeSchema,WriterBriefResultSchema,i=>({method:"GET",tenantId:i.tenantId,path:projectProduction2(i,"brief-versions","active")})),"writer.validate":operation(Writer,WriterValidationResultSchema,i=>({method:"POST",tenantId:i.tenantId,path:projectProduction2(i.basis,"writer-proposals","validate"),body:{basis:i.basis,proposal:i.proposal,...i.revisionReason?{revisionReason:i.revisionReason}:{}}}),[["basis","basis","SUCCESS"]],{readOnly:true}),"director.context":operation(DirectorScopeSchema,DirectorContextResultSchema,i=>({method:"GET",tenantId:i.tenantId,path:projectProduction2(i,"director","context")})),"director.validate":operation(Director,DirectorValidationResultSchema,i=>({method:"POST",tenantId:i.tenantId,path:projectProduction2(i.basis,"director-proposals","validate"),body:{basis:i.basis,proposal:i.proposal,...i.revisionReason?{revisionReason:i.revisionReason}:{}}}),[["basis","basis","SUCCESS"]],{readOnly:true}),"consistency-profile.get":productionRead(ConsistencyProfileScopeSchema,ConsistencyProfileViewSchema,()=>["consistency-profile"]),"consistency-profile.version":productionRead(ConsistencyProfileVersionQuerySchema,ConsistencyProfileVersionSchema,i=>["consistency-profile","versions",i.profileId],void 0,[["profileId","id"]]),"consistency-profile.configure":productionWrite(ConfigureConsistencyProfileSchema,ConsistencyProfileReceiptSchema,()=>["consistency-profile"],{tenantInBody:true})};var audioCaptionOperations={"caption.transcript_draft":productionWrite(CaptionTranscriptPlanSchema,CaptionTranscriptDraftSchema,()=>["captions","transcript-draft"],{readOnly:true}),"caption.author_transcript":productionWrite(AuthorTranscriptCaptionsSchema,CaptionReceiptSchema,()=>["captions","from-transcript"]),"audio.export":operation(AudioGetSchema,AudioExportResultSchema,i=>({method:"GET",tenantId:i.tenantId,path:path("productions",i.productionId,"audio",i.purpose,"versions",i.versionId,"export-data")}),[],{readOnly:true}),"caption.export":operation(CaptionExportSchema,CaptionExportResultSchema,i=>({method:"GET",tenantId:i.tenantId,path:path("productions",i.productionId,"captions","versions",i.versionId,"export-data"),query:{format:i.format}}),[],{readOnly:true}),"audio.basis":productionRead(AudioReadScopeSchema,AudioBasisSchema,i=>["audio",i.purpose,"basis"],void 0,[["purpose","purpose"]]),"audio.current":productionRead(AudioReadScopeSchema,AudioViewSchema,i=>["audio",i.purpose,"current"],void 0,[["purpose","version.purpose"]]),"audio.get":productionRead(AudioGetSchema,AudioViewSchema,i=>["audio",i.purpose,"versions",i.versionId],void 0,[["versionId","version.id"],["purpose","version.purpose"]]),"audio.query":productionRead(AudioQuerySchema,AudioPageSchema,i=>["audio",i.purpose,"versions"],pageQuery,[["purpose","items.*.version.purpose"]]),"audio.import":productionWrite(AudioImportRequestSchema,AudioReceiptSchema,i=>["audio",i.purpose],{pathFields:["purpose"],identity:[["purpose","version.purpose"]]}),"caption.basis":productionRead(CaptionScopeSchema,CaptionBasisSchema,()=>["captions","basis"]),"caption.current":productionRead(CaptionScopeSchema,CaptionViewSchema,()=>["captions","current"]),"caption.get":productionRead(CaptionGetSchema,CaptionViewSchema,i=>["captions","versions",i.versionId],void 0,[["versionId","version.id"]]),"caption.query":productionRead(CaptionQuerySchema,CaptionPageSchema,()=>["captions","versions"],pageQuery),"caption.author":productionWrite(AuthorCaptionsSchema,CaptionReceiptSchema,()=>["captions"])};var discoveryOperations={"artifact.query":operation(ArtifactDiscoveryQuerySchema,ArtifactDiscoveryPageSchema,input=>({method:"GET",tenantId:input.tenantId,path:path("artifact-discovery"),query:{...pageQuery(input),projectId:input.projectId,productionId:input.productionId,artifactId:input.artifactId,mediaCategory:input.mediaCategory,family:input.family,search:input.search,lifecycle:input.lifecycle}}),[["artifactId","items.*.artifactId"]])};var temporalEvidenceOperations={"temporal-evidence.read-video":productionWrite(OriginalVideoReadSchema,OriginalVideoResultSchema,()=>["temporal-evidence","original-video"],{tenantInBody:true,readOnly:true,identity:[["tenantId","source.tenantId"],["productionId","source.productionId"],["artifactId","source.artifactId"],["representationId","source.representationId"],["checksumSha256","source.checksumSha256"]]}),"temporal-evidence.target":productionWrite(TemporalEvidenceTargetSchema,TemporalEvidenceSourceSchema,()=>["temporal-evidence","target"],{tenantInBody:true,readOnly:true,identity:[["artifactId","artifactId"],["representationId","representationId"],["checksumSha256","checksumSha256"]]}),"temporal-evidence.start":productionWrite(TemporalEvidenceStartSchema,TemporalEvidenceAdmissionSchema,()=>["temporal-evidence"],{tenantInBody:true,identity:[["artifactId","source.artifactId"],["representationId","source.representationId"],["checksumSha256","source.checksumSha256"]]}),"temporal-evidence.get":productionRead(TemporalEvidenceGetSchema,TemporalEvidenceViewSchema,i=>["temporal-evidence",i.evidenceId],void 0,[["evidenceId","evidenceId"]]),"temporal-evidence.cancel":productionWrite(TemporalEvidenceGetSchema,cancellation,i=>["temporal-evidence",i.evidenceId,"cancel"],{pathFields:["evidenceId"]})};var scopeKeys=["tenantId","projectId","productionId"];function navigationResponseMatches(value2){if(!value2||typeof value2!=="object")return true;const result=value2;if(result.evidence?.source!=="production_snapshot")return true;if(!result.actions?.items||!result.operations?.items)return false;const same3=(a,b)=>typeof a==="string"&&typeof b==="string"&&a.toLowerCase()===b.toLowerCase();const hintsMatch=input=>!input||scopeKeys.every(key10=>input[key10]===void 0||same3(input[key10],result[key10]));return result.actions.items.every(action=>scopeKeys.every(key10=>same3(action.context[key10],result[key10]))&&action.context.revision===result.evidence.revision&&hintsMatch(action.inputHints?.knownInputs)&&hintsMatch(action.inspect?.arguments))&&result.operations.items.every(operation2=>{const inspect=operation2.inspect;const input=inspect?.tool==="studio_capability_query"?inspect.arguments.arguments:inspect?.arguments;return hintsMatch(inspect?.arguments)&&hintsMatch(input)&&(!inspect||input?.operationId===operation2.id)})}var envelopes=new Set(["choices","related","operations","items","project","production","productions","artifact","primaryRepresentation","relations","storyVersion","planVersion","version","manifest","timeline","basis","review","selection","decision","target","admission","policy","finalDelivery","receipt","render","evidence","source","sourceIdentity","preparation","link","body","latestReview","finalReady","approval","binding","standard","snapshot","sequence","frames","frameOutput","acceptance","reference","candidate","connection","scope","profile","current","feedback","share","ownerContext","comparison","candidates","reviewContext","input","recordDraft","owner","output","result","briefVersion","deliveryTarget","deliverySnapshot","validation","preparations","view","generationDrafts","request","generation","handoff","mediaRead","reviewTarget","reviews"]);var uuid8=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function same2(left,right){if(Array.isArray(left)||Array.isArray(right))return Array.isArray(left)&&Array.isArray(right)&&left.length===right.length&&left.every((item,i)=>same2(item,right[i]));if(left&&right&&typeof left==="object"&&typeof right==="object"){const a=left,b=right;const keys=Object.keys(a);return keys.length===Object.keys(b).length&&keys.every(key10=>Object.hasOwn(b,key10)&&same2(a[key10],b[key10]))}return typeof left==="string"&&typeof right==="string"&&uuid8.test(left)&&uuid8.test(right)?left.toLowerCase()===right.toLowerCase():left===right}function scopeMatches(value2,scope8,depth2=0){if(!value2||typeof value2!=="object")return true;if(depth2>12)return false;if(Array.isArray(value2))return value2.every(item=>scopeMatches(item,scope8,depth2+1));const record=value2;for(const key10 of["tenantId","projectId","productionId"])if(scope8[key10]!==void 0&&record[key10]!==void 0&&record[key10]!==null&&!same2(record[key10],scope8[key10]))return false;return Object.entries(record).every(([key10,item])=>{if(key10==="feedback"&&item&&typeof item==="object"&&scope8.operationId!==void 0&&!same2(item.operationId,scope8.operationId))return false;return!envelopes.has(key10)||scopeMatches(item,scope8,depth2+1)})}function targetsMatch(value2,parts,expected){if(!parts.length)return same2(value2,expected);const[part,...rest]=parts;if(part==="*")return Array.isArray(value2)&&value2.every(item=>targetsMatch(item,rest,expected));return!!value2&&typeof value2==="object"&&targetsMatch(value2[part],rest,expected)}function deviceBound(request,result){const target3=request;const receipt=result?.deviceExecution;if(target3.mode===void 0)return receipt?.target==="TENANT_DEVICE"&&typeof result?.runtimeJobId==="string"&&(!target3.deviceId||same2(target3.deviceId,receipt.deviceId));return!!receipt&&receipt.mode===target3.mode&&!!receipt.runtimeJobId&&(!target3.validationMode||target3.validationMode===receipt.validationMode)&&(!target3.deviceId||same2(target3.deviceId,receipt.deviceId))}function deviceJobMatches(result){const value2=result;return value2?.runtimeJobId===void 0||value2.deviceExecution?.runtimeJobId===void 0||same2(value2.runtimeJobId,value2.deviceExecution.runtimeJobId)}function assertResponseBindings(result,input,identity6,method,pathOrBindings,additionalBindings=[]){if(result===null)return;const expectedPath=typeof pathOrBindings==="string"?pathOrBindings:void 0;const identityWhenPresent=typeof pathOrBindings==="string"||pathOrBindings===void 0?additionalBindings:pathOrBindings;const record=result;const basis=input.basis;const basisInput2=basis?.input;const nested=input.scope??basis?.scope??basisInput2?.scope??basis;if(input.deviceExecution!==void 0&&!deviceBound(input.deviceExecution,result)||!deviceJobMatches(result)||!scopeMatches(result,input)||!navigationResponseMatches(result)||nested!==void 0&&!scopeMatches(result,nested)||expectedPath!==void 0&&(typeof record?.path!=="string"||record.path.replace(/[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}/gi,id15=>id15.toLowerCase())!==expectedPath.replace(/[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}/gi,id15=>id15.toLowerCase()))||[...identity6,...identityWhenPresent.filter(([,target3])=>!!record&&Object.hasOwn(record,target3))].some(([key10,target3,whenStatus])=>{if(whenStatus!==void 0&&record?.semanticStatus!==whenStatus)return false;const expected=key10.split(".").reduce((value2,field)=>value2&&typeof value2==="object"?value2[field]:void 0,input);return expected!==void 0&&!targetsMatch(result,target3.split("."),expected)})||Array.isArray(record?.items)&&typeof input.limit==="number"&&record.items.length>input.limit)throw new NativeStudioSdkError("RESPONSE_SCOPE_MISMATCH","INTERNAL_OPERATIONAL_FAILURE",method==="POST"?"UNKNOWN":"NO_WRITE")}function seriesPath(projectId,...suffix){return path("projects",projectId,"series-standards",...suffix)}var seriesPost=(group,...suffix)=>({tenantId,projectId,...body})=>({method:"POST",tenantId,path:seriesPath(projectId,group,...suffix),body});var seriesStandardOperations={"series.list":operation(SeriesStandardListSchema,SeriesStandardPageSchema,i=>({method:"GET",tenantId:i.tenantId,path:seriesPath(i.projectId),query:{after:i.after,limit:i.limit}})),"series.get":operation(SeriesStandardQuerySchema,SeriesStandardVersionSchema,i=>({method:"GET",tenantId:i.tenantId,path:seriesPath(i.projectId,i.seriesId),query:{version:i.version}}),[["seriesId","seriesId"],["version","version"]]),"series.publish":operation(PublishSeriesStandardSchema,PublishSeriesStandardReceiptSchema,({tenantId,projectId,...body})=>({method:"POST",tenantId,path:seriesPath(projectId),body}),[["seriesId","standard.seriesId"],["idempotencyKey","idempotencyKey"],["brand.ownerProjectId","standard.brand.ownerProjectId"],["brand.brandId","standard.brand.brandId"],["brand.version","standard.brand.version"],["brand.grantId","standard.brand.grantId"],["brand.variantId","standard.brand.variantId"],["brand.selectedClaimIds","standard.brand.selectedClaimIds"]]),"series.bind":operation(BindSeriesStandardSchema,BindSeriesStandardReceiptSchema,({tenantId,projectId,...body})=>({method:"POST",tenantId,path:seriesPath(projectId,"bindings"),body}),[["seriesId","binding.standard.seriesId"],["version","binding.standard.version"],["characterVariantIds","binding.characterVariantIds"],["idempotencyKey","idempotencyKey"]]),"series.binding":operation(ProductionSeriesQuerySchema,ProductionSeriesBindingSchema,i=>({method:"GET",tenantId:i.tenantId,path:seriesPath(i.projectId,"bindings",i.productionId),query:{productionRevision:i.productionRevision,atRevision:i.atRevision}}),[["productionRevision","productionRevision"]]),"series.receipt":operation(SeriesStandardReceiptQuerySchema,SeriesStandardReceiptSchema,({tenantId,projectId,idempotencyKey:idempotencyKey2})=>({method:"POST",tenantId,path:seriesPath(projectId,"receipts","query"),body:{idempotencyKey:idempotencyKey2}}),[["idempotencyKey","idempotencyKey"]],{readOnly:true}),"series.canon.record":operation(RecordSeriesCanonSchema,SeriesCanonSchema,seriesPost("canon","record"),[["idempotencyKey","idempotencyKey"],["seriesId","seriesId"],["branchId","branchId"],["bindingRevision","bindingRevision"],["seriesVersion","seriesVersion"],["relation","relation"]]),"series.canon.get":operation(SeriesCanonQuerySchema,SeriesCanonSchema,seriesPost("canon","query"),[["seriesId","seriesId"],["branchId","branchId"],["ordinal","ordinal"]],{readOnly:true}),"series.canon.receipt":operation(SeriesCanonReceiptQuerySchema,SeriesCanonSchema,seriesPost("canon","receipts","query"),[["idempotencyKey","idempotencyKey"]],{readOnly:true}),"series.improvement.command":operation(SeriesImprovementCommandSchema,SeriesImprovementReceiptSchema,seriesPost("improvements","commands"),[["action","action"],["seriesId","seriesId"],["proposalId","proposalId"],["idempotencyKey","idempotencyKey"],["baseVersion","proposal.baseVersion"]]),"series.improvement.query":operation(SeriesImprovementQuerySchema,SeriesImprovementViewSchema,seriesPost("improvements","query"),[["action","action"],["seriesId","seriesId"],["proposalId","proposalId"]],{readOnly:true}),"series.improvement.receipt":operation(SeriesImprovementReceiptQuerySchema,SeriesImprovementReceiptSchema,seriesPost("improvements","receipts","query"),[["idempotencyKey","idempotencyKey"]],{readOnly:true})};function improvementResponseMatches(value2){const root=value2;const sameScope=item=>item.tenantId===root.tenantId&&item.projectId===root.projectId&&item.seriesId===root.seriesId;if(root.action==="LIST")return root.items.every(sameScope);const{proposal,decision}=root;return sameScope(proposal)&&proposal.proposalId===root.proposalId&&(root.action==="GET"||(root.action==="PROPOSE"?decision===null:decision?.action===root.action))&&(!decision||sameScope(decision)&&decision.proposalId===proposal.proposalId&&(decision.action==="DECLINE"||sameScope(decision.published)&&decision.published.version===proposal.baseVersion+1))}function assertSeriesResponseVersions(operation2,input,result){if(operation2==="series.binding"&&typeof input.atRevision==="number"){if(result.productionRevision<=input.atRevision)return;throw new NativeStudioSdkError("RESPONSE_SCOPE_MISMATCH","INTERNAL_OPERATIONAL_FAILURE","NO_WRITE")}if(operation2==="series.publish"){const receipt=result;if(receipt.standard.version===Number(input.expectedVersion)+1)return}else if(operation2==="series.bind"){const{binding}=result;if(binding.productionRevision===Number(input.expectedProductionRevision)+1&&binding.profileVersion===Number(input.expectedProfileVersion)+1)return}else if(operation2==="series.canon.record"){if(result.ordinal===Number(input.expectedHeadOrdinal)+1)return}else if(operation2.startsWith("series.improvement.")){if(improvementResponseMatches(result))return;if(operation2!=="series.improvement.command")throw new NativeStudioSdkError("RESPONSE_SCOPE_MISMATCH","INTERNAL_OPERATIONAL_FAILURE","NO_WRITE")}else return;throw new NativeStudioSdkError("RESPONSE_SCOPE_MISMATCH","INTERNAL_OPERATIONAL_FAILURE","UNKNOWN")}function brandRequest(suffix){return({tenantId,projectId,...body})=>({method:"POST",tenantId,path:path("projects",projectId,"series-standards","brand",...suffix),body})}var enterpriseBrandOperations={"series.brand.command":operation(EnterpriseBrandCommandSchema,EnterpriseBrandReceiptSchema,brandRequest(["commands"]),[["action","action"],["idempotencyKey","idempotencyKey"]]),"series.brand.get":operation(EnterpriseBrandQuerySchema,EnterpriseBrandViewSchema,brandRequest(["query"]),[["action","action"]],{readOnly:true}),"series.brand.receipt":operation(EnterpriseBrandReceiptQuerySchema,EnterpriseBrandReceiptSchema,brandRequest(["receipts","query"]),[["idempotencyKey","idempotencyKey"]],{readOnly:true})};var sameUuid=(left,right)=>typeof right==="string"&&left.toLowerCase()===right.toLowerCase();function assertEnterpriseBrandResponse(key10,input,value2){if(!Object.hasOwn(enterpriseBrandOperations,key10))return;const output=value2;const owner="publication"in output?output.publication:output.grant;const ownerProjectId=input.ownerProjectId??input.projectId;const variantIds=Array.isArray(input.variantIds)?input.variantIds:void 0;const grantMatches=!("grant"in output)||(input.grantId===void 0||sameUuid(output.grant.grantId,input.grantId))&&(input.consumerProjectId===void 0||sameUuid(output.grant.consumerProjectId,input.consumerProjectId))&&(input.expiresAt===void 0||output.grant.expiresAt===input.expiresAt)&&(!variantIds||output.grant.variantIds.length===variantIds.length&&output.grant.variantIds.every((id15,index)=>sameUuid(id15,variantIds[index])))&&(key10!=="series.brand.command"||output.grant.revokedAt!==null===(output.action==="REVOKE"))&&(key10!=="series.brand.get"||sameUuid(output.grant.projectId,input.projectId)||sameUuid(output.grant.consumerProjectId,input.projectId));const valid=sameUuid(owner.tenantId,input.tenantId)&&sameUuid(owner.projectId,ownerProjectId)&&(input.brandId===void 0||sameUuid(owner.brandId,input.brandId))&&(input.version===void 0||owner.version===input.version)&&(input.expectedVersion===void 0||owner.version===Number(input.expectedVersion)+1)&&grantMatches&&(output.action!=="PUBLICATION"||sameUuid(owner.projectId,input.projectId)||typeof output.grantId==="string"&&sameUuid(output.grantId,input.grantId));if(!valid)throw new NativeStudioSdkError("RESPONSE_SCOPE_MISMATCH","INTERNAL_OPERATIONAL_FAILURE",key10==="series.brand.command"?"UNKNOWN":"NO_WRITE")}import{createHash as createHash11}from"node:crypto";import{z as z205}from"zod";var render=RoughCutGetSchema.omit({tenantId:true});var mediaInput=z205.discriminatedUnion("kind",[AudioGetSchema.omit({tenantId:true}).extend({kind:z205.literal("AUDIO")}),CaptionExportSchema.omit({tenantId:true}).extend({kind:z205.literal("CAPTION")}),ArtifactDiscoveryMediaSchema.omit({tenantId:true}).extend({kind:z205.literal("DISCOVERED_ARTIFACT"),contentType:DiscoveryContentTypeSchema}),AudioGetSchema.omit({tenantId:true}).extend({kind:z205.literal("AUDIO_WAV")}),CaptionGetSchema.omit({tenantId:true}).extend({kind:z205.enum(["CAPTION_JSON","CAPTION_SRT"])}),TemporalEvidenceGetSchema.omit({tenantId:true}).extend({kind:z205.literal("TEMPORAL_FRAME"),ordinal:z205.int().nonnegative().max(63)}),TemporalEvidenceGetSchema.omit({tenantId:true}).extend({kind:z205.enum(["TEMPORAL_SHEET","TEMPORAL_MANIFEST"])}),VideoGetInputSchema.omit({tenantId:true}).extend({kind:z205.enum(["VIDEO_GENERATION","VIDEO_GENERATION_POSTER"])}),render.extend({kind:z205.literal("CODE_VIDEO")}),render.extend({kind:z205.enum(["ROUGH_CUT_VIDEO","ROUGH_CUT_POSTER","FINAL_VIDEO","FINAL_POSTER"])}),TimelineScopeSchema.omit({tenantId:true}).extend({kind:z205.literal("DELIVERED_VIDEO")}),DeliveryManifestGetSchema.omit({tenantId:true}).extend({kind:z205.literal("DELIVERY_MANIFEST")})]);var expectedInput=z205.strictObject({checksumSha256:z205.string().regex(/^[0-9a-f]{64}$/),byteSize:z205.int().positive().max(128*1024*1024).optional()});async function readNativeMedia(transport,tenantId,raw,expected,options){if(!raw||raw.tenantId!==void 0&&(typeof raw.tenantId!=="string"||raw.tenantId.toLowerCase()!==tenantId.toLowerCase()))sdkInputError();const parsed=mediaInput.safeParse(Object.fromEntries(Object.entries(raw).filter(([key10])=>key10!=="tenantId"))),identity6=expectedInput.safeParse({checksumSha256:expected?.checksumSha256,byteSize:expected?.byteSize});if(!parsed.success||!identity6.success)sdkInputError();const input=parsed.data;let suffix,contentType;if(input.kind==="DISCOVERED_ARTIFACT"){suffix=[];contentType=input.contentType}else if(input.kind==="AUDIO"||input.kind==="AUDIO_WAV"){suffix=["audio",input.purpose,"versions",input.versionId,"export"];contentType="audio/wav"}else if("versionId"in input){suffix=["captions","versions",input.versionId,"export"];contentType=(input.kind==="CAPTION"?input.format==="JSON":input.kind==="CAPTION_JSON")?"application/json":"application/x-subrip"}else if("evidenceId"in input){const kind=input.kind==="TEMPORAL_FRAME"?"FRAME":input.kind==="TEMPORAL_SHEET"?"SHEET":"MANIFEST";if(!TemporalEvidenceMediaSchema.safeParse({tenantId,productionId:input.productionId,evidenceId:input.evidenceId,kind,...input.kind==="TEMPORAL_FRAME"?{ordinal:input.ordinal}:{}}).success)sdkInputError();suffix=["temporal-evidence",input.evidenceId,"media",kind];contentType=kind==="MANIFEST"?"application/json":"image/png"}else if("generationId"in input){suffix=["video-generations",input.generationId,input.kind==="VIDEO_GENERATION"?"media":"poster"];contentType=input.kind==="VIDEO_GENERATION"?"video/mp4":"image/png"}else if(input.kind==="DELIVERED_VIDEO"){suffix=["deliveries","media"];contentType="video/mp4"}else if(input.kind==="CODE_VIDEO"){suffix=["compositions","renders",input.renderId,"media"];contentType="video/mp4"}else if(input.kind==="DELIVERY_MANIFEST"){suffix=["deliveries","manifests",input.manifestId,"download"];contentType="application/json"}else{const poster2=input.kind.endsWith("POSTER");suffix=[input.kind.startsWith("ROUGH_CUT")?"rough-cuts":"final-renders",input.renderId,poster2?"poster":"media"];contentType=poster2?"image/png":"video/mp4"}const result=await transport.binary({method:"GET",tenantId,path:input.kind==="DISCOVERED_ARTIFACT"?path("projects",input.projectId,"artifacts",input.artifactId,"representations",input.representationId,"media"):path("productions",input.productionId,...suffix),...input.kind==="TEMPORAL_FRAME"?{query:{ordinal:input.ordinal}}:{},...input.kind==="CAPTION"?{query:{format:input.format}}:{},...input.kind==="CAPTION_JSON"||input.kind==="CAPTION_SRT"?{query:{format:input.kind==="CAPTION_JSON"?"JSON":"SRT"}}:{}},[contentType],Math.min(identity6.data.byteSize??128*1024*1024,input.kind==="AUDIO"||input.kind==="AUDIO_WAV"?12582912:input.kind.startsWith("CAPTION")?131072:128*1024*1024),options);const checksumSha256=createHash11("sha256").update(result.bytes).digest("hex");if(checksumSha256!==identity6.data.checksumSha256||identity6.data.byteSize!==void 0&&result.bytes.byteLength!==identity6.data.byteSize||result.etag&&result.etag!==`"${checksumSha256}"`)throw new NativeStudioSdkError("MEDIA_IDENTITY_MISMATCH","INTERNAL_OPERATIONAL_FAILURE","NO_WRITE");return{...result,checksumSha256}}var identity5=TenantMediaDownloadSchema.extend({checksumSha256:LocalDigestSchema,byteSize:MediaObjectVersionSchema.shape.byteSize});async function readImmutableMedia(transport,tenantId,raw,options={}){if(!raw||Object.hasOwn(raw,"tenantId"))sdkInputError();const input=identity5.safeParse({...raw,tenantId});if(!input.success)sdkInputError();const{checksumSha256,byteSize,...scope8}=input.data;const timeout=AbortSignal.timeout(12e4);const signal=options.signal?AbortSignal.any([options.signal,timeout]):timeout;const ticket=await transport.json({method:"POST",readOnly:true,tenantId,path:tenantMediaDownloadPath,body:scope8},MediaObjectTicketSchema,{signal});if(ticket.method!=="GET"||ticket.object.tenantId!==scope8.tenantId||ticket.object.projectId!==scope8.projectId||ticket.object.checksumSha256!==checksumSha256||ticket.object.byteSize!==byteSize)throw new NativeStudioSdkError("MEDIA_IDENTITY_MISMATCH","INTERNAL_OPERATIONAL_FAILURE","NO_WRITE");return{...await downloadImmutableObject(ticket,{signal}),representationId:scope8.representationId}}var nativeFailureCodes=new Set([...NativeToolAuthorityFailureSchema.shape.error.shape.code.options,...FederationFailureCodeSchema.options,"REQUEST_CONFLICT","HOST_UNAVAILABLE","CREDENTIAL_UNAVAILABLE","CREDENTIAL_SCOPE_MISMATCH","BINDING_REVOKED","UNAUTHENTICATED","FORBIDDEN","NOT_FOUND","INVALID_INPUT","REVISION_CONFLICT","STALE_BASIS","BLOCKED","CAPABILITY_UNAVAILABLE","DEVICE_UNAVAILABLE","CAPABILITY_VERSION_MISMATCH","PROVIDER_UNAVAILABLE","BUDGET_BLOCKED","CANCELLED","SUPERSEDED","INTERNAL_OPERATIONAL_FAILURE","IDEMPOTENCY_CONFLICT","CONTINUITY_CONFLICT","INPUT_UNAVAILABLE","AUDIO_UNAVAILABLE","CAPTION_UNAVAILABLE","TEST_EVIDENCE_DENIED","CONFLICT","INVALID_MEDIA","LEASE_LOST","SOURCE_UNAVAILABLE","TOOL_AUTHORITY_UNAVAILABLE","ACTIVE_EXECUTION_EXISTS","BINDING_UNAVAILABLE","PROVIDER_CAPABILITY_UNAVAILABLE","REPLAY_EXHAUSTED","RESYNC_REQUIRED"]);var statuses={400:["INVALID_INPUT"],413:["INVALID_INPUT"],415:["INVALID_INPUT"],401:["BLOCKED"],403:["BLOCKED"],404:["NOT_FOUND"],409:["REVISION_CONFLICT","STALE_BASIS","BLOCKED","CAPABILITY_UNAVAILABLE","BUDGET_BLOCKED","CANCELLED","SUPERSEDED"],422:["INVALID_INPUT"],429:["BUDGET_BLOCKED","PROVIDER_UNAVAILABLE"]};function failureOutcome(write2,status,declared){if(!write2)return"NO_WRITE";if(declared==="NO_WRITE"||declared==="UNKNOWN"||declared==="REJECTED")return declared;return["INVALID_INPUT","NOT_FOUND","BLOCKED","REVISION_CONFLICT","STALE_BASIS","BUDGET_BLOCKED"].includes(status)?"REJECTED":"UNKNOWN"}async function nativeFailure(response,signal){try{if(response.headers.get("content-type")?.split(";")[0]?.trim()!=="application/json")return null;const bytes=await boundedResponseBytes(response,64*1024,signal);const raw=JSON.parse(new TextDecoder("utf-8",{fatal:true}).decode(bytes));if(!raw||typeof raw!=="object"||Array.isArray(raw))return null;const record=raw;const status=InterfaceSemanticStatusSchema.safeParse(record.semanticStatus);if(!status.success||!(statuses[response.status]??(response.status>=500?["INTERNAL_OPERATIONAL_FAILURE","PROVIDER_UNAVAILABLE","CAPABILITY_UNAVAILABLE"]:[])).includes(status.data))return null;const error=record.error;const code=error?.code;const mismatch2=capabilityMismatch(code,status.data,error?.details);const known=typeof code==="string"&&nativeFailureCodes.has(code)&&(code!=="CAPABILITY_VERSION_MISMATCH"||!!mismatch2);return{semanticStatus:status.data,code:known?code:status.data,mismatch:mismatch2,outcome:error&&typeof error==="object"&&!Array.isArray(error)&&(known||error.outcome==="UNKNOWN")?error.outcome:void 0}}catch{return null}finally{void response.body?.cancel().catch(()=>{})}}function capabilityMismatch(code,status,detail){if(code==="CAPABILITY_VERSION_MISMATCH"&&status==="CAPABILITY_UNAVAILABLE")return CapabilityVersionMismatchSchema.safeParse(detail).data}var NativeStudioHttpTransport=class{constructor(config){this.config=config;try{this.origin=new URL(config.baseUrl);if(this.origin.username||this.origin.password||this.origin.search||this.origin.hash||this.origin.pathname!=="/"||this.origin.protocol!=="https:"&&!(this.origin.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(this.origin.hostname)))sdkInputError()}catch{sdkInputError()}this.timeout=config.timeoutMs??3e4;this.jsonLimit=config.maxJsonBytes??18*1024*1024;if(!Number.isSafeInteger(this.timeout)||this.timeout<1||this.timeout>3e5||!Number.isSafeInteger(this.jsonLimit)||this.jsonLimit<1024||this.jsonLimit>32*1024*1024)sdkInputError()}config;origin;timeout;jsonLimit;async response(request,options){const write2=request.method==="POST"&&!request.readOnly;if(!request.path.startsWith("/v1/")||request.path.includes("?")||request.path.includes("#")||request.path.includes(".."))sdkInputError();const url=new URL(request.path,this.origin);if(url.origin!==this.origin.origin||!url.pathname.startsWith("/v1/")||!["GET","POST"].includes(request.method)||!TenantIdSchema.safeParse(request.tenantId).success)sdkInputError();for(const[key10,value2]of Object.entries(request.query??{}))if(value2!==void 0)url.searchParams.set(key10,String(value2));let body;try{if(request.importedVideo){const v=request.importedVideo;if(request.method!=="POST"||request.body!==void 0||!/^\/v1\/productions\/[a-f0-9-]{36}\/imported-visuals\/originals\/bytes$/i.test(request.path)||!(v.bytes instanceof Uint8Array)||v.bytes.length<32||v.bytes.length>128*1024*1024||!/^[A-Za-z0-9_-]+$/.test(v.metadata)||v.metadata.length>8192)sdkInputError();body=new Uint8Array(v.bytes)}else body=request.body===void 0?void 0:JSON.stringify(request.body);if(typeof body==="string"&&new TextEncoder().encode(body).byteLength>18*1024*1024)sdkInputError()}catch{sdkInputError()}const timeout=AbortSignal.timeout(this.timeout);const signal=options.signal?AbortSignal.any([options.signal,timeout]):timeout;if(signal.aborted)throw new NativeStudioSdkError("REQUEST_ABORTED","BLOCKED","NO_WRITE");let authorization;if(request.authentication==="runtime-proof"){if(request.method!=="POST"||!/^\/v1\/projects\/[0-9a-f-]{36}\/(?:native-tool-grants\/[0-9a-f-]{36}\/(?:proof|status)|productions\/[0-9a-f-]{36}\/native-tool-credentials\/exchange)$/.test(request.path))sdkInputError()}else{try{authorization=await abortable(Promise.resolve().then(()=>this.config.authorization(signal)),signal)}catch{throw new NativeStudioSdkError(signal.aborted?"REQUEST_ABORTED":"UNAUTHENTICATED","BLOCKED","NO_WRITE")}if(typeof authorization!=="string"||!/^Bearer [A-Za-z0-9._~+/-]+={0,2}$/.test(authorization)||authorization.length>16384)throw new NativeStudioSdkError("UNAUTHENTICATED","BLOCKED","NO_WRITE")}if(signal.aborted)throw new NativeStudioSdkError("REQUEST_ABORTED","BLOCKED","NO_WRITE");try{const pending=Promise.resolve().then(()=>(this.config.fetch??fetch)(url,{method:request.method,redirect:"error",cache:"no-store",signal,headers:{...authorization===void 0?{}:{authorization},"x-native-tenant-id":request.tenantId,accept:"application/json",...request.body===void 0?{}:{"content-type":"application/json"},...request.importedVideo?{"content-type":"video/mp4","x-native-import-metadata":request.importedVideo.metadata}:{}},...body===void 0?{}:{body}}));void pending.then(late=>{if(signal.aborted)void late.body?.cancel().catch(()=>{})},()=>{});const response=await abortable(pending,signal);if(!response.ok){const status=response.status;const native=await nativeFailure(response,signal);const code=status===401?"UNAUTHENTICATED":status===403?"FORBIDDEN":status===404?"NOT_FOUND":status===400||status===413||status===415||status===422?"INVALID_INPUT":status===409?"REVISION_CONFLICT":"HTTP_FAILURE";const semanticStatus=status===401||status===403?"BLOCKED":status===404?"NOT_FOUND":status===400||status===413||status===415||status===422?"INVALID_INPUT":status===409?"REVISION_CONFLICT":"INTERNAL_OPERATIONAL_FAILURE";throw new NativeStudioSdkError(native?.code??code,native?.semanticStatus??semanticStatus,failureOutcome(write2,native?.semanticStatus??semanticStatus,native?.outcome),status,[],native?.mismatch)}return{response,signal}}catch(error){if(error instanceof NativeStudioSdkError)throw error;throw new NativeStudioSdkError(write2?"OUTCOME_UNKNOWN":signal.aborted?"REQUEST_ABORTED":"TRANSPORT_UNAVAILABLE","INTERNAL_OPERATIONAL_FAILURE",write2?"UNKNOWN":"NO_WRITE")}}async json(request,schema,options={}){const limit=options.maxJsonBytes??this.jsonLimit;if(!Number.isSafeInteger(limit)||limit<1024||limit>this.jsonLimit)sdkInputError();const{response,signal}=await this.response(request,options);try{const contentType=response.headers.get("content-type")?.split(";")[0]?.trim();if(contentType!=="application/json"){void response.body?.cancel().catch(()=>{});throw new Error}const bytes=await boundedResponseBytes(response,limit,signal);return schema.parse(JSON.parse(new TextDecoder("utf-8",{fatal:true}).decode(bytes)))}catch(error){if(error instanceof NativeStudioSdkError)throw new NativeStudioSdkError(error.code,error.semanticStatus,request.method==="POST"&&!request.readOnly?"UNKNOWN":"NO_WRITE",error.status);throw new NativeStudioSdkError("RESPONSE_INVALID","INTERNAL_OPERATIONAL_FAILURE",request.method==="POST"&&!request.readOnly?"UNKNOWN":"NO_WRITE")}}async binary(request,contentTypes,limit,options={}){if(request.method!=="GET"||!Number.isSafeInteger(limit)||limit<1||limit>128*1024*1024)sdkInputError();const{response,signal}=await this.response(request,options);const contentType=response.headers.get("content-type")?.split(";")[0]?.trim()??"";if(!contentTypes.includes(contentType)){await response.body?.cancel().catch(()=>{});throw new NativeStudioSdkError("RESPONSE_INVALID","INTERNAL_OPERATIONAL_FAILURE","NO_WRITE")}try{return{bytes:await boundedResponseBytes(response,limit,signal),contentType,etag:response.headers.get("etag")}}catch(error){throw new NativeStudioSdkError(error instanceof NativeStudioSdkError?error.code:signal.aborted?"REQUEST_ABORTED":"RESPONSE_INVALID","INTERNAL_OPERATIONAL_FAILURE","NO_WRITE")}}};var sdkOperations=Object.freeze({...coreOperations,...deviceManagementOperations,...deviceLibraryOperations,...navigationOperations,...discoveryOperations,...agentHostOperations,...agentHostExecutionOperations,...nativeToolAuthorityOperations,...compositionOperations,...assemblyOperations,...editorOperations,...reviewerOperations,...repairStrategyOperations,...canonicalRepairOperations,...programmaticReviewOperations,...compositionSourceOperations,...programmaticExplorationOperations,...deliveryOperations,...shotPreparationOperations,...generationOperations,...keyframeReviewOperations,...videoReviewOperations,...providerOperations,...speechOperations,...voiceProfileOperations,...shareOperations,...voiceReviewOperations,...observationOperations,...soundMakingPlanOperations,...lifecycleEventOperations,...federationOperations,...temporalEvidenceOperations,...audioCaptionOperations,...planningIntelligenceOperations,...importedVisualOperations,...sourceSyncOperations,...visualExplorationOperations,...referencePreviewOperations,...mediaDescriptorOperations,...seriesStandardOperations,...enterpriseBrandOperations});var NativeStudioAgentClient=class{deviceRenders=new NativeStudioDeviceRenders(this);navigation=new NativeStudioNavigationFacade(this);tenantId;directSources;transport;constructor(config){const tenant2=TenantIdSchema.safeParse(config.tenantId);if(!tenant2.success)sdkInputError();this.tenantId=tenant2.data.toLowerCase();this.transport=new NativeStudioHttpTransport(config);this.directSources=new NativeStudioDirectSources(this.tenantId,this.transport)}async call(key10,raw,options={}){if(!Object.hasOwn(sdkOperations,key10)||!raw||typeof raw!=="object"||Array.isArray(raw))sdkInputError();if(raw.tenantId!==void 0&&(typeof raw.tenantId!=="string"||raw.tenantId.toLowerCase()!==this.tenantId))sdkInputError();const spec=sdkOperations[key10];if(spec.request===null)throw new NativeStudioSdkError("CAPABILITY_UNAVAILABLE","CAPABILITY_UNAVAILABLE","NO_WRITE");const parsed=spec.input.safeParse({...raw,tenantId:this.tenantId});if(!parsed.success)sdkInputError(inputIssues(parsed.error,spec.input));if((key10==="rough-cut.start"||key10==="final-render.start")&&"deviceExecution"in parsed.data&&DeviceRenderTargetSchema.safeParse(parsed.data.deviceExecution).data?.validationMode){try{const advertised=await this.transport.json({method:"GET",tenantId:this.tenantId,path:path("local-execution","tenant-media","capabilities")},TenantMediaCapabilitySchema,options);if(advertised.tenantId!==this.tenantId)throw Error()}catch{throw new NativeStudioSdkError("CAPABILITY_UNAVAILABLE","BLOCKED","NO_WRITE")}}const request=spec.request(parsed.data);const result=await this.transport.json({...request,readOnly:spec.readOnly},spec.output,options);assertManagementReceipt(key10,parsed.data,result);assertResponseBindings(result,parsed.data,spec.identity,spec.readOnly?"GET":request.method,spec.expectedPath?spec.expectedPath(parsed.data,result):void 0,spec.identityWhenPresent);assertSeriesResponseVersions(key10,parsed.data,result);assertEnterpriseBrandResponse(key10,parsed.data,result);if(key10==="temporal-evidence.read-video")assertOriginalVideoBytes(result);if(key10==="reference-preview.get")assertPreviewBytes(result);if(key10==="source-sync.audio"||key10==="audio.export"||key10==="caption.export")assertExportBytes(result,key10==="caption.export"&&"format"in parsed.data?String(parsed.data.format):void 0);return result}async sourceMedia(raw,options={},expected){if(Object.hasOwn(raw,"tenantId"))sdkInputError();const parsed=SourceLibraryMediaSchema.safeParse({...raw,tenantId:this.tenantId});if(!parsed.success)sdkInputError();const input=parsed.data;const result=await this.transport.binary({method:"GET",tenantId:this.tenantId,path:path("projects",input.projectId,"source-artifacts",input.artifactId,"media")},["image/png","image/jpeg","image/webp","text/plain","application/json"],8*1024*1024,options);const checksumSha256=createHash12("sha256").update(result.bytes).digest("hex");if(result.etag&&result.etag!==`"${checksumSha256}"`||expected&&(expected.checksumSha256!==checksumSha256||expected.byteSize!==result.bytes.byteLength))throw new NativeStudioSdkError("MEDIA_IDENTITY_MISMATCH","INTERNAL_OPERATIONAL_FAILURE","NO_WRITE");return{...result,checksumSha256}}media(input,expected,options={}){return readNativeMedia(this.transport,this.tenantId,input,expected,options)}immutableMedia(input,options={}){return readImmutableMedia(this.transport,this.tenantId,input,options)}async keyframeMedia(raw,expected,options={}){if(!raw||Object.hasOwn(raw,"tenantId")||!/^[a-f0-9]{64}$/.test(expected?.checksumSha256??"")||expected?.byteSize!==void 0&&(!Number.isSafeInteger(expected.byteSize)||expected.byteSize<1||expected.byteSize>8*1024*1024))sdkInputError();const parsed=KeyframeGetInputSchema.safeParse({...raw,tenantId:this.tenantId});if(!parsed.success)sdkInputError();const i=parsed.data,value2=await this.transport.json({method:"GET",tenantId:this.tenantId,path:path("productions",i.productionId,"keyframe-generations",i.generationId,"media")},KeyframeMediaSchema,options);const bytes=Buffer.from(value2.contentBase64,"base64"),checksumSha256=createHash12("sha256").update(bytes).digest("hex");if(bytes.toString("base64")!==value2.contentBase64||bytes.length!==value2.byteSize||checksumSha256!==value2.checksumSha256||checksumSha256!==expected.checksumSha256||expected.byteSize!==void 0&&bytes.length!==expected.byteSize)throw new NativeStudioSdkError("MEDIA_IDENTITY_MISMATCH","INTERNAL_OPERATIONAL_FAILURE","NO_WRITE");return{bytes,checksumSha256,contentType:value2.contentType}}};function schemaNode(value2,root){if(root.$schema!==void 0&&root.$schema!=="https://json-schema.org/draft/2020-12/schema")return null;const seen=new Set;const scoped=node=>["$id","$anchor","$dynamicAnchor","$dynamicRef","$recursiveAnchor","$recursiveRef","$vocabulary"].some(key10=>key10 in node);while(value2&&typeof value2==="object"&&!Array.isArray(value2)){const node=value2;if(scoped(node))return null;if("$ref"in node&&typeof node.$ref!=="string")return null;if(typeof node.$ref!=="string")return node;if(seen.has(value2)||!node.$ref.startsWith("#/"))return null;seen.add(value2);let target3=root;for(const part of node.$ref.slice(2).split("/")){const key10=part.replaceAll("~1","/").replaceAll("~0","~");if(!target3||typeof target3!=="object"||!Object.hasOwn(target3,key10))return null;if(scoped(target3))return null;target3=target3[key10]}value2=target3}return null}import{z as z206}from"zod";var definitions=new WeakMap;function inputDefinition(name2,input){let names=definitions.get(input);if(!names){names=new Map;definitions.set(input,names)}let definition=names.get(name2);if(!definition){try{definition={name:name2,inputSchema:z206.toJSONSchema(input,{io:"input",reused:"ref"})};if(Buffer.byteLength(JSON.stringify(definition))>160*1024)throw Error()}catch{throw new NativeStudioSdkError("CAPABILITY_UNAVAILABLE","BLOCKED","NO_WRITE")}names.set(name2,definition)}return definition}import{createHash as createHash13}from"node:crypto";import{z as z207}from"zod";var Input=z207.discriminatedUnion("kind",[KeyframeGetInputSchema.extend({kind:z207.literal("KEYFRAME")}),VideoGetInputSchema.extend({kind:z207.literal("VIDEO_POSTER")}),RoughCutGetSchema.extend({kind:z207.enum(["ROUGH_CUT_POSTER","FINAL_POSTER"])})]);var sdkImageMediaTools={KEYFRAME:"keyframe_media",VIDEO_POSTER:"video_poster",ROUGH_CUT_POSTER:"rough_cut_poster",FINAL_POSTER:"final_render_poster"};var Identity=z207.strictObject({checksumSha256:z207.string().regex(/^[0-9a-f]{64}$/),byteSize:z207.int().positive().max(16*1024*1024).optional()});var Metadata=KeyframeMediaSchema.omit({contentBase64:true});async function readMcpImageMedia(config,raw,expected,options){if(!raw||raw.tenantId!==void 0&&(typeof raw.tenantId!=="string"||raw.tenantId.toLowerCase()!==config.tenantId))sdkInputError();const input=Input.safeParse({...raw,tenantId:config.tenantId}),identity6=Identity.safeParse(expected);if(!input.success||!identity6.success)sdkInputError();const{kind,...argumentsInput}=input.data;const timeout=AbortSignal.timeout(config.timeoutMs),signal=options.signal?AbortSignal.any([timeout,options.signal]):timeout;if(signal.aborted)throw new NativeStudioSdkError("REQUEST_ABORTED","BLOCKED","NO_WRITE");let response;try{response=await abortable(config.client.callTool({name:sdkImageMediaTools[kind],arguments:argumentsInput},{signal,timeout:config.timeoutMs,nativeReadOnly:true}),signal)}catch{throw new NativeStudioSdkError(signal.aborted?"REQUEST_ABORTED":"TRANSPORT_UNAVAILABLE","INTERNAL_OPERATIONAL_FAILURE","NO_WRITE")}try{if(Buffer.byteLength(JSON.stringify(response),"utf8")>config.maxJsonBytes)throw Error();const envelope=z207.object({semanticStatus:InterfaceSemanticStatusSchema,data:z207.unknown().optional(),error:z207.object({code:z207.string()}).optional()}).parse(response.structuredContent);if(response.isError||envelope.semanticStatus!=="SUCCESS"){const status=["SUCCESS","ACCEPTED"].includes(envelope.semanticStatus)?"INTERNAL_OPERATIONAL_FAILURE":envelope.semanticStatus;throw new NativeStudioSdkError(envelope.error&&nativeFailureCodes.has(envelope.error.code)?envelope.error.code:status,status,"NO_WRITE")}const metadata=Metadata.parse(envelope.data),images=response.content.filter(c=>c.type==="image");if(images.length!==1||response.content.length!==1)throw Error();const block=images[0],bytes=Buffer.from(block.data,"base64"),checksumSha256=createHash13("sha256").update(bytes).digest("hex");if(bytes.toString("base64")!==block.data||bytes.length!==metadata.byteSize||block.mimeType!==metadata.contentType||checksumSha256!==metadata.checksumSha256||checksumSha256!==identity6.data.checksumSha256||identity6.data.byteSize!==void 0&&bytes.length!==identity6.data.byteSize)throw new NativeStudioSdkError("MEDIA_IDENTITY_MISMATCH","INTERNAL_OPERATIONAL_FAILURE","NO_WRITE");return{...metadata,bytes}}catch(error){if(error instanceof NativeStudioSdkError)throw error;throw new NativeStudioSdkError("RESPONSE_INVALID","INTERNAL_OPERATIONAL_FAILURE","NO_WRITE")}}var sdkMcpTools=Object.freeze({"series.list":"series_list","series.get":"series_get","series.publish":"series_publish","series.bind":"series_bind","series.binding":"series_binding","series.receipt":"series_receipt","series.brand.command":"series_brand_command","series.brand.get":"series_brand_get","series.brand.receipt":"series_brand_receipt","series.canon.record":"series_canon_record","series.canon.get":"series_canon_get","series.canon.receipt":"series_canon_receipt","series.improvement.command":"series_improvement_command","series.improvement.query":"series_improvement_query","series.improvement.receipt":"series_improvement_receipt","federation.link.receiver":"federation_link_receiver","federation.link.targets":"federation_link_targets","federation.link.start":"federation_link_start","federation.link.get":"federation_link_get","federation.link.confirm":"federation_link_confirm","federation.link.cancel":"federation_link_cancel","federation.delivery.inspect":"federation_delivery_inspect","federation.receipt-inbound.configure":"federation_receipt_inbound_configure","federation.receipt-inbound.contract":"federation_receipt_inbound_contract","federation.receipt-inbound.handoff":"federation_receipt_inbound_handoff","federation.receipt-inbound.catalog":"federation_receipt_inbound_catalog","federation.receipt-inbound.query":"federation_receipt_inbound_query","federation.receipt-inbound.command":"federation_receipt_inbound_command","federation.catalog":"federation_catalog","federation.observe":"federation_observe","federation.result.reference":"federation_result_reference","federation.result.read":"federation_result_read","federation.receipt-route.configure":"federation_receipt_route_configure","federation.receipt.query":"federation_receipt_query","federation.receipt.command":"federation_receipt_command","federation.receipt.recover":"federation_receipt_recover","federation.subscription.handoff":"federation_subscription_handoff","federation.subscription.contract":"federation_subscription_contract","federation.inbound.catalog":"federation_inbound_catalog","federation.inbound.configure":"federation_inbound_configure","federation.inbound.query":"federation_inbound_query","federation.inbound.receipt":"federation_inbound_receipt","federation.inbound.replay":"federation_inbound_replay","federation.recover":"federation_recover","federation.route.configure":"federation_route_configure","federation.subscription.set":"federation_subscription_set","federation.subscription.get":"federation_subscription_get","federation.query":"federation_query","federation.receipt":"federation_receipt","workspace.devices.list":"workspace_devices_list","device.status":"device_status","device.enroll":"device_enroll","device.enrollment.issue":"device_enrollment_issue","device.enrollment.lookup":"device_enrollment_lookup","device.revoke":"device_revoke","device.management-receipt":"device_management_receipt","workspace.get":"workspace_get","workspace.caller":"workspace_caller","workspace.status":"workspace_status","workspace.query":"workspace_query","device-library.query":"device_library_query","device-library.admit":"device_library_admit","device-library.receipt":"device_library_receipt","devices.list":"list_devices","studio.capability.groups":"studio_capability_groups","studio.capability.query":"studio_capability_query","studio.capability.invoke":"studio_capability_invoke","studio.start":"studio_start","studio.media.readiness":"studio_media_readiness","studio.capability.search":"studio_capability_search","studio.capability.describe":"studio_capability_describe","studio.navigate":"studio_navigate","sound-plan.context":"sound_plan_context","sound-plan.get":"sound_plan_get","sound-plan.validate":"sound_plan_validate","sound-plan.accept":"sound_plan_accept","media-observation.options":"media_observation_options","media-observation.start":"media_observation_start","media-observation.start-local":"media_observation_start_local","media-observation.get-local":"media_observation_get_local","media-observation.device.quote":"media_observation_device_quote","media-observation.device.start":"media_observation_device_start","media-observation.device.get":"media_observation_device_get","media-observation.get":"media_observation_get","media-observation.cancel":"media_observation_cancel","production-guidance.context":"production_guidance_context","speech.options":"speech_options","provider.model.get":"provider_model_get","speech.start":"speech_start","speech.device.quote":"speech_device_quote","speech.device.start":"speech_device_start","speech.start-local":"speech_start_local","speech.get-local":"speech_get_local","speech.get":"speech_get","speech.cancel":"speech_cancel","provider.model.query":"provider_model_catalog_query","provider.model.configure":"provider_model_configure","provider.model.disable":"provider_model_disable","artifact.query":"artifact_discovery_query","imported-visual.query":"imported_visual_query","imported-visual.start-from-source":"imported_visual_start_from_source","imported-visual.review.target":"imported_visual_review_target","imported-visual.review.record":"imported_visual_review","source-sync.review.target":"source_sync_review_target","source-sync.review.record":"source_sync_review","source-sync.review.get":"source_sync_review_get","temporal-evidence.read-video":"temporal_evidence_read_video","temporal-evidence.target":"temporal_evidence_target","temporal-evidence.start":"temporal_evidence_start","temporal-evidence.get":"temporal_evidence_get","temporal-evidence.cancel":"temporal_evidence_cancel","visual-sequence.register":"visual_sequence_register","visual-sequence.start-registration":"visual_sequence_start_registration","visual-sequence.get":"visual_sequence_get","visual-sequence.query":"visual_sequence_query","project.create":"project_create","production.create":"production_create","production.terminate":"production_terminate","project.query":"project_query","project.get":"project_get","source.query":"source_query","source.ingest":"source_ingest","source.text":"source_read","production.query":"production_query","production.snapshot":"production_snapshot","brief.accept":"brief_accept","story.accept":"story_accept","scene-shot-plan.accept":"scene_shot_plan_accept","story.query":"story_query","story.active":"story_active","scene-shot-plan.query":"scene_shot_plan_query","scene-shot-plan.active":"scene_shot_plan_active","operation.query":"operation_query","operation.get":"operation_get","agent-host.get":"agent_host_binding_get","agent-host.readiness":"agent_host_readiness","agent-host.history":"agent_host_binding_history","agent-host.configure":null,"agent-host.selection.update":"agent_host_selection_update","agent-host.revoke":"agent_host_binding_revoke","agent-host-execution.start":"agent_host_execution_start","agent-host.contract":"agent_host_contract","agent-host-execution.get":"agent_host_execution_get","agent-host-execution.query":"agent_host_execution_query","agent-host-execution.events":"agent_host_execution_events","agent-host-execution.dispatch":"agent_host_execution_dispatch","agent-host-execution.reconcile":"agent_host_execution_reconcile","agent-host-execution.legacy-release":"agent_host_execution_legacy_release","agent-host-execution.legacy-release.get":"agent_host_execution_legacy_release_get","agent-host-execution.cancel":"agent_host_execution_cancel","native-tool-grant.configure":"native_tool_grant_configure","native-tool-grant.get":"native_tool_grant_get","native-tool-grant.revoke":"native_tool_grant_revoke","composition.capabilities":"composition_capabilities","composition.brief":"composition_brief","composition.put-input":"composition_put_input","composition.making.validate":"composition_making_validate","composition.validate":"composition_validate","composition.create":"composition_create","composition.revise":"composition_revise","composition.get":"composition_get","composition.history":"composition_history","composition.render":"composition_render","composition.render.get":"composition_render_get","composition.render.query":"composition_render_query","composition.render.cancel":"composition_render_cancel","composition.sample":"composition_sample","composition.observe":"composition_observe","timeline.basis":"timeline_basis","timeline.build":"timeline_build","timeline.current":"timeline_current","timeline.get":"timeline_get","timeline.query":"timeline_query","rough-cut.start":"rough_cut_start","rough-cut.admission-receipt":"rough_cut_admission_receipt","rough-cut.get":"rough_cut_get","rough-cut.query":"rough_cut_query","rough-cut.cancel":"rough_cut_cancel","rough-cut.media-ticket":"rough_cut_media_ticket","rough-cut.review.target":"rough_cut_review_target","rough-cut.review.record":"rough_cut_review_record","rough-cut.review.query":"rough_cut_review_query","rough-cut.finding.query":"rough_cut_finding_query","final-ready.get":"final_ready_get","final-ready.decide":"final_ready_decide","final-ready.revoke":"final_ready_revoke","final-ready.query":"final_ready_query","final-render.eligibility":"final_render_eligibility","final-render.start":"final_render_start","final-render.admission-receipt":"final_render_admission_receipt","final-render.get":"final_render_get","final-render.query":"final_render_query","final-render.cancel":"final_render_cancel","final-render.media-ticket":"final_render_media_ticket","editor.context":"editor_context","editor.validate":"editor_validate","reviewer.final-output-context":"reviewer_final_output_context","reviewer.context":"reviewer_context","reviewer.validate":"reviewer_proposal_validate","repair-strategy.review1.context":"repair_strategy_review1_context","repair-strategy.review1.validate":"repair_strategy_review1_validate","repair-strategy.context":"repair_strategy_context","repair-strategy.validate":"repair_strategy_validate","canonical-repair.author":"repair_author","canonical-repair.author-review1":"repair_author_review1","canonical-repair.proof-review1":"repair_proof_review1","canonical-repair.get":"repair_get","canonical-repair.execute":"repair_execute","canonical-repair.proof":"repair_proof","programmatic-review.target":"composition_review_target","programmatic-review.record":"composition_review_record","programmatic-review.query":"composition_review_query","programmatic-review.decide":"composition_acceptance_decide","composition.source.inspect":"composition_source_inspect","reviewer.source-context":"reviewer_source_context","exploration.programmatic.compare":"exploration_programmatic_compare","exploration.programmatic.recommendation.context":"exploration_programmatic_recommendation_context","exploration.programmatic.recommendation.validate":"exploration_programmatic_recommendation_validate","delivery.policy.configure":"delivery_configure","delivery.policy.get":"delivery_policy","delivery.snapshot":"delivery_snapshot","delivery.target":"delivery_target","delivery.start":"delivery_start","delivery.get":"delivery_get","delivery.approve":"delivery_approve","delivery.cancel":"delivery_cancel","delivery.manifest":"delivery_manifest","shot-preparation.prepare":"shot_prepare","shot-preparation.get":"shot_preparation_get","shot-preparation.active":"shot_preparation_active","shot-preparation.query":"shot_preparation_query","keyframe.start":"keyframe_start","keyframe.device.quote":"keyframe_device_quote","keyframe.device.start":"keyframe_device_start","keyframe.get":"keyframe_get","imported-visual.register-source":"imported_visual_register_source","imported-visual.register":"imported_visual_register","imported-visual.revise":"imported_visual_revise","imported-visual.original":"imported_visual_original","imported-visual.history":"imported_visual_history","imported-visual.normalize":"imported_visual_normalize","imported-visual.get":"imported_visual_get","imported-visual.decide":"imported_visual_decide","imported-visual.cancel":"imported_visual_cancel","source-sync.start":"source_sync_start","source-sync.get":"source_sync_get","source-sync.cancel":"source_sync_cancel","source-sync.version":"source_sync_version","exploration.context":"exploration_context","exploration.plan.validate":"exploration_plan_validate","exploration.compare":"exploration_compare","exploration.recommendation.context":"exploration_recommendation_context","exploration.recommendation.validate":"exploration_recommendation_validate","composition.render.media-target":"composition_render_media","delivery.download":"delivery_download","temporal-evidence.download":"temporal_evidence_download","video.options":"video_options","studio.capabilities":"studio_capabilities","reference-preview.start":"reference_preview_start","reference-preview.status":"reference_preview_status","reference-preview.get":"reference_preview_get","reference-preview.cancel":"reference_preview_cancel","brief.active":"brief_active","writer.validate":"writer_proposal_validate","director.context":"director_context","director.validate":"director_proposal_validate","consistency-profile.get":"consistency_profile_get","share.create":"share_create","share.get":"share_get","share.list":"share_list","share.revoke":"share_revoke","share.link":"share_link","share.receipt":"share_receipt","voice-profile.create":"voice_profile_create","voice-profile.revise":"voice_profile_revise","voice-profile.publish":"voice_profile_publish","voice-profile.set-enabled":"voice_profile_set_enabled","voice-profile.list":"voice_profile_list","voice-profile.get":"voice_profile_get","voice-profile.version":"voice_profile_version","voice-profile.set-reference":"voice_profile_set_reference","voice-profile.reference":"voice_profile_reference","voice-review.target":"voice_review_target","voice-review.record":"voice_review_record","voice-review.get":"voice_review_get","consistency-profile.version":"consistency_profile_version","consistency-profile.configure":"consistency_profile_configure","audio.export":"audio_export","caption.export":"caption_export","source-sync.audio":"source_sync_audio","audio.basis":"audio_basis","audio.current":"audio_current","audio.get":"audio_get","audio.query":"audio_query","audio.import":"audio_import","caption.basis":"caption_basis","caption.current":"caption_current","caption.get":"caption_get","caption.query":"caption_query","caption.author":"caption_author","caption.transcript_draft":"caption_transcript_draft","caption.author_transcript":"caption_author_transcript","keyframe.query":"keyframe_query","keyframe.cancel":"keyframe_cancel","video.start":"video_start","video.device.quote":"video_device_quote","video.device.start":"video_device_start","video.get":"video_get","video.query":"video_query","video.cancel":"video_cancel","keyframe-review.target":"keyframe_review_target","keyframe-review.record":"keyframe_review_record","keyframe-review.query":"keyframe_review_query","keyframe-review.decide":"keyframe_reference_decide","keyframe-reference.get":"keyframe_reference_get","keyframe-reference.query":"keyframe_reference_query","keyframe-reference.revoke":"keyframe_reference_revoke","video-review.target":"video_review_target","video-review.record":"video_review_record","video-review.query":"video_review_query","video-review.decide":"shot_acceptance_decide","shot-acceptance.get":"shot_acceptance_get","shot-acceptance.query":"shot_acceptance_query","shot-acceptance.revoke":"shot_acceptance_revoke","provider.configure":null,"provider.query":"provider_connection_query","provider.models":"provider_model_query","provider.keyframe-default.set":"provider_keyframe_default_set","provider.disable":"provider_connection_disable","provider.revoke":"provider_credential_revoke","webhook.configure":null,"webhook.secret.prepare":null,"webhook.configure-reference":"webhook_configure","webhook.disable":"webhook_disable","webhook.replay":"webhook_replay","production.feedback":"production_feedback","production.events.read":"production_events_read","lifecycle-event.capabilities":"lifecycle_events_capabilities","lifecycle-event.subscriptions":"lifecycle_events_query","lifecycle-event.events":"lifecycle_events_query","lifecycle-event.deliveries":"lifecycle_events_query","lifecycle-event.attempts":"lifecycle_events_query"});var nestedScope=new Set(["writer.validate","exploration.context","exploration.plan.validate","exploration.compare","exploration.recommendation.context","exploration.recommendation.validate","director.validate","editor.context","editor.validate","reviewer.final-output-context","reviewer.context","reviewer.validate","reviewer.source-context","repair-strategy.context","repair-strategy.validate","repair-strategy.review1.validate","exploration.programmatic.compare","exploration.programmatic.recommendation.context","exploration.programmatic.recommendation.validate","canonical-repair.author"]);var projectInPath=new Set(["canonical-repair.proof-review1","canonical-repair.get","canonical-repair.execute","canonical-repair.proof"]);function sdkMcpInput(key10,input){return Object.fromEntries(Object.entries(input).filter(([k])=>!(k==="tenantId"&&nestedScope.has(key10))&&!(k==="projectId"&&projectInPath.has(key10))))}import{createHash as createHash14}from"node:crypto";import{z as z208}from"zod";var expectedSchema=z208.strictObject({checksumSha256:z208.string().regex(/^[a-f0-9]{64}$/),byteSize:z208.int().positive().max(16*1024*1024).optional()});async function readMcpEvidenceImage(config,raw,expected,options){if(!raw||raw.tenantId!==void 0&&(typeof raw.tenantId!=="string"||raw.tenantId.toLowerCase()!==config.tenantId))sdkInputError();const input=TemporalEvidenceImageSchema.safeParse({...raw,tenantId:config.tenantId}),identity6=expectedSchema.safeParse({checksumSha256:expected?.checksumSha256,byteSize:expected?.byteSize});if(!input.success||!identity6.success)sdkInputError();const deadline=AbortSignal.timeout(config.timeoutMs),signal=options.signal?AbortSignal.any([options.signal,deadline]):deadline;if(signal.aborted)throw new NativeStudioSdkError("REQUEST_ABORTED","BLOCKED","NO_WRITE");let reply2;try{reply2=await abortable(config.client.callTool({name:"temporal_evidence_read_image",arguments:input.data},{signal,timeout:config.timeoutMs,nativeReadOnly:true}),signal)}catch{throw new NativeStudioSdkError(signal.aborted?"REQUEST_ABORTED":"TRANSPORT_UNAVAILABLE","INTERNAL_OPERATIONAL_FAILURE","NO_WRITE")}try{if(Buffer.byteLength(JSON.stringify(reply2),"utf8")>config.maxJsonBytes)throw Error();const texts=reply2.content.filter(block2=>block2.type==="text"),images=reply2.content.filter(block2=>block2.type==="image");const carrier=reply2.structuredContent!==void 0?reply2.structuredContent:texts.length===1?JSON.parse(texts[0].text):void 0;const envelope=z208.object({semanticStatus:InterfaceSemanticStatusSchema,data:z208.unknown().optional(),error:z208.object({code:z208.string()}).optional()}).parse(carrier);if(reply2.isError)throw new NativeStudioSdkError(envelope.error&&nativeFailureCodes.has(envelope.error.code)?envelope.error.code:envelope.semanticStatus,envelope.semanticStatus==="SUCCESS"||envelope.semanticStatus==="ACCEPTED"?"INTERNAL_OPERATIONAL_FAILURE":envelope.semanticStatus,"REJECTED");if(envelope.semanticStatus!=="SUCCESS"||images.length!==1||(reply2.structuredContent!==void 0?reply2.content.length!==1||texts.length!==0:reply2.content.length!==2||texts.length!==1))throw Error();const metadata=TemporalEvidenceImageMetadataSchema.parse(envelope.data);assertResponseBindings(metadata,input.data,[["evidenceId","evidenceId"],["kind","kind"],["ordinal","ordinal"]],"GET");const block=images[0],bytes=Buffer.from(block.data,"base64"),checksumSha256=createHash14("sha256").update(bytes).digest("hex");if(block.mimeType!==metadata.contentType||bytes.toString("base64")!==block.data||bytes.byteLength!==metadata.byteSize||checksumSha256!==metadata.checksumSha256||checksumSha256!==identity6.data.checksumSha256||identity6.data.byteSize!==void 0&&bytes.byteLength!==identity6.data.byteSize)throw new NativeStudioSdkError("MEDIA_IDENTITY_MISMATCH","INTERNAL_OPERATIONAL_FAILURE","NO_WRITE");return{...metadata,bytes}}catch(e){if(e instanceof NativeStudioSdkError)throw e;throw new NativeStudioSdkError("RESPONSE_INVALID","INTERNAL_OPERATIONAL_FAILURE","NO_WRITE")}}import{createHash as createHash15}from"node:crypto";import{z as z209}from"zod";var inputSchema=z209.discriminatedUnion("kind",[AudioGetSchema.extend({kind:z209.literal("AUDIO_WAV")}),CaptionGetSchema.extend({kind:z209.enum(["CAPTION_JSON","CAPTION_SRT"])}),SourceSyncAudioGetSchema.extend({kind:z209.literal("SOURCE_SYNC_WAV")})]);var expectedSchema2=z209.strictObject({checksumSha256:z209.string().regex(/^[0-9a-f]{64}$/),byteSize:z209.int().positive().max(12582912).optional()});var outputSchema=z209.strictObject({semanticStatus:z209.literal("SUCCESS"),data:z209.strictObject({contentType:z209.enum(["audio/wav","application/json","application/x-subrip"]),checksumSha256:z209.string().regex(/^[0-9a-f]{64}$/),representationId:z209.uuid().optional(),byteSize:z209.int().positive().max(12582912).optional(),contentBase64:z209.string().max(16777216).optional(),text:z209.string().max(131072).optional()})});async function readMcpAuxiliaryMedia(config,raw,expected,options){if(!raw||raw.tenantId!==void 0&&(typeof raw.tenantId!=="string"||raw.tenantId.toLowerCase()!==config.tenantId))sdkInputError();const parsed=inputSchema.safeParse({...raw,tenantId:config.tenantId}),identity6=expectedSchema2.safeParse(expected);if(!parsed.success||!identity6.success)sdkInputError();const{kind,...arguments_}=parsed.data;const name2=kind==="AUDIO_WAV"?"audio_export":kind==="SOURCE_SYNC_WAV"?"source_sync_audio":"caption_export";const contentType=kind.endsWith("WAV")?"audio/wav":kind==="CAPTION_JSON"?"application/json":"application/x-subrip";const deadline=AbortSignal.timeout(config.timeoutMs),signal=options.signal?AbortSignal.any([options.signal,deadline]):deadline;if(signal.aborted)throw new NativeStudioSdkError("REQUEST_ABORTED","BLOCKED","NO_WRITE");let reply2;try{reply2=await abortable(config.client.callTool({name:name2,arguments:{...arguments_,...kind.startsWith("CAPTION")?{format:kind==="CAPTION_JSON"?"JSON":"SRT"}:{}}},{signal,timeout:config.timeoutMs,nativeReadOnly:true}),signal)}catch{throw new NativeStudioSdkError(signal.aborted?"REQUEST_ABORTED":"TRANSPORT_UNAVAILABLE","INTERNAL_OPERATIONAL_FAILURE","NO_WRITE")}try{if(Buffer.byteLength(JSON.stringify(reply2),"utf8")>config.maxJsonBytes||reply2.isError)throw Error();const texts=reply2.content.filter(x=>x.type==="text");const result=outputSchema.parse(reply2.structuredContent??(texts.length===1?JSON.parse(texts[0].text):void 0)).data;const wav=contentType==="audio/wav";if(result.contentType!==contentType||(wav?result.text!==void 0||result.contentBase64===void 0:result.contentBase64!==void 0||result.text===void 0))throw Error();const bytes=wav?Buffer.from(result.contentBase64,"base64"):Buffer.from(result.text,"utf8");const checksumSha256=createHash15("sha256").update(bytes).digest("hex");if(wav&&bytes.toString("base64")!==result.contentBase64||bytes.length>(wav?12582912:131072)||checksumSha256!==result.checksumSha256||checksumSha256!==identity6.data.checksumSha256||result.byteSize!==void 0&&bytes.length!==result.byteSize||identity6.data.byteSize!==void 0&&bytes.length!==identity6.data.byteSize)throw new NativeStudioSdkError("MEDIA_IDENTITY_MISMATCH","INTERNAL_OPERATIONAL_FAILURE","NO_WRITE");return{bytes,contentType,checksumSha256,etag:null}}catch(error){if(error instanceof NativeStudioSdkError)throw error;throw new NativeStudioSdkError("RESPONSE_INVALID","INTERNAL_OPERATIONAL_FAILURE","NO_WRITE")}}import{createHash as createHash16}from"node:crypto";import{z as z210}from"zod";var inputSchema2=z210.discriminatedUnion("kind",[KeyframeGetInputSchema.extend({kind:z210.literal("KEYFRAME")}),VideoGetInputSchema.extend({kind:z210.literal("VIDEO_POSTER")}),RoughCutGetSchema.extend({kind:z210.literal("ROUGH_CUT_POSTER")}),FinalRenderGetSchema.extend({kind:z210.literal("FINAL_POSTER")}),ReferencePreviewOperationInputSchema.extend({kind:z210.literal("REFERENCE_PREVIEW")})]);var sdkMcpImageTools=Object.freeze({KEYFRAME:"keyframe_media",VIDEO_POSTER:"video_poster",ROUGH_CUT_POSTER:"rough_cut_poster",FINAL_POSTER:"final_render_poster",REFERENCE_PREVIEW:"reference_preview_get"});var identitySchema=z210.strictObject({checksumSha256:z210.string().regex(/^[a-f0-9]{64}$/),byteSize:z210.int().positive().max(16*1024*1024).optional()});var metadataSchema=z210.strictObject({contentType:z210.enum(["image/png","image/jpeg","image/webp"]),checksumSha256:identitySchema.shape.checksumSha256,byteSize:z210.int().positive().max(16*1024*1024)});async function readMcpImage(config,raw,expected,options){if(!raw||raw.tenantId!==void 0&&(typeof raw.tenantId!=="string"||raw.tenantId.toLowerCase()!==config.tenantId))sdkInputError();const input=inputSchema2.safeParse({...raw,tenantId:config.tenantId}),identity6=identitySchema.safeParse(expected);if(!input.success||!identity6.success)sdkInputError();const{kind,...arguments_}=input.data;const deadline=AbortSignal.timeout(config.timeoutMs),signal=options.signal?AbortSignal.any([options.signal,deadline]):deadline;if(signal.aborted)throw new NativeStudioSdkError("REQUEST_ABORTED","BLOCKED","NO_WRITE");let reply2;try{reply2=await abortable(config.client.callTool({name:sdkMcpImageTools[kind],arguments:arguments_},{signal,timeout:config.timeoutMs,nativeReadOnly:true}),signal)}catch{throw new NativeStudioSdkError(signal.aborted?"REQUEST_ABORTED":"TRANSPORT_UNAVAILABLE","INTERNAL_OPERATIONAL_FAILURE","NO_WRITE")}try{if(Buffer.byteLength(JSON.stringify(reply2),"utf8")>config.maxJsonBytes)throw Error();const texts=reply2.content.filter(b=>b.type==="text"),images=reply2.content.filter(b=>b.type==="image");const carrier=reply2.structuredContent??(texts.length===1?JSON.parse(texts[0].text):void 0);const envelope=z210.object({semanticStatus:InterfaceSemanticStatusSchema,data:z210.unknown().optional(),error:z210.object({code:z210.string()}).optional()}).parse(carrier);if(reply2.isError)throw new NativeStudioSdkError(envelope.error&&nativeFailureCodes.has(envelope.error.code)?envelope.error.code:"RESPONSE_INVALID",envelope.semanticStatus==="SUCCESS"?"INTERNAL_OPERATIONAL_FAILURE":envelope.semanticStatus,"NO_WRITE");if(envelope.semanticStatus!=="SUCCESS"||images.length!==1||reply2.content.length!==(kind==="REFERENCE_PREVIEW"?2:1)||texts.length!==(kind==="REFERENCE_PREVIEW"?1:0))throw Error();const metadata=kind==="REFERENCE_PREVIEW"?ReferencePreviewResultSchema.parse(envelope.data):metadataSchema.parse(envelope.data);const block=images[0],bytes=Buffer.from(block.data,"base64"),checksumSha256=createHash16("sha256").update(bytes).digest("hex");if(block.mimeType!==metadata.contentType||bytes.toString("base64")!==block.data||bytes.length>(kind==="KEYFRAME"?8:16)*1024*1024||bytes.length!==metadata.byteSize||checksumSha256!==metadata.checksumSha256||checksumSha256!==identity6.data.checksumSha256||identity6.data.byteSize!==void 0&&bytes.length!==identity6.data.byteSize||"contentBase64"in metadata&&metadata.contentBase64!==block.data)throw new NativeStudioSdkError("MEDIA_IDENTITY_MISMATCH","INTERNAL_OPERATIONAL_FAILURE","NO_WRITE");return{bytes,contentType:metadata.contentType,checksumSha256,etag:null}}catch(error){if(error instanceof NativeStudioSdkError)throw error;throw new NativeStudioSdkError("RESPONSE_INVALID","INTERNAL_OPERATIONAL_FAILURE","NO_WRITE")}}function memberCapabilityPort(client,tenantId){return{async callTool(params,options){const{nativeReadOnly,capabilityVersion,...requestOptions}=options??{};const direct=McpEntryToolNames.some(name3=>name3===params.name);if(!direct&&nativeReadOnly===void 0)throw new NativeStudioSdkError("CAPABILITY_UNAVAILABLE","BLOCKED","NO_WRITE");const name2=nativeReadOnly?"studio_capability_query":"studio_capability_invoke";const request=direct?params:{name:name2,arguments:{tenantId,tool:params.name,arguments:params.arguments??{},...capabilityVersion&&{capabilityVersion}}};const response=await client.callTool(request,{...requestOptions,...!direct?{toolDefinition:inputDefinition(name2,CapabilityInvocationInputSchema)}:{}});if(direct&&!params.name.startsWith("studio_capability_"))return response;const gateway=request.name==="studio_capability_query"||request.name==="studio_capability_invoke";if(!gateway)return response;const parsed=CapabilityInvocationOutputSchema.safeParse(response.structuredContent);const target3=direct?params.arguments?.tool:params.name;if(!parsed.success){if(response.isError&&isNativeDenial(response.structuredContent))return response;throw new NativeStudioSdkError("RESPONSE_INVALID","INTERNAL_OPERATIONAL_FAILURE",nativeReadOnly?"NO_WRITE":"UNKNOWN")}if(parsed.data.tool!==target3)throw new NativeStudioSdkError("RESPONSE_INVALID","INTERNAL_OPERATIONAL_FAILURE",nativeReadOnly?"NO_WRITE":"UNKNOWN");if(direct&&!response.isError)return response;return{...response,structuredContent:parsed.data.result}}}}function isNativeDenial(value2){return value2!==null&&typeof value2==="object"&&"semanticStatus"in value2&&"error"in value2}var NativeStudioMcpClient=class{constructor(config){this.config=config;const tenant2=TenantIdSchema.safeParse(config.tenantId);if(!tenant2.success||typeof config.client?.callTool!=="function")sdkInputError();this.tenantId=tenant2.data.toLowerCase();if(config.mode!=="native")this.config={...config,client:memberCapabilityPort(config.client,this.tenantId)};this.timeout=config.timeoutMs??3e4;this.limit=config.maxJsonBytes??16*1024*1024;if(!Number.isSafeInteger(this.timeout)||this.timeout<1||this.timeout>3e5||!Number.isSafeInteger(this.limit)||this.limit<1024||this.limit>32*1024*1024)sdkInputError()}config;deviceRenders=new NativeStudioDeviceRenders(this);navigation=new NativeStudioNavigationFacade(this);tenantId;timeout;limit;imageMedia(input,expected,options={}){return readMcpImageMedia({...this.config,tenantId:this.tenantId,timeoutMs:this.timeout,maxJsonBytes:this.limit},input,expected,options)}evidenceImage(input,expected,options={}){return readMcpEvidenceImage({...this.config,tenantId:this.tenantId,timeoutMs:this.timeout,maxJsonBytes:this.limit},input,expected,options)}auxiliaryMedia(input,expected,options={}){return readMcpAuxiliaryMedia({...this.config,tenantId:this.tenantId,timeoutMs:this.timeout,maxJsonBytes:this.limit},input,expected,options)}image(input,expected,options={}){return readMcpImage({...this.config,tenantId:this.tenantId,timeoutMs:this.timeout,maxJsonBytes:this.limit},input,expected,options)}async call(key10,raw,options={}){if(!Object.hasOwn(sdkOperations,key10)||!raw||typeof raw!=="object"||Array.isArray(raw))sdkInputError();if(raw.tenantId!==void 0&&(typeof raw.tenantId!=="string"||raw.tenantId.toLowerCase()!==this.tenantId))sdkInputError();const limit=options.maxJsonBytes??this.limit;if(!Number.isSafeInteger(limit)||limit<1024||limit>this.limit)sdkInputError();const tool=sdkMcpTools[key10];if(tool===null)throw new NativeStudioSdkError("CAPABILITY_UNAVAILABLE","CAPABILITY_UNAVAILABLE","NO_WRITE");let capabilityVersion=options.capabilityVersion;if(capabilityVersion!==void 0){if(!CapabilityVersionSchema.safeParse(capabilityVersion).success)sdkInputError();if(this.config.mode==="native"||McpEntryToolNames.some(name2=>name2===tool))throw new NativeStudioSdkError("CAPABILITY_UNAVAILABLE","CAPABILITY_UNAVAILABLE","NO_WRITE")}const spec=sdkOperations[key10],parsed=spec.input.safeParse({...raw,tenantId:this.tenantId});if(!parsed.success)sdkInputError(inputIssues(parsed.error,spec.input));const input=parsed.data;if(Buffer.byteLength(JSON.stringify(input),"utf8")>18*1024*1024)sdkInputError();const request=spec.request===null?{method:spec.readOnly?"GET":"POST"}:spec.request(input);const write2=request.method==="POST"&&!spec.readOnly,outcome=write2?"UNKNOWN":"NO_WRITE";const signal=options.signal?AbortSignal.any([options.signal,AbortSignal.timeout(this.timeout)]):AbortSignal.timeout(this.timeout);if(signal.aborted)throw new NativeStudioSdkError("REQUEST_ABORTED","BLOCKED","NO_WRITE");if((key10==="rough-cut.start"||key10==="final-render.start")&&"deviceExecution"in input&&input.deviceExecution){const target3=DeviceRenderTargetSchema.parse(input.deviceExecution);const description=await this.navigation.describe({tool},{signal});const root=description.definition.inputSchema;const properties=schemaNode(root,root)?.properties;const policy=properties&&typeof properties==="object"?properties.deviceExecution:void 0;const policyFields=schemaNode(policy,root)?.properties;if(!schemaNode(policy,root)||target3.validationMode&&(!policyFields||typeof policyFields!=="object"||!Object.hasOwn(policyFields,"validationMode")))throw new NativeStudioSdkError("CAPABILITY_UNAVAILABLE","BLOCKED","NO_WRITE");if(this.config.mode!=="native")capabilityVersion??=description.capabilityVersion;if(signal.aborted)throw new NativeStudioSdkError("REQUEST_ABORTED","BLOCKED","NO_WRITE")}const definition=inputDefinition(tool,spec.input);let result;try{result=await abortable(this.config.client.callTool({name:tool,arguments:sdkMcpInput(key10,input)},{signal,timeout:this.timeout,toolDefinition:definition,nativeReadOnly:!write2,...capabilityVersion&&{capabilityVersion}}),signal)}catch{throw new NativeStudioSdkError(write2?"OUTCOME_UNKNOWN":signal.aborted?"REQUEST_ABORTED":"TRANSPORT_UNAVAILABLE","INTERNAL_OPERATIONAL_FAILURE",outcome)}let value2;try{if(Buffer.byteLength(JSON.stringify(result),"utf8")>limit)throw new Error;if("structuredContent"in result&&result.structuredContent!==void 0)value2=result.structuredContent;else if("content"in result&&result.content.length===1&&result.content[0]?.type==="text")value2=JSON.parse(result.content[0].text);else throw new Error}catch{throw new NativeStudioSdkError("RESPONSE_INVALID","INTERNAL_OPERATIONAL_FAILURE",outcome)}const envelope=value2&&typeof value2==="object"&&!Array.isArray(value2)?value2:{};if("isError"in result&&result.isError){const status=InterfaceSemanticStatusSchema.safeParse(envelope.semanticStatus);const semantic=status.success&&!["SUCCESS","ACCEPTED","NO_CHANGE"].includes(status.data)?status.data:"INTERNAL_OPERATIONAL_FAILURE";const error=envelope.error&&typeof envelope.error==="object"&&!Array.isArray(envelope.error)?envelope.error:void 0;const code=error?.code;const valid=status.success&&!["SUCCESS","ACCEPTED","NO_CHANGE"].includes(status.data);const suppliedVersion=capabilityVersion??(McpCapabilityGatewayNames.some(name2=>name2===tool)&&"capabilityVersion"in input?input.capabilityVersion:void 0);const reportedMismatch=capabilityMismatch(code,semantic,error?.details);const mismatch2=reportedMismatch?.kind==="CAPABILITY_DEFINITION"&&(reportedMismatch.expectedVersion===reportedMismatch.actualVersion||suppliedVersion!==void 0&&reportedMismatch.actualVersion!==suppliedVersion)?void 0:reportedMismatch;const known=valid&&typeof code==="string"&&nativeFailureCodes.has(code)&&(code!=="CAPABILITY_VERSION_MISMATCH"||!!mismatch2);throw new NativeStudioSdkError(known&&typeof code==="string"?code:semantic,semantic,failureOutcome(write2,semantic,valid&&error?.outcome==="UNKNOWN"?"UNKNOWN":known?error?.outcome:void 0),null,[],mismatch2)}if(envelope.semanticStatus==="NOT_FOUND"&&envelope.data===void 0)throw new NativeStudioSdkError("NOT_FOUND","NOT_FOUND",write2?"REJECTED":"NO_WRITE");const schema=spec.output;for(const candidate of[value2,envelope.data,envelope.data&&typeof envelope.data==="object"&&!Array.isArray(envelope.data)?{...envelope.data,semanticStatus:envelope.semanticStatus}:void 0]){const parsedOutput=schema.safeParse(candidate);if(parsedOutput.success){if(key10==="reference-preview.get")assertPreviewBytes(parsedOutput.data);if(key10==="temporal-evidence.read-video")assertOriginalVideoBytes(parsedOutput.data);if(key10==="audio.export"||key10==="caption.export"||key10==="source-sync.audio")assertExportBytes(parsedOutput.data,key10==="caption.export"&&"format"in input?String(input.format):void 0);assertManagementReceipt(key10,input,parsedOutput.data);assertResponseBindings(parsedOutput.data,input,spec.identity,write2?"POST":"GET",spec.expectedPath?spec.expectedPath(input,parsedOutput.data):void 0,spec.identityWhenPresent);assertSeriesResponseVersions(key10,input,parsedOutput.data);assertEnterpriseBrandResponse(key10,input,parsedOutput.data);return parsedOutput.data}}throw new NativeStudioSdkError("RESPONSE_INVALID","INTERNAL_OPERATIONAL_FAILURE",outcome)}};var NativeStudioNavigationClient=class{constructor(config){this.config=config;if(typeof config.client?.callTool!=="function")sdkInputError();this.native=new NativeStudioMcpClient({...config,client:{callTool:async(params,options)=>{const definition=this.definitions.get(params.name);const result=await config.client.callTool(params,{...options,...definition?{toolDefinition:definition}:{}});if(params.name==="studio_capability_describe"&&!result.isError){const parsed=CapabilityDescribeSchema.safeParse(result.structuredContent);const projectId=params.arguments?.projectId;if(parsed.success&&parsed.data.tenantId.toLowerCase()===config.tenantId.toLowerCase()&&parsed.data.tool===params.arguments?.tool){this.contexts.set(parsed.data.schemaCursor,{tool:parsed.data.tool,...typeof projectId==="string"?{projectId}:{}});if(this.contexts.size>32)this.contexts.delete(this.contexts.keys().next().value)}}return result}}})}config;native;definitions=new Map;contexts=new Map;async entrypoints(options={}){const value2=await this.native.call("studio.capability.groups",{includeDefinitions:true},options);const tools=value2.definitions;const required=this.config.mode==="native"?NavigationToolNames:McpEntryToolNames.filter(name2=>name2!=="studio_capability_invoke");const names=new Set(this.config.mode==="native"?[...NavigationToolNames,"nvs_open_execution"]:McpEntryToolNames);if(!tools||tools.some(tool=>!names.has(tool.name)||tool.inputSchema.type!=="object")||new Set(tools.map(tool=>tool.name)).size!==tools.length||Buffer.byteLength(JSON.stringify(tools))>(this.config.mode==="native"?160*1024:24*1024)||required.some(name2=>!tools.some(tool=>tool.name===name2)))this.invalid();this.definitions.clear();this.contexts.clear();for(const tool of tools)this.remember(tool);return{tools}}async selectedSchema(reference3,expectedTool,options={}){if(!reference3||reference3.length>2048||!/^[a-zA-Z0-9_-]{1,120}$/.test(expectedTool))sdkInputError();const context=this.contexts.get(reference3);if(context&&context.tool!==expectedTool)this.invalid();const projectId=options.projectId??context?.projectId;const description=await this.native.call("studio.capability.describe",{tool:expectedTool,schemaCursor:reference3,...projectId?{projectId}:{}},options);return this.selectDescription(description,expectedTool,{...projectId?{projectId}:{}})}selectDescription(raw,expectedTool,options={}){const parsed=CapabilityDescribeSchema.safeParse(raw);if(!parsed.success||parsed.data.tenantId.toLowerCase()!==this.config.tenantId.toLowerCase()||parsed.data.tool!==expectedTool)this.invalid();const description=parsed.data;const definition=description.definition;if(definition.name!==expectedTool)this.invalid();const selected=definition;this.remember(selected);this.contexts.set(description.schemaCursor,{tool:expectedTool,...options.projectId?{projectId:options.projectId}:{}});if(this.contexts.size>32)this.contexts.delete(this.contexts.keys().next().value);return description}remember(tool){if(!PublicToolDefinitionSchema.safeParse(tool).success||tool.inputSchema?.type!=="object"||Buffer.byteLength(JSON.stringify(tool))>160*1024)this.invalid();this.definitions.delete(tool.name);this.definitions.set(tool.name,structuredClone(tool));if(this.definitions.size>32)this.definitions.delete(this.definitions.keys().next().value)}invalid(){throw new NativeStudioSdkError("RESPONSE_INVALID","INTERNAL_OPERATIONAL_FAILURE","NO_WRITE")}};var sdkCarrierDifferences={"studio.capabilities":{kind:"MCP_DISCOVERY",role:"Configured MCP capability inventory"},"studio.start":{kind:"MCP_DISCOVERY",role:"Progressive MCP entry navigation"},"studio.media.readiness":{kind:"MCP_DISCOVERY",role:"Goal-specific render and host navigation"},"studio.navigate":{kind:"MCP_DISCOVERY",role:"Progressive MCP context navigation"},"studio.capability.groups":{kind:"MCP_DISCOVERY",role:"MCP tool groups"},"studio.capability.search":{kind:"MCP_DISCOVERY",role:"MCP tool search"},"studio.capability.describe":{kind:"MCP_DISCOVERY",role:"MCP tool schemas"},"studio.capability.query":{kind:"MCP_DISPATCH",role:"Compact MCP read dispatch to existing native Owners"},"studio.capability.invoke":{kind:"MCP_DISPATCH",role:"Compact MCP write dispatch to existing native Owners"},"agent-host.configure":{kind:"PRIVATE_HTTP",role:"Private host configuration credential injection"},"provider.configure":{kind:"PRIVATE_HTTP",role:"Private provider credential injection"},"webhook.configure":{kind:"PRIVATE_HTTP",role:"Private signing-secret configuration; models use webhook.configure-reference"},"webhook.secret.prepare":{kind:"PRIVATE_HTTP",role:"Private caller-bound signing-secret preparation"}};function assertCarrierCoverage(operations2,differences){const expected=Object.entries(operations2).filter(([key10,value2])=>value2.request===null||sdkMcpTools[key10]===null).map(([key10])=>key10).sort();if(JSON.stringify(expected)!==JSON.stringify(Object.keys(differences).sort()))throw Error("SDK carrier inventory is incomplete")}var NativeStudioRuntimeAuthorityClient=class{tenantId;origin;transport;constructor(config){const tenant2=TenantIdSchema.safeParse(config.tenantId);if(!tenant2.success)sdkInputError();this.tenantId=tenant2.data.toLowerCase();if(config.maxJsonBytes!==void 0&&config.maxJsonBytes>65536)sdkInputError();try{this.origin=new URL(config.baseUrl);if(this.origin.protocol!=="https:")sdkInputError()}catch{sdkInputError()}this.transport=new NativeStudioHttpTransport({...config,maxJsonBytes:config.maxJsonBytes??65536,authorization:()=>{throw new Error("Runtime proof has no bearer credential")}})}input(schema,raw){if(!raw||typeof raw!=="object"||Array.isArray(raw))sdkInputError();const record=raw;if(record.tenantId!==void 0&&(typeof record.tenantId!=="string"||record.tenantId.toLowerCase()!==this.tenantId))sdkInputError();const parsed=schema.safeParse({...record,tenantId:this.tenantId});if(!parsed.success)sdkInputError();return parsed.data}resource(projectId,resource){if(resource!==new URL(`/mcp/native/v1/projects/${projectId}`,this.origin).href)throw new NativeStudioSdkError("RESPONSE_SCOPE_MISMATCH","INTERNAL_OPERATIONAL_FAILURE","UNKNOWN")}async prove(raw,options={}){const value2=this.input(NativeRuntimeProofRequestSchema,raw),result=await this.transport.json({method:"POST",tenantId:this.tenantId,path:path("projects",value2.projectId,"native-tool-grants",value2.grantId,"proof"),body:{assertion:value2.assertion},authentication:"runtime-proof"},NativeToolGrantViewSchema,options);assertResponseBindings(result,value2,[["grantId","grantId"]],"POST");this.resource(value2.projectId,result.resource);return result}async status(raw,options={}){const value2=this.input(NativeRuntimeProofRequestSchema,raw);try{const result=await this.transport.json({method:"POST",tenantId:this.tenantId,path:path("projects",value2.projectId,"native-tool-grants",value2.grantId,"status"),body:{assertion:value2.assertion},authentication:"runtime-proof"},NativeToolGrantViewSchema,options);assertResponseBindings(result,value2,[["grantId","grantId"]],"POST");this.resource(value2.projectId,result.resource);return result}catch(error){if(error instanceof NativeStudioSdkError)throw new NativeStudioSdkError(error.code,error.semanticStatus,"NO_WRITE",error.status);throw error}}async exchange(raw,options={}){const value2=this.input(NativeToolCredentialExchangeSchema,raw),result=await this.transport.json({method:"POST",tenantId:this.tenantId,path:path("projects",value2.projectId,"productions",value2.productionId,"native-tool-credentials","exchange"),body:{authorityRef:value2.authorityRef,assertion:value2.assertion},authentication:"runtime-proof"},NativeToolCredentialReplySchema,options);this.resource(value2.projectId,result.resource);if(!result.accessToken.startsWith(`nvst_${result.tokenId}.`))throw new NativeStudioSdkError("RESPONSE_SCOPE_MISMATCH","INTERNAL_OPERATIONAL_FAILURE","UNKNOWN");return result}};import{setTimeout as delay}from"node:timers/promises";async function*queryPages(client,key10,input,options={}){const maxPages=options.maxPages??50,maxItems=options.maxItems??1e3;if(!Number.isSafeInteger(maxPages)||maxPages<1||maxPages>500||!Number.isSafeInteger(maxItems)||maxItems<1||maxItems>1e4)sdkInputError();const seen=new Set;let next=input.next,count2=0;if(next)seen.add(next);for(let pageNumber=0;pageNumber<maxPages;pageNumber++){const page5=await client.call(key10,{...input,...next===void 0?{}:{next}},options);count2+=page5.items.length;if(count2>maxItems)throw new NativeStudioSdkError("OBSERVATION_LIMIT","WAITING_INPUT","NO_WRITE");if(page5.page.hasMore&&(!page5.page.next||seen.has(page5.page.next)))throw new NativeStudioSdkError("CONTINUATION_INVALID","INTERNAL_OPERATIONAL_FAILURE","NO_WRITE");yield page5;if(!page5.page.hasMore)return;next=page5.page.next;seen.add(next)}throw new NativeStudioSdkError("OBSERVATION_LIMIT","WAITING_INPUT","NO_WRITE")}async function waitForOperation(client,input,options={}){const maxPolls=options.maxPolls??60,timeoutMs=options.timeoutMs??9e4,intervalMs=options.intervalMs??1e3;const adaptive=options.intervalMs===void 0;let previous,pause=intervalMs;if(!Number.isSafeInteger(maxPolls)||maxPolls<1||maxPolls>1e3||!Number.isSafeInteger(timeoutMs)||timeoutMs<1||timeoutMs>18e5||!Number.isSafeInteger(intervalMs)||intervalMs<10||intervalMs>1e4)sdkInputError();const deadline=AbortSignal.timeout(timeoutMs),signal=options.signal?AbortSignal.any([options.signal,deadline]):deadline;try{for(let poll=0;poll<maxPolls;poll++){signal.throwIfAborted();const result=await abortable(client.call("operation.get",input,{signal}),signal);signal.throwIfAborted();if(!["ACCEPTED","WAITING_PROVIDER","RETRYING"].includes(result.semanticStatus))return result;const progress=JSON.stringify([result.semanticStatus,result.targets,result.work,result.blockers,result.nextActions]);pause=adaptive&&progress===previous?Math.min(5e3,pause*2):intervalMs;previous=progress;if(poll<maxPolls-1)await delay(pause,void 0,{signal})}}catch(error){if(!deadline.aborted||options.signal?.aborted)throw error}throw new NativeStudioSdkError("OBSERVATION_LIMIT","WAITING_INPUT","NO_WRITE")}import{setTimeout as delay2}from"node:timers/promises";async function*observeProduction(client,input,options={}){const polls=options.maxPolls??60,timeout=options.timeoutMs??3e5,events=options.maxEvents??1e3,byteLimit=options.maxBytes??2*1024*1024;for(const[n,max]of[[polls,1e3],[timeout,18e5],[events,1e4],[byteLimit,16*1024*1024]])if(!Number.isSafeInteger(n)||n<1||n>max)sdkInputError();if(byteLimit<1024)sdkInputError();const controller=new AbortController;const timer=setTimeout(()=>controller.abort(),timeout);const signal=options.signal?AbortSignal.any([options.signal,controller.signal]):controller.signal;let after=input.after,etag=input.ifNoneMatch,count2=0,bytes=0,unchanged=0;try{for(let n=0;n<polls;n++){signal.throwIfAborted();const page5=ProductionEventReadSchema.parse(await abortable(client.call("production.events.read",{...input,...after?{after}:{},...etag?{ifNoneMatch:etag}:{}},{signal,maxJsonBytes:128*1024}),signal));signal.throwIfAborted();count2+=page5.items.length;bytes+=Buffer.byteLength(JSON.stringify(page5));if(count2>events||bytes>byteLimit)throw new NativeStudioSdkError("OBSERVATION_LIMIT","WAITING_INPUT","NO_WRITE");if(page5.hasMore&&(page5.nextCursor===after||page5.items.length===0))throw new NativeStudioSdkError("CONTINUATION_INVALID","INTERNAL_OPERATIONAL_FAILURE","NO_WRITE");yield page5;after=page5.nextCursor;etag=page5.current.etag;unchanged=page5.items.length===0&&page5.current.condition==="NOT_MODIFIED"?unchanged+1:0;if(n+1<polls&&!page5.hasMore)await delay2(Math.min(3e4,page5.current.retryAfterMs*2**Math.min(unchanged,3)),void 0,{signal})}}catch(error){if(!controller.signal.aborted||options.signal?.aborted)throw error;throw new NativeStudioSdkError("OBSERVATION_LIMIT","WAITING_INPUT","NO_WRITE")}finally{clearTimeout(timer);controller.abort()}}import{createHmac,timingSafeEqual}from"node:crypto";function verifyWebhookNotification(input){const match=/^t=([1-9][0-9]{0,11}),v1=([a-f0-9]{64})$/.exec(input.signature);const now=input.now??Date.now();if(!(input.body instanceof Uint8Array)||input.body.length>128*1024||!match||!Number.isSafeInteger(now)||Math.abs(now/1e3-Number(match[1]))>300||typeof input.secret!=="string"||input.secret.length<32||input.secret.length>256||input.eventVersion!=="1"||!/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/.test(input.deliveryId))throw Error("WEBHOOK_INVALID");const expected=createHmac("sha256",input.secret).update(match[1]+".").update(input.body).digest();if(!timingSafeEqual(expected,Buffer.from(match[2],"hex")))throw Error("WEBHOOK_INVALID");try{const event3=ExternalLifecycleEventSchema.parse(JSON.parse(new TextDecoder("utf-8",{fatal:true}).decode(input.body)));if(event3.eventId!==input.eventId)throw Error();return event3}catch{throw Error("WEBHOOK_INVALID")}}import{createHash as createHash17}from"node:crypto";var inputSchema3=FederationResultReadSchema.omit({reference:true}).extend({event:ExternalLifecycleEventSchema});var mismatch=()=>{throw new NativeStudioSdkError("FEDERATION_NOTICE_RESULT_MISMATCH","INTERNAL_OPERATIONAL_FAILURE","NO_WRITE")};function parseReply(schema,raw,maxBytes){try{const text6=canonicalFederationReadJson(raw);if(Buffer.byteLength(text6)>maxBytes)return mismatch();const result=schema.safeParse(JSON.parse(text6));if(!result.success)return mismatch();return result.data}catch{return mismatch()}}async function readFederationLifecycleResult(client,raw,options={}){let expected;try{const input=inputSchema3.parse(JSON.parse(canonicalFederationJson(raw)));expected=FederationResultValueSchema.parse({tenantId:input.tenantId,productionId:input.productionId,source:input.source,schemaVersion:1,resourceType:"nvs.lifecycle-event",resourceId:input.event.eventId,revision:String(input.event.basis.productionRevision),event:input.event})}catch{sdkInputError()}const bytes=canonicalFederationJson(expected);const digest6="sha256:"+createHash17("sha256").update(bytes).digest("hex");const cap=options.maxJsonBytes??65536;if(!Number.isSafeInteger(cap)||cap<1024)sdkInputError();const requestOptions={...options,maxJsonBytes:Math.min(cap,65536)};const aborted=()=>{if(requestOptions.signal?.aborted)throw new NativeStudioSdkError("REQUEST_ABORTED","BLOCKED","NO_WRITE")};async function query(operation2,input){aborted();try{const pending=client.call(operation2,input,{...requestOptions});return await(requestOptions.signal?abortable(pending,requestOptions.signal):pending)}catch(error){aborted();throw error}}const scope8={tenantId:expected.tenantId,productionId:expected.productionId};const reference3=parseReply(FederationResultReferenceSchema,await query("federation.result.reference",{...scope8,resourceType:"nvs.lifecycle-event",resourceId:expected.resourceId}),requestOptions.maxJsonBytes);if(reference3.tenantId!==scope8.tenantId||reference3.productionId!==scope8.productionId||reference3.source!==expected.source||reference3.reference.resourceType!==expected.resourceType||reference3.reference.resourceId!==expected.resourceId||reference3.reference.revision!==expected.revision||reference3.reference.digest!==digest6)mismatch();const pinnedReference=canonicalFederationJson(reference3.reference);const result=parseReply(FederationResultSnapshotSchema,await query("federation.result.read",{...scope8,source:expected.source,reference:{...reference3.reference}}),requestOptions.maxJsonBytes);const value2=result.value;if(value2.resourceType!=="nvs.lifecycle-event"||result.tenantId!==scope8.tenantId||result.productionId!==scope8.productionId||result.source!==expected.source||canonicalFederationJson(result.reference)!==pinnedReference||canonicalFederationJson(value2)!==bytes)return mismatch();return{...result,value:value2}}export{LocalIdSchema,LocalDigestSchema,LocalRevisionSchema,LocalTimeSchema,LocalPackageVersionSchema,LocalProjectScopeSchema,LocalWorkScopeSchema,LocalDevicePlatformSchema,EnrollLocalDeviceSchema,LocalDeviceViewSchema,LocalDeviceChallengeSchema,RevokeLocalDeviceSchema,WorkspaceDeviceListInputSchema,WorkspaceDeviceListSchema,LegacyCaptionRenderStyleSchema,RegularCaptionRenderStyleSchema,kokoroCpuProfile,CpuSpeechInputSchema,CpuSpeechCapabilitySchema,CpuSpeechInstallationSchema,processorFamilies,TenantProcessorKindSchema,referenceThumbnailProfile,ProjectDeviceListSchema,RoughCutViewSchema,FinalRenderViewSchema,LocalLeaseBindingSchema,mediaCategoryOf,localLibraryProfile,LocalLibraryReferenceSchema,LocalLibraryItemSchema,LocalLibraryPageSchema,LocalLibraryProjectionSchema,LocalLibraryProjectionPageSchema,LocalLibraryProjectionQuerySchema,LocalLibraryImportSchema,LocalLibraryReadReplySchema,LocalLibraryGetSchema,LocalLibraryCallSchema,LocalLibraryCapabilitySchema,LocalLibraryUsageSchema,RoughCutRequirementSchema,ReviewEvidenceMediaSchema,whisperCppRecognitionProfile,LocalWhisperToolSelectionSchema,canonicalLocalJson,VideoReviewRequirementSchema,VisualRequirementSchema,KeyframeObservationSchema,ReviewIntelligenceBasisSchema,ValidateReviewIntelligenceSchema,ReviewIntelligenceContextResultSchema,StartLocalPreviewSchema,LocalDeviceSessionSchema,LocalDeviceTransportConfigurationSchema,LocalPreviewAdmissionSchema,StartLocalFinalRenderSchema,LocalFinalRenderAdmissionSchema,LocalManagementCommandSchema,LocalManagementResultSchema,LocalManagementReceiptSchema,LocalDeviceManagementCommandSchema,DeviceEnrollmentScopeSchema,DeviceEnrollmentHandoffSchema,DeviceEnrollmentTicketSchema,DeviceEnrollmentReceiptSchema,DeviceEnrollmentObservationSchema,deviceEnrollmentSigningInput,ComponentStatusSchema,WorkspaceStatusSchema,DeviceStatusInputSchema,DeviceStatusSchema,tenantRenderValidationProfile,TenantRenderMediaTicketSchema,LocalLibraryCommandSchema,LocalLibraryCommandQuerySchema,LocalLibraryAdmissionSchema,importedNormalizationValidationProfile,LocalLibraryCommandStatusSchema,renderDeviceSelection,NavigationGroupIdSchema,NavigationGroups,navigationGroup,NavigationProfile,NavigationProfileKey,NavigationToolNames,CapabilityGroupsSchema,CapabilityDescribeSchema,McpEntryToolNames,CapabilityInvocationInputSchema,CapabilityInvocationOutputSchema,DeviceDiscoveryInputSchema,DeviceRenderIntentSchema,DeviceRenderReadSchema,DeviceRenderDownloadSchema,PreparedDeviceRenderSchema,DeviceRenderReceiptHandoffSchema,DeviceRenderAdmissionSchema,NativeStudioDeviceRenders,checkedManagementReceipt,assertManagementReceipt,validateDeviceEnrollmentHandoff,issueDeviceEnrollment,lookupDeviceEnrollment,submitDeviceEnrollment,recoverDeviceEnrollment,NativeStudioNavigationFacade,sdkOperations,NativeStudioAgentClient,sdkImageMediaTools,sdkMcpTools,NativeStudioMcpClient,NativeStudioNavigationClient,sdkCarrierDifferences,assertCarrierCoverage,NativeStudioRuntimeAuthorityClient,queryPages,waitForOperation,observeProduction,verifyWebhookNotification,readFederationLifecycleResult};
|
|
1
|
+
import{ArtifactIdSchema,ArtifactRelationIdSchema,ArtifactRepresentationIdSchema,BriefIdSchema,BriefVersionIdSchema,CapabilityVersionMismatchSchema,CapabilityVersionSchema,ContinuationSchema,ContinuityEdgeIdSchema,CreateProjectRequestSchema,CreatedProjectResultSchema,DeliveryOutputProfileSchema,HumanLinksSchema,HumanTenantSchema,InterfaceSemanticStatusSchema,NextActionSchema,OperationIdSchema,PrincipalIdSchema,ProductionIdSchema,ProductionSchema,ProductionStateSchema,ProjectIdSchema,ProjectLibraryPageSchema,ProjectLibraryQuerySchema,ProjectLibraryScopeSchema,ProjectSchema,ProjectWorkspaceSchema,QueryLimitSchema,QueryPageInfoSchema,SceneIdSchema,SceneShotPlanIdSchema,SceneShotPlanVersionIdSchema,ShotIdSchema,SourceLibraryItemSchema,SourceLibraryMediaSchema,SourceLibraryPageSchema,SourceLibraryQuerySchema,StoryIdSchema,StoryVersionIdSchema,StudioInputContentSchema,TenantIdSchema,WorkSummarySchema,finalProfileIds}from"./chunk-WTJVS2VS.js";import{NativeStudioSdkError,sdkInputError}from"./chunk-TT7IA5HB.js";import{createHash}from"node:crypto";import{z}from"zod";var LocalIdSchema=z.uuid().overwrite(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 z5}from"zod";import{z as z4}from"zod";import{z as z3}from"zod";import{z as z2}from"zod";var HOST_PROTOCOL="NVS_AGENT_HOST_V1";var HostProtocolDigest="c4b254f091c364e0fab8d43ad551f296a3bce2996bdb2c5349307c62295c1769";var HostDelegationDigest="03e0bad50c7c6ecf7979db72c0927fa43904d8fbad67ae02447a87a9263f2730";var HostReferenceSchema=z2.string().min(1).max(256).refine(v=>Array.from(v).every(c=>{const n=c.codePointAt(0);return n>=32&&(n<127||n>159)&&(n<55296||n>57343)}));var HostScopeSchema=z2.strictObject({namespace:HostReferenceSchema,ref:HostReferenceSchema});var HostChoiceSchema=z2.strictObject({agentKey:HostReferenceSchema,agentVersion:HostReferenceSchema,modelOptionKey:HostReferenceSchema});var CurrentHostSelectionSchema=HostChoiceSchema.extend({contractVersion:z2.literal(2),hostKey:z2.string().regex(/^[a-z0-9][a-z0-9_-]{0,63}$/),hostScope:HostScopeSchema}).strict();var HistoricalHostSelectionSchema=z2.object({hostKey:z2.string().min(1).max(64)}).catchall(z2.union([HostReferenceSchema,z2.number().int().nonnegative()])).refine(v=>!Object.hasOwn(v,"contractVersion")&&Object.keys(v).length<=32);var HostBearerSchema=z2.string().min(16).max(4096).regex(/^[A-Za-z0-9._~+/-]+={0,2}$/).meta({writeOnly:true});var CurrentHostInstallationTransportSchema=z2.strictObject({protocol:z2.literal(HOST_PROTOCOL),hostContractDigest:z2.literal(HostProtocolDigest),installationId:z2.string().regex(/^[A-Za-z0-9_-]{1,160}$/),installationRevisionId:z2.string().regex(/^[A-Za-z0-9_-]{1,160}$/),slotKey:z2.string().regex(/^[a-z0-9_-]{1,64}$/),contractDigest:z2.literal(HostDelegationDigest),capabilityDigest:z2.string().regex(/^[a-f0-9]{64}$/)});var HistoricalHostTransportSchema=z2.strictObject({protocol:HostReferenceSchema.refine(v=>v!==HOST_PROTOCOL),installationId:HostReferenceSchema,installationRevisionId:HostReferenceSchema,slotKey:HostReferenceSchema,contractDigest:z2.string().regex(/^[a-f0-9]{64}$/).optional(),capabilityDigest:z2.string().regex(/^[a-f0-9]{64}$/).optional()});var Id=z3.uuid().toLowerCase();var ReadId=z3.uuid().regex(/^[0-9a-f-]{36}$/);var Key=z3.string().regex(/^[a-z0-9][a-z0-9_-]{0,63}$/);var Revision=z3.int().min(0).max(999999999);var AgentHostScopeSchema=z3.strictObject({tenantId:Id,projectId:Id});var ReadScope=z3.strictObject({tenantId:ReadId,projectId:ReadId});var AgentHostSelectionSchema=CurrentHostSelectionSchema;var AgentHostReadSelectionSchema=z3.union([CurrentHostSelectionSchema,HistoricalHostSelectionSchema]);var ConfigureAgentHostSchema=AgentHostScopeSchema.extend({requestId:Id,bindingId:Id,expectedRevision:z3.int().min(0).max(999999998),selection:AgentHostSelectionSchema,apiCredential:HostBearerSchema});var RevokeAgentHostSchema=AgentHostScopeSchema.extend({requestId:Id,bindingId:Id,expectedRevision:z3.int().min(1).max(999999998)});var AgentHostBindingSchema=ReadScope.extend({bindingId:ReadId,revision:Revision.refine(value2=>value2>0),configurationVersion:Revision.refine(value2=>value2>0),enabled:z3.boolean(),selection:AgentHostReadSelectionSchema,updatedAt:z3.iso.datetime({offset:true})}).refine(value2=>value2.configurationVersion<=value2.revision);var CurrentAgentHostBindingSchema=AgentHostBindingSchema.safeExtend({selection:CurrentHostSelectionSchema});var UpdateAgentHostSelectionSchema=ConfigureAgentHostSchema.omit({apiCredential:true}).extend({expectedRevision:z3.int().min(1).max(999999998),expectedConfigurationVersion:z3.int().positive().max(999999998)});var AgentHostCurrentSchema=z3.strictObject({binding:AgentHostBindingSchema.nullable()});var AgentHostHistoryQuerySchema=AgentHostScopeSchema.extend({limit:z3.int().min(1).max(100).default(20),beforeVersion:z3.int().positive().max(999999999).optional()});var AgentHostConfigurationVersionSchema=ReadScope.extend({bindingId:ReadId,version:z3.int().positive().max(999999999),selection:AgentHostReadSelectionSchema,createdByPrincipalId:ReadId,createdAt:z3.iso.datetime({offset:true}),revokedAt:z3.iso.datetime({offset:true}).nullable()});var AgentHostHistoryPageSchema=z3.strictObject({items:z3.array(AgentHostConfigurationVersionSchema).max(100),hasMore:z3.boolean(),nextBeforeVersion:z3.int().positive().max(999999999).nullable()}).refine(page5=>page5.hasMore===(page5.nextBeforeVersion!==null)&&(!page5.hasMore||page5.items.length>0));var AgentHostReadinessSchema=ReadScope.extend({binding:AgentHostBindingSchema.nullable(),registeredHostKeys:z3.array(Key).max(16),configurationStatus:z3.enum(["NOT_CONFIGURED","REVOKED","HOST_UNAVAILABLE","CREDENTIAL_UNAVAILABLE","CONFIGURATION_CHANGED","CONFIGURED"]),remoteCredentialVerification:z3.enum(["NOT_CHECKED","VERIFIED"]),nativeToolAuthority:z3.enum(["NOT_CONNECTED","UNVERIFIED","VERIFIED"]),executionAvailability:z3.enum(["UNAVAILABLE","AVAILABLE"]),reason:z3.enum(["NATIVE_TOOL_AUTHORITY_NOT_CONNECTED","NATIVE_TOOL_AUTHORITY_NOT_QUALIFIED","CONFIGURATION_CHANGED"]).nullable(),checkedAt:z3.iso.datetime({offset:true})}).refine(v=>{const verified=v.nativeToolAuthority==="VERIFIED";return(v.binding===null||v.binding.tenantId===v.tenantId&&v.binding.projectId===v.projectId)&&verified===(v.remoteCredentialVerification==="VERIFIED")&&verified===(v.executionAvailability==="AVAILABLE")&&verified===(v.reason===null)&&(!verified||v.configurationStatus==="CONFIGURED"&&v.binding?.enabled===true)});var AgentHostFailureSchema=z3.strictObject({semanticStatus:z3.enum(["INVALID_INPUT","NOT_FOUND","BLOCKED","REVISION_CONFLICT","CAPABILITY_UNAVAILABLE","INTERNAL_OPERATIONAL_FAILURE"]),error:z3.strictObject({code:z3.enum(["INVALID_INPUT","UNAUTHENTICATED","FORBIDDEN","NOT_FOUND","REVISION_CONFLICT","REQUEST_CONFLICT","HOST_UNAVAILABLE","CREDENTIAL_UNAVAILABLE","CREDENTIAL_SCOPE_MISMATCH","BINDING_REVOKED","INTERNAL_OPERATIONAL_FAILURE"]),message:z3.literal("Agent Host operation did not complete")})});var id=z4.uuid().regex(/^[0-9a-f-]{36}$/);var requestId=z4.uuid().toLowerCase();var key=z4.string().regex(/^[A-Za-z0-9_-]{1,160}$/);var NativeRuntimePublicKeySchema=z4.strictObject({kty:z4.literal("EC"),crv:z4.literal("P-256"),x:z4.string().regex(/^[A-Za-z0-9_-]{43}$/),y:z4.string().regex(/^[A-Za-z0-9_-]{43}$/)});var ConfigureNativeToolGrantSchema=AgentHostScopeSchema.extend({requestId,bindingId:requestId,expectedBindingRevision:z4.int().positive(),expectedConfigurationVersion:z4.int().positive(),runtimeKey:key,installationId:key,installationRevisionId:key,publicKey:NativeRuntimePublicKeySchema,expiresAt:z4.iso.datetime({offset:true})});var NativeToolGrantGetSchema=AgentHostScopeSchema.extend({grantId:requestId});var RevokeNativeToolGrantSchema=NativeToolGrantGetSchema.extend({requestId,expectedRevision:z4.int().positive()});var NativeRuntimeProofRequestSchema=NativeToolGrantGetSchema.extend({assertion:z4.string().regex(/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/).max(4096).meta({writeOnly:true})});var NativeRuntimeStatusClaimsSchema=z4.strictObject({iss:key,sub:key,aud:z4.url().max(2048),grantId:id,installationRevisionId:key,jti:id,iat:z4.int().nonnegative(),exp:z4.int().positive()}).refine(v=>v.exp>v.iat&&v.exp-v.iat<=60);var NativeRuntimeProofClaimsSchema=z4.strictObject({iss:key,sub:key,aud:z4.url().max(2048),grantId:id,grantRevision:z4.int().positive(),installationRevisionId:key,challengeId:id,jti:id,iat:z4.int().nonnegative(),exp:z4.int().positive()}).refine(v=>v.exp>v.iat&&v.exp-v.iat<=60);var NativeToolGrantViewSchema=z4.strictObject({tenantId:id,projectId:id}).extend({protocol:z4.literal("NATIVESTUDIO_RUNTIME_REGISTRATION_V1"),grantId:id,bindingId:id,bindingRevision:z4.int().positive(),configurationVersion:z4.int().positive(),selection:AgentHostReadSelectionSchema,runtimeKey:key,installationId:key,installationRevisionId:key,publicKey:NativeRuntimePublicKeySchema,resource:z4.url().max(2048),revision:z4.int().positive(),enabled:z4.boolean(),createdByPrincipalId:id,runtimePrincipalId:id,createdAt:z4.iso.datetime({offset:true}),expiresAt:z4.iso.datetime({offset:true}),challengeId:id,challengeExpiresAt:z4.iso.datetime({offset:true}),verifiedAt:z4.iso.datetime({offset:true}).nullable(),revokedAt:z4.iso.datetime({offset:true}).nullable()}).refine(v=>{const resource=new URL(v.resource);return resource.protocol==="https:"&&!resource.username&&!resource.password&&!resource.search&&!resource.hash&&resource.pathname===`/mcp/native/v1/projects/${v.projectId}`&&v.enabled===(v.revokedAt===null)&&Date.parse(v.challengeExpiresAt)<=Date.parse(v.expiresAt)});var LocalDevicePlatformSchema=z5.strictObject({os:z5.enum(["darwin","linux","win32"]),architecture:z5.enum(["x64","arm64"])});var EnrollLocalDeviceSchema=z5.strictObject({tenantId:LocalIdSchema,requestId:LocalIdSchema,expectedPrincipalId:LocalIdSchema.optional(),label:z5.string().trim().min(1).max(120),platform:LocalDevicePlatformSchema,runtimeVersion:LocalPackageVersionSchema,publicKey:NativeRuntimePublicKeySchema});var LocalDeviceViewSchema=EnrollLocalDeviceSchema.omit({requestId:true,expectedPrincipalId:true}).extend({deviceId:LocalIdSchema,revision:LocalRevisionSchema,enrolledByPrincipalId:LocalIdSchema,createdAt:LocalTimeSchema,verifiedAt:LocalTimeSchema.nullable(),revokedAt:LocalTimeSchema.nullable()}).refine(v=>[v.verifiedAt,v.revokedAt].every(time2=>time2===null||Date.parse(time2)>=Date.parse(v.createdAt)));var LocalDeviceChallengeSchema=z5.strictObject({tenantId:LocalIdSchema,deviceId:LocalIdSchema,deviceRevision:LocalRevisionSchema,challengeId:LocalIdSchema,audience:z5.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=z5.strictObject({protocol:z5.literal("NVS_LOCAL_DEVICE_PROOF_V1"),tenantId:LocalIdSchema,deviceId:LocalIdSchema,deviceRevision:LocalRevisionSchema,challengeId:LocalIdSchema,audience:z5.string().min(1).max(2048),jti:LocalIdSchema,iat:z5.int().nonnegative(),exp:z5.int().positive()}).refine(v=>v.exp>v.iat&&v.exp-v.iat<=60);var ProveLocalDeviceSchema=z5.strictObject({tenantId:LocalIdSchema,deviceId:LocalIdSchema,deviceRevision:LocalRevisionSchema,challengeId:LocalIdSchema,assertion:z5.string().max(4096).regex(/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/).meta({writeOnly:true})});var RevokeLocalDeviceSchema=z5.strictObject({tenantId:LocalIdSchema,deviceId:LocalIdSchema,requestId:LocalIdSchema,expectedRevision:LocalRevisionSchema});import{z as z7}from"zod";import{z as z6}from"zod";var InventoryArguments=z6.strictObject({tenantId:z6.uuid()});var DeviceSetupRecoverySchema=z6.strictObject({reason:z6.enum(["NO_REGISTERED_DEVICE","NO_SUITABLE_DEVICE","CAPABILITY_MISSING","DEVICE_DISCONNECTED","DEVICE_BUSY","INCOMPLETE_INVENTORY"]),action:z6.enum(["PREPARE_OR_REPAIR_HOST","RECONNECT_EXISTING_HOST","WAIT","INSPECT_EXISTING"]),inspect:z6.discriminatedUnion("tool",[z6.strictObject({tool:z6.literal("workspace_caller"),arguments:InventoryArguments}),z6.strictObject({tool:z6.literal("studio_capability_query"),arguments:z6.strictObject({tenantId:z6.uuid(),tool:z6.literal("workspace_devices_list"),arguments:InventoryArguments})})]),guidance:z6.string().min(1).max(1e3)}).superRefine((value2,ctx)=>{const action=value2.reason==="DEVICE_BUSY"?"WAIT":value2.reason==="INCOMPLETE_INVENTORY"||value2.reason==="NO_SUITABLE_DEVICE"?"INSPECT_EXISTING":value2.reason==="DEVICE_DISCONNECTED"?"RECONNECT_EXISTING_HOST":"PREPARE_OR_REPAIR_HOST";const tool=action==="WAIT"||action==="INSPECT_EXISTING"?"studio_capability_query":"workspace_caller";if(value2.action!==action||value2.inspect.tool!==tool)ctx.addIssue({code:"custom",message:"Recovery must match the observed device condition"});if(value2.inspect.tool==="studio_capability_query"&&value2.inspect.arguments.tenantId.toLowerCase()!==value2.inspect.arguments.arguments.tenantId.toLowerCase())ctx.addIssue({code:"custom",message:"Recovery scope must match the inventory target"})});var WorkspaceDeviceListInputSchema=z7.strictObject({tenantId:LocalIdSchema,deviceId:LocalIdSchema.optional(),after:LocalIdSchema.optional(),limit:z7.int().min(1).max(50).default(25)});var WorkspaceDeviceInventoryItemSchema=z7.strictObject({deviceId:LocalIdSchema,label:z7.string().trim().min(1).max(120),platform:LocalDevicePlatformSchema,runtimeVersion:LocalPackageVersionSchema.nullable(),runtimeVersionObservedAt:LocalTimeSchema.nullable(),revision:LocalRevisionSchema,createdAt:LocalTimeSchema,verifiedAt:LocalTimeSchema.nullable(),revokedAt:LocalTimeSchema.nullable(),lastSeenAt:LocalTimeSchema.nullable(),connection:z7.enum(["UNVERIFIED","REVOKED","OWNER_UNAVAILABLE","CONNECTED","DISCONNECTED"])}).refine(value2=>value2.runtimeVersion===null===(value2.runtimeVersionObservedAt===null),{message:"Runtime version and observation time must be present together"});var WorkspaceDeviceListSchema=z7.strictObject({tenantId:LocalIdSchema,observedAt:LocalTimeSchema,items:z7.array(WorkspaceDeviceInventoryItemSchema).max(50),nextCursor:LocalIdSchema.nullable(),recovery:DeviceSetupRecoverySchema.optional()});import{z as z8}from"zod";var identity={deviceId:LocalIdSchema,deviceRevision:LocalRevisionSchema};var WorkspaceDeviceAuthoritySchema=z8.strictObject({...identity,authority:z8.literal("WORKSPACE_DEVICE_V1")});var LocalDeviceExecutionTargetSchema=z8.discriminatedUnion("kind",[WorkspaceDeviceAuthoritySchema.extend({kind:z8.literal("DEVICE")}),z8.strictObject({kind:z8.literal("SERVER")})]);var TenantDeviceTargetSchema=WorkspaceDeviceAuthoritySchema.extend({keyFingerprint:LocalDigestSchema});function sameDeviceAuthority(a,b){return a.deviceId===b.deviceId&&a.deviceRevision===b.deviceRevision&&a.authority===b.authority}import{z as z65}from"zod";import{z as z28}from"zod";import{z as z26}from"zod";import{z as z9}from"zod";var offset=z9.int().min(0).max(4094).multipleOf(2);var dimension=z9.int().min(2).max(4096).multipleOf(2);var ClipFramingSchema=z9.strictObject({algorithm:z9.literal("CROP_PAD_V1"),crop:z9.strictObject({x:offset,y:offset,width:dimension,height:dimension}),anchorXPermille:z9.int().min(0).max(1e3),anchorYPermille:z9.int().min(0).max(1e3)});var PicturePolicySchema=z9.literal("CROP_PAD_V1");import{z as z10}from"zod";var ClipTransitionSchema=z10.union([z10.literal("CUT"),z10.strictObject({kind:z10.literal("CROSS_DISSOLVE_V1"),durationFrames:z10.int().min(2).max(30)})]);import{z as z11}from"zod";var sha=z11.string().regex(/^[0-9a-f]{64}$/);var GraphicPlacementSchema=z11.strictObject({startFrame:z11.int().nonnegative().max(1800),endFrame:z11.int().positive().max(1800),anchor:z11.enum(["TOP_LEFT","TOP_RIGHT","BOTTOM_LEFT","BOTTOM_RIGHT"]),widthPermille:z11.int().min(50).max(400),marginXPermille:z11.int().min(0).max(100),marginYPermille:z11.int().min(0).max(100),opacityPermille:z11.int().min(100).max(1e3)}).refine(v=>v.endFrame>v.startFrame,"Graphic frame interval must advance");var TimelineGraphicInputSchema=z11.strictObject({artifactId:ArtifactIdSchema,placement:GraphicPlacementSchema});var TimelineGraphicSourceSchema=z11.strictObject({tenantId:TenantIdSchema,projectId:ProjectIdSchema,productionId:ProductionIdSchema.nullable(),artifactId:ArtifactIdSchema,representationId:ArtifactRepresentationIdSchema,checksumSha256:sha,contentType:z11.enum(["image/png","image/webp"]),byteSize:z11.int().positive().max(16*1024*1024),width:z11.int().positive().max(8192),height:z11.int().positive().max(8192)});var TimelineGraphicSchema=z11.strictObject({source:TimelineGraphicSourceSchema,placement:GraphicPlacementSchema});import{z as z13}from"zod";import{z as z12}from"zod";var id2=z12.uuid().toLowerCase();var hash=z12.string().regex(/^[0-9a-f]{64}$/);var CaptionTranscriptPlacementSchema=z12.discriminatedUnion("kind",[z12.strictObject({kind:z12.literal("AUDIO_TRACK"),purpose:z12.enum(["VOICEOVER","MUSIC"])}),z12.strictObject({kind:z12.literal("SPEECH_CUE"),cueId:z12.string().regex(/^[a-z][a-z0-9_-]{0,63}$/)}),z12.strictObject({kind:z12.literal("TIMELINE_OUTPUT")})]);var CaptionTranscriptPlanSchema=z12.strictObject({tenantId:TenantIdSchema,productionId:ProductionIdSchema,timelineVersionId:id2,language:z12.string().regex(/^[A-Za-z]{2,8}(?:-[A-Za-z0-9]{1,8})*$/).max(60),sources:z12.array(z12.strictObject({observationId:id2,placement:CaptionTranscriptPlacementSchema,granularity:z12.enum(["word","segment"])})).min(1).max(64)});var AuthorTranscriptCaptionsSchema=CaptionTranscriptPlanSchema.extend({expectedProductionRevision:z12.int().positive(),expectedCaptionVersion:z12.int().nonnegative(),idempotencyKey:z12.string().trim().min(1).max(200)});var CaptionTranscriptProvenanceSchema=z12.strictObject({schemaVersion:z12.literal(1),advisory:z12.literal(true),timing:z12.literal("PROVIDER_REPORTED"),timelineVersionId:id2,timingFingerprint:hash,sources:z12.array(z12.strictObject({observationId:id2,artifactId:id2,representationId:id2,checksumSha256:hash,placement:CaptionTranscriptPlacementSchema,granularity:z12.enum(["word","segment"]),sourceInMs:z12.int().nonnegative(),sourceOutMs:z12.int().positive(),startMs:z12.int().nonnegative(),spanIndices:z12.array(z12.int().nonnegative().max(1199)).min(1).max(120),excludedSpans:z12.int().nonnegative().max(1200)})).min(1).max(64)});var sha2=z13.string().regex(/^[0-9a-f]{64}$/);var CaptionContentSchema=z13.strictObject({language:z13.string().regex(/^[A-Za-z]{2,8}(?:-[A-Za-z0-9]{1,8})*$/).max(60),durationMs:z13.int().min(3e4).max(6e4),cues:z13.array(z13.strictObject({startMs:z13.int().nonnegative().max(59999),endMs:z13.int().positive().max(6e4),text:z13.string().min(1).max(240)})).min(1).max(120)});var CaptionScopeSchema=z13.strictObject({tenantId:TenantIdSchema,productionId:ProductionIdSchema});var AuthorCaptionsSchema=CaptionScopeSchema.extend({expectedProductionRevision:z13.int().positive(),expectedCaptionVersion:z13.int().nonnegative(),idempotencyKey:z13.string().trim().min(1).max(200),content:CaptionContentSchema});var CaptionGetSchema=CaptionScopeSchema.extend({versionId:z13.uuid()});var CaptionQuerySchema=CaptionScopeSchema.extend({limit:QueryLimitSchema,next:ContinuationSchema.optional()});var CaptionRepresentationSchema=z13.strictObject({id:z13.uuid(),checksumSha256:sha2,byteSize:z13.int().positive().max(131072)});var CaptionVersionSchema=CaptionScopeSchema.extend({transcriptProvenance:CaptionTranscriptProvenanceSchema.optional(),id:z13.uuid(),captionId:z13.uuid(),projectId:z13.uuid(),version:z13.int().positive(),artifactId:z13.uuid(),content:CaptionContentSchema,fingerprint:sha2,original:CaptionRepresentationSchema,subtitle:CaptionRepresentationSchema,previousVersionId:z13.uuid().nullable(),createdByPrincipalId:z13.uuid(),createdAt:z13.iso.datetime({offset:true})});var CaptionViewSchema=z13.strictObject({version:CaptionVersionSchema,isCurrent:z13.boolean(),availability:z13.enum(["AVAILABLE","UNAVAILABLE"])});var CaptionReceiptSchema=z13.strictObject({semanticStatus:z13.literal("SUCCESS"),version:CaptionVersionSchema,productionRevision:z13.int().positive()});var CaptionBasisSchema=CaptionScopeSchema.extend({productionRevision:z13.int().positive(),currentVersion:z13.int().nonnegative(),currentVersionId:z13.uuid().nullable(),authorable:z13.boolean()});var CaptionPageSchema=z13.strictObject({items:z13.array(CaptionViewSchema).max(200),page:QueryPageInfoSchema});var CaptionExportSchema=CaptionGetSchema.extend({format:z13.enum(["JSON","SRT"])});var CaptionSnapshotSchema=z13.strictObject({currentVersion:z13.int().positive().nullable(),currentVersionId:z13.uuid().nullable(),artifactId:z13.uuid().nullable(),availability:z13.enum(["NONE","AVAILABLE","UNAVAILABLE"]),cueCount:z13.int().nonnegative().max(120),durationMs:z13.int().min(3e4).max(6e4).nullable(),attachedToTimeline:z13.boolean(),attachedCaptionVersionId:z13.uuid().nullable().optional(),attachedTimelineVersionId:z13.uuid().nullable().optional()});var CaptionTranscriptDraftSchema=z13.strictObject({content:CaptionContentSchema,provenance:CaptionTranscriptProvenanceSchema});import{z as z14}from"zod";var LegacyCaptionRenderStyleSchema=z14.strictObject({id:z14.literal("PLAIN_TEXT_NOTO_SANS_SC_V1"),fontSha256:z14.literal("a3041811a78c361b1de50f953c805e0244951c21c5bd412f7232ef0d899af0da"),framePolicy:z14.literal("PTS_HALF_OPEN_CEIL_V1")});var RegularCaptionRenderStyleSchema=z14.strictObject({id:z14.literal("PLAIN_TEXT_NATIVE_SC_REGULAR_V2"),fontSha256:z14.literal("e5a51f41fc1b827da651afee3975e07a182ff4f8e04d9dfc0a3cecd6177a52b6"),framePolicy:z14.literal("PTS_HALF_OPEN_CEIL_V1")});var CaptionRenderStyleSchema=z14.discriminatedUnion("id",[LegacyCaptionRenderStyleSchema,RegularCaptionRenderStyleSchema]);import{z as z17}from"zod";import{z as z16}from"zod";import{z as z15}from"zod";var VoiceProfileRefSchema=z15.strictObject({ownerSystem:z15.string().regex(/^[a-z][a-z0-9-]{1,79}$/),ownerTenantRef:z15.string().trim().min(1).max(160),voiceProfileRef:z15.string().trim().min(1).max(160),version:z15.int().positive(),digest:z15.string().regex(/^[a-f0-9]{64}$/)});var VoiceLocaleSchema=z15.string().min(2).max(35).refine(value2=>{try{return value2.toLowerCase()!=="auto"&&Intl.getCanonicalLocales(value2).length===1}catch{return false}},"A concrete BCP 47 language is required").describe("Concrete BCP 47 tag, for example zh or en-US; auto is not a language");var VoiceProfileUseSchema=z15.strictObject({ref:VoiceProfileRefSchema,bindingKey:z15.string().regex(/^[a-z][a-z0-9_-]{0,63}$/),language:VoiceLocaleSchema,usage:z15.enum(["AUDITION","PRODUCTION"])});var sha3=z16.string().regex(/^[0-9a-f]{64}$/);var AudioPurposeSchema=z16.enum(["VOICEOVER","MUSIC"]);var AudioProductionScopeSchema=z16.strictObject({tenantId:TenantIdSchema,productionId:ProductionIdSchema});var AudioScopeSchema=AudioProductionScopeSchema.extend({purpose:AudioPurposeSchema});var AudioMaterialPurposeSchema=z16.enum(["VOICEOVER","MUSIC","VOICE_SAMPLE"]);var AudioReadScopeSchema=AudioScopeSchema.extend({purpose:AudioMaterialPurposeSchema});var AudioMediaSchema=z16.strictObject({profile:z16.literal("PCM_S16LE_48000_V1"),audioCodec:z16.literal("pcm_s16le"),sampleRateHz:z16.literal(48e3),audioChannels:z16.union([z16.literal(1),z16.literal(2)]),sampleCount:z16.int().min(4800).max(288e4),durationMs:z16.int().min(100).max(6e4)}).refine(m=>m.sampleCount*1e3===m.durationMs*m.sampleRateHz,{message:"Exact PCM sample count must match duration"});var AudioImportSchema=AudioScopeSchema.extend({expectedProductionRevision:z16.int().positive(),expectedAudioVersion:z16.int().nonnegative(),idempotencyKey:z16.string().trim().min(1).max(200),contentType:z16.literal("audio/wav"),originalName:z16.string().trim().min(1).max(255).regex(/^[^\p{Cc}]*$/u).optional()});var AudioImportRequestSchema=AudioImportSchema.extend({contentBase64:z16.string().min(60).max(16777216).regex(/^[A-Za-z0-9+/]*={0,2}$/)});var AudioPublicationSchema=AudioImportSchema.extend({purpose:AudioMaterialPurposeSchema});var AudioGetSchema=AudioReadScopeSchema.extend({versionId:z16.uuid()});var AudioQuerySchema=AudioReadScopeSchema.extend({limit:QueryLimitSchema,next:ContinuationSchema.optional()});var AudioRepresentationSchema=z16.strictObject({id:z16.uuid(),checksumSha256:sha3,byteSize:z16.int().min(44).max(12582912)});var AudioVersionSchema=AudioReadScopeSchema.extend({id:z16.uuid(),audioId:z16.uuid(),projectId:z16.uuid(),version:z16.int().positive(),artifactId:z16.uuid(),original:AudioRepresentationSchema,media:AudioMediaSchema,originalName:z16.string().trim().min(1).max(255).regex(/^[^\p{Cc}]*$/u).nullable(),previousVersionId:z16.uuid().nullable(),createdByPrincipalId:z16.uuid(),createdAt:z16.iso.datetime({offset:true}),generation:z16.strictObject({generationId:z16.uuid(),voiceProfile:VoiceProfileUseSchema.optional(),executionClass:z16.enum(["LIVE","TEST_ONLY"]),executionTarget:z16.literal("TENANT_DEVICE").optional(),sourceArtifactId:z16.uuid(),sourceRepresentationId:z16.uuid(),sourceChecksumSha256:sha3,sourceByteSize:z16.int().min(44).max(12582912),sourceMedia:z16.strictObject({sampleRateHz:z16.int().positive().max(48e3),audioChannels:z16.union([z16.literal(1),z16.literal(2)]),sampleCount:z16.int().positive()}),normalizationVersion:z16.literal("SPEECH_PCM_V1"),padSamples:z16.int().min(0).max(47)}).optional()}).refine(v=>v.version===1===(v.previousVersionId===null),{message:"Audio replacement history must preserve exact preceding version"});var AudioViewSchema=z16.strictObject({version:AudioVersionSchema,isCurrent:z16.boolean(),availability:z16.enum(["AVAILABLE","UNAVAILABLE"])});var ProductionAudioVersionSchema=AudioVersionSchema.safeExtend({purpose:AudioPurposeSchema});var AudioReceiptSchema=z16.strictObject({semanticStatus:z16.literal("SUCCESS"),version:AudioVersionSchema,productionRevision:z16.int().positive()});var AudioBasisSchema=AudioReadScopeSchema.extend({productionRevision:z16.int().positive(),currentVersion:z16.int().nonnegative(),currentVersionId:z16.uuid().nullable(),importable:z16.boolean()});var AudioPageSchema=z16.strictObject({items:z16.array(AudioViewSchema).max(200),page:QueryPageInfoSchema});var AudioSnapshotSchema=z16.strictObject({tracks:z16.array(z16.strictObject({purpose:AudioPurposeSchema,currentVersion:z16.int().positive().nullable(),currentVersionId:z16.uuid().nullable(),artifactId:z16.uuid().nullable(),availability:z16.enum(["NONE","AVAILABLE","UNAVAILABLE"]),durationMs:z16.int().min(100).max(6e4).nullable(),audioChannels:z16.union([z16.literal(1),z16.literal(2)]).nullable(),attachedToTimeline:z16.boolean()})).length(2)});var placement={sourceInMs:z17.int().nonnegative().max(6e4),sourceOutMs:z17.int().positive().max(6e4),startMs:z17.int().nonnegative().max(6e4),gainPermille:z17.int().nonnegative().max(1e3)};var TimelineAudioInputSchema=z17.strictObject({tracks:z17.array(z17.strictObject({purpose:AudioPurposeSchema,versionId:z17.uuid(),...placement})).min(1).max(2),duckingMusicPermille:z17.int().nonnegative().max(1e3).default(1e3)}).superRefine((audio2,ctx)=>{if(new Set(audio2.tracks.map(t=>t.purpose)).size!==audio2.tracks.length||audio2.tracks.some(t=>t.sourceOutMs<=t.sourceInMs)||audio2.duckingMusicPermille<1e3&&audio2.tracks.length!==2)ctx.addIssue({code:"custom",message:"Distinct purposes, advancing trims and explicit ducking pair required"})});var AudioMixProfileSchema=z17.strictObject({id:z17.literal("PCM_WINDOW_MIX_AAC_V1"),sampleRateHz:z17.literal(48e3),audioChannels:z17.literal(2),audioCodec:z17.literal("aac"),bitrate:z17.literal(192e3),peakPermille:z17.literal(950),duckingMusicPermille:z17.int().nonnegative().max(1e3)});var TimelineAudioCompositionSchema=z17.strictObject({mix:AudioMixProfileSchema,tracks:z17.array(z17.strictObject({source:ProductionAudioVersionSchema,...placement})).min(1).max(2)}).superRefine((audio2,ctx)=>{if(new Set(audio2.tracks.map(t=>t.source.purpose)).size!==audio2.tracks.length||audio2.tracks.some(t=>t.sourceOutMs<=t.sourceInMs||t.sourceOutMs>t.source.media.durationMs)||audio2.mix.duckingMusicPermille<1e3&&audio2.tracks.length!==2)ctx.addIssue({code:"custom",message:"Invalid exact audio composition"})});var RenderedAudioSchema=z17.strictObject({audioCodec:z17.literal("aac"),sampleRateHz:z17.literal(48e3),audioChannels:z17.literal(2),sampleCount:z17.int().positive().max(288e4)});import{z as z18}from"zod";var Fingerprint=z18.string().regex(/^[0-9a-f]{64}$/);var AcceptedShotReferenceSchema=z18.strictObject({acceptanceId:z18.uuid(),reviewId:z18.uuid(),generationId:z18.uuid(),candidateId:z18.uuid(),shotId:ShotIdSchema,artifactId:ArtifactIdSchema,representationId:ArtifactRepresentationIdSchema,checksumSha256:Fingerprint,artifactChecksumSha256:Fingerprint,preparationId:z18.uuid(),contractId:z18.uuid(),contractFingerprint:Fingerprint,planVersionId:SceneShotPlanVersionIdSchema,planVersion:z18.int().positive(),shotPlanningRevision:z18.int().positive(),executionClass:z18.enum(["LIVE","TEST_ONLY"]),reviewResult:z18.enum(["PASS","WARNING"])});import{z as z20}from"zod";import{z as z19}from"zod";var ProviderIdSchema=z19.enum(["QWEN_CN","VOLCENGINE_CN","GEMINI","OPENAI","XAI"]);var ProviderConnectionIdSchema=z19.uuid().brand();var ModelProfileIdSchema=z19.string().regex(/^[a-z][a-z0-9-]{1,79}$/);var GeometryPolicySchema=z19.enum(["STRICT","PAD_TO_ASPECT"]);var ProviderSelectionSchema=z19.strictObject({connectionId:ProviderConnectionIdSchema,modelProfileId:ModelProfileIdSchema});var TenantProviderExecutionGrantSchema=z19.strictObject({projectId:z19.uuid(),modelProfileId:ModelProfileIdSchema,modelProfileVersion:z19.int().positive(),workload:z19.enum(["KEYFRAME_GENERATE","VIDEO_GENERATE","SPEECH_SYNTHESIS","TRANSCRIPTION","AUDIO_OBSERVATION","VIDEO_OBSERVATION"]),disclosure:z19.enum(["TEXT_ONLY","IMMUTABLE_PROJECT_INPUTS"]),expiresAt:z19.iso.datetime({offset:true}),maxPerRequestMicros:z19.int().min(0).max(1e9),maxTotalMicros:z19.int().min(0).max(1e9),maxSubmissions:z19.int().min(1).max(1e4)}).refine(v=>v.maxPerRequestMicros<=v.maxTotalMicros);var providerConfigurationFields={providerId:ProviderIdSchema,label:z19.string().trim().min(1).max(100),allowedModelProfileIds:z19.array(ModelProfileIdSchema).min(1).max(16),qwenEndpoint:z19.literal("QIANWEN_PLATFORM").optional(),credentialService:z19.enum(["ARK","DOUBAO_SPEECH"]).optional(),qwenWorkspaceId:z19.string().regex(/^[a-z0-9][a-z0-9-]{0,63}$/).optional(),geometryPolicy:GeometryPolicySchema.default("STRICT")};var ProviderConfigurationSchema=z19.strictObject({...providerConfigurationFields,tenantExecution:z19.array(TenantProviderExecutionGrantSchema).min(1).max(64).optional()}).superRefine((v,c)=>{if(new Set(v.allowedModelProfileIds).size!==v.allowedModelProfileIds.length)c.addIssue({code:"custom",message:"Duplicate model profile"});const grants=v.tenantExecution??[];const keys=new Set(grants.map(g=>[g.projectId.toLowerCase(),g.modelProfileId,g.workload].join(":")));if(keys.size!==grants.length||grants.some(g=>!v.allowedModelProfileIds.includes(g.modelProfileId)))c.addIssue({code:"custom",message:"Invalid tenant execution scope",path:["tenantExecution"]});if(v.qwenWorkspaceId&&v.providerId!=="QWEN_CN")c.addIssue({code:"custom",message:"Workspace only applies to Qwen China"});if(v.credentialService&&v.providerId!=="VOLCENGINE_CN")c.addIssue({code:"custom",message:"Credential service applies to Volcengine"});if(v.qwenEndpoint&&(v.providerId!=="QWEN_CN"||v.qwenWorkspaceId))c.addIssue({code:"custom",message:"Qianwen platform requires an exact Qwen route without a workspace"})});var ConfigureProviderInputSchema=z19.strictObject({tenantId:TenantIdSchema,connectionId:ProviderConnectionIdSchema,expectedVersion:z19.int().nonnegative(),configuration:ProviderConfigurationSchema,apiKey:z19.string().min(8).max(4096).regex(/^[!-~]+$/)});var ProviderConnectionViewSchema=z19.strictObject({tenantId:TenantIdSchema,connectionId:ProviderConnectionIdSchema,version:z19.int().positive(),enabled:z19.boolean(),credentialConfigured:z19.boolean(),configuration:z19.object(providerConfigurationFields),createdByPrincipalId:PrincipalIdSchema,updatedAt:z19.iso.datetime({offset:true})});var ProviderConnectionCommandSchema=z19.strictObject({tenantId:TenantIdSchema,connectionId:ProviderConnectionIdSchema,expectedVersion:z19.int().positive()});var ProviderCredentialRevokeSchema=z19.strictObject({tenantId:TenantIdSchema,connectionId:ProviderConnectionIdSchema,version:z19.int().positive()});var SetKeyframeDefaultSchema=z19.strictObject({tenantId:TenantIdSchema,selection:ProviderSelectionSchema,expectedRevision:z19.int().nonnegative()});var ProviderExecutionBindingSchema=z19.strictObject({tenantId:TenantIdSchema,connectionId:ProviderConnectionIdSchema,connectionVersion:z19.int().positive(),providerId:ProviderIdSchema,modelProfileId:ModelProfileIdSchema,modelProfileVersion:z19.int().positive(),modelId:z19.string().min(1).max(160),credentialRef:z19.uuid(),credentialVersion:z19.int().positive(),geometryPolicy:GeometryPolicySchema,qwenEndpoint:z19.literal("QIANWEN_PLATFORM").optional()}).refine(binding=>!binding.qwenEndpoint||binding.providerId==="QWEN_CN",{message:"Qianwen platform binding requires Qwen China"});var GenerationCostVariantSchema=z20.strictObject({mode:z20.enum(["REFERENCE_TO_IMAGE","REFERENCE_TO_VIDEO","FIRST_FRAME_TO_VIDEO","FIRST_LAST_FRAME_TO_VIDEO"]),aspectRatio:z20.enum(["16:9","9:16"]),workingWidth:z20.int().min(0).max(4096),workingHeight:z20.int().min(0).max(4096),hasAudio:z20.boolean(),references:z20.int().min(0).max(24),durationSeconds:z20.number().finite().min(0).max(30)});var GenerationCostPolicySchema=z20.strictObject({currency:z20.literal("USD"),sourceUrl:z20.url({protocol:/^https$/}).max(2e3),rationale:z20.string().trim().min(1).max(2e3),validUntil:z20.iso.datetime({offset:true}),rules:z20.array(z20.strictObject({id:z20.string().regex(/^[a-zA-Z0-9_-]{1,80}$/),variant:GenerationCostVariantSchema,upperBoundMicros:z20.int().nonnegative().max(1e9)})).min(1).max(64)}).refine(p=>new Set(p.rules.map(r=>r.id)).size===p.rules.length,"Duplicate cost rule");var ExpectedGenerationExecutionSchema=z20.strictObject({connectionVersion:z20.int().positive(),modelProfileVersion:z20.int().positive(),quoteValidUntil:z20.iso.datetime({offset:true})});var GenerationCostQuoteSchema=z20.strictObject({currency:z20.literal("USD"),upperBoundMicros:z20.int().nonnegative().max(1e9),selection:ProviderSelectionSchema,expectedExecution:ExpectedGenerationExecutionSchema,sourceUrl:z20.url({protocol:/^https$/}).max(2e3),ruleIds:z20.array(z20.string()).min(1).max(64),preparationId:z20.uuid(),contractFingerprint:z20.string().regex(/^[a-f0-9]{64}$/)});import{z as z25}from"zod";import{z as z21}from"zod";var id3=z21.uuid().toLowerCase();var hash2=z21.string().regex(/^[0-9a-f]{64}$/);var NativeVideoAudioMetadataSchema=z21.strictObject({normalizationVersion:z21.literal("VIDEO_AUDIO_PCM_V1"),sourceCodec:z21.literal("aac"),sourceSampleRateHz:z21.int().min(8e3).max(96e3),sourceChannels:z21.union([z21.literal(1),z21.literal(2)]),sourceFrameRateHz:z21.union([z21.literal(24),z21.literal(30)]),sourceFrameCount:z21.int().positive().max(905),sourceStartOffsetMs:z21.number().finite().min(-500).max(5e3),sourceDeclaredDurationMs:z21.number().positive().max(31e3),alignment:z21.literal("TRIM_PAD_PCM_TO_VIDEO_ZERO_V1"),media:z21.strictObject({profile:z21.literal("PCM_S16LE_48000_NATIVE_VIDEO_V1"),audioCodec:z21.literal("pcm_s16le"),sampleRateHz:z21.literal(48e3),audioChannels:z21.union([z21.literal(1),z21.literal(2)]),sampleCount:z21.int().positive().max(1448e3),durationMs:z21.number().positive().max(30200)}).refine(m=>m.durationMs===m.sampleCount/48),checksumSha256:hash2}).superRefine((v,ctx)=>{if(v.media.sampleCount!==v.sourceFrameCount*(48e3/v.sourceFrameRateHz)||v.media.audioChannels!==v.sourceChannels)ctx.addIssue({code:"custom",message:"Native PCM must follow the exact source video frame clock"})});var NativeVideoSoundReferenceSchema=z21.strictObject({id:id3,tenantId:id3,projectId:id3,productionId:id3,shotId:id3,generationId:id3,videoArtifactId:id3,videoRepresentationId:id3,videoChecksumSha256:hash2,artifactId:id3,representationId:id3,checksumSha256:hash2,byteSize:z21.int().min(44).max(12582912),metadata:NativeVideoAudioMetadataSchema,executionClass:z21.enum(["LIVE","TEST_ONLY"])});import{z as z22}from"zod";var KeyframePurposeSchema=z22.enum(["START_FRAME","END_FRAME","SUBJECT_REFERENCE"]);var AcceptedKeyframeReferenceSchema=z22.strictObject({acceptanceId:z22.uuid(),reviewId:z22.uuid(),generationId:z22.uuid(),candidateId:z22.uuid(),shotId:ShotIdSchema,framePurpose:KeyframePurposeSchema,artifactId:ArtifactIdSchema,representationId:ArtifactRepresentationIdSchema,checksumSha256:z22.string().regex(/^[0-9a-f]{64}$/),artifactChecksumSha256:z22.string().regex(/^[0-9a-f]{64}$/),planVersionId:SceneShotPlanVersionIdSchema,planVersion:z22.int().positive(),shotPlanningRevision:z22.int().positive(),executionClass:z22.enum(["LIVE","TEST_ONLY"])});import{z as z24}from"zod";import{z as z23}from"zod";var ConsistencyReviewScaleSchema=z23.enum(["INTRA_SHOT","INTER_SHOT","PRODUCTION"]);var State=z23.string().trim().min(1).max(300);var StoryTime=z23.int().nonnegative().max(31536e8);var position=z23.int().min(1).max(999);var StateChange=z23.strictObject({atPermille:position,from:State,to:State,reason:State});var TimeJump=z23.strictObject({atPermille:position,fromMs:StoryTime,toMs:StoryTime,reason:State});var ContinuityExpectationSchema=z23.discriminatedUnion("kind",[z23.strictObject({kind:z23.literal("STATE"),mode:z23.enum(["PRESERVE","PLANNED_TRANSITIONS"]),entry:State,exit:State,changes:z23.array(StateChange).min(1).max(16).optional()}).superRefine((v,c)=>{const changes=v.changes??[];if(v.mode==="PLANNED_TRANSITIONS"!==!!changes.length||!changes.length&&v.entry!==v.exit||changes.length&&(changes[0].from!==v.entry||changes.at(-1).to!==v.exit)||changes.some((x,i)=>x.from===x.to||i>0&&(x.atPermille<=changes[i-1].atPermille||x.from!==changes[i-1].to)))c.addIssue({code:"custom",message:"State changes require an ordered explicit plan with exact entry and exit"})}),z23.strictObject({kind:z23.literal("TIME"),mode:z23.enum(["MONOTONIC","PLANNED_JUMPS"]),entryMs:StoryTime,exitMs:StoryTime,jumps:z23.array(TimeJump).min(1).max(16).optional()}).superRefine((v,c)=>{const jumps=v.jumps??[];if(v.mode==="PLANNED_JUMPS"!==!!jumps.length||!jumps.length&&v.exitMs<v.entryMs||jumps.length&&(jumps[0].fromMs<v.entryMs||jumps.at(-1).toMs>v.exitMs)||jumps.some((x,i)=>x.fromMs===x.toMs||i>0&&(x.atPermille<=jumps[i-1].atPermille||x.fromMs<jumps[i-1].toMs)))c.addIssue({code:"custom",message:"Story time requires monotonic segments separated by exact planned jumps"})})]);var ContinuitySampleSchema=z23.strictObject({atMs:z23.int().nonnegative().max(6e4),state:State.optional(),storyTimeMs:StoryTime.optional()}).superRefine((v,c)=>{if(v.state!==void 0===(v.storyTimeMs!==void 0))c.addIssue({code:"custom",message:"A sample observes exactly one state or story-time value"})});var ContinuitySamplesSchema=z23.array(ContinuitySampleSchema).min(3).max(64);var PreparationIdSchema=z24.uuid().brand();var GenerationContractIdSchema=z24.uuid().brand();var ContentFingerprintSchema=z24.string().regex(/^[0-9a-f]{64}$/);var PreparationTargetSchema=z24.discriminatedUnion("mediaType",[z24.strictObject({mediaType:z24.literal("IMAGE"),purpose:z24.enum(["KEYFRAME","REFERENCE_FRAME"]),framePurpose:z24.enum(["START_FRAME","END_FRAME","SUBJECT_REFERENCE"])}),z24.strictObject({mediaType:z24.literal("VIDEO"),purpose:z24.literal("SHOT_CANDIDATE")})]);var PreparationBasisSchema=z24.strictObject({tenantId:TenantIdSchema,projectId:ProjectIdSchema,productionId:ProductionIdSchema,sceneId:SceneIdSchema,shotId:ShotIdSchema,productionRevision:z24.int().positive(),briefVersionId:BriefVersionIdSchema,briefVersion:z24.int().positive(),storyVersionId:StoryVersionIdSchema,storyVersion:z24.int().positive(),planVersionId:SceneShotPlanVersionIdSchema,planVersion:z24.int().positive(),shotPlanningRevision:z24.int().positive(),resolverVersion:z24.literal("w7-product-preflight-v1"),consistencyProfile:z24.strictObject({id:z24.uuid(),version:z24.int().positive(),effectiveFingerprint:ContentFingerprintSchema}).optional()});var ReferenceRoleSchema=z24.enum(["PRODUCT_IDENTITY","PRODUCT_PACKSHOT","CHARACTER_IDENTITY","WARDROBE","LOCATION","STYLE","START_FRAME_ANCHOR","END_FRAME_ANCHOR"]);var ReferenceBindingInputSchema=z24.strictObject({keyframeAcceptanceId:z24.uuid().optional(),role:ReferenceRoleSchema,artifactId:ArtifactIdSchema,representationId:ArtifactRepresentationIdSchema,checksumSha256:ContentFingerprintSchema,reason:z24.string().trim().min(1).max(500)});var ExactEvidenceReferenceSchema=z24.strictObject({artifactId:ArtifactIdSchema,representationId:ArtifactRepresentationIdSchema,checksumSha256:ContentFingerprintSchema,artifactChecksumSha256:ContentFingerprintSchema});var ResolvedReferenceSchema=ReferenceBindingInputSchema.extend({artifactChecksumSha256:ContentFingerprintSchema,contentType:z24.enum(["image/png","image/jpeg","image/webp"]),acceptedKeyframe:AcceptedKeyframeReferenceSchema.optional(),consistencyRuleId:z24.uuid().optional(),subjectId:z24.uuid().optional(),authority:z24.enum(["BRIEF_SOURCE_AND_EXPLICIT_BINDING","EXPLICIT_SHOT_BINDING","CANONICAL_PROFILE_MASTER","ACCEPTED_KEYFRAME_AND_EXPLICIT_BINDING"])});var ResolvedConstraintSchema=z24.strictObject({continuity:ContinuityExpectationSchema.optional(),reviewScales:z24.array(ConsistencyReviewScaleSchema).min(1).max(3).optional(),key:z24.string().min(1).max(200),family:z24.enum(["PRODUCT_IDENTITY","CHARACTER_IDENTITY","WARDROBE","LOCATION","STYLE","SHOT_INTENT","BOUNDARY_CONTINUITY"]),scope:z24.enum(["PROJECT","PRODUCTION","SCENE","SHOT","CONTINUITY_EDGE"]),subjectId:z24.uuid().optional(),dimension:z24.string().regex(/^[A-Z][A-Z0-9_]{0,63}$/).optional(),enforcement:z24.enum(["LOCKED","REQUIRED","PREFERRED"]),expected:z24.string().min(1).max(1e3),source:z24.strictObject({kind:z24.enum(["BRIEF","SCENE","SHOT","CONTINUITY_EDGE","CONSISTENCY_PROFILE"]),id:z24.uuid(),version:z24.int().positive()})});var PreparationBlockerSchema=z24.strictObject({code:z24.enum(["MISSING_PRODUCT_REFERENCE","CANONICAL_SOURCE_UNAVAILABLE","CONSTRAINT_CONFLICT","PREVIOUS_SHOT_EVIDENCE_UNAVAILABLE","GENERATED_KEYFRAME_REQUIRED"]),summary:z24.string().min(1).max(1e3),relatedShotId:ShotIdSchema.optional(),edgeId:ContinuityEdgeIdSchema.optional()});var ConstraintSetSchema=z24.strictObject({preparationId:PreparationIdSchema,version:z24.int().positive(),fingerprint:ContentFingerprintSchema,items:z24.array(ResolvedConstraintSchema).max(2048)});var ReferenceSetSchema=z24.strictObject({preparationId:PreparationIdSchema,version:z24.int().positive(),fingerprint:ContentFingerprintSchema,bindings:z24.array(ResolvedReferenceSchema).max(12)});var VideoGenerationIdSchema=z25.uuid().brand();var VideoProviderProfileSchema=z25.strictObject({id:z25.string().regex(/^[a-z][a-z0-9-]{1,79}$/),adapterVersion:z25.string().min(1).max(80),model:z25.string().min(1).max(160),executionClass:z25.enum(["LIVE","TEST_ONLY"]),mediaType:z25.literal("VIDEO"),modes:z25.array(z25.enum(["REFERENCE_TO_VIDEO","FIRST_FRAME_TO_VIDEO","FIRST_LAST_FRAME_TO_VIDEO"])).min(1).max(3),referenceRoles:z25.array(ReferenceRoleSchema).min(1).max(8),aspectRatios:z25.array(z25.enum(["16:9","9:16"])).min(1).max(2),minDurationSeconds:z25.int().min(1),maxDurationSeconds:z25.int().max(30),maxReferences:z25.int().min(1).max(10),combineAnchorsAndReferences:z25.boolean(),workingWidth:z25.int().positive().max(4096),workingHeight:z25.int().positive().max(4096),frameRate:z25.union([z25.literal(24),z25.literal(30)]),sourceFormat:z25.strictObject({videoCodec:z25.literal("hevc"),pixelFormat:z25.literal("yuv420p10le")}).optional(),hasAudio:z25.boolean(),nativeAudioChannels:z25.union([z25.literal(1),z25.literal(2)]).optional(),correlationStrategy:z25.literal("PROVIDER_TASK_ID")});var VideoOptionsInputSchema=z25.strictObject({tenantId:TenantIdSchema});var VideoStartInputSchema=z25.strictObject({expectedExecution:ExpectedGenerationExecutionSchema.optional(),tenantId:TenantIdSchema,projectId:ProjectIdSchema,productionId:ProductionIdSchema,shotId:ShotIdSchema,preparationId:PreparationIdSchema,contractId:GenerationContractIdSchema,contractFingerprint:ContentFingerprintSchema,selection:ProviderSelectionSchema,idempotencyKey:z25.string().trim().min(1).max(200)});var VideoDeviceStartInputSchema=VideoStartInputSchema.omit({selection:true,expectedExecution:true}).extend({deviceId:z25.uuid(),approvedQuote:GenerationCostQuoteSchema});var VideoGetInputSchema=z25.strictObject({tenantId:TenantIdSchema,productionId:ProductionIdSchema,generationId:VideoGenerationIdSchema});var VideoQueryInputSchema=z25.strictObject({tenantId:TenantIdSchema,productionId:ProductionIdSchema,shotId:ShotIdSchema.optional(),limit:QueryLimitSchema,next:ContinuationSchema.optional()});var VideoAdmissionSchema=z25.strictObject({semanticStatus:z25.literal("ACCEPTED"),generationId:VideoGenerationIdSchema,operationId:OperationIdSchema,productionId:ProductionIdSchema,contractId:GenerationContractIdSchema,executionClass:z25.enum(["LIVE","TEST_ONLY"])});var VideoTechnicalMetadataSchema=z25.strictObject({contentType:z25.literal("video/mp4"),checksumSha256:ContentFingerprintSchema,byteSize:z25.int().positive().max(128*1024*1024),width:z25.int().positive().max(4096),height:z25.int().positive().max(4096),durationMs:z25.int().min(1).max(30150),frameRate:z25.number().positive().max(120),videoCodec:z25.enum(["h264","hevc"]),pixelFormat:z25.literal("yuv420p10le").optional(),hasAudio:z25.boolean(),nativeAudio:NativeVideoAudioMetadataSchema.optional()});var VideoPosterSchema=z25.strictObject({representationId:ArtifactRepresentationIdSchema,contentType:z25.literal("image/png"),checksumSha256:ContentFingerprintSchema,byteSize:z25.int().positive().max(2*1024*1024),width:z25.int().positive().max(320),height:z25.int().positive().max(320)});var VideoCandidateSchema=VideoTechnicalMetadataSchema.extend({nativeSound:NativeVideoSoundReferenceSchema.optional(),id:z25.uuid(),artifactId:ArtifactIdSchema,representationId:ArtifactRepresentationIdSchema,poster:VideoPosterSchema,availability:z25.enum(["AVAILABLE","INVALID"]),observation:z25.enum(["NOT_OBSERVED","OBSERVED"]),evaluation:z25.enum(["UNREVIEWED","PASS","WARNING","FAIL"]),accepted:z25.boolean(),reviewId:z25.uuid().optional(),reviewVersion:z25.int().positive().optional(),acceptanceDecisionId:z25.uuid().optional(),freshness:z25.enum(["CURRENT_BASIS","STALE_BASIS"])});var VideoGenerationViewSchema=z25.strictObject({generationId:VideoGenerationIdSchema,tenantId:TenantIdSchema,projectId:ProjectIdSchema,productionId:ProductionIdSchema,shotId:ShotIdSchema,preparationId:PreparationIdSchema,contractId:GenerationContractIdSchema,contractFingerprint:ContentFingerprintSchema,connection:z25.strictObject({connectionId:z25.uuid(),connectionVersion:z25.int().positive(),modelProfileId:z25.string(),modelProfileVersion:z25.int().positive()}),operationId:OperationIdSchema,provider:VideoProviderProfileSchema,runtimeStatus:z25.enum(["PENDING","READY","RUNNING","WAITING","SUCCEEDED","FAILED","CANCELLED","SUPERSEDED"]),providerStatus:z25.enum(["NOT_SUBMITTED","SUBMITTING","PENDING","UNKNOWN","SUCCEEDED","FAILED"]),freshness:z25.enum(["CURRENT_BASIS","STALE_BASIS"]),cancellationRequested:z25.boolean(),candidate:VideoCandidateSchema.nullable(),createdByPrincipalId:PrincipalIdSchema,createdAt:z25.iso.datetime({offset:true})});var VideoQueryPageSchema=z25.strictObject({items:z25.array(VideoGenerationViewSchema),page:QueryPageInfoSchema});var VideoSummarySchema=z25.strictObject({generations:z25.int().nonnegative(),running:z25.int().nonnegative(),waiting:z25.int().nonnegative(),registeredCandidates:z25.int().nonnegative(),testCandidates:z25.int().nonnegative(),liveCandidates:z25.int().nonnegative()});var TimelineDurationSchema=z26.strictObject({totalMs:z26.int().positive().max(603e4),targetMs:z26.int().min(3e4).max(6e4),minMs:z26.literal(3e4),maxMs:z26.literal(6e4),deltaTargetMs:z26.int(),classification:z26.enum(["TOO_SHORT","WITHIN_TARGET","TOO_LONG"])});var TimelineClipSchema=z26.strictObject({ordinal:z26.int().positive().max(200),source:AcceptedShotReferenceSchema,technical:VideoTechnicalMetadataSchema,sourceInMs:z26.int().nonnegative(),sourceOutMs:z26.int().positive(),startMs:z26.int().nonnegative(),durationMs:z26.int().positive(),transition:ClipTransitionSchema,framing:ClipFramingSchema.optional()});var TimelineManifestSchema=z26.strictObject({schemaVersion:z26.literal(1),caption:CaptionVersionSchema.optional(),captionStyle:CaptionRenderStyleSchema.optional(),audio:TimelineAudioCompositionSchema.optional(),graphics:z26.array(TimelineGraphicSchema).max(8).optional(),basis:z26.strictObject({briefVersionId:BriefVersionIdSchema,briefVersion:z26.int().positive(),storyVersion:z26.int().positive(),planVersionId:SceneShotPlanVersionIdSchema,planVersion:z26.int().positive()}),output:z26.strictObject({aspectRatio:z26.enum(["16:9","9:16"]),profile:DeliveryOutputProfileSchema}),clips:z26.array(TimelineClipSchema).min(1).max(200),duration:TimelineDurationSchema,missingPlannedShotIds:z26.array(ShotIdSchema).max(200),executionClass:z26.enum(["LIVE","TEST_ONLY"])});var TimelineVersionIdentityShape={id:z26.uuid(),timelineId:z26.uuid(),tenantId:TenantIdSchema,projectId:ProjectIdSchema,productionId:ProductionIdSchema,version:z26.int().positive(),fingerprint:z26.string().regex(/^[0-9a-f]{64}$/),createdByPrincipalId:PrincipalIdSchema,createdAt:z26.iso.datetime({offset:true})};function validateTimelineAttachments(timeline,context){if(timeline.audio?.tracks.some(t=>t.source.tenantId!==timeline.tenantId||t.source.projectId!==timeline.projectId||t.source.productionId!==timeline.productionId||t.startMs+t.sourceOutMs-t.sourceInMs>timeline.duration.totalMs||(t.startMs+t.sourceOutMs-t.sourceInMs)*48>Math.round(timeline.duration.totalMs*30/1e3)*1600))context.addIssue({code:"custom",message:"Timeline audio ownership or physical placement mismatch"});const caption=timeline.caption;if(timeline.captionStyle&&!caption)context.addIssue({code:"custom",message:"Timeline caption style requires an exact caption"});if(caption&&(caption.tenantId!==timeline.tenantId||caption.projectId!==timeline.projectId||caption.productionId!==timeline.productionId||caption.content.durationMs!==timeline.duration.totalMs))context.addIssue({code:"custom",message:"Timeline caption ownership or duration mismatch"})}var TimelineVersionSchema=TimelineManifestSchema.extend(TimelineVersionIdentityShape).superRefine(validateTimelineAttachments);import{z as z27}from"zod";var RoughCutProfileIdSchema=z27.enum(["PREVIEW_H264_480P_V1","PREVIEW_H264_720P_V1","PREVIEW_H264_1080P_V1"]);var RoughCutProfileSchema=z27.strictObject({captionPolicy:z27.literal("BURN_IN").optional(),captionStyle:CaptionRenderStyleSchema.optional(),graphicsPolicy:z27.literal("OVERLAY_V1").optional(),id:RoughCutProfileIdSchema,algorithm:z27.enum(["ORDERED_TRIM_CUT_V1","ORDERED_COMPOSE_V2"]),picturePolicy:PicturePolicySchema.optional(),width:z27.union([z27.literal(854),z27.literal(480),z27.literal(1280),z27.literal(720),z27.literal(1920),z27.literal(1080)]),height:z27.union([z27.literal(854),z27.literal(480),z27.literal(1280),z27.literal(720),z27.literal(1920),z27.literal(1080)]),frameRate:z27.literal(30),codec:z27.literal("h264"),pixelFormat:z27.literal("yuv420p"),fit:z27.literal("PAD"),hasAudio:z27.boolean(),audioMix:AudioMixProfileSchema.optional(),framePolicy:z27.literal("CUMULATIVE_NEAREST_FRAME")}).superRefine((profile,context)=>{const pair=profile.id==="PREVIEW_H264_480P_V1"?[854,480]:profile.id==="PREVIEW_H264_720P_V1"?[1280,720]:[1920,1080];if(!(profile.width===pair[0]&&profile.height===pair[1]||profile.width===pair[1]&&profile.height===pair[0]))context.addIssue({code:"custom",message:"Exact preview profile geometry required"});if(profile.hasAudio!==!!profile.audioMix)context.addIssue({code:"custom",message:"Audio policy requires exact native mix"});if(!!profile.captionStyle!==!!profile.captionPolicy)context.addIssue({code:"custom",message:"Caption policy and style must agree"})});var RoughCutManifestSchema=z28.strictObject({schemaVersion:z28.literal(1),timeline:TimelineVersionSchema,profile:RoughCutProfileSchema,frames:z28.array(z28.strictObject({ordinal:z28.int().positive().max(200),startFrame:z28.int().nonnegative().max(1800),frameCount:z28.int().positive().max(1800),overlapFrames:z28.int().nonnegative().max(30).default(0)})).min(1).max(200),totalFrames:z28.int().min(900).max(1800)});import{z as z54}from"zod";import{z as z52}from"zod";import{z as z50}from"zod";import{z as z29}from"zod";var Fingerprint2=z29.string().regex(/^[0-9a-f]{64}$/);var ProgrammaticAcceptedVisualSourceReferenceSchema=z29.strictObject({sourceKind:z29.literal("PROGRAMMATIC"),acceptanceId:z29.uuid(),reviewId:z29.uuid(),renderId:z29.uuid(),compositionId:z29.uuid(),compositionVersionId:z29.uuid(),compositionVersion:z29.int().positive(),compositionFingerprint:Fingerprint2,renderManifestFingerprint:Fingerprint2,shotId:ShotIdSchema,artifactId:ArtifactIdSchema,representationId:ArtifactRepresentationIdSchema,checksumSha256:Fingerprint2,artifactChecksumSha256:Fingerprint2,planVersionId:SceneShotPlanVersionIdSchema,planVersion:z29.int().positive(),shotPlanningRevision:z29.int().positive(),executionClass:z29.enum(["LIVE","TEST_ONLY"]),reviewResult:z29.enum(["PASS","WARNING"])});var ImportedAcceptedVisualSourceReferenceSchema=z29.strictObject({sourceKind:z29.literal("IMPORTED"),acceptanceId:z29.uuid(),reviewId:z29.uuid(),normalizationId:z29.uuid(),sourceId:z29.uuid(),sourceVersionId:z29.uuid(),shotId:ShotIdSchema,artifactId:ArtifactIdSchema,representationId:ArtifactRepresentationIdSchema,checksumSha256:Fingerprint2,executionClass:z29.enum(["LIVE","TEST_ONLY"]),reviewResult:z29.enum(["PASS","WARNING"])});var AcceptedVisualSourceReferenceSchema=z29.union([AcceptedShotReferenceSchema,ProgrammaticAcceptedVisualSourceReferenceSchema,ImportedAcceptedVisualSourceReferenceSchema]);import{z as z49}from"zod";import{z as z31}from"zod";import{z as z30}from"zod";var id4=z30.uuid().toLowerCase();var hash3=z30.string().regex(/^[0-9a-f]{64}$/);var ImportedSynchronousAudioPurposeSchema=z30.literal("SOURCE_SYNC");var SourceSyncPcmMediaSchema=z30.strictObject({profile:z30.literal("PCM_S16LE_48000_SOURCE_SYNC_V1"),audioCodec:z30.literal("pcm_s16le"),sampleRateHz:z30.literal(48e3),audioChannels:z30.union([z30.literal(1),z30.literal(2)]),sampleCount:z30.int().min(1600).max(576e3),durationMs:z30.number().positive().max(12e3)}).refine(m=>m.sampleCount%1600===0&&m.durationMs===m.sampleCount/48);var ImportedSynchronousAudioExtractionSchema=z30.strictObject({schemaVersion:z30.literal(1),purpose:ImportedSynchronousAudioPurposeSchema,tenantId:id4,projectId:id4,productionId:id4,shotId:id4,sourceId:id4,sourceVersionId:id4,normalizationId:id4,originalArtifactId:id4,originalRepresentationId:id4,originalChecksumSha256:hash3,sourceRange:z30.strictObject({clock:z30.literal("SOURCE_ZERO_BASED_CFR30"),startFrame:z30.int().nonnegative().max(1799),endFrame:z30.int().positive().max(1800)}),destinationStartSample:z30.literal(0)}).refine(v=>v.sourceRange.endFrame>v.sourceRange.startFrame&&v.sourceRange.endFrame-v.sourceRange.startFrame<=360);var ImportedSynchronousAudioSourceSchema=z30.strictObject({schemaVersion:z30.literal(1),purpose:ImportedSynchronousAudioPurposeSchema,tenantId:id4,projectId:id4,productionId:id4,shotId:id4,sourceId:id4,sourceVersionId:id4,normalizationId:id4,originalArtifactId:id4,originalRepresentationId:id4,originalChecksumSha256:hash3,sourceRange:z30.strictObject({clock:z30.literal("SOURCE_ZERO_BASED_CFR30"),startFrame:z30.int().nonnegative(),endFrame:z30.int().positive()}),destinationStartSample:z30.int().nonnegative(),media:z30.union([AudioMediaSchema,SourceSyncPcmMediaSchema]),wavChecksumSha256:hash3,wavByteSize:z30.int().min(44).max(12582912)}).superRefine((v,ctx)=>{if(v.sourceRange.endFrame<=v.sourceRange.startFrame||(v.sourceRange.endFrame-v.sourceRange.startFrame)*1600!==v.media.sampleCount)ctx.addIssue({code:"custom",message:"Exact CFR30 interval and PCM48k sample mapping required"})});var id5=z31.uuid().toLowerCase();var key2=z31.string().trim().min(1).max(200);var SourceSyncAudioStartSchema=z31.strictObject({tenantId:id5,productionId:id5,normalizationId:id5,expectedProductionRevision:z31.int().positive(),expectedVersion:z31.int().nonnegative(),idempotencyKey:key2});var SourceSyncAudioGetSchema=z31.strictObject({tenantId:id5,productionId:id5,shotId:id5,versionId:id5});var SourceSyncAudioVersionSchema=z31.strictObject({schemaVersion:z31.literal(1),purpose:z31.literal("SOURCE_SYNC"),id:id5,audioId:id5,version:z31.int().positive(),tenantId:id5,projectId:id5,productionId:id5,shotId:id5,normalizationId:id5,artifactId:id5,representationId:id5,provenance:ImportedSynchronousAudioSourceSchema,previousVersionId:id5.nullable(),executionClass:z31.enum(["LIVE","TEST_ONLY"]),createdByPrincipalId:id5,createdAt:z31.iso.datetime({offset:true})});var SourceSyncAudioReceiptSchema=z31.strictObject({semanticStatus:z31.literal("SUCCESS"),version:SourceSyncAudioVersionSchema,productionRevision:z31.int().positive()});var SourceSyncAudioViewSchema=z31.strictObject({version:SourceSyncAudioVersionSchema,status:z31.enum(["CURRENT","STALE"]),availability:z31.enum(["AVAILABLE","UNAVAILABLE"])});import{z as z32}from"zod";var SourceSoundTreatmentSchema=z32.strictObject({policy:z32.enum(["KEEP","MUTE","DUCK"]),gainPermille:z32.int().min(0).max(1e3),duckingPermille:z32.int().min(0).max(1e3)}).superRefine((v,c)=>{if(v.policy==="MUTE"&&v.gainPermille!==0||v.policy!=="DUCK"&&v.duckingPermille!==1e3)c.addIssue({code:"custom",message:"Mute requires zero gain; ducking requires explicit DUCK"})});import{z as z35}from"zod";import{z as z33}from"zod";var SpeechParameterValueSchema=z33.union([z33.string().max(4096),z33.number().finite(),z33.boolean(),z33.array(z33.string().max(4096)).max(100),z33.record(z33.string().min(1).max(100),z33.string().max(4096)).refine(v=>Object.keys(v).length<=100)]);var SpeechParameterRuleSchema=z33.strictObject({label:z33.string().trim().min(1).max(100).regex(/^[^\p{Cc}]*$/u),type:z33.enum(["NUMBER","INTEGER","STRING","BOOLEAN","STRING_ARRAY","STRING_MAP"]),required:z33.boolean().default(false),min:z33.number().optional(),max:z33.number().optional(),maxLength:z33.int().positive().max(4096).optional(),options:z33.array(z33.string().min(1).max(100)).max(100).optional(),default:SpeechParameterValueSchema.optional(),unit:z33.string().max(40).optional(),description:z33.string().max(500).optional(),maxItems:z33.int().positive().max(100).optional(),maxKeyLength:z33.int().positive().max(100).optional()});var SpeechParametersSchema=z33.record(z33.string().regex(/^[a-z][a-z0-9_]{0,49}$/),SpeechParameterValueSchema).refine(p=>Object.keys(p).length<=24);var SpeechVoiceSchema=z33.strictObject({id:z33.string().min(1).max(100),label:z33.string().min(1).max(100),languages:z33.array(z33.string().min(2).max(20)).min(1).max(32).optional(),parameterDefaults:SpeechParametersSchema.optional(),parameterOptions:z33.record(z33.string(),z33.array(z33.string().min(1).max(100)).min(1).max(100)).optional(),unsupportedParameters:z33.array(z33.string()).max(24).optional()});import{z as z34}from"zod";var cpuSpeechResources={schemaVersion:1,wrapper:{name:"sherpa-onnx-node",url:"https://registry.npmjs.org/sherpa-onnx-node/-/sherpa-onnx-node-1.12.33.tgz",byteSize:10289,sha256:"c56a08c884dcd3ec4b4d815edea4aabbff62fbcd1b0176e88480b5d9b920fa03"},engines:[{platform:"linux-x64",package:"sherpa-onnx-linux-x64",url:"https://registry.npmjs.org/sherpa-onnx-linux-x64/-/sherpa-onnx-linux-x64-1.12.33.tgz",byteSize:10137208,sha256:"651f529869249628c3e304744ab21d658f880be3684e8ead93702f2055bfb5d1",engineDigest:"dbc8c7bcdcd9dc24183894eabb945001ae001fe69cd16c427f01cf41e598c33a",fileCount:25,unpackedBytes:30623890},{platform:"linux-arm64",package:"sherpa-onnx-linux-arm64",url:"https://registry.npmjs.org/sherpa-onnx-linux-arm64/-/sherpa-onnx-linux-arm64-1.12.33.tgz",byteSize:12826691,sha256:"fec1be880a3e6a79e30db4075690759218a28923fafda51983649bcae3efdfbf",engineDigest:"447387941363150362e034f0e8bceb11922b95f11d8553882b7386ad24f1e92f",fileCount:25,unpackedBytes:37679333},{platform:"darwin-x64",package:"sherpa-onnx-darwin-x64",url:"https://registry.npmjs.org/sherpa-onnx-darwin-x64/-/sherpa-onnx-darwin-x64-1.12.33.tgz",byteSize:25289549,sha256:"137082336fa9bf721385c85828b29766dd0d8e0ce67dcc8691d9a5daa7171ce9",engineDigest:"a298b1bd79b690a7cc26eed975980ff69262967627340525a9ef66a8ca45b091",fileCount:26,unpackedBytes:85413811},{platform:"darwin-arm64",package:"sherpa-onnx-darwin-arm64",url:"https://registry.npmjs.org/sherpa-onnx-darwin-arm64/-/sherpa-onnx-darwin-arm64-1.12.33.tgz",byteSize:22164444,sha256:"c5d96d89deadb042f603a83dd0b93b9f147ca635ae3316e83718cd5566c0b61a",engineDigest:"f409d0ef9b864983c784b27369b40a20a988347ecfdbc27a34ea8a8533ccb589",fileCount:26,unpackedBytes:75969095}],model:{url:"https://github.com/k2-fsa/sherpa-onnx/releases/download/tts-models/kokoro-int8-multi-lang-v1_1.tar.bz2",byteSize:147052523,sha256:"259c9c8bc906d6078e4e0570421885dabb68b539c2f970fcbb890a58eeaf3e9c",directory:"kokoro-int8-multi-lang-v1_1",treeDigest:"ebd0959580940e20dbb10a55775ec94e47229c7c503f65932403fe0764667126",fileCount:377,unpackedBytes:215227172}};var kokoroCpuProfile=Object.freeze({id:"KOKORO_INT8_ZH_EN_V1",adapter:"KOKORO_ONNX_CPU_V1",engineVersion:"1.12.33",engineDigest:"f409d0ef9b864983c784b27369b40a20a988347ecfdbc27a34ea8a8533ccb589",modelDigest:"ebd0959580940e20dbb10a55775ec94e47229c7c503f65932403fe0764667126",modelArchiveSha256:"259c9c8bc906d6078e4e0570421885dabb68b539c2f970fcbb890a58eeaf3e9c",sampleRateHz:24e3,speakerCount:103,maxCharacters:600,maxDurationMs:6e4});var CpuSpeechToolSelectionSchema=z34.strictObject({engineDirectory:z34.string().min(1).max(4096),modelDirectory:z34.string().min(1).max(4096)});var CpuSpeechInputSchema=z34.strictObject({text:z34.string().min(1).max(kokoroCpuProfile.maxCharacters).refine(s=>s.trim().length>0&&!new RegExp("\\p{Cc}","u").test(s.replace(/[\t\n]/g,""))&&new TextEncoder().encode(s).length<=2400),voiceId:z34.int().min(0).max(kokoroCpuProfile.speakerCount-1),language:z34.enum(["zh","en"]),speed:z34.number().min(.5).max(2).default(1)});var SpeechDeliverySchema=z34.discriminatedUnion("mode",[z34.strictObject({mode:z34.literal("NON_STREAMING"),output:z34.literal("COMPLETE_AUDIO")}),z34.strictObject({mode:z34.literal("SENTENCE_CHUNKED"),output:z34.literal("ORDERED_SENTENCES")}),z34.strictObject({mode:z34.literal("TRUE_STREAMING"),output:z34.literal("CONTINUOUS_AUDIO")})]);var CpuSpeechIdentitySchema=z34.strictObject({profileId:z34.literal(kokoroCpuProfile.id),adapter:z34.literal(kokoroCpuProfile.adapter),platform:z34.strictObject({os:z34.enum(["darwin","linux"]),architecture:z34.enum(["arm64","x64"])}),engineVersion:z34.literal(kokoroCpuProfile.engineVersion),engineDigest:LocalDigestSchema,modelDigest:z34.literal(kokoroCpuProfile.modelDigest),bridgeSha256:LocalDigestSchema,nodeSha256:LocalDigestSchema}).refine(v=>cpuSpeechResources.engines.some(e=>e.platform===v.platform.os+"-"+v.platform.architecture&&e.engineDigest===v.engineDigest));var CpuSpeechObservationSchema=z34.strictObject({inputSha256:LocalDigestSchema,voiceId:CpuSpeechInputSchema.shape.voiceId,language:CpuSpeechInputSchema.shape.language,outputSha256:LocalDigestSchema,outputBytes:z34.int().min(4844).max(2880044),sampleRateHz:z34.literal(kokoroCpuProfile.sampleRateHz),sampleCount:z34.int().min(2400).max(144e4),durationMs:z34.number().min(100).max(kokoroCpuProfile.maxDurationMs),modelLoadMs:z34.number().nonnegative(),synthesisMs:z34.number().nonnegative(),outputReadyMs:z34.number().positive(),realTimeFactor:z34.number().nonnegative(),cpuMs:z34.number().nonnegative(),peakRssBytes:z34.int().positive()});var CpuSpeechQualificationSchema=z34.strictObject({identity:CpuSpeechIdentitySchema,delivery:z34.strictObject({mode:z34.literal("NON_STREAMING"),output:z34.literal("COMPLETE_AUDIO")}),cancellation:z34.literal("OWNED_PROCESS"),technicalStatus:z34.literal("TECHNICALLY_OBSERVED"),listeningStatus:z34.literal("NOT_PROVEN"),observations:z34.array(CpuSpeechObservationSchema).min(3).max(24),observedAt:z34.iso.datetime({offset:true})});var CpuSpeechCapabilitySchema=z34.strictObject({identity:CpuSpeechIdentitySchema,voices:z34.array(z34.strictObject({voiceId:CpuSpeechInputSchema.shape.voiceId,languages:z34.array(CpuSpeechInputSchema.shape.language).min(1).max(2).refine(v=>new Set(v).size===v.length)})).min(1).max(8).refine(v=>new Set(v.map(s=>s.voiceId)).size===v.length)});var CpuSpeechInstallationSchema=CpuSpeechToolSelectionSchema.extend({voiceIds:z34.array(CpuSpeechInputSchema.shape.voiceId).min(1).max(8).refine(v=>new Set(v).size===v.length)});var NativeSpeechExecutionSchema=z35.strictObject({schemaVersion:z35.literal(1),profileId:z35.literal(kokoroCpuProfile.id),modelDigest:z35.literal(kokoroCpuProfile.modelDigest)});var speed=SpeechParameterRuleSchema.safeExtend({type:z35.literal("NUMBER"),min:z35.number().min(.5).max(2),max:z35.number().min(.5).max(2),default:z35.number().min(.5).max(2).default(1)}).refine(r=>r.min<=r.max&&r.default>=r.min&&r.default<=r.max);var voice=SpeechVoiceSchema.safeExtend({id:z35.string().regex(/^(?:[0-9]|[1-9][0-9]|10[0-2])$/),languages:z35.array(z35.enum(["zh","en"])).min(1).max(2).optional()});var NativeSpeechModelProfileSchema=z35.strictObject({id:ModelProfileIdSchema,version:z35.int().positive(),label:z35.string().trim().min(1).max(100).regex(/^[^\p{Cc}]*$/u),protocol:z35.literal(kokoroCpuProfile.adapter),execution:NativeSpeechExecutionSchema,textMaxCharacters:z35.int().min(1).max(kokoroCpuProfile.maxCharacters),languages:z35.array(z35.enum(["zh","en"])).min(1).max(2).refine(v=>new Set(v).size===v.length),voices:z35.array(voice).min(1).max(kokoroCpuProfile.speakerCount).refine(v=>new Set(v.map(voice2=>voice2.id)).size===v.length),parameters:z35.strictObject({speed}),sourceUrl:z35.literal("https://k2-fsa.github.io/sherpa/onnx/tts/pretrained_models/kokoro.html"),output:z35.literal("PCM_S16LE_48000_V1"),normalizationVersion:z35.literal("SPEECH_PCM_V1")});import{z as z48}from"zod";import{z as z39}from"zod";import{z as z37}from"zod";import{z as z36}from"zod";var receiptId=z36.string().regex(/^[A-Za-z0-9_.:-]{1,500}$/);var resultHost="dashscope-result-bj.oss-cn-beijing.aliyuncs.com";var maxQwenTtsAudioBytes=12*1024*1024;var QwenTtsReceiptSchema=z36.strictObject({providerRequestId:receiptId,audioId:receiptId,audioUrl:z36.url().max(8192).meta({writeOnly:true}),expiresAt:z36.iso.datetime(),usage:z36.strictObject({characters:z36.int().min(0).max(6e3)}).optional()}).refine(({audioUrl,expiresAt})=>{try{const url=new URL(audioUrl);const expires=url.searchParams.getAll("Expires");return url.href===audioUrl&&url.protocol==="https:"&&url.hostname===resultHost&&!url.username&&!url.password&&!url.port&&!url.hash&&url.pathname.endsWith(".wav")&&(expires.length===0||expires.length===1&&/^\d{1,12}$/.test(expires[0])&&Number(expires[0])*1e3===Date.parse(expiresAt))}catch{return false}},"Invalid Qwen TTS audio receipt");var QwenSpeechProviderStateSchema=z36.discriminatedUnion("state",[z36.strictObject({state:z36.literal("RECEIVED"),receipt:QwenTtsReceiptSchema}),z36.strictObject({state:z36.literal("UNKNOWN")}),z36.strictObject({state:z36.literal("REJECTED")})]);var MacSpeechIdentitySchema=z37.strictObject({adapter:z37.literal("MACOS_SAY_V1"),voiceId:z37.literal("com.apple.speech.synthesis.voice.Albert"),locale:z37.literal("en-US"),systemBuild:z37.string().regex(/^[A-Za-z0-9]{1,40}$/),saySha256:LocalDigestSchema,sandboxSha256:LocalDigestSchema,synthesizerSha256:LocalDigestSchema,voiceCatalogSha256:LocalDigestSchema,voiceProbeSha256:LocalDigestSchema});var MacSpeechInputSchema=z37.strictObject({text:z37.string().min(1).max(2e3).refine(text6=>text6.trim().length>0&&!text6.includes("[[")&&!new RegExp("\\p{Cc}","u").test(text6)&&new TextEncoder().encode(text6).length<=4096),rateWordsPerMinute:z37.int().min(80).max(240)});var SpeechSynthesisRecipeSchema=MacSpeechInputSchema.extend({processor:z37.literal("SPEECH_SYNTHESIZE"),identity:MacSpeechIdentitySchema});var audioObject=z37.strictObject({checksumSha256:LocalDigestSchema,byteSize:z37.int().min(44).max(12*1024*1024)});var SpeechSynthesisEvidenceSchema=z37.strictObject({processor:z37.literal("SPEECH_SYNTHESIZE"),source:audioObject,normalized:audioObject,sourceMedia:z37.strictObject({sampleRateHz:z37.literal(22050),audioChannels:z37.literal(1),sampleCount:z37.int().min(2205).max(1323e3)}),media:AudioMediaSchema.refine(value2=>value2.audioChannels===1),padSamples:z37.int().min(0).max(47)});var QwenSpeechRecipeSchema=z37.strictObject({processor:z37.literal("SPEECH_EXTERNAL_QWEN"),generationId:LocalIdSchema,quoteFingerprint:LocalDigestSchema});var QwenSpeechEvidenceSchema=SpeechSynthesisEvidenceSchema.extend({processor:z37.literal("SPEECH_EXTERNAL_QWEN"),providerRequestId:QwenTtsReceiptSchema.shape.providerRequestId,audioId:QwenTtsReceiptSchema.shape.audioId,sourceMedia:z37.strictObject({sampleRateHz:z37.literal([8e3,12e3,16e3,22050,24e3,32e3,44100,48e3]),audioChannels:z37.union([z37.literal(1),z37.literal(2)]),sampleCount:z37.int().min(800).max(288e4)}).refine(({sampleRateHz,sampleCount})=>sampleCount>=sampleRateHz/10&&sampleCount<=sampleRateHz*60)});import{z as z38}from"zod";var NativeSpeechOptionsSchema=z38.strictObject({schemaVersion:z38.literal(1),models:z38.array(z38.strictObject({modelProfileId:ModelProfileIdSchema,modelProfileVersion:z38.int().positive(),label:z38.string().min(1).max(100),profileId:z38.literal(kokoroCpuProfile.id),textMaxCharacters:z38.int().min(1).max(kokoroCpuProfile.maxCharacters)})).max(20),devices:z38.array(z38.strictObject({deviceId:z38.uuid(),label:z38.string().min(1).max(120),profileId:z38.literal(kokoroCpuProfile.id),voices:CpuSpeechCapabilitySchema.shape.voices})).max(50),possiblyTruncated:z38.boolean()});var SpeechModelProfileSchema=z39.strictObject({id:ModelProfileIdSchema,version:z39.int().positive(),providerId:ProviderIdSchema,modelId:z39.string().min(1).max(160).nullable(),protocol:z39.enum(["QWEN_TTS","QWEN_AUDIO_TTS","OPENAI_TTS","XAI_TTS","GEMINI_INTERACTIONS_TTS","VOLCENGINE_TTS"]),label:z39.string().trim().min(1).max(100).regex(/^[^\p{Cc}]*$/u),textMaxCharacters:z39.int().positive().max(6e3),requestTimeoutMs:z39.int().positive().max(3e5),workspaceRequired:z39.boolean(),voices:z39.array(SpeechVoiceSchema).min(1).max(100),languages:z39.array(z39.string().min(2).max(20)).min(1).max(32),parameters:z39.record(z39.string().regex(/^[a-z][a-z0-9_]{0,49}$/),SpeechParameterRuleSchema),sourceUrl:z39.url().max(2048),verifiedAt:z39.iso.date(),providerTextMaxCharacters:z39.int().positive().nullable(),resourceId:z39.string().min(1).max(100).nullable(),output:z39.literal("PCM_S16LE_48000_V1"),normalizationVersion:z39.literal("SPEECH_PCM_V1")});var SpeechScopeSchema=z39.strictObject({tenantId:TenantIdSchema,productionId:ProductionIdSchema});var SpeechExecutionBindingSchema=z39.strictObject({tenantId:TenantIdSchema,connectionId:z39.uuid(),connectionVersion:z39.int().positive(),credentialRef:z39.uuid(),credentialVersion:z39.int().positive(),profile:SpeechModelProfileSchema,executionClass:z39.enum(["LIVE","TEST_ONLY"])});var SpeechStartSchema=SpeechScopeSchema.extend({voiceProfile:VoiceProfileUseSchema.optional(),soundCue:z39.strictObject({soundPlanVersionId:z39.uuid(),cueId:z39.string().regex(/^[a-z][a-z0-9_-]{0,63}$/)}).optional(),expectedProductionRevision:z39.int().positive(),expectedAudioVersion:z39.int().nonnegative(),expectedModelProfileVersion:z39.int().positive(),idempotencyKey:z39.string().trim().min(1).max(200),selection:ProviderSelectionSchema,text:z39.string().min(1).max(6e3).refine(s=>s.trim().length>0&&!s.includes("\0")),voice:z39.string().min(1).max(100),parameters:SpeechParametersSchema.default({})});var SpeechGetSchema=SpeechScopeSchema.extend({generationId:z39.uuid()});var SpeechAdmissionSchema=z39.strictObject({humanLinks:HumanLinksSchema.optional(),semanticStatus:z39.literal("ACCEPTED"),generationId:z39.uuid(),runtimeJobId:z39.uuid(),productionRevision:z39.int().positive(),executionClass:z39.enum(["LIVE","TEST_ONLY"])});var SpeechGenerationViewSchema=SpeechAdmissionSchema.omit({semanticStatus:true}).extend({tenantId:TenantIdSchema,productionId:ProductionIdSchema,soundCue:SpeechStartSchema.shape.soundCue,voiceProfile:VoiceProfileUseSchema.optional(),text:z39.string().min(1).max(6e3),voice:z39.string().min(1).max(100),parameters:SpeechParametersSchema,profile:SpeechModelProfileSchema,connectionId:z39.uuid(),connectionVersion:z39.int().positive(),runtimeStatus:z39.enum(["PENDING","READY","RUNNING","WAITING","SUCCEEDED","FAILED","CANCELLED","SUPERSEDED"]),providerStatus:z39.enum(["NOT_SUBMITTED","SUBMITTING","UNKNOWN","SUCCEEDED","REJECTED"]),cancellationRequested:z39.boolean(),result:AudioReceiptSchema.nullable(),createdAt:z39.iso.datetime({offset:true})});var localSpeechBody=z39.strictObject({expectedProductionRevision:SpeechStartSchema.shape.expectedProductionRevision,expectedAudioVersion:SpeechStartSchema.shape.expectedAudioVersion,idempotencyKey:SpeechStartSchema.shape.idempotencyKey,text:SpeechStartSchema.shape.text,rateWordsPerMinute:MacSpeechInputSchema.shape.rateWordsPerMinute.optional(),voiceProfile:VoiceProfileUseSchema.optional(),soundCue:SpeechStartSchema.shape.soundCue,deviceExecution:z39.strictObject({deviceId:z39.uuid().optional()})});function refineLocalSpeech(v,ctx){const valid=v.voiceProfile?v.rateWordsPerMinute===void 0&&CpuSpeechInputSchema.shape.text.safeParse(v.text).success&&(v.voiceProfile.usage!=="AUDITION"||!v.soundCue):false;const systemValid=!v.voiceProfile&&!v.soundCue&&MacSpeechInputSchema.safeParse({text:v.text,rateWordsPerMinute:v.rateWordsPerMinute}).success;if(!(v.voiceProfile?valid:systemValid))ctx.addIssue({code:"custom",message:"Exact saved CPU voice or anonymous system voice required"})}var LocalSpeechBodySchema=localSpeechBody.superRefine(refineLocalSpeech);var LocalSpeechStartSchema=SpeechScopeSchema.extend(localSpeechBody.shape).superRefine(refineLocalSpeech);var NativeSpeechBindingSchema=z39.strictObject({profile:NativeSpeechModelProfileSchema,voice:z39.string().min(1).max(100),parameters:SpeechParametersSchema});var NativeSpeechBasisSchema=z39.strictObject({schemaVersion:z39.literal(1),modelProfileId:ModelProfileIdSchema,modelProfileVersion:z39.int().positive(),label:z39.string().min(1).max(100),voice:z39.string().min(1).max(100),parameters:SpeechParametersSchema,execution:NativeSpeechExecutionSchema});var LocalSpeechBindingSchema=z39.strictObject({target:z39.literal("TENANT_DEVICE"),tenantId:TenantIdSchema,deviceId:z39.uuid(),identity:z39.union([MacSpeechIdentitySchema,CpuSpeechIdentitySchema]),native:NativeSpeechBindingSchema.optional(),executionClass:z39.literal("LIVE")}).refine(v=>v.identity.adapter==="KOKORO_ONNX_CPU_V1"===!!v.native);var localSpeechExecution=z39.strictObject({target:z39.literal("TENANT_DEVICE"),deviceId:z39.uuid(),identity:LocalSpeechBindingSchema.shape.identity});var LocalSpeechAdmissionSchema=SpeechAdmissionSchema.extend({executionClass:z39.literal("LIVE"),deviceExecution:localSpeechExecution});var LocalSpeechGenerationViewSchema=SpeechGenerationViewSchema.omit({voiceProfile:true,soundCue:true,parameters:true,profile:true,voice:true,connectionId:true,connectionVersion:true,providerStatus:true}).extend({executionClass:z39.literal("LIVE"),deviceExecution:localSpeechExecution,rateWordsPerMinute:MacSpeechInputSchema.shape.rateWordsPerMinute.optional(),voiceProfile:VoiceProfileUseSchema.optional(),soundCue:SpeechStartSchema.shape.soundCue,nativeBasis:NativeSpeechBasisSchema.optional()});var SpeechOptionsSchema=SpeechScopeSchema.extend({native:NativeSpeechOptionsSchema.optional(),options:z39.array(z39.strictObject({selection:ProviderSelectionSchema,profile:SpeechModelProfileSchema,connectionLabel:z39.string().min(1).max(100),connectionVersion:z39.int().positive(),executionTarget:z39.literal("TENANT_DEVICE").optional()})).max(100),possiblyTruncated:z39.boolean()});import{z as z47}from"zod";import{z as z44}from"zod";import{z as z40}from"zod";var KeyframeGenerationIdSchema=z40.uuid().brand();var KeyframeProviderProfileSchema=z40.strictObject({id:z40.string().regex(/^[a-zA-Z0-9][a-zA-Z0-9_.-]{0,79}$/),adapterVersion:z40.string().min(1).max(80),model:z40.string().min(1).max(120),executionClass:z40.enum(["LIVE","TEST_ONLY"]),mediaType:z40.literal("IMAGE"),mode:z40.literal("REFERENCE_TO_IMAGE"),referenceRoles:z40.array(ReferenceRoleSchema).min(1).max(6),aspectRatios:z40.array(z40.enum(["16:9","9:16"])).min(1).max(2),maxReferences:z40.int().min(1).max(12),correlationLookup:z40.boolean()});var KeyframeStartInputSchema=z40.strictObject({expectedExecution:ExpectedGenerationExecutionSchema.optional(),selection:ProviderSelectionSchema.optional(),tenantId:TenantIdSchema,projectId:ProjectIdSchema,productionId:ProductionIdSchema,shotId:ShotIdSchema,preparationId:PreparationIdSchema,contractId:GenerationContractIdSchema,contractFingerprint:ContentFingerprintSchema,idempotencyKey:z40.string().trim().min(1).max(200)});var KeyframeDeviceStartInputSchema=KeyframeStartInputSchema.omit({selection:true,expectedExecution:true}).extend({deviceId:z40.uuid(),approvedQuote:GenerationCostQuoteSchema});var KeyframeGetInputSchema=z40.strictObject({tenantId:TenantIdSchema,productionId:ProductionIdSchema,generationId:KeyframeGenerationIdSchema});var KeyframeQueryInputSchema=z40.strictObject({tenantId:TenantIdSchema,productionId:ProductionIdSchema,shotId:ShotIdSchema.optional(),limit:QueryLimitSchema,next:ContinuationSchema.optional()});var KeyframeAdmissionSchema=z40.strictObject({semanticStatus:z40.literal("ACCEPTED"),generationId:KeyframeGenerationIdSchema,operationId:OperationIdSchema,productionId:ProductionIdSchema,contractId:GenerationContractIdSchema,executionClass:z40.enum(["LIVE","TEST_ONLY"])});var KeyframeCandidateSchema=z40.strictObject({id:z40.uuid(),artifactId:ArtifactIdSchema,representationId:ArtifactRepresentationIdSchema,availability:z40.enum(["AVAILABLE","INVALID"]),observation:z40.enum(["NOT_OBSERVED","OBSERVED"]),evaluation:z40.enum(["UNREVIEWED","PASS","WARNING","FAIL"]),accepted:z40.boolean(),reviewId:z40.uuid().optional(),reviewVersion:z40.int().positive().optional(),acceptanceDecisionId:z40.uuid().optional(),freshness:z40.enum(["CURRENT_BASIS","STALE_BASIS"]),checksumSha256:ContentFingerprintSchema,contentType:z40.enum(["image/png","image/jpeg","image/webp"]),byteSize:z40.int().positive(),width:z40.int().positive(),height:z40.int().positive()});var KeyframeGenerationViewSchema=z40.strictObject({connection:z40.strictObject({connectionId:z40.uuid(),connectionVersion:z40.int().positive(),modelProfileId:z40.string(),modelProfileVersion:z40.int().positive()}).optional(),generationId:KeyframeGenerationIdSchema,tenantId:TenantIdSchema,projectId:ProjectIdSchema,productionId:ProductionIdSchema,shotId:ShotIdSchema,preparationId:PreparationIdSchema,contractId:GenerationContractIdSchema,contractFingerprint:ContentFingerprintSchema,operationId:OperationIdSchema,provider:KeyframeProviderProfileSchema,runtimeStatus:z40.enum(["PENDING","READY","RUNNING","WAITING","SUCCEEDED","FAILED","CANCELLED","SUPERSEDED"]),providerStatus:z40.enum(["NOT_SUBMITTED","SUBMITTING","PENDING","UNKNOWN","SUCCEEDED","FAILED"]),freshness:z40.enum(["CURRENT_BASIS","STALE_BASIS"]),cancellationRequested:z40.boolean(),candidate:KeyframeCandidateSchema.nullable(),createdByPrincipalId:PrincipalIdSchema,createdAt:z40.iso.datetime({offset:true})});var KeyframeQueryPageSchema=z40.strictObject({items:z40.array(KeyframeGenerationViewSchema),page:QueryPageInfoSchema});var KeyframeMediaSchema=z40.strictObject({contentType:z40.enum(["image/png","image/jpeg","image/webp"]),checksumSha256:ContentFingerprintSchema,byteSize:z40.int().positive().max(8*1024*1024),contentBase64:z40.string().min(4).max(4*Math.ceil(8*1024*1024/3))});var KeyframeSummarySchema=z40.strictObject({generations:z40.int().nonnegative(),running:z40.int().nonnegative(),waiting:z40.int().nonnegative(),registeredCandidates:z40.int().nonnegative(),testCandidates:z40.int().nonnegative(),liveCandidates:z40.int().nonnegative()});import{z as z43}from"zod";import{z as z42}from"zod";import{z as z41}from"zod";var MatrixParameterRuleSchema=SpeechParameterRuleSchema.extend({numberOptions:z41.array(z41.number().finite()).min(1).max(32).optional()}).superRefine((r,ctx)=>{const numeric=r.type==="NUMBER"||r.type==="INTEGER";const stringValid=v=>typeof v==="string"&&v.length<=(r.maxLength??4096)&&(!r.options||r.options.includes(v));const valid=v=>numeric?typeof v==="number"&&Number.isFinite(v)&&(r.type!=="INTEGER"||Number.isInteger(v))&&(r.min===void 0||v>=r.min)&&(r.max===void 0||v<=r.max)&&(!r.numberOptions||r.numberOptions.includes(v)):r.type==="BOOLEAN"?typeof v==="boolean":r.type==="STRING"?stringValid(v):r.type==="STRING_ARRAY"?Array.isArray(v)&&v.length<=(r.maxItems??100)&&v.every(stringValid):!!v&&typeof v==="object"&&!Array.isArray(v)&&Object.keys(v).length<=(r.maxItems??100)&&Object.entries(v).every(([k,item])=>k.length>0&&k.length<=(r.maxKeyLength??100)&&stringValid(item));if(r.min!==void 0&&r.max!==void 0&&r.min>r.max||r.numberOptions&&(!numeric||new Set(r.numberOptions).size!==r.numberOptions.length||r.numberOptions.some(v=>!valid(v)))||r.default!==void 0&&!valid(r.default))ctx.addIssue({code:"custom",message:"Typed parameter range, choices and default must agree"})});var AsrProfileSchema=z42.strictObject({id:ModelProfileIdSchema,version:z42.int().positive(),providerId:ProviderIdSchema,sourceUrl:z42.url().max(2048),verifiedAt:z42.iso.date(),modelId:z42.string().min(1).max(160),label:z42.string().min(1).max(100),protocol:z42.enum(["OPENAI_TRANSCRIPTION_V1","OPENAI_WHISPER_TRANSCRIPTION_V1","QWEN_ASR_V1"]),modes:z42.tuple([z42.literal("TRANSCRIPTION")]),inputKinds:z42.array(z42.enum(["AUDIO","VIDEO"])).min(1).max(2),requestTimeoutMs:z42.int().min(1e3).max(18e4),maxBytes:z42.int().positive().max(12582912),maxDurationMs:z42.int().positive().max(6e4),parameters:z42.record(z42.string().regex(/^[a-z][a-z0-9_]{0,49}$/),MatrixParameterRuleSchema)}).superRefine((p,c)=>{const openai=p.providerId==="OPENAI";const whisper=p.protocol==="OPENAI_WHISPER_TRANSCRIPTION_V1";const fields=openai?whisper?{prompt:"STRING",language:"STRING",temperature:"NUMBER",timestamp_granularities:"STRING_ARRAY"}:{prompt:"STRING",languages:"STRING_ARRAY",keywords:"STRING_ARRAY"}:{context:"STRING",language:"STRING",enable_itn:"BOOLEAN"};if(p.providerId!==(p.protocol==="QWEN_ASR_V1"?"QWEN_CN":"OPENAI")||new Set(p.inputKinds).size!==p.inputKinds.length||!openai&&(p.maxBytes>7340032||p.inputKinds.includes("VIDEO"))||Object.entries(p.parameters).some(([key10,rule])=>fields[key10]!==rule.type))c.addIssue({code:"custom",message:"ASR protocol capability mismatch"});if(whisper){const rule=p.parameters.timestamp_granularities;if(!rule?.required||!rule.options?.length||rule.options.some(v=>!["word","segment"].includes(v)))c.addIssue({code:"custom",message:"Timed ASR requires explicit supported granularities"});const temperature=p.parameters.temperature;if(temperature&&(temperature.min===void 0||temperature.min<0||temperature.max===void 0||temperature.max>1))c.addIssue({code:"custom",message:"Whisper temperature must stay within 0\u20131"})}});var TranscriptText={schemaVersion:z42.literal(1),text:z42.string().max(6e4),languages:z42.array(z42.string().min(2).max(40)).max(32)};var TimedText=z42.strictObject({text:z42.string().min(1).max(2500),startMs:z42.int().nonnegative().max(6e4),endMs:z42.int().positive().max(6e4)}).refine(v=>v.endMs>v.startMs,"Transcript interval must advance");var TranscriptSchema=z42.discriminatedUnion("timing",[z42.strictObject({...TranscriptText,timing:z42.literal("UNAVAILABLE")}),z42.strictObject({...TranscriptText,timing:z42.literal("PROVIDER_REPORTED"),timeBase:z42.literal("ORIGINAL_MEDIA_MS"),granularities:z42.array(z42.enum(["word","segment"])).min(1).max(2),words:z42.array(TimedText).max(1200),segments:z42.array(TimedText).max(240)}).superRefine((v,c)=>{if(new Set(v.granularities).size!==v.granularities.length)c.addIssue({code:"custom",message:"Duplicate timing granularity"});for(const[kind,items]of[["word",v.words],["segment",v.segments]]){if(!v.granularities.includes(kind)&&items.length>0||v.granularities.includes(kind)&&v.text.trim()&&!items.length||items.some((item,i)=>i>0&&item.startMs<items[i-1].endMs))c.addIssue({code:"custom",message:"Missing, unordered or overlapping Provider timing"})}})]);var ObservationModeSchema=z43.enum(["AUDIO","AUDIOVISUAL","VIDEO","VIDEO_ALL_FRAMES","TRANSCRIPTION"]);var ObservationParametersSchema=SpeechParametersSchema;var VisualObservationProfileSchema=z43.strictObject({id:ModelProfileIdSchema,version:z43.int().positive(),providerId:ProviderIdSchema,sourceUrl:z43.url().max(2048),modelId:z43.string().min(1).max(160),label:z43.string().min(1).max(100),protocol:z43.enum(["GEMINI_INTERACTIONS_V1","QIANWEN_VIDEO_V1"]),modes:z43.array(z43.enum(["AUDIO","AUDIOVISUAL","VIDEO","VIDEO_ALL_FRAMES"])).min(1).max(4),requestTimeoutMs:z43.int().min(1e3).max(18e4),maxBytes:z43.int().positive().max(12582912),maxDurationMs:z43.int().positive().max(6e4),parameters:z43.record(z43.string(),z43.strictObject({type:z43.enum(["NUMBER","INTEGER","BOOLEAN","STRING"]),min:z43.number().optional(),max:z43.number().optional(),options:z43.array(z43.string()).max(20).optional(),default:z43.union([z43.number().finite(),z43.boolean(),z43.string().max(200)])}))}).superRefine((p,c)=>{if(new Set(p.modes).size!==p.modes.length)c.addIssue({code:"custom",message:"Duplicate observation mode"});if((p.protocol==="QIANWEN_VIDEO_V1"||p.modes.includes("AUDIOVISUAL"))&&p.maxBytes>8388608)c.addIssue({code:"custom",message:"Video observation input exceeds supported bound"});const gemini=p.protocol==="GEMINI_INTERACTIONS_V1";const allowed=gemini?["max_output_tokens"]:["fps","max_tokens"];if(p.providerId!==(gemini?"GEMINI":"QWEN_CN")||p.modes.some(m=>!(gemini?["AUDIO","AUDIOVISUAL"]:["VIDEO","VIDEO_ALL_FRAMES"]).includes(m))||Object.keys(p.parameters).some(k=>!allowed.includes(k))||allowed.some(k=>!p.parameters[k]))c.addIssue({code:"custom",message:"Observation protocol/profile mismatch"});for(const[k,r]of Object.entries(p.parameters)){const n=r.default;const lo=k==="fps"?1:256,hi=k==="fps"?10:4096;if(typeof n!=="number"||!["NUMBER","INTEGER"].includes(r.type)||k!=="fps"&&r.type!=="INTEGER"||r.min===void 0||r.max===void 0||r.min<lo||r.max>hi||r.min>r.max||n<r.min||n>r.max||r.type==="INTEGER"&&!Number.isSafeInteger(n))c.addIssue({code:"custom",message:"Unsupported observation parameter rule"})}});var ObservationProfileSchema=z43.union([VisualObservationProfileSchema,AsrProfileSchema]);var ProviderTenantInputSchema=z44.strictObject({tenantId:TenantIdSchema});var ImageModelProfileSchema=z44.strictObject({referenceRoles:z44.array(ReferenceRoleSchema.exclude(["START_FRAME_ANCHOR","END_FRAME_ANCHOR"])).min(1).max(6).optional(),id:ModelProfileIdSchema,version:z44.int().positive(),providerId:ProviderIdSchema,modelId:z44.string().min(1).max(160),protocol:z44.enum(["QWEN_EDIT","ARK_IMAGE","GEMINI_IMAGE","OPENAI_IMAGE","XAI_IMAGE"]),maxReferences:z44.int().positive(),promptMaxUtf8Bytes:z44.int().positive(),requestTimeoutMs:z44.int().positive(),workingWidth:z44.int().nonnegative(),workingHeight:z44.int().nonnegative()});var VideoModelProfileSchema=z44.strictObject({id:ModelProfileIdSchema,version:z44.int().positive(),providerId:ProviderIdSchema,modelId:z44.string().min(1).max(160),protocol:z44.enum(["QWEN_VIDEO","VOLCENGINE_VIDEO"]),requestTimeoutMs:z44.int().positive(),promptMaxCharacters:z44.int().positive(),resolution:z44.enum(["720P","1080P"]),adapterVersion:z44.string().min(1).max(80),capabilities:VideoProviderProfileSchema.omit({id:true,adapterVersion:true,model:true,executionClass:true})});var ProviderDefaultViewSchema=z44.strictObject({selection:ProviderSelectionSchema,revision:z44.int().positive()});var scan=z44.strictObject({limit:z44.literal(100),possiblyTruncated:z44.boolean()});var ProviderConnectionPageSchema=scan.extend({items:z44.array(ProviderConnectionViewSchema).max(100)});var ProviderModelsViewSchema=z44.strictObject({catalog:z44.array(ImageModelProfileSchema).max(100),videoCatalog:z44.array(VideoModelProfileSchema).max(100),speechCatalog:z44.array(SpeechModelProfileSchema).max(100).default([]),observationCatalog:z44.array(ObservationProfileSchema).max(100).default([]),available:z44.array(z44.strictObject({selection:ProviderSelectionSchema,profile:KeyframeProviderProfileSchema})).max(1600),defaultSelection:ProviderDefaultViewSchema.nullable(),connectionScan:scan});import{z as z45}from"zod";var key3=z45.string().regex(/^[A-Za-z][A-Za-z0-9_.-]{0,99}$/);var value=z45.union([z45.string().max(160),z45.number().finite(),z45.boolean()]);var ModelAudioCapabilitySchema=z45.enum(["SYNCHRONIZED_AUDIO","SPEECH_GENERATION","SPEECH_RECOGNITION","TRANSCRIPT_TIMESTAMPS","VOICE_REFERENCE","AUDIO_REFERENCE","AUDIO_DRIVEN_VIDEO","LIP_SYNCHRONIZATION","AUDIO_EDITING","SEPARATE_STEMS"]);var ModelCapabilityMatrixSchema=z45.strictObject({schemaVersion:z45.literal(1),service:key3,lifecycle:z45.enum(["ACTIVE","DEPRECATED","RETIRED"]),sources:z45.array(z45.strictObject({url:z45.url().max(2048),checkedAt:z45.iso.date()})).min(1).max(8),modes:z45.array(key3).min(1).max(16),claims:z45.array(z45.strictObject({capability:ModelAudioCapabilitySchema,modes:z45.array(key3).min(1).max(16),support:z45.enum(["SUPPORTED","UNSUPPORTED","UNKNOWN"]),control:z45.enum(["PARAMETER","PROMPT","ALWAYS_ON","MEDIA_INPUT","NONE"]),parameterPath:key3.optional(),access:z45.enum(["PUBLIC","QUALIFIED_ACCOUNT"]).default("PUBLIC"),description:z45.string().max(600).optional()})).max(64),parameters:z45.record(key3,MatrixParameterRuleSchema),constraints:z45.array(z45.strictObject({modes:z45.array(key3).min(1).max(16),when:z45.strictObject({parameter:key3,equals:value}).optional(),require:z45.array(key3).max(16).default([]),forbid:z45.array(key3).max(16).default([]),requireValues:z45.record(key3,value).default({}),reason:z45.string().min(1).max(300)})).max(32),references:z45.array(z45.strictObject({kind:z45.enum(["VOICE_ID","AUDIO_REFERENCE","DRIVING_AUDIO"]),modes:z45.array(key3).min(1).max(16),parameterPath:key3,maxItems:z45.int().min(1).max(10),minDurationMs:z45.int().positive().optional(),maxDurationMs:z45.int().positive().max(6e4).optional(),maxTotalDurationMs:z45.int().positive().max(6e4).optional(),maxBytes:z45.int().positive().max(67108864).optional(),formats:z45.array(z45.enum(["WAV","MP3"])).max(2),requiresVisual:z45.boolean(),access:z45.enum(["PUBLIC","QUALIFIED_ACCOUNT"])})).max(16),outputAudioChannels:z45.union([z45.literal(1),z45.literal(2)]).optional()}).superRefine((m,ctx)=>{const modes=new Set(m.modes);const claims=m.claims.flatMap(c=>c.modes.map(mode=>`${c.capability}:${mode}:${c.access}`));if(modes.size!==m.modes.length||new Set(claims).size!==claims.length||Object.keys(m.parameters).length>48||[...m.claims,...m.constraints,...m.references].some(r=>r.modes.some(mode=>!modes.has(mode)))||m.claims.some(r=>r.control==="PARAMETER"&&(!r.parameterPath||!Object.hasOwn(m.parameters,r.parameterPath)))||m.constraints.some(r=>r.when&&!Object.hasOwn(m.parameters,r.when.parameter)))ctx.addIssue({code:"custom",message:"Matrix modes and parameter references must resolve"});for(const rule of Object.values(m.parameters))if(rule.min!==void 0&&rule.max!==void 0&&rule.min>rule.max)ctx.addIssue({code:"custom",message:"Matrix parameter range must advance"})});import{z as z46}from"zod";var rate=z46.int().positive().max(1e9);var ruleId=z46.string().regex(/^[a-zA-Z0-9_-]{1,80}$/);var sourceUrl=z46.url({protocol:/^https$/}).max(2e3).refine(value2=>{const url=new URL(value2);return!url.username&&!url.password&&!url.search});function speechCostUpperBoundMicros(characters,microsPerMillion){return Math.ceil(characters*microsPerMillion/1e6)}var SpeechCostPolicySchema=z46.strictObject({currency:z46.literal("USD"),unit:z46.literal("INPUT_CHARACTER"),ruleId,upperBoundMicrosPerMillionCharacters:rate,sourceUrl,validUntil:z46.iso.datetime({offset:true})});var SpeechCostQuoteSchema=z46.strictObject({workload:z46.literal("SPEECH_SYNTHESIS"),currency:z46.literal("USD"),projectId:ProjectIdSchema,selection:ProviderSelectionSchema,expectedExecution:ExpectedGenerationExecutionSchema.extend({credentialVersion:z46.int().positive()}),intentFingerprint:z46.string().regex(/^[a-f0-9]{64}$/),textCharacters:z46.int().min(1).max(600),billableCharactersUpperBound:z46.int().min(1).max(2400),upperBoundMicros:z46.int().positive().max(1e9),upperBoundMicrosPerMillionCharacters:rate,ruleId,sourceUrl}).refine(value2=>value2.billableCharactersUpperBound>=value2.textCharacters&&value2.billableCharactersUpperBound<=value2.textCharacters*4&&value2.upperBoundMicros===speechCostUpperBoundMicros(value2.billableCharactersUpperBound,value2.upperBoundMicrosPerMillionCharacters),"Speech quote must match its exact character bound and rate");var SpeechDeviceStartSchema=SpeechStartSchema.extend({deviceId:z46.uuid().optional(),approvedQuote:SpeechCostQuoteSchema});var cost={costPolicy:GenerationCostPolicySchema.optional()};var matrix={matrix:ModelCapabilityMatrixSchema.optional()};var ProviderModelDefinitionSchema=z47.discriminatedUnion("family",[z47.strictObject({family:z47.literal("NATIVE_SPEECH"),profile:NativeSpeechModelProfileSchema}),z47.strictObject({family:z47.literal("IMAGE"),profile:ImageModelProfileSchema,...matrix,...cost}),z47.strictObject({family:z47.literal("VIDEO"),profile:VideoModelProfileSchema,...matrix,...cost}),z47.strictObject({family:z47.literal("SPEECH"),profile:SpeechModelProfileSchema,...matrix}),z47.strictObject({family:z47.literal("OBSERVATION"),profile:ObservationProfileSchema,...matrix}),z47.strictObject({family:z47.literal("DECLARED"),profile:z47.strictObject({id:ModelProfileIdSchema,version:z47.int().positive(),providerId:ProviderIdSchema,modelId:z47.string().min(1).max(160),protocol:z47.literal("DOCUMENTED_ONLY")}),matrix:ModelCapabilityMatrixSchema})]);var ProviderModelViewSchema=z47.strictObject({tenantId:TenantIdSchema,id:ModelProfileIdSchema,version:z47.int().positive(),enabled:z47.boolean(),definition:ProviderModelDefinitionSchema}).refine(v=>v.id===v.definition.profile.id&&v.version===v.definition.profile.version,{message:"Model version identity mismatch"});var ConfigureProviderModelSchema=z47.strictObject({tenantId:TenantIdSchema,expectedVersion:z47.int().nonnegative(),definition:ProviderModelDefinitionSchema,speechCostPolicy:SpeechCostPolicySchema.optional()}).refine(v=>!v.speechCostPolicy||v.definition.family==="SPEECH",{message:"Speech cost policy requires a speech model"}).refine(v=>v.definition.profile.version===v.expectedVersion+1,{message:"Next model version required"}).refine(v=>new TextEncoder().encode(JSON.stringify(v.definition)).length<=65536,{message:"Model definition too large"});var DisableProviderModelSchema=z47.strictObject({tenantId:TenantIdSchema,id:ModelProfileIdSchema,expectedVersion:z47.int().positive()});var ProviderModelPageSchema=z47.strictObject({items:z47.array(ProviderModelViewSchema).max(100),possiblyTruncated:z47.boolean()});var ProviderModelGetSchema=z47.strictObject({tenantId:TenantIdSchema,id:ModelProfileIdSchema,version:z47.int().positive().optional()});var id6=z48.uuid().toLowerCase();var SoundPlanScopeSchema=z48.strictObject({tenantId:id6,productionId:id6});var SoundPlanBasisSchema=z48.strictObject({briefVersionId:id6,briefVersion:z48.int().positive(),storyVersionId:id6,storyVersion:z48.int().positive(),planVersionId:id6,planVersion:z48.int().positive()});var SoundPlanModelSchema=z48.strictObject({modelProfileId:z48.string().regex(/^[a-z][a-z0-9-]{1,79}$/),modelProfileVersion:z48.int().positive(),connectionId:id6});var SoundPlanNativeSpeechSchema=SoundPlanModelSchema.omit({connectionId:true}).extend({schemaVersion:z48.literal(1),execution:NativeSpeechExecutionSchema});var SoundMakingPlanContentSchema=z48.strictObject({visuals:z48.array(z48.strictObject({shotId:id6,method:z48.enum(["CODE","GENERATED","IMPORTED"]),model:SoundPlanModelSchema.optional(),nativeAudio:z48.boolean().optional(),sourceSound:SourceSoundTreatmentSchema,rationale:z48.string().trim().min(1).max(600)})).min(1).max(200),cues:z48.array(z48.strictObject({id:z48.string().regex(/^[a-z][a-z0-9_-]{0,63}$/),role:z48.enum(["NARRATION","DIALOGUE","MUSIC","AMBIENCE","SOUND_EFFECT"]),source:z48.enum(["TTS","NATIVE_VIDEO","IMPORTED_AUDIO","EXISTING_AUDIO"]),shotIds:z48.array(id6).min(1).max(200),startMs:z48.int().min(0).max(6e4),endMs:z48.int().positive().max(6e4),text:z48.string().trim().min(1).max(6e3).optional(),voice:z48.string().min(1).max(100).optional(),voiceProfile:VoiceProfileUseSchema.extend({usage:z48.literal("PRODUCTION")}).optional(),model:SoundPlanModelSchema.optional(),nativeModel:SoundPlanNativeSpeechSchema.optional(),parameters:SpeechParametersSchema.optional(),audio:z48.strictObject({purpose:z48.enum(["VOICEOVER","MUSIC"]),versionId:z48.uuid()}).optional(),lipSync:z48.enum(["REQUIRED","NONE"]),exactSpeech:z48.boolean()})).max(64),unknowns:z48.array(z48.string().trim().min(1).max(300)).max(16)}).superRefine((v,c)=>{if(new Set(v.visuals.map(s=>s.shotId)).size!==v.visuals.length||new Set(v.cues.map(s=>s.id)).size!==v.cues.length)c.addIssue({code:"custom",message:"Visual Shot and cue identities must be unique"});for(const s of v.visuals)if(s.method==="GENERATED"!==!!s.model||s.method==="GENERATED"&&s.nativeAudio===void 0||s.method!=="GENERATED"&&s.nativeAudio!==void 0||s.method==="CODE"&&s.sourceSound.policy!=="MUTE")c.addIssue({code:"custom",message:"Generated visuals require a model; CODE has no native sound"});for(const cue of v.cues)if(cue.endMs<=cue.startMs||new Set(cue.shotIds).size!==cue.shotIds.length||cue.source==="TTS"&&(!cue.text||!cue.voice||!!cue.model===!!cue.nativeModel||cue.nativeModel&&!cue.voiceProfile||!["NARRATION","DIALOGUE"].includes(cue.role))||cue.exactSpeech&&!cue.text||["NARRATION","DIALOGUE"].includes(cue.role)&&!cue.text||["IMPORTED_AUDIO","EXISTING_AUDIO"].includes(cue.source)!==!!cue.audio||cue.audio&&((["NARRATION","DIALOGUE"].includes(cue.role)?"VOICEOVER":"MUSIC")!==cue.audio.purpose||!["NARRATION","DIALOGUE","MUSIC"].includes(cue.role))||cue.source!=="TTS"&&(!!cue.voice||!!cue.model||!!cue.nativeModel||!!cue.parameters||!!cue.voiceProfile)||cue.source==="NATIVE_VIDEO"&&["NARRATION","DIALOGUE"].includes(cue.role)&&cue.shotIds.length!==1||cue.lipSync==="REQUIRED"&&(cue.source!=="NATIVE_VIDEO"||cue.shotIds.length!==1))c.addIssue({code:"custom",message:"Invalid speech, cue timing or synchronization intent"})});var SoundPlanVersionSchema=SoundPlanScopeSchema.extend({id:id6,soundPlanId:id6,projectId:id6,version:z48.int().positive(),basis:SoundPlanBasisSchema,content:SoundMakingPlanContentSchema,createdByPrincipalId:id6,createdAt:z48.iso.datetime({offset:true})});var SoundPlanValidateSchema=SoundPlanScopeSchema.extend({expectedProductionRevision:z48.int().positive(),basis:SoundPlanBasisSchema,content:SoundMakingPlanContentSchema});var SoundPlanAcceptSchema=SoundPlanValidateSchema.extend({expectedVersion:z48.int().nonnegative(),idempotencyKey:z48.string().trim().min(1).max(200)});var SoundPlanGetSchema=SoundPlanScopeSchema.extend({versionId:id6.optional()});var SoundPlanDiagnosticSchema=z48.strictObject({severity:z48.enum(["ERROR","WARNING"]),code:z48.string().regex(/^[A-Z][A-Z0-9_]{0,79}$/),shotId:id6.optional(),cueId:z48.string().max(64).optional(),message:z48.string().max(500)});var SoundPlanValidationSchema=z48.strictObject({executable:z48.boolean(),diagnostics:z48.array(SoundPlanDiagnosticSchema).max(256),semantics:z48.literal("PLAN_VALIDATION_NOT_CREATIVE_OR_LISTENING_APPROVAL")});var SoundPlanViewSchema=z48.strictObject({version:SoundPlanVersionSchema,current:z48.boolean(),freshness:z48.enum(["CURRENT_BASIS","STALE_BASIS"])});var SoundPlanReceiptSchema=z48.strictObject({semanticStatus:z48.literal("SUCCESS"),version:SoundPlanVersionSchema,productionRevision:z48.int().positive()});var SoundPlanContextSchema=SoundPlanScopeSchema.extend({projectId:id6,productionRevision:z48.int().positive(),runnable:z48.boolean(),basis:SoundPlanBasisSchema.nullable(),targetDurationMs:z48.int().positive().nullable(),shots:z48.array(z48.strictObject({shotId:id6,durationMs:z48.int().positive()})).max(200),currentVersion:z48.int().nonnegative(),currentVersionId:id6.nullable(),capabilities:z48.strictObject({models:z48.array(ProviderModelViewSchema).max(100),video:z48.array(z48.strictObject({selection:ProviderSelectionSchema,profile:VideoProviderProfileSchema})).max(1600),speech:SpeechOptionsSchema.shape.options,audio:z48.array(AudioViewSchema).max(64)})});var TimelineSourceSoundInputSchema=z49.strictObject({duckingMusicPermille:z49.int().nonnegative().max(1e3).optional(),soundPlanVersionId:z49.uuid(),clips:z49.array(z49.strictObject({ordinal:z49.int().min(1).max(200),treatment:SourceSoundTreatmentSchema,importedAudioVersionId:z49.uuid().optional()})).min(1).max(200),speechCues:z49.array(z49.strictObject({cueId:z49.string().regex(/^[a-z][a-z0-9_-]{0,63}$/),audioVersionId:z49.uuid()})).max(64)});var TimelineSourceSoundSourceSchema=z49.discriminatedUnion("kind",[z49.strictObject({kind:z49.literal("NATIVE_GENERATED"),version:NativeVideoSoundReferenceSchema}),z49.strictObject({kind:z49.literal("IMPORTED_SYNC"),version:SourceSyncAudioVersionSchema})]);var TimelineSourceSoundCompositionSchema=z49.strictObject({schemaVersion:z49.literal(1),soundPlanVersionId:z49.uuid(),soundPlanFingerprint:z49.string().regex(/^[0-9a-f]{64}$/),plannedCues:SoundMakingPlanContentSchema.shape.cues,mix:AudioMixProfileSchema,clips:z49.array(z49.strictObject({ordinal:z49.int().min(1).max(200),treatment:SourceSoundTreatmentSchema,source:TimelineSourceSoundSourceSchema.optional(),sourceInSample:z49.int().nonnegative().max(288e4),sourceOutSample:z49.int().nonnegative().max(288e4),startSample:z49.int().nonnegative().max(288e4),outputSampleCount:z49.int().positive().max(288e4)})).min(1).max(200),speechCues:z49.array(z49.strictObject({cueId:z49.string().regex(/^[a-z][a-z0-9_-]{0,63}$/),source:ProductionAudioVersionSchema,sourceInMs:z49.literal(0),sourceOutMs:z49.int().positive().max(6e4),startMs:z49.int().nonnegative().max(6e4),gainPermille:z49.literal(1e3)})).max(64)}).superRefine((v,ctx)=>{if(new Set(v.clips.map(c=>c.ordinal)).size!==v.clips.length||new Set(v.speechCues.map(c=>c.cueId)).size!==v.speechCues.length||v.speechCues.some(c=>c.source.purpose!=="VOICEOVER"||c.sourceOutMs!==c.source.media.durationMs)||v.clips.some(c=>c.treatment.policy!=="MUTE"!==!!c.source||c.source&&c.sourceOutSample<=c.sourceInSample))ctx.addIssue({code:"custom",message:"Explicit distinct clip sound decisions and exact source required"})});var TimelineV2ClipSchema=TimelineManifestSchema.shape.clips.element.extend({source:AcceptedVisualSourceReferenceSchema});var TimelineV2ManifestSchema=TimelineManifestSchema.extend({schemaVersion:z50.literal(2),clips:z50.array(TimelineV2ClipSchema).min(1).max(200),sourceSound:TimelineSourceSoundCompositionSchema.optional()});var TimelineV2VersionSchema=TimelineV2ManifestSchema.extend(TimelineVersionIdentityShape).superRefine(validateTimelineAttachments);import{z as z51}from"zod";var sha4=z51.string().regex(/^[0-9a-f]{64}$/);var VisualFrameSequenceSchema=z51.strictObject({schemaVersion:z51.literal(1),profileId:z51.literal("RGBA_PNG_SEQUENCE_30_V1"),tenantId:TenantIdSchema,projectId:ProjectIdSchema,productionId:ProductionIdSchema.nullable(),artifactId:ArtifactIdSchema,representationId:ArtifactRepresentationIdSchema,checksumSha256:sha4,width:z51.int().min(1).max(1920),height:z51.int().min(1).max(1920),frameRate:z51.literal(30),frameCount:z51.int().min(1).max(360),alpha:z51.literal("STRAIGHT_RGBA"),frames:z51.array(z51.strictObject({ordinal:z51.int().min(0).max(359),artifactId:ArtifactIdSchema,representationId:ArtifactRepresentationIdSchema,checksumSha256:sha4,byteSize:z51.int().min(1).max(16*1024*1024)})).min(1).max(360)}).superRefine((v,context)=>{if(v.width*v.height>1920*1080||v.frames.length!==v.frameCount||v.frames.some((f,i)=>f.ordinal!==i)||new Set(v.frames.map(f=>f.representationId)).size!==v.frames.length||v.frames.reduce((n,f)=>n+f.byteSize,0)>64*1024*1024)context.addIssue({code:"custom",message:"Frame sequence geometry/order/identity/byte budget mismatch"})});var VisualLayerPlacementSchema=z51.strictObject({xPermille:z51.int().min(0).max(1e3),yPermille:z51.int().min(0).max(1e3),widthPermille:z51.int().min(1).max(1e3),heightPermille:z51.int().min(1).max(1e3)}).refine(v=>v.xPermille+v.widthPermille<=1e3&&v.yPermille+v.heightPermille<=1e3,"Layer rectangle must fit the canvas");var VisualLayerSchema=z51.strictObject({id:z51.uuid(),source:VisualFrameSequenceSchema,sourceInFrame:z51.int().min(0).max(359),sourceOutFrame:z51.int().min(1).max(360),startFrame:z51.int().min(0).max(1799),zIndex:z51.int().min(0).max(7),opacityPermille:z51.int().min(0).max(1e3),placement:VisualLayerPlacementSchema}).superRefine((v,context)=>{if(v.sourceOutFrame<=v.sourceInFrame||v.sourceOutFrame>v.source.frameCount||v.startFrame+v.sourceOutFrame-v.sourceInFrame>1800)context.addIssue({code:"custom",message:"Layer source/output frame interval mismatch"})});var VisualLayerCompositionSchema=z51.strictObject({schemaVersion:z51.literal(1),profileId:z51.literal("STRAIGHT_ALPHA_FRAME_OVERLAY_30_V1"),tenantId:TenantIdSchema,projectId:ProjectIdSchema,productionId:ProductionIdSchema,totalFrames:z51.int().min(1).max(1800),layers:z51.array(VisualLayerSchema).min(1).max(8)}).superRefine((v,context)=>{const sources=new Map;const frames=new Map;let bytes=0;for(const layer of v.layers){const source6=layer.source;const body=JSON.stringify(source6);for(const frame2 of source6.frames){const identity6=JSON.stringify({artifactId:frame2.artifactId,checksumSha256:frame2.checksumSha256,byteSize:frame2.byteSize,width:source6.width,height:source6.height});if(frames.has(frame2.representationId)&&frames.get(frame2.representationId)!==identity6)context.addIssue({code:"custom",message:"Shared frame representation has inconsistent facts"});frames.set(frame2.representationId,identity6)}if(source6.tenantId!==v.tenantId||source6.projectId!==v.projectId||source6.productionId!==null&&source6.productionId!==v.productionId||layer.startFrame+layer.sourceOutFrame-layer.sourceInFrame>v.totalFrames||sources.has(source6.representationId)&&sources.get(source6.representationId)!==body)context.addIssue({code:"custom",message:"Layer source scope/identity/output bounds mismatch"});if(!sources.has(source6.representationId))bytes+=source6.frames.reduce((n,f)=>n+f.byteSize,0);sources.set(source6.representationId,body)}if(new Set(v.layers.map(l=>l.id)).size!==v.layers.length||new Set(v.layers.map(l=>l.zIndex)).size!==v.layers.length||bytes>256*1024*1024)context.addIssue({code:"custom",message:"Layer instance/z-order/byte budget mismatch"})});var TimelineVisualLayerInputSchema=z52.strictObject({id:z52.uuid(),artifactId:ArtifactIdSchema,sourceInFrame:z52.int().min(0).max(359),sourceOutFrame:z52.int().min(1).max(360),startFrame:z52.int().min(0).max(1799),zIndex:z52.int().min(0).max(7),opacityPermille:z52.int().min(0).max(1e3),placement:VisualLayerPlacementSchema}).refine(layer=>layer.sourceOutFrame>layer.sourceInFrame&&layer.startFrame+layer.sourceOutFrame-layer.sourceInFrame<=1800,"Dynamic layer interval must advance and fit the output clock");var TimelineV3ManifestSchema=TimelineV2ManifestSchema.extend({schemaVersion:z52.literal(3),visualLayers:VisualLayerCompositionSchema});var TimelineV3VersionSchema=TimelineV3ManifestSchema.extend(TimelineVersionIdentityShape).superRefine((timeline,context)=>{validateTimelineAttachments(timeline,context);validateTimelineVisualLayerClock(timeline,context)});function validateTimelineVisualLayerClock(timeline,context){const composition2=timeline.visualLayers;let sourceMs=0;let totalFrames=0;let previousFrames=0;for(const[index,clip]of timeline.clips.entries()){const previousBoundary=Math.round(sourceMs*30/1e3);sourceMs+=clip.durationMs;const frames=Math.round(sourceMs*30/1e3)-previousBoundary;const overlap=clip.transition==="CUT"?0:clip.transition.durationFrames;if(clip.ordinal!==index+1||frames<1||overlap>0&&(index===0||overlap>=frames||overlap>=previousFrames))context.addIssue({code:"custom",message:"Dynamic Timeline clip frame plan mismatch"});totalFrames+=frames-overlap;previousFrames=frames}if(timeline.tenantId!==void 0&&composition2.tenantId!==timeline.tenantId||timeline.projectId!==void 0&&composition2.projectId!==timeline.projectId||timeline.productionId!==void 0&&composition2.productionId!==timeline.productionId||composition2.totalFrames!==totalFrames||Math.abs(totalFrames*1e3/30-timeline.duration.totalMs)>1e3/60+.001)context.addIssue({code:"custom",message:"Dynamic Timeline ownership or physical output clock mismatch"})}import{z as z53}from"zod";var FinalRenderProfileIdSchema=z53.enum(["FINAL_H264_720P_V1","FINAL_H264_1080P_V1","FINAL_H264_480P_V1"]);var FinalRenderProfileSchema=z53.strictObject({id:FinalRenderProfileIdSchema,algorithm:z53.enum(["ORDERED_TRIM_CUT_V1","ORDERED_COMPOSE_V2"]),picturePolicy:PicturePolicySchema.optional(),width:z53.union([z53.literal(1280),z53.literal(720),z53.literal(1920),z53.literal(1080),z53.literal(854),z53.literal(480)]),height:z53.union([z53.literal(1280),z53.literal(720),z53.literal(1920),z53.literal(1080),z53.literal(854),z53.literal(480)]),frameRate:z53.literal(30),codec:z53.literal("h264"),pixelFormat:z53.literal("yuv420p"),fit:z53.literal("PAD"),hasAudio:z53.boolean(),audioMix:AudioMixProfileSchema.optional(),framePolicy:z53.literal("CUMULATIVE_NEAREST_FRAME"),encoder:z53.literal("libx264"),crf:z53.literal(18),preset:z53.literal("veryfast"),gopFrames:z53.literal(30),bFrames:z53.literal(0),audioPolicy:z53.enum(["SILENT","MIXED"]),captionPolicy:z53.enum(["NONE","BURN_IN"]),sourceQualityPolicy:z53.literal("NO_UPSCALE_V1"),captionStyle:CaptionRenderStyleSchema.optional(),graphicsPolicy:z53.literal("OVERLAY_V1").optional()}).superRefine((profile,context)=>{if(profile.hasAudio!==!!profile.audioMix||profile.hasAudio!==(profile.audioPolicy==="MIXED"))context.addIssue({code:"custom",message:"Exact native audio policy and mix must agree"});if(!!profile.captionStyle!==(profile.captionPolicy==="BURN_IN"))context.addIssue({code:"custom",message:"Caption burn-in requires exact native style"});const pair=profile.id==="FINAL_H264_720P_V1"?[1280,720]:profile.id==="FINAL_H264_480P_V1"?[854,480]:[1920,1080];if(!(profile.width===pair[0]&&profile.height===pair[1]||profile.width===pair[1]&&profile.height===pair[0]))context.addIssue({code:"custom",message:"Final profile geometry mismatch"})});var VisualLayerPolicySchema=z54.enum(["STRAIGHT_ALPHA_FRAME_OVERLAY_30_V1","STRAIGHT_ALPHA_FRAME_OVERLAY_30_V2"]);var VisualLayerPreviewProfileSchema=RoughCutProfileSchema.safeExtend({visualLayerPolicy:VisualLayerPolicySchema});var VisualLayerFinalProfileSchema=FinalRenderProfileSchema.safeExtend({visualLayerPolicy:VisualLayerPolicySchema,visualLayerSourceQualityPolicy:z54.literal("NO_UPSCALE_V1")});var shape={schemaVersion:z54.literal(3),timeline:TimelineV3VersionSchema};var preview=RoughCutManifestSchema.extend({...shape,profile:VisualLayerPreviewProfileSchema});var final=RoughCutManifestSchema.extend({...shape,profile:VisualLayerFinalProfileSchema});function validateClock(value2,context){if(value2.totalFrames!==value2.timeline.visualLayers.totalFrames)context.addIssue({code:"custom",message:"Dynamic render must use the frozen layer clock"})}var VisualLayerPreviewManifestSchema=preview.superRefine(validateClock);var VisualLayerFinalManifestSchema=final.superRefine(validateClock);var VisualLayerRenderManifestSchema=z54.union([VisualLayerPreviewManifestSchema,VisualLayerFinalManifestSchema]);import{z as z59}from"zod";import{z as z56}from"zod";import{z as z55}from"zod";var processorFamilies={IMPORTED_VISUAL_NORMALIZE:"ARTIFACT_INGEST",SOURCE_SYNC_AUDIO:"ARTIFACT_INGEST",TEMPORAL_SAMPLE:"TEMPORAL_SAMPLE",DELIVERY_VALIDATE:"DELIVERY_VALIDATE",COMPOSITION_RENDER:"COMPOSITION_RENDER",IMPORT_ORIGINAL:"ARTIFACT_INGEST",LOCAL_MEDIA_INSPECT:"OBSERVE",LOCAL_MEDIA_PUBLISH:"ARTIFACT_INGEST",IMPORT_PROJECT_SOURCE:"ARTIFACT_INGEST",REGISTER_VISUAL_SEQUENCE:"ARTIFACT_INGEST",REFERENCE_PREVIEW:"PLANNING_MATERIALIZE",SPEECH_SYNTHESIZE:"AUDIO_GENERATE",SPEECH_SYNTHESIZE_CPU:"AUDIO_GENERATE",SPEECH_EXTERNAL_QWEN:"AUDIO_GENERATE",TRANSCRIBE_AUDIO:"OBSERVE",TRANSCRIBE_EXTERNAL_QWEN:"OBSERVE",KEYFRAME_GENERATE:"KEYFRAME_GENERATE",VIDEO_GENERATE:"VIDEO_GENERATE"};var TenantProcessorKindSchema=z55.enum(Object.keys(processorFamilies));var referenceThumbnailProfile={processor:"REFERENCE_PREVIEW",format:"PNG_480_INSIDE_V1",maxDimension:480,maxBytes:1024*1024};var validationMode=z56.literal("TENANT_TRUSTED_VALIDATOR").optional();var DeviceRenderTargetSchema=z56.strictObject({mode:z56.literal("tenant-device-only"),deviceId:z56.uuid().optional(),validationMode});var DeviceRenderReceiptSchema=z56.strictObject({mode:z56.literal("tenant-device-only"),deviceId:z56.uuid(),runtimeJobId:z56.uuid(),validationMode});var projectDeviceScope=z56.strictObject({tenantId:z56.uuid(),projectId:z56.uuid(),kind:z56.enum(["preview","final","library",...TenantProcessorKindSchema.options])});var ProjectDeviceListInputSchema=projectDeviceScope.extend({deviceId:z56.uuid().optional()});var ProjectDeviceListSchema=projectDeviceScope.extend({items:z56.array(z56.strictObject({deviceId:z56.uuid(),label:z56.string().trim().min(1).max(120),availability:z56.enum(["AVAILABLE","BUSY","OFFLINE","UNQUALIFIED"])})).max(50),truncated:z56.boolean(),validationMode:z56.literal("TENANT_TRUSTED_VALIDATOR").nullable(),recovery:DeviceSetupRecoverySchema.optional()});import{z as z58}from"zod";import{z as z57}from"zod";var TimelineVersionReaderSchema=z57.discriminatedUnion("schemaVersion",[TimelineVersionSchema,TimelineV2VersionSchema,TimelineV3VersionSchema]);var TimelineManifestReaderSchema=z57.discriminatedUnion("schemaVersion",[TimelineManifestSchema,TimelineV2ManifestSchema,TimelineV3ManifestSchema.superRefine(validateTimelineVisualLayerClock)]);var TimelineScopeSchema=z58.strictObject({tenantId:TenantIdSchema,productionId:ProductionIdSchema});var TimelineClipInputSchema=z58.strictObject({shotId:ShotIdSchema,acceptanceId:z58.uuid(),framing:ClipFramingSchema.optional(),transition:ClipTransitionSchema.optional(),sourceInMs:z58.int().nonnegative().max(30150),sourceOutMs:z58.int().positive().max(30150)}).refine(v=>v.sourceOutMs>v.sourceInMs,"Clip source range must advance");var BuildTimelineShapeSchema=TimelineScopeSchema.extend({schemaVersion:z58.union([z58.literal(2),z58.literal(3)]).optional(),expectedProductionRevision:z58.int().positive(),expectedTimelineVersion:z58.int().nonnegative(),idempotencyKey:z58.string().trim().min(1).max(200),clips:z58.array(TimelineClipInputSchema).min(1).max(200),captionVersionId:z58.uuid().optional(),audio:TimelineAudioInputSchema.optional(),sourceSound:TimelineSourceSoundInputSchema.optional(),graphics:z58.array(TimelineGraphicInputSchema).max(8).optional(),visualLayers:z58.array(TimelineVisualLayerInputSchema).min(1).max(8).optional()});var BuildTimelineSchema=BuildTimelineShapeSchema.superRefine((input,context)=>{if(input.sourceSound&&!input.schemaVersion)context.addIssue({code:"custom",message:"Source sound requires explicit Timeline2/3"});if(input.schemaVersion===3!==!!input.visualLayers?.length)context.addIssue({code:"custom",message:"Dynamic layers require explicit Timeline3"});if(input.visualLayers&&(new Set(input.visualLayers.map(layer=>layer.id)).size!==input.visualLayers.length||new Set(input.visualLayers.map(layer=>layer.zIndex)).size!==input.visualLayers.length))context.addIssue({code:"custom",message:"Dynamic layer IDs and z-order must be unique"})});var TimelineStaleReasonSchema=z58.enum(["BRIEF_CHANGED","STORY_CHANGED","PLAN_CHANGED","SHOT_ACCEPTANCE_CHANGED","PRODUCTION_UNAVAILABLE","CAPTION_VERSION_CHANGED","CAPTION_UNAVAILABLE","AUDIO_VERSION_CHANGED","AUDIO_UNAVAILABLE","GRAPHIC_UNAVAILABLE","VISUAL_LAYER_UNAVAILABLE","SOUND_PLAN_CHANGED","SOURCE_SOUND_UNAVAILABLE"]);var TimelineViewSchema=z58.strictObject({version:TimelineVersionReaderSchema,isCurrent:z58.boolean(),freshness:z58.enum(["CURRENT_BASIS","STALE_BASIS"]),staleReasons:z58.array(TimelineStaleReasonSchema).max(13),assemblyStatus:z58.enum(["DRAFT","ASSEMBLY_READY"])});var TimelineGetSchema=TimelineScopeSchema.extend({versionId:z58.uuid()});var TimelineQuerySchema=TimelineScopeSchema.extend({limit:QueryLimitSchema,next:ContinuationSchema.optional()});var TimelinePageSchema=z58.strictObject({items:z58.array(TimelineViewSchema),page:QueryPageInfoSchema});var TimelineBuildReceiptSchema=z58.strictObject({semanticStatus:z58.literal("SUCCESS"),version:TimelineVersionReaderSchema,productionRevision:z58.int().positive()});var TimelineBasisSchema=TimelineScopeSchema.extend({productionRevision:z58.int().positive(),currentTimelineVersion:z58.int().nonnegative(),runnable:z58.boolean(),planningReady:z58.boolean(),output:TimelineManifestSchema.shape.output.nullable(),targetDurationMs:z58.int().positive().nullable(),shots:z58.array(z58.strictObject({shotId:ShotIdSchema,ordinal:z58.int().positive(),acceptanceStatus:z58.enum(["NONE","CURRENT","STALE"]),source:AcceptedVisualSourceReferenceSchema.nullable(),technical:VideoTechnicalMetadataSchema.nullable()})).max(200)});var TimelineSnapshotSchema=z58.strictObject({currentVersion:z58.int().positive().nullable(),stale:z58.boolean(),timelineId:z58.uuid().nullable(),versionId:z58.uuid().nullable(),assemblyStatus:z58.enum(["DRAFT","ASSEMBLY_READY"]).nullable(),totalDurationMs:z58.int().positive().nullable(),durationClassification:TimelineDurationSchema.shape.classification.nullable(),missingPlannedShots:z58.int().nonnegative(),staleReasons:z58.array(TimelineStaleReasonSchema).max(13)});var sha5=z59.string().regex(/^[0-9a-f]{64}$/);var RoughCutStartSchema=TimelineScopeSchema.extend({deviceExecution:DeviceRenderTargetSchema.optional(),timelineVersionId:z59.uuid(),timelineFingerprint:sha5,expectedProductionRevision:z59.int().positive(),profileId:RoughCutProfileIdSchema,idempotencyKey:z59.string().trim().min(1).max(200)});var RoughCutGetSchema=TimelineScopeSchema.extend({renderId:z59.uuid()});var RoughCutQuerySchema=TimelineScopeSchema.extend({limit:QueryLimitSchema,next:ContinuationSchema.optional()});var RoughCutV2ManifestSchema=RoughCutManifestSchema.extend({schemaVersion:z59.literal(2),timeline:TimelineV2VersionSchema});var RoughCutManifestReaderSchema=z59.discriminatedUnion("schemaVersion",[RoughCutManifestSchema,RoughCutV2ManifestSchema,VisualLayerPreviewManifestSchema]);var RoughCutTechnicalSchema=VideoTechnicalMetadataSchema.extend({hasAudio:z59.boolean(),audio:RenderedAudioSchema.optional(),durationMs:z59.int().min(29983).max(60017),frameRate:z59.literal(30),frameCount:z59.int().min(900).max(1800),engineVersion:z59.string().min(1).max(200)}).superRefine((v,ctx)=>{if(v.hasAudio!==!!v.audio||v.audio&&v.audio.sampleCount!==v.frameCount*1600)ctx.addIssue({code:"custom",message:"Actual audio stream must match physical output samples"})});var RoughCutArtifactSchema=RoughCutTechnicalSchema.safeExtend({artifactId:z59.uuid(),representationId:z59.uuid(),version:z59.int().positive(),poster:VideoPosterSchema,availability:z59.enum(["AVAILABLE","INVALID"]),reviewState:z59.enum(["UNREVIEWED","PASS","WARNING","FAIL"])});var RoughCutAdmissionSchema=z59.strictObject({humanLinks:HumanLinksSchema.optional(),deviceExecution:DeviceRenderReceiptSchema.optional(),semanticStatus:z59.literal("ACCEPTED"),renderId:z59.uuid(),operationId:OperationIdSchema,productionId:z59.uuid(),timelineVersionId:z59.uuid(),timelineFingerprint:sha5,executionClass:z59.enum(["LIVE","TEST_ONLY"]),manifestFingerprint:sha5,productionRevision:z59.int().positive()});var RoughCutViewSchema=TimelineScopeSchema.extend({humanLinks:HumanLinksSchema.optional(),renderId:z59.uuid(),projectId:ProjectIdSchema,runtimeJobId:z59.uuid(),operationId:OperationIdSchema,manifest:RoughCutManifestReaderSchema,manifestFingerprint:sha5,runtimeStatus:VideoGenerationViewSchema.shape.runtimeStatus,cancellationRequested:z59.boolean(),isCurrentTimeline:z59.boolean(),freshness:z59.enum(["CURRENT_BASIS","STALE_BASIS"]),staleReasons:z59.array(z59.string().min(1).max(120)).max(16),executionClass:z59.enum(["LIVE","TEST_ONLY"]),roughCut:RoughCutArtifactSchema.nullable(),createdByPrincipalId:PrincipalIdSchema,createdAt:z59.iso.datetime({offset:true})});var RoughCutPageSchema=z59.strictObject({items:z59.array(RoughCutViewSchema),page:QueryPageInfoSchema});var RoughCutSnapshotSchema=z59.strictObject({latestVersion:z59.int().positive().nullable(),reviewState:z59.enum(["UNREVIEWED","PASS","WARNING","FAIL"]).nullable(),latestRenderId:z59.uuid().nullable(),runtimeStatus:VideoGenerationViewSchema.shape.runtimeStatus.nullable(),currentRenderId:z59.uuid().nullable(),currentArtifactId:z59.uuid().nullable(),currentTimelineVersionId:z59.uuid().nullable(),stale:z59.boolean()});import{z as z63}from"zod";import{z as z61}from"zod";import{z as z60}from"zod";var sha6=z60.string().regex(/^[0-9a-f]{64}$/);var DeliveryPolicySchema=z60.strictObject({schemaVersion:z60.literal(1),requiredAudio:z60.boolean(),requiredCaptions:z60.boolean(),requiredGraphics:z60.boolean(),finalApproval:z60.enum(["AUTOMATIC","HUMAN"])});var DeliveryPolicyInputSchema=DeliveryPolicySchema.extend({requiredAudio:z60.boolean().default(false),requiredCaptions:z60.boolean().default(false),requiredGraphics:z60.boolean().default(false),finalApproval:z60.enum(["AUTOMATIC","HUMAN"]).default("AUTOMATIC")});var DeliveryCompositionSchema=z60.strictObject({hasAudio:z60.boolean(),hasCaptions:z60.boolean(),hasGraphics:z60.boolean()});var DeliveryTargetSchema=z60.strictObject({tenantId:z60.uuid(),projectId:z60.uuid(),productionId:z60.uuid(),renderId:z60.uuid(),timelineVersionId:z60.uuid(),timelineFingerprint:sha6,selectionId:z60.uuid(),selectionVersion:z60.int().positive(),renderManifestFingerprint:sha6,artifactId:z60.uuid(),representationId:z60.uuid(),checksumSha256:sha6,byteSize:z60.int().positive().max(128*1024*1024),executionClass:z60.enum(["LIVE","TEST_ONLY"])});var deliveryPhysicalCheckKeys=["FILE_READABLE","CHECKSUM","CONTAINER_PROFILE","DURATION","VIDEO_DECODE","AUDIO_DECODE","REQUIRED_AUDIO","REQUIRED_CAPTIONS","REQUIRED_GRAPHICS","MISSING_MEDIA","BLACK_FRAMES"];var DeliveryCheckKeySchema=z60.enum([...deliveryPhysicalCheckKeys,"ARTIFACT_REGISTRATION","PROVENANCE","MANIFEST_INTEGRITY","EXACT_BASIS","BLOCKING_FINDINGS"]);var DeliveryCheckSchema=z60.strictObject({key:DeliveryCheckKeySchema,status:z60.enum(["PASS","FAIL","UNVERIFIED","NOT_APPLICABLE"]),detail:z60.string().trim().min(1).max(1e3)});var DeliveryPhysicalChecksSchema=z60.array(DeliveryCheckSchema.extend({key:z60.enum(deliveryPhysicalCheckKeys)})).length(deliveryPhysicalCheckKeys.length).refine(checks=>new Set(checks.map(check=>check.key)).size===deliveryPhysicalCheckKeys.length,"Exact physical media checks required");var DeliveryValidationReviewSchema=z60.strictObject({id:z60.uuid(),target:DeliveryTargetSchema,policy:DeliveryPolicySchema,policyFingerprint:sha6,composition:DeliveryCompositionSchema,checks:z60.array(DeliveryCheckSchema).length(DeliveryCheckKeySchema.options.length),result:z60.enum(["PASS","FAIL"]),blockingChecks:z60.array(DeliveryCheckKeySchema).max(DeliveryCheckKeySchema.options.length),createdAt:z60.iso.datetime({offset:true})}).superRefine((review2,ctx)=>{const seen=new Set;const blocked=new Set;const{policy,composition:composition2}=review2;for(const check of review2.checks){if(seen.has(check.key))ctx.addIssue({code:"custom",message:"Duplicate deterministic delivery check"});seen.add(check.key);const mayOmit=check.key==="AUDIO_DECODE"&&!composition2.hasAudio||check.key==="REQUIRED_AUDIO"&&!policy.requiredAudio||check.key==="REQUIRED_CAPTIONS"&&!policy.requiredCaptions||check.key==="REQUIRED_GRAPHICS"&&!policy.requiredGraphics;if(check.status==="NOT_APPLICABLE"&&!mayOmit)ctx.addIssue({code:"custom",message:"Required delivery evidence cannot be omitted"});if(check.status==="FAIL"||check.status==="UNVERIFIED")blocked.add(check.key)}if(policy.requiredAudio&&!composition2.hasAudio)blocked.add("REQUIRED_AUDIO");if(policy.requiredCaptions&&!composition2.hasCaptions)blocked.add("REQUIRED_CAPTIONS");if(policy.requiredGraphics&&!composition2.hasGraphics)blocked.add("REQUIRED_GRAPHICS");const expected=DeliveryCheckKeySchema.options.filter(key10=>blocked.has(key10));if(review2.result!==(expected.length?"FAIL":"PASS")||JSON.stringify(review2.blockingChecks)!==JSON.stringify(expected))ctx.addIssue({code:"custom",message:"Review result and blockers must match complete owned evidence"})});var sha7=z61.string().regex(/^[0-9a-f]{64}$/);function sameTarget(a,b){return Object.keys(DeliveryTargetSchema.shape).every(key10=>a[key10]===b[key10])}var DeliveryApprovalSchema=z61.strictObject({id:z61.uuid(),reviewId:z61.uuid(),target:DeliveryTargetSchema,policyFingerprint:sha7,authority:z61.literal("HUMAN"),action:z61.enum(["APPROVE","REJECT"]),principalId:z61.uuid(),createdAt:z61.iso.datetime({offset:true})});var DeliveryManifestLinkSchema=z61.strictObject({id:z61.uuid(),checksumSha256:sha7,target:DeliveryTargetSchema,policyFingerprint:sha7,reviewId:z61.uuid()});var FinalDeliveryReceiptSchema=z61.strictObject({id:z61.uuid(),deliveryRole:z61.literal("FINAL_ARTIFACT"),review:DeliveryValidationReviewSchema,manifest:DeliveryManifestLinkSchema,approval:DeliveryApprovalSchema.nullable(),productionRevision:z61.int().positive(),completedAt:z61.iso.datetime({offset:true})}).superRefine((receipt,ctx)=>{const{review:review2,manifest,approval}=receipt;if(review2.result!=="PASS"||!sameTarget(manifest.target,review2.target)||manifest.reviewId!==review2.id||manifest.policyFingerprint!==review2.policyFingerprint)ctx.addIssue({code:"custom",message:"Final delivery requires an exact PASS Review and Manifest"});if(review2.policy.finalApproval==="HUMAN"){if(!approval||approval.action!=="APPROVE"||approval.reviewId!==review2.id||approval.policyFingerprint!==review2.policyFingerprint||!sameTarget(approval.target,review2.target))ctx.addIssue({code:"custom",message:"Configured Human gate requires exact Human approval"})}else if(approval){ctx.addIssue({code:"custom",message:"Automatic delivery does not carry an unconfigured approval"})}});import{z as z62}from"zod";var sha8=z62.string().regex(/^[0-9a-f]{64}$/);var DecideFinalReadySchema=TimelineScopeSchema.extend({renderId:z62.uuid(),reviewId:z62.uuid(),basisFingerprint:sha8,action:z62.enum(["SELECT","REJECT"]),acknowledgeWarnings:z62.boolean().default(false),expectedProductionRevision:z62.int().positive(),expectedFinalReadyVersion:z62.int().nonnegative(),reason:z62.string().trim().min(1).max(2500),idempotencyKey:z62.string().trim().min(1).max(200)});var RevokeFinalReadySchema=TimelineScopeSchema.extend({selectionId:z62.uuid(),expectedFinalReadyVersion:z62.int().positive(),expectedProductionRevision:z62.int().positive(),reason:z62.string().trim().min(1).max(2500),idempotencyKey:z62.string().trim().min(1).max(200)});var FinalReadyDecisionSchema=TimelineScopeSchema.extend({id:z62.uuid(),projectId:ProjectIdSchema,version:z62.int().positive(),action:z62.enum(["SELECT","REJECT","REVOKE"]),renderId:z62.uuid(),reviewId:z62.uuid(),basisFingerprint:sha8,timelineVersionId:z62.uuid(),timelineFingerprint:sha8,artifactId:z62.uuid(),representationId:z62.uuid(),checksumSha256:sha8,outputProfile:DeliveryOutputProfileSchema,executionClass:z62.enum(["LIVE","TEST_ONLY"]),previousSelectionId:z62.uuid().nullable(),acknowledgeWarnings:z62.boolean(),warningKeys:z62.array(z62.string()).max(300),reason:z62.string().min(1).max(2500),createdByPrincipalId:PrincipalIdSchema,createdAt:z62.iso.datetime({offset:true})});var FinalReadyViewSchema=TimelineScopeSchema.extend({version:z62.int().nonnegative(),status:z62.enum(["NONE","CURRENT","STALE"]),selection:FinalReadyDecisionSchema.nullable(),staleReasons:z62.array(z62.string()).max(24)});var FinalReadyQuerySchema=TimelineScopeSchema.extend({limit:QueryLimitSchema,next:ContinuationSchema.optional()});var FinalReadyPageSchema=z62.strictObject({items:z62.array(FinalReadyDecisionSchema),page:QueryPageInfoSchema});var FinalReadyReceiptSchema=z62.strictObject({semanticStatus:z62.literal("SUCCESS"),decision:FinalReadyDecisionSchema,productionRevision:z62.int().positive()});var RoughCutReviewSnapshotSchema=z62.strictObject({currentRenderId:z62.uuid().nullable(),latestReviewId:z62.uuid().nullable(),reviewVersion:z62.int().nonnegative(),result:z62.enum(["PASS","WARNING","FAIL"]).nullable(),current:z62.boolean(),inspectable:z62.boolean(),executionClass:z62.enum(["LIVE","TEST_ONLY"]).nullable(),findings:z62.strictObject({open:z62.int().nonnegative(),blocking:z62.int().nonnegative(),warnings:z62.int().nonnegative()}),finalReady:FinalReadyViewSchema,latestDecision:FinalReadyDecisionSchema.nullable()});var sha9=z63.string().regex(/^[0-9a-f]{64}$/);function hasTimelineAudio(timeline){return!!timeline.audio||!!timeline.sourceSound&&(timeline.sourceSound.clips.some(c=>!!c.source)||timeline.sourceSound.speechCues.length>0)}var FinalRenderStartSchema=TimelineScopeSchema.extend({deviceExecution:DeviceRenderTargetSchema.optional(),selectionId:z63.uuid(),expectedFinalReadyVersion:z63.int().positive(),timelineVersionId:z63.uuid(),timelineFingerprint:sha9,expectedProductionRevision:z63.int().positive(),profileId:FinalRenderProfileIdSchema,audioPolicy:z63.enum(["SILENT","MIXED"]),captionPolicy:z63.enum(["NONE","BURN_IN"]),idempotencyKey:z63.string().trim().min(1).max(200)});var FinalRenderGetSchema=RoughCutGetSchema;var FinalRenderQuerySchema=RoughCutQuerySchema;var finalManifestShape={selection:FinalReadyDecisionSchema.refine(v=>v.action==="SELECT"),selectionVersion:z63.int().positive(),profile:FinalRenderProfileSchema};var finalV1=RoughCutManifestSchema.extend(finalManifestShape);var finalV2=RoughCutV2ManifestSchema.extend(finalManifestShape);var finalV3=VisualLayerFinalManifestSchema.safeExtend({...finalManifestShape,profile:VisualLayerFinalProfileSchema});function validateFinalManifest(manifest,context){const{selection:selected,timeline,profile}=manifest;const expectedProfile=finalProfileIds[timeline.output.profile];const landscape=timeline.output.aspectRatio==="16:9";if(!!profile.picturePolicy!==timeline.clips.some(c=>!!c.framing)||profile.audioPolicy!==(hasTimelineAudio(timeline)?"MIXED":"SILENT")||!!profile.audioMix!==hasTimelineAudio(timeline)||profile.captionPolicy!==(timeline.caption?"BURN_IN":"NONE")||!!profile.captionStyle!==!!timeline.caption||!!profile.graphicsPolicy!==!!timeline.graphics?.length||selected.tenantId!==timeline.tenantId||selected.projectId!==timeline.projectId||selected.productionId!==timeline.productionId||selected.timelineVersionId!==timeline.id||selected.timelineFingerprint!==timeline.fingerprint||selected.version>manifest.selectionVersion||selected.outputProfile!==timeline.output.profile||selected.executionClass!==timeline.executionClass||profile.id!==expectedProfile||profile.width>profile.height!==landscape)context.addIssue({code:"custom",message:"Final selection, Timeline and profile mismatch"})}var FinalRenderManifestSchema=finalV1.superRefine(validateFinalManifest);var FinalRenderV2ManifestSchema=finalV2.superRefine(validateFinalManifest);var FinalRenderV3ManifestSchema=finalV3.superRefine(validateFinalManifest);var FinalRenderManifestReaderSchema=z63.discriminatedUnion("schemaVersion",[FinalRenderManifestSchema,FinalRenderV2ManifestSchema,FinalRenderV3ManifestSchema]);var FinalRenderTechnicalSchema=RoughCutTechnicalSchema;var FinalRenderArtifactSchema=RoughCutArtifactSchema.safeExtend({reviewState:z63.literal("UNREVIEWED"),deliveryRole:z63.literal("NONE")});var FinalRenderAdmissionSchema=RoughCutAdmissionSchema.extend({selectionId:z63.uuid(),selectionVersion:z63.int().positive(),profileId:FinalRenderProfileIdSchema});var FinalRenderViewSchema=RoughCutViewSchema.omit({roughCut:true,manifest:true,staleReasons:true}).extend({manifest:FinalRenderManifestReaderSchema,finalOutput:FinalRenderArtifactSchema.nullable(),finalDelivery:FinalDeliveryReceiptSchema.nullable().default(null),staleReasons:z63.array(z63.string().min(1).max(120)).max(24)});var FinalRenderPageSchema=z63.strictObject({items:z63.array(FinalRenderViewSchema).max(200),page:QueryPageInfoSchema});var FinalRenderSourceBlockerSchema=z63.strictObject({code:z63.enum(["SOURCE_RESOLUTION_INSUFFICIENT","SOURCE_MEDIA_UNSUPPORTED"]),shotId:z63.uuid(),ordinal:z63.int().positive().max(200),actualWidth:z63.int().positive().max(4096),actualHeight:z63.int().positive().max(4096),requiredWidth:z63.int().positive().max(4096),requiredHeight:z63.int().positive().max(4096)});var FinalRenderEligibilitySchema=TimelineScopeSchema.extend({productionRevision:z63.int().positive(),finalReady:FinalReadyViewSchema,profile:z63.union([FinalRenderProfileSchema,VisualLayerFinalProfileSchema]).nullable(),renderable:z63.boolean(),blockers:z63.array(z63.string().min(1).max(120)).max(24),sourceBlockers:z63.array(FinalRenderSourceBlockerSchema).max(200),supportedAudioPolicy:z63.enum(["SILENT","MIXED"]),supportedCaptionPolicy:z63.enum(["NONE","BURN_IN"])});var FinalRenderSnapshotSchema=z63.strictObject({latestRenderId:z63.uuid().nullable(),runtimeStatus:RoughCutViewSchema.shape.runtimeStatus.nullable(),currentRenderId:z63.uuid().nullable(),currentArtifactId:z63.uuid().nullable(),stale:z63.boolean(),eligibility:FinalRenderEligibilitySchema});import{z as z64}from"zod";var pixel=z64.int().nonnegative().max(4096);var dimension2=z64.int().positive().max(4096);var frame=z64.int().nonnegative().max(1800);var sample=z64.int().nonnegative().max(288e4);var rectangle=z64.strictObject({x:pixel,y:pixel,width:dimension2,height:dimension2});var window=z64.strictObject({start:sample,count:sample});var source=z64.strictObject({representationId:z64.uuid(),checksum:LocalDigestSchema,byteSize:z64.int().positive().max(134217728)});var LocalMediaRecipeSchema=z64.strictObject({protocol:z64.literal("NVS_RESOLVED_MEDIA_RECIPE_V2"),family:z64.enum(["ROUGH_CUT_RENDER","FINAL_RENDER"]),width:dimension2,height:dimension2,totalFrames:z64.int().min(900).max(1800),crf:z64.union([z64.literal(18),z64.literal(23)]),algorithm:z64.enum(["ORDERED_TRIM_CUT_V1","ORDERED_COMPOSE_V2"]),clips:z64.array(z64.strictObject({representationId:z64.uuid(),technical:VideoTechnicalMetadataSchema,sourceInMs:z64.int().nonnegative().max(6e4),sourceOutMs:z64.int().positive().max(6e4),startFrame:frame,frameCount:z64.int().positive().max(1800),overlapFrames:frame,crop:rectangle.nullable(),viewport:rectangle})).min(1).max(32),caption:z64.strictObject({style:CaptionRenderStyleSchema,references:z64.array(z64.strictObject({representationId:z64.uuid(),expectedUtf8:z64.string().max(65536)})).length(2),cues:z64.array(z64.strictObject({ordinal:z64.int().nonnegative().max(512),startFrame:frame,endFrame:frame,fontSize:z64.int().min(16).max(256),margin:pixel,text:z64.string().min(1).max(2e3)})).min(1).max(512)}).nullable(),audio:z64.strictObject({algorithm:z64.literal("PCM_WINDOW_MIX_AAC_V1"),tracks:z64.array(source.extend({channels:z64.union([z64.literal(1),z64.literal(2)]),sampleCount:z64.int().positive().max(288e4),sourceIn:sample,sourceOut:sample,start:sample,count:sample,gain:z64.int().nonnegative().max(1e3),duck:z64.int().nonnegative().max(1e3),duckWindows:z64.array(window).max(512)})).min(1).max(266)}).nullable(),graphics:z64.array(source.extend({contentType:z64.enum(["image/png","image/webp"]),sourceWidth:dimension2,sourceHeight:dimension2,width:dimension2,height:dimension2,x:pixel,y:pixel,startFrame:frame,endFrame:frame,opacity:z64.number().min(.1).max(1)})).max(8),visual:z64.strictObject({policy:VisualLayerPolicySchema.optional(),composition:VisualLayerCompositionSchema,plans:z64.array(z64.strictObject({id:z64.uuid(),startFrame:frame,endFrame:frame,width:dimension2,height:dimension2,x:pixel,y:pixel,opacityPermille:z64.int().min(0).max(1e3)})).max(8)}).nullable()}).superRefine((r,ctx)=>{if(r.width%2||r.height%2||r.clips.some(c=>c.viewport.x+c.viewport.width>r.width||c.viewport.y+c.viewport.height>r.height||c.sourceOutMs<=c.sourceInMs)||r.audio?.tracks.some(t=>t.sourceIn>=t.sourceOut||t.sourceOut>t.sampleCount||t.start+t.count>r.totalFrames*1600))ctx.addIssue({code:"custom",message:"Invalid bounded execution geometry or sample window"})});var previewProfile=z65.strictObject({kind:z65.literal("ROUGH_CUT_PREVIEW_V1"),profileId:z65.literal("PREVIEW_H264_480P_V1"),contractDigest:LocalDigestSchema});var studioProfile=z65.strictObject({kind:z65.literal("STUDIO_MEDIA_V2"),profileId:z65.literal("STUDIO_MEDIA_V2"),contractDigest:LocalDigestSchema});var audioProfile=z65.strictObject({kind:z65.literal("AUDIO_MEDIA_V1"),profileId:z65.literal("AUDIO_MEDIA_V1"),contractDigest:LocalDigestSchema});var LocalExecutionProfileSchema=z65.discriminatedUnion("kind",[previewProfile,studioProfile,audioProfile]);var LocalToolchainSchema=z65.strictObject({platform:LocalDevicePlatformSchema,rendererVersion:LocalPackageVersionSchema,rendererDigest:LocalDigestSchema,ffmpeg:z65.strictObject({version:z65.string().min(1).max(160),binaryDigest:LocalDigestSchema}),ffprobe:z65.strictObject({version:z65.string().min(1).max(160),binaryDigest:LocalDigestSchema}),profile:LocalExecutionProfileSchema,supported:z65.array(z65.strictObject({profile:LocalExecutionProfileSchema,rendererVersion:LocalPackageVersionSchema,rendererDigest:LocalDigestSchema})).max(4).optional()});function selectLocalToolchain(raw,contractDigest){const parsed=LocalToolchainSchema.safeParse(raw);if(!parsed.success)return null;const value2=parsed.data;if(value2.profile.contractDigest===contractDigest){return value2.supported&&value2.profile.kind!=="AUDIO_MEDIA_V1"?{...value2,supported:value2.supported.filter(s=>s.profile.kind!=="AUDIO_MEDIA_V1")}:value2}const selected=value2.supported?.find(s=>s.profile.contractDigest===contractDigest);if(!selected)return null;const{supported,...base3}=value2;void supported;return LocalToolchainSchema.parse({...base3,...selected})}var frozen=LocalWorkScopeSchema.extend({protocol:z65.literal("NVS_LOCAL_WORK_V1"),operationId:OperationIdSchema,renderId:LocalIdSchema,productionRevision:LocalRevisionSchema,executionClass:z65.enum(["LIVE","TEST_ONLY"]),policy:LocalPlacementPolicySchema,profile:previewProfile,manifest:RoughCutManifestReaderSchema,manifestFingerprint:LocalDigestSchema,sources:z65.array(z65.strictObject({artifactId:LocalIdSchema,representationId:LocalIdSchema,checksumSha256:LocalDigestSchema,byteSize:z65.int().positive(),contentType:z65.string().min(1).max(100)})).min(1).max(512)});var studio=frozen.extend({protocol:z65.literal("NVS_LOCAL_WORK_V2"),profile:studioProfile,manifest:z65.union([RoughCutManifestReaderSchema,FinalRenderManifestReaderSchema]),recipe:LocalMediaRecipeSchema,recipeFingerprint:LocalDigestSchema});var LocalFrozenWorkSchema=z65.discriminatedUnion("protocol",[frozen,studio]).superRefine((v,ctx)=>{const t=v.manifest.timeline;if(t.tenantId!==v.tenantId||t.projectId!==v.projectId||t.productionId!==v.productionId||t.executionClass!==v.executionClass)ctx.addIssue({code:"custom",message:"Frozen manifest scope/class mismatch"});if(v.protocol==="NVS_LOCAL_WORK_V2"&&(v.manifest.schemaVersion===3!==!!v.recipe.visual||v.manifest.schemaVersion===3&&v.manifest.profile.visualLayerPolicy!==(v.recipe.visual?.policy??"STRAIGHT_ALPHA_FRAME_OVERLAY_30_V1")))ctx.addIssue({code:"custom",message:"Recipe must preserve the frozen visual policy"});if(new Set(v.sources.map(s=>s.representationId)).size!==v.sources.length)ctx.addIssue({code:"custom",message:"Duplicate source representation"});if(v.protocol==="NVS_LOCAL_WORK_V2"&&(v.recipe.width!==v.manifest.profile.width||v.recipe.height!==v.manifest.profile.height||v.recipe.totalFrames!==v.manifest.totalFrames||v.recipe.family==="FINAL_RENDER"!=="selection"in v.manifest))ctx.addIssue({code:"custom",message:"Recipe must match its native render family and geometry"})});var LocalLeaseBindingSchema=LocalWorkScopeSchema.extend({attemptId:LocalIdSchema,assignmentRevision:LocalRevisionSchema,workerId:z65.string().min(1).max(200),workFingerprint:LocalDigestSchema,toolchainFingerprint:LocalDigestSchema});var target=LocalDeviceExecutionTargetSchema;var LocalExecutionLeaseSchema=LocalLeaseBindingSchema.extend({target,issuedAt:LocalTimeSchema,expiresAt:LocalTimeSchema}).refine(v=>Date.parse(v.expiresAt)>Date.parse(v.issuedAt));var LocalWorkAssignmentSchema=z65.strictObject({work:LocalFrozenWorkSchema,lease:LocalExecutionLeaseSchema,toolchain:LocalToolchainSchema,tenantMediaValidation:z65.literal(true).optional()}).superRefine(({work,lease,toolchain,tenantMediaValidation},ctx)=>{if(["tenantId","projectId","productionId","runtimeJobId"].some(k=>work[k]!==lease[k]))ctx.addIssue({code:"custom",message:"Assignment work scope mismatch"});if(tenantMediaValidation&&(work.protocol!=="NVS_LOCAL_WORK_V2"||work.policy.mode!=="local-only"))ctx.addIssue({code:"custom",message:"Invalid tenant validation assignment"});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 z67}from"zod";import{z as z66}from"zod";var MediaCategorySchema=z66.enum(["IMAGE","VIDEO","AUDIO","DOCUMENT"]);function mediaCategoryOf(contentType){if(contentType.startsWith("image/"))return"IMAGE";if(contentType.startsWith("video/"))return"VIDEO";if(contentType.startsWith("audio/"))return"AUDIO";return"DOCUMENT"}var localLibraryProfile={protocol:"NVS_LOCAL_LIBRARY_V1",inspection:"LOCAL_FILE_DECODE_V1",publication:"COMMITTED_SOURCE_READBACK_V1"};var LocalLibraryContentTypeSchema=z67.enum(["video/mp4","image/png","image/jpeg","image/webp","audio/wav","text/plain","application/json","application/pdf","application/octet-stream"]);var LocalLibraryVersionSchema=z67.strictObject({fileId:LocalIdSchema,versionId:LocalIdSchema,checksumSha256:LocalDigestSchema,byteSize:z67.int().nonnegative().max(128*1024*1024),contentType:LocalLibraryContentTypeSchema});var LocalLibraryReferenceSchema=LocalProjectScopeSchema.extend({deviceId:LocalIdSchema,...LocalLibraryVersionSchema.shape});var LocalLibraryMetadataSchema=z67.strictObject({label:z67.string().trim().min(1).max(255)});var LocalLibraryAccessCommandSchema=z67.strictObject({reference:LocalLibraryReferenceSchema,requestId:LocalIdSchema,expectedRevision:z67.int().nonnegative(),metadata:LocalLibraryMetadataSchema.nullable(),allowInspect:z67.boolean(),allowPublish:z67.boolean(),expiresAt:LocalTimeSchema});var LocalLibraryAccessReceiptSchema=LocalLibraryAccessCommandSchema.extend({revision:z67.int().positive(),recordedAt:LocalTimeSchema});var LocalLibraryAccessQuerySchema=z67.strictObject({reference:LocalLibraryReferenceSchema,requestId:LocalIdSchema});var LocalLibraryAccessCurrentSchema=z67.strictObject({reference:LocalLibraryReferenceSchema});var LocalLibraryAccessStateSchema=z67.strictObject({state:z67.enum(["LOCAL_ONLY","PENDING","SYNCED","UNKNOWN","REJECTED"]),desired:LocalLibraryAccessCommandSchema.nullable(),confirmed:LocalLibraryAccessReceiptSchema.nullable()});var LocalLibraryItemSchema=z67.strictObject({reference:LocalLibraryReferenceSchema,ownerKey:LocalDigestSchema,title:z67.string().trim().min(1).max(255),createdAt:LocalTimeSchema,revision:z67.int().positive(),access:LocalLibraryAccessStateSchema});var pageFields={after:LocalDigestSchema.nullable().default(null),limit:z67.int().min(1).max(16).default(16)};var LocalLibraryQuerySchema=LocalProjectScopeSchema.extend({projectId:LocalIdSchema.optional(),deviceId:LocalIdSchema,ownerKey:LocalDigestSchema.optional(),search:z67.string().trim().min(1).max(200).optional(),mediaCategory:MediaCategorySchema.optional(),...pageFields});var LocalLibraryPageSchema=z67.strictObject({items:z67.array(LocalLibraryItemSchema).max(16),nextCursor:LocalDigestSchema.nullable()});var LocalLibraryProjectionSchema=z67.strictObject({reference:LocalLibraryReferenceSchema,metadata:LocalLibraryMetadataSchema.nullable(),accessRevision:z67.int().positive(),allowInspect:z67.boolean(),allowPublish:z67.boolean(),expiresAt:LocalTimeSchema});var LocalLibraryProjectionPageSchema=z67.strictObject({items:z67.array(LocalLibraryProjectionSchema).max(16),nextCursor:LocalDigestSchema.nullable()});var LocalLibraryProjectionQuerySchema=LocalLibraryQuerySchema.omit({ownerKey:true}).extend({projectId:LocalIdSchema});var LocalLibraryImportSchema=z67.strictObject({requestId:LocalIdSchema,reference:LocalLibraryReferenceSchema,ownerKey:LocalDigestSchema,title:z67.string().trim().min(1).max(255)});var LocalLibraryImportReceiptQuerySchema=LocalProjectScopeSchema.extend({deviceId:LocalIdSchema,requestId:LocalIdSchema,ownerKey:LocalDigestSchema.optional()});var LocalLibraryReadSchema=z67.strictObject({reference:LocalLibraryReferenceSchema,ownerKey:LocalDigestSchema.optional(),offset:z67.int().nonnegative(),length:z67.int().min(1).max(128*1024)});var LocalLibraryReadReplySchema=z67.strictObject({reference:LocalLibraryReferenceSchema,offset:z67.int().nonnegative(),contentBase64:z67.string().max(174764).regex(/^[A-Za-z0-9+/]*={0,2}$/),complete:z67.boolean()});var LocalLibraryGetSchema=z67.strictObject({reference:LocalLibraryReferenceSchema,ownerKey:LocalDigestSchema.optional()});var LocalLibraryAccessInputSchema=z67.strictObject({command:LocalLibraryAccessCommandSchema,expectedLocalRevision:z67.int().positive(),ownerKey:LocalDigestSchema.optional()});var LocalLibraryCallSchema=z67.discriminatedUnion("action",[LocalLibraryQuerySchema.extend({action:z67.literal("list")}),LocalLibraryGetSchema.extend({action:z67.literal("get")}),LocalLibraryProjectionQuerySchema.extend({action:z67.literal("scoped-list")}),z67.strictObject({action:z67.literal("scoped-get"),reference:LocalLibraryReferenceSchema}),z67.strictObject({action:z67.literal("usage"),ownerKey:LocalDigestSchema.optional()}),LocalLibraryReadSchema.extend({action:z67.literal("read")}),LocalLibraryAccessInputSchema.extend({action:z67.literal("access")}),LocalLibraryAccessQuerySchema.extend({action:z67.literal("sync"),ownerKey:LocalDigestSchema.optional()}),LocalLibraryAccessQuerySchema.extend({action:z67.literal("resume-access"),ownerKey:LocalDigestSchema.optional()}),LocalLibraryImportReceiptQuerySchema.extend({action:z67.literal("import-receipt")})]);var LocalLibraryCapabilitySchema=z67.strictObject({protocol:z67.literal("NVS_LOCAL_LIBRARY_V1"),available:z67.boolean(),profileDigest:LocalDigestSchema});var LocalLibraryUsageSchema=z67.strictObject({fileCount:z67.int().nonnegative(),totalBytes:z67.int().nonnegative(),quotaBytes:z67.int().positive(),availableDiskBytes:z67.int().nonnegative()});import{z as z76}from"zod";import{z as z68}from"zod";var TemporalEvidenceReferenceSchema=z68.strictObject({evidenceId:z68.uuid(),frameSetArtifactId:z68.uuid(),contactSheetArtifactId:z68.uuid(),manifestRepresentationId:z68.uuid(),sheetRepresentationId:z68.uuid(),planFingerprint:z68.string().regex(/^[0-9a-f]{64}$/),sourceArtifactId:z68.uuid(),sourceRepresentationId:z68.uuid(),sourceChecksumSha256:z68.string().regex(/^[0-9a-f]{64}$/),timestampsMs:z68.array(z68.number().nonnegative().max(6e4)).min(1).max(64),executionClass:z68.enum(["LIVE","TEST_ONLY"])});var TemporalEvidenceIdsSchema=z68.array(z68.uuid()).min(1).max(8).refine(v=>new Set(v).size===v.length,"Evidence references must be unique");import{z as z75}from"zod";import{z as z70}from"zod";import{z as z69}from"zod";var ListeningEvidenceIdsSchema=z69.array(z69.string().min(1).max(100)).max(64);var ListeningEvidenceSchema=z69.strictObject({id:z69.string().trim().min(1).max(100),kind:z69.enum(["AUDIO_LISTENING","VIDEO_WITH_AUDIO_PLAYBACK"]),media:z69.strictObject({artifactId:z69.uuid(),representationId:z69.uuid(),checksumSha256:z69.string().regex(/^[0-9a-f]{64}$/)}),coverage:z69.array(z69.strictObject({startMs:z69.int().nonnegative().max(6e4),endMs:z69.int().positive().max(6e4)}).refine(v=>v.endMs>v.startMs)).min(1).max(200),producer:z69.string().trim().min(1).max(200)});var ListeningEvidenceSetSchema=z69.array(ListeningEvidenceSchema).max(64).refine(v=>new Set(v.map(e=>e.id)).size===v.length);var sha10=z70.string().regex(/^[a-f0-9]{64}$/);var VoiceListeningIntervalSchema=ListeningEvidenceSchema.shape.coverage.element;var VoiceExpectationSchema=z70.strictObject({voiceProfile:VoiceProfileRefSchema,referenceId:z70.uuid()});var VoiceRuleTargetsSchema=z70.discriminatedUnion("kind",[z70.strictObject({kind:z70.literal("VOICEOVER")}),z70.strictObject({kind:z70.literal("SOUND_CUES"),cueIds:z70.array(z70.string().regex(/^[a-z][a-z0-9_-]{0,63}$/)).min(1).max(64).refine(ids=>new Set(ids).size===ids.length)})]);var VoiceConsistencyReasonSchema=z70.enum(["NO_SOURCE","VOICE_UNAVAILABLE","REFERENCE_CHANGED","AUDIO_UNAVAILABLE","IDENTITY_MISMATCH","NO_COMPARISON","COMPARISON_NOT_MATCHED","COMPARISON_STALE","TEST_ONLY"]);var VoiceRequirementGateSchema=z70.strictObject({qualified:z70.boolean(),evidenceFingerprint:sha10,listeningIntervals:z70.array(VoiceListeningIntervalSchema).min(1).max(264),sourceAudioVersionIds:z70.array(z70.uuid()).max(65),reasons:z70.array(VoiceConsistencyReasonSchema).max(9)}).refine(v=>v.qualified===(v.reasons.length===0)&&(!v.qualified||v.sourceAudioVersionIds.length>0));var VoiceSourceEvidenceSchema=z70.strictObject({audioVersionId:z70.uuid(),voiceProfile:VoiceProfileRefSchema.nullable(),referenceId:z70.uuid().nullable(),comparisonId:z70.uuid().nullable(),comparisonVersion:z70.int().nonnegative(),comparisonFingerprint:sha10.nullable(),identityResult:z70.enum(["MATCH","DIFFERENT","UNDETERMINED"]).nullable(),current:z70.boolean(),executionClass:z70.enum(["LIVE","TEST_ONLY"]).nullable(),reasons:z70.array(VoiceConsistencyReasonSchema).max(9)});var VoiceExpectationEvidenceSchema=VoiceExpectationSchema.extend({current:z70.boolean(),executionClass:z70.enum(["LIVE","TEST_ONLY"]).nullable(),reasons:z70.array(VoiceConsistencyReasonSchema).max(9)});var ProductionVoiceEvidenceSchema=z70.strictObject({expectations:z70.array(VoiceExpectationEvidenceSchema).max(16),sources:z70.array(VoiceSourceEvidenceSchema).max(65)});import{z as z71}from"zod";var sha11=z71.string().regex(/^[0-9a-f]{64}$/);var CompositionFindingLocalitySchema=z71.strictObject({schemaVersion:z71.literal(1),sourceKind:z71.literal("CODE"),role:z71.enum(["PRIMARY_VISUAL","VISUAL_LAYER"]),compositionId:z71.uuid(),compositionVersionId:z71.uuid(),compositionVersion:z71.int().positive(),compositionFingerprint:sha11,renderId:z71.uuid(),renderManifestFingerprint:sha11,artifactId:z71.uuid(),representationId:z71.uuid(),checksumSha256:sha11,clipOrdinal:z71.int().min(1).max(200).nullable(),visualLayerId:z71.uuid().nullable(),sourceInFrame:z71.int().min(0).max(359),sourceOutFrame:z71.int().min(1).max(360),mapping:z71.literal("INTERSECTING_NATIVE_30FPS_FRAME_CELLS")}).superRefine((v,ctx)=>{if(v.sourceOutFrame<=v.sourceInFrame||(v.role==="PRIMARY_VISUAL"?v.clipOrdinal===null||v.visualLayerId!==null:v.visualLayerId===null||v.clipOrdinal!==null))ctx.addIssue({code:"custom",message:"CODE locality requires an exact occurrence and advancing local frame interval"})});import{z as z72}from"zod";var CanonicalFactSchema=z72.strictObject({key:z72.string().regex(/^[A-Z][A-Z0-9_]{1,59}$/),value:z72.string().trim().min(1).max(300),sourceArtifactId:ArtifactIdSchema,evidence:z72.discriminatedUnion("kind",[z72.strictObject({kind:z72.literal("JSON_POINTER"),pointer:z72.string().startsWith("/").max(200)}),z72.strictObject({kind:z72.literal("EXACT_TEXT_LINE")})])});var BriefContentSchema=z72.strictObject({objective:z72.string().trim().min(1).max(1e3),productPresentationGoal:z72.string().trim().min(1).max(1e3),audience:z72.string().trim().min(1).max(300).optional(),styleTone:z72.string().trim().min(1).max(300).optional(),callToAction:z72.string().trim().min(1).max(300).optional(),targetDurationSeconds:z72.int().min(30).max(60),aspectRatio:z72.enum(["16:9","9:16"]),outputProfile:DeliveryOutputProfileSchema,canonicalFacts:z72.array(CanonicalFactSchema).max(32).default([])});var AcceptBriefRequestSchema=z72.strictObject({tenantId:TenantIdSchema,expectedProductionRevision:z72.int().positive(),revisionReason:z72.string().trim().min(1).max(1e3).optional(),sourceArtifactIds:z72.array(ArtifactIdSchema).max(20).default([]),content:BriefContentSchema});var BriefSourceReferenceSchema=z72.strictObject({artifactId:ArtifactIdSchema,checksumSha256:z72.string().regex(/^[0-9a-f]{64}$/)});var BriefVersionSchema=z72.strictObject({id:BriefVersionIdSchema,briefId:BriefIdSchema,tenantId:TenantIdSchema,projectId:ProjectIdSchema,productionId:ProductionIdSchema,version:z72.int().positive(),content:BriefContentSchema,sources:z72.array(BriefSourceReferenceSchema).min(1).max(20),createdByPrincipalId:PrincipalIdSchema,createdAt:z72.iso.datetime({offset:true})});var AcceptBriefResultSchema=z72.discriminatedUnion("semanticStatus",[z72.strictObject({semanticStatus:z72.literal("SUCCESS"),briefVersion:BriefVersionSchema,productionRevision:z72.int().positive(),activeBriefVersion:z72.int().positive()}),z72.strictObject({semanticStatus:z72.literal("NEEDS_INPUT"),missingFacts:z72.array(z72.enum(["PRODUCT_INFORMATION_SOURCE","PRODUCT_NAME"])).min(1)})]);import{z as z73}from"zod";var StoryFactKeySchema=z73.string().regex(/^[A-Z][A-Z0-9_]{1,59}$/);var StoryFactClaimSchema=z73.strictObject({key:StoryFactKeySchema,value:z73.string().trim().min(1).max(300)});var StoryBeatSchema=z73.strictObject({summary:z73.string().trim().min(1).max(600),sceneRequirements:z73.array(z73.string().trim().min(1).max(300)).max(8).default([])});var StoryContentSchema=z73.strictObject({narrativeIntent:z73.string().trim().min(1).max(2e3),beats:z73.array(StoryBeatSchema).min(1).max(24),factualClaims:z73.array(StoryFactClaimSchema).max(32).default([])});var AcceptStoryRequestSchema=z73.strictObject({tenantId:TenantIdSchema,expectedProductionRevision:z73.int().positive(),expectedBriefVersion:z73.int().positive(),revisionReason:z73.string().trim().min(1).max(1e3).optional(),idempotencyKey:z73.string().trim().min(1).max(200),content:StoryContentSchema});var StoryVersionSchema=z73.strictObject({id:StoryVersionIdSchema,storyId:StoryIdSchema,tenantId:TenantIdSchema,projectId:ProjectIdSchema,productionId:ProductionIdSchema,version:z73.int().positive(),briefVersionId:BriefVersionIdSchema,briefVersion:z73.int().positive(),content:StoryContentSchema,createdByPrincipalId:PrincipalIdSchema,createdAt:z73.iso.datetime({offset:true})});var AcceptStoryResultSchema=z73.discriminatedUnion("semanticStatus",[z73.strictObject({semanticStatus:z73.literal("SUCCESS"),storyVersion:StoryVersionSchema,productionRevision:z73.int().positive(),activeStoryVersion:z73.int().positive()}),z73.strictObject({semanticStatus:z73.literal("NEEDS_INPUT"),missingPrerequisites:z73.array(z73.literal("ACTIVE_BRIEF")).min(1)})]);import{z as z74}from"zod";var ConsistencyFamilySchema=z74.enum(["PRODUCT_IDENTITY","CHARACTER_IDENTITY","WARDROBE","LOCATION","BOUNDARY_CONTINUITY","STYLE","VOICE_IDENTITY"]);var ConsistencyEnforcementSchema=z74.enum(["LOCKED","REQUIRED","PREFERRED","FREE"]);var ConsistencyMasterReferenceSchema=z74.strictObject({artifactId:ArtifactIdSchema,representationId:ArtifactRepresentationIdSchema,checksumSha256:z74.string().regex(/^[0-9a-f]{64}$/),artifactChecksumSha256:z74.string().regex(/^[0-9a-f]{64}$/),contentType:z74.enum(["image/png","image/jpeg","image/webp","audio/wav"])});var Fact=z74.strictObject({dimension:z74.string().regex(/^[A-Z][A-Z0-9_]{0,63}$/),value:z74.string().trim().min(1).max(1e3)});var ConsistencySubjectSchema=z74.strictObject({id:z74.uuid(),kind:z74.enum(["CHARACTER","VOICE"]),displayName:z74.string().trim().min(1).max(200),facts:z74.array(Fact).min(1).max(32),master:ConsistencyMasterReferenceSchema,voiceExpectation:VoiceExpectationSchema.optional()}).superRefine((s,c)=>{if(new Set(s.facts.map(f=>f.dimension)).size!==s.facts.length)c.addIssue({code:"custom",message:"Canonical subject dimensions must be unique"});if(s.kind==="VOICE"!==(s.master.contentType==="audio/wav"))c.addIssue({code:"custom",message:"Character requires an image master; Voice requires audio"});if(s.voiceExpectation&&s.kind!=="VOICE")c.addIssue({code:"custom",message:"Only Voice subjects carry a voice expectation"})});var ConsistencyRuleScopeSchema=z74.discriminatedUnion("kind",[z74.strictObject({kind:z74.literal("PROJECT")}),z74.strictObject({kind:z74.literal("PRODUCTION")}),z74.strictObject({kind:z74.literal("SCENE"),id:z74.uuid()}),z74.strictObject({kind:z74.literal("SHOT"),id:z74.uuid()}),z74.strictObject({kind:z74.literal("CONTINUITY_EDGE"),id:z74.uuid()})]);var ConsistencyRuleSchema=z74.strictObject({voiceTargets:VoiceRuleTargetsSchema.optional(),reviewScales:z74.array(ConsistencyReviewScaleSchema).min(1).max(3).refine(s=>new Set(s).size===s.length,"Review scales must be unique").optional(),continuity:ContinuityExpectationSchema.optional(),id:z74.uuid(),family:ConsistencyFamilySchema,subjectId:z74.uuid().nullable(),dimension:z74.string().regex(/^[A-Z][A-Z0-9_]{0,63}$/),scope:ConsistencyRuleScopeSchema,enforcement:ConsistencyEnforcementSchema,expected:z74.string().trim().min(1).max(1e3).nullable(),referenceMode:z74.enum(["NONE","SUBJECT_MASTER","EXACT"]),reference:ConsistencyMasterReferenceSchema.optional(),override:z74.strictObject({priorRuleId:z74.uuid(),reason:z74.string().trim().min(1).max(1e3)}).optional(),transition:z74.strictObject({edgeId:z74.uuid(),from:z74.string().trim().min(1).max(1e3),to:z74.string().trim().min(1).max(1e3),reason:z74.string().trim().min(1).max(1e3)}).optional()}).superRefine((r,c)=>{const invalid=message=>c.addIssue({code:"custom",message});if(r.continuity&&(r.enforcement==="FREE"||r.family==="VOICE_IDENTITY"))invalid("FREE/Voice rules cannot create visual state/time obligations");if(r.family==="VOICE_IDENTITY"&&r.enforcement!=="FREE"&&(!r.voiceTargets||r.referenceMode!=="SUBJECT_MASTER"||r.reviewScales?.length!==1||r.reviewScales[0]!=="PRODUCTION"))invalid("Active Voice identity requires explicit audio targets, subject reference and full-production review");if(r.voiceTargets&&(r.family!=="VOICE_IDENTITY"||r.enforcement==="FREE"))invalid("Only active Voice rules select audio targets");if(r.enforcement==="FREE"!==(r.expected===null))invalid("FREE has no expected obligation; other enforcement requires an expectation");if(r.enforcement==="FREE"&&r.referenceMode!=="NONE")invalid("FREE cannot require reference conditioning");if(r.referenceMode==="EXACT"!==(r.reference!==void 0))invalid("Only EXACT reference mode carries an exact reference");if(r.referenceMode==="SUBJECT_MASTER"&&!r.subjectId)invalid("SUBJECT_MASTER requires an exact canonical subject");if(["CHARACTER_IDENTITY","WARDROBE","VOICE_IDENTITY"].includes(r.family)&&!r.subjectId)invalid("Character, Wardrobe and Voice obligations require an exact subject");if(r.family==="CHARACTER_IDENTITY"&&["LOCKED","REQUIRED"].includes(r.enforcement)&&r.referenceMode==="NONE")invalid("Mandatory Character identity requires concrete identity evidence");if(r.transition&&(r.family!=="WARDROBE"||r.transition.to!==r.expected||!r.override))invalid("A planned Wardrobe transition must name the changed inherited rule and new expectation")});var ConsistencyProfileContentSchema=z74.strictObject({subjects:z74.array(ConsistencySubjectSchema).max(32),rules:z74.array(ConsistencyRuleSchema).max(256)}).superRefine((p,c)=>{const invalid=message=>c.addIssue({code:"custom",message});if(new Set(p.subjects.map(s=>s.id)).size!==p.subjects.length||new Set(p.rules.map(r=>r.id)).size!==p.rules.length)invalid("Consistency subjects and rules require distinct stable IDs");if(p.rules.filter(r=>r.family==="VOICE_IDENTITY"&&r.enforcement!=="FREE").length>16)invalid("Voice obligations exceed their bounded rule budget");for(const r of p.rules){const s=p.subjects.find(s2=>s2.id===r.subjectId);if(r.subjectId&&!s)invalid("Rule names an unknown canonical subject");if(r.family==="VOICE_IDENTITY"&&r.enforcement!=="FREE"&&!s?.voiceExpectation)invalid("Active Voice identity requires an exact approved voice expectation");if(s&&r.family==="VOICE_IDENTITY"!==(s.kind==="VOICE")&&["CHARACTER_IDENTITY","WARDROBE","VOICE_IDENTITY"].includes(r.family))invalid("Rule family and canonical subject kind disagree");if(r.override&&!p.rules.some(prior=>prior.id===r.override.priorRuleId))invalid("An override must name an existing inherited rule");if(r.reference&&r.family==="VOICE_IDENTITY"!==(r.reference.contentType==="audio/wav"))invalid("Visual obligations cannot use audio and Voice obligations cannot use images")}});var ConsistencyProfileScopeSchema=z74.strictObject({tenantId:TenantIdSchema,productionId:ProductionIdSchema});var ConsistencyProfileVersionQuerySchema=ConsistencyProfileScopeSchema.extend({profileId:z74.uuid()});var ConfigureConsistencyProfileSchema=ConsistencyProfileScopeSchema.extend({expectedProductionRevision:z74.int().positive(),expectedProfileVersion:z74.int().nonnegative(),content:ConsistencyProfileContentSchema,reason:z74.string().trim().min(1).max(2e3),idempotencyKey:z74.string().trim().min(1).max(200)});var ConsistencyProfileVersionSchema=ConsistencyProfileScopeSchema.extend({id:z74.uuid(),projectId:ProjectIdSchema,version:z74.int().positive(),previousVersionId:z74.uuid().nullable(),content:ConsistencyProfileContentSchema,fingerprint:z74.string().regex(/^[0-9a-f]{64}$/),reason:z74.string().trim().min(1).max(2e3),createdByPrincipalId:PrincipalIdSchema,createdAt:z74.iso.datetime({offset:true})});var ConsistencyProfileViewSchema=ConsistencyProfileScopeSchema.extend({productionRevision:z74.int().positive(),current:ConsistencyProfileVersionSchema.nullable()});var ConsistencyProfileReceiptSchema=z74.strictObject({semanticStatus:z74.literal("SUCCESS"),profile:ConsistencyProfileVersionSchema,productionRevision:z74.int().positive()});var sha12=z75.string().regex(/^[0-9a-f]{64}$/);var RoughCutReviewScopeSchema=TimelineScopeSchema.extend({renderId:z75.uuid()});var ReviewIntervalSchema=z75.strictObject({startMs:z75.int().nonnegative().max(6e4),endMs:z75.int().positive().max(6e4)}).refine(v=>v.endMs>v.startMs,"Review interval must advance");var RoughCutRequirementSchema=z75.strictObject({voiceIdentity:VoiceRequirementGateSchema.optional(),continuity:ContinuityExpectationSchema.optional(),consistencyScale:ConsistencyReviewScaleSchema.optional(),consistencyFamily:z75.enum(["PRODUCT_IDENTITY","CHARACTER_IDENTITY","WARDROBE","LOCATION","STYLE","BOUNDARY_CONTINUITY","VOICE_IDENTITY"]).optional(),consistencySubject:ConsistencySubjectSchema.optional(),consistencyReference:ConsistencyMasterReferenceSchema.optional(),key:z75.string().min(1).max(220),dimension:z75.enum(["PRODUCT_PRESENTATION","CANONICAL_FACT","NARRATIVE","PACING","REPETITION","STYLE","TECHNICAL","TRANSITION"]),expected:z75.string().min(1).max(4e3),enforcement:z75.enum(["LOCKED","REQUIRED","PREFERRED"]),scope:z75.enum(["PRODUCTION","TRANSITION"]),interval:ReviewIntervalSchema,shotIds:z75.array(z75.uuid()).min(1).max(200)});var RoughCutObservationSchema=z75.strictObject({listeningEvidenceIds:ListeningEvidenceIdsSchema.optional(),continuitySamples:ContinuitySamplesSchema.optional(),temporalEvidenceIds:TemporalEvidenceIdsSchema.optional(),key:z75.string().min(1).max(220),status:z75.enum(["SATISFIED","VIOLATED","NOT_OBSERVABLE","NOT_APPLICABLE"]),confidence:z75.enum(["CLEAR","UNCERTAIN"]),observed:z75.string().trim().min(1).max(1800),interval:ReviewIntervalSchema,location:z75.strictObject({interval:ReviewIntervalSchema,shotIds:z75.array(z75.uuid()).min(1).max(200)}).optional()});var RoughCutInspectionSchema=z75.strictObject({actor:z75.enum(["HUMAN","EXTERNAL_AGENT"]),method:z75.literal("FULL_TEMPORAL_INSPECTION"),coverage:z75.array(ReviewIntervalSchema).min(1).max(200)});var RoughCutReviewBasisSchema=z75.strictObject({voiceEvidence:ProductionVoiceEvidenceSchema.optional(),consistencyRequirements:z75.array(RoughCutRequirementSchema).max(256).optional(),artifactId:z75.uuid(),representationId:z75.uuid(),checksumSha256:sha12,manifestFingerprint:sha12,manifest:RoughCutManifestReaderSchema,brief:BriefVersionSchema,story:StoryVersionSchema});var RecordRoughCutReviewSchema=RoughCutReviewScopeSchema.extend({listeningEvidence:ListeningEvidenceSetSchema.optional(),artifactId:z75.uuid(),representationId:z75.uuid(),checksumSha256:sha12,basisFingerprint:sha12,expectedProductionRevision:z75.int().positive(),expectedReviewVersion:z75.int().nonnegative(),idempotencyKey:z75.string().trim().min(1).max(200),inspection:RoughCutInspectionSchema,observations:z75.array(RoughCutObservationSchema).min(1).max(300),summary:z75.string().trim().min(1).max(2500)});var RoughCutReviewRecordSchema=RoughCutReviewScopeSchema.extend({listeningEvidence:ListeningEvidenceSetSchema.optional(),id:z75.uuid(),projectId:ProjectIdSchema,version:z75.int().positive(),kind:z75.literal("PRODUCTION_REVIEW_2"),lifecycle:z75.literal("COMPLETED"),evaluatorVersion:z75.literal("production-review-v1"),basis:RoughCutReviewBasisSchema,basisFingerprint:sha12,executionClass:z75.enum(["LIVE","TEST_ONLY"]),technical:RoughCutTechnicalSchema,durationMs:z75.int().min(3e4).max(6e4),requirements:z75.array(RoughCutRequirementSchema).min(1).max(300),inspection:RoughCutInspectionSchema,observations:z75.array(RoughCutObservationSchema).min(1).max(300),result:z75.enum(["PASS","WARNING","FAIL"]),blockingKeys:z75.array(z75.string()).max(300),warningKeys:z75.array(z75.string()).max(300),summary:z75.string().min(1).max(2500),createdByPrincipalId:PrincipalIdSchema,createdAt:z75.iso.datetime({offset:true})});var RoughCutReviewTargetSchema=RoughCutReviewScopeSchema.extend({temporalEvidence:z75.array(TemporalEvidenceReferenceSchema).max(8).optional(),projectId:ProjectIdSchema,productionRevision:z75.int().positive(),productionRunnable:z75.boolean(),executionClass:z75.enum(["LIVE","TEST_ONLY"]),freshness:z75.enum(["CURRENT_BASIS","STALE_BASIS"]),staleReasons:z75.array(z75.string()).max(18),inspectable:z75.boolean(),durationMs:z75.int().min(3e4).max(6e4),basis:RoughCutReviewBasisSchema,basisFingerprint:sha12,technical:RoughCutTechnicalSchema,requirements:z75.array(RoughCutRequirementSchema).min(1).max(300),latestReview:RoughCutReviewRecordSchema.nullable(),reviewVersion:z75.int().nonnegative(),finalReadyVersion:z75.int().nonnegative()});var RoughCutFindingSchema=RoughCutReviewScopeSchema.extend({compositionLocality:z75.array(CompositionFindingLocalitySchema).min(1).max(208).optional(),id:z75.uuid(),projectId:ProjectIdSchema,reviewId:z75.uuid(),reviewVersion:z75.int().positive(),basisFingerprint:sha12,artifactId:z75.uuid(),timelineVersionId:z75.uuid(),requirement:RoughCutRequirementSchema,observation:RoughCutObservationSchema,blocking:z75.boolean(),severity:z75.enum(["BLOCKING","WARNING"]),remediation:z75.enum(["REVISE_PRODUCTION","REVISE_TRANSITION","CORRECT_CANONICAL_CONTRADICTION"]),affectedScope:z75.strictObject({kind:z75.enum(["PRODUCTION","SHOT","TRANSITION","TIMELINE_REGION"]),interval:ReviewIntervalSchema,shotIds:z75.array(z75.uuid()).min(1).max(200)}),initialLifecycle:z75.literal("OPEN"),createdAt:z75.iso.datetime({offset:true})});var RoughCutFindingViewSchema=RoughCutFindingSchema.extend({lifecycle:z75.enum(["OPEN","REMEDIATION_PLANNED","RESOLVED","WAIVED","SUPERSEDED"]),proofReviewId:z75.uuid().nullable(),proofDecisionId:z75.uuid().nullable()});var RoughCutReviewQuerySchema=RoughCutReviewScopeSchema.extend({limit:QueryLimitSchema,next:ContinuationSchema.optional()});var RoughCutReviewPageSchema=z75.strictObject({items:z75.array(RoughCutReviewRecordSchema),page:QueryPageInfoSchema});var RoughCutFindingQuerySchema=TimelineScopeSchema.extend({renderId:z75.uuid().optional(),limit:QueryLimitSchema,next:ContinuationSchema.optional()});var RoughCutFindingGetSchema=TimelineScopeSchema.extend({findingId:z75.uuid()});var RoughCutFindingPageSchema=z75.strictObject({items:z75.array(RoughCutFindingViewSchema),page:QueryPageInfoSchema});var RoughCutReviewReceiptSchema=z75.strictObject({semanticStatus:z75.literal("SUCCESS"),review:RoughCutReviewRecordSchema,findingIds:z75.array(z75.uuid()).max(300),productionRevision:z75.int().positive()});var ReviewEvidenceKeySchema=z76.string().regex(/^[a-z][a-z0-9_-]{0,39}$/);var ReviewEvidenceMediaSchema=z76.strictObject({artifactId:z76.uuid(),representationId:z76.uuid(),checksumSha256:z76.string().regex(/^[0-9a-f]{64}$/)});var common={id:ReviewEvidenceKeySchema,label:z76.string().trim().min(1).max(200),producer:z76.enum(["EXTERNAL_AGENT_HOST","HUMAN","VLM"]),media:ReviewEvidenceMediaSchema};var ReviewIntelligenceEvidenceSchema=z76.discriminatedUnion("kind",[z76.strictObject({...common,kind:z76.literal("METADATA")}),z76.strictObject({...common,kind:z76.literal("IMAGE_PIXELS")}),z76.strictObject({...common,kind:z76.literal("REGISTERED_TEMPORAL_FRAMES"),reference:TemporalEvidenceReferenceSchema}),z76.strictObject({...common,kind:z76.literal("VIDEO_PLAYBACK"),coverage:z76.array(ReviewIntervalSchema).min(1).max(200)}),z76.strictObject({...common,kind:z76.literal("AUDIO_LISTENING"),coverage:z76.array(ReviewIntervalSchema).min(1).max(200)}),z76.strictObject({...common,kind:z76.literal("VIDEO_WITH_AUDIO_PLAYBACK"),coverage:z76.array(ReviewIntervalSchema).min(1).max(200)}),z76.strictObject({...common,kind:z76.literal("VIDEO_FRAMES"),timestampsMs:z76.array(z76.number().nonnegative().max(6e4)).min(1).max(64)})]);import{z as z77}from"zod";var whisperCppRecognitionProfile=Object.freeze({id:"WHISPER_CPP_TINY_EN_Q5_1_PCM16K_V1",sourceRevision:"2eeeba56e9edd762b4b38467bab96c2517163158",modelSha256:"c77c5766f1cef09b6b7d47f21b546cbddd4157886b3b5d6d4f709e91e66c7c2b",language:"en",sampleRateHz:16e3,maxDurationMs:6e4});var LocalWhisperIdentitySchema=z77.strictObject({profileId:z77.literal(whisperCppRecognitionProfile.id),binarySha256:LocalDigestSchema,modelSha256:z77.literal(whisperCppRecognitionProfile.modelSha256)});var LocalWhisperToolSelectionSchema=z77.strictObject({binaryPath:z77.string().min(1).max(4096),binarySha256:LocalDigestSchema,modelPath:z77.string().min(1).max(4096)});function canonicalLocalJson(value2){if(value2===null||typeof value2==="string"||typeof value2==="boolean")return JSON.stringify(value2);if(typeof value2==="number"&&Number.isFinite(value2))return JSON.stringify(value2);if(Array.isArray(value2))return"["+value2.map(canonicalLocalJson).join(",")+"]";if(typeof value2==="object")return"{"+Object.entries(value2).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 MAX_SHOT_REVIEW_REQUIREMENTS=2200;import{z as z78}from"zod";var ObservationScopeSchema=z78.strictObject({tenantId:z78.uuid(),productionId:z78.uuid()});var audioSourceRequest=z78.strictObject({kind:z78.literal("AUDIO"),media:ReviewEvidenceMediaSchema,versionId:z78.uuid(),purpose:z78.enum(["VOICEOVER","MUSIC"])});var ObservationSourceRequestSchema=z78.discriminatedUnion("kind",[audioSourceRequest,z78.strictObject({kind:z78.literal("VIDEO"),media:ReviewEvidenceMediaSchema})]);var ObservationStartSchema=ObservationScopeSchema.extend({expectedProductionRevision:z78.int().positive(),idempotencyKey:z78.string().min(1).max(200),source:ObservationSourceRequestSchema,mode:ObservationModeSchema,selection:ProviderSelectionSchema,expectedModelProfileVersion:z78.int().positive(),parameters:ObservationParametersSchema.default({})}).refine(q=>q.mode==="TRANSCRIPTION"||q.mode==="AUDIO"===(q.source.kind==="AUDIO"),{message:"Observation input/mode mismatch"});var ObservationGetSchema=ObservationScopeSchema.extend({observationId:z78.uuid()});var ObservationBindingSchema=z78.strictObject({tenantId:z78.uuid(),connectionId:z78.uuid(),connectionVersion:z78.int().positive(),credentialRef:z78.string(),credentialVersion:z78.int().positive(),profile:ObservationProfileSchema,matrix:ModelCapabilityMatrixSchema.optional(),executionClass:z78.enum(["LIVE","TEST_ONLY"])}).refine(v=>!v.profile.modes.some(m=>m==="TRANSCRIPTION")||!!v.matrix,{message:"ASR requires its frozen capability matrix"});var ObservationSourceSchema=ReviewEvidenceMediaSchema.extend({tenantId:z78.uuid(),projectId:z78.uuid(),productionId:z78.uuid(),byteSize:z78.int().positive().max(12582912),durationMs:z78.number().positive().max(6e4),frameRate:z78.number().positive().max(60).optional(),executionClass:z78.enum(["LIVE","TEST_ONLY"])});var json=z78.record(z78.string(),z78.unknown());var ObservationResultSchema=z78.strictObject({schemaVersion:z78.int().positive(),advisory:z78.literal(true),producer:z78.enum(["VLM","ASR"]).optional(),source:ObservationSourceSchema,input:json,provider:json,observedAt:z78.iso.datetime(),report:json,transcript:TranscriptSchema.optional(),evidence:ReviewIntelligenceEvidenceSchema.optional(),limitations:z78.array(z78.string().max(200)).max(20)}).refine(v=>v.producer==="ASR"===!!v.transcript&&!(v.producer==="ASR"&&v.evidence),{message:"ASR transcript cannot provide listening or visual Review evidence"}).refine(v=>new TextEncoder().encode(JSON.stringify(v)).length<=131072,{message:"Observation report too large"}).refine(v=>v.transcript?.timing!=="PROVIDER_REPORTED"||v.provider.protocol==="OPENAI_WHISPER_TRANSCRIPTION_V1"&&[...v.transcript.words,...v.transcript.segments].every(item=>item.endMs<=v.source.durationMs),{message:"Transcript timing requires the exact supported protocol and media duration"});var ObservationAdmissionSchema=z78.strictObject({semanticStatus:z78.literal("ACCEPTED"),observationId:z78.uuid(),runtimeJobId:z78.uuid(),productionRevision:z78.int().positive(),executionClass:z78.enum(["LIVE","TEST_ONLY"])});var ObservationViewSchema=ObservationScopeSchema.extend({observationId:z78.uuid(),runtimeJobId:z78.uuid(),request:ObservationStartSchema,profile:ObservationProfileSchema,matrix:ModelCapabilityMatrixSchema.optional(),parameters:ObservationParametersSchema,executionClass:z78.enum(["LIVE","TEST_ONLY"]),runtimeStatus:z78.enum(["PENDING","READY","RUNNING","WAITING","SUCCEEDED","FAILED","CANCELLED","SUPERSEDED"]),providerStatus:z78.enum(["NOT_SUBMITTED","SUBMITTING","UNKNOWN","SUCCEEDED","REJECTED"]),cancellationRequested:z78.boolean(),failure:z78.strictObject({classification:z78.string().min(1).max(100),summary:z78.string().min(1).max(1e3)}).nullable(),result:ObservationResultSchema.nullable(),createdAt:z78.iso.datetime()});var ObservationOptionsSchema=ObservationScopeSchema.extend({options:z78.array(z78.strictObject({selection:ProviderSelectionSchema,profile:ObservationProfileSchema,matrix:ModelCapabilityMatrixSchema.optional(),connectionLabel:z78.string(),connectionVersion:z78.int().positive()})).max(100),possiblyTruncated:z78.boolean()});var LocalObservationStartSchema=ObservationScopeSchema.extend({expectedProductionRevision:ObservationStartSchema.shape.expectedProductionRevision,idempotencyKey:ObservationStartSchema.shape.idempotencyKey,source:audioSourceRequest,mode:z78.literal("TRANSCRIPTION"),deviceExecution:z78.strictObject({deviceId:z78.uuid().optional()})});var localObservationExecution=z78.strictObject({target:z78.literal("TENANT_DEVICE"),deviceId:z78.uuid(),identity:LocalWhisperIdentitySchema});var LocalObservationBindingSchema=localObservationExecution.extend({tenantId:z78.uuid(),executionClass:z78.literal("LIVE"),source:ObservationSourceSchema});var LocalObservationAdmissionSchema=ObservationAdmissionSchema.extend({executionClass:z78.literal("LIVE"),deviceExecution:localObservationExecution});var LocalObservationResultSchema=z78.strictObject({schemaVersion:z78.literal(1),advisory:z78.literal(true),producer:z78.literal("ASR"),source:ObservationSourceSchema,deviceExecution:localObservationExecution,observedAt:z78.iso.datetime(),transcript:TranscriptSchema.options[0],inputPcmSha256:z78.string().regex(/^[0-9a-f]{64}$/),inputPcmByteSize:z78.int().min(44).max(1920044)}).refine(v=>new TextEncoder().encode(JSON.stringify(v)).length<=131072,{message:"Observation report too large"});var LocalObservationViewSchema=ObservationViewSchema.omit({profile:true,matrix:true,parameters:true,providerStatus:true}).extend({request:LocalObservationStartSchema,executionClass:z78.literal("LIVE"),deviceExecution:localObservationExecution,result:LocalObservationResultSchema.nullable()});var qwenAsrModelId="qwen3-asr-flash-2026-02-10";var QwenAsrDeviceQuoteInputSchema=ObservationScopeSchema.extend({expectedProductionRevision:ObservationStartSchema.shape.expectedProductionRevision,idempotencyKey:ObservationStartSchema.shape.idempotencyKey,source:audioSourceRequest,mode:z78.literal("TRANSCRIPTION"),selection:ProviderSelectionSchema.extend({modelProfileId:z78.literal(qwenAsrModelId)}),expectedModelProfileVersion:z78.literal(1),parameters:ObservationParametersSchema.default({}),deviceId:z78.uuid()});var QwenAsrCostQuoteSchema=z78.strictObject({protocol:z78.literal("NVS_QWEN_ASR_COST_QUOTE_V1"),currency:z78.literal("USD"),ruleId:z78.string().min(1).max(100),sourceUrl:z78.url().max(2048),selection:QwenAsrDeviceQuoteInputSchema.shape.selection,connectionVersion:z78.int().positive(),modelProfileVersion:z78.literal(1),deviceId:z78.uuid(),intentFingerprint:z78.string().regex(/^[0-9a-f]{64}$/),inputDurationMs:z78.number().positive().max(6e4),reservedSeconds:z78.int().min(1).max(60),upperBoundMicrosPerSecond:z78.int().positive().max(1e6),upperBoundMicros:z78.int().positive().max(6e7),validUntil:z78.iso.datetime()});var QwenAsrDeviceStartSchema=QwenAsrDeviceQuoteInputSchema.extend({approvedQuote:QwenAsrCostQuoteSchema});var qwenAsrDeviceExecution=z78.strictObject({target:z78.literal("TENANT_EXTERNAL_PROVIDER"),deviceId:z78.uuid()});var QwenAsrDeviceAdmissionSchema=ObservationAdmissionSchema.extend({executionClass:z78.literal("LIVE"),deviceExecution:qwenAsrDeviceExecution});var qwenAsrTokenCount=z78.int().min(0).max(1e7).optional();var QwenAsrDeviceResultSchema=ObservationResultSchema.safeExtend({producer:z78.literal("ASR"),transcript:TranscriptSchema.options[0],input:z78.strictObject({kind:z78.literal("ORIGINAL_PCM_WAV_TRANSCRIPTION"),checksumSha256:ObservationSourceSchema.shape.checksumSha256,byteSize:ObservationSourceSchema.shape.byteSize,timeScaleFactor:z78.literal(1)}),provider:z78.strictObject({protocol:z78.literal("QWEN_ASR_V1"),requestedModel:z78.literal(qwenAsrModelId),model:z78.literal(qwenAsrModelId),requestId:z78.string().regex(/^[A-Za-z0-9_.:-]{1,500}$/),usage:z78.strictObject({seconds:z78.int().min(0).max(60).optional(),prompt_tokens:qwenAsrTokenCount,completion_tokens:qwenAsrTokenCount,total_tokens:qwenAsrTokenCount})}),report:z78.strictObject({task:z78.literal("SPEECH_RECOGNITION")})});var QwenAsrDeviceViewSchema=ObservationViewSchema.extend({request:QwenAsrDeviceQuoteInputSchema,executionClass:z78.literal("LIVE"),deviceExecution:qwenAsrDeviceExecution,result:QwenAsrDeviceResultSchema.nullable()});var ProductionGuidanceSchema=z78.strictObject({version:z78.enum(["NVS_PRODUCTION_GUIDANCE_V1","NVS_PRODUCTION_GUIDANCE_V2"]),instructions:z78.string().min(1).max(16e3)});var ProductionGuidanceContextSchema=ObservationScopeSchema.extend({projectId:z78.uuid(),revision:z78.int().positive(),guidance:ProductionGuidanceSchema});import{z as z86}from"zod";import{z as z80}from"zod";import{z as z79}from"zod";var Fingerprint3=z79.string().regex(/^[0-9a-f]{64}$/);var VideoReviewScopeSchema=z79.strictObject({tenantId:TenantIdSchema,productionId:ProductionIdSchema,generationId:z79.uuid()});var VideoReviewRequirementSchema=z79.strictObject({intentPath:z79.string().min(1).max(220).optional(),continuity:ContinuityExpectationSchema.optional(),interval:z79.strictObject({startMs:z79.int().nonnegative().max(6e4),endMs:z79.int().positive().max(6e4)}).refine(v=>v.endMs>v.startMs,"Requirement interval must advance").optional(),key:z79.string().min(1).max(220),family:z79.enum(["PRODUCT_IDENTITY","CHARACTER_IDENTITY","WARDROBE","LOCATION","STYLE","SHOT_INTENT","BOUNDARY_CONTINUITY","SOUND"]),expected:z79.string().min(1).max(2500),enforcement:z79.enum(["LOCKED","REQUIRED","PREFERRED"]),evidenceWindow:z79.enum(["WHOLE_VIDEO","START","END","TEMPORAL"])});var VideoObservationSchema=z79.strictObject({listeningEvidenceIds:ListeningEvidenceIdsSchema.optional(),continuitySamples:ContinuitySamplesSchema.optional(),temporalEvidenceIds:TemporalEvidenceIdsSchema.optional(),key:z79.string().min(1).max(220),status:z79.enum(["SATISFIED","VIOLATED","NOT_OBSERVABLE","NOT_APPLICABLE"]),confidence:z79.enum(["CLEAR","UNCERTAIN"]),observed:z79.string().trim().min(1).max(1800),interval:z79.strictObject({startMs:z79.int().nonnegative(),endMs:z79.int().positive()}).refine(v=>v.endMs>v.startMs,"Observation interval must advance").optional()});var RecordVideoReviewSchema=VideoReviewScopeSchema.extend({listeningEvidence:ListeningEvidenceSetSchema.optional(),candidateId:z79.uuid(),representationId:ArtifactRepresentationIdSchema,checksumSha256:Fingerprint3,expectedReviewVersion:z79.int().nonnegative(),idempotencyKey:z79.string().trim().min(1).max(200),observations:z79.array(VideoObservationSchema).min(1).max(MAX_SHOT_REVIEW_REQUIREMENTS),summary:z79.string().trim().min(1).max(2500)});var VideoReviewRecordSchema=z79.strictObject({listeningEvidence:ListeningEvidenceSetSchema.optional(),id:z79.uuid(),tenantId:TenantIdSchema,projectId:ProjectIdSchema,productionId:ProductionIdSchema,generationId:z79.uuid(),candidateId:z79.uuid(),artifactId:ArtifactIdSchema,representationId:ArtifactRepresentationIdSchema,checksumSha256:Fingerprint3,shotId:ShotIdSchema,version:z79.int().positive(),preparationId:z79.uuid(),contractId:z79.uuid(),contractFingerprint:Fingerprint3,executionClass:z79.enum(["LIVE","TEST_ONLY"]),kind:z79.literal("SHOT_REVIEW_1"),lifecycle:z79.literal("COMPLETED"),evaluatorVersion:z79.literal("shot-review-v1"),source:z79.literal("EXPLICIT_MEDIA_INSPECTION"),technical:VideoTechnicalMetadataSchema,requirements:z79.array(VideoReviewRequirementSchema).min(1).max(MAX_SHOT_REVIEW_REQUIREMENTS),observations:z79.array(VideoObservationSchema).min(1).max(MAX_SHOT_REVIEW_REQUIREMENTS),result:z79.enum(["PASS","WARNING","FAIL"]),blockingKeys:z79.array(z79.string()).max(MAX_SHOT_REVIEW_REQUIREMENTS),warningKeys:z79.array(z79.string()).max(MAX_SHOT_REVIEW_REQUIREMENTS),summary:z79.string().min(1).max(2500),createdByPrincipalId:PrincipalIdSchema,createdAt:z79.iso.datetime({offset:true})});var DecideVideoShotSchema=VideoReviewScopeSchema.extend({candidateId:z79.uuid(),reviewId:z79.uuid(),expectedAcceptanceVersion:z79.int().nonnegative(),action:z79.enum(["ACCEPT","REJECT"]),acknowledgeWarnings:z79.boolean().default(false),reason:z79.string().trim().min(1).max(2500),idempotencyKey:z79.string().trim().min(1).max(200)});var ShotAcceptanceScopeSchema=z79.strictObject({tenantId:TenantIdSchema,productionId:ProductionIdSchema,shotId:ShotIdSchema});var RevokeShotAcceptanceSchema=ShotAcceptanceScopeSchema.extend({acceptanceId:z79.uuid(),expectedAcceptanceVersion:z79.int().positive(),reason:z79.string().trim().min(1).max(2500),idempotencyKey:z79.string().trim().min(1).max(200)});var GeneratedShotAcceptanceDecisionSchema=z79.strictObject({id:z79.uuid(),tenantId:TenantIdSchema,projectId:ProjectIdSchema,productionId:ProductionIdSchema,shotId:ShotIdSchema,acceptanceVersion:z79.int().positive(),generationId:z79.uuid(),candidateId:z79.uuid(),artifactId:ArtifactIdSchema,representationId:ArtifactRepresentationIdSchema,reviewId:z79.uuid(),action:z79.enum(["ACCEPT","REJECT","REVOKE"]),reference:AcceptedShotReferenceSchema.nullable(),previousAcceptanceId:z79.uuid().nullable(),warningKeys:z79.array(z79.string()).max(MAX_SHOT_REVIEW_REQUIREMENTS),acknowledgeWarnings:z79.boolean(),reason:z79.string().min(1).max(2500),createdByPrincipalId:PrincipalIdSchema,createdAt:z79.iso.datetime({offset:true})});var ProgrammaticShotAcceptanceDecisionSchema=z79.strictObject({sourceKind:z79.literal("PROGRAMMATIC"),id:z79.uuid(),tenantId:TenantIdSchema,projectId:ProjectIdSchema,productionId:ProductionIdSchema,shotId:ShotIdSchema,acceptanceVersion:z79.int().positive(),renderId:z79.uuid(),compositionId:z79.uuid(),compositionVersionId:z79.uuid(),artifactId:ArtifactIdSchema,representationId:ArtifactRepresentationIdSchema,reviewId:z79.uuid(),action:z79.enum(["ACCEPT","REJECT","REVOKE"]),reference:ProgrammaticAcceptedVisualSourceReferenceSchema.nullable(),previousAcceptanceId:z79.uuid().nullable(),warningKeys:z79.array(z79.string()).max(MAX_SHOT_REVIEW_REQUIREMENTS),acknowledgeWarnings:z79.boolean(),reason:z79.string().min(1).max(2500),createdByPrincipalId:PrincipalIdSchema,createdAt:z79.iso.datetime({offset:true})});var ShotAcceptanceDecisionSchema=z79.union([GeneratedShotAcceptanceDecisionSchema,ProgrammaticShotAcceptanceDecisionSchema,z79.strictObject({sourceKind:z79.literal("IMPORTED"),id:z79.uuid(),tenantId:TenantIdSchema,projectId:ProjectIdSchema,productionId:ProductionIdSchema,shotId:ShotIdSchema,acceptanceVersion:z79.int().positive(),normalizationId:z79.uuid(),sourceId:z79.uuid(),sourceVersionId:z79.uuid(),artifactId:ArtifactIdSchema,representationId:ArtifactRepresentationIdSchema,reviewId:z79.uuid(),action:z79.enum(["ACCEPT","REJECT","REVOKE"]),reference:ImportedAcceptedVisualSourceReferenceSchema.nullable(),previousAcceptanceId:z79.uuid().nullable(),warningKeys:z79.array(z79.string()).max(MAX_SHOT_REVIEW_REQUIREMENTS),acknowledgeWarnings:z79.boolean(),reason:z79.string().min(1).max(2500),createdByPrincipalId:PrincipalIdSchema,createdAt:z79.iso.datetime({offset:true})})]);var VideoReviewTargetSchema=VideoReviewScopeSchema.extend({temporalEvidence:z79.array(TemporalEvidenceReferenceSchema).max(8).optional(),projectId:ProjectIdSchema,shotId:ShotIdSchema,preparationId:z79.uuid(),contractId:z79.uuid(),contractFingerprint:Fingerprint3,executionClass:z79.enum(["LIVE","TEST_ONLY"]),freshness:z79.enum(["CURRENT_BASIS","STALE_BASIS"]),runtimeSucceeded:z79.boolean(),productionRunnable:z79.boolean(),candidate:VideoCandidateSchema,requirements:z79.array(VideoReviewRequirementSchema).min(1).max(MAX_SHOT_REVIEW_REQUIREMENTS),latestReview:VideoReviewRecordSchema.nullable(),reviewVersion:z79.int().nonnegative(),acceptanceVersion:z79.int().nonnegative(),activeAcceptanceId:z79.uuid().nullable()});var ShotAcceptanceViewSchema=ShotAcceptanceScopeSchema.extend({acceptanceVersion:z79.int().nonnegative(),status:z79.enum(["NONE","CURRENT","STALE"]),acceptance:ShotAcceptanceDecisionSchema.nullable(),reference:AcceptedVisualSourceReferenceSchema.nullable()});var VideoReviewQuerySchema=VideoReviewScopeSchema.extend({limit:QueryLimitSchema,next:ContinuationSchema.optional()});var VideoReviewPageSchema=z79.strictObject({items:z79.array(VideoReviewRecordSchema),page:QueryPageInfoSchema});var ShotDecisionQuerySchema=ShotAcceptanceScopeSchema.extend({limit:QueryLimitSchema,next:ContinuationSchema.optional()});var ShotDecisionPageSchema=z79.strictObject({items:z79.array(ShotAcceptanceDecisionSchema),page:QueryPageInfoSchema});var VideoReviewReceiptSchema=z79.strictObject({semanticStatus:z79.literal("SUCCESS"),review:VideoReviewRecordSchema,productionRevision:z79.int().positive()});var ShotDecisionReceiptSchema=z79.strictObject({semanticStatus:z79.literal("SUCCESS"),decision:ShotAcceptanceDecisionSchema,productionRevision:z79.int().positive()});var Fingerprint4=z80.string().regex(/^[0-9a-f]{64}$/);var ProgrammaticVideoReviewScopeSchema=z80.strictObject({tenantId:TenantIdSchema,productionId:ProductionIdSchema,renderId:z80.uuid()});var ProgrammaticReviewMediaSchema=VideoTechnicalMetadataSchema.extend({artifactId:ArtifactIdSchema,representationId:ArtifactRepresentationIdSchema,availability:z80.enum(["AVAILABLE","INVALID"])});var ProgrammaticVideoReviewRecordSchema=z80.strictObject({sourceKind:z80.literal("PROGRAMMATIC"),id:z80.uuid(),tenantId:TenantIdSchema,projectId:ProjectIdSchema,productionId:ProductionIdSchema,shotId:ShotIdSchema,renderId:z80.uuid(),compositionId:z80.uuid(),compositionVersionId:z80.uuid(),compositionVersion:z80.int().positive(),compositionFingerprint:Fingerprint4,renderManifestFingerprint:Fingerprint4,artifactId:ArtifactIdSchema,representationId:ArtifactRepresentationIdSchema,checksumSha256:Fingerprint4,version:z80.int().positive(),planVersionId:z80.uuid(),planVersion:z80.int().positive(),shotPlanningRevision:z80.int().positive(),executionClass:z80.enum(["LIVE","TEST_ONLY"]),kind:z80.literal("SHOT_REVIEW_1"),lifecycle:z80.literal("COMPLETED"),evaluatorVersion:z80.literal("shot-review-v1"),source:z80.literal("EXPLICIT_MEDIA_INSPECTION"),technical:VideoTechnicalMetadataSchema,requirements:z80.array(VideoReviewRequirementSchema).min(1).max(MAX_SHOT_REVIEW_REQUIREMENTS),observations:z80.array(VideoObservationSchema).min(1).max(MAX_SHOT_REVIEW_REQUIREMENTS),result:z80.enum(["PASS","WARNING","FAIL"]),blockingKeys:z80.array(z80.string()).max(MAX_SHOT_REVIEW_REQUIREMENTS),warningKeys:z80.array(z80.string()).max(MAX_SHOT_REVIEW_REQUIREMENTS),summary:z80.string().min(1).max(2500),createdByPrincipalId:PrincipalIdSchema,createdAt:z80.iso.datetime({offset:true})});var ProgrammaticVideoReviewTargetSchema=ProgrammaticVideoReviewScopeSchema.extend({sourceKind:z80.literal("PROGRAMMATIC"),temporalEvidence:z80.array(TemporalEvidenceReferenceSchema).max(8).optional(),projectId:ProjectIdSchema,shotId:ShotIdSchema,compositionId:z80.uuid(),compositionVersionId:z80.uuid(),compositionVersion:z80.int().positive(),compositionFingerprint:Fingerprint4,renderManifestFingerprint:Fingerprint4,executionClass:z80.enum(["LIVE","TEST_ONLY"]),freshness:z80.enum(["CURRENT_BASIS","STALE_BASIS"]),runtimeSucceeded:z80.boolean(),productionRunnable:z80.boolean(),media:ProgrammaticReviewMediaSchema,requirements:z80.array(VideoReviewRequirementSchema).min(1).max(MAX_SHOT_REVIEW_REQUIREMENTS),latestReview:ProgrammaticVideoReviewRecordSchema.nullable(),reviewVersion:z80.int().nonnegative(),acceptanceVersion:z80.int().nonnegative(),activeAcceptanceId:z80.uuid().nullable()});var RecordProgrammaticVideoReviewSchema=ProgrammaticVideoReviewScopeSchema.extend({representationId:ArtifactRepresentationIdSchema,checksumSha256:Fingerprint4,expectedReviewVersion:z80.int().nonnegative(),idempotencyKey:z80.string().trim().min(1).max(200),observations:z80.array(VideoObservationSchema).min(1).max(MAX_SHOT_REVIEW_REQUIREMENTS),summary:z80.string().trim().min(1).max(2500)});var DecideProgrammaticShotSchema=ProgrammaticVideoReviewScopeSchema.extend({reviewId:z80.uuid(),expectedAcceptanceVersion:z80.int().nonnegative(),action:z80.enum(["ACCEPT","REJECT"]),acknowledgeWarnings:z80.boolean().default(false),reason:z80.string().trim().min(1).max(2500),idempotencyKey:z80.string().trim().min(1).max(200)});var ProgrammaticVideoReviewQuerySchema=ProgrammaticVideoReviewScopeSchema.extend({limit:QueryLimitSchema,next:ContinuationSchema.optional()});var ProgrammaticVideoReviewPageSchema=z80.strictObject({items:z80.array(ProgrammaticVideoReviewRecordSchema),page:QueryPageInfoSchema});var ProgrammaticVideoReviewReceiptSchema=z80.strictObject({semanticStatus:z80.literal("SUCCESS"),review:ProgrammaticVideoReviewRecordSchema,productionRevision:z80.int().positive()});import{z as z84}from"zod";import{z as z82}from"zod";import{z as z81}from"zod";var Intent=z81.string().trim().min(1).max(300);var CameraIntentSchema=z81.strictObject({scale:z81.enum(["EXTREME_CLOSE_UP","CLOSE_UP","MEDIUM","WIDE","EXTREME_WIDE"]),framing:z81.enum(["CENTERED","OFF_CENTER","SYMMETRICAL","OVER_SHOULDER"]),angle:z81.enum(["EYE_LEVEL","HIGH","LOW","TOP_DOWN"]),movement:z81.enum(["STATIC","PAN","TILT","DOLLY","TRACK","ORBIT","CRANE","ZOOM"]),stability:z81.enum(["LOCKED","STABILIZED","HANDHELD"]),direction:z81.enum(["LEFT","RIGHT","UP","DOWN","FORWARD","BACKWARD","CLOCKWISE","COUNTERCLOCKWISE"]).optional(),lensIntent:z81.string().trim().min(1).max(120).optional()});var ShotTemporalBeatSchema=z81.strictObject({startSeconds:z81.number().min(0).max(30),endSeconds:z81.number().positive().max(30),action:Intent});var ShotDirectionSchema=z81.strictObject({camera:CameraIntentSchema,temporalBeats:z81.array(ShotTemporalBeatSchema).min(1).max(8),environmentIntent:Intent.optional(),lightingIntent:Intent.optional(),styleIntent:Intent.optional(),audioIntent:Intent.optional()});function checkShotDirectionTiming(direction,duration){let cursor=0;for(const beat of direction.temporalBeats){if(Math.abs(beat.startSeconds-cursor)>1e-6||beat.endSeconds<=beat.startSeconds)return false;cursor=beat.endSeconds}return Math.abs(cursor-duration)<=1e-6}var PlanningClientKeySchema=z82.string().regex(/^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/);var BoundaryRequirementSchema=z82.strictObject({attribute:z82.string().regex(/^[A-Za-z][A-Za-z0-9_.-]{0,59}$/),value:z82.string().trim().min(1).max(300)});var ShotIntentSchema=z82.strictObject({narrativePurpose:z82.string().trim().min(1).max(600),subjectAction:z82.string().trim().min(1).max(600),targetDurationSeconds:z82.number().min(.5).max(30),subjectRequirements:z82.array(z82.string().trim().min(1).max(300)).max(16).default([]),cameraComposition:z82.string().trim().min(1).max(500).optional(),factualClaims:z82.array(StoryFactClaimSchema).max(16).default([]),requiresGeneratedKeyframe:z82.boolean().default(false),sourceMediaAllowed:z82.boolean().default(false),direction:ShotDirectionSchema.optional()}).superRefine((value2,context)=>{if(value2.direction&&!checkShotDirectionTiming(value2.direction,value2.targetDurationSeconds))context.addIssue({code:"custom",path:["direction","temporalBeats"],message:"Temporal beats must be contiguous from zero and cover exactly the Shot duration"})});var ShotPlanInputSchema=z82.strictObject({clientKey:PlanningClientKeySchema,shotId:ShotIdSchema.optional(),intent:ShotIntentSchema,entryBoundary:z82.array(BoundaryRequirementSchema).max(24).default([]),exitBoundary:z82.array(BoundaryRequirementSchema).max(24).default([])});var ScenePlanInputSchema=z82.strictObject({clientKey:PlanningClientKeySchema,sceneId:SceneIdSchema.optional(),purpose:z82.string().trim().min(1).max(800),locationContext:z82.string().trim().min(1).max(300).optional(),timeContext:z82.string().trim().min(1).max(300).optional(),entryBoundary:z82.array(BoundaryRequirementSchema).max(24).default([]),exitBoundary:z82.array(BoundaryRequirementSchema).max(24).default([]),shots:z82.array(ShotPlanInputSchema).min(1).max(24)});var ContinuityRequirementSchema=z82.strictObject({mode:z82.enum(["PERSIST","TRANSITION","REESTABLISH","REVIEW"]),attribute:z82.string().regex(/^[A-Za-z][A-Za-z0-9_.-]{0,59}$/),description:z82.string().trim().min(1).max(500)});var ContinuityEdgeInputSchema=z82.strictObject({fromShotKey:PlanningClientKeySchema,toShotKey:PlanningClientKeySchema,requirements:z82.array(ContinuityRequirementSchema).min(1).max(24)});var AcceptSceneShotPlanRequestSchema=z82.strictObject({tenantId:TenantIdSchema,expectedProductionRevision:z82.int().positive(),expectedStoryVersion:z82.int().positive(),revisionReason:z82.string().trim().min(1).max(1e3).optional(),idempotencyKey:z82.string().trim().min(1).max(200),scenes:z82.array(ScenePlanInputSchema).min(1).max(12),continuityEdges:z82.array(ContinuityEdgeInputSchema).max(64).default([])});var ShotPlanEntrySchema=z82.strictObject({shotId:ShotIdSchema,clientKey:PlanningClientKeySchema,ordinal:z82.int().positive(),planningRevision:z82.int().positive(),intent:ShotIntentSchema,entryBoundary:z82.array(BoundaryRequirementSchema).max(24),exitBoundary:z82.array(BoundaryRequirementSchema).max(24)});var ScenePlanEntrySchema=z82.strictObject({sceneId:SceneIdSchema,clientKey:PlanningClientKeySchema,ordinal:z82.int().positive(),purpose:z82.string().trim().min(1).max(800),locationContext:z82.string().trim().min(1).max(300).optional(),timeContext:z82.string().trim().min(1).max(300).optional(),entryBoundary:z82.array(BoundaryRequirementSchema).max(24),exitBoundary:z82.array(BoundaryRequirementSchema).max(24),shots:z82.array(ShotPlanEntrySchema).min(1).max(24)});var ContinuityEdgeSchema=z82.strictObject({id:ContinuityEdgeIdSchema,fromShotId:ShotIdSchema,toShotId:ShotIdSchema,requirements:z82.array(ContinuityRequirementSchema).min(1).max(24)});var SceneShotPlanVersionSchema=z82.strictObject({id:SceneShotPlanVersionIdSchema,planId:SceneShotPlanIdSchema,tenantId:TenantIdSchema,projectId:ProjectIdSchema,productionId:ProductionIdSchema,version:z82.int().positive(),storyVersionId:StoryVersionIdSchema,storyVersion:z82.int().positive(),briefVersionId:BriefVersionIdSchema,briefVersion:z82.int().positive(),scenes:z82.array(ScenePlanEntrySchema).min(1).max(12),continuityEdges:z82.array(ContinuityEdgeSchema).max(64),createdByPrincipalId:PrincipalIdSchema,createdAt:z82.iso.datetime({offset:true})});var AcceptSceneShotPlanResultSchema=z82.discriminatedUnion("semanticStatus",[z82.strictObject({semanticStatus:z82.literal("SUCCESS"),planVersion:SceneShotPlanVersionSchema,productionRevision:z82.int().positive(),activeSceneShotPlanVersion:z82.int().positive()}),z82.strictObject({semanticStatus:z82.literal("NEEDS_INPUT"),missingPrerequisites:z82.array(z82.literal("ACTIVE_STORY")).min(1)})]);import{z as z83}from"zod";var WriterScopeSchema=z83.strictObject({tenantId:TenantIdSchema,projectId:ProjectIdSchema,productionId:ProductionIdSchema});var WriterBasisSchema=WriterScopeSchema.extend({productionRevision:z83.int().positive(),briefVersionId:BriefVersionIdSchema,briefVersion:z83.int().positive()});var IntentSchema=z83.string().trim().min(1).max(600);var WriterAlternativeSchema=z83.strictObject({alternativeId:z83.string().regex(/^[a-z][a-z0-9_-]{0,39}$/),title:z83.string().trim().min(1).max(120),story:StoryContentSchema,rationale:z83.strictObject({coreMessage:IntentSchema,hook:IntentSchema,audienceFit:IntentSchema,pacingIntent:IntentSchema,endingIntent:IntentSchema,tradeoffs:z83.array(IntentSchema).max(6)}),beatDurationsSeconds:z83.array(z83.int().positive().max(60)).min(1).max(24)});var WriterProposalSchema=z83.strictObject({origin:z83.strictObject({kind:z83.literal("EXTERNAL_AGENT_HOST"),label:z83.string().trim().min(1).max(100)}),unknowns:z83.array(z83.string().trim().min(1).max(300)).max(8),alternatives:z83.array(WriterAlternativeSchema).min(1).max(3)});var ValidateWriterProposalSchema=z83.strictObject({basis:WriterBasisSchema,revisionReason:AcceptStoryRequestSchema.shape.revisionReason,proposal:WriterProposalSchema});var MissingBriefSchema=z83.strictObject({semanticStatus:z83.literal("NEEDS_INPUT"),missingPrerequisites:z83.array(z83.literal("ACTIVE_BRIEF")).min(1).max(1)});var WriterBriefResultSchema=z83.discriminatedUnion("semanticStatus",[z83.strictObject({semanticStatus:z83.literal("SUCCESS"),basis:WriterBasisSchema,briefVersion:BriefVersionSchema}),MissingBriefSchema]);var WriterAcceptanceDraftSchema=z83.strictObject({alternativeId:WriterAlternativeSchema.shape.alternativeId,projectId:ProjectIdSchema,productionId:ProductionIdSchema,request:AcceptStoryRequestSchema.omit({idempotencyKey:true})});var WriterValidationResultSchema=z83.discriminatedUnion("semanticStatus",[z83.strictObject({semanticStatus:z83.literal("SUCCESS"),advisory:z83.literal(true),basis:WriterBasisSchema,proposal:WriterProposalSchema,acceptanceDrafts:z83.array(WriterAcceptanceDraftSchema).min(1).max(3),limitations:z83.array(z83.enum(["PROSE_IS_CREATIVE_INTENT_NOT_FACT_VERIFIED","PACING_IS_ADVISORY_NOT_TIMELINE_TRUTH","ACCEPTANCE_RECHECKS_CURRENT_BASIS"])).length(3)}),MissingBriefSchema]);var DirectorScopeSchema=WriterScopeSchema;var DirectorBasisSchema=WriterBasisSchema.extend({storyVersionId:StoryVersionIdSchema,storyVersion:z84.int().positive(),sceneShotPlanVersionId:SceneShotPlanVersionIdSchema.nullable(),sceneShotPlanVersion:z84.int().positive().nullable()}).refine(value2=>value2.sceneShotPlanVersionId===null===(value2.sceneShotPlanVersion===null),"Current plan ID and version must both be present or null");var Intent2=z84.string().trim().min(1).max(600);var Plan=AcceptSceneShotPlanRequestSchema.pick({scenes:true,continuityEdges:true});var DirectorAlternativeSchema=z84.strictObject({alternativeId:z84.string().regex(/^[a-z][a-z0-9_-]{0,39}$/),title:z84.string().trim().min(1).max(120),plan:Plan,rationale:z84.strictObject({storyInterpretation:Intent2,visualApproach:Intent2,pacingIntent:Intent2,tradeoffs:z84.array(Intent2).max(6)}),shotStoryBeats:z84.array(z84.strictObject({shotKey:PlanningClientKeySchema,beatOrdinals:z84.array(z84.int().positive().max(24)).min(1).max(4)})).min(1).max(48)}).refine(value2=>value2.plan.scenes.reduce((n,scene)=>n+scene.shots.length,0)<=48,"Director alternatives contain at most 48 Shots");var DirectorProposalSchema=z84.strictObject({origin:z84.strictObject({kind:z84.literal("EXTERNAL_AGENT_HOST"),label:z84.string().trim().min(1).max(100)}),unknowns:z84.array(z84.string().trim().min(1).max(300)).max(8),alternatives:z84.array(DirectorAlternativeSchema).min(1).max(3)});var ValidateDirectorProposalSchema=z84.strictObject({basis:DirectorBasisSchema,revisionReason:AcceptSceneShotPlanRequestSchema.shape.revisionReason,proposal:DirectorProposalSchema}).refine(value2=>new TextEncoder().encode(JSON.stringify(value2)).byteLength<=1024*1024,"Director validation input exceeds the 1 MiB JSON budget");var Missing=z84.strictObject({semanticStatus:z84.literal("NEEDS_INPUT"),missingPrerequisites:z84.array(z84.enum(["ACTIVE_BRIEF","ACTIVE_STORY"])).min(1).max(2)});var DirectorContextResultSchema=z84.discriminatedUnion("semanticStatus",[z84.strictObject({semanticStatus:z84.literal("SUCCESS"),basis:DirectorBasisSchema,briefVersion:BriefVersionSchema,storyVersion:StoryVersionSchema,sceneShotPlanVersion:SceneShotPlanVersionSchema.nullable(),stalePrerequisites:z84.array(z84.enum(["CURRENT_STORY","CURRENT_SCENE_SHOT_PLAN"])).min(1).max(2).optional()}),Missing]);var DirectorAcceptanceDraftSchema=z84.strictObject({alternativeId:DirectorAlternativeSchema.shape.alternativeId,projectId:DirectorScopeSchema.shape.projectId,productionId:DirectorScopeSchema.shape.productionId,request:AcceptSceneShotPlanRequestSchema.omit({idempotencyKey:true})});var DirectorValidationResultSchema=z84.discriminatedUnion("semanticStatus",[z84.strictObject({semanticStatus:z84.literal("SUCCESS"),advisory:z84.literal(true),basis:DirectorBasisSchema,proposal:DirectorProposalSchema,acceptanceDrafts:z84.array(DirectorAcceptanceDraftSchema).min(1).max(3),limitations:z84.array(z84.enum(["PROSE_IS_CREATIVE_INTENT_NOT_FACT_VERIFIED","DIRECTION_IS_INTENT_NOT_OBSERVED_MEDIA","ACCEPTANCE_RECHECKS_CURRENT_BASIS","PREPARATION_AND_GENERATION_REMAIN_SEPARATE"])).length(4)}),Missing]);import{z as z85}from"zod";var Fingerprint5=z85.string().regex(/^[0-9a-f]{64}$/);var KeyframeReviewScopeSchema=z85.strictObject({tenantId:TenantIdSchema,productionId:ProductionIdSchema,generationId:z85.uuid()});var VisualRequirementSchema=z85.strictObject({intentPath:z85.string().min(1).max(220).optional(),key:z85.string().min(1).max(200),expected:z85.string().min(1).max(2500),enforcement:z85.enum(["LOCKED","REQUIRED","PREFERRED"])});var Region=z85.strictObject({x:z85.number().min(0).max(1),y:z85.number().min(0).max(1),width:z85.number().positive().max(1),height:z85.number().positive().max(1)}).refine(r=>r.x+r.width<=1&&r.y+r.height<=1,"Evidence region must fit within the image");var KeyframeObservationSchema=z85.strictObject({key:z85.string().min(1).max(200),status:z85.enum(["SATISFIED","VIOLATED","NOT_OBSERVABLE","NOT_APPLICABLE"]),confidence:z85.enum(["CLEAR","UNCERTAIN"]),observed:z85.string().trim().min(1).max(1500),region:Region.optional()});var RecordKeyframeReviewSchema=KeyframeReviewScopeSchema.extend({candidateId:z85.uuid(),representationId:z85.uuid(),checksumSha256:Fingerprint5,expectedReviewVersion:z85.int().nonnegative(),idempotencyKey:z85.string().trim().min(1).max(200),observations:z85.array(KeyframeObservationSchema).min(1).max(MAX_SHOT_REVIEW_REQUIREMENTS),summary:z85.string().trim().min(1).max(2e3)});var KeyframeReviewRecordSchema=z85.strictObject({id:z85.uuid(),tenantId:TenantIdSchema,projectId:ProjectIdSchema,productionId:ProductionIdSchema,generationId:z85.uuid(),candidateId:z85.uuid(),artifactId:z85.uuid(),representationId:z85.uuid(),checksumSha256:Fingerprint5,shotId:ShotIdSchema,framePurpose:KeyframePurposeSchema,version:z85.int().positive(),preparationId:z85.uuid(),contractId:z85.uuid(),contractFingerprint:Fingerprint5,executionClass:z85.enum(["LIVE","TEST_ONLY"]),kind:z85.literal("KEYFRAME_REFERENCE"),lifecycle:z85.literal("COMPLETED"),evaluatorVersion:z85.literal("keyframe-reference-v1"),source:z85.literal("EXPLICIT_VISUAL_INSPECTION"),requirements:z85.array(VisualRequirementSchema).min(1).max(MAX_SHOT_REVIEW_REQUIREMENTS),observations:z85.array(KeyframeObservationSchema).min(1).max(MAX_SHOT_REVIEW_REQUIREMENTS),result:z85.enum(["PASS","WARNING","FAIL"]),blockingKeys:z85.array(z85.string()).max(MAX_SHOT_REVIEW_REQUIREMENTS),warningKeys:z85.array(z85.string()).max(MAX_SHOT_REVIEW_REQUIREMENTS),summary:z85.string().min(1).max(2e3),createdByPrincipalId:PrincipalIdSchema,createdAt:z85.iso.datetime({offset:true})});var DecideKeyframeSchema=KeyframeReviewScopeSchema.extend({candidateId:z85.uuid(),reviewId:z85.uuid(),expectedSelectionVersion:z85.int().nonnegative(),action:z85.enum(["ACCEPT","REJECT"]),acknowledgeWarnings:z85.boolean().default(false),reason:z85.string().trim().min(1).max(2e3),idempotencyKey:z85.string().trim().min(1).max(200)});var KeyframeReferenceScopeSchema=z85.strictObject({tenantId:TenantIdSchema,productionId:ProductionIdSchema,shotId:ShotIdSchema,framePurpose:KeyframePurposeSchema});var RevokeKeyframeSchema=KeyframeReferenceScopeSchema.extend({acceptanceId:z85.uuid(),expectedSelectionVersion:z85.int().positive(),reason:z85.string().trim().min(1).max(2e3),idempotencyKey:z85.string().trim().min(1).max(200)});var KeyframeDecisionRecordSchema=z85.strictObject({id:z85.uuid(),tenantId:TenantIdSchema,projectId:ProjectIdSchema,productionId:ProductionIdSchema,shotId:ShotIdSchema,framePurpose:KeyframePurposeSchema,selectionVersion:z85.int().positive(),generationId:z85.uuid(),candidateId:z85.uuid(),reviewId:z85.uuid(),action:z85.enum(["ACCEPT","REJECT","REVOKE"]),reference:AcceptedKeyframeReferenceSchema.nullable(),previousAcceptanceId:z85.uuid().nullable(),warningKeys:z85.array(z85.string()).max(MAX_SHOT_REVIEW_REQUIREMENTS),acknowledgeWarnings:z85.boolean(),reason:z85.string().min(1).max(2e3),createdByPrincipalId:PrincipalIdSchema,createdAt:z85.iso.datetime({offset:true})});var KeyframeReviewTargetSchema=KeyframeReviewScopeSchema.extend({projectId:ProjectIdSchema,shotId:ShotIdSchema,framePurpose:KeyframePurposeSchema,preparationId:z85.uuid(),contractId:z85.uuid(),contractFingerprint:Fingerprint5,executionClass:z85.enum(["LIVE","TEST_ONLY"]),freshness:z85.enum(["CURRENT_BASIS","STALE_BASIS"]),runtimeSucceeded:z85.boolean(),productionRunnable:z85.boolean(),candidate:KeyframeCandidateSchema,requirements:z85.array(VisualRequirementSchema).min(1).max(MAX_SHOT_REVIEW_REQUIREMENTS),latestReview:KeyframeReviewRecordSchema.nullable(),reviewVersion:z85.int().nonnegative(),selectionVersion:z85.int().nonnegative(),activeAcceptanceId:z85.uuid().nullable()});var KeyframeReferenceViewSchema=KeyframeReferenceScopeSchema.extend({selectionVersion:z85.int().nonnegative(),status:z85.enum(["NONE","CURRENT","STALE"]),acceptance:KeyframeDecisionRecordSchema.nullable(),reference:AcceptedKeyframeReferenceSchema.nullable()});var KeyframeReviewQuerySchema=KeyframeReviewScopeSchema.extend({limit:QueryLimitSchema,next:ContinuationSchema.optional()});var KeyframeReviewPageSchema=z85.strictObject({items:z85.array(KeyframeReviewRecordSchema),page:QueryPageInfoSchema});var KeyframeReviewReceiptSchema=z85.strictObject({semanticStatus:z85.literal("SUCCESS"),review:KeyframeReviewRecordSchema,productionRevision:z85.int().positive()});var KeyframeDecisionReceiptSchema=z85.strictObject({semanticStatus:z85.literal("SUCCESS"),decision:KeyframeDecisionRecordSchema,productionRevision:z85.int().positive()});var KeyframeDecisionQuerySchema=KeyframeReferenceScopeSchema.extend({limit:QueryLimitSchema,next:ContinuationSchema.optional()});var KeyframeDecisionPageSchema=z85.strictObject({items:z85.array(KeyframeDecisionRecordSchema),page:QueryPageInfoSchema});var KeyframeReviewSummarySchema=z85.strictObject({reviewedCandidates:z85.int().nonnegative(),unreviewedCandidates:z85.int().nonnegative(),decisionCount:z85.int().nonnegative()});var sha13=z86.string().regex(/^[0-9a-f]{64}$/);var evidenceIds=z86.array(ReviewEvidenceKeySchema).max(16);var ReviewIntelligenceTargetSchema=z86.discriminatedUnion("kind",[z86.strictObject({kind:z86.literal("IMAGE"),generationId:z86.uuid()}),z86.strictObject({kind:z86.literal("VIDEO"),generationId:z86.uuid()}),z86.strictObject({kind:z86.literal("ROUGH_CUT"),renderId:z86.uuid()}),z86.strictObject({kind:z86.literal("PROGRAMMATIC"),renderId:z86.uuid()})]);var ReviewIntelligenceContextInputSchema=z86.strictObject({scope:DirectorScopeSchema,target:ReviewIntelligenceTargetSchema});var ReviewIntelligenceBasisSchema=ReviewIntelligenceContextInputSchema.extend({contextFingerprint:sha13});var ReviewIntelligenceOwnerTargetSchema=z86.discriminatedUnion("kind",[z86.strictObject({kind:z86.literal("IMAGE"),target:KeyframeReviewTargetSchema}),z86.strictObject({kind:z86.literal("VIDEO"),target:VideoReviewTargetSchema}),z86.strictObject({kind:z86.literal("ROUGH_CUT"),target:RoughCutReviewTargetSchema}),z86.strictObject({kind:z86.literal("PROGRAMMATIC"),target:ProgrammaticVideoReviewTargetSchema})]);var review=z86.discriminatedUnion("kind",[z86.strictObject({kind:z86.literal("IMAGE"),observations:z86.array(KeyframeObservationSchema.extend({evidenceIds})).min(1).max(MAX_SHOT_REVIEW_REQUIREMENTS)}),z86.strictObject({kind:z86.literal("VIDEO"),observations:z86.array(VideoObservationSchema.extend({evidenceIds})).min(1).max(MAX_SHOT_REVIEW_REQUIREMENTS)}),z86.strictObject({kind:z86.literal("PROGRAMMATIC"),observations:z86.array(VideoObservationSchema.extend({evidenceIds})).min(1).max(MAX_SHOT_REVIEW_REQUIREMENTS)}),z86.strictObject({kind:z86.literal("ROUGH_CUT"),observations:z86.array(RoughCutObservationSchema.extend({evidenceIds})).min(1).max(300),inspection:RoughCutInspectionSchema})]);var ValidateReviewIntelligenceSchema=z86.strictObject({basis:ReviewIntelligenceBasisSchema,proposal:z86.strictObject({origin:z86.strictObject({kind:z86.literal("EXTERNAL_AGENT_HOST"),label:z86.string().trim().min(1).max(100)}),summary:z86.string().trim().min(1).max(2e3),evidence:z86.array(ReviewIntelligenceEvidenceSchema).max(256),review})}).refine(input=>new TextEncoder().encode(JSON.stringify(input)).byteLength<=1024*1024,"Review Intelligence input exceeds the 1 MiB JSON budget");var ReviewIntelligenceContextResultSchema=z86.strictObject({semanticStatus:z86.literal("SUCCESS"),advisory:z86.literal(true),basis:ReviewIntelligenceBasisSchema,productionGuidance:ProductionGuidanceSchema.optional(),ownerContext:DirectorContextResultSchema,reviewTarget:ReviewIntelligenceOwnerTargetSchema,limitations:z86.array(z86.enum(["NO_IMPLICIT_MEDIA_OR_MODEL_CALL","READS_ARE_NOT_ATOMIC_OR_RESERVED"])).length(2)});var ReviewIntelligenceRecordDraftSchema=z86.discriminatedUnion("kind",[z86.strictObject({kind:z86.literal("PROGRAMMATIC"),input:RecordProgrammaticVideoReviewSchema.omit({idempotencyKey:true})}),z86.strictObject({kind:z86.literal("IMAGE"),input:RecordKeyframeReviewSchema.omit({idempotencyKey:true})}),z86.strictObject({kind:z86.literal("VIDEO"),input:RecordVideoReviewSchema.omit({idempotencyKey:true})}),z86.strictObject({kind:z86.literal("ROUGH_CUT"),input:RecordRoughCutReviewSchema.omit({idempotencyKey:true})})]);var ReviewIntelligenceIssueSchema=z86.strictObject({requirement:z86.union([VisualRequirementSchema,VideoReviewRequirementSchema,RoughCutRequirementSchema]),observation:z86.union([KeyframeObservationSchema,VideoObservationSchema,RoughCutObservationSchema]),evidenceIds,blocking:z86.boolean(),severity:z86.enum(["BLOCKING","WARNING"]),affectedScope:z86.strictObject({kind:z86.enum(["PRODUCTION","SHOT","TRANSITION","TIMELINE_REGION"]),interval:ReviewIntervalSchema,shotIds:z86.array(z86.uuid()).min(1).max(200)}).optional()});var ReviewIntelligenceValidationResultSchema=z86.strictObject({semanticStatus:z86.literal("SUCCESS"),advisory:z86.literal(true),basis:ReviewIntelligenceBasisSchema,proposal:ValidateReviewIntelligenceSchema.shape.proposal,canonicalRulePreview:z86.strictObject({source:z86.literal("EXISTING_CANONICAL_DOMAIN_RULES"),authoritative:z86.literal(false),evaluatorVersion:z86.enum(["keyframe-reference-v1","shot-review-v1","production-review-v1"]),result:z86.enum(["PASS","WARNING","FAIL"]),blockingKeys:z86.array(z86.string()).max(MAX_SHOT_REVIEW_REQUIREMENTS),warningKeys:z86.array(z86.string()).max(MAX_SHOT_REVIEW_REQUIREMENTS)}),issueProposals:z86.array(ReviewIntelligenceIssueSchema).max(MAX_SHOT_REVIEW_REQUIREMENTS),recordDraft:ReviewIntelligenceRecordDraftSchema,limitations:z86.array(z86.enum(["EVIDENCE_DECLARATIONS_ARE_NOT_ATTESTED_PIXEL_READS","RULE_PREVIEW_IS_NOT_A_CANONICAL_REVIEW","RECORD_RECHECKS_CURRENTNESS_CAS_AND_EXECUTION_CLASS","ACCEPTANCE_REMAINS_A_SEPARATE_OWNER_DECISION"])).length(4)});import{z as z89}from"zod";import{z as z88}from"zod";import{z as z87}from"zod";var maxMediaObjectBytes=128*1024*1024;var mediaObjectTransferPath="/v1/object-transfers";var mediaBrowserReadPath=mediaObjectTransferPath+"/browser-read";var MediaBrowserContentTypeSchema=z87.enum(["image/png","image/jpeg","image/webp","video/mp4","audio/wav","audio/mpeg","application/json","text/plain","application/x-subrip"]);var MediaObjectVersionSchema=LocalProjectScopeSchema.extend({versionId:LocalIdSchema,role:z87.enum(["SOURCE","VIDEO","POSTER","AUDIO","FRAME","SHEET","MANIFEST"]),byteSize:z87.int().min(1).max(maxMediaObjectBytes),checksumSha256:LocalDigestSchema});var MediaTransferGrantSchema=z87.strictObject({protocol:z87.literal("NVS_MEDIA_TRANSFER_V1"),storageId:z87.string().regex(/^[A-Za-z0-9_-]{1,100}$/),method:z87.enum(["GET","PUT","HEAD"]),object:MediaObjectVersionSchema,issuedAt:LocalTimeSchema,expiresAt:LocalTimeSchema});var MediaObjectTicketSchema=z87.strictObject({endpoint:z87.url().max(2048),credential:z87.string().regex(/^[A-Za-z0-9_-]{1,2048}\.[A-Za-z0-9_-]{43}$/).meta({writeOnly:true}),method:z87.enum(["GET","PUT"]),object:MediaObjectVersionSchema});var MediaBrowserReadGrantSchema=z87.strictObject({protocol:z87.literal("NVS_MEDIA_BROWSER_READ_V1"),storageId:z87.string().regex(/^[A-Za-z0-9_-]{1,100}$/),object:MediaObjectVersionSchema,contentType:MediaBrowserContentTypeSchema,representationId:LocalIdSchema,attachment:z87.boolean(),issuedAt:LocalTimeSchema,expiresAt:LocalTimeSchema});var MediaBrowserReadTicketSchema=z87.strictObject({url:z87.url().max(4096).refine(value2=>{const url=new URL(value2);return(url.protocol==="https:"||url.protocol==="http:"&&url.hostname==="127.0.0.1")&&!url.username&&!url.password&&!url.hash&&url.pathname===mediaBrowserReadPath&&url.searchParams.size===1&&/^[A-Za-z0-9_-]{1,3072}\.[A-Za-z0-9_-]{43}$/.test(url.searchParams.get("ticket")??"")}),expiresAt:LocalTimeSchema,object:MediaObjectVersionSchema,contentType:MediaBrowserContentTypeSchema});var QwenDeviceCredentialScopeSchema=z88.strictObject({tenantId:LocalIdSchema,connectionId:LocalIdSchema,connectionVersion:z88.int().positive(),workspace:z88.string().regex(/^[a-z0-9][a-z0-9-]{0,63}$/)});var QwenDeviceCredentialIdentitySchema=QwenDeviceCredentialScopeSchema.extend({proofSha256:LocalDigestSchema});var QwenDeviceCredentialSelectionSchema=QwenDeviceCredentialScopeSchema.extend({privateKeyFile:z88.string().min(1).max(4096)});var qwenSource=ResolvedReferenceSchema.pick({artifactId:true,representationId:true,checksumSha256:true,contentType:true,role:true}).extend({byteSize:MediaObjectVersionSchema.shape.byteSize.max(8*1024*1024)});var keyframeBytes=z88.strictObject({checksumSha256:LocalDigestSchema,byteSize:MediaObjectVersionSchema.shape.byteSize.max(8*1024*1024),width:z88.int().positive().max(4096),height:z88.int().positive().max(4096)});var externalKeyframe=z88.literal("KEYFRAME_GENERATE");var QwenKeyframeRecipeSchema=z88.strictObject({processor:externalKeyframe,generationId:LocalIdSchema,credential:QwenDeviceCredentialIdentitySchema,quoteFingerprint:LocalDigestSchema,prompt:z88.string().trim().min(1).refine(value2=>new TextEncoder().encode(value2).length<=1300),aspectRatio:z88.enum(["16:9","9:16"]),sources:z88.array(qwenSource).min(1).max(3)});var QwenKeyframeEvidenceSchema=z88.strictObject({processor:externalKeyframe,providerExecutionId:z88.string().regex(/^[A-Za-z0-9_.:-]{1,500}$/),providerResultId:LocalDigestSchema,image:keyframeBytes});var QwenVideoRecipeSchema=QwenKeyframeRecipeSchema.extend({processor:z88.literal("VIDEO_GENERATE"),prompt:z88.string().trim().min(1).max(2e4),mode:z88.enum(["REFERENCE_TO_VIDEO","FIRST_FRAME_TO_VIDEO","FIRST_LAST_FRAME_TO_VIDEO"]),durationSeconds:z88.int().min(2).max(30),sources:z88.array(qwenSource).min(1).max(10)});var QwenVideoTaskIdSchema=z88.string().regex(/^[A-Za-z0-9_-]{1,160}$/);var QwenVideoEvidenceSchema=z88.strictObject({processor:z88.literal("VIDEO_GENERATE"),providerExecutionId:QwenVideoTaskIdSchema,providerResultId:QwenVideoTaskIdSchema,video:VideoTechnicalMetadataSchema.extend({videoCodec:z88.literal("h264"),frameRate:z88.literal(30),hasAudio:z88.literal(false),frameCount:z88.int().positive().max(902)}),poster:keyframeBytes});var ExternalGenerationReservationMarkerSchema=z88.strictObject({protocol:z88.literal("NVS_TENANT_EXTERNAL_GENERATION_V1"),tenantId:LocalIdSchema,projectId:LocalIdSchema,productionId:LocalIdSchema,runtimeJobId:LocalIdSchema,shotId:LocalIdSchema,preparationId:LocalIdSchema,contractId:LocalIdSchema,workload:z88.enum(["KEYFRAME_GENERATE","VIDEO_GENERATE"]),policyRevision:z88.int().positive(),contractFingerprint:LocalDigestSchema,originRequestFingerprint:LocalDigestSchema,bindingFingerprint:LocalDigestSchema,inputsFingerprint:LocalDigestSchema,quoteFingerprint:LocalDigestSchema});function checkProcessorDeclaration(enabled,kinds,context){if(enabled!==!!kinds?.length||kinds&&new Set(kinds).size!==kinds.length)context.addIssue({code:"custom",path:["processorCapabilities"],message:"Explicit unique processor capabilities must match processing enablement"})}var StartLocalPreviewSchema=RoughCutStartSchema.omit({deviceExecution:true}).extend({placement:LocalPlacementPolicySchema,localProfile:z89.literal("STUDIO_MEDIA_V2").optional()});var LocalDeviceScopeSchema=z89.strictObject({tenantId:LocalIdSchema,deviceId:LocalIdSchema});var LocalDeviceSessionSchema=z89.strictObject({...LocalDeviceScopeSchema.shape,expiresAt:LocalTimeSchema,credential:z89.string().length(43).regex(/^[A-Za-z0-9_-]+$/).meta({writeOnly:true})});var LocalDeviceHeartbeatSchema=LocalDeviceScopeSchema.extend({runtimeVersion:LocalPackageVersionSchema,toolchain:LocalToolchainSchema,available:z89.boolean(),maxConcurrentJobs:z89.int().min(1).max(2).optional(),validationProfileDigest:LocalDigestSchema.optional(),processorProfileDigest:LocalDigestSchema.optional(),localLibraryProfileDigest:LocalDigestSchema.optional(),macSpeechIdentity:MacSpeechIdentitySchema.optional(),cpuSpeech:CpuSpeechCapabilitySchema.optional(),whisperIdentity:LocalWhisperIdentitySchema.optional(),qwenIdentities:z89.array(QwenDeviceCredentialIdentitySchema).min(1).max(16).optional(),processorCapabilities:z89.array(TenantProcessorKindSchema).min(1).max(TenantProcessorKindSchema.options.length).optional()}).superRefine((value2,context)=>checkProcessorDeclaration(!!value2.processorProfileDigest,value2.processorCapabilities,context));var ClaimLocalPreviewSchema=LocalProjectScopeSchema.extend({requestId:LocalIdSchema,deviceId:LocalIdSchema,tenantMediaValidation:z89.literal(true).optional()});var LocalOutputStageSchema=LocalLeaseBindingSchema.extend({uploadRequestId:LocalIdSchema,role:z89.enum(["VIDEO","POSTER"]),checksumSha256:LocalDigestSchema,byteSize:z89.int().positive().max(128*1024*1024)});var LocalOutputTicketSchema=z89.strictObject({receiptId:LocalIdSchema,role:z89.enum(["VIDEO","POSTER"]),checksumSha256:LocalDigestSchema,byteSize:z89.int().positive(),uploaded:z89.boolean()});var LocalSourceRequestSchema=LocalLeaseBindingSchema.extend({representationId:LocalIdSchema});var LocalProofChallengeRequestSchema=LocalDeviceScopeSchema.extend({deviceRevision:z89.int().positive()});var LocalPreviewPlacementViewSchema=z89.strictObject({target:z89.enum(["DEVICE","SERVER"]),reason:z89.enum(["LOCAL_AVAILABLE","CLOUD_ONLY","OFFLINE","UNQUALIFIED","BUSY","LEASE_RECOVERY"]),policy:LocalPlacementPolicySchema});var LocalDeviceTransportConfigurationSchema=z89.strictObject({endpoint:z89.string().url().max(2048),tenantId:LocalIdSchema,deviceId:LocalIdSchema,deviceRevision:z89.int().positive(),privateKeyFile:z89.string().min(1).max(4096),platform:LocalDevicePlatformSchema,tenantMediaValidation:z89.literal(true).optional(),tenantMediaProcessing:z89.literal(true).optional(),processorCapabilities:z89.array(TenantProcessorKindSchema).min(1).max(TenantProcessorKindSchema.options.length).optional(),compositionBrowser:z89.string().min(1).max(4096).optional(),macSpeechIdentity:MacSpeechIdentitySchema.optional(),cpuSpeech:CpuSpeechCapabilitySchema.optional(),cpuSpeechTools:CpuSpeechToolSelectionSchema.optional(),whisperIdentity:LocalWhisperIdentitySchema.optional(),whisperTools:LocalWhisperToolSelectionSchema.optional(),qwenDeviceCredentials:z89.array(QwenDeviceCredentialSelectionSchema).max(16).optional(),qwenIdentities:LocalDeviceHeartbeatSchema.shape.qwenIdentities}).superRefine((value2,context)=>checkProcessorDeclaration(value2.tenantMediaProcessing===true,value2.processorCapabilities,context));var LocalPreviewAdmissionSchema=RoughCutAdmissionSchema.extend({placement:LocalPreviewPlacementViewSchema});var StartLocalFinalRenderSchema=FinalRenderStartSchema.omit({deviceExecution:true}).extend({placement:LocalPlacementPolicySchema});var LocalFinalRenderAdmissionSchema=FinalRenderAdmissionSchema.extend({placement:LocalPreviewPlacementViewSchema});var LocalClaimReceiptSchema=z89.strictObject({found:z89.boolean(),assignment:LocalWorkAssignmentSchema.nullable()});var LocalWorkStateSchema=z89.strictObject({binding:LocalLeaseBindingSchema,status:z89.enum(["ACTIVE","FENCED","OUTCOME_UNKNOWN"]),assignment:LocalWorkAssignmentSchema.nullable()});import{z as z90}from"zod";var LocalManagementCommandSchema=z90.discriminatedUnion("kind",[z90.strictObject({kind:z90.literal("ENROLL"),input:EnrollLocalDeviceSchema}),z90.strictObject({kind:z90.literal("REVOKE_DEVICE"),input:RevokeLocalDeviceSchema}),z90.strictObject({kind:z90.literal("PREVIEW"),input:StartLocalPreviewSchema}),z90.strictObject({kind:z90.literal("FINAL_RENDER"),input:StartLocalFinalRenderSchema})]);var LocalManagementResultSchema=z90.union([LocalDeviceViewSchema,LocalPreviewAdmissionSchema,LocalFinalRenderAdmissionSchema,z90.strictObject({semanticStatus:z90.literal("SUCCESS")})]);var LocalManagementReceiptSchema=z90.strictObject({fingerprint:z90.string().regex(/^[a-f0-9]{64}$/),result:LocalManagementResultSchema.nullable()});var LocalDeviceManagementCommandSchema=LocalManagementCommandSchema;var ScopedLocalManagementReceiptSchema=z90.strictObject({tenantId:LocalIdSchema,command:LocalDeviceManagementCommandSchema}).refine(value2=>value2.tenantId.toLowerCase()===value2.command.input.tenantId.toLowerCase(),{message:"Management receipt must use the authorized tenant"});import{z as z92}from"zod";import{z as z91}from"zod";var WorkspaceScopeSchema=z91.strictObject({tenantId:TenantIdSchema});var WorkspaceViewSchema=HumanTenantSchema;var skillUrl=z91.url().max(4096).refine(value2=>{try{const u=new URL(value2);return value2===value2.trim()&&![...value2].some(c=>c.charCodeAt(0)<=32||c.charCodeAt(0)===127)&&!u.username&&!u.password&&!/[?#]/.test(value2)&&(u.protocol==="https:"||u.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(u.hostname))}catch{return false}});var PublicDownloadDescriptorSchema=z91.discriminatedUnion("status",[z91.strictObject({status:z91.literal("AVAILABLE"),url:skillUrl}),z91.strictObject({status:z91.enum(["UNCONFIGURED","UNAVAILABLE"]),url:z91.null()})]);var WorkspaceCallerSchema=z91.strictObject({humanLinks:HumanLinksSchema.optional(),tenantId:z91.uuid(),principalId:z91.uuid(),serverOrigin:z91.url().refine(value2=>{const u=new URL(value2);return u.origin===value2&&!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))}),skill:PublicDownloadDescriptorSchema,hostReleases:PublicDownloadDescriptorSchema});var WorkspacePageSchema=z91.strictObject({items:z91.array(WorkspaceViewSchema).max(100),possiblyTruncated:z91.boolean()});var DeviceEnrollmentScopeSchema=z92.strictObject({origin:WorkspaceCallerSchema.shape.serverOrigin,tenantId:z92.uuid(),principalId:z92.uuid()});var DeviceEnrollmentHandoffSchema=z92.strictObject({protocol:z92.literal("NVS_DEVICE_ENROLLMENT_HANDOFF_V1"),scope:DeviceEnrollmentScopeSchema,command:LocalManagementCommandSchema.options[0],fingerprint:z92.string().regex(/^[a-f0-9]{64}$/)}).refine(({scope:scope8,command:command4})=>scope8.tenantId.toLowerCase()===command4.input.tenantId.toLowerCase()&&scope8.principalId.toLowerCase()===command4.input.expectedPrincipalId?.toLowerCase(),{message:"Enrollment must match the target workspace and member"});import{z as z93}from"zod";var fingerprint=z93.string().regex(/^[a-f0-9]{64}$/);var scope={tenantId:z93.uuid(),requestId:z93.uuid()};var DeviceEnrollmentIssueSchema=EnrollLocalDeviceSchema.extend({expectedPrincipalId:z93.uuid()});var DeviceEnrollmentLookupSchema=z93.strictObject(scope);var DeviceEnrollmentTicketSchema=z93.strictObject({...scope,protocol:z93.literal("NVS_DEVICE_ENROLLMENT_V1"),enrollmentId:z93.uuid(),deviceId:z93.uuid(),fingerprint,issuedAt:z93.iso.datetime(),expiresAt:z93.iso.datetime()}).refine(({issuedAt,expiresAt})=>{const ttl=Date.parse(expiresAt)-Date.parse(issuedAt);return ttl>0&&ttl<=3e5});var DeviceEnrollmentRedeemSchema=z93.strictObject({tenantId:z93.uuid(),enrollmentId:z93.uuid(),signature:z93.string().regex(/^[A-Za-z0-9_-]{86}$/).meta({writeOnly:true})});var DeviceEnrollmentReceiptSchema=z93.strictObject({fingerprint,result:LocalDeviceViewSchema});var DeviceEnrollmentObservationSchema=z93.discriminatedUnion("state",[z93.strictObject({...scope,state:z93.literal("NOT_FOUND")}),z93.strictObject({...scope,state:z93.literal("ISSUED"),ticket:DeviceEnrollmentTicketSchema}),z93.strictObject({...scope,state:z93.literal("EXPIRED"),fingerprint}),z93.strictObject({...scope,state:z93.literal("ENROLLED"),receipt:DeviceEnrollmentReceiptSchema})]);function deviceEnrollmentSigningInput(ticket){return canonicalLocalJson(DeviceEnrollmentTicketSchema.parse(ticket))}import{z as z94}from"zod";var timestamp=z94.iso.datetime();var reason=z94.string().regex(/^[A-Z][A-Z0-9_]{0,79}$/);var absent=z94.strictObject({state:z94.enum(["NONE","UNKNOWN","NOT_APPLICABLE"])});var occurrence=z94.strictObject({state:z94.literal("OBSERVED"),at:timestamp,reasonCode:reason});var event=z94.union([occurrence,absent]);var count=z94.int().nonnegative();var depth=z94.union([z94.strictObject({state:z94.literal("OBSERVED"),ready:count,pending:count,running:count,waiting:count}),absent.extend({state:z94.enum(["UNKNOWN","NOT_APPLICABLE"])})]);var health=z94.strictObject({at:timestamp.nullable(),reasonCode:reason});var ComponentStatusSchema=z94.strictObject({protocol:z94.literal("NVS_COMPONENT_STATUS_V1"),observedAt:timestamp,liveness:health.extend({state:z94.enum(["ALIVE","STOPPED","STALE","UNKNOWN"])}),readiness:health.extend({state:z94.enum(["READY","BLOCKED","UNKNOWN"])}),lastSuccess:event,lastFailure:event,queueDepth:depth,nextRetry:event});var WorkspaceStatusSchema=ComponentStatusSchema.extend({component:z94.enum(["STUDIO_API","STUDIO_MCP"]),source:z94.literal("AUTHORIZED_WORKSPACE_READ"),tenantId:z94.uuid(),agentGrantId:z94.uuid().optional()});var DeviceStatusInputSchema=z94.strictObject({tenantId:z94.uuid(),deviceId:z94.uuid()});var DeviceStatusSchema=ComponentStatusSchema.extend({component:z94.literal("EXECUTION_NODE"),source:z94.literal("DEVICE_HEARTBEAT_AND_NATIVE_WORK"),tenantId:z94.uuid(),deviceId:z94.uuid(),deviceRevision:z94.int().positive(),runtimeVersion:z94.string().min(1).max(120).nullable(),runtimeVersionObservedAt:timestamp.nullable(),capabilityMismatch:CapabilityVersionMismatchSchema.optional()});import{z as z95}from"zod";var TenantMediaComputeModeSchema=z95.enum(["STAGE_ONE","TENANT_TRUSTED_VALIDATOR"]);var tenantRenderValidationProfile={protocol:"NVS_TENANT_MEDIA_REPORT_V1",inspection:"STUDIO_DECODE_READBACK_V1"};var TenantMediaWorkSchema=LocalWorkScopeSchema.extend({protocol:z95.literal("NVS_TENANT_MEDIA_WORK_V1"),family:z95.enum(["ROUGH_CUT_RENDER","FINAL_RENDER"]),validationMode:z95.literal("TENANT_TRUSTED_VALIDATOR"),operationId:OperationIdSchema,originRequestFingerprint:LocalDigestSchema,basisFingerprint:LocalDigestSchema,policyRevision:LocalRevisionSchema,target:TenantDeviceTargetSchema,renderProfileDigest:LocalDigestSchema,validationProfileDigest:LocalDigestSchema,audioRequired:z95.boolean()});var renderChecks=["CONTAINER_PROFILE","DURATION","VIDEO_DECODE","AUDIO_DECODE","POSTER_DECODE"];var renderCheck=z95.strictObject({key:z95.enum(renderChecks),result:z95.enum(["PASS","FAIL","UNVERIFIED","NOT_APPLICABLE"])});var TenantMediaValidationBodySchema=LocalLeaseBindingSchema.extend({schemaVersion:z95.literal(1),work:TenantMediaWorkSchema,originRequestFingerprint:LocalDigestSchema,requestId:LocalIdSchema,validationRequestId:LocalIdSchema,outputs:z95.array(MediaObjectVersionSchema).length(2),checks:z95.array(renderCheck).length(renderChecks.length),technical:RoughCutTechnicalSchema.nullable()}).superRefine((report,ctx)=>{const{work,outputs,checks}=report;if(work.tenantId!==report.tenantId||work.projectId!==report.projectId||work.productionId!==report.productionId||work.runtimeJobId!==report.runtimeJobId||work.originRequestFingerprint!==report.originRequestFingerprint)ctx.addIssue({code:"custom",path:["work"],message:"Work scope mismatch"});if(!outputs.some(output=>output.role==="VIDEO")||!outputs.some(output=>output.role==="POSTER")||new Set(outputs.map(output=>output.versionId)).size!==2||outputs.some(output=>output.tenantId!==report.tenantId||output.projectId!==report.projectId))ctx.addIssue({code:"custom",path:["outputs"],message:"Exact video and poster versions required"});if(new Set(checks.map(check=>check.key)).size!==renderChecks.length||checks.some(check=>check.result==="NOT_APPLICABLE"!==(check.key==="AUDIO_DECODE"&&!work.audioRequired)))ctx.addIssue({code:"custom",path:["checks"],message:"Exact applicable checks required"});const video=outputs.find(output=>output.role==="VIDEO");if(checks.every(check=>check.result==="PASS"||check.result==="NOT_APPLICABLE")&&!report.technical||report.technical&&(report.technical.checksumSha256!==video?.checksumSha256||report.technical.byteSize!==video?.byteSize||report.technical.hasAudio!==work.audioRequired))ctx.addIssue({code:"custom",path:["technical"],message:"Exact inspected video required"})});var TenantMediaValidationReportSchema=TenantMediaValidationBodySchema.safeExtend({reportFingerprint:LocalDigestSchema,signature:z95.string().regex(/^[A-Za-z0-9_-]{86}$/)});import{z as z96}from"zod";var PrepareTenantMediaValidationSchema=LocalLeaseBindingSchema.extend({requestId:LocalIdSchema,outputReceiptIds:z96.array(LocalIdSchema).length(2).refine(ids=>new Set(ids).size===2)});var TenantMediaValidationRequestSchema=LocalLeaseBindingSchema.extend({requestId:LocalIdSchema,validationRequestId:LocalIdSchema,work:TenantMediaWorkSchema,outputs:z96.array(MediaObjectVersionSchema).length(2)});var TenantMediaValidationReadbackSchema=z96.strictObject({request:TenantMediaValidationRequestSchema,tickets:z96.array(MediaObjectTicketSchema).length(2)});var TenantMediaDownloadSchema=LocalProjectScopeSchema.extend({representationId:LocalIdSchema});var TenantMediaOutputStageSchema=z96.strictObject({ticket:MediaObjectTicketSchema,uploaded:z96.boolean()});var TenantRenderMediaInputSchema=TimelineScopeSchema.extend({renderId:z96.uuid(),role:z96.enum(["VIDEO","POSTER"])});var TenantRenderMediaTicketSchema=TenantRenderMediaInputSchema.extend({representationId:z96.uuid(),ticket:MediaObjectTicketSchema.extend({object:MediaObjectVersionSchema.extend({tenantId:z96.uuid(),projectId:z96.uuid(),versionId:z96.uuid()})})});var TenantMediaCapabilitySchema=z96.strictObject({tenantId:LocalIdSchema,validationMode:z96.literal("TENANT_TRUSTED_VALIDATOR")});import{z as z119}from"zod";import{z as z108}from"zod";import{z as z97}from"zod";var IMPORTED_VISUAL_PROFILE_ID="IMPORTED_H264_SDR_CFR30_VISUAL_V1";var IMPORTED_VISUAL_MAX_BYTES=128*1024*1024;var Hash=z97.string().regex(/^[0-9a-f]{64}$/);var PositiveInteger=z97.int().positive().max(1e9);var ImportedVisualRationalSchema=z97.strictObject({numerator:PositiveInteger,denominator:PositiveInteger});var geometry=limit=>z97.strictObject({width:z97.int().min(2).max(limit).multipleOf(2),height:z97.int().min(2).max(limit).multipleOf(2)}).refine(({width,height})=>width*9===height*16||width*16===height*9,"Only exact 16:9 or 9:16 geometry is supported");var ImportedVisualToolchainSchema=z97.strictObject({ffmpegVersion:z97.string().startsWith("ffmpeg version ").max(512),ffprobeVersion:z97.string().startsWith("ffprobe version ").max(512)});var ImportedVisualSourceInputSchema=z97.strictObject({contentType:z97.literal("video/mp4"),checksumSha256:Hash,byteSize:z97.int().min(32).max(IMPORTED_VISUAL_MAX_BYTES),executionClass:z97.enum(["LIVE","TEST_ONLY"])});var ImportedVisualSourceRangeSchema=z97.strictObject({clock:z97.literal("SOURCE_ZERO_BASED_CFR30"),startFrame:z97.int().min(0).max(1799),endFrame:z97.int().min(1).max(1800)}).refine(v=>v.endFrame>v.startFrame&&v.endFrame-v.startFrame<=360,"The half-open interval must contain 1 to 360 frames");var ImportedVisualNormalizationRequestSchema=z97.strictObject({schemaVersion:z97.literal(1),profileId:z97.literal(IMPORTED_VISUAL_PROFILE_ID),source:ImportedVisualSourceInputSchema,sourceRange:ImportedVisualSourceRangeSchema,output:geometry(1920),audioPolicy:z97.enum(["REQUIRE_NO_AUDIO","SILENT_DERIVATIVE"]),expectedToolchain:ImportedVisualToolchainSchema});var ImportedVisualSourceMetadataSchema=z97.strictObject({...ImportedVisualSourceInputSchema.shape,geometry:geometry(3840),videoCodec:z97.literal("h264"),pixelFormat:z97.literal("yuv420p"),sampleAspectRatio:z97.literal("1:1"),rotationDegrees:z97.literal(0),startPts:z97.literal(0),timeBase:ImportedVisualRationalSchema,frameRate:ImportedVisualRationalSchema,frameCount:z97.int().min(1).max(3600),durationTicks:z97.int().positive().max(6e10),availableCfr30Frames:z97.int().min(0).max(1800),color:z97.strictObject({range:z97.enum(["tv","unknown"]),space:z97.enum(["bt709","unknown"]),transfer:z97.enum(["bt709","unknown"]),primaries:z97.enum(["bt709","unknown"])}),audio:z97.strictObject({codec:z97.literal("aac"),sampleRateHz:z97.union([z97.literal(44100),z97.literal(48e3)]),channels:z97.union([z97.literal(1),z97.literal(2)]),startPts:z97.int(),timeBase:ImportedVisualRationalSchema,durationTicks:z97.int().positive().max(6e10)}).nullable(),fullDecode:z97.literal(true),cfrTimestampsVerified:z97.literal(true)}).superRefine((v,ctx)=>{if(![v.durationTicks,v.timeBase.numerator,v.timeBase.denominator,v.frameRate.numerator,v.frameRate.denominator,v.frameCount,v.availableCfr30Frames].every(Number.isSafeInteger)||v.timeBase.denominator<=0||v.frameRate.numerator<=0||v.frameRate.denominator<=0)return;const ticks=BigInt(v.durationTicks)*BigInt(v.timeBase.numerator);const base3=BigInt(v.timeBase.denominator);const declaredFrames=ticks*BigInt(v.frameRate.numerator);const expectedFrames=BigInt(v.frameCount)*base3*BigInt(v.frameRate.denominator);if(ticks>60n*base3||declaredFrames!==expectedFrames||BigInt(v.availableCfr30Frames)!==ticks*30n/base3||v.audio&&BigInt(v.audio.durationTicks)*BigInt(v.audio.timeBase.numerator)>60n*BigInt(v.audio.timeBase.denominator))ctx.addIssue({code:"custom",message:"Media clock/count/duration metadata is inconsistent"})});var ImportedVisualInspectionSchema=z97.strictObject({profileId:z97.literal(IMPORTED_VISUAL_PROFILE_ID),source:ImportedVisualSourceMetadataSchema,toolchain:ImportedVisualToolchainSchema,evidenceScope:z97.literal("TECHNICAL_MEDIA_ONLY")});var ImportedVisualNormalizationReceiptSchema=z97.strictObject({schemaVersion:z97.literal(1),request:ImportedVisualNormalizationRequestSchema,original:ImportedVisualSourceMetadataSchema,output:ImportedVisualSourceMetadataSchema,toolchain:ImportedVisualToolchainSchema,frameMap:z97.array(z97.strictObject({outputFrame:z97.int().min(0).max(359),sourceFrame:z97.int().min(0).max(3599),sourcePts:z97.int().min(0).max(6e10)})).min(1).max(360),audioDisposition:z97.enum(["NO_AUDIO_PRESENT","REMOVED_FROM_DERIVATIVE_ONLY"]),evidenceScope:z97.literal("TECHNICAL_MEDIA_ONLY")}).superRefine((v,ctx)=>{const count2=v.request.sourceRange.endFrame-v.request.sourceRange.startFrame;const source6=v.original;if(![source6.frameRate.numerator,source6.frameRate.denominator,source6.timeBase.numerator,source6.timeBase.denominator,v.request.sourceRange.startFrame].every(Number.isSafeInteger)||source6.frameRate.numerator<=0||source6.frameRate.denominator<=0)return;const rounded=i=>(2n*BigInt(i)*30n*BigInt(source6.frameRate.denominator)+BigInt(source6.frameRate.numerator))/(2n*BigInt(source6.frameRate.numerator));const exactFrameMap=v.frameMap.every((m,i)=>{if(!Number.isSafeInteger(m.sourcePts)||!Number.isSafeInteger(m.sourceFrame))return false;const absoluteFrame=BigInt(v.request.sourceRange.startFrame+i);return BigInt(m.sourcePts)*BigInt(source6.timeBase.numerator)*BigInt(source6.frameRate.numerator)===BigInt(m.sourceFrame)*BigInt(source6.timeBase.denominator)*BigInt(source6.frameRate.denominator)&&rounded(m.sourceFrame)<=absoluteFrame&&(m.sourceFrame+1===source6.frameCount||rounded(m.sourceFrame+1)>absoluteFrame)});if(!exactFrameMap||v.request.sourceRange.endFrame>source6.availableCfr30Frames||v.output.geometry.width>source6.geometry.width||v.output.geometry.height>source6.geometry.height||v.output.geometry.width*source6.geometry.height!==v.output.geometry.height*source6.geometry.width)ctx.addIssue({code:"custom",message:"Receipt frame mapping or geometry violates the pinned profile"});if(v.output.frameCount!==count2||v.frameMap.length!==count2||v.frameMap.some((m,i)=>m.outputFrame!==i||m.sourceFrame>=v.original.frameCount)||v.output.frameRate.numerator!==30||v.output.frameRate.denominator!==1||v.output.audio||v.original.checksumSha256!==v.request.source.checksumSha256||v.original.byteSize!==v.request.source.byteSize||v.original.executionClass!==v.request.source.executionClass||v.output.executionClass!==v.original.executionClass||v.output.geometry.width!==v.request.output.width||v.output.geometry.height!==v.request.output.height||v.toolchain.ffmpegVersion!==v.request.expectedToolchain.ffmpegVersion||v.toolchain.ffprobeVersion!==v.request.expectedToolchain.ffprobeVersion||v.audioDisposition!==(v.original.audio?"REMOVED_FROM_DERIVATIVE_ONLY":"NO_AUDIO_PRESENT")||v.original.audio&&v.request.audioPolicy!=="SILENT_DERIVATIVE"){ctx.addIssue({code:"custom",message:"Normalization receipt does not match its exact request/source/output"})}});import{z as z98}from"zod";var Uuid=z98.uuid();var Hash2=z98.string().regex(/^[0-9a-f]{64}$/);var ImportedVisualOriginalRegisterSchema=z98.strictObject({deviceId:z98.uuid().toLowerCase().optional(),projectSourceArtifactId:z98.uuid().optional(),tenantId:Uuid,projectId:Uuid,productionId:Uuid,shotId:Uuid,expectedProductionRevision:z98.int().nonnegative(),source:z98.strictObject({contentType:z98.literal("video/mp4"),checksumSha256:Hash2,byteSize:z98.int().min(32).max(128*1024*1024),executionClass:z98.enum(["LIVE","TEST_ONLY"])}),declaredProvenance:z98.strictObject({originalName:z98.string().trim().min(1).max(255).optional(),authorship:z98.string().trim().min(1).max(500).optional(),license:z98.string().trim().min(1).max(500).optional()}),idempotencyKey:z98.string().trim().min(1).max(200)});var ImportedVisualFromProjectSourceSchema=ImportedVisualOriginalRegisterSchema.omit({source:true,projectSourceArtifactId:true}).extend({projectSourceArtifactId:Uuid});var ImportedVisualOriginalReviseSchema=ImportedVisualOriginalRegisterSchema.extend({sourceId:Uuid,expectedVersion:z98.int().positive()});var ImportedVisualNormalizeStartSchema=z98.strictObject({deviceExecution:DeviceRenderTargetSchema.optional(),tenantId:Uuid,projectId:Uuid,productionId:Uuid,shotId:Uuid,sourceId:Uuid,sourceVersionId:Uuid,expectedProductionRevision:z98.int().nonnegative(),request:ImportedVisualNormalizationRequestSchema,idempotencyKey:z98.string().trim().min(1).max(200)});var ImportedVisualGetSchema=z98.strictObject({tenantId:Uuid,productionId:Uuid,normalizationId:Uuid});var ImportedVisualReviewSchema=z98.strictObject({tenantId:Uuid,productionId:Uuid,normalizationId:Uuid,representationId:Uuid,checksumSha256:Hash2,expectedReviewVersion:z98.int().nonnegative(),observations:z98.array(VideoObservationSchema).min(1).max(MAX_SHOT_REVIEW_REQUIREMENTS),summary:z98.string().trim().min(1).max(2500),idempotencyKey:z98.string().trim().min(1).max(200)});var ImportedVisualDecisionSchema=z98.strictObject({tenantId:Uuid,productionId:Uuid,normalizationId:Uuid,reviewId:Uuid,expectedAcceptanceVersion:z98.int().nonnegative(),action:z98.enum(["ACCEPT","REJECT"]),acknowledgeWarnings:z98.boolean().default(false),reason:z98.string().trim().min(1).max(2500),idempotencyKey:z98.string().trim().min(1).max(200)});var ImportedVisualOriginalViewSchema=z98.strictObject({sourceId:Uuid,versionId:Uuid,version:z98.int().positive(),tenantId:Uuid,projectId:Uuid,productionId:Uuid,shotId:Uuid,artifactId:Uuid,representationId:Uuid,metadata:ImportedVisualSourceMetadataSchema,declaredProvenance:ImportedVisualOriginalRegisterSchema.shape.declaredProvenance.optional(),executionClass:z98.enum(["LIVE","TEST_ONLY"]),current:z98.boolean(),createdAt:z98.iso.datetime({offset:true})});var ImportedVisualNormalizationViewSchema=z98.strictObject({normalizationId:Uuid,runtimeJobId:Uuid,sourceId:Uuid,sourceVersionId:Uuid,lifecycle:z98.string(),cancellationRequested:z98.boolean(),receipt:ImportedVisualNormalizationReceiptSchema.nullable(),output:z98.strictObject({artifactId:Uuid,representationId:Uuid,posterArtifactId:Uuid,posterRepresentationId:Uuid}).nullable()});import{z as z99}from"zod";var id7=z99.uuid().toLowerCase();var SourceSyncRuntimeStartSchema=SourceSyncAudioStartSchema.extend({deviceId:id7.optional()});var SourceSyncRuntimePublicationSchema=SourceSyncRuntimeStartSchema.transform(({deviceId,...publication})=>{void deviceId;return publication});var SourceSyncRuntimeScopeSchema=z99.strictObject({tenantId:id7,productionId:id7,requestId:id7});var SourceSyncRuntimeAdmissionSchema=z99.strictObject({requestId:id7,runtimeJobId:id7,productionRevision:z99.int().positive()});var SourceSyncRuntimeViewSchema=SourceSyncRuntimeAdmissionSchema.extend({normalizationId:id7,lifecycle:z99.enum(["PENDING","READY","RUNNING","WAITING","SUCCEEDED","FAILED","CANCELLED","SUPERSEDED"]),cancellationRequested:z99.boolean(),output:SourceSyncAudioReceiptSchema.nullable()});import{z as z100}from"zod";var id8=z100.uuid().toLowerCase();var hash4=z100.string().regex(/^[0-9a-f]{64}$/);var SourceSyncMediaIdentitySchema=z100.strictObject({artifactId:id8,representationId:id8,checksumSha256:hash4});var sampleRange=z100.strictObject({startSample:z100.int().nonnegative(),endSample:z100.int().positive()}).refine(v=>v.endSample>v.startSample);var frameRange=z100.strictObject({startFrame:z100.int().nonnegative(),endFrame:z100.int().positive()}).refine(v=>v.endFrame>v.startFrame);var SourceSyncListeningEvidenceSchema=z100.discriminatedUnion("kind",[z100.strictObject({id:z100.string().trim().min(1).max(100),kind:z100.literal("AUDIO_LISTENING"),media:SourceSyncMediaIdentitySchema,coverage:z100.array(sampleRange).min(1).max(64),producer:z100.string().trim().min(1).max(200)}),z100.strictObject({id:z100.string().trim().min(1).max(100),kind:z100.literal("VIDEO_PLAYBACK"),media:SourceSyncMediaIdentitySchema,coverage:z100.array(frameRange).min(1).max(64),producer:z100.string().trim().min(1).max(200)})]);var SourceSyncObservationSchema=z100.strictObject({key:z100.enum(["AUDIBILITY","AUDIO_VISUAL_ALIGNMENT"]),status:z100.enum(["SATISFIED","VIOLATED","NOT_OBSERVABLE"]),confidence:z100.enum(["CLEAR","UNCERTAIN"]),observed:z100.string().trim().min(1).max(2e3),evidenceIds:z100.array(z100.string().trim().min(1).max(100)).max(64)});var SourceSyncReviewTargetSchema=z100.strictObject({version:SourceSyncAudioVersionSchema,audio:SourceSyncMediaIdentitySchema,visual:SourceSyncMediaIdentitySchema,sampleCount:z100.int().positive(),frameCount:z100.int().positive().max(360),currentReviewVersion:z100.int().nonnegative(),declarationScope:z100.literal("ATTRIBUTED_OBSERVATIONS_NOT_LISTENING_ATTESTATION")});var SourceSyncReviewInputSchema=SourceSyncAudioGetSchema.extend({tenantId:id8,productionId:id8,shotId:id8,versionId:id8,expectedReviewVersion:z100.int().nonnegative(),audio:SourceSyncMediaIdentitySchema,visual:SourceSyncMediaIdentitySchema,evidence:z100.array(SourceSyncListeningEvidenceSchema).max(64),observations:z100.array(SourceSyncObservationSchema).length(2),summary:z100.string().trim().min(1).max(4e3),idempotencyKey:z100.string().trim().min(1).max(200)});var SourceSyncReviewRecordSchema=z100.strictObject({id:id8,versionId:id8,reviewVersion:z100.int().positive(),tenantId:id8,productionId:id8,shotId:id8,audio:SourceSyncMediaIdentitySchema,visual:SourceSyncMediaIdentitySchema,evidence:z100.array(SourceSyncListeningEvidenceSchema).max(64),observations:z100.array(SourceSyncObservationSchema).length(2),outcome:z100.enum(["PASS","FAIL","NEEDS_REVIEW"]),summary:z100.string(),createdByPrincipalId:id8,executionClass:z100.enum(["LIVE","TEST_ONLY"]),createdAt:z100.iso.datetime({offset:true})});var SourceSyncReviewGetSchema=SourceSyncAudioGetSchema.extend({tenantId:id8,productionId:id8,shotId:id8,versionId:id8,reviewId:id8});import{z as z101}from"zod";var ImportedVideoReviewRecordSchema=VideoReviewRecordSchema.omit({generationId:true,candidateId:true,preparationId:true,contractId:true,contractFingerprint:true}).extend({sourceKind:z101.literal("IMPORTED"),normalizationId:z101.uuid(),sourceId:z101.uuid(),sourceVersionId:z101.uuid(),planVersionId:z101.uuid(),shotPlanningRevision:z101.int().positive()});var ImportedVideoReviewReceiptSchema=z101.strictObject({semanticStatus:z101.literal("SUCCESS"),review:ImportedVideoReviewRecordSchema,productionRevision:z101.int().positive()});import{z as z102}from"zod";var ImportedVisualCancellationSchema=z102.strictObject({cancellationRequested:z102.boolean()});var ImportedVisualAdmissionSchema=z102.strictObject({semanticStatus:z102.literal("ACCEPTED"),normalizationId:z102.uuid(),runtimeJobId:z102.uuid(),sourceId:z102.uuid(),sourceVersionId:z102.uuid(),productionRevision:z102.int().positive(),deviceExecution:DeviceRenderReceiptSchema.optional()});var ImportedVisualReviewTargetSchema=ProgrammaticVideoReviewTargetSchema.omit({renderId:true,compositionId:true,compositionVersionId:true,compositionVersion:true,compositionFingerprint:true,renderManifestFingerprint:true}).extend({sourceKind:z102.literal("IMPORTED"),normalizationId:z102.uuid(),sourceId:z102.uuid(),sourceVersionId:z102.uuid(),latestReview:ImportedVideoReviewRecordSchema.nullable()});import{z as z103}from"zod";var ImportedVisualOriginalGetSchema=z103.strictObject({tenantId:z103.uuid(),productionId:z103.uuid(),sourceId:z103.uuid(),version:z103.int().positive().optional()});var ImportedVisualOriginalHistoryQuerySchema=z103.strictObject({tenantId:z103.uuid(),productionId:z103.uuid(),sourceId:z103.uuid(),beforeVersion:z103.int().positive().optional(),limit:z103.int().min(1).max(50).default(20)});var ImportedVisualOriginalHistorySchema=z103.strictObject({sourceId:z103.uuid(),items:z103.array(ImportedVisualOriginalViewSchema).max(50),nextBeforeVersion:z103.int().positive().nullable()});var ImportedVisualOriginalQuerySchema=z103.strictObject({tenantId:z103.uuid().toLowerCase(),productionId:z103.uuid().toLowerCase(),shotId:z103.uuid().toLowerCase().optional(),afterSourceId:z103.uuid().toLowerCase().optional(),limit:z103.int().min(1).max(50).default(20)});var ImportedVisualOriginalPageSchema=z103.strictObject({tenantId:z103.uuid(),productionId:z103.uuid(),items:z103.array(ImportedVisualOriginalViewSchema).max(50),nextAfterSourceId:z103.uuid().nullable()}).refine(p=>p.nextAfterSourceId===null||p.items.at(-1)?.sourceId===p.nextAfterSourceId);import{z as z104}from"zod";var Content=z104.string().min(44).max(178956972).refine(value2=>{if(value2.length%4||/[^A-Za-z0-9+/=]/.test(value2))return false;const padding=value2.endsWith("==")?2:value2.endsWith("=")?1:0;return value2.indexOf("=")===(padding?value2.length-padding:-1)},"Invalid base64").refine(value2=>{const alphabet="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";return value2.endsWith("==")?alphabet.indexOf(value2.at(-3))%16===0:value2.endsWith("=")?alphabet.indexOf(value2.at(-2))%4===0:true},"Noncanonical base64");var ImportedVisualOriginalUploadSchema=ImportedVisualOriginalRegisterSchema.extend({contentBase64:Content});var ImportedVisualOriginalRevisionUploadSchema=ImportedVisualOriginalReviseSchema.extend({contentBase64:Content});var LegacyImportedVisualUploadSchema=ImportedVisualOriginalUploadSchema.omit({deviceId:true});var LegacyImportedVisualRevisionSchema=ImportedVisualOriginalRevisionUploadSchema.omit({deviceId:true});var LegacyImportedVisualProjectSourceSchema=ImportedVisualFromProjectSourceSchema.omit({deviceId:true});import{z as z105}from"zod";var DirectOriginalCommandSchema=z105.discriminatedUnion("operation",[z105.strictObject({operation:z105.literal("REGISTER"),input:ImportedVisualOriginalRegisterSchema}),z105.strictObject({operation:z105.literal("REVISE"),input:ImportedVisualOriginalReviseSchema})]);var DirectOriginalKeySchema=LocalWorkScopeSchema.omit({runtimeJobId:true}).extend({intakeId:LocalIdSchema});var DirectOriginalAdmissionSchema=z105.strictObject({state:z105.literal("SUBMITTED"),tenantId:z105.uuid(),projectId:z105.uuid(),productionId:z105.uuid(),intakeId:z105.uuid(),runtimeJobId:z105.uuid(),operationId:OperationIdSchema});var accepted=z105.strictObject({state:z105.literal("ACCEPTED"),original:ImportedVisualOriginalViewSchema});var DirectOriginalStageSchema=z105.discriminatedUnion("state",[accepted,DirectOriginalAdmissionSchema,DirectOriginalKeySchema.extend({state:z105.literal("UPLOAD"),ticket:MediaObjectTicketSchema,uploaded:z105.boolean()})]);var DirectOriginalSubmitSchema=z105.discriminatedUnion("state",[accepted,DirectOriginalAdmissionSchema]);import{z as z107}from"zod";import{z as z106}from"zod";var ArtifactLifecycleSchema=z106.enum(["CREATING","PROCESSING","READY","INVALID","ARCHIVED"]);var ArtifactMetadataSchema=z106.object({id:ArtifactIdSchema,tenantId:TenantIdSchema,projectId:ProjectIdSchema,productionId:ProductionIdSchema.nullable(),family:z106.string().trim().min(1),origin:z106.string().trim().min(1),lifecycle:ArtifactLifecycleSchema,createdByPrincipalId:PrincipalIdSchema,checksumSha256:z106.string().regex(/^[0-9a-f]{64}$/).nullable(),contentType:z106.string().trim().min(1).nullable(),primaryRepresentationId:ArtifactRepresentationIdSchema.nullable(),mediaMetadata:z106.record(z106.string(),z106.unknown()),createdAt:z106.iso.datetime({offset:true}),readyAt:z106.iso.datetime({offset:true}).nullable()});var ArtifactRepresentationSchema=z106.object({id:ArtifactRepresentationIdSchema,tenantId:TenantIdSchema,artifactId:ArtifactIdSchema,role:z106.string().trim().min(1),storageDriver:z106.string().trim().min(1),storageLocator:z106.record(z106.string(),z106.unknown()),checksumSha256:z106.string().regex(/^[0-9a-f]{64}$/),contentType:z106.string().trim().min(1),byteSize:z106.string().regex(/^\d+$/),width:z106.int().positive().nullable(),height:z106.int().positive().nullable(),durationMs:z106.string().regex(/^\d+$/).nullable(),frameRate:z106.string().nullable(),videoCodec:z106.string().nullable(),audioCodec:z106.string().nullable(),hasAudio:z106.boolean().nullable(),sampleRateHz:z106.int().positive().nullable(),audioChannels:z106.int().positive().nullable(),createdAt:z106.iso.datetime({offset:true})});var ArtifactRelationSchema=z106.object({id:ArtifactRelationIdSchema,tenantId:TenantIdSchema,sourceArtifactId:ArtifactIdSchema,targetArtifactId:ArtifactIdSchema,relationType:z106.string().trim().min(1),createdByPrincipalId:PrincipalIdSchema,createdAt:z106.iso.datetime({offset:true})});var RegisterReadyArtifactInputSchema=z106.object({tenantId:TenantIdSchema,projectId:ProjectIdSchema,productionId:ProductionIdSchema.nullable(),principalId:PrincipalIdSchema,family:z106.string().trim().min(1),origin:z106.string().trim().min(1),representation:z106.object({role:z106.string().trim().min(1),storageDriver:z106.string().trim().min(1),storageLocator:z106.record(z106.string(),z106.unknown()),checksumSha256:z106.string().regex(/^[0-9a-f]{64}$/),contentType:z106.string().trim().min(1),byteSize:z106.string().regex(/^\d+$/),width:z106.int().positive().nullable(),height:z106.int().positive().nullable(),durationMs:z106.string().regex(/^\d+$/).nullable(),frameRate:z106.string().nullable(),videoCodec:z106.string().nullable(),audioCodec:z106.string().nullable(),hasAudio:z106.boolean().nullable(),sampleRateHz:z106.int().positive().nullable(),audioChannels:z106.int().positive().nullable()}),mediaMetadata:z106.record(z106.string(),z106.unknown()).default({}),provenance:z106.array(z106.object({targetArtifactId:ArtifactIdSchema,relationType:z106.string().trim().min(1)})).default([])});var ReadyArtifactRegistrationSchema=z106.object({artifact:ArtifactMetadataSchema,primaryRepresentation:ArtifactRepresentationSchema,relations:z106.array(ArtifactRelationSchema)});var SourceInputMetadataSchema=z106.strictObject({idempotencyKey:z106.string().trim().min(1).max(200).optional(),tenantId:TenantIdSchema,kind:z106.enum(["PRODUCT_INFORMATION","REFERENCE_IMAGE","REFERENCE_VIDEO"]),contentType:z106.enum(["text/plain","application/json","image/png","image/jpeg","image/webp","video/mp4"]),originalName:z106.string().trim().min(1).max(255).optional()});var UploadSourceInputRequestSchema=SourceInputMetadataSchema.extend({contentBase64:z106.string().min(4).max(11184812).regex(/^[A-Za-z0-9+/]*={0,2}$/)});var DirectProjectSourceCommandSchema=z107.strictObject({projectId:LocalIdSchema,metadata:SourceInputMetadataSchema.extend({tenantId:LocalIdSchema.pipe(TenantIdSchema),idempotencyKey:z107.string().trim().min(1).max(200)}),checksumSha256:LocalDigestSchema,byteSize:z107.int().positive().max(8*1024*1024),requestedDeviceId:LocalIdSchema.optional()}).refine(({metadata})=>metadata.kind==="REFERENCE_VIDEO"?metadata.contentType==="video/mp4":metadata.kind==="REFERENCE_IMAGE"&&["image/png","image/jpeg","image/webp"].includes(metadata.contentType));var DirectProjectSourceKeySchema=LocalProjectScopeSchema.extend({intakeId:LocalIdSchema});var DirectProjectSourceAdmissionSchema=DirectProjectSourceKeySchema.extend({state:z107.literal("SUBMITTED"),productionId:LocalIdSchema,runtimeJobId:LocalIdSchema,operationId:OperationIdSchema});var accepted2=z107.strictObject({state:z107.literal("ACCEPTED"),registration:ReadyArtifactRegistrationSchema});var DirectProjectSourceStageSchema=z107.discriminatedUnion("state",[accepted2,DirectProjectSourceAdmissionSchema,DirectProjectSourceKeySchema.extend({state:z107.literal("UPLOAD"),ticket:MediaObjectTicketSchema,uploaded:z107.boolean()})]);var DirectProjectSourceSubmitSchema=z107.discriminatedUnion("state",[accepted2,DirectProjectSourceAdmissionSchema]);var LocalLibraryDestinationSchema=z108.discriminatedUnion("kind",[z108.strictObject({kind:z108.literal("ORIGINAL"),command:DirectOriginalCommandSchema}),z108.strictObject({kind:z108.literal("PROJECT_SOURCE"),command:DirectProjectSourceCommandSchema})]);function localLibraryInspectable(reference3){if(reference3.contentType==="video/mp4")return reference3.byteSize>=32;return["image/png","image/jpeg","image/webp"].includes(reference3.contentType)&&reference3.byteSize>0&&reference3.byteSize<=8*1024*1024}var sameId=(left,right)=>left.toLowerCase()===right.toLowerCase();function destinationMatches(destination,reference3){if(destination.kind==="ORIGINAL"){const{input}=destination.command;return sameId(input.tenantId,reference3.tenantId)&&sameId(input.projectId,reference3.projectId)&&(!input.deviceId||sameId(input.deviceId,reference3.deviceId))&&input.source.contentType===reference3.contentType&&input.source.byteSize===reference3.byteSize&&input.source.checksumSha256===reference3.checksumSha256}const{command:command4}=destination;return sameId(command4.metadata.tenantId,reference3.tenantId)&&sameId(command4.projectId,reference3.projectId)&&(!command4.requestedDeviceId||sameId(command4.requestedDeviceId,reference3.deviceId))&&command4.metadata.contentType===reference3.contentType&&command4.byteSize===reference3.byteSize&&command4.checksumSha256===reference3.checksumSha256}var command=LocalWorkScopeSchema.omit({runtimeJobId:true}).extend({requestId:LocalIdSchema,reference:LocalLibraryReferenceSchema,accessRevision:z108.int().positive()});var LocalLibraryCommandSchema=z108.discriminatedUnion("action",[command.extend({action:z108.literal("INSPECT")}),command.extend({action:z108.literal("PUBLISH"),destination:LocalLibraryDestinationSchema})]).superRefine((value2,ctx)=>{if(value2.reference.tenantId!==value2.tenantId||value2.reference.projectId!==value2.projectId)ctx.addIssue({code:"custom",message:"Exact local file project required"});if(!localLibraryInspectable(value2.reference))ctx.addIssue({code:"custom",message:"A qualified media file version is required"});if(value2.action!=="PUBLISH")return;const d=value2.destination;if(d.kind==="ORIGINAL"){const input=d.command.input;if(!sameId(input.tenantId,value2.tenantId)||!sameId(input.projectId,value2.projectId)||!sameId(input.productionId,value2.productionId)||input.deviceId&&!sameId(input.deviceId,value2.reference.deviceId)||input.source.byteSize!==value2.reference.byteSize||input.source.checksumSha256!==value2.reference.checksumSha256||input.source.contentType!==value2.reference.contentType)ctx.addIssue({code:"custom",message:"Original must bind exact local file and native Production"})}else if(!sameId(d.command.metadata.tenantId,value2.tenantId)||!sameId(d.command.projectId,value2.projectId)||d.command.requestedDeviceId&&!sameId(d.command.requestedDeviceId,value2.reference.deviceId)||d.command.byteSize!==value2.reference.byteSize||d.command.checksumSha256!==value2.reference.checksumSha256||d.command.metadata.contentType!==value2.reference.contentType)ctx.addIssue({code:"custom",message:"Project SOURCE must bind exact local file"})});var LocalLibraryCommandQuerySchema=LocalWorkScopeSchema.omit({runtimeJobId:true}).extend({requestId:LocalIdSchema});var LocalLibraryAdmissionSchema=LocalWorkScopeSchema.extend({state:z108.literal("SUBMITTED"),requestId:LocalIdSchema,operationId:OperationIdSchema,reference:LocalLibraryReferenceSchema,accessRevision:z108.int().positive()});var LocalLibraryInspectionSchema=z108.discriminatedUnion("kind",[z108.strictObject({kind:z108.literal("VIDEO"),metadata:ImportedVisualSourceMetadataSchema}),z108.strictObject({kind:z108.literal("IMAGE"),checksumSha256:LocalDigestSchema,byteSize:z108.int().positive().max(8*1024*1024),width:z108.int().positive().max(4096),height:z108.int().positive().max(4096)})]);var LocalLibraryInspectRecipeSchema=z108.strictObject({processor:z108.literal("LOCAL_MEDIA_INSPECT"),reference:LocalLibraryReferenceSchema,accessRevision:z108.int().positive(),libraryProfileDigest:LocalDigestSchema}).refine(({reference:reference3})=>localLibraryInspectable(reference3),"Qualified local inspection required");var LocalLibraryPublishRecipeSchema=z108.strictObject({processor:z108.literal("LOCAL_MEDIA_PUBLISH"),reference:LocalLibraryReferenceSchema,accessRevision:z108.int().positive(),libraryProfileDigest:LocalDigestSchema,destination:LocalLibraryDestinationSchema,object:MediaObjectVersionSchema.extend({role:z108.literal("SOURCE")})}).refine(({reference:reference3,object,destination})=>localLibraryInspectable(reference3)&&destinationMatches(destination,reference3)&&object.tenantId===reference3.tenantId&&object.projectId===reference3.projectId&&object.checksumSha256===reference3.checksumSha256&&object.byteSize===reference3.byteSize,"Publication must use the exact local file version and native destination");var LocalLibraryInspectEvidenceSchema=z108.strictObject({processor:z108.literal("LOCAL_MEDIA_INSPECT"),inspection:LocalLibraryInspectionSchema});var LocalLibraryPublishEvidenceSchema=z108.strictObject({processor:z108.literal("LOCAL_MEDIA_PUBLISH"),inspection:LocalLibraryInspectionSchema});import{z as z109}from"zod";var sha14=z109.string().regex(/^[0-9a-f]{64}$/);var TemporalEvidenceSourceSchema=z109.strictObject({tenantId:z109.uuid(),projectId:z109.uuid(),productionId:z109.uuid(),artifactId:z109.uuid(),representationId:z109.uuid(),checksumSha256:sha14,byteSize:z109.int().positive().max(128*1024*1024),width:z109.int().min(16).max(4096),height:z109.int().min(16).max(4096),durationMs:z109.int().positive().max(6e4),frameRate:z109.number().min(1).max(60),frameCount:z109.int().positive().max(3600),videoCodec:z109.literal("h264"),executionClass:z109.enum(["LIVE","TEST_ONLY"])}).refine(v=>Math.abs(v.frameCount/v.frameRate*1e3-v.durationMs)<=150,"Exact frame count, duration and rate must agree");var TemporalRiskWindowSchema=z109.strictObject({startMs:z109.int().nonnegative().max(6e4),endMs:z109.int().positive().max(6e4),reason:z109.enum(["TEMPORAL_BEAT","PRIOR_FINDING","SUSPICIOUS_DRIFT","SCENE_CHANGE"])}).refine(v=>v.endMs>v.startMs,"Risk window must advance");var TemporalSamplingProfileSchema=z109.strictObject({id:z109.literal("ADAPTIVE_TEMPORAL_V1"),motion:z109.enum(["NORMAL","HIGH"]),lockedIdentity:z109.boolean(),windows:z109.array(TemporalRiskWindowSchema).max(32)});var TemporalSampleSchema=z109.strictObject({ordinal:z109.int().nonnegative().max(63),frameIndex:z109.int().nonnegative().max(3599),timestampMs:z109.number().nonnegative().max(6e4),reasons:z109.array(z109.enum(["START","END","INTERIOR","HIGH_MOTION","LOCKED_IDENTITY","TEMPORAL_BEAT","PRIOR_FINDING","SUSPICIOUS_DRIFT","SCENE_CHANGE"])).min(1).max(9)});var TemporalSamplingPlanSchema=z109.strictObject({schemaVersion:z109.literal(1),source:TemporalEvidenceSourceSchema,profile:TemporalSamplingProfileSchema,samples:z109.array(TemporalSampleSchema).min(1).max(64),frameWidth:z109.int().min(16).max(320),frameHeight:z109.int().min(16).max(320),columns:z109.int().min(1).max(4),rows:z109.int().min(1).max(16),gutterPx:z109.literal(8)}).superRefine((p,ctx)=>{const s=p.samples;if(s[0]?.frameIndex!==0||s.at(-1)?.frameIndex!==p.source.frameCount-1||p.rows!==Math.ceil(s.length/p.columns)||p.columns!==Math.min(4,s.length)||s.some((v,i)=>v.ordinal!==i||v.frameIndex>=p.source.frameCount||Math.abs(v.timestampMs-v.frameIndex*1e3/p.source.frameRate)>.001||i>0&&v.frameIndex<=s[i-1].frameIndex||new Set(v.reasons).size!==v.reasons.length)||p.profile.windows.some(w=>w.endMs>p.source.durationMs))ctx.addIssue({code:"custom",message:"Temporal samples must preserve exact bounded source order, time and layout"})});var ExtractedTemporalFrameSchema=z109.strictObject({sample:TemporalSampleSchema,checksumSha256:sha14,byteSize:z109.int().positive().max(2*1024*1024),width:z109.int().positive().max(320),height:z109.int().positive().max(320),contentType:z109.literal("image/png")});var TemporalEvidenceManifestSchema=z109.strictObject({schemaVersion:z109.literal(1),plan:TemporalSamplingPlanSchema,engineVersion:z109.string().min(1).max(200),frames:z109.array(ExtractedTemporalFrameSchema).min(1).max(64),sheet:z109.strictObject({checksumSha256:sha14,byteSize:z109.int().positive().max(16*1024*1024),width:z109.int().positive().max(1320),height:z109.int().positive().max(5256),contentType:z109.literal("image/png")})}).superRefine((m,ctx)=>{const p=m.plan;if(m.frames.length!==p.samples.length||m.frames.some((f,i)=>JSON.stringify(f.sample)!==JSON.stringify(p.samples[i])||f.width!==p.frameWidth||f.height!==p.frameHeight)||m.sheet.width!==p.columns*p.frameWidth+(p.columns+1)*p.gutterPx||m.sheet.height!==p.rows*p.frameHeight+(p.rows+1)*p.gutterPx)ctx.addIssue({code:"custom",message:"Evidence frames and sheet must match the exact sampling plan"})});function processorToolchain(raw,processor){const parsed=LocalToolchainSchema.safeParse(raw);if(!parsed.success)return null;const value2=parsed.data;if(processor!=="SPEECH_SYNTHESIZE_CPU"){if(value2.profile.kind!=="STUDIO_MEDIA_V2")return null;return selectLocalToolchain(value2,value2.profile.contractDigest)}const selected=value2.profile.kind==="AUDIO_MEDIA_V1"?value2:value2.supported?.find(s=>s.profile.kind==="AUDIO_MEDIA_V1");if(!selected)return null;const{supported,...base3}=value2;void supported;return LocalToolchainSchema.parse({...base3,profile:selected.profile,rendererVersion:selected.rendererVersion,rendererDigest:selected.rendererDigest})}import{z as z114}from"zod";import{z as z113}from"zod";import{z as z111}from"zod";import{z as z110}from"zod";var sha15=z110.string().regex(/^[0-9a-f]{64}$/);var name=z110.string().regex(/^[A-Za-z][A-Za-z0-9_.-]{0,63}$/);var CompositionPathSchema=z110.string().max(240).regex(/^[A-Za-z0-9_-][A-Za-z0-9_.-]*(?:\/[A-Za-z0-9_.-]+)*$/).refine(v=>!v.split("/").some(p=>p==="."||p===".."));var CompositionScopeSchema=z110.strictObject({tenantId:z110.uuid(),productionId:z110.uuid()});var CompositionBasisPinSchema=z110.strictObject({briefVersionId:z110.uuid(),storyVersionId:z110.uuid(),planVersionId:z110.uuid(),shotId:z110.uuid().nullable()});var CompositionBindingSchema=z110.strictObject({name,purpose:z110.enum(["SOURCE","DEPENDENCY_MANIFEST","DEPENDENCY_LOCK","DATA","FONT","IMAGE","VIDEO"]),artifactId:z110.uuid(),representationId:z110.uuid(),checksumSha256:sha15,declaredOrigin:z110.enum(["CODE","AI","HUMAN","IMPORTED","UNKNOWN"])});var parameter=z110.discriminatedUnion("type",[z110.strictObject({name,type:z110.literal("STRING"),value:z110.string().max(4e3),maxLength:z110.int().min(0).max(4e3)}).refine(v=>v.value.length<=v.maxLength),z110.strictObject({name,type:z110.literal("NUMBER"),value:z110.number().finite(),minimum:z110.number().finite(),maximum:z110.number().finite()}).refine(v=>v.minimum<=v.value&&v.value<=v.maximum),z110.strictObject({name,type:z110.literal("BOOLEAN"),value:z110.boolean()})]);var CompositionContentSchema=z110.strictObject({schemaVersion:z110.literal(1),provider:z110.literal("HYPERFRAME"),dialect:z110.literal("HYPERFRAME_HTML_GSAP_V1"),role:z110.enum(["PRIMARY_VISUAL","VISUAL_LAYER"]),executionClass:z110.enum(["LIVE","TEST_ONLY"]),intent:z110.string().trim().min(1).max(2e3),viewport:z110.strictObject({width:z110.int().min(1).max(8192),height:z110.int().min(1).max(8192)}),clock:z110.strictObject({numerator:z110.int().positive(),denominator:z110.int().positive(),frameCount:z110.int().positive().max(2147483647)}),entrypoint:CompositionPathSchema,parameterSchemaVersion:z110.literal(1),parameters:z110.array(parameter).max(64),bindings:z110.array(CompositionBindingSchema).min(3).max(64),dependencies:z110.array(z110.strictObject({name:z110.string().regex(/^(?:@[a-z0-9._-]+\/)?[a-z0-9._-]+$/),version:z110.string().regex(/^\d+\.\d+\.\d+(?:-[A-Za-z0-9.-]+)?$/),integrity:z110.string().regex(/^sha(?:256|384|512)-[A-Za-z0-9+/]+={0,2}$/)})).min(1).max(64),randomSeed:z110.int().nonnegative().max(4294967295).nullable()}).superRefine((c,ctx)=>{for(const list of[c.parameters,c.bindings,c.dependencies])if(new Set(list.map(x=>x.name)).size!==list.length)ctx.addIssue({code:"custom",message:"Names must be unique within each input group"});for(const purpose of["SOURCE","DEPENDENCY_MANIFEST","DEPENDENCY_LOCK"])if(c.bindings.filter(x=>x.purpose===purpose).length!==1)ctx.addIssue({code:"custom",path:["bindings"],message:"Exactly one "+purpose+" binding is required"});if(c.bindings.find(x=>x.purpose==="SOURCE")?.declaredOrigin!=="CODE")ctx.addIssue({code:"custom",path:["bindings"],message:"Programmatic source must retain CODE provenance"});for(const p of["@hyperframes/engine","@hyperframes/producer","gsap"])if(!c.dependencies.some(x=>x.name===p))ctx.addIssue({code:"custom",path:["dependencies"],message:"Missing authoring dependency: "+p})});var CompositionSourceBundleSchema=z110.strictObject({schemaVersion:z110.literal(1),entrypoint:CompositionPathSchema,files:z110.array(z110.strictObject({path:CompositionPathSchema,contentType:z110.enum(["text/html","text/css","text/javascript","image/svg+xml","application/json"]),content:z110.string().max(1048576)})).min(1).max(128)}).superRefine((b,ctx)=>{if(new Set(b.files.map(x=>x.path)).size!==b.files.length)ctx.addIssue({code:"custom",message:"Source paths must be unique"});if(!b.files.some(x=>x.path===b.entrypoint&&x.contentType==="text/html"))ctx.addIssue({code:"custom",message:"Entrypoint must resolve to a declared HTML file"})});var SubmitCompositionSchema=CompositionScopeSchema.extend({compositionId:z110.uuid().nullable(),expectedVersion:z110.int().nonnegative(),previousVersionId:z110.uuid().nullable(),expectedProductionRevision:z110.int().positive(),basis:CompositionBasisPinSchema,content:CompositionContentSchema,idempotencyKey:z110.string().trim().min(1).max(200)}).superRefine((i,ctx)=>{if(i.expectedVersion===0!==(i.compositionId===null&&i.previousVersionId===null)||i.expectedVersion>0&&(!i.compositionId||!i.previousVersionId))ctx.addIssue({code:"custom",message:"Create and exact-version revision identities must not be mixed"});if(i.content.role==="PRIMARY_VISUAL"&&!i.basis.shotId)ctx.addIssue({code:"custom",message:"Primary visual must bind a planned Shot"})});var CompositionGetSchema=CompositionScopeSchema.extend({compositionId:z110.uuid(),versionId:z110.uuid().optional()});var CompositionHistorySchema=CompositionScopeSchema.extend({compositionId:z110.uuid(),limit:z110.int().min(1).max(100).default(20),beforeVersion:z110.int().positive().optional()});var CompositionInputFactSchema=CompositionBindingSchema.extend({contentType:z110.string().min(1),byteSize:z110.int().positive().max(67108864),registeredOrigin:z110.string().min(1),executionClass:z110.enum(["LIVE","TEST_ONLY"]).nullable()});var CompositionVersionSchema=CompositionScopeSchema.extend({id:z110.uuid(),compositionId:z110.uuid(),projectId:z110.uuid(),version:z110.int().positive(),previousVersionId:z110.uuid().nullable(),basis:CompositionBasisPinSchema,content:CompositionContentSchema,inputs:z110.array(CompositionInputFactSchema).min(3).max(64),fingerprint:sha15,createdByPrincipalId:z110.uuid(),createdAt:z110.iso.datetime({offset:true})}).refine(v=>v.version===1===(v.previousVersionId===null));var CompositionReceiptSchema=z110.strictObject({semanticStatus:z110.literal("SUCCESS"),version:CompositionVersionSchema,productionRevision:z110.int().positive()});var CompositionViewSchema=z110.strictObject({version:CompositionVersionSchema,isCurrent:z110.boolean(),basisStatus:z110.enum(["CURRENT","STALE"]),inputStatus:z110.enum(["AVAILABLE","UNAVAILABLE"]),byteReadback:z110.literal("NOT_CHECKED")});var CompositionPageSchema=z110.strictObject({items:z110.array(CompositionViewSchema).max(100),hasMore:z110.boolean(),nextBeforeVersion:z110.int().positive().nullable()});var CompositionDependencyManifestSchema=z110.object({dependencies:z110.record(z110.string(),z110.string())});var CompositionDependencyLockSchema=z110.object({lockfileVersion:z110.literal(3),packages:z110.record(z110.string(),z110.object({version:z110.string().optional(),integrity:z110.string().optional(),dependencies:z110.record(z110.string(),z110.string()).optional()}))});var HyperframeLegacyRenderProfileSchema=z111.strictObject({id:z111.literal("HYPERFRAME_1080P30_FULL_PAINT_V1"),adapter:z111.literal("native-hyperframe-v1"),engine:z111.literal("0.8.134"),producer:z111.literal("0.8.134"),gsap:z111.literal("3.15.0"),node:z111.string().min(1).max(80),browser:z111.string().min(1).max(160),browserSha256:z111.string().regex(/^[0-9a-f]{64}$/),ffmpeg:z111.string().min(1).max(240),maxFrames:z111.literal(360),timeoutMs:z111.literal(6e5),maxRssBytes:z111.literal(3221225472),maxScratchBytes:z111.literal(3221225472),maxOutputBytes:z111.literal(134217728),maxCpuMs:z111.literal(6e5),capture:z111.literal("PNG_SOFTWARE_SCREENSHOT_FULL_PAINT"),encode:z111.literal("H264_YUV420P_CRF18_THREADS2_NO_AUDIO")});var HyperframeCachedRenderProfileSchema=HyperframeLegacyRenderProfileSchema.extend({id:z111.literal("HYPERFRAME_1080P30_FRAME_CACHE_V2"),adapter:z111.literal("native-hyperframe-cache-v2"),encode:z111.literal("H264_YUV420P_CRF18_VERYFAST_THREADS2_NO_AUDIO")});var HyperframeRenderProfileSchema=z111.discriminatedUnion("id",[HyperframeLegacyRenderProfileSchema,HyperframeCachedRenderProfileSchema]);var CompositionRenderStartSchema=CompositionGetSchema.extend({versionId:z111.uuid(),fingerprint:z111.string().regex(/^[0-9a-f]{64}$/),expectedProductionRevision:z111.int().positive(),profileId:z111.enum(["HYPERFRAME_1080P30_FULL_PAINT_V1","HYPERFRAME_1080P30_FRAME_CACHE_V2","HYPERFRAME_RGBA_PNG30_FULL_PAINT_V1"]),idempotencyKey:z111.string().trim().min(1).max(200),deviceId:z111.uuid().toLowerCase().optional()});var CompositionRenderGetSchema=CompositionScopeSchema.extend({renderId:z111.uuid()});var CompositionRenderManifestSchema=z111.strictObject({schemaVersion:z111.literal(1),version:CompositionVersionSchema,profile:HyperframeRenderProfileSchema,firstFrame:z111.literal(0),frameCount:z111.int().min(1).max(360)}).superRefine((m,ctx)=>{if(m.frameCount!==m.version.content.clock.frameCount||m.version.inputs.reduce((n,i)=>n+i.byteSize,0)>134217728)ctx.addIssue({code:"custom",message:"Exact frame count and aggregate input budget required"})});var CompositionRenderReceiptSchema=z111.strictObject({semanticStatus:z111.literal("ACCEPTED"),renderId:z111.uuid(),runtimeJobId:z111.uuid(),compositionVersionId:z111.uuid(),manifestFingerprint:z111.string().regex(/^[0-9a-f]{64}$/),productionRevision:z111.int().positive()});var CompositionRenderTechnicalSchema=z111.strictObject({width:z111.literal(1920),height:z111.literal(1080),frameRate:z111.literal(30),frameCount:z111.int().min(1).max(360),durationMs:z111.number().positive(),contentType:z111.literal("video/mp4"),videoCodec:z111.literal("h264"),pixelFormat:z111.literal("yuv420p"),hasAudio:z111.literal(false),fullDecode:z111.literal(true),checksumSha256:z111.string().regex(/^[0-9a-f]{64}$/),byteSize:z111.int().min(1).max(134217728),decodedFramesSha256:z111.string().regex(/^[0-9a-f]{64}$/)});var CompositionRenderResourcesSchema=z111.strictObject({sampleIntervalMs:z111.literal(100),sampledTreePeakRssBytes:z111.int().nonnegative(),sampledTreeCpuMs:z111.number().nonnegative(),observedPids:z111.int().nonnegative(),scratchPeakBytes:z111.int().nonnegative(),wallMs:z111.number().nonnegative(),processGroupCleaned:z111.literal(true)});import{z as z112}from"zod";var HyperframeAlphaRenderProfileSchema=HyperframeLegacyRenderProfileSchema.extend({id:z112.literal("HYPERFRAME_RGBA_PNG30_FULL_PAINT_V1"),adapter:z112.literal("native-hyperframe-alpha-v1"),encode:z112.literal("RGBA_PNG_SEQUENCE_30_V1"),maxOutputBytes:z112.literal(67108864),maxDecodedBytes:z112.literal(536870912)});var CompositionFrameRenderManifestSchema=z112.strictObject({...CompositionRenderManifestSchema.shape,schemaVersion:z112.literal(2),profile:HyperframeAlphaRenderProfileSchema}).superRefine((m,context)=>{const c=m.version.content;if(m.frameCount!==c.clock.frameCount||m.version.inputs.reduce((n,i)=>n+i.byteSize,0)>134217728||c.role!=="VISUAL_LAYER"||c.viewport.width>1920||c.viewport.height>1920||c.viewport.width*c.viewport.height>1920*1080||c.viewport.width*c.viewport.height*m.frameCount*4>m.profile.maxDecodedBytes||c.clock.numerator!==30||c.clock.denominator!==1)context.addIssue({code:"custom",message:"Qualified CODE alpha geometry/role/clock/decoded budget mismatch"})});var CompositionFrameTechnicalSchema=z112.strictObject({profileId:z112.literal("RGBA_PNG_SEQUENCE_30_V1"),width:z112.int().min(1).max(1920),height:z112.int().min(1).max(1920),frameRate:z112.literal(30),frameCount:z112.int().min(1).max(360),alpha:z112.literal("STRAIGHT_RGBA"),fullDecode:z112.literal(true),frames:z112.array(z112.strictObject({ordinal:z112.int().min(0).max(359),checksumSha256:z112.string().regex(/^[0-9a-f]{64}$/),byteSize:z112.int().min(1).max(16777216)})).min(1).max(360)}).superRefine((value2,context)=>{if(value2.frames.length!==value2.frameCount||value2.frames.some((f,i)=>f.ordinal!==i)||value2.width*value2.height>1920*1080||value2.width*value2.height*value2.frameCount*4>536870912||value2.frames.reduce((n,f)=>n+f.byteSize,0)>67108864)context.addIssue({code:"custom",message:"CODE frame order/geometry/byte budget mismatch"})});var CompositionFrameRenderOutputSchema=z112.strictObject({sequence:VisualFrameSequenceSchema,technical:CompositionFrameTechnicalSchema,resources:CompositionRenderResourcesSchema}).superRefine((output,context)=>{if(output.sequence.width!==output.technical.width||output.sequence.height!==output.technical.height||output.sequence.frameCount!==output.technical.frameCount||output.sequence.frames.some((frame2,i)=>frame2.ordinal!==output.technical.frames[i]?.ordinal||frame2.checksumSha256!==output.technical.frames[i]?.checksumSha256||frame2.byteSize!==output.technical.frames[i]?.byteSize))context.addIssue({code:"custom",message:"CODE frame output must identify the exact native sequence"})});var CompositionRenderManifestReaderSchema=z113.discriminatedUnion("schemaVersion",[CompositionRenderManifestSchema,CompositionFrameRenderManifestSchema]);var CompositionRenderViewSchema=z113.strictObject({sourceIdentity:z113.strictObject({tenantId:z113.uuid(),projectId:z113.uuid(),productionId:z113.uuid(),compositionId:z113.uuid(),versionId:z113.uuid(),fingerprint:z113.string().regex(/^[0-9a-f]{64}$/),shotId:z113.uuid().nullable(),role:z113.enum(["PRIMARY_VISUAL","VISUAL_LAYER"])}).optional(),frameOutput:CompositionFrameRenderOutputSchema.optional(),receipt:CompositionRenderReceiptSchema,lifecycle:z113.string().min(1).max(80),cancellationRequested:z113.boolean(),failureClassification:z113.string().min(1).max(80).nullable(),output:z113.strictObject({artifactId:z113.uuid(),representationId:z113.uuid(),technical:CompositionRenderTechnicalSchema,resources:CompositionRenderResourcesSchema}).nullable()}).superRefine((view,context)=>{if(view.sourceIdentity&&view.sourceIdentity.versionId!==view.receipt.compositionVersionId)context.addIssue({code:"custom",message:"Render source identity must bind the admitted exact version"});if(view.frameOutput&&view.output!==null)context.addIssue({code:"custom",message:"CODE frame output must match its render Production and exclude an MP4 output"})});var CompositionRenderCancellationSchema=z113.strictObject({cancellationRequested:z113.boolean()});var identity2=z114.strictObject({artifactId:LocalIdSchema,representationId:LocalIdSchema});var ProcessorCompositionAllocationSchema=z114.strictObject({sequence:identity2,frames:z114.array(identity2).min(1).max(360)}).refine(({sequence,frames})=>{const entries=[sequence,...frames];return new Set(entries.map(entry=>entry.artifactId)).size===entries.length&&new Set(entries.map(entry=>entry.representationId)).size===entries.length});var processorCompositionFields={manifest:CompositionRenderManifestReaderSchema,allocation:ProcessorCompositionAllocationSchema.nullable()};var base={processor:z114.literal("COMPOSITION_RENDER"),resources:CompositionRenderResourcesSchema};var ProcessorCompositionVideoEvidenceSchema=z114.strictObject({...base,format:z114.literal("MP4"),technical:CompositionRenderTechnicalSchema});var ProcessorCompositionSequenceEvidenceSchema=z114.strictObject({...base,format:z114.literal("RGBA_SEQUENCE"),technical:CompositionFrameTechnicalSchema,sequence:VisualFrameSequenceSchema});var ProcessorCompositionEvidenceSchema=z114.discriminatedUnion("format",[ProcessorCompositionVideoEvidenceSchema,ProcessorCompositionSequenceEvidenceSchema]);import{z as z118}from"zod";import{z as z115}from"zod";var VisualSequenceScopeSchema=z115.strictObject({tenantId:TenantIdSchema,projectId:ProjectIdSchema});var RegisterVisualSequenceSchema=VisualSequenceScopeSchema.extend({deviceId:z115.uuid().toLowerCase().optional(),productionId:ProductionIdSchema.nullable(),idempotencyKey:z115.string().trim().min(1).max(200),width:z115.int().min(1).max(1920),height:z115.int().min(1).max(1920),frameArtifactIds:z115.array(ArtifactIdSchema).min(1).max(360)}).refine(v=>v.width*v.height<=1920*1080&&new Set(v.frameArtifactIds).size===v.frameArtifactIds.length,"Sequence requires bounded geometry and unique ordered frame Artifacts");var VisualSequenceGetSchema=VisualSequenceScopeSchema.extend({artifactId:ArtifactIdSchema});var LegacyVisualSequenceRegistrationSchema=z115.strictObject(RegisterVisualSequenceSchema.shape).omit({deviceId:true}).refine(input=>RegisterVisualSequenceSchema.safeParse(input).success);var VisualSequenceRegistrationAdmissionSchema=z115.strictObject({semanticStatus:z115.literal("ACCEPTED"),requestId:z115.uuid(),runtimeJobId:z115.uuid(),runtimeProductionId:ProductionIdSchema,operationId:OperationIdSchema,artifactId:ArtifactIdSchema,representationId:z115.uuid()});var VisualSequenceViewSchema=z115.strictObject({sequence:VisualFrameSequenceSchema,freshness:z115.enum(["CURRENT_BASIS","STALE_BASIS"]),staleReasons:z115.array(z115.enum(["SEQUENCE_UNAVAILABLE","FRAME_UNAVAILABLE"])).max(2),createdAt:z115.iso.datetime({offset:true})});var VisualSequenceQuerySchema=VisualSequenceScopeSchema.extend({limit:QueryLimitSchema,next:ContinuationSchema.optional()});var VisualSequencePageSchema=z115.strictObject({items:z115.array(VisualSequenceViewSchema).max(100),page:QueryPageInfoSchema});var{checksumSha256:_checksum,...manifestShape}=VisualFrameSequenceSchema.shape;var VisualSequenceManifestSchema=z115.strictObject(manifestShape).superRefine((value2,context)=>{if(!VisualFrameSequenceSchema.safeParse({...value2,checksumSha256:"0".repeat(64)}).success)context.addIssue({code:"custom",message:"Invalid canonical frame sequence manifest"})});import{z as z116}from"zod";var TranscribeAudioRecipeSchema=z116.strictObject({processor:z116.literal("TRANSCRIBE_AUDIO"),source:ObservationSourceSchema.extend({contentType:z116.literal("audio/wav")}),identity:LocalWhisperIdentitySchema});var TranscribeAudioEvidenceSchema=z116.strictObject({processor:z116.literal("TRANSCRIBE_AUDIO"),identity:LocalWhisperIdentitySchema,transcript:TranscriptSchema.refine(transcript=>transcript.timing==="UNAVAILABLE"),inputPcmSha256:LocalDigestSchema,inputPcmByteSize:z116.int().min(44).max(1920044)});var QwenAsrRecipeSchema=z116.strictObject({processor:z116.literal("TRANSCRIBE_EXTERNAL_QWEN"),observationId:LocalIdSchema,quoteFingerprint:LocalDigestSchema,credential:QwenDeviceCredentialIdentitySchema,source:TranscribeAudioRecipeSchema.shape.source,parameters:z116.strictObject({context:z116.string().max(2e3).refine(value2=>!value2.includes("\0")).optional(),language:z116.string().regex(/^[a-zA-Z][a-zA-Z0-9-]{1,19}$/).optional(),enable_itn:z116.boolean().optional()})});var asrTokens=z116.int().min(0).max(1e7).optional();var QwenAsrEvidenceSchema=z116.strictObject({processor:z116.literal("TRANSCRIBE_EXTERNAL_QWEN"),providerRequestId:z116.string().regex(/^[A-Za-z0-9_.:-]{1,500}$/),model:z116.literal("qwen3-asr-flash-2026-02-10"),usage:z116.strictObject({seconds:z116.int().min(0).max(60).optional(),prompt_tokens:asrTokens,completion_tokens:asrTokens,total_tokens:asrTokens}),transcript:TranscriptSchema.options[0]});import{z as z117}from"zod";var CpuSpeechRecipeSchema=CpuSpeechInputSchema.extend({processor:z117.literal("SPEECH_SYNTHESIZE_CPU"),identity:CpuSpeechIdentitySchema,voiceProfile:VoiceProfileUseSchema}).refine(v=>v.voiceProfile.language===v.language);var CpuSpeechEvidenceSchema=SpeechSynthesisEvidenceSchema.extend({processor:z117.literal("SPEECH_SYNTHESIZE_CPU"),sourceMedia:z117.strictObject({sampleRateHz:z117.literal(24e3),audioChannels:z117.literal(1),sampleCount:z117.int().min(2400).max(144e4)})});var sourceReference=z118.strictObject({artifactId:LocalIdSchema,representationId:LocalIdSchema,byteSize:MediaObjectVersionSchema.shape.byteSize,checksumSha256:LocalDigestSchema,contentType:z118.string().min(1).max(100)});var source2=sourceReference.extend({contentType:z118.literal("video/mp4")});var ReferencePreviewRecipeSchema=z118.strictObject({processor:z118.literal("REFERENCE_PREVIEW"),briefVersionId:LocalIdSchema,source:sourceReference.extend({contentType:z118.enum(["image/png","image/jpeg","image/webp"]),byteSize:z118.int().positive().max(8*1024*1024)})});var normalize=z118.strictObject({processor:z118.literal("IMPORTED_VISUAL_NORMALIZE"),source:source2,request:ImportedVisualNormalizationRequestSchema}).refine(({request,source:source6})=>request.source.byteSize===source6.byteSize&&request.source.checksumSha256===source6.checksumSha256,"Original representation must match the normalization request");var audio=z118.strictObject({processor:z118.literal("SOURCE_SYNC_AUDIO"),source:source2,input:ImportedVisualSourceInputSchema,extraction:ImportedSynchronousAudioExtractionSchema}).refine(value2=>value2.source.checksumSha256===value2.input.checksumSha256&&value2.source.checksumSha256===value2.extraction.originalChecksumSha256&&value2.source.representationId===value2.extraction.originalRepresentationId&&value2.source.artifactId===value2.extraction.originalArtifactId&&value2.source.byteSize===value2.input.byteSize);var temporal=z118.strictObject({processor:z118.literal("TEMPORAL_SAMPLE"),source:source2,plan:TemporalSamplingPlanSchema}).refine(value2=>value2.source.checksumSha256===value2.plan.source.checksumSha256&&value2.source.representationId===value2.plan.source.representationId&&value2.source.artifactId===value2.plan.source.artifactId&&value2.source.byteSize===value2.plan.source.byteSize);var delivery=z118.strictObject({processor:z118.literal("DELIVERY_VALIDATE"),recipe:LocalMediaRecipeSchema.refine(value2=>value2.family==="FINAL_RENDER"),target:DeliveryTargetSchema.pick({representationId:true,checksumSha256:true,byteSize:true,artifactId:true}).extend({contentType:z118.literal("video/mp4")}),policy:z118.strictObject({requiredAudio:z118.boolean(),requiredCaptions:z118.boolean(),requiredGraphics:z118.boolean()}),engineVersion:z118.string().min(1).max(200),sources:z118.array(sourceReference).min(1).max(512),manifestBasisFingerprint:LocalDigestSchema}).refine(({sources,target:target3})=>new Set([target3.representationId,...sources.map(v=>v.representationId)]).size===sources.length+1);var composition=z118.strictObject({processor:z118.literal("COMPOSITION_RENDER"),...processorCompositionFields,sources:z118.array(sourceReference).min(1).max(64)}).refine(({manifest,allocation,sources})=>{const inputs=manifest.version.inputs;return(manifest.schemaVersion===1?allocation===null:allocation?.frames.length===manifest.frameCount)&&new Set(inputs.map(input=>input.representationId)).size===sources.length&&new Set(sources.map(source6=>source6.representationId)).size===sources.length&&inputs.every(input=>sources.some(source6=>source6.representationId===input.representationId&&source6.artifactId===input.artifactId&&source6.checksumSha256===input.checksumSha256&&source6.byteSize===input.byteSize&&source6.contentType===input.contentType))});var directOriginal=z118.strictObject({processor:z118.literal("IMPORT_ORIGINAL"),command:DirectOriginalCommandSchema,object:MediaObjectVersionSchema.extend({role:z118.literal("SOURCE")})}).refine(({command:{input},object})=>input.tenantId===object.tenantId&&input.projectId===object.projectId&&input.source.checksumSha256===object.checksumSha256&&input.source.byteSize===object.byteSize);var projectSource=z118.strictObject({processor:z118.literal("IMPORT_PROJECT_SOURCE"),metadata:SourceInputMetadataSchema.extend({idempotencyKey:z118.string().trim().min(1).max(200)}),projectId:LocalIdSchema,object:MediaObjectVersionSchema.extend({role:z118.literal("SOURCE")})}).refine(({metadata,projectId,object})=>metadata.tenantId===object.tenantId&&projectId===object.projectId&&object.byteSize<=8*1024*1024&&(metadata.kind==="REFERENCE_VIDEO"?metadata.contentType==="video/mp4":metadata.kind==="REFERENCE_IMAGE"&&["image/png","image/jpeg","image/webp"].includes(metadata.contentType)));var visualSequence=z118.strictObject({processor:z118.literal("REGISTER_VISUAL_SEQUENCE"),input:RegisterVisualSequenceSchema,manifest:VisualSequenceManifestSchema,sources:z118.array(sourceReference).min(1).max(360)}).refine(({input,manifest,sources})=>input.tenantId===manifest.tenantId&&input.projectId===manifest.projectId&&input.productionId===manifest.productionId&&new Set(sources.map(source6=>source6.representationId)).size===sources.length&&manifest.frames.every(frame2=>sources.some(source6=>source6.artifactId===frame2.artifactId&&source6.representationId===frame2.representationId&&source6.byteSize===frame2.byteSize&&source6.checksumSha256===frame2.checksumSha256&&source6.contentType==="image/png")));var TenantProcessorRecipeSchema=z118.discriminatedUnion("processor",[normalize,audio,temporal,delivery,composition,directOriginal,projectSource,ReferencePreviewRecipeSchema,LocalLibraryInspectRecipeSchema,LocalLibraryPublishRecipeSchema,visualSequence,SpeechSynthesisRecipeSchema,CpuSpeechRecipeSchema,QwenSpeechRecipeSchema,TranscribeAudioRecipeSchema,QwenAsrRecipeSchema,QwenKeyframeRecipeSchema,QwenVideoRecipeSchema]);var TenantProcessorWorkSchema=TenantMediaWorkSchema.omit({audioRequired:true,renderProfileDigest:true}).extend({protocol:z119.literal("NVS_TENANT_PROCESSOR_V1"),family:z119.enum(["ARTIFACT_INGEST","PLANNING_MATERIALIZE","TEMPORAL_SAMPLE","DELIVERY_VALIDATE","COMPOSITION_RENDER","AUDIO_GENERATE","OBSERVE","KEYFRAME_GENERATE","VIDEO_GENERATE"]),processor:TenantProcessorKindSchema,recipeFingerprint:LocalDigestSchema,toolchainFingerprint:LocalDigestSchema,externalGeneration:ExternalGenerationReservationMarkerSchema.optional()}).refine(value2=>processorFamilies[value2.processor]===value2.family&&(value2.processor==="KEYFRAME_GENERATE"||value2.processor==="VIDEO_GENERATE")===!!value2.externalGeneration);var TenantComputeWorkSchema=z119.discriminatedUnion("protocol",[TenantMediaWorkSchema,TenantProcessorWorkSchema]);var importedNormalizationValidationProfile={processor:"IMPORTED_VISUAL_NORMALIZE",protocol:"NVS_TENANT_PROCESSOR_REPORT_V1",inspection:"IMPORTED_MP4_AND_POSTER_READBACK_V1"};var ClaimTenantProcessorSchema=LocalProjectScopeSchema.extend({requestId:LocalIdSchema});var TenantProcessorAssignmentSchema=z119.strictObject({work:TenantProcessorWorkSchema,recipe:TenantProcessorRecipeSchema,lease:LocalExecutionLeaseSchema,toolchain:LocalToolchainSchema}).superRefine(({work,recipe,lease,toolchain},ctx)=>{const selected=work.processor==="SPEECH_SYNTHESIZE_CPU"?processorToolchain(toolchain,work.processor):toolchain;if(!selected||toolchain.profile.kind==="AUDIO_MEDIA_V1"&&work.processor!=="SPEECH_SYNTHESIZE_CPU"||canonicalLocalJson(selected)!==canonicalLocalJson(toolchain))ctx.addIssue({code:"custom",message:"Exact processor media profile required"});const target3=lease.target;if((recipe.processor==="LOCAL_MEDIA_INSPECT"||recipe.processor==="LOCAL_MEDIA_PUBLISH")&&(recipe.reference.tenantId!==work.tenantId||recipe.reference.projectId!==work.projectId||recipe.reference.deviceId!==work.target.deviceId||recipe.processor==="LOCAL_MEDIA_PUBLISH"&&recipe.destination.kind==="ORIGINAL"&&recipe.destination.command.input.productionId.toLowerCase()!==work.productionId))ctx.addIssue({code:"custom",message:"Local file reference must match native target and scope"});if(recipe.processor!==work.processor||lease.tenantId!==work.tenantId||lease.projectId!==work.projectId||lease.productionId!==work.productionId||lease.runtimeJobId!==work.runtimeJobId||lease.toolchainFingerprint!==work.toolchainFingerprint||target3.kind!=="DEVICE"||!sameDeviceAuthority(target3,work.target))ctx.addIssue({code:"custom",message:"Assignment must match the frozen device work"})});var TenantProcessorClaimReceiptSchema=z119.strictObject({found:z119.boolean(),assignment:TenantProcessorAssignmentSchema.nullable()});var StageTenantProcessorOutputSchema=LocalLeaseBindingSchema.extend({requestId:LocalIdSchema,role:z119.enum(["VIDEO","POSTER","AUDIO","FRAME","SHEET","MANIFEST"]),ordinal:z119.int().nonnegative().max(359).default(0),checksumSha256:LocalDigestSchema,byteSize:MediaObjectVersionSchema.shape.byteSize});var PrepareTenantProcessorReportSchema=LocalLeaseBindingSchema.extend({requestId:LocalIdSchema,outputVersionIds:z119.array(LocalIdSchema).max(362).refine(ids=>ids.length===new Set(ids).size)});var TenantProcessorReportRequestSchema=LocalLeaseBindingSchema.extend({requestId:LocalIdSchema,validationRequestId:LocalIdSchema,work:TenantProcessorWorkSchema,outputs:z119.array(MediaObjectVersionSchema).max(362)});var poster=z119.strictObject({checksumSha256:LocalDigestSchema,byteSize:z119.int().min(1).max(2*1024*1024),width:z119.int().min(1).max(320),height:z119.int().min(1).max(320)});var TenantProcessorEvidenceSchema=z119.discriminatedUnion("processor",[LocalLibraryInspectEvidenceSchema,LocalLibraryPublishEvidenceSchema,z119.strictObject({processor:z119.literal("IMPORTED_VISUAL_NORMALIZE"),receipt:ImportedVisualNormalizationReceiptSchema,posterEvidence:poster}),z119.strictObject({processor:z119.literal("SOURCE_SYNC_AUDIO"),provenance:ImportedSynchronousAudioSourceSchema}),z119.strictObject({processor:z119.literal("TEMPORAL_SAMPLE"),manifest:TemporalEvidenceManifestSchema}),z119.strictObject({processor:z119.literal("DELIVERY_VALIDATE"),checks:DeliveryPhysicalChecksSchema,technical:FinalRenderTechnicalSchema.nullable()}),ProcessorCompositionEvidenceSchema,SpeechSynthesisEvidenceSchema,CpuSpeechEvidenceSchema,QwenSpeechEvidenceSchema,TranscribeAudioEvidenceSchema,QwenAsrEvidenceSchema,QwenKeyframeEvidenceSchema,QwenVideoEvidenceSchema,z119.strictObject({processor:z119.literal("REFERENCE_PREVIEW"),image:z119.strictObject({checksumSha256:LocalDigestSchema,byteSize:z119.int().positive().max(referenceThumbnailProfile.maxBytes),width:z119.int().positive().max(referenceThumbnailProfile.maxDimension),height:z119.int().positive().max(referenceThumbnailProfile.maxDimension)})}),z119.strictObject({processor:z119.literal("IMPORT_ORIGINAL"),metadata:ImportedVisualSourceMetadataSchema}),z119.strictObject({processor:z119.literal("IMPORT_PROJECT_SOURCE"),validated:z119.strictObject({checksumSha256:LocalDigestSchema,byteSize:z119.int().positive().max(8*1024*1024),width:z119.int().positive().max(4096),height:z119.int().positive().max(4096),video:ImportedVisualSourceMetadataSchema.optional()})}),z119.strictObject({processor:z119.literal("REGISTER_VISUAL_SEQUENCE"),evidence:z119.strictObject({checksumSha256:VisualFrameSequenceSchema.shape.checksumSha256,width:VisualFrameSequenceSchema.shape.width,height:VisualFrameSequenceSchema.shape.height,frames:VisualFrameSequenceSchema.shape.frames,byteSize:z119.int().positive().max(2*1024*1024)})})]);var TenantProcessorReportBodySchema=TenantProcessorReportRequestSchema.extend({schemaVersion:z119.literal(1),evidence:TenantProcessorEvidenceSchema}).superRefine(({work,outputs,evidence:evidence2,...binding},ctx)=>{if(work.tenantId!==binding.tenantId||work.projectId!==binding.projectId||work.productionId!==binding.productionId||work.runtimeJobId!==binding.runtimeJobId||work.toolchainFingerprint!==binding.toolchainFingerprint||evidence2.processor!==work.processor||new Set(outputs.map(value2=>value2.versionId)).size!==outputs.length||outputs.some(object=>object.tenantId!==work.tenantId||object.projectId!==work.projectId)||!matchesEvidence(outputs,evidence2))ctx.addIssue({code:"custom",message:"Report must bind the exact processor and committed media versions"})});function matchesEvidence(outputs,evidence2){const matches=(index,role,expected)=>{const output=outputs[index];return output?.role===role&&output.checksumSha256===expected.checksumSha256&&output.byteSize===expected.byteSize};switch(evidence2.processor){case"REFERENCE_PREVIEW":return outputs.length===1&&matches(0,"POSTER",evidence2.image);case"IMPORTED_VISUAL_NORMALIZE":return outputs.length===2&&matches(0,"VIDEO",evidence2.receipt.output)&&matches(1,"POSTER",evidence2.posterEvidence);case"SOURCE_SYNC_AUDIO":return outputs.length===1&&matches(0,"AUDIO",{checksumSha256:evidence2.provenance.wavChecksumSha256,byteSize:evidence2.provenance.wavByteSize});case"SPEECH_SYNTHESIZE":case"SPEECH_SYNTHESIZE_CPU":case"SPEECH_EXTERNAL_QWEN":return outputs.length===2&&matches(0,"AUDIO",evidence2.source)&&matches(1,"AUDIO",evidence2.normalized);case"TEMPORAL_SAMPLE":{const frames=evidence2.manifest.frames;return outputs.length===frames.length+2&&frames.every((value2,index)=>matches(index,"FRAME",value2))&&matches(frames.length,"SHEET",evidence2.manifest.sheet)&&outputs.at(-1)?.role==="MANIFEST"}case"DELIVERY_VALIDATE":case"TRANSCRIBE_AUDIO":case"TRANSCRIBE_EXTERNAL_QWEN":case"LOCAL_MEDIA_INSPECT":case"LOCAL_MEDIA_PUBLISH":case"IMPORT_ORIGINAL":case"IMPORT_PROJECT_SOURCE":return outputs.length===0;case"REGISTER_VISUAL_SEQUENCE":return outputs.length===1&&matches(0,"MANIFEST",evidence2.evidence);case"KEYFRAME_GENERATE":return outputs.length===1&&matches(0,"FRAME",evidence2.image);case"VIDEO_GENERATE":return outputs.length===2&&matches(0,"VIDEO",evidence2.video)&&matches(1,"POSTER",evidence2.poster);case"COMPOSITION_RENDER":if(evidence2.format==="MP4")return outputs.length===1&&matches(0,"VIDEO",evidence2.technical);return outputs.length===evidence2.technical.frames.length+1&&evidence2.technical.frames.every((value2,index)=>matches(index,"FRAME",value2))&&outputs.at(-1)?.role==="MANIFEST"&&outputs.at(-1)?.checksumSha256===evidence2.sequence.checksumSha256}}var TenantProcessorReportSchema=TenantProcessorReportBodySchema.safeExtend({reportFingerprint:LocalDigestSchema,signature:z119.string().regex(/^[A-Za-z0-9_-]{86}$/)});var TenantProcessorReceiptQuerySchema=LocalLeaseBindingSchema.extend({requestId:LocalIdSchema});var TenantProcessorStateSchema=z119.strictObject({binding:LocalLeaseBindingSchema,state:z119.enum(["FENCED","PENDING"])});var TenantProcessorFailureSchema=LocalLeaseBindingSchema.extend({code:z119.literal("INVALID_SOURCE")});var TenantProcessorProviderOutcomeSchema=LocalLeaseBindingSchema.extend({outcome:z119.enum(["UNKNOWN","REJECTED","WAITING","INVALID_RESULT"]),providerExecutionId:QwenVideoTaskIdSchema.optional()}).refine(value2=>!["WAITING","INVALID_RESULT"].includes(value2.outcome)||!!value2.providerExecutionId);var TenantProcessorProviderTaskSchema=LocalLeaseBindingSchema.extend({providerExecutionId:QwenVideoTaskIdSchema.optional()});var TenantProcessorInvalidSpeechSchema=LocalLeaseBindingSchema.extend(QwenSpeechEvidenceSchema.pick({providerRequestId:true,audioId:true}).shape);var TenantProcessorReceiptSchema=TenantProcessorReceiptQuerySchema.extend({operationId:TenantProcessorWorkSchema.shape.operationId,reportFingerprint:LocalDigestSchema,result:z119.union([z119.strictObject({sourceArtifactId:LocalIdSchema,representationId:LocalIdSchema,reusedExisting:z119.boolean()}),z119.strictObject({localMediaInspectionId:LocalIdSchema}),z119.strictObject({normalizationId:LocalIdSchema,artifactId:LocalIdSchema,representationId:LocalIdSchema,posterArtifactId:LocalIdSchema,posterRepresentationId:LocalIdSchema}),SourceSyncAudioReceiptSchema,z119.strictObject({generationId:LocalIdSchema,audio:AudioReceiptSchema}),z119.strictObject({observationId:LocalIdSchema}),z119.strictObject({generationId:LocalIdSchema,candidateId:LocalIdSchema,artifactId:LocalIdSchema,representationId:LocalIdSchema}),z119.strictObject({evidenceId:LocalIdSchema,frameSetArtifactId:LocalIdSchema,contactSheetArtifactId:LocalIdSchema}),z119.strictObject({deliveryValidationId:LocalIdSchema,reviewId:LocalIdSchema}),z119.strictObject({renderId:LocalIdSchema,artifactId:LocalIdSchema,representationId:LocalIdSchema}),ImportedVisualOriginalViewSchema,ReadyArtifactRegistrationSchema,z119.strictObject({requestId:LocalIdSchema,artifactId:LocalIdSchema,representationId:LocalIdSchema})])});import{z as z120}from"zod";var LocalLibraryCommandStatusSchema=z120.strictObject({admission:LocalLibraryAdmissionSchema,lifecycle:z120.enum(["READY","WAITING","RUNNING","SUCCEEDED","FAILED","CANCELLED","SUPERSEDED"]),receipt:TenantProcessorReceiptSchema.nullable(),inspection:LocalLibraryInspectionSchema.nullable(),failureSummary:z120.string().max(500).nullable()}).superRefine(({admission,receipt},ctx)=>{if(receipt&&(receipt.tenantId!==admission.tenantId||receipt.projectId!==admission.projectId||receipt.productionId!==admission.productionId||receipt.runtimeJobId!==admission.runtimeJobId||receipt.operationId!==admission.operationId))ctx.addIssue({code:"custom",message:"Original native receipt must match admitted local file work"})});function abortable(promise,signal){if(signal.aborted){void promise.catch(()=>{});return Promise.reject(signal.reason)}return new Promise((resolve,reject)=>{const abort=()=>reject(signal.reason);signal.addEventListener("abort",abort,{once:true});promise.then(resolve,reject).finally(()=>signal.removeEventListener("abort",abort))})}async function boundedResponseBytes(response,limit,signal){const length=response.headers.get("content-length");if(length!==null&&(!/^\d+$/.test(length)||Number(length)>limit)){void response.body?.cancel().catch(()=>{});throw new NativeStudioSdkError("RESPONSE_TOO_LARGE","INTERNAL_OPERATIONAL_FAILURE","UNKNOWN")}if(!response.body)return new Uint8Array;const reader=response.body.getReader();const chunks=[];let size=0;try{while(true){const next=await abortable(reader.read(),signal);if(next.done)break;size+=next.value.byteLength;if(size>limit)throw new NativeStudioSdkError("RESPONSE_TOO_LARGE","INTERNAL_OPERATIONAL_FAILURE","UNKNOWN");chunks.push(next.value)}const result=new Uint8Array(size);let offset2=0;for(const chunk of chunks){result.set(chunk,offset2);offset2+=chunk.byteLength}return result}finally{void reader.cancel().catch(()=>{});reader.releaseLock()}}var failed=()=>new NativeStudioSdkError("MEDIA_IDENTITY_MISMATCH","INTERNAL_OPERATIONAL_FAILURE","NO_WRITE");async function downloadImmutableObject(ticket,options={}){const object=MediaObjectVersionSchema.parse(ticket.object),url=new URL(ticket.endpoint);if(ticket.method!=="GET"||url.pathname!==mediaObjectTransferPath||url.username||url.password||url.search||url.hash||url.protocol!=="https:"&&!(url.protocol==="http:"&&url.hostname==="127.0.0.1"))throw failed();const timeout=AbortSignal.timeout(12e4);const signal=options.signal?AbortSignal.any([options.signal,timeout]):timeout;try{const response=await fetch(url,{headers:{authorization:"Bearer "+ticket.credential},credentials:"omit",redirect:"error",signal});if(response.status!==200||response.headers.get("x-media-object-version")!==object.versionId||response.headers.get("x-content-sha256")!==object.checksumSha256||response.headers.get("content-length")!==String(object.byteSize)){await response.body?.cancel();throw failed()}const bytes=await boundedResponseBytes(response,object.byteSize,signal);if(bytes.byteLength!==object.byteSize||createHash("sha256").update(bytes).digest("hex")!==object.checksumSha256)throw failed();return{bytes,object}}catch{throw failed()}}async function downloadRenderObject(ticket,options){if(ticket.object.role==="SOURCE")throw failed();const result=await downloadImmutableObject(ticket,options);return{...result,contentType:result.object.role==="VIDEO"?"video/mp4":"image/png"}}import{z as z186}from"zod";import{z as z121}from"zod";var OperationTargetSchema=z121.object({type:z121.string().min(1).max(120),id:z121.string().min(1).max(2048),version:z121.int().positive().nullable()});var OperationFailureReasonSchema=z121.enum(["AMBIGUOUS","PERMANENT_OPERATIONAL","SEMANTIC","RATE_LIMIT","TRANSIENT","NOT_RECORDED"]);var productionScope=z121.strictObject({tenantId:TenantIdSchema,productionId:ProductionIdSchema});var OperationFailureSchema=z121.strictObject({reasonCodes:z121.array(OperationFailureReasonSchema).min(1).max(OperationFailureReasonSchema.options.length).refine(codes=>new Set(codes).size===codes.length),summary:z121.string().min(1).max(1e3),next:z121.discriminatedUnion("capability",[z121.strictObject({capability:z121.literal("operation.get"),input:productionScope.extend({operationId:OperationIdSchema})}),z121.strictObject({capability:z121.literal("production.snapshot"),input:productionScope})])});var OperationSummarySchema=z121.object({humanLinks:HumanLinksSchema.optional(),id:OperationIdSchema,productionId:ProductionIdSchema,semanticStatus:InterfaceSemanticStatusSchema,targets:z121.array(OperationTargetSchema).max(100),work:WorkSummarySchema,blockers:z121.array(z121.string().min(1).max(1e3)).max(100),failure:OperationFailureSchema.optional(),nextActions:z121.array(NextActionSchema).max(50),startedAt:z121.iso.datetime({offset:true}),updatedAt:z121.iso.datetime({offset:true})});import{z as z124}from"zod";import{z as z123}from"zod";import{z as z122}from"zod";var sha16=z122.string().regex(/^[0-9a-f]{64}$/);var DeliveryManifestBasisSchema=z122.strictObject({schemaVersion:z122.literal(1),evaluatorVersion:z122.literal("DELIVERY_V1"),target:DeliveryTargetSchema,policyVersionId:z122.uuid(),policyVersion:z122.int().positive(),policy:DeliveryPolicySchema,policyFingerprint:sha16,finalRenderRuntimeJobId:z122.uuid(),finalRenderManifest:FinalRenderManifestReaderSchema,finalRenderTechnical:FinalRenderTechnicalSchema,roughCutReview:RoughCutReviewRecordSchema,artifacts:z122.array(z122.strictObject({artifactId:z122.uuid(),family:z122.string().min(1).max(100),origin:z122.string().min(1).max(100),checksumSha256:sha16})).min(1).max(2e3),relations:z122.array(z122.strictObject({id:z122.uuid(),sourceArtifactId:z122.uuid(),targetArtifactId:z122.uuid(),relationType:z122.string().min(1).max(100)})).max(4e3)}).superRefine((basis,ctx)=>{const t=basis.target,m=basis.finalRenderManifest;if(t.selectionId!==m.selection.id||t.selectionVersion!==m.selectionVersion||t.timelineVersionId!==m.timeline.id||t.timelineFingerprint!==m.timeline.fingerprint||t.tenantId!==m.timeline.tenantId||t.projectId!==m.timeline.projectId||t.productionId!==m.timeline.productionId||t.executionClass!==m.timeline.executionClass||t.checksumSha256!==basis.finalRenderTechnical.checksumSha256||t.byteSize!==basis.finalRenderTechnical.byteSize||basis.finalRenderTechnical.hasAudio!==m.profile.hasAudio||basis.roughCutReview.id!==m.selection.reviewId||basis.roughCutReview.basisFingerprint!==m.selection.basisFingerprint||!basis.artifacts.some(a=>a.artifactId===t.artifactId&&a.checksumSha256===t.checksumSha256)||new Set(basis.artifacts.map(a=>a.artifactId)).size!==basis.artifacts.length||new Set(basis.relations.map(r=>r.id)).size!==basis.relations.length||basis.relations.some(r=>!basis.artifacts.some(a=>a.artifactId===r.sourceArtifactId)||!basis.artifacts.some(a=>a.artifactId===r.targetArtifactId)))ctx.addIssue({code:"custom",message:"Manifest must identify exact render, Review-2 and provenance"})});var ProductionDeliveryManifestSchema=DeliveryManifestBasisSchema.safeExtend({reviewId:z122.uuid(),productionRevision:z122.int().positive(),completedAt:z122.iso.datetime({offset:true})});var DeliveryManifestGetSchema=TimelineScopeSchema.extend({manifestId:z122.uuid()});var RegisteredDeliveryManifestSchema=z122.strictObject({link:DeliveryManifestLinkSchema,body:ProductionDeliveryManifestSchema}).refine(v=>v.link.reviewId===v.body.reviewId&&v.link.policyFingerprint===v.body.policyFingerprint&&Object.keys(DeliveryTargetSchema.shape).every(key10=>v.link.target[key10]===v.body.target[key10]),"Manifest registration must match exact body");var sha17=z123.string().regex(/^[0-9a-f]{64}$/);var mutation=TimelineScopeSchema.extend({expectedProductionRevision:z123.int().positive(),idempotencyKey:z123.string().trim().min(1).max(200)});var ConfigureDeliveryPolicySchema=mutation.extend({expectedPolicyVersion:z123.int().nonnegative(),policy:DeliveryPolicyInputSchema});var DeliveryPolicyVersionSchema=TimelineScopeSchema.extend({id:z123.uuid(),projectId:z123.uuid(),version:z123.int().positive(),policy:DeliveryPolicySchema,policyFingerprint:sha17,createdByPrincipalId:z123.uuid(),createdAt:z123.iso.datetime({offset:true})});var DeliveryPolicyReceiptSchema=z123.strictObject({policy:DeliveryPolicyVersionSchema,productionRevision:z123.int().positive()});var LegacyStartDeliveryValidationSchema=mutation.extend({target:DeliveryTargetSchema,expectedPolicyVersion:z123.int().nonnegative()}).refine(v=>v.target.tenantId===v.tenantId&&v.target.productionId===v.productionId,"Exact delivery target must match command scope");var StartDeliveryValidationSchema=LegacyStartDeliveryValidationSchema.safeExtend({deviceId:z123.uuid().toLowerCase().optional()});var DeliveryValidationGetSchema=TimelineScopeSchema.extend({validationId:z123.uuid()});var DecideDeliveryApprovalSchema=mutation.extend({validationId:z123.uuid(),reviewId:z123.uuid(),target:DeliveryTargetSchema,policyFingerprint:sha17,action:z123.enum(["APPROVE","REJECT"])}).refine(v=>v.target.tenantId===v.tenantId&&v.target.productionId===v.productionId,"Exact approval target must match command scope");var DeliveryAdmissionSchema=z123.strictObject({humanLinks:HumanLinksSchema.optional(),semanticStatus:z123.literal("ACCEPTED"),validationId:z123.uuid(),runtimeJobId:z123.uuid(),operationId:z123.string().min(1),target:DeliveryTargetSchema,policyVersionId:z123.uuid(),policyVersion:z123.int().positive(),policyFingerprint:sha17,manifestBasisFingerprint:sha17,evaluatorVersion:z123.literal("DELIVERY_V1"),productionRevision:z123.int().positive()});var DeliveryFindingSchema=z123.strictObject({id:z123.uuid(),reviewId:z123.uuid(),target:DeliveryTargetSchema,key:DeliveryCheckKeySchema,detail:z123.string().trim().min(1).max(1e3),blocking:z123.literal(true),createdAt:z123.iso.datetime({offset:true})});var DeliveryCompletionBlockerSchema=z123.enum(["VALIDATION_FAILED","EXACT_OUTPUT_CHANGED","DELIVERY_POLICY_CHANGED","FINAL_READY_STALE","ARTIFACT_UNAVAILABLE","PROVENANCE_INCOMPLETE","MANIFEST_NOT_REGISTERED","MANIFEST_BINDING_MISMATCH","BLOCKING_FINDINGS","TEST_EVIDENCE_DISABLED","APPROVAL_BINDING_MISMATCH","APPROVAL_REJECTED"]);var DeliveryReviewReceiptSchema=z123.strictObject({review:DeliveryValidationReviewSchema,action:z123.enum(["COMPLETE","WAITING_HUMAN","BLOCK"]),blockers:z123.array(DeliveryCompletionBlockerSchema).max(12),productionRevision:z123.int().positive()});var DeliveryDecisionReceiptSchema=z123.strictObject({humanLinks:HumanLinksSchema.optional(),approval:DeliveryApprovalSchema,finalDelivery:FinalDeliveryReceiptSchema.nullable(),productionRevision:z123.int().positive(),condition:z123.enum(["RUNNABLE","BLOCKED"])});var DeliveryValidationViewSchema=z123.strictObject({humanLinks:HumanLinksSchema.optional(),admission:DeliveryAdmissionSchema,policy:DeliveryPolicyVersionSchema,manifestBasis:DeliveryManifestBasisSchema,runtimeStatus:z123.enum(["PENDING","READY","RUNNING","WAITING","SUCCEEDED","FAILED","CANCELLED","SUPERSEDED"]),current:z123.boolean(),reviewReceipt:DeliveryReviewReceiptSchema.nullable(),findings:z123.array(DeliveryFindingSchema).max(16),approval:DeliveryApprovalSchema.nullable(),finalDelivery:FinalDeliveryReceiptSchema.nullable()});var DeliverySnapshotSchema=TimelineScopeSchema.extend({humanLinks:HumanLinksSchema.optional(),productionRevision:z123.int().positive(),policy:DeliveryPolicyVersionSchema.nullable(),currentValidationId:z123.uuid().nullable(),finalDelivery:FinalDeliveryReceiptSchema.nullable()});var DeliverySummarySchema=z124.strictObject({policy:DeliveryPolicyVersionSchema.nullable(),validation:z124.strictObject({id:z124.uuid(),runtimeStatus:DeliveryValidationViewSchema.shape.runtimeStatus,current:z124.boolean(),reviewId:z124.uuid().nullable(),result:z124.enum(["PASS","FAIL"]).nullable(),action:z124.enum(["COMPLETE","WAITING_HUMAN","BLOCK"]).nullable(),blockingChecks:z124.array(DeliveryCheckKeySchema).max(16),approvalAction:z124.enum(["APPROVE","REJECT"]).nullable()}).nullable(),finalDelivery:FinalDeliveryReceiptSchema.nullable()});import{z as z128}from"zod";import{z as z127}from"zod";import{z as z126}from"zod";import{z as z125}from"zod";var ShotSoundContentSchema=z125.strictObject({model:z125.strictObject({modelProfileId:z125.string().regex(/^[a-z][a-z0-9-]{1,79}$/),modelProfileVersion:z125.int().positive(),connectionId:z125.uuid()}).optional(),nativeAudio:z125.boolean(),cues:z125.array(z125.strictObject({id:z125.string().regex(/^[a-z][a-z0-9_-]{0,63}$/),role:z125.enum(["DIALOGUE","MUSIC","AMBIENCE","SOUND_EFFECT","NARRATION"]),startMs:z125.int().nonnegative().max(3e4),endMs:z125.int().positive().max(3e4),text:z125.string().trim().min(1).max(6e3).optional(),exactSpeech:z125.boolean(),lipSync:z125.enum(["REQUIRED","NONE"])}).refine(v=>v.endMs>v.startMs)).max(64)});var ShotSoundInstructionSchema=z125.strictObject({soundPlanVersionId:z125.uuid().toLowerCase(),fingerprint:z125.string().regex(/^[0-9a-f]{64}$/),content:ShotSoundContentSchema});var GenerationContractSchema=z126.strictObject({id:GenerationContractIdSchema,schemaVersion:z126.literal(1),preparationId:PreparationIdSchema,target:PreparationTargetSchema,basis:PreparationBasisSchema,mode:z126.enum(["REFERENCE_TO_IMAGE","REFERENCE_TO_VIDEO","FIRST_FRAME_TO_VIDEO","FIRST_LAST_FRAME_TO_VIDEO"]),creativeInstruction:z126.strictObject({sound:ShotSoundInstructionSchema.optional(),shot:ShotIntentSchema,scenePurpose:z126.string().min(1).max(800),locationContext:z126.string().max(300).optional(),timeContext:z126.string().max(300).optional(),productPresentationGoal:z126.string().min(1).max(1e3),styleTone:z126.string().max(300).optional(),entryBoundary:z126.array(BoundaryRequirementSchema).max(48),exitBoundary:z126.array(BoundaryRequirementSchema).max(48)}),acceptedShotReferences:z126.array(AcceptedVisualSourceReferenceSchema).max(24).default([]),constraintSetFingerprint:ContentFingerprintSchema,referenceSetFingerprint:ContentFingerprintSchema,output:z126.strictObject({aspectRatio:z126.enum(["16:9","9:16"]),targetDurationSeconds:z126.number().min(.5).max(30).nullable(),workingResolution:z126.null(),frameRate:z126.null(),finalDeliveryProfile:DeliveryOutputProfileSchema}),requiredCapabilities:z126.strictObject({referenceConditioning:z126.literal(true),referenceRoles:z126.array(ReferenceRoleSchema).min(1).max(8),startFrameControl:z126.boolean(),endFrameControl:z126.boolean(),nativeAudio:z126.boolean().optional()}),fingerprint:ContentFingerprintSchema}).superRefine((value2,context)=>{const invalid=message=>context.addIssue({code:"custom",message});if(value2.target.mediaType==="IMAGE"&&value2.acceptedShotReferences.length)invalid("Image generation cannot depend on accepted video Shots");if(value2.target.mediaType==="IMAGE"&&(value2.mode!=="REFERENCE_TO_IMAGE"||value2.output.targetDurationSeconds!==null||value2.requiredCapabilities.startFrameControl||value2.requiredCapabilities.endFrameControl))invalid("Image generation cannot claim video duration or frame-control semantics");if(value2.target.mediaType==="VIDEO"&&(value2.mode==="REFERENCE_TO_IMAGE"||value2.output.targetDurationSeconds===null))invalid("Video generation requires video mode and duration");const roles=value2.requiredCapabilities.referenceRoles;if(!roles.some(role=>role==="PRODUCT_IDENTITY"||role==="PRODUCT_PACKSHOT"))invalid("Product identity requires concrete reference conditioning");if(value2.requiredCapabilities.startFrameControl&&!roles.includes("START_FRAME_ANCHOR"))invalid("Start-frame control requires an exact anchor role");if(value2.requiredCapabilities.endFrameControl&&!roles.includes("END_FRAME_ANCHOR"))invalid("End-frame control requires an exact anchor role");if(value2.mode==="FIRST_LAST_FRAME_TO_VIDEO"&&(!value2.requiredCapabilities.startFrameControl||!value2.requiredCapabilities.endFrameControl))invalid("First/last mode requires both anchor capabilities")});var PrepareShotRequestSchema=z127.strictObject({tenantId:TenantIdSchema,expectedProductionRevision:z127.int().positive(),expectedPlanVersionId:SceneShotPlanVersionIdSchema,expectedPlanVersion:z127.int().positive(),expectedShotPlanningRevision:z127.int().positive(),expectedPreparationVersion:z127.int().nonnegative(),idempotencyKey:z127.string().trim().min(1).max(200),target:PreparationTargetSchema,referenceBindings:z127.array(ReferenceBindingInputSchema).max(12).default([])});var PreparationVersionSchema=z127.strictObject({id:PreparationIdSchema,version:z127.int().positive(),basis:PreparationBasisSchema,target:PreparationTargetSchema,constraints:ConstraintSetSchema,referenceSet:ReferenceSetSchema,canonicalSources:z127.array(ExactEvidenceReferenceSchema).max(64),acceptedShotReferences:z127.array(AcceptedVisualSourceReferenceSchema).max(24).default([]),blockers:z127.array(PreparationBlockerSchema).max(2048),contract:GenerationContractSchema.nullable(),createdByPrincipalId:PrincipalIdSchema,createdAt:z127.iso.datetime({offset:true})}).superRefine((value2,context)=>{const invalid=message=>context.addIssue({code:"custom",message});if(value2.constraints.preparationId!==value2.id||value2.referenceSet.preparationId!==value2.id||value2.constraints.version!==value2.version||value2.referenceSet.version!==value2.version)invalid("Resolved snapshot identity must match preparation");if(value2.contract!==null!==(value2.blockers.length===0))invalid("A preparation contract exists only for an unblocked preflight");if(value2.contract&&(value2.contract.preparationId!==value2.id||JSON.stringify(value2.contract.basis)!==JSON.stringify(value2.basis)||JSON.stringify(value2.contract.target)!==JSON.stringify(value2.target)||value2.contract.constraintSetFingerprint!==value2.constraints.fingerprint||value2.contract.referenceSetFingerprint!==value2.referenceSet.fingerprint||JSON.stringify(value2.contract.acceptedShotReferences)!==JSON.stringify(value2.acceptedShotReferences)))invalid("Generation Contract must freeze the exact preparation basis and snapshots")});var PrepareShotResultSchema=z127.strictObject({semanticStatus:z127.literal("SUCCESS"),preparation:PreparationVersionSchema,productionRevision:z127.int().positive()});var PreparationViewSchema=z127.strictObject({preparation:PreparationVersionSchema,freshness:z127.enum(["CURRENT_BASIS","STALE_BASIS"]),superseded:z127.boolean(),freshnessReasons:z127.array(z127.enum(["PLAN_CHANGED","SHOT_CHANGED","REFERENCE_UNAVAILABLE","CONSISTENCY_PROFILE_CHANGED","SOUND_PLAN_CHANGED","SUPERSEDED","KEYFRAME_SELECTION_CHANGED","PREDECESSOR_ACCEPTANCE_CHANGED"])).max(8),execution:z127.strictObject({eligibleVideoSelections:z127.array(ProviderSelectionSchema).max(1600).optional(),available:z127.boolean(),reasons:z127.array(z127.enum(["STALE_BASIS","PREPARATION_BLOCKED","PRODUCTION_NOT_RUNNABLE","PROVIDER_CAPABILITY_UNAVAILABLE","VIDEO_SELECTION_REQUIRED"])).min(0).max(4)})});var PreparationQueryInputSchema=z127.strictObject({tenantId:TenantIdSchema,productionId:ProductionIdSchema,shotId:ShotIdSchema.optional(),mediaType:z127.enum(["IMAGE","VIDEO"]).optional(),limit:QueryLimitSchema,next:ContinuationSchema.optional()});var PreparationQueryPageSchema=z127.strictObject({items:z127.array(PreparationViewSchema),page:QueryPageInfoSchema});var PreparationGetInputSchema=z127.strictObject({tenantId:TenantIdSchema,productionId:ProductionIdSchema,preparationId:PreparationIdSchema});var PreparationActiveInputSchema=z127.strictObject({tenantId:TenantIdSchema,productionId:ProductionIdSchema,shotId:ShotIdSchema,mediaType:z127.enum(["IMAGE","VIDEO"])});var PreparationSummarySchema=z127.strictObject({latest:z127.int().nonnegative(),current:z127.int().nonnegative(),stale:z127.int().nonnegative(),contractValid:z127.int().nonnegative(),preflightBlocked:z127.int().nonnegative(),executionAvailable:z127.int().nonnegative()});var NullableVersionSchema=z128.int().positive().nullable();var ProductionBlockerSchema=z128.object({code:z128.string().min(1).max(120),summary:z128.string().min(1).max(1e3),targetType:z128.string().min(1).max(80),targetId:z128.string().min(1).max(2048)});var ProductionSnapshotSchema=z128.object({humanLinks:HumanLinksSchema.optional(),tenantId:TenantIdSchema,projectId:ProjectIdSchema,productionId:ProductionIdSchema,state:ProductionStateSchema,planning:z128.object({activeBriefVersion:NullableVersionSchema,activeStoryVersion:NullableVersionSchema,activeSceneShotPlanVersion:NullableVersionSchema}),preparation:PreparationSummarySchema.optional(),keyframes:KeyframeSummarySchema.optional(),keyframeReview:KeyframeReviewSummarySchema.optional(),videos:VideoSummarySchema.optional(),captions:CaptionSnapshotSchema.optional(),audio:AudioSnapshotSchema.optional(),shots:z128.object({planned:z128.int().nonnegative(),ready:z128.int().nonnegative(),generating:z128.int().nonnegative(),candidates:z128.int().nonnegative(),accepted:z128.int().nonnegative(),blocked:z128.int().nonnegative(),stale:z128.int().nonnegative()}),findings:z128.object({open:z128.int().nonnegative(),blocking:z128.int().nonnegative(),warnings:z128.int().nonnegative()}),timeline:z128.object({currentVersion:NullableVersionSchema,stale:z128.boolean(),...TimelineSnapshotSchema.omit({currentVersion:true,stale:true}).partial().shape}),roughCut:RoughCutSnapshotSchema.partial().required({latestVersion:true,reviewState:true}),review2:RoughCutReviewSnapshotSchema.optional(),final:z128.object({ready:FinalReadyViewSchema.optional(),render:FinalRenderSnapshotSchema.optional(),renderState:z128.string().min(1).max(120).nullable(),delivery:DeliverySummarySchema.optional(),deliveryValidationState:z128.string().min(1).max(120).nullable()}),work:WorkSummarySchema,activeOperations:z128.array(OperationSummarySchema).max(20),blockers:z128.array(ProductionBlockerSchema).max(100),latestDecisions:z128.array(z128.string().min(1).max(1e3)).max(50),nextActions:z128.array(NextActionSchema).max(50),generatedAt:z128.iso.datetime({offset:true})});import{z as z129}from"zod";var ProductionQueryInputSchema=z129.object({tenantId:TenantIdSchema,projectId:ProjectIdSchema.optional(),search:z129.string().trim().min(1).max(200).optional(),attention:z129.enum(["NEEDS_YOU","WORKING","FINISHED"]).optional(),limit:QueryLimitSchema,next:ContinuationSchema.optional()});var ProductionQueryPageSchema=z129.object({items:z129.array(ProductionSchema),page:QueryPageInfoSchema});var OperationQueryInputSchema=z129.object({tenantId:TenantIdSchema,productionId:ProductionIdSchema,limit:QueryLimitSchema,next:ContinuationSchema.optional()});var OperationQueryPageSchema=z129.object({items:z129.array(OperationSummarySchema),page:QueryPageInfoSchema});var StoryQueryInputSchema=z129.object({tenantId:TenantIdSchema,productionId:ProductionIdSchema,limit:QueryLimitSchema,next:ContinuationSchema.optional()});var StoryQueryPageSchema=z129.object({items:z129.array(StoryVersionSchema),page:QueryPageInfoSchema});var SceneShotPlanQueryInputSchema=z129.object({tenantId:TenantIdSchema,productionId:ProductionIdSchema,limit:QueryLimitSchema,next:ContinuationSchema.optional()});var SceneShotPlanQueryPageSchema=z129.object({items:z129.array(SceneShotPlanVersionSchema),page:QueryPageInfoSchema});import{z as z130}from"zod";var InterfaceCancellationDataSchema=z130.strictObject({cancellationAccepted:z130.boolean()});var InterfaceCancellationReceiptSchema=InterfaceCancellationDataSchema.extend({semanticStatus:z130.literal("SUCCESS")});import{z as z131}from"zod";var id9=z131.uuid();var sha18=z131.string().regex(/^[0-9a-f]{64}$/);var AgentHostExecutionScopeSchema=z131.strictObject({tenantId:id9,projectId:id9,productionId:id9});var StartAgentHostExecutionSchema=AgentHostExecutionScopeSchema.extend({requestId:id9,studioInputArtifactId:id9,bindingId:id9,expectedProductionRevision:z131.int().positive(),expectedBindingRevision:z131.int().positive(),expectedConfigurationVersion:z131.int().positive()});var AgentHostExecutionGetSchema=AgentHostExecutionScopeSchema.extend({executionId:id9});var AgentHostExecutionQuerySchema=AgentHostExecutionScopeSchema.extend({limit:z131.int().min(1).max(100).default(20),beforeId:id9.optional()});var AgentHostExecutionSourceSchema=z131.strictObject({artifactId:id9,representationId:id9,checksumSha256:sha18,byteSize:z131.int().positive().max(8388608),contentType:z131.string().min(1).max(100),kind:z131.enum(["PRODUCT_INFORMATION","REFERENCE_IMAGE","REFERENCE_VIDEO"])});var AgentHostExecutionInputSchema=AgentHostExecutionScopeSchema.extend({protocol:z131.literal("NATIVESTUDIO_PRODUCTION_V1"),executionId:id9,hostRequestId:id9,productionRevision:z131.int().positive(),studioInput:StudioInputContentSchema,intake:AgentHostExecutionSourceSchema,sources:z131.array(AgentHostExecutionSourceSchema).max(12)}).refine(v=>v.studioInput.productionId===v.productionId&&v.studioInput.sourceArtifactIds.length===v.sources.length&&new Set(v.sources.map(s=>s.artifactId)).size===v.sources.length&&v.sources.every((s,index)=>s.artifactId===v.studioInput.sourceArtifactIds[index])&&!v.sources.some(s=>s.artifactId===v.intake.artifactId));var AgentHostInstallationTransportSchema=z131.union([CurrentHostInstallationTransportSchema,HistoricalHostTransportSchema]);var AgentHostNativeToolAuthoritySchema=AgentHostExecutionScopeSchema.extend({protocol:z131.literal("NATIVESTUDIO_AGENT_TOOLS_V1"),authorityRef:id9,executionId:id9,hostRequestId:id9,bindingId:id9,configurationVersion:z131.int().positive(),inputFingerprint:sha18,capabilityDigest:sha18,expiresAt:z131.iso.datetime({offset:true}),executionClass:z131.enum(["LIVE","TEST_ONLY"]),transport:AgentHostInstallationTransportSchema.optional()});var AgentHostExecutionSnapshotSchema=z131.strictObject({binding:AgentHostBindingSchema,input:AgentHostExecutionInputSchema,authority:AgentHostNativeToolAuthoritySchema}).refine(v=>v.binding.tenantId===v.input.tenantId&&v.binding.projectId===v.input.projectId&&v.binding.enabled&&v.authority.tenantId===v.input.tenantId&&v.authority.projectId===v.input.projectId&&v.authority.productionId===v.input.productionId&&v.authority.executionId===v.input.executionId&&v.authority.hostRequestId===v.input.hostRequestId&&v.authority.bindingId===v.binding.bindingId&&v.authority.configurationVersion===v.binding.configurationVersion);var AgentHostTaskObservationSchema=z131.strictObject({requestId:id9,runKey:z131.string().regex(/^[A-Za-z0-9_-]{1,160}$/),status:z131.enum(["accepted","running","succeeded","failed","cancelled","unknown"]),agentKey:HostReferenceSchema,agentVersion:z131.union([HostReferenceSchema,z131.int().positive()]),modelOptionKey:HostReferenceSchema,cancelRequested:z131.boolean(),createdAt:z131.iso.datetime({offset:true}),updatedAt:z131.iso.datetime({offset:true}),timing:z131.strictObject({acceptedAt:z131.iso.datetime({offset:true}),deadlineAt:z131.iso.datetime({offset:true}),limitSource:z131.literal("TASK_POLICY")}).nullable()});var AgentHostDispatchPhaseSchema=z131.enum(["ADMITTED","SENDING","OUTCOME_UNKNOWN","OBSERVING","REJECTED","CANCELLED_BEFORE_SUBMISSION"]);var AgentHostExecutionViewSchema=AgentHostExecutionScopeSchema.extend({executionId:id9,requestId:id9,requestedByPrincipalId:id9,hostRequestId:id9,revision:z131.int().positive(),contractVersion:z131.union([z131.literal(1),z131.literal(2)]).optional(),legacyDispatchFenceReleased:z131.boolean().optional(),snapshotFingerprint:sha18,snapshot:AgentHostExecutionSnapshotSchema,dispatchPhase:AgentHostDispatchPhaseSchema,active:z131.boolean(),observation:AgentHostTaskObservationSchema.nullable(),cancelRequestId:id9.nullable(),errorCode:z131.string().regex(/^[A-Z_]{1,80}$/).nullable(),createdAt:z131.iso.datetime({offset:true}),updatedAt:z131.iso.datetime({offset:true})}).refine(v=>(!v.legacyDispatchFenceReleased||v.contractVersion===1)&&v.snapshot.input.executionId===v.executionId&&v.snapshot.input.hostRequestId===v.hostRequestId&&v.snapshot.input.tenantId===v.tenantId&&v.snapshot.input.projectId===v.projectId&&v.snapshot.input.productionId===v.productionId&&(!v.observation||v.observation.requestId===v.hostRequestId&&v.observation.agentKey===v.snapshot.binding.selection.agentKey&&v.observation.agentVersion===v.snapshot.binding.selection.agentVersion&&v.observation.modelOptionKey===v.snapshot.binding.selection.modelOptionKey));var AgentHostExecutionPageSchema=z131.strictObject({items:z131.array(AgentHostExecutionViewSchema).max(100),hasMore:z131.boolean(),nextBeforeId:id9.nullable()}).refine(v=>v.hasMore===(v.nextBeforeId!==null)&&(!v.hasMore||v.nextBeforeId===v.items.at(-1)?.executionId)&&new Set(v.items.map(item=>item.executionId)).size===v.items.length);var AgentHostExecutionEventSchema=z131.strictObject({id:id9,executionId:id9,revision:z131.int().positive(),action:z131.enum(["ADMIT","CLAIM","RECOVER_UNKNOWN","OBSERVE","REJECT","CANCEL_REQUEST","CANCEL_UNSENT"]),createdByPrincipalId:id9,observation:AgentHostTaskObservationSchema.nullable(),errorCode:z131.string().regex(/^[A-Z_]{1,80}$/).nullable(),createdAt:z131.iso.datetime({offset:true})});var AgentHostExecutionEventQuerySchema=AgentHostExecutionGetSchema.extend({limit:z131.int().min(1).max(100).default(20),beforeRevision:z131.int().positive().optional()});var AgentHostExecutionEventPageSchema=z131.strictObject({items:z131.array(AgentHostExecutionEventSchema).max(100),hasMore:z131.boolean(),nextBeforeRevision:z131.int().positive().nullable()}).refine(v=>v.hasMore===(v.nextBeforeRevision!==null)&&(!v.hasMore||v.nextBeforeRevision===v.items.at(-1)?.revision)&&v.items.every((item,index)=>!index||item.revision<v.items[index-1].revision));var AgentHostExecutionFailureSchema=z131.strictObject({semanticStatus:z131.enum(["INVALID_INPUT","NOT_FOUND","BLOCKED","REVISION_CONFLICT","CAPABILITY_UNAVAILABLE","INTERNAL_OPERATIONAL_FAILURE"]),error:z131.strictObject({code:z131.enum(["INVALID_INPUT","UNAUTHENTICATED","FORBIDDEN","NOT_FOUND","REVISION_CONFLICT","REQUEST_CONFLICT","SOURCE_UNAVAILABLE","TOOL_AUTHORITY_UNAVAILABLE","ACTIVE_EXECUTION_EXISTS","LEASE_LOST","BINDING_UNAVAILABLE","INTERNAL_OPERATIONAL_FAILURE"]),message:z131.literal("Agent Host execution did not complete")})});import{z as z133}from"zod";import{z as z132}from"zod";var key4=z132.string().trim().min(1).max(200);var ScopedSourceInputSchema=SourceInputMetadataSchema.extend({projectId:ProjectIdSchema,idempotencyKey:key4});var ScopedSourceUploadSchema=UploadSourceInputRequestSchema.extend({projectId:ProjectIdSchema,idempotencyKey:key4});var SourceReadSchema=SourceLibraryMediaSchema.extend({offsetBytes:z132.int().min(0).max(8388608).default(0),maxTextBytes:z132.int().min(4).max(65536).default(16384)});var SourceTextWindowSchema=SourceLibraryMediaSchema.extend({contentType:z132.enum(["text/plain","application/json"]),checksumSha256:z132.string().regex(/^[0-9a-f]{64}$/),totalBytes:z132.int().positive().max(8388608),offsetBytes:z132.int().nonnegative(),byteLength:z132.int().nonnegative().max(65536),nextOffsetBytes:z132.int().nonnegative().nullable(),text:z132.string().max(65536)});var InterfaceImageMetadataSchema=KeyframeMediaSchema.omit({contentBase64:true});var InterfacePosterMetadataSchema=InterfaceImageMetadataSchema.extend({contentType:z133.literal("image/png")});var InterfaceDownloadDescriptorSchema=z133.strictObject({humanLinks:HumanLinksSchema.optional(),method:z133.literal("GET"),path:z133.string().min(1).max(2048),tenantId:TenantIdSchema,authentication:z133.literal("BEARER_AND_TENANT_HEADER"),contentType:z133.enum(["video/mp4","image/png","application/json"]),checksumSha256:z133.string().regex(/^[0-9a-f]{64}$/),byteSize:z133.int().positive().max(128*1024*1024)});var tenantMediaDownloadPath="/v1/local-execution/tenant-media/download";var InterfaceDeliveryDownloadDescriptorSchema=z133.discriminatedUnion("method",[InterfaceDownloadDescriptorSchema,InterfaceDownloadDescriptorSchema.extend({method:z133.literal("POST"),path:z133.literal(tenantMediaDownloadPath),productionId:ProductionIdSchema,contentType:z133.literal("video/mp4"),body:z133.strictObject({tenantId:TenantIdSchema,projectId:ProjectIdSchema,representationId:ArtifactRepresentationIdSchema})})]);var SourceReadResultSchema=z133.union([SourceTextWindowSchema,SourceLibraryMediaSchema.extend(InterfaceImageMetadataSchema.shape).strict(),SourceLibraryMediaSchema.extend({contentType:z133.literal("video/mp4"),checksumSha256:z133.string().regex(/^[0-9a-f]{64}$/),byteSize:z133.int().positive().max(8388608),importOperation:z133.literal("imported-visual.register-source")}).strict()]);import{z as z134}from"zod";var StartReferencePreviewSchema=z134.strictObject({tenantId:TenantIdSchema,projectId:ProjectIdSchema,productionId:ProductionIdSchema,sourceArtifactId:ArtifactIdSchema,expectedBriefVersion:z134.int().positive(),idempotencyKey:z134.string().regex(/^[A-Za-z0-9_-]{8,80}$/),deviceId:z134.uuid().optional()});var ReferencePreviewAdmissionSchema=z134.strictObject({semanticStatus:z134.literal("ACCEPTED"),operationId:OperationIdSchema,productionId:ProductionIdSchema,sourceArtifactId:ArtifactIdSchema,briefVersion:z134.int().positive()});var ReferencePreviewResultSchema=z134.strictObject({semanticStatus:z134.literal("SUCCESS"),sourceArtifactId:ArtifactIdSchema,representationId:ArtifactRepresentationIdSchema,contentType:z134.literal("image/png"),checksumSha256:z134.string().regex(/^[0-9a-f]{64}$/),width:z134.int().positive(),height:z134.int().positive(),byteSize:z134.int().positive(),contentBase64:z134.string().min(4)});var ReferencePreviewOperationInputSchema=z134.strictObject({tenantId:TenantIdSchema,projectId:ProjectIdSchema,productionId:ProductionIdSchema,operationId:OperationIdSchema});var ReferencePreviewReadResultSchema=z134.union([ReferencePreviewResultSchema,z134.strictObject({semanticStatus:z134.literal("ACCEPTED")})]);var ReferencePreviewCancelResultSchema=z134.union([z134.strictObject({semanticStatus:z134.literal("ACCEPTED")}),z134.strictObject({semanticStatus:z134.literal("NOT_FOUND")})]);import{z as z135}from"zod";var StudioCapabilitiesInputSchema=z135.strictObject({tenantId:TenantIdSchema,productionId:ProductionIdSchema.optional()});var StudioCapabilitiesSchema=z135.strictObject({semanticStatus:z135.literal("SUCCESS"),capabilities:z135.array(z135.strictObject({capability:z135.string().min(1).max(120),tool:z135.string().min(1).max(120).optional(),availability:z135.enum(["AVAILABLE","UNAVAILABLE"]),reason:z135.string().min(1).max(1e3).nullable()})).max(512)});var VideoOptionsSchema=z135.array(z135.strictObject({selection:ProviderSelectionSchema,profile:VideoProviderProfileSchema})).max(1600);import{z as z136}from"zod";var RenderReadinessInputSchema=z136.strictObject({tenantId:z136.uuid(),projectId:z136.uuid().optional(),productionId:z136.uuid().optional(),kind:z136.enum(["preview","final"]),deviceId:z136.uuid().optional(),hostAccess:z136.enum(["MCP_ONLY","AUTHORIZED_HOST"]).optional()});var RenderReadinessSchema=RenderReadinessInputSchema.omit({hostAccess:true}).extend({protocol:z136.literal("NVS_RENDER_READINESS_V1"),observedAt:z136.iso.datetime(),state:z136.enum(["SELECT_PROJECT","SELECT_PRODUCTION","BUSINESS_BLOCKED","AUTHORIZATION_REQUIRED","CHECK_DEVICE_INVENTORY","DEVICE_QUALIFICATION_UNKNOWN","WAIT_FOR_DEVICE","PREPARE_HOST","HOST_HANDOFF_REQUIRED","DEVICE_UNAVAILABLE","READY"]),reasonCode:z136.string().regex(/^[A-Z][A-Z0-9_]{0,79}$/),writeAuthorization:z136.enum(["READ_ONLY","WRITE_SCOPE_PRESENT","CHECK_AT_ADMISSION"]),blockers:FinalRenderEligibilitySchema.shape.blockers.optional(),sourceBlockers:FinalRenderEligibilitySchema.shape.sourceBlockers.optional(),candidates:ProjectDeviceListSchema.optional(),executionTarget:DeviceRenderTargetSchema.optional(),nextAction:z136.strictObject({owner:z136.enum(["AGENT","HOST_OWNER","AUTHORIZED_MEMBER","TENANT_OPERATOR"]),inspect:z136.strictObject({tool:z136.enum(["studio_capability_query","studio_capability_describe","workspace_caller"]),arguments:z136.record(z136.string(),z136.unknown())}).optional(),hostRequirements:z136.strictObject({packageName:z136.literal("@nativestudio/cli"),nodeMajor:z136.literal(24),permission:z136.literal("AUTHORIZED_USER_SHELL")}).optional()})});function renderDeviceSelection(candidates,requestedDeviceId){const fixed=requestedDeviceId?.toLowerCase();const available=candidates.items.filter(item=>item.availability==="AVAILABLE"&&(!fixed||item.deviceId.toLowerCase()===fixed));if(available.length>1)return{state:"DEVICE_SELECTION_REQUIRED"};if(available[0]&&(fixed||!candidates.truncated))return{state:"AVAILABLE",deviceId:available[0].deviceId};return{state:candidates.truncated?"INCOMPLETE_INVENTORY":"UNAVAILABLE"}}function currentPreviewRenderBasis(basis,current){if(!current||!current.isCurrent||current.assemblyStatus!=="ASSEMBLY_READY"||current.freshness!=="CURRENT_BASIS"||basis.currentTimelineVersion!==current.version.version)return null;return{timelineVersionId:current.version.id,timelineFingerprint:current.version.fingerprint,expectedProductionRevision:basis.productionRevision}}import{z as z139}from"zod";import{z as z137}from"zod";var uuid=z137.uuid().toLowerCase();var timestamp2=z137.iso.datetime();var version=z137.int().positive();var digest=z137.string().regex(/^[a-f0-9]{64}$/);var requestKey=z137.string().trim().min(1).max(200);var reason2=z137.string().trim().min(1).max(2e3);var scope2=z137.strictObject({tenantId:TenantIdSchema,projectId:ProjectIdSchema});var commandBase=scope2.extend({idempotencyKey:requestKey,reason:reason2});var claim=z137.strictObject({id:uuid,statement:z137.string().trim().min(1).max(1e3),evidenceArtifactId:ArtifactIdSchema,evidenceChecksumSha256:digest});var variant=z137.strictObject({id:uuid,market:z137.string().regex(/^(?:[A-Z]{2}|GLOBAL)$/),locale:z137.string().regex(/^[a-z]{2,3}(?:-[a-zA-Z0-9]{2,8}){0,4}$/),channel:z137.enum(["WEB","SOCIAL","PAID_AD","INTERNAL","EVENT","COMMERCE"]),allowedClaimIds:z137.array(uuid).max(20),requiredGraphicsSha256:z137.array(digest).max(4)});var brandContent=z137.strictObject({name:z137.string().trim().min(1).max(200),validFrom:timestamp2,validUntil:timestamp2,claims:z137.array(claim).max(40),variants:z137.array(variant).min(1).max(30)}).superRefine((value2,ctx)=>{const claimIds=new Set(value2.claims.map(item=>item.id));if(Date.parse(value2.validFrom)>=Date.parse(value2.validUntil))ctx.addIssue({code:"custom",path:["validUntil"],message:"End of brand validity must follow its start"});if(claimIds.size!==value2.claims.length||new Set(value2.variants.map(item=>item.id)).size!==value2.variants.length)ctx.addIssue({code:"custom",message:"Brand claims and variants require unique identities"});for(const[index,item]of value2.variants.entries()){if(new Set(item.allowedClaimIds).size!==item.allowedClaimIds.length||item.allowedClaimIds.some(id15=>!claimIds.has(id15)))ctx.addIssue({code:"custom",path:["variants",index,"allowedClaimIds"],message:"Every approved claim must appear once in this brand release"});if(new Set(item.requiredGraphicsSha256).size!==item.requiredGraphicsSha256.length)ctx.addIssue({code:"custom",path:["variants",index,"requiredGraphicsSha256"],message:"Required graphics must have distinct checksums"})}});var BrandPublicationSchema=scope2.extend({brandId:uuid,version,content:brandContent,fingerprint:digest,reason:reason2,createdByPrincipalId:PrincipalIdSchema,createdAt:timestamp2});var grantFields={grantId:uuid,brandId:uuid,version,consumerProjectId:ProjectIdSchema,variantIds:z137.array(uuid).min(1).max(30).refine(ids=>new Set(ids).size===ids.length),expiresAt:timestamp2};var BrandGrantSchema=scope2.extend({...grantFields,reason:reason2,createdByPrincipalId:PrincipalIdSchema,createdAt:timestamp2,revokedAt:timestamp2.nullable(),revokedByPrincipalId:PrincipalIdSchema.nullable(),revocationReason:reason2.nullable()});var EnterpriseBrandCommandSchema=z137.discriminatedUnion("action",[commandBase.extend({action:z137.literal("PUBLISH"),brandId:uuid,expectedVersion:z137.int().nonnegative(),content:brandContent}),commandBase.extend({action:z137.literal("GRANT"),...grantFields}),commandBase.extend({action:z137.literal("REVOKE"),grantId:uuid})]);var EnterpriseBrandReceiptSchema=z137.discriminatedUnion("action",[scope2.extend({action:z137.literal("PUBLISH"),idempotencyKey:requestKey,publication:BrandPublicationSchema}),scope2.extend({action:z137.enum(["GRANT","REVOKE"]),idempotencyKey:requestKey,grant:BrandGrantSchema})]);var BrandSelectionSchema=z137.strictObject({ownerProjectId:ProjectIdSchema,brandId:uuid,version,grantId:uuid,variantId:uuid,selectedClaimIds:z137.array(uuid).max(20).refine(ids=>new Set(ids).size===ids.length)});var BoundBrandVariantSchema=BrandSelectionSchema.extend({variant,selectedClaims:z137.array(claim).max(20),releaseFingerprint:digest});var EnterpriseBrandQuerySchema=z137.discriminatedUnion("action",[scope2.extend({action:z137.literal("PUBLICATION"),ownerProjectId:ProjectIdSchema,brandId:uuid,version,grantId:uuid.optional()}),scope2.extend({action:z137.literal("GRANT"),ownerProjectId:ProjectIdSchema,grantId:uuid})]);var EnterpriseBrandViewSchema=z137.discriminatedUnion("action",[scope2.extend({action:z137.literal("PUBLICATION"),grantId:uuid.optional(),publication:BrandPublicationSchema}),scope2.extend({action:z137.literal("GRANT"),grant:BrandGrantSchema})]);var EnterpriseBrandReceiptQuerySchema=scope2.extend({idempotencyKey:requestKey});import{z as z138}from"zod";var uuid2=z138.uuid().toLowerCase();var change=z138.strictObject({ruleId:uuid2,expected:z138.string().trim().min(1).max(1e3)});var SeriesCharacterVariantSchema=z138.strictObject({id:uuid2,subjectId:uuid2,name:z138.string().trim().min(1).max(200),wardrobe:z138.array(change).min(1).max(8).refine(rules=>new Set(rules.map(rule=>rule.ruleId)).size===rules.length),voiceSubjectId:uuid2.optional()});var SeriesCharacterVariantsSchema=z138.array(SeriesCharacterVariantSchema).min(1).max(16).refine(variants=>new Set(variants.map(variant2=>variant2.id)).size===variants.length);var SeriesCharacterVariantIdsSchema=z138.array(uuid2).min(1).max(16).refine(ids=>new Set(ids).size===ids.length);var digest2=z139.string().regex(/^[a-f0-9]{64}$/);var revision=z139.int().positive();var requestKey2=z139.string().trim().min(1).max(200);var reason3=z139.string().trim().min(1).max(2e3);var SeriesProjectScopeSchema=z139.strictObject({tenantId:TenantIdSchema,projectId:ProjectIdSchema});var identity3=SeriesProjectScopeSchema.extend({seriesId:z139.uuid()});var SeriesStandardQuerySchema=identity3.extend({version:revision.optional()});var SeriesStandardListSchema=SeriesProjectScopeSchema.extend({after:z139.uuid().optional(),limit:z139.int().positive().max(40).default(10)});var standard=z139.strictObject({name:z139.string().trim().min(1).max(200),consistency:ConsistencyProfileContentSchema,characterVariants:SeriesCharacterVariantsSchema.optional()});var PublishSeriesStandardSchema=identity3.extend({expectedVersion:z139.int().nonnegative(),brand:BrandSelectionSchema.optional(),content:standard.extend({graphics:z139.array(TimelineGraphicInputSchema).max(4)}).superRefine(({consistency,graphics},ctx)=>{if(!consistency.rules.length&&!graphics.length)ctx.addIssue({code:"custom",message:"A series standard needs a rule or a graphic"});for(const[index,rule]of consistency.rules.entries()){if(rule.scope.kind!=="PROJECT"||rule.transition||rule.voiceTargets?.kind==="SOUND_CUES")ctx.addIssue({code:"custom",path:["consistency","rules",index],message:"Reusable rules require project scope and cannot name episode-specific cues or transitions"})}if(new Set(graphics.map(g=>g.artifactId.toLowerCase())).size!==graphics.length)ctx.addIssue({code:"custom",path:["graphics"],message:"Duplicate required graphic"})}),reason:reason3,idempotencyKey:requestKey2});var SeriesStandardVersionSchema=identity3.extend({version:revision,brand:BoundBrandVariantSchema.optional(),content:standard.extend({graphics:z139.array(TimelineGraphicSchema).max(4)}),fingerprint:digest2,reason:reason3,createdByPrincipalId:PrincipalIdSchema,createdAt:z139.iso.datetime()});var SeriesStandardPageSchema=SeriesProjectScopeSchema.extend({items:z139.array(SeriesStandardVersionSchema.omit({content:true,brand:true}).extend({name:standard.shape.name})).max(40),next:z139.uuid().nullable()});var ProductionSeriesScopeSchema=SeriesProjectScopeSchema.extend({productionId:ProductionIdSchema});var ProductionSeriesQuerySchema=ProductionSeriesScopeSchema.extend({productionRevision:revision.optional(),atRevision:revision.optional()}).refine(query=>query.productionRevision===void 0||query.atRevision===void 0,"Use either the binding revision or a production receipt revision");var BindSeriesStandardSchema=ProductionSeriesScopeSchema.extend({seriesId:z139.uuid(),version:revision,expectedProductionRevision:revision,expectedProfileVersion:z139.int().nonnegative(),characterVariantIds:SeriesCharacterVariantIdsSchema.optional(),reason:reason3,idempotencyKey:requestKey2});var ProductionSeriesBindingSchema=ProductionSeriesScopeSchema.extend({standard:SeriesStandardVersionSchema,characterVariantIds:SeriesCharacterVariantIdsSchema.optional(),profileId:z139.uuid(),profileVersion:revision,productionRevision:revision,reason:reason3,createdByPrincipalId:PrincipalIdSchema,createdAt:z139.iso.datetime()});var PublishSeriesStandardReceiptSchema=z139.strictObject({action:z139.literal("PUBLISH"),idempotencyKey:requestKey2,standard:SeriesStandardVersionSchema});var BindSeriesStandardReceiptSchema=z139.strictObject({action:z139.literal("BIND"),idempotencyKey:requestKey2,binding:ProductionSeriesBindingSchema});var SeriesStandardReceiptSchema=z139.discriminatedUnion("action",[PublishSeriesStandardReceiptSchema,BindSeriesStandardReceiptSchema]);var SeriesStandardReceiptQuerySchema=SeriesProjectScopeSchema.extend({idempotencyKey:requestKey2});import{z as z140}from"zod";var id10=z140.uuid().toLowerCase();var ordinal=z140.int().positive();var scope3=z140.strictObject({tenantId:TenantIdSchema,projectId:ProjectIdSchema});var branch=scope3.extend({seriesId:id10,branchId:id10});var reference=z140.strictObject({branchId:id10,ordinal});var state=z140.record(z140.string().regex(/^[A-Z][A-Z0-9_.-]{0,63}$/),z140.string().trim().min(1).max(1e3)).refine(value2=>Object.keys(value2).length<=48,"Up to 48 canonical facts");var time=z140.strictObject({startTick:z140.int().nonnegative(),endTick:z140.int().positive()}).refine(range=>range.endTick>range.startTick,"Story time must have a positive duration");var relation=z140.discriminatedUnion("kind",[z140.strictObject({kind:z140.literal("CONTINUE")}),z140.strictObject({kind:z140.literal("FLASHBACK"),anchor:reference}),z140.strictObject({kind:z140.literal("FORK"),anchor:reference})]);var episode={productionId:ProductionIdSchema,storyTime:time,entryState:state,exitState:state,relation,reason:z140.string().trim().min(1).max(2e3),idempotencyKey:z140.string().trim().min(1).max(200)};var RecordSeriesCanonSchema=branch.extend({...episode,expectedHeadOrdinal:z140.int().nonnegative(),bindingRevision:ordinal,seriesVersion:ordinal});var SeriesCanonSchema=branch.extend({...episode,ordinal,bindingRevision:ordinal,seriesVersion:ordinal,basis:reference.nullable(),continuation:z140.strictObject({head:reference,endTick:z140.int().positive(),state}),createdAt:z140.iso.datetime(),createdByPrincipalId:PrincipalIdSchema});var SeriesCanonQuerySchema=branch.extend({ordinal:ordinal.optional()});var SeriesCanonReceiptQuerySchema=scope3.extend({idempotencyKey:episode.idempotencyKey});import{z as z141}from"zod";var id11=z141.uuid().toLowerCase();var version2=z141.int().positive();var scope4=z141.strictObject({tenantId:TenantIdSchema,projectId:ProjectIdSchema});var series=scope4.extend({seriesId:id11});var identity4=series.extend({proposalId:id11});var requestKey3=z141.string().trim().min(1).max(200);var reason4=z141.string().trim().min(1).max(2e3);var command2=identity4.extend({reason:reason4,idempotencyKey:requestKey3});var finding=z141.strictObject({kind:z141.literal("FINDING"),productionId:ProductionIdSchema,bindingRevision:version2,findingId:id11});var canon=z141.strictObject({kind:z141.literal("CANON"),branchId:id11,ordinal:version2});var source3=z141.discriminatedUnion("kind",[finding,canon]);var evidence=z141.discriminatedUnion("kind",[finding.extend({renderId:id11,reviewId:id11,timelineVersionId:id11,seriesVersion:version2,manifestFingerprint:z141.string().regex(/^[a-f0-9]{64}$/)}),canon.extend({productionId:ProductionIdSchema,bindingRevision:version2,seriesVersion:version2})]);var draft=z141.strictObject({content:PublishSeriesStandardSchema.shape.content,brand:BrandSelectionSchema.optional()});var SeriesImprovementCommandSchema=z141.discriminatedUnion("action",[command2.extend({action:z141.literal("PROPOSE"),baseVersion:version2,source:source3,draft}),command2.extend({action:z141.literal("APPROVE")}),command2.extend({action:z141.literal("DECLINE")})]);var actor={createdAt:z141.iso.datetime(),createdByPrincipalId:PrincipalIdSchema,reason:reason4};var SeriesImprovementProposalSchema=identity4.extend({baseVersion:version2,evidence,draft,...actor});var SeriesImprovementDecisionSchema=z141.discriminatedUnion("action",[identity4.extend({action:z141.literal("APPROVE"),published:SeriesStandardVersionSchema,...actor}),identity4.extend({action:z141.literal("DECLINE"),...actor})]);var SeriesImprovementReceiptSchema=identity4.extend({action:z141.enum(["PROPOSE","APPROVE","DECLINE"]),idempotencyKey:requestKey3,proposal:SeriesImprovementProposalSchema,decision:SeriesImprovementDecisionSchema.nullable()});var SeriesImprovementQuerySchema=z141.discriminatedUnion("action",[identity4.extend({action:z141.literal("GET")}),series.extend({action:z141.literal("LIST"),after:id11.optional(),limit:z141.int().min(1).max(20).default(10)})]);var SeriesImprovementViewSchema=z141.discriminatedUnion("action",[identity4.extend({action:z141.literal("GET"),proposal:SeriesImprovementProposalSchema,decision:SeriesImprovementDecisionSchema.nullable()}),series.extend({action:z141.literal("LIST"),items:z141.array(SeriesImprovementProposalSchema.omit({draft:true}).extend({disposition:z141.enum(["PENDING","APPROVED","DECLINED"])})).max(20),next:id11.nullable()})]);var SeriesImprovementReceiptQuerySchema=scope4.extend({idempotencyKey:requestKey3});import{z as z142}from"zod";var Key2=z142.string().regex(/^[a-z][a-z0-9_-]{0,39}$/);var Intent3=z142.string().trim().min(1).max(600);var ExplorationScopeSchema=DirectorScopeSchema.extend({shotId:ShotIdSchema});var ExplorationBasisSchema=DirectorBasisSchema.safeExtend({shotId:ShotIdSchema,shotPlanningRevision:z142.int().positive()});var ExplorationContextInputSchema=z142.strictObject({scope:ExplorationScopeSchema,preparationIds:z142.array(PreparationIdSchema).max(6).default([])}).refine(v=>new Set(v.preparationIds).size===v.preparationIds.length,"Preparation IDs must be distinct");var ExplorationProfileIdentitySchema=KeyframeProviderProfileSchema.pick({id:true,adapterVersion:true,model:true,executionClass:true});var ExplorationOptionSchema=z142.strictObject({selection:ProviderSelectionSchema.nullable(),profile:z142.discriminatedUnion("mediaType",[KeyframeProviderProfileSchema,VideoProviderProfileSchema])});var Missing2=z142.strictObject({semanticStatus:z142.literal("NEEDS_INPUT"),missingPrerequisites:z142.array(z142.enum(["ACTIVE_BRIEF","ACTIVE_STORY","ACTIVE_SCENE_SHOT_PLAN"])).min(1).max(3)});var ExplorationContextResultSchema=z142.discriminatedUnion("semanticStatus",[z142.strictObject({semanticStatus:z142.literal("SUCCESS"),advisory:z142.literal(true),basis:ExplorationBasisSchema,owner:DirectorContextResultSchema.options[0],preparations:z142.array(z142.strictObject({view:PreparationViewSchema,eligibleOptions:z142.array(ExplorationOptionSchema).max(24),eligibleOptionCount:z142.int().nonnegative(),optionsTruncated:z142.boolean()})).max(6)}),Missing2]);var ImageDraft=KeyframeStartInputSchema.omit({idempotencyKey:true});var VideoDraft=VideoStartInputSchema.omit({idempotencyKey:true});var ExplorationCommandSchema=z142.strictObject({commandKey:Key2,purpose:Intent3,mediaType:z142.enum(["IMAGE","VIDEO"]),preparationId:PreparationIdSchema,contractId:ImageDraft.shape.contractId,contractFingerprint:ImageDraft.shape.contractFingerprint,selection:ProviderSelectionSchema.nullable(),profile:ExplorationProfileIdentitySchema});var ValidateExplorationPlanSchema=z142.strictObject({basis:ExplorationBasisSchema,plan:z142.strictObject({origin:z142.strictObject({kind:z142.literal("EXTERNAL_AGENT_HOST"),label:z142.string().trim().min(1).max(100)}),objective:Intent3,comparisonCriteria:z142.array(Intent3).min(1).max(8),unknowns:z142.array(z142.string().trim().min(1).max(300)).max(8),maximumGenerationCommands:z142.int().min(1).max(6),commands:z142.array(ExplorationCommandSchema).min(1).max(6)})}).refine(v=>new TextEncoder().encode(JSON.stringify(v)).byteLength<=1024*1024,"Exploration input exceeds the 1 MiB JSON budget");var ExplorationDraftSchema=z142.discriminatedUnion("mediaType",[z142.strictObject({commandKey:Key2,mediaType:z142.literal("IMAGE"),request:ImageDraft}),z142.strictObject({commandKey:Key2,mediaType:z142.literal("VIDEO"),request:VideoDraft})]);var ExplorationValidationResultSchema=z142.discriminatedUnion("semanticStatus",[z142.strictObject({semanticStatus:z142.literal("SUCCESS"),advisory:z142.literal(true),basis:ExplorationBasisSchema,plan:ValidateExplorationPlanSchema.shape.plan,generationDrafts:z142.array(ExplorationDraftSchema).min(1).max(6),limitations:z142.array(z142.enum(["ADMISSION_RECHECKS_BASIS_AND_PROVIDER","COMMAND_COUNT_IS_NOT_MONETARY_BUDGET","NO_AUTOMATIC_EXECUTION_OR_ACCEPTANCE","QUALITY_REQUIRES_EXACT_MEDIA_INSPECTION"])).length(4)}),Missing2]);var ExplorationCompareInputSchema=z142.strictObject({scope:ExplorationScopeSchema,items:z142.array(z142.strictObject({label:Key2,mediaType:z142.enum(["IMAGE","VIDEO"]),generationId:z142.uuid()})).min(2).max(6)});var ExplorationComparisonResultSchema=z142.strictObject({semanticStatus:z142.literal("SUCCESS"),advisory:z142.literal(true),scope:ExplorationScopeSchema,items:z142.array(z142.discriminatedUnion("mediaType",[z142.strictObject({label:Key2,mediaType:z142.literal("IMAGE"),generation:KeyframeGenerationViewSchema,handoff:z142.strictObject({mediaRead:KeyframeReviewScopeSchema,reviewTarget:KeyframeReviewScopeSchema}).nullable()}),z142.strictObject({label:Key2,mediaType:z142.literal("VIDEO"),generation:VideoGenerationViewSchema,handoff:z142.strictObject({mediaRead:VideoReviewScopeSchema,reviewTarget:VideoReviewScopeSchema}).nullable()})])).min(2).max(6),limitations:z142.tuple([z142.literal("OWNER_STATES_ARE_NOT_VISUAL_SCORES"),z142.literal("REVIEW_AND_ACCEPTANCE_REMAIN_EXPLICIT")])});import{z as z143}from"zod";var sha19=z143.string().regex(/^[0-9a-f]{64}$/);var FinalOutputReviewContextInputSchema=z143.strictObject({scope:DirectorScopeSchema,renderId:z143.uuid()});var FinalOutputReviewBasisSchema=FinalOutputReviewContextInputSchema.extend({contextFingerprint:sha19});var FinalOutputReviewContextResultSchema=z143.strictObject({semanticStatus:z143.literal("SUCCESS"),advisory:z143.literal(true),basis:FinalOutputReviewBasisSchema,ownerContext:DirectorContextResultSchema,deliveryTarget:DeliveryTargetSchema,deliverySnapshot:DeliverySnapshotSchema,validation:DeliveryValidationViewSchema.nullable(),manifest:RegisteredDeliveryManifestSchema.nullable(),limitations:z143.array(z143.enum(["OWNER_REVIEW_3_REMAINS_AUTHORITATIVE","NO_CALLER_SUPPLIED_DELIVERY_CHECKS","NO_IMPLICIT_MEDIA_OR_MODEL_CALL","READS_ARE_NOT_ATOMIC_OR_RESERVED"])).length(4)});import{z as z148}from"zod";import{z as z147}from"zod";import{z as z146}from"zod";import{z as z144}from"zod";var Text=z144.string().trim().min(1).max(600);var Method=z144.enum(["HUMAN","AI","CODE"]);var Key3=z144.string().regex(/^[a-z][a-z0-9_.:-]{0,99}$/);var CompositionAuthoringObligationsSchema=z144.strictObject({schemaVersion:z144.literal(1),basis:CompositionBasisPinSchema,productionRevision:z144.int().positive(),output:BriefContentSchema.pick({targetDurationSeconds:true,aspectRatio:true,outputProfile:true}),objective:BriefContentSchema.shape.objective,productPresentationGoal:BriefContentSchema.shape.productPresentationGoal,audience:BriefContentSchema.shape.audience,styleTone:BriefContentSchema.shape.styleTone,callToAction:BriefContentSchema.shape.callToAction,narrativeIntent:StoryContentSchema.shape.narrativeIntent,canonicalFacts:BriefContentSchema.shape.canonicalFacts,storyBeats:StoryContentSchema.shape.beats,storyFactualClaims:StoryContentSchema.shape.factualClaims,shot:ShotPlanEntrySchema.nullable(),obligationKeys:z144.array(Key3).min(1).max(384).refine(v=>new Set(v).size===v.length,"Obligation keys must be unique"),semantics:z144.literal("ACCEPTED_INTENT_NOT_OBSERVED_MEDIA")}).refine(v=>v.basis.shotId===null===(v.shot===null)&&(!v.shot||v.shot.shotId===v.basis.shotId),"Authoring Shot must match the exact planning basis");var MakingAlternativeSchema=z144.strictObject({alternativeId:z144.string().regex(/^[a-z][a-z0-9_-]{0,39}$/),title:z144.string().trim().min(1).max(120),method:z144.enum(["HUMAN","AI","CODE","HYBRID"]),contributions:z144.array(z144.strictObject({method:Method,role:z144.enum(["PRIMARY_VISUAL","VISUAL_LAYER"]),intent:Text})).min(1).max(6),rationale:Text,tradeoffs:z144.array(Text).max(6),obligationKeys:z144.array(Key3).min(1).max(384)}).superRefine((v,ctx)=>{const methods=new Set(v.contributions.map(c=>c.method));if(v.method==="HYBRID"?methods.size<2:methods.size!==1||!methods.has(v.method))ctx.addIssue({code:"custom",path:["contributions"],message:"Contributions must match the advisory making method"});if(new Set(v.contributions.map(c=>c.method+":"+c.role)).size!==v.contributions.length)ctx.addIssue({code:"custom",path:["contributions"],message:"Method/role contributions must be unique"});if(new Set(v.obligationKeys).size!==v.obligationKeys.length)ctx.addIssue({code:"custom",path:["obligationKeys"],message:"Obligation references must be unique"})});var ValidateCompositionMakingSchema=CompositionScopeSchema.extend({projectId:z144.uuid(),expectedProductionRevision:z144.int().positive(),basis:CompositionBasisPinSchema,proposal:z144.strictObject({origin:z144.strictObject({kind:z144.literal("EXTERNAL_AGENT_HOST"),label:z144.string().trim().min(1).max(100)}),makingIntent:z144.enum(["REAL_WORLD_CAPTURE","GENERATED_SCENE","PROGRAMMATIC_EXPLANATION"]),unknowns:z144.array(z144.string().trim().min(1).max(300)).max(8),alternatives:z144.array(MakingAlternativeSchema).min(1).max(3)})}).superRefine((v,ctx)=>{if(new Set(v.proposal.alternatives.map(a=>a.alternativeId)).size!==v.proposal.alternatives.length)ctx.addIssue({code:"custom",message:"Alternative IDs must be unique"});if(new TextEncoder().encode(JSON.stringify(v)).byteLength>131072)ctx.addIssue({code:"custom",message:"Making proposal exceeds the 128 KiB UTF-8 JSON budget"})});var CompositionMakingValidationSchema=CompositionScopeSchema.extend({semanticStatus:z144.literal("SUCCESS"),advisory:z144.literal(true),projectId:z144.uuid(),authoring:CompositionAuthoringObligationsSchema,proposal:ValidateCompositionMakingSchema.shape.proposal,limitations:z144.tuple([z144.literal("STRATEGY_IS_AGENT_ADVICE_NOT_CANONICAL_SELECTION"),z144.literal("SOURCE_METHOD_IS_NOT_PROVENANCE_OR_PROVIDER_ELIGIBILITY"),z144.literal("AUTHORING_AND_RENDER_RECHECK_CURRENT_BASIS"),z144.literal("INDEPENDENT_REVIEW_AND_DELIVERY_REMAIN_REQUIRED")])}).superRefine((v,ctx)=>{const required=new Set(v.authoring.obligationKeys);if(new Set(v.proposal.alternatives.map(a=>a.alternativeId)).size!==v.proposal.alternatives.length||v.proposal.alternatives.some(a=>a.obligationKeys.length!==required.size||a.obligationKeys.some(k=>!required.has(k))))ctx.addIssue({code:"custom",message:"Making result must retain unique alternatives and exact native obligation coverage"})});import{z as z145}from"zod";var CompositionAuthoringRequirementsSchema=z145.strictObject({videoFrameCache:z145.strictObject({profileId:z145.literal("HYPERFRAME_1080P30_FRAME_CACHE_V2"),media:z145.literal("MANAGED_MP4_H264_CFR30_SDR_YUV420P"),maxVideos:z145.literal(4),maxDimension:z145.literal(1920),maxPixels:z145.literal(2073600),maxSourceSeconds:z145.literal(60),playbackRate:z145.literal(1),loop:z145.literal(false),sourceOffset:z145.literal("ZERO_BASED_FRAME_ALIGNED"),srcPattern:z145.literal("/inputs/{inputName}.mp4"),attributes:z145.tuple([z145.literal("id"),z145.literal("src"),z145.literal("data-start"),z145.literal("data-duration")]),dynamicVideoSupported:z145.literal(false),nativePlaybackAndCanvasSamplingSupported:z145.literal(false)}).optional(),semantics:z145.literal("REQUIREMENTS_NOT_RUNTIME_OR_REVIEW_EVIDENCE"),dependencies:CompositionContentSchema.shape.dependencies,html:z145.strictObject({entrypoint:z145.literal("index.html"),stageSelector:z145.literal("#stage"),timelineRegistry:z145.literal("window.__timelines"),readinessPromise:z145.literal("window.__nativeReady"),gsapScript:z145.literal("/_native/gsap.min.js"),managedInputsScript:z145.literal("/native-inputs.js"),rootAttributes:z145.tuple([z145.literal("data-composition-id"),z145.literal("data-width"),z145.literal("data-height"),z145.literal("data-duration")]),timing:z145.literal("PAUSED_GSAP_TIMELINE_WITH_DURATION_MATCHING_LOCAL_CLOCK")})});var jsonSchema=z145.record(z145.string().max(120),z145.json());var CompositionAuthoringGuideSchema=z145.strictObject({inputTool:z145.literal("composition_put_input"),inputField:z145.literal("contentUtf8"),encoding:z145.literal("UTF8_JSON"),schemas:z145.strictObject({SOURCE:jsonSchema,DEPENDENCY_MANIFEST:jsonSchema,DEPENDENCY_LOCK:jsonSchema}),rendererRequirements:CompositionAuthoringRequirementsSchema.nullable(),dependencyInputs:z145.strictObject({dependencies:CompositionContentSchema.shape.dependencies,manifest:CompositionDependencyManifestSchema,lock:CompositionDependencyLockSchema}).nullable().optional(),validation:z145.literal("NATIVE_OWNER_RECHECKS_BYTES_BASIS_AND_SEMANTIC_REFINEMENTS")}).refine(v=>new TextEncoder().encode(JSON.stringify(v)).byteLength<=65536);var CreateCompositionSchema=SubmitCompositionSchema.safeExtend({compositionId:z146.null(),expectedVersion:z146.literal(0),previousVersionId:z146.null()});var ReviseCompositionSchema=SubmitCompositionSchema.safeExtend({compositionId:z146.uuid(),expectedVersion:z146.int().positive(),previousVersionId:z146.uuid()});var CompositionBriefQuerySchema=CompositionScopeSchema.extend({shotId:z146.uuid().nullable().default(null)});var CompositionAuthoringBriefSchema=CompositionScopeSchema.extend({projectId:z146.uuid(),productionRevision:z146.int().positive(),planningStatus:z146.enum(["READY","MISSING_PLANNING","STALE_PLANNING","INACTIVE"]),basis:CompositionBasisPinSchema.nullable(),briefContent:BriefContentSchema.nullable(),storyContent:StoryContentSchema.nullable(),shot:ShotPlanEntrySchema.nullable(),authoring:CompositionAuthoringObligationsSchema.nullable().optional()});var ValidateCompositionSchema=CompositionScopeSchema.extend({expectedProductionRevision:z146.int().positive(),basis:CompositionBasisPinSchema,content:CompositionContentSchema}).superRefine((v,ctx)=>{if(v.content.role==="PRIMARY_VISUAL"&&!v.basis.shotId)ctx.addIssue({code:"custom",path:["basis","shotId"],message:"Primary visual requires a planned Shot"})});var CompositionValidationReceiptSchema=z146.strictObject({authoringValidation:z146.literal("PASS"),basis:CompositionBasisPinSchema,productionRevision:z146.int().positive(),contentFingerprint:z146.string().regex(/^[0-9a-f]{64}$/),inputCount:z146.int().min(3).max(64),byteReadback:z146.literal("VERIFIED"),rendererValidation:z146.literal("NOT_EXECUTED"),renderAvailability:z146.enum(["AVAILABLE","UNAVAILABLE"]),nextActions:z146.array(z146.enum(["CREATE_COMPOSITION","REVISE_COMPOSITION"])).max(2)});var PutCompositionInputSchema=CompositionScopeSchema.extend({name:CompositionBindingSchema.shape.name,purpose:z146.enum(["SOURCE","DEPENDENCY_MANIFEST","DEPENDENCY_LOCK","DATA"]),declaredOrigin:CompositionBindingSchema.shape.declaredOrigin,executionClass:z146.enum(["LIVE","TEST_ONLY"]),contentUtf8:z146.string().min(1).max(8388608),idempotencyKey:z146.string().trim().min(1).max(200)}).superRefine((v,ctx)=>{if(v.purpose==="SOURCE"&&v.declaredOrigin!=="CODE")ctx.addIssue({code:"custom",path:["declaredOrigin"],message:"Programmatic source must retain CODE provenance"})});var CompositionInputReceiptSchema=z146.strictObject({binding:CompositionBindingSchema,projectId:z146.uuid(),contentType:z146.literal("application/json"),byteSize:z146.int().positive().max(8388608),executionClass:z146.enum(["LIVE","TEST_ONLY"]),inputStatus:z146.enum(["AVAILABLE","UNAVAILABLE"]),byteReadback:z146.literal("VERIFIED_AT_REGISTRATION")});var CompositionCapabilitySchema=z146.strictObject({capability:z146.string().min(1).max(80),tool:z146.string().nullable(),availability:z146.enum(["AVAILABLE","UNAVAILABLE"]),reason:z146.string().nullable()});var CompositionCapabilitiesSchema=z146.strictObject({provider:z146.literal("HYPERFRAME"),dialect:z146.literal("HYPERFRAME_HTML_GSAP_V1"),planningStatus:CompositionAuthoringBriefSchema.shape.planningStatus,capabilities:z146.array(CompositionCapabilitySchema).max(18),inputLimitsMiB:z146.strictObject({SOURCE:z146.literal(8),DEPENDENCY_MANIFEST:z146.literal(8),DEPENDENCY_LOCK:z146.literal(8),DATA:z146.literal(8),FONT:z146.literal(32),IMAGE:z146.literal(8),VIDEO:z146.literal(64)}),clockSemantics:z146.literal("RATIONAL_FPS_HALF_OPEN_FRAMES"),rendererValidation:z146.enum(["C3_PENDING","PER_REQUEST_CONFORMANCE"]),authoringGuide:CompositionAuthoringGuideSchema.optional()});var CompositionFailureSchema=z146.strictObject({semanticStatus:z146.enum(["INVALID_INPUT","NOT_FOUND","REVISION_CONFLICT","STALE_BASIS","BLOCKED","CAPABILITY_UNAVAILABLE","INTERNAL_OPERATIONAL_FAILURE"]),error:z146.strictObject({code:z146.string().max(80),message:z146.string().max(2e3)}),retryable:z146.boolean(),nextActions:z146.array(z146.string().max(80)).max(4),diagnostics:z146.array(z146.strictObject({code:z146.string().max(80),message:z146.string().max(2e3)})).max(32)});var ParameterValue=z147.strictObject({kind:z147.literal("PARAMETER_VALUE"),name:CompositionBindingSchema.shape.name,value:z147.union([z147.string().max(4e3),z147.number().finite(),z147.boolean()])});var Binding=CompositionBindingSchema.extend({purpose:z147.enum(["SOURCE","DATA","FONT","IMAGE","VIDEO"])});var CompositionRepairConsumerSchema=z147.discriminatedUnion("role",[z147.strictObject({role:z147.literal("PRIMARY_VISUAL"),clipOrdinal:z147.int().min(1).max(200)}),z147.strictObject({role:z147.literal("VISUAL_LAYER"),visualLayerId:z147.uuid()})]);var Consumers=z147.array(CompositionRepairConsumerSchema).min(1).max(208).refine(items=>new Set(items.map(i=>i.role==="PRIMARY_VISUAL"?i.role+i.clipOrdinal:i.role+i.visualLayerId)).size===items.length,"Coordinated consumers must be unique exact occurrences");var CompositionRepairPatchSchema=z147.discriminatedUnion("kind",[ParameterValue,z147.strictObject({kind:z147.literal("BINDING_REPLACE"),binding:Binding})]);var ReviseCompositionRepairActionSchema=z147.strictObject({kind:z147.literal("REVISE_COMPOSITION"),localityIndex:z147.int().min(0).max(207),patches:z147.array(CompositionRepairPatchSchema).min(1).max(16),coordinatedConsumers:Consumers.optional()}).superRefine((v,ctx)=>{const names=v.patches.map(p=>p.kind+":"+(p.kind==="PARAMETER_VALUE"?p.name:p.binding.name));if(new Set(names).size!==names.length)ctx.addIssue({code:"custom",message:"Local Composition patch targets must be unique"})});var CompositionRepairSubjectSchema=z147.strictObject({locality:CompositionFindingLocalitySchema,composition:CompositionViewSchema,render:CompositionRenderViewSchema});var{idempotencyKey,...revisionShape}=ReviseCompositionSchema.shape;var RevisionDraft=z147.strictObject(revisionShape).refine(v=>v.content.role!=="PRIMARY_VISUAL"||v.basis.shotId!==null,"Primary repair retains an exact planned Shot");var CompositionRepairHandoffSchema=z147.strictObject({kind:z147.literal("COMPOSITION_REVISE"),locality:CompositionFindingLocalitySchema,input:RevisionDraft,renderProfileId:z147.enum(["HYPERFRAME_1080P30_FULL_PAINT_V1","HYPERFRAME_1080P30_FRAME_CACHE_V2","HYPERFRAME_RGBA_PNG30_FULL_PAINT_V1"]),sourceReviewRequired:z147.boolean(),coordinatedConsumers:Consumers.optional()}).superRefine((v,ctx)=>{if(v.input.compositionId!==v.locality.compositionId||v.input.previousVersionId!==v.locality.compositionVersionId||v.input.expectedVersion!==v.locality.compositionVersion||v.input.content.role!==v.locality.role||v.coordinatedConsumers?.some(i=>i.role!==v.locality.role)||v.sourceReviewRequired!==(v.locality.role==="PRIMARY_VISUAL")||!(v.locality.role==="PRIMARY_VISUAL"?["HYPERFRAME_1080P30_FULL_PAINT_V1","HYPERFRAME_1080P30_FRAME_CACHE_V2"].includes(v.renderProfileId):v.renderProfileId==="HYPERFRAME_RGBA_PNG30_FULL_PAINT_V1"))ctx.addIssue({code:"custom",message:"Composition repair handoff must retain exact locality identity, role and original output profile"})});var text=z148.string().trim().min(1).max(2e3);var key5=z148.string().regex(/^[a-z][a-z0-9_-]{0,39}$/);var RepairStrategyContextInputSchema=z148.strictObject({scope:DirectorScopeSchema,findingId:z148.uuid()});var RepairStrategyBasisSchema=RepairStrategyContextInputSchema.extend({contextFingerprint:z148.string().regex(/^[0-9a-f]{64}$/)});var RepairStrategyActionSchema=z148.discriminatedUnion("kind",[ReviseCompositionRepairActionSchema,z148.strictObject({kind:z148.literal("TRIM_CLIP"),ordinal:z148.int().min(1).max(200),sourceInMs:z148.int().nonnegative().max(30150),sourceOutMs:z148.int().positive().max(30150)}),z148.strictObject({kind:z148.literal("REVISE_CAPTIONS"),content:CaptionContentSchema}),z148.strictObject({kind:z148.literal("ADJUST_TRANSITION"),ordinal:z148.int().min(2).max(200),transition:ClipTransitionSchema}),z148.strictObject({kind:z148.literal("ADJUST_AUDIO_COMPOSITION"),audio:TimelineAudioInputSchema}),z148.strictObject({kind:z148.literal("ACKNOWLEDGE_WARNINGS"),acknowledgements:z148.array(z148.strictObject({key:z148.string().min(1).max(220),reason:text})).min(1).max(300)}),z148.strictObject({kind:z148.literal("REGENERATE_SHOT"),shotId:z148.uuid()}),z148.strictObject({kind:z148.literal("REQUEST_HUMAN_INPUT"),question:text}),z148.strictObject({kind:z148.literal("REQUEST_CANONICAL_CHANGE"),requestedChange:text})]);var RepairStrategyAlternativeSchema=z148.strictObject({id:key5,rationale:text,whySmallerChangeInsufficient:text,action:RepairStrategyActionSchema});var ValidateRepairStrategySchema=z148.strictObject({basis:RepairStrategyBasisSchema,proposal:z148.strictObject({origin:z148.strictObject({kind:z148.literal("EXTERNAL_AGENT_HOST"),label:z148.string().trim().min(1).max(100)}),summary:text,alternatives:z148.array(RepairStrategyAlternativeSchema).min(1).max(6),selectedAlternativeId:key5})}).refine(v=>new TextEncoder().encode(JSON.stringify(v)).byteLength<=1024*1024,"Repair Strategy input exceeds the 1 MiB JSON budget");var RepairStrategyContextResultSchema=z148.strictObject({compositionRepairAvailable:z148.boolean().optional(),semanticStatus:z148.literal("SUCCESS"),advisory:z148.literal(true),basis:RepairStrategyBasisSchema,ownerContext:DirectorContextResultSchema,finding:RoughCutFindingViewSchema,reviewTarget:RoughCutReviewTargetSchema,finalReady:FinalReadyViewSchema,eligibility:z148.strictObject({ready:z148.boolean(),reasons:z148.array(z148.enum(["FINDING_NOT_OPEN","TARGET_STALE","MEDIA_UNAVAILABLE","PRODUCTION_UNAVAILABLE","REVIEW_CHANGED","FINDING_BASIS_CHANGED"])).max(6)})});var RepairStrategyHandoffSchema=z148.discriminatedUnion("kind",[CompositionRepairHandoffSchema,z148.strictObject({kind:z148.literal("TIMELINE_BUILD"),input:BuildTimelineShapeSchema.omit({idempotencyKey:true})}),z148.strictObject({kind:z148.literal("CAPTION_AUTHOR"),input:AuthorCaptionsSchema.omit({idempotencyKey:true})}),z148.strictObject({kind:z148.literal("FINAL_READY_DECIDE"),input:DecideFinalReadySchema.omit({idempotencyKey:true})}),z148.strictObject({kind:z148.literal("REGENERATION_INTENT"),preparationQuery:PreparationActiveInputSchema,admission:z148.literal("EXPLICIT_NATIVE_PREPARATION_AND_SELECTION_REQUIRED")}),z148.strictObject({kind:z148.literal("HUMAN_INPUT_INTENT"),question:text}),z148.strictObject({kind:z148.literal("CANONICAL_CHANGE_INTENT"),requestedChange:text})]);var RepairStrategyValidationResultSchema=z148.strictObject({semanticStatus:z148.literal("SUCCESS"),advisory:z148.literal(true),basis:RepairStrategyBasisSchema,proposal:ValidateRepairStrategySchema.shape.proposal,finding:RoughCutFindingViewSchema,alternatives:z148.array(z148.strictObject({alternativeId:key5,affectedScope:RoughCutFindingViewSchema.shape.affectedScope,handoff:RepairStrategyHandoffSchema,materialChange:z148.boolean(),preservedAcceptanceIds:z148.array(z148.uuid()).max(200),followUp:z148.array(z148.enum(["REVOKE_FINAL_READY_AND_REFRESH","REFRESH_TIMELINE_BASIS","ATTACH_NEW_CAPTION","REFRESH_AND_PREPARE_SHOT","EXPLICIT_VIDEO_GENERATION","REVIEW_1","SHOT_ACCEPTANCE","REBUILD_TIMELINE","ROUGH_CUT_RENDER","REVIEW_2","FINAL_READY_DECISION","AUTHORIZED_PLANNING_DECISION","COMPOSITION_REVISE","COMPOSITION_RENDER"])).max(10)})).min(1).max(6),selectedAlternativeId:key5,limitations:z148.tuple([z148.literal("NO_CANONICAL_REPAIR_LIFECYCLE_OR_WRITE"),z148.literal("READS_ARE_NOT_ATOMIC_OR_RESERVED"),z148.literal("CREATIVE_RATIONALE_IS_NOT_VERIFIED"),z148.literal("OWNER_RECHECKS_CAS_IDEMPOTENCY_AND_EXECUTION_CLASS"),z148.literal("MATERIAL_REPAIR_REQUIRES_NEW_OBSERVATION_AND_REVIEW")])}).superRefine((v,ctx)=>{const ids=v.alternatives.map(a=>a.alternativeId);const proposed=v.proposal.alternatives.map(a=>a.id);if(v.finding.id!==v.basis.findingId||v.finding.tenantId!==v.basis.scope.tenantId||v.finding.projectId!==v.basis.scope.projectId||v.finding.productionId!==v.basis.scope.productionId||v.selectedAlternativeId!==v.proposal.selectedAlternativeId||!ids.includes(v.selectedAlternativeId)||new Set(ids).size!==ids.length||ids.length!==proposed.length||ids.some(id15=>!proposed.includes(id15)))ctx.addIssue({code:"custom",message:"Repair validation must retain exact Finding and proposal selection"});for(const alternative of v.alternatives){const h=alternative.handoff;if("input"in h&&(h.input.tenantId!==v.basis.scope.tenantId||h.input.productionId!==v.basis.scope.productionId))ctx.addIssue({code:"custom",message:"Repair handoff must retain the exact native Tenant/Production scope"})}});import{z as z149}from"zod";var text2=z149.string().trim().min(1).max(2e3);var key6=z149.string().regex(/^[a-z][a-z0-9_-]{0,39}$/);var EditorContextInputSchema=z149.strictObject({scope:DirectorScopeSchema,timelineVersionId:z149.uuid()});var EditorBasisSchema=EditorContextInputSchema.extend({contextFingerprint:z149.string().regex(/^[0-9a-f]{64}$/)});var EditorAlternativeSchema=z149.strictObject({id:key6,rationale:text2,pacingIntent:text2,action:z149.discriminatedUnion("kind",[z149.strictObject({kind:z149.literal("BUILD_TIMELINE"),clips:BuildTimelineSchema.shape.clips}),z149.strictObject({kind:z149.literal("EDIT_GRAPHICS"),graphics:z149.array(TimelineGraphicInputSchema).min(1).max(8)}),z149.strictObject({kind:z149.literal("EDIT_VISUAL_LAYERS"),visualLayers:z149.array(TimelineVisualLayerInputSchema).min(1).max(8)}),z149.strictObject({kind:z149.literal("EDIT_AUDIO_COMPOSITION"),audio:TimelineAudioInputSchema}),z149.strictObject({kind:z149.literal("REVISE_CAPTIONS"),content:CaptionContentSchema}),z149.strictObject({kind:z149.literal("REQUEST_COMPOSITION_CAPABILITY"),concern:z149.enum(["TRANSITION","AUDIO_VISUAL_ALIGNMENT","VOICE_TIMING","CAPTION_RETIMING"]),requestedChange:text2}),z149.strictObject({kind:z149.literal("REQUEST_HUMAN_INPUT"),question:text2})])});var ValidateEditorProposalSchema=z149.strictObject({basis:EditorBasisSchema,proposal:z149.strictObject({origin:z149.strictObject({kind:z149.literal("EXTERNAL_AGENT_HOST"),label:z149.string().trim().min(1).max(100)}),summary:text2,alternatives:z149.array(EditorAlternativeSchema).min(1).max(6),selectedAlternativeId:key6})}).refine(v=>new TextEncoder().encode(JSON.stringify(v)).byteLength<=1024*1024,"Editor Intelligence input exceeds the 1 MiB JSON budget");var EditorContextResultSchema=z149.strictObject({semanticStatus:z149.literal("SUCCESS"),advisory:z149.literal(true),basis:EditorBasisSchema,ownerContext:DirectorContextResultSchema,timeline:TimelineViewSchema,timelineBasis:TimelineBasisSchema,finalReady:FinalReadyViewSchema,eligibility:z149.strictObject({ready:z149.boolean(),reasons:z149.array(z149.enum(["TIMELINE_NOT_CURRENT","TIMELINE_STALE","PRODUCTION_UNAVAILABLE","PLANNING_NOT_READY","CREATIVE_BASIS_CHANGED","NO_CURRENT_ACCEPTED_MEDIA","COMPOSITION_VERSION_UNSUPPORTED"])).max(7)})});var ReviewScope=z149.strictObject({kind:z149.literal("PRODUCTION"),interval:z149.strictObject({startMs:z149.literal(0),endMs:z149.int().positive().max(603e4)}),shotIds:z149.array(z149.uuid()).min(1).max(200),dimensions:z149.array(z149.enum(["PACING","ORDERING","CUT_CONTINUITY","PRODUCT_PRESENTATION","CAPTION_TIMING_VISIBILITY","AUDIO_VISUAL_ALIGNMENT","BASIC_MIX"])).min(4).max(7),requirement:z149.literal("COMPLETE_NEW_OUTPUT_INSPECTION")});var EditorHandoffSchema=z149.discriminatedUnion("kind",[z149.strictObject({kind:z149.literal("TIMELINE_BUILD"),input:BuildTimelineShapeSchema.omit({idempotencyKey:true}),preview:TimelineManifestReaderSchema,assemblyStatus:z149.enum(["DRAFT","ASSEMBLY_READY"]),changedOrdinals:z149.array(z149.int().positive().max(200)).max(200),changedGraphicArtifactIds:z149.array(z149.uuid()).max(8),changedAudioPurposes:z149.array(z149.enum(["VOICEOVER","MUSIC"])).max(2),preservedAcceptanceIds:z149.array(z149.uuid()).max(200),reviewScope:ReviewScope,followUp:z149.array(z149.enum(["NATIVE_TIMELINE_BUILD","COMPLETE_TIMELINE","ROUGH_CUT_RENDER","REVIEW_2","FINAL_READY_DECISION"])).min(4).max(5)}),z149.strictObject({kind:z149.literal("CAPTION_AUTHOR"),input:AuthorCaptionsSchema.omit({idempotencyKey:true}),attachment:z149.strictObject({expectedTimelineVersion:z149.int().positive(),preserveCurrentComposition:z149.literal(true),composition:z149.strictObject({schemaVersion:BuildTimelineShapeSchema.shape.schemaVersion,clips:BuildTimelineSchema.shape.clips,audio:BuildTimelineSchema.shape.audio.optional(),sourceSound:BuildTimelineShapeSchema.shape.sourceSound,graphics:BuildTimelineSchema.shape.graphics.optional(),visualLayers:BuildTimelineShapeSchema.shape.visualLayers})}),followUp:z149.tuple([z149.literal("NATIVE_CAPTION_AUTHOR"),z149.literal("ATTACH_NEW_CAPTION_TO_TIMELINE"),z149.literal("ROUGH_CUT_RENDER"),z149.literal("REVIEW_2"),z149.literal("FINAL_READY_DECISION")])}),z149.strictObject({kind:z149.literal("COMPOSITION_CAPABILITY_INTENT"),concern:z149.enum(["TRANSITION","AUDIO_VISUAL_ALIGNMENT","VOICE_TIMING","CAPTION_RETIMING"]),requestedChange:text2,admission:z149.literal("EXPLICIT_CANONICAL_CAPABILITY_REQUIRED")}),z149.strictObject({kind:z149.literal("HUMAN_INPUT_INTENT"),question:text2})]);var EditorValidationResultSchema=z149.strictObject({semanticStatus:z149.literal("SUCCESS"),advisory:z149.literal(true),basis:EditorBasisSchema,proposal:ValidateEditorProposalSchema.shape.proposal,alternatives:z149.array(z149.strictObject({alternativeId:key6,handoff:EditorHandoffSchema})).min(1).max(6),selectedAlternativeId:key6,limitations:z149.tuple([z149.literal("NO_TIMELINE_WRITE_RENDER_OR_PROVIDER_CALL"),z149.literal("READS_ARE_NOT_ATOMIC_OR_RESERVED"),z149.literal("CREATIVE_RATIONALE_IS_NOT_VERIFIED"),z149.literal("OWNER_RECHECKS_CAS_IDEMPOTENCY_AND_EXECUTION_CLASS"),z149.literal("EDIT_REQUIRES_NEW_OUTPUT_INSPECTION_AND_REVIEW")])});import{z as z150}from"zod";var scope5={tenantId:z150.uuid(),productionId:z150.uuid()};var TemporalEvidenceTargetSchema=z150.strictObject({...scope5,artifactId:z150.uuid(),representationId:z150.uuid(),checksumSha256:z150.string().regex(/^[0-9a-f]{64}$/)});var OriginalVideoReadSchema=TemporalEvidenceTargetSchema;var OriginalVideoResultSchema=z150.strictObject({source:TemporalEvidenceSourceSchema,contentType:z150.literal("video/mp4"),dataBase64:z150.string().min(4).max(4*Math.ceil(8*1024*1024/3)).regex(/^[A-Za-z0-9+/]+={0,2}$/)}).refine(v=>{const padding=v.dataBase64.endsWith("==")?2:v.dataBase64.endsWith("=")?1:0;return v.dataBase64.length%4===0&&v.source.byteSize<=8*1024*1024&&v.dataBase64.length/4*3-padding===v.source.byteSize},"Original video must match its exact bounded byte size");var TemporalEvidenceStartSchema=TemporalEvidenceTargetSchema.extend({profile:TemporalSamplingProfileSchema,expectedProductionRevision:z150.int().positive(),idempotencyKey:z150.string().trim().min(1).max(128),deviceId:z150.uuid().toLowerCase().optional()});var TemporalEvidenceGetSchema=z150.strictObject({...scope5,evidenceId:z150.uuid()});var TemporalEvidenceAdmissionSchema=z150.strictObject({semanticStatus:z150.literal("ACCEPTED"),evidenceId:z150.uuid(),runtimeJobId:z150.uuid(),operationId:z150.string().min(1),source:TemporalEvidenceSourceSchema,planFingerprint:z150.string().regex(/^[0-9a-f]{64}$/),productionRevision:z150.int().positive()});var TemporalEvidenceOutputSchema=z150.strictObject({frameSetArtifactId:z150.uuid(),manifestRepresentationId:z150.uuid(),frameRepresentationIds:z150.array(z150.uuid()).min(1).max(64),contactSheetArtifactId:z150.uuid(),sheetRepresentationId:z150.uuid(),manifest:TemporalEvidenceManifestSchema,createdAt:z150.iso.datetime({offset:true})}).refine(v=>v.frameRepresentationIds.length===v.manifest.frames.length&&new Set(v.frameRepresentationIds).size===v.frameRepresentationIds.length,"Exact frame representations must be complete and unique");var TemporalEvidenceViewSchema=z150.strictObject({evidenceId:z150.uuid(),runtimeJobId:z150.uuid(),operationId:z150.string().min(1),source:TemporalEvidenceSourceSchema,planFingerprint:z150.string().regex(/^[0-9a-f]{64}$/),runtimeState:z150.enum(["PENDING","READY","RUNNING","WAITING","SUCCEEDED","FAILED","CANCELLED","SUPERSEDED"]),output:TemporalEvidenceOutputSchema.nullable()});var TemporalEvidenceMediaSchema=TemporalEvidenceGetSchema.extend({kind:z150.enum(["FRAME","SHEET","MANIFEST"]),ordinal:z150.int().nonnegative().max(63).optional()}).refine(v=>v.kind==="FRAME"?v.ordinal!==void 0:v.ordinal===void 0,"Only individual frames require an ordinal");var TemporalEvidenceImageSchema=TemporalEvidenceMediaSchema.safeExtend({kind:z150.enum(["FRAME","SHEET"])});var TemporalEvidenceImageMetadataSchema=TemporalEvidenceImageSchema.safeExtend({contentType:z150.literal("image/png"),checksumSha256:z150.string().regex(/^[0-9a-f]{64}$/),byteSize:z150.int().positive().max(16*1024*1024)});import{z as z151}from"zod";var Text2=z151.string().trim().min(1).max(1e3);var bounded=(value2,bytes)=>new TextEncoder().encode(JSON.stringify(value2)).byteLength<=bytes;var ExplorationComparisonCriterionSchema=z151.strictObject({key:ReviewEvidenceKeySchema,description:Text2,modality:z151.enum(["VISUAL","TEMPORAL"])});var ExplorationRecommendationContextInputSchema=ExplorationCompareInputSchema.extend({criteria:z151.array(ExplorationComparisonCriterionSchema).min(1).max(8)}).superRefine((v,c)=>{if(new Set(v.items.map(i=>i.mediaType)).size!==1)c.addIssue({code:"custom",message:"Recommendation compares one media type"});if(new Set(v.items.map(i=>i.label)).size!==v.items.length||new Set(v.items.map(i=>i.generationId.toLowerCase())).size!==v.items.length)c.addIssue({code:"custom",message:"Labels and generation identities must be distinct"});if(new Set(v.criteria.map(i=>i.key)).size!==v.criteria.length)c.addIssue({code:"custom",message:"Comparison criterion keys must be distinct"});if(v.items[0].mediaType==="IMAGE"&&v.criteria.some(i=>i.modality==="TEMPORAL"))c.addIssue({code:"custom",message:"Temporal comparison requires VIDEO"});if(!bounded(v,1024*1024))c.addIssue({code:"custom",message:"Recommendation input exceeds 1 MiB"})});var ExplorationRecommendationBasisSchema=z151.strictObject({input:ExplorationRecommendationContextInputSchema,contextFingerprint:z151.string().regex(/^[0-9a-f]{64}$/)});var ExplorationRecommendationCandidateSchema=z151.strictObject({label:ReviewEvidenceKeySchema,readiness:z151.enum(["REVIEWABLE","UNAVAILABLE"]),reasons:z151.array(z151.enum(["NO_CANDIDATE","STALE_BASIS","PRODUCTION_NOT_RUNNABLE","OUTPUT_NOT_INSPECTABLE"])).max(4),reviewContext:ReviewIntelligenceContextResultSchema.nullable()});var ExplorationRecommendationContextResultSchema=z151.strictObject({semanticStatus:z151.literal("SUCCESS"),advisory:z151.literal(true),basis:ExplorationRecommendationBasisSchema,comparison:ExplorationComparisonResultSchema,candidates:z151.array(ExplorationRecommendationCandidateSchema).min(2).max(6),limitations:z151.tuple([z151.literal("READS_ARE_NOT_ATOMIC_OR_RESERVED"),z151.literal("NO_IMPLICIT_MEDIA_OR_MODEL_CALL")])}).refine(v=>bounded(v,2*1024*1024),"Recommendation context exceeds 2 MiB");var ExplorationComparisonJudgmentSchema=z151.strictObject({label:ReviewEvidenceKeySchema,criterionKey:ReviewEvidenceKeySchema,judgment:z151.enum(["FAVORABLE","UNFAVORABLE","UNCERTAIN","NOT_OBSERVABLE"]),rationale:Text2,evidenceIds:z151.array(ReviewEvidenceKeySchema).max(16)});var ExplorationRecommendationDecisionSchema=z151.discriminatedUnion("kind",[z151.strictObject({kind:z151.literal("RECOMMEND"),label:ReviewEvidenceKeySchema,rationale:Text2,notSelected:z151.array(z151.strictObject({label:ReviewEvidenceKeySchema,reason:Text2})).min(1).max(5)}),z151.strictObject({kind:z151.literal("NO_RECOMMENDATION"),reason:Text2})]);var ValidateExplorationRecommendationSchema=z151.strictObject({basis:ExplorationRecommendationBasisSchema,proposal:z151.strictObject({origin:z151.strictObject({kind:z151.literal("EXTERNAL_AGENT_HOST"),label:z151.string().trim().min(1).max(100)}),summary:z151.string().trim().min(1).max(2e3),assessments:z151.array(z151.strictObject({label:ReviewEvidenceKeySchema,reviewProposal:ValidateReviewIntelligenceSchema.shape.proposal})).max(6),judgments:z151.array(ExplorationComparisonJudgmentSchema).max(48),decision:ExplorationRecommendationDecisionSchema,unknowns:z151.array(z151.string().trim().min(1).max(300)).max(8)})}).refine(v=>bounded(v,1024*1024),"Recommendation input exceeds 1 MiB");var ExplorationRecommendationValidationResultSchema=z151.strictObject({semanticStatus:z151.literal("SUCCESS"),advisory:z151.literal(true),basis:ExplorationRecommendationBasisSchema,origin:ValidateExplorationRecommendationSchema.shape.proposal.shape.origin,summary:z151.string(),judgments:z151.array(ExplorationComparisonJudgmentSchema).max(48),decision:ExplorationRecommendationDecisionSchema,unknowns:z151.array(z151.string()).max(8),reviews:z151.array(z151.strictObject({label:ReviewEvidenceKeySchema,validation:ReviewIntelligenceValidationResultSchema})).max(6),limitations:z151.tuple([z151.literal("HOST_PREFERENCE_IS_NOT_CANONICAL_SELECTION"),z151.literal("EVIDENCE_DECLARATIONS_ARE_NOT_ATTESTED_INSPECTION"),z151.literal("RULE_PREVIEWS_ARE_NOT_CANONICAL_REVIEWS"),z151.literal("EXPLICIT_RECORD_AND_SEPARATE_ACCEPTANCE_REQUIRED"),z151.literal("OWNER_RECHECKS_CURRENTNESS_CAS_AND_EXECUTION_CLASS")])}).refine(v=>bounded(v,4*1024*1024),"Recommendation result exceeds 4 MiB");import{z as z153}from"zod";import{z as z152}from"zod";var Review1FindingSchema=z152.strictObject({id:z152.uuid(),tenantId:TenantIdSchema,projectId:ProjectIdSchema,productionId:ProductionIdSchema,shotId:ShotIdSchema,mediaType:z152.enum(["IMAGE","VIDEO"]),framePurpose:z152.string().max(40).optional(),generationId:z152.uuid(),candidateId:z152.uuid(),reviewId:z152.uuid(),artifactId:z152.uuid(),representationId:z152.uuid(),checksumSha256:z152.string().regex(/^[0-9a-f]{64}$/),preparationId:z152.uuid(),contractId:z152.uuid(),contractFingerprint:z152.string().regex(/^[0-9a-f]{64}$/),executionClass:z152.enum(["LIVE","TEST_ONLY"]),requirement:z152.union([VideoReviewRequirementSchema,VisualRequirementSchema]),observation:z152.union([VideoObservationSchema,KeyframeObservationSchema]),blocking:z152.boolean(),severity:z152.enum(["BLOCKING","WARNING"]),basisFingerprint:z152.string().regex(/^[0-9a-f]{64}$/),createdAt:z152.iso.datetime({offset:true})}).superRefine((v,c)=>{if(v.requirement.key!==v.observation.key||v.blocking!==(v.severity==="BLOCKING"))c.addIssue({code:"custom",message:"Finding must bind its exact native obligation"})});var Review1FindingViewSchema=Review1FindingSchema.safeExtend({lifecycle:z152.enum(["OPEN","REMEDIATION_PLANNED","RESOLVED","SUPERSEDED"]),proofReviewId:z152.uuid().nullable()});var Review1RepairSourceSchema=z152.strictObject(Review1FindingSchema.shape).omit({id:true,createdAt:true}).superRefine((v,c)=>{if(v.requirement.key!==v.observation.key||v.blocking!==(v.severity==="BLOCKING"))c.addIssue({code:"custom",message:"Source must bind its exact native obligation"})});var Review1RepairSourceQuerySchema=z152.strictObject({tenantId:TenantIdSchema,projectId:ProjectIdSchema,productionId:ProductionIdSchema,mediaType:z152.enum(["IMAGE","VIDEO"]),generationId:z152.uuid(),reviewId:z152.uuid(),requirementKey:z152.string().min(1).max(220)});var sha20=z153.string().regex(/^[0-9a-f]{64}$/);var handoffs={REVISE_COMPOSITION:"COMPOSITION_REVISE",TRIM_CLIP:"TIMELINE_BUILD",ADJUST_TRANSITION:"TIMELINE_BUILD",ADJUST_AUDIO_COMPOSITION:"TIMELINE_BUILD",REVISE_CAPTIONS:"CAPTION_AUTHOR",ACKNOWLEDGE_WARNINGS:"FINAL_READY_DECIDE",REGENERATE_SHOT:"REGENERATION_INTENT",REQUEST_HUMAN_INPUT:"HUMAN_INPUT_INTENT",REQUEST_CANONICAL_CHANGE:"CANONICAL_CHANGE_INTENT"};var SemanticRepairBudgetSchema=z153.strictObject({maxSemanticAttempts:z153.int().min(1).max(20),maxElapsedMs:z153.int().min(1).max(864e5),currency:z153.literal("USD"),maxCostMicros:z153.int().min(0).max(1e9),maxConsecutiveNoImprovement:z153.int().min(1).max(20)});var RepairPlanScopeSchema=z153.strictObject({tenantId:TenantIdSchema,productionId:ProductionIdSchema,planId:z153.uuid()});var AuthorRepairPlanSchema=z153.strictObject({strategy:ValidateRepairStrategySchema,expectedProductionRevision:z153.int().positive(),expectedCaseVersion:z153.int().nonnegative(),budget:SemanticRepairBudgetSchema,idempotencyKey:z153.string().trim().min(1).max(200)}).superRefine((v,c)=>{const p=v.strategy.proposal;if(new Set(p.alternatives.map(a=>a.id)).size!==p.alternatives.length||!p.alternatives.some(a=>a.id===p.selectedAlternativeId))c.addIssue({code:"custom",message:"Repair authoring requires unique alternatives and an explicit selection"})});var RepairDecisionSchema=z153.strictObject({id:z153.uuid(),tenantId:TenantIdSchema,projectId:ProjectIdSchema,productionId:ProductionIdSchema,caseId:z153.uuid(),caseVersion:z153.int().positive(),basis:RepairStrategyBasisSchema,sourceReviewId:z153.uuid(),sourceRenderId:z153.uuid().nullable(),review1Source:Review1FindingSchema.optional(),sourceBasisFingerprint:sha20,affectedScopeFingerprint:sha20,obligationFingerprint:sha20,proposal:ValidateRepairStrategySchema.shape.proposal,selectedAlternativeId:z153.string().regex(/^[a-z][a-z0-9_-]{0,39}$/),handoff:RepairStrategyHandoffSchema,budget:SemanticRepairBudgetSchema,createdByPrincipalId:PrincipalIdSchema,createdAt:z153.iso.datetime({offset:true})}).superRefine((d,c)=>{if(d.sourceRenderId===null!==!!d.review1Source||d.review1Source&&(d.review1Source.id!==d.basis.findingId||d.review1Source.reviewId!==d.sourceReviewId||d.review1Source.tenantId!==d.tenantId||d.review1Source.projectId!==d.projectId||d.review1Source.productionId!==d.productionId||d.handoff.kind!=="REGENERATION_INTENT"))c.addIssue({code:"custom",message:"Repair must retain its native Review layer and source"});if(d.basis.scope.tenantId!==d.tenantId||d.basis.scope.productionId!==d.productionId||d.basis.scope.projectId!==d.projectId)c.addIssue({code:"custom",message:"Repair Decision scope must be exactly owned"});if(d.selectedAlternativeId!==d.proposal.selectedAlternativeId||new Set(d.proposal.alternatives.map(a=>a.id)).size!==d.proposal.alternatives.length||!d.proposal.alternatives.some(a=>a.id===d.selectedAlternativeId&&handoffs[a.action.kind]===d.handoff.kind))c.addIssue({code:"custom",message:"Repair Decision must bind the explicit selected alternative"})});var SemanticRepairAttemptSchema=z153.strictObject({id:z153.uuid(),planId:z153.uuid(),caseId:z153.uuid(),ordinal:z153.int().min(1).max(20),executionIdentity:z153.string().trim().min(1).max(200),strategyFingerprint:sha20,startedAt:z153.iso.datetime({offset:true}),reservedCostMicros:z153.int().min(0).max(1e9),chargedCostMicros:z153.int().min(0).max(1e9).nullable(),currency:z153.literal("USD"),outcome:z153.enum(["IN_FLIGHT","AWAITING_REVIEW","IMPROVED","NO_IMPROVEMENT","OPERATIONAL_FAILURE","WAIVED"])});var RecordRepairProofSchema=RepairPlanScopeSchema.extend({attemptId:z153.uuid(),renderId:z153.uuid(),reviewId:z153.uuid(),expectedProductionRevision:z153.int().positive(),idempotencyKey:z153.string().trim().min(1).max(200)});import{z as z154}from"zod";var AuthorReview1RepairSchema=z154.strictObject({tenantId:TenantIdSchema,projectId:ProjectIdSchema,productionId:ProductionIdSchema,mediaType:z154.enum(["IMAGE","VIDEO"]),generationId:z154.uuid(),reviewId:z154.uuid(),requirementKey:z154.string().min(1).max(220),reason:z154.string().trim().min(1).max(2e3),expectedProductionRevision:z154.int().positive(),expectedCaseVersion:z154.int().nonnegative(),budget:SemanticRepairBudgetSchema,idempotencyKey:z154.string().trim().min(1).max(200)});var RecordReview1RepairProofSchema=RepairPlanScopeSchema.extend({attemptId:z154.uuid(),generationId:z154.uuid(),reviewId:z154.uuid(),expectedProductionRevision:z154.int().positive(),idempotencyKey:z154.string().trim().min(1).max(200)});import{z as z155}from"zod";var ExecuteRepairSchema=RepairPlanScopeSchema.extend({expectedProductionRevision:z155.int().positive(),expectedCaseVersion:z155.int().positive(),idempotencyKey:z155.string().trim().min(1).max(200),generation:VideoStartInputSchema.omit({idempotencyKey:true}).optional(),keyframeGeneration:KeyframeStartInputSchema.omit({idempotencyKey:true}).optional()});var RepairAttemptEventSchema=z155.strictObject({id:z155.uuid(),attemptId:z155.uuid(),version:z155.int().positive(),outcome:SemanticRepairAttemptSchema.shape.outcome.exclude(["IN_FLIGHT"]),renderId:z155.uuid().nullable(),reviewId:z155.uuid().nullable(),generationId:z155.uuid().optional(),recordedAt:z155.iso.datetime({offset:true})});var RepairAttemptViewSchema=SemanticRepairAttemptSchema.extend({costQuote:GenerationCostQuoteSchema.optional(),events:z155.array(RepairAttemptEventSchema).max(40)});var RepairCaseViewSchema=z155.strictObject({id:z155.uuid(),version:z155.int().positive(),issueKey:z155.string().regex(/^[0-9a-f]{64}$/),budget:SemanticRepairBudgetSchema,openedAt:z155.iso.datetime({offset:true})});var RepairPlanViewSchema=z155.strictObject({review1Finding:Review1FindingViewSchema.optional(),decision:RepairDecisionSchema,repairCase:RepairCaseViewSchema,attempts:z155.array(RepairAttemptViewSchema).max(20)});var RepairAuthorReceiptSchema=z155.strictObject({semanticStatus:z155.literal("SUCCESS"),decision:RepairDecisionSchema,productionRevision:z155.int().positive()});var RepairExecutionReceiptSchema=z155.strictObject({costQuote:GenerationCostQuoteSchema.optional(),semanticStatus:z155.literal("ACCEPTED"),attempt:SemanticRepairAttemptSchema,decision:RepairDecisionSchema,productionRevision:z155.int().positive(),generation:ExecuteRepairSchema.shape.generation.nullable(),keyframeGeneration:ExecuteRepairSchema.shape.keyframeGeneration.nullable().optional()});var RepairProgressSchema=z155.strictObject({view:RepairPlanViewSchema,stage:z155.enum(["WAITING_INPUT","WAITING_GENERATION","WAITING_COMPOSITION_RENDER","WAITING_SOURCE_ACCEPTANCE","WAITING_RENDER","AWAITING_REVIEW","WAIVED","OPERATIONAL_FAILURE","IMPROVED","NO_IMPROVEMENT"]),renderId:z155.uuid().nullable(),generationId:z155.uuid().nullable()});var RepairProofReceiptSchema=z155.strictObject({semanticStatus:z155.literal("SUCCESS"),event:RepairAttemptEventSchema,productionRevision:z155.int().positive()});import{z as z156}from"zod";var EXTERNAL_EVENT_TYPES=["production.work_changed","production.started","production.failed","production.cancelled","finding.opened","artifact.created","shot.candidate_ready","shot.accepted","review.completed","rough_cut.ready","final_render.ready","approval.required","production.completed","delivery.validation_failed"];var ExternalEventTypeSchema=z156.enum(EXTERNAL_EVENT_TYPES);var LifecycleEventScopeSchema=z156.object({tenantId:TenantIdSchema,productionId:ProductionIdSchema}).strict();var ExternalLifecycleEventSchema=z156.object({schemaVersion:z156.literal(1),eventId:z156.uuid(),tenantId:TenantIdSchema,productionId:ProductionIdSchema,projectId:z156.uuid(),type:ExternalEventTypeSchema,target:z156.object({type:z156.string().min(1).max(60),id:z156.uuid()}).strict(),occurredAt:z156.iso.datetime(),basis:z156.object({productionRevision:z156.number().int().positive()}).strict(),payload:z156.object({sourceEventType:z156.string().min(1).max(100),artifactId:z156.uuid().optional(),candidateId:z156.uuid().optional(),reviewId:z156.uuid().optional(),findingId:z156.uuid().optional(),shotId:z156.uuid().optional(),manifestId:z156.uuid().optional(),validationId:z156.uuid().optional(),action:z156.string().max(40).optional(),result:z156.string().max(40).optional(),executionClass:z156.enum(["LIVE","TEST_ONLY"]).optional()}).strict()}).strict();var WebhookEndpointSchema=z156.url().max(2048).refine(value2=>{const u=new URL(value2);return u.protocol==="https:"&&!u.username&&!u.password&&!u.hash&&(!u.port||u.port==="443")&&!u.hostname.startsWith("[")});var ConfigureWebhookSchema=LifecycleEventScopeSchema.extend({subscriptionId:z156.uuid(),expectedRevision:z156.number().int().nonnegative(),idempotencyKey:z156.string().min(1).max(128),endpoint:WebhookEndpointSchema,eventTypes:z156.array(ExternalEventTypeSchema).min(1).max(EXTERNAL_EVENT_TYPES.length).refine(v=>new Set(v).size===v.length),signingSecret:z156.string().min(32).max(256)}).strict();var PrepareWebhookSecretSchema=LifecycleEventScopeSchema.extend({subscriptionId:z156.uuid(),secretRef:z156.uuid(),signingSecret:z156.string().min(32).max(256)}).strict();var WebhookSecretReferenceSchema=PrepareWebhookSecretSchema.omit({signingSecret:true});var ConfigureWebhookReferenceSchema=ConfigureWebhookSchema.omit({signingSecret:true}).extend({secretRef:z156.uuid()}).strict();var WebhookAvailabilitySchema=z156.discriminatedUnion("status",[z156.strictObject({status:z156.literal("AVAILABLE"),reason:z156.literal("SIGNING_STORAGE_READY")}),z156.strictObject({status:z156.literal("UNCONFIGURED"),reason:z156.literal("SIGNING_STORAGE_NOT_CONFIGURED")}),z156.strictObject({status:z156.literal("UNAVAILABLE"),reason:z156.literal("SIGNING_STORAGE_UNAVAILABLE")})]);var DisableWebhookSchema=LifecycleEventScopeSchema.extend({subscriptionId:z156.uuid(),expectedRevision:z156.number().int().positive(),idempotencyKey:z156.string().min(1).max(128)}).strict();var ReplayWebhookSchema=DisableWebhookSchema.extend({eventId:z156.uuid()}).strict();var QueryLifecycleEventsSchema=LifecycleEventScopeSchema.extend({kind:z156.enum(["subscriptions","events","deliveries","attempts"]),subscriptionId:z156.uuid().optional(),deliveryId:z156.uuid().optional(),after:z156.uuid().optional(),limit:z156.number().int().min(1).max(50).default(20)}).strict().refine(v=>v.kind!=="attempts"||!!v.deliveryId);var WebhookSubscriptionSchema=LifecycleEventScopeSchema.extend({subscriptionId:z156.uuid(),version:z156.number().int().positive(),revision:z156.number().int().positive(),state:z156.enum(["ACTIVE","DISABLED","DEGRADED"]),endpoint:WebhookEndpointSchema,eventTypes:z156.array(ExternalEventTypeSchema),updatedAt:z156.iso.datetime()}).strict();import{z as z157}from"zod";var WebhookReplayReceiptSchema=z157.strictObject({deliveryId:z157.uuid(),eventId:z157.uuid(),runtimeJobId:z157.uuid()});var WebhookDeliveryViewSchema=z157.strictObject({deliveryId:z157.uuid(),eventId:z157.uuid(),subscriptionId:z157.uuid(),subscriptionVersion:z157.int().positive(),replayNumber:z157.int().nonnegative(),runtimeJobId:z157.uuid(),lifecycle:z157.enum(["PENDING","READY","RUNNING","WAITING","SUCCEEDED","FAILED","CANCELLED","SUPERSEDED"]),runtimeAttempts:z157.int().nonnegative(),wakeAt:z157.iso.datetime({offset:true}).nullable()});var WebhookAttemptViewSchema=z157.strictObject({attemptId:z157.uuid(),runtimeAttemptId:z157.uuid(),outcome:z157.enum(["STARTED","ACKNOWLEDGED","TRANSIENT","PERMANENT","SKIPPED"]),responseStatus:z157.int().min(100).max(599).nullable(),startedAt:z157.iso.datetime({offset:true}),endedAt:z157.iso.datetime({offset:true}).nullable()});var page={next:z157.uuid().nullable()};var WebhookSubscriptionPageSchema=z157.strictObject({...page,items:z157.array(WebhookSubscriptionSchema).max(50)});var ExternalLifecycleEventPageSchema=z157.strictObject({...page,items:z157.array(ExternalLifecycleEventSchema).max(50)});var WebhookDeliveryPageSchema=z157.strictObject({...page,items:z157.array(WebhookDeliveryViewSchema).max(50)});var WebhookAttemptPageSchema=z157.strictObject({...page,items:z157.array(WebhookAttemptViewSchema).max(50)});var LifecycleEventCapabilitiesSchema=z157.strictObject({configuration:WebhookAvailabilitySchema,readinessScope:z157.literal("CURRENT_PROCESS_SIGNING_STORAGE"),deliveryConfirmation:z157.literal("READ_NATIVE_DELIVERIES_AND_ATTEMPTS"),eventTypes:z157.array(ExternalEventTypeSchema).max(14),unavailableNativeEvents:z157.array(z157.enum(["production.failed","production.cancelled","finding.opened"])).max(3),delivery:z157.literal("AT_LEAST_ONCE"),payload:z157.literal("QUERY_NOTIFICATION"),scope:z157.literal("PRODUCTION"),automaticOutboundAttempts:z157.literal(3),manualReplaysPerEvent:z157.literal(3),projectOnlyArtifacts:z157.literal("UNAVAILABLE"),orderingGuaranteed:z157.literal(false),signature:z157.literal("HMAC_SHA256_TIMESTAMP_DOT_EXACT_BODY")});import{z as z158}from"zod";var sha21=z158.string().regex(/^[0-9a-f]{64}$/);var CompositionSourceInspectSchema=CompositionGetSchema.extend({versionId:z158.uuid(),fingerprint:sha21,file:CompositionPathSchema.optional(),startLine:z158.int().min(1).max(8388609).default(1),lineLimit:z158.int().min(1).max(200).default(80)});var CompositionSourceInspectionSchema=z158.strictObject({composition:CompositionViewSchema,source:CompositionInputFactSchema,byteReadback:z158.literal("VERIFIED"),selection:z158.strictObject({file:CompositionPathSchema.nullable(),startLine:z158.int().positive(),lineLimit:z158.int().min(1).max(200)}),files:z158.array(z158.strictObject({path:CompositionPathSchema,contentType:z158.string().max(80),byteSize:z158.int().nonnegative().max(8388608),lineCount:z158.int().positive().max(8388609)})).min(1).max(128),window:z158.strictObject({file:CompositionPathSchema,startLine:z158.int().positive(),lines:z158.array(z158.strictObject({number:z158.int().positive(),text:z158.string().max(65536)})).max(200),hasMore:z158.boolean(),nextLine:z158.int().positive().nullable()}).nullable(),limitations:z158.tuple([z158.literal("SOURCE_INSPECTION_IS_NOT_OUTPUT_REVIEW"),z158.literal("READS_ARE_NOT_ATOMIC_OR_RESERVED")])});var SourceReviewContextInputSchema=z158.strictObject({scope:DirectorScopeSchema,source:CompositionSourceInspectSchema,renderId:z158.uuid().optional()}).refine(i=>i.scope.tenantId===i.source.tenantId&&i.scope.productionId===i.source.productionId,"Source Review retains exact Tenant/Production scope");var SourceReviewContextSchema=z158.strictObject({semanticStatus:z158.literal("SUCCESS"),advisory:z158.literal(true),basis:z158.strictObject({input:SourceReviewContextInputSchema,contextFingerprint:sha21}),ownerContext:DirectorContextResultSchema,source:CompositionSourceInspectionSchema,render:CompositionRenderViewSchema.nullable(),outputReviewTarget:ProgrammaticVideoReviewTargetSchema.nullable(),limitations:z158.tuple([z158.literal("SOURCE_REASONING_DOES_NOT_CERTIFY_OUTPUT_QUALITY"),z158.literal("INDEPENDENT_OUTPUT_REVIEW_AND_ACCEPTANCE_REQUIRED"),z158.literal("READS_ARE_NOT_ATOMIC_OR_RESERVED")])});import{z as z159}from"zod";var key7=z159.string().regex(/^[a-z][a-z0-9_-]{0,39}$/);var ProgrammaticCompareSchema=z159.strictObject({scope:ExplorationScopeSchema,items:z159.array(z159.strictObject({label:key7,renderId:z159.uuid()})).min(2).max(6)}).superRefine((i,c)=>{if(new Set(i.items.map(v=>v.label)).size!==i.items.length||new Set(i.items.map(v=>v.renderId.toLowerCase())).size!==i.items.length)c.addIssue({code:"custom",message:"Programmatic labels and exact renders must be distinct"})});var ProgrammaticComparisonSchema=z159.strictObject({semanticStatus:z159.literal("SUCCESS"),advisory:z159.literal(true),scope:ExplorationScopeSchema,selection:ProgrammaticCompareSchema.shape.items,items:z159.array(z159.strictObject({label:key7,sourceKind:z159.literal("PROGRAMMATIC"),composition:CompositionViewSchema,render:CompositionRenderViewSchema,reviewTarget:ProgrammaticVideoReviewTargetSchema.nullable()})).min(2).max(6),limitations:z159.tuple([z159.literal("OWNER_STATES_ARE_NOT_VISUAL_SCORES"),z159.literal("REVIEW_AND_ACCEPTANCE_REMAIN_EXPLICIT")])}).superRefine((v,c)=>{if(v.items.length!==v.selection.length||v.items.some((item,i)=>item.label!==v.selection[i].label||item.render.receipt.renderId!==v.selection[i].renderId))c.addIssue({code:"custom",message:"Programmatic comparison retains every exact selected label/render"});for(const item of v.items){const owner=item.composition.version,target3=item.reviewTarget;if(owner.tenantId!==v.scope.tenantId||owner.projectId!==v.scope.projectId||owner.productionId!==v.scope.productionId||owner.basis.shotId!==v.scope.shotId||owner.content.role!=="PRIMARY_VISUAL"||owner.id!==item.render.receipt.compositionVersionId||target3&&(target3.renderId!==item.render.receipt.renderId||target3.compositionVersionId!==owner.id||target3.tenantId!==v.scope.tenantId||target3.projectId!==v.scope.projectId||target3.productionId!==v.scope.productionId||target3.shotId!==v.scope.shotId))c.addIssue({code:"custom",message:"Programmatic comparison retains exact native source/output scope"})}}).refine(i=>new TextEncoder().encode(JSON.stringify(i)).byteLength<=2*1024*1024,"Programmatic comparison exceeds2MiB");var ProgrammaticRecommendationContextInputSchema=ProgrammaticCompareSchema.safeExtend({criteria:z159.array(ExplorationComparisonCriterionSchema).min(1).max(8)}).refine(i=>new Set(i.criteria.map(v=>v.key)).size===i.criteria.length,"Criteria must be distinct");var ProgrammaticRecommendationBasisSchema=z159.strictObject({input:ProgrammaticRecommendationContextInputSchema,contextFingerprint:z159.string().regex(/^[0-9a-f]{64}$/)});var ProgrammaticRecommendationContextSchema=z159.strictObject({semanticStatus:z159.literal("SUCCESS"),advisory:z159.literal(true),basis:ProgrammaticRecommendationBasisSchema,comparison:ProgrammaticComparisonSchema,candidates:z159.array(ExplorationRecommendationCandidateSchema).min(2).max(6),limitations:z159.tuple([z159.literal("READS_ARE_NOT_ATOMIC_OR_RESERVED"),z159.literal("NO_IMPLICIT_MEDIA_OR_MODEL_CALL")])}).superRefine((v,c)=>{if(JSON.stringify(v.basis.input.scope)!==JSON.stringify(v.comparison.scope)||JSON.stringify(v.basis.input.items)!==JSON.stringify(v.comparison.selection)||v.candidates.length!==v.comparison.items.length||v.candidates.some((candidate,i)=>candidate.label!==v.comparison.items[i].label))c.addIssue({code:"custom",message:"Programmatic Recommendation keeps exact comparison scope/selection"});for(const candidate of v.candidates){const target3=candidate.reviewContext?.reviewTarget;const item=v.comparison.items.find(i=>i.label===candidate.label);if(target3&&(target3.kind!=="PROGRAMMATIC"||target3.target.renderId!==item?.render.receipt.renderId||target3.target.compositionVersionId!==item.composition.version.id))c.addIssue({code:"custom",message:"Candidate assessment binds the exact native CODE output"})}}).refine(i=>new TextEncoder().encode(JSON.stringify(i)).byteLength<=2*1024*1024,"Programmatic recommendation context exceeds2MiB");var ValidateProgrammaticRecommendationSchema=z159.strictObject({basis:ProgrammaticRecommendationBasisSchema,proposal:ValidateExplorationRecommendationSchema.shape.proposal}).refine(i=>new TextEncoder().encode(JSON.stringify(i)).byteLength<=1024*1024,"Programmatic recommendation input exceeds1MiB");var ProgrammaticRecommendationValidationSchema=z159.strictObject({...ExplorationRecommendationValidationResultSchema.shape,basis:ProgrammaticRecommendationBasisSchema}).superRefine((v,c)=>{const s=v.basis.input.scope;for(const assessment of v.reviews){const item=v.basis.input.items.find(i=>i.label===assessment.label),draft2=assessment.validation.recordDraft;if(!item||draft2.kind!=="PROGRAMMATIC"||draft2.input.renderId!==item.renderId||draft2.input.tenantId!==s.tenantId||draft2.input.productionId!==s.productionId||assessment.validation.basis.scope.projectId!==s.projectId)c.addIssue({code:"custom",message:"Recommendation review draft binds exact CODE output and scope"})}}).refine(i=>new TextEncoder().encode(JSON.stringify(i)).byteLength<=4*1024*1024,"Programmatic recommendation result exceeds4MiB");import{z as z160}from"zod";var CompositionRenderQuerySchema=CompositionScopeSchema.extend({limit:z160.int().min(1).max(24).default(12),next:ContinuationSchema.optional(),shotId:z160.uuid().optional(),role:z160.enum(["PRIMARY_VISUAL","VISUAL_LAYER"]).default("PRIMARY_VISUAL")});var CompositionRenderObservationSchema=z160.strictObject({render:CompositionRenderViewSchema,createdAt:z160.iso.datetime({offset:true}),version:z160.int().positive(),executionClass:z160.enum(["LIVE","TEST_ONLY"]),freshness:z160.enum(["CURRENT_BASIS","STALE_BASIS"]),available:z160.boolean(),review:z160.strictObject({result:z160.enum(["UNREVIEWED","PASS","WARNING","FAIL"]),reviewId:z160.uuid().nullable(),acceptanceId:z160.uuid().nullable(),accepted:z160.boolean()})}).superRefine((v,ctx)=>{if(!v.render.sourceIdentity||v.review.result==="UNREVIEWED"!==(v.review.reviewId===null)||v.review.accepted!==(v.review.acceptanceId!==null)||v.review.accepted&&(!v.review.acceptanceId||!v.review.reviewId||!v.available||v.freshness!=="CURRENT_BASIS"||!["PASS","WARNING"].includes(v.review.result)))ctx.addIssue({code:"custom",message:"Observation requires exact native source/Review/acceptance identity"})});var CompositionRenderPageSchema=z160.strictObject({items:z160.array(CompositionRenderObservationSchema).max(24),page:QueryPageInfoSchema}).refine(v=>new TextEncoder().encode(JSON.stringify(v)).byteLength<=4194304,"Render observation page exceeds 4 MiB");var CompositionRenderMediaDescriptorSchema=z160.strictObject({path:z160.string().regex(/^\/v1\/productions\/[0-9a-f-]{36}\/compositions\/renders\/[0-9a-f-]{36}\/media$/i),contentType:z160.literal("video/mp4"),checksumSha256:z160.string().regex(/^[0-9a-f]{64}$/),byteSize:z160.int().positive().max(134217728),authentication:z160.literal("BEARER_AND_TENANT_HEADER")});import{z as z161}from"zod";var CompositionSampleStartSchema=CompositionRenderGetSchema.extend({expectedProductionRevision:z161.int().positive(),profile:TemporalSamplingProfileSchema,idempotencyKey:z161.string().trim().min(1).max(128)});var CompositionObserveGetSchema=CompositionRenderGetSchema.extend({evidenceId:z161.uuid()});var RenderObservationIdentitySchema=z161.strictObject({renderId:z161.uuid(),compositionVersionId:z161.uuid(),artifactId:z161.uuid(),representationId:z161.uuid(),checksumSha256:z161.string().regex(/^[0-9a-f]{64}$/)});var CompositionSampleReceiptSchema=RenderObservationIdentitySchema.extend({evidence:TemporalEvidenceAdmissionSchema,nextActions:z161.tuple([z161.literal("READ_OBSERVATION")])});var CompositionFrameObservationSchema=z161.strictObject({ordinal:z161.int().nonnegative().max(63),frameIndex:z161.int().nonnegative().max(3599),timestampMs:z161.number().nonnegative().max(6e4),checksumSha256:z161.string().regex(/^[0-9a-f]{64}$/),representationId:z161.uuid(),diagnostic:z161.literal("FRAME_EVIDENCE_READY")});var CompositionObservationViewSchema=RenderObservationIdentitySchema.extend({evidence:TemporalEvidenceViewSchema,frames:z161.array(CompositionFrameObservationSchema).max(64),contactSheetArtifactId:z161.uuid().nullable(),nextActions:z161.array(z161.enum(["READ_OBSERVATION","READ_FRAME_MEDIA","REVISE_COMPOSITION","RENDER_REVISION"])).min(1).max(4)});var scope6={projectId:ProjectIdSchema,productionId:ProductionIdSchema};var ScopedAcceptBriefSchema=AcceptBriefRequestSchema.extend(scope6);var ScopedAcceptStorySchema=AcceptStoryRequestSchema.extend(scope6);var ScopedAcceptSceneShotPlanSchema=AcceptSceneShotPlanRequestSchema.extend(scope6);import{z as z162}from"zod";var NativeToolAuthorityFailureSchema=z162.strictObject({semanticStatus:z162.enum(["INVALID_INPUT","NOT_FOUND","BLOCKED","REVISION_CONFLICT","CAPABILITY_UNAVAILABLE","INTERNAL_OPERATIONAL_FAILURE"]),error:z162.strictObject({code:z162.enum(["INVALID_INPUT","UNAUTHENTICATED","FORBIDDEN","NOT_FOUND","BINDING_UNAVAILABLE","REQUEST_CONFLICT","REVISION_CONFLICT","GRANT_CONFLICT","GRANT_EXPIRED","GRANT_REVOKED","PROOF_INVALID","PROOF_REPLAY","CHALLENGE_EXPIRED","PERMIT_UNAVAILABLE","QUALIFICATION_UNAVAILABLE","CREDENTIAL_INVALID","CREDENTIAL_EXPIRED","CREDENTIAL_UNAVAILABLE","CREDENTIAL_LIMIT","HOST_RUN_UNAVAILABLE","INTERNAL_OPERATIONAL_FAILURE"]),message:z162.literal("Native tool authority operation did not complete")})});import{z as z163}from"zod";var id12=z163.uuid().regex(/^[0-9a-f-]{36}$/);var sha22=z163.string().regex(/^[a-f0-9]{64}$/);var key8=z163.string().regex(/^[A-Za-z0-9_-]{1,160}$/);var NativeRuntimeQualificationSchema=z163.strictObject({protocol:z163.literal("NATIVESTUDIO_RUNTIME_TOOLS_V1"),runtimeKey:key8,installationId:key8,installationRevisionId:key8,resource:z163.url().max(2048),publicKeyFingerprint:sha22,bindingId:id12,configurationVersion:z163.int().positive(),selection:AgentHostReadSelectionSchema,capabilityDigest:sha22,executionClass:z163.enum(["LIVE","TEST_ONLY"]),transport:AgentHostInstallationTransportSchema.optional()});var NativeToolPermitSchema=z163.strictObject({proof:AgentHostNativeToolAuthoritySchema,input:AgentHostExecutionInputSchema,grant:NativeToolGrantViewSchema,qualification:NativeRuntimeQualificationSchema,requestedByPrincipalId:id12,createdAt:z163.iso.datetime({offset:true})}).refine(v=>v.proof.tenantId===v.input.tenantId&&v.proof.projectId===v.input.projectId&&v.proof.productionId===v.input.productionId&&v.proof.executionId===v.input.executionId&&v.proof.hostRequestId===v.input.hostRequestId&&v.grant.tenantId===v.input.tenantId&&v.grant.projectId===v.input.projectId&&v.grant.enabled&&v.grant.verifiedAt!==null&&v.proof.bindingId===v.grant.bindingId&&v.proof.configurationVersion===v.grant.configurationVersion&&v.qualification.runtimeKey===v.grant.runtimeKey&&v.qualification.installationId===v.grant.installationId&&v.qualification.installationRevisionId===v.grant.installationRevisionId&&v.qualification.resource===v.grant.resource&&v.qualification.bindingId===v.grant.bindingId&&v.qualification.configurationVersion===v.grant.configurationVersion&&v.qualification.capabilityDigest===v.proof.capabilityDigest&&v.qualification.executionClass===v.proof.executionClass&&(v.proof.transport===void 0?v.qualification.transport===void 0:v.qualification.transport?.protocol===v.proof.transport.protocol&&v.qualification.transport.installationId===v.proof.transport.installationId&&v.qualification.transport.installationRevisionId===v.proof.transport.installationRevisionId&&v.qualification.transport.slotKey===v.proof.transport.slotKey&&(v.proof.transport.protocol!=="NVS_AGENT_HOST_V1"||v.qualification.transport.protocol==="NVS_AGENT_HOST_V1"&&v.qualification.transport.contractDigest===v.proof.transport.contractDigest&&v.qualification.transport.capabilityDigest===v.proof.transport.capabilityDigest)&&v.proof.transport.installationId===v.grant.installationId&&v.proof.transport.installationRevisionId===v.grant.installationRevisionId)&&Date.parse(v.proof.expiresAt)<=Date.parse(v.grant.expiresAt));var NativeToolPermitGetSchema=AgentHostExecutionScopeSchema.extend({authorityRef:id12});var NativeExecutionProofClaimsSchema=AgentHostExecutionScopeSchema.extend({iss:key8,sub:key8,aud:z163.url().max(2048),grantId:id12,grantRevision:z163.int().positive(),installationRevisionId:key8,authorityRef:id12,executionId:id12,hostRequestId:id12,inputFingerprint:sha22,runKey:key8,jti:id12,iat:z163.int().nonnegative(),exp:z163.int().positive()}).refine(v=>v.exp>v.iat&&v.exp-v.iat<=60);var NativeToolCredentialExchangeSchema=NativeToolPermitGetSchema.extend({assertion:z163.string().regex(/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/).max(8192).meta({writeOnly:true})});var NativeToolCredentialMetadataSchema=NativeToolPermitGetSchema.extend({protocol:z163.literal("NATIVESTUDIO_NATIVE_CREDENTIAL_V1"),tokenId:id12,grantId:id12,grantRevision:z163.int().positive(),executionId:id12,hostRequestId:id12,runKey:key8,jti:id12,assertionFingerprint:sha22,tokenFingerprint:sha22,issuedAt:z163.iso.datetime({offset:true}),expiresAt:z163.iso.datetime({offset:true})});var NativeToolCredentialReplySchema=z163.strictObject({tokenType:z163.literal("Bearer"),accessToken:z163.string().regex(/^nvst_[0-9a-f-]{36}\.[A-Za-z0-9_-]{43}$/).meta({readOnly:true}),tokenId:id12,resource:z163.url().max(2048),expiresAt:z163.iso.datetime({offset:true})}).refine(v=>v.accessToken.startsWith(`nvst_${v.tokenId}.`));var NativeToolSessionSchema=NativeToolPermitGetSchema.extend({authorityProtocol:z163.literal("NVS_GENERIC_EXECUTION_V1").optional(),tokenId:id12,executionId:id12,hostRequestId:id12,grantId:id12,grantRevision:z163.int().positive(),runKey:key8,runtimePrincipalId:id12,approvedByPrincipalId:id12,requestedByPrincipalId:id12,capabilityDigest:sha22,resource:z163.url().max(2048),issuer:z163.url().max(2048),subject:z163.string().max(200),executionClass:z163.enum(["LIVE","TEST_ONLY"]),expiresAt:z163.iso.datetime({offset:true})});import{z as z164}from"zod";var CreateProductionRequestSchema=z164.strictObject({tenantId:TenantIdSchema,projectId:ProjectIdSchema,idempotencyKey:z164.string().trim().min(1).max(200)});var CreatedProductionResultSchema=CreatedProjectResultSchema;import{z as z165}from"zod";var sha23=z165.string().regex(/^[0-9a-f]{64}$/);var WavExportResultSchema=z165.strictObject({contentType:z165.literal("audio/wav"),checksumSha256:sha23,byteSize:z165.int().min(44).max(12582912),contentBase64:z165.string().min(60).max(16777216).regex(/^[A-Za-z0-9+/]+={0,2}$/)});var AudioExportResultSchema=WavExportResultSchema.extend({representationId:z165.uuid()});var CaptionExportResultSchema=z165.strictObject({contentType:z165.enum(["application/json","application/x-subrip"]),checksumSha256:sha23,representationId:z165.uuid(),text:z165.string().min(1).max(131072)});import{z as z166}from"zod";var tenant=TenantIdSchema.toLowerCase();var project=ProjectIdSchema.toLowerCase();var production=ProductionIdSchema.toLowerCase();var artifact=ArtifactIdSchema.toLowerCase();var representation=ArtifactRepresentationIdSchema.toLowerCase();var DiscoverableArtifactFamilySchema=z166.enum(["SOURCE","KEYFRAME_CANDIDATE","SHOT_CANDIDATE","COMPOSITION_RENDER_OUTPUT","ROUGH_CUT","FINAL_RENDER_OUTPUT","IMPORTED_VISUAL_ORIGINAL","IMPORTED_VISUAL_NORMALIZED","IMPORTED_VISUAL_POSTER","AUDIO","AUDIO_SOURCE_SYNC","CAPTION","CONTACT_SHEET"]);var DiscoveryContentTypeSchema=MediaBrowserContentTypeSchema;var ArtifactDiscoveryQuerySchema=z166.strictObject({tenantId:tenant,projectId:project.optional(),productionId:production.optional(),artifactId:artifact.optional(),mediaCategory:MediaCategorySchema.optional(),family:DiscoverableArtifactFamilySchema.optional(),search:z166.string().trim().min(1).max(200).optional(),lifecycle:z166.enum(["READY","ARCHIVED"]).default("READY"),limit:QueryLimitSchema,next:ContinuationSchema.optional()});var ArtifactDiscoveryMediaSchema=z166.strictObject({tenantId:tenant,projectId:project,artifactId:artifact,representationId:representation});var ArtifactMediaTicketRequestSchema=ArtifactDiscoveryMediaSchema.extend({download:z166.boolean().optional()});var ArtifactMediaTicketSchema=ArtifactDiscoveryMediaSchema.extend(MediaBrowserReadTicketSchema.shape);var ArtifactDiscoveryItemSchema=z166.strictObject({humanLinks:HumanLinksSchema.optional(),artifactId:ArtifactIdSchema,projectId:ProjectIdSchema,projectName:z166.string().min(1).max(500),projectLifecycle:ProjectSchema.shape.lifecycle.nullable().default(null),productionId:ProductionIdSchema.nullable(),representationId:ArtifactRepresentationIdSchema,family:DiscoverableArtifactFamilySchema,lifecycle:z166.enum(["READY","ARCHIVED"]),origin:z166.string().min(1).max(120),contentType:DiscoveryContentTypeSchema,checksumSha256:z166.string().regex(/^[a-f0-9]{64}$/),byteSize:z166.int().positive(),width:z166.int().positive().nullable(),height:z166.int().positive().nullable(),durationMs:z166.int().nonnegative().nullable(),createdAt:z166.iso.datetime({offset:true}),originalName:z166.string().max(255).nullable(),sourceKind:SourceLibraryItemSchema.shape.kind.nullable().default(null),executionClass:z166.enum(["LIVE","TEST_ONLY","UNKNOWN"]),mediaAvailable:z166.boolean(),sourceVersionId:z166.uuid().nullable(),normalizationId:z166.uuid().nullable()});var ArtifactDiscoveryPageSchema=z166.strictObject({items:z166.array(ArtifactDiscoveryItemSchema).max(100),page:QueryPageInfoSchema});import{z as z167}from"zod";var TerminateProductionSchema=z167.strictObject({tenantId:TenantIdSchema,projectId:ProjectIdSchema,productionId:ProductionIdSchema,outcome:z167.enum(["FAILED","CANCELLED"]),expectedProductionRevision:z167.int().positive(),reason:z167.string().trim().min(1).max(1e3),idempotencyKey:z167.string().trim().min(1).max(200)});var ProductionTerminationReceiptSchema=z167.strictObject({decisionId:z167.uuid(),productionId:ProductionIdSchema,projectId:ProjectIdSchema,state:ProductionStateSchema});import{z as z168}from"zod";var text3=z168.string().trim().min(1).max(600);var key9=z168.string().regex(/^[a-z][a-z0-9_-]{0,39}$/);var Review1RepairSourceResultSchema=z168.strictObject({input:Review1RepairSourceQuerySchema,source:Review1RepairSourceSchema,productionRevision:z168.int().positive(),caseVersion:z168.int().nonnegative(),budget:SemanticRepairBudgetSchema.nullable()}).superRefine((v,c)=>{const fields=["tenantId","projectId","productionId","mediaType","generationId","reviewId"];if(fields.some(key10=>v.input[key10]!==v.source[key10])||v.input.requirementKey!==v.source.requirement.key)c.addIssue({code:"custom",message:"Native source must match the exact scoped Review obligation"})});var Review1RepairStrategyBasisSchema=z168.strictObject({input:Review1RepairSourceQuerySchema,contextFingerprint:z168.string().regex(/^[0-9a-f]{64}$/)});var Review1RepairStrategyContextSchema=z168.strictObject({semanticStatus:z168.literal("SUCCESS"),advisory:z168.literal(true),basis:Review1RepairStrategyBasisSchema,owner:Review1RepairSourceResultSchema});var ValidateReview1RepairStrategySchema=z168.strictObject({basis:Review1RepairStrategyBasisSchema,budget:SemanticRepairBudgetSchema.optional(),proposal:z168.strictObject({origin:z168.strictObject({kind:z168.literal("EXTERNAL_AGENT_HOST"),label:z168.string().trim().min(1).max(100)}),summary:text3,alternatives:z168.array(z168.strictObject({id:key9,rationale:text3,whySmallerChangeInsufficient:text3,action:z168.discriminatedUnion("kind",[z168.strictObject({kind:z168.literal("REGENERATE_SHOT")}),z168.strictObject({kind:z168.literal("REQUEST_HUMAN_INPUT"),question:text3}),z168.strictObject({kind:z168.literal("REQUEST_CANONICAL_CHANGE"),requestedChange:text3})])})).min(1).max(6),selectedAlternativeId:key9})}).refine(v=>new TextEncoder().encode(JSON.stringify(v)).byteLength<=1024*1024,"Review-1 strategy exceeds 1 MiB");var Review1RepairStrategyValidationSchema=z168.strictObject({semanticStatus:z168.literal("SUCCESS"),advisory:z168.literal(true),basis:Review1RepairStrategyBasisSchema,proposal:ValidateReview1RepairStrategySchema.shape.proposal,alternatives:z168.array(z168.strictObject({alternativeId:key9,handoff:z168.discriminatedUnion("kind",[z168.strictObject({kind:z168.literal("AUTHOR_REVIEW1_REPAIR"),input:AuthorReview1RepairSchema.omit({idempotencyKey:true})}),z168.strictObject({kind:z168.literal("HUMAN_INPUT_INTENT"),question:text3}),z168.strictObject({kind:z168.literal("CANONICAL_CHANGE_INTENT"),requestedChange:text3})])})).min(1).max(6),selectedAlternativeId:key9,followUp:z168.union([z168.tuple([]),z168.tuple([z168.literal("EXPLICIT_NATIVE_AUTHORING"),z168.literal("OWNER_BUDGET_AND_COST_ADMISSION"),z168.literal("EXPLICIT_NATIVE_EXECUTION"),z168.literal("INDEPENDENT_REVIEW_1_AND_NATIVE_PROOF")])])});import{z as z170}from"zod";import{z as z169}from"zod";var NavigationGroupIdSchema=z169.enum(["navigation","materials","planning","execution","review","delivery","local","administration","unclassified"]);var NavigationGroups=Object.freeze([{id:"navigation",title:"\u5BFC\u822A\u4E0E\u6062\u590D",description:"Locate Productions, inspect state and reconcile original Operations"},{id:"materials",title:"\u9879\u76EE\u4E0E\u7D20\u6750",description:"Projects, source material, references and Artifact discovery"},{id:"planning",title:"\u521B\u4F5C\u4E0E\u8BA1\u5212",description:"Brief, Story, Scenes, Shots and creative plans"},{id:"execution",title:"\u6267\u884C\u4E0E\u8FDB\u5EA6",description:"Generation, runtime Jobs, observation and cancellation"},{id:"review",title:"\u5BA1\u67E5\u4E0E\u4FEE\u590D",description:"Review targets, Findings, evidence and repair"},{id:"delivery",title:"\u88C5\u914D\u4E0E\u4EA4\u4ED8",description:"Timeline, composition, preview, rendering and delivery"},{id:"local",title:"\u672C\u5730\u6267\u884C",description:"Authorized local Runtime, media tools and Agent connections"},{id:"administration",title:"\u7BA1\u7406\u4E0E\u96C6\u6210",description:"Tenant integration, Providers and native authority configuration"},{id:"unclassified",title:"\u5F85\u5206\u7C7B\u80FD\u529B",description:"Registered capabilities awaiting explicit semantic classification"}]);var namespaces=[["navigation",/^nvs_open_execution$/],["local",/^(?:local_|device_|list_devices$)/],["administration",/^(?:provider_|tenant_|oauth_|credential_|native_tool_|agent_host_|webhook_|federation_)/],["review",/(?:^|_)(?:review|reviewer|finding|repair)(?:_|$)/],["navigation",/^(?:workspace_|studio_|operation_|production_(?:query|snapshot)|job_(?:get|query)|production_guidance_)/],["materials",/^(?:project_|source_|artifact_|reference_|visual_sequence_|imported_visual_|source_sync_)/],["planning",/^(?:brief_|story_|scene_|shot_|writer_|director_|exploration_|consistency_|series_|voice_profile_|making_|sound_plan_|planning_|editor_)/],["delivery",/^(?:share_|timeline_|composition_|rough_cut_|final_|delivery_|caption_|audio_)/],["execution",/^(?:production_|keyframe_|video_|generation_|speech_|media_observation_|temporal_evidence_|lifecycle_)/]];function navigationGroup(tool){return namespaces.find(([,pattern])=>pattern.test(tool))?.[0]??"unclassified"}var NavigationProfile="contextual-v1";var NavigationProfileKey="io.nativestudio/discovery-profile";var NavigationToolNames=["studio_start","studio_capability_search","studio_capability_describe","studio_capability_groups","studio_navigate"];var Scope=z170.object({tenantId:TenantIdSchema,projectId:ProjectIdSchema.optional()});var ToolName=z170.string().regex(/^[a-zA-Z0-9_-]{1,120}$/);var StudioStartInputSchema=ProductionQueryInputSchema.extend({limit:z170.int().min(1).max(5).default(5)}).strict();var StudioStartSchema=z170.object({tenantId:TenantIdSchema,choices:ProductionQueryPageSchema.shape.items.max(5),page:ProductionQueryPageSchema.shape.page,selection:z170.enum(["NONE","ONE","CHOOSE"]),guidance:z170.literal("Select an explicit Production ID, then call studio_navigate. Never infer an ID.")}).strict();var CapabilitySummarySchema=z170.object({tool:ToolName,title:z170.string().max(500),description:z170.string().max(6e3),family:z170.string().min(1).max(120),group:NavigationGroupIdSchema.optional(),readOnly:z170.boolean(),invocationTool:z170.enum(["studio_capability_query","studio_capability_invoke"]).optional(),registration:z170.literal("REGISTERED")}).strict();var CapabilitySearchInputSchema=Scope.extend({query:z170.string().trim().min(1).max(240),family:z170.string().regex(/^[a-z0-9_-]{1,120}$/).optional(),group:NavigationGroupIdSchema.optional(),limit:z170.int().min(1).max(8).default(5),next:z170.string().min(1).max(2048).optional()}).strict();var CapabilitySearchSchema=z170.object({tenantId:TenantIdSchema,catalogVersion:z170.string().regex(/^[a-f0-9]{64}$/),outcome:z170.enum(["MATCHES","AMBIGUOUS","NO_MATCH"]),candidates:z170.array(CapabilitySummarySchema.extend({matchedTerms:z170.array(z170.string().max(120)).max(24)})).max(8),page:z170.object({hasMore:z170.boolean(),next:z170.string().max(2048).nullable()}).strict(),guidance:z170.literal("Registration is not availability or authorization. Inspect the selected schema and native context before invoking its typed command.")}).strict();var CapabilityDescribeInputSchema=Scope.extend({tool:ToolName,schemaCursor:z170.string().min(1).max(2048).optional()}).strict();var JsonSchema=z170.record(z170.string(),z170.unknown());var PublicToolDefinitionSchema=z170.object({name:ToolName,title:z170.string().optional(),description:z170.string().optional(),inputSchema:JsonSchema,outputSchema:JsonSchema.optional(),annotations:JsonSchema.optional(),execution:JsonSchema.optional(),_meta:JsonSchema.optional(),icons:z170.array(JsonSchema).optional()}).strict();var CapabilityGroupsInputSchema=Scope.extend({includeDefinitions:z170.boolean().optional()}).strict();var CapabilityGroupsSchema=z170.object({tenantId:TenantIdSchema,catalogVersion:z170.string().regex(/^[a-f0-9]{64}$/),definitions:z170.array(PublicToolDefinitionSchema).max(6).optional(),groups:z170.array(z170.object({id:NavigationGroupIdSchema,title:z170.string().max(120),description:z170.string().max(500),count:z170.int().nonnegative(),readOnlyCount:z170.int().nonnegative()}).strict()).max(9)}).strict();var CapabilityDescribeSchema=CapabilitySummarySchema.extend({tenantId:TenantIdSchema,catalogVersion:z170.string().regex(/^[a-f0-9]{64}$/),capabilityVersion:CapabilityVersionSchema.optional(),outputContract:z170.enum(["DECLARED","NOT_DECLARED"]),schemaCursor:z170.string().min(1).max(2048),definition:PublicToolDefinitionSchema,guidance:z170.literal("Use this bounded definition as client-local schema metadata. Standard tools/list stays stable; commands revalidate authority and current state.")}).strict();var StudioNavigateInputSchema=Scope.extend({productionId:ProductionIdSchema,goal:z170.string().trim().min(1).max(240).optional(),actionLimit:z170.int().min(1).max(8).default(8).describe("Native action page size: 1\u20138 (default 8). Omit this field unless a smaller page is needed."),actionNext:z170.string().min(1).max(2048).optional().describe("Opaque actions.page.next; keep the same goal and actionLimit. Changed native state requires a fresh first page.")}).strict();import{z as z171}from"zod";var McpEntryToolNames=["workspace_caller","studio_capability_groups","studio_capability_search","studio_capability_describe","studio_capability_query","studio_capability_invoke"];var McpCapabilityGatewayNames=["studio_capability_query","studio_capability_invoke"];var CapabilityInvocationInputSchema=z171.strictObject({tenantId:TenantIdSchema,tool:z171.string().regex(/^[a-zA-Z0-9_-]{1,120}$/),arguments:z171.record(z171.string(),z171.unknown()),capabilityVersion:CapabilityVersionSchema.optional()});var CapabilityInvocationOutputSchema=z171.strictObject({tool:z171.string().regex(/^[a-zA-Z0-9_-]{1,120}$/),result:z171.unknown().optional()});import{z as z172}from"zod";var OperationArguments=z172.strictObject({tenantId:TenantIdSchema,productionId:ProductionIdSchema,operationId:OperationSummarySchema.shape.id});var OperationInspect=z172.discriminatedUnion("tool",[z172.strictObject({tool:z172.literal("operation_get"),arguments:OperationArguments}),z172.strictObject({tool:z172.literal("studio_capability_query"),arguments:CapabilityInvocationInputSchema.extend({tool:z172.literal("operation_get"),arguments:OperationArguments})})]);var SnapshotArguments=OperationArguments.omit({operationId:true});var FailureInspect=z172.union([OperationInspect,z172.strictObject({tool:z172.literal("production_snapshot"),arguments:SnapshotArguments}),z172.strictObject({tool:z172.literal("studio_capability_query"),arguments:CapabilityInvocationInputSchema.extend({tool:z172.literal("production_snapshot"),arguments:SnapshotArguments})})]);var Evidence=z172.object({path:z172.string().min(1).max(120)}).strict();var StudioNavigationSchema=z172.object({tenantId:TenantIdSchema,projectId:ProjectIdSchema,productionId:ProductionIdSchema,evidence:z172.object({source:z172.literal("production_snapshot"),revision:z172.int().positive(),generatedAt:z172.iso.datetime({offset:true})}).strict(),state:ProductionSnapshotSchema.shape.state.extend({blockingReason:z172.string().max(1e3).nullable(),waitingReason:z172.string().max(1e3).nullable()}),stateReasonsTruncated:z172.object({blockingReason:z172.boolean(),waitingReason:z172.boolean()}).strict(),planning:ProductionSnapshotSchema.shape.planning,shots:ProductionSnapshotSchema.shape.shots,work:ProductionSnapshotSchema.shape.work,findings:ProductionSnapshotSchema.shape.findings,timeline:ProductionSnapshotSchema.shape.timeline.pick({currentVersion:true,stale:true}),final:ProductionSnapshotSchema.shape.final.pick({renderState:true,deliveryValidationState:true}),blockers:z172.object({total:z172.int().nonnegative(),truncated:z172.boolean(),items:z172.array(ProductionSnapshotSchema.shape.blockers.element.extend({evidence:Evidence})).max(10)}).strict(),actions:z172.object({total:z172.int().nonnegative(),truncated:z172.boolean(),items:z172.array(NextActionSchema.extend({tool:z172.string().min(1).max(120).nullable(),registration:z172.enum(["REGISTERED","NOT_ON_SURFACE"]),readOnly:z172.boolean().nullable(),invocationTool:z172.enum(["studio_capability_query","studio_capability_invoke"]).optional(),purpose:z172.string().max(500).nullable(),group:NavigationGroupIdSchema.nullable(),context:z172.object({tenantId:TenantIdSchema,projectId:ProjectIdSchema,productionId:ProductionIdSchema,revision:z172.int().positive()}).strict(),inputHints:z172.object({knownInputs:z172.partialRecord(z172.enum(["tenantId","projectId","productionId","shotId","sceneId","findingId","operationId","artifactId"]),z172.string().min(1).max(2048)),schemaFingerprint:z172.string().regex(/^[a-f0-9]{64}$/).nullable(),requiredInputs:z172.array(z172.string()).max(128),missingInputs:z172.array(z172.string()).max(128),schemaInspectionRequired:z172.literal(true)}).strict().nullable(),recommendation:z172.array(z172.enum(["NATIVE_AVAILABLE","NATIVE_UNAVAILABLE","GOAL_MATCH","INSPECT_SCHEMA","NOT_ON_SURFACE"])).max(4),inspect:z172.object({tool:z172.literal("studio_capability_describe"),arguments:CapabilityDescribeInputSchema}).strict().nullable(),evidence:Evidence})).max(8),page:z172.object({hasMore:z172.boolean(),next:z172.string().max(2048).nullable()}).strict()}).strict(),operations:z172.object({total:z172.int().nonnegative(),truncated:z172.boolean(),items:z172.array(OperationSummarySchema.pick({id:true,productionId:true,semanticStatus:true,startedAt:true,updatedAt:true}).extend({inspect:OperationInspect.nullable(),failure:OperationFailureSchema.extend({next:FailureInspect.nullable()}).optional(),targetCount:z172.int().nonnegative(),blockerCount:z172.int().nonnegative(),evidence:Evidence})).max(5)}).strict(),related:CapabilitySearchSchema.nullable(),guidance:z172.literal("Use native IDs and revision from this snapshot. An outstanding or unacknowledged write must be reconciled through its Operation; never replay it automatically. Commands revalidate current authority, prerequisites, revision and idempotency.")}).strict();import{z as z174}from"zod";import{z as z173}from"zod";var VoiceReferenceAudioSchema=z173.strictObject({audioVersionId:z173.uuid(),projectId:z173.uuid(),productionId:z173.uuid(),artifactId:z173.uuid(),representationId:z173.uuid(),checksumSha256:z173.string().regex(/^[a-f0-9]{64}$/),byteSize:z173.int().min(44).max(12582912),durationMs:z173.int().min(100).max(6e4),executionClass:z173.enum(["LIVE","TEST_ONLY"]),voiceProfile:VoiceProfileUseSchema.safeExtend({usage:z173.literal("AUDITION")})});var VoiceReferenceSchema=z173.strictObject({humanLinks:HumanLinksSchema.optional(),id:z173.uuid(),tenantId:TenantIdSchema,voiceProfileId:z173.uuid(),ref:VoiceProfileRefSchema,version:z173.int().positive(),audio:VoiceReferenceAudioSchema.nullable(),createdByPrincipalId:z173.uuid(),createdAt:z173.iso.datetime({offset:true})}).refine(v=>v.ref.ownerSystem==="native-video-studio"&&v.ref.ownerTenantRef===v.tenantId&&v.ref.voiceProfileRef===v.voiceProfileId&&(!v.audio||Object.entries(v.ref).every(([key10,value2])=>v.audio.voiceProfile.ref[key10]===value2)),"Reference selection must preserve its exact workspace voice identity");var VoiceReferenceGetSchema=z173.strictObject({tenantId:TenantIdSchema,voiceProfileId:z173.uuid(),referenceId:z173.uuid()});var VoiceProfileScopeSchema=z174.strictObject({tenantId:TenantIdSchema,voiceProfileId:z174.uuid()});var VoiceProfileBindingSchema=z174.strictObject({key:z174.string().regex(/^[a-z][a-z0-9_-]{0,63}$/),modelProfileId:ModelProfileIdSchema,modelProfileVersion:z174.int().positive(),voice:z174.string().min(1).max(100),languages:z174.array(VoiceLocaleSchema).min(1).max(16).refine(v=>new Set(v.map(s=>s.toLowerCase())).size===v.length),parameters:SpeechParametersSchema.default({}),nativeExecution:NativeSpeechExecutionSchema.optional()});var VoiceProfileContentSchema=z174.strictObject({displayName:z174.string().trim().min(1).max(100).regex(/^[^\p{Cc}]*$/u),description:z174.string().trim().max(1e3).default(""),style:z174.string().trim().max(400).default(""),origin:z174.enum(["PRESET","LICENSED_REFERENCE","CLONED_WITH_CONSENT"]),allowedUses:z174.array(z174.enum(["AUDITION","PRODUCTION"])).min(1).max(2).refine(v=>new Set(v).size===v.length).default(["AUDITION","PRODUCTION"]),expiresAt:z174.iso.datetime({offset:true}).optional(),rightsStatement:z174.string().trim().min(1).max(1e3).optional(),bindings:z174.array(VoiceProfileBindingSchema).min(1).max(8).refine(v=>new Set(v.map(b=>b.key)).size===v.length)});var command3={tenantId:TenantIdSchema,idempotencyKey:z174.string().trim().min(1).max(200)};var revision2={voiceProfileId:z174.uuid(),expectedRevision:z174.int().positive()};var VoiceProfileCommandSchema=z174.discriminatedUnion("action",[z174.strictObject({...command3,action:z174.literal("CREATE"),content:VoiceProfileContentSchema}),z174.strictObject({...command3,...revision2,action:z174.literal("REVISE"),content:VoiceProfileContentSchema}),z174.strictObject({...command3,...revision2,action:z174.literal("PUBLISH")}),z174.strictObject({...command3,...revision2,action:z174.literal("SET_ENABLED"),enabled:z174.boolean()}),z174.strictObject({...command3,...revision2,action:z174.literal("SET_REFERENCE"),voiceProfileVersion:z174.int().positive(),audioVersionId:z174.uuid().nullable()})]);var VoiceProfileVersionQuerySchema=VoiceProfileScopeSchema.extend({version:z174.int().positive()});var VoiceProfileListSchema=z174.strictObject({tenantId:TenantIdSchema,search:z174.string().trim().max(100).optional(),status:z174.enum(["DRAFT","PUBLISHED","DISABLED"]).optional(),limit:z174.int().min(1).max(100).default(25),next:z174.string().min(1).max(4096).optional()});var VoiceProfileReceiptSchema=z174.strictObject({humanLinks:HumanLinksSchema.optional(),reference:VoiceReferenceSchema.optional(),semanticStatus:z174.literal("SUCCESS"),tenantId:TenantIdSchema,voiceProfileId:z174.uuid(),revision:z174.int().positive(),publishedVersion:z174.int().positive().nullable(),enabled:z174.boolean()});var VoiceProfileVersionSchema=z174.strictObject({humanLinks:HumanLinksSchema.optional(),ref:VoiceProfileRefSchema,content:VoiceProfileContentSchema,publishedByPrincipalId:z174.uuid(),publishedAt:z174.iso.datetime({offset:true})});var VoiceProfileSummarySchema=VoiceProfileReceiptSchema.omit({semanticStatus:true}).extend({displayName:z174.string().min(1).max(100),status:z174.enum(["DRAFT","PUBLISHED","DISABLED"]),updatedAt:z174.iso.datetime({offset:true})});var VoiceProfileViewSchema=VoiceProfileSummarySchema.extend({reference:VoiceReferenceSchema.nullable().default(null),draft:VoiceProfileContentSchema,draftDigest:z174.string().regex(/^[a-f0-9]{64}$/),published:VoiceProfileVersionSchema.nullable()});var VoiceProfilePageSchema=z174.strictObject({humanLinks:HumanLinksSchema.optional(),items:z174.array(VoiceProfileSummarySchema).max(100),next:z174.string().max(4096).nullable()});var VoiceProfileCreateSchema=VoiceProfileCommandSchema.options[0].omit({action:true});var VoiceProfileReviseSchema=VoiceProfileCommandSchema.options[1].omit({action:true});var VoiceProfilePublishSchema=VoiceProfileCommandSchema.options[2].omit({action:true});var VoiceProfileSetEnabledSchema=VoiceProfileCommandSchema.options[3].omit({action:true});var VoiceProfileSetReferenceSchema=VoiceProfileCommandSchema.options[4].omit({action:true});import{z as z175}from"zod";var sha24=z175.string().regex(/^[a-f0-9]{64}$/);var VoiceReviewAudioSchema=VoiceReferenceAudioSchema.omit({voiceProfile:true}).extend({voiceProfile:VoiceProfileUseSchema});var VoiceReviewScopeSchema=z175.strictObject({tenantId:TenantIdSchema,voiceProfileId:z175.uuid()});var VoiceReviewTargetQuerySchema=VoiceReviewScopeSchema.extend({audioVersionId:z175.uuid()});var VoiceReviewBasisSchema=z175.strictObject({reference:VoiceReferenceSchema.safeExtend({audio:VoiceReferenceAudioSchema}),candidate:VoiceReviewAudioSchema}).refine(v=>Object.entries(v.reference.ref).every(([key10,value2])=>v.candidate.voiceProfile.ref[key10]===value2),"Comparison must preserve the exact same voice identity");var VoiceIdentityObservationSchema=z175.strictObject({status:z175.enum(["MATCH","DIFFERENT","UNDETERMINED"]),confidence:z175.enum(["CLEAR","UNCERTAIN"]),observed:z175.string().trim().min(1).max(1800)});var VoiceNaturalnessObservationSchema=z175.strictObject({status:z175.enum(["NATURAL","NEEDS_WORK","NOT_ASSESSED"]),observed:z175.string().trim().min(1).max(1800)});var RecordVoiceReviewSchema=VoiceReviewTargetQuerySchema.extend({referenceId:z175.uuid(),basisFingerprint:sha24,expectedReviewVersion:z175.int().nonnegative(),idempotencyKey:z175.string().trim().min(1).max(200),actor:z175.enum(["HUMAN","EXTERNAL_AGENT"]),referenceListening:ListeningEvidenceSchema,candidateListening:ListeningEvidenceSchema,identity:VoiceIdentityObservationSchema,naturalness:VoiceNaturalnessObservationSchema});var VoiceReviewRecordSchema=VoiceReviewTargetQuerySchema.extend({id:z175.uuid(),version:z175.int().positive(),basis:VoiceReviewBasisSchema,basisFingerprint:sha24,actor:z175.enum(["HUMAN","EXTERNAL_AGENT"]),executionClass:z175.enum(["LIVE","TEST_ONLY"]),referenceListening:ListeningEvidenceSchema,candidateListening:ListeningEvidenceSchema,identity:VoiceIdentityObservationSchema,naturalness:VoiceNaturalnessObservationSchema,identityResult:z175.enum(["MATCH","DIFFERENT","UNDETERMINED"]),createdByPrincipalId:z175.uuid(),createdAt:z175.iso.datetime({offset:true})}).refine(v=>v.basis.reference.audio.audioVersionId!==v.basis.candidate.audioVersionId&&v.basis.reference.tenantId===v.tenantId&&v.basis.reference.voiceProfileId===v.voiceProfileId&&v.basis.candidate.audioVersionId===v.audioVersionId&&v.executionClass===([v.basis.reference.audio,v.basis.candidate].some(a=>a.executionClass==="TEST_ONLY")?"TEST_ONLY":"LIVE")&&v.identityResult===(v.identity.confidence==="CLEAR"?v.identity.status:"UNDETERMINED"),"Review must preserve exact comparison scope, execution class and independent result");var VoiceReviewStaleReasonSchema=z175.enum(["NO_REFERENCE","REFERENCE_CHANGED","REVIEW_SUPERSEDED","VOICE_UNAVAILABLE","AUDIO_UNAVAILABLE","IDENTITY_MISMATCH","SAME_AUDIO","TEST_ONLY"]);var VoiceReviewTargetSchema=VoiceReviewTargetQuerySchema.extend({humanLinks:HumanLinksSchema.optional(),basis:VoiceReviewBasisSchema.nullable(),basisFingerprint:sha24.nullable(),reviewVersion:z175.int().nonnegative(),eligible:z175.boolean(),staleReasons:z175.array(VoiceReviewStaleReasonSchema).max(8),latestReview:VoiceReviewRecordSchema.nullable()}).refine(v=>v.eligible===(v.staleReasons.length===0)&&(!v.eligible||!!v.basis&&!!v.basisFingerprint)&&v.basis===null===(v.basisFingerprint===null)&&(!v.basis||v.basis.reference.tenantId===v.tenantId&&v.basis.reference.voiceProfileId===v.voiceProfileId&&v.basis.candidate.audioVersionId===v.audioVersionId)&&v.reviewVersion===(v.latestReview?.version??0)&&(!v.latestReview||v.latestReview.tenantId===v.tenantId&&v.latestReview.voiceProfileId===v.voiceProfileId&&v.latestReview.audioVersionId===v.audioVersionId&&v.latestReview.basis.reference.id===v.basis?.reference.id),"Target projection must preserve exact scope and eligibility");var VoiceReviewGetSchema=VoiceReviewScopeSchema.extend({reviewId:z175.uuid()});var VoiceReviewViewSchema=z175.strictObject({humanLinks:HumanLinksSchema.optional(),review:VoiceReviewRecordSchema,current:z175.boolean(),staleReasons:z175.array(VoiceReviewStaleReasonSchema).max(8)}).refine(v=>v.current===(v.staleReasons.length===0),"Historical applicability must agree with currentness reasons");var VoiceReviewReceiptSchema=z175.strictObject({humanLinks:HumanLinksSchema.optional(),semanticStatus:z175.literal("SUCCESS"),review:VoiceReviewRecordSchema});import{z as z176}from"zod";var ProductionEventCursorSchema=z176.strictObject({v:z176.literal(1),t:z176.uuid(),p:z176.uuid(),e:z176.uuid(),n:z176.string().regex(/^(0|[1-9][0-9]{0,18})$/)});var ProductionFeedbackInputSchema=LifecycleEventScopeSchema.extend({operationId:OperationIdSchema.optional(),ifNoneMatch:z176.string().regex(/^[a-f0-9]{64}$/).optional()}).strict();var ProductionFeedbackSchema=LifecycleEventScopeSchema.extend({projectId:z176.uuid(),operationId:OperationIdSchema.nullable(),productionRevision:z176.int().positive(),state:ProductionStateSchema,semanticStatus:InterfaceSemanticStatusSchema,work:WorkSummarySchema,blockers:z176.array(z176.string().min(1).max(1e3)).max(100),nextActions:z176.array(NextActionSchema).max(50),media:z176.strictObject({previewReady:z176.boolean(),finalRenderReady:z176.boolean(),deliveryComplete:z176.boolean()}),humanLinks:HumanLinksSchema}).strict();var ProductionFeedbackResultSchema=LifecycleEventScopeSchema.extend({condition:z176.enum(["CURRENT","NOT_MODIFIED"]),etag:z176.string().regex(/^[a-f0-9]{64}$/),cursor:z176.string().min(1).max(4096),retryAfterMs:z176.int().min(1e3).max(3e4),feedback:ProductionFeedbackSchema.nullable()}).strict().refine(v=>v.condition==="CURRENT"===(v.feedback!==null));var ReadProductionEventsSchema=ProductionFeedbackInputSchema.extend({after:z176.string().min(1).max(4096).optional(),start:z176.enum(["CURRENT","BEGINNING"]).default("CURRENT"),limit:z176.int().min(1).max(50).default(20)}).strict();var ProductionEventReadSchema=z176.strictObject({items:z176.array(ExternalLifecycleEventSchema).max(50),nextCursor:z176.string().min(1).max(4096),watermark:z176.string().min(1).max(4096),hasMore:z176.boolean(),current:ProductionFeedbackResultSchema});import{z as z177}from"zod";var scope7=z177.strictObject({tenantId:z177.uuid().toLowerCase(),shareId:z177.uuid().toLowerCase()});var ShareCreateSchema=ArtifactDiscoveryMediaSchema.extend({shareId:z177.uuid().toLowerCase(),idempotencyKey:z177.string().min(1).max(128),title:z177.string().trim().min(1).max(160).default("Video"),expiresAt:z177.iso.datetime({offset:true}).optional()}).strict();var ShareGetSchema=scope7;var ShareRevokeSchema=scope7.extend({expectedRevision:z177.int().positive(),idempotencyKey:z177.string().min(1).max(128)}).strict();var ShareListSchema=z177.strictObject({tenantId:z177.uuid().toLowerCase(),projectId:z177.uuid().toLowerCase().optional(),artifactId:z177.uuid().toLowerCase().optional(),after:z177.uuid().toLowerCase().optional(),limit:z177.int().min(1).max(50).default(20)});var ShareViewSchema=ArtifactDiscoveryMediaSchema.extend({shareId:z177.uuid(),productionId:z177.uuid().nullable(),createdByPrincipalId:z177.uuid(),title:z177.string().min(1).max(160),purpose:z177.enum(["PREVIEW","ROUGH_CUT","FINAL_RENDER"]),contentType:z177.literal("video/mp4"),checksumSha256:z177.string().regex(/^[a-f0-9]{64}$/),byteSize:z177.int().positive().max(128*1024*1024),revision:z177.int().positive(),state:z177.enum(["PREPARING","ACTIVE","REVOKED","EXPIRED","AUTHORITY_REVOKED"]),createdAt:z177.iso.datetime({offset:true}),expiresAt:z177.iso.datetime({offset:true})}).strict();var ShareUrlSchema=z177.url().max(2048).refine(value2=>{try{const u=new URL(value2);return!u.username&&!u.password&&!u.search&&/^\/s\/[a-f0-9-]{36}$/.test(u.pathname)&&/^#key=[A-Za-z0-9_-]{43}$/.test(u.hash)&&(u.protocol==="https:"||u.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(u.hostname))}catch{return false}});var ShareLinkResultSchema=z177.strictObject({share:ShareViewSchema,url:ShareUrlSchema.nullable(),linkState:z177.enum(["AVAILABLE","UNCONFIGURED","UNAVAILABLE","NOT_ACTIVE"])}).refine(v=>v.linkState==="AVAILABLE"===(v.url!==null)).refine(v=>!v.url||v.share.state==="ACTIVE"&&new URL(v.url).pathname==="/s/"+v.share.shareId);var SharePageSchema=z177.strictObject({items:z177.array(ShareViewSchema).max(50),next:z177.uuid().nullable()});var SharePublicInputSchema=z177.strictObject({shareId:z177.uuid().toLowerCase(),secret:z177.string().regex(/^[A-Za-z0-9_-]{43}$/)});import{z as z178}from"zod";var sha25=z178.string().regex(/^[a-f0-9]{64}$/);var ReleaseLegacyHostExecutionSchema=AgentHostExecutionGetSchema.extend({requestId:z178.uuid(),expectedRevision:z178.int().positive(),hostRequestId:z178.uuid(),snapshotFingerprint:sha25,evidenceRef:z178.string().min(1).max(512).refine(v=>Array.from(v).every(c=>{const n=c.codePointAt(0);return n>=32&&(n<127||n>159)&&(n<55296||n>57343)})),evidenceSha256:sha25,decision:z178.literal("RELEASE_NATIVE_DISPATCH_FENCE")});var LegacyHostExecutionReleaseSchema=ReleaseLegacyHostExecutionSchema.extend({releasedByPrincipalId:z178.uuid(),releasedAt:z178.iso.datetime({offset:true})});import{z as z183}from"zod";import{z as z182}from"zod";import{z as z179}from"zod";function orderedFederationWindow(value2){return Date.parse(value2.notBefore)<Date.parse(value2.expiresAt)}var FederationFailureCodeSchema=z179.enum(["FEDERATION_FORBIDDEN","FEDERATION_UNCONFIGURED","FEDERATION_INVALID_INPUT","FEDERATION_INVALID_ID","FEDERATION_INVALID_REFERENCE","FEDERATION_INVALID_MODE","FEDERATION_INVALID_GRANT_VERSION","FEDERATION_INVALID_REVISION","FEDERATION_INVALID_STATE","FEDERATION_INVALID_SOURCE","FEDERATION_INVALID_VALIDITY","FEDERATION_REMOTE_SERVICE_REQUIRED","FEDERATION_EVENT_NOT_ALLOWED","FEDERATION_EVENT_NOT_SELECTED","FEDERATION_SCOPE_MISMATCH","FEDERATION_PRODUCTION_NOT_FOUND","FEDERATION_ROUTE_NOT_FOUND","FEDERATION_STREAM_NOT_FOUND","FEDERATION_CONNECTION_CONFLICT","FEDERATION_GRANT_CONFLICT","FEDERATION_GRANT_VERSION_CONFLICT","FEDERATION_ROUTE_IDENTITY_CONFLICT","FEDERATION_REVISION_CONFLICT","FEDERATION_IDEMPOTENCY_CONFLICT","FEDERATION_CONCURRENT_CHANGE","FEDERATION_ROUTE_CAPACITY","FEDERATION_SUBSCRIPTION_CAPACITY","FEDERATION_SUBSCRIPTION_NOT_FOUND","FEDERATION_SUBSCRIBER_IDENTITY_CONFLICT","FEDERATION_SUBSCRIPTION_CANCELLED","FEDERATION_INITIAL_SELECTION_REQUIRED","FEDERATION_SELECTION_EXCEEDS_AUTHORITY","FEDERATION_SELECTION_EXCEEDS_GRANT","FEDERATION_RESYNC_REQUIRED","FEDERATION_GAP_NOT_REPAIRED","FEDERATION_HOLD_REQUIRED","FEDERATION_RECOVERY_EXHAUSTED","FEDERATION_BINDING_NOT_FOUND","FEDERATION_INBOX_NOT_FOUND","FEDERATION_INBOUND_CONFLICT","FEDERATION_INBOX_NOT_QUARANTINED","FEDERATION_RESULT_NOT_FOUND","FEDERATION_RESULT_MISMATCH","FEDERATION_CONTRACT_MISMATCH","FEDERATION_RECEIPT_ROUTE_NOT_FOUND","FEDERATION_RECEIPT_DELIVERY_NOT_FOUND","FEDERATION_RECEIPT_CONFLICT"]);var ref=z179.string().min(1).max(256).refine(v=>Array.from(v).every(c=>{const code=c.codePointAt(0);return code>=32&&code!==127&&(code<55296||code>57343)}));var types=z179.array(ExternalEventTypeSchema).min(1).max(14).refine(v=>new Set(v).size===v.length);var uuid3=z179.uuid().toLowerCase();var FederationScopeSchema=LifecycleEventScopeSchema.extend({tenantId:uuid3.brand(),productionId:uuid3.brand()});var routeInput=FederationScopeSchema.extend({routeId:uuid3,requestId:ref,expectedRevision:z179.int().nonnegative(),remoteService:ref,remoteTenant:ref,grantRef:ref,grantVersion:z179.int().min(1).max(2147483647),grantEventTypes:types,selectedEventTypes:types,notBefore:z179.iso.datetime(),expiresAt:z179.iso.datetime(),state:z179.enum(["ACTIVE","PAUSED"]),publicationMode:z179.enum(["FIXED","ON_DEMAND"]).default("ON_DEMAND")}).strict();var FederationRouteConfigureSchema=routeInput.refine(orderedFederationWindow).refine(v=>v.selectedEventTypes.every(type=>v.grantEventTypes.includes(type)));var FederationRouteSchema=routeInput.omit({requestId:true,expectedRevision:true}).extend({connectionRef:ref,source:z179.string().min(1).max(2048),serviceRef:z179.literal("native-video-studio"),revision:z179.int().positive(),epoch:uuid3,position:z179.string().regex(/^(0|[1-9][0-9]{0,18})$/),gap:z179.boolean(),publicationMode:z179.enum(["FIXED","ON_DEMAND"]).default("FIXED")}).strict();var FederationSubscriptionSetSchema=FederationScopeSchema.extend({subscriptionId:uuid3,routeId:uuid3,requestId:ref,expectedRevision:z179.int().nonnegative(),subscriberKind:z179.enum(["SYSTEM","AGENT_RUNTIME","HOST_BOT"]),subscriberRef:ref,eventTypes:types,expiresAt:z179.iso.datetime(),state:z179.enum(["ACTIVE","PAUSED","CANCELLED"])}).strict();var FederationSubscriptionGetSchema=FederationScopeSchema.extend({subscriptionId:uuid3}).strict();var FederationSubscriptionSchema=FederationSubscriptionSetSchema.omit({requestId:true,expectedRevision:true}).extend({revision:z179.int().positive(),startCursor:z179.string().min(1).max(4096),effective:z179.enum(["ACTIVE","PAUSED","CANCELLED","EXPIRED","BLOCKED"])}).strict();var FederationBootstrapSchema=FederationScopeSchema.extend({cursor:z179.string().min(1).max(4096),feedback:ProductionFeedbackSchema}).strict().refine(v=>v.tenantId===v.feedback.tenantId&&v.productionId===v.feedback.productionId);var FederationSubscriptionResultSchema=FederationScopeSchema.extend({subscription:FederationSubscriptionSchema,bootstrap:FederationBootstrapSchema}).strict().refine(v=>v.tenantId===v.subscription.tenantId&&v.productionId===v.subscription.productionId&&v.bootstrap.tenantId===v.tenantId&&v.bootstrap.productionId===v.productionId);var FederationCatalogSchema=FederationScopeSchema.extend({configuration:z179.enum(["CONFIGURED","UNCONFIGURED"]),transport:z179.literal("NOT_OBSERVED"),profile:z179.literal("eventsdk/1.2"),runtimeSubscription:z179.literal("EXPLICIT_SELECTION"),runtimeWake:z179.literal("RECEIVER_OWNED"),defaultPublication:z179.literal(false),bootstrap:FederationBootstrapSchema,routes:z179.array(FederationRouteSchema).max(32),events:z179.array(z179.strictObject({type:ExternalEventTypeSchema,wireType:ref,dataschema:ref,defaultEnabled:z179.literal(false)})).max(14)}).strict().refine(v=>v.routes.every(r=>r.tenantId===v.tenantId&&r.productionId===v.productionId)&&v.bootstrap.tenantId===v.tenantId&&v.bootstrap.productionId===v.productionId);var FederationQuerySchema=FederationScopeSchema.extend({kind:z179.enum(["routes","subscriptions","deliveries"]),routeId:uuid3.optional(),eventId:uuid3.optional(),deliveryId:z179.string().regex(/^[0-9a-f]{64}$/).optional(),after:z179.string().min(1).max(64).optional(),limit:z179.int().min(1).max(50).default(20)}).strict().refine(v=>!v.after||(v.kind==="deliveries"?/^[0-9a-f]{64}$/.test(v.after):z179.uuid().safeParse(v.after).success)).refine(v=>v.kind==="deliveries"||!v.eventId&&!v.deliveryId);var FederationDeliverySchema=FederationScopeSchema.extend({routeId:uuid3,eventId:uuid3,deliveryId:z179.string().regex(/^[0-9a-f]{64}$/),eventType:ExternalEventTypeSchema,state:z179.enum(["PENDING","UNKNOWN","PUBLISHED","HOLD"]),attempts:z179.int().nonnegative(),acknowledgement:z179.enum(["BROKER_STORED","NOT_CONFIRMED"]),reason:z179.string().max(100).nullable()}).strict();var page2=(kind,item)=>FederationScopeSchema.extend({kind:z179.literal(kind),items:z179.array(item).max(50),next:(kind==="deliveries"?z179.string().regex(/^[0-9a-f]{64}$/):uuid3).nullable()}).strict();var FederationQueryResultSchema=z179.discriminatedUnion("kind",[page2("routes",FederationRouteSchema),page2("subscriptions",FederationSubscriptionSchema),page2("deliveries",FederationDeliverySchema)]).refine(v=>v.items.every(item=>{const r=item;return r.tenantId===v.tenantId&&r.productionId===v.productionId}));var FederationReceiptInputSchema=FederationScopeSchema.extend({requestId:ref}).strict();var FederationRecoverSchema=FederationScopeSchema.extend({kind:z179.enum(["RETRY_HOLD","REPAIR_GAP"]),routeId:uuid3,requestId:ref,expectedRevision:z179.int().positive(),reason:ref,deliveryId:z179.string().regex(/^[0-9a-f]{64}$/).optional(),expectedAttempts:z179.int().nonnegative().optional(),acknowledgeDuplicateRisk:z179.literal(true).optional()}).strict().refine(v=>v.kind==="RETRY_HOLD"?v.deliveryId!==void 0&&v.expectedAttempts!==void 0&&v.acknowledgeDuplicateRisk===true:v.deliveryId===void 0&&v.expectedAttempts===void 0&&v.acknowledgeDuplicateRisk===void 0);var FederationRecoverySchema=FederationScopeSchema.extend({kind:z179.enum(["RETRY_HOLD","REPAIR_GAP"]),requestId:ref,recoveryId:uuid3,routeId:uuid3,revision:z179.int().positive(),epoch:uuid3,position:z179.string().regex(/^(0|[1-9][0-9]{0,18})$/),gap:z179.boolean(),deliveryId:z179.string().regex(/^[0-9a-f]{64}$/).nullable(),attempts:z179.int().nonnegative().nullable(),recoveryCount:z179.int().min(0).max(3).nullable(),effect:z179.literal("TRANSPORT_ONLY")}).strict().refine(v=>v.kind==="RETRY_HOLD"?v.deliveryId!==null&&v.attempts!==null&&v.recoveryCount!==null&&v.recoveryCount>0:v.deliveryId===null&&v.attempts===null&&v.recoveryCount===null&&!v.gap);var FederationObservationSchema=FederationScopeSchema.extend({asOf:z179.iso.datetime(),routes:z179.array(z179.strictObject({routeId:uuid3,state:z179.enum(["ACTIVE","PAUSED"]),gap:z179.boolean(),position:z179.string(),sourceHead:z179.string().nullable(),sourceLag:z179.string().nullable(),pending:z179.int().nonnegative(),unknown:z179.int().nonnegative(),hold:z179.int().nonnegative(),published:z179.int().nonnegative(),demandBlocked:z179.int().nonnegative(),inFlight:z179.int().nonnegative(),oldestUnsettledEventAt:z179.iso.datetime().nullable(),lastTickAt:z179.iso.datetime().nullable(),faultCode:z179.string().regex(/^[A-Z][A-Z0-9_]{0,63}$/).nullable()})).max(32),workers:z179.array(z179.strictObject({source:z179.string().min(1).max(2048),workerRef:ref,instanceId:uuid3,status:z179.enum(["STARTING","CONNECTED","RECONNECTING","DISABLED","SHADOW","CONFIGURATION_ERROR","STOPPED"]),observedAt:z179.iso.datetime(),configurationRevision:z179.string().regex(/^sha256:[a-f0-9]{64}$/).nullable(),fresh:z179.boolean(),connected:z179.boolean()})).max(32),workersTruncated:z179.boolean(),meaning:z179.literal("BROKER_ACK_IS_NOT_APPLIED")}).strict();var FederationReceiptSchema=FederationReceiptInputSchema.extend({result:z179.union([FederationRouteSchema,FederationSubscriptionResultSchema,FederationRecoverySchema]).nullable()}).strict().refine(v=>!v.result||v.result.tenantId===v.tenantId&&v.result.productionId===v.productionId);import{z as z181}from"zod";import{z as z180}from"zod";var clean=v=>Array.from(v).every(c=>{const n=c.codePointAt(0);return n>=32&&n!==127&&(n<55296||n>57343)});var FederationPeerRefSchema=z180.string().min(1).max(256).refine(clean);var FederationOpaqueUriSchema=z180.string().min(1).max(512).regex(/^[A-Za-z][A-Za-z0-9+.-]*:\S+$/u).refine(v=>clean(v)&&URL.canParse(v));var RESOURCE_CHANGE_TYPE="com.nativestudio.federation.resource.changed.v1";var RESOURCE_CHANGE_SCHEMA="urn:nativestudio:federation:resource-change:v1";var FederationSourceScopeSchema=z180.strictObject({namespace:FederationPeerRefSchema,ref:FederationPeerRefSchema});var ResourceChangeSchema=z180.strictObject({schemaVersion:z180.literal(1),sourceScope:FederationSourceScopeSchema,resource:z180.strictObject({namespace:FederationPeerRefSchema,ref:FederationOpaqueUriSchema,version:FederationPeerRefSchema}),changeKind:FederationPeerRefSchema,parentRef:FederationOpaqueUriSchema.nullable().optional()});var distinct=a=>new Set(a).size===a.length;var FederationSourceSelectionSchema=z180.strictObject({scope:FederationSourceScopeSchema,resourceNamespace:FederationPeerRefSchema,changeKinds:z180.array(FederationPeerRefSchema).min(1).max(32).refine(distinct),resourcePrefixes:z180.array(FederationOpaqueUriSchema).min(1).max(16).refine(distinct)});var HistoricalSourceScopeSchema=z180.record(FederationPeerRefSchema,FederationPeerRefSchema).refine(v=>Object.keys(v).length<=32);var HistoricalSourceSelectionSchema=z180.record(FederationPeerRefSchema,z180.union([FederationPeerRefSchema,z180.array(z180.string().min(1).max(512).refine(clean)).max(32),HistoricalSourceScopeSchema])).refine(v=>Object.keys(v).length<=32&&JSON.stringify(v).length<=32768);var uuid4=z181.uuid().toLowerCase();var clean2=v=>Array.from(v).every(c=>{const code=c.codePointAt(0);return code>=32&&code!==127&&(code<55296||code>57343)});var ref2=z181.string().min(1).max(256).refine(clean2);var uri=z181.string().min(1).max(2048).refine(v=>URL.canParse(v)&&!/\s/.test(v)&&clean2(v));var bindingInput=FederationScopeSchema.extend({connectionRef:ref2.optional(),bindingId:uuid4,requestId:ref2,expectedRevision:z181.int().nonnegative(),source:uri,contractVersion:z181.literal(2),remoteService:ref2,sourceSelection:FederationSourceSelectionSchema,remoteTenant:ref2,consumerRef:ref2,grantRef:ref2,grantVersion:z181.int().min(1).max(2147483647),notBefore:z181.iso.datetime(),expiresAt:z181.iso.datetime(),state:z181.enum(["ACTIVE","PAUSED","REVOKED"])}).strict();var InboundBindingConfigureSchema=bindingInput.refine(orderedFederationWindow);var bindingView=bindingInput.omit({requestId:true,expectedRevision:true}).extend({revision:z181.int().positive(),installationSource:uri,connectionRef:ref2,direction:z181.literal("INBOUND"),effective:z181.enum(["ACTIVE","PAUSED","REVOKED","EXPIRED","BLOCKED"])}).strict();var CurrentInboundBindingSchema=bindingView.extend({eventType:z181.literal(RESOURCE_CHANGE_TYPE),dataSchema:z181.literal(RESOURCE_CHANGE_SCHEMA)}).refine(orderedFederationWindow);var InboundBindingSchema=z181.union([CurrentInboundBindingSchema,bindingView.extend({contractVersion:z181.literal(1).default(1),sourceSelection:HistoricalSourceSelectionSchema.optional(),eventType:ref2.optional(),dataSchema:uri.optional()})]);var InboundNoticeSchema=z181.strictObject({resourceRef:z181.string().min(1).max(512),resourceVersion:ref2,changeKind:ref2,contractVersion:z181.literal(2).optional(),resourceNamespace:ref2.optional(),sourceService:ref2.optional(),sourceScope:HistoricalSourceScopeSchema.optional(),parentRef:uri.nullable().optional()}).refine(v=>v.contractVersion!==2||v.sourceService!==void 0&&ResourceChangeSchema.safeParse({schemaVersion:1,sourceScope:v.sourceScope,resource:{namespace:v.resourceNamespace,ref:v.resourceRef,version:v.resourceVersion},changeKind:v.changeKind,...v.parentRef!==void 0?{parentRef:v.parentRef}:{}}).success);var InboundInboxViewSchema=FederationScopeSchema.extend({id:uuid4,bindingId:uuid4,source:uri,eventId:ref2,consumerRef:ref2,disposition:z181.enum(["RECEIVED","HOLD","APPLIED","REJECTED","UNKNOWN"]),revision:z181.int().positive(),generation:z181.int().nonnegative(),attempts:z181.int().nonnegative(),recoveryCount:z181.int().min(0).max(3),workState:z181.enum(["READY","QUARANTINED","SETTLED"]),reason:ref2.nullable(),receivedAt:z181.iso.datetime(),resourceRef:z181.string().min(1).max(512).refine(clean2),resourceVersion:ref2}).strict();var signalBase=FederationScopeSchema.extend({inboxId:uuid4,consumerRef:ref2,source:uri,sourceTenant:ref2,effect:z181.literal("REFRESH_HINT"),appliedAt:z181.iso.datetime()}).strict();var InboundSignalSchema=InboundNoticeSchema.safeExtend(signalBase.shape);var InboundReplaySchema=FederationScopeSchema.extend({inboxId:uuid4,requestId:ref2,expectedGeneration:z181.int().nonnegative(),expectedReceiptRevision:z181.int().positive(),reason:ref2,acknowledgeDuplicateRisk:z181.literal(true)}).strict();var InboundReplayResultSchema=FederationScopeSchema.extend({inboxId:uuid4,requestId:ref2,replayId:uuid4,status:z181.literal("QUEUED_FOR_VERIFICATION"),effect:z181.literal("TRANSPORT_ONLY")}).strict();var InboundReplayViewSchema=InboundReplayResultSchema.omit({status:true}).extend({status:z181.enum(["PENDING","REQUEUED","DENIED"]),reasonCode:ref2.nullable()}).strict();var InboundQuarantineViewSchema=FederationScopeSchema.extend({id:uuid4,bindingId:uuid4,deliveryRef:z181.string().min(1).max(2048).refine(clean2),reasonCode:ref2,recordedAt:z181.iso.datetime()}).strict();var InboundQuerySchema=FederationScopeSchema.extend({kind:z181.enum(["bindings","inbox","signals","replays","quarantine"]),after:uuid4.optional(),limit:z181.int().min(1).max(50).default(20)}).strict();var InboundSignalsQuerySchema=InboundQuerySchema.omit({kind:true});var page3=(kind,schema)=>FederationScopeSchema.extend({kind:z181.literal(kind),items:z181.array(schema).max(50),next:uuid4.nullable()}).strict();var signalsPage=page3("signals",InboundSignalSchema);var InboundSignalsPageSchema=signalsPage.refine(p=>p.items.every((item,index)=>item.tenantId===p.tenantId&&item.productionId===p.productionId&&(index===0||p.items[index-1].inboxId<item.inboxId))&&(p.next===null||p.items.at(-1)?.inboxId===p.next));var signalPosition=z181.string().regex(/^(0|[1-9][0-9]{0,18})$/).refine(value2=>value2.length<19||value2<="9223372036854775807");var InboundSignalCheckpointSchema=z181.strictObject({epoch:uuid4,position:signalPosition,inboxId:uuid4.nullable()}).refine(checkpoint=>checkpoint.position==="0"===(checkpoint.inboxId===null));var InboundSignalChangesQuerySchema=FederationScopeSchema.extend({after:z181.union([z181.enum(["CURRENT","BEGINNING"]),InboundSignalCheckpointSchema]),limit:InboundQuerySchema.shape.limit}).strict();var InboundSignalChangesPageSchema=FederationScopeSchema.extend({items:z181.array(InboundSignalSchema).max(50),checkpoint:InboundSignalCheckpointSchema,hasMore:z181.boolean()}).strict().refine(page5=>page5.items.every(item=>item.tenantId===page5.tenantId&&item.productionId===page5.productionId)&&new Set(page5.items.map(item=>item.inboxId)).size===page5.items.length&&(page5.items.length===0?!page5.hasMore:page5.items.at(-1).inboxId===page5.checkpoint.inboxId));function inboundSignalChangesMatch(input,page5){const{after,limit,tenantId,productionId}=input;const{checkpoint,items,hasMore}=page5;if(page5.tenantId!==tenantId||page5.productionId!==productionId||items.length>limit||hasMore&&items.length!==limit)return false;if(after==="CURRENT")return items.length===0;const from=after==="BEGINNING"?0n:BigInt(after.position);if(BigInt(checkpoint.position)!==from+BigInt(items.length))return false;return after==="BEGINNING"||checkpoint.epoch===after.epoch&&(items.length===0?checkpoint.inboxId===after.inboxId:items.every(item=>item.inboxId!==after.inboxId))}var InboundQueryResultSchema=z181.discriminatedUnion("kind",[page3("bindings",InboundBindingSchema),page3("inbox",InboundInboxViewSchema),signalsPage,page3("replays",InboundReplayViewSchema),page3("quarantine",InboundQuarantineViewSchema)]);var InboundReceiptInputSchema=FederationScopeSchema.extend({kind:z181.enum(["EVENT","COMMAND"]),source:uri.optional(),eventId:ref2.optional(),consumerRef:ref2.optional(),requestId:ref2.optional()}).strict().refine(v=>v.kind==="EVENT"?v.source!==void 0&&v.eventId!==void 0&&v.consumerRef!==void 0&&v.requestId===void 0:v.requestId!==void 0&&v.source===void 0&&v.eventId===void 0&&v.consumerRef===void 0);var InboundReceiptSchema=z181.discriminatedUnion("kind",[FederationScopeSchema.extend({kind:z181.literal("EVENT"),source:uri,eventId:ref2,consumerRef:ref2,result:InboundInboxViewSchema.nullable()}).strict(),FederationScopeSchema.extend({kind:z181.literal("COMMAND"),requestId:ref2,result:z181.union([InboundBindingSchema,InboundReplayResultSchema]).nullable()}).strict()]);var InboundCatalogSchema=FederationScopeSchema.extend({defaultReceive:z181.literal(false),configuration:z181.enum(["CONFIGURED","UNCONFIGURED"]),effect:z181.literal("REFRESH_HINT"),bindings:z181.array(CurrentInboundBindingSchema).max(32),events:z181.array(z181.strictObject({sourceService:ref2,type:ref2,dataSchema:uri})).max(32)}).strict().refine(v=>v.bindings.every(b=>b.tenantId===v.tenantId&&b.productionId===v.productionId&&b.effective==="ACTIVE"));var ref3=z182.string().min(1).max(256);var source4=z182.string().min(1).max(2048).refine(v=>URL.canParse(v));var FederationResourceTypeSchema=z182.enum(["nvs.lifecycle-event","nvs.federation.refresh-hint"]);var FederationResultRefSchema=z182.strictObject({sourceSystem:z182.literal("native-video-studio"),resourceType:FederationResourceTypeSchema,resourceId:ref3,revision:z182.string().regex(/^[1-9][0-9]{0,18}$/),digest:z182.string().regex(/^sha256:[a-f0-9]{64}$/),evidenceRef:ref3.optional()});var FederationResultLocatorSchema=FederationScopeSchema.extend({resourceType:FederationResourceTypeSchema,resourceId:z182.uuid().toLowerCase()}).strict();var base2=FederationScopeSchema.extend({schemaVersion:z182.literal(1),source:source4,resourceId:z182.uuid(),revision:ref3});var FederationResultValueSchema=z182.discriminatedUnion("resourceType",[base2.extend({resourceType:z182.literal("nvs.lifecycle-event"),event:ExternalLifecycleEventSchema}).strict(),base2.extend({resourceType:z182.literal("nvs.federation.refresh-hint"),revision:z182.literal("1"),consumerRef:ref3,peerSource:source4,peerTenant:ref3,resourceRef:z182.string().min(1).max(512),resourceVersion:ref3,changeKind:ref3,contractVersion:z182.literal(2).optional(),resourceNamespace:ref3.optional(),sourceService:ref3.optional(),sourceScope:HistoricalSourceScopeSchema.optional(),parentRef:z182.string().min(1).max(512).nullable().optional(),appliedAt:z182.iso.datetime()}).strict().refine(v=>{if(v.sourceService===void 0&&(v.sourceScope!==void 0||v.parentRef!==void 0))return false;return InboundNoticeSchema.safeParse({resourceRef:v.resourceRef,resourceVersion:v.resourceVersion,changeKind:v.changeKind,contractVersion:v.contractVersion,resourceNamespace:v.resourceNamespace,...v.sourceService?{sourceService:v.sourceService,sourceScope:v.sourceScope,parentRef:v.parentRef}:{}}).success})]).refine(v=>v.resourceType!=="nvs.lifecycle-event"||v.event.tenantId===v.tenantId&&v.event.productionId===v.productionId&&v.event.eventId===v.resourceId&&String(v.event.basis.productionRevision)===v.revision);var FederationResultReadSchema=FederationScopeSchema.extend({source:source4,reference:FederationResultRefSchema}).strict();var FederationResultReferenceSchema=FederationScopeSchema.extend({source:source4,reference:FederationResultRefSchema,meaning:z182.literal("IMMUTABLE_FACT")}).strict();var FederationResultSnapshotSchema=FederationResultReferenceSchema.extend({value:FederationResultValueSchema}).strict().refine(v=>v.value.source===v.source&&v.value.tenantId===v.tenantId&&v.value.productionId===v.productionId&&v.reference.resourceType===v.value.resourceType&&v.reference.resourceId===v.value.resourceId&&v.reference.revision===v.value.revision);function canonicalFederationJson(value2){return boundedJson(value2,2048,16,32768)}function canonicalFederationReadJson(value2){return boundedJson(value2,4096,24,65536)}function canonicalFederationCatalogJson(value2){return boundedJson(value2,2e4,32,131072)}function boundedJson(value2,maxNodes,maxDepth,maxBytes){let nodes=0;let bytes=0;const encoder=new TextEncoder;const reserve=size=>{bytes+=size;if(bytes>maxBytes)throw Error("FEDERATION_JSON_SIZE")};const scalar=text6=>{reserve(encoder.encode(text6).byteLength);return text6};const seen=new Set;const encode=(v,depth2)=>{if(++nodes>maxNodes||depth2>maxDepth)throw Error("FEDERATION_JSON_BUDGET");if(v===null||typeof v==="boolean")return scalar(String(v));if(typeof v==="number"&&Number.isFinite(v))return scalar(JSON.stringify(v));if(typeof v==="string"){if(v.length>maxBytes)throw Error("FEDERATION_JSON_SIZE");if(/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/u.test(v))throw Error("FEDERATION_JSON_UNICODE");return scalar(JSON.stringify(v))}if(!v||typeof v!=="object"||seen.has(v))throw Error("FEDERATION_JSON_VALUE");seen.add(v);try{if(Array.isArray(v)){if(v.length>maxNodes-nodes)throw Error("FEDERATION_JSON_BUDGET");if(Reflect.ownKeys(v).length!==v.length+1)throw Error("FEDERATION_JSON_ARRAY");reserve(v.length===0?2:v.length+1);const items=[];for(let index=0;index<v.length;index++){const property=Object.getOwnPropertyDescriptor(v,String(index));if(!property||!("value"in property))throw Error("FEDERATION_JSON_ARRAY");items.push(encode(property.value,depth2+1))}return"["+items.join(",")+"]"}if(Object.getPrototypeOf(v)!==Object.prototype&&Object.getPrototypeOf(v)!==null)throw Error("FEDERATION_JSON_OBJECT");if(Object.getOwnPropertySymbols(v).length)throw Error("FEDERATION_JSON_OBJECT");const keys=Object.keys(v);if(keys.length>maxNodes-nodes)throw Error("FEDERATION_JSON_BUDGET");reserve(keys.length===0?2:keys.length*2+1);return"{"+keys.sort().map(key10=>{const property=Object.getOwnPropertyDescriptor(v,key10);if(!property||!("value"in property))throw Error("FEDERATION_JSON_PROPERTY");return encode(key10,depth2+1)+":"+encode(property.value,depth2+1)}).join(",")+"}"}finally{seen.delete(v)}};return encode(value2,0)}var canonicalHostContractJson=canonicalFederationCatalogJson;var bounded2=z183.unknown().refine(value2=>{try{canonicalHostContractJson(value2);return true}catch{return false}},{abort:true});var digest3=z183.string().regex(/^sha256:[a-f0-9]{64}$/);var jsonSchema2=z183.record(z183.string(),z183.json());var operations={"installation.read":{method:"GET",path:"/nvs-agent-host/v1/installations/{installationId}"},"task.submit":{method:"POST",path:"/nvs-agent-host/v1/tasks"},"task.by-request":{method:"GET",path:"/nvs-agent-host/v1/tasks/by-request"},"task.get":{method:"GET",path:"/nvs-agent-host/v1/tasks/{runKey}"},"task.cancel":{method:"POST",path:"/nvs-agent-host/v1/tasks/{runKey}/cancel"}};var eventing={standard:"EventSDK",notificationProfile:"eventsdk/1.2",receiptProfile:"eventsdk/1.1",requiredForHostExecution:false,defaultReceive:false,subscriberKinds:["SYSTEM","AGENT_RUNTIME","HOST_BOT"],authorization:"INDEPENDENT_CURRENT_AUTHORITY",wake:"RECEIVER_OWNED",adoption:"RECEIVER_OWNER_GOAL_REQUIRED",receiptMeaning:"LOCAL_APPLIED_IS_NOT_AGENT_ADOPTION",operations:{catalog:"federation.catalog",select:"federation.subscription.set",read:"federation.subscription.get",handoff:"federation.subscription.handoff",contract:"federation.subscription.contract",resultReference:"federation.result.reference",resultRead:"federation.result.read",receiptInspection:"federation.delivery.inspect",receiptHandoff:"federation.receipt-inbound.handoff"}};var semanticChecks=["OPAQUE_SCOPE_IS_NOT_NATIVE_TENANT_MAPPING","JSON_SCHEMA_PLUS_SEMANTIC_CHECKS_REQUIRED","I_JSON_FINITE_PLAIN_DENSE_JSON_NO_DUPLICATE_KEYS_OR_LONE_SURROGATES","HOST_REFERENCES_1_TO_256_UNICODE_CODEPOINTS_WITHOUT_C0_C1_CONTROLS","CURRENT_REGISTRATION_CONSENT_GRANT_PERMIT_LEASE_ACCESS_REQUIRED","INSTALLATION_RECHECK_BEFORE_AND_AFTER_NATIVE_MANIFEST","INPUT_SHA256_CANONICAL_COMPLETE_INPUT_INCLUDING_NATIVE_PROOF","EXACT_REQUEST_INPUT_SCOPE_CHOICE_INSTALLATION_AUTHORITY_AND_TASK","RESPONSE_TIME_ORDER_FRESH_AUTHORIZATION_AND_DEADLINES_WITHIN_NATIVE_PROOF","SUBMIT_DEADLINE_INCLUDES_CREDENTIAL_ACCESS_AND_NATIVE_AUTHORITY_EXPIRY","NO_WRITE_BEFORE_DISPATCH_UNKNOWN_AFTER_DISPATCH_NO_AUTOMATIC_RETRY","RECOVERY_OBSERVES_ORIGINAL_REQUEST_WITHOUT_RESUBMISSION","CANCEL_USES_DISTINCT_REQUEST_AND_EXACT_ORIGINAL_TASK","HOST_REPORT_IS_NOT_PRODUCTION_TRUTH_OR_RESULT_ADOPTION","SUBSCRIPTION_EXECUTION_AND_CONTENT_AUTHORITY_ARE_INDEPENDENT"];var route=value2=>z183.strictObject({method:z183.literal(value2.method),path:z183.literal(value2.path)});var AgentHostContractDocumentSchema=bounded2.pipe(z183.strictObject({contract:z183.literal("nvs-agent-host-contract/1"),hostProtocol:z183.literal(HOST_PROTOCOL),hostContractDigest:z183.literal(HostProtocolDigest),delegationContractDigest:z183.literal(HostDelegationDigest),nativeSelectionVersion:z183.literal(2),nativeProfileVersion:z183.literal(2),schemaDialect:z183.literal("https://json-schema.org/draft/2020-12/schema"),origin:z183.literal("DEPLOYMENT_REGISTERED_ONLY"),credential:z183.literal("PRIVATE_BEARER_NEVER_HUMAN_TOKEN"),scopeQuery:z183.tuple([z183.literal("scopeNamespace"),z183.literal("scopeRef")]),requestQuery:z183.literal("requestId"),operations:z183.strictObject({"installation.read":route(operations["installation.read"]),"task.submit":route(operations["task.submit"]),"task.by-request":route(operations["task.by-request"]),"task.get":route(operations["task.get"]),"task.cancel":route(operations["task.cancel"])}),schemas:z183.strictObject({selection:jsonSchema2,installation:jsonSchema2,taskRequest:jsonSchema2,taskResponse:jsonSchema2,taskCancel:jsonSchema2}),semanticChecks:z183.array(z183.enum(semanticChecks)).length(semanticChecks.length).refine(values=>values.every((v,i)=>v===semanticChecks[i])),maxTaskBytes:z183.literal(131072),currentAuthority:z183.literal("NOT_OBSERVED"),eventing:z183.strictObject({standard:z183.literal(eventing.standard),notificationProfile:z183.literal(eventing.notificationProfile),receiptProfile:z183.literal(eventing.receiptProfile),requiredForHostExecution:z183.literal(false),defaultReceive:z183.literal(false),subscriberKinds:z183.tuple([z183.literal("SYSTEM"),z183.literal("AGENT_RUNTIME"),z183.literal("HOST_BOT")]),authorization:z183.literal(eventing.authorization),wake:z183.literal(eventing.wake),adoption:z183.literal(eventing.adoption),receiptMeaning:z183.literal(eventing.receiptMeaning),operations:z183.strictObject({catalog:z183.literal(eventing.operations.catalog),select:z183.literal(eventing.operations.select),read:z183.literal(eventing.operations.read),handoff:z183.literal(eventing.operations.handoff),contract:z183.literal(eventing.operations.contract),resultReference:z183.literal(eventing.operations.resultReference),resultRead:z183.literal(eventing.operations.resultRead),receiptInspection:z183.literal(eventing.operations.receiptInspection),receiptHandoff:z183.literal(eventing.operations.receiptHandoff)})}),qualification:z183.literal("NVS_DECLARATION_ONLY")}));var AgentHostContractInputSchema=AgentHostScopeSchema.extend({expectedDigest:digest3.optional()}).strict();var AgentHostContractSchema=bounded2.pipe(AgentHostScopeSchema.extend({document:AgentHostContractDocumentSchema,digest:digest3,maxReplyBytes:z183.literal(131072)}).strict());import{z as z184}from"zod";var id13=z184.uuid().toLowerCase();var EventLinkScopeSchema=FederationScopeSchema.extend({tenantId:id13.pipe(TenantIdSchema),productionId:id13.pipe(ProductionIdSchema)});var EventLinkContinuationScopeSchema=z184.strictObject({workspace:id13,productionId:id13,eventLink:id13});var EventLinkStateLocatorSchema=z184.string().regex(/^[a-f0-9]{64}[A-Za-z0-9_-]{43}$/).transform(value2=>{const uuid9=v=>[v.slice(0,8),v.slice(8,12),v.slice(12,16),v.slice(16,20),v.slice(20)].join("-");return{requestId:uuid9(value2.slice(0,32)),productionId:uuid9(value2.slice(32,64))}}).pipe(z184.strictObject({requestId:id13,productionId:id13}));var EventLinkRequestInputSchema=EventLinkScopeSchema.extend({requestId:id13});var EventLinkStartInputSchema=EventLinkRequestInputSchema.extend({targetId:z184.string().regex(/^[a-zA-Z0-9_.:-]{1,80}$/),eventType:ExternalEventTypeSchema});var EventLinkConfirmInputSchema=EventLinkRequestInputSchema.extend({expiresAt:z184.iso.datetime().transform(v=>new Date(v).toISOString()),publicationMode:z184.enum(["FIXED","ON_DEMAND"])});var EventLinkCallbackInputSchema=EventLinkRequestInputSchema.extend({callback:z184.string().min(1).max(8192)});var EventLinkTargetsSchema=EventLinkScopeSchema.extend({sdkVersion:z184.literal("0.4.0"),protocol:z184.literal("event-link/1"),role:z184.literal("SENDER"),configuration:z184.enum(["CONFIGURED","UNCONFIGURED"]),targets:z184.array(z184.strictObject({id:z184.string().max(80),displayName:z184.string().min(1).max(160),serviceRef:z184.string().min(1).max(256),eventTypes:z184.array(ExternalEventTypeSchema).min(1).max(14)})).max(32)});var EventLinkViewSchema=EventLinkRequestInputSchema.extend({phase:z184.enum(["LOGIN","EXCHANGING","CONFIRM","CONFIRMED","DENIED","CANCELLED","EXPIRED","UNKNOWN"]),targetId:z184.string().max(80),eventType:ExternalEventTypeSchema,expiresAt:z184.iso.datetime(),peer:z184.strictObject({serviceRef:z184.string().min(1).max(256),tenantRef:z184.string().min(1).max(256),displayName:z184.string().min(1).max(160)}).nullable(),route:FederationRouteSchema.nullable()}).refine(v=>v.phase==="CONFIRMED"?!!v.route&&v.route.tenantId===v.tenantId&&v.route.productionId===v.productionId&&v.route.routeId===v.requestId&&v.route.selectedEventTypes.length===1&&v.route.selectedEventTypes[0]===v.eventType&&v.peer?.tenantRef===v.route.remoteTenant&&v.peer?.serviceRef===v.route.remoteService:v.route===null);var authorizationUrl=z184.url().max(8192).refine(value2=>{try{const u=new URL(value2);return!u.username&&!u.password&&!u.hash&&(u.protocol==="https:"||u.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(u.hostname))&&u.pathname==="/eventsdk/connect/authorize"}catch{return false}});var EventLinkStartSchema=EventLinkViewSchema.safeExtend({authorizationUrl:authorizationUrl.nullable(),continuationUrl:z184.url().max(2048)}).refine(v=>{const human=new URL(v.continuationUrl);if(human.username||human.password||human.hash||human.pathname!=="/settings/events"||human.protocol!=="https:"&&!(human.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(human.hostname))||human.searchParams.size!==3||!EventLinkContinuationScopeSchema.safeParse(Object.fromEntries(human.searchParams)).success||human.searchParams.get("workspace")!==v.tenantId||human.searchParams.get("eventLink")!==v.requestId||human.searchParams.get("productionId")!==v.productionId)return false;if(v.phase!=="LOGIN")return v.authorizationUrl===null;if(!v.authorizationUrl)return false;const p=new URL(v.authorizationUrl).searchParams;return p.get("request_id")===v.requestId&&p.get("profile")==="event-link/1"&&p.get("state")?.startsWith((v.requestId+v.productionId).replaceAll("-",""))===true&&EventLinkStateLocatorSchema.safeParse(p.get("state")).success});var EventLinkConfirmedSchema=EventLinkViewSchema.refine(v=>v.phase==="CONFIRMED");var EventLinkCancelledSchema=EventLinkViewSchema.refine(v=>v.phase==="CANCELLED");import{z as z185}from"zod";var ref4=z185.uuid().toLowerCase();var proof=z185.string().regex(/^[A-Za-z0-9_-]{43}$/);var EventReceiverLocatorSchema=z185.strictObject({ref:ref4,proof});var EventReceiverAccessSchema=EventReceiverLocatorSchema.extend({tenantId:EventLinkScopeSchema.shape.tenantId});var EventReceiverBeginInputSchema=z185.strictObject({authorization:z185.string().min(1).max(8192),resume:EventReceiverLocatorSchema.optional()});var EventReceiverBeginSchema=EventReceiverLocatorSchema.extend({expiresAt:z185.iso.datetime()});var EventReceiverPrepareSchema=EventReceiverAccessSchema.extend({productionId:EventLinkScopeSchema.shape.productionId,sourceSelection:FederationSourceSelectionSchema,expiresAt:z185.iso.datetime().transform(v=>new Date(v).toISOString())});var EventReceiverDecideSchema=EventReceiverAccessSchema.extend({consentBinding:z185.string().regex(/^[a-f0-9]{64}$/).optional(),decision:z185.enum(["allow","deny"])}).refine(v=>v.decision==="deny"||v.consentBinding!==void 0);var EventReceiverChoiceSchema=EventLinkScopeSchema.extend({sourceSelection:FederationSourceSelectionSchema,expiresAt:z185.iso.datetime()});var EventReceiverViewSchema=z185.strictObject({ref:ref4,state:z185.enum(["PENDING","APPROVED","CONSUMED","DENIED","EXPIRED"]),expiresAt:z185.iso.datetime(),source:z185.strictObject({displayName:z185.string().min(1).max(160),serviceRef:FederationPeerRefSchema,tenantRef:FederationPeerRefSchema,installationSource:z185.string().min(1).max(2048)}),eventType:z185.literal(RESOURCE_CHANGE_TYPE),effect:z185.literal("REFRESH_HINT"),choice:EventReceiverChoiceSchema.nullable()});var EventReceiverInspectionSchema=z185.strictObject({view:EventReceiverViewSchema,callback:z185.strictObject({redirectUri:z185.url().max(2048),state:z185.string().max(8192),issuer:z185.url()})});var EventReceiverReviewSchema=z185.strictObject({view:EventReceiverViewSchema,consentBinding:z185.string().regex(/^[a-f0-9]{64}$/)});var EventReceiverDecisionSchema=z185.strictObject({ref:ref4,redirectUri:z185.url().max(16384)});var EventReceiverPortalSchema=EventLinkScopeSchema.extend({role:z185.literal("RECEIVER"),protocol:z185.literal("event-link/1"),sdkVersion:z185.literal("0.4.0"),configuration:z185.enum(["CONFIGURED","UNCONFIGURED"]),authorizationEndpoint:z185.url().nullable(),tokenEndpoint:z185.url().nullable(),eventType:z185.literal(RESOURCE_CHANGE_TYPE),dataSchema:z185.literal(RESOURCE_CHANGE_SCHEMA),effect:z185.literal("REFRESH_HINT"),defaultReceive:z185.literal(false)});var intent=z186.strictObject({productionId:z186.uuid(),idempotencyKey:z186.string().trim().min(1).max(200),deviceId:z186.uuid().optional(),validationMode:DeviceRenderTargetSchema.shape.validationMode});var DeviceDiscoveryInputSchema=ProjectDeviceListInputSchema.omit({tenantId:true});var DeviceRenderIntentSchema=z186.discriminatedUnion("kind",[intent.extend({kind:z186.literal("preview"),profileId:RoughCutProfileIdSchema.optional()}),intent.extend({kind:z186.literal("final")})]);var DeviceRenderReadSchema=z186.strictObject({kind:z186.enum(["preview","final"]),productionId:z186.uuid(),renderId:z186.uuid()});var basisInput=DeviceRenderReadSchema.pick({kind:true,productionId:true});var DeviceRenderDownloadSchema=DeviceRenderReadSchema.extend({role:z186.enum(["VIDEO","POSTER"])});var PreparedDeviceRenderSchema=z186.discriminatedUnion("kind",[z186.strictObject({kind:z186.literal("preview"),command:RoughCutStartSchema.extend({deviceExecution:DeviceRenderTargetSchema})}),z186.strictObject({kind:z186.literal("final"),command:FinalRenderStartSchema.extend({deviceExecution:DeviceRenderTargetSchema})})]);var DeviceRenderReceiptHandoffSchema=z186.strictObject({protocol:z186.literal("NVS_RENDER_RECEIPT_V1"),scope:z186.strictObject({resource:z186.string().min(1).max(2048),tenantId:z186.uuid(),projectId:z186.uuid(),principalId:z186.uuid(),grantId:z186.uuid()}),prepared:PreparedDeviceRenderSchema});var DeviceRenderAdmissionSchema=z186.union([RoughCutAdmissionSchema.extend({deviceExecution:DeviceRenderReceiptSchema}),FinalRenderAdmissionSchema.extend({deviceExecution:DeviceRenderReceiptSchema})]);var NativeStudioDeviceRenders=class{constructor(caller){this.caller=caller}caller;list(raw,options){const input=DeviceDiscoveryInputSchema.parse(raw);return this.caller.call("devices.list",{...input,tenantId:this.caller.tenantId},options)}async basis(raw,options){const{kind,productionId}=basisInput.parse(raw);const scope8={tenantId:this.caller.tenantId,productionId};if(kind==="final"){const e=await this.caller.call("final-render.eligibility",scope8,options);const selection2=e.finalReady.selection;const basis2=e.renderable&&e.profile&&selection2?{selectionId:selection2.id,expectedFinalReadyVersion:e.finalReady.version,timelineVersionId:selection2.timelineVersionId,timelineFingerprint:selection2.timelineFingerprint,expectedProductionRevision:e.productionRevision,profileId:e.profile.id,audioPolicy:e.profile.audioPolicy,captionPolicy:e.profile.captionPolicy}:null;return{kind,basis:basis2,blockers:basis2?[]:e.blockers.length?e.blockers:["FINAL_READY_NOT_CURRENT"],sourceBlockers:e.sourceBlockers}}const basis=await this.caller.call("timeline.basis",scope8,options);if(!basis.runnable||basis.currentTimelineVersion===0)return{kind,basis:null,blockers:["TIMELINE_NOT_RUNNABLE"]};const current=await this.caller.call("timeline.current",scope8,options);const selection=currentPreviewRenderBasis(basis,current);return{kind,basis:selection,blockers:selection?[]:["TIMELINE_NOT_CURRENT"]}}async prepare(raw,options){const input=DeviceRenderIntentSchema.parse(raw);const scope8={tenantId:this.caller.tenantId,productionId:input.productionId};const base3={...scope8,idempotencyKey:input.idempotencyKey,deviceExecution:{mode:"tenant-device-only",...input.deviceId?{deviceId:input.deviceId}:{},...input.validationMode?{validationMode:input.validationMode}:{}}};const{basis}=await this.basis({kind:input.kind,productionId:input.productionId},options);if(!basis)throw new NativeStudioSdkError("STALE_BASIS","STALE_BASIS","NO_WRITE");return PreparedDeviceRenderSchema.parse({kind:input.kind,command:{...base3,...basis,...input.kind==="preview"&&{profileId:input.profileId??"PREVIEW_H264_480P_V1"}}})}get(raw,options){const{kind,...input}=DeviceRenderReadSchema.parse(raw);return kind==="preview"?this.caller.call("rough-cut.get",input,options):this.caller.call("final-render.get",input,options)}async mediaTicket(raw,options){const{kind,...input}=DeviceRenderDownloadSchema.parse(raw);const result=kind==="preview"?await this.caller.call("rough-cut.media-ticket",input,options):await this.caller.call("final-render.media-ticket",input,options);if(result.ticket.object.tenantId!==this.caller.tenantId||result.ticket.method!=="GET"||result.ticket.object.role!==input.role)throw new NativeStudioSdkError("MEDIA_IDENTITY_MISMATCH","INTERNAL_OPERATIONAL_FAILURE","NO_WRITE");return result}async download(raw,options,expectedProjectId){const input=DeviceRenderDownloadSchema.parse(raw);const{role,...scope8}=input;const view=await this.get(scope8,options);const accepted3="roughCut"in view?view.roughCut:view.finalOutput;const expected=role==="POSTER"?accepted3?.poster:accepted3;const failure=()=>new NativeStudioSdkError("MEDIA_IDENTITY_MISMATCH","INTERNAL_OPERATIONAL_FAILURE","NO_WRITE");if(!expected||expectedProjectId&&expectedProjectId!==view.projectId)throw failure();const media=await this.mediaTicket(input,options);if(media.ticket.object.projectId!==view.projectId||media.representationId!==expected.representationId||media.ticket.object.checksumSha256!==expected.checksumSha256||media.ticket.object.byteSize!==expected.byteSize)throw failure();const output=await downloadRenderObject(media.ticket,options);return{...output,representationId:media.representationId,renderId:media.renderId}}receipt(raw,options){const prepared=PreparedDeviceRenderSchema.parse(raw);return prepared.kind==="preview"?this.caller.call("rough-cut.admission-receipt",prepared.command,options):this.caller.call("final-render.admission-receipt",prepared.command,options)}start(raw,options){const prepared=PreparedDeviceRenderSchema.parse(raw);return prepared.kind==="preview"?this.caller.call("rough-cut.start",prepared.command,options):this.caller.call("final-render.start",prepared.command,options)}};import{createHash as createHash5}from"node:crypto";import{createHash as createHash4}from"node:crypto";import{z as z187}from"zod";import{createHash as createHash2}from"node:crypto";function assertFederationExchangeReply(key10,i,r){let valid=true,write2=false;if(key10==="federation.subscription.contract"){valid=r.subscription.revision===i.expectedRevision&&(!i.expectedSource||i.expectedSource===r.source)&&(r.status!=="READY"||(!i.expectedCatalogDigest||i.expectedCatalogDigest===r.catalogDigest)&&r.catalogDigest==="sha256:"+createHash2("sha256").update(canonicalFederationCatalogJson(r.catalog)).digest("hex"))}if(key10==="federation.result.reference"){const ref7=r.reference;valid=i.resourceType===ref7.resourceType&&i.resourceId===ref7.resourceId}if(key10==="federation.result.read")valid=canonicalFederationJson(i.reference)===canonicalFederationJson(r.reference)&&r.reference.digest==="sha256:"+createHash2("sha256").update(canonicalFederationJson(r.value)).digest("hex");if(key10==="federation.receipt-route.configure"){write2=true;valid=["grantRef","grantVersion","state","receiptProfile"].every(k=>i[k]===r[k])&&r.revision===Number(i.expectedRevision)+1&&Date.parse(String(i.notBefore))===Date.parse(String(r.notBefore))&&Date.parse(String(i.expiresAt))===Date.parse(String(r.expiresAt))}if(key10==="federation.receipt.query")valid=r.items.every(v=>(!i.routeId||v.routeId===i.routeId)&&(!i.inboxId||v.inboxId===i.inboxId)&&(!i.originDeliveryId||v.originDelivery?.deliveryId===i.originDeliveryId));if(key10==="federation.receipt.command")valid=i.requestId===r.requestId&&(!r.result||!("requestId"in r.result)||r.result.requestId===i.requestId);if(key10==="federation.receipt.recover"){write2=true;valid=i.requestId===r.requestId&&r.generation===Number(i.expectedGeneration)+1&&r.attempts===i.expectedAttempts}if(key10==="federation.subscription.handoff")valid=i.expectedRevision===void 0||i.expectedRevision===r.subscription.revision;if(!valid)throw new NativeStudioSdkError("RESPONSE_SCOPE_MISMATCH","INTERNAL_OPERATIONAL_FAILURE",write2?"UNKNOWN":"NO_WRITE")}import{createHash as createHash3}from"node:crypto";function validAcceptance(i,r){const b=r.binding;return b.bindingId===i.bindingId&&b.revision===i.expectedRevision&&(!i.expectedSource||i.expectedSource===r.source)&&(!i.expectedDigest||i.expectedDigest===r.digest)&&(r.document===null||r.digest==="sha256:"+createHash3("sha256").update(canonicalFederationReadJson(r.document)).digest("hex"))}function assertReceiptInboundReply(key10,i,r){if(!key10.startsWith("federation.receipt-inbound."))return;let valid=true;const write2=key10.endsWith(".configure");if(key10.endsWith(".contract"))valid=validAcceptance(i,r);if(key10.endsWith(".handoff")){const inspection=r.inspection,delivery2=inspection.delivery;valid=delivery2.digest===i.expectedDeliveryDigest&&validAcceptance({...i,expectedDigest:i.expectedAcceptanceDigest},r.acceptance)}if(write2)valid=["contractVersion","remoteService","source","remoteTenant","peerType","consumerRef","peerConsumerRef","peerTargetScope","grantRef","grantVersion","state"].every(k=>i[k]===r[k])&&r.revision===Number(i.expectedRevision)+1&&Date.parse(String(i.notBefore))===Date.parse(String(r.notBefore))&&Date.parse(String(i.expiresAt))===Date.parse(String(r.expiresAt));if(key10.endsWith(".command"))valid=i.requestId===r.requestId;if(key10.endsWith(".catalog"))valid=r.bindings.every(b=>b.tenantId===i.tenantId&&b.productionId===i.productionId&&b.effective==="ACTIVE");if(key10.endsWith(".query"))valid=r.items.every(v=>(!i.bindingId||v.bindingId===i.bindingId)&&(!i.originalDeliveryId||v.originalDeliveryId===i.originalDeliveryId));if(!valid)throw new NativeStudioSdkError("RESPONSE_SCOPE_MISMATCH","INTERNAL_OPERATIONAL_FAILURE",write2?"UNKNOWN":"NO_WRITE")}function assertDeliveryInspectionReply(key10,i,raw){if(key10!=="federation.delivery.inspect")return;const d=raw.delivery,b=raw.receiptBinding;if(i.expectedSource&&i.expectedSource!==raw.source||i.expectedDigest&&i.expectedDigest!==d.digest||(i.receiptBindingId?b?.bindingId!==i.receiptBindingId:b!==null))throw new NativeStudioSdkError("RESPONSE_SCOPE_MISMATCH","INTERNAL_OPERATIONAL_FAILURE","NO_WRITE")}function assertFederationReply(key10,input,raw){if(!key10.startsWith("federation.")||!raw||typeof raw!=="object")return;const result=raw;assertDeliveryInspectionReply(key10,input,result);assertReceiptInboundReply(key10,input,result);assertFederationExchangeReply(key10,input,result);let valid=true;if(key10==="federation.inbound.configure"){valid=["contractVersion","source","remoteService","remoteTenant","consumerRef","grantRef","grantVersion","state"].every(k=>input[k]===result[k])&&result.revision===Number(input.expectedRevision)+1&&Date.parse(String(input.notBefore))===Date.parse(String(result.notBefore))&&Date.parse(String(input.expiresAt))===Date.parse(String(result.expiresAt))&&(!input.connectionRef||input.connectionRef===result.connectionRef)&&canonicalFederationJson(input.sourceSelection??null)===canonicalFederationJson(result.sourceSelection??null)}if(key10==="federation.inbound.replay")valid=input.requestId===result.requestId;if(key10==="federation.inbound.catalog")valid=result.bindings.every(b=>["tenantId","productionId"].every(k=>input[k]===b[k]));if(key10==="federation.inbound.signals"&&typeof input.after==="string"){const[first]=result.items;valid=first===void 0||first.inboxId>input.after}if(key10==="federation.inbound.signal-changes")valid=inboundSignalChangesMatch(input,result);if(key10==="federation.inbound.receipt")valid=input.kind==="COMMAND"?input.requestId===result.requestId&&(!result.result||!("requestId"in result.result)||input.requestId===result.result.requestId):["source","eventId","consumerRef"].every(k=>input[k]===result[k]&&(!result.result||input[k]===result.result[k]));if(key10==="federation.recover"){valid=input.requestId===result.requestId&&result.revision===Number(input.expectedRevision)+1&&(input.deliveryId??null)===result.deliveryId&&(input.kind!=="RETRY_HOLD"||input.expectedAttempts===result.attempts)}if(key10==="federation.receipt")valid=input.requestId===result.requestId;if(key10==="federation.query"){valid=result.items.every(r=>["routeId","eventId","deliveryId"].every(k=>input[k]===void 0||r[k]===input[k]))}if(key10==="federation.route.configure"||key10==="federation.subscription.set"){const route5=key10==="federation.route.configure";const view=route5?result:result.subscription;const refs=route5?["remoteService","remoteTenant","grantRef"]:["subscriberKind","subscriberRef"];const arrays=route5?["grantEventTypes","selectedEventTypes"]:["eventTypes"];valid=refs.every(k=>input[k]===view[k])&&arrays.every(k=>JSON.stringify([...input[k]].sort())===JSON.stringify([...view[k]].sort()))&&view.revision===Number(input.expectedRevision)+1&&view.state===input.state&&Date.parse(String(input.expiresAt))===Date.parse(String(view.expiresAt));if(route5)valid=valid&&input.publicationMode===view.publicationMode&&Date.parse(String(input.notBefore))===Date.parse(String(view.notBefore))}if(!valid)throw new NativeStudioSdkError("RESPONSE_SCOPE_MISMATCH","INTERNAL_OPERATIONAL_FAILURE",key10==="federation.route.configure"||key10==="federation.subscription.set"||key10==="federation.inbound.configure"||key10==="federation.inbound.replay"||key10==="federation.recover"?"UNKNOWN":"NO_WRITE")}var success=z187.strictObject({semanticStatus:z187.literal("SUCCESS")});var same=(a,b)=>canonicalLocalJson(a??null)===canonicalLocalJson(b??null);var commandFingerprint=command4=>createHash4("sha256").update(canonicalLocalJson(command4)).digest("hex");function resultMatches(command4,raw){const schema=command4.kind==="ENROLL"?LocalDeviceViewSchema:command4.kind==="PREVIEW"?LocalPreviewAdmissionSchema:command4.kind==="FINAL_RENDER"?LocalFinalRenderAdmissionSchema:success;const parsed=schema.safeParse(raw);if(!parsed.success)return false;const result=parsed.data,original=command4.input;for(const key10 of["tenantId","projectId","deviceId","productionId","timelineVersionId"])if(key10 in original&&key10 in result&&String(result[key10]).toLowerCase()!==String(original[key10]).toLowerCase())return false;if(command4.kind==="ENROLL")return result.revokedAt===null&&(!command4.input.expectedPrincipalId||String(result.enrolledByPrincipalId).toLowerCase()===command4.input.expectedPrincipalId.toLowerCase())&&["publicKey","label","platform","runtimeVersion"].every(key10=>same(original[key10],result[key10]));if(command4.kind==="PREVIEW"||command4.kind==="FINAL_RENDER")return same(original.timelineFingerprint,result.timelineFingerprint)&&same(command4.input.placement,result.placement.policy);return true}function checkedManagementReceipt(rawCommand,rawReceipt){const command4=LocalDeviceManagementCommandSchema.parse(rawCommand);const receipt=LocalManagementReceiptSchema.parse(rawReceipt);if(receipt.fingerprint!==commandFingerprint(command4)||receipt.result!==null&&!resultMatches(command4,receipt.result))throw new NativeStudioSdkError("LOCAL_RECEIPT_INVALID","BLOCKED","NO_WRITE");return receipt}function checkedEnrollmentObservation(original,observation,write2){const command4="kind"in original?original:void 0;const request="kind"in original?original.input:original;const bound=value2=>value2.tenantId.toLowerCase()===request.tenantId.toLowerCase()&&value2.requestId.toLowerCase()===request.requestId.toLowerCase();const invalid=()=>{throw new NativeStudioSdkError("DEVICE_ENROLLMENT_RESPONSE_INVALID","BLOCKED",write2?"UNKNOWN":"NO_WRITE")};if(!bound(observation))invalid();const fingerprint2=command4&&commandFingerprint(command4);if(observation.state==="ISSUED"&&(!bound(observation.ticket)||fingerprint2&&observation.ticket.fingerprint!==fingerprint2))invalid();if(observation.state==="EXPIRED"&&fingerprint2&&observation.fingerprint!==fingerprint2)invalid();if(observation.state==="ENROLLED"){const{receipt}=observation;if(receipt.result.tenantId.toLowerCase()!==request.tenantId.toLowerCase()||command4&&(receipt.fingerprint!==fingerprint2||!resultMatches(command4,receipt.result)))invalid()}return observation}function assertManagementReceipt(key10,input,result){assertFederationReply(key10,input,result);if(key10==="device.management-receipt")checkedManagementReceipt(input.command,result);else if(key10==="device.enrollment.issue"||key10==="device.enrollment.lookup"){const write2=key10==="device.enrollment.issue";const original=write2?{kind:"ENROLL",input:DeviceEnrollmentIssueSchema.parse(input)}:DeviceEnrollmentLookupSchema.parse(input);checkedEnrollmentObservation(original,DeviceEnrollmentObservationSchema.parse(result),write2)}else if(key10==="device.enroll"){const command4=LocalDeviceManagementCommandSchema.parse({kind:"ENROLL",input});if(!resultMatches(command4,result))throw new NativeStudioSdkError("RESPONSE_SCOPE_MISMATCH","INTERNAL_OPERATIONAL_FAILURE","UNKNOWN")}}function validateDeviceEnrollmentHandoff(raw){const parsed=DeviceEnrollmentHandoffSchema.safeParse(raw);if(!parsed.success||createHash5("sha256").update(canonicalLocalJson(parsed.data.command)).digest("hex")!==parsed.data.fingerprint)throw new NativeStudioSdkError("DEVICE_HANDOFF_INVALID","INVALID_INPUT","NO_WRITE");return parsed.data}async function issueDeviceEnrollment(client,raw,options={}){const handoff=await verifyCaller(client,raw,options);const result=await client.call("device.enrollment.issue",DeviceEnrollmentIssueSchema.parse(handoff.command.input),options);return checkedEnrollmentObservation(handoff.command,result,true)}async function lookupDeviceEnrollment(client,raw,options={}){const handoff=await verifyCaller(client,raw,options);const{tenantId,requestId:requestId2}=handoff.command.input;const result=await client.call("device.enrollment.lookup",{tenantId,requestId:requestId2},options);return checkedEnrollmentObservation(handoff.command,result,false)}async function verifyCaller(client,raw,options){const handoff=validateDeviceEnrollmentHandoff(raw);const{tenantId,principalId,origin}=handoff.scope;if(tenantId.toLowerCase()!==client.tenantId.toLowerCase())throw new NativeStudioSdkError("FORBIDDEN","BLOCKED","NO_WRITE");const caller=await client.call("workspace.caller",{tenantId},options);if(caller.serverOrigin!==origin||caller.tenantId.toLowerCase()!==tenantId.toLowerCase()||caller.principalId.toLowerCase()!==principalId.toLowerCase())throw new NativeStudioSdkError("FORBIDDEN","BLOCKED","NO_WRITE");return handoff}async function submitDeviceEnrollment(client,raw,options={}){const handoff=await verifyCaller(client,raw,options);const result=await client.call("device.enroll",handoff.command.input,options);return{fingerprint:handoff.fingerprint,result}}async function recoverDeviceEnrollment(client,raw,options={}){const handoff=await verifyCaller(client,raw,options);return client.call("device.management-receipt",{tenantId:handoff.scope.tenantId,command:handoff.command},options)}import"zod";function descriptorOperation(input,output,request,expectedPath){return Object.freeze({...operation(input,output,request,[],{readOnly:true}),expectedPath})}function operation(input,output,request,identity6=[],options={}){return Object.freeze({input,output,request,identity:identity6,readOnly:options.readOnly,expectedPath:void 0,identityWhenPresent:options.identityWhenPresent??[]})}function path(...parts){return"/v1/"+parts.map(value2=>encodeURIComponent(value2)).join("/")}function pageQuery(input){return{limit:input.limit,next:input.next}}function mcpOperation(input,output,readOnly,identity6=[],expectedPath){return Object.freeze({input,output,request:null,readOnly,identity:identity6,expectedPath,identityWhenPresent:[]})}var post=(action,input,output,readOnly,identity6=[])=>operation(input,output,i=>({method:"POST",tenantId:i.tenantId,path:path("shares",action),body:i}),identity6,{readOnly});var target2=["shareId","projectId","artifactId","representationId"].map(k=>[k,"share."+k]);var shareOperations={"share.create":post("create",ShareCreateSchema,ShareLinkResultSchema,false,target2),"share.link":post("link",ShareGetSchema,ShareLinkResultSchema,false,[["shareId","share.shareId"]]),"share.get":post("get",ShareGetSchema,ShareViewSchema.nullable(),true,[["shareId","shareId"]]),"share.list":post("list",ShareListSchema,SharePageSchema,true,[["artifactId","items.*.artifactId"]]),"share.revoke":post("revoke",ShareRevokeSchema,ShareViewSchema,false,[["shareId","shareId"]]),"share.receipt":post("receipt",ShareCreateSchema,ShareViewSchema.nullable(),true,[...["shareId","projectId","artifactId","representationId"].map(k=>[k,k])])};import{z as z189}from"zod";function inputIssues(error,schema){const fields=new Set;const collect=node=>{if(node instanceof z189.ZodObject)Object.keys(node.shape).forEach(key10=>fields.add(key10));else if(node instanceof z189.ZodUnion)node.options.forEach(branch2=>collect(branch2))};collect(schema);const result=new Map;for(const issue of error.issues){const first=issue.path[0];const field=typeof first==="string"&&first.length<=120&&fields.has(first)?first:"$";const safe={field,code:issue.code};result.set(`${field}:${safe.code}`,safe);if(result.size>=8)break}return[...result.values()]}import{z as z190}from"zod";var success2=z190.strictObject({semanticStatus:z190.literal("SUCCESS")});var deviceManagementOperations={"device.status":operation(DeviceStatusInputSchema,DeviceStatusSchema,({tenantId,deviceId})=>({method:"GET",path:path("local-execution","devices",deviceId,"status"),tenantId}),[["tenantId","tenantId"],["deviceId","deviceId"]]),"device.enrollment.issue":operation(DeviceEnrollmentIssueSchema,DeviceEnrollmentObservationSchema,body=>({method:"POST",path:path("local-execution","devices","enrollments"),tenantId:body.tenantId,body}),[["tenantId","tenantId"],["requestId","requestId"]]),"device.enrollment.lookup":operation(DeviceEnrollmentLookupSchema,DeviceEnrollmentObservationSchema,({tenantId,requestId:requestId2})=>({method:"GET",path:path("local-execution","devices","enrollments",requestId2),tenantId}),[["tenantId","tenantId"],["requestId","requestId"]]),"workspace.devices.list":operation(WorkspaceDeviceListInputSchema,WorkspaceDeviceListSchema,({tenantId,deviceId,after,limit})=>({method:"GET",tenantId,path:path("local-execution","devices"),query:{deviceId,after,limit}}),[["deviceId","items.*.deviceId"]],{readOnly:true}),"device.enroll":operation(EnrollLocalDeviceSchema,LocalDeviceViewSchema,i=>({method:"POST",tenantId:i.tenantId,path:path("local-execution","devices","enroll"),body:i}),[["tenantId","tenantId"],["publicKey","publicKey"],["label","label"],["platform","platform"],["runtimeVersion","runtimeVersion"]]),"device.revoke":operation(RevokeLocalDeviceSchema,success2,i=>({method:"POST",tenantId:i.tenantId,path:path("local-execution","devices","revoke"),body:i})),"device.management-receipt":operation(ScopedLocalManagementReceiptSchema,LocalManagementReceiptSchema,i=>({method:"POST",tenantId:i.tenantId,path:path("local-execution","management-receipt"),body:i.command}),[],{readOnly:true})};import{createHash as createHash6}from"node:crypto";var identityFailure=()=>new NativeStudioSdkError("MEDIA_IDENTITY_MISMATCH","INTERNAL_OPERATIONAL_FAILURE","UNKNOWN");function checkTicket({endpoint,method,object},expected){const url=new URL(endpoint);if(method!=="PUT"||object.role!=="SOURCE"||object.tenantId!==expected.tenantId||object.projectId!==expected.projectId||object.byteSize!==expected.byteSize||object.checksumSha256!==expected.checksumSha256||url.pathname!==mediaObjectTransferPath||url.username||url.password||url.search||url.hash||url.protocol!=="https:"&&!(url.protocol==="http:"&&url.hostname==="127.0.0.1"))throw identityFailure();return url}async function upload(ticket,url,bytes,options){const timeout=AbortSignal.timeout(12e4);const signal=options.signal?AbortSignal.any([options.signal,timeout]):timeout;try{const result=await fetch(url,{method:"PUT",redirect:"error",headers:{authorization:"Bearer "+ticket.credential},body:new Uint8Array(bytes),signal});await result.body?.cancel();if(result.status===204)return}catch{}throw new NativeStudioSdkError("OBJECT_UPLOAD_UNCONFIRMED","BLOCKED","UNKNOWN")}var NativeStudioDirectSources=class{constructor(tenantId,transport){this.tenantId=tenantId;this.transport=transport}tenantId;transport;async importProjectSource(intent2,input,options={}){if(!(input instanceof Uint8Array)||input.length<1||input.length>8*1024*1024)sdkInputError();const bytes=Buffer.from(input);const result=DirectProjectSourceCommandSchema.safeParse({...intent2,metadata:{...intent2.metadata,tenantId:this.tenantId},byteSize:bytes.length,checksumSha256:createHash6("sha256").update(bytes).digest("hex")});if(!result.success)sdkInputError();const{projectId,...body}=result.data;const scope8={tenantId:this.tenantId,projectId};const endpoint=action=>path("projects",projectId,"source-artifacts","direct",action);const validate=receipt2=>{if(receipt2.state==="ACCEPTED"){const{artifact:artifact2,primaryRepresentation}=receipt2.registration;if(artifact2.tenantId!==scope8.tenantId||artifact2.projectId!==projectId||artifact2.productionId!==null||artifact2.lifecycle!=="READY"||primaryRepresentation.artifactId!==artifact2.id||primaryRepresentation.tenantId!==scope8.tenantId||primaryRepresentation.checksumSha256!==body.checksumSha256||primaryRepresentation.byteSize!==String(body.byteSize))throw identityFailure()}else if(receipt2.tenantId!==scope8.tenantId||receipt2.projectId!==projectId)throw identityFailure();return receipt2};const stage=await this.transport.json({method:"POST",tenantId:scope8.tenantId,path:endpoint("stage"),body},DirectProjectSourceStageSchema,options);if(stage.state!=="UPLOAD")return validate(stage);if(stage.tenantId!==scope8.tenantId||stage.projectId!==projectId)throw identityFailure();const url=checkTicket(stage.ticket,{...scope8,...body});if(!stage.uploaded)await upload(stage.ticket,url,bytes,options);const receipt=await this.transport.json({method:"POST",tenantId:scope8.tenantId,path:endpoint("submit"),body:{tenantId:scope8.tenantId,intakeId:stage.intakeId}},DirectProjectSourceSubmitSchema,options);if(receipt.state==="SUBMITTED"&&receipt.intakeId!==stage.intakeId)throw identityFailure();return validate(receipt)}async importOriginal(raw,input,options={}){const parsed=DirectOriginalCommandSchema.safeParse(raw);if(!parsed.success)sdkInputError();const command4=parsed.data;const{tenantId,projectId,productionId,shotId,source:source6}=command4.input;if(tenantId!==this.tenantId||!(input instanceof Uint8Array)||input.length!==source6.byteSize)sdkInputError();const bytes=Buffer.from(input);if(createHash6("sha256").update(bytes).digest("hex")!==source6.checksumSha256)sdkInputError();const scope8={tenantId,projectId,productionId};const endpoint=action=>path("productions",productionId,"imported-visuals","originals","direct",action);const validate=receipt2=>{const value2=receipt2.state==="ACCEPTED"?receipt2.original:receipt2;if(value2.tenantId!==tenantId||value2.projectId!==projectId||value2.productionId!==productionId)throw identityFailure();if(receipt2.state==="ACCEPTED"){const{original}=receipt2;if(original.shotId!==shotId||original.metadata.checksumSha256!==source6.checksumSha256||original.metadata.byteSize!==source6.byteSize||command4.operation==="REVISE"&&(original.sourceId!==command4.input.sourceId||original.version!==command4.input.expectedVersion+1))throw identityFailure()}return receipt2};const stage=await this.transport.json({method:"POST",tenantId,path:endpoint("stage"),body:command4},DirectOriginalStageSchema,options);if(stage.state!=="UPLOAD")return validate(stage);if(stage.tenantId!==tenantId||stage.projectId!==projectId||stage.productionId!==productionId)throw identityFailure();const url=checkTicket(stage.ticket,{...scope8,...source6});if(!stage.uploaded)await upload(stage.ticket,url,bytes,options);const receipt=await this.transport.json({method:"POST",tenantId,path:endpoint("submit"),body:{...scope8,intakeId:stage.intakeId}},DirectOriginalSubmitSchema,options);if(receipt.state==="SUBMITTED"&&receipt.intakeId!==stage.intakeId)throw identityFailure();return validate(receipt)}};var NativeStudioNavigationFacade=class{constructor(caller){this.caller=caller}caller;find(input,options){return this.caller.call("studio.start",input,options)}overview(input,options){return this.caller.call("studio.navigate",input,options)}next(input,options){return this.overview(input,options)}resume(input,options){return this.caller.call("operation.get",input,options)}groups(input={},options){return this.caller.call("studio.capability.groups",input,options)}search(input,options){return this.caller.call("studio.capability.search",input,options)}describe(input,options){return this.caller.call("studio.capability.describe",input,options)}query(input,options){return this.caller.call("studio.capability.query",input,options)}invoke(input,options){return this.caller.call("studio.capability.invoke",input,options)}};import{createHash as createHash12}from"node:crypto";import{createHash as createHash7}from"node:crypto";function assertExportBytes(value2,captionFormat){const v=value2;const bytes=v.contentBase64!==void 0?Buffer.from(v.contentBase64,"base64"):Buffer.from(v.text,"utf8");if(v.contentBase64!==void 0&&(bytes.toString("base64")!==v.contentBase64||bytes.length!==v.byteSize||bytes.toString("ascii",0,4)!=="RIFF"||bytes.toString("ascii",8,12)!=="WAVE")||bytes.length>(v.contentBase64!==void 0?12582912:131072)||captionFormat!==void 0&&v.contentType!==(captionFormat==="JSON"?"application/json":"application/x-subrip")||createHash7("sha256").update(bytes).digest("hex")!==v.checksumSha256)throw new NativeStudioSdkError("MEDIA_IDENTITY_MISMATCH","INTERNAL_OPERATIONAL_FAILURE","NO_WRITE")}import{createHash as createHash8}from"node:crypto";function assertPreviewBytes(value2){const v=value2;if(v.semanticStatus!=="SUCCESS")return;const data=v.contentBase64;if(typeof data!=="string"||data.length>4*Math.ceil(8*1024*1024/3))throw new NativeStudioSdkError("RESPONSE_INVALID","INTERNAL_OPERATIONAL_FAILURE","NO_WRITE");const bytes=Buffer.from(data,"base64");if(bytes.length!==v.byteSize||bytes.toString("base64")!==data||!bytes.subarray(0,8).equals(Buffer.from([137,80,78,71,13,10,26,10]))||createHash8("sha256").update(bytes).digest("hex")!==v.checksumSha256)throw new NativeStudioSdkError("MEDIA_IDENTITY_MISMATCH","INTERNAL_OPERATIONAL_FAILURE","NO_WRITE")}import{createHash as createHash9}from"node:crypto";function assertOriginalVideoBytes(value2){const v=value2;const bytes=Buffer.from(v.dataBase64,"base64");if(bytes.toString("base64")!==v.dataBase64||bytes.length!==v.source.byteSize||bytes.subarray(4,8).toString("ascii")!=="ftyp"||createHash9("sha256").update(bytes).digest("hex")!==v.source.checksumSha256)throw new NativeStudioSdkError("RESPONSE_INVALID","INTERNAL_OPERATIONAL_FAILURE","NO_WRITE")}import{z as z191}from"zod";var production2=z191.strictObject({tenantId:TenantIdSchema,productionId:ProductionIdSchema});var sourceUpload=UploadSourceInputRequestSchema.extend({projectId:ProjectIdSchema,idempotencyKey:z191.string().trim().min(1).max(200)});var projectProduction=(p,prod,suffix)=>path("projects",p,"productions",prod,suffix);var coreOperations={"workspace.status":operation(WorkspaceScopeSchema,WorkspaceStatusSchema,({tenantId})=>({method:"GET",path:path("workspace","status"),tenantId}),[["tenantId","tenantId"]]),"workspace.get":operation(WorkspaceScopeSchema,WorkspaceViewSchema,i=>({method:"GET",path:path("workspace"),tenantId:i.tenantId})),"workspace.caller":operation(WorkspaceScopeSchema,WorkspaceCallerSchema,i=>({method:"GET",path:path("workspace","caller"),tenantId:i.tenantId}),[["tenantId","tenantId"]]),"workspace.query":operation(WorkspaceScopeSchema,WorkspacePageSchema,i=>({method:"GET",path:path("workspaces"),tenantId:i.tenantId})),"visual-sequence.start-registration":operation(RegisterVisualSequenceSchema,VisualSequenceRegistrationAdmissionSchema,i=>{const{tenantId,projectId,...body}=i;return{method:"POST",path:path("projects",projectId,"visual-sequences","jobs"),tenantId,body}}),"visual-sequence.register":operation(LegacyVisualSequenceRegistrationSchema,VisualSequenceViewSchema,i=>{const{tenantId,projectId,...body}=i;return{method:"POST",path:path("projects",projectId,"visual-sequences"),tenantId,body}},[["projectId","sequence.projectId"]]),"visual-sequence.get":operation(VisualSequenceGetSchema,VisualSequenceViewSchema,i=>({method:"GET",path:path("projects",i.projectId,"visual-sequences",i.artifactId),tenantId:i.tenantId}),[["artifactId","sequence.artifactId"]]),"visual-sequence.query":operation(VisualSequenceQuerySchema,VisualSequencePageSchema,i=>({method:"GET",path:path("projects",i.projectId,"visual-sequences"),tenantId:i.tenantId,query:pageQuery(i)})),"project.create":operation(CreateProjectRequestSchema,CreatedProjectResultSchema,input=>({method:"POST",path:path("projects"),tenantId:input.tenantId,body:input})),"production.create":operation(CreateProductionRequestSchema,CreatedProductionResultSchema,input=>({method:"POST",path:path("projects",input.projectId,"productions"),tenantId:input.tenantId,body:{idempotencyKey:input.idempotencyKey}}),[["projectId","project.id"]]),"production.terminate":operation(TerminateProductionSchema,ProductionTerminationReceiptSchema,input=>({method:"POST",path:path("projects",input.projectId,"productions",input.productionId,"terminate"),tenantId:input.tenantId,body:{outcome:input.outcome,expectedProductionRevision:input.expectedProductionRevision,reason:input.reason,idempotencyKey:input.idempotencyKey}}),[["productionId","productionId"],["projectId","projectId"]]),"project.query":operation(ProjectLibraryQuerySchema,ProjectLibraryPageSchema,input=>({method:"GET",path:path("projects"),tenantId:input.tenantId,query:pageQuery(input)})),"project.get":operation(ProjectLibraryScopeSchema,ProjectWorkspaceSchema,input=>({method:"GET",path:path("projects",input.projectId),tenantId:input.tenantId}),[["projectId","project.id"]]),"devices.list":operation(ProjectDeviceListInputSchema,ProjectDeviceListSchema,({tenantId,projectId,kind,deviceId})=>({method:"GET",path:path("local-execution","projects",projectId,"devices"),tenantId,query:{kind,deviceId}}),[["projectId","projectId"],["kind","kind"],["deviceId","items.*.deviceId"]],{readOnly:true}),"source.query":operation(SourceLibraryQuerySchema,SourceLibraryPageSchema,input=>({method:"GET",path:input.projectId?path("projects",input.projectId,"source-artifacts"):path("source-artifacts"),tenantId:input.tenantId,query:pageQuery(input)})),"source.ingest":operation(sourceUpload,ReadyArtifactRegistrationSchema,input=>{const{projectId,...body}=input;return{method:"POST",path:path("projects",projectId,"source-artifacts"),tenantId:input.tenantId,body}}),"source.text":operation(SourceReadSchema,SourceTextWindowSchema,input=>({method:"GET",path:path("projects",input.projectId,"source-artifacts",input.artifactId,"text"),tenantId:input.tenantId,query:{offsetBytes:input.offsetBytes,maxTextBytes:input.maxTextBytes}}),[["artifactId","artifactId"]]),"production.query":operation(ProductionQueryInputSchema.strict(),ProductionQueryPageSchema,input=>({method:"GET",path:path("productions"),tenantId:input.tenantId,query:{...pageQuery(input),projectId:input.projectId,search:input.search,attention:input.attention}})),"production.snapshot":operation(production2,ProductionSnapshotSchema,input=>({method:"GET",path:path("productions",input.productionId,"snapshot"),tenantId:input.tenantId})),"brief.accept":operation(ScopedAcceptBriefSchema,AcceptBriefResultSchema,input=>{const{projectId,productionId,...body}=input;return{method:"POST",path:projectProduction(projectId,productionId,"brief-versions"),tenantId:input.tenantId,body}}),"story.accept":operation(ScopedAcceptStorySchema,AcceptStoryResultSchema,input=>{const{projectId,productionId,...body}=input;return{method:"POST",path:projectProduction(projectId,productionId,"story-versions"),tenantId:input.tenantId,body}}),"scene-shot-plan.accept":operation(ScopedAcceptSceneShotPlanSchema,AcceptSceneShotPlanResultSchema,input=>{const{projectId,productionId,...body}=input;return{method:"POST",path:projectProduction(projectId,productionId,"scene-shot-plan-versions"),tenantId:input.tenantId,body}}),"story.query":operation(StoryQueryInputSchema.strict(),StoryQueryPageSchema,input=>({method:"GET",path:path("productions",input.productionId,"stories"),tenantId:input.tenantId,query:pageQuery(input)})),"story.active":operation(production2,StoryVersionSchema,input=>({method:"GET",path:path("productions",input.productionId,"stories","active"),tenantId:input.tenantId})),"scene-shot-plan.query":operation(SceneShotPlanQueryInputSchema.strict(),SceneShotPlanQueryPageSchema,input=>({method:"GET",path:path("productions",input.productionId,"scene-shot-plans"),tenantId:input.tenantId,query:pageQuery(input)})),"scene-shot-plan.active":operation(production2,SceneShotPlanVersionSchema,input=>({method:"GET",path:path("productions",input.productionId,"scene-shot-plans","active"),tenantId:input.tenantId})),"operation.query":operation(OperationQueryInputSchema.strict(),OperationQueryPageSchema,input=>({method:"GET",path:path("productions",input.productionId,"operations"),tenantId:input.tenantId,query:pageQuery(input)})),"operation.get":operation(production2.extend({operationId:OperationIdSchema}),OperationSummarySchema,input=>({method:"GET",path:path("productions",input.productionId,"operations",input.operationId),tenantId:input.tenantId}),[["operationId","id"]])};var reference2=["tenantId","projectId","deviceId","fileId","versionId","checksumSha256","byteSize","contentType"];var deviceLibraryOperations={"device-library.query":operation(LocalLibraryProjectionQuerySchema,LocalLibraryProjectionPageSchema,({tenantId,projectId,deviceId,after,limit,search,mediaCategory})=>({method:"GET",tenantId,path:path("local-execution","projects",projectId,"devices",deviceId,"library"),query:{after:after??void 0,limit,search,mediaCategory}}),[["tenantId","items.*.reference.tenantId"],["projectId","items.*.reference.projectId"],["deviceId","items.*.reference.deviceId"]],{readOnly:true}),"device-library.admit":operation(LocalLibraryCommandSchema,LocalLibraryAdmissionSchema,({tenantId,productionId,...body})=>({method:"POST",tenantId,path:path("productions",productionId,"device-library","commands"),body:{tenantId,productionId,...body}}),[["tenantId","tenantId"],["projectId","projectId"],["productionId","productionId"],["requestId","requestId"],["accessRevision","accessRevision"],...reference2.map(field=>[`reference.${field}`,`reference.${field}`])]),"device-library.receipt":operation(LocalLibraryCommandQuerySchema,LocalLibraryCommandStatusSchema.nullable(),({tenantId,projectId,productionId,requestId:requestId2})=>({method:"GET",tenantId,path:path("productions",productionId,"device-library","commands",requestId2),query:{projectId}}),[["tenantId","admission.tenantId"],["projectId","admission.projectId"],["productionId","admission.productionId"],["requestId","admission.requestId"],["tenantId","admission.reference.tenantId"],["projectId","admission.reference.projectId"]],{readOnly:true})};var navigationOperations={"studio.media.readiness":mcpOperation(RenderReadinessInputSchema,RenderReadinessSchema,true,[["tenantId","tenantId"],["projectId","projectId"],["productionId","productionId"],["kind","kind"],["deviceId","deviceId"]]),"studio.capability.query":mcpOperation(CapabilityInvocationInputSchema,CapabilityInvocationOutputSchema,true,[["tool","tool"]]),"studio.capability.invoke":mcpOperation(CapabilityInvocationInputSchema,CapabilityInvocationOutputSchema,false,[["tool","tool"]]),"studio.capability.groups":mcpOperation(CapabilityGroupsInputSchema,CapabilityGroupsSchema,true),"studio.start":mcpOperation(StudioStartInputSchema,StudioStartSchema,true),"studio.capability.search":mcpOperation(CapabilitySearchInputSchema,CapabilitySearchSchema,true),"studio.capability.describe":mcpOperation(CapabilityDescribeInputSchema,CapabilityDescribeSchema,true),"studio.navigate":mcpOperation(StudioNavigateInputSchema,StudioNavigationSchema,true,[["productionId","productionId"],["projectId","projectId"]])};import{createHash as createHash10}from"node:crypto";var verifiedHostContract=AgentHostContractSchema.refine(v=>v.digest==="sha256:"+createHash10("sha256").update(canonicalHostContractJson(v.document)).digest("hex"));function write(input,suffix){return operation(input,AgentHostBindingSchema,value2=>({method:"POST",tenantId:value2.tenantId,path:path("projects",value2.projectId,"agent-host",...suffix),body:Object.fromEntries(Object.entries(value2).filter(([key10])=>!["tenantId","projectId"].includes(key10)))}),[["bindingId","bindingId"]])}var agentHostOperations={"agent-host.contract":operation(AgentHostContractInputSchema,verifiedHostContract,value2=>({method:"GET",tenantId:value2.tenantId,path:path("projects",value2.projectId,"agent-host","contract"),query:{expectedDigest:value2.expectedDigest}}),[["expectedDigest","digest"]],{readOnly:true}),"agent-host.get":operation(AgentHostScopeSchema,AgentHostCurrentSchema,value2=>({method:"GET",tenantId:value2.tenantId,path:path("projects",value2.projectId,"agent-host")})),"agent-host.readiness":operation(AgentHostScopeSchema,AgentHostReadinessSchema,value2=>({method:"GET",tenantId:value2.tenantId,path:path("projects",value2.projectId,"agent-host","readiness")})),"agent-host.history":operation(AgentHostHistoryQuerySchema,AgentHostHistoryPageSchema,value2=>({method:"GET",tenantId:value2.tenantId,path:path("projects",value2.projectId,"agent-host","history"),query:{limit:value2.limit,beforeVersion:value2.beforeVersion}})),"agent-host.configure":write(ConfigureAgentHostSchema,[]),"agent-host.selection.update":write(UpdateAgentHostSelectionSchema,["selection"]),"agent-host.revoke":write(RevokeAgentHostSchema,["revoke"])};var route2=(scope8,...suffix)=>path("projects",scope8.projectId,"productions",scope8.productionId,"agent-host-executions",...suffix);var mutation2=action=>operation(AgentHostExecutionGetSchema,AgentHostExecutionViewSchema,value2=>({method:"POST",tenantId:value2.tenantId,path:route2(value2,value2.executionId,action),body:{}}),[["executionId","executionId"]]);var agentHostExecutionOperations={"agent-host-execution.legacy-release.get":operation(AgentHostExecutionGetSchema,LegacyHostExecutionReleaseSchema,value2=>({method:"GET",tenantId:value2.tenantId,path:route2(value2,value2.executionId,"legacy-release")}),[["executionId","executionId"]]),"agent-host-execution.legacy-release":operation(ReleaseLegacyHostExecutionSchema,LegacyHostExecutionReleaseSchema,value2=>({method:"POST",tenantId:value2.tenantId,path:route2(value2,value2.executionId,"legacy-release"),body:Object.fromEntries(Object.entries(value2).filter(([key10])=>!["tenantId","projectId","productionId","executionId"].includes(key10)))}),[["executionId","executionId"],["requestId","requestId"],["hostRequestId","hostRequestId"],["expectedRevision","expectedRevision"],["snapshotFingerprint","snapshotFingerprint"],["evidenceRef","evidenceRef"],["evidenceSha256","evidenceSha256"]]),"agent-host-execution.start":operation(StartAgentHostExecutionSchema,AgentHostExecutionViewSchema,value2=>({method:"POST",tenantId:value2.tenantId,path:route2(value2),body:Object.fromEntries(Object.entries(value2).filter(([key10])=>!["tenantId","projectId","productionId"].includes(key10)))}),[["requestId","requestId"],["bindingId","snapshot.binding.bindingId"],["studioInputArtifactId","snapshot.input.intake.artifactId"],["expectedProductionRevision","snapshot.input.productionRevision"],["expectedBindingRevision","snapshot.binding.revision"],["expectedConfigurationVersion","snapshot.binding.configurationVersion"]]),"agent-host-execution.get":operation(AgentHostExecutionGetSchema,AgentHostExecutionViewSchema,value2=>({method:"GET",tenantId:value2.tenantId,path:route2(value2,value2.executionId)}),[["executionId","executionId"]]),"agent-host-execution.query":operation(AgentHostExecutionQuerySchema,AgentHostExecutionPageSchema,value2=>({method:"GET",tenantId:value2.tenantId,path:route2(value2),query:{limit:value2.limit,beforeId:value2.beforeId}})),"agent-host-execution.events":operation(AgentHostExecutionEventQuerySchema,AgentHostExecutionEventPageSchema,value2=>({method:"GET",tenantId:value2.tenantId,path:route2(value2,value2.executionId,"events"),query:{limit:value2.limit,beforeRevision:value2.beforeRevision}}),[["executionId","items.*.executionId"]]),"agent-host-execution.dispatch":mutation2("dispatch"),"agent-host-execution.reconcile":mutation2("reconcile"),"agent-host-execution.cancel":mutation2("cancel")};var route3=(v,...suffix)=>path("projects",v.projectId,"native-tool-grants",...suffix);var nativeToolAuthorityOperations={"native-tool-grant.configure":operation(ConfigureNativeToolGrantSchema,NativeToolGrantViewSchema,v=>({method:"POST",tenantId:v.tenantId,path:route3(v),body:Object.fromEntries(Object.entries(v).filter(([k])=>!["tenantId","projectId"].includes(k)))}),[["bindingId","bindingId"],["expectedBindingRevision","bindingRevision"],["expectedConfigurationVersion","configurationVersion"],["runtimeKey","runtimeKey"],["installationId","installationId"],["installationRevisionId","installationRevisionId"],["publicKey.x","publicKey.x"],["publicKey.y","publicKey.y"]]),"native-tool-grant.get":operation(NativeToolGrantGetSchema,NativeToolGrantViewSchema,v=>({method:"GET",tenantId:v.tenantId,path:route3(v,v.grantId)}),[["grantId","grantId"]]),"native-tool-grant.revoke":operation(RevokeNativeToolGrantSchema,NativeToolGrantViewSchema,v=>({method:"POST",tenantId:v.tenantId,path:route3(v,v.grantId,"revoke"),body:{requestId:v.requestId,expectedRevision:v.expectedRevision}}),[["grantId","grantId"]])};function productionRead(input,output,suffix,query=()=>({}),identity6=[]){return operation(input,output,value2=>({method:"GET",tenantId:value2.tenantId,path:path("productions",value2.productionId,...suffix(value2)),query:query(value2)}),identity6)}function productionWrite(input,output,suffix,options={}){return operation(input,output,value2=>({method:"POST",tenantId:value2.tenantId,path:path("productions",value2.productionId,...suffix(value2)),body:Object.fromEntries(Object.entries(value2).filter(([key10])=>key10!=="productionId"&&(options.tenantInBody||key10!=="tenantId")&&!options.pathFields?.includes(key10)))}),options.identity,options.readOnly===void 0?{}:{readOnly:options.readOnly})}var compositionOperations={"composition.render.query":productionRead(CompositionRenderQuerySchema,CompositionRenderPageSchema,()=>["compositions","renders"],i=>({limit:i.limit,next:i.next,shotId:i.shotId,role:i.role}),[["shotId","items.*.render.sourceIdentity.shotId"],["role","items.*.render.sourceIdentity.role"]]),"composition.capabilities":productionRead(CompositionScopeSchema,CompositionCapabilitiesSchema,()=>["compositions","capabilities"]),"composition.brief":productionRead(CompositionBriefQuerySchema,CompositionAuthoringBriefSchema,()=>["compositions","brief"],i=>({...i.shotId?{shotId:i.shotId}:{}})),"composition.put-input":productionWrite(PutCompositionInputSchema,CompositionInputReceiptSchema,()=>["compositions","inputs"]),"composition.making.validate":productionWrite(ValidateCompositionMakingSchema,CompositionMakingValidationSchema,()=>["compositions","making","validate"],{readOnly:true,identity:[["projectId","projectId"],["expectedProductionRevision","authoring.productionRevision"],["basis.briefVersionId","authoring.basis.briefVersionId"],["basis.storyVersionId","authoring.basis.storyVersionId"],["basis.planVersionId","authoring.basis.planVersionId"],["basis.shotId","authoring.basis.shotId"],["proposal.makingIntent","proposal.makingIntent"]]}),"composition.validate":productionWrite(ValidateCompositionSchema,CompositionValidationReceiptSchema,()=>["compositions","validate"],{readOnly:true}),"composition.create":productionWrite(CreateCompositionSchema,CompositionReceiptSchema,()=>["compositions"]),"composition.revise":productionWrite(ReviseCompositionSchema,CompositionReceiptSchema,()=>["compositions","revise"],{identity:[["compositionId","version.compositionId"]]}),"composition.get":productionRead(CompositionGetSchema,CompositionViewSchema,i=>["compositions",i.compositionId],i=>({versionId:i.versionId}),[["compositionId","version.compositionId"],["versionId","version.id"]]),"composition.history":productionRead(CompositionHistorySchema,CompositionPageSchema,i=>["compositions",i.compositionId,"versions"],i=>({limit:i.limit,beforeVersion:i.beforeVersion}),[["compositionId","items.*.version.compositionId"]]),"composition.render":productionWrite(CompositionRenderStartSchema,CompositionRenderReceiptSchema,()=>["compositions","renders"],{identity:[["versionId","compositionVersionId"]]}),"composition.render.get":productionRead(CompositionRenderGetSchema,CompositionRenderViewSchema,i=>["compositions","renders",i.renderId],void 0,[["renderId","receipt.renderId"]]),"composition.render.cancel":productionWrite(CompositionRenderGetSchema,CompositionRenderCancellationSchema,i=>["compositions","renders",i.renderId,"cancel"],{pathFields:["renderId"]}),"composition.sample":productionWrite(CompositionSampleStartSchema,CompositionSampleReceiptSchema,()=>["compositions","samples"],{identity:[["renderId","renderId"]]}),"composition.observe":productionRead(CompositionObserveGetSchema,CompositionObservationViewSchema,i=>["compositions","renders",i.renderId,"observations",i.evidenceId],void 0,[["renderId","renderId"],["evidenceId","evidence.evidenceId"]])};var cancellation=InterfaceCancellationReceiptSchema;var assemblyOperations={"timeline.basis":productionRead(TimelineScopeSchema,TimelineBasisSchema,()=>["timeline","basis"]),"timeline.build":productionWrite(BuildTimelineSchema,TimelineBuildReceiptSchema,()=>["timeline"]),"timeline.current":productionRead(TimelineScopeSchema,TimelineViewSchema,()=>["timeline","current"]),"timeline.get":productionRead(TimelineGetSchema,TimelineViewSchema,i=>["timeline","versions",i.versionId],void 0,[["versionId","version.id"]]),"timeline.query":productionRead(TimelineQuerySchema,TimelinePageSchema,()=>["timeline","versions"],pageQuery),"rough-cut.admission-receipt":productionWrite(RoughCutStartSchema,RoughCutAdmissionSchema,()=>["rough-cuts","admission-receipt"],{tenantInBody:true,readOnly:true,identity:[["timelineVersionId","timelineVersionId"],["timelineFingerprint","timelineFingerprint"]]}),"rough-cut.start":productionWrite(RoughCutStartSchema,RoughCutAdmissionSchema,()=>["rough-cuts"],{tenantInBody:true,identity:[["timelineVersionId","timelineVersionId"],["timelineFingerprint","timelineFingerprint"]]}),"rough-cut.get":productionRead(RoughCutGetSchema,RoughCutViewSchema,i=>["rough-cuts",i.renderId],void 0,[["renderId","renderId"]]),"rough-cut.query":productionRead(RoughCutQuerySchema,RoughCutPageSchema,()=>["rough-cuts"],pageQuery),"rough-cut.cancel":productionWrite(RoughCutGetSchema,cancellation,i=>["rough-cuts",i.renderId,"cancel"],{pathFields:["renderId"]}),"rough-cut.review.target":productionRead(RoughCutReviewScopeSchema,RoughCutReviewTargetSchema,i=>["rough-cut-review",i.renderId],void 0,[["renderId","renderId"]]),"rough-cut.review.record":productionWrite(RecordRoughCutReviewSchema,RoughCutReviewReceiptSchema,i=>["rough-cut-review",i.renderId],{pathFields:["renderId"],identity:[["renderId","review.renderId"]]}),"rough-cut.review.query":productionRead(RoughCutReviewQuerySchema,RoughCutReviewPageSchema,i=>["rough-cut-review",i.renderId,"history"],pageQuery,[["renderId","items.*.renderId"]]),"rough-cut.finding.query":productionRead(RoughCutFindingQuerySchema,RoughCutFindingPageSchema,()=>["rough-cut-review","findings"],i=>({...pageQuery(i),renderId:i.renderId}),[["renderId","items.*.renderId"]]),"final-ready.get":productionRead(TimelineScopeSchema,FinalReadyViewSchema,()=>["final-ready"]),"final-ready.decide":productionWrite(DecideFinalReadySchema,FinalReadyReceiptSchema,()=>["final-ready","decisions"],{identity:[["renderId","decision.renderId"],["reviewId","decision.reviewId"]]}),"final-ready.revoke":productionWrite(RevokeFinalReadySchema,FinalReadyReceiptSchema,()=>["final-ready","revoke"]),"final-ready.query":productionRead(FinalReadyQuerySchema,FinalReadyPageSchema,()=>["final-ready","decisions"],pageQuery),"final-render.eligibility":productionRead(TimelineScopeSchema,FinalRenderEligibilitySchema,()=>["final-renders","eligibility"]),"final-render.admission-receipt":productionWrite(FinalRenderStartSchema,FinalRenderAdmissionSchema,()=>["final-renders","admission-receipt"],{tenantInBody:true,readOnly:true,identity:[["timelineVersionId","timelineVersionId"],["timelineFingerprint","timelineFingerprint"]]}),"final-render.start":productionWrite(FinalRenderStartSchema,FinalRenderAdmissionSchema,()=>["final-renders"],{tenantInBody:true,identity:[["selectionId","selectionId"],["timelineVersionId","timelineVersionId"],["timelineFingerprint","timelineFingerprint"]]}),"final-render.get":productionRead(FinalRenderGetSchema,FinalRenderViewSchema,i=>["final-renders",i.renderId],void 0,[["renderId","renderId"]]),"final-render.query":productionRead(FinalRenderQuerySchema,FinalRenderPageSchema,()=>["final-renders"],pageQuery),"final-render.cancel":productionWrite(FinalRenderGetSchema,cancellation,i=>["final-renders",i.renderId,"cancel"],{pathFields:["renderId"]})};var Context=EditorContextInputSchema.extend({tenantId:TenantIdSchema}).refine(i=>i.tenantId.toLowerCase()===i.scope.tenantId.toLowerCase());var Validate=ValidateEditorProposalSchema.safeExtend({tenantId:TenantIdSchema}).refine(i=>i.tenantId.toLowerCase()===i.basis.scope.tenantId.toLowerCase());var editorOperations={"editor.context":operation(Context,EditorContextResultSchema,i=>({method:"POST",tenantId:i.scope.tenantId,path:path("projects",i.scope.projectId,"productions",i.scope.productionId,"editor-intelligence","context"),body:{scope:i.scope,timelineVersionId:i.timelineVersionId}}),[["scope.tenantId","basis.scope.tenantId"],["scope.projectId","basis.scope.projectId"],["scope.productionId","basis.scope.productionId"],["timelineVersionId","timeline.version.id"]],{readOnly:true}),"editor.validate":operation(Validate,EditorValidationResultSchema,i=>({method:"POST",tenantId:i.basis.scope.tenantId,path:path("projects",i.basis.scope.projectId,"productions",i.basis.scope.productionId,"editor-intelligence","proposals","validate"),body:{basis:i.basis,proposal:i.proposal}}),[["basis.scope.tenantId","basis.scope.tenantId"],["basis.scope.projectId","basis.scope.projectId"],["basis.scope.productionId","basis.scope.productionId"],["basis.timelineVersionId","basis.timelineVersionId"],["basis.contextFingerprint","basis.contextFingerprint"]],{readOnly:true})};var Context2=ReviewIntelligenceContextInputSchema.extend({tenantId:TenantIdSchema}).refine(i=>i.tenantId.toLowerCase()===i.scope.tenantId.toLowerCase());var Validate2=ValidateReviewIntelligenceSchema.safeExtend({tenantId:TenantIdSchema}).refine(i=>i.tenantId.toLowerCase()===i.basis.scope.tenantId.toLowerCase());var FinalContext=FinalOutputReviewContextInputSchema.extend({tenantId:TenantIdSchema}).refine(i=>i.tenantId.toLowerCase()===i.scope.tenantId.toLowerCase());var reviewerOperations={"reviewer.final-output-context":operation(FinalContext,FinalOutputReviewContextResultSchema,i=>({method:"POST",tenantId:i.tenantId,path:path("projects",i.scope.projectId,"productions",i.scope.productionId,"review-intelligence","final-output","context"),body:{scope:i.scope,renderId:i.renderId}}),[["scope","basis.scope"],["renderId","basis.renderId"],["renderId","deliveryTarget.renderId"]],{readOnly:true}),"reviewer.context":operation(Context2,ReviewIntelligenceContextResultSchema,i=>({method:"POST",tenantId:i.scope.tenantId,path:path("projects",i.scope.projectId,"productions",i.scope.productionId,"review-intelligence","context"),body:{scope:i.scope,target:i.target}}),[["scope.tenantId","basis.scope.tenantId"],["scope.projectId","basis.scope.projectId"],["scope.productionId","basis.scope.productionId"],["target.kind","basis.target.kind"],["target.renderId","basis.target.renderId"],["target.generationId","basis.target.generationId"],["scope.tenantId","reviewTarget.target.tenantId"],["scope.projectId","reviewTarget.target.projectId"],["scope.productionId","reviewTarget.target.productionId"],["target.kind","reviewTarget.kind"],["target.renderId","reviewTarget.target.renderId"],["target.generationId","reviewTarget.target.generationId"]],{readOnly:true}),"reviewer.validate":operation(Validate2,ReviewIntelligenceValidationResultSchema,i=>({method:"POST",tenantId:i.basis.scope.tenantId,path:path("projects",i.basis.scope.projectId,"productions",i.basis.scope.productionId,"review-intelligence","proposals","validate"),body:{basis:i.basis,proposal:i.proposal}}),[["basis.scope.tenantId","basis.scope.tenantId"],["basis.scope.projectId","basis.scope.projectId"],["basis.scope.productionId","basis.scope.productionId"],["basis.target.kind","basis.target.kind"],["basis.target.renderId","basis.target.renderId"],["basis.target.generationId","basis.target.generationId"],["basis.contextFingerprint","basis.contextFingerprint"],["basis.scope.tenantId","recordDraft.input.tenantId"],["basis.scope.productionId","recordDraft.input.productionId"],["basis.target.kind","recordDraft.kind"],["basis.target.renderId","recordDraft.input.renderId"],["basis.target.generationId","recordDraft.input.generationId"]],{readOnly:true})};var Context3=RepairStrategyContextInputSchema.extend({tenantId:TenantIdSchema}).refine(i=>i.tenantId.toLowerCase()===i.scope.tenantId.toLowerCase());var Validate3=ValidateRepairStrategySchema.safeExtend({tenantId:TenantIdSchema}).refine(i=>i.tenantId.toLowerCase()===i.basis.scope.tenantId.toLowerCase());var Review1Validate=ValidateReview1RepairStrategySchema.safeExtend({tenantId:TenantIdSchema}).refine(i=>i.tenantId.toLowerCase()===i.basis.input.tenantId.toLowerCase());var repairStrategyOperations={"repair-strategy.review1.context":operation(Review1RepairSourceQuerySchema,Review1RepairStrategyContextSchema,i=>({method:"POST",tenantId:i.tenantId,path:path("projects",i.projectId,"productions",i.productionId,"repair-strategy","review1","context"),body:i}),[["tenantId","basis.input.tenantId"],["projectId","basis.input.projectId"],["productionId","basis.input.productionId"],["generationId","basis.input.generationId"],["reviewId","basis.input.reviewId"],["requirementKey","basis.input.requirementKey"]],{readOnly:true}),"repair-strategy.review1.validate":operation(Review1Validate,Review1RepairStrategyValidationSchema,i=>({method:"POST",tenantId:i.tenantId,path:path("projects",i.basis.input.projectId,"productions",i.basis.input.productionId,"repair-strategy","review1","proposals","validate"),body:{basis:i.basis,proposal:i.proposal,...i.budget?{budget:i.budget}:{}}}),[["basis","basis"],["proposal.selectedAlternativeId","selectedAlternativeId"]],{readOnly:true}),"repair-strategy.context":operation(Context3,RepairStrategyContextResultSchema,i=>({method:"POST",tenantId:i.scope.tenantId,path:path("projects",i.scope.projectId,"productions",i.scope.productionId,"repair-strategy","context"),body:{scope:i.scope,findingId:i.findingId}}),[["scope.tenantId","basis.scope.tenantId"],["scope.projectId","basis.scope.projectId"],["scope.productionId","basis.scope.productionId"],["findingId","finding.id"]],{readOnly:true}),"repair-strategy.validate":operation(Validate3,RepairStrategyValidationResultSchema,i=>({method:"POST",tenantId:i.basis.scope.tenantId,path:path("projects",i.basis.scope.projectId,"productions",i.basis.scope.productionId,"repair-strategy","proposals","validate"),body:{basis:i.basis,proposal:i.proposal}}),[["basis.scope.tenantId","basis.scope.tenantId"],["basis.scope.projectId","basis.scope.projectId"],["basis.scope.productionId","basis.scope.productionId"],["basis.findingId","finding.id"],["basis.contextFingerprint","basis.contextFingerprint"],["proposal.selectedAlternativeId","selectedAlternativeId"]],{readOnly:true})};var ownedRequest=(action,i)=>{const{projectId,...body}=i;return{method:"POST",tenantId:i.tenantId,path:path("projects",projectId,"productions",i.productionId,"repairs",action),body}};var Author=AuthorRepairPlanSchema.safeExtend({tenantId:TenantIdSchema}).refine(i=>i.tenantId.toLowerCase()===i.strategy.basis.scope.tenantId.toLowerCase());var canonicalRepairOperations={"canonical-repair.author-review1":operation(AuthorReview1RepairSchema,RepairAuthorReceiptSchema,i=>({method:"POST",tenantId:i.tenantId,path:path("projects",i.projectId,"productions",i.productionId,"repairs","author-review1"),body:i}),[["reviewId","decision.sourceReviewId"],["generationId","decision.review1Source.generationId"],["mediaType","decision.review1Source.mediaType"],["requirementKey","decision.review1Source.requirement.key"]]),"canonical-repair.proof-review1":operation(RecordReview1RepairProofSchema.extend({projectId:ProjectIdSchema}),RepairProofReceiptSchema,i=>ownedRequest("proof-review1",i),[["attemptId","event.attemptId"],["generationId","event.generationId"],["reviewId","event.reviewId"]]),"canonical-repair.author":operation(Author,RepairAuthorReceiptSchema,i=>{const{tenantId,...body}=i;const s=i.strategy.basis.scope;return{method:"POST",tenantId,path:path("projects",s.projectId,"productions",s.productionId,"repairs","author"),body}},[["strategy.basis.scope.tenantId","decision.tenantId"],["strategy.basis.scope.projectId","decision.projectId"],["strategy.basis.scope.productionId","decision.productionId"],["strategy.basis.findingId","decision.basis.findingId"],["strategy.basis.contextFingerprint","decision.basis.contextFingerprint"],["strategy.proposal.selectedAlternativeId","decision.selectedAlternativeId"]]),"canonical-repair.get":operation(RepairPlanScopeSchema.extend({projectId:ProjectIdSchema}),RepairPlanViewSchema,i=>ownedRequest("get",i),[["planId","decision.id"]],{readOnly:true}),"canonical-repair.execute":operation(ExecuteRepairSchema.extend({projectId:ProjectIdSchema}),RepairProgressSchema,i=>ownedRequest("execute",i),[["planId","view.decision.id"]]),"canonical-repair.proof":operation(RecordRepairProofSchema.extend({projectId:ProjectIdSchema}),RepairProofReceiptSchema,i=>ownedRequest("proof",i),[["attemptId","event.attemptId"],["renderId","event.renderId"],["reviewId","event.reviewId"]])};var programmaticReviewOperations={"programmatic-review.target":productionRead(ProgrammaticVideoReviewScopeSchema,ProgrammaticVideoReviewTargetSchema,i=>["video-review","programmatic",i.renderId],void 0,[["renderId","renderId"]]),"programmatic-review.record":productionWrite(RecordProgrammaticVideoReviewSchema,ProgrammaticVideoReviewReceiptSchema,i=>["video-review","programmatic",i.renderId],{pathFields:["renderId"],identity:[["renderId","review.renderId"],["representationId","review.representationId"],["checksumSha256","review.checksumSha256"]]}),"programmatic-review.query":productionRead(ProgrammaticVideoReviewQuerySchema,ProgrammaticVideoReviewPageSchema,i=>["video-review","programmatic",i.renderId,"history"],pageQuery,[["renderId","items.*.renderId"]]),"programmatic-review.decide":productionWrite(DecideProgrammaticShotSchema,ShotDecisionReceiptSchema.extend({decision:ProgrammaticShotAcceptanceDecisionSchema}),i=>["video-review","programmatic",i.renderId,"decisions"],{pathFields:["renderId"],identity:[["renderId","decision.renderId"],["reviewId","decision.reviewId"],["action","decision.action"]]})};var Context4=SourceReviewContextInputSchema.safeExtend({tenantId:TenantIdSchema}).refine(i=>i.tenantId.toLowerCase()===i.scope.tenantId.toLowerCase());var compositionSourceOperations={"composition.source.inspect":productionWrite(CompositionSourceInspectSchema,CompositionSourceInspectionSchema,()=>["compositions","source","inspect"],{readOnly:true,identity:[["compositionId","composition.version.compositionId"],["versionId","composition.version.id"],["fingerprint","composition.version.fingerprint"],["file","window.file"],["startLine","selection.startLine"]]}),"reviewer.source-context":operation(Context4,SourceReviewContextSchema,i=>({method:"POST",tenantId:i.scope.tenantId,path:path("projects",i.scope.projectId,"productions",i.scope.productionId,"review-intelligence","source","context"),body:{scope:i.scope,source:i.source,...i.renderId?{renderId:i.renderId}:{}}}),[["scope.tenantId","basis.input.scope.tenantId"],["scope.projectId","source.composition.version.projectId"],["scope.productionId","source.composition.version.productionId"],["source.compositionId","source.composition.version.compositionId"],["source.versionId","source.composition.version.id"],["source.fingerprint","source.composition.version.fingerprint"],["source.file","source.window.file"],["source.startLine","source.selection.startLine"],["renderId","render.receipt.renderId"]],{readOnly:true})};var Compare=ProgrammaticCompareSchema.safeExtend({tenantId:TenantIdSchema}).refine(i=>i.tenantId.toLowerCase()===i.scope.tenantId.toLowerCase());var Context5=ProgrammaticRecommendationContextInputSchema.safeExtend({tenantId:TenantIdSchema}).refine(i=>i.tenantId.toLowerCase()===i.scope.tenantId.toLowerCase());var Validate4=ValidateProgrammaticRecommendationSchema.safeExtend({tenantId:TenantIdSchema}).refine(i=>i.tenantId.toLowerCase()===i.basis.input.scope.tenantId.toLowerCase());var programmaticExplorationOperations={"exploration.programmatic.compare":operation(Compare,ProgrammaticComparisonSchema,i=>({method:"POST",tenantId:i.scope.tenantId,path:path("projects",i.scope.projectId,"productions",i.scope.productionId,"visual-exploration","programmatic","compare"),body:{scope:i.scope,items:i.items}}),[["scope.tenantId","scope.tenantId"],["scope.projectId","scope.projectId"],["scope.productionId","scope.productionId"],["scope.shotId","scope.shotId"],["items","selection"]],{readOnly:true}),"exploration.programmatic.recommendation.context":operation(Context5,ProgrammaticRecommendationContextSchema,i=>({method:"POST",tenantId:i.scope.tenantId,path:path("projects",i.scope.projectId,"productions",i.scope.productionId,"exploration-recommendation","programmatic","context"),body:{scope:i.scope,items:i.items,criteria:i.criteria}}),[["scope.tenantId","basis.input.scope.tenantId"],["scope.projectId","basis.input.scope.projectId"],["scope.productionId","basis.input.scope.productionId"],["scope.shotId","basis.input.scope.shotId"],["items","basis.input.items"]],{readOnly:true}),"exploration.programmatic.recommendation.validate":operation(Validate4,ProgrammaticRecommendationValidationSchema,i=>({method:"POST",tenantId:i.basis.input.scope.tenantId,path:path("projects",i.basis.input.scope.projectId,"productions",i.basis.input.scope.productionId,"exploration-recommendation","programmatic","proposals","validate"),body:{basis:i.basis,proposal:i.proposal}}),[["basis.contextFingerprint","basis.contextFingerprint"],["basis.input.scope.tenantId","basis.input.scope.tenantId"],["basis.input.scope.projectId","basis.input.scope.projectId"],["basis.input.scope.productionId","basis.input.scope.productionId"],["basis.input.items","basis.input.items"],["proposal.decision.kind","decision.kind"],["proposal.decision.label","decision.label"]],{readOnly:true})};var targetIdentity=prefix=>Object.keys(DeliveryTargetSchema.shape).map(key10=>["target."+key10,prefix+"."+key10]);var deliveryOperations={"delivery.policy.configure":productionWrite(ConfigureDeliveryPolicySchema,DeliveryPolicyReceiptSchema,()=>["deliveries","policy"],{tenantInBody:true}),"delivery.policy.get":productionRead(TimelineScopeSchema,DeliveryPolicyVersionSchema,()=>["deliveries","policy"]),"delivery.snapshot":productionRead(TimelineScopeSchema,DeliverySnapshotSchema,()=>["deliveries","snapshot"]),"delivery.target":productionRead(RoughCutGetSchema,DeliveryTargetSchema,i=>["deliveries","targets",i.renderId],void 0,[["renderId","renderId"]]),"delivery.start":productionWrite(StartDeliveryValidationSchema,DeliveryAdmissionSchema,()=>["deliveries"],{tenantInBody:true,identity:targetIdentity("target")}),"delivery.get":productionRead(DeliveryValidationGetSchema,DeliveryValidationViewSchema,i=>["deliveries",i.validationId],void 0,[["validationId","admission.validationId"]]),"delivery.approve":productionWrite(DecideDeliveryApprovalSchema,DeliveryDecisionReceiptSchema,i=>["deliveries",i.validationId,"approval"],{tenantInBody:true,pathFields:["validationId"],identity:[...targetIdentity("approval.target"),["reviewId","approval.reviewId"],["policyFingerprint","approval.policyFingerprint"],["action","approval.action"]]}),"delivery.cancel":productionWrite(DeliveryValidationGetSchema,cancellation,i=>["deliveries",i.validationId,"cancel"],{pathFields:["validationId"]}),"delivery.manifest":productionRead(DeliveryManifestGetSchema,RegisteredDeliveryManifestSchema,i=>["deliveries","manifests",i.manifestId],void 0,[["manifestId","link.id"]])};var prepare=PrepareShotRequestSchema.extend({projectId:ProjectIdSchema,productionId:ProductionIdSchema,shotId:ShotIdSchema});var shotPreparationOperations={"shot-preparation.prepare":operation(prepare,PrepareShotResultSchema,i=>({method:"POST",tenantId:i.tenantId,path:path("projects",i.projectId,"productions",i.productionId,"shots",i.shotId,"preparations"),body:Object.fromEntries(Object.entries(i).filter(([k])=>!["projectId","productionId","shotId"].includes(k)))}),[["projectId","preparation.basis.projectId"],["shotId","preparation.basis.shotId"],["expectedPlanVersionId","preparation.basis.planVersionId"],["expectedPlanVersion","preparation.basis.planVersion"],["expectedShotPlanningRevision","preparation.basis.shotPlanningRevision"],["target","preparation.target"]]),"shot-preparation.get":productionRead(PreparationGetInputSchema,PreparationViewSchema,i=>["shot-preparations",i.preparationId],void 0,[["preparationId","preparation.id"]]),"shot-preparation.active":productionRead(PreparationActiveInputSchema,PreparationViewSchema,i=>["shots",i.shotId,"preparations","active"],i=>({mediaType:i.mediaType}),[["shotId","preparation.basis.shotId"],["mediaType","preparation.target.mediaType"]]),"shot-preparation.query":productionRead(PreparationQueryInputSchema,PreparationQueryPageSchema,()=>["shot-preparations"],i=>({...pageQuery(i),shotId:i.shotId,mediaType:i.mediaType}),[["shotId","items.*.preparation.basis.shotId"],["mediaType","items.*.preparation.target.mediaType"]])};var generationOperations={"keyframe.device.quote":productionWrite(KeyframeStartInputSchema,GenerationCostQuoteSchema.nullable(),()=>["keyframe-generations","device","quote"],{tenantInBody:true,readOnly:true}),"keyframe.device.start":productionWrite(KeyframeDeviceStartInputSchema,KeyframeAdmissionSchema,()=>["keyframe-generations","device"],{tenantInBody:true,identity:[["contractId","contractId"]]}),"keyframe.start":productionWrite(KeyframeStartInputSchema,KeyframeAdmissionSchema,()=>["keyframe-generations"],{tenantInBody:true,identity:[["contractId","contractId"]]}),"keyframe.get":productionRead(KeyframeGetInputSchema,KeyframeGenerationViewSchema,i=>["keyframe-generations",i.generationId],void 0,[["generationId","generationId"]]),"keyframe.query":productionRead(KeyframeQueryInputSchema,KeyframeQueryPageSchema,()=>["keyframe-generations"],i=>({...pageQuery(i),shotId:i.shotId}),[["shotId","items.*.shotId"]]),"keyframe.cancel":productionWrite(KeyframeGetInputSchema,InterfaceCancellationReceiptSchema,i=>["keyframe-generations",i.generationId,"cancel"],{pathFields:["generationId"]}),"video.start":productionWrite(VideoStartInputSchema,VideoAdmissionSchema,()=>["video-generations"],{tenantInBody:true,identity:[["contractId","contractId"]]}),"video.device.quote":productionWrite(VideoStartInputSchema,GenerationCostQuoteSchema.nullable(),()=>["video-generations","device","quote"],{tenantInBody:true,readOnly:true}),"video.device.start":productionWrite(VideoDeviceStartInputSchema,VideoAdmissionSchema,()=>["video-generations","device"],{tenantInBody:true,identity:[["contractId","contractId"]]}),"video.get":productionRead(VideoGetInputSchema,VideoGenerationViewSchema,i=>["video-generations",i.generationId],void 0,[["generationId","generationId"]]),"video.query":productionRead(VideoQueryInputSchema,VideoQueryPageSchema,()=>["video-generations"],i=>({...pageQuery(i),shotId:i.shotId}),[["shotId","items.*.shotId"]]),"video.cancel":productionWrite(VideoGetInputSchema,InterfaceCancellationReceiptSchema,i=>["video-generations",i.generationId,"cancel"],{pathFields:["generationId"]})};var keyframeReviewOperations={"keyframe-review.target":productionRead(KeyframeReviewScopeSchema,KeyframeReviewTargetSchema,i=>["keyframe-review",i.generationId],void 0,[["generationId","generationId"]]),"keyframe-review.record":productionWrite(RecordKeyframeReviewSchema,KeyframeReviewReceiptSchema,i=>["keyframe-review",i.generationId],{pathFields:["generationId"],identity:[["generationId","review.generationId"],["candidateId","review.candidateId"],["representationId","review.representationId"],["checksumSha256","review.checksumSha256"]]}),"keyframe-review.query":productionRead(KeyframeReviewQuerySchema,KeyframeReviewPageSchema,i=>["keyframe-review",i.generationId,"history"],pageQuery,[["generationId","items.*.generationId"]]),"keyframe-review.decide":productionWrite(DecideKeyframeSchema,KeyframeDecisionReceiptSchema,i=>["keyframe-review",i.generationId,"decisions"],{pathFields:["generationId"],identity:[["generationId","decision.generationId"],["candidateId","decision.candidateId"],["reviewId","decision.reviewId"],["action","decision.action"]]}),"keyframe-reference.get":productionRead(KeyframeReferenceScopeSchema,KeyframeReferenceViewSchema,i=>["keyframe-review","references",i.shotId,i.framePurpose],void 0,[["shotId","shotId"],["framePurpose","framePurpose"]]),"keyframe-reference.query":productionRead(KeyframeDecisionQuerySchema,KeyframeDecisionPageSchema,i=>["keyframe-review","references",i.shotId,i.framePurpose,"history"],pageQuery,[["shotId","items.*.shotId"],["framePurpose","items.*.framePurpose"]]),"keyframe-reference.revoke":productionWrite(RevokeKeyframeSchema,KeyframeDecisionReceiptSchema,i=>["keyframe-review","references",i.shotId,i.framePurpose,"revoke"],{pathFields:["shotId","framePurpose"],identity:[["shotId","decision.shotId"],["framePurpose","decision.framePurpose"],["acceptanceId","decision.previousAcceptanceId"]]})};var videoReviewOperations={"video-review.target":productionRead(VideoReviewScopeSchema,VideoReviewTargetSchema,i=>["video-review",i.generationId],void 0,[["generationId","generationId"]]),"video-review.record":productionWrite(RecordVideoReviewSchema,VideoReviewReceiptSchema,i=>["video-review",i.generationId],{pathFields:["generationId"],identity:[["generationId","review.generationId"],["candidateId","review.candidateId"],["representationId","review.representationId"],["checksumSha256","review.checksumSha256"]]}),"video-review.query":productionRead(VideoReviewQuerySchema,VideoReviewPageSchema,i=>["video-review",i.generationId,"history"],pageQuery,[["generationId","items.*.generationId"]]),"video-review.decide":productionWrite(DecideVideoShotSchema,ShotDecisionReceiptSchema.extend({decision:GeneratedShotAcceptanceDecisionSchema}),i=>["video-review",i.generationId,"decisions"],{pathFields:["generationId"],identity:[["generationId","decision.generationId"],["candidateId","decision.candidateId"],["reviewId","decision.reviewId"],["action","decision.action"]]}),"shot-acceptance.get":productionRead(ShotAcceptanceScopeSchema,ShotAcceptanceViewSchema,i=>["video-review","shots",i.shotId,"acceptance"],void 0,[["shotId","shotId"]]),"shot-acceptance.query":productionRead(ShotDecisionQuerySchema,ShotDecisionPageSchema,i=>["video-review","shots",i.shotId,"decisions"],pageQuery,[["shotId","items.*.shotId"]]),"shot-acceptance.revoke":productionWrite(RevokeShotAcceptanceSchema,ShotDecisionReceiptSchema,i=>["video-review","shots",i.shotId,"revoke"],{pathFields:["shotId"],identity:[["shotId","decision.shotId"],["acceptanceId","decision.previousAcceptanceId"]]})};import{z as z192}from"zod";var providerOperations={"provider.model.get":operation(ProviderModelGetSchema,ProviderModelViewSchema,i=>({method:"GET",tenantId:i.tenantId,path:path("provider-models",i.id),query:{version:i.version}}),[["id","id"],["version","version"]]),"provider.model.query":operation(ProviderTenantInputSchema,ProviderModelPageSchema,i=>({method:"GET",tenantId:i.tenantId,path:path("provider-models")})),"provider.model.configure":operation(ConfigureProviderModelSchema,ProviderModelViewSchema,i=>({method:"POST",tenantId:i.tenantId,path:path("provider-models","configure"),body:i}),[["definition.profile.id","id"],["definition.profile.version","version"]]),"provider.model.disable":operation(DisableProviderModelSchema,z192.strictObject({disabled:z192.literal(true)}),i=>({method:"POST",tenantId:i.tenantId,path:path("provider-models","disable"),body:i})),"provider.configure":operation(ConfigureProviderInputSchema,ProviderConnectionViewSchema,i=>({method:"POST",tenantId:i.tenantId,path:path("provider-connections","configure"),body:i}),[["connectionId","connectionId"],["configuration","configuration"]]),"provider.query":operation(ProviderTenantInputSchema,ProviderConnectionPageSchema,i=>({method:"GET",tenantId:i.tenantId,path:path("provider-connections")})),"provider.models":operation(ProviderTenantInputSchema,ProviderModelsViewSchema,i=>({method:"GET",tenantId:i.tenantId,path:path("provider-connections","models")})),"provider.keyframe-default.set":operation(SetKeyframeDefaultSchema,ProviderDefaultViewSchema,i=>({method:"POST",tenantId:i.tenantId,path:path("provider-connections","keyframe-default"),body:i}),[["selection","selection"]]),"provider.disable":operation(ProviderConnectionCommandSchema,z192.strictObject({disabled:z192.literal(true)}),i=>({method:"POST",tenantId:i.tenantId,path:path("provider-connections","disable"),body:i})),"provider.revoke":operation(ProviderCredentialRevokeSchema,z192.strictObject({revoked:z192.literal(true)}),i=>({method:"POST",tenantId:i.tenantId,path:path("provider-connections","revoke"),body:i}))};import{z as z193}from"zod";var observationOperations={"media-observation.device.quote":productionWrite(QwenAsrDeviceQuoteInputSchema,QwenAsrCostQuoteSchema,()=>["media-observations","device","quote"],{readOnly:true}),"media-observation.device.start":productionWrite(QwenAsrDeviceStartSchema,QwenAsrDeviceAdmissionSchema,()=>["media-observations","device"]),"media-observation.device.get":productionRead(ObservationGetSchema,QwenAsrDeviceViewSchema,q=>["media-observations","device",q.observationId],void 0,[["observationId","observationId"]]),"media-observation.start-local":productionWrite(LocalObservationStartSchema,LocalObservationAdmissionSchema,()=>["media-observations","local"]),"media-observation.get-local":productionRead(ObservationGetSchema,LocalObservationViewSchema,q=>["media-observations","local",q.observationId],void 0,[["observationId","observationId"]]),"production-guidance.context":productionRead(ObservationScopeSchema,ProductionGuidanceContextSchema,()=>["media-observations","context"]),"media-observation.options":productionRead(ObservationScopeSchema,ObservationOptionsSchema,()=>["media-observations","options"]),"media-observation.start":productionWrite(ObservationStartSchema,ObservationAdmissionSchema,()=>["media-observations"]),"media-observation.get":productionRead(ObservationGetSchema,ObservationViewSchema,q=>["media-observations",q.observationId],void 0,[["observationId","observationId"]]),"media-observation.cancel":productionWrite(ObservationGetSchema,z193.strictObject({cancellationRequested:z193.boolean()}),q=>["media-observations",q.observationId,"cancel"],{pathFields:["observationId"]})};import{z as z194}from"zod";var speechOperations={"speech.device.quote":productionWrite(SpeechStartSchema,SpeechCostQuoteSchema.nullable(),()=>["speech-generations","device","quote"],{readOnly:true}),"speech.device.start":productionWrite(SpeechDeviceStartSchema,SpeechAdmissionSchema,()=>["speech-generations","device"]),"speech.start-local":productionWrite(LocalSpeechStartSchema,LocalSpeechAdmissionSchema,()=>["speech-generations","local"]),"speech.get-local":productionRead(SpeechGetSchema,LocalSpeechGenerationViewSchema,q=>["speech-generations","local",q.generationId],void 0,[["generationId","generationId"]]),"speech.options":productionRead(SpeechScopeSchema,SpeechOptionsSchema,()=>["speech-generations","options"]),"speech.start":productionWrite(SpeechStartSchema,SpeechAdmissionSchema,()=>["speech-generations"]),"speech.get":productionRead(SpeechGetSchema,SpeechGenerationViewSchema,q=>["speech-generations",q.generationId],void 0,[["generationId","generationId"]]),"speech.cancel":productionWrite(SpeechGetSchema,z194.strictObject({cancellationRequested:z194.boolean()}),q=>["speech-generations",q.generationId,"cancel"],{pathFields:["generationId"]})};var voiceProfileOperations={"voice-profile.set-reference":operation(VoiceProfileSetReferenceSchema,VoiceProfileReceiptSchema,({voiceProfileId,...body})=>({method:"POST",tenantId:body.tenantId,path:path("voice-profiles",voiceProfileId,"reference"),body}),[["voiceProfileId","voiceProfileId"]]),"voice-profile.reference":operation(VoiceReferenceGetSchema,VoiceReferenceSchema,i=>({method:"GET",tenantId:i.tenantId,path:path("voice-profiles",i.voiceProfileId,"references",i.referenceId)}),[["voiceProfileId","voiceProfileId"],["referenceId","id"]],{readOnly:true}),"voice-profile.create":operation(VoiceProfileCreateSchema,VoiceProfileReceiptSchema,i=>({method:"POST",tenantId:i.tenantId,path:path("voice-profiles"),body:i})),"voice-profile.revise":operation(VoiceProfileReviseSchema,VoiceProfileReceiptSchema,({voiceProfileId,...body})=>({method:"POST",tenantId:body.tenantId,path:path("voice-profiles",voiceProfileId,"draft"),body}),[["voiceProfileId","voiceProfileId"]]),"voice-profile.publish":operation(VoiceProfilePublishSchema,VoiceProfileReceiptSchema,({voiceProfileId,...body})=>({method:"POST",tenantId:body.tenantId,path:path("voice-profiles",voiceProfileId,"publish"),body}),[["voiceProfileId","voiceProfileId"]]),"voice-profile.set-enabled":operation(VoiceProfileSetEnabledSchema,VoiceProfileReceiptSchema,({voiceProfileId,...body})=>({method:"POST",tenantId:body.tenantId,path:path("voice-profiles",voiceProfileId,"availability"),body}),[["voiceProfileId","voiceProfileId"],["enabled","enabled"]]),"voice-profile.list":operation(VoiceProfileListSchema,VoiceProfilePageSchema,({tenantId,...query})=>({method:"GET",tenantId,path:path("voice-profiles"),query}),[],{readOnly:true}),"voice-profile.get":operation(VoiceProfileScopeSchema,VoiceProfileViewSchema,i=>({method:"GET",tenantId:i.tenantId,path:path("voice-profiles",i.voiceProfileId)}),[["voiceProfileId","voiceProfileId"]],{readOnly:true}),"voice-profile.version":operation(VoiceProfileVersionQuerySchema,VoiceProfileVersionSchema,i=>({method:"GET",tenantId:i.tenantId,path:path("voice-profiles",i.voiceProfileId,"versions",String(i.version))}),[["voiceProfileId","ref.voiceProfileRef"],["tenantId","ref.ownerTenantRef"],["version","ref.version"]],{readOnly:true})};var voiceReviewOperations={"voice-review.target":operation(VoiceReviewTargetQuerySchema,VoiceReviewTargetSchema,({tenantId,voiceProfileId,...query})=>({method:"GET",tenantId,path:path("voice-profiles",voiceProfileId,"review-target"),query}),[["voiceProfileId","voiceProfileId"],["audioVersionId","audioVersionId"]],{readOnly:true}),"voice-review.record":operation(RecordVoiceReviewSchema,VoiceReviewReceiptSchema,({voiceProfileId,...body})=>({method:"POST",tenantId:body.tenantId,path:path("voice-profiles",voiceProfileId,"reviews"),body}),[["voiceProfileId","review.voiceProfileId"],["audioVersionId","review.audioVersionId"],["referenceId","review.basis.reference.id"]]),"voice-review.get":operation(VoiceReviewGetSchema,VoiceReviewViewSchema,i=>({method:"GET",tenantId:i.tenantId,path:path("voice-profiles",i.voiceProfileId,"reviews",i.reviewId)}),[["voiceProfileId","review.voiceProfileId"],["reviewId","review.id"]],{readOnly:true})};var soundMakingPlanOperations={"sound-plan.context":productionRead(SoundPlanScopeSchema,SoundPlanContextSchema,()=>["sound-making-plan","context"],()=>({}),[["tenantId","tenantId"],["productionId","productionId"]]),"sound-plan.get":productionRead(SoundPlanGetSchema,SoundPlanViewSchema,()=>["sound-making-plan"],q=>({versionId:q.versionId}),[["tenantId","version.tenantId"],["productionId","version.productionId"],["versionId","version.id"]]),"sound-plan.validate":productionWrite(SoundPlanValidateSchema,SoundPlanValidationSchema,()=>["sound-making-plan","validate"],{readOnly:true}),"sound-plan.accept":productionWrite(SoundPlanAcceptSchema,SoundPlanReceiptSchema,()=>["sound-making-plan"],{identity:[["tenantId","version.tenantId"],["productionId","version.productionId"]]})};import{z as z195}from"zod";var post2=(input,output,action,identity6=[],readOnly=false)=>operation(input,output,i=>({method:"POST",tenantId:i.tenantId,path:path("lifecycle-events",action),body:i}),identity6,{readOnly});var lifecycleEventOperations={"production.feedback":post2(ProductionFeedbackInputSchema,ProductionFeedbackResultSchema,"feedback",[],true),"production.events.read":post2(ReadProductionEventsSchema,ProductionEventReadSchema,"read",[],true),"webhook.configure":post2(ConfigureWebhookSchema,WebhookSubscriptionSchema,"configure",[["subscriptionId","subscriptionId"]]),"webhook.secret.prepare":post2(PrepareWebhookSecretSchema,WebhookSecretReferenceSchema,"secret-prepare",[["subscriptionId","subscriptionId"],["secretRef","secretRef"]]),"webhook.configure-reference":post2(ConfigureWebhookReferenceSchema,WebhookSubscriptionSchema,"configure-reference",[["subscriptionId","subscriptionId"]]),"webhook.disable":post2(DisableWebhookSchema,WebhookSubscriptionSchema,"disable",[["subscriptionId","subscriptionId"]]),"webhook.replay":post2(ReplayWebhookSchema,WebhookReplayReceiptSchema,"replay",[["eventId","eventId"]]),"lifecycle-event.capabilities":post2(LifecycleEventScopeSchema,LifecycleEventCapabilitiesSchema,"capabilities",[],true),"lifecycle-event.subscriptions":post2(QueryLifecycleEventsSchema.safeExtend({kind:z195.literal("subscriptions")}),WebhookSubscriptionPageSchema,"query",[["subscriptionId","items.*.subscriptionId"]],true),"lifecycle-event.events":post2(QueryLifecycleEventsSchema.safeExtend({kind:z195.literal("events")}),ExternalLifecycleEventPageSchema,"query",[],true),"lifecycle-event.deliveries":post2(QueryLifecycleEventsSchema.safeExtend({kind:z195.literal("deliveries")}),WebhookDeliveryPageSchema,"query",[["subscriptionId","items.*.subscriptionId"],["deliveryId","items.*.deliveryId"]],true),"lifecycle-event.attempts":post2(QueryLifecycleEventsSchema.safeExtend({kind:z195.literal("attempts")}),WebhookAttemptPageSchema,"query",[],true)};import{z as z198}from"zod";import{z as z196}from"zod";var FederationHandoffInputSchema=FederationSubscriptionGetSchema.extend({expectedRevision:z196.int().positive().optional()}).strict();var FederationHandoffSchema=FederationSubscriptionResultSchema.safeExtend({contract:z196.literal("nvs-agent-event-handoff/1"),source:z196.string().min(1).max(2048),notificationProfile:z196.literal("eventsdk/1.2"),receiptProfile:z196.literal("eventsdk/1.1"),status:z196.enum(["READY","NOT_ACTIVE"]),defaultReceive:z196.literal(false),wake:z196.literal("RECEIVER_OWNED"),adoption:z196.literal("RECEIVER_OWNER_GOAL_REQUIRED"),cursorMeaning:z196.literal("NVS_SOURCE_COMMIT_POSITION_NOT_RECEIVER_SEQUENCE"),resultReferenceOperation:z196.literal("federation.result.reference"),resultReadOperation:z196.literal("federation.result.read"),receiptMeaning:z196.literal("LOCAL_APPLIED_IS_NOT_AGENT_ADOPTION"),events:z196.array(z196.strictObject({type:ExternalEventTypeSchema,wireType:z196.string(),dataSchema:z196.string()})).max(14)}).strict().refine(v=>v.status==="READY"===(v.subscription.effective==="ACTIVE")).refine(v=>v.status==="NOT_ACTIVE"?v.events.length===0:new Set(v.events.map(e=>e.type)).size===v.events.length&&v.events.length===v.subscription.eventTypes.length&&v.events.every(e=>v.subscription.eventTypes.includes(e.type)&&e.wireType===`com.nativestudio.${e.type}.v1`&&e.dataSchema===`urn:nativestudio:events:${e.type}:v1`));import{z as z197}from"zod";function federationPublicationContract(type){return{type,wireType:`com.nativestudio.${type}.v1`,dataschema:`urn:nativestudio:events:${type}:v1`,defaultEnabled:false}}var FEDERATION_EVENT_CATALOG=Object.freeze(EXTERNAL_EVENT_TYPES.map(type=>Object.freeze(federationPublicationContract(type))));var readOperation=z197.enum(["federation.result.reference","federation.result.read","federation.inbound.signals","delivery.get","delivery.manifest"]);var eventDescription=z197.strictObject({wireType:z197.string().min(1).max(256),dataschema:z197.url().max(2048),trigger:z197.string().min(1).max(512),readOperations:z197.array(readOperation).min(1).max(4)});var jsonSchema3=z197.record(z197.string(),z197.json());var outbound=eventDescription.extend({nativeType:ExternalEventTypeSchema,effect:z197.literal("LIFECYCLE_NOTICE")}).refine(event3=>{const contract=federationPublicationContract(event3.nativeType);return event3.wireType===contract.wireType&&event3.dataschema===contract.dataschema});var inbound=eventDescription.extend({wireType:z197.literal(RESOURCE_CHANGE_TYPE),dataschema:z197.literal(RESOURCE_CHANGE_SCHEMA),dataSchema:jsonSchema3,effect:z197.literal("REFRESH_HINT")});var FederationEventDefinitionsSchema=FederationScopeSchema.extend({contract:z197.literal("nvs-event-definitions/1"),cloudEventsSpecVersion:z197.literal("1.0"),profile:z197.literal("eventsdk/1.2"),outboundDataSchema:jsonSchema3,outbound:z197.array(outbound).length(EXTERNAL_EVENT_TYPES.length).refine(events=>new Set(events.map(event3=>event3.nativeType)).size===events.length),inbound:z197.array(inbound).length(1)}).strict();var digest4=z198.string().regex(/^sha256:[a-f0-9]{64}$/);var FederationContractInputSchema=FederationHandoffInputSchema.extend({expectedRevision:z198.int().positive(),expectedSource:z198.string().min(1).max(2048).optional(),expectedCatalogDigest:digest4.optional()}).strict();var event2=z198.strictObject({type:z198.string().min(1).max(256),dataschema:z198.string().min(1).max(2048),description:z198.string().min(1).max(1024),dataSchema:z198.record(z198.string(),z198.json()),resourceAccess:z198.strictObject({providerPath:z198.literal("/v1/federation/result-read"),tools:z198.tuple([z198.literal("federation_result_reference"),z198.literal("federation_result_read")])})});var FederationNativeCatalogSchema=z198.unknown().refine(value2=>{try{canonicalFederationCatalogJson(value2);return true}catch{return false}}).pipe(z198.strictObject({schemaVersion:z198.literal(1),serviceRef:z198.literal("native-video-studio"),events:z198.array(event2).min(1).max(14)}));var FederationContractSchema=FederationHandoffSchema.safeExtend({producerContract:z198.literal("nvs-producer-contract/1"),catalog:FederationNativeCatalogSchema.nullable(),catalogDigest:digest4.nullable(),maxCatalogBytes:z198.literal(131072),maxEventBytes:z198.literal(32768),maxResultValueBytes:z198.literal(32768),qualification:z198.literal("NVS_CONTRACT_ONLY")}).refine(v=>v.status==="NOT_ACTIVE"?v.catalog===null&&v.catalogDigest===null:!!v.catalog&&!!v.catalogDigest&&v.catalog.events.length===v.events.length&&new Set(v.catalog.events.map(e=>e.type)).size===v.events.length&&v.catalog.events.every(entry=>v.events.some(e=>e.wireType===entry.type&&e.dataSchema===entry.dataschema)));var federationPost=(input,output,action,readOnly,bindings=[])=>operation(input,output,i=>({method:"POST",path:path("federation",action),tenantId:i.tenantId,body:i}),[["tenantId","tenantId"],["productionId","productionId"],...bindings],{readOnly});import{z as z200}from"zod";import{z as z199}from"zod";var clean3=v=>Array.from(v).every(char=>{const code=char.codePointAt(0);return code>=32&&code!==127&&(code<55296||code>57343)});var text4=max=>z199.string().min(1).max(max).refine(clean3);var hash5=z199.string().regex(/^[a-f0-9]{64}$/);var FederationReceiptOriginSchema=z199.strictObject({schemaVersion:z199.literal(1),sourceService:text4(256),bindingId:z199.uuid().toLowerCase(),source:text4(2048).refine(v=>URL.canParse(v)&&!/\s/u.test(v)),sourceTenant:text4(256),eventId:text4(256),deliveryId:hash5,digest:hash5,logicalDigest:hash5,connectionRef:text4(256),grantRef:text4(256),grantVersion:z199.int().min(1).max(2147483647),consumerRef:text4(256),targetScope:text4(128),deliveryRef:text4(2048)});var ref5=z200.string().min(1).max(256).refine(v=>Array.from(v).every(c=>{const p=c.codePointAt(0);return p>=32&&p!==127&&(p<55296||p>57343)}));var uuid5=z200.uuid().toLowerCase();var id14=z200.string().regex(/^[a-f0-9]{64}$/);var receiptRouteInput=FederationScopeSchema.extend({routeId:uuid5,bindingId:uuid5,requestId:ref5,expectedRevision:z200.int().nonnegative(),grantRef:ref5,grantVersion:z200.int().min(1).max(2147483647),notBefore:z200.iso.datetime(),expiresAt:z200.iso.datetime(),state:z200.enum(["ACTIVE","PAUSED","REVOKED"]),receiptProfile:z200.literal("eventsdk/1.1")}).strict();var FederationReceiptRouteConfigureSchema=receiptRouteInput.refine(orderedFederationWindow);var FederationReceiptRouteSchema=receiptRouteInput.omit({requestId:true,expectedRevision:true}).extend({revision:z200.int().positive(),source:z200.string().min(1).max(2048),connectionRef:ref5,remoteService:z200.string().min(1).max(256),remoteTenant:ref5,peerSource:z200.string().min(1).max(2048),effective:z200.enum(["ACTIVE","PAUSED","REVOKED","EXPIRED","BLOCKED"])}).strict();var FederationReceiptDeliverySchema=FederationScopeSchema.extend({id:id14,routeId:uuid5,inboxId:uuid5,eventId:ref5,receiptRef:ref5,receiptRevision:z200.int().positive(),grantRef:ref5,grantVersion:z200.int().positive(),state:z200.enum(["PENDING","UNKNOWN","PUBLISHED","HOLD"]),attempts:z200.int().nonnegative(),generation:z200.int().nonnegative(),recoveryCount:z200.int().min(0).max(3),reason:ref5.nullable(),originDelivery:FederationReceiptOriginSchema.optional(),ack:z200.strictObject({stream:ref5,sequence:z200.int().positive(),duplicate:z200.boolean()}).nullable()}).strict().refine(v=>!v.originDelivery||v.originDelivery.targetScope===v.tenantId+"/"+v.productionId);var FederationReceiptQuerySchema=FederationScopeSchema.extend({kind:z200.enum(["routes","deliveries"]),routeId:uuid5.optional(),inboxId:uuid5.optional(),originDeliveryId:id14.optional(),after:ref5.optional(),limit:z200.int().min(1).max(50).default(20)}).strict().refine(v=>v.kind==="deliveries"||!v.inboxId&&!v.originDeliveryId).refine(v=>!v.after||(v.kind==="routes"?z200.uuid().safeParse(v.after).success:id14.safeParse(v.after).success));var FederationReceiptQueryResultSchema=z200.discriminatedUnion("kind",[FederationScopeSchema.extend({kind:z200.literal("routes"),items:z200.array(FederationReceiptRouteSchema).max(50),next:uuid5.nullable()}).strict(),FederationScopeSchema.extend({kind:z200.literal("deliveries"),items:z200.array(FederationReceiptDeliverySchema).max(50),next:id14.nullable()}).strict()]).refine(v=>v.items.every(item=>item.tenantId===v.tenantId&&item.productionId===v.productionId));var FederationReceiptRecoverSchema=FederationScopeSchema.extend({routeId:uuid5,deliveryId:id14,requestId:ref5,expectedGeneration:z200.int().nonnegative(),expectedAttempts:z200.int().positive(),reason:ref5,acknowledgeDuplicateRisk:z200.literal(true)}).strict();var FederationReceiptRecoverySchema=FederationScopeSchema.extend({routeId:uuid5,deliveryId:id14,requestId:ref5,recoveryId:uuid5,attempts:z200.int().positive(),generation:z200.int().positive(),recoveryCount:z200.int().min(1).max(3),effect:z200.literal("TRANSPORT_ONLY")}).strict();var FederationReceiptCommandInputSchema=FederationScopeSchema.extend({requestId:ref5}).strict();var FederationReceiptCommandSchema=FederationReceiptCommandInputSchema.extend({result:z200.union([FederationReceiptRouteSchema,FederationReceiptRecoverySchema]).nullable()}).strict().refine(v=>!v.result||v.result.tenantId===v.tenantId&&v.result.productionId===v.productionId);var federationExchangeOperations={"federation.subscription.contract":federationPost(FederationContractInputSchema,FederationContractSchema,"subscription-contract",true,[["subscriptionId","subscription.subscriptionId"]]),"federation.result.reference":federationPost(FederationResultLocatorSchema,FederationResultReferenceSchema,"result-reference",true),"federation.result.read":federationPost(FederationResultReadSchema,FederationResultSnapshotSchema,"result-read",true,[["source","source"]]),"federation.receipt-route.configure":federationPost(FederationReceiptRouteConfigureSchema,FederationReceiptRouteSchema,"receipt-route-configure",false,[["routeId","routeId"],["bindingId","bindingId"]]),"federation.receipt.query":federationPost(FederationReceiptQuerySchema,FederationReceiptQueryResultSchema,"receipt-query",true,[["kind","kind"]]),"federation.receipt.command":federationPost(FederationReceiptCommandInputSchema,FederationReceiptCommandSchema,"receipt-command",true),"federation.receipt.recover":federationPost(FederationReceiptRecoverSchema,FederationReceiptRecoverySchema,"receipt-recover",false,[["routeId","routeId"],["deliveryId","deliveryId"]]),"federation.subscription.handoff":federationPost(FederationHandoffInputSchema,FederationHandoffSchema,"subscription-handoff",true,[["subscriptionId","subscription.subscriptionId"]])};var federationEventLinkOperations={"federation.link.receiver":federationPost(EventLinkScopeSchema,EventReceiverPortalSchema,"link-receiver",true),"federation.link.targets":federationPost(EventLinkScopeSchema,EventLinkTargetsSchema,"link-targets",true),"federation.link.start":federationPost(EventLinkStartInputSchema,EventLinkStartSchema,"link-start",false,[["requestId","requestId"],["targetId","targetId"],["eventType","eventType"]]),"federation.link.get":federationPost(EventLinkRequestInputSchema,EventLinkViewSchema,"link-get",true,[["requestId","requestId"]]),"federation.link.confirm":federationPost(EventLinkConfirmInputSchema,EventLinkConfirmedSchema,"link-confirm",false,[["requestId","requestId"],["expiresAt","route.expiresAt"],["publicationMode","route.publicationMode"]]),"federation.link.cancel":federationPost(EventLinkRequestInputSchema,EventLinkCancelledSchema,"link-cancel",false,[["requestId","requestId"]])};import{z as z201}from"zod";var PEER_RECEIPT_SCHEMA="https://eventsdk.dev/schemas/v1/business-receipt.schema.json";var PUBLISHED_DELIVERY_NAMESPACE="native-video-studio";var PUBLISHED_DELIVERY_PREFIX="urn:nativestudio:published-delivery:v1:";var clean4=v=>Array.from(v).every(c=>{const n=c.codePointAt(0);return n>=32&&n!==127&&(n<55296||n>57343)});var text5=n=>z201.string().min(1).max(n).refine(clean4);var ref6=text5(256);var uuid6=z201.uuid().toLowerCase();var uri2=text5(2048).refine(v=>URL.canParse(v)&&!/\s/u.test(v));var hash6=z201.string().regex(/^[a-f0-9]{64}$/);function publishedDeliveryReceiptRef(deliveryId,digest6){return PUBLISHED_DELIVERY_PREFIX+hash6.parse(deliveryId)+":"+hash6.parse(digest6)}var PeerTerminalReceiptSchema=z201.strictObject({receiptRef:ref6,originSource:uri2,originEventId:ref6,deliveryRef:text5(2048),consumerRef:ref6,targetScope:text5(2048),disposition:z201.enum(["APPLIED","REJECTED"]),recordedAt:z201.iso.datetime({offset:true}),revision:z201.int().min(1).max(2147483647),reasonCode:ref6.optional(),resultRef:z201.strictObject({sourceSystem:ref6,resourceType:ref6,resourceId:text5(2048),revision:ref6,digest:ref6,evidenceRef:text5(2048).optional()}).optional()});var receiptInboundInput=FederationScopeSchema.extend({contractVersion:z201.literal(2),remoteService:ref6,bindingId:uuid6,routeId:uuid6,requestId:ref6,expectedRevision:z201.int().min(0),source:uri2,remoteTenant:ref6,peerType:ref6.refine(v=>!/\s/u.test(v)),consumerRef:ref6,peerConsumerRef:ref6,peerTargetScope:text5(2048),grantRef:ref6,grantVersion:z201.int().min(1).max(2147483647),notBefore:z201.iso.datetime({offset:true}),expiresAt:z201.iso.datetime({offset:true}),state:z201.enum(["ACTIVE","PAUSED","REVOKED"])}).strict();var ReceiptInboundConfigureSchema=receiptInboundInput.refine(orderedFederationWindow);var ReceiptInboundBindingSchema=receiptInboundInput.omit({requestId:true,expectedRevision:true}).extend({installationSource:uri2,remoteService:ref6,contractVersion:z201.union([z201.literal(1),z201.literal(2)]).default(1),connectionRef:ref6,direction:z201.literal("INBOUND"),profile:z201.literal("eventsdk/1.1"),revision:z201.int().positive(),effective:z201.enum(["ACTIVE","PAUSED","REVOKED","EXPIRED","BLOCKED"])}).strict().refine(b=>b.state==="ACTIVE"?b.effective!=="PAUSED":b.effective===b.state).refine(orderedFederationWindow);var CurrentReceiptInboundBindingSchema=ReceiptInboundBindingSchema.safeExtend({contractVersion:z201.literal(2)});var ReceiptObservationSchema=FederationScopeSchema.extend({id:uuid6,bindingId:uuid6,routeId:uuid6,originalEventId:uuid6,originalDeliveryId:hash6,originalDigest:hash6,peerSource:uri2,peerTenant:ref6,receiptRef:ref6,receiptRevision:z201.int().positive(),peerConsumerRef:ref6,peerTargetScope:text5(2048),disposition:z201.enum(["APPLIED","REJECTED"]),peerRecordedAt:z201.iso.datetime({offset:true}),receivedAt:z201.iso.datetime(),hasResultRef:z201.boolean(),meaning:z201.literal("PEER_REPORTED_ONLY")}).strict();var ReceiptInboundQuarantineSchema=FederationScopeSchema.extend({id:uuid6,bindingId:uuid6,deliveryRef:text5(2048),reasonCode:ref6,recordedAt:z201.iso.datetime()}).strict();var ReceiptInboundQuerySchema=FederationScopeSchema.extend({kind:z201.enum(["bindings","observations","quarantine"]),bindingId:uuid6.optional(),originalDeliveryId:hash6.optional(),limit:z201.int().min(1).max(50).default(25),after:uuid6.optional()}).strict().refine(v=>!v.originalDeliveryId||v.kind==="observations");var page4=FederationScopeSchema.extend({next:uuid6.nullable()});var ReceiptInboundQueryResultSchema=z201.discriminatedUnion("kind",[page4.extend({kind:z201.literal("bindings"),items:z201.array(ReceiptInboundBindingSchema).max(50)}).strict(),page4.extend({kind:z201.literal("observations"),items:z201.array(ReceiptObservationSchema).max(50)}).strict(),page4.extend({kind:z201.literal("quarantine"),items:z201.array(ReceiptInboundQuarantineSchema).max(50)}).strict()]).refine(v=>v.items.every(item=>item.tenantId===v.tenantId&&item.productionId===v.productionId));var ReceiptInboundCatalogSchema=FederationScopeSchema.extend({defaultReceive:z201.literal(false),meaning:z201.literal("PEER_REPORTED_ONLY"),bindings:z201.array(CurrentReceiptInboundBindingSchema).max(32)}).strict().refine(v=>v.bindings.every(b=>b.tenantId===v.tenantId&&b.productionId===v.productionId&&b.effective==="ACTIVE"));var ReceiptInboundCommandInputSchema=FederationScopeSchema.extend({requestId:ref6}).strict();var ReceiptInboundCommandSchema=ReceiptInboundCommandInputSchema.extend({result:ReceiptInboundBindingSchema.nullable()}).strict().refine(v=>!v.result||v.result.tenantId===v.tenantId&&v.result.productionId===v.productionId);import{z as z204}from"zod";import{z as z202}from"zod";var uuid7=z202.uuid().toLowerCase();var hash7=z202.string().regex(/^[a-f0-9]{64}$/);var source5=ReceiptInboundBindingSchema.shape.installationSource;var FederationDeliveryInspectInputSchema=FederationScopeSchema.extend({routeId:uuid7,eventId:uuid7,deliveryId:hash7,expectedSource:source5.optional(),expectedDigest:hash7.optional(),receiptBindingId:uuid7.optional()}).strict();var FederationInspectedDeliverySchema=FederationDeliverySchema.extend({source:source5,digest:hash7,connectionRef:ReceiptInboundBindingSchema.shape.connectionRef,grantRef:ReceiptInboundBindingSchema.shape.grantRef,grantVersion:ReceiptInboundBindingSchema.shape.grantVersion}).strict().refine(d=>d.acknowledgement===(d.state==="PUBLISHED"?"BROKER_STORED":"NOT_CONFIRMED")).refine(d=>d.state!=="PUBLISHED"||d.attempts>0);var FederationDeliveryInspectionSchema=FederationScopeSchema.extend({contract:z202.literal("nvs-federation-delivery-inspection/1"),asOf:z202.iso.datetime(),source:source5,delivery:FederationInspectedDeliverySchema,receiptBinding:ReceiptInboundBindingSchema.nullable(),receiptObservation:ReceiptObservationSchema.nullable(),receiptStatus:z202.enum(["NOT_REQUESTED","NOT_OBSERVED","PEER_REPORTED"]),meaning:z202.literal("NATIVE_TRANSPORT_AND_PEER_REPORT_ONLY")}).strict().refine(v=>{const d=v.delivery,b=v.receiptBinding,o=v.receiptObservation;if(d.tenantId!==v.tenantId||d.productionId!==v.productionId||d.source!==v.source)return false;if(!b)return!o&&v.receiptStatus==="NOT_REQUESTED";if(b.tenantId!==v.tenantId||b.productionId!==v.productionId||b.routeId!==d.routeId||b.installationSource!==v.source)return false;if(!o)return v.receiptStatus==="NOT_OBSERVED";return v.receiptStatus==="PEER_REPORTED"&&d.attempts>0&&o.tenantId===v.tenantId&&o.productionId===v.productionId&&o.bindingId===b.bindingId&&o.routeId===d.routeId&&o.originalDeliveryId===d.deliveryId&&o.originalEventId===d.eventId&&o.originalDigest===d.digest&&o.peerSource===b.source&&o.peerTenant===b.remoteTenant&&o.peerConsumerRef===b.peerConsumerRef&&o.peerTargetScope===b.peerTargetScope});import{z as z203}from"zod";var digest5=z203.string().regex(/^sha256:[a-f0-9]{64}$/);var ReceiptAcceptanceInputSchema=FederationScopeSchema.extend({bindingId:z203.uuid().toLowerCase(),expectedRevision:z203.int().positive(),expectedSource:ReceiptInboundBindingSchema.shape.installationSource.optional(),expectedDigest:digest5.optional()}).strict();function createReceiptAcceptanceDocument(raw){const b=CurrentReceiptInboundBindingSchema.parse(raw);return{contract:"nvs-receipt-acceptance/1",bindingId:b.bindingId,bindingRevision:b.revision,tenantId:b.tenantId,productionId:b.productionId,routeId:b.routeId,receiver:{serviceRef:"native-video-studio",source:b.installationSource,consumerRef:b.consumerRef},wire:{specversion:"1.0",profile:"eventsdk/1.1",kind:"RECEIPT",source:b.source,serviceorigin:b.remoteService,sourcetenant:b.remoteTenant,audience:"native-video-studio",type:b.peerType,dataschema:PEER_RECEIPT_SCHEMA,datacontenttype:"application/json",connectionref:b.connectionRef,grantref:b.grantRef,grantversion:b.grantVersion},notBefore:b.notBefore,expiresAt:b.expiresAt,dataSchema:z203.record(z203.string(),z203.json()).parse(z203.toJSONSchema(PeerTerminalReceiptSchema.extend({originSource:z203.literal(b.installationSource),consumerRef:z203.literal(b.peerConsumerRef),targetScope:z203.literal(b.peerTargetScope)}),{target:"draft-2020-12",io:"input"})),association:{rule:"EXACT_ATTEMPTED_NATIVE_OUTBOX_DELIVERY",resourcenamespace:PUBLISHED_DELIVERY_NAMESPACE,resourceRefPrefix:PUBLISHED_DELIVERY_PREFIX,resourceRefComponents:["deliveryId","fullEnvelopeSha256"],resourceRefDelimiter:":",resourceRefPattern:"^"+PUBLISHED_DELIVERY_PREFIX+"[a-f0-9]{64}:[a-f0-9]{64}$",digestAlgorithm:"SHA-256",digestEncoding:"LOWERCASE_HEX",correlationid:"ORIGINAL_NATIVE_EVENT_ID",causationid:"ORIGINAL_NATIVE_EVENT_ID",originEventId:"ORIGINAL_NATIVE_EVENT_ID"},sourceProof:{profile:"eventsdk-origin/1",required:true},maxWireBytes:32768,meaning:"PEER_REPORTED_ONLY",qualification:"NVS_RECEIVER_POLICY_ONLY"}}var boundedDocument=z203.unknown().refine(v=>{try{canonicalFederationReadJson(v);return true}catch{return false}}).pipe(z203.record(z203.string(),z203.json()));var ReceiptAcceptanceSchema=FederationScopeSchema.extend({contract:z203.literal("nvs-receipt-acceptance/1"),source:ReceiptInboundBindingSchema.shape.installationSource,binding:ReceiptInboundBindingSchema,status:z203.enum(["POLICY_ACTIVE","NOT_ACTIVE"]),document:boundedDocument.nullable(),digest:digest5.nullable(),maxDocumentBytes:z203.literal(65536),qualification:z203.literal("NVS_RECEIVER_POLICY_ONLY")}).strict().refine(v=>{try{const b=v.binding;if(b.tenantId!==v.tenantId||b.productionId!==v.productionId||b.installationSource!==v.source)return false;if(b.contractVersion!==2||b.effective!=="ACTIVE")return v.status==="NOT_ACTIVE"&&v.document===null&&v.digest===null;return v.status==="POLICY_ACTIVE"&&v.document!==null&&v.digest!==null&&canonicalFederationReadJson(v.document)===canonicalFederationReadJson(createReceiptAcceptanceDocument(b))}catch{return false}});var ReceiptHandoffInputSchema=FederationDeliveryInspectInputSchema.omit({receiptBindingId:true,expectedDigest:true,expectedSource:true}).extend({bindingId:ReceiptAcceptanceInputSchema.shape.bindingId,expectedRevision:ReceiptAcceptanceInputSchema.shape.expectedRevision,expectedSource:ReceiptInboundBindingSchema.shape.installationSource,expectedDeliveryDigest:FederationDeliveryInspectInputSchema.shape.deliveryId,expectedAcceptanceDigest:ReceiptAcceptanceInputSchema.shape.expectedDigest}).strict();function receiptHandoffStatus(i,a){if(i.receiptStatus==="PEER_REPORTED")return"PEER_REPORTED";if(i.delivery.attempts===0)return"ORIGINAL_NOT_ATTEMPTED";if(a.status!=="POLICY_ACTIVE")return"POLICY_NOT_ACTIVE";return"AWAITING_PEER_REPORT"}function receiptBindingInObservedWindow(i){const b=i.receiptBinding,observed=Date.parse(i.asOf);return b!==null&&Date.parse(b.notBefore)<=observed&&observed<Date.parse(b.expiresAt)}function association(i){return{resourcenamespace:PUBLISHED_DELIVERY_NAMESPACE,resourceref:publishedDeliveryReceiptRef(i.delivery.deliveryId,i.delivery.digest),correlationid:i.delivery.eventId,causationid:i.delivery.eventId}}var reply=FederationScopeSchema.extend({contract:z204.literal("nvs-receipt-handoff/1"),source:ReceiptInboundBindingSchema.shape.installationSource,inspection:FederationDeliveryInspectionSchema,acceptance:ReceiptAcceptanceSchema,status:z204.enum(["PEER_REPORTED","ORIGINAL_NOT_ATTEMPTED","POLICY_NOT_ACTIVE","AWAITING_PEER_REPORT"]),association:z204.strictObject({resourcenamespace:z204.literal(PUBLISHED_DELIVERY_NAMESPACE),resourceref:z204.string().min(1).max(256),correlationid:z204.uuid().toLowerCase(),causationid:z204.uuid().toLowerCase()}).nullable(),maxReplyBytes:z204.literal(131072),qualification:z204.literal("NVS_READ_SNAPSHOT_ONLY")}).strict().refine(v=>{try{const i=v.inspection,a=v.acceptance;if(!i.receiptBinding||i.source!==v.source||a.source!==v.source||i.tenantId!==v.tenantId||i.productionId!==v.productionId||a.tenantId!==v.tenantId||a.productionId!==v.productionId||a.status==="POLICY_ACTIVE"&&!receiptBindingInObservedWindow(i)||canonicalFederationReadJson(i.receiptBinding)!==canonicalFederationReadJson(a.binding)||v.status!==receiptHandoffStatus(i,a))return false;return v.status==="AWAITING_PEER_REPORT"?canonicalFederationReadJson(v.association)===canonicalFederationReadJson(association(i)):v.association===null}catch{return false}});var ReceiptHandoffSchema=z204.unknown().refine(v=>{try{canonicalFederationCatalogJson(v);return true}catch{return false}},{abort:true}).pipe(reply);var federationReceiptInboundOperations={"federation.receipt-inbound.handoff":federationPost(ReceiptHandoffInputSchema,ReceiptHandoffSchema,"receipt-inbound-handoff",true,[["bindingId","acceptance.binding.bindingId"],["routeId","inspection.delivery.routeId"],["eventId","inspection.delivery.eventId"],["deliveryId","inspection.delivery.deliveryId"]]),"federation.receipt-inbound.contract":federationPost(ReceiptAcceptanceInputSchema,ReceiptAcceptanceSchema,"receipt-inbound-contract",true,[["bindingId","binding.bindingId"]]),"federation.receipt-inbound.configure":federationPost(ReceiptInboundConfigureSchema,CurrentReceiptInboundBindingSchema,"receipt-inbound-configure",false,[["bindingId","bindingId"],["routeId","routeId"]]),"federation.receipt-inbound.catalog":federationPost(FederationScopeSchema,ReceiptInboundCatalogSchema,"receipt-inbound-catalog",true),"federation.receipt-inbound.query":federationPost(ReceiptInboundQuerySchema,ReceiptInboundQueryResultSchema,"receipt-inbound-query",true,[["kind","kind"]]),"federation.receipt-inbound.command":federationPost(ReceiptInboundCommandInputSchema,ReceiptInboundCommandSchema,"receipt-inbound-command",true)};var federationDeliveryInspectionOperations={"federation.delivery.inspect":federationPost(FederationDeliveryInspectInputSchema,FederationDeliveryInspectionSchema,"delivery-inspect",true,[["routeId","delivery.routeId"],["eventId","delivery.eventId"],["deliveryId","delivery.deliveryId"]])};var federationOperations={...federationEventLinkOperations,...federationDeliveryInspectionOperations,...federationReceiptInboundOperations,...federationExchangeOperations,"federation.inbound.catalog":federationPost(FederationScopeSchema,InboundCatalogSchema,"inbound-catalog",true),"federation.inbound.configure":federationPost(InboundBindingConfigureSchema,CurrentInboundBindingSchema,"inbound-configure",false,[["bindingId","bindingId"],["source","source"]]),"federation.inbound.query":federationPost(InboundQuerySchema,InboundQueryResultSchema,"inbound-query",true,[["kind","kind"]]),"federation.inbound.signals":federationPost(InboundSignalsQuerySchema,InboundSignalsPageSchema,"inbound-signals",true),"federation.inbound.signal-changes":federationPost(InboundSignalChangesQuerySchema,InboundSignalChangesPageSchema,"inbound-signal-changes",true),"federation.inbound.receipt":federationPost(InboundReceiptInputSchema,InboundReceiptSchema,"inbound-receipt",true,[["kind","kind"]]),"federation.inbound.replay":federationPost(InboundReplaySchema,InboundReplayResultSchema,"inbound-replay",false,[["inboxId","inboxId"],["requestId","requestId"]]),"federation.observe":federationPost(FederationScopeSchema,FederationObservationSchema,"observe",true),"federation.recover":federationPost(FederationRecoverSchema,FederationRecoverySchema,"recover",false,[["routeId","routeId"],["requestId","requestId"],["kind","kind"]]),"federation.catalog":federationPost(FederationScopeSchema,FederationCatalogSchema,"catalog",true),"federation.event-definitions":federationPost(FederationScopeSchema,FederationEventDefinitionsSchema,"event-definitions",true),"federation.route.configure":federationPost(FederationRouteConfigureSchema,FederationRouteSchema,"route-configure",false,[["routeId","routeId"],["grantRef","grantRef"],["grantVersion","grantVersion"],["remoteService","remoteService"],["remoteTenant","remoteTenant"]]),"federation.subscription.set":federationPost(FederationSubscriptionSetSchema,FederationSubscriptionResultSchema,"subscription-set",false,[["subscriptionId","subscription.subscriptionId"],["routeId","subscription.routeId"],["subscriberKind","subscription.subscriberKind"],["subscriberRef","subscription.subscriberRef"]]),"federation.subscription.get":federationPost(FederationSubscriptionGetSchema,FederationSubscriptionResultSchema,"subscription-get",true,[["subscriptionId","subscription.subscriptionId"]]),"federation.query":federationPost(FederationQuerySchema,FederationQueryResultSchema,"query",true,[["kind","kind"]]),"federation.receipt":federationPost(FederationReceiptInputSchema,FederationReceiptSchema,"receipt",true,[["requestId","requestId"]])};var renderTicket=resource=>operation(TenantRenderMediaInputSchema,TenantRenderMediaTicketSchema,i=>({method:"GET",tenantId:i.tenantId,path:path("productions",i.productionId,resource,i.renderId,"media-ticket"),query:{role:i.role}}),[["renderId","renderId"],["role","role"],["role","ticket.object.role"]],{readOnly:true});var mediaDescriptorOperations={"rough-cut.media-ticket":renderTicket("rough-cuts"),"final-render.media-ticket":renderTicket("final-renders"),"composition.render.media-target":descriptorOperation(CompositionRenderGetSchema,CompositionRenderMediaDescriptorSchema,i=>({method:"GET",tenantId:i.tenantId,path:path("productions",i.productionId,"compositions","renders",i.renderId,"media-target")}),i=>path("productions",i.productionId,"compositions","renders",i.renderId,"media")),"delivery.download":descriptorOperation(TimelineScopeSchema,InterfaceDeliveryDownloadDescriptorSchema,i=>({method:"GET",tenantId:i.tenantId,path:path("productions",i.productionId,"deliveries","download")}),(i,o)=>o.method==="POST"?tenantMediaDownloadPath:path("productions",i.productionId,"deliveries","media")),"temporal-evidence.download":descriptorOperation(TemporalEvidenceMediaSchema,InterfaceDownloadDescriptorSchema,i=>({method:"GET",tenantId:i.tenantId,path:path("productions",i.productionId,"temporal-evidence",i.evidenceId,"media",i.kind,"descriptor"),query:i.kind==="FRAME"?{ordinal:i.ordinal}:{}}),i=>path("productions",i.productionId,"temporal-evidence",i.evidenceId,"media",i.kind)+(i.kind==="FRAME"?"?ordinal="+i.ordinal:"")),"video.options":operation(VideoOptionsInputSchema,VideoOptionsSchema,i=>({method:"GET",tenantId:i.tenantId,path:path("video-options")}),[],{readOnly:true})};var referencePreviewOperations={"studio.capabilities":mcpOperation(StudioCapabilitiesInputSchema,StudioCapabilitiesSchema,true),"reference-preview.start":operation(StartReferencePreviewSchema,ReferencePreviewAdmissionSchema,i=>{const{tenantId,productionId,...body}=i;return{method:"POST",tenantId,path:path("productions",productionId,"reference-previews"),body}},[["sourceArtifactId","sourceArtifactId"],["expectedBriefVersion","briefVersion"]],{readOnly:false}),"reference-preview.status":operation(ReferencePreviewOperationInputSchema,OperationSummarySchema,i=>({method:"GET",tenantId:i.tenantId,path:path("productions",i.productionId,"reference-previews",i.operationId,"status"),query:{projectId:i.projectId}}),[["operationId","id"]],{readOnly:true}),"reference-preview.get":operation(ReferencePreviewOperationInputSchema,ReferencePreviewReadResultSchema,i=>({method:"GET",tenantId:i.tenantId,path:path("productions",i.productionId,"reference-previews",i.operationId),query:{projectId:i.projectId}}),[],{readOnly:true}),"reference-preview.cancel":operation(ReferencePreviewOperationInputSchema,ReferencePreviewCancelResultSchema,i=>({method:"POST",tenantId:i.tenantId,path:path("productions",i.productionId,"reference-previews",i.operationId,"cancel"),body:{projectId:i.projectId}}),[],{readOnly:false})};var Context6=ExplorationContextInputSchema.safeExtend({tenantId:TenantIdSchema}).refine(i=>i.tenantId.toLowerCase()===i.scope.tenantId.toLowerCase());var Plan2=ValidateExplorationPlanSchema.safeExtend({tenantId:TenantIdSchema}).refine(i=>i.tenantId.toLowerCase()===i.basis.tenantId.toLowerCase());var Compare2=ExplorationCompareInputSchema.extend({tenantId:TenantIdSchema}).refine(i=>i.tenantId.toLowerCase()===i.scope.tenantId.toLowerCase());var Recommendation=ExplorationRecommendationContextInputSchema.safeExtend({tenantId:TenantIdSchema}).refine(i=>i.tenantId.toLowerCase()===i.scope.tenantId.toLowerCase());var Validate5=ValidateExplorationRecommendationSchema.safeExtend({tenantId:TenantIdSchema}).refine(i=>i.tenantId.toLowerCase()===i.basis.input.scope.tenantId.toLowerCase());var route4=(s,family,...suffix)=>path("projects",s.projectId,"productions",s.productionId,family,...suffix);var ownerOperations={"exploration.context":operation(Context6,ExplorationContextResultSchema,i=>({method:"POST",tenantId:i.tenantId,path:route4(i.scope,"visual-exploration","context"),body:{scope:i.scope,preparationIds:i.preparationIds}}),[["scope.tenantId","basis.tenantId","SUCCESS"],["scope.projectId","basis.projectId","SUCCESS"],["scope.productionId","basis.productionId","SUCCESS"],["scope.shotId","basis.shotId","SUCCESS"]],{readOnly:true}),"exploration.plan.validate":operation(Plan2,ExplorationValidationResultSchema,i=>({method:"POST",tenantId:i.tenantId,path:route4(i.basis,"visual-exploration","plans","validate"),body:{basis:i.basis,plan:i.plan}}),[["basis","basis","SUCCESS"]],{readOnly:true}),"exploration.compare":operation(Compare2,ExplorationComparisonResultSchema,i=>({method:"POST",tenantId:i.tenantId,path:route4(i.scope,"visual-exploration","compare"),body:{scope:i.scope,items:i.items}}),[["scope","scope"]],{readOnly:true}),"exploration.recommendation.context":operation(Recommendation,ExplorationRecommendationContextResultSchema,i=>({method:"POST",tenantId:i.tenantId,path:route4(i.scope,"exploration-recommendation","context"),body:{scope:i.scope,items:i.items,criteria:i.criteria}}),[["scope","basis.input.scope"],["items","basis.input.items"],["criteria","basis.input.criteria"]],{readOnly:true}),"exploration.recommendation.validate":operation(Validate5,ExplorationRecommendationValidationResultSchema,i=>({method:"POST",tenantId:i.tenantId,path:route4(i.basis.input.scope,"exploration-recommendation","proposals","validate"),body:{basis:i.basis,proposal:i.proposal}}),[["basis","basis"],["proposal.decision.kind","decision.kind"],["proposal.decision.label","decision.label"]],{readOnly:true})};var visualExplorationOperations=ownerOperations;import{z as z205}from"zod";var ownerOperations2={"imported-visual.query":productionRead(ImportedVisualOriginalQuerySchema,ImportedVisualOriginalPageSchema,()=>["imported-visuals","originals"],i=>({limit:i.limit,afterSourceId:i.afterSourceId,shotId:i.shotId}),[["shotId","items.*.shotId"]]),"imported-visual.register-source":productionWrite(LegacyImportedVisualProjectSourceSchema,ImportedVisualOriginalViewSchema,()=>["imported-visuals","originals","from-source"],{identity:[["projectId","projectId"],["shotId","shotId"]]}),"imported-visual.start-from-source":productionWrite(ImportedVisualFromProjectSourceSchema,DirectOriginalSubmitSchema,()=>["imported-visuals","originals","from-source","v1"]),"imported-visual.register":operation(LegacyImportedVisualUploadSchema,ImportedVisualOriginalViewSchema,i=>{const{contentBase64,tenantId,productionId,...fields}=i;return{method:"POST",tenantId,path:path("productions",productionId,"imported-visuals","originals","bytes"),importedVideo:{bytes:Buffer.from(contentBase64,"base64"),metadata:Buffer.from(JSON.stringify(fields)).toString("base64url")}}},[["shotId","shotId"]]),"imported-visual.revise":productionWrite(LegacyImportedVisualRevisionSchema,ImportedVisualOriginalViewSchema,i=>["imported-visuals","originals",i.sourceId,"revisions"],{pathFields:["sourceId"],identity:[["sourceId","sourceId"],["shotId","shotId"]]}),"imported-visual.original":productionRead(ImportedVisualOriginalGetSchema,ImportedVisualOriginalViewSchema,i=>["imported-visuals","originals",i.sourceId],i=>({version:i.version}),[["sourceId","sourceId"],["version","version"]]),"imported-visual.history":productionRead(ImportedVisualOriginalHistoryQuerySchema,ImportedVisualOriginalHistorySchema,i=>["imported-visuals","originals",i.sourceId,"history"],i=>({limit:i.limit,beforeVersion:i.beforeVersion}),[["sourceId","sourceId"],["sourceId","items.*.sourceId"]]),"imported-visual.normalize":productionWrite(ImportedVisualNormalizeStartSchema,ImportedVisualAdmissionSchema,()=>["imported-visuals","normalizations"],{identity:[["sourceId","sourceId"],["sourceVersionId","sourceVersionId"]]}),"imported-visual.get":productionRead(ImportedVisualGetSchema,ImportedVisualNormalizationViewSchema,i=>["imported-visuals","normalizations",i.normalizationId],void 0,[["normalizationId","normalizationId"]]),"imported-visual.review.target":productionRead(ImportedVisualGetSchema,ImportedVisualReviewTargetSchema,i=>["imported-visuals","normalizations",i.normalizationId,"review-target"],void 0,[["normalizationId","normalizationId"]]),"imported-visual.review.record":productionWrite(ImportedVisualReviewSchema,ImportedVideoReviewReceiptSchema,i=>["imported-visuals","normalizations",i.normalizationId,"reviews"],{pathFields:["normalizationId"],identity:[["normalizationId","review.normalizationId"],["representationId","review.representationId"],["checksumSha256","review.checksumSha256"]]}),"imported-visual.decide":productionWrite(ImportedVisualDecisionSchema,ShotDecisionReceiptSchema,i=>["imported-visuals","normalizations",i.normalizationId,"decisions"],{pathFields:["normalizationId"],identity:[["normalizationId","decision.normalizationId"],["reviewId","decision.reviewId"]]}),"imported-visual.cancel":productionWrite(ImportedVisualGetSchema,z205.strictObject({cancellationRequested:z205.boolean()}),i=>["imported-visuals","normalizations",i.normalizationId,"cancel"],{pathFields:["normalizationId"]})};var importedVisualOperations=ownerOperations2;var versionPath=i=>["source-sync-audios","shots",i.shotId,"versions",i.versionId];var ownerOperations3={"source-sync.start":productionWrite(SourceSyncRuntimeStartSchema,SourceSyncRuntimeAdmissionSchema,()=>["source-sync-audios","requests"]),"source-sync.get":productionRead(SourceSyncRuntimeScopeSchema,SourceSyncRuntimeViewSchema,i=>["source-sync-audios","requests",i.requestId],void 0,[["requestId","requestId"]]),"source-sync.cancel":productionWrite(SourceSyncRuntimeScopeSchema,ImportedVisualCancellationSchema,i=>["source-sync-audios","requests",i.requestId,"cancel"],{pathFields:["requestId"]}),"source-sync.audio":productionRead(SourceSyncAudioGetSchema,WavExportResultSchema,i=>[...versionPath(i),"audio"]),"source-sync.version":productionRead(SourceSyncAudioGetSchema,SourceSyncAudioViewSchema,versionPath,void 0,[["versionId","version.id"],["shotId","version.shotId"]]),"source-sync.review.target":productionRead(SourceSyncAudioGetSchema,SourceSyncReviewTargetSchema,i=>[...versionPath(i),"review-target"],void 0,[["versionId","version.id"],["shotId","version.shotId"]]),"source-sync.review.record":productionWrite(SourceSyncReviewInputSchema,SourceSyncReviewRecordSchema,i=>[...versionPath(i),"reviews"],{pathFields:["shotId","versionId"],identity:[["versionId","versionId"],["shotId","shotId"],["audio","audio"],["visual","visual"]]}),"source-sync.review.get":productionRead(SourceSyncReviewGetSchema,SourceSyncReviewRecordSchema,i=>[...versionPath(i),"reviews",i.reviewId],void 0,[["versionId","versionId"],["shotId","shotId"],["reviewId","id"]])};var sourceSyncOperations=ownerOperations3;var Writer=ValidateWriterProposalSchema.extend({tenantId:TenantIdSchema}).refine(i=>i.tenantId.toLowerCase()===i.basis.tenantId.toLowerCase());var Director=ValidateDirectorProposalSchema.safeExtend({tenantId:TenantIdSchema}).refine(i=>i.tenantId.toLowerCase()===i.basis.tenantId.toLowerCase());var projectProduction2=(scope8,...suffix)=>path("projects",scope8.projectId,"productions",scope8.productionId,...suffix);var planningIntelligenceOperations={"brief.active":operation(WriterScopeSchema,WriterBriefResultSchema,i=>({method:"GET",tenantId:i.tenantId,path:projectProduction2(i,"brief-versions","active")})),"writer.validate":operation(Writer,WriterValidationResultSchema,i=>({method:"POST",tenantId:i.tenantId,path:projectProduction2(i.basis,"writer-proposals","validate"),body:{basis:i.basis,proposal:i.proposal,...i.revisionReason?{revisionReason:i.revisionReason}:{}}}),[["basis","basis","SUCCESS"]],{readOnly:true}),"director.context":operation(DirectorScopeSchema,DirectorContextResultSchema,i=>({method:"GET",tenantId:i.tenantId,path:projectProduction2(i,"director","context")})),"director.validate":operation(Director,DirectorValidationResultSchema,i=>({method:"POST",tenantId:i.tenantId,path:projectProduction2(i.basis,"director-proposals","validate"),body:{basis:i.basis,proposal:i.proposal,...i.revisionReason?{revisionReason:i.revisionReason}:{}}}),[["basis","basis","SUCCESS"]],{readOnly:true}),"consistency-profile.get":productionRead(ConsistencyProfileScopeSchema,ConsistencyProfileViewSchema,()=>["consistency-profile"]),"consistency-profile.version":productionRead(ConsistencyProfileVersionQuerySchema,ConsistencyProfileVersionSchema,i=>["consistency-profile","versions",i.profileId],void 0,[["profileId","id"]]),"consistency-profile.configure":productionWrite(ConfigureConsistencyProfileSchema,ConsistencyProfileReceiptSchema,()=>["consistency-profile"],{tenantInBody:true})};var audioCaptionOperations={"caption.transcript_draft":productionWrite(CaptionTranscriptPlanSchema,CaptionTranscriptDraftSchema,()=>["captions","transcript-draft"],{readOnly:true}),"caption.author_transcript":productionWrite(AuthorTranscriptCaptionsSchema,CaptionReceiptSchema,()=>["captions","from-transcript"]),"audio.export":operation(AudioGetSchema,AudioExportResultSchema,i=>({method:"GET",tenantId:i.tenantId,path:path("productions",i.productionId,"audio",i.purpose,"versions",i.versionId,"export-data")}),[],{readOnly:true}),"caption.export":operation(CaptionExportSchema,CaptionExportResultSchema,i=>({method:"GET",tenantId:i.tenantId,path:path("productions",i.productionId,"captions","versions",i.versionId,"export-data"),query:{format:i.format}}),[],{readOnly:true}),"audio.basis":productionRead(AudioReadScopeSchema,AudioBasisSchema,i=>["audio",i.purpose,"basis"],void 0,[["purpose","purpose"]]),"audio.current":productionRead(AudioReadScopeSchema,AudioViewSchema,i=>["audio",i.purpose,"current"],void 0,[["purpose","version.purpose"]]),"audio.get":productionRead(AudioGetSchema,AudioViewSchema,i=>["audio",i.purpose,"versions",i.versionId],void 0,[["versionId","version.id"],["purpose","version.purpose"]]),"audio.query":productionRead(AudioQuerySchema,AudioPageSchema,i=>["audio",i.purpose,"versions"],pageQuery,[["purpose","items.*.version.purpose"]]),"audio.import":productionWrite(AudioImportRequestSchema,AudioReceiptSchema,i=>["audio",i.purpose],{pathFields:["purpose"],identity:[["purpose","version.purpose"]]}),"caption.basis":productionRead(CaptionScopeSchema,CaptionBasisSchema,()=>["captions","basis"]),"caption.current":productionRead(CaptionScopeSchema,CaptionViewSchema,()=>["captions","current"]),"caption.get":productionRead(CaptionGetSchema,CaptionViewSchema,i=>["captions","versions",i.versionId],void 0,[["versionId","version.id"]]),"caption.query":productionRead(CaptionQuerySchema,CaptionPageSchema,()=>["captions","versions"],pageQuery),"caption.author":productionWrite(AuthorCaptionsSchema,CaptionReceiptSchema,()=>["captions"])};var discoveryOperations={"artifact.query":operation(ArtifactDiscoveryQuerySchema,ArtifactDiscoveryPageSchema,input=>({method:"GET",tenantId:input.tenantId,path:path("artifact-discovery"),query:{...pageQuery(input),projectId:input.projectId,productionId:input.productionId,artifactId:input.artifactId,mediaCategory:input.mediaCategory,family:input.family,search:input.search,lifecycle:input.lifecycle}}),[["artifactId","items.*.artifactId"]])};var temporalEvidenceOperations={"temporal-evidence.read-video":productionWrite(OriginalVideoReadSchema,OriginalVideoResultSchema,()=>["temporal-evidence","original-video"],{tenantInBody:true,readOnly:true,identity:[["tenantId","source.tenantId"],["productionId","source.productionId"],["artifactId","source.artifactId"],["representationId","source.representationId"],["checksumSha256","source.checksumSha256"]]}),"temporal-evidence.target":productionWrite(TemporalEvidenceTargetSchema,TemporalEvidenceSourceSchema,()=>["temporal-evidence","target"],{tenantInBody:true,readOnly:true,identity:[["artifactId","artifactId"],["representationId","representationId"],["checksumSha256","checksumSha256"]]}),"temporal-evidence.start":productionWrite(TemporalEvidenceStartSchema,TemporalEvidenceAdmissionSchema,()=>["temporal-evidence"],{tenantInBody:true,identity:[["artifactId","source.artifactId"],["representationId","source.representationId"],["checksumSha256","source.checksumSha256"]]}),"temporal-evidence.get":productionRead(TemporalEvidenceGetSchema,TemporalEvidenceViewSchema,i=>["temporal-evidence",i.evidenceId],void 0,[["evidenceId","evidenceId"]]),"temporal-evidence.cancel":productionWrite(TemporalEvidenceGetSchema,cancellation,i=>["temporal-evidence",i.evidenceId,"cancel"],{pathFields:["evidenceId"]})};var scopeKeys=["tenantId","projectId","productionId"];function navigationResponseMatches(value2){if(!value2||typeof value2!=="object")return true;const result=value2;if(result.evidence?.source!=="production_snapshot")return true;if(!result.actions?.items||!result.operations?.items)return false;const same3=(a,b)=>typeof a==="string"&&typeof b==="string"&&a.toLowerCase()===b.toLowerCase();const hintsMatch=input=>!input||scopeKeys.every(key10=>input[key10]===void 0||same3(input[key10],result[key10]));return result.actions.items.every(action=>scopeKeys.every(key10=>same3(action.context[key10],result[key10]))&&action.context.revision===result.evidence.revision&&hintsMatch(action.inputHints?.knownInputs)&&hintsMatch(action.inspect?.arguments))&&result.operations.items.every(operation2=>{return[operation2.inspect,operation2.failure?.next].every(read=>{if(!read)return true;const selected=read.tool==="studio_capability_query"?read.arguments:read;return hintsMatch(read.arguments)&&hintsMatch(selected.arguments)&&(selected.tool!=="operation_get"||selected.arguments.operationId===operation2.id)})})}var envelopes=new Set(["choices","related","operations","activeOperations","items","project","production","productions","artifact","primaryRepresentation","relations","storyVersion","planVersion","version","manifest","timeline","basis","review","selection","decision","target","admission","policy","finalDelivery","receipt","render","evidence","source","sourceIdentity","preparation","link","body","latestReview","finalReady","approval","binding","standard","snapshot","sequence","frames","frameOutput","acceptance","reference","candidate","connection","scope","profile","current","feedback","share","ownerContext","comparison","candidates","reviewContext","input","recordDraft","owner","output","result","briefVersion","deliveryTarget","deliverySnapshot","validation","preparations","view","generationDrafts","request","generation","handoff","mediaRead","reviewTarget","reviews"]);var uuid8=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function same2(left,right){if(Array.isArray(left)||Array.isArray(right))return Array.isArray(left)&&Array.isArray(right)&&left.length===right.length&&left.every((item,i)=>same2(item,right[i]));if(left&&right&&typeof left==="object"&&typeof right==="object"){const a=left,b=right;const keys=Object.keys(a);return keys.length===Object.keys(b).length&&keys.every(key10=>Object.hasOwn(b,key10)&&same2(a[key10],b[key10]))}return typeof left==="string"&&typeof right==="string"&&uuid8.test(left)&&uuid8.test(right)?left.toLowerCase()===right.toLowerCase():left===right}function scopeMatches(value2,scope8,depth2=0){if(!value2||typeof value2!=="object")return true;if(depth2>12)return false;if(Array.isArray(value2))return value2.every(item=>scopeMatches(item,scope8,depth2+1));const record=value2;for(const key10 of["tenantId","projectId","productionId"])if(scope8[key10]!==void 0&&record[key10]!==void 0&&record[key10]!==null&&!same2(record[key10],scope8[key10]))return false;const next=record.failure?.next;if((next?.capability==="operation.get"||next?.capability==="production.snapshot")&&typeof record.id==="string"&&typeof record.productionId==="string"&&(!next.input||!same2(next.input.productionId,record.productionId)||scope8.tenantId!==void 0&&!same2(next.input.tenantId,scope8.tenantId)||next.capability==="operation.get"&&next.input.operationId!==record.id))return false;return Object.entries(record).every(([key10,item])=>{if(key10==="feedback"&&item&&typeof item==="object"&&scope8.operationId!==void 0&&!same2(item.operationId,scope8.operationId))return false;return!envelopes.has(key10)||scopeMatches(item,scope8,depth2+1)})}function targetsMatch(value2,parts,expected){if(!parts.length)return same2(value2,expected);const[part,...rest]=parts;if(part==="*")return Array.isArray(value2)&&value2.every(item=>targetsMatch(item,rest,expected));return!!value2&&typeof value2==="object"&&targetsMatch(value2[part],rest,expected)}function deviceBound(request,result){const target3=request;const receipt=result?.deviceExecution;if(target3.mode===void 0)return receipt?.target==="TENANT_DEVICE"&&typeof result?.runtimeJobId==="string"&&(!target3.deviceId||same2(target3.deviceId,receipt.deviceId));return!!receipt&&receipt.mode===target3.mode&&!!receipt.runtimeJobId&&(!target3.validationMode||target3.validationMode===receipt.validationMode)&&(!target3.deviceId||same2(target3.deviceId,receipt.deviceId))}function deviceJobMatches(result){const value2=result;return value2?.runtimeJobId===void 0||value2.deviceExecution?.runtimeJobId===void 0||same2(value2.runtimeJobId,value2.deviceExecution.runtimeJobId)}function assertResponseBindings(result,input,identity6,method,pathOrBindings,additionalBindings=[]){if(result===null)return;const expectedPath=typeof pathOrBindings==="string"?pathOrBindings:void 0;const identityWhenPresent=typeof pathOrBindings==="string"||pathOrBindings===void 0?additionalBindings:pathOrBindings;const record=result;const basis=input.basis;const basisInput2=basis?.input;const nested=input.scope??basis?.scope??basisInput2?.scope??basis;if(input.deviceExecution!==void 0&&!deviceBound(input.deviceExecution,result)||!deviceJobMatches(result)||!scopeMatches(result,input)||!navigationResponseMatches(result)||nested!==void 0&&!scopeMatches(result,nested)||expectedPath!==void 0&&(typeof record?.path!=="string"||record.path.replace(/[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}/gi,id15=>id15.toLowerCase())!==expectedPath.replace(/[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}/gi,id15=>id15.toLowerCase()))||[...identity6,...identityWhenPresent.filter(([,target3])=>!!record&&Object.hasOwn(record,target3))].some(([key10,target3,whenStatus])=>{if(whenStatus!==void 0&&record?.semanticStatus!==whenStatus)return false;const expected=key10.split(".").reduce((value2,field)=>value2&&typeof value2==="object"?value2[field]:void 0,input);return expected!==void 0&&!targetsMatch(result,target3.split("."),expected)})||Array.isArray(record?.items)&&typeof input.limit==="number"&&record.items.length>input.limit)throw new NativeStudioSdkError("RESPONSE_SCOPE_MISMATCH","INTERNAL_OPERATIONAL_FAILURE",method==="POST"?"UNKNOWN":"NO_WRITE")}function seriesPath(projectId,...suffix){return path("projects",projectId,"series-standards",...suffix)}var seriesPost=(group,...suffix)=>({tenantId,projectId,...body})=>({method:"POST",tenantId,path:seriesPath(projectId,group,...suffix),body});var seriesStandardOperations={"series.list":operation(SeriesStandardListSchema,SeriesStandardPageSchema,i=>({method:"GET",tenantId:i.tenantId,path:seriesPath(i.projectId),query:{after:i.after,limit:i.limit}})),"series.get":operation(SeriesStandardQuerySchema,SeriesStandardVersionSchema,i=>({method:"GET",tenantId:i.tenantId,path:seriesPath(i.projectId,i.seriesId),query:{version:i.version}}),[["seriesId","seriesId"],["version","version"]]),"series.publish":operation(PublishSeriesStandardSchema,PublishSeriesStandardReceiptSchema,({tenantId,projectId,...body})=>({method:"POST",tenantId,path:seriesPath(projectId),body}),[["seriesId","standard.seriesId"],["idempotencyKey","idempotencyKey"],["brand.ownerProjectId","standard.brand.ownerProjectId"],["brand.brandId","standard.brand.brandId"],["brand.version","standard.brand.version"],["brand.grantId","standard.brand.grantId"],["brand.variantId","standard.brand.variantId"],["brand.selectedClaimIds","standard.brand.selectedClaimIds"]]),"series.bind":operation(BindSeriesStandardSchema,BindSeriesStandardReceiptSchema,({tenantId,projectId,...body})=>({method:"POST",tenantId,path:seriesPath(projectId,"bindings"),body}),[["seriesId","binding.standard.seriesId"],["version","binding.standard.version"],["characterVariantIds","binding.characterVariantIds"],["idempotencyKey","idempotencyKey"]]),"series.binding":operation(ProductionSeriesQuerySchema,ProductionSeriesBindingSchema,i=>({method:"GET",tenantId:i.tenantId,path:seriesPath(i.projectId,"bindings",i.productionId),query:{productionRevision:i.productionRevision,atRevision:i.atRevision}}),[["productionRevision","productionRevision"]]),"series.receipt":operation(SeriesStandardReceiptQuerySchema,SeriesStandardReceiptSchema,({tenantId,projectId,idempotencyKey:idempotencyKey2})=>({method:"POST",tenantId,path:seriesPath(projectId,"receipts","query"),body:{idempotencyKey:idempotencyKey2}}),[["idempotencyKey","idempotencyKey"]],{readOnly:true}),"series.canon.record":operation(RecordSeriesCanonSchema,SeriesCanonSchema,seriesPost("canon","record"),[["idempotencyKey","idempotencyKey"],["seriesId","seriesId"],["branchId","branchId"],["bindingRevision","bindingRevision"],["seriesVersion","seriesVersion"],["relation","relation"]]),"series.canon.get":operation(SeriesCanonQuerySchema,SeriesCanonSchema,seriesPost("canon","query"),[["seriesId","seriesId"],["branchId","branchId"],["ordinal","ordinal"]],{readOnly:true}),"series.canon.receipt":operation(SeriesCanonReceiptQuerySchema,SeriesCanonSchema,seriesPost("canon","receipts","query"),[["idempotencyKey","idempotencyKey"]],{readOnly:true}),"series.improvement.command":operation(SeriesImprovementCommandSchema,SeriesImprovementReceiptSchema,seriesPost("improvements","commands"),[["action","action"],["seriesId","seriesId"],["proposalId","proposalId"],["idempotencyKey","idempotencyKey"],["baseVersion","proposal.baseVersion"]]),"series.improvement.query":operation(SeriesImprovementQuerySchema,SeriesImprovementViewSchema,seriesPost("improvements","query"),[["action","action"],["seriesId","seriesId"],["proposalId","proposalId"]],{readOnly:true}),"series.improvement.receipt":operation(SeriesImprovementReceiptQuerySchema,SeriesImprovementReceiptSchema,seriesPost("improvements","receipts","query"),[["idempotencyKey","idempotencyKey"]],{readOnly:true})};function improvementResponseMatches(value2){const root=value2;const sameScope=item=>item.tenantId===root.tenantId&&item.projectId===root.projectId&&item.seriesId===root.seriesId;if(root.action==="LIST")return root.items.every(sameScope);const{proposal,decision}=root;return sameScope(proposal)&&proposal.proposalId===root.proposalId&&(root.action==="GET"||(root.action==="PROPOSE"?decision===null:decision?.action===root.action))&&(!decision||sameScope(decision)&&decision.proposalId===proposal.proposalId&&(decision.action==="DECLINE"||sameScope(decision.published)&&decision.published.version===proposal.baseVersion+1))}function assertSeriesResponseVersions(operation2,input,result){if(operation2==="series.binding"&&typeof input.atRevision==="number"){if(result.productionRevision<=input.atRevision)return;throw new NativeStudioSdkError("RESPONSE_SCOPE_MISMATCH","INTERNAL_OPERATIONAL_FAILURE","NO_WRITE")}if(operation2==="series.publish"){const receipt=result;if(receipt.standard.version===Number(input.expectedVersion)+1)return}else if(operation2==="series.bind"){const{binding}=result;if(binding.productionRevision===Number(input.expectedProductionRevision)+1&&binding.profileVersion===Number(input.expectedProfileVersion)+1)return}else if(operation2==="series.canon.record"){if(result.ordinal===Number(input.expectedHeadOrdinal)+1)return}else if(operation2.startsWith("series.improvement.")){if(improvementResponseMatches(result))return;if(operation2!=="series.improvement.command")throw new NativeStudioSdkError("RESPONSE_SCOPE_MISMATCH","INTERNAL_OPERATIONAL_FAILURE","NO_WRITE")}else return;throw new NativeStudioSdkError("RESPONSE_SCOPE_MISMATCH","INTERNAL_OPERATIONAL_FAILURE","UNKNOWN")}function brandRequest(suffix){return({tenantId,projectId,...body})=>({method:"POST",tenantId,path:path("projects",projectId,"series-standards","brand",...suffix),body})}var enterpriseBrandOperations={"series.brand.command":operation(EnterpriseBrandCommandSchema,EnterpriseBrandReceiptSchema,brandRequest(["commands"]),[["action","action"],["idempotencyKey","idempotencyKey"]]),"series.brand.get":operation(EnterpriseBrandQuerySchema,EnterpriseBrandViewSchema,brandRequest(["query"]),[["action","action"]],{readOnly:true}),"series.brand.receipt":operation(EnterpriseBrandReceiptQuerySchema,EnterpriseBrandReceiptSchema,brandRequest(["receipts","query"]),[["idempotencyKey","idempotencyKey"]],{readOnly:true})};var sameUuid=(left,right)=>typeof right==="string"&&left.toLowerCase()===right.toLowerCase();function assertEnterpriseBrandResponse(key10,input,value2){if(!Object.hasOwn(enterpriseBrandOperations,key10))return;const output=value2;const owner="publication"in output?output.publication:output.grant;const ownerProjectId=input.ownerProjectId??input.projectId;const variantIds=Array.isArray(input.variantIds)?input.variantIds:void 0;const grantMatches=!("grant"in output)||(input.grantId===void 0||sameUuid(output.grant.grantId,input.grantId))&&(input.consumerProjectId===void 0||sameUuid(output.grant.consumerProjectId,input.consumerProjectId))&&(input.expiresAt===void 0||output.grant.expiresAt===input.expiresAt)&&(!variantIds||output.grant.variantIds.length===variantIds.length&&output.grant.variantIds.every((id15,index)=>sameUuid(id15,variantIds[index])))&&(key10!=="series.brand.command"||output.grant.revokedAt!==null===(output.action==="REVOKE"))&&(key10!=="series.brand.get"||sameUuid(output.grant.projectId,input.projectId)||sameUuid(output.grant.consumerProjectId,input.projectId));const valid=sameUuid(owner.tenantId,input.tenantId)&&sameUuid(owner.projectId,ownerProjectId)&&(input.brandId===void 0||sameUuid(owner.brandId,input.brandId))&&(input.version===void 0||owner.version===input.version)&&(input.expectedVersion===void 0||owner.version===Number(input.expectedVersion)+1)&&grantMatches&&(output.action!=="PUBLICATION"||sameUuid(owner.projectId,input.projectId)||typeof output.grantId==="string"&&sameUuid(output.grantId,input.grantId));if(!valid)throw new NativeStudioSdkError("RESPONSE_SCOPE_MISMATCH","INTERNAL_OPERATIONAL_FAILURE",key10==="series.brand.command"?"UNKNOWN":"NO_WRITE")}import{createHash as createHash11}from"node:crypto";import{z as z206}from"zod";var render=RoughCutGetSchema.omit({tenantId:true});var mediaInput=z206.discriminatedUnion("kind",[AudioGetSchema.omit({tenantId:true}).extend({kind:z206.literal("AUDIO")}),CaptionExportSchema.omit({tenantId:true}).extend({kind:z206.literal("CAPTION")}),ArtifactDiscoveryMediaSchema.omit({tenantId:true}).extend({kind:z206.literal("DISCOVERED_ARTIFACT"),contentType:DiscoveryContentTypeSchema}),AudioGetSchema.omit({tenantId:true}).extend({kind:z206.literal("AUDIO_WAV")}),CaptionGetSchema.omit({tenantId:true}).extend({kind:z206.enum(["CAPTION_JSON","CAPTION_SRT"])}),TemporalEvidenceGetSchema.omit({tenantId:true}).extend({kind:z206.literal("TEMPORAL_FRAME"),ordinal:z206.int().nonnegative().max(63)}),TemporalEvidenceGetSchema.omit({tenantId:true}).extend({kind:z206.enum(["TEMPORAL_SHEET","TEMPORAL_MANIFEST"])}),VideoGetInputSchema.omit({tenantId:true}).extend({kind:z206.enum(["VIDEO_GENERATION","VIDEO_GENERATION_POSTER"])}),render.extend({kind:z206.literal("CODE_VIDEO")}),render.extend({kind:z206.enum(["ROUGH_CUT_VIDEO","ROUGH_CUT_POSTER","FINAL_VIDEO","FINAL_POSTER"])}),TimelineScopeSchema.omit({tenantId:true}).extend({kind:z206.literal("DELIVERED_VIDEO")}),DeliveryManifestGetSchema.omit({tenantId:true}).extend({kind:z206.literal("DELIVERY_MANIFEST")})]);var expectedInput=z206.strictObject({checksumSha256:z206.string().regex(/^[0-9a-f]{64}$/),byteSize:z206.int().positive().max(128*1024*1024).optional()});async function readNativeMedia(transport,tenantId,raw,expected,options){if(!raw||raw.tenantId!==void 0&&(typeof raw.tenantId!=="string"||raw.tenantId.toLowerCase()!==tenantId.toLowerCase()))sdkInputError();const parsed=mediaInput.safeParse(Object.fromEntries(Object.entries(raw).filter(([key10])=>key10!=="tenantId"))),identity6=expectedInput.safeParse({checksumSha256:expected?.checksumSha256,byteSize:expected?.byteSize});if(!parsed.success||!identity6.success)sdkInputError();const input=parsed.data;let suffix,contentType;if(input.kind==="DISCOVERED_ARTIFACT"){suffix=[];contentType=input.contentType}else if(input.kind==="AUDIO"||input.kind==="AUDIO_WAV"){suffix=["audio",input.purpose,"versions",input.versionId,"export"];contentType="audio/wav"}else if("versionId"in input){suffix=["captions","versions",input.versionId,"export"];contentType=(input.kind==="CAPTION"?input.format==="JSON":input.kind==="CAPTION_JSON")?"application/json":"application/x-subrip"}else if("evidenceId"in input){const kind=input.kind==="TEMPORAL_FRAME"?"FRAME":input.kind==="TEMPORAL_SHEET"?"SHEET":"MANIFEST";if(!TemporalEvidenceMediaSchema.safeParse({tenantId,productionId:input.productionId,evidenceId:input.evidenceId,kind,...input.kind==="TEMPORAL_FRAME"?{ordinal:input.ordinal}:{}}).success)sdkInputError();suffix=["temporal-evidence",input.evidenceId,"media",kind];contentType=kind==="MANIFEST"?"application/json":"image/png"}else if("generationId"in input){suffix=["video-generations",input.generationId,input.kind==="VIDEO_GENERATION"?"media":"poster"];contentType=input.kind==="VIDEO_GENERATION"?"video/mp4":"image/png"}else if(input.kind==="DELIVERED_VIDEO"){suffix=["deliveries","media"];contentType="video/mp4"}else if(input.kind==="CODE_VIDEO"){suffix=["compositions","renders",input.renderId,"media"];contentType="video/mp4"}else if(input.kind==="DELIVERY_MANIFEST"){suffix=["deliveries","manifests",input.manifestId,"download"];contentType="application/json"}else{const poster2=input.kind.endsWith("POSTER");suffix=[input.kind.startsWith("ROUGH_CUT")?"rough-cuts":"final-renders",input.renderId,poster2?"poster":"media"];contentType=poster2?"image/png":"video/mp4"}const result=await transport.binary({method:"GET",tenantId,path:input.kind==="DISCOVERED_ARTIFACT"?path("projects",input.projectId,"artifacts",input.artifactId,"representations",input.representationId,"media"):path("productions",input.productionId,...suffix),...input.kind==="TEMPORAL_FRAME"?{query:{ordinal:input.ordinal}}:{},...input.kind==="CAPTION"?{query:{format:input.format}}:{},...input.kind==="CAPTION_JSON"||input.kind==="CAPTION_SRT"?{query:{format:input.kind==="CAPTION_JSON"?"JSON":"SRT"}}:{}},[contentType],Math.min(identity6.data.byteSize??128*1024*1024,input.kind==="AUDIO"||input.kind==="AUDIO_WAV"?12582912:input.kind.startsWith("CAPTION")?131072:128*1024*1024),options);const checksumSha256=createHash11("sha256").update(result.bytes).digest("hex");if(checksumSha256!==identity6.data.checksumSha256||identity6.data.byteSize!==void 0&&result.bytes.byteLength!==identity6.data.byteSize||result.etag&&result.etag!==`"${checksumSha256}"`)throw new NativeStudioSdkError("MEDIA_IDENTITY_MISMATCH","INTERNAL_OPERATIONAL_FAILURE","NO_WRITE");return{...result,checksumSha256}}var identity5=TenantMediaDownloadSchema.extend({checksumSha256:LocalDigestSchema,byteSize:MediaObjectVersionSchema.shape.byteSize});async function readImmutableMedia(transport,tenantId,raw,options={}){if(!raw||Object.hasOwn(raw,"tenantId"))sdkInputError();const input=identity5.safeParse({...raw,tenantId});if(!input.success)sdkInputError();const{checksumSha256,byteSize,...scope8}=input.data;const timeout=AbortSignal.timeout(12e4);const signal=options.signal?AbortSignal.any([options.signal,timeout]):timeout;const ticket=await transport.json({method:"POST",readOnly:true,tenantId,path:tenantMediaDownloadPath,body:scope8},MediaObjectTicketSchema,{signal});if(ticket.method!=="GET"||ticket.object.tenantId!==scope8.tenantId||ticket.object.projectId!==scope8.projectId||ticket.object.checksumSha256!==checksumSha256||ticket.object.byteSize!==byteSize)throw new NativeStudioSdkError("MEDIA_IDENTITY_MISMATCH","INTERNAL_OPERATIONAL_FAILURE","NO_WRITE");return{...await downloadImmutableObject(ticket,{signal}),representationId:scope8.representationId}}var nativeFailureCodes=new Set([...NativeToolAuthorityFailureSchema.shape.error.shape.code.options,...FederationFailureCodeSchema.options,"REQUEST_CONFLICT","HOST_UNAVAILABLE","CREDENTIAL_UNAVAILABLE","CREDENTIAL_SCOPE_MISMATCH","BINDING_REVOKED","UNAUTHENTICATED","FORBIDDEN","NOT_FOUND","INVALID_INPUT","REVISION_CONFLICT","STALE_BASIS","BLOCKED","CAPABILITY_UNAVAILABLE","DEVICE_UNAVAILABLE","CAPABILITY_VERSION_MISMATCH","PROVIDER_UNAVAILABLE","BUDGET_BLOCKED","CANCELLED","SUPERSEDED","INTERNAL_OPERATIONAL_FAILURE","IDEMPOTENCY_CONFLICT","CONTINUITY_CONFLICT","INPUT_UNAVAILABLE","AUDIO_UNAVAILABLE","CAPTION_UNAVAILABLE","TEST_EVIDENCE_DENIED","CONFLICT","INVALID_MEDIA","LEASE_LOST","SOURCE_UNAVAILABLE","TOOL_AUTHORITY_UNAVAILABLE","ACTIVE_EXECUTION_EXISTS","BINDING_UNAVAILABLE","PROVIDER_CAPABILITY_UNAVAILABLE","REPLAY_EXHAUSTED","RESYNC_REQUIRED"]);var statuses={400:["INVALID_INPUT"],413:["INVALID_INPUT"],415:["INVALID_INPUT"],401:["BLOCKED"],403:["BLOCKED"],404:["NOT_FOUND"],409:["REVISION_CONFLICT","STALE_BASIS","BLOCKED","CAPABILITY_UNAVAILABLE","BUDGET_BLOCKED","CANCELLED","SUPERSEDED"],422:["INVALID_INPUT"],429:["BUDGET_BLOCKED","PROVIDER_UNAVAILABLE"]};function failureOutcome(write2,status,declared){if(!write2)return"NO_WRITE";if(declared==="NO_WRITE"||declared==="UNKNOWN"||declared==="REJECTED")return declared;return["INVALID_INPUT","NOT_FOUND","BLOCKED","REVISION_CONFLICT","STALE_BASIS","BUDGET_BLOCKED"].includes(status)?"REJECTED":"UNKNOWN"}async function nativeFailure(response,signal){try{if(response.headers.get("content-type")?.split(";")[0]?.trim()!=="application/json")return null;const bytes=await boundedResponseBytes(response,64*1024,signal);const raw=JSON.parse(new TextDecoder("utf-8",{fatal:true}).decode(bytes));if(!raw||typeof raw!=="object"||Array.isArray(raw))return null;const record=raw;const status=InterfaceSemanticStatusSchema.safeParse(record.semanticStatus);if(!status.success||!(statuses[response.status]??(response.status>=500?["INTERNAL_OPERATIONAL_FAILURE","PROVIDER_UNAVAILABLE","CAPABILITY_UNAVAILABLE"]:[])).includes(status.data))return null;const error=record.error;const code=error?.code;const mismatch2=capabilityMismatch(code,status.data,error?.details);const known=typeof code==="string"&&nativeFailureCodes.has(code)&&(code!=="CAPABILITY_VERSION_MISMATCH"||!!mismatch2);return{semanticStatus:status.data,code:known?code:status.data,mismatch:mismatch2,outcome:error&&typeof error==="object"&&!Array.isArray(error)&&(known||error.outcome==="UNKNOWN")?error.outcome:void 0}}catch{return null}finally{void response.body?.cancel().catch(()=>{})}}function capabilityMismatch(code,status,detail){if(code==="CAPABILITY_VERSION_MISMATCH"&&status==="CAPABILITY_UNAVAILABLE")return CapabilityVersionMismatchSchema.safeParse(detail).data}var NativeStudioHttpTransport=class{constructor(config){this.config=config;try{this.origin=new URL(config.baseUrl);if(this.origin.username||this.origin.password||this.origin.search||this.origin.hash||this.origin.pathname!=="/"||this.origin.protocol!=="https:"&&!(this.origin.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(this.origin.hostname)))sdkInputError()}catch{sdkInputError()}this.timeout=config.timeoutMs??3e4;this.jsonLimit=config.maxJsonBytes??18*1024*1024;if(!Number.isSafeInteger(this.timeout)||this.timeout<1||this.timeout>3e5||!Number.isSafeInteger(this.jsonLimit)||this.jsonLimit<1024||this.jsonLimit>32*1024*1024)sdkInputError()}config;origin;timeout;jsonLimit;async response(request,options){const write2=request.method==="POST"&&!request.readOnly;if(!request.path.startsWith("/v1/")||request.path.includes("?")||request.path.includes("#")||request.path.includes(".."))sdkInputError();const url=new URL(request.path,this.origin);if(url.origin!==this.origin.origin||!url.pathname.startsWith("/v1/")||!["GET","POST"].includes(request.method)||!TenantIdSchema.safeParse(request.tenantId).success)sdkInputError();for(const[key10,value2]of Object.entries(request.query??{}))if(value2!==void 0)url.searchParams.set(key10,String(value2));let body;try{if(request.importedVideo){const v=request.importedVideo;if(request.method!=="POST"||request.body!==void 0||!/^\/v1\/productions\/[a-f0-9-]{36}\/imported-visuals\/originals\/bytes$/i.test(request.path)||!(v.bytes instanceof Uint8Array)||v.bytes.length<32||v.bytes.length>128*1024*1024||!/^[A-Za-z0-9_-]+$/.test(v.metadata)||v.metadata.length>8192)sdkInputError();body=new Uint8Array(v.bytes)}else body=request.body===void 0?void 0:JSON.stringify(request.body);if(typeof body==="string"&&new TextEncoder().encode(body).byteLength>18*1024*1024)sdkInputError()}catch{sdkInputError()}const timeout=AbortSignal.timeout(this.timeout);const signal=options.signal?AbortSignal.any([options.signal,timeout]):timeout;if(signal.aborted)throw new NativeStudioSdkError("REQUEST_ABORTED","BLOCKED","NO_WRITE");let authorization;if(request.authentication==="runtime-proof"){if(request.method!=="POST"||!/^\/v1\/projects\/[0-9a-f-]{36}\/(?:native-tool-grants\/[0-9a-f-]{36}\/(?:proof|status)|productions\/[0-9a-f-]{36}\/native-tool-credentials\/exchange)$/.test(request.path))sdkInputError()}else{try{authorization=await abortable(Promise.resolve().then(()=>this.config.authorization(signal)),signal)}catch{throw new NativeStudioSdkError(signal.aborted?"REQUEST_ABORTED":"UNAUTHENTICATED","BLOCKED","NO_WRITE")}if(typeof authorization!=="string"||!/^Bearer [A-Za-z0-9._~+/-]+={0,2}$/.test(authorization)||authorization.length>16384)throw new NativeStudioSdkError("UNAUTHENTICATED","BLOCKED","NO_WRITE")}if(signal.aborted)throw new NativeStudioSdkError("REQUEST_ABORTED","BLOCKED","NO_WRITE");try{const pending=Promise.resolve().then(()=>(this.config.fetch??fetch)(url,{method:request.method,redirect:"error",cache:"no-store",signal,headers:{...authorization===void 0?{}:{authorization},"x-native-tenant-id":request.tenantId,accept:"application/json",...request.body===void 0?{}:{"content-type":"application/json"},...request.importedVideo?{"content-type":"video/mp4","x-native-import-metadata":request.importedVideo.metadata}:{}},...body===void 0?{}:{body}}));void pending.then(late=>{if(signal.aborted)void late.body?.cancel().catch(()=>{})},()=>{});const response=await abortable(pending,signal);if(!response.ok){const status=response.status;const native=await nativeFailure(response,signal);const code=status===401?"UNAUTHENTICATED":status===403?"FORBIDDEN":status===404?"NOT_FOUND":status===400||status===413||status===415||status===422?"INVALID_INPUT":status===409?"REVISION_CONFLICT":"HTTP_FAILURE";const semanticStatus=status===401||status===403?"BLOCKED":status===404?"NOT_FOUND":status===400||status===413||status===415||status===422?"INVALID_INPUT":status===409?"REVISION_CONFLICT":"INTERNAL_OPERATIONAL_FAILURE";throw new NativeStudioSdkError(native?.code??code,native?.semanticStatus??semanticStatus,failureOutcome(write2,native?.semanticStatus??semanticStatus,native?.outcome),status,[],native?.mismatch)}return{response,signal}}catch(error){if(error instanceof NativeStudioSdkError)throw error;throw new NativeStudioSdkError(write2?"OUTCOME_UNKNOWN":signal.aborted?"REQUEST_ABORTED":"TRANSPORT_UNAVAILABLE","INTERNAL_OPERATIONAL_FAILURE",write2?"UNKNOWN":"NO_WRITE")}}async json(request,schema,options={}){const limit=options.maxJsonBytes??this.jsonLimit;if(!Number.isSafeInteger(limit)||limit<1024||limit>this.jsonLimit)sdkInputError();const{response,signal}=await this.response(request,options);try{const contentType=response.headers.get("content-type")?.split(";")[0]?.trim();if(contentType!=="application/json"){void response.body?.cancel().catch(()=>{});throw new Error}const bytes=await boundedResponseBytes(response,limit,signal);return schema.parse(JSON.parse(new TextDecoder("utf-8",{fatal:true}).decode(bytes)))}catch(error){if(error instanceof NativeStudioSdkError)throw new NativeStudioSdkError(error.code,error.semanticStatus,request.method==="POST"&&!request.readOnly?"UNKNOWN":"NO_WRITE",error.status);throw new NativeStudioSdkError("RESPONSE_INVALID","INTERNAL_OPERATIONAL_FAILURE",request.method==="POST"&&!request.readOnly?"UNKNOWN":"NO_WRITE")}}async binary(request,contentTypes,limit,options={}){if(request.method!=="GET"||!Number.isSafeInteger(limit)||limit<1||limit>128*1024*1024)sdkInputError();const{response,signal}=await this.response(request,options);const contentType=response.headers.get("content-type")?.split(";")[0]?.trim()??"";if(!contentTypes.includes(contentType)){await response.body?.cancel().catch(()=>{});throw new NativeStudioSdkError("RESPONSE_INVALID","INTERNAL_OPERATIONAL_FAILURE","NO_WRITE")}try{return{bytes:await boundedResponseBytes(response,limit,signal),contentType,etag:response.headers.get("etag")}}catch(error){throw new NativeStudioSdkError(error instanceof NativeStudioSdkError?error.code:signal.aborted?"REQUEST_ABORTED":"RESPONSE_INVALID","INTERNAL_OPERATIONAL_FAILURE","NO_WRITE")}}};var sdkOperations=Object.freeze({...coreOperations,...deviceManagementOperations,...deviceLibraryOperations,...navigationOperations,...discoveryOperations,...agentHostOperations,...agentHostExecutionOperations,...nativeToolAuthorityOperations,...compositionOperations,...assemblyOperations,...editorOperations,...reviewerOperations,...repairStrategyOperations,...canonicalRepairOperations,...programmaticReviewOperations,...compositionSourceOperations,...programmaticExplorationOperations,...deliveryOperations,...shotPreparationOperations,...generationOperations,...keyframeReviewOperations,...videoReviewOperations,...providerOperations,...speechOperations,...voiceProfileOperations,...shareOperations,...voiceReviewOperations,...observationOperations,...soundMakingPlanOperations,...lifecycleEventOperations,...federationOperations,...temporalEvidenceOperations,...audioCaptionOperations,...planningIntelligenceOperations,...importedVisualOperations,...sourceSyncOperations,...visualExplorationOperations,...referencePreviewOperations,...mediaDescriptorOperations,...seriesStandardOperations,...enterpriseBrandOperations});var NativeStudioAgentClient=class{deviceRenders=new NativeStudioDeviceRenders(this);navigation=new NativeStudioNavigationFacade(this);tenantId;directSources;transport;constructor(config){const tenant2=TenantIdSchema.safeParse(config.tenantId);if(!tenant2.success)sdkInputError();this.tenantId=tenant2.data.toLowerCase();this.transport=new NativeStudioHttpTransport(config);this.directSources=new NativeStudioDirectSources(this.tenantId,this.transport)}async call(key10,raw,options={}){if(!Object.hasOwn(sdkOperations,key10)||!raw||typeof raw!=="object"||Array.isArray(raw))sdkInputError();if(raw.tenantId!==void 0&&(typeof raw.tenantId!=="string"||raw.tenantId.toLowerCase()!==this.tenantId))sdkInputError();const spec=sdkOperations[key10];if(spec.request===null)throw new NativeStudioSdkError("CAPABILITY_UNAVAILABLE","CAPABILITY_UNAVAILABLE","NO_WRITE");const parsed=spec.input.safeParse({...raw,tenantId:this.tenantId});if(!parsed.success)sdkInputError(inputIssues(parsed.error,spec.input));if((key10==="rough-cut.start"||key10==="final-render.start")&&"deviceExecution"in parsed.data&&DeviceRenderTargetSchema.safeParse(parsed.data.deviceExecution).data?.validationMode){try{const advertised=await this.transport.json({method:"GET",tenantId:this.tenantId,path:path("local-execution","tenant-media","capabilities")},TenantMediaCapabilitySchema,options);if(advertised.tenantId!==this.tenantId)throw Error()}catch{throw new NativeStudioSdkError("CAPABILITY_UNAVAILABLE","BLOCKED","NO_WRITE")}}const request=spec.request(parsed.data);const result=await this.transport.json({...request,readOnly:spec.readOnly},spec.output,options);assertManagementReceipt(key10,parsed.data,result);assertResponseBindings(result,parsed.data,spec.identity,spec.readOnly?"GET":request.method,spec.expectedPath?spec.expectedPath(parsed.data,result):void 0,spec.identityWhenPresent);assertSeriesResponseVersions(key10,parsed.data,result);assertEnterpriseBrandResponse(key10,parsed.data,result);if(key10==="temporal-evidence.read-video")assertOriginalVideoBytes(result);if(key10==="reference-preview.get")assertPreviewBytes(result);if(key10==="source-sync.audio"||key10==="audio.export"||key10==="caption.export")assertExportBytes(result,key10==="caption.export"&&"format"in parsed.data?String(parsed.data.format):void 0);return result}async sourceMedia(raw,options={},expected){if(Object.hasOwn(raw,"tenantId"))sdkInputError();const parsed=SourceLibraryMediaSchema.safeParse({...raw,tenantId:this.tenantId});if(!parsed.success)sdkInputError();const input=parsed.data;const result=await this.transport.binary({method:"GET",tenantId:this.tenantId,path:path("projects",input.projectId,"source-artifacts",input.artifactId,"media")},["image/png","image/jpeg","image/webp","text/plain","application/json"],8*1024*1024,options);const checksumSha256=createHash12("sha256").update(result.bytes).digest("hex");if(result.etag&&result.etag!==`"${checksumSha256}"`||expected&&(expected.checksumSha256!==checksumSha256||expected.byteSize!==result.bytes.byteLength))throw new NativeStudioSdkError("MEDIA_IDENTITY_MISMATCH","INTERNAL_OPERATIONAL_FAILURE","NO_WRITE");return{...result,checksumSha256}}media(input,expected,options={}){return readNativeMedia(this.transport,this.tenantId,input,expected,options)}immutableMedia(input,options={}){return readImmutableMedia(this.transport,this.tenantId,input,options)}async keyframeMedia(raw,expected,options={}){if(!raw||Object.hasOwn(raw,"tenantId")||!/^[a-f0-9]{64}$/.test(expected?.checksumSha256??"")||expected?.byteSize!==void 0&&(!Number.isSafeInteger(expected.byteSize)||expected.byteSize<1||expected.byteSize>8*1024*1024))sdkInputError();const parsed=KeyframeGetInputSchema.safeParse({...raw,tenantId:this.tenantId});if(!parsed.success)sdkInputError();const i=parsed.data,value2=await this.transport.json({method:"GET",tenantId:this.tenantId,path:path("productions",i.productionId,"keyframe-generations",i.generationId,"media")},KeyframeMediaSchema,options);const bytes=Buffer.from(value2.contentBase64,"base64"),checksumSha256=createHash12("sha256").update(bytes).digest("hex");if(bytes.toString("base64")!==value2.contentBase64||bytes.length!==value2.byteSize||checksumSha256!==value2.checksumSha256||checksumSha256!==expected.checksumSha256||expected.byteSize!==void 0&&bytes.length!==expected.byteSize)throw new NativeStudioSdkError("MEDIA_IDENTITY_MISMATCH","INTERNAL_OPERATIONAL_FAILURE","NO_WRITE");return{bytes,checksumSha256,contentType:value2.contentType}}};function schemaNode(value2,root){if(root.$schema!==void 0&&root.$schema!=="https://json-schema.org/draft/2020-12/schema")return null;const seen=new Set;const scoped=node=>["$id","$anchor","$dynamicAnchor","$dynamicRef","$recursiveAnchor","$recursiveRef","$vocabulary"].some(key10=>key10 in node);while(value2&&typeof value2==="object"&&!Array.isArray(value2)){const node=value2;if(scoped(node))return null;if("$ref"in node&&typeof node.$ref!=="string")return null;if(typeof node.$ref!=="string")return node;if(seen.has(value2)||!node.$ref.startsWith("#/"))return null;seen.add(value2);let target3=root;for(const part of node.$ref.slice(2).split("/")){const key10=part.replaceAll("~1","/").replaceAll("~0","~");if(!target3||typeof target3!=="object"||!Object.hasOwn(target3,key10))return null;if(scoped(target3))return null;target3=target3[key10]}value2=target3}return null}import{z as z207}from"zod";var definitions=new WeakMap;function inputDefinition(name2,input){let names=definitions.get(input);if(!names){names=new Map;definitions.set(input,names)}let definition=names.get(name2);if(!definition){try{definition={name:name2,inputSchema:z207.toJSONSchema(input,{io:"input",reused:"ref"})};if(Buffer.byteLength(JSON.stringify(definition))>160*1024)throw Error()}catch{throw new NativeStudioSdkError("CAPABILITY_UNAVAILABLE","BLOCKED","NO_WRITE")}names.set(name2,definition)}return definition}import{createHash as createHash13}from"node:crypto";import{z as z208}from"zod";var Input=z208.discriminatedUnion("kind",[KeyframeGetInputSchema.extend({kind:z208.literal("KEYFRAME")}),VideoGetInputSchema.extend({kind:z208.literal("VIDEO_POSTER")}),RoughCutGetSchema.extend({kind:z208.enum(["ROUGH_CUT_POSTER","FINAL_POSTER"])})]);var sdkImageMediaTools={KEYFRAME:"keyframe_media",VIDEO_POSTER:"video_poster",ROUGH_CUT_POSTER:"rough_cut_poster",FINAL_POSTER:"final_render_poster"};var Identity=z208.strictObject({checksumSha256:z208.string().regex(/^[0-9a-f]{64}$/),byteSize:z208.int().positive().max(16*1024*1024).optional()});var Metadata=KeyframeMediaSchema.omit({contentBase64:true});async function readMcpImageMedia(config,raw,expected,options){if(!raw||raw.tenantId!==void 0&&(typeof raw.tenantId!=="string"||raw.tenantId.toLowerCase()!==config.tenantId))sdkInputError();const input=Input.safeParse({...raw,tenantId:config.tenantId}),identity6=Identity.safeParse(expected);if(!input.success||!identity6.success)sdkInputError();const{kind,...argumentsInput}=input.data;const timeout=AbortSignal.timeout(config.timeoutMs),signal=options.signal?AbortSignal.any([timeout,options.signal]):timeout;if(signal.aborted)throw new NativeStudioSdkError("REQUEST_ABORTED","BLOCKED","NO_WRITE");let response;try{response=await abortable(config.client.callTool({name:sdkImageMediaTools[kind],arguments:argumentsInput},{signal,timeout:config.timeoutMs,nativeReadOnly:true}),signal)}catch{throw new NativeStudioSdkError(signal.aborted?"REQUEST_ABORTED":"TRANSPORT_UNAVAILABLE","INTERNAL_OPERATIONAL_FAILURE","NO_WRITE")}try{if(Buffer.byteLength(JSON.stringify(response),"utf8")>config.maxJsonBytes)throw Error();const envelope=z208.object({semanticStatus:InterfaceSemanticStatusSchema,data:z208.unknown().optional(),error:z208.object({code:z208.string()}).optional()}).parse(response.structuredContent);if(response.isError||envelope.semanticStatus!=="SUCCESS"){const status=["SUCCESS","ACCEPTED"].includes(envelope.semanticStatus)?"INTERNAL_OPERATIONAL_FAILURE":envelope.semanticStatus;throw new NativeStudioSdkError(envelope.error&&nativeFailureCodes.has(envelope.error.code)?envelope.error.code:status,status,"NO_WRITE")}const metadata=Metadata.parse(envelope.data),images=response.content.filter(c=>c.type==="image");if(images.length!==1||response.content.length!==1)throw Error();const block=images[0],bytes=Buffer.from(block.data,"base64"),checksumSha256=createHash13("sha256").update(bytes).digest("hex");if(bytes.toString("base64")!==block.data||bytes.length!==metadata.byteSize||block.mimeType!==metadata.contentType||checksumSha256!==metadata.checksumSha256||checksumSha256!==identity6.data.checksumSha256||identity6.data.byteSize!==void 0&&bytes.length!==identity6.data.byteSize)throw new NativeStudioSdkError("MEDIA_IDENTITY_MISMATCH","INTERNAL_OPERATIONAL_FAILURE","NO_WRITE");return{...metadata,bytes}}catch(error){if(error instanceof NativeStudioSdkError)throw error;throw new NativeStudioSdkError("RESPONSE_INVALID","INTERNAL_OPERATIONAL_FAILURE","NO_WRITE")}}var sdkMcpTools=Object.freeze({"series.list":"series_list","series.get":"series_get","series.publish":"series_publish","series.bind":"series_bind","series.binding":"series_binding","series.receipt":"series_receipt","series.brand.command":"series_brand_command","series.brand.get":"series_brand_get","series.brand.receipt":"series_brand_receipt","series.canon.record":"series_canon_record","series.canon.get":"series_canon_get","series.canon.receipt":"series_canon_receipt","series.improvement.command":"series_improvement_command","series.improvement.query":"series_improvement_query","series.improvement.receipt":"series_improvement_receipt","federation.link.receiver":"federation_link_receiver","federation.link.targets":"federation_link_targets","federation.link.start":"federation_link_start","federation.link.get":"federation_link_get","federation.link.confirm":"federation_link_confirm","federation.link.cancel":"federation_link_cancel","federation.delivery.inspect":"federation_delivery_inspect","federation.receipt-inbound.configure":"federation_receipt_inbound_configure","federation.receipt-inbound.contract":"federation_receipt_inbound_contract","federation.receipt-inbound.handoff":"federation_receipt_inbound_handoff","federation.receipt-inbound.catalog":"federation_receipt_inbound_catalog","federation.receipt-inbound.query":"federation_receipt_inbound_query","federation.receipt-inbound.command":"federation_receipt_inbound_command","federation.catalog":"federation_catalog","federation.event-definitions":"federation_event_definitions","federation.observe":"federation_observe","federation.result.reference":"federation_result_reference","federation.result.read":"federation_result_read","federation.receipt-route.configure":"federation_receipt_route_configure","federation.receipt.query":"federation_receipt_query","federation.receipt.command":"federation_receipt_command","federation.receipt.recover":"federation_receipt_recover","federation.subscription.handoff":"federation_subscription_handoff","federation.subscription.contract":"federation_subscription_contract","federation.inbound.catalog":"federation_inbound_catalog","federation.inbound.configure":"federation_inbound_configure","federation.inbound.query":"federation_inbound_query","federation.inbound.signals":"federation_inbound_signals","federation.inbound.signal-changes":"federation_inbound_signal_changes","federation.inbound.receipt":"federation_inbound_receipt","federation.inbound.replay":"federation_inbound_replay","federation.recover":"federation_recover","federation.route.configure":"federation_route_configure","federation.subscription.set":"federation_subscription_set","federation.subscription.get":"federation_subscription_get","federation.query":"federation_query","federation.receipt":"federation_receipt","workspace.devices.list":"workspace_devices_list","device.status":"device_status","device.enroll":"device_enroll","device.enrollment.issue":"device_enrollment_issue","device.enrollment.lookup":"device_enrollment_lookup","device.revoke":"device_revoke","device.management-receipt":"device_management_receipt","workspace.get":"workspace_get","workspace.caller":"workspace_caller","workspace.status":"workspace_status","workspace.query":"workspace_query","device-library.query":"device_library_query","device-library.admit":"device_library_admit","device-library.receipt":"device_library_receipt","devices.list":"list_devices","studio.capability.groups":"studio_capability_groups","studio.capability.query":"studio_capability_query","studio.capability.invoke":"studio_capability_invoke","studio.start":"studio_start","studio.media.readiness":"studio_media_readiness","studio.capability.search":"studio_capability_search","studio.capability.describe":"studio_capability_describe","studio.navigate":"studio_navigate","sound-plan.context":"sound_plan_context","sound-plan.get":"sound_plan_get","sound-plan.validate":"sound_plan_validate","sound-plan.accept":"sound_plan_accept","media-observation.options":"media_observation_options","media-observation.start":"media_observation_start","media-observation.start-local":"media_observation_start_local","media-observation.get-local":"media_observation_get_local","media-observation.device.quote":"media_observation_device_quote","media-observation.device.start":"media_observation_device_start","media-observation.device.get":"media_observation_device_get","media-observation.get":"media_observation_get","media-observation.cancel":"media_observation_cancel","production-guidance.context":"production_guidance_context","speech.options":"speech_options","provider.model.get":"provider_model_get","speech.start":"speech_start","speech.device.quote":"speech_device_quote","speech.device.start":"speech_device_start","speech.start-local":"speech_start_local","speech.get-local":"speech_get_local","speech.get":"speech_get","speech.cancel":"speech_cancel","provider.model.query":"provider_model_catalog_query","provider.model.configure":"provider_model_configure","provider.model.disable":"provider_model_disable","artifact.query":"artifact_discovery_query","imported-visual.query":"imported_visual_query","imported-visual.start-from-source":"imported_visual_start_from_source","imported-visual.review.target":"imported_visual_review_target","imported-visual.review.record":"imported_visual_review","source-sync.review.target":"source_sync_review_target","source-sync.review.record":"source_sync_review","source-sync.review.get":"source_sync_review_get","temporal-evidence.read-video":"temporal_evidence_read_video","temporal-evidence.target":"temporal_evidence_target","temporal-evidence.start":"temporal_evidence_start","temporal-evidence.get":"temporal_evidence_get","temporal-evidence.cancel":"temporal_evidence_cancel","visual-sequence.register":"visual_sequence_register","visual-sequence.start-registration":"visual_sequence_start_registration","visual-sequence.get":"visual_sequence_get","visual-sequence.query":"visual_sequence_query","project.create":"project_create","production.create":"production_create","production.terminate":"production_terminate","project.query":"project_query","project.get":"project_get","source.query":"source_query","source.ingest":"source_ingest","source.text":"source_read","production.query":"production_query","production.snapshot":"production_snapshot","brief.accept":"brief_accept","story.accept":"story_accept","scene-shot-plan.accept":"scene_shot_plan_accept","story.query":"story_query","story.active":"story_active","scene-shot-plan.query":"scene_shot_plan_query","scene-shot-plan.active":"scene_shot_plan_active","operation.query":"operation_query","operation.get":"operation_get","agent-host.get":"agent_host_binding_get","agent-host.readiness":"agent_host_readiness","agent-host.history":"agent_host_binding_history","agent-host.configure":null,"agent-host.selection.update":"agent_host_selection_update","agent-host.revoke":"agent_host_binding_revoke","agent-host-execution.start":"agent_host_execution_start","agent-host.contract":"agent_host_contract","agent-host-execution.get":"agent_host_execution_get","agent-host-execution.query":"agent_host_execution_query","agent-host-execution.events":"agent_host_execution_events","agent-host-execution.dispatch":"agent_host_execution_dispatch","agent-host-execution.reconcile":"agent_host_execution_reconcile","agent-host-execution.legacy-release":"agent_host_execution_legacy_release","agent-host-execution.legacy-release.get":"agent_host_execution_legacy_release_get","agent-host-execution.cancel":"agent_host_execution_cancel","native-tool-grant.configure":"native_tool_grant_configure","native-tool-grant.get":"native_tool_grant_get","native-tool-grant.revoke":"native_tool_grant_revoke","composition.capabilities":"composition_capabilities","composition.brief":"composition_brief","composition.put-input":"composition_put_input","composition.making.validate":"composition_making_validate","composition.validate":"composition_validate","composition.create":"composition_create","composition.revise":"composition_revise","composition.get":"composition_get","composition.history":"composition_history","composition.render":"composition_render","composition.render.get":"composition_render_get","composition.render.query":"composition_render_query","composition.render.cancel":"composition_render_cancel","composition.sample":"composition_sample","composition.observe":"composition_observe","timeline.basis":"timeline_basis","timeline.build":"timeline_build","timeline.current":"timeline_current","timeline.get":"timeline_get","timeline.query":"timeline_query","rough-cut.start":"rough_cut_start","rough-cut.admission-receipt":"rough_cut_admission_receipt","rough-cut.get":"rough_cut_get","rough-cut.query":"rough_cut_query","rough-cut.cancel":"rough_cut_cancel","rough-cut.media-ticket":"rough_cut_media_ticket","rough-cut.review.target":"rough_cut_review_target","rough-cut.review.record":"rough_cut_review_record","rough-cut.review.query":"rough_cut_review_query","rough-cut.finding.query":"rough_cut_finding_query","final-ready.get":"final_ready_get","final-ready.decide":"final_ready_decide","final-ready.revoke":"final_ready_revoke","final-ready.query":"final_ready_query","final-render.eligibility":"final_render_eligibility","final-render.start":"final_render_start","final-render.admission-receipt":"final_render_admission_receipt","final-render.get":"final_render_get","final-render.query":"final_render_query","final-render.cancel":"final_render_cancel","final-render.media-ticket":"final_render_media_ticket","editor.context":"editor_context","editor.validate":"editor_validate","reviewer.final-output-context":"reviewer_final_output_context","reviewer.context":"reviewer_context","reviewer.validate":"reviewer_proposal_validate","repair-strategy.review1.context":"repair_strategy_review1_context","repair-strategy.review1.validate":"repair_strategy_review1_validate","repair-strategy.context":"repair_strategy_context","repair-strategy.validate":"repair_strategy_validate","canonical-repair.author":"repair_author","canonical-repair.author-review1":"repair_author_review1","canonical-repair.proof-review1":"repair_proof_review1","canonical-repair.get":"repair_get","canonical-repair.execute":"repair_execute","canonical-repair.proof":"repair_proof","programmatic-review.target":"composition_review_target","programmatic-review.record":"composition_review_record","programmatic-review.query":"composition_review_query","programmatic-review.decide":"composition_acceptance_decide","composition.source.inspect":"composition_source_inspect","reviewer.source-context":"reviewer_source_context","exploration.programmatic.compare":"exploration_programmatic_compare","exploration.programmatic.recommendation.context":"exploration_programmatic_recommendation_context","exploration.programmatic.recommendation.validate":"exploration_programmatic_recommendation_validate","delivery.policy.configure":"delivery_configure","delivery.policy.get":"delivery_policy","delivery.snapshot":"delivery_snapshot","delivery.target":"delivery_target","delivery.start":"delivery_start","delivery.get":"delivery_get","delivery.approve":"delivery_approve","delivery.cancel":"delivery_cancel","delivery.manifest":"delivery_manifest","shot-preparation.prepare":"shot_prepare","shot-preparation.get":"shot_preparation_get","shot-preparation.active":"shot_preparation_active","shot-preparation.query":"shot_preparation_query","keyframe.start":"keyframe_start","keyframe.device.quote":"keyframe_device_quote","keyframe.device.start":"keyframe_device_start","keyframe.get":"keyframe_get","imported-visual.register-source":"imported_visual_register_source","imported-visual.register":"imported_visual_register","imported-visual.revise":"imported_visual_revise","imported-visual.original":"imported_visual_original","imported-visual.history":"imported_visual_history","imported-visual.normalize":"imported_visual_normalize","imported-visual.get":"imported_visual_get","imported-visual.decide":"imported_visual_decide","imported-visual.cancel":"imported_visual_cancel","source-sync.start":"source_sync_start","source-sync.get":"source_sync_get","source-sync.cancel":"source_sync_cancel","source-sync.version":"source_sync_version","exploration.context":"exploration_context","exploration.plan.validate":"exploration_plan_validate","exploration.compare":"exploration_compare","exploration.recommendation.context":"exploration_recommendation_context","exploration.recommendation.validate":"exploration_recommendation_validate","composition.render.media-target":"composition_render_media","delivery.download":"delivery_download","temporal-evidence.download":"temporal_evidence_download","video.options":"video_options","studio.capabilities":"studio_capabilities","reference-preview.start":"reference_preview_start","reference-preview.status":"reference_preview_status","reference-preview.get":"reference_preview_get","reference-preview.cancel":"reference_preview_cancel","brief.active":"brief_active","writer.validate":"writer_proposal_validate","director.context":"director_context","director.validate":"director_proposal_validate","consistency-profile.get":"consistency_profile_get","share.create":"share_create","share.get":"share_get","share.list":"share_list","share.revoke":"share_revoke","share.link":"share_link","share.receipt":"share_receipt","voice-profile.create":"voice_profile_create","voice-profile.revise":"voice_profile_revise","voice-profile.publish":"voice_profile_publish","voice-profile.set-enabled":"voice_profile_set_enabled","voice-profile.list":"voice_profile_list","voice-profile.get":"voice_profile_get","voice-profile.version":"voice_profile_version","voice-profile.set-reference":"voice_profile_set_reference","voice-profile.reference":"voice_profile_reference","voice-review.target":"voice_review_target","voice-review.record":"voice_review_record","voice-review.get":"voice_review_get","consistency-profile.version":"consistency_profile_version","consistency-profile.configure":"consistency_profile_configure","audio.export":"audio_export","caption.export":"caption_export","source-sync.audio":"source_sync_audio","audio.basis":"audio_basis","audio.current":"audio_current","audio.get":"audio_get","audio.query":"audio_query","audio.import":"audio_import","caption.basis":"caption_basis","caption.current":"caption_current","caption.get":"caption_get","caption.query":"caption_query","caption.author":"caption_author","caption.transcript_draft":"caption_transcript_draft","caption.author_transcript":"caption_author_transcript","keyframe.query":"keyframe_query","keyframe.cancel":"keyframe_cancel","video.start":"video_start","video.device.quote":"video_device_quote","video.device.start":"video_device_start","video.get":"video_get","video.query":"video_query","video.cancel":"video_cancel","keyframe-review.target":"keyframe_review_target","keyframe-review.record":"keyframe_review_record","keyframe-review.query":"keyframe_review_query","keyframe-review.decide":"keyframe_reference_decide","keyframe-reference.get":"keyframe_reference_get","keyframe-reference.query":"keyframe_reference_query","keyframe-reference.revoke":"keyframe_reference_revoke","video-review.target":"video_review_target","video-review.record":"video_review_record","video-review.query":"video_review_query","video-review.decide":"shot_acceptance_decide","shot-acceptance.get":"shot_acceptance_get","shot-acceptance.query":"shot_acceptance_query","shot-acceptance.revoke":"shot_acceptance_revoke","provider.configure":null,"provider.query":"provider_connection_query","provider.models":"provider_model_query","provider.keyframe-default.set":"provider_keyframe_default_set","provider.disable":"provider_connection_disable","provider.revoke":"provider_credential_revoke","webhook.configure":null,"webhook.secret.prepare":null,"webhook.configure-reference":"webhook_configure","webhook.disable":"webhook_disable","webhook.replay":"webhook_replay","production.feedback":"production_feedback","production.events.read":"production_events_read","lifecycle-event.capabilities":"lifecycle_events_capabilities","lifecycle-event.subscriptions":"lifecycle_events_query","lifecycle-event.events":"lifecycle_events_query","lifecycle-event.deliveries":"lifecycle_events_query","lifecycle-event.attempts":"lifecycle_events_query"});var nestedScope=new Set(["writer.validate","exploration.context","exploration.plan.validate","exploration.compare","exploration.recommendation.context","exploration.recommendation.validate","director.validate","editor.context","editor.validate","reviewer.final-output-context","reviewer.context","reviewer.validate","reviewer.source-context","repair-strategy.context","repair-strategy.validate","repair-strategy.review1.validate","exploration.programmatic.compare","exploration.programmatic.recommendation.context","exploration.programmatic.recommendation.validate","canonical-repair.author"]);var projectInPath=new Set(["canonical-repair.proof-review1","canonical-repair.get","canonical-repair.execute","canonical-repair.proof"]);function sdkMcpInput(key10,input){return Object.fromEntries(Object.entries(input).filter(([k])=>!(k==="tenantId"&&nestedScope.has(key10))&&!(k==="projectId"&&projectInPath.has(key10))))}import{createHash as createHash14}from"node:crypto";import{z as z209}from"zod";var expectedSchema=z209.strictObject({checksumSha256:z209.string().regex(/^[a-f0-9]{64}$/),byteSize:z209.int().positive().max(16*1024*1024).optional()});async function readMcpEvidenceImage(config,raw,expected,options){if(!raw||raw.tenantId!==void 0&&(typeof raw.tenantId!=="string"||raw.tenantId.toLowerCase()!==config.tenantId))sdkInputError();const input=TemporalEvidenceImageSchema.safeParse({...raw,tenantId:config.tenantId}),identity6=expectedSchema.safeParse({checksumSha256:expected?.checksumSha256,byteSize:expected?.byteSize});if(!input.success||!identity6.success)sdkInputError();const deadline=AbortSignal.timeout(config.timeoutMs),signal=options.signal?AbortSignal.any([options.signal,deadline]):deadline;if(signal.aborted)throw new NativeStudioSdkError("REQUEST_ABORTED","BLOCKED","NO_WRITE");let reply2;try{reply2=await abortable(config.client.callTool({name:"temporal_evidence_read_image",arguments:input.data},{signal,timeout:config.timeoutMs,nativeReadOnly:true}),signal)}catch{throw new NativeStudioSdkError(signal.aborted?"REQUEST_ABORTED":"TRANSPORT_UNAVAILABLE","INTERNAL_OPERATIONAL_FAILURE","NO_WRITE")}try{if(Buffer.byteLength(JSON.stringify(reply2),"utf8")>config.maxJsonBytes)throw Error();const texts=reply2.content.filter(block2=>block2.type==="text"),images=reply2.content.filter(block2=>block2.type==="image");const carrier=reply2.structuredContent!==void 0?reply2.structuredContent:texts.length===1?JSON.parse(texts[0].text):void 0;const envelope=z209.object({semanticStatus:InterfaceSemanticStatusSchema,data:z209.unknown().optional(),error:z209.object({code:z209.string()}).optional()}).parse(carrier);if(reply2.isError)throw new NativeStudioSdkError(envelope.error&&nativeFailureCodes.has(envelope.error.code)?envelope.error.code:envelope.semanticStatus,envelope.semanticStatus==="SUCCESS"||envelope.semanticStatus==="ACCEPTED"?"INTERNAL_OPERATIONAL_FAILURE":envelope.semanticStatus,"REJECTED");if(envelope.semanticStatus!=="SUCCESS"||images.length!==1||(reply2.structuredContent!==void 0?reply2.content.length!==1||texts.length!==0:reply2.content.length!==2||texts.length!==1))throw Error();const metadata=TemporalEvidenceImageMetadataSchema.parse(envelope.data);assertResponseBindings(metadata,input.data,[["evidenceId","evidenceId"],["kind","kind"],["ordinal","ordinal"]],"GET");const block=images[0],bytes=Buffer.from(block.data,"base64"),checksumSha256=createHash14("sha256").update(bytes).digest("hex");if(block.mimeType!==metadata.contentType||bytes.toString("base64")!==block.data||bytes.byteLength!==metadata.byteSize||checksumSha256!==metadata.checksumSha256||checksumSha256!==identity6.data.checksumSha256||identity6.data.byteSize!==void 0&&bytes.byteLength!==identity6.data.byteSize)throw new NativeStudioSdkError("MEDIA_IDENTITY_MISMATCH","INTERNAL_OPERATIONAL_FAILURE","NO_WRITE");return{...metadata,bytes}}catch(e){if(e instanceof NativeStudioSdkError)throw e;throw new NativeStudioSdkError("RESPONSE_INVALID","INTERNAL_OPERATIONAL_FAILURE","NO_WRITE")}}import{createHash as createHash15}from"node:crypto";import{z as z210}from"zod";var inputSchema=z210.discriminatedUnion("kind",[AudioGetSchema.extend({kind:z210.literal("AUDIO_WAV")}),CaptionGetSchema.extend({kind:z210.enum(["CAPTION_JSON","CAPTION_SRT"])}),SourceSyncAudioGetSchema.extend({kind:z210.literal("SOURCE_SYNC_WAV")})]);var expectedSchema2=z210.strictObject({checksumSha256:z210.string().regex(/^[0-9a-f]{64}$/),byteSize:z210.int().positive().max(12582912).optional()});var outputSchema=z210.strictObject({semanticStatus:z210.literal("SUCCESS"),data:z210.strictObject({contentType:z210.enum(["audio/wav","application/json","application/x-subrip"]),checksumSha256:z210.string().regex(/^[0-9a-f]{64}$/),representationId:z210.uuid().optional(),byteSize:z210.int().positive().max(12582912).optional(),contentBase64:z210.string().max(16777216).optional(),text:z210.string().max(131072).optional()})});async function readMcpAuxiliaryMedia(config,raw,expected,options){if(!raw||raw.tenantId!==void 0&&(typeof raw.tenantId!=="string"||raw.tenantId.toLowerCase()!==config.tenantId))sdkInputError();const parsed=inputSchema.safeParse({...raw,tenantId:config.tenantId}),identity6=expectedSchema2.safeParse(expected);if(!parsed.success||!identity6.success)sdkInputError();const{kind,...arguments_}=parsed.data;const name2=kind==="AUDIO_WAV"?"audio_export":kind==="SOURCE_SYNC_WAV"?"source_sync_audio":"caption_export";const contentType=kind.endsWith("WAV")?"audio/wav":kind==="CAPTION_JSON"?"application/json":"application/x-subrip";const deadline=AbortSignal.timeout(config.timeoutMs),signal=options.signal?AbortSignal.any([options.signal,deadline]):deadline;if(signal.aborted)throw new NativeStudioSdkError("REQUEST_ABORTED","BLOCKED","NO_WRITE");let reply2;try{reply2=await abortable(config.client.callTool({name:name2,arguments:{...arguments_,...kind.startsWith("CAPTION")?{format:kind==="CAPTION_JSON"?"JSON":"SRT"}:{}}},{signal,timeout:config.timeoutMs,nativeReadOnly:true}),signal)}catch{throw new NativeStudioSdkError(signal.aborted?"REQUEST_ABORTED":"TRANSPORT_UNAVAILABLE","INTERNAL_OPERATIONAL_FAILURE","NO_WRITE")}try{if(Buffer.byteLength(JSON.stringify(reply2),"utf8")>config.maxJsonBytes||reply2.isError)throw Error();const texts=reply2.content.filter(x=>x.type==="text");const result=outputSchema.parse(reply2.structuredContent??(texts.length===1?JSON.parse(texts[0].text):void 0)).data;const wav=contentType==="audio/wav";if(result.contentType!==contentType||(wav?result.text!==void 0||result.contentBase64===void 0:result.contentBase64!==void 0||result.text===void 0))throw Error();const bytes=wav?Buffer.from(result.contentBase64,"base64"):Buffer.from(result.text,"utf8");const checksumSha256=createHash15("sha256").update(bytes).digest("hex");if(wav&&bytes.toString("base64")!==result.contentBase64||bytes.length>(wav?12582912:131072)||checksumSha256!==result.checksumSha256||checksumSha256!==identity6.data.checksumSha256||result.byteSize!==void 0&&bytes.length!==result.byteSize||identity6.data.byteSize!==void 0&&bytes.length!==identity6.data.byteSize)throw new NativeStudioSdkError("MEDIA_IDENTITY_MISMATCH","INTERNAL_OPERATIONAL_FAILURE","NO_WRITE");return{bytes,contentType,checksumSha256,etag:null}}catch(error){if(error instanceof NativeStudioSdkError)throw error;throw new NativeStudioSdkError("RESPONSE_INVALID","INTERNAL_OPERATIONAL_FAILURE","NO_WRITE")}}import{createHash as createHash16}from"node:crypto";import{z as z211}from"zod";var inputSchema2=z211.discriminatedUnion("kind",[KeyframeGetInputSchema.extend({kind:z211.literal("KEYFRAME")}),VideoGetInputSchema.extend({kind:z211.literal("VIDEO_POSTER")}),RoughCutGetSchema.extend({kind:z211.literal("ROUGH_CUT_POSTER")}),FinalRenderGetSchema.extend({kind:z211.literal("FINAL_POSTER")}),ReferencePreviewOperationInputSchema.extend({kind:z211.literal("REFERENCE_PREVIEW")})]);var sdkMcpImageTools=Object.freeze({KEYFRAME:"keyframe_media",VIDEO_POSTER:"video_poster",ROUGH_CUT_POSTER:"rough_cut_poster",FINAL_POSTER:"final_render_poster",REFERENCE_PREVIEW:"reference_preview_get"});var identitySchema=z211.strictObject({checksumSha256:z211.string().regex(/^[a-f0-9]{64}$/),byteSize:z211.int().positive().max(16*1024*1024).optional()});var metadataSchema=z211.strictObject({contentType:z211.enum(["image/png","image/jpeg","image/webp"]),checksumSha256:identitySchema.shape.checksumSha256,byteSize:z211.int().positive().max(16*1024*1024)});async function readMcpImage(config,raw,expected,options){if(!raw||raw.tenantId!==void 0&&(typeof raw.tenantId!=="string"||raw.tenantId.toLowerCase()!==config.tenantId))sdkInputError();const input=inputSchema2.safeParse({...raw,tenantId:config.tenantId}),identity6=identitySchema.safeParse(expected);if(!input.success||!identity6.success)sdkInputError();const{kind,...arguments_}=input.data;const deadline=AbortSignal.timeout(config.timeoutMs),signal=options.signal?AbortSignal.any([options.signal,deadline]):deadline;if(signal.aborted)throw new NativeStudioSdkError("REQUEST_ABORTED","BLOCKED","NO_WRITE");let reply2;try{reply2=await abortable(config.client.callTool({name:sdkMcpImageTools[kind],arguments:arguments_},{signal,timeout:config.timeoutMs,nativeReadOnly:true}),signal)}catch{throw new NativeStudioSdkError(signal.aborted?"REQUEST_ABORTED":"TRANSPORT_UNAVAILABLE","INTERNAL_OPERATIONAL_FAILURE","NO_WRITE")}try{if(Buffer.byteLength(JSON.stringify(reply2),"utf8")>config.maxJsonBytes)throw Error();const texts=reply2.content.filter(b=>b.type==="text"),images=reply2.content.filter(b=>b.type==="image");const carrier=reply2.structuredContent??(texts.length===1?JSON.parse(texts[0].text):void 0);const envelope=z211.object({semanticStatus:InterfaceSemanticStatusSchema,data:z211.unknown().optional(),error:z211.object({code:z211.string()}).optional()}).parse(carrier);if(reply2.isError)throw new NativeStudioSdkError(envelope.error&&nativeFailureCodes.has(envelope.error.code)?envelope.error.code:"RESPONSE_INVALID",envelope.semanticStatus==="SUCCESS"?"INTERNAL_OPERATIONAL_FAILURE":envelope.semanticStatus,"NO_WRITE");if(envelope.semanticStatus!=="SUCCESS"||images.length!==1||reply2.content.length!==(kind==="REFERENCE_PREVIEW"?2:1)||texts.length!==(kind==="REFERENCE_PREVIEW"?1:0))throw Error();const metadata=kind==="REFERENCE_PREVIEW"?ReferencePreviewResultSchema.parse(envelope.data):metadataSchema.parse(envelope.data);const block=images[0],bytes=Buffer.from(block.data,"base64"),checksumSha256=createHash16("sha256").update(bytes).digest("hex");if(block.mimeType!==metadata.contentType||bytes.toString("base64")!==block.data||bytes.length>(kind==="KEYFRAME"?8:16)*1024*1024||bytes.length!==metadata.byteSize||checksumSha256!==metadata.checksumSha256||checksumSha256!==identity6.data.checksumSha256||identity6.data.byteSize!==void 0&&bytes.length!==identity6.data.byteSize||"contentBase64"in metadata&&metadata.contentBase64!==block.data)throw new NativeStudioSdkError("MEDIA_IDENTITY_MISMATCH","INTERNAL_OPERATIONAL_FAILURE","NO_WRITE");return{bytes,contentType:metadata.contentType,checksumSha256,etag:null}}catch(error){if(error instanceof NativeStudioSdkError)throw error;throw new NativeStudioSdkError("RESPONSE_INVALID","INTERNAL_OPERATIONAL_FAILURE","NO_WRITE")}}function memberCapabilityPort(client,tenantId){return{async callTool(params,options){const{nativeReadOnly,capabilityVersion,...requestOptions}=options??{};const direct=McpEntryToolNames.some(name3=>name3===params.name);if(!direct&&nativeReadOnly===void 0)throw new NativeStudioSdkError("CAPABILITY_UNAVAILABLE","BLOCKED","NO_WRITE");const name2=nativeReadOnly?"studio_capability_query":"studio_capability_invoke";const request=direct?params:{name:name2,arguments:{tenantId,tool:params.name,arguments:params.arguments??{},...capabilityVersion&&{capabilityVersion}}};const response=await client.callTool(request,{...requestOptions,...!direct?{toolDefinition:inputDefinition(name2,CapabilityInvocationInputSchema)}:{}});if(direct&&!params.name.startsWith("studio_capability_"))return response;const gateway=request.name==="studio_capability_query"||request.name==="studio_capability_invoke";if(!gateway)return response;const parsed=CapabilityInvocationOutputSchema.safeParse(response.structuredContent);const target3=direct?params.arguments?.tool:params.name;if(!parsed.success){if(response.isError&&isNativeDenial(response.structuredContent))return response;throw new NativeStudioSdkError("RESPONSE_INVALID","INTERNAL_OPERATIONAL_FAILURE",nativeReadOnly?"NO_WRITE":"UNKNOWN")}if(parsed.data.tool!==target3)throw new NativeStudioSdkError("RESPONSE_INVALID","INTERNAL_OPERATIONAL_FAILURE",nativeReadOnly?"NO_WRITE":"UNKNOWN");if(direct&&!response.isError)return response;return{...response,structuredContent:parsed.data.result}}}}function isNativeDenial(value2){return value2!==null&&typeof value2==="object"&&"semanticStatus"in value2&&"error"in value2}var NativeStudioMcpClient=class{constructor(config){this.config=config;const tenant2=TenantIdSchema.safeParse(config.tenantId);if(!tenant2.success||typeof config.client?.callTool!=="function")sdkInputError();this.tenantId=tenant2.data.toLowerCase();if(config.mode!=="native")this.config={...config,client:memberCapabilityPort(config.client,this.tenantId)};this.timeout=config.timeoutMs??3e4;this.limit=config.maxJsonBytes??16*1024*1024;if(!Number.isSafeInteger(this.timeout)||this.timeout<1||this.timeout>3e5||!Number.isSafeInteger(this.limit)||this.limit<1024||this.limit>32*1024*1024)sdkInputError()}config;deviceRenders=new NativeStudioDeviceRenders(this);navigation=new NativeStudioNavigationFacade(this);tenantId;timeout;limit;imageMedia(input,expected,options={}){return readMcpImageMedia({...this.config,tenantId:this.tenantId,timeoutMs:this.timeout,maxJsonBytes:this.limit},input,expected,options)}evidenceImage(input,expected,options={}){return readMcpEvidenceImage({...this.config,tenantId:this.tenantId,timeoutMs:this.timeout,maxJsonBytes:this.limit},input,expected,options)}auxiliaryMedia(input,expected,options={}){return readMcpAuxiliaryMedia({...this.config,tenantId:this.tenantId,timeoutMs:this.timeout,maxJsonBytes:this.limit},input,expected,options)}image(input,expected,options={}){return readMcpImage({...this.config,tenantId:this.tenantId,timeoutMs:this.timeout,maxJsonBytes:this.limit},input,expected,options)}async call(key10,raw,options={}){if(!Object.hasOwn(sdkOperations,key10)||!raw||typeof raw!=="object"||Array.isArray(raw))sdkInputError();if(raw.tenantId!==void 0&&(typeof raw.tenantId!=="string"||raw.tenantId.toLowerCase()!==this.tenantId))sdkInputError();const limit=options.maxJsonBytes??this.limit;if(!Number.isSafeInteger(limit)||limit<1024||limit>this.limit)sdkInputError();const tool=sdkMcpTools[key10];if(tool===null)throw new NativeStudioSdkError("CAPABILITY_UNAVAILABLE","CAPABILITY_UNAVAILABLE","NO_WRITE");let capabilityVersion=options.capabilityVersion;if(capabilityVersion!==void 0){if(!CapabilityVersionSchema.safeParse(capabilityVersion).success)sdkInputError();if(this.config.mode==="native"||McpEntryToolNames.some(name2=>name2===tool))throw new NativeStudioSdkError("CAPABILITY_UNAVAILABLE","CAPABILITY_UNAVAILABLE","NO_WRITE")}const spec=sdkOperations[key10],parsed=spec.input.safeParse({...raw,tenantId:this.tenantId});if(!parsed.success)sdkInputError(inputIssues(parsed.error,spec.input));const input=parsed.data;if(Buffer.byteLength(JSON.stringify(input),"utf8")>18*1024*1024)sdkInputError();const request=spec.request===null?{method:spec.readOnly?"GET":"POST"}:spec.request(input);const write2=request.method==="POST"&&!spec.readOnly,outcome=write2?"UNKNOWN":"NO_WRITE";const signal=options.signal?AbortSignal.any([options.signal,AbortSignal.timeout(this.timeout)]):AbortSignal.timeout(this.timeout);if(signal.aborted)throw new NativeStudioSdkError("REQUEST_ABORTED","BLOCKED","NO_WRITE");if((key10==="rough-cut.start"||key10==="final-render.start")&&"deviceExecution"in input&&input.deviceExecution){const target3=DeviceRenderTargetSchema.parse(input.deviceExecution);const description=await this.navigation.describe({tool},{signal});const root=description.definition.inputSchema;const properties=schemaNode(root,root)?.properties;const policy=properties&&typeof properties==="object"?properties.deviceExecution:void 0;const policyFields=schemaNode(policy,root)?.properties;if(!schemaNode(policy,root)||target3.validationMode&&(!policyFields||typeof policyFields!=="object"||!Object.hasOwn(policyFields,"validationMode")))throw new NativeStudioSdkError("CAPABILITY_UNAVAILABLE","BLOCKED","NO_WRITE");if(this.config.mode!=="native")capabilityVersion??=description.capabilityVersion;if(signal.aborted)throw new NativeStudioSdkError("REQUEST_ABORTED","BLOCKED","NO_WRITE")}const definition=inputDefinition(tool,spec.input);let result;try{result=await abortable(this.config.client.callTool({name:tool,arguments:sdkMcpInput(key10,input)},{signal,timeout:this.timeout,toolDefinition:definition,nativeReadOnly:!write2,...capabilityVersion&&{capabilityVersion}}),signal)}catch{throw new NativeStudioSdkError(write2?"OUTCOME_UNKNOWN":signal.aborted?"REQUEST_ABORTED":"TRANSPORT_UNAVAILABLE","INTERNAL_OPERATIONAL_FAILURE",outcome)}let value2;try{if(Buffer.byteLength(JSON.stringify(result),"utf8")>limit)throw new Error;if("structuredContent"in result&&result.structuredContent!==void 0)value2=result.structuredContent;else if("content"in result&&result.content.length===1&&result.content[0]?.type==="text")value2=JSON.parse(result.content[0].text);else throw new Error}catch{throw new NativeStudioSdkError("RESPONSE_INVALID","INTERNAL_OPERATIONAL_FAILURE",outcome)}const envelope=value2&&typeof value2==="object"&&!Array.isArray(value2)?value2:{};if("isError"in result&&result.isError){const status=InterfaceSemanticStatusSchema.safeParse(envelope.semanticStatus);const semantic=status.success&&!["SUCCESS","ACCEPTED","NO_CHANGE"].includes(status.data)?status.data:"INTERNAL_OPERATIONAL_FAILURE";const error=envelope.error&&typeof envelope.error==="object"&&!Array.isArray(envelope.error)?envelope.error:void 0;const code=error?.code;const valid=status.success&&!["SUCCESS","ACCEPTED","NO_CHANGE"].includes(status.data);const suppliedVersion=capabilityVersion??(McpCapabilityGatewayNames.some(name2=>name2===tool)&&"capabilityVersion"in input?input.capabilityVersion:void 0);const reportedMismatch=capabilityMismatch(code,semantic,error?.details);const mismatch2=reportedMismatch?.kind==="CAPABILITY_DEFINITION"&&(reportedMismatch.expectedVersion===reportedMismatch.actualVersion||suppliedVersion!==void 0&&reportedMismatch.actualVersion!==suppliedVersion)?void 0:reportedMismatch;const known=valid&&typeof code==="string"&&nativeFailureCodes.has(code)&&(code!=="CAPABILITY_VERSION_MISMATCH"||!!mismatch2);throw new NativeStudioSdkError(known&&typeof code==="string"?code:semantic,semantic,failureOutcome(write2,semantic,valid&&error?.outcome==="UNKNOWN"?"UNKNOWN":known?error?.outcome:void 0),null,[],mismatch2)}if(envelope.semanticStatus==="NOT_FOUND"&&envelope.data===void 0)throw new NativeStudioSdkError("NOT_FOUND","NOT_FOUND",write2?"REJECTED":"NO_WRITE");const schema=spec.output;for(const candidate of[value2,envelope.data,envelope.data&&typeof envelope.data==="object"&&!Array.isArray(envelope.data)?{...envelope.data,semanticStatus:envelope.semanticStatus}:void 0]){const parsedOutput=schema.safeParse(candidate);if(parsedOutput.success){if(key10==="reference-preview.get")assertPreviewBytes(parsedOutput.data);if(key10==="temporal-evidence.read-video")assertOriginalVideoBytes(parsedOutput.data);if(key10==="audio.export"||key10==="caption.export"||key10==="source-sync.audio")assertExportBytes(parsedOutput.data,key10==="caption.export"&&"format"in input?String(input.format):void 0);assertManagementReceipt(key10,input,parsedOutput.data);assertResponseBindings(parsedOutput.data,input,spec.identity,write2?"POST":"GET",spec.expectedPath?spec.expectedPath(input,parsedOutput.data):void 0,spec.identityWhenPresent);assertSeriesResponseVersions(key10,input,parsedOutput.data);assertEnterpriseBrandResponse(key10,input,parsedOutput.data);return parsedOutput.data}}throw new NativeStudioSdkError("RESPONSE_INVALID","INTERNAL_OPERATIONAL_FAILURE",outcome)}};var NativeStudioNavigationClient=class{constructor(config){this.config=config;if(typeof config.client?.callTool!=="function")sdkInputError();this.native=new NativeStudioMcpClient({...config,client:{callTool:async(params,options)=>{const definition=this.definitions.get(params.name);const result=await config.client.callTool(params,{...options,...definition?{toolDefinition:definition}:{}});if(params.name==="studio_capability_describe"&&!result.isError){const parsed=CapabilityDescribeSchema.safeParse(result.structuredContent);const projectId=params.arguments?.projectId;if(parsed.success&&parsed.data.tenantId.toLowerCase()===config.tenantId.toLowerCase()&&parsed.data.tool===params.arguments?.tool){this.contexts.set(parsed.data.schemaCursor,{tool:parsed.data.tool,...typeof projectId==="string"?{projectId}:{}});if(this.contexts.size>32)this.contexts.delete(this.contexts.keys().next().value)}}return result}}})}config;native;definitions=new Map;contexts=new Map;async entrypoints(options={}){const value2=await this.native.call("studio.capability.groups",{includeDefinitions:true},options);const tools=value2.definitions;const required=this.config.mode==="native"?NavigationToolNames:McpEntryToolNames.filter(name2=>name2!=="studio_capability_invoke");const names=new Set(this.config.mode==="native"?[...NavigationToolNames,"nvs_open_execution"]:McpEntryToolNames);if(!tools||tools.some(tool=>!names.has(tool.name)||tool.inputSchema.type!=="object")||new Set(tools.map(tool=>tool.name)).size!==tools.length||Buffer.byteLength(JSON.stringify(tools))>(this.config.mode==="native"?160*1024:24*1024)||required.some(name2=>!tools.some(tool=>tool.name===name2)))this.invalid();this.definitions.clear();this.contexts.clear();for(const tool of tools)this.remember(tool);return{tools}}async selectedSchema(reference3,expectedTool,options={}){if(!reference3||reference3.length>2048||!/^[a-zA-Z0-9_-]{1,120}$/.test(expectedTool))sdkInputError();const context=this.contexts.get(reference3);if(context&&context.tool!==expectedTool)this.invalid();const projectId=options.projectId??context?.projectId;const description=await this.native.call("studio.capability.describe",{tool:expectedTool,schemaCursor:reference3,...projectId?{projectId}:{}},options);return this.selectDescription(description,expectedTool,{...projectId?{projectId}:{}})}selectDescription(raw,expectedTool,options={}){const parsed=CapabilityDescribeSchema.safeParse(raw);if(!parsed.success||parsed.data.tenantId.toLowerCase()!==this.config.tenantId.toLowerCase()||parsed.data.tool!==expectedTool)this.invalid();const description=parsed.data;const definition=description.definition;if(definition.name!==expectedTool)this.invalid();const selected=definition;this.remember(selected);this.contexts.set(description.schemaCursor,{tool:expectedTool,...options.projectId?{projectId:options.projectId}:{}});if(this.contexts.size>32)this.contexts.delete(this.contexts.keys().next().value);return description}remember(tool){if(!PublicToolDefinitionSchema.safeParse(tool).success||tool.inputSchema?.type!=="object"||Buffer.byteLength(JSON.stringify(tool))>160*1024)this.invalid();this.definitions.delete(tool.name);this.definitions.set(tool.name,structuredClone(tool));if(this.definitions.size>32)this.definitions.delete(this.definitions.keys().next().value)}invalid(){throw new NativeStudioSdkError("RESPONSE_INVALID","INTERNAL_OPERATIONAL_FAILURE","NO_WRITE")}};var sdkCarrierDifferences={"studio.capabilities":{kind:"MCP_DISCOVERY",role:"Configured MCP capability inventory"},"studio.start":{kind:"MCP_DISCOVERY",role:"Progressive MCP entry navigation"},"studio.media.readiness":{kind:"MCP_DISCOVERY",role:"Goal-specific render and host navigation"},"studio.navigate":{kind:"MCP_DISCOVERY",role:"Progressive MCP context navigation"},"studio.capability.groups":{kind:"MCP_DISCOVERY",role:"MCP tool groups"},"studio.capability.search":{kind:"MCP_DISCOVERY",role:"MCP tool search"},"studio.capability.describe":{kind:"MCP_DISCOVERY",role:"MCP tool schemas"},"studio.capability.query":{kind:"MCP_DISPATCH",role:"Compact MCP read dispatch to existing native Owners"},"studio.capability.invoke":{kind:"MCP_DISPATCH",role:"Compact MCP write dispatch to existing native Owners"},"agent-host.configure":{kind:"PRIVATE_HTTP",role:"Private host configuration credential injection"},"provider.configure":{kind:"PRIVATE_HTTP",role:"Private provider credential injection"},"webhook.configure":{kind:"PRIVATE_HTTP",role:"Private signing-secret configuration; models use webhook.configure-reference"},"webhook.secret.prepare":{kind:"PRIVATE_HTTP",role:"Private caller-bound signing-secret preparation"}};function assertCarrierCoverage(operations2,differences){const expected=Object.entries(operations2).filter(([key10,value2])=>value2.request===null||sdkMcpTools[key10]===null).map(([key10])=>key10).sort();if(JSON.stringify(expected)!==JSON.stringify(Object.keys(differences).sort()))throw Error("SDK carrier inventory is incomplete")}var NativeStudioRuntimeAuthorityClient=class{tenantId;origin;transport;constructor(config){const tenant2=TenantIdSchema.safeParse(config.tenantId);if(!tenant2.success)sdkInputError();this.tenantId=tenant2.data.toLowerCase();if(config.maxJsonBytes!==void 0&&config.maxJsonBytes>65536)sdkInputError();try{this.origin=new URL(config.baseUrl);if(this.origin.protocol!=="https:")sdkInputError()}catch{sdkInputError()}this.transport=new NativeStudioHttpTransport({...config,maxJsonBytes:config.maxJsonBytes??65536,authorization:()=>{throw new Error("Runtime proof has no bearer credential")}})}input(schema,raw){if(!raw||typeof raw!=="object"||Array.isArray(raw))sdkInputError();const record=raw;if(record.tenantId!==void 0&&(typeof record.tenantId!=="string"||record.tenantId.toLowerCase()!==this.tenantId))sdkInputError();const parsed=schema.safeParse({...record,tenantId:this.tenantId});if(!parsed.success)sdkInputError();return parsed.data}resource(projectId,resource){if(resource!==new URL(`/mcp/native/v1/projects/${projectId}`,this.origin).href)throw new NativeStudioSdkError("RESPONSE_SCOPE_MISMATCH","INTERNAL_OPERATIONAL_FAILURE","UNKNOWN")}async prove(raw,options={}){const value2=this.input(NativeRuntimeProofRequestSchema,raw),result=await this.transport.json({method:"POST",tenantId:this.tenantId,path:path("projects",value2.projectId,"native-tool-grants",value2.grantId,"proof"),body:{assertion:value2.assertion},authentication:"runtime-proof"},NativeToolGrantViewSchema,options);assertResponseBindings(result,value2,[["grantId","grantId"]],"POST");this.resource(value2.projectId,result.resource);return result}async status(raw,options={}){const value2=this.input(NativeRuntimeProofRequestSchema,raw);try{const result=await this.transport.json({method:"POST",tenantId:this.tenantId,path:path("projects",value2.projectId,"native-tool-grants",value2.grantId,"status"),body:{assertion:value2.assertion},authentication:"runtime-proof"},NativeToolGrantViewSchema,options);assertResponseBindings(result,value2,[["grantId","grantId"]],"POST");this.resource(value2.projectId,result.resource);return result}catch(error){if(error instanceof NativeStudioSdkError)throw new NativeStudioSdkError(error.code,error.semanticStatus,"NO_WRITE",error.status);throw error}}async exchange(raw,options={}){const value2=this.input(NativeToolCredentialExchangeSchema,raw),result=await this.transport.json({method:"POST",tenantId:this.tenantId,path:path("projects",value2.projectId,"productions",value2.productionId,"native-tool-credentials","exchange"),body:{authorityRef:value2.authorityRef,assertion:value2.assertion},authentication:"runtime-proof"},NativeToolCredentialReplySchema,options);this.resource(value2.projectId,result.resource);if(!result.accessToken.startsWith(`nvst_${result.tokenId}.`))throw new NativeStudioSdkError("RESPONSE_SCOPE_MISMATCH","INTERNAL_OPERATIONAL_FAILURE","UNKNOWN");return result}};import{setTimeout as delay}from"node:timers/promises";async function*queryPages(client,key10,input,options={}){const maxPages=options.maxPages??50,maxItems=options.maxItems??1e3;if(!Number.isSafeInteger(maxPages)||maxPages<1||maxPages>500||!Number.isSafeInteger(maxItems)||maxItems<1||maxItems>1e4)sdkInputError();const seen=new Set;let next=input.next,count2=0;if(next)seen.add(next);for(let pageNumber=0;pageNumber<maxPages;pageNumber++){const page5=await client.call(key10,{...input,...next===void 0?{}:{next}},options);count2+=page5.items.length;if(count2>maxItems)throw new NativeStudioSdkError("OBSERVATION_LIMIT","WAITING_INPUT","NO_WRITE");if(page5.page.hasMore&&(!page5.page.next||seen.has(page5.page.next)))throw new NativeStudioSdkError("CONTINUATION_INVALID","INTERNAL_OPERATIONAL_FAILURE","NO_WRITE");yield page5;if(!page5.page.hasMore)return;next=page5.page.next;seen.add(next)}throw new NativeStudioSdkError("OBSERVATION_LIMIT","WAITING_INPUT","NO_WRITE")}async function waitForOperation(client,input,options={}){const maxPolls=options.maxPolls??60,timeoutMs=options.timeoutMs??9e4,intervalMs=options.intervalMs??1e3;const adaptive=options.intervalMs===void 0;let previous,pause=intervalMs;if(!Number.isSafeInteger(maxPolls)||maxPolls<1||maxPolls>1e3||!Number.isSafeInteger(timeoutMs)||timeoutMs<1||timeoutMs>18e5||!Number.isSafeInteger(intervalMs)||intervalMs<10||intervalMs>1e4)sdkInputError();const deadline=AbortSignal.timeout(timeoutMs),signal=options.signal?AbortSignal.any([options.signal,deadline]):deadline;try{for(let poll=0;poll<maxPolls;poll++){signal.throwIfAborted();const result=await abortable(client.call("operation.get",input,{signal}),signal);signal.throwIfAborted();if(!["ACCEPTED","WAITING_PROVIDER","RETRYING"].includes(result.semanticStatus))return result;const progress=JSON.stringify([result.semanticStatus,result.targets,result.work,result.blockers,result.nextActions]);pause=adaptive&&progress===previous?Math.min(5e3,pause*2):intervalMs;previous=progress;if(poll<maxPolls-1)await delay(pause,void 0,{signal})}}catch(error){if(!deadline.aborted||options.signal?.aborted)throw error}throw new NativeStudioSdkError("OBSERVATION_LIMIT","WAITING_INPUT","NO_WRITE")}import{setTimeout as delay2}from"node:timers/promises";async function*observeProduction(client,input,options={}){const polls=options.maxPolls??60,timeout=options.timeoutMs??3e5,events=options.maxEvents??1e3,byteLimit=options.maxBytes??2*1024*1024;for(const[n,max]of[[polls,1e3],[timeout,18e5],[events,1e4],[byteLimit,16*1024*1024]])if(!Number.isSafeInteger(n)||n<1||n>max)sdkInputError();if(byteLimit<1024)sdkInputError();const controller=new AbortController;const timer=setTimeout(()=>controller.abort(),timeout);const signal=options.signal?AbortSignal.any([options.signal,controller.signal]):controller.signal;let after=input.after,etag=input.ifNoneMatch,count2=0,bytes=0,unchanged=0;try{for(let n=0;n<polls;n++){signal.throwIfAborted();const page5=ProductionEventReadSchema.parse(await abortable(client.call("production.events.read",{...input,...after?{after}:{},...etag?{ifNoneMatch:etag}:{}},{signal,maxJsonBytes:128*1024}),signal));signal.throwIfAborted();count2+=page5.items.length;bytes+=Buffer.byteLength(JSON.stringify(page5));if(count2>events||bytes>byteLimit)throw new NativeStudioSdkError("OBSERVATION_LIMIT","WAITING_INPUT","NO_WRITE");if(page5.hasMore&&(page5.nextCursor===after||page5.items.length===0))throw new NativeStudioSdkError("CONTINUATION_INVALID","INTERNAL_OPERATIONAL_FAILURE","NO_WRITE");yield page5;after=page5.nextCursor;etag=page5.current.etag;unchanged=page5.items.length===0&&page5.current.condition==="NOT_MODIFIED"?unchanged+1:0;if(n+1<polls&&!page5.hasMore)await delay2(Math.min(3e4,page5.current.retryAfterMs*2**Math.min(unchanged,3)),void 0,{signal})}}catch(error){if(!controller.signal.aborted||options.signal?.aborted)throw error;throw new NativeStudioSdkError("OBSERVATION_LIMIT","WAITING_INPUT","NO_WRITE")}finally{clearTimeout(timer);controller.abort()}}import{createHmac,timingSafeEqual}from"node:crypto";function verifyWebhookNotification(input){const match=/^t=([1-9][0-9]{0,11}),v1=([a-f0-9]{64})$/.exec(input.signature);const now=input.now??Date.now();if(!(input.body instanceof Uint8Array)||input.body.length>128*1024||!match||!Number.isSafeInteger(now)||Math.abs(now/1e3-Number(match[1]))>300||typeof input.secret!=="string"||input.secret.length<32||input.secret.length>256||input.eventVersion!=="1"||!/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/.test(input.deliveryId))throw Error("WEBHOOK_INVALID");const expected=createHmac("sha256",input.secret).update(match[1]+".").update(input.body).digest();if(!timingSafeEqual(expected,Buffer.from(match[2],"hex")))throw Error("WEBHOOK_INVALID");try{const event3=ExternalLifecycleEventSchema.parse(JSON.parse(new TextDecoder("utf-8",{fatal:true}).decode(input.body)));if(event3.eventId!==input.eventId)throw Error();return event3}catch{throw Error("WEBHOOK_INVALID")}}import{createHash as createHash17}from"node:crypto";var inputSchema3=FederationResultReadSchema.omit({reference:true}).extend({event:ExternalLifecycleEventSchema});var mismatch=()=>{throw new NativeStudioSdkError("FEDERATION_NOTICE_RESULT_MISMATCH","INTERNAL_OPERATIONAL_FAILURE","NO_WRITE")};function parseReply(schema,raw,maxBytes){try{const text6=canonicalFederationReadJson(raw);if(Buffer.byteLength(text6)>maxBytes)return mismatch();const result=schema.safeParse(JSON.parse(text6));if(!result.success)return mismatch();return result.data}catch{return mismatch()}}async function readFederationLifecycleResult(client,raw,options={}){let expected;try{const input=inputSchema3.parse(JSON.parse(canonicalFederationJson(raw)));expected=FederationResultValueSchema.parse({tenantId:input.tenantId,productionId:input.productionId,source:input.source,schemaVersion:1,resourceType:"nvs.lifecycle-event",resourceId:input.event.eventId,revision:String(input.event.basis.productionRevision),event:input.event})}catch{sdkInputError()}const bytes=canonicalFederationJson(expected);const digest6="sha256:"+createHash17("sha256").update(bytes).digest("hex");const cap=options.maxJsonBytes??65536;if(!Number.isSafeInteger(cap)||cap<1024)sdkInputError();const requestOptions={...options,maxJsonBytes:Math.min(cap,65536)};const aborted=()=>{if(requestOptions.signal?.aborted)throw new NativeStudioSdkError("REQUEST_ABORTED","BLOCKED","NO_WRITE")};async function query(operation2,input){aborted();try{const pending=client.call(operation2,input,{...requestOptions});return await(requestOptions.signal?abortable(pending,requestOptions.signal):pending)}catch(error){aborted();throw error}}const scope8={tenantId:expected.tenantId,productionId:expected.productionId};const reference3=parseReply(FederationResultReferenceSchema,await query("federation.result.reference",{...scope8,resourceType:"nvs.lifecycle-event",resourceId:expected.resourceId}),requestOptions.maxJsonBytes);if(reference3.tenantId!==scope8.tenantId||reference3.productionId!==scope8.productionId||reference3.source!==expected.source||reference3.reference.resourceType!==expected.resourceType||reference3.reference.resourceId!==expected.resourceId||reference3.reference.revision!==expected.revision||reference3.reference.digest!==digest6)mismatch();const pinnedReference=canonicalFederationJson(reference3.reference);const result=parseReply(FederationResultSnapshotSchema,await query("federation.result.read",{...scope8,source:expected.source,reference:{...reference3.reference}}),requestOptions.maxJsonBytes);const value2=result.value;if(value2.resourceType!=="nvs.lifecycle-event"||result.tenantId!==scope8.tenantId||result.productionId!==scope8.productionId||result.source!==expected.source||canonicalFederationJson(result.reference)!==pinnedReference||canonicalFederationJson(value2)!==bytes)return mismatch();return{...result,value:value2}}export{LocalIdSchema,LocalDigestSchema,LocalRevisionSchema,LocalTimeSchema,LocalPackageVersionSchema,LocalProjectScopeSchema,LocalWorkScopeSchema,LocalDevicePlatformSchema,EnrollLocalDeviceSchema,LocalDeviceViewSchema,LocalDeviceChallengeSchema,RevokeLocalDeviceSchema,WorkspaceDeviceListInputSchema,WorkspaceDeviceListSchema,LegacyCaptionRenderStyleSchema,RegularCaptionRenderStyleSchema,kokoroCpuProfile,CpuSpeechInputSchema,CpuSpeechCapabilitySchema,CpuSpeechInstallationSchema,processorFamilies,TenantProcessorKindSchema,referenceThumbnailProfile,ProjectDeviceListSchema,RoughCutViewSchema,FinalRenderViewSchema,LocalLeaseBindingSchema,mediaCategoryOf,localLibraryProfile,LocalLibraryReferenceSchema,LocalLibraryItemSchema,LocalLibraryPageSchema,LocalLibraryProjectionSchema,LocalLibraryProjectionPageSchema,LocalLibraryProjectionQuerySchema,LocalLibraryImportSchema,LocalLibraryReadReplySchema,LocalLibraryGetSchema,LocalLibraryCallSchema,LocalLibraryCapabilitySchema,LocalLibraryUsageSchema,RoughCutRequirementSchema,ReviewEvidenceMediaSchema,whisperCppRecognitionProfile,LocalWhisperToolSelectionSchema,canonicalLocalJson,VideoReviewRequirementSchema,VisualRequirementSchema,KeyframeObservationSchema,ReviewIntelligenceBasisSchema,ValidateReviewIntelligenceSchema,ReviewIntelligenceContextResultSchema,StartLocalPreviewSchema,LocalDeviceSessionSchema,LocalDeviceTransportConfigurationSchema,LocalPreviewAdmissionSchema,StartLocalFinalRenderSchema,LocalFinalRenderAdmissionSchema,LocalManagementCommandSchema,LocalManagementResultSchema,LocalManagementReceiptSchema,LocalDeviceManagementCommandSchema,DeviceEnrollmentScopeSchema,DeviceEnrollmentHandoffSchema,DeviceEnrollmentTicketSchema,DeviceEnrollmentReceiptSchema,DeviceEnrollmentObservationSchema,deviceEnrollmentSigningInput,ComponentStatusSchema,WorkspaceStatusSchema,DeviceStatusInputSchema,DeviceStatusSchema,tenantRenderValidationProfile,TenantRenderMediaTicketSchema,LocalLibraryCommandSchema,LocalLibraryCommandQuerySchema,LocalLibraryAdmissionSchema,importedNormalizationValidationProfile,LocalLibraryCommandStatusSchema,renderDeviceSelection,NavigationGroupIdSchema,NavigationGroups,navigationGroup,NavigationProfile,NavigationProfileKey,NavigationToolNames,CapabilityGroupsSchema,CapabilityDescribeSchema,McpEntryToolNames,CapabilityInvocationInputSchema,CapabilityInvocationOutputSchema,DeviceDiscoveryInputSchema,DeviceRenderIntentSchema,DeviceRenderReadSchema,DeviceRenderDownloadSchema,PreparedDeviceRenderSchema,DeviceRenderReceiptHandoffSchema,DeviceRenderAdmissionSchema,NativeStudioDeviceRenders,checkedManagementReceipt,assertManagementReceipt,validateDeviceEnrollmentHandoff,issueDeviceEnrollment,lookupDeviceEnrollment,submitDeviceEnrollment,recoverDeviceEnrollment,NativeStudioNavigationFacade,sdkOperations,NativeStudioAgentClient,sdkImageMediaTools,sdkMcpTools,NativeStudioMcpClient,NativeStudioNavigationClient,sdkCarrierDifferences,assertCarrierCoverage,NativeStudioRuntimeAuthorityClient,queryPages,waitForOperation,observeProduction,verifyWebhookNotification,readFederationLifecycleResult};
|