@nativestudio/cli 0.3.0-rc.2 → 0.3.0-rc.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/COMPATIBILITY.json +7 -7
- package/README.md +27 -3
- package/components/runtime.json +3 -3
- package/components/runtime.tgz +0 -0
- package/dist/_chunks/{chunk-BVSTJQJI.js → chunk-6LU6GJKW.js} +1 -1
- package/dist/_chunks/chunk-CA54SKBO.js +1 -0
- package/dist/_chunks/chunk-D533YC7J.js +1 -0
- package/dist/_chunks/{chunk-C33A2DW4.js → chunk-DXJQWTLG.js} +1 -1
- package/dist/_chunks/{chunk-7S3DJ2QE.js → chunk-FU3524Z6.js} +1 -1
- package/dist/_chunks/chunk-INLSOHAK.js +1 -0
- package/dist/_chunks/chunk-JPH576UL.js +1 -0
- package/dist/_chunks/chunk-KB2GVAN7.js +1 -0
- package/dist/_chunks/{chunk-C753RRRA.js → chunk-KNFUMWDY.js} +1 -1
- package/dist/_chunks/chunk-N6S6HCWE.js +1 -0
- package/dist/_chunks/chunk-PBEHCYR7.js +1 -0
- package/dist/_chunks/chunk-RVGDXRPK.js +1 -0
- package/dist/_chunks/chunk-YKOJPJZR.js +1 -0
- package/dist/_chunks/{files-FZEK2ZZJ.js → files-TTIQ7LYJ.js} +1 -1
- package/dist/_chunks/local-main-S2K34Y2F.js +1 -0
- package/dist/_chunks/local-mcp-LCHXL2IE.js +1 -0
- package/dist/_chunks/{main-VRIQTI6R.js → main-KLXOK7QK.js} +2 -2
- package/dist/_chunks/mcp-P7W623FE.js +1 -0
- package/dist/_chunks/oauth-WJ36KWAC.js +1 -0
- package/dist/_chunks/project-connect-W7V3OALV.js +1 -0
- package/dist/_chunks/render-main-ZW6UJHGN.js +1 -0
- package/dist/_chunks/src-BXLFLNRG.js +1 -0
- package/dist/_chunks/{stdio-main-KOGQ5OWF.js → stdio-main-4Z2JVCMO.js} +1 -1
- package/dist/_types/cli/local/desktop-contract.d.ts +1382 -0
- package/dist/_types/cli/local/desktop-device-contract.d.ts +1165 -0
- package/dist/_types/cli/local/desktop-device-navigation.d.ts +3 -0
- package/dist/_types/cli/local/desktop-device-owner.d.ts +275 -0
- package/dist/_types/cli/local/desktop-device-state.d.ts +230 -0
- package/dist/_types/cli/local/desktop-owner.d.ts +552 -1
- package/dist/_types/cli/local/ledger.d.ts +62 -10
- package/dist/_types/cli/local/manager.d.ts +485 -20
- package/dist/_types/cli/local/mcp-tools.d.ts +75 -12
- package/dist/_types/cli/local/project-render-tools.d.ts +522 -0
- package/dist/_types/cli/local/releases.d.ts +10 -2
- package/dist/_types/cli/local-management.d.ts +3 -0
- package/dist/_types/cli/local-navigation.d.ts +1 -0
- package/dist/_types/contracts/delivery-manifest.d.ts +63 -27
- package/dist/_types/contracts/delivery-operations.d.ts +21 -9
- package/dist/_types/contracts/device-render.d.ts +10 -0
- package/dist/_types/contracts/exploration-recommendation.d.ts +84 -36
- package/dist/_types/contracts/final-render.d.ts +9 -0
- package/dist/_types/contracts/index.d.ts +1 -0
- package/dist/_types/contracts/local-execution/agent-context.d.ts +365 -0
- package/dist/_types/contracts/local-execution/agent-evidence.d.ts +79 -0
- package/dist/_types/contracts/local-execution/agent-grant.d.ts +31 -0
- package/dist/_types/contracts/local-execution/agent-review.d.ts +733 -46
- package/dist/_types/contracts/local-execution/device.d.ts +10 -2
- package/dist/_types/contracts/local-execution/index.d.ts +6 -0
- package/dist/_types/contracts/local-execution/ipc.d.ts +1759 -37
- package/dist/_types/contracts/local-execution/lifecycle.d.ts +48 -6
- package/dist/_types/contracts/local-execution/local-navigation.d.ts +112 -10
- package/dist/_types/contracts/local-execution/management.d.ts +394 -0
- package/dist/_types/contracts/local-execution/media-recipe.d.ts +203 -0
- package/dist/_types/contracts/local-execution/offline.d.ts +59 -0
- package/dist/_types/contracts/local-execution/preview.d.ts +7607 -159
- package/dist/_types/contracts/local-execution/work.d.ts +7674 -294
- package/dist/_types/contracts/local-execution/workspace.d.ts +136 -0
- package/dist/_types/contracts/programmatic-exploration.d.ts +42 -18
- package/dist/_types/contracts/repair-strategy.d.ts +42 -18
- package/dist/_types/contracts/review-intelligence-final-output.d.ts +42 -18
- package/dist/_types/contracts/review-intelligence.d.ts +84 -36
- package/dist/_types/contracts/rough-cut-manifest.d.ts +7 -3
- package/dist/_types/contracts/rough-cut-profile.d.ts +12 -3
- package/dist/_types/contracts/rough-cut-review.d.ts +126 -54
- package/dist/_types/contracts/rough-cut.d.ts +85 -32
- package/dist/_types/contracts/visual-layer-render.d.ts +21 -9
- package/dist/_types/sdk/local-runtime/device-client.d.ts +138 -2
- package/dist/_types/sdk/local-runtime/workspace.d.ts +181 -0
- package/dist/_types/sdk/local-runtime-client.d.ts +1294 -56
- package/dist/entry.js +1 -1
- package/dist/local-management.js +1 -1
- package/dist/local-navigation.js +1 -1
- package/dist/native/JobNative.cs +10 -0
- package/dist/native/JobRunner.cs +24 -3
- package/dist/native/NativeMain.cs +15 -0
- package/package.json +1 -1
- package/dist/_chunks/chunk-66CUOZVI.js +0 -1
- package/dist/_chunks/chunk-E57YVMQ4.js +0 -1
- package/dist/_chunks/chunk-HLKERZIE.js +0 -1
- package/dist/_chunks/chunk-K6LVS2IN.js +0 -1
- package/dist/_chunks/chunk-KHKUJXQX.js +0 -1
- package/dist/_chunks/chunk-VC3ODN3M.js +0 -1
- package/dist/_chunks/local-main-NLFS74Q4.js +0 -1
- package/dist/_chunks/local-mcp-OLHBBVNN.js +0 -1
- package/dist/_chunks/mcp-EIMXNRH3.js +0 -1
- package/dist/_chunks/oauth-F7EZGVME.js +0 -1
- package/dist/_chunks/project-connect-MXM7IY55.js +0 -1
- package/dist/_chunks/src-7F6ZEU3U.js +0 -1
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{ArtifactIdSchema,ArtifactRepresentationIdSchema,BriefIdSchema,BriefVersionIdSchema,ContinuationSchema,ContinuityEdgeIdSchema,DeliveryOutputProfileSchema,OperationIdSchema,PrincipalIdSchema,ProductionIdSchema,ProjectIdSchema,QueryLimitSchema,QueryPageInfoSchema,SceneIdSchema,SceneShotPlanIdSchema,SceneShotPlanVersionIdSchema,ShotIdSchema,StoryIdSchema,StoryVersionIdSchema,TenantIdSchema}from"./chunk-VPYAXWXY.js";import{z}from"zod";var Id=z.uuid().transform(value2=>value2.toLowerCase());var ReadId=z.uuid().regex(/^[0-9a-f-]{36}$/);var Key=z.string().regex(/^[a-z0-9][a-z0-9_-]{0,63}$/);var Revision=z.int().min(0).max(999999999);var AgentHostScopeSchema=z.strictObject({tenantId:Id,projectId:Id});var ReadScope=z.strictObject({tenantId:ReadId,projectId:ReadId});var AgentHostSelectionSchema=z.strictObject({hostKey:Key,tenantKey:Key,workspaceKey:Key,projectKey:Key,agentKey:Key,agentVersion:z.int().positive().max(1e9),modelOptionKey:Key});var ConfigureAgentHostSchema=AgentHostScopeSchema.extend({requestId:Id,bindingId:Id,expectedRevision:z.int().min(0).max(999999998),selection:AgentHostSelectionSchema,apiCredential:z.string().regex(/^agxk_[A-Za-z0-9_-]{43}$/).meta({writeOnly:true})});var RevokeAgentHostSchema=AgentHostScopeSchema.extend({requestId:Id,bindingId:Id,expectedRevision:z.int().min(1).max(999999998)});var AgentHostBindingSchema=ReadScope.extend({bindingId:ReadId,revision:Revision.refine(value2=>value2>0),configurationVersion:Revision.refine(value2=>value2>0),enabled:z.boolean(),selection:AgentHostSelectionSchema,updatedAt:z.iso.datetime({offset:true})}).refine(value2=>value2.configurationVersion<=value2.revision);var UpdateAgentHostSelectionSchema=ConfigureAgentHostSchema.omit({apiCredential:true}).extend({expectedRevision:z.int().min(1).max(999999998),expectedConfigurationVersion:z.int().positive().max(999999998)});var AgentHostCurrentSchema=z.strictObject({binding:AgentHostBindingSchema.nullable()});var AgentHostHistoryQuerySchema=AgentHostScopeSchema.extend({limit:z.int().min(1).max(100).default(20),beforeVersion:z.int().positive().max(999999999).optional()});var AgentHostConfigurationVersionSchema=ReadScope.extend({bindingId:ReadId,version:z.int().positive().max(999999999),selection:AgentHostSelectionSchema,createdByPrincipalId:ReadId,createdAt:z.iso.datetime({offset:true}),revokedAt:z.iso.datetime({offset:true}).nullable()});var AgentHostHistoryPageSchema=z.strictObject({items:z.array(AgentHostConfigurationVersionSchema).max(100),hasMore:z.boolean(),nextBeforeVersion:z.int().positive().max(999999999).nullable()}).refine(page=>page.hasMore===(page.nextBeforeVersion!==null)&&(!page.hasMore||page.items.length>0));var AgentHostReadinessSchema=ReadScope.extend({binding:AgentHostBindingSchema.nullable(),registeredHostKeys:z.array(Key).max(16),configurationStatus:z.enum(["NOT_CONFIGURED","REVOKED","HOST_UNAVAILABLE","CREDENTIAL_UNAVAILABLE","CONFIGURATION_CHANGED","CONFIGURED"]),remoteCredentialVerification:z.enum(["NOT_CHECKED","VERIFIED"]),nativeToolAuthority:z.enum(["NOT_CONNECTED","UNVERIFIED","VERIFIED"]),executionAvailability:z.enum(["UNAVAILABLE","AVAILABLE"]),reason:z.enum(["NATIVE_TOOL_AUTHORITY_NOT_CONNECTED","NATIVE_TOOL_AUTHORITY_NOT_QUALIFIED","CONFIGURATION_CHANGED"]).nullable(),checkedAt:z.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=z.strictObject({semanticStatus:z.enum(["INVALID_INPUT","NOT_FOUND","BLOCKED","REVISION_CONFLICT","CAPABILITY_UNAVAILABLE","INTERNAL_OPERATIONAL_FAILURE"]),error:z.strictObject({code:z.enum(["INVALID_INPUT","UNAUTHENTICATED","FORBIDDEN","NOT_FOUND","REVISION_CONFLICT","REQUEST_CONFLICT","HOST_UNAVAILABLE","CREDENTIAL_UNAVAILABLE","CREDENTIAL_SCOPE_MISMATCH","BINDING_REVOKED","INTERNAL_OPERATIONAL_FAILURE"]),message:z.literal("Agent Host operation did not complete")})});import{z as z2}from"zod";var id=z2.uuid().regex(/^[0-9a-f-]{36}$/);var requestId=z2.uuid().transform(v=>v.toLowerCase());var key=z2.string().regex(/^[A-Za-z0-9_-]{1,160}$/);var NativeRuntimePublicKeySchema=z2.strictObject({kty:z2.literal("EC"),crv:z2.literal("P-256"),x:z2.string().regex(/^[A-Za-z0-9_-]{43}$/),y:z2.string().regex(/^[A-Za-z0-9_-]{43}$/)});var ConfigureNativeToolGrantSchema=AgentHostScopeSchema.extend({requestId,bindingId:requestId,expectedBindingRevision:z2.int().positive(),expectedConfigurationVersion:z2.int().positive(),runtimeKey:key,installationId:key,installationRevisionId:key,publicKey:NativeRuntimePublicKeySchema,expiresAt:z2.iso.datetime({offset:true})});var NativeToolGrantGetSchema=AgentHostScopeSchema.extend({grantId:requestId});var RevokeNativeToolGrantSchema=NativeToolGrantGetSchema.extend({requestId,expectedRevision:z2.int().positive()});var NativeRuntimeProofRequestSchema=NativeToolGrantGetSchema.extend({assertion:z2.string().regex(/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/).max(4096).meta({writeOnly:true})});var NativeRuntimeStatusClaimsSchema=z2.strictObject({iss:key,sub:key,aud:z2.url().max(2048),grantId:id,installationRevisionId:key,jti:id,iat:z2.int().nonnegative(),exp:z2.int().positive()}).refine(v=>v.exp>v.iat&&v.exp-v.iat<=60);var NativeRuntimeProofClaimsSchema=z2.strictObject({iss:key,sub:key,aud:z2.url().max(2048),grantId:id,grantRevision:z2.int().positive(),installationRevisionId:key,challengeId:id,jti:id,iat:z2.int().nonnegative(),exp:z2.int().positive()}).refine(v=>v.exp>v.iat&&v.exp-v.iat<=60);var NativeToolGrantViewSchema=z2.strictObject({tenantId:id,projectId:id}).extend({protocol:z2.literal("NATIVESTUDIO_RUNTIME_REGISTRATION_V1"),grantId:id,bindingId:id,bindingRevision:z2.int().positive(),configurationVersion:z2.int().positive(),selection:AgentHostSelectionSchema,runtimeKey:key,installationId:key,installationRevisionId:key,publicKey:NativeRuntimePublicKeySchema,resource:z2.url().max(2048),revision:z2.int().positive(),enabled:z2.boolean(),createdByPrincipalId:id,runtimePrincipalId:id,createdAt:z2.iso.datetime({offset:true}),expiresAt:z2.iso.datetime({offset:true}),challengeId:id,challengeExpiresAt:z2.iso.datetime({offset:true}),verifiedAt:z2.iso.datetime({offset:true}).nullable(),revokedAt:z2.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)});import{z as z3}from"zod";var offset=z3.int().min(0).max(4094).multipleOf(2);var dimension=z3.int().min(2).max(4096).multipleOf(2);var ClipFramingSchema=z3.strictObject({algorithm:z3.literal("CROP_PAD_V1"),crop:z3.strictObject({x:offset,y:offset,width:dimension,height:dimension}),anchorXPermille:z3.int().min(0).max(1e3),anchorYPermille:z3.int().min(0).max(1e3)});var PicturePolicySchema=z3.literal("CROP_PAD_V1");import{z as z4}from"zod";var ClipTransitionSchema=z4.union([z4.literal("CUT"),z4.strictObject({kind:z4.literal("CROSS_DISSOLVE_V1"),durationFrames:z4.int().min(2).max(30)})]);import{z as z5}from"zod";var sha=z5.string().regex(/^[0-9a-f]{64}$/);var GraphicPlacementSchema=z5.strictObject({startFrame:z5.int().nonnegative().max(1800),endFrame:z5.int().positive().max(1800),anchor:z5.enum(["TOP_LEFT","TOP_RIGHT","BOTTOM_LEFT","BOTTOM_RIGHT"]),widthPermille:z5.int().min(50).max(400),marginXPermille:z5.int().min(0).max(100),marginYPermille:z5.int().min(0).max(100),opacityPermille:z5.int().min(100).max(1e3)}).refine(v=>v.endFrame>v.startFrame,"Graphic frame interval must advance");var TimelineGraphicInputSchema=z5.strictObject({artifactId:ArtifactIdSchema,placement:GraphicPlacementSchema});var TimelineGraphicSourceSchema=z5.strictObject({tenantId:TenantIdSchema,projectId:ProjectIdSchema,productionId:ProductionIdSchema.nullable(),artifactId:ArtifactIdSchema,representationId:ArtifactRepresentationIdSchema,checksumSha256:sha,contentType:z5.enum(["image/png","image/webp"]),byteSize:z5.int().positive().max(16*1024*1024),width:z5.int().positive().max(8192),height:z5.int().positive().max(8192)});var TimelineGraphicSchema=z5.strictObject({source:TimelineGraphicSourceSchema,placement:GraphicPlacementSchema});import{z as z6}from"zod";var id2=z6.uuid().toLowerCase();var hash=z6.string().regex(/^[0-9a-f]{64}$/);var CaptionTranscriptPlacementSchema=z6.discriminatedUnion("kind",[z6.strictObject({kind:z6.literal("AUDIO_TRACK"),purpose:z6.enum(["VOICEOVER","MUSIC"])}),z6.strictObject({kind:z6.literal("SPEECH_CUE"),cueId:z6.string().regex(/^[a-z][a-z0-9_-]{0,63}$/)}),z6.strictObject({kind:z6.literal("TIMELINE_OUTPUT")})]);var CaptionTranscriptPlanSchema=z6.strictObject({tenantId:TenantIdSchema,productionId:ProductionIdSchema,timelineVersionId:id2,language:z6.string().regex(/^[A-Za-z]{2,8}(?:-[A-Za-z0-9]{1,8})*$/).max(60),sources:z6.array(z6.strictObject({observationId:id2,placement:CaptionTranscriptPlacementSchema,granularity:z6.enum(["word","segment"])})).min(1).max(64)});var AuthorTranscriptCaptionsSchema=CaptionTranscriptPlanSchema.extend({expectedProductionRevision:z6.int().positive(),expectedCaptionVersion:z6.int().nonnegative(),idempotencyKey:z6.string().trim().min(1).max(200)});var CaptionTranscriptProvenanceSchema=z6.strictObject({schemaVersion:z6.literal(1),advisory:z6.literal(true),timing:z6.literal("PROVIDER_REPORTED"),timelineVersionId:id2,timingFingerprint:hash,sources:z6.array(z6.strictObject({observationId:id2,artifactId:id2,representationId:id2,checksumSha256:hash,placement:CaptionTranscriptPlacementSchema,granularity:z6.enum(["word","segment"]),sourceInMs:z6.int().nonnegative(),sourceOutMs:z6.int().positive(),startMs:z6.int().nonnegative(),spanIndices:z6.array(z6.int().nonnegative().max(1199)).min(1).max(120),excludedSpans:z6.int().nonnegative().max(1200)})).min(1).max(64)});import{z as z7}from"zod";var sha2=z7.string().regex(/^[0-9a-f]{64}$/);var CaptionContentSchema=z7.strictObject({language:z7.string().regex(/^[A-Za-z]{2,8}(?:-[A-Za-z0-9]{1,8})*$/).max(60),durationMs:z7.int().min(3e4).max(6e4),cues:z7.array(z7.strictObject({startMs:z7.int().nonnegative().max(59999),endMs:z7.int().positive().max(6e4),text:z7.string().min(1).max(240)})).min(1).max(120)});var CaptionScopeSchema=z7.strictObject({tenantId:TenantIdSchema,productionId:ProductionIdSchema});var AuthorCaptionsSchema=CaptionScopeSchema.extend({expectedProductionRevision:z7.int().positive(),expectedCaptionVersion:z7.int().nonnegative(),idempotencyKey:z7.string().trim().min(1).max(200),content:CaptionContentSchema});var CaptionGetSchema=CaptionScopeSchema.extend({versionId:z7.uuid()});var CaptionQuerySchema=CaptionScopeSchema.extend({limit:QueryLimitSchema,next:ContinuationSchema.optional()});var CaptionRepresentationSchema=z7.strictObject({id:z7.uuid(),checksumSha256:sha2,byteSize:z7.int().positive().max(131072)});var CaptionVersionSchema=CaptionScopeSchema.extend({transcriptProvenance:CaptionTranscriptProvenanceSchema.optional(),id:z7.uuid(),captionId:z7.uuid(),projectId:z7.uuid(),version:z7.int().positive(),artifactId:z7.uuid(),content:CaptionContentSchema,fingerprint:sha2,original:CaptionRepresentationSchema,subtitle:CaptionRepresentationSchema,previousVersionId:z7.uuid().nullable(),createdByPrincipalId:z7.uuid(),createdAt:z7.iso.datetime({offset:true})});var CaptionViewSchema=z7.strictObject({version:CaptionVersionSchema,isCurrent:z7.boolean(),availability:z7.enum(["AVAILABLE","UNAVAILABLE"])});var CaptionReceiptSchema=z7.strictObject({semanticStatus:z7.literal("SUCCESS"),version:CaptionVersionSchema,productionRevision:z7.int().positive()});var CaptionBasisSchema=CaptionScopeSchema.extend({productionRevision:z7.int().positive(),currentVersion:z7.int().nonnegative(),currentVersionId:z7.uuid().nullable(),authorable:z7.boolean()});var CaptionPageSchema=z7.strictObject({items:z7.array(CaptionViewSchema).max(200),page:QueryPageInfoSchema});var CaptionExportSchema=CaptionGetSchema.extend({format:z7.enum(["JSON","SRT"])});var CaptionSnapshotSchema=z7.strictObject({currentVersion:z7.int().positive().nullable(),currentVersionId:z7.uuid().nullable(),artifactId:z7.uuid().nullable(),availability:z7.enum(["NONE","AVAILABLE","UNAVAILABLE"]),cueCount:z7.int().nonnegative().max(120),durationMs:z7.int().min(3e4).max(6e4).nullable(),attachedToTimeline:z7.boolean(),attachedCaptionVersionId:z7.uuid().nullable().optional(),attachedTimelineVersionId:z7.uuid().nullable().optional()});var CaptionTranscriptDraftSchema=z7.strictObject({content:CaptionContentSchema,provenance:CaptionTranscriptProvenanceSchema});import{z as z8}from"zod";var LegacyCaptionRenderStyleSchema=z8.strictObject({id:z8.literal("PLAIN_TEXT_NOTO_SANS_SC_V1"),fontSha256:z8.literal("a3041811a78c361b1de50f953c805e0244951c21c5bd412f7232ef0d899af0da"),framePolicy:z8.literal("PTS_HALF_OPEN_CEIL_V1")});var RegularCaptionRenderStyleSchema=z8.strictObject({id:z8.literal("PLAIN_TEXT_NATIVE_SC_REGULAR_V2"),fontSha256:z8.literal("e5a51f41fc1b827da651afee3975e07a182ff4f8e04d9dfc0a3cecd6177a52b6"),framePolicy:z8.literal("PTS_HALF_OPEN_CEIL_V1")});var CaptionRenderStyleSchema=z8.discriminatedUnion("id",[LegacyCaptionRenderStyleSchema,RegularCaptionRenderStyleSchema]);import{z as z9}from"zod";var sha3=z9.string().regex(/^[0-9a-f]{64}$/);var AudioPurposeSchema=z9.enum(["VOICEOVER","MUSIC"]);var AudioProductionScopeSchema=z9.strictObject({tenantId:TenantIdSchema,productionId:ProductionIdSchema});var AudioScopeSchema=AudioProductionScopeSchema.extend({purpose:AudioPurposeSchema});var AudioMediaSchema=z9.strictObject({profile:z9.literal("PCM_S16LE_48000_V1"),audioCodec:z9.literal("pcm_s16le"),sampleRateHz:z9.literal(48e3),audioChannels:z9.union([z9.literal(1),z9.literal(2)]),sampleCount:z9.int().min(4800).max(288e4),durationMs:z9.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:z9.int().positive(),expectedAudioVersion:z9.int().nonnegative(),idempotencyKey:z9.string().trim().min(1).max(200),contentType:z9.literal("audio/wav"),originalName:z9.string().trim().min(1).max(255).regex(/^[^\p{Cc}]*$/u).optional()});var AudioImportRequestSchema=AudioImportSchema.extend({contentBase64:z9.string().min(60).max(16777216).regex(/^[A-Za-z0-9+/]*={0,2}$/)});var AudioGetSchema=AudioScopeSchema.extend({versionId:z9.uuid()});var AudioQuerySchema=AudioScopeSchema.extend({limit:QueryLimitSchema,next:ContinuationSchema.optional()});var AudioRepresentationSchema=z9.strictObject({id:z9.uuid(),checksumSha256:sha3,byteSize:z9.int().min(44).max(12582912)});var AudioVersionSchema=AudioScopeSchema.extend({id:z9.uuid(),audioId:z9.uuid(),projectId:z9.uuid(),version:z9.int().positive(),artifactId:z9.uuid(),original:AudioRepresentationSchema,media:AudioMediaSchema,originalName:z9.string().trim().min(1).max(255).regex(/^[^\p{Cc}]*$/u).nullable(),previousVersionId:z9.uuid().nullable(),createdByPrincipalId:z9.uuid(),createdAt:z9.iso.datetime({offset:true}),generation:z9.strictObject({generationId:z9.uuid(),executionClass:z9.enum(["LIVE","TEST_ONLY"]),sourceArtifactId:z9.uuid(),sourceRepresentationId:z9.uuid(),sourceChecksumSha256:sha3,sourceByteSize:z9.int().min(44).max(12582912),sourceMedia:z9.strictObject({sampleRateHz:z9.int().positive().max(48e3),audioChannels:z9.union([z9.literal(1),z9.literal(2)]),sampleCount:z9.int().positive()}),normalizationVersion:z9.literal("SPEECH_PCM_V1"),padSamples:z9.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=z9.strictObject({version:AudioVersionSchema,isCurrent:z9.boolean(),availability:z9.enum(["AVAILABLE","UNAVAILABLE"])});var AudioReceiptSchema=z9.strictObject({semanticStatus:z9.literal("SUCCESS"),version:AudioVersionSchema,productionRevision:z9.int().positive()});var AudioBasisSchema=AudioScopeSchema.extend({productionRevision:z9.int().positive(),currentVersion:z9.int().nonnegative(),currentVersionId:z9.uuid().nullable(),importable:z9.boolean()});var AudioPageSchema=z9.strictObject({items:z9.array(AudioViewSchema).max(200),page:QueryPageInfoSchema});var AudioSnapshotSchema=z9.strictObject({tracks:z9.array(z9.strictObject({purpose:AudioPurposeSchema,currentVersion:z9.int().positive().nullable(),currentVersionId:z9.uuid().nullable(),artifactId:z9.uuid().nullable(),availability:z9.enum(["NONE","AVAILABLE","UNAVAILABLE"]),durationMs:z9.int().min(100).max(6e4).nullable(),audioChannels:z9.union([z9.literal(1),z9.literal(2)]).nullable(),attachedToTimeline:z9.boolean()})).length(2)});import{z as z10}from"zod";var placement={sourceInMs:z10.int().nonnegative().max(6e4),sourceOutMs:z10.int().positive().max(6e4),startMs:z10.int().nonnegative().max(6e4),gainPermille:z10.int().nonnegative().max(1e3)};var TimelineAudioInputSchema=z10.strictObject({tracks:z10.array(z10.strictObject({purpose:AudioPurposeSchema,versionId:z10.uuid(),...placement})).min(1).max(2),duckingMusicPermille:z10.int().nonnegative().max(1e3).default(1e3)}).superRefine((audio,ctx)=>{if(new Set(audio.tracks.map(t=>t.purpose)).size!==audio.tracks.length||audio.tracks.some(t=>t.sourceOutMs<=t.sourceInMs)||audio.duckingMusicPermille<1e3&&audio.tracks.length!==2)ctx.addIssue({code:"custom",message:"Distinct purposes, advancing trims and explicit ducking pair required"})});var AudioMixProfileSchema=z10.strictObject({id:z10.literal("PCM_WINDOW_MIX_AAC_V1"),sampleRateHz:z10.literal(48e3),audioChannels:z10.literal(2),audioCodec:z10.literal("aac"),bitrate:z10.literal(192e3),peakPermille:z10.literal(950),duckingMusicPermille:z10.int().nonnegative().max(1e3)});var TimelineAudioCompositionSchema=z10.strictObject({mix:AudioMixProfileSchema,tracks:z10.array(z10.strictObject({source:AudioVersionSchema,...placement})).min(1).max(2)}).superRefine((audio,ctx)=>{if(new Set(audio.tracks.map(t=>t.source.purpose)).size!==audio.tracks.length||audio.tracks.some(t=>t.sourceOutMs<=t.sourceInMs||t.sourceOutMs>t.source.media.durationMs)||audio.mix.duckingMusicPermille<1e3&&audio.tracks.length!==2)ctx.addIssue({code:"custom",message:"Invalid exact audio composition"})});var RenderedAudioSchema=z10.strictObject({audioCodec:z10.literal("aac"),sampleRateHz:z10.literal(48e3),audioChannels:z10.literal(2),sampleCount:z10.int().positive().max(288e4)});import{z as z11}from"zod";var Fingerprint=z11.string().regex(/^[0-9a-f]{64}$/);var AcceptedShotReferenceSchema=z11.strictObject({acceptanceId:z11.uuid(),reviewId:z11.uuid(),generationId:z11.uuid(),candidateId:z11.uuid(),shotId:ShotIdSchema,artifactId:ArtifactIdSchema,representationId:ArtifactRepresentationIdSchema,checksumSha256:Fingerprint,artifactChecksumSha256:Fingerprint,preparationId:z11.uuid(),contractId:z11.uuid(),contractFingerprint:Fingerprint,planVersionId:SceneShotPlanVersionIdSchema,planVersion:z11.int().positive(),shotPlanningRevision:z11.int().positive(),executionClass:z11.enum(["LIVE","TEST_ONLY"]),reviewResult:z11.enum(["PASS","WARNING"])});import{z as z12}from"zod";var ProviderIdSchema=z12.enum(["QWEN_CN","VOLCENGINE_CN","GEMINI","OPENAI","XAI"]);var ProviderConnectionIdSchema=z12.uuid().brand();var ModelProfileIdSchema=z12.string().regex(/^[a-z][a-z0-9-]{1,79}$/);var GeometryPolicySchema=z12.enum(["STRICT","PAD_TO_ASPECT"]);var ProviderSelectionSchema=z12.strictObject({connectionId:ProviderConnectionIdSchema,modelProfileId:ModelProfileIdSchema});var ProviderConfigurationSchema=z12.strictObject({providerId:ProviderIdSchema,label:z12.string().trim().min(1).max(100),allowedModelProfileIds:z12.array(ModelProfileIdSchema).min(1).max(16),qwenEndpoint:z12.literal("QIANWEN_PLATFORM").optional(),credentialService:z12.enum(["ARK","DOUBAO_SPEECH"]).optional(),qwenWorkspaceId:z12.string().regex(/^[a-z0-9][a-z0-9-]{0,63}$/).optional(),geometryPolicy:GeometryPolicySchema.default("STRICT")}).superRefine((v,c)=>{if(new Set(v.allowedModelProfileIds).size!==v.allowedModelProfileIds.length)c.addIssue({code:"custom",message:"Duplicate model profile"});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=z12.strictObject({tenantId:TenantIdSchema,connectionId:ProviderConnectionIdSchema,expectedVersion:z12.int().nonnegative(),configuration:ProviderConfigurationSchema,apiKey:z12.string().min(8).max(4096).regex(/^[!-~]+$/)});var ProviderConnectionViewSchema=z12.strictObject({tenantId:TenantIdSchema,connectionId:ProviderConnectionIdSchema,version:z12.int().positive(),enabled:z12.boolean(),credentialConfigured:z12.boolean(),configuration:ProviderConfigurationSchema,createdByPrincipalId:PrincipalIdSchema,updatedAt:z12.iso.datetime({offset:true})});var ProviderConnectionCommandSchema=z12.strictObject({tenantId:TenantIdSchema,connectionId:ProviderConnectionIdSchema,expectedVersion:z12.int().positive()});var ProviderCredentialRevokeSchema=z12.strictObject({tenantId:TenantIdSchema,connectionId:ProviderConnectionIdSchema,version:z12.int().positive()});var SetKeyframeDefaultSchema=z12.strictObject({tenantId:TenantIdSchema,selection:ProviderSelectionSchema,expectedRevision:z12.int().nonnegative()});var ProviderExecutionBindingSchema=z12.strictObject({tenantId:TenantIdSchema,connectionId:ProviderConnectionIdSchema,connectionVersion:z12.int().positive(),providerId:ProviderIdSchema,modelProfileId:ModelProfileIdSchema,modelProfileVersion:z12.int().positive(),modelId:z12.string().min(1).max(160),credentialRef:z12.uuid(),credentialVersion:z12.int().positive(),geometryPolicy:GeometryPolicySchema,qwenEndpoint:z12.literal("QIANWEN_PLATFORM").optional()}).refine(binding=>!binding.qwenEndpoint||binding.providerId==="QWEN_CN",{message:"Qianwen platform binding requires Qwen China"});import{z as z13}from"zod";var GenerationCostVariantSchema=z13.strictObject({mode:z13.enum(["REFERENCE_TO_IMAGE","REFERENCE_TO_VIDEO","FIRST_FRAME_TO_VIDEO","FIRST_LAST_FRAME_TO_VIDEO"]),aspectRatio:z13.enum(["16:9","9:16"]),workingWidth:z13.int().min(0).max(4096),workingHeight:z13.int().min(0).max(4096),hasAudio:z13.boolean(),references:z13.int().min(0).max(24),durationSeconds:z13.number().finite().min(0).max(30)});var GenerationCostPolicySchema=z13.strictObject({currency:z13.literal("USD"),sourceUrl:z13.url({protocol:/^https$/}).max(2e3),rationale:z13.string().trim().min(1).max(2e3),validUntil:z13.iso.datetime({offset:true}),rules:z13.array(z13.strictObject({id:z13.string().regex(/^[a-zA-Z0-9_-]{1,80}$/),variant:GenerationCostVariantSchema,upperBoundMicros:z13.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=z13.strictObject({connectionVersion:z13.int().positive(),modelProfileVersion:z13.int().positive(),quoteValidUntil:z13.iso.datetime({offset:true})});var GenerationCostQuoteSchema=z13.strictObject({currency:z13.literal("USD"),upperBoundMicros:z13.int().nonnegative().max(1e9),selection:ProviderSelectionSchema,expectedExecution:ExpectedGenerationExecutionSchema,sourceUrl:z13.url({protocol:/^https$/}).max(2e3),ruleIds:z13.array(z13.string()).min(1).max(64),preparationId:z13.uuid(),contractFingerprint:z13.string().regex(/^[a-f0-9]{64}$/)});import{z as z14}from"zod";var id3=z14.uuid().toLowerCase();var hash2=z14.string().regex(/^[0-9a-f]{64}$/);var NativeVideoAudioMetadataSchema=z14.strictObject({normalizationVersion:z14.literal("VIDEO_AUDIO_PCM_V1"),sourceCodec:z14.literal("aac"),sourceSampleRateHz:z14.int().min(8e3).max(96e3),sourceChannels:z14.union([z14.literal(1),z14.literal(2)]),sourceFrameRateHz:z14.union([z14.literal(24),z14.literal(30)]),sourceFrameCount:z14.int().positive().max(905),sourceStartOffsetMs:z14.number().finite().min(-500).max(5e3),sourceDeclaredDurationMs:z14.number().positive().max(31e3),alignment:z14.literal("TRIM_PAD_PCM_TO_VIDEO_ZERO_V1"),media:z14.strictObject({profile:z14.literal("PCM_S16LE_48000_NATIVE_VIDEO_V1"),audioCodec:z14.literal("pcm_s16le"),sampleRateHz:z14.literal(48e3),audioChannels:z14.union([z14.literal(1),z14.literal(2)]),sampleCount:z14.int().positive().max(1448e3),durationMs:z14.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=z14.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:z14.int().min(44).max(12582912),metadata:NativeVideoAudioMetadataSchema,executionClass:z14.enum(["LIVE","TEST_ONLY"])});import{z as z15}from"zod";var KeyframePurposeSchema=z15.enum(["START_FRAME","END_FRAME","SUBJECT_REFERENCE"]);var AcceptedKeyframeReferenceSchema=z15.strictObject({acceptanceId:z15.uuid(),reviewId:z15.uuid(),generationId:z15.uuid(),candidateId:z15.uuid(),shotId:ShotIdSchema,framePurpose:KeyframePurposeSchema,artifactId:ArtifactIdSchema,representationId:ArtifactRepresentationIdSchema,checksumSha256:z15.string().regex(/^[0-9a-f]{64}$/),artifactChecksumSha256:z15.string().regex(/^[0-9a-f]{64}$/),planVersionId:SceneShotPlanVersionIdSchema,planVersion:z15.int().positive(),shotPlanningRevision:z15.int().positive(),executionClass:z15.enum(["LIVE","TEST_ONLY"])});import{z as z16}from"zod";var ConsistencyReviewScaleSchema=z16.enum(["INTRA_SHOT","INTER_SHOT","PRODUCTION"]);var State=z16.string().trim().min(1).max(300);var StoryTime=z16.int().nonnegative().max(31536e8);var position=z16.int().min(1).max(999);var StateChange=z16.strictObject({atPermille:position,from:State,to:State,reason:State});var TimeJump=z16.strictObject({atPermille:position,fromMs:StoryTime,toMs:StoryTime,reason:State});var ContinuityExpectationSchema=z16.discriminatedUnion("kind",[z16.strictObject({kind:z16.literal("STATE"),mode:z16.enum(["PRESERVE","PLANNED_TRANSITIONS"]),entry:State,exit:State,changes:z16.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"})}),z16.strictObject({kind:z16.literal("TIME"),mode:z16.enum(["MONOTONIC","PLANNED_JUMPS"]),entryMs:StoryTime,exitMs:StoryTime,jumps:z16.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=z16.strictObject({atMs:z16.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=z16.array(ContinuitySampleSchema).min(3).max(64);import{z as z17}from"zod";var PreparationIdSchema=z17.uuid().brand();var GenerationContractIdSchema=z17.uuid().brand();var ContentFingerprintSchema=z17.string().regex(/^[0-9a-f]{64}$/);var PreparationTargetSchema=z17.discriminatedUnion("mediaType",[z17.strictObject({mediaType:z17.literal("IMAGE"),purpose:z17.enum(["KEYFRAME","REFERENCE_FRAME"]),framePurpose:z17.enum(["START_FRAME","END_FRAME","SUBJECT_REFERENCE"])}),z17.strictObject({mediaType:z17.literal("VIDEO"),purpose:z17.literal("SHOT_CANDIDATE")})]);var PreparationBasisSchema=z17.strictObject({tenantId:TenantIdSchema,projectId:ProjectIdSchema,productionId:ProductionIdSchema,sceneId:SceneIdSchema,shotId:ShotIdSchema,productionRevision:z17.int().positive(),briefVersionId:BriefVersionIdSchema,briefVersion:z17.int().positive(),storyVersionId:StoryVersionIdSchema,storyVersion:z17.int().positive(),planVersionId:SceneShotPlanVersionIdSchema,planVersion:z17.int().positive(),shotPlanningRevision:z17.int().positive(),resolverVersion:z17.literal("w7-product-preflight-v1"),consistencyProfile:z17.strictObject({id:z17.uuid(),version:z17.int().positive(),effectiveFingerprint:ContentFingerprintSchema}).optional()});var ReferenceRoleSchema=z17.enum(["PRODUCT_IDENTITY","PRODUCT_PACKSHOT","CHARACTER_IDENTITY","WARDROBE","LOCATION","STYLE","START_FRAME_ANCHOR","END_FRAME_ANCHOR"]);var ReferenceBindingInputSchema=z17.strictObject({keyframeAcceptanceId:z17.uuid().optional(),role:ReferenceRoleSchema,artifactId:ArtifactIdSchema,representationId:ArtifactRepresentationIdSchema,checksumSha256:ContentFingerprintSchema,reason:z17.string().trim().min(1).max(500)});var ExactEvidenceReferenceSchema=z17.strictObject({artifactId:ArtifactIdSchema,representationId:ArtifactRepresentationIdSchema,checksumSha256:ContentFingerprintSchema,artifactChecksumSha256:ContentFingerprintSchema});var ResolvedReferenceSchema=ReferenceBindingInputSchema.extend({artifactChecksumSha256:ContentFingerprintSchema,contentType:z17.enum(["image/png","image/jpeg","image/webp"]),acceptedKeyframe:AcceptedKeyframeReferenceSchema.optional(),consistencyRuleId:z17.uuid().optional(),subjectId:z17.uuid().optional(),authority:z17.enum(["BRIEF_SOURCE_AND_EXPLICIT_BINDING","EXPLICIT_SHOT_BINDING","CANONICAL_PROFILE_MASTER","ACCEPTED_KEYFRAME_AND_EXPLICIT_BINDING"])});var ResolvedConstraintSchema=z17.strictObject({continuity:ContinuityExpectationSchema.optional(),reviewScales:z17.array(ConsistencyReviewScaleSchema).min(1).max(3).optional(),key:z17.string().min(1).max(200),family:z17.enum(["PRODUCT_IDENTITY","CHARACTER_IDENTITY","WARDROBE","LOCATION","STYLE","SHOT_INTENT","BOUNDARY_CONTINUITY"]),scope:z17.enum(["PROJECT","PRODUCTION","SCENE","SHOT","CONTINUITY_EDGE"]),subjectId:z17.uuid().optional(),dimension:z17.string().regex(/^[A-Z][A-Z0-9_]{0,63}$/).optional(),enforcement:z17.enum(["LOCKED","REQUIRED","PREFERRED"]),expected:z17.string().min(1).max(1e3),source:z17.strictObject({kind:z17.enum(["BRIEF","SCENE","SHOT","CONTINUITY_EDGE","CONSISTENCY_PROFILE"]),id:z17.uuid(),version:z17.int().positive()})});var PreparationBlockerSchema=z17.strictObject({code:z17.enum(["MISSING_PRODUCT_REFERENCE","CANONICAL_SOURCE_UNAVAILABLE","CONSTRAINT_CONFLICT","PREVIOUS_SHOT_EVIDENCE_UNAVAILABLE","GENERATED_KEYFRAME_REQUIRED"]),summary:z17.string().min(1).max(1e3),relatedShotId:ShotIdSchema.optional(),edgeId:ContinuityEdgeIdSchema.optional()});var ConstraintSetSchema=z17.strictObject({preparationId:PreparationIdSchema,version:z17.int().positive(),fingerprint:ContentFingerprintSchema,items:z17.array(ResolvedConstraintSchema).max(2048)});var ReferenceSetSchema=z17.strictObject({preparationId:PreparationIdSchema,version:z17.int().positive(),fingerprint:ContentFingerprintSchema,bindings:z17.array(ResolvedReferenceSchema).max(12)});import{z as z18}from"zod";var VideoGenerationIdSchema=z18.uuid().brand();var VideoProviderProfileSchema=z18.strictObject({id:z18.string().regex(/^[a-z][a-z0-9-]{1,79}$/),adapterVersion:z18.string().min(1).max(80),model:z18.string().min(1).max(160),executionClass:z18.enum(["LIVE","TEST_ONLY"]),mediaType:z18.literal("VIDEO"),modes:z18.array(z18.enum(["REFERENCE_TO_VIDEO","FIRST_FRAME_TO_VIDEO","FIRST_LAST_FRAME_TO_VIDEO"])).min(1).max(3),referenceRoles:z18.array(ReferenceRoleSchema).min(1).max(8),aspectRatios:z18.array(z18.enum(["16:9","9:16"])).min(1).max(2),minDurationSeconds:z18.int().min(1),maxDurationSeconds:z18.int().max(30),maxReferences:z18.int().min(1).max(10),combineAnchorsAndReferences:z18.boolean(),workingWidth:z18.int().positive().max(4096),workingHeight:z18.int().positive().max(4096),frameRate:z18.union([z18.literal(24),z18.literal(30)]),sourceFormat:z18.strictObject({videoCodec:z18.literal("hevc"),pixelFormat:z18.literal("yuv420p10le")}).optional(),hasAudio:z18.boolean(),nativeAudioChannels:z18.union([z18.literal(1),z18.literal(2)]).optional(),correlationStrategy:z18.literal("PROVIDER_TASK_ID")});var VideoStartInputSchema=z18.strictObject({expectedExecution:ExpectedGenerationExecutionSchema.optional(),tenantId:TenantIdSchema,projectId:ProjectIdSchema,productionId:ProductionIdSchema,shotId:ShotIdSchema,preparationId:PreparationIdSchema,contractId:GenerationContractIdSchema,contractFingerprint:ContentFingerprintSchema,selection:ProviderSelectionSchema,idempotencyKey:z18.string().trim().min(1).max(200)});var VideoGetInputSchema=z18.strictObject({tenantId:TenantIdSchema,productionId:ProductionIdSchema,generationId:VideoGenerationIdSchema});var VideoQueryInputSchema=z18.strictObject({tenantId:TenantIdSchema,productionId:ProductionIdSchema,shotId:ShotIdSchema.optional(),limit:QueryLimitSchema,next:ContinuationSchema.optional()});var VideoAdmissionSchema=z18.strictObject({semanticStatus:z18.literal("ACCEPTED"),generationId:VideoGenerationIdSchema,operationId:OperationIdSchema,productionId:ProductionIdSchema,contractId:GenerationContractIdSchema,executionClass:z18.enum(["LIVE","TEST_ONLY"])});var VideoTechnicalMetadataSchema=z18.strictObject({contentType:z18.literal("video/mp4"),checksumSha256:ContentFingerprintSchema,byteSize:z18.int().positive().max(128*1024*1024),width:z18.int().positive().max(4096),height:z18.int().positive().max(4096),durationMs:z18.int().min(1).max(30150),frameRate:z18.number().positive().max(120),videoCodec:z18.enum(["h264","hevc"]),pixelFormat:z18.literal("yuv420p10le").optional(),hasAudio:z18.boolean(),nativeAudio:NativeVideoAudioMetadataSchema.optional()});var VideoPosterSchema=z18.strictObject({representationId:ArtifactRepresentationIdSchema,contentType:z18.literal("image/png"),checksumSha256:ContentFingerprintSchema,byteSize:z18.int().positive().max(2*1024*1024),width:z18.int().positive().max(320),height:z18.int().positive().max(320)});var VideoCandidateSchema=VideoTechnicalMetadataSchema.extend({nativeSound:NativeVideoSoundReferenceSchema.optional(),id:z18.uuid(),artifactId:ArtifactIdSchema,representationId:ArtifactRepresentationIdSchema,poster:VideoPosterSchema,availability:z18.enum(["AVAILABLE","INVALID"]),observation:z18.enum(["NOT_OBSERVED","OBSERVED"]),evaluation:z18.enum(["UNREVIEWED","PASS","WARNING","FAIL"]),accepted:z18.boolean(),reviewId:z18.uuid().optional(),reviewVersion:z18.int().positive().optional(),acceptanceDecisionId:z18.uuid().optional(),freshness:z18.enum(["CURRENT_BASIS","STALE_BASIS"])});var VideoGenerationViewSchema=z18.strictObject({generationId:VideoGenerationIdSchema,tenantId:TenantIdSchema,projectId:ProjectIdSchema,productionId:ProductionIdSchema,shotId:ShotIdSchema,preparationId:PreparationIdSchema,contractId:GenerationContractIdSchema,contractFingerprint:ContentFingerprintSchema,connection:z18.strictObject({connectionId:z18.uuid(),connectionVersion:z18.int().positive(),modelProfileId:z18.string(),modelProfileVersion:z18.int().positive()}),operationId:OperationIdSchema,provider:VideoProviderProfileSchema,runtimeStatus:z18.enum(["PENDING","READY","RUNNING","WAITING","SUCCEEDED","FAILED","CANCELLED","SUPERSEDED"]),providerStatus:z18.enum(["NOT_SUBMITTED","SUBMITTING","PENDING","UNKNOWN","SUCCEEDED","FAILED"]),freshness:z18.enum(["CURRENT_BASIS","STALE_BASIS"]),cancellationRequested:z18.boolean(),candidate:VideoCandidateSchema.nullable(),createdByPrincipalId:PrincipalIdSchema,createdAt:z18.iso.datetime({offset:true})});var VideoQueryPageSchema=z18.strictObject({items:z18.array(VideoGenerationViewSchema),page:QueryPageInfoSchema});var VideoSummarySchema=z18.strictObject({generations:z18.int().nonnegative(),running:z18.int().nonnegative(),waiting:z18.int().nonnegative(),registeredCandidates:z18.int().nonnegative(),testCandidates:z18.int().nonnegative(),liveCandidates:z18.int().nonnegative()});import{z as z19}from"zod";var TimelineDurationSchema=z19.strictObject({totalMs:z19.int().positive().max(603e4),targetMs:z19.int().min(3e4).max(6e4),minMs:z19.literal(3e4),maxMs:z19.literal(6e4),deltaTargetMs:z19.int(),classification:z19.enum(["TOO_SHORT","WITHIN_TARGET","TOO_LONG"])});var TimelineClipSchema=z19.strictObject({ordinal:z19.int().positive().max(200),source:AcceptedShotReferenceSchema,technical:VideoTechnicalMetadataSchema,sourceInMs:z19.int().nonnegative(),sourceOutMs:z19.int().positive(),startMs:z19.int().nonnegative(),durationMs:z19.int().positive(),transition:ClipTransitionSchema,framing:ClipFramingSchema.optional()});var TimelineManifestSchema=z19.strictObject({schemaVersion:z19.literal(1),caption:CaptionVersionSchema.optional(),captionStyle:CaptionRenderStyleSchema.optional(),audio:TimelineAudioCompositionSchema.optional(),graphics:z19.array(TimelineGraphicSchema).max(8).optional(),basis:z19.strictObject({briefVersionId:BriefVersionIdSchema,briefVersion:z19.int().positive(),storyVersion:z19.int().positive(),planVersionId:SceneShotPlanVersionIdSchema,planVersion:z19.int().positive()}),output:z19.strictObject({aspectRatio:z19.enum(["16:9","9:16"]),profile:DeliveryOutputProfileSchema}),clips:z19.array(TimelineClipSchema).min(1).max(200),duration:TimelineDurationSchema,missingPlannedShotIds:z19.array(ShotIdSchema).max(200),executionClass:z19.enum(["LIVE","TEST_ONLY"])});var TimelineVersionIdentityShape={id:z19.uuid(),timelineId:z19.uuid(),tenantId:TenantIdSchema,projectId:ProjectIdSchema,productionId:ProductionIdSchema,version:z19.int().positive(),fingerprint:z19.string().regex(/^[0-9a-f]{64}$/),createdByPrincipalId:PrincipalIdSchema,createdAt:z19.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 z20}from"zod";var RoughCutProfileSchema=z20.strictObject({captionPolicy:z20.literal("BURN_IN").optional(),captionStyle:CaptionRenderStyleSchema.optional(),graphicsPolicy:z20.literal("OVERLAY_V1").optional(),id:z20.literal("PREVIEW_H264_480P_V1"),algorithm:z20.enum(["ORDERED_TRIM_CUT_V1","ORDERED_COMPOSE_V2"]),picturePolicy:PicturePolicySchema.optional(),width:z20.union([z20.literal(854),z20.literal(480)]),height:z20.union([z20.literal(854),z20.literal(480)]),frameRate:z20.literal(30),codec:z20.literal("h264"),pixelFormat:z20.literal("yuv420p"),fit:z20.literal("PAD"),hasAudio:z20.boolean(),audioMix:AudioMixProfileSchema.optional(),framePolicy:z20.literal("CUMULATIVE_NEAREST_FRAME")}).superRefine((profile,context)=>{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"})});import{z as z21}from"zod";var RoughCutManifestSchema=z21.strictObject({schemaVersion:z21.literal(1),timeline:TimelineVersionSchema,profile:RoughCutProfileSchema,frames:z21.array(z21.strictObject({ordinal:z21.int().positive().max(200),startFrame:z21.int().nonnegative().max(1800),frameCount:z21.int().positive().max(1800),overlapFrames:z21.int().nonnegative().max(30).default(0)})).min(1).max(200),totalFrames:z21.int().min(900).max(1800)});import{z as z22}from"zod";var Fingerprint2=z22.string().regex(/^[0-9a-f]{64}$/);var ProgrammaticAcceptedVisualSourceReferenceSchema=z22.strictObject({sourceKind:z22.literal("PROGRAMMATIC"),acceptanceId:z22.uuid(),reviewId:z22.uuid(),renderId:z22.uuid(),compositionId:z22.uuid(),compositionVersionId:z22.uuid(),compositionVersion:z22.int().positive(),compositionFingerprint:Fingerprint2,renderManifestFingerprint:Fingerprint2,shotId:ShotIdSchema,artifactId:ArtifactIdSchema,representationId:ArtifactRepresentationIdSchema,checksumSha256:Fingerprint2,artifactChecksumSha256:Fingerprint2,planVersionId:SceneShotPlanVersionIdSchema,planVersion:z22.int().positive(),shotPlanningRevision:z22.int().positive(),executionClass:z22.enum(["LIVE","TEST_ONLY"]),reviewResult:z22.enum(["PASS","WARNING"])});var ImportedAcceptedVisualSourceReferenceSchema=z22.strictObject({sourceKind:z22.literal("IMPORTED"),acceptanceId:z22.uuid(),reviewId:z22.uuid(),normalizationId:z22.uuid(),sourceId:z22.uuid(),sourceVersionId:z22.uuid(),shotId:ShotIdSchema,artifactId:ArtifactIdSchema,representationId:ArtifactRepresentationIdSchema,checksumSha256:Fingerprint2,executionClass:z22.enum(["LIVE","TEST_ONLY"]),reviewResult:z22.enum(["PASS","WARNING"])});var AcceptedVisualSourceReferenceSchema=z22.union([AcceptedShotReferenceSchema,ProgrammaticAcceptedVisualSourceReferenceSchema,ImportedAcceptedVisualSourceReferenceSchema]);import{z as z23}from"zod";var SourceSoundTreatmentSchema=z23.strictObject({policy:z23.enum(["KEEP","MUTE","DUCK"]),gainPermille:z23.int().min(0).max(1e3),duckingPermille:z23.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 z24}from"zod";var SpeechParameterValueSchema=z24.union([z24.string().max(4096),z24.number().finite(),z24.boolean(),z24.array(z24.string().max(4096)).max(100),z24.record(z24.string().min(1).max(100),z24.string().max(4096)).refine(v=>Object.keys(v).length<=100)]);var SpeechParameterRuleSchema=z24.strictObject({label:z24.string().trim().min(1).max(100).regex(/^[^\p{Cc}]*$/u),type:z24.enum(["NUMBER","INTEGER","STRING","BOOLEAN","STRING_ARRAY","STRING_MAP"]),required:z24.boolean().default(false),min:z24.number().optional(),max:z24.number().optional(),maxLength:z24.int().positive().max(4096).optional(),options:z24.array(z24.string().min(1).max(100)).max(100).optional(),default:SpeechParameterValueSchema.optional(),unit:z24.string().max(40).optional(),description:z24.string().max(500).optional(),maxItems:z24.int().positive().max(100).optional(),maxKeyLength:z24.int().positive().max(100).optional()});var SpeechParametersSchema=z24.record(z24.string().regex(/^[a-z][a-z0-9_]{0,49}$/),SpeechParameterValueSchema).refine(p=>Object.keys(p).length<=24);var SpeechModelProfileSchema=z24.strictObject({id:ModelProfileIdSchema,version:z24.int().positive(),providerId:ProviderIdSchema,modelId:z24.string().min(1).max(160).nullable(),protocol:z24.enum(["QWEN_TTS","QWEN_AUDIO_TTS","OPENAI_TTS","XAI_TTS","GEMINI_INTERACTIONS_TTS","VOLCENGINE_TTS"]),label:z24.string().trim().min(1).max(100).regex(/^[^\p{Cc}]*$/u),textMaxCharacters:z24.int().positive().max(6e3),requestTimeoutMs:z24.int().positive().max(3e5),workspaceRequired:z24.boolean(),voices:z24.array(z24.strictObject({id:z24.string().min(1).max(100),label:z24.string().min(1).max(100),languages:z24.array(z24.string().min(2).max(20)).min(1).max(32).optional(),parameterDefaults:SpeechParametersSchema.optional(),parameterOptions:z24.record(z24.string(),z24.array(z24.string().min(1).max(100)).min(1).max(100)).optional(),unsupportedParameters:z24.array(z24.string()).max(24).optional()})).min(1).max(100),languages:z24.array(z24.string().min(2).max(20)).min(1).max(32),parameters:z24.record(z24.string().regex(/^[a-z][a-z0-9_]{0,49}$/),SpeechParameterRuleSchema),sourceUrl:z24.url().max(2048),verifiedAt:z24.iso.date(),providerTextMaxCharacters:z24.int().positive().nullable(),resourceId:z24.string().min(1).max(100).nullable(),output:z24.literal("PCM_S16LE_48000_V1"),normalizationVersion:z24.literal("SPEECH_PCM_V1")});var SpeechScopeSchema=z24.strictObject({tenantId:TenantIdSchema,productionId:ProductionIdSchema});var SpeechExecutionBindingSchema=z24.strictObject({tenantId:TenantIdSchema,connectionId:z24.uuid(),connectionVersion:z24.int().positive(),credentialRef:z24.uuid(),credentialVersion:z24.int().positive(),profile:SpeechModelProfileSchema,executionClass:z24.enum(["LIVE","TEST_ONLY"])});var SpeechStartSchema=SpeechScopeSchema.extend({soundCue:z24.strictObject({soundPlanVersionId:z24.uuid(),cueId:z24.string().regex(/^[a-z][a-z0-9_-]{0,63}$/)}).optional(),expectedProductionRevision:z24.int().positive(),expectedAudioVersion:z24.int().nonnegative(),expectedModelProfileVersion:z24.int().positive(),idempotencyKey:z24.string().trim().min(1).max(200),selection:ProviderSelectionSchema,text:z24.string().min(1).max(6e3).refine(s=>s.trim().length>0&&!s.includes("\0")),voice:z24.string().min(1).max(100),parameters:SpeechParametersSchema.default({})});var SpeechGetSchema=SpeechScopeSchema.extend({generationId:z24.uuid()});var SpeechAdmissionSchema=z24.strictObject({semanticStatus:z24.literal("ACCEPTED"),generationId:z24.uuid(),runtimeJobId:z24.uuid(),productionRevision:z24.int().positive(),executionClass:z24.enum(["LIVE","TEST_ONLY"])});var SpeechGenerationViewSchema=SpeechAdmissionSchema.omit({semanticStatus:true}).extend({tenantId:TenantIdSchema,productionId:ProductionIdSchema,soundCue:SpeechStartSchema.shape.soundCue,text:z24.string().min(1).max(6e3),voice:z24.string().min(1).max(100),parameters:SpeechParametersSchema,profile:SpeechModelProfileSchema,connectionId:z24.uuid(),connectionVersion:z24.int().positive(),runtimeStatus:z24.enum(["PENDING","READY","RUNNING","WAITING","SUCCEEDED","FAILED","CANCELLED","SUPERSEDED"]),providerStatus:z24.enum(["NOT_SUBMITTED","SUBMITTING","UNKNOWN","SUCCEEDED","REJECTED"]),cancellationRequested:z24.boolean(),result:AudioReceiptSchema.nullable(),createdAt:z24.iso.datetime({offset:true})});var SpeechOptionsSchema=SpeechScopeSchema.extend({options:z24.array(z24.strictObject({selection:ProviderSelectionSchema,profile:SpeechModelProfileSchema,connectionLabel:z24.string().min(1).max(100),connectionVersion:z24.int().positive()})).max(100),possiblyTruncated:z24.boolean()});import{z as z25}from"zod";var KeyframeGenerationIdSchema=z25.uuid().brand();var KeyframeProviderProfileSchema=z25.strictObject({id:z25.string().regex(/^[a-zA-Z0-9][a-zA-Z0-9_.-]{0,79}$/),adapterVersion:z25.string().min(1).max(80),model:z25.string().min(1).max(120),executionClass:z25.enum(["LIVE","TEST_ONLY"]),mediaType:z25.literal("IMAGE"),mode:z25.literal("REFERENCE_TO_IMAGE"),referenceRoles:z25.array(ReferenceRoleSchema).min(1).max(6),aspectRatios:z25.array(z25.enum(["16:9","9:16"])).min(1).max(2),maxReferences:z25.int().min(1).max(12),correlationLookup:z25.boolean()});var KeyframeStartInputSchema=z25.strictObject({expectedExecution:ExpectedGenerationExecutionSchema.optional(),selection:ProviderSelectionSchema.optional(),tenantId:TenantIdSchema,projectId:ProjectIdSchema,productionId:ProductionIdSchema,shotId:ShotIdSchema,preparationId:PreparationIdSchema,contractId:GenerationContractIdSchema,contractFingerprint:ContentFingerprintSchema,idempotencyKey:z25.string().trim().min(1).max(200)});var KeyframeGetInputSchema=z25.strictObject({tenantId:TenantIdSchema,productionId:ProductionIdSchema,generationId:KeyframeGenerationIdSchema});var KeyframeQueryInputSchema=z25.strictObject({tenantId:TenantIdSchema,productionId:ProductionIdSchema,shotId:ShotIdSchema.optional(),limit:QueryLimitSchema,next:ContinuationSchema.optional()});var KeyframeAdmissionSchema=z25.strictObject({semanticStatus:z25.literal("ACCEPTED"),generationId:KeyframeGenerationIdSchema,operationId:OperationIdSchema,productionId:ProductionIdSchema,contractId:GenerationContractIdSchema,executionClass:z25.enum(["LIVE","TEST_ONLY"])});var KeyframeCandidateSchema=z25.strictObject({id:z25.uuid(),artifactId:ArtifactIdSchema,representationId:ArtifactRepresentationIdSchema,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"]),checksumSha256:ContentFingerprintSchema,contentType:z25.enum(["image/png","image/jpeg","image/webp"]),byteSize:z25.int().positive(),width:z25.int().positive(),height:z25.int().positive()});var KeyframeGenerationViewSchema=z25.strictObject({connection:z25.strictObject({connectionId:z25.uuid(),connectionVersion:z25.int().positive(),modelProfileId:z25.string(),modelProfileVersion:z25.int().positive()}).optional(),generationId:KeyframeGenerationIdSchema,tenantId:TenantIdSchema,projectId:ProjectIdSchema,productionId:ProductionIdSchema,shotId:ShotIdSchema,preparationId:PreparationIdSchema,contractId:GenerationContractIdSchema,contractFingerprint:ContentFingerprintSchema,operationId:OperationIdSchema,provider:KeyframeProviderProfileSchema,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:KeyframeCandidateSchema.nullable(),createdByPrincipalId:PrincipalIdSchema,createdAt:z25.iso.datetime({offset:true})});var KeyframeQueryPageSchema=z25.strictObject({items:z25.array(KeyframeGenerationViewSchema),page:QueryPageInfoSchema});var KeyframeMediaSchema=z25.strictObject({contentType:z25.enum(["image/png","image/jpeg","image/webp"]),checksumSha256:ContentFingerprintSchema,byteSize:z25.int().positive().max(8*1024*1024),contentBase64:z25.string().min(4).max(4*Math.ceil(8*1024*1024/3))});var KeyframeSummarySchema=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()});import{z as z26}from"zod";var MatrixParameterRuleSchema=SpeechParameterRuleSchema.extend({numberOptions:z26.array(z26.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"})});import{z as z27}from"zod";var AsrProfileSchema=z27.strictObject({id:ModelProfileIdSchema,version:z27.int().positive(),providerId:ProviderIdSchema,sourceUrl:z27.url().max(2048),verifiedAt:z27.iso.date(),modelId:z27.string().min(1).max(160),label:z27.string().min(1).max(100),protocol:z27.enum(["OPENAI_TRANSCRIPTION_V1","OPENAI_WHISPER_TRANSCRIPTION_V1","QWEN_ASR_V1"]),modes:z27.tuple([z27.literal("TRANSCRIPTION")]),inputKinds:z27.array(z27.enum(["AUDIO","VIDEO"])).min(1).max(2),requestTimeoutMs:z27.int().min(1e3).max(18e4),maxBytes:z27.int().positive().max(12582912),maxDurationMs:z27.int().positive().max(6e4),parameters:z27.record(z27.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(([key4,rule])=>fields[key4]!==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:z27.literal(1),text:z27.string().max(6e4),languages:z27.array(z27.string().min(2).max(40)).max(32)};var TimedText=z27.strictObject({text:z27.string().min(1).max(2500),startMs:z27.int().nonnegative().max(6e4),endMs:z27.int().positive().max(6e4)}).refine(v=>v.endMs>v.startMs,"Transcript interval must advance");var TranscriptSchema=z27.discriminatedUnion("timing",[z27.strictObject({...TranscriptText,timing:z27.literal("UNAVAILABLE")}),z27.strictObject({...TranscriptText,timing:z27.literal("PROVIDER_REPORTED"),timeBase:z27.literal("ORIGINAL_MEDIA_MS"),granularities:z27.array(z27.enum(["word","segment"])).min(1).max(2),words:z27.array(TimedText).max(1200),segments:z27.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"})}})]);import{z as z28}from"zod";var ObservationModeSchema=z28.enum(["AUDIO","AUDIOVISUAL","VIDEO","VIDEO_ALL_FRAMES","TRANSCRIPTION"]);var ObservationParametersSchema=SpeechParametersSchema;var VisualObservationProfileSchema=z28.strictObject({id:ModelProfileIdSchema,version:z28.int().positive(),providerId:ProviderIdSchema,sourceUrl:z28.url().max(2048),modelId:z28.string().min(1).max(160),label:z28.string().min(1).max(100),protocol:z28.enum(["GEMINI_INTERACTIONS_V1","QIANWEN_VIDEO_V1"]),modes:z28.array(z28.enum(["AUDIO","AUDIOVISUAL","VIDEO","VIDEO_ALL_FRAMES"])).min(1).max(4),requestTimeoutMs:z28.int().min(1e3).max(18e4),maxBytes:z28.int().positive().max(12582912),maxDurationMs:z28.int().positive().max(6e4),parameters:z28.record(z28.string(),z28.strictObject({type:z28.enum(["NUMBER","INTEGER","BOOLEAN","STRING"]),min:z28.number().optional(),max:z28.number().optional(),options:z28.array(z28.string()).max(20).optional(),default:z28.union([z28.number().finite(),z28.boolean(),z28.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=z28.union([VisualObservationProfileSchema,AsrProfileSchema]);import{z as z29}from"zod";var ProviderTenantInputSchema=z29.strictObject({tenantId:TenantIdSchema});var ImageModelProfileSchema=z29.strictObject({referenceRoles:z29.array(ReferenceRoleSchema.exclude(["START_FRAME_ANCHOR","END_FRAME_ANCHOR"])).min(1).max(6).optional(),id:ModelProfileIdSchema,version:z29.int().positive(),providerId:ProviderIdSchema,modelId:z29.string().min(1).max(160),protocol:z29.enum(["QWEN_EDIT","ARK_IMAGE","GEMINI_IMAGE","OPENAI_IMAGE","XAI_IMAGE"]),maxReferences:z29.int().positive(),promptMaxUtf8Bytes:z29.int().positive(),requestTimeoutMs:z29.int().positive(),workingWidth:z29.int().nonnegative(),workingHeight:z29.int().nonnegative()});var VideoModelProfileSchema=z29.strictObject({id:ModelProfileIdSchema,version:z29.int().positive(),providerId:ProviderIdSchema,modelId:z29.string().min(1).max(160),protocol:z29.enum(["QWEN_VIDEO","VOLCENGINE_VIDEO"]),requestTimeoutMs:z29.int().positive(),promptMaxCharacters:z29.int().positive(),resolution:z29.enum(["720P","1080P"]),adapterVersion:z29.string().min(1).max(80),capabilities:VideoProviderProfileSchema.omit({id:true,adapterVersion:true,model:true,executionClass:true})});var ProviderDefaultViewSchema=z29.strictObject({selection:ProviderSelectionSchema,revision:z29.int().positive()});var scan=z29.strictObject({limit:z29.literal(100),possiblyTruncated:z29.boolean()});var ProviderConnectionPageSchema=scan.extend({items:z29.array(ProviderConnectionViewSchema).max(100)});var ProviderModelsViewSchema=z29.strictObject({catalog:z29.array(ImageModelProfileSchema).max(100),videoCatalog:z29.array(VideoModelProfileSchema).max(100),speechCatalog:z29.array(SpeechModelProfileSchema).max(100).default([]),observationCatalog:z29.array(ObservationProfileSchema).max(100).default([]),available:z29.array(z29.strictObject({selection:ProviderSelectionSchema,profile:KeyframeProviderProfileSchema})).max(1600),defaultSelection:ProviderDefaultViewSchema.nullable(),connectionScan:scan});import{z as z30}from"zod";var key2=z30.string().regex(/^[A-Za-z][A-Za-z0-9_.-]{0,99}$/);var value=z30.union([z30.string().max(160),z30.number().finite(),z30.boolean()]);var ModelAudioCapabilitySchema=z30.enum(["SYNCHRONIZED_AUDIO","SPEECH_GENERATION","SPEECH_RECOGNITION","TRANSCRIPT_TIMESTAMPS","VOICE_REFERENCE","AUDIO_REFERENCE","AUDIO_DRIVEN_VIDEO","LIP_SYNCHRONIZATION","AUDIO_EDITING","SEPARATE_STEMS"]);var ModelCapabilityMatrixSchema=z30.strictObject({schemaVersion:z30.literal(1),service:key2,lifecycle:z30.enum(["ACTIVE","DEPRECATED","RETIRED"]),sources:z30.array(z30.strictObject({url:z30.url().max(2048),checkedAt:z30.iso.date()})).min(1).max(8),modes:z30.array(key2).min(1).max(16),claims:z30.array(z30.strictObject({capability:ModelAudioCapabilitySchema,modes:z30.array(key2).min(1).max(16),support:z30.enum(["SUPPORTED","UNSUPPORTED","UNKNOWN"]),control:z30.enum(["PARAMETER","PROMPT","ALWAYS_ON","MEDIA_INPUT","NONE"]),parameterPath:key2.optional(),access:z30.enum(["PUBLIC","QUALIFIED_ACCOUNT"]).default("PUBLIC"),description:z30.string().max(600).optional()})).max(64),parameters:z30.record(key2,MatrixParameterRuleSchema),constraints:z30.array(z30.strictObject({modes:z30.array(key2).min(1).max(16),when:z30.strictObject({parameter:key2,equals:value}).optional(),require:z30.array(key2).max(16).default([]),forbid:z30.array(key2).max(16).default([]),requireValues:z30.record(key2,value).default({}),reason:z30.string().min(1).max(300)})).max(32),references:z30.array(z30.strictObject({kind:z30.enum(["VOICE_ID","AUDIO_REFERENCE","DRIVING_AUDIO"]),modes:z30.array(key2).min(1).max(16),parameterPath:key2,maxItems:z30.int().min(1).max(10),minDurationMs:z30.int().positive().optional(),maxDurationMs:z30.int().positive().max(6e4).optional(),maxTotalDurationMs:z30.int().positive().max(6e4).optional(),maxBytes:z30.int().positive().max(67108864).optional(),formats:z30.array(z30.enum(["WAV","MP3"])).max(2),requiresVisual:z30.boolean(),access:z30.enum(["PUBLIC","QUALIFIED_ACCOUNT"])})).max(16),outputAudioChannels:z30.union([z30.literal(1),z30.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 z31}from"zod";var cost={costPolicy:GenerationCostPolicySchema.optional()};var matrix={matrix:ModelCapabilityMatrixSchema.optional()};var ProviderModelDefinitionSchema=z31.discriminatedUnion("family",[z31.strictObject({family:z31.literal("IMAGE"),profile:ImageModelProfileSchema,...matrix,...cost}),z31.strictObject({family:z31.literal("VIDEO"),profile:VideoModelProfileSchema,...matrix,...cost}),z31.strictObject({family:z31.literal("SPEECH"),profile:SpeechModelProfileSchema,...matrix}),z31.strictObject({family:z31.literal("OBSERVATION"),profile:ObservationProfileSchema,...matrix}),z31.strictObject({family:z31.literal("DECLARED"),profile:z31.strictObject({id:ModelProfileIdSchema,version:z31.int().positive(),providerId:ProviderIdSchema,modelId:z31.string().min(1).max(160),protocol:z31.literal("DOCUMENTED_ONLY")}),matrix:ModelCapabilityMatrixSchema})]);var ProviderModelViewSchema=z31.strictObject({tenantId:TenantIdSchema,id:ModelProfileIdSchema,version:z31.int().positive(),enabled:z31.boolean(),definition:ProviderModelDefinitionSchema}).refine(v=>v.id===v.definition.profile.id&&v.version===v.definition.profile.version,{message:"Model version identity mismatch"});var ConfigureProviderModelSchema=z31.strictObject({tenantId:TenantIdSchema,expectedVersion:z31.int().nonnegative(),definition:ProviderModelDefinitionSchema}).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=z31.strictObject({tenantId:TenantIdSchema,id:ModelProfileIdSchema,expectedVersion:z31.int().positive()});var ProviderModelPageSchema=z31.strictObject({items:z31.array(ProviderModelViewSchema).max(100),possiblyTruncated:z31.boolean()});var ProviderModelGetSchema=z31.strictObject({tenantId:TenantIdSchema,id:ModelProfileIdSchema,version:z31.int().positive().optional()});import{z as z32}from"zod";var id4=z32.uuid().toLowerCase();var SoundPlanScopeSchema=z32.strictObject({tenantId:id4,productionId:id4});var SoundPlanBasisSchema=z32.strictObject({briefVersionId:id4,briefVersion:z32.int().positive(),storyVersionId:id4,storyVersion:z32.int().positive(),planVersionId:id4,planVersion:z32.int().positive()});var SoundPlanModelSchema=z32.strictObject({modelProfileId:z32.string().regex(/^[a-z][a-z0-9-]{1,79}$/),modelProfileVersion:z32.int().positive(),connectionId:id4});var SoundMakingPlanContentSchema=z32.strictObject({visuals:z32.array(z32.strictObject({shotId:id4,method:z32.enum(["CODE","GENERATED","IMPORTED"]),model:SoundPlanModelSchema.optional(),nativeAudio:z32.boolean().optional(),sourceSound:SourceSoundTreatmentSchema,rationale:z32.string().trim().min(1).max(600)})).min(1).max(200),cues:z32.array(z32.strictObject({id:z32.string().regex(/^[a-z][a-z0-9_-]{0,63}$/),role:z32.enum(["NARRATION","DIALOGUE","MUSIC","AMBIENCE","SOUND_EFFECT"]),source:z32.enum(["TTS","NATIVE_VIDEO","IMPORTED_AUDIO","EXISTING_AUDIO"]),shotIds:z32.array(id4).min(1).max(200),startMs:z32.int().min(0).max(6e4),endMs:z32.int().positive().max(6e4),text:z32.string().trim().min(1).max(6e3).optional(),voice:z32.string().min(1).max(100).optional(),model:SoundPlanModelSchema.optional(),parameters:SpeechParametersSchema.optional(),audio:z32.strictObject({purpose:z32.enum(["VOICEOVER","MUSIC"]),versionId:z32.uuid()}).optional(),lipSync:z32.enum(["REQUIRED","NONE"]),exactSpeech:z32.boolean()})).max(64),unknowns:z32.array(z32.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||!["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.parameters)||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:id4,soundPlanId:id4,projectId:id4,version:z32.int().positive(),basis:SoundPlanBasisSchema,content:SoundMakingPlanContentSchema,createdByPrincipalId:id4,createdAt:z32.iso.datetime({offset:true})});var SoundPlanValidateSchema=SoundPlanScopeSchema.extend({expectedProductionRevision:z32.int().positive(),basis:SoundPlanBasisSchema,content:SoundMakingPlanContentSchema});var SoundPlanAcceptSchema=SoundPlanValidateSchema.extend({expectedVersion:z32.int().nonnegative(),idempotencyKey:z32.string().trim().min(1).max(200)});var SoundPlanGetSchema=SoundPlanScopeSchema.extend({versionId:id4.optional()});var SoundPlanDiagnosticSchema=z32.strictObject({severity:z32.enum(["ERROR","WARNING"]),code:z32.string().regex(/^[A-Z][A-Z0-9_]{0,79}$/),shotId:id4.optional(),cueId:z32.string().max(64).optional(),message:z32.string().max(500)});var SoundPlanValidationSchema=z32.strictObject({executable:z32.boolean(),diagnostics:z32.array(SoundPlanDiagnosticSchema).max(256),semantics:z32.literal("PLAN_VALIDATION_NOT_CREATIVE_OR_LISTENING_APPROVAL")});var SoundPlanViewSchema=z32.strictObject({version:SoundPlanVersionSchema,current:z32.boolean(),freshness:z32.enum(["CURRENT_BASIS","STALE_BASIS"])});var SoundPlanReceiptSchema=z32.strictObject({semanticStatus:z32.literal("SUCCESS"),version:SoundPlanVersionSchema,productionRevision:z32.int().positive()});var SoundPlanContextSchema=SoundPlanScopeSchema.extend({projectId:id4,productionRevision:z32.int().positive(),runnable:z32.boolean(),basis:SoundPlanBasisSchema.nullable(),targetDurationMs:z32.int().positive().nullable(),shots:z32.array(z32.strictObject({shotId:id4,durationMs:z32.int().positive()})).max(200),currentVersion:z32.int().nonnegative(),currentVersionId:id4.nullable(),capabilities:z32.strictObject({models:z32.array(ProviderModelViewSchema).max(100),video:z32.array(z32.strictObject({selection:ProviderSelectionSchema,profile:VideoProviderProfileSchema})).max(1600),speech:SpeechOptionsSchema.shape.options,audio:z32.array(AudioViewSchema).max(64)})});import{z as z35}from"zod";import{z as z34}from"zod";import{z as z33}from"zod";var id5=z33.uuid().toLowerCase();var hash3=z33.string().regex(/^[0-9a-f]{64}$/);var ImportedSynchronousAudioPurposeSchema=z33.literal("SOURCE_SYNC");var SourceSyncPcmMediaSchema=z33.strictObject({profile:z33.literal("PCM_S16LE_48000_SOURCE_SYNC_V1"),audioCodec:z33.literal("pcm_s16le"),sampleRateHz:z33.literal(48e3),audioChannels:z33.union([z33.literal(1),z33.literal(2)]),sampleCount:z33.int().min(1600).max(576e3),durationMs:z33.number().positive().max(12e3)}).refine(m=>m.sampleCount%1600===0&&m.durationMs===m.sampleCount/48);var ImportedSynchronousAudioExtractionSchema=z33.strictObject({schemaVersion:z33.literal(1),purpose:ImportedSynchronousAudioPurposeSchema,tenantId:id5,projectId:id5,productionId:id5,shotId:id5,sourceId:id5,sourceVersionId:id5,normalizationId:id5,originalArtifactId:id5,originalRepresentationId:id5,originalChecksumSha256:hash3,sourceRange:z33.strictObject({clock:z33.literal("SOURCE_ZERO_BASED_CFR30"),startFrame:z33.int().nonnegative().max(1799),endFrame:z33.int().positive().max(1800)}),destinationStartSample:z33.literal(0)}).refine(v=>v.sourceRange.endFrame>v.sourceRange.startFrame&&v.sourceRange.endFrame-v.sourceRange.startFrame<=360);var ImportedSynchronousAudioSourceSchema=z33.strictObject({schemaVersion:z33.literal(1),purpose:ImportedSynchronousAudioPurposeSchema,tenantId:id5,projectId:id5,productionId:id5,shotId:id5,sourceId:id5,sourceVersionId:id5,normalizationId:id5,originalArtifactId:id5,originalRepresentationId:id5,originalChecksumSha256:hash3,sourceRange:z33.strictObject({clock:z33.literal("SOURCE_ZERO_BASED_CFR30"),startFrame:z33.int().nonnegative(),endFrame:z33.int().positive()}),destinationStartSample:z33.int().nonnegative(),media:z33.union([AudioMediaSchema,SourceSyncPcmMediaSchema]),wavChecksumSha256:hash3,wavByteSize:z33.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 id6=z34.uuid().toLowerCase();var key3=z34.string().trim().min(1).max(200);var SourceSyncAudioStartSchema=z34.strictObject({tenantId:id6,productionId:id6,normalizationId:id6,expectedProductionRevision:z34.int().positive(),expectedVersion:z34.int().nonnegative(),idempotencyKey:key3});var SourceSyncAudioGetSchema=z34.strictObject({tenantId:id6,productionId:id6,shotId:id6,versionId:id6});var SourceSyncAudioVersionSchema=z34.strictObject({schemaVersion:z34.literal(1),purpose:z34.literal("SOURCE_SYNC"),id:id6,audioId:id6,version:z34.int().positive(),tenantId:id6,projectId:id6,productionId:id6,shotId:id6,normalizationId:id6,artifactId:id6,representationId:id6,provenance:ImportedSynchronousAudioSourceSchema,previousVersionId:id6.nullable(),executionClass:z34.enum(["LIVE","TEST_ONLY"]),createdByPrincipalId:id6,createdAt:z34.iso.datetime({offset:true})});var SourceSyncAudioReceiptSchema=z34.strictObject({semanticStatus:z34.literal("SUCCESS"),version:SourceSyncAudioVersionSchema,productionRevision:z34.int().positive()});var SourceSyncAudioViewSchema=z34.strictObject({version:SourceSyncAudioVersionSchema,status:z34.enum(["CURRENT","STALE"]),availability:z34.enum(["AVAILABLE","UNAVAILABLE"])});var TimelineSourceSoundInputSchema=z35.strictObject({duckingMusicPermille:z35.int().nonnegative().max(1e3).optional(),soundPlanVersionId:z35.uuid(),clips:z35.array(z35.strictObject({ordinal:z35.int().min(1).max(200),treatment:SourceSoundTreatmentSchema,importedAudioVersionId:z35.uuid().optional()})).min(1).max(200),speechCues:z35.array(z35.strictObject({cueId:z35.string().regex(/^[a-z][a-z0-9_-]{0,63}$/),audioVersionId:z35.uuid()})).max(64)});var TimelineSourceSoundSourceSchema=z35.discriminatedUnion("kind",[z35.strictObject({kind:z35.literal("NATIVE_GENERATED"),version:NativeVideoSoundReferenceSchema}),z35.strictObject({kind:z35.literal("IMPORTED_SYNC"),version:SourceSyncAudioVersionSchema})]);var TimelineSourceSoundCompositionSchema=z35.strictObject({schemaVersion:z35.literal(1),soundPlanVersionId:z35.uuid(),soundPlanFingerprint:z35.string().regex(/^[0-9a-f]{64}$/),plannedCues:SoundMakingPlanContentSchema.shape.cues,mix:AudioMixProfileSchema,clips:z35.array(z35.strictObject({ordinal:z35.int().min(1).max(200),treatment:SourceSoundTreatmentSchema,source:TimelineSourceSoundSourceSchema.optional(),sourceInSample:z35.int().nonnegative().max(288e4),sourceOutSample:z35.int().nonnegative().max(288e4),startSample:z35.int().nonnegative().max(288e4),outputSampleCount:z35.int().positive().max(288e4)})).min(1).max(200),speechCues:z35.array(z35.strictObject({cueId:z35.string().regex(/^[a-z][a-z0-9_-]{0,63}$/),source:AudioVersionSchema,sourceInMs:z35.literal(0),sourceOutMs:z35.int().positive().max(6e4),startMs:z35.int().nonnegative().max(6e4),gainPermille:z35.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"})});import{z as z36}from"zod";var TimelineV2ClipSchema=TimelineManifestSchema.shape.clips.element.extend({source:AcceptedVisualSourceReferenceSchema});var TimelineV2ManifestSchema=TimelineManifestSchema.extend({schemaVersion:z36.literal(2),clips:z36.array(TimelineV2ClipSchema).min(1).max(200),sourceSound:TimelineSourceSoundCompositionSchema.optional()});var TimelineV2VersionSchema=TimelineV2ManifestSchema.extend(TimelineVersionIdentityShape).superRefine(validateTimelineAttachments);import{z as z37}from"zod";var sha4=z37.string().regex(/^[0-9a-f]{64}$/);var VisualFrameSequenceSchema=z37.strictObject({schemaVersion:z37.literal(1),profileId:z37.literal("RGBA_PNG_SEQUENCE_30_V1"),tenantId:TenantIdSchema,projectId:ProjectIdSchema,productionId:ProductionIdSchema.nullable(),artifactId:ArtifactIdSchema,representationId:ArtifactRepresentationIdSchema,checksumSha256:sha4,width:z37.int().min(1).max(1920),height:z37.int().min(1).max(1920),frameRate:z37.literal(30),frameCount:z37.int().min(1).max(360),alpha:z37.literal("STRAIGHT_RGBA"),frames:z37.array(z37.strictObject({ordinal:z37.int().min(0).max(359),artifactId:ArtifactIdSchema,representationId:ArtifactRepresentationIdSchema,checksumSha256:sha4,byteSize:z37.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=z37.strictObject({xPermille:z37.int().min(0).max(1e3),yPermille:z37.int().min(0).max(1e3),widthPermille:z37.int().min(1).max(1e3),heightPermille:z37.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=z37.strictObject({id:z37.uuid(),source:VisualFrameSequenceSchema,sourceInFrame:z37.int().min(0).max(359),sourceOutFrame:z37.int().min(1).max(360),startFrame:z37.int().min(0).max(1799),zIndex:z37.int().min(0).max(7),opacityPermille:z37.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=z37.strictObject({schemaVersion:z37.literal(1),profileId:z37.literal("STRAIGHT_ALPHA_FRAME_OVERLAY_30_V1"),tenantId:TenantIdSchema,projectId:ProjectIdSchema,productionId:ProductionIdSchema,totalFrames:z37.int().min(1).max(1800),layers:z37.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 source=layer.source;const body=JSON.stringify(source);for(const frame of source.frames){const identity=JSON.stringify({artifactId:frame.artifactId,checksumSha256:frame.checksumSha256,byteSize:frame.byteSize,width:source.width,height:source.height});if(frames.has(frame.representationId)&&frames.get(frame.representationId)!==identity)context.addIssue({code:"custom",message:"Shared frame representation has inconsistent facts"});frames.set(frame.representationId,identity)}if(source.tenantId!==v.tenantId||source.projectId!==v.projectId||source.productionId!==null&&source.productionId!==v.productionId||layer.startFrame+layer.sourceOutFrame-layer.sourceInFrame>v.totalFrames||sources.has(source.representationId)&&sources.get(source.representationId)!==body)context.addIssue({code:"custom",message:"Layer source scope/identity/output bounds mismatch"});if(!sources.has(source.representationId))bytes+=source.frames.reduce((n,f)=>n+f.byteSize,0);sources.set(source.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"})});import{z as z38}from"zod";var TimelineVisualLayerInputSchema=z38.strictObject({id:z38.uuid(),artifactId:ArtifactIdSchema,sourceInFrame:z38.int().min(0).max(359),sourceOutFrame:z38.int().min(1).max(360),startFrame:z38.int().min(0).max(1799),zIndex:z38.int().min(0).max(7),opacityPermille:z38.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:z38.literal(3),visualLayers:VisualLayerCompositionSchema});var TimelineV3VersionSchema=TimelineV3ManifestSchema.extend(TimelineVersionIdentityShape).superRefine((timeline,context)=>{validateTimelineAttachments(timeline,context);validateTimelineVisualLayerClock(timeline,context)});function validateTimelineVisualLayerClock(timeline,context){const composition=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&&composition.tenantId!==timeline.tenantId||timeline.projectId!==void 0&&composition.projectId!==timeline.projectId||timeline.productionId!==void 0&&composition.productionId!==timeline.productionId||composition.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 z39}from"zod";var FinalRenderProfileIdSchema=z39.enum(["FINAL_H264_720P_V1","FINAL_H264_1080P_V1","FINAL_H264_480P_V1"]);var FinalRenderProfileSchema=z39.strictObject({id:FinalRenderProfileIdSchema,algorithm:z39.enum(["ORDERED_TRIM_CUT_V1","ORDERED_COMPOSE_V2"]),picturePolicy:PicturePolicySchema.optional(),width:z39.union([z39.literal(1280),z39.literal(720),z39.literal(1920),z39.literal(1080),z39.literal(854),z39.literal(480)]),height:z39.union([z39.literal(1280),z39.literal(720),z39.literal(1920),z39.literal(1080),z39.literal(854),z39.literal(480)]),frameRate:z39.literal(30),codec:z39.literal("h264"),pixelFormat:z39.literal("yuv420p"),fit:z39.literal("PAD"),hasAudio:z39.boolean(),audioMix:AudioMixProfileSchema.optional(),framePolicy:z39.literal("CUMULATIVE_NEAREST_FRAME"),encoder:z39.literal("libx264"),crf:z39.literal(18),preset:z39.literal("veryfast"),gopFrames:z39.literal(30),bFrames:z39.literal(0),audioPolicy:z39.enum(["SILENT","MIXED"]),captionPolicy:z39.enum(["NONE","BURN_IN"]),sourceQualityPolicy:z39.literal("NO_UPSCALE_V1"),captionStyle:CaptionRenderStyleSchema.optional(),graphicsPolicy:z39.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"})});import{z as z40}from"zod";var dynamicPolicy=z40.literal("STRAIGHT_ALPHA_FRAME_OVERLAY_30_V1");var VisualLayerPreviewProfileSchema=RoughCutProfileSchema.safeExtend({visualLayerPolicy:dynamicPolicy});var VisualLayerFinalProfileSchema=FinalRenderProfileSchema.safeExtend({visualLayerPolicy:dynamicPolicy,visualLayerSourceQualityPolicy:z40.literal("NO_UPSCALE_V1")});var shape={schemaVersion:z40.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=z40.union([VisualLayerPreviewManifestSchema,VisualLayerFinalManifestSchema]);import{z as z41}from"zod";var TimelineVersionReaderSchema=z41.discriminatedUnion("schemaVersion",[TimelineVersionSchema,TimelineV2VersionSchema,TimelineV3VersionSchema]);var TimelineManifestReaderSchema=z41.discriminatedUnion("schemaVersion",[TimelineManifestSchema,TimelineV2ManifestSchema,TimelineV3ManifestSchema.superRefine(validateTimelineVisualLayerClock)]);import{z as z42}from"zod";var TimelineScopeSchema=z42.strictObject({tenantId:TenantIdSchema,productionId:ProductionIdSchema});var TimelineClipInputSchema=z42.strictObject({shotId:ShotIdSchema,acceptanceId:z42.uuid(),framing:ClipFramingSchema.optional(),transition:ClipTransitionSchema.optional(),sourceInMs:z42.int().nonnegative().max(30150),sourceOutMs:z42.int().positive().max(30150)}).refine(v=>v.sourceOutMs>v.sourceInMs,"Clip source range must advance");var BuildTimelineShapeSchema=TimelineScopeSchema.extend({schemaVersion:z42.union([z42.literal(2),z42.literal(3)]).optional(),expectedProductionRevision:z42.int().positive(),expectedTimelineVersion:z42.int().nonnegative(),idempotencyKey:z42.string().trim().min(1).max(200),clips:z42.array(TimelineClipInputSchema).min(1).max(200),captionVersionId:z42.uuid().optional(),audio:TimelineAudioInputSchema.optional(),sourceSound:TimelineSourceSoundInputSchema.optional(),graphics:z42.array(TimelineGraphicInputSchema).max(8).optional(),visualLayers:z42.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=z42.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=z42.strictObject({version:TimelineVersionReaderSchema,isCurrent:z42.boolean(),freshness:z42.enum(["CURRENT_BASIS","STALE_BASIS"]),staleReasons:z42.array(TimelineStaleReasonSchema).max(13),assemblyStatus:z42.enum(["DRAFT","ASSEMBLY_READY"])});var TimelineGetSchema=TimelineScopeSchema.extend({versionId:z42.uuid()});var TimelineQuerySchema=TimelineScopeSchema.extend({limit:QueryLimitSchema,next:ContinuationSchema.optional()});var TimelinePageSchema=z42.strictObject({items:z42.array(TimelineViewSchema),page:QueryPageInfoSchema});var TimelineBuildReceiptSchema=z42.strictObject({semanticStatus:z42.literal("SUCCESS"),version:TimelineVersionReaderSchema,productionRevision:z42.int().positive()});var TimelineBasisSchema=TimelineScopeSchema.extend({productionRevision:z42.int().positive(),currentTimelineVersion:z42.int().nonnegative(),runnable:z42.boolean(),planningReady:z42.boolean(),output:TimelineManifestSchema.shape.output.nullable(),targetDurationMs:z42.int().positive().nullable(),shots:z42.array(z42.strictObject({shotId:ShotIdSchema,ordinal:z42.int().positive(),acceptanceStatus:z42.enum(["NONE","CURRENT","STALE"]),source:AcceptedVisualSourceReferenceSchema.nullable(),technical:VideoTechnicalMetadataSchema.nullable()})).max(200)});var TimelineSnapshotSchema=z42.strictObject({currentVersion:z42.int().positive().nullable(),stale:z42.boolean(),timelineId:z42.uuid().nullable(),versionId:z42.uuid().nullable(),assemblyStatus:z42.enum(["DRAFT","ASSEMBLY_READY"]).nullable(),totalDurationMs:z42.int().positive().nullable(),durationClassification:TimelineDurationSchema.shape.classification.nullable(),missingPlannedShots:z42.int().nonnegative(),staleReasons:z42.array(TimelineStaleReasonSchema).max(13)});import{z as z43}from"zod";var sha5=z43.string().regex(/^[0-9a-f]{64}$/);var RoughCutStartSchema=TimelineScopeSchema.extend({timelineVersionId:z43.uuid(),timelineFingerprint:sha5,expectedProductionRevision:z43.int().positive(),profileId:z43.literal("PREVIEW_H264_480P_V1"),idempotencyKey:z43.string().trim().min(1).max(200)});var RoughCutGetSchema=TimelineScopeSchema.extend({renderId:z43.uuid()});var RoughCutQuerySchema=TimelineScopeSchema.extend({limit:QueryLimitSchema,next:ContinuationSchema.optional()});var RoughCutV2ManifestSchema=RoughCutManifestSchema.extend({schemaVersion:z43.literal(2),timeline:TimelineV2VersionSchema});var RoughCutManifestReaderSchema=z43.discriminatedUnion("schemaVersion",[RoughCutManifestSchema,RoughCutV2ManifestSchema,VisualLayerPreviewManifestSchema]);var RoughCutTechnicalSchema=VideoTechnicalMetadataSchema.extend({hasAudio:z43.boolean(),audio:RenderedAudioSchema.optional(),durationMs:z43.int().min(29983).max(60017),frameRate:z43.literal(30),frameCount:z43.int().min(900).max(1800),engineVersion:z43.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:z43.uuid(),representationId:z43.uuid(),version:z43.int().positive(),poster:VideoPosterSchema,availability:z43.enum(["AVAILABLE","INVALID"]),reviewState:z43.enum(["UNREVIEWED","PASS","WARNING","FAIL"])});var RoughCutAdmissionSchema=z43.strictObject({semanticStatus:z43.literal("ACCEPTED"),renderId:z43.uuid(),operationId:OperationIdSchema,productionId:z43.uuid(),timelineVersionId:z43.uuid(),timelineFingerprint:sha5,executionClass:z43.enum(["LIVE","TEST_ONLY"]),manifestFingerprint:sha5,productionRevision:z43.int().positive()});var RoughCutViewSchema=TimelineScopeSchema.extend({renderId:z43.uuid(),projectId:ProjectIdSchema,runtimeJobId:z43.uuid(),operationId:OperationIdSchema,manifest:RoughCutManifestReaderSchema,manifestFingerprint:sha5,runtimeStatus:VideoGenerationViewSchema.shape.runtimeStatus,cancellationRequested:z43.boolean(),isCurrentTimeline:z43.boolean(),freshness:z43.enum(["CURRENT_BASIS","STALE_BASIS"]),staleReasons:z43.array(z43.string().min(1).max(120)).max(16),executionClass:z43.enum(["LIVE","TEST_ONLY"]),roughCut:RoughCutArtifactSchema.nullable(),createdByPrincipalId:PrincipalIdSchema,createdAt:z43.iso.datetime({offset:true})});var RoughCutPageSchema=z43.strictObject({items:z43.array(RoughCutViewSchema),page:QueryPageInfoSchema});var RoughCutSnapshotSchema=z43.strictObject({latestVersion:z43.int().positive().nullable(),reviewState:z43.enum(["UNREVIEWED","PASS","WARNING","FAIL"]).nullable(),latestRenderId:z43.uuid().nullable(),runtimeStatus:VideoGenerationViewSchema.shape.runtimeStatus.nullable(),currentRenderId:z43.uuid().nullable(),currentArtifactId:z43.uuid().nullable(),currentTimelineVersionId:z43.uuid().nullable(),stale:z43.boolean()});import{z as z44}from"zod";var TemporalEvidenceReferenceSchema=z44.strictObject({evidenceId:z44.uuid(),frameSetArtifactId:z44.uuid(),contactSheetArtifactId:z44.uuid(),manifestRepresentationId:z44.uuid(),sheetRepresentationId:z44.uuid(),planFingerprint:z44.string().regex(/^[0-9a-f]{64}$/),sourceArtifactId:z44.uuid(),sourceRepresentationId:z44.uuid(),sourceChecksumSha256:z44.string().regex(/^[0-9a-f]{64}$/),timestampsMs:z44.array(z44.number().nonnegative().max(6e4)).min(1).max(64),executionClass:z44.enum(["LIVE","TEST_ONLY"])});var TemporalEvidenceIdsSchema=z44.array(z44.uuid()).min(1).max(8).refine(v=>new Set(v).size===v.length,"Evidence references must be unique");import{z as z45}from"zod";var ListeningEvidenceIdsSchema=z45.array(z45.string().min(1).max(100)).max(64);var ListeningEvidenceSchema=z45.strictObject({id:z45.string().trim().min(1).max(100),kind:z45.enum(["AUDIO_LISTENING","VIDEO_WITH_AUDIO_PLAYBACK"]),media:z45.strictObject({artifactId:z45.uuid(),representationId:z45.uuid(),checksumSha256:z45.string().regex(/^[0-9a-f]{64}$/)}),coverage:z45.array(z45.strictObject({startMs:z45.int().nonnegative().max(6e4),endMs:z45.int().positive().max(6e4)}).refine(v=>v.endMs>v.startMs)).min(1).max(200),producer:z45.string().trim().min(1).max(200)});var ListeningEvidenceSetSchema=z45.array(ListeningEvidenceSchema).max(64).refine(v=>new Set(v.map(e=>e.id)).size===v.length);import{z as z46}from"zod";var sha6=z46.string().regex(/^[0-9a-f]{64}$/);var CompositionFindingLocalitySchema=z46.strictObject({schemaVersion:z46.literal(1),sourceKind:z46.literal("CODE"),role:z46.enum(["PRIMARY_VISUAL","VISUAL_LAYER"]),compositionId:z46.uuid(),compositionVersionId:z46.uuid(),compositionVersion:z46.int().positive(),compositionFingerprint:sha6,renderId:z46.uuid(),renderManifestFingerprint:sha6,artifactId:z46.uuid(),representationId:z46.uuid(),checksumSha256:sha6,clipOrdinal:z46.int().min(1).max(200).nullable(),visualLayerId:z46.uuid().nullable(),sourceInFrame:z46.int().min(0).max(359),sourceOutFrame:z46.int().min(1).max(360),mapping:z46.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 z47}from"zod";var CanonicalFactSchema=z47.strictObject({key:z47.string().regex(/^[A-Z][A-Z0-9_]{1,59}$/),value:z47.string().trim().min(1).max(300),sourceArtifactId:ArtifactIdSchema,evidence:z47.discriminatedUnion("kind",[z47.strictObject({kind:z47.literal("JSON_POINTER"),pointer:z47.string().startsWith("/").max(200)}),z47.strictObject({kind:z47.literal("EXACT_TEXT_LINE")})])});var BriefContentSchema=z47.strictObject({objective:z47.string().trim().min(1).max(1e3),productPresentationGoal:z47.string().trim().min(1).max(1e3),audience:z47.string().trim().min(1).max(300).optional(),styleTone:z47.string().trim().min(1).max(300).optional(),callToAction:z47.string().trim().min(1).max(300).optional(),targetDurationSeconds:z47.int().min(30).max(60),aspectRatio:z47.enum(["16:9","9:16"]),outputProfile:DeliveryOutputProfileSchema,canonicalFacts:z47.array(CanonicalFactSchema).max(32).default([])});var AcceptBriefRequestSchema=z47.strictObject({tenantId:TenantIdSchema,expectedProductionRevision:z47.int().positive(),revisionReason:z47.string().trim().min(1).max(1e3).optional(),sourceArtifactIds:z47.array(ArtifactIdSchema).max(20).default([]),content:BriefContentSchema});var BriefSourceReferenceSchema=z47.strictObject({artifactId:ArtifactIdSchema,checksumSha256:z47.string().regex(/^[0-9a-f]{64}$/)});var BriefVersionSchema=z47.strictObject({id:BriefVersionIdSchema,briefId:BriefIdSchema,tenantId:TenantIdSchema,projectId:ProjectIdSchema,productionId:ProductionIdSchema,version:z47.int().positive(),content:BriefContentSchema,sources:z47.array(BriefSourceReferenceSchema).min(1).max(20),createdByPrincipalId:PrincipalIdSchema,createdAt:z47.iso.datetime({offset:true})});var AcceptBriefResultSchema=z47.discriminatedUnion("semanticStatus",[z47.strictObject({semanticStatus:z47.literal("SUCCESS"),briefVersion:BriefVersionSchema,productionRevision:z47.int().positive(),activeBriefVersion:z47.int().positive()}),z47.strictObject({semanticStatus:z47.literal("NEEDS_INPUT"),missingFacts:z47.array(z47.enum(["PRODUCT_INFORMATION_SOURCE","PRODUCT_NAME"])).min(1)})]);import{z as z48}from"zod";var StoryFactKeySchema=z48.string().regex(/^[A-Z][A-Z0-9_]{1,59}$/);var StoryFactClaimSchema=z48.strictObject({key:StoryFactKeySchema,value:z48.string().trim().min(1).max(300)});var StoryBeatSchema=z48.strictObject({summary:z48.string().trim().min(1).max(600),sceneRequirements:z48.array(z48.string().trim().min(1).max(300)).max(8).default([])});var StoryContentSchema=z48.strictObject({narrativeIntent:z48.string().trim().min(1).max(2e3),beats:z48.array(StoryBeatSchema).min(1).max(24),factualClaims:z48.array(StoryFactClaimSchema).max(32).default([])});var AcceptStoryRequestSchema=z48.strictObject({tenantId:TenantIdSchema,expectedProductionRevision:z48.int().positive(),expectedBriefVersion:z48.int().positive(),revisionReason:z48.string().trim().min(1).max(1e3).optional(),idempotencyKey:z48.string().trim().min(1).max(200),content:StoryContentSchema});var StoryVersionSchema=z48.strictObject({id:StoryVersionIdSchema,storyId:StoryIdSchema,tenantId:TenantIdSchema,projectId:ProjectIdSchema,productionId:ProductionIdSchema,version:z48.int().positive(),briefVersionId:BriefVersionIdSchema,briefVersion:z48.int().positive(),content:StoryContentSchema,createdByPrincipalId:PrincipalIdSchema,createdAt:z48.iso.datetime({offset:true})});var AcceptStoryResultSchema=z48.discriminatedUnion("semanticStatus",[z48.strictObject({semanticStatus:z48.literal("SUCCESS"),storyVersion:StoryVersionSchema,productionRevision:z48.int().positive(),activeStoryVersion:z48.int().positive()}),z48.strictObject({semanticStatus:z48.literal("NEEDS_INPUT"),missingPrerequisites:z48.array(z48.literal("ACTIVE_BRIEF")).min(1)})]);import{z as z49}from"zod";var ConsistencyFamilySchema=z49.enum(["PRODUCT_IDENTITY","CHARACTER_IDENTITY","WARDROBE","LOCATION","BOUNDARY_CONTINUITY","STYLE","VOICE_IDENTITY"]);var ConsistencyEnforcementSchema=z49.enum(["LOCKED","REQUIRED","PREFERRED","FREE"]);var ConsistencyMasterReferenceSchema=z49.strictObject({artifactId:ArtifactIdSchema,representationId:ArtifactRepresentationIdSchema,checksumSha256:z49.string().regex(/^[0-9a-f]{64}$/),artifactChecksumSha256:z49.string().regex(/^[0-9a-f]{64}$/),contentType:z49.enum(["image/png","image/jpeg","image/webp","audio/wav"])});var Fact=z49.strictObject({dimension:z49.string().regex(/^[A-Z][A-Z0-9_]{0,63}$/),value:z49.string().trim().min(1).max(1e3)});var ConsistencySubjectSchema=z49.strictObject({id:z49.uuid(),kind:z49.enum(["CHARACTER","VOICE"]),displayName:z49.string().trim().min(1).max(200),facts:z49.array(Fact).min(1).max(32),master:ConsistencyMasterReferenceSchema}).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"})});var ConsistencyRuleScopeSchema=z49.discriminatedUnion("kind",[z49.strictObject({kind:z49.literal("PROJECT")}),z49.strictObject({kind:z49.literal("PRODUCTION")}),z49.strictObject({kind:z49.literal("SCENE"),id:z49.uuid()}),z49.strictObject({kind:z49.literal("SHOT"),id:z49.uuid()}),z49.strictObject({kind:z49.literal("CONTINUITY_EDGE"),id:z49.uuid()})]);var ConsistencyRuleSchema=z49.strictObject({reviewScales:z49.array(ConsistencyReviewScaleSchema).min(1).max(3).refine(s=>new Set(s).size===s.length,"Review scales must be unique").optional(),continuity:ContinuityExpectationSchema.optional(),id:z49.uuid(),family:ConsistencyFamilySchema,subjectId:z49.uuid().nullable(),dimension:z49.string().regex(/^[A-Z][A-Z0-9_]{0,63}$/),scope:ConsistencyRuleScopeSchema,enforcement:ConsistencyEnforcementSchema,expected:z49.string().trim().min(1).max(1e3).nullable(),referenceMode:z49.enum(["NONE","SUBJECT_MASTER","EXACT"]),reference:ConsistencyMasterReferenceSchema.optional(),override:z49.strictObject({priorRuleId:z49.uuid(),reason:z49.string().trim().min(1).max(1e3)}).optional(),transition:z49.strictObject({edgeId:z49.uuid(),from:z49.string().trim().min(1).max(1e3),to:z49.string().trim().min(1).max(1e3),reason:z49.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.reviewScales)invalid("Native Voice review remains inactive");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=z49.strictObject({subjects:z49.array(ConsistencySubjectSchema).max(32),rules:z49.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");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(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=z49.strictObject({tenantId:TenantIdSchema,productionId:ProductionIdSchema});var ConsistencyProfileVersionQuerySchema=ConsistencyProfileScopeSchema.extend({profileId:z49.uuid()});var ConfigureConsistencyProfileSchema=ConsistencyProfileScopeSchema.extend({expectedProductionRevision:z49.int().positive(),expectedProfileVersion:z49.int().nonnegative(),content:ConsistencyProfileContentSchema,reason:z49.string().trim().min(1).max(2e3),idempotencyKey:z49.string().trim().min(1).max(200)});var ConsistencyProfileVersionSchema=ConsistencyProfileScopeSchema.extend({id:z49.uuid(),projectId:ProjectIdSchema,version:z49.int().positive(),previousVersionId:z49.uuid().nullable(),content:ConsistencyProfileContentSchema,fingerprint:z49.string().regex(/^[0-9a-f]{64}$/),reason:z49.string().trim().min(1).max(2e3),createdByPrincipalId:PrincipalIdSchema,createdAt:z49.iso.datetime({offset:true})});var ConsistencyProfileViewSchema=ConsistencyProfileScopeSchema.extend({productionRevision:z49.int().positive(),current:ConsistencyProfileVersionSchema.nullable()});var ConsistencyProfileReceiptSchema=z49.strictObject({semanticStatus:z49.literal("SUCCESS"),profile:ConsistencyProfileVersionSchema,productionRevision:z49.int().positive()});import{z as z50}from"zod";var sha7=z50.string().regex(/^[0-9a-f]{64}$/);var RoughCutReviewScopeSchema=TimelineScopeSchema.extend({renderId:z50.uuid()});var ReviewIntervalSchema=z50.strictObject({startMs:z50.int().nonnegative().max(6e4),endMs:z50.int().positive().max(6e4)}).refine(v=>v.endMs>v.startMs,"Review interval must advance");var RoughCutRequirementSchema=z50.strictObject({continuity:ContinuityExpectationSchema.optional(),consistencyScale:ConsistencyReviewScaleSchema.optional(),consistencyFamily:z50.enum(["PRODUCT_IDENTITY","CHARACTER_IDENTITY","WARDROBE","LOCATION","STYLE","BOUNDARY_CONTINUITY"]).optional(),consistencySubject:ConsistencySubjectSchema.optional(),consistencyReference:ConsistencyMasterReferenceSchema.optional(),key:z50.string().min(1).max(220),dimension:z50.enum(["PRODUCT_PRESENTATION","CANONICAL_FACT","NARRATIVE","PACING","REPETITION","STYLE","TECHNICAL","TRANSITION"]),expected:z50.string().min(1).max(4e3),enforcement:z50.enum(["LOCKED","REQUIRED","PREFERRED"]),scope:z50.enum(["PRODUCTION","TRANSITION"]),interval:ReviewIntervalSchema,shotIds:z50.array(z50.uuid()).min(1).max(200)});var RoughCutObservationSchema=z50.strictObject({listeningEvidenceIds:ListeningEvidenceIdsSchema.optional(),continuitySamples:ContinuitySamplesSchema.optional(),temporalEvidenceIds:TemporalEvidenceIdsSchema.optional(),key:z50.string().min(1).max(220),status:z50.enum(["SATISFIED","VIOLATED","NOT_OBSERVABLE","NOT_APPLICABLE"]),confidence:z50.enum(["CLEAR","UNCERTAIN"]),observed:z50.string().trim().min(1).max(1800),interval:ReviewIntervalSchema,location:z50.strictObject({interval:ReviewIntervalSchema,shotIds:z50.array(z50.uuid()).min(1).max(200)}).optional()});var RoughCutInspectionSchema=z50.strictObject({actor:z50.enum(["HUMAN","EXTERNAL_AGENT"]),method:z50.literal("FULL_TEMPORAL_INSPECTION"),coverage:z50.array(ReviewIntervalSchema).min(1).max(200)});var RoughCutReviewBasisSchema=z50.strictObject({consistencyRequirements:z50.array(RoughCutRequirementSchema).max(256).optional(),artifactId:z50.uuid(),representationId:z50.uuid(),checksumSha256:sha7,manifestFingerprint:sha7,manifest:RoughCutManifestReaderSchema,brief:BriefVersionSchema,story:StoryVersionSchema});var RecordRoughCutReviewSchema=RoughCutReviewScopeSchema.extend({listeningEvidence:ListeningEvidenceSetSchema.optional(),artifactId:z50.uuid(),representationId:z50.uuid(),checksumSha256:sha7,basisFingerprint:sha7,expectedProductionRevision:z50.int().positive(),expectedReviewVersion:z50.int().nonnegative(),idempotencyKey:z50.string().trim().min(1).max(200),inspection:RoughCutInspectionSchema,observations:z50.array(RoughCutObservationSchema).min(1).max(300),summary:z50.string().trim().min(1).max(2500)});var RoughCutReviewRecordSchema=RoughCutReviewScopeSchema.extend({listeningEvidence:ListeningEvidenceSetSchema.optional(),id:z50.uuid(),projectId:ProjectIdSchema,version:z50.int().positive(),kind:z50.literal("PRODUCTION_REVIEW_2"),lifecycle:z50.literal("COMPLETED"),evaluatorVersion:z50.literal("production-review-v1"),basis:RoughCutReviewBasisSchema,basisFingerprint:sha7,executionClass:z50.enum(["LIVE","TEST_ONLY"]),technical:RoughCutTechnicalSchema,durationMs:z50.int().min(3e4).max(6e4),requirements:z50.array(RoughCutRequirementSchema).min(1).max(300),inspection:RoughCutInspectionSchema,observations:z50.array(RoughCutObservationSchema).min(1).max(300),result:z50.enum(["PASS","WARNING","FAIL"]),blockingKeys:z50.array(z50.string()).max(300),warningKeys:z50.array(z50.string()).max(300),summary:z50.string().min(1).max(2500),createdByPrincipalId:PrincipalIdSchema,createdAt:z50.iso.datetime({offset:true})});var RoughCutReviewTargetSchema=RoughCutReviewScopeSchema.extend({temporalEvidence:z50.array(TemporalEvidenceReferenceSchema).max(8).optional(),projectId:ProjectIdSchema,productionRevision:z50.int().positive(),productionRunnable:z50.boolean(),executionClass:z50.enum(["LIVE","TEST_ONLY"]),freshness:z50.enum(["CURRENT_BASIS","STALE_BASIS"]),staleReasons:z50.array(z50.string()).max(18),inspectable:z50.boolean(),durationMs:z50.int().min(3e4).max(6e4),basis:RoughCutReviewBasisSchema,basisFingerprint:sha7,technical:RoughCutTechnicalSchema,requirements:z50.array(RoughCutRequirementSchema).min(1).max(300),latestReview:RoughCutReviewRecordSchema.nullable(),reviewVersion:z50.int().nonnegative(),finalReadyVersion:z50.int().nonnegative()});var RoughCutFindingSchema=RoughCutReviewScopeSchema.extend({compositionLocality:z50.array(CompositionFindingLocalitySchema).min(1).max(208).optional(),id:z50.uuid(),projectId:ProjectIdSchema,reviewId:z50.uuid(),reviewVersion:z50.int().positive(),basisFingerprint:sha7,artifactId:z50.uuid(),timelineVersionId:z50.uuid(),requirement:RoughCutRequirementSchema,observation:RoughCutObservationSchema,blocking:z50.boolean(),severity:z50.enum(["BLOCKING","WARNING"]),remediation:z50.enum(["REVISE_PRODUCTION","REVISE_TRANSITION","CORRECT_CANONICAL_CONTRADICTION"]),affectedScope:z50.strictObject({kind:z50.enum(["PRODUCTION","SHOT","TRANSITION","TIMELINE_REGION"]),interval:ReviewIntervalSchema,shotIds:z50.array(z50.uuid()).min(1).max(200)}),initialLifecycle:z50.literal("OPEN"),createdAt:z50.iso.datetime({offset:true})});var RoughCutFindingViewSchema=RoughCutFindingSchema.extend({lifecycle:z50.enum(["OPEN","REMEDIATION_PLANNED","RESOLVED","WAIVED","SUPERSEDED"]),proofReviewId:z50.uuid().nullable(),proofDecisionId:z50.uuid().nullable()});var RoughCutReviewQuerySchema=RoughCutReviewScopeSchema.extend({limit:QueryLimitSchema,next:ContinuationSchema.optional()});var RoughCutReviewPageSchema=z50.strictObject({items:z50.array(RoughCutReviewRecordSchema),page:QueryPageInfoSchema});var RoughCutFindingQuerySchema=TimelineScopeSchema.extend({renderId:z50.uuid().optional(),limit:QueryLimitSchema,next:ContinuationSchema.optional()});var RoughCutFindingGetSchema=TimelineScopeSchema.extend({findingId:z50.uuid()});var RoughCutFindingPageSchema=z50.strictObject({items:z50.array(RoughCutFindingViewSchema),page:QueryPageInfoSchema});var RoughCutReviewReceiptSchema=z50.strictObject({semanticStatus:z50.literal("SUCCESS"),review:RoughCutReviewRecordSchema,findingIds:z50.array(z50.uuid()).max(300),productionRevision:z50.int().positive()});import{z as z51}from"zod";var ReviewEvidenceKeySchema=z51.string().regex(/^[a-z][a-z0-9_-]{0,39}$/);var ReviewEvidenceMediaSchema=z51.strictObject({artifactId:z51.uuid(),representationId:z51.uuid(),checksumSha256:z51.string().regex(/^[0-9a-f]{64}$/)});var common={id:ReviewEvidenceKeySchema,label:z51.string().trim().min(1).max(200),producer:z51.enum(["EXTERNAL_AGENT_HOST","HUMAN","VLM"]),media:ReviewEvidenceMediaSchema};var ReviewIntelligenceEvidenceSchema=z51.discriminatedUnion("kind",[z51.strictObject({...common,kind:z51.literal("METADATA")}),z51.strictObject({...common,kind:z51.literal("IMAGE_PIXELS")}),z51.strictObject({...common,kind:z51.literal("REGISTERED_TEMPORAL_FRAMES"),reference:TemporalEvidenceReferenceSchema}),z51.strictObject({...common,kind:z51.literal("VIDEO_PLAYBACK"),coverage:z51.array(ReviewIntervalSchema).min(1).max(200)}),z51.strictObject({...common,kind:z51.literal("AUDIO_LISTENING"),coverage:z51.array(ReviewIntervalSchema).min(1).max(200)}),z51.strictObject({...common,kind:z51.literal("VIDEO_WITH_AUDIO_PLAYBACK"),coverage:z51.array(ReviewIntervalSchema).min(1).max(200)}),z51.strictObject({...common,kind:z51.literal("VIDEO_FRAMES"),timestampsMs:z51.array(z51.number().nonnegative().max(6e4)).min(1).max(64)})]);import{z as z52}from"zod";var ObservationScopeSchema=z52.strictObject({tenantId:z52.uuid(),productionId:z52.uuid()});var ObservationSourceRequestSchema=z52.discriminatedUnion("kind",[z52.strictObject({kind:z52.literal("AUDIO"),media:ReviewEvidenceMediaSchema,versionId:z52.uuid(),purpose:z52.enum(["VOICEOVER","MUSIC"])}),z52.strictObject({kind:z52.literal("VIDEO"),media:ReviewEvidenceMediaSchema})]);var ObservationStartSchema=ObservationScopeSchema.extend({expectedProductionRevision:z52.int().positive(),idempotencyKey:z52.string().min(1).max(200),source:ObservationSourceRequestSchema,mode:ObservationModeSchema,selection:ProviderSelectionSchema,expectedModelProfileVersion:z52.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:z52.uuid()});var ObservationBindingSchema=z52.strictObject({tenantId:z52.uuid(),connectionId:z52.uuid(),connectionVersion:z52.int().positive(),credentialRef:z52.string(),credentialVersion:z52.int().positive(),profile:ObservationProfileSchema,matrix:ModelCapabilityMatrixSchema.optional(),executionClass:z52.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:z52.uuid(),projectId:z52.uuid(),productionId:z52.uuid(),byteSize:z52.int().positive().max(12582912),durationMs:z52.number().positive().max(6e4),frameRate:z52.number().positive().max(60).optional(),executionClass:z52.enum(["LIVE","TEST_ONLY"])});var json=z52.record(z52.string(),z52.unknown());var ObservationResultSchema=z52.strictObject({schemaVersion:z52.int().positive(),advisory:z52.literal(true),producer:z52.enum(["VLM","ASR"]).optional(),source:ObservationSourceSchema,input:json,provider:json,observedAt:z52.iso.datetime(),report:json,transcript:TranscriptSchema.optional(),evidence:ReviewIntelligenceEvidenceSchema.optional(),limitations:z52.array(z52.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=z52.strictObject({semanticStatus:z52.literal("ACCEPTED"),observationId:z52.uuid(),runtimeJobId:z52.uuid(),productionRevision:z52.int().positive(),executionClass:z52.enum(["LIVE","TEST_ONLY"])});var ObservationViewSchema=ObservationScopeSchema.extend({observationId:z52.uuid(),runtimeJobId:z52.uuid(),request:ObservationStartSchema,profile:ObservationProfileSchema,matrix:ModelCapabilityMatrixSchema.optional(),parameters:ObservationParametersSchema,executionClass:z52.enum(["LIVE","TEST_ONLY"]),runtimeStatus:z52.enum(["PENDING","READY","RUNNING","WAITING","SUCCEEDED","FAILED","CANCELLED","SUPERSEDED"]),providerStatus:z52.enum(["NOT_SUBMITTED","SUBMITTING","UNKNOWN","SUCCEEDED","REJECTED"]),cancellationRequested:z52.boolean(),failure:z52.strictObject({classification:z52.string().min(1).max(100),summary:z52.string().min(1).max(1e3)}).nullable(),result:ObservationResultSchema.nullable(),createdAt:z52.iso.datetime()});var ObservationOptionsSchema=ObservationScopeSchema.extend({options:z52.array(z52.strictObject({selection:ProviderSelectionSchema,profile:ObservationProfileSchema,matrix:ModelCapabilityMatrixSchema.optional(),connectionLabel:z52.string(),connectionVersion:z52.int().positive()})).max(100),possiblyTruncated:z52.boolean()});var ProductionGuidanceSchema=z52.strictObject({version:z52.enum(["NVS_PRODUCTION_GUIDANCE_V1","NVS_PRODUCTION_GUIDANCE_V2"]),instructions:z52.string().min(1).max(16e3)});var ProductionGuidanceContextSchema=ObservationScopeSchema.extend({projectId:z52.uuid(),revision:z52.int().positive(),guidance:ProductionGuidanceSchema});var MAX_SHOT_REVIEW_REQUIREMENTS=2200;import{z as z53}from"zod";var Fingerprint3=z53.string().regex(/^[0-9a-f]{64}$/);var VideoReviewScopeSchema=z53.strictObject({tenantId:TenantIdSchema,productionId:ProductionIdSchema,generationId:z53.uuid()});var VideoReviewRequirementSchema=z53.strictObject({intentPath:z53.string().min(1).max(220).optional(),continuity:ContinuityExpectationSchema.optional(),interval:z53.strictObject({startMs:z53.int().nonnegative().max(6e4),endMs:z53.int().positive().max(6e4)}).refine(v=>v.endMs>v.startMs,"Requirement interval must advance").optional(),key:z53.string().min(1).max(220),family:z53.enum(["PRODUCT_IDENTITY","CHARACTER_IDENTITY","WARDROBE","LOCATION","STYLE","SHOT_INTENT","BOUNDARY_CONTINUITY","SOUND"]),expected:z53.string().min(1).max(2500),enforcement:z53.enum(["LOCKED","REQUIRED","PREFERRED"]),evidenceWindow:z53.enum(["WHOLE_VIDEO","START","END","TEMPORAL"])});var VideoObservationSchema=z53.strictObject({listeningEvidenceIds:ListeningEvidenceIdsSchema.optional(),continuitySamples:ContinuitySamplesSchema.optional(),temporalEvidenceIds:TemporalEvidenceIdsSchema.optional(),key:z53.string().min(1).max(220),status:z53.enum(["SATISFIED","VIOLATED","NOT_OBSERVABLE","NOT_APPLICABLE"]),confidence:z53.enum(["CLEAR","UNCERTAIN"]),observed:z53.string().trim().min(1).max(1800),interval:z53.strictObject({startMs:z53.int().nonnegative(),endMs:z53.int().positive()}).refine(v=>v.endMs>v.startMs,"Observation interval must advance").optional()});var RecordVideoReviewSchema=VideoReviewScopeSchema.extend({listeningEvidence:ListeningEvidenceSetSchema.optional(),candidateId:z53.uuid(),representationId:ArtifactRepresentationIdSchema,checksumSha256:Fingerprint3,expectedReviewVersion:z53.int().nonnegative(),idempotencyKey:z53.string().trim().min(1).max(200),observations:z53.array(VideoObservationSchema).min(1).max(MAX_SHOT_REVIEW_REQUIREMENTS),summary:z53.string().trim().min(1).max(2500)});var VideoReviewRecordSchema=z53.strictObject({listeningEvidence:ListeningEvidenceSetSchema.optional(),id:z53.uuid(),tenantId:TenantIdSchema,projectId:ProjectIdSchema,productionId:ProductionIdSchema,generationId:z53.uuid(),candidateId:z53.uuid(),artifactId:ArtifactIdSchema,representationId:ArtifactRepresentationIdSchema,checksumSha256:Fingerprint3,shotId:ShotIdSchema,version:z53.int().positive(),preparationId:z53.uuid(),contractId:z53.uuid(),contractFingerprint:Fingerprint3,executionClass:z53.enum(["LIVE","TEST_ONLY"]),kind:z53.literal("SHOT_REVIEW_1"),lifecycle:z53.literal("COMPLETED"),evaluatorVersion:z53.literal("shot-review-v1"),source:z53.literal("EXPLICIT_MEDIA_INSPECTION"),technical:VideoTechnicalMetadataSchema,requirements:z53.array(VideoReviewRequirementSchema).min(1).max(MAX_SHOT_REVIEW_REQUIREMENTS),observations:z53.array(VideoObservationSchema).min(1).max(MAX_SHOT_REVIEW_REQUIREMENTS),result:z53.enum(["PASS","WARNING","FAIL"]),blockingKeys:z53.array(z53.string()).max(MAX_SHOT_REVIEW_REQUIREMENTS),warningKeys:z53.array(z53.string()).max(MAX_SHOT_REVIEW_REQUIREMENTS),summary:z53.string().min(1).max(2500),createdByPrincipalId:PrincipalIdSchema,createdAt:z53.iso.datetime({offset:true})});var DecideVideoShotSchema=VideoReviewScopeSchema.extend({candidateId:z53.uuid(),reviewId:z53.uuid(),expectedAcceptanceVersion:z53.int().nonnegative(),action:z53.enum(["ACCEPT","REJECT"]),acknowledgeWarnings:z53.boolean().default(false),reason:z53.string().trim().min(1).max(2500),idempotencyKey:z53.string().trim().min(1).max(200)});var ShotAcceptanceScopeSchema=z53.strictObject({tenantId:TenantIdSchema,productionId:ProductionIdSchema,shotId:ShotIdSchema});var RevokeShotAcceptanceSchema=ShotAcceptanceScopeSchema.extend({acceptanceId:z53.uuid(),expectedAcceptanceVersion:z53.int().positive(),reason:z53.string().trim().min(1).max(2500),idempotencyKey:z53.string().trim().min(1).max(200)});var GeneratedShotAcceptanceDecisionSchema=z53.strictObject({id:z53.uuid(),tenantId:TenantIdSchema,projectId:ProjectIdSchema,productionId:ProductionIdSchema,shotId:ShotIdSchema,acceptanceVersion:z53.int().positive(),generationId:z53.uuid(),candidateId:z53.uuid(),artifactId:ArtifactIdSchema,representationId:ArtifactRepresentationIdSchema,reviewId:z53.uuid(),action:z53.enum(["ACCEPT","REJECT","REVOKE"]),reference:AcceptedShotReferenceSchema.nullable(),previousAcceptanceId:z53.uuid().nullable(),warningKeys:z53.array(z53.string()).max(MAX_SHOT_REVIEW_REQUIREMENTS),acknowledgeWarnings:z53.boolean(),reason:z53.string().min(1).max(2500),createdByPrincipalId:PrincipalIdSchema,createdAt:z53.iso.datetime({offset:true})});var ProgrammaticShotAcceptanceDecisionSchema=z53.strictObject({sourceKind:z53.literal("PROGRAMMATIC"),id:z53.uuid(),tenantId:TenantIdSchema,projectId:ProjectIdSchema,productionId:ProductionIdSchema,shotId:ShotIdSchema,acceptanceVersion:z53.int().positive(),renderId:z53.uuid(),compositionId:z53.uuid(),compositionVersionId:z53.uuid(),artifactId:ArtifactIdSchema,representationId:ArtifactRepresentationIdSchema,reviewId:z53.uuid(),action:z53.enum(["ACCEPT","REJECT","REVOKE"]),reference:ProgrammaticAcceptedVisualSourceReferenceSchema.nullable(),previousAcceptanceId:z53.uuid().nullable(),warningKeys:z53.array(z53.string()).max(MAX_SHOT_REVIEW_REQUIREMENTS),acknowledgeWarnings:z53.boolean(),reason:z53.string().min(1).max(2500),createdByPrincipalId:PrincipalIdSchema,createdAt:z53.iso.datetime({offset:true})});var ShotAcceptanceDecisionSchema=z53.union([GeneratedShotAcceptanceDecisionSchema,ProgrammaticShotAcceptanceDecisionSchema,z53.strictObject({sourceKind:z53.literal("IMPORTED"),id:z53.uuid(),tenantId:TenantIdSchema,projectId:ProjectIdSchema,productionId:ProductionIdSchema,shotId:ShotIdSchema,acceptanceVersion:z53.int().positive(),normalizationId:z53.uuid(),sourceId:z53.uuid(),sourceVersionId:z53.uuid(),artifactId:ArtifactIdSchema,representationId:ArtifactRepresentationIdSchema,reviewId:z53.uuid(),action:z53.enum(["ACCEPT","REJECT","REVOKE"]),reference:ImportedAcceptedVisualSourceReferenceSchema.nullable(),previousAcceptanceId:z53.uuid().nullable(),warningKeys:z53.array(z53.string()).max(MAX_SHOT_REVIEW_REQUIREMENTS),acknowledgeWarnings:z53.boolean(),reason:z53.string().min(1).max(2500),createdByPrincipalId:PrincipalIdSchema,createdAt:z53.iso.datetime({offset:true})})]);var VideoReviewTargetSchema=VideoReviewScopeSchema.extend({temporalEvidence:z53.array(TemporalEvidenceReferenceSchema).max(8).optional(),projectId:ProjectIdSchema,shotId:ShotIdSchema,preparationId:z53.uuid(),contractId:z53.uuid(),contractFingerprint:Fingerprint3,executionClass:z53.enum(["LIVE","TEST_ONLY"]),freshness:z53.enum(["CURRENT_BASIS","STALE_BASIS"]),runtimeSucceeded:z53.boolean(),productionRunnable:z53.boolean(),candidate:VideoCandidateSchema,requirements:z53.array(VideoReviewRequirementSchema).min(1).max(MAX_SHOT_REVIEW_REQUIREMENTS),latestReview:VideoReviewRecordSchema.nullable(),reviewVersion:z53.int().nonnegative(),acceptanceVersion:z53.int().nonnegative(),activeAcceptanceId:z53.uuid().nullable()});var ShotAcceptanceViewSchema=ShotAcceptanceScopeSchema.extend({acceptanceVersion:z53.int().nonnegative(),status:z53.enum(["NONE","CURRENT","STALE"]),acceptance:ShotAcceptanceDecisionSchema.nullable(),reference:AcceptedVisualSourceReferenceSchema.nullable()});var VideoReviewQuerySchema=VideoReviewScopeSchema.extend({limit:QueryLimitSchema,next:ContinuationSchema.optional()});var VideoReviewPageSchema=z53.strictObject({items:z53.array(VideoReviewRecordSchema),page:QueryPageInfoSchema});var ShotDecisionQuerySchema=ShotAcceptanceScopeSchema.extend({limit:QueryLimitSchema,next:ContinuationSchema.optional()});var ShotDecisionPageSchema=z53.strictObject({items:z53.array(ShotAcceptanceDecisionSchema),page:QueryPageInfoSchema});var VideoReviewReceiptSchema=z53.strictObject({semanticStatus:z53.literal("SUCCESS"),review:VideoReviewRecordSchema,productionRevision:z53.int().positive()});var ShotDecisionReceiptSchema=z53.strictObject({semanticStatus:z53.literal("SUCCESS"),decision:ShotAcceptanceDecisionSchema,productionRevision:z53.int().positive()});import{z as z54}from"zod";var Fingerprint4=z54.string().regex(/^[0-9a-f]{64}$/);var ProgrammaticVideoReviewScopeSchema=z54.strictObject({tenantId:TenantIdSchema,productionId:ProductionIdSchema,renderId:z54.uuid()});var ProgrammaticReviewMediaSchema=VideoTechnicalMetadataSchema.extend({artifactId:ArtifactIdSchema,representationId:ArtifactRepresentationIdSchema,availability:z54.enum(["AVAILABLE","INVALID"])});var ProgrammaticVideoReviewRecordSchema=z54.strictObject({sourceKind:z54.literal("PROGRAMMATIC"),id:z54.uuid(),tenantId:TenantIdSchema,projectId:ProjectIdSchema,productionId:ProductionIdSchema,shotId:ShotIdSchema,renderId:z54.uuid(),compositionId:z54.uuid(),compositionVersionId:z54.uuid(),compositionVersion:z54.int().positive(),compositionFingerprint:Fingerprint4,renderManifestFingerprint:Fingerprint4,artifactId:ArtifactIdSchema,representationId:ArtifactRepresentationIdSchema,checksumSha256:Fingerprint4,version:z54.int().positive(),planVersionId:z54.uuid(),planVersion:z54.int().positive(),shotPlanningRevision:z54.int().positive(),executionClass:z54.enum(["LIVE","TEST_ONLY"]),kind:z54.literal("SHOT_REVIEW_1"),lifecycle:z54.literal("COMPLETED"),evaluatorVersion:z54.literal("shot-review-v1"),source:z54.literal("EXPLICIT_MEDIA_INSPECTION"),technical:VideoTechnicalMetadataSchema,requirements:z54.array(VideoReviewRequirementSchema).min(1).max(MAX_SHOT_REVIEW_REQUIREMENTS),observations:z54.array(VideoObservationSchema).min(1).max(MAX_SHOT_REVIEW_REQUIREMENTS),result:z54.enum(["PASS","WARNING","FAIL"]),blockingKeys:z54.array(z54.string()).max(MAX_SHOT_REVIEW_REQUIREMENTS),warningKeys:z54.array(z54.string()).max(MAX_SHOT_REVIEW_REQUIREMENTS),summary:z54.string().min(1).max(2500),createdByPrincipalId:PrincipalIdSchema,createdAt:z54.iso.datetime({offset:true})});var ProgrammaticVideoReviewTargetSchema=ProgrammaticVideoReviewScopeSchema.extend({sourceKind:z54.literal("PROGRAMMATIC"),temporalEvidence:z54.array(TemporalEvidenceReferenceSchema).max(8).optional(),projectId:ProjectIdSchema,shotId:ShotIdSchema,compositionId:z54.uuid(),compositionVersionId:z54.uuid(),compositionVersion:z54.int().positive(),compositionFingerprint:Fingerprint4,renderManifestFingerprint:Fingerprint4,executionClass:z54.enum(["LIVE","TEST_ONLY"]),freshness:z54.enum(["CURRENT_BASIS","STALE_BASIS"]),runtimeSucceeded:z54.boolean(),productionRunnable:z54.boolean(),media:ProgrammaticReviewMediaSchema,requirements:z54.array(VideoReviewRequirementSchema).min(1).max(MAX_SHOT_REVIEW_REQUIREMENTS),latestReview:ProgrammaticVideoReviewRecordSchema.nullable(),reviewVersion:z54.int().nonnegative(),acceptanceVersion:z54.int().nonnegative(),activeAcceptanceId:z54.uuid().nullable()});var RecordProgrammaticVideoReviewSchema=ProgrammaticVideoReviewScopeSchema.extend({representationId:ArtifactRepresentationIdSchema,checksumSha256:Fingerprint4,expectedReviewVersion:z54.int().nonnegative(),idempotencyKey:z54.string().trim().min(1).max(200),observations:z54.array(VideoObservationSchema).min(1).max(MAX_SHOT_REVIEW_REQUIREMENTS),summary:z54.string().trim().min(1).max(2500)});var DecideProgrammaticShotSchema=ProgrammaticVideoReviewScopeSchema.extend({reviewId:z54.uuid(),expectedAcceptanceVersion:z54.int().nonnegative(),action:z54.enum(["ACCEPT","REJECT"]),acknowledgeWarnings:z54.boolean().default(false),reason:z54.string().trim().min(1).max(2500),idempotencyKey:z54.string().trim().min(1).max(200)});var ProgrammaticVideoReviewQuerySchema=ProgrammaticVideoReviewScopeSchema.extend({limit:QueryLimitSchema,next:ContinuationSchema.optional()});var ProgrammaticVideoReviewPageSchema=z54.strictObject({items:z54.array(ProgrammaticVideoReviewRecordSchema),page:QueryPageInfoSchema});var ProgrammaticVideoReviewReceiptSchema=z54.strictObject({semanticStatus:z54.literal("SUCCESS"),review:ProgrammaticVideoReviewRecordSchema,productionRevision:z54.int().positive()});import{z as z55}from"zod";var Intent=z55.string().trim().min(1).max(300);var CameraIntentSchema=z55.strictObject({scale:z55.enum(["EXTREME_CLOSE_UP","CLOSE_UP","MEDIUM","WIDE","EXTREME_WIDE"]),framing:z55.enum(["CENTERED","OFF_CENTER","SYMMETRICAL","OVER_SHOULDER"]),angle:z55.enum(["EYE_LEVEL","HIGH","LOW","TOP_DOWN"]),movement:z55.enum(["STATIC","PAN","TILT","DOLLY","TRACK","ORBIT","CRANE","ZOOM"]),stability:z55.enum(["LOCKED","STABILIZED","HANDHELD"]),direction:z55.enum(["LEFT","RIGHT","UP","DOWN","FORWARD","BACKWARD","CLOCKWISE","COUNTERCLOCKWISE"]).optional(),lensIntent:z55.string().trim().min(1).max(120).optional()});var ShotTemporalBeatSchema=z55.strictObject({startSeconds:z55.number().min(0).max(30),endSeconds:z55.number().positive().max(30),action:Intent});var ShotDirectionSchema=z55.strictObject({camera:CameraIntentSchema,temporalBeats:z55.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}import{z as z56}from"zod";var PlanningClientKeySchema=z56.string().regex(/^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/);var BoundaryRequirementSchema=z56.strictObject({attribute:z56.string().regex(/^[A-Za-z][A-Za-z0-9_.-]{0,59}$/),value:z56.string().trim().min(1).max(300)});var ShotIntentSchema=z56.strictObject({narrativePurpose:z56.string().trim().min(1).max(600),subjectAction:z56.string().trim().min(1).max(600),targetDurationSeconds:z56.number().min(.5).max(30),subjectRequirements:z56.array(z56.string().trim().min(1).max(300)).max(16).default([]),cameraComposition:z56.string().trim().min(1).max(500).optional(),factualClaims:z56.array(StoryFactClaimSchema).max(16).default([]),requiresGeneratedKeyframe:z56.boolean().default(false),sourceMediaAllowed:z56.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=z56.strictObject({clientKey:PlanningClientKeySchema,shotId:ShotIdSchema.optional(),intent:ShotIntentSchema,entryBoundary:z56.array(BoundaryRequirementSchema).max(24).default([]),exitBoundary:z56.array(BoundaryRequirementSchema).max(24).default([])});var ScenePlanInputSchema=z56.strictObject({clientKey:PlanningClientKeySchema,sceneId:SceneIdSchema.optional(),purpose:z56.string().trim().min(1).max(800),locationContext:z56.string().trim().min(1).max(300).optional(),timeContext:z56.string().trim().min(1).max(300).optional(),entryBoundary:z56.array(BoundaryRequirementSchema).max(24).default([]),exitBoundary:z56.array(BoundaryRequirementSchema).max(24).default([]),shots:z56.array(ShotPlanInputSchema).min(1).max(24)});var ContinuityRequirementSchema=z56.strictObject({mode:z56.enum(["PERSIST","TRANSITION","REESTABLISH","REVIEW"]),attribute:z56.string().regex(/^[A-Za-z][A-Za-z0-9_.-]{0,59}$/),description:z56.string().trim().min(1).max(500)});var ContinuityEdgeInputSchema=z56.strictObject({fromShotKey:PlanningClientKeySchema,toShotKey:PlanningClientKeySchema,requirements:z56.array(ContinuityRequirementSchema).min(1).max(24)});var AcceptSceneShotPlanRequestSchema=z56.strictObject({tenantId:TenantIdSchema,expectedProductionRevision:z56.int().positive(),expectedStoryVersion:z56.int().positive(),revisionReason:z56.string().trim().min(1).max(1e3).optional(),idempotencyKey:z56.string().trim().min(1).max(200),scenes:z56.array(ScenePlanInputSchema).min(1).max(12),continuityEdges:z56.array(ContinuityEdgeInputSchema).max(64).default([])});var ShotPlanEntrySchema=z56.strictObject({shotId:ShotIdSchema,clientKey:PlanningClientKeySchema,ordinal:z56.int().positive(),planningRevision:z56.int().positive(),intent:ShotIntentSchema,entryBoundary:z56.array(BoundaryRequirementSchema).max(24),exitBoundary:z56.array(BoundaryRequirementSchema).max(24)});var ScenePlanEntrySchema=z56.strictObject({sceneId:SceneIdSchema,clientKey:PlanningClientKeySchema,ordinal:z56.int().positive(),purpose:z56.string().trim().min(1).max(800),locationContext:z56.string().trim().min(1).max(300).optional(),timeContext:z56.string().trim().min(1).max(300).optional(),entryBoundary:z56.array(BoundaryRequirementSchema).max(24),exitBoundary:z56.array(BoundaryRequirementSchema).max(24),shots:z56.array(ShotPlanEntrySchema).min(1).max(24)});var ContinuityEdgeSchema=z56.strictObject({id:ContinuityEdgeIdSchema,fromShotId:ShotIdSchema,toShotId:ShotIdSchema,requirements:z56.array(ContinuityRequirementSchema).min(1).max(24)});var SceneShotPlanVersionSchema=z56.strictObject({id:SceneShotPlanVersionIdSchema,planId:SceneShotPlanIdSchema,tenantId:TenantIdSchema,projectId:ProjectIdSchema,productionId:ProductionIdSchema,version:z56.int().positive(),storyVersionId:StoryVersionIdSchema,storyVersion:z56.int().positive(),briefVersionId:BriefVersionIdSchema,briefVersion:z56.int().positive(),scenes:z56.array(ScenePlanEntrySchema).min(1).max(12),continuityEdges:z56.array(ContinuityEdgeSchema).max(64),createdByPrincipalId:PrincipalIdSchema,createdAt:z56.iso.datetime({offset:true})});var AcceptSceneShotPlanResultSchema=z56.discriminatedUnion("semanticStatus",[z56.strictObject({semanticStatus:z56.literal("SUCCESS"),planVersion:SceneShotPlanVersionSchema,productionRevision:z56.int().positive(),activeSceneShotPlanVersion:z56.int().positive()}),z56.strictObject({semanticStatus:z56.literal("NEEDS_INPUT"),missingPrerequisites:z56.array(z56.literal("ACTIVE_STORY")).min(1)})]);import{z as z57}from"zod";var WriterScopeSchema=z57.strictObject({tenantId:TenantIdSchema,projectId:ProjectIdSchema,productionId:ProductionIdSchema});var WriterBasisSchema=WriterScopeSchema.extend({productionRevision:z57.int().positive(),briefVersionId:BriefVersionIdSchema,briefVersion:z57.int().positive()});var IntentSchema=z57.string().trim().min(1).max(600);var WriterAlternativeSchema=z57.strictObject({alternativeId:z57.string().regex(/^[a-z][a-z0-9_-]{0,39}$/),title:z57.string().trim().min(1).max(120),story:StoryContentSchema,rationale:z57.strictObject({coreMessage:IntentSchema,hook:IntentSchema,audienceFit:IntentSchema,pacingIntent:IntentSchema,endingIntent:IntentSchema,tradeoffs:z57.array(IntentSchema).max(6)}),beatDurationsSeconds:z57.array(z57.int().positive().max(60)).min(1).max(24)});var WriterProposalSchema=z57.strictObject({origin:z57.strictObject({kind:z57.literal("EXTERNAL_AGENT_HOST"),label:z57.string().trim().min(1).max(100)}),unknowns:z57.array(z57.string().trim().min(1).max(300)).max(8),alternatives:z57.array(WriterAlternativeSchema).min(1).max(3)});var ValidateWriterProposalSchema=z57.strictObject({basis:WriterBasisSchema,revisionReason:AcceptStoryRequestSchema.shape.revisionReason,proposal:WriterProposalSchema});var MissingBriefSchema=z57.strictObject({semanticStatus:z57.literal("NEEDS_INPUT"),missingPrerequisites:z57.array(z57.literal("ACTIVE_BRIEF")).min(1).max(1)});var WriterBriefResultSchema=z57.discriminatedUnion("semanticStatus",[z57.strictObject({semanticStatus:z57.literal("SUCCESS"),basis:WriterBasisSchema,briefVersion:BriefVersionSchema}),MissingBriefSchema]);var WriterAcceptanceDraftSchema=z57.strictObject({alternativeId:WriterAlternativeSchema.shape.alternativeId,projectId:ProjectIdSchema,productionId:ProductionIdSchema,request:AcceptStoryRequestSchema.omit({idempotencyKey:true})});var WriterValidationResultSchema=z57.discriminatedUnion("semanticStatus",[z57.strictObject({semanticStatus:z57.literal("SUCCESS"),advisory:z57.literal(true),basis:WriterBasisSchema,proposal:WriterProposalSchema,acceptanceDrafts:z57.array(WriterAcceptanceDraftSchema).min(1).max(3),limitations:z57.array(z57.enum(["PROSE_IS_CREATIVE_INTENT_NOT_FACT_VERIFIED","PACING_IS_ADVISORY_NOT_TIMELINE_TRUTH","ACCEPTANCE_RECHECKS_CURRENT_BASIS"])).length(3)}),MissingBriefSchema]);import{z as z58}from"zod";var DirectorScopeSchema=WriterScopeSchema;var DirectorBasisSchema=WriterBasisSchema.extend({storyVersionId:StoryVersionIdSchema,storyVersion:z58.int().positive(),sceneShotPlanVersionId:SceneShotPlanVersionIdSchema.nullable(),sceneShotPlanVersion:z58.int().positive().nullable()}).refine(value2=>value2.sceneShotPlanVersionId===null===(value2.sceneShotPlanVersion===null),"Current plan ID and version must both be present or null");var Intent2=z58.string().trim().min(1).max(600);var Plan=AcceptSceneShotPlanRequestSchema.pick({scenes:true,continuityEdges:true});var DirectorAlternativeSchema=z58.strictObject({alternativeId:z58.string().regex(/^[a-z][a-z0-9_-]{0,39}$/),title:z58.string().trim().min(1).max(120),plan:Plan,rationale:z58.strictObject({storyInterpretation:Intent2,visualApproach:Intent2,pacingIntent:Intent2,tradeoffs:z58.array(Intent2).max(6)}),shotStoryBeats:z58.array(z58.strictObject({shotKey:PlanningClientKeySchema,beatOrdinals:z58.array(z58.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=z58.strictObject({origin:z58.strictObject({kind:z58.literal("EXTERNAL_AGENT_HOST"),label:z58.string().trim().min(1).max(100)}),unknowns:z58.array(z58.string().trim().min(1).max(300)).max(8),alternatives:z58.array(DirectorAlternativeSchema).min(1).max(3)});var ValidateDirectorProposalSchema=z58.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=z58.strictObject({semanticStatus:z58.literal("NEEDS_INPUT"),missingPrerequisites:z58.array(z58.enum(["ACTIVE_BRIEF","ACTIVE_STORY"])).min(1).max(2)});var DirectorContextResultSchema=z58.discriminatedUnion("semanticStatus",[z58.strictObject({semanticStatus:z58.literal("SUCCESS"),basis:DirectorBasisSchema,briefVersion:BriefVersionSchema,storyVersion:StoryVersionSchema,sceneShotPlanVersion:SceneShotPlanVersionSchema.nullable(),stalePrerequisites:z58.array(z58.enum(["CURRENT_STORY","CURRENT_SCENE_SHOT_PLAN"])).min(1).max(2).optional()}),Missing]);var DirectorAcceptanceDraftSchema=z58.strictObject({alternativeId:DirectorAlternativeSchema.shape.alternativeId,projectId:DirectorScopeSchema.shape.projectId,productionId:DirectorScopeSchema.shape.productionId,request:AcceptSceneShotPlanRequestSchema.omit({idempotencyKey:true})});var DirectorValidationResultSchema=z58.discriminatedUnion("semanticStatus",[z58.strictObject({semanticStatus:z58.literal("SUCCESS"),advisory:z58.literal(true),basis:DirectorBasisSchema,proposal:DirectorProposalSchema,acceptanceDrafts:z58.array(DirectorAcceptanceDraftSchema).min(1).max(3),limitations:z58.array(z58.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 z59}from"zod";var Fingerprint5=z59.string().regex(/^[0-9a-f]{64}$/);var KeyframeReviewScopeSchema=z59.strictObject({tenantId:TenantIdSchema,productionId:ProductionIdSchema,generationId:z59.uuid()});var VisualRequirementSchema=z59.strictObject({intentPath:z59.string().min(1).max(220).optional(),key:z59.string().min(1).max(200),expected:z59.string().min(1).max(2500),enforcement:z59.enum(["LOCKED","REQUIRED","PREFERRED"])});var Region=z59.strictObject({x:z59.number().min(0).max(1),y:z59.number().min(0).max(1),width:z59.number().positive().max(1),height:z59.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=z59.strictObject({key:z59.string().min(1).max(200),status:z59.enum(["SATISFIED","VIOLATED","NOT_OBSERVABLE","NOT_APPLICABLE"]),confidence:z59.enum(["CLEAR","UNCERTAIN"]),observed:z59.string().trim().min(1).max(1500),region:Region.optional()});var RecordKeyframeReviewSchema=KeyframeReviewScopeSchema.extend({candidateId:z59.uuid(),representationId:z59.uuid(),checksumSha256:Fingerprint5,expectedReviewVersion:z59.int().nonnegative(),idempotencyKey:z59.string().trim().min(1).max(200),observations:z59.array(KeyframeObservationSchema).min(1).max(MAX_SHOT_REVIEW_REQUIREMENTS),summary:z59.string().trim().min(1).max(2e3)});var KeyframeReviewRecordSchema=z59.strictObject({id:z59.uuid(),tenantId:TenantIdSchema,projectId:ProjectIdSchema,productionId:ProductionIdSchema,generationId:z59.uuid(),candidateId:z59.uuid(),artifactId:z59.uuid(),representationId:z59.uuid(),checksumSha256:Fingerprint5,shotId:ShotIdSchema,framePurpose:KeyframePurposeSchema,version:z59.int().positive(),preparationId:z59.uuid(),contractId:z59.uuid(),contractFingerprint:Fingerprint5,executionClass:z59.enum(["LIVE","TEST_ONLY"]),kind:z59.literal("KEYFRAME_REFERENCE"),lifecycle:z59.literal("COMPLETED"),evaluatorVersion:z59.literal("keyframe-reference-v1"),source:z59.literal("EXPLICIT_VISUAL_INSPECTION"),requirements:z59.array(VisualRequirementSchema).min(1).max(MAX_SHOT_REVIEW_REQUIREMENTS),observations:z59.array(KeyframeObservationSchema).min(1).max(MAX_SHOT_REVIEW_REQUIREMENTS),result:z59.enum(["PASS","WARNING","FAIL"]),blockingKeys:z59.array(z59.string()).max(MAX_SHOT_REVIEW_REQUIREMENTS),warningKeys:z59.array(z59.string()).max(MAX_SHOT_REVIEW_REQUIREMENTS),summary:z59.string().min(1).max(2e3),createdByPrincipalId:PrincipalIdSchema,createdAt:z59.iso.datetime({offset:true})});var DecideKeyframeSchema=KeyframeReviewScopeSchema.extend({candidateId:z59.uuid(),reviewId:z59.uuid(),expectedSelectionVersion:z59.int().nonnegative(),action:z59.enum(["ACCEPT","REJECT"]),acknowledgeWarnings:z59.boolean().default(false),reason:z59.string().trim().min(1).max(2e3),idempotencyKey:z59.string().trim().min(1).max(200)});var KeyframeReferenceScopeSchema=z59.strictObject({tenantId:TenantIdSchema,productionId:ProductionIdSchema,shotId:ShotIdSchema,framePurpose:KeyframePurposeSchema});var RevokeKeyframeSchema=KeyframeReferenceScopeSchema.extend({acceptanceId:z59.uuid(),expectedSelectionVersion:z59.int().positive(),reason:z59.string().trim().min(1).max(2e3),idempotencyKey:z59.string().trim().min(1).max(200)});var KeyframeDecisionRecordSchema=z59.strictObject({id:z59.uuid(),tenantId:TenantIdSchema,projectId:ProjectIdSchema,productionId:ProductionIdSchema,shotId:ShotIdSchema,framePurpose:KeyframePurposeSchema,selectionVersion:z59.int().positive(),generationId:z59.uuid(),candidateId:z59.uuid(),reviewId:z59.uuid(),action:z59.enum(["ACCEPT","REJECT","REVOKE"]),reference:AcceptedKeyframeReferenceSchema.nullable(),previousAcceptanceId:z59.uuid().nullable(),warningKeys:z59.array(z59.string()).max(MAX_SHOT_REVIEW_REQUIREMENTS),acknowledgeWarnings:z59.boolean(),reason:z59.string().min(1).max(2e3),createdByPrincipalId:PrincipalIdSchema,createdAt:z59.iso.datetime({offset:true})});var KeyframeReviewTargetSchema=KeyframeReviewScopeSchema.extend({projectId:ProjectIdSchema,shotId:ShotIdSchema,framePurpose:KeyframePurposeSchema,preparationId:z59.uuid(),contractId:z59.uuid(),contractFingerprint:Fingerprint5,executionClass:z59.enum(["LIVE","TEST_ONLY"]),freshness:z59.enum(["CURRENT_BASIS","STALE_BASIS"]),runtimeSucceeded:z59.boolean(),productionRunnable:z59.boolean(),candidate:KeyframeCandidateSchema,requirements:z59.array(VisualRequirementSchema).min(1).max(MAX_SHOT_REVIEW_REQUIREMENTS),latestReview:KeyframeReviewRecordSchema.nullable(),reviewVersion:z59.int().nonnegative(),selectionVersion:z59.int().nonnegative(),activeAcceptanceId:z59.uuid().nullable()});var KeyframeReferenceViewSchema=KeyframeReferenceScopeSchema.extend({selectionVersion:z59.int().nonnegative(),status:z59.enum(["NONE","CURRENT","STALE"]),acceptance:KeyframeDecisionRecordSchema.nullable(),reference:AcceptedKeyframeReferenceSchema.nullable()});var KeyframeReviewQuerySchema=KeyframeReviewScopeSchema.extend({limit:QueryLimitSchema,next:ContinuationSchema.optional()});var KeyframeReviewPageSchema=z59.strictObject({items:z59.array(KeyframeReviewRecordSchema),page:QueryPageInfoSchema});var KeyframeReviewReceiptSchema=z59.strictObject({semanticStatus:z59.literal("SUCCESS"),review:KeyframeReviewRecordSchema,productionRevision:z59.int().positive()});var KeyframeDecisionReceiptSchema=z59.strictObject({semanticStatus:z59.literal("SUCCESS"),decision:KeyframeDecisionRecordSchema,productionRevision:z59.int().positive()});var KeyframeDecisionQuerySchema=KeyframeReferenceScopeSchema.extend({limit:QueryLimitSchema,next:ContinuationSchema.optional()});var KeyframeDecisionPageSchema=z59.strictObject({items:z59.array(KeyframeDecisionRecordSchema),page:QueryPageInfoSchema});var KeyframeReviewSummarySchema=z59.strictObject({reviewedCandidates:z59.int().nonnegative(),unreviewedCandidates:z59.int().nonnegative(),decisionCount:z59.int().nonnegative()});import{z as z60}from"zod";var sha8=z60.string().regex(/^[0-9a-f]{64}$/);var evidenceIds=z60.array(ReviewEvidenceKeySchema).max(16);var ReviewIntelligenceTargetSchema=z60.discriminatedUnion("kind",[z60.strictObject({kind:z60.literal("IMAGE"),generationId:z60.uuid()}),z60.strictObject({kind:z60.literal("VIDEO"),generationId:z60.uuid()}),z60.strictObject({kind:z60.literal("ROUGH_CUT"),renderId:z60.uuid()}),z60.strictObject({kind:z60.literal("PROGRAMMATIC"),renderId:z60.uuid()})]);var ReviewIntelligenceContextInputSchema=z60.strictObject({scope:DirectorScopeSchema,target:ReviewIntelligenceTargetSchema});var ReviewIntelligenceBasisSchema=ReviewIntelligenceContextInputSchema.extend({contextFingerprint:sha8});var ReviewIntelligenceOwnerTargetSchema=z60.discriminatedUnion("kind",[z60.strictObject({kind:z60.literal("IMAGE"),target:KeyframeReviewTargetSchema}),z60.strictObject({kind:z60.literal("VIDEO"),target:VideoReviewTargetSchema}),z60.strictObject({kind:z60.literal("ROUGH_CUT"),target:RoughCutReviewTargetSchema}),z60.strictObject({kind:z60.literal("PROGRAMMATIC"),target:ProgrammaticVideoReviewTargetSchema})]);var review=z60.discriminatedUnion("kind",[z60.strictObject({kind:z60.literal("IMAGE"),observations:z60.array(KeyframeObservationSchema.extend({evidenceIds})).min(1).max(MAX_SHOT_REVIEW_REQUIREMENTS)}),z60.strictObject({kind:z60.literal("VIDEO"),observations:z60.array(VideoObservationSchema.extend({evidenceIds})).min(1).max(MAX_SHOT_REVIEW_REQUIREMENTS)}),z60.strictObject({kind:z60.literal("PROGRAMMATIC"),observations:z60.array(VideoObservationSchema.extend({evidenceIds})).min(1).max(MAX_SHOT_REVIEW_REQUIREMENTS)}),z60.strictObject({kind:z60.literal("ROUGH_CUT"),observations:z60.array(RoughCutObservationSchema.extend({evidenceIds})).min(1).max(300),inspection:RoughCutInspectionSchema})]);var ValidateReviewIntelligenceSchema=z60.strictObject({basis:ReviewIntelligenceBasisSchema,proposal:z60.strictObject({origin:z60.strictObject({kind:z60.literal("EXTERNAL_AGENT_HOST"),label:z60.string().trim().min(1).max(100)}),summary:z60.string().trim().min(1).max(2e3),evidence:z60.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=z60.strictObject({semanticStatus:z60.literal("SUCCESS"),advisory:z60.literal(true),basis:ReviewIntelligenceBasisSchema,productionGuidance:ProductionGuidanceSchema.optional(),ownerContext:DirectorContextResultSchema,reviewTarget:ReviewIntelligenceOwnerTargetSchema,limitations:z60.array(z60.enum(["NO_IMPLICIT_MEDIA_OR_MODEL_CALL","READS_ARE_NOT_ATOMIC_OR_RESERVED"])).length(2)});var ReviewIntelligenceRecordDraftSchema=z60.discriminatedUnion("kind",[z60.strictObject({kind:z60.literal("PROGRAMMATIC"),input:RecordProgrammaticVideoReviewSchema.omit({idempotencyKey:true})}),z60.strictObject({kind:z60.literal("IMAGE"),input:RecordKeyframeReviewSchema.omit({idempotencyKey:true})}),z60.strictObject({kind:z60.literal("VIDEO"),input:RecordVideoReviewSchema.omit({idempotencyKey:true})}),z60.strictObject({kind:z60.literal("ROUGH_CUT"),input:RecordRoughCutReviewSchema.omit({idempotencyKey:true})})]);var ReviewIntelligenceIssueSchema=z60.strictObject({requirement:z60.union([VisualRequirementSchema,VideoReviewRequirementSchema,RoughCutRequirementSchema]),observation:z60.union([KeyframeObservationSchema,VideoObservationSchema,RoughCutObservationSchema]),evidenceIds,blocking:z60.boolean(),severity:z60.enum(["BLOCKING","WARNING"]),affectedScope:z60.strictObject({kind:z60.enum(["PRODUCTION","SHOT","TRANSITION","TIMELINE_REGION"]),interval:ReviewIntervalSchema,shotIds:z60.array(z60.uuid()).min(1).max(200)}).optional()});var ReviewIntelligenceValidationResultSchema=z60.strictObject({semanticStatus:z60.literal("SUCCESS"),advisory:z60.literal(true),basis:ReviewIntelligenceBasisSchema,proposal:ValidateReviewIntelligenceSchema.shape.proposal,canonicalRulePreview:z60.strictObject({source:z60.literal("EXISTING_CANONICAL_DOMAIN_RULES"),authoritative:z60.literal(false),evaluatorVersion:z60.enum(["keyframe-reference-v1","shot-review-v1","production-review-v1"]),result:z60.enum(["PASS","WARNING","FAIL"]),blockingKeys:z60.array(z60.string()).max(MAX_SHOT_REVIEW_REQUIREMENTS),warningKeys:z60.array(z60.string()).max(MAX_SHOT_REVIEW_REQUIREMENTS)}),issueProposals:z60.array(ReviewIntelligenceIssueSchema).max(MAX_SHOT_REVIEW_REQUIREMENTS),recordDraft:ReviewIntelligenceRecordDraftSchema,limitations:z60.array(z60.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)});export{AgentHostScopeSchema,AgentHostSelectionSchema,ConfigureAgentHostSchema,RevokeAgentHostSchema,AgentHostBindingSchema,UpdateAgentHostSelectionSchema,AgentHostCurrentSchema,AgentHostHistoryQuerySchema,AgentHostHistoryPageSchema,AgentHostReadinessSchema,NativeRuntimePublicKeySchema,ConfigureNativeToolGrantSchema,NativeToolGrantGetSchema,RevokeNativeToolGrantSchema,NativeRuntimeProofRequestSchema,NativeToolGrantViewSchema,ClipTransitionSchema,TimelineGraphicInputSchema,CaptionTranscriptPlanSchema,AuthorTranscriptCaptionsSchema,CaptionContentSchema,CaptionScopeSchema,AuthorCaptionsSchema,CaptionGetSchema,CaptionQuerySchema,CaptionViewSchema,CaptionReceiptSchema,CaptionBasisSchema,CaptionPageSchema,CaptionExportSchema,CaptionSnapshotSchema,CaptionTranscriptDraftSchema,AudioScopeSchema,AudioImportRequestSchema,AudioGetSchema,AudioQuerySchema,AudioViewSchema,AudioReceiptSchema,AudioBasisSchema,AudioPageSchema,AudioSnapshotSchema,TimelineAudioInputSchema,ProviderSelectionSchema,ConfigureProviderInputSchema,ProviderConnectionViewSchema,ProviderConnectionCommandSchema,ProviderCredentialRevokeSchema,SetKeyframeDefaultSchema,GenerationCostQuoteSchema,PreparationIdSchema,GenerationContractIdSchema,ContentFingerprintSchema,PreparationTargetSchema,PreparationBasisSchema,ReferenceRoleSchema,ReferenceBindingInputSchema,ExactEvidenceReferenceSchema,PreparationBlockerSchema,ConstraintSetSchema,ReferenceSetSchema,VideoProviderProfileSchema,VideoStartInputSchema,VideoGetInputSchema,VideoQueryInputSchema,VideoAdmissionSchema,VideoGenerationViewSchema,VideoQueryPageSchema,VideoSummarySchema,RoughCutManifestSchema,AcceptedVisualSourceReferenceSchema,SourceSyncAudioStartSchema,SourceSyncAudioGetSchema,SourceSyncAudioVersionSchema,SourceSyncAudioReceiptSchema,SourceSyncAudioViewSchema,SpeechScopeSchema,SpeechStartSchema,SpeechGetSchema,SpeechAdmissionSchema,SpeechGenerationViewSchema,SpeechOptionsSchema,KeyframeProviderProfileSchema,KeyframeStartInputSchema,KeyframeGetInputSchema,KeyframeQueryInputSchema,KeyframeAdmissionSchema,KeyframeGenerationViewSchema,KeyframeQueryPageSchema,KeyframeMediaSchema,KeyframeSummarySchema,ProviderTenantInputSchema,ProviderDefaultViewSchema,ProviderConnectionPageSchema,ProviderModelsViewSchema,ProviderModelViewSchema,ConfigureProviderModelSchema,DisableProviderModelSchema,ProviderModelPageSchema,ProviderModelGetSchema,SoundPlanScopeSchema,SoundPlanValidateSchema,SoundPlanAcceptSchema,SoundPlanGetSchema,SoundPlanValidationSchema,SoundPlanViewSchema,SoundPlanReceiptSchema,SoundPlanContextSchema,VisualFrameSequenceSchema,TimelineVisualLayerInputSchema,FinalRenderProfileIdSchema,FinalRenderProfileSchema,VisualLayerFinalProfileSchema,VisualLayerFinalManifestSchema,TimelineManifestReaderSchema,TimelineScopeSchema,BuildTimelineShapeSchema,BuildTimelineSchema,TimelineViewSchema,TimelineGetSchema,TimelineQuerySchema,TimelinePageSchema,TimelineBuildReceiptSchema,TimelineBasisSchema,TimelineSnapshotSchema,RoughCutStartSchema,RoughCutGetSchema,RoughCutQuerySchema,RoughCutV2ManifestSchema,RoughCutManifestReaderSchema,RoughCutTechnicalSchema,RoughCutArtifactSchema,RoughCutAdmissionSchema,RoughCutViewSchema,RoughCutPageSchema,RoughCutSnapshotSchema,MAX_SHOT_REVIEW_REQUIREMENTS,CompositionFindingLocalitySchema,BriefContentSchema,AcceptBriefRequestSchema,AcceptBriefResultSchema,StoryContentSchema,AcceptStoryRequestSchema,StoryVersionSchema,AcceptStoryResultSchema,ConsistencyProfileScopeSchema,ConsistencyProfileVersionQuerySchema,ConfigureConsistencyProfileSchema,ConsistencyProfileVersionSchema,ConsistencyProfileViewSchema,ConsistencyProfileReceiptSchema,RoughCutReviewScopeSchema,RecordRoughCutReviewSchema,RoughCutReviewRecordSchema,RoughCutReviewTargetSchema,RoughCutFindingViewSchema,RoughCutReviewQuerySchema,RoughCutReviewPageSchema,RoughCutFindingQuerySchema,RoughCutFindingPageSchema,RoughCutReviewReceiptSchema,ReviewEvidenceKeySchema,ReviewEvidenceMediaSchema,ObservationScopeSchema,ObservationStartSchema,ObservationGetSchema,ObservationAdmissionSchema,ObservationViewSchema,ObservationOptionsSchema,ProductionGuidanceContextSchema,VideoReviewScopeSchema,VideoReviewRequirementSchema,VideoObservationSchema,RecordVideoReviewSchema,VideoReviewRecordSchema,DecideVideoShotSchema,ShotAcceptanceScopeSchema,RevokeShotAcceptanceSchema,GeneratedShotAcceptanceDecisionSchema,ProgrammaticShotAcceptanceDecisionSchema,VideoReviewTargetSchema,ShotAcceptanceViewSchema,VideoReviewQuerySchema,VideoReviewPageSchema,ShotDecisionQuerySchema,ShotDecisionPageSchema,VideoReviewReceiptSchema,ShotDecisionReceiptSchema,ProgrammaticVideoReviewScopeSchema,ProgrammaticVideoReviewTargetSchema,RecordProgrammaticVideoReviewSchema,DecideProgrammaticShotSchema,ProgrammaticVideoReviewQuerySchema,ProgrammaticVideoReviewPageSchema,ProgrammaticVideoReviewReceiptSchema,BoundaryRequirementSchema,ShotIntentSchema,AcceptSceneShotPlanRequestSchema,ShotPlanEntrySchema,SceneShotPlanVersionSchema,AcceptSceneShotPlanResultSchema,WriterScopeSchema,ValidateWriterProposalSchema,WriterBriefResultSchema,WriterValidationResultSchema,DirectorScopeSchema,DirectorBasisSchema,ValidateDirectorProposalSchema,DirectorContextResultSchema,DirectorValidationResultSchema,KeyframeReviewScopeSchema,VisualRequirementSchema,KeyframeObservationSchema,RecordKeyframeReviewSchema,DecideKeyframeSchema,KeyframeReferenceScopeSchema,RevokeKeyframeSchema,KeyframeReviewTargetSchema,KeyframeReferenceViewSchema,KeyframeReviewQuerySchema,KeyframeReviewPageSchema,KeyframeReviewReceiptSchema,KeyframeDecisionReceiptSchema,KeyframeDecisionQuerySchema,KeyframeDecisionPageSchema,KeyframeReviewSummarySchema,ReviewIntelligenceContextInputSchema,ReviewIntelligenceBasisSchema,ValidateReviewIntelligenceSchema,ReviewIntelligenceContextResultSchema,ReviewIntelligenceValidationResultSchema};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{LocalDoctorReportSchema,LocalManagementInventorySchema,LocalRuntimeDescriptorSchema,LocalToolChoiceSchema,LocalToolSelectionSchema,LocalUpdatePlanSchema,NativeStudioLocalRuntimeClient,asset,canonicalLocalJson,catalogue,select}from"./chunk-KHKUJXQX.js";import{assertExecutable,directory,entries,fail,localSocketPath,optional,read,sha256,sha512,verifyBackup,write}from"./chunk-66CUOZVI.js";import{z}from"zod";import{constants,createReadStream}from"node:fs";import{open,realpath}from"node:fs/promises";import{isAbsolute}from"node:path";import{createHash}from"node:crypto";async function toolPreference(previous,cloud,explicit){if(explicit)return LocalToolChoiceSchema.parse(explicit);const raw=previous?JSON.parse((await read(previous,32768)).toString()):cloud?JSON.parse((await read(cloud,32768)).toString()).tools:null;const selected=raw?LocalToolSelectionSchema.parse(raw):null;return selected?.mode==="INSTALLED"?{...selected,mode:"INSTALLED"}:{mode:"MANAGED"}}async function captureInstalledTools(paths){paths=z.strictObject({mode:z.literal("INSTALLED").optional(),ffmpeg:z.string().min(1).max(4096),ffprobe:z.string().min(1).max(4096)}).parse(paths);const selected={};for(const name of["ffmpeg","ffprobe"]){if(!isAbsolute(paths[name]))fail("TOOL_PATH_INVALID");const path=await realpath(paths[name]);await assertExecutable(path);const file=await open(path,constants.O_RDONLY|constants.O_NOFOLLOW|constants.O_NONBLOCK);try{const before=await file.stat();if(!before.isFile()||before.size<1||before.size>256*1024*1024)fail("TOOL_PATH_INVALID");const h=createHash("sha256");let count=0;for await(const chunk of createReadStream(path,{fd:file.fd,autoClose:false})){count+=chunk.length;if(count>before.size)fail("TOOL_CHANGED");h.update(chunk)}const after=await file.stat();if(count!==before.size||after.size!==before.size||after.mtimeMs!==before.mtimeMs)fail("TOOL_CHANGED");selected[name]={path,digest:h.digest("hex")}}finally{await file.close()}}return LocalToolChoiceSchema.parse({mode:"INSTALLED",...selected})}var requiredRuntimeFiles=["package.json","dist/entry.js","dist/supervisor.mjs","dist/parent-lifetime.mjs","dist/execution-identity.json"];var allowedRuntimeFiles=new Set([...requiredRuntimeFiles,"README.md","LICENSE","dist/THIRD_PARTY_NOTICES.md","dist/BUNDLED_DEPENDENCIES.json","dist/agent-supervisor.mjs",...["Bootstrap.ps1","NativeMain.cs","PrivateAccess.cs","PipeBridge.cs","JobNative.cs","JobRunner.cs"].map(name=>"dist/native/"+name)]);import{spawn}from"node:child_process";import{open as open2}from"node:fs/promises";import{dirname,join,delimiter}from"node:path";var environment=()=>({...Object.fromEntries(["HOME","USER","LOGNAME","TMPDIR","CODEX_HOME","SystemRoot","SYSTEMROOT","USERPROFILE","LOCALAPPDATA","APPDATA","TEMP","TMP"].flatMap(k=>process.env[k]?[[k,process.env[k]]]:[])),PATH:dirname(process.execPath)+(process.platform==="win32"?"":delimiter+["/usr/bin","/bin"].join(delimiter)),LANG:"C",LC_ALL:"C",UV_THREADPOOL_SIZE:"2",NVS_INSTALL_OWNER:"MANAGED"});async function verifySlot(root,slot){if(requiredRuntimeFiles.some(name=>!Object.hasOwn(slot.files,name)))fail("SLOT_FILES_MISSING");for(const[name,hash]of Object.entries(slot.files)){if(!allowedRuntimeFiles.has(name))fail("SLOT_PATH_INVALID");if(sha256(await read(join(root,name),64*1024*1024))!==hash)fail("SLOT_INTEGRITY_INVALID")}}async function probe(root,expected){const bytes=await new Promise((resolve,reject)=>{const child=spawn(process.execPath,["--max-old-space-size=256",join(root,"dist/entry.js"),"--describe"],{env:environment(),stdio:["ignore","pipe","ignore"],shell:false});const parts=[];let size=0;const timer=setTimeout(()=>child.kill("SIGKILL"),1e4);child.stdout.on("data",b=>{size+=b.length;if(size>65536)child.kill("SIGKILL");else parts.push(b)});child.on("error",reject);child.on("close",code=>{clearTimeout(timer);if(code!==0||size>65536)reject(Error("Runtime descriptor unavailable"));else resolve(Buffer.concat(parts))})});const descriptor=LocalRuntimeDescriptorSchema.parse(JSON.parse(bytes.toString()));if(canonicalLocalJson(descriptor)!==canonicalLocalJson(expected))fail("RUNTIME_DESCRIPTOR_MISMATCH");return descriptor}async function ownerClient(stateDirectory){await directory(stateDirectory);return new NativeStudioLocalRuntimeClient({stateDirectory,authorization:async()=>"Bearer "+(await read(join(stateDirectory,"control-token"),128)).toString()})}async function runningInventory(client,root,slot){const inventory=await client.inventory(),status=await client.status();if(canonicalLocalJson(inventory.descriptor)!==canonicalLocalJson(slot.descriptor)||status.versions.find(v=>v.component==="RUNTIME")?.executablePath!==join(root,"dist/entry.js"))fail("RUNTIME_ALREADY_RUNNING");return inventory}async function launch(root,slot,stateDirectory,cloudConfig,toolsConfig){await verifySlot(root,slot);await probe(root,slot.descriptor);await directory(stateDirectory);const existing=await ownerClient(stateDirectory);try{return await runningInventory(existing,root,slot)}catch(e){if(e instanceof Error&&e.message.includes("RUNTIME_ALREADY_RUNNING"))throw e}const log=await open2(join(stateDirectory,"runtime-process.log"),"a",384);const child=spawn(process.execPath,["--max-old-space-size=256",join(root,"dist/entry.js"),"serve","--state-dir",stateDirectory,...cloudConfig?["--cloud-config",cloudConfig]:[],...toolsConfig?["--tools-config",toolsConfig]:[]],{env:environment(),detached:true,windowsHide:true,stdio:["ignore",log.fd,log.fd],shell:false});let spawnError=false;child.once("error",()=>{spawnError=true});child.unref();await log.close();const deadline=Date.now()+15e3;while(Date.now()<deadline){if(spawnError||child.exitCode!==null)fail("RUNTIME_START_FAILED");try{return await runningInventory(existing,root,slot)}catch{}await new Promise(r=>setTimeout(r,100))}child.kill("SIGTERM");fail("RUNTIME_START_UNCONFIRMED")}async function waitStopped(stateDirectory){const client=await ownerClient(stateDirectory),deadline=Date.now()+1e4;while(Date.now()<deadline){try{await client.inventory()}catch{const{lstat:lstat2}=await import("node:fs/promises");try{if(process.platform!=="win32")await lstat2(localSocketPath(stateDirectory))}catch(e){if(e.code==="ENOENT")return}const{createConnection}=await import("node:net");const closed=await new Promise(resolve=>{const s=createConnection(localSocketPath(stateDirectory));s.once("connect",()=>{s.destroy();resolve(false)});s.once("error",e=>resolve(["ECONNREFUSED","ENOENT"].includes(e.code??"")));s.setTimeout(300,()=>{s.destroy();resolve(false)})});if(closed)return}await new Promise(r=>setTimeout(r,100))}fail("RUNTIME_STOP_UNCONFIRMED")}async function socketAbsent(stateDirectory){const{createConnection}=await import("node:net");return new Promise(resolve=>{const socket=createConnection(localSocketPath(stateDirectory));socket.once("connect",()=>{socket.destroy();resolve(false)});socket.once("error",error=>resolve(["ECONNREFUSED","ENOENT"].includes(error.code??"")));socket.setTimeout(500,()=>{socket.destroy();resolve(false)})})}async function probeTools(root,stateDirectory,selection){const{execFile}=await import("node:child_process");const bytes=await new Promise((resolve,reject)=>execFile(process.execPath,["--max-old-space-size=256",join(root,"dist/entry.js"),"--qualify-tools","--state-dir",stateDirectory,"--tools-config",selection],{env:environment(),timeout:5e4,maxBuffer:65536},(error,stdout)=>error?reject(Error("Tool probe failed")):resolve(stdout)));const report=LocalDoctorReportSchema.parse(JSON.parse(bytes));if(report.availability!=="AVAILABLE")fail("TOOL_QUALIFICATION_FAILED");return report}import{randomUUID}from"node:crypto";import{lstat}from"node:fs/promises";import{join as join2}from"node:path";async function identity(path,cloud){if(!path)return null;const raw=JSON.parse((await read(path,32768)).toString());const tools=LocalToolSelectionSchema.parse(cloud?raw.tools:raw);return tools.ffmpeg.digest+":"+tools.ffprobe.digest}async function effective(path,cloud){return path?identity(path,false):identity(cloud,true)}async function assertPendingCompatible(raw,expected,previous,next,cloud){const i=LocalManagementInventorySchema.parse(raw);if(i.pendingRenderers.some(d=>d!==expected.rendererDigest))fail("NATIVE_RECOVERY_REQUIRED");if(i.pendingExecutions+i.pendingRequests===0)return;if(i.descriptor.profileDigest!==expected.profileDigest)fail("NATIVE_RECOVERY_REQUIRED");const before=await effective(previous,cloud);const after=await effective(next,cloud);if(!before||before!==after)fail("NATIVE_RECOVERY_REQUIRED")}async function assertPendingToolIdentity(raw,previous,cloud,next){const i=LocalManagementInventorySchema.parse(raw);if(i.pendingExecutions+i.pendingRequests>0&&await effective(previous,cloud)!==next)fail("NATIVE_RECOVERY_REQUIRED")}async function assertNoStoppedJournal(state){for(const suffix of["","-wal","-shm","-journal"]){try{await lstat(join2(state,"journal.sqlite"+suffix))}catch(e){if(e.code==="ENOENT")continue;throw e}fail("RUNTIME_STATUS_REQUIRED")}}async function prepareInstallation(manager,version,raw){const c=await manager.configuration(),current=(await manager.ledger.current()).value;if(current.transition)fail("ACTIVATION_IN_PROGRESS");const trusted=await catalogue(c),release=select(trusted.signed,version),explicit=raw===void 0?void 0:LocalToolChoiceSchema.parse(raw),preference=await toolPreference(current.active?.toolsConfigPath??null,c.cloudConfigFile,explicit),toolSelection=explicit||preference.mode==="INSTALLED"||release.tools?preference:void 0;if(toolSelection?.mode==="MANAGED"&&!release.tools)fail("MANAGED_TOOLS_UNAVAILABLE");let runtimeRevision=null;try{const inventory=await(await ownerClient(c.stateDirectory)).inventory();runtimeRevision=inventory.runtimeRevision;const previous=current.active?.toolsConfigPath??null;await assertPendingCompatible(inventory,release.descriptor,previous,previous,c.cloudConfigFile);const desired=preference.mode==="INSTALLED"?preference:release.tools;if(desired)await assertPendingToolIdentity(inventory,previous,c.cloudConfigFile,preference.mode==="INSTALLED"?preference.ffmpeg.digest+":"+preference.ffprobe.digest:release.tools.ffmpeg.sha256+":"+release.tools.ffprobe.sha256)}catch(e){if(e instanceof Error&&e.message.includes("NATIVE_RECOVERY_REQUIRED"))throw e;if(!await socketAbsent(c.stateDirectory))fail("RUNTIME_STATUS_REQUIRED");await assertNoStoppedJournal(c.stateDirectory)}const body={protocol:"NVS_LOCAL_UPDATE_PLAN_V1",planId:randomUUID(),installationRevision:current.revision,runtimeRevision,catalogueFingerprint:trusted.fingerprint,trustFingerprint:trusted.trustFingerprint,release,...toolSelection?{toolSelection}:{},createdAt:new Date().toISOString(),expiresAt:new Date(Math.min(Date.now()+18e5,Date.parse(trusted.signed.catalogue.expiresAt))).toISOString()};const plan=LocalUpdatePlanSchema.parse({...body,fingerprint:sha256(canonicalLocalJson(body))});await write(join2(manager.ledger.root,"plans",plan.planId+".json"),canonicalLocalJson(plan),true);return plan}function newerVersion(candidate,current){const parse=v=>{const core=v.split("+")[0],i=core.indexOf("-");return{parts:(i<0?core:core.slice(0,i)).split(".").map(BigInt),pre:i<0?null:core.slice(i+1).split(".")}};const a=parse(candidate),b=parse(current);for(let i=0;i<3;i++){if(a.parts[i]!==b.parts[i])return a.parts[i]>b.parts[i]}if(!a.pre||!b.pre)return!a.pre&&!!b.pre;for(let i=0;i<Math.max(a.pre.length,b.pre.length);i++){const x=a.pre[i],y=b.pre[i];if(x===y)continue;if(x===void 0||y===void 0)return y===void 0;const xn=/^\d+$/.test(x),yn=/^\d+$/.test(y);if(xn&&yn)return BigInt(x)>BigInt(y);if(xn!==yn)return!xn;return x>y}return false}import{randomUUID as randomUUID2}from"node:crypto";import{join as join3,dirname as dirname2}from"node:path";import{z as z2}from"zod";async function grant(manager,raw,output){const i=z2.strictObject({projects:z2.array(z2.strictObject({tenantId:z2.uuid(),projectId:z2.uuid()})).min(1).max(100),expiresAt:z2.iso.datetime({offset:true})}).parse(raw);const c=await manager.configuration(),client=await ownerClient(c.stateDirectory);await directory(dirname2(output));const connector=await client.call({operation:"session.issue",...i});await write(output,canonicalLocalJson(connector),true);await write(join3(manager.ledger.root,"grants",randomUUID2()+".json"),canonicalLocalJson({...i,output}),true);return{granted:true,projects:i.projects,expiresAt:i.expiresAt}}async function reconnect(manager){const{entries:entries2}=await import("./files-FZEK2ZZJ.js"),c=await manager.configuration(),client=await ownerClient(c.stateDirectory);let renewed=0,blocked=0;for(const name of await entries2(join3(manager.ledger.root,"grants"))){if(!/^[0-9a-f-]{36}\.json$/.test(name))continue;try{const g=z2.strictObject({projects:z2.array(z2.strictObject({tenantId:z2.uuid(),projectId:z2.uuid()})).max(100),expiresAt:z2.iso.datetime({offset:true}),output:z2.string().min(1)}).parse(await optional(join3(manager.ledger.root,"grants",name)));if(Date.parse(g.expiresAt)<=Date.now())continue;const connector=await client.call({operation:"session.issue",projects:g.projects,expiresAt:g.expiresAt});await write(g.output,canonicalLocalJson(connector));renewed++}catch{blocked++}}return{renewed,blocked}}import{randomUUID as randomUUID4}from"node:crypto";import{join as join7}from"node:path";import{z as z5}from"zod";import{z as z3}from"zod";import{join as join4}from"node:path";var slotSchema=z3.strictObject({id:z3.uuid(),descriptor:LocalRuntimeDescriptorSchema,toolsConfigPath:z3.string().nullable().default(null),files:z3.record(z3.string().min(1).max(100),z3.string().regex(/^[0-9a-f]{64}$/))});var transitionSchema=z3.strictObject({id:z3.uuid(),planId:z3.uuid(),fingerprint:z3.string().regex(/^[0-9a-f]{64}$/),phase:z3.enum(["STAGING","STAGED","DRAINING","ACTIVATING","VERIFYING","ROLLBACK_REQUIRED"]),previous:slotSchema.nullable(),candidate:slotSchema.nullable(),backupPath:z3.string().nullable(),failedPhase:z3.enum(["STAGING","STAGED","DRAINING","ACTIVATING","VERIFYING","ROLLBACK_REQUIRED"]).nullable().default(null)});var installationSchema=z3.strictObject({revision:z3.int().nonnegative(),active:slotSchema.nullable(),transition:transitionSchema.nullable()});var recordSchema=z3.strictObject({previous:z3.string().nullable(),value:installationSchema,digest:z3.string().regex(/^[0-9a-f]{64}$/)});var InstallationLedger=class _InstallationLedger{constructor(root){this.root=root}root;static async open(path){const root=await directory(path);for(const name of["revisions","plans","slots","grants"])await directory(join4(root,name));return new _InstallationLedger(root)}async current(){const names=(await entries(join4(this.root,"revisions"))).filter(n=>/^\d{12}\.json$/.test(n)).sort();let previous=null,value={revision:0,active:null,transition:null};for(const[i,name]of names.entries()){const raw=JSON.parse((await read(join4(this.root,"revisions",name),262144,true)).toString());const r=recordSchema.parse(raw);const expected=sha256(canonicalLocalJson({previous:raw.previous,value:raw.value}));if(r.value.revision!==i+1||r.previous!==previous||r.digest!==expected)fail("INSTALLATION_HISTORY_INVALID");previous=r.digest;value=r.value}return{value,digest:previous}}async commit(expected,next){const current=await this.current();if(current.value.revision!==expected.revision)fail("REVISION_CONFLICT");const value=installationSchema.parse({...next,revision:expected.revision+1});const record={previous:current.digest,value,digest:sha256(canonicalLocalJson({previous:current.digest,value}))};try{await write(join4(this.root,"revisions",String(value.revision).padStart(12,"0")+".json"),canonicalLocalJson(record),true)}catch(e){if(e.code==="EEXIST")fail("REVISION_CONFLICT");throw e}return value}slotPath(slot){return join4(this.root,"slots",slot.id)}};import{randomUUID as randomUUID3}from"node:crypto";import{chmod as chmod2}from"node:fs/promises";import{join as join6}from"node:path";import{constants as constants2}from"node:fs";import{open as open3}from"node:fs/promises";import{z as z4}from"zod";var metadataSchema=z4.strictObject({protocol:z4.literal("NVS_PRODUCT_COMPONENT_V1"),version:z4.string().min(1).max(120),byteSize:z4.int().positive().max(64*1024*1024),sha512:z4.string().regex(/^[a-f0-9]{128}$/)});async function regularBytes(url,maximum){const file=await open3(url,constants2.O_RDONLY|constants2.O_NOFOLLOW);try{const stat=await file.stat();if(!stat.isFile()||stat.size>maximum)fail("EMBEDDED_COMPONENT_INVALID");const bytes=Buffer.alloc(stat.size+1);let size=0;while(size<bytes.length){const result=await file.read(bytes,size,bytes.length-size,null);if(!result.bytesRead)break;size+=result.bytesRead}if(size!==stat.size)fail("EMBEDDED_COMPONENT_INVALID");return bytes.subarray(0,size)}finally{await file.close()}}async function verifiedEmbeddedAsset(base,release){try{const info=metadataSchema.parse(JSON.parse((await regularBytes(new URL("runtime.json",base),4096)).toString()));if(info.version!==release.descriptor.version)fail("EMBEDDED_RELEASE_MISMATCH");if(info.byteSize!==release.package.byteSize||info.sha512!==release.package.sha512)fail("EMBEDDED_RELEASE_MISMATCH");const bytes=await regularBytes(new URL("runtime.tgz",base),info.byteSize);if(bytes.length!==release.package.byteSize||sha512(bytes)!==release.package.sha512)fail("EMBEDDED_COMPONENT_INVALID");return bytes}catch(error){if(error instanceof Error&&error.message.includes("EMBEDDED_RELEASE_MISMATCH"))throw error;fail("EMBEDDED_COMPONENT_INVALID")}}async function embeddedAsset(release){if(false)return null;if(release.descriptor.version!=="0.3.0-rc.2")return null;if(false)fail("EMBEDDED_COMPONENT_INVALID");const base=new URL("./components/",import.meta.resolve("@nativestudio/cli/package.json"));return verifiedEmbeddedAsset(base,release)}import{gunzipSync}from"node:zlib";import{chmod}from"node:fs/promises";import{join as join5}from"node:path";async function unpack(bytes,root,expectedVersion){const data=gunzipSync(bytes,{maxOutputLength:64*1024*1024}),files=new Map;let offset=0;while(offset+512<=data.length){const header=data.subarray(offset,offset+512);if(header.every(b=>b===0))break;const text=(a,b)=>header.subarray(a,b).toString().replace(/\0.*$/s,"");const number=(a,b)=>{const v=text(a,b).trim();if(!/^[0-7]+$/.test(v))fail("PACKAGE_FORMAT_INVALID");return parseInt(v,8)};const sum=number(148,156);let actual=0;for(let i=0;i<512;i++)actual+=i>=148&&i<156?32:header[i];if(actual!==sum||!text(257,263).startsWith("ustar"))fail("PACKAGE_FORMAT_INVALID");const name=text(0,100),prefix=text(345,500),path=(prefix?prefix+"/":"")+name,size=number(124,136),kind=text(156,157);if(!Number.isSafeInteger(size)||size<0||offset+512+size>data.length)fail("PACKAGE_FORMAT_INVALID");if(kind==="5"){if(!/^package(?:\/dist(?:\/native)?)?\/?$/.test(path))fail("PACKAGE_PATH_INVALID")}else{if(kind!=="0"&&kind!=="")fail("PACKAGE_LINK_OR_METADATA_REFUSED");if(!path.startsWith("package/")||!allowedRuntimeFiles.has(path.slice(8))||files.has(path.slice(8)))fail("PACKAGE_PATH_INVALID");files.set(path.slice(8),data.subarray(offset+512,offset+512+size))}offset+=512+Math.ceil(size/512)*512}if(!requiredRuntimeFiles.every(p=>files.has(p)))fail("PACKAGE_FILES_MISSING");const manifest=JSON.parse(files.get("package.json").toString());const deps=manifest.dependencies;if(manifest.name!=="@nativestudio/local-runtime"||manifest.version!==expectedVersion||manifest.type!=="module"||Object.keys(deps??{}).length||Object.keys(manifest.optionalDependencies??{}).length||["preinstall","install","postinstall","prepare"].some(name=>Object.hasOwn(manifest.scripts??{},name))||!["dist/entry.js","./dist/entry.js"].includes(manifest.bin?.["nvs-runtime"]??"")||Object.keys(manifest.bin??{}).length!==1)fail("PACKAGE_IDENTITY_INVALID");const hashes={};await directory(join5(root,"dist"));if([...files.keys()].some(p=>p.startsWith("dist/native/")))await directory(join5(root,"dist/native"));for(const[path,contents]of files){await write(join5(root,path),contents,true);await chmod(join5(root,path),path.endsWith("entry.js")?320:256);hashes[path]=sha256(contents)}return hashes}async function stage(ledger,release,origin){const id=randomUUID3(),root=await directory(join6(ledger.root,"slots",id));const bytes=await embeddedAsset(release)??await asset(release.package,origin),files=await unpack(bytes,root,release.descriptor.version);const slot={id,files,descriptor:release.descriptor,toolsConfigPath:null};await probe(root,slot.descriptor);return slot}async function managedTools(release,origin,stateDirectory,selectionId){if(!release.tools)return null;const result={};for(const name of["ffmpeg","ffprobe"]){const a=release.tools[name],dir=await directory(join6(stateDirectory,"tools",a.sha256)),path2=join6(dir,name+(process.platform==="win32"?".exe":""));try{if(sha256(await read(path2,256*1024*1024))!==a.sha256)fail("TOOL_INTEGRITY_INVALID")}catch(e){if(e.code!=="ENOENT")throw e;const bytes=await asset(a,origin);if(sha256(bytes)!==a.sha256)fail("TOOL_INTEGRITY_INVALID");await write(path2,bytes,true);await chmod2(path2,320)}result[name]={path:path2,digest:a.sha256}}const selection={mode:"MANAGED",ffmpeg:result.ffmpeg,ffprobe:result.ffprobe};const path=join6(await directory(join6(stateDirectory,"tool-selections")),selectionId+".json");await write(path,JSON.stringify(selection));return path}async function selectedTools(release,origin,state,slotId,cloudConfig,previousSelection,explicit){const preference=await toolPreference(previousSelection,cloudConfig,explicit);if(preference.mode==="INSTALLED"){const path=join6(await directory(join6(state,"tool-selections")),slotId+".json");await write(path,JSON.stringify(preference),true);return path}if(explicit?.mode==="MANAGED"&&!release.tools)fail("MANAGED_TOOLS_UNAVAILABLE");return await managedTools(release,origin,state,slotId)??previousSelection}var configurationSchema=z5.strictObject({stateDirectory:z5.string().min(1).max(4096),catalogueUrl:z5.string().url(),publicKeyFile:z5.string().min(1).max(4096),cloudConfigFile:z5.string().nullable().default(null),notifications:z5.boolean().default(true),rejectedVersions:z5.array(LocalRuntimeDescriptorSchema.shape.version).max(64).default([])});var LocalInstallationManager=class _LocalInstallationManager{constructor(ledger){this.ledger=ledger}ledger;static async open(root){return new _LocalInstallationManager(await InstallationLedger.open(root))}async configure(raw,options={}){const c=configurationSchema.parse(raw);c.stateDirectory=await directory(c.stateDirectory);await write(join7(this.ledger.root,"configuration.json"),canonicalLocalJson(c),options.ifAbsent);return{configured:true}}async configuration(){const value=await optional(join7(this.ledger.root,"configuration.json"));if(!value)fail("CONFIGURATION_REQUIRED");return configurationSchema.parse(value)}async status(){const s=(await this.ledger.current()).value;let c;try{c=await this.configuration()}catch(error){if(error instanceof Error&&error.message.includes("CONFIGURATION_REQUIRED"))return{protocol:"NVS_LOCAL_INSTALLATION_STATUS_V1",revision:s.revision,activeVersion:s.active?.descriptor.version??null,running:null,phase:s.transition?.phase??"IDLE",nextActions:[{surface:"CLI",operation:"local.configure",availability:"AVAILABLE",reason:"INSTALL_REQUIRED"}]};throw error}let running=null;try{running=await(await ownerClient(c.stateDirectory)).status()}catch{}return{protocol:"NVS_LOCAL_INSTALLATION_STATUS_V1",revision:s.revision,activeVersion:s.active?.descriptor.version??null,entryPath:s.active?join7(this.ledger.slotPath(s.active),"dist/entry.js"):null,installOwner:"MANAGED",phase:s.transition?.phase??"IDLE",running,nextActions:[{surface:"CLI",operation:s.transition?"local.update.reconcile":s.active?"local.start":"local.install",availability:"AVAILABLE",reason:s.transition?"RECOVERY_REQUIRED":s.active?"READY":"INSTALL_REQUIRED"}]}}async reject(version){LocalRuntimeDescriptorSchema.shape.version.parse(version);const c=await this.configuration();await this.configure({...c,rejectedVersions:[...new Set([...c.rejectedVersions,version])]});return{rejected:true,version,selectedVersion:(await this.ledger.current()).value.active?.descriptor.version??null}}async check(){const c=await this.configuration(),v=await catalogue(c);return{installation:await this.status(),catalogueFingerprint:v.fingerprint,available:v.signed.catalogue.releases.filter(r=>r.descriptor.platform.os===process.platform&&r.descriptor.platform.architecture===process.arch).map(r=>r.descriptor),notifications:c.notifications,rejectedVersions:c.rejectedVersions}}prepare(version,choice){return prepareInstallation(this,version,choice)}async plan(id){if(!z5.uuid().safeParse(id).success)fail("PLAN_INVALID");const p=LocalUpdatePlanSchema.parse(JSON.parse((await read(join7(this.ledger.root,"plans",id+".json"))).toString()));const{fingerprint,...body}=p;if(sha256(canonicalLocalJson(body))!==fingerprint)fail("PLAN_CHANGED");return p}async transition(s,phase,patch={}){if(!s.transition)fail("TRANSITION_REQUIRED");return this.ledger.commit(s,{active:s.active,transition:{...s.transition,...patch,phase}})}async apply(id,approval){const plan=await this.plan(id),c=await this.configuration();if(approval!==plan.fingerprint)fail("USER_APPROVAL_REQUIRED");const trusted=await catalogue(c);if(Date.parse(plan.expiresAt)<=Date.now()||plan.trustFingerprint!==trusted.trustFingerprint||canonicalLocalJson(select(trusted.signed,plan.release.descriptor.version))!==canonicalLocalJson(plan.release))fail("PLAN_CHANGED");let s=(await this.ledger.current()).value;if(s.revision!==plan.installationRevision||s.transition)fail("REVISION_CONFLICT");if(plan.runtimeRevision!==null){const i=await(await ownerClient(c.stateDirectory)).inventory();if(i.runtimeRevision!==plan.runtimeRevision||i.pendingRenderers.some(d=>d!==plan.release.descriptor.rendererDigest))fail("REVISION_CONFLICT")}if(plan.runtimeRevision===null){if(!await socketAbsent(c.stateDirectory))fail("REVISION_CONFLICT");await assertNoStoppedJournal(c.stateDirectory)}s=await this.ledger.commit(s,{active:s.active,transition:{id:randomUUID4(),planId:id,fingerprint:approval,phase:"STAGING",previous:s.active,candidate:null,backupPath:null,failedPhase:null}});try{let candidate=await stage(this.ledger,plan.release,trusted.origin);const tools=await selectedTools(plan.release,trusted.origin,c.stateDirectory,candidate.id,c.cloudConfigFile,s.active?.toolsConfigPath??null,plan.toolSelection);candidate={...candidate,toolsConfigPath:tools};if(tools)await probeTools(this.ledger.slotPath(candidate),c.stateDirectory,tools);s=await this.transition(s,"STAGED",{candidate});if(plan.runtimeRevision!==null){const client=await ownerClient(c.stateDirectory),i=await client.inventory();if(i.runtimeRevision!==plan.runtimeRevision||i.pendingRenderers.some(d=>d!==candidate.descriptor.rendererDigest))fail("REVISION_CONFLICT");await assertPendingCompatible(i,candidate.descriptor,s.active?.toolsConfigPath??null,tools,c.cloudConfigFile);s=await this.transition(s,"DRAINING");const result=await client.call({operation:"runtime.stop",expectedRuntimeRevision:plan.runtimeRevision});if(!result||typeof result!=="object"||!("backupPath"in result)||typeof result.backupPath!=="string")fail("JOURNAL_BACKUP_REQUIRED");await verifyBackup(result.backupPath,c.stateDirectory);s=await this.transition(s,"ACTIVATING",{backupPath:result.backupPath});await waitStopped(c.stateDirectory);await assertPendingCompatible("inventory"in result?result.inventory:null,candidate.descriptor,s.active?.toolsConfigPath??null,tools,c.cloudConfigFile)}else{if(!await socketAbsent(c.stateDirectory))fail("REVISION_CONFLICT");await assertNoStoppedJournal(c.stateDirectory);s=await this.transition(s,"ACTIVATING")}s=await this.ledger.commit(s,{active:candidate,transition:{...s.transition,phase:"VERIFYING"}});await this.startSlot(candidate,c);s=await this.ledger.commit(s,{active:candidate,transition:null});await this.reconnect();return{activated:true,revision:s.revision,version:candidate.descriptor.version}}catch(error){const actual=(await this.ledger.current()).value;if(actual.transition?.planId===id)await this.transition(actual,"ROLLBACK_REQUIRED",{failedPhase:actual.transition.phase});throw error}}async startSlot(slot,c){return launch(this.ledger.slotPath(slot),slot,c.stateDirectory,c.cloudConfigFile??void 0,slot.toolsConfigPath??void 0)}async start(){const s=(await this.ledger.current()).value;if(s.transition)fail("ACTIVATION_IN_PROGRESS");if(!s.active)fail("INSTALL_REQUIRED");const c=await this.configuration(),inventory=await this.startSlot(s.active,c);const clients=await this.reconnect();let updateNotice={status:"DISABLED"};if(c.notifications){try{const v=await catalogue(c,AbortSignal.timeout(1500));updateNotice={status:"CHECKED",versions:v.signed.catalogue.releases.filter(r=>r.descriptor.platform.os===process.platform&&r.descriptor.platform.architecture===process.arch&&newerVersion(r.descriptor.version,s.active.descriptor.version)&&!c.rejectedVersions.includes(r.descriptor.version)).map(r=>r.descriptor.version)}}catch{updateNotice={status:"UNAVAILABLE"}}}return{...inventory,clients,updateNotice}}async stop(){const c=await this.configuration(),client=await ownerClient(c.stateDirectory),i=await client.inventory();const result=await client.call({operation:"runtime.stop",expectedRuntimeRevision:i.runtimeRevision});await waitStopped(c.stateDirectory);return result}async reconcile(id,approval){const s=(await this.ledger.current()).value,c=await this.configuration();if(!s.transition||s.transition.planId!==id||s.transition.fingerprint!==approval)fail("USER_APPROVAL_REQUIRED");if(s.active?.id===s.transition.previous?.id&&["STAGING","STAGED"].includes(s.transition.failedPhase??s.transition.phase)){const next2=await this.ledger.commit(s,{active:s.transition.previous,transition:null});return{rolledBack:true,revision:next2.revision,version:next2.active?.descriptor.version??null}}const candidate=s.transition.candidate;if(candidate){try{const i=await runningInventory(await ownerClient(c.stateDirectory),this.ledger.slotPath(candidate),candidate);if(canonicalLocalJson(i.descriptor)===canonicalLocalJson(candidate.descriptor)){await verifySlot(this.ledger.slotPath(candidate),candidate);const next2=await this.ledger.commit(s,{active:candidate,transition:null});await this.reconnect();return{recovered:true,revision:next2.revision,version:candidate.descriptor.version}}}catch{}}await waitStopped(c.stateDirectory);const previous=s.transition.previous;const next=await this.ledger.commit(s,{active:previous,transition:null});if(previous)await this.startSlot(previous,c);await this.reconnect();return{rolledBack:true,revision:next.revision,version:previous?.descriptor.version??null}}grant(raw,output){return grant(this,raw,output)}reconnect(){return reconnect(this)}};export{toolPreference,captureInstalledTools,ownerClient,socketAbsent,LocalInstallationManager};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{KeyframeObservationSchema,NativeRuntimePublicKeySchema,ReviewEvidenceMediaSchema,ReviewIntelligenceBasisSchema,ReviewIntelligenceContextResultSchema,RoughCutAdmissionSchema,RoughCutManifestReaderSchema,RoughCutStartSchema,RoughCutTechnicalSchema,ValidateReviewIntelligenceSchema,VisualRequirementSchema}from"./chunk-HLKERZIE.js";import{OperationIdSchema}from"./chunk-VPYAXWXY.js";import{fail,localSocketPath,privateAccess,privateDirectory,read,sha256,sha512}from"./chunk-66CUOZVI.js";import{NativeStudioSdkError}from"./chunk-6NVIN2NI.js";import{z as z2}from"zod";import{z}from"zod";var LocalIdSchema=z.uuid().transform(v=>v.toLowerCase());var LocalDigestSchema=z.string().length(64).regex(/^[0-9a-f]{64}$/);var LocalRevisionSchema=z.int().positive();var LocalTimeSchema=z.iso.datetime({offset:true});var LocalPackageVersionSchema=z.string().max(120).regex(/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-(?:0|[1-9]\d*|\d*[A-Za-z-][0-9A-Za-z-]*)(?:\.(?:0|[1-9]\d*|\d*[A-Za-z-][0-9A-Za-z-]*))*)?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/).refine(v=>v===v.trim());var LocalProjectScopeSchema=z.strictObject({tenantId:LocalIdSchema,projectId:LocalIdSchema});var LocalWorkScopeSchema=LocalProjectScopeSchema.extend({productionId:LocalIdSchema,runtimeJobId:LocalIdSchema});var LocalPlacementPolicySchema=z.discriminatedUnion("mode",[z.strictObject({mode:z.literal("local-only"),deviceId:LocalIdSchema}),z.strictObject({mode:z.literal("local-preferred"),deviceId:LocalIdSchema}),z.strictObject({mode:z.literal("cloud-only")})]);var LocalPlacementAvailabilitySchema=z.discriminatedUnion("status",[z.strictObject({status:z.literal("AVAILABLE"),deviceId:LocalIdSchema}),z.strictObject({status:z.literal("UNAVAILABLE"),deviceId:LocalIdSchema,reason:z.enum(["OFFLINE","UNQUALIFIED","BUSY"])}),z.strictObject({status:z.literal("DENIED"),reason:z.enum(["FORBIDDEN","APPROVAL_REQUIRED","INVALID_INPUT"])})]);var LocalDevicePlatformSchema=z2.strictObject({os:z2.enum(["darwin","linux","win32"]),architecture:z2.enum(["x64","arm64"])});var EnrollLocalDeviceSchema=z2.strictObject({tenantId:LocalIdSchema,requestId:LocalIdSchema,label:z2.string().trim().min(1).max(120),platform:LocalDevicePlatformSchema,runtimeVersion:LocalPackageVersionSchema,publicKey:NativeRuntimePublicKeySchema});var LocalDeviceViewSchema=EnrollLocalDeviceSchema.omit({requestId:true}).extend({deviceId:LocalIdSchema,revision:LocalRevisionSchema,enrolledByPrincipalId:LocalIdSchema,createdAt:LocalTimeSchema,verifiedAt:LocalTimeSchema.nullable(),revokedAt:LocalTimeSchema.nullable()}).refine(v=>[v.verifiedAt,v.revokedAt].every(time=>time===null||Date.parse(time)>=Date.parse(v.createdAt)));var LocalDeviceChallengeSchema=z2.strictObject({tenantId:LocalIdSchema,deviceId:LocalIdSchema,deviceRevision:LocalRevisionSchema,challengeId:LocalIdSchema,audience:z2.string().min(1).max(2048),issuedAt:LocalTimeSchema,expiresAt:LocalTimeSchema}).refine(v=>{const ttl=Date.parse(v.expiresAt)-Date.parse(v.issuedAt);return ttl>0&&ttl<=3e5});var LocalDeviceProofClaimsSchema=z2.strictObject({protocol:z2.literal("NVS_LOCAL_DEVICE_PROOF_V1"),tenantId:LocalIdSchema,deviceId:LocalIdSchema,deviceRevision:LocalRevisionSchema,challengeId:LocalIdSchema,audience:z2.string().min(1).max(2048),jti:LocalIdSchema,iat:z2.int().nonnegative(),exp:z2.int().positive()}).refine(v=>v.exp>v.iat&&v.exp-v.iat<=60);var ProveLocalDeviceSchema=z2.strictObject({tenantId:LocalIdSchema,deviceId:LocalIdSchema,deviceRevision:LocalRevisionSchema,challengeId:LocalIdSchema,assertion:z2.string().max(4096).regex(/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/).meta({writeOnly:true})});var GrantLocalDeviceSchema=LocalProjectScopeSchema.extend({requestId:LocalIdSchema,deviceId:LocalIdSchema,deviceRevision:LocalRevisionSchema,expectedRevision:z2.int().nonnegative(),expiresAt:LocalTimeSchema,capability:z2.literal("ROUGH_CUT_PREVIEW_V1")});var LocalDeviceGrantSchema=GrantLocalDeviceSchema.omit({requestId:true,expectedRevision:true}).extend({grantId:LocalIdSchema,revision:LocalRevisionSchema,approvedByPrincipalId:LocalIdSchema,createdAt:LocalTimeSchema,revokedAt:LocalTimeSchema.nullable()}).refine(v=>Date.parse(v.expiresAt)>Date.parse(v.createdAt));var RevokeLocalDeviceGrantSchema=LocalProjectScopeSchema.extend({grantId:LocalIdSchema,requestId:LocalIdSchema,expectedRevision:LocalRevisionSchema});var RevokeLocalDeviceSchema=z2.strictObject({tenantId:LocalIdSchema,deviceId:LocalIdSchema,requestId:LocalIdSchema,expectedRevision:LocalRevisionSchema});import{z as z4}from"zod";import{z as z3}from"zod";var LocalExecutionProfileSchema=z3.strictObject({kind:z3.literal("ROUGH_CUT_PREVIEW_V1"),profileId:z3.literal("PREVIEW_H264_480P_V1"),contractDigest:LocalDigestSchema});var LocalToolchainSchema=z3.strictObject({platform:LocalDevicePlatformSchema,rendererVersion:LocalPackageVersionSchema,rendererDigest:LocalDigestSchema,ffmpeg:z3.strictObject({version:z3.string().min(1).max(160),binaryDigest:LocalDigestSchema}),ffprobe:z3.strictObject({version:z3.string().min(1).max(160),binaryDigest:LocalDigestSchema}),profile:LocalExecutionProfileSchema});var LocalFrozenWorkSchema=LocalWorkScopeSchema.extend({protocol:z3.literal("NVS_LOCAL_WORK_V1"),operationId:OperationIdSchema,renderId:LocalIdSchema,productionRevision:LocalRevisionSchema,executionClass:z3.enum(["LIVE","TEST_ONLY"]),policy:LocalPlacementPolicySchema,profile:LocalExecutionProfileSchema,manifest:RoughCutManifestReaderSchema,manifestFingerprint:LocalDigestSchema,sources:z3.array(z3.strictObject({artifactId:LocalIdSchema,representationId:LocalIdSchema,checksumSha256:LocalDigestSchema,byteSize:z3.int().positive(),contentType:z3.string().min(1).max(100)})).min(1).max(512)}).superRefine((v,ctx)=>{const t=v.manifest.timeline;if(t.tenantId!==v.tenantId||t.projectId!==v.projectId||t.productionId!==v.productionId||t.executionClass!==v.executionClass)ctx.addIssue({code:"custom",message:"Frozen manifest scope/class mismatch"});if(new Set(v.sources.map(s=>s.representationId)).size!==v.sources.length)ctx.addIssue({code:"custom",message:"Duplicate source representation"})});var LocalLeaseBindingSchema=LocalWorkScopeSchema.extend({attemptId:LocalIdSchema,assignmentRevision:LocalRevisionSchema,workerId:z3.string().min(1).max(200),workFingerprint:LocalDigestSchema,toolchainFingerprint:LocalDigestSchema});var target=z3.discriminatedUnion("kind",[z3.strictObject({kind:z3.literal("DEVICE"),deviceId:LocalIdSchema,deviceRevision:LocalRevisionSchema,grantId:LocalIdSchema,grantRevision:LocalRevisionSchema}),z3.strictObject({kind:z3.literal("SERVER")})]);var LocalExecutionLeaseSchema=LocalLeaseBindingSchema.extend({target,issuedAt:LocalTimeSchema,expiresAt:LocalTimeSchema}).refine(v=>Date.parse(v.expiresAt)>Date.parse(v.issuedAt));var LocalWorkAssignmentSchema=z3.strictObject({work:LocalFrozenWorkSchema,lease:LocalExecutionLeaseSchema,toolchain:LocalToolchainSchema}).superRefine(({work,lease,toolchain},ctx)=>{if(["tenantId","projectId","productionId","runtimeJobId"].some(k=>work[k]!==lease[k]))ctx.addIssue({code:"custom",message:"Assignment work scope mismatch"});const p=work.policy,t=lease.target;if(p.mode==="cloud-only"&&t.kind!=="SERVER"||p.mode==="local-only"&&t.kind!=="DEVICE"||t.kind==="DEVICE"&&(p.mode==="cloud-only"||p.deviceId!==t.deviceId))ctx.addIssue({code:"custom",message:"Assignment contradicts placement policy"});if(work.profile.contractDigest!==toolchain.profile.contractDigest)ctx.addIssue({code:"custom",message:"Unqualified execution profile"})});var StartLocalPreviewSchema=RoughCutStartSchema.extend({placement:LocalPlacementPolicySchema});var LocalDeviceScopeSchema=z4.strictObject({tenantId:LocalIdSchema,deviceId:LocalIdSchema});var LocalDeviceSessionSchema=z4.strictObject({...LocalDeviceScopeSchema.shape,expiresAt:LocalTimeSchema,credential:z4.string().length(43).regex(/^[A-Za-z0-9_-]+$/).meta({writeOnly:true})});var LocalDeviceHeartbeatSchema=LocalDeviceScopeSchema.extend({toolchain:LocalToolchainSchema,available:z4.boolean()});var ClaimLocalPreviewSchema=LocalProjectScopeSchema.extend({requestId:LocalIdSchema,deviceId:LocalIdSchema});var LocalOutputStageSchema=LocalLeaseBindingSchema.extend({uploadRequestId:LocalIdSchema,role:z4.enum(["VIDEO","POSTER"]),checksumSha256:LocalDigestSchema,byteSize:z4.int().positive().max(128*1024*1024)});var LocalOutputTicketSchema=z4.strictObject({receiptId:LocalIdSchema,role:z4.enum(["VIDEO","POSTER"]),checksumSha256:LocalDigestSchema,byteSize:z4.int().positive(),uploaded:z4.boolean()});var LocalSourceRequestSchema=LocalLeaseBindingSchema.extend({representationId:LocalIdSchema});var LocalProofChallengeRequestSchema=LocalDeviceScopeSchema.extend({deviceRevision:z4.int().positive()});var LocalPreviewPlacementViewSchema=z4.strictObject({target:z4.enum(["DEVICE","SERVER"]),reason:z4.enum(["LOCAL_AVAILABLE","CLOUD_ONLY","OFFLINE","UNQUALIFIED","BUSY","LEASE_RECOVERY"]),policy:LocalPlacementPolicySchema});var LocalDeviceTransportConfigurationSchema=z4.strictObject({endpoint:z4.string().url().max(2048),tenantId:LocalIdSchema,deviceId:LocalIdSchema,deviceRevision:z4.int().positive(),projects:z4.array(LocalProjectScopeSchema).min(1).max(20),privateKeyFile:z4.string().min(1).max(4096),platform:LocalDevicePlatformSchema});var LocalPreviewAdmissionSchema=RoughCutAdmissionSchema.extend({placement:LocalPreviewPlacementViewSchema});var LocalClaimReceiptSchema=z4.strictObject({found:z4.boolean(),assignment:LocalWorkAssignmentSchema.nullable()});var LocalWorkStateSchema=z4.strictObject({binding:LocalLeaseBindingSchema,status:z4.enum(["ACTIVE","FENCED","OUTCOME_UNKNOWN"]),assignment:LocalWorkAssignmentSchema.nullable()});import{z as z9}from"zod";import{z as z6}from"zod";import{z as z5}from"zod";var executable=z5.strictObject({path:z5.string().min(1).max(4096),digest:LocalDigestSchema});var LocalToolSelectionSchema=z5.strictObject({mode:z5.enum(["MANAGED","INSTALLED"]),ffmpeg:executable,ffprobe:executable});var LocalRuntimeDescriptorSchema=z6.strictObject({protocol:z6.literal("NVS_RUNTIME_DESCRIPTOR_V1"),version:LocalPackageVersionSchema,node:z6.strictObject({major:z6.literal(24),minMinor:z6.literal(12)}),platform:LocalDevicePlatformSchema,ipcProtocol:z6.literal("NVS_LOCAL_IPC_V1"),workProtocol:z6.literal("NVS_LOCAL_WORK_V1"),journalSchema:z6.literal(1),rendererDigest:LocalDigestSchema,profileDigest:LocalDigestSchema});var LocalSessionConnectorSchema=z6.strictObject({protocol:z6.literal("NVS_LOCAL_CONNECTOR_V1"),stateDirectory:z6.string().min(1).max(4096),credential:z6.string().length(43).regex(/^[A-Za-z0-9_-]{43}$/),expiresAt:LocalTimeSchema,projects:z6.array(LocalProjectScopeSchema).min(1).max(100)});var LocalManagementInventorySchema=z6.strictObject({runtimeRevision:z6.int().positive(),descriptor:LocalRuntimeDescriptorSchema,activeProcesses:z6.int().nonnegative(),pendingExecutions:z6.int().nonnegative(),pendingRequests:z6.int().nonnegative(),pendingRenderers:z6.array(LocalDigestSchema).max(64)});var LocalReleaseAssetSchema=z6.strictObject({url:z6.string().url().max(2048),byteSize:z6.int().positive().max(256*1024*1024),sha512:z6.string().length(128).regex(/^[0-9a-f]{128}$/)});var LocalReleaseSchema=z6.strictObject({descriptor:LocalRuntimeDescriptorSchema,package:LocalReleaseAssetSchema,tools:z6.strictObject({ffmpeg:LocalReleaseAssetSchema.extend({sha256:LocalDigestSchema}),ffprobe:LocalReleaseAssetSchema.extend({sha256:LocalDigestSchema})}).nullable()});var LocalReleaseCatalogueSchema=z6.strictObject({protocol:z6.literal("NVS_LOCAL_RELEASE_CATALOGUE_V1"),issuedAt:LocalTimeSchema,expiresAt:LocalTimeSchema,releases:z6.array(LocalReleaseSchema).min(1).max(32)}).refine(v=>Date.parse(v.expiresAt)>Date.parse(v.issuedAt)&&Date.parse(v.expiresAt)-Date.parse(v.issuedAt)<=7*864e5&&new Set(v.releases.map(r=>[r.descriptor.version,r.descriptor.platform.os,r.descriptor.platform.architecture].join(":"))).size===v.releases.length);var LocalSignedCatalogueSchema=z6.strictObject({catalogue:LocalReleaseCatalogueSchema,signature:z6.string().length(86).regex(/^[A-Za-z0-9_-]{85}[AQgw]$/)});var LocalToolChoiceSchema=z6.discriminatedUnion("mode",[z6.strictObject({mode:z6.literal("MANAGED")}),LocalToolSelectionSchema.extend({mode:z6.literal("INSTALLED")})]);var LocalUpdatePlanSchema=z6.strictObject({protocol:z6.literal("NVS_LOCAL_UPDATE_PLAN_V1"),planId:LocalIdSchema,installationRevision:z6.int().nonnegative(),runtimeRevision:z6.int().positive().nullable(),catalogueFingerprint:LocalDigestSchema,trustFingerprint:LocalDigestSchema.optional(),release:LocalReleaseSchema,toolSelection:LocalToolChoiceSchema.optional(),fingerprint:LocalDigestSchema,createdAt:LocalTimeSchema,expiresAt:LocalTimeSchema});var LocalClientNextActionSchema=z6.strictObject({surface:z6.enum(["CLI","LOCAL_IPC","REMOTE"]),operation:z6.enum(["runtime.status","local.configure","local.install","local.start","local.connect","local.grant","local.status","local.doctor","local.stop","local.update.check","local.update.prepare","local.update.apply","local.update.reconcile","execution.inspect","rough_cut_get","operation_get"]),availability:z6.enum(["AVAILABLE","BLOCKED"]),reason:z6.enum(["READY","INSTALL_REQUIRED","AUTHORIZATION_REQUIRED","VERSION_INCOMPATIBLE","UPDATE_AVAILABLE","RECOVERY_REQUIRED","USER_APPROVAL_REQUIRED","TRUST_REQUIRED","UNAVAILABLE"])});import{z as z8}from"zod";import{z as z7}from"zod";function canonicalLocalJson(value){if(value===null||typeof value==="string"||typeof value==="boolean")return JSON.stringify(value);if(typeof value==="number"&&Number.isFinite(value))return JSON.stringify(value);if(Array.isArray(value))return"["+value.map(canonicalLocalJson).join(",")+"]";if(typeof value==="object")return"{"+Object.entries(value).filter(([,v])=>v!==void 0).sort(([a],[b])=>a<b?-1:a>b?1:0).map(([k,v])=>JSON.stringify(k)+":"+canonicalLocalJson(v)).join(",")+"}";throw new Error("Fingerprint input must be finite JSON data")}var sha=z7.string().regex(/^[a-f0-9]{64}$/);var qualifiedVersion=z7.enum(["0.164.0","0.165.0"]);var LocalAgentGrantSchema=z7.strictObject({protocol:z7.literal("NVS_CODEX_REVIEW_GRANT_V1"),binary:z7.string().min(1).max(4096).startsWith("/"),binaryDigest:sha,version:qualifiedVersion,model:z7.string().regex(/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,99}$/),reasoningEffort:z7.enum(["low","medium","high","xhigh"]).optional(),reviewerLabel:z7.string().trim().min(1).max(100),inference:z7.literal("REMOTE_OPENAI"),remoteUseApproved:z7.literal(true),imageDisclosureApproved:z7.literal(true).optional(),projects:z7.array(LocalProjectScopeSchema).min(1).max(100),expiresAt:z7.iso.datetime({offset:true})});var LocalAgentSnapshotSchema=z7.strictObject({basis:ReviewIntelligenceBasisSchema.extend({target:z7.strictObject({kind:z7.literal("IMAGE"),generationId:z7.uuid()})}),productionRevision:z7.int().positive(),reviewVersion:z7.int().nonnegative(),executionClass:z7.enum(["LIVE","TEST_ONLY"]),media:ReviewEvidenceMediaSchema,requirements:z7.array(VisualRequirementSchema).min(1).max(64),image:z7.strictObject({contentType:z7.literal("image/png"),byteSize:z7.int().positive().max(8388608),width:z7.int().positive().max(4096),height:z7.int().positive().max(4096)}).optional()}).refine(v=>new TextEncoder().encode(JSON.stringify(v)).length<=32768).refine(v=>new Set(v.requirements.map(r=>r.key)).size===v.requirements.length);var LocalAgentProbeSchema=z7.strictObject({configured:z7.boolean(),available:z7.boolean(),reason:z7.enum(["GRANT_REQUIRED","READY","RUNTIME_UNAVAILABLE","GRANT_EXPIRED"]),grantFingerprint:sha.nullable(),inference:z7.literal("REMOTE_OPENAI")});var LocalAgentPlanSchema=z7.strictObject({protocol:z7.literal("NVS_LOCAL_AGENT_REVIEW_V1"),id:z7.uuid(),grantFingerprint:sha,snapshot:LocalAgentSnapshotSchema,expiresAt:z7.iso.datetime({offset:true}),fingerprint:sha});var LocalAgentMetadataAnswerSchema=z7.strictObject({summary:z7.string().trim().min(1).max(1500),observations:z7.array(z7.strictObject({key:z7.string().min(1).max(200),observed:z7.string().trim().min(1).max(1e3)})).min(1).max(64)});var LocalAgentPixelAnswerSchema=z7.strictObject({summary:z7.string().trim().min(1).max(1500),imageReadback:z7.string().trim().min(1).max(800),observations:z7.array(KeyframeObservationSchema.omit({region:true})).min(1).max(64)});var LocalAgentAnswerSchema=z7.union([LocalAgentMetadataAnswerSchema,LocalAgentPixelAnswerSchema]).refine(v=>new TextEncoder().encode(JSON.stringify(v)).length<=96*1024);var LocalAgentImageReceiptSchema=z7.strictObject({protocol:z7.literal("NVS_LOCAL_AGENT_IMAGE_V1"),draftId:z7.uuid(),media:ReviewEvidenceMediaSchema,byteSize:z7.int().positive().max(8388608),contentType:z7.literal("image/png"),width:z7.int().positive().max(4096),height:z7.int().positive().max(4096)});var LocalAgentReviewViewSchema=z7.strictObject({plan:LocalAgentPlanSchema,revision:z7.int().positive(),phase:z7.enum(["PREPARED","RUNNING","RESULT_PENDING","UNKNOWN"]),answer:LocalAgentAnswerSchema.nullable(),imageReceipt:LocalAgentImageReceiptSchema.optional(),provenance:z7.strictObject({adapter:z7.literal("CODEX_METADATA_V1"),binaryDigest:sha,version:qualifiedVersion,model:z7.string().max(100),reasoningEffort:z7.enum(["low","medium","high","xhigh"]).optional(),reviewerLabel:z7.string().max(100),inference:z7.literal("REMOTE_OPENAI"),evidence:z7.enum(["METADATA_ONLY","IMAGE_PIXELS"])})}).refine(v=>{const image=v.plan.snapshot.image,receipt=v.imageReceipt;if(receipt&&(!image||receipt.draftId!==v.plan.id||canonicalLocalJson(receipt.media)!==canonicalLocalJson(v.plan.snapshot.media)||canonicalLocalJson({contentType:receipt.contentType,byteSize:receipt.byteSize,width:receipt.width,height:receipt.height})!==canonicalLocalJson(image)))return false;if(v.phase==="RESULT_PENDING"!==!!v.answer)return false;if(v.answer&&!!image!=="imageReadback"in v.answer)return false;const pixels=v.phase==="RESULT_PENDING"&&!!image;return v.provenance.evidence===(pixels?"IMAGE_PIXELS":"METADATA_ONLY")&&(!pixels||!!receipt)});function localAgentSnapshotFromContext(raw,includeImage=false){const c=ReviewIntelligenceContextResultSchema.parse(raw);if(c.reviewTarget.kind!=="IMAGE"||c.basis.target.kind!=="IMAGE"||c.ownerContext.semanticStatus!=="SUCCESS")throw Error("LOCAL_AGENT_CONTEXT_UNAVAILABLE");const t=c.reviewTarget.target,scope=c.basis.scope;if(!t.runtimeSucceeded||t.candidate.availability!=="AVAILABLE"||t.candidate.freshness!=="CURRENT_BASIS"||!t.productionRunnable||t.freshness!=="CURRENT_BASIS"||t.generationId!==c.basis.target.generationId||t.tenantId!==scope.tenantId||t.projectId!==scope.projectId||t.productionId!==scope.productionId||c.ownerContext.basis.tenantId!==scope.tenantId||c.ownerContext.basis.projectId!==scope.projectId||c.ownerContext.basis.productionId!==scope.productionId)throw Error("LOCAL_AGENT_CONTEXT_UNAVAILABLE");return LocalAgentSnapshotSchema.parse({basis:c.basis,productionRevision:c.ownerContext.basis.productionRevision,reviewVersion:t.reviewVersion,executionClass:t.executionClass,media:{artifactId:t.candidate.artifactId,representationId:t.candidate.representationId,checksumSha256:t.candidate.checksumSha256},requirements:t.requirements,...includeImage?{image:{contentType:t.candidate.contentType,byteSize:t.candidate.byteSize,width:t.candidate.width,height:t.candidate.height}}:{}})}function localAgentNativeProposal(raw){const v=LocalAgentReviewViewSchema.parse(raw);if(v.phase!=="RESULT_PENDING"||!v.answer)throw Error("LOCAL_AGENT_RESULT_UNAVAILABLE");const keys=new Set(v.answer.observations.map(o=>o.key));if(keys.size!==v.answer.observations.length||keys.size!==v.plan.snapshot.requirements.length||v.plan.snapshot.requirements.some(r=>!keys.has(r.key)))throw Error("LOCAL_AGENT_RESULT_UNAVAILABLE");const p=v.provenance;const pixels=p.evidence==="IMAGE_PIXELS";return ValidateReviewIntelligenceSchema.parse({basis:v.plan.snapshot.basis,proposal:{origin:{kind:"EXTERNAL_AGENT_HOST",label:p.reviewerLabel},summary:`${pixels?"IMAGE_PIXELS":"METADATA_ONLY; no visual inspection"}. Codex ${p.version}; model ${p.model}; effort ${p.reasoningEffort??"DEFAULT"}; binary ${p.binaryDigest}; draft ${v.plan.id}; plan ${v.plan.fingerprint}. ${v.answer.summary}`,evidence:pixels?[{id:"original_image",label:"Verified ORIGINAL PNG attachment",producer:"EXTERNAL_AGENT_HOST",kind:"IMAGE_PIXELS",media:v.plan.snapshot.media}]:[],review:{kind:"IMAGE",observations:v.answer.observations.map(o=>({...o,status:pixels&&"status"in o?o.status:"NOT_OBSERVABLE",confidence:pixels&&"confidence"in o?o.confidence:"UNCERTAIN",evidenceIds:pixels?["original_image"]:[]}))}}})}var projectInput=LocalProjectScopeSchema;var LocalExecutionListInputSchema=LocalProjectScopeSchema.extend({after:z8.string().length(64).regex(/^[0-9a-f]{64}$/).nullable().default(null),limit:z8.int().min(1).max(16).default(8)});var LocalIpcCallSchema=z8.discriminatedUnion("operation",[z8.strictObject({operation:z8.literal("agent.grant"),grant:LocalAgentGrantSchema,approval:z8.string().regex(/^[a-f0-9]{64}$/)}),z8.strictObject({operation:z8.literal("agent.probe")}),z8.strictObject({operation:z8.literal("agent.revoke"),approval:z8.string().regex(/^[a-f0-9]{64}$/)}),z8.strictObject({operation:z8.literal("agent.prepare"),snapshot:LocalAgentSnapshotSchema}),z8.strictObject({operation:z8.literal("agent.start"),id:z8.uuid(),expectedRevision:LocalRevisionSchema,approval:z8.string().regex(/^[a-f0-9]{64}$/)}),z8.strictObject({operation:z8.literal("agent.inspect"),id:z8.uuid()}),z8.strictObject({operation:z8.literal("runtime.status")}),z8.strictObject({operation:z8.literal("runtime.doctor")}),z8.strictObject({operation:z8.literal("runtime.inventory")}),z8.strictObject({operation:z8.literal("session.issue"),projects:z8.array(projectInput).min(1).max(100),expiresAt:z8.iso.datetime({offset:true})}),z8.strictObject({operation:z8.literal("runtime.stop"),expectedRuntimeRevision:LocalRevisionSchema}),z8.strictObject({operation:z8.literal("execution.inspect"),input:LocalWorkScopeSchema}),z8.strictObject({operation:z8.literal("execution.list"),input:LocalExecutionListInputSchema}),z8.strictObject({operation:z8.literal("update.check")}),z8.strictObject({operation:z8.literal("update.prepare"),targetVersion:LocalPackageVersionSchema,expectedRuntimeRevision:LocalRevisionSchema}),z8.strictObject({operation:z8.literal("update.apply"),planId:LocalIdSchema,targetVersion:LocalPackageVersionSchema,expectedRuntimeRevision:LocalRevisionSchema})]);var LocalNextActionSchema=z8.strictObject({call:LocalIpcCallSchema,availability:z8.enum(["AVAILABLE","BLOCKED"]),reason:z8.enum(["READY","INSTALL_REQUIRED","AUTHORIZATION_REQUIRED","VERSION_INCOMPATIBLE","UPDATE_AVAILABLE","RECOVERY_REQUIRED"])});var LocalIpcRequestSchema=z8.strictObject({protocol:z8.literal("NVS_LOCAL_IPC_V1"),requestId:LocalIdSchema,call:LocalIpcCallSchema});var LocalVersionReportSchema=z8.strictObject({component:z8.enum(["CLI","SDK","MCP","RUNTIME","MEDIA_TOOLS"]),installedVersion:LocalPackageVersionSchema.nullable(),runningVersion:LocalPackageVersionSchema.nullable(),availableVersion:LocalPackageVersionSchema.nullable(),executablePath:z8.string().min(1).max(4096).nullable(),installOwner:z8.enum(["NPM_GLOBAL","PROJECT","NPX","MANAGED","TARBALL","UNKNOWN"])});var LocalRuntimeStatusSchema=z8.strictObject({protocol:z8.literal("NVS_LOCAL_IPC_V1"),runtimeRevision:LocalRevisionSchema,state:z8.enum(["IDLE","EXECUTING","DRAINING","RECOVERY_REQUIRED"]),journalSchemaVersion:z8.literal(1),workProtocols:z8.array(z8.literal("NVS_LOCAL_WORK_V1")).min(1).max(1),versions:z8.array(LocalVersionReportSchema).max(8),authorizedProjects:z8.array(projectInput).max(100),nextActions:z8.array(LocalNextActionSchema).max(8)});var LocalDoctorReportSchema=z8.strictObject({mode:z8.enum(["MANAGED","INSTALLED"]),availability:z8.enum(["AVAILABLE","UNAVAILABLE"]),reason:z8.enum(["QUALIFIED_PROCESS_TOOLS","MANAGED_TOOLS_MISSING","TOOL_QUALIFICATION_FAILED"]),nativeExecutionReady:z8.boolean(),tools:z8.array(z8.strictObject({name:z8.enum(["FFMPEG","FFPROBE"]),path:z8.string().min(1).max(4096),version:z8.string().min(1).max(200),digest:z8.string().regex(/^[0-9a-f]{64}$/)})).max(2)});var LocalExecutionInspectionSchema=z8.strictObject({binding:LocalLeaseBindingSchema,revision:LocalRevisionSchema,phase:z8.enum(["STAGED","RUNNING","RECOVERY_REQUIRED","OUTPUT_PENDING","RECEIPT_RECORDED","FENCED"]),checkpoint:z8.enum(["ADOPTED","SOURCES_READY","PROCESS_STARTED","OUTPUT_STAGED"])});var LocalExecutionPageSchema=z8.strictObject({items:z8.array(LocalExecutionInspectionSchema).max(16),nextCursor:z8.string().length(64).regex(/^[0-9a-f]{64}$/).nullable()});var LocalIpcErrorCodeSchema=z8.enum(["FORBIDDEN","INVALID_INPUT","FRAME_LIMIT","BUSY","AUTHORIZATION_REQUIRED","REVISION_CONFLICT","CAPABILITY_UNAVAILABLE","INTERNAL_OPERATIONAL_FAILURE","AGENT_APPROVAL_REQUIRED","AGENT_GRANT_REQUIRED","AGENT_OUTCOME_UNKNOWN","AGENT_IMAGE_REQUIRED","AGENT_IMAGE_INVALID","AGENT_IMAGE_BUDGET_EXCEEDED","AGENT_IMAGE_AUTHORIZATION_REQUIRED"]);var LocalIpcResponseSchema=z8.discriminatedUnion("semanticStatus",[z8.strictObject({protocol:z8.literal("NVS_LOCAL_IPC_V1"),requestId:LocalIdSchema,semanticStatus:z8.literal("SUCCESS"),data:z8.union([LocalRuntimeStatusSchema,LocalDoctorReportSchema,LocalExecutionInspectionSchema.nullable(),z8.strictObject({state:z8.literal("DRAINING"),inventory:LocalManagementInventorySchema.optional(),backupPath:z8.string().min(1).max(4096).optional()}),LocalSessionConnectorSchema,LocalManagementInventorySchema,LocalExecutionPageSchema,LocalAgentProbeSchema,LocalAgentReviewViewSchema])}),z8.strictObject({protocol:z8.literal("NVS_LOCAL_IPC_V1"),requestId:LocalIdSchema.nullable(),semanticStatus:z8.enum(["BLOCKED","INVALID_INPUT"]),error:z8.strictObject({code:LocalIpcErrorCodeSchema})})]);var LocalMcpToolNameSchema=z9.enum(["local_navigate","local_capability_describe","local_runtime_status","local_execution_list","local_execution_inspect","local_update_check"]);var LocalMcpActionSchema=z9.strictObject({tool:LocalMcpToolNameSchema,arguments:z9.record(z9.string(),z9.unknown()),availability:z9.enum(["AVAILABLE","BLOCKED"]).optional(),reason:z9.string().max(100).optional()});var LocalMcpNavigationSchema=z9.strictObject({location:z9.literal("LOCAL"),state:z9.enum(["UNAVAILABLE","IDLE","EXECUTING","DRAINING","RECOVERY_REQUIRED"]),authorizedProjects:z9.array(LocalProjectScopeSchema).max(100).optional(),groups:z9.array(z9.strictObject({id:z9.string().max(40),label:z9.string().max(100),tools:z9.array(LocalMcpToolNameSchema).max(6)})).max(4),nextActions:z9.array(z9.union([LocalMcpActionSchema,LocalClientNextActionSchema])).max(16)});var LocalMcpExecutionPageSchema=LocalExecutionPageSchema.extend({nextActions:z9.array(LocalMcpActionSchema).max(16)});var LocalMcpInspectionSchema=z9.strictObject({location:z9.literal("LOCAL"),execution:LocalExecutionInspectionSchema.nullable(),nextActions:z9.array(LocalMcpActionSchema).max(4)});var LocalMcpUpdateSchema=z9.strictObject({location:z9.literal("LOCAL"),running:z9.array(LocalVersionReportSchema).max(8),available:z9.array(LocalRuntimeDescriptorSchema).max(32),nextActions:z9.array(LocalClientNextActionSchema).max(4)});var LocalMcpDescriptionSchema=z9.strictObject({location:z9.literal("LOCAL"),tool:LocalMcpToolNameSchema,schema:z9.object({name:LocalMcpToolNameSchema,description:z9.string(),inputSchema:z9.record(z9.string(),z9.unknown())}).passthrough()});var LocalMcpFailureSchema=z9.strictObject({semanticStatus:z9.enum(["BLOCKED","INVALID_INPUT"]),error:z9.strictObject({code:z9.enum(["AUTHORIZATION_REQUIRED","FORBIDDEN","LOCAL_RUNTIME_UNAVAILABLE","RELEASE_UNAVAILABLE","VERSION_INCOMPATIBLE","INVALID_INPUT","LOCAL_CAPABILITY_UNAVAILABLE"]),outcome:z9.literal("NO_WRITE")}),nextActions:z9.array(LocalClientNextActionSchema).max(4)});var LocalMcpOutputSchemas={local_navigate:LocalMcpNavigationSchema,local_capability_describe:LocalMcpDescriptionSchema,local_runtime_status:LocalRuntimeStatusSchema.omit({nextActions:true}).extend({nextActions:z9.array(LocalMcpActionSchema).max(8)}),local_execution_list:LocalMcpExecutionPageSchema,local_execution_inspect:LocalMcpInspectionSchema,local_update_check:LocalMcpUpdateSchema};import{z as z11}from"zod";function localBudget(timeoutMs,parent){if(!Number.isInteger(timeoutMs)||timeoutMs<1||timeoutMs>6e4)throw Error("LOCAL_DEADLINE_INVALID");const controller=new AbortController,timer=setTimeout(()=>controller.abort(),timeoutMs);return{signal:parent?AbortSignal.any([parent,controller.signal]):controller.signal,close:()=>clearTimeout(timer)}}async function localAbortable(work,signal){if(signal.aborted)void work.catch(()=>{});signal.throwIfAborted();return new Promise((resolve,reject)=>{const abort=()=>reject(Error("LOCAL_DEADLINE"));signal.addEventListener("abort",abort,{once:true});work.then(v=>{signal.removeEventListener("abort",abort);resolve(v)},e=>{signal.removeEventListener("abort",abort);reject(e)});if(signal.aborted)abort()})}import{z as z10}from"zod";var output=z10.discriminatedUnion("role",[z10.strictObject({role:z10.literal("VIDEO"),receiptId:LocalIdSchema,checksumSha256:LocalDigestSchema,byteSize:z10.int().positive().max(128*1024*1024),contentType:z10.literal("video/mp4")}),z10.strictObject({role:z10.literal("POSTER"),receiptId:LocalIdSchema,checksumSha256:LocalDigestSchema,byteSize:z10.int().positive().max(2*1024*1024),contentType:z10.literal("image/png")})]);var LocalCompletionSubmissionSchema=LocalLeaseBindingSchema.extend({requestId:LocalIdSchema,outputs:z10.array(output).length(2),technical:RoughCutTechnicalSchema}).superRefine((v,ctx)=>{const video=v.outputs.find(o=>o.role==="VIDEO");if(new Set(v.outputs.map(o=>o.role)).size!==2||new Set(v.outputs.map(o=>o.receiptId)).size!==2||!video||video.checksumSha256!==v.technical.checksumSha256||video.byteSize!==v.technical.byteSize)ctx.addIssue({code:"custom",message:"Exact video/poster receipts required"})});var LocalVerifiedUploadSchema=z10.strictObject({binding:LocalLeaseBindingSchema,output,verifiedAt:LocalTimeSchema});var LocalCompletionReceiptSchema=LocalLeaseBindingSchema.extend({submissionFingerprint:LocalDigestSchema.optional(),semanticStatus:z10.literal("SUCCESS"),requestId:LocalIdSchema,renderId:LocalIdSchema,operationId:OperationIdSchema,artifactId:LocalIdSchema,videoRepresentationId:LocalIdSchema,posterRepresentationId:LocalIdSchema,checksumSha256:LocalDigestSchema,acceptedAt:LocalTimeSchema});var GetLocalCompletionReceiptSchema=LocalLeaseBindingSchema.pick({tenantId:true,projectId:true,productionId:true,runtimeJobId:true}).extend({requestId:LocalIdSchema});var NativeStudioLocalDeviceClient=class{constructor(options){this.options=options;const u=new URL(options.baseUrl);if(u.username||u.password||u.search||u.hash||u.pathname!=="/"||u.protocol!=="https:"&&!(u.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(u.hostname)))throw new NativeStudioSdkError("INVALID_INPUT","INVALID_INPUT","NO_WRITE");this.origin=u.origin}options;origin;async command(route,raw,input,output2,signal){let started=false;const budget=localBudget(15e3,signal);try{const i=input.parse(raw);if(i.tenantId!==this.options.tenantId)throw Error();budget.signal.throwIfAborted();const authorization=await localAbortable(Promise.resolve().then(()=>this.options.authorization()),budget.signal);if(authorization!==authorization.trim()||!/^Bearer [A-Za-z0-9._~-]{1,8192}$/.test(authorization))throw Error();const body=JSON.stringify(i);if(Buffer.byteLength(body)>65536)throw Error();budget.signal.throwIfAborted();started=true;const r=await fetch(this.origin+"/v1/local-execution/"+route,{method:"POST",headers:{authorization,"content-type":"application/json"},body,redirect:"error",signal:budget.signal});if(!r.ok){await r.body?.cancel();throw new NativeStudioSdkError(r.status===403||r.status===401?"FORBIDDEN":"LOCAL_COMMAND_REFUSED","BLOCKED",r.status>=500?"UNKNOWN":"REJECTED",r.status)}const parts=[];let size=0;for await(const b of r.body??[]){size+=b.length;if(size>262144)throw Error();parts.push(b)}const value=output2.parse(JSON.parse(Buffer.concat(parts).toString()));if(value&&typeof value==="object"){const result=value,request3=i;for(const key of["tenantId","projectId","deviceId"])if(key in result&&key in request3&&result[key]!==request3[key])throw Error()}return value}catch(e){if(e instanceof NativeStudioSdkError)throw e;throw new NativeStudioSdkError(started?"LOCAL_COMMAND_UNKNOWN":"INVALID_INPUT",started?"BLOCKED":"INVALID_INPUT",started?"UNKNOWN":"NO_WRITE")}finally{budget.close()}}enroll(input,signal){return this.command("devices/enroll",input,EnrollLocalDeviceSchema,LocalDeviceViewSchema,signal)}grant(input,signal){return this.command("devices/grant",input,GrantLocalDeviceSchema,LocalDeviceGrantSchema,signal)}revokeDevice(input,signal){return this.command("devices/revoke",input,RevokeLocalDeviceSchema,z11.strictObject({semanticStatus:z11.literal("SUCCESS")}),signal)}revokeGrant(input,signal){return this.command("devices/revoke-grant",input,RevokeLocalDeviceGrantSchema,z11.strictObject({semanticStatus:z11.literal("SUCCESS")}),signal)}startPreview(input,signal){return this.command("previews",input,StartLocalPreviewSchema,LocalPreviewAdmissionSchema,signal)}};import{randomUUID,createHash}from"node:crypto";import{request}from"node:http";import{z as z12}from"zod";import{constants}from"node:fs";import{open,realpath}from"node:fs/promises";async function checkedLocalDirectory(path){await privateDirectory(path);return realpath(path)}async function readLocalCredential(path,maximum=32768){await privateAccess(path,"file");const file=await open(path,constants.O_RDONLY|constants.O_NOFOLLOW);try{const stat=await file.stat();if(!stat.isFile()||stat.nlink!==1||process.platform!=="win32"&&(stat.uid!==process.getuid?.()||stat.mode&63)||stat.size>maximum)throw Error("LOCAL_CREDENTIAL_INVALID");const bytes=Buffer.alloc(Math.min(maximum+1,stat.size+1));let used=0;while(used<bytes.length){const part=await file.read(bytes,used,bytes.length-used,null);if(!part.bytesRead)break;used+=part.bytesRead}if(used>stat.size)throw Error("LOCAL_CREDENTIAL_INVALID");if(used>maximum)throw Error("LOCAL_CREDENTIAL_INVALID");return bytes.subarray(0,used)}finally{await file.close()}}async function stageAgentImage(options,view,input,signal){const budget=localBudget(options.timeoutMs??1e4,signal);let dispatched=false;try{budget.signal.throwIfAborted();if(input.byteLength>8388608)throw Error();const bytes=Buffer.from(input),snapshot=view.plan.snapshot,id=z12.uuid().parse(view.plan.id),requestId=randomUUID();if(!snapshot.image||bytes.length!==snapshot.image.byteSize||bytes.length>8388608||createHash("sha256").update(bytes).digest("hex")!==snapshot.media.checksumSha256)throw Error();const root=await checkedLocalDirectory(options.stateDirectory),path=localSocketPath(root);await privateAccess(path,"pipe");const auth=await localAbortable(Promise.resolve().then(options.authorization),budget.signal);budget.signal.throwIfAborted();if(!/^Bearer [A-Za-z0-9_-]{43}$/.test(auth))throw Error();const reply=await new Promise((resolve,reject)=>{const req=request({socketPath:path,path:"/ipc/v1/agent-images/"+id,method:"PUT",signal:budget.signal,headers:{authorization:auth,"content-type":"image/png","content-length":bytes.length,"x-nvs-request-id":requestId}},res=>{let size=0;const chunks=[];res.on("error",reject);res.on("aborted",()=>reject(Error()));res.on("data",b=>{size+=b.length;if(size>262144)req.destroy(Error());else chunks.push(b)});res.on("end",()=>{try{resolve(JSON.parse(Buffer.concat(chunks).toString()))}catch{reject(Error())}})});req.on("error",reject);dispatched=true;req.end(bytes)});const response=LocalIpcResponseSchema.parse(reply);if(response.requestId!==requestId&&!(response.requestId===null&&response.semanticStatus!=="SUCCESS"&&["BUSY","FORBIDDEN"].includes(response.error.code)))throw Error();if(response.semanticStatus!=="SUCCESS")throw new NativeStudioSdkError(response.error.code,response.semanticStatus,response.error.code==="INTERNAL_OPERATIONAL_FAILURE"?"UNKNOWN":"REJECTED");const v=LocalAgentReviewViewSchema.parse(response.data),receipt=v.imageReceipt;if(v.plan.id!==id||canonicalLocalJson(v.plan)!==canonicalLocalJson(view.plan)||v.revision<view.revision||v.phase!=="PREPARED"||!receipt||receipt.draftId!==id||canonicalLocalJson(receipt.media)!==canonicalLocalJson(snapshot.media)||canonicalLocalJson({contentType:receipt.contentType,byteSize:receipt.byteSize,width:receipt.width,height:receipt.height})!==canonicalLocalJson(snapshot.image))throw Error();return v}catch(e){if(e instanceof NativeStudioSdkError)throw e;throw new NativeStudioSdkError("LOCAL_AGENT_IMAGE_TRANSFER_FAILED","BLOCKED",dispatched?"UNKNOWN":"NO_WRITE")}finally{budget.close()}}import{randomUUID as randomUUID2}from"node:crypto";import{request as request2}from"node:http";var NativeStudioLocalRuntimeClient=class _NativeStudioLocalRuntimeClient{constructor(options){this.options=options}options;static async fromConnector(path){const initial=LocalSessionConnectorSchema.parse(JSON.parse((await readLocalCredential(path)).toString()));return new _NativeStudioLocalRuntimeClient({stateDirectory:initial.stateDirectory,projects:initial.projects,authorization:async()=>{const current=LocalSessionConnectorSchema.parse(JSON.parse((await readLocalCredential(path)).toString()));if(current.stateDirectory!==initial.stateDirectory||canonicalLocalJson(current.projects)!==canonicalLocalJson(initial.projects)||Date.parse(current.expiresAt)>Date.parse(initial.expiresAt)||Date.parse(current.expiresAt)<=Date.now())throw Error("LOCAL_AUTHORIZATION_REQUIRED");return"Bearer "+current.credential}})}async call(call,signal){let started=false;const budget=localBudget(this.options.timeoutMs??(["runtime.doctor","agent.probe","agent.grant","agent.start"].includes(call.operation)?6e4:1e4),signal);const readOnly=["runtime.status","runtime.doctor","runtime.inventory","execution.inspect","execution.list","update.check","agent.probe","agent.inspect"].includes(call.operation);try{const input=LocalIpcRequestSchema.parse({protocol:"NVS_LOCAL_IPC_V1",requestId:randomUUID2(),call});const root=await checkedLocalDirectory(this.options.stateDirectory);const path=localSocketPath(root);await privateAccess(path,"pipe");budget.signal.throwIfAborted();const auth=await localAbortable(Promise.resolve().then(()=>this.options.authorization()),budget.signal);budget.signal.throwIfAborted();if(auth.length!==50||!/^Bearer [A-Za-z0-9_-]{43}$/.test(auth))throw Error();const body=JSON.stringify(input);const reply=await new Promise((resolve,reject)=>{const abort=budget.signal;const req=request2({socketPath:path,method:"POST",path:"/ipc/v1",signal:abort,headers:{authorization:auth,"content-type":"application/json","content-length":Buffer.byteLength(body)}},res=>{const chunks=[];let length=0;res.on("error",reject);res.on("aborted",()=>reject(Error()));res.on("data",b=>{length+=b.length;if(length>256*1024)req.destroy(Error());else chunks.push(b)});res.on("end",()=>{try{resolve(JSON.parse(Buffer.concat(chunks).toString()))}catch{reject(Error())}})});req.on("error",reject);started=true;req.end(body)});const value=LocalIpcResponseSchema.parse(reply);if(value.requestId!==input.requestId&&!(value.requestId===null&&value.semanticStatus!=="SUCCESS"&&["FORBIDDEN","BUSY","INVALID_INPUT"].includes(value.error.code)))throw Error();if(value.semanticStatus!=="SUCCESS")throw new NativeStudioSdkError(value.error.code,value.semanticStatus,readOnly?"NO_WRITE":value.error.code==="INTERNAL_OPERATIONAL_FAILURE"?"UNKNOWN":"REJECTED");if(value.requestId!==input.requestId)throw Error();return value.data}catch(error){if(error instanceof NativeStudioSdkError)throw error;throw new NativeStudioSdkError("LOCAL_RUNTIME_UNAVAILABLE","BLOCKED",started&&!readOnly?"UNKNOWN":"NO_WRITE")}finally{budget.close()}}response(schema,raw){const result=schema.safeParse(raw);if(!result.success)throw new NativeStudioSdkError("LOCAL_RESPONSE_INVALID","BLOCKED","NO_WRITE");return result.data}async status(signal){const value=this.response(LocalRuntimeStatusSchema,await this.call({operation:"runtime.status"},signal));if(this.options.projects&&value.authorizedProjects.some(p=>!this.options.projects.some(q=>q.tenantId===p.tenantId&&q.projectId===p.projectId)))throw new NativeStudioSdkError("LOCAL_SCOPE_INVALID","BLOCKED","NO_WRITE");return value}async doctor(signal){return this.response(LocalDoctorReportSchema,await this.call({operation:"runtime.doctor"},signal))}async inventory(signal){return this.response(LocalManagementInventorySchema,await this.call({operation:"runtime.inventory"},signal))}async grantAgent(raw,approval){return this.response(LocalAgentProbeSchema,await this.call({operation:"agent.grant",grant:LocalAgentGrantSchema.parse(raw),approval}))}async revokeAgent(approval){return this.response(LocalAgentProbeSchema,await this.call({operation:"agent.revoke",approval}))}async probeAgent(){return this.response(LocalAgentProbeSchema,await this.call({operation:"agent.probe"}))}async prepareAgentReview(snapshot){const input=LocalAgentSnapshotSchema.parse(snapshot);const v=this.response(LocalAgentReviewViewSchema,await this.call({operation:"agent.prepare",snapshot:input}));if(canonicalLocalJson(v.plan.snapshot)!==canonicalLocalJson(input))throw new NativeStudioSdkError("LOCAL_RESPONSE_INVALID","BLOCKED","UNKNOWN");return v}async startAgentReview(id,expectedRevision,approval){const v=this.response(LocalAgentReviewViewSchema,await this.call({operation:"agent.start",id,expectedRevision,approval}));if(v.plan.id!==id||v.plan.fingerprint!==approval)throw new NativeStudioSdkError("LOCAL_RESPONSE_INVALID","BLOCKED","UNKNOWN");return v}async stageAgentImage(id,bytes,signal){const budget=localBudget(this.options.timeoutMs??1e4,signal);try{return await stageAgentImage(this.options,await this.inspectAgentReview(id,budget.signal),bytes,budget.signal)}finally{budget.close()}}async inspectAgentReview(id,signal){const v=this.response(LocalAgentReviewViewSchema,await this.call({operation:"agent.inspect",id},signal));if(v.plan.id!==id)throw new NativeStudioSdkError("LOCAL_RESPONSE_INVALID","BLOCKED","NO_WRITE");return v}async executions(input,signal){const i=LocalExecutionListInputSchema.parse(input);if(this.options.projects&&!this.options.projects.some(p=>p.tenantId===i.tenantId&&p.projectId===i.projectId))throw new NativeStudioSdkError("FORBIDDEN","BLOCKED","NO_WRITE");const page=this.response(LocalExecutionPageSchema,await this.call({operation:"execution.list",input:i},signal));if(page.items.some(e=>e.binding.tenantId!==i.tenantId||e.binding.projectId!==i.projectId))throw new NativeStudioSdkError("LOCAL_SCOPE_INVALID","BLOCKED","NO_WRITE");return page}async inspect(raw,signal){const input=LocalWorkScopeSchema.parse(raw);if(this.options.projects&&!this.options.projects.some(p=>p.tenantId===input.tenantId&&p.projectId===input.projectId))throw new NativeStudioSdkError("FORBIDDEN","BLOCKED","NO_WRITE");const value=this.response(LocalExecutionInspectionSchema.nullable(),await this.call({operation:"execution.inspect",input},signal));if(value&&["tenantId","projectId","productionId","runtimeJobId"].some(k=>value.binding[k]!==input[k]))throw new NativeStudioSdkError("LOCAL_SCOPE_INVALID","BLOCKED","NO_WRITE");return value}};import{createPublicKey,verify}from"node:crypto";function endpoint(raw){const u=new URL(raw);if(u.username||u.password||u.search||u.hash||u.protocol!=="https:"&&!(u.protocol==="http:"&&["127.0.0.1","localhost","[::1]"].includes(u.hostname)))fail("RELEASE_ORIGIN_INVALID");return u}async function fetchBytes(raw,maximum,origin,signal=AbortSignal.timeout(3e4)){const u=endpoint(raw);if(u.origin!==origin)fail("RELEASE_ORIGIN_INVALID");const r=await fetch(u,{redirect:"error",signal,headers:{accept:"application/octet-stream"}});if(!r.ok||Number(r.headers.get("content-length"))>maximum){await r.body?.cancel();fail("RELEASE_UNAVAILABLE")}const parts=[];let size=0;for await(const part of r.body??[]){size+=part.byteLength;if(size>maximum){await r.body?.cancel().catch(()=>{});fail("RELEASE_LIMIT")}parts.push(part)}return Buffer.concat(parts)}async function catalogue(trust,signal){const origin=endpoint(trust.catalogueUrl).origin;const bytes=await fetchBytes(trust.catalogueUrl,65536,origin,signal??AbortSignal.timeout(3e4));const signed=LocalSignedCatalogueSchema.parse(JSON.parse(bytes.toString()));const key=createPublicKey((await read(trust.publicKeyFile,16384)).toString());if(key.asymmetricKeyType!=="ed25519"||!verify(null,Buffer.from(canonicalLocalJson(signed.catalogue)),key,Buffer.from(signed.signature,"base64url")))fail("RELEASE_SIGNATURE_INVALID");const now=Date.now();if(Date.parse(signed.catalogue.issuedAt)>now||Date.parse(signed.catalogue.expiresAt)<=now)fail("RELEASE_EXPIRED");for(const release of signed.catalogue.releases){for(const a of[release.package,...release.tools?Object.values(release.tools):[]])if(endpoint(a.url).origin!==origin)fail("RELEASE_ORIGIN_INVALID")}return{signed,fingerprint:sha256(canonicalLocalJson(signed.catalogue)),origin,trustFingerprint:sha256(canonicalLocalJson({catalogueUrl:endpoint(trust.catalogueUrl).href,publicKey:key.export({type:"spki",format:"der"}).toString("base64")}))}}function select(signed,version){const r=signed.catalogue.releases.find(r2=>r2.descriptor.version===version&&r2.descriptor.platform.os===process.platform&&r2.descriptor.platform.architecture===process.arch);if(!r)fail("VERSION_INCOMPATIBLE");const[major,minor]=process.versions.node.split(".").map(Number);if(major!==r.descriptor.node.major||minor<r.descriptor.node.minMinor)fail("NODE_VERSION_INCOMPATIBLE");return r}async function asset(a,origin){const bytes=await fetchBytes(a.url,a.byteSize,origin,AbortSignal.timeout(12e4));if(bytes.length!==a.byteSize||sha512(bytes)!==a.sha512)fail("RELEASE_INTEGRITY_INVALID");return bytes}export{LocalWorkScopeSchema,EnrollLocalDeviceSchema,GrantLocalDeviceSchema,RevokeLocalDeviceGrantSchema,RevokeLocalDeviceSchema,LocalToolSelectionSchema,LocalRuntimeDescriptorSchema,LocalManagementInventorySchema,LocalToolChoiceSchema,LocalUpdatePlanSchema,canonicalLocalJson,LocalAgentGrantSchema,localAgentSnapshotFromContext,localAgentNativeProposal,LocalExecutionListInputSchema,LocalDoctorReportSchema,StartLocalPreviewSchema,LocalDeviceTransportConfigurationSchema,LocalMcpFailureSchema,LocalMcpOutputSchemas,NativeStudioLocalDeviceClient,NativeStudioLocalRuntimeClient,endpoint,catalogue,select,asset};
|