@nativestudio/cli 0.3.0-rc.15 → 0.3.0-rc.17
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/COMPATIBILITY.json +8 -8
- package/components/runtime.json +4 -4
- package/components/runtime.tgz +0 -0
- package/dist/_chunks/chunk-3KBIDTXT.js +1 -0
- package/dist/_chunks/{chunk-ZADAXKKY.js → chunk-4IFMG2ZS.js} +1 -1
- package/dist/_chunks/chunk-4NJIT52T.js +1 -0
- package/dist/_chunks/{chunk-NPDLPC5B.js → chunk-53EULX5D.js} +1 -1
- package/dist/_chunks/{chunk-I5KYSPUJ.js → chunk-65X56WAQ.js} +1 -1
- package/dist/_chunks/{chunk-BX2SNMA4.js → chunk-744IEPTK.js} +1 -1
- package/dist/_chunks/{chunk-CFZNDURD.js → chunk-BR26X3ZF.js} +1 -1
- package/dist/_chunks/chunk-C7CSZFV6.js +1 -0
- package/dist/_chunks/chunk-CW67UB2I.js +1 -0
- package/dist/_chunks/{chunk-O47YYPL7.js → chunk-GKDGSAI5.js} +1 -1
- package/dist/_chunks/{chunk-6UYY5KHI.js → chunk-HAOCQVMU.js} +1 -1
- package/dist/_chunks/{chunk-BBTZJB2G.js → chunk-HI5SIUX7.js} +1 -1
- package/dist/_chunks/{chunk-OVIR77ET.js → chunk-IHTF6VEC.js} +1 -1
- package/dist/_chunks/chunk-K25YVVTT.js +1 -0
- package/dist/_chunks/{chunk-ZOODOQBH.js → chunk-KYNC2BSW.js} +1 -1
- package/dist/_chunks/{chunk-TTB7CYC5.js → chunk-ORFGJBJA.js} +1 -1
- package/dist/_chunks/chunk-SDTAJ7FI.js +1 -0
- package/dist/_chunks/{chunk-AAGFHT2D.js → chunk-TWC3NXFA.js} +1 -1
- package/dist/_chunks/{chunk-PB2HLRXG.js → chunk-UGOXJEDU.js} +1 -1
- package/dist/_chunks/{chunk-SAPEOZ2V.js → chunk-UMCOLDHH.js} +1 -1
- package/dist/_chunks/{connect-RIODOO3C.js → connect-OY623MMA.js} +1 -1
- package/dist/_chunks/{device-management-VECG3RA4.js → device-management-CXSZFF53.js} +1 -1
- package/dist/_chunks/device-preflight-6HKPPZ5L.js +1 -0
- package/dist/_chunks/{devices-inventory-E6TE4H7T.js → devices-inventory-K553HAF3.js} +1 -1
- package/dist/_chunks/{devices-main-7JHMJNGV.js → devices-main-LBDRDV2M.js} +1 -1
- package/dist/_chunks/host-main-ZMBFHY55.js +1 -0
- package/dist/_chunks/http-profile-D65WSTZU.js +1 -0
- package/dist/_chunks/{library-main-AWUEMZFQ.js → library-main-RNDPNKYK.js} +1 -1
- package/dist/_chunks/{local-main-BNFNAPRG.js → local-main-RC4RM3OB.js} +1 -1
- package/dist/_chunks/{local-mcp-HU6MII3G.js → local-mcp-LQCQ3WLF.js} +1 -1
- package/dist/_chunks/{main-BSMCHALI.js → main-CPIMF4PS.js} +2 -2
- package/dist/_chunks/mcp-HQQJCKHS.js +1 -0
- package/dist/_chunks/{observe-entry-D7F6OQ7Y.js → observe-entry-4GPGZ3NJ.js} +1 -1
- package/dist/_chunks/remote-client-6XHMNMXK.js +1 -0
- package/dist/_chunks/{render-main-O3IN6EFV.js → render-main-ATCEBECW.js} +1 -1
- package/dist/_chunks/{source-import-Y2Z3BVWY.js → source-import-HIL7NW3L.js} +1 -1
- package/dist/_chunks/src-MRFJOTKK.js +1 -0
- package/dist/_chunks/stdio-main-T4ORVLSX.js +1 -0
- package/dist/_chunks/workspace-main-44ECTGHC.js +1 -0
- package/dist/_types/cli/local/desktop-contract.d.ts +13 -13
- package/dist/_types/cli/local/desktop-device-contract.d.ts +3 -3
- package/dist/_types/cli/local/desktop-device-owner.d.ts +1 -1
- package/dist/_types/cli/local/desktop-device-state.d.ts +2 -2
- package/dist/_types/cli/local/desktop-library.d.ts +1 -1
- package/dist/_types/cli/local/desktop-owner.d.ts +3 -3
- package/dist/_types/cli/local/manager.d.ts +2 -2
- package/dist/_types/cli/local/mcp-tools.d.ts +2 -2
- package/dist/_types/cli/local-management.d.ts +1 -1
- package/dist/_types/contracts/agent-execution-lifecycle.d.ts +55 -43
- package/dist/_types/contracts/agent-execution-oauth.d.ts +2 -2
- package/dist/_types/contracts/agent-execution-registration.d.ts +59 -15
- package/dist/_types/contracts/agent-execution-selection.d.ts +7 -7
- package/dist/_types/contracts/agent-host-contract.d.ts +189 -0
- package/dist/_types/contracts/agent-host-execution.d.ts +92 -61
- package/dist/_types/contracts/agent-host-generic-transport.d.ts +4 -4
- package/dist/_types/contracts/agent-host-legacy-release.d.ts +31 -0
- package/dist/_types/contracts/agent-host-protocol.d.ts +71 -0
- package/dist/_types/contracts/agent-host-wire.d.ts +263 -0
- package/dist/_types/contracts/agent-host.d.ts +126 -65
- package/dist/_types/contracts/artifact-discovery.d.ts +16 -16
- package/dist/_types/contracts/composition-observation.d.ts +1 -1
- package/dist/_types/contracts/delivery-operations.d.ts +1 -1
- package/dist/_types/contracts/delivery-summary.d.ts +1 -1
- package/dist/_types/contracts/device-onboarding.d.ts +35 -0
- package/dist/_types/contracts/device-render.d.ts +32 -0
- package/dist/_types/contracts/exploration-recommendation.d.ts +2 -2
- package/dist/_types/contracts/federation-event-link-receiver.d.ts +200 -0
- package/dist/_types/contracts/federation-event-link.d.ts +485 -0
- package/dist/_types/contracts/federation-result.d.ts +239 -0
- package/dist/_types/contracts/final-ready.d.ts +2 -2
- package/dist/_types/contracts/final-render.d.ts +2 -2
- package/dist/_types/contracts/index.d.ts +7 -0
- package/dist/_types/contracts/interface/execution-output.d.ts +9 -6
- package/dist/_types/contracts/interface/production-snapshot.d.ts +5 -5
- package/dist/_types/contracts/keyframe-generation.d.ts +2 -2
- package/dist/_types/contracts/keyframe-review.d.ts +1 -1
- package/dist/_types/contracts/lifecycle-event-projections.d.ts +2 -2
- package/dist/_types/contracts/lifecycle-events.d.ts +2 -2
- package/dist/_types/contracts/local-execution/device-inventory.d.ts +34 -2
- package/dist/_types/contracts/local-execution/index.d.ts +1 -0
- package/dist/_types/contracts/local-execution/ipc.d.ts +6 -6
- package/dist/_types/contracts/local-execution/library.d.ts +2 -2
- package/dist/_types/contracts/local-execution/processor.d.ts +7 -7
- package/dist/_types/contracts/local-execution/workspace.d.ts +1 -1
- package/dist/_types/contracts/mcp-capabilities.d.ts +15 -0
- package/dist/_types/contracts/media-observation.d.ts +3 -3
- package/dist/_types/contracts/native-tool-authority.d.ts +25 -21
- package/dist/_types/contracts/native-tool-execution.d.ts +60 -39
- package/dist/_types/contracts/navigation-context.d.ts +25 -6
- package/dist/_types/contracts/navigation-groups.d.ts +1 -1
- package/dist/_types/contracts/navigation.d.ts +17 -5
- package/dist/_types/contracts/repair-strategy.d.ts +1 -1
- package/dist/_types/contracts/review-intelligence-final-output.d.ts +1 -1
- package/dist/_types/contracts/rough-cut.d.ts +1 -1
- package/dist/_types/contracts/shares.d.ts +19 -19
- package/dist/_types/contracts/speech.d.ts +5 -5
- package/dist/_types/contracts/temporal-evidence-operation.d.ts +1 -1
- package/dist/_types/contracts/video-generation.d.ts +2 -2
- package/dist/_types/contracts/video-review.d.ts +1 -1
- package/dist/_types/contracts/visual-exploration.d.ts +2 -2
- package/dist/_types/contracts/voice-profile/contracts.d.ts +4 -4
- package/dist/_types/sdk/local-runtime/workspace.d.ts +4 -4
- package/dist/_types/sdk/local-runtime-client.d.ts +3 -3
- package/dist/entry.js +1 -1
- package/dist/local-management.js +1 -1
- package/dist/local-navigation.js +1 -1
- package/package.json +1 -1
- package/dist/_chunks/chunk-5UJEP7FY.js +0 -1
- package/dist/_chunks/chunk-H6EZKOYR.js +0 -1
- package/dist/_chunks/chunk-NQVUVPW5.js +0 -1
- package/dist/_chunks/chunk-PDQYFIQQ.js +0 -1
- package/dist/_chunks/chunk-VOGKKZQH.js +0 -1
- package/dist/_chunks/chunk-YV447AB5.js +0 -1
- package/dist/_chunks/device-preflight-73KVSHZG.js +0 -1
- package/dist/_chunks/host-main-KDORT44Q.js +0 -1
- package/dist/_chunks/http-profile-QINBH2FP.js +0 -1
- package/dist/_chunks/mcp-3VZZFXNG.js +0 -1
- package/dist/_chunks/remote-client-XIJ6RQLU.js +0 -1
- package/dist/_chunks/src-3S6CAUSJ.js +0 -1
- package/dist/_chunks/stdio-main-T4WMBNKB.js +0 -1
- package/dist/_chunks/workspace-main-KWFTVTZG.js +0 -1
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{AcceptBriefRequestSchema,AcceptBriefResultSchema,AcceptSceneShotPlanRequestSchema,AcceptSceneShotPlanResultSchema,AcceptStoryRequestSchema,AcceptStoryResultSchema,AcceptedVisualSourceReferenceSchema,AgentHostBindingSchema,AgentHostCurrentSchema,AgentHostHistoryPageSchema,AgentHostHistoryQuerySchema,AgentHostReadinessSchema,AgentHostScopeSchema,AgentHostSelectionSchema,AudioBasisSchema,AudioGetSchema,AudioImportRequestSchema,AudioPageSchema,AudioQuerySchema,AudioReadScopeSchema,AudioReceiptSchema,AudioSnapshotSchema,AudioViewSchema,AuthorCaptionsSchema,AuthorTranscriptCaptionsSchema,BoundaryRequirementSchema,BriefContentSchema,BuildTimelineSchema,BuildTimelineShapeSchema,CaptionBasisSchema,CaptionContentSchema,CaptionExportSchema,CaptionGetSchema,CaptionPageSchema,CaptionQuerySchema,CaptionReceiptSchema,CaptionScopeSchema,CaptionSnapshotSchema,CaptionTranscriptDraftSchema,CaptionTranscriptPlanSchema,CaptionViewSchema,ClipTransitionSchema,CompositionBasisPinSchema,CompositionBindingSchema,CompositionContentSchema,CompositionDependencyLockSchema,CompositionDependencyManifestSchema,CompositionFindingLocalitySchema,CompositionGetSchema,CompositionHistorySchema,CompositionInputFactSchema,CompositionPageSchema,CompositionPathSchema,CompositionReceiptSchema,CompositionRenderCancellationSchema,CompositionRenderGetSchema,CompositionRenderReceiptSchema,CompositionRenderStartSchema,CompositionRenderViewSchema,CompositionScopeSchema,CompositionViewSchema,ConfigureAgentHostSchema,ConfigureConsistencyProfileSchema,ConfigureNativeToolGrantSchema,ConfigureProviderInputSchema,ConfigureProviderModelSchema,ConsistencyProfileReceiptSchema,ConsistencyProfileScopeSchema,ConsistencyProfileVersionQuerySchema,ConsistencyProfileVersionSchema,ConsistencyProfileViewSchema,ConstraintSetSchema,ContentFingerprintSchema,DecideFinalReadySchema,DecideKeyframeSchema,DecideProgrammaticShotSchema,DecideVideoShotSchema,DeliveryApprovalSchema,DeliveryCheckKeySchema,DeliveryManifestLinkSchema,DeliveryPolicyInputSchema,DeliveryPolicySchema,DeliveryTargetSchema,DeliveryValidationReviewSchema,DeviceRenderReceiptSchema,DeviceRenderTargetSchema,DirectOriginalCommandSchema,DirectOriginalStageSchema,DirectOriginalSubmitSchema,DirectProjectSourceCommandSchema,DirectProjectSourceStageSchema,DirectProjectSourceSubmitSchema,DirectorBasisSchema,DirectorContextResultSchema,DirectorScopeSchema,DirectorValidationResultSchema,DisableProviderModelSchema,EnrollLocalDeviceSchema,ExactEvidenceReferenceSchema,FinalDeliveryReceiptSchema,FinalReadyPageSchema,FinalReadyQuerySchema,FinalReadyReceiptSchema,FinalReadyViewSchema,FinalRenderAdmissionSchema,FinalRenderEligibilitySchema,FinalRenderGetSchema,FinalRenderManifestReaderSchema,FinalRenderPageSchema,FinalRenderQuerySchema,FinalRenderSnapshotSchema,FinalRenderStartSchema,FinalRenderTechnicalSchema,FinalRenderViewSchema,GeneratedShotAcceptanceDecisionSchema,GenerationContractIdSchema,GenerationCostQuoteSchema,ImportedVideoReviewReceiptSchema,ImportedVisualAdmissionSchema,ImportedVisualCancellationSchema,ImportedVisualDecisionSchema,ImportedVisualFromProjectSourceSchema,ImportedVisualGetSchema,ImportedVisualNormalizationViewSchema,ImportedVisualNormalizeStartSchema,ImportedVisualOriginalGetSchema,ImportedVisualOriginalHistoryQuerySchema,ImportedVisualOriginalHistorySchema,ImportedVisualOriginalPageSchema,ImportedVisualOriginalQuerySchema,ImportedVisualOriginalViewSchema,ImportedVisualReviewSchema,ImportedVisualReviewTargetSchema,KeyframeAdmissionSchema,KeyframeDecisionPageSchema,KeyframeDecisionQuerySchema,KeyframeDecisionReceiptSchema,KeyframeDeviceStartInputSchema,KeyframeGenerationViewSchema,KeyframeGetInputSchema,KeyframeMediaSchema,KeyframeObservationSchema,KeyframeProviderProfileSchema,KeyframeQueryInputSchema,KeyframeQueryPageSchema,KeyframeReferenceScopeSchema,KeyframeReferenceViewSchema,KeyframeReviewPageSchema,KeyframeReviewQuerySchema,KeyframeReviewReceiptSchema,KeyframeReviewScopeSchema,KeyframeReviewSummarySchema,KeyframeReviewTargetSchema,KeyframeStartInputSchema,KeyframeSummarySchema,LegacyImportedVisualProjectSourceSchema,LegacyImportedVisualRevisionSchema,LegacyImportedVisualUploadSchema,LegacyVisualSequenceRegistrationSchema,ListeningEvidenceSchema,LocalDeviceViewSchema,LocalDigestSchema,LocalLibraryAdmissionSchema,LocalLibraryCommandQuerySchema,LocalLibraryCommandSchema,LocalLibraryCommandStatusSchema,LocalLibraryProjectionPageSchema,LocalLibraryProjectionQuerySchema,LocalManagementReceiptSchema,LocalObservationAdmissionSchema,LocalObservationStartSchema,LocalObservationViewSchema,LocalSpeechAdmissionSchema,LocalSpeechGenerationViewSchema,LocalSpeechStartSchema,MediaBrowserContentTypeSchema,MediaBrowserReadTicketSchema,MediaCategorySchema,MediaObjectTicketSchema,MediaObjectVersionSchema,ModelProfileIdSchema,NativeRuntimeProofRequestSchema,NativeRuntimePublicKeySchema,NativeSpeechExecutionSchema,NativeToolGrantGetSchema,NativeToolGrantViewSchema,ObservationAdmissionSchema,ObservationGetSchema,ObservationOptionsSchema,ObservationScopeSchema,ObservationStartSchema,ObservationViewSchema,PreparationBasisSchema,PreparationBlockerSchema,PreparationIdSchema,PreparationTargetSchema,ProductionGuidanceContextSchema,ProgrammaticShotAcceptanceDecisionSchema,ProgrammaticVideoReviewPageSchema,ProgrammaticVideoReviewQuerySchema,ProgrammaticVideoReviewReceiptSchema,ProgrammaticVideoReviewScopeSchema,ProgrammaticVideoReviewTargetSchema,ProjectDeviceListInputSchema,ProjectDeviceListSchema,ProviderConnectionCommandSchema,ProviderConnectionPageSchema,ProviderConnectionViewSchema,ProviderCredentialRevokeSchema,ProviderDefaultViewSchema,ProviderModelGetSchema,ProviderModelPageSchema,ProviderModelViewSchema,ProviderModelsViewSchema,ProviderSelectionSchema,ProviderTenantInputSchema,QwenAsrCostQuoteSchema,QwenAsrDeviceAdmissionSchema,QwenAsrDeviceQuoteInputSchema,QwenAsrDeviceStartSchema,QwenAsrDeviceViewSchema,ReadyArtifactRegistrationSchema,RecordKeyframeReviewSchema,RecordProgrammaticVideoReviewSchema,RecordRoughCutReviewSchema,RecordVideoReviewSchema,ReferenceBindingInputSchema,ReferenceRoleSchema,ReferenceSetSchema,RegisterVisualSequenceSchema,ReviewEvidenceKeySchema,ReviewIntelligenceContextInputSchema,ReviewIntelligenceContextResultSchema,ReviewIntelligenceValidationResultSchema,RevokeAgentHostSchema,RevokeFinalReadySchema,RevokeKeyframeSchema,RevokeLocalDeviceSchema,RevokeNativeToolGrantSchema,RevokeShotAcceptanceSchema,RoughCutAdmissionSchema,RoughCutFindingPageSchema,RoughCutFindingQuerySchema,RoughCutFindingViewSchema,RoughCutGetSchema,RoughCutPageSchema,RoughCutProfileIdSchema,RoughCutQuerySchema,RoughCutReviewPageSchema,RoughCutReviewQuerySchema,RoughCutReviewReceiptSchema,RoughCutReviewRecordSchema,RoughCutReviewScopeSchema,RoughCutReviewSnapshotSchema,RoughCutReviewTargetSchema,RoughCutSnapshotSchema,RoughCutStartSchema,RoughCutViewSchema,SceneShotPlanVersionSchema,ScopedLocalManagementReceiptSchema,SetKeyframeDefaultSchema,ShotAcceptanceScopeSchema,ShotAcceptanceViewSchema,ShotDecisionPageSchema,ShotDecisionQuerySchema,ShotDecisionReceiptSchema,ShotIntentSchema,ShotPlanEntrySchema,SoundPlanAcceptSchema,SoundPlanContextSchema,SoundPlanGetSchema,SoundPlanReceiptSchema,SoundPlanScopeSchema,SoundPlanValidateSchema,SoundPlanValidationSchema,SoundPlanViewSchema,SourceInputMetadataSchema,SourceSyncAudioGetSchema,SourceSyncAudioViewSchema,SourceSyncReviewGetSchema,SourceSyncReviewInputSchema,SourceSyncReviewRecordSchema,SourceSyncReviewTargetSchema,SourceSyncRuntimeAdmissionSchema,SourceSyncRuntimeScopeSchema,SourceSyncRuntimeStartSchema,SourceSyncRuntimeViewSchema,SpeechAdmissionSchema,SpeechCostQuoteSchema,SpeechDeviceStartSchema,SpeechGenerationViewSchema,SpeechGetSchema,SpeechOptionsSchema,SpeechParametersSchema,SpeechScopeSchema,SpeechStartSchema,StoryContentSchema,StoryVersionSchema,SubmitCompositionSchema,TemporalEvidenceManifestSchema,TemporalEvidenceSourceSchema,TemporalSamplingProfileSchema,TenantMediaCapabilitySchema,TenantMediaDownloadSchema,TenantRenderMediaInputSchema,TenantRenderMediaTicketSchema,TimelineAudioInputSchema,TimelineBasisSchema,TimelineBuildReceiptSchema,TimelineGetSchema,TimelineGraphicInputSchema,TimelineManifestReaderSchema,TimelinePageSchema,TimelineQuerySchema,TimelineScopeSchema,TimelineSnapshotSchema,TimelineViewSchema,TimelineVisualLayerInputSchema,UpdateAgentHostSelectionSchema,UploadSourceInputRequestSchema,ValidateDirectorProposalSchema,ValidateReviewIntelligenceSchema,ValidateWriterProposalSchema,VideoAdmissionSchema,VideoDeviceStartInputSchema,VideoGenerationViewSchema,VideoGetInputSchema,VideoObservationSchema,VideoOptionsInputSchema,VideoProviderProfileSchema,VideoQueryInputSchema,VideoQueryPageSchema,VideoReviewPageSchema,VideoReviewQuerySchema,VideoReviewReceiptSchema,VideoReviewRequirementSchema,VideoReviewScopeSchema,VideoReviewTargetSchema,VideoStartInputSchema,VideoSummarySchema,VisualRequirementSchema,VisualSequenceGetSchema,VisualSequencePageSchema,VisualSequenceQuerySchema,VisualSequenceRegistrationAdmissionSchema,VisualSequenceViewSchema,VoiceLocaleSchema,VoiceProfileRefSchema,VoiceProfileUseSchema,WorkspaceDeviceListInputSchema,WorkspaceDeviceListSchema,WriterBriefResultSchema,WriterScopeSchema,WriterValidationResultSchema,assertManagementReceipt,mediaObjectTransferPath}from"./chunk-PDQYFIQQ.js";import{CreateProjectRequestSchema,CreatedProjectResultSchema,HumanTenantSchema,ProductionSchema,ProductionStateSchema,ProjectLibraryPageSchema,ProjectLibraryQuerySchema,ProjectLibraryScopeSchema,ProjectSchema,ProjectWorkspaceSchema,SourceLibraryItemSchema,SourceLibraryMediaSchema,SourceLibraryPageSchema,SourceLibraryQuerySchema,StudioInputContentSchema}from"./chunk-YV447AB5.js";import{ArtifactIdSchema,ArtifactRepresentationIdSchema,ContinuationSchema,DeliveryOutputProfileSchema,HumanLinksSchema,InterfaceSemanticStatusSchema,NextActionSchema,OperationIdSchema,PrincipalIdSchema,ProductionIdSchema,ProjectIdSchema,QueryLimitSchema,QueryPageInfoSchema,SceneShotPlanVersionIdSchema,ShotIdSchema,TenantIdSchema,WorkSummarySchema}from"./chunk-6UYY5KHI.js";import{NativeStudioSdkError,sdkInputError}from"./chunk-HTUTYIRU.js";import{createHash}from"node:crypto";function abortable(promise,signal){if(signal.aborted){void promise.catch(()=>{});return Promise.reject(signal.reason)}return new Promise((resolve,reject)=>{const abort=()=>reject(signal.reason);signal.addEventListener("abort",abort,{once:true});promise.then(resolve,reject).finally(()=>signal.removeEventListener("abort",abort))})}async function boundedResponseBytes(response,limit,signal){const length=response.headers.get("content-length");if(length!==null&&(!/^\d+$/.test(length)||Number(length)>limit)){void response.body?.cancel().catch(()=>{});throw new NativeStudioSdkError("RESPONSE_TOO_LARGE","INTERNAL_OPERATIONAL_FAILURE","UNKNOWN")}if(!response.body)return new Uint8Array;const reader=response.body.getReader();const chunks=[];let size=0;try{while(true){const next=await abortable(reader.read(),signal);if(next.done)break;size+=next.value.byteLength;if(size>limit)throw new NativeStudioSdkError("RESPONSE_TOO_LARGE","INTERNAL_OPERATIONAL_FAILURE","UNKNOWN");chunks.push(next.value)}const result=new Uint8Array(size);let offset=0;for(const chunk of chunks){result.set(chunk,offset);offset+=chunk.byteLength}return result}finally{void reader.cancel().catch(()=>{});reader.releaseLock()}}var failed=()=>new NativeStudioSdkError("MEDIA_IDENTITY_MISMATCH","INTERNAL_OPERATIONAL_FAILURE","NO_WRITE");async function downloadImmutableObject(ticket,options={}){const object=MediaObjectVersionSchema.parse(ticket.object),url=new URL(ticket.endpoint);if(ticket.method!=="GET"||url.pathname!==mediaObjectTransferPath||url.username||url.password||url.search||url.hash||url.protocol!=="https:"&&!(url.protocol==="http:"&&url.hostname==="127.0.0.1"))throw failed();const timeout=AbortSignal.timeout(12e4);const signal=options.signal?AbortSignal.any([options.signal,timeout]):timeout;try{const response=await fetch(url,{headers:{authorization:"Bearer "+ticket.credential},credentials:"omit",redirect:"error",signal});if(response.status!==200||response.headers.get("x-media-object-version")!==object.versionId||response.headers.get("x-content-sha256")!==object.checksumSha256||response.headers.get("content-length")!==String(object.byteSize)){await response.body?.cancel();throw failed()}const bytes=await boundedResponseBytes(response,object.byteSize,signal);if(bytes.byteLength!==object.byteSize||createHash("sha256").update(bytes).digest("hex")!==object.checksumSha256)throw failed();return{bytes,object}}catch{throw failed()}}async function downloadRenderObject(ticket,options){if(ticket.object.role==="SOURCE")throw failed();const result=await downloadImmutableObject(ticket,options);return{...result,contentType:result.object.role==="VIDEO"?"video/mp4":"image/png"}}import{z as z63}from"zod";import{z}from"zod";var OperationTargetSchema=z.object({type:z.string().min(1).max(120),id:z.string().min(1).max(2048),version:z.int().positive().nullable()});var OperationSummarySchema=z.object({humanLinks:HumanLinksSchema.optional(),id:OperationIdSchema,productionId:ProductionIdSchema,semanticStatus:InterfaceSemanticStatusSchema,targets:z.array(OperationTargetSchema).max(100),work:WorkSummarySchema,blockers:z.array(z.string().min(1).max(1e3)).max(100),nextActions:z.array(NextActionSchema).max(50),startedAt:z.iso.datetime({offset:true}),updatedAt:z.iso.datetime({offset:true})});import{z as z4}from"zod";import{z as z3}from"zod";import{z as z2}from"zod";var sha=z2.string().regex(/^[0-9a-f]{64}$/);var DeliveryManifestBasisSchema=z2.strictObject({schemaVersion:z2.literal(1),evaluatorVersion:z2.literal("DELIVERY_V1"),target:DeliveryTargetSchema,policyVersionId:z2.uuid(),policyVersion:z2.int().positive(),policy:DeliveryPolicySchema,policyFingerprint:sha,finalRenderRuntimeJobId:z2.uuid(),finalRenderManifest:FinalRenderManifestReaderSchema,finalRenderTechnical:FinalRenderTechnicalSchema,roughCutReview:RoughCutReviewRecordSchema,artifacts:z2.array(z2.strictObject({artifactId:z2.uuid(),family:z2.string().min(1).max(100),origin:z2.string().min(1).max(100),checksumSha256:sha})).min(1).max(2e3),relations:z2.array(z2.strictObject({id:z2.uuid(),sourceArtifactId:z2.uuid(),targetArtifactId:z2.uuid(),relationType:z2.string().min(1).max(100)})).max(4e3)}).superRefine((basis,ctx)=>{const t=basis.target,m=basis.finalRenderManifest;if(t.selectionId!==m.selection.id||t.selectionVersion!==m.selectionVersion||t.timelineVersionId!==m.timeline.id||t.timelineFingerprint!==m.timeline.fingerprint||t.tenantId!==m.timeline.tenantId||t.projectId!==m.timeline.projectId||t.productionId!==m.timeline.productionId||t.executionClass!==m.timeline.executionClass||t.checksumSha256!==basis.finalRenderTechnical.checksumSha256||t.byteSize!==basis.finalRenderTechnical.byteSize||basis.finalRenderTechnical.hasAudio!==m.profile.hasAudio||basis.roughCutReview.id!==m.selection.reviewId||basis.roughCutReview.basisFingerprint!==m.selection.basisFingerprint||!basis.artifacts.some(a=>a.artifactId===t.artifactId&&a.checksumSha256===t.checksumSha256)||new Set(basis.artifacts.map(a=>a.artifactId)).size!==basis.artifacts.length||new Set(basis.relations.map(r=>r.id)).size!==basis.relations.length||basis.relations.some(r=>!basis.artifacts.some(a=>a.artifactId===r.sourceArtifactId)||!basis.artifacts.some(a=>a.artifactId===r.targetArtifactId)))ctx.addIssue({code:"custom",message:"Manifest must identify exact render, Review-2 and provenance"})});var ProductionDeliveryManifestSchema=DeliveryManifestBasisSchema.safeExtend({reviewId:z2.uuid(),productionRevision:z2.int().positive(),completedAt:z2.iso.datetime({offset:true})});var DeliveryManifestGetSchema=TimelineScopeSchema.extend({manifestId:z2.uuid()});var RegisteredDeliveryManifestSchema=z2.strictObject({link:DeliveryManifestLinkSchema,body:ProductionDeliveryManifestSchema}).refine(v=>v.link.reviewId===v.body.reviewId&&v.link.policyFingerprint===v.body.policyFingerprint&&Object.keys(DeliveryTargetSchema.shape).every(key10=>v.link.target[key10]===v.body.target[key10]),"Manifest registration must match exact body");var sha2=z3.string().regex(/^[0-9a-f]{64}$/);var mutation=TimelineScopeSchema.extend({expectedProductionRevision:z3.int().positive(),idempotencyKey:z3.string().trim().min(1).max(200)});var ConfigureDeliveryPolicySchema=mutation.extend({expectedPolicyVersion:z3.int().nonnegative(),policy:DeliveryPolicyInputSchema});var DeliveryPolicyVersionSchema=TimelineScopeSchema.extend({id:z3.uuid(),projectId:z3.uuid(),version:z3.int().positive(),policy:DeliveryPolicySchema,policyFingerprint:sha2,createdByPrincipalId:z3.uuid(),createdAt:z3.iso.datetime({offset:true})});var DeliveryPolicyReceiptSchema=z3.strictObject({policy:DeliveryPolicyVersionSchema,productionRevision:z3.int().positive()});var LegacyStartDeliveryValidationSchema=mutation.extend({target:DeliveryTargetSchema,expectedPolicyVersion:z3.int().nonnegative()}).refine(v=>v.target.tenantId===v.tenantId&&v.target.productionId===v.productionId,"Exact delivery target must match command scope");var StartDeliveryValidationSchema=LegacyStartDeliveryValidationSchema.safeExtend({deviceId:z3.uuid().toLowerCase().optional()});var DeliveryValidationGetSchema=TimelineScopeSchema.extend({validationId:z3.uuid()});var DecideDeliveryApprovalSchema=mutation.extend({validationId:z3.uuid(),reviewId:z3.uuid(),target:DeliveryTargetSchema,policyFingerprint:sha2,action:z3.enum(["APPROVE","REJECT"])}).refine(v=>v.target.tenantId===v.tenantId&&v.target.productionId===v.productionId,"Exact approval target must match command scope");var DeliveryAdmissionSchema=z3.strictObject({humanLinks:HumanLinksSchema.optional(),semanticStatus:z3.literal("ACCEPTED"),validationId:z3.uuid(),runtimeJobId:z3.uuid(),operationId:z3.string().min(1),target:DeliveryTargetSchema,policyVersionId:z3.uuid(),policyVersion:z3.int().positive(),policyFingerprint:sha2,manifestBasisFingerprint:sha2,evaluatorVersion:z3.literal("DELIVERY_V1"),productionRevision:z3.int().positive()});var DeliveryFindingSchema=z3.strictObject({id:z3.uuid(),reviewId:z3.uuid(),target:DeliveryTargetSchema,key:DeliveryCheckKeySchema,detail:z3.string().trim().min(1).max(1e3),blocking:z3.literal(true),createdAt:z3.iso.datetime({offset:true})});var DeliveryCompletionBlockerSchema=z3.enum(["VALIDATION_FAILED","EXACT_OUTPUT_CHANGED","DELIVERY_POLICY_CHANGED","FINAL_READY_STALE","ARTIFACT_UNAVAILABLE","PROVENANCE_INCOMPLETE","MANIFEST_NOT_REGISTERED","MANIFEST_BINDING_MISMATCH","BLOCKING_FINDINGS","TEST_EVIDENCE_DISABLED","APPROVAL_BINDING_MISMATCH","APPROVAL_REJECTED"]);var DeliveryReviewReceiptSchema=z3.strictObject({review:DeliveryValidationReviewSchema,action:z3.enum(["COMPLETE","WAITING_HUMAN","BLOCK"]),blockers:z3.array(DeliveryCompletionBlockerSchema).max(12),productionRevision:z3.int().positive()});var DeliveryDecisionReceiptSchema=z3.strictObject({humanLinks:HumanLinksSchema.optional(),approval:DeliveryApprovalSchema,finalDelivery:FinalDeliveryReceiptSchema.nullable(),productionRevision:z3.int().positive(),condition:z3.enum(["RUNNABLE","BLOCKED"])});var DeliveryValidationViewSchema=z3.strictObject({humanLinks:HumanLinksSchema.optional(),admission:DeliveryAdmissionSchema,policy:DeliveryPolicyVersionSchema,manifestBasis:DeliveryManifestBasisSchema,runtimeStatus:z3.enum(["PENDING","READY","RUNNING","WAITING","SUCCEEDED","FAILED","CANCELLED","SUPERSEDED"]),current:z3.boolean(),reviewReceipt:DeliveryReviewReceiptSchema.nullable(),findings:z3.array(DeliveryFindingSchema).max(16),approval:DeliveryApprovalSchema.nullable(),finalDelivery:FinalDeliveryReceiptSchema.nullable()});var DeliverySnapshotSchema=TimelineScopeSchema.extend({humanLinks:HumanLinksSchema.optional(),productionRevision:z3.int().positive(),policy:DeliveryPolicyVersionSchema.nullable(),currentValidationId:z3.uuid().nullable(),finalDelivery:FinalDeliveryReceiptSchema.nullable()});var DeliverySummarySchema=z4.strictObject({policy:DeliveryPolicyVersionSchema.nullable(),validation:z4.strictObject({id:z4.uuid(),runtimeStatus:DeliveryValidationViewSchema.shape.runtimeStatus,current:z4.boolean(),reviewId:z4.uuid().nullable(),result:z4.enum(["PASS","FAIL"]).nullable(),action:z4.enum(["COMPLETE","WAITING_HUMAN","BLOCK"]).nullable(),blockingChecks:z4.array(DeliveryCheckKeySchema).max(16),approvalAction:z4.enum(["APPROVE","REJECT"]).nullable()}).nullable(),finalDelivery:FinalDeliveryReceiptSchema.nullable()});import{z as z8}from"zod";import{z as z7}from"zod";import{z as z6}from"zod";import{z as z5}from"zod";var ShotSoundContentSchema=z5.strictObject({model:z5.strictObject({modelProfileId:z5.string().regex(/^[a-z][a-z0-9-]{1,79}$/),modelProfileVersion:z5.int().positive(),connectionId:z5.uuid()}).optional(),nativeAudio:z5.boolean(),cues:z5.array(z5.strictObject({id:z5.string().regex(/^[a-z][a-z0-9_-]{0,63}$/),role:z5.enum(["DIALOGUE","MUSIC","AMBIENCE","SOUND_EFFECT","NARRATION"]),startMs:z5.int().nonnegative().max(3e4),endMs:z5.int().positive().max(3e4),text:z5.string().trim().min(1).max(6e3).optional(),exactSpeech:z5.boolean(),lipSync:z5.enum(["REQUIRED","NONE"])}).refine(v=>v.endMs>v.startMs)).max(64)});var ShotSoundInstructionSchema=z5.strictObject({soundPlanVersionId:z5.uuid().toLowerCase(),fingerprint:z5.string().regex(/^[0-9a-f]{64}$/),content:ShotSoundContentSchema});var GenerationContractSchema=z6.strictObject({id:GenerationContractIdSchema,schemaVersion:z6.literal(1),preparationId:PreparationIdSchema,target:PreparationTargetSchema,basis:PreparationBasisSchema,mode:z6.enum(["REFERENCE_TO_IMAGE","REFERENCE_TO_VIDEO","FIRST_FRAME_TO_VIDEO","FIRST_LAST_FRAME_TO_VIDEO"]),creativeInstruction:z6.strictObject({sound:ShotSoundInstructionSchema.optional(),shot:ShotIntentSchema,scenePurpose:z6.string().min(1).max(800),locationContext:z6.string().max(300).optional(),timeContext:z6.string().max(300).optional(),productPresentationGoal:z6.string().min(1).max(1e3),styleTone:z6.string().max(300).optional(),entryBoundary:z6.array(BoundaryRequirementSchema).max(48),exitBoundary:z6.array(BoundaryRequirementSchema).max(48)}),acceptedShotReferences:z6.array(AcceptedVisualSourceReferenceSchema).max(24).default([]),constraintSetFingerprint:ContentFingerprintSchema,referenceSetFingerprint:ContentFingerprintSchema,output:z6.strictObject({aspectRatio:z6.enum(["16:9","9:16"]),targetDurationSeconds:z6.number().min(.5).max(30).nullable(),workingResolution:z6.null(),frameRate:z6.null(),finalDeliveryProfile:DeliveryOutputProfileSchema}),requiredCapabilities:z6.strictObject({referenceConditioning:z6.literal(true),referenceRoles:z6.array(ReferenceRoleSchema).min(1).max(8),startFrameControl:z6.boolean(),endFrameControl:z6.boolean(),nativeAudio:z6.boolean().optional()}),fingerprint:ContentFingerprintSchema}).superRefine((value,context)=>{const invalid=message=>context.addIssue({code:"custom",message});if(value.target.mediaType==="IMAGE"&&value.acceptedShotReferences.length)invalid("Image generation cannot depend on accepted video Shots");if(value.target.mediaType==="IMAGE"&&(value.mode!=="REFERENCE_TO_IMAGE"||value.output.targetDurationSeconds!==null||value.requiredCapabilities.startFrameControl||value.requiredCapabilities.endFrameControl))invalid("Image generation cannot claim video duration or frame-control semantics");if(value.target.mediaType==="VIDEO"&&(value.mode==="REFERENCE_TO_IMAGE"||value.output.targetDurationSeconds===null))invalid("Video generation requires video mode and duration");const roles=value.requiredCapabilities.referenceRoles;if(!roles.some(role=>role==="PRODUCT_IDENTITY"||role==="PRODUCT_PACKSHOT"))invalid("Product identity requires concrete reference conditioning");if(value.requiredCapabilities.startFrameControl&&!roles.includes("START_FRAME_ANCHOR"))invalid("Start-frame control requires an exact anchor role");if(value.requiredCapabilities.endFrameControl&&!roles.includes("END_FRAME_ANCHOR"))invalid("End-frame control requires an exact anchor role");if(value.mode==="FIRST_LAST_FRAME_TO_VIDEO"&&(!value.requiredCapabilities.startFrameControl||!value.requiredCapabilities.endFrameControl))invalid("First/last mode requires both anchor capabilities")});var PrepareShotRequestSchema=z7.strictObject({tenantId:TenantIdSchema,expectedProductionRevision:z7.int().positive(),expectedPlanVersionId:SceneShotPlanVersionIdSchema,expectedPlanVersion:z7.int().positive(),expectedShotPlanningRevision:z7.int().positive(),expectedPreparationVersion:z7.int().nonnegative(),idempotencyKey:z7.string().trim().min(1).max(200),target:PreparationTargetSchema,referenceBindings:z7.array(ReferenceBindingInputSchema).max(12).default([])});var PreparationVersionSchema=z7.strictObject({id:PreparationIdSchema,version:z7.int().positive(),basis:PreparationBasisSchema,target:PreparationTargetSchema,constraints:ConstraintSetSchema,referenceSet:ReferenceSetSchema,canonicalSources:z7.array(ExactEvidenceReferenceSchema).max(64),acceptedShotReferences:z7.array(AcceptedVisualSourceReferenceSchema).max(24).default([]),blockers:z7.array(PreparationBlockerSchema).max(2048),contract:GenerationContractSchema.nullable(),createdByPrincipalId:PrincipalIdSchema,createdAt:z7.iso.datetime({offset:true})}).superRefine((value,context)=>{const invalid=message=>context.addIssue({code:"custom",message});if(value.constraints.preparationId!==value.id||value.referenceSet.preparationId!==value.id||value.constraints.version!==value.version||value.referenceSet.version!==value.version)invalid("Resolved snapshot identity must match preparation");if(value.contract!==null!==(value.blockers.length===0))invalid("A preparation contract exists only for an unblocked preflight");if(value.contract&&(value.contract.preparationId!==value.id||JSON.stringify(value.contract.basis)!==JSON.stringify(value.basis)||JSON.stringify(value.contract.target)!==JSON.stringify(value.target)||value.contract.constraintSetFingerprint!==value.constraints.fingerprint||value.contract.referenceSetFingerprint!==value.referenceSet.fingerprint||JSON.stringify(value.contract.acceptedShotReferences)!==JSON.stringify(value.acceptedShotReferences)))invalid("Generation Contract must freeze the exact preparation basis and snapshots")});var PrepareShotResultSchema=z7.strictObject({semanticStatus:z7.literal("SUCCESS"),preparation:PreparationVersionSchema,productionRevision:z7.int().positive()});var PreparationViewSchema=z7.strictObject({preparation:PreparationVersionSchema,freshness:z7.enum(["CURRENT_BASIS","STALE_BASIS"]),superseded:z7.boolean(),freshnessReasons:z7.array(z7.enum(["PLAN_CHANGED","SHOT_CHANGED","REFERENCE_UNAVAILABLE","CONSISTENCY_PROFILE_CHANGED","SOUND_PLAN_CHANGED","SUPERSEDED","KEYFRAME_SELECTION_CHANGED","PREDECESSOR_ACCEPTANCE_CHANGED"])).max(8),execution:z7.strictObject({eligibleVideoSelections:z7.array(ProviderSelectionSchema).max(1600).optional(),available:z7.boolean(),reasons:z7.array(z7.enum(["STALE_BASIS","PREPARATION_BLOCKED","PRODUCTION_NOT_RUNNABLE","PROVIDER_CAPABILITY_UNAVAILABLE","VIDEO_SELECTION_REQUIRED"])).min(0).max(4)})});var PreparationQueryInputSchema=z7.strictObject({tenantId:TenantIdSchema,productionId:ProductionIdSchema,shotId:ShotIdSchema.optional(),mediaType:z7.enum(["IMAGE","VIDEO"]).optional(),limit:QueryLimitSchema,next:ContinuationSchema.optional()});var PreparationQueryPageSchema=z7.strictObject({items:z7.array(PreparationViewSchema),page:QueryPageInfoSchema});var PreparationGetInputSchema=z7.strictObject({tenantId:TenantIdSchema,productionId:ProductionIdSchema,preparationId:PreparationIdSchema});var PreparationActiveInputSchema=z7.strictObject({tenantId:TenantIdSchema,productionId:ProductionIdSchema,shotId:ShotIdSchema,mediaType:z7.enum(["IMAGE","VIDEO"])});var PreparationSummarySchema=z7.strictObject({latest:z7.int().nonnegative(),current:z7.int().nonnegative(),stale:z7.int().nonnegative(),contractValid:z7.int().nonnegative(),preflightBlocked:z7.int().nonnegative(),executionAvailable:z7.int().nonnegative()});var NullableVersionSchema=z8.int().positive().nullable();var ProductionBlockerSchema=z8.object({code:z8.string().min(1).max(120),summary:z8.string().min(1).max(1e3),targetType:z8.string().min(1).max(80),targetId:z8.string().min(1).max(2048)});var ProductionSnapshotSchema=z8.object({humanLinks:HumanLinksSchema.optional(),tenantId:TenantIdSchema,projectId:ProjectIdSchema,productionId:ProductionIdSchema,state:ProductionStateSchema,planning:z8.object({activeBriefVersion:NullableVersionSchema,activeStoryVersion:NullableVersionSchema,activeSceneShotPlanVersion:NullableVersionSchema}),preparation:PreparationSummarySchema.optional(),keyframes:KeyframeSummarySchema.optional(),keyframeReview:KeyframeReviewSummarySchema.optional(),videos:VideoSummarySchema.optional(),captions:CaptionSnapshotSchema.optional(),audio:AudioSnapshotSchema.optional(),shots:z8.object({planned:z8.int().nonnegative(),ready:z8.int().nonnegative(),generating:z8.int().nonnegative(),candidates:z8.int().nonnegative(),accepted:z8.int().nonnegative(),blocked:z8.int().nonnegative(),stale:z8.int().nonnegative()}),findings:z8.object({open:z8.int().nonnegative(),blocking:z8.int().nonnegative(),warnings:z8.int().nonnegative()}),timeline:z8.object({currentVersion:NullableVersionSchema,stale:z8.boolean(),...TimelineSnapshotSchema.omit({currentVersion:true,stale:true}).partial().shape}),roughCut:RoughCutSnapshotSchema.partial().required({latestVersion:true,reviewState:true}),review2:RoughCutReviewSnapshotSchema.optional(),final:z8.object({ready:FinalReadyViewSchema.optional(),render:FinalRenderSnapshotSchema.optional(),renderState:z8.string().min(1).max(120).nullable(),delivery:DeliverySummarySchema.optional(),deliveryValidationState:z8.string().min(1).max(120).nullable()}),work:WorkSummarySchema,activeOperations:z8.array(OperationSummarySchema).max(20),blockers:z8.array(ProductionBlockerSchema).max(100),latestDecisions:z8.array(z8.string().min(1).max(1e3)).max(50),nextActions:z8.array(NextActionSchema).max(50),generatedAt:z8.iso.datetime({offset:true})});import{z as z9}from"zod";var ProductionQueryInputSchema=z9.object({tenantId:TenantIdSchema,projectId:ProjectIdSchema.optional(),search:z9.string().trim().min(1).max(200).optional(),attention:z9.enum(["NEEDS_YOU","WORKING","FINISHED"]).optional(),limit:QueryLimitSchema,next:ContinuationSchema.optional()});var ProductionQueryPageSchema=z9.object({items:z9.array(ProductionSchema),page:QueryPageInfoSchema});var OperationQueryInputSchema=z9.object({tenantId:TenantIdSchema,productionId:ProductionIdSchema,limit:QueryLimitSchema,next:ContinuationSchema.optional()});var OperationQueryPageSchema=z9.object({items:z9.array(OperationSummarySchema),page:QueryPageInfoSchema});var StoryQueryInputSchema=z9.object({tenantId:TenantIdSchema,productionId:ProductionIdSchema,limit:QueryLimitSchema,next:ContinuationSchema.optional()});var StoryQueryPageSchema=z9.object({items:z9.array(StoryVersionSchema),page:QueryPageInfoSchema});var SceneShotPlanQueryInputSchema=z9.object({tenantId:TenantIdSchema,productionId:ProductionIdSchema,limit:QueryLimitSchema,next:ContinuationSchema.optional()});var SceneShotPlanQueryPageSchema=z9.object({items:z9.array(SceneShotPlanVersionSchema),page:QueryPageInfoSchema});import{z as z10}from"zod";var InterfaceCancellationDataSchema=z10.strictObject({cancellationAccepted:z10.boolean()});var InterfaceCancellationReceiptSchema=InterfaceCancellationDataSchema.extend({semanticStatus:z10.literal("SUCCESS")});import{z as z16}from"zod";import{z as z15}from"zod";import{z as z11}from"zod";var AgentExecutionContractDigest="834d35515b14007b7900b09bb8e2988169fe6400c77109dba0f793a628c32c90";var key=z11.string().regex(/^[A-Za-z0-9_-]{1,160}$/);var AgentHostGenericInstallationTransportSchema=z11.strictObject({protocol:z11.literal("AGENT_STACK_GENERIC_INSTALLATION_V3"),installationId:key,installationRevisionId:key,slotKey:z11.string().regex(/^[a-z0-9_-]{1,64}$/),contractDigest:z11.literal(AgentExecutionContractDigest),capabilityDigest:z11.string().regex(/^[a-f0-9]{64}$/)});import{z as z12}from"zod";var id=z12.uuid();var sha3=z12.string().regex(/^[0-9a-f]{64}$/);var AgentHostExecutionScopeSchema=z12.strictObject({tenantId:id,projectId:id,productionId:id});var StartAgentHostExecutionSchema=AgentHostExecutionScopeSchema.extend({requestId:id,studioInputArtifactId:id,bindingId:id,expectedProductionRevision:z12.int().positive(),expectedBindingRevision:z12.int().positive(),expectedConfigurationVersion:z12.int().positive()});var AgentHostExecutionGetSchema=AgentHostExecutionScopeSchema.extend({executionId:id});var AgentHostExecutionQuerySchema=AgentHostExecutionScopeSchema.extend({limit:z12.int().min(1).max(100).default(20),beforeId:id.optional()});var AgentHostExecutionSourceSchema=z12.strictObject({artifactId:id,representationId:id,checksumSha256:sha3,byteSize:z12.int().positive().max(8388608),contentType:z12.string().min(1).max(100),kind:z12.enum(["PRODUCT_INFORMATION","REFERENCE_IMAGE","REFERENCE_VIDEO"])});var AgentHostExecutionInputSchema=AgentHostExecutionScopeSchema.extend({protocol:z12.literal("NATIVESTUDIO_PRODUCTION_V1"),executionId:id,hostRequestId:id,productionRevision:z12.int().positive(),studioInput:StudioInputContentSchema,intake:AgentHostExecutionSourceSchema,sources:z12.array(AgentHostExecutionSourceSchema).max(12)}).refine(v=>v.studioInput.productionId===v.productionId&&v.studioInput.sourceArtifactIds.length===v.sources.length&&new Set(v.sources.map(s=>s.artifactId)).size===v.sources.length&&v.sources.every((s,index)=>s.artifactId===v.studioInput.sourceArtifactIds[index])&&!v.sources.some(s=>s.artifactId===v.intake.artifactId));var NativeInstallationTransportSchema=z12.strictObject({protocol:z12.literal("AGENT_STACK_NATIVE_INSTALLATION_V2"),installationId:z12.string().regex(/^[A-Za-z0-9_-]{1,160}$/),installationRevisionId:z12.string().regex(/^[A-Za-z0-9_-]{1,160}$/),slotKey:z12.string().regex(/^[a-z0-9_-]{1,64}$/)});var AgentHostInstallationTransportSchema=z12.discriminatedUnion("protocol",[NativeInstallationTransportSchema,AgentHostGenericInstallationTransportSchema]);var AgentHostNativeToolAuthoritySchema=AgentHostExecutionScopeSchema.extend({protocol:z12.literal("NATIVESTUDIO_AGENT_TOOLS_V1"),authorityRef:id,executionId:id,hostRequestId:id,bindingId:id,configurationVersion:z12.int().positive(),inputFingerprint:sha3,capabilityDigest:sha3,expiresAt:z12.iso.datetime({offset:true}),executionClass:z12.enum(["LIVE","TEST_ONLY"]),transport:AgentHostInstallationTransportSchema.optional()});var AgentHostExecutionSnapshotSchema=z12.strictObject({binding:AgentHostBindingSchema,input:AgentHostExecutionInputSchema,authority:AgentHostNativeToolAuthoritySchema}).refine(v=>v.binding.tenantId===v.input.tenantId&&v.binding.projectId===v.input.projectId&&v.binding.enabled&&v.authority.tenantId===v.input.tenantId&&v.authority.projectId===v.input.projectId&&v.authority.productionId===v.input.productionId&&v.authority.executionId===v.input.executionId&&v.authority.hostRequestId===v.input.hostRequestId&&v.authority.bindingId===v.binding.bindingId&&v.authority.configurationVersion===v.binding.configurationVersion);var AgentHostTaskObservationSchema=z12.strictObject({requestId:id,runKey:z12.string().regex(/^[A-Za-z0-9_-]{1,160}$/),status:z12.enum(["accepted","running","succeeded","failed","cancelled","unknown"]),agentKey:z12.string().min(1).max(64),agentVersion:z12.int().positive(),modelOptionKey:z12.string().min(1).max(64),cancelRequested:z12.boolean(),createdAt:z12.iso.datetime({offset:true}),updatedAt:z12.iso.datetime({offset:true}),timing:z12.strictObject({acceptedAt:z12.iso.datetime({offset:true}),deadlineAt:z12.iso.datetime({offset:true}),limitSource:z12.literal("TASK_POLICY")}).nullable()});var AgentHostDispatchPhaseSchema=z12.enum(["ADMITTED","SENDING","OUTCOME_UNKNOWN","OBSERVING","REJECTED","CANCELLED_BEFORE_SUBMISSION"]);var AgentHostExecutionViewSchema=AgentHostExecutionScopeSchema.extend({executionId:id,requestId:id,requestedByPrincipalId:id,hostRequestId:id,revision:z12.int().positive(),snapshotFingerprint:sha3,snapshot:AgentHostExecutionSnapshotSchema,dispatchPhase:AgentHostDispatchPhaseSchema,active:z12.boolean(),observation:AgentHostTaskObservationSchema.nullable(),cancelRequestId:id.nullable(),errorCode:z12.string().regex(/^[A-Z_]{1,80}$/).nullable(),createdAt:z12.iso.datetime({offset:true}),updatedAt:z12.iso.datetime({offset:true})}).refine(v=>v.snapshot.input.executionId===v.executionId&&v.snapshot.input.hostRequestId===v.hostRequestId&&v.snapshot.input.tenantId===v.tenantId&&v.snapshot.input.projectId===v.projectId&&v.snapshot.input.productionId===v.productionId&&(!v.observation||v.observation.requestId===v.hostRequestId&&v.observation.agentKey===v.snapshot.binding.selection.agentKey&&v.observation.agentVersion===v.snapshot.binding.selection.agentVersion&&v.observation.modelOptionKey===v.snapshot.binding.selection.modelOptionKey));var AgentHostExecutionPageSchema=z12.strictObject({items:z12.array(AgentHostExecutionViewSchema).max(100),hasMore:z12.boolean(),nextBeforeId:id.nullable()}).refine(v=>v.hasMore===(v.nextBeforeId!==null)&&(!v.hasMore||v.nextBeforeId===v.items.at(-1)?.executionId)&&new Set(v.items.map(item=>item.executionId)).size===v.items.length);var AgentHostExecutionEventSchema=z12.strictObject({id,executionId:id,revision:z12.int().positive(),action:z12.enum(["ADMIT","CLAIM","RECOVER_UNKNOWN","OBSERVE","REJECT","CANCEL_REQUEST","CANCEL_UNSENT"]),createdByPrincipalId:id,observation:AgentHostTaskObservationSchema.nullable(),errorCode:z12.string().regex(/^[A-Z_]{1,80}$/).nullable(),createdAt:z12.iso.datetime({offset:true})});var AgentHostExecutionEventQuerySchema=AgentHostExecutionGetSchema.extend({limit:z12.int().min(1).max(100).default(20),beforeRevision:z12.int().positive().optional()});var AgentHostExecutionEventPageSchema=z12.strictObject({items:z12.array(AgentHostExecutionEventSchema).max(100),hasMore:z12.boolean(),nextBeforeRevision:z12.int().positive().nullable()}).refine(v=>v.hasMore===(v.nextBeforeRevision!==null)&&(!v.hasMore||v.nextBeforeRevision===v.items.at(-1)?.revision)&&v.items.every((item,index)=>!index||item.revision<v.items[index-1].revision));var AgentHostExecutionFailureSchema=z12.strictObject({semanticStatus:z12.enum(["INVALID_INPUT","NOT_FOUND","BLOCKED","REVISION_CONFLICT","CAPABILITY_UNAVAILABLE","INTERNAL_OPERATIONAL_FAILURE"]),error:z12.strictObject({code:z12.enum(["INVALID_INPUT","UNAUTHENTICATED","FORBIDDEN","NOT_FOUND","REVISION_CONFLICT","REQUEST_CONFLICT","SOURCE_UNAVAILABLE","TOOL_AUTHORITY_UNAVAILABLE","ACTIVE_EXECUTION_EXISTS","LEASE_LOST","BINDING_UNAVAILABLE","INTERNAL_OPERATIONAL_FAILURE"]),message:z12.literal("Agent Host execution did not complete")})});import{z as z13}from"zod";var id2=z13.uuid().regex(/^[0-9a-f-]{36}$/);var key2=z13.string().regex(/^[A-Za-z0-9_-]{1,160}$/);var digest=z13.string().regex(/^[a-f0-9]{64}$/);var https=z13.url().max(2048).refine(v=>{const u=new URL(v);return u.protocol==="https:"&&!u.username&&!u.password&&!u.search&&!u.hash});var AgentExecutionLimitsSchema=z13.strictObject({grantMaxSeconds:z13.int().positive().max(30*86400),executionMaxSeconds:z13.int().min(10).max(21600),leaseMaxSeconds:z13.int().positive(),renewWindowSeconds:z13.int().positive(),renewBeforeSeconds:z13.int().positive(),assertionSeconds:z13.literal(60),clockSkewSeconds:z13.literal(5)}).refine(v=>v.renewBeforeSeconds<=v.renewWindowSeconds&&v.renewWindowSeconds<v.leaseMaxSeconds&&v.leaseMaxSeconds<=v.executionMaxSeconds);var AgentExecutionCapabilitiesSchema=z13.strictObject({protocol:z13.literal("delegated-mcp-execution"),protocolVersion:z13.literal(1),contractDigest:z13.literal(AgentExecutionContractDigest),issuer:https.refine(v=>new URL(v).origin===v),resource:https,endpoints:z13.strictObject({capabilities:https,authorize:https,token:https,identity:https,bind:https,bindingQuery:https,access:https,accessQuery:https,leaseRenew:https,leaseQuery:https,close:https}),supportedProfiles:z13.tuple([z13.literal("stateless-json-v1")]),limits:AgentExecutionLimitsSchema}).refine(v=>new URL(v.resource).origin===v.issuer&&Object.values(v.endpoints).every(e=>new URL(e).origin===v.issuer));var AgentExecutionDescriptorSchema=z13.strictObject({schemaVersion:z13.literal(1),runtimeKey:key2,installationId:key2,displayName:z13.string().min(1).max(160),redirectUri:https,publicJwk:NativeRuntimePublicKeySchema});var AgentExecutionProfileSchema=z13.strictObject({schemaVersion:z13.literal(1),profileKey:key2,revision:z13.int().positive(),capabilities:AgentExecutionCapabilitiesSchema,capabilityDigest:digest,nativeToolCapabilityDigest:digest,redirectOrigins:z13.array(https.refine(v=>new URL(v).origin===v)).min(1).max(16),scopes:z13.array(z13.string().regex(/^[A-Za-z0-9:_-]{1,128}$/)).min(1).max(32),bootstrap:z13.strictObject({slotKey:z13.string().regex(/^[a-z0-9][a-z0-9_-]{0,63}$/),entryTool:z13.string().regex(/^[A-Za-z0-9_.-]{1,128}$/),argumentsMode:z13.literal("task-input")})});var AgentExecutionRegistrationSchema=AgentExecutionDescriptorSchema.extend({clientId:key2,registrationRevision:z13.int().positive(),issuer:https,resource:https,keyId:z13.string().regex(/^[A-Za-z0-9_-]{43}$/),protocol:z13.literal("delegated-mcp-execution"),protocolVersion:z13.literal(1),contractDigest:z13.literal(AgentExecutionContractDigest),capabilityDigest:digest});var ApproveAgentExecutionRegistrationSchema=AgentHostScopeSchema.extend({requestId:id2,bindingId:id2,expectedBindingRevision:z13.int().positive(),expectedConfigurationVersion:z13.int().positive(),profileKey:key2,expectedProfileRevision:z13.int().positive(),descriptor:AgentExecutionDescriptorSchema});var AgentExecutionRegistrationGetSchema=AgentHostScopeSchema.extend({clientId:id2});var RevokeAgentExecutionRegistrationSchema=AgentExecutionRegistrationGetSchema.extend({requestId:id2,expectedRevision:z13.int().positive()});var AgentExecutionRegistrationViewSchema=AgentExecutionRegistrationGetSchema.extend({schemaVersion:z13.literal(1),revision:z13.int().positive(),enabled:z13.boolean(),bindingId:id2,bindingRevision:z13.int().positive(),configurationVersion:z13.int().positive(),profile:AgentExecutionProfileSchema,registration:AgentExecutionRegistrationSchema,approvedByPrincipalId:id2,createdAt:z13.iso.datetime(),revokedAt:z13.iso.datetime().nullable()}).refine(v=>v.clientId===v.registration.clientId&&v.enabled===(v.revokedAt===null)&&v.registration.capabilityDigest===v.profile.capabilityDigest&&v.registration.resource===v.profile.capabilities.resource&&v.registration.issuer===v.profile.capabilities.issuer);import{z as z14}from"zod";var id3=z14.uuid();var opaque=z14.string().min(1).max(4096);var digest2=z14.string().regex(/^[a-f0-9]{64}$/);var AgentExecutionConsentSchema=z14.strictObject({response_type:z14.literal("code"),client_id:id3,redirect_uri:z14.url().max(2048),resource:z14.url().max(2048),scope:z14.string().min(1).max(4096),state:z14.string().min(1).max(512),code_challenge:z14.string().regex(/^[A-Za-z0-9_-]{43}$/),code_challenge_method:z14.literal("S256")});var ApproveAgentExecutionConsentSchema=AgentHostScopeSchema.extend({profileKey:z14.string().regex(/^[A-Za-z0-9_-]{1,160}$/),requestId:id3,consent:AgentExecutionConsentSchema,expiresInSeconds:z14.int().min(60).max(30*86400)});var AgentExecutionGrantSchema=z14.strictObject({protocolVersion:z14.literal(1),clientId:id3,registrationRevision:z14.int().positive(),resource:z14.url().max(2048),grantRef:id3,grantRevision:z14.int().positive(),expiresAt:z14.iso.datetime(),scopes:z14.array(z14.string().min(1).max(128)).min(1).max(32)});var AgentExecutionTokenFormSchema=z14.discriminatedUnion("grant_type",[z14.strictObject({grant_type:z14.literal("authorization_code"),client_id:id3,resource:z14.url().max(2048),registration_revision:z14.string().regex(/^[1-9][0-9]{0,14}$/),code:opaque,code_verifier:z14.string().regex(/^[A-Za-z0-9._~-]{43,128}$/),redirect_uri:z14.url().max(2048),client_assertion_type:z14.literal("urn:ietf:params:oauth:client-assertion-type:jwt-bearer"),client_assertion:opaque}),z14.strictObject({grant_type:z14.literal("refresh_token"),client_id:id3,resource:z14.url().max(2048),registration_revision:z14.string().regex(/^[1-9][0-9]{0,14}$/),refresh_token:opaque,client_assertion_type:z14.literal("urn:ietf:params:oauth:client-assertion-type:jwt-bearer"),client_assertion:opaque})]);var AgentExecutionAssertionSchema=z14.strictObject({iss:id3,sub:id3,aud:z14.url().max(2048),iat:z14.int().nonnegative(),exp:z14.int().positive(),jti:id3,requestDigest:digest2}).refine(v=>v.exp===v.iat+60);var id4=z15.uuid();var key3=z15.string().regex(/^[A-Za-z0-9_-]{1,160}$/);var digest3=z15.string().regex(/^[a-f0-9]{64}$/);var time=z15.iso.datetime();var AgentExecutionIdentitySchema=z15.strictObject({authorityRef:key3,executionId:key3,installationId:key3,installationRevisionId:key3,invocationId:id4,inputDigest:digest3});var AgentExecutionLeaseSchema=z15.strictObject({protocolVersion:z15.literal(1),bindingId:key3,executionId:key3,leaseRevision:z15.int().positive(),expiresAt:time,hardExpiresAt:time,renewedAt:time,renewBeforeSeconds:z15.int().positive()});var AgentExecutionBindingReceiptSchema=AgentExecutionIdentitySchema.extend({protocolVersion:z15.literal(1),bindingId:key3,grantRef:key3,grantRevision:z15.int().positive(),hardExpiresAt:time,boundAt:time,lease:AgentExecutionLeaseSchema});var AgentExecutionAccessMetadataSchema=z15.strictObject({protocolVersion:z15.literal(1),bindingId:key3,executionId:key3,accessGeneration:z15.int().positive(),expiresAt:time});var AgentExecutionPayloadSchemas={identity:z15.strictObject({}),bind:AgentExecutionIdentitySchema.extend({deadlineAt:time}),bindingQuery:z15.strictObject({authorityRef:key3,executionId:key3,originalRequestId:id4}),access:z15.strictObject({bindingId:key3,executionId:key3,expectedAccessGeneration:z15.int().nonnegative()}),accessQuery:z15.strictObject({bindingId:key3,executionId:key3,originalRequestId:id4}),leaseRenew:z15.strictObject({bindingId:key3,executionId:key3,expectedLeaseRevision:z15.int().positive()}),leaseQuery:z15.strictObject({bindingId:key3,executionId:key3,originalRequestId:id4}),close:z15.strictObject({bindingId:key3,executionId:key3,reason:z15.enum(["FINISHED","CANCELLED","ABORTED"])})};var envelope=z15.strictObject({protocolVersion:z15.literal(1),contractDigest:z15.literal(AgentExecutionContractDigest),capabilityDigest:digest3,requestId:id4,clientId:id4,registrationRevision:z15.int().positive(),resource:z15.url().max(2048),grantRef:id4,grantRevision:z15.int().positive(),payload:z15.unknown(),clientAssertion:z15.string().min(1).max(4096)});var AgentExecutionRequestSchemas={identity:envelope.extend({payload:AgentExecutionPayloadSchemas.identity}),bind:envelope.extend({payload:AgentExecutionPayloadSchemas.bind}),bindingQuery:envelope.extend({payload:AgentExecutionPayloadSchemas.bindingQuery}),access:envelope.extend({payload:AgentExecutionPayloadSchemas.access}),accessQuery:envelope.extend({payload:AgentExecutionPayloadSchemas.accessQuery}),leaseRenew:envelope.extend({payload:AgentExecutionPayloadSchemas.leaseRenew}),leaseQuery:envelope.extend({payload:AgentExecutionPayloadSchemas.leaseQuery}),close:envelope.extend({payload:AgentExecutionPayloadSchemas.close})};var AgentExecutionQualificationSchema=z15.strictObject({protocol:z15.literal("NVS_GENERIC_EXECUTION_QUALIFICATION_V1"),transport:AgentHostGenericInstallationTransportSchema,selection:AgentHostSelectionSchema,checkedAt:time,executionClass:z15.enum(["LIVE","TEST_ONLY"])});var AgentExecutionPermitSchema=z15.strictObject({schemaVersion:z15.literal(1),proof:AgentHostNativeToolAuthoritySchema,input:AgentHostExecutionInputSchema,inputDigest:digest3,guidance:z15.strictObject({version:z15.string().min(1).max(100),instructions:z15.string().min(1).max(2e4)}),registration:AgentExecutionRegistrationViewSchema,grant:AgentExecutionGrantSchema,qualification:AgentExecutionQualificationSchema,requestedByPrincipalId:id4,createdAt:time}).refine(v=>v.proof.transport?.protocol==="AGENT_STACK_GENERIC_INSTALLATION_V3"&&v.proof.tenantId===v.registration.tenantId&&v.proof.projectId===v.registration.projectId&&v.proof.productionId===v.input.productionId&&v.proof.executionId===v.input.executionId&&v.proof.hostRequestId===v.input.hostRequestId&&v.proof.bindingId===v.registration.bindingId&&v.proof.configurationVersion===v.registration.configurationVersion&&v.proof.capabilityDigest===v.registration.profile.nativeToolCapabilityDigest&&v.proof.transport.capabilityDigest===v.registration.profile.capabilityDigest&&v.grant.clientId===v.registration.clientId&&v.grant.resource===v.registration.registration.resource&&v.grant.registrationRevision===v.registration.registration.registrationRevision&&v.qualification.transport.installationId===v.proof.transport.installationId&&v.qualification.transport.installationRevisionId===v.proof.transport.installationRevisionId&&v.qualification.transport.capabilityDigest===v.proof.transport.capabilityDigest&&v.qualification.transport.slotKey===v.proof.transport.slotKey&&Date.parse(v.proof.expiresAt)<=Date.parse(v.grant.expiresAt)&&v.input.tenantId===v.proof.tenantId&&v.input.projectId===v.proof.projectId&&v.registration.enabled&&v.proof.transport.installationId===v.registration.registration.installationId&&v.proof.transport.slotKey===v.registration.profile.bootstrap.slotKey&&v.proof.executionClass===v.qualification.executionClass);var AgentExecutionBindingSchema=z15.strictObject({protocol:z15.literal("delegated-mcp-execution"),protocolVersion:z15.literal(1),contractDigest:z15.literal(AgentExecutionContractDigest),capabilityDigest:digest3,issuer:z15.url(),resource:z15.url(),slotKey:z15.string().regex(/^[a-z0-9][a-z0-9_-]{0,63}$/),registration:AgentExecutionRegistrationViewSchema.shape.registration,grant:AgentExecutionGrantSchema,endpoints:AgentExecutionRegistrationViewSchema.shape.profile.shape.capabilities.shape.endpoints,limits:AgentExecutionRegistrationViewSchema.shape.profile.shape.capabilities.shape.limits,bootstrap:AgentExecutionRegistrationViewSchema.shape.profile.shape.bootstrap,transportPolicy:z15.strictObject({profile:z15.literal("stateless-json-v1")}),runtimePolicy:z15.strictObject({sandbox:z15.literal("read-only"),webSearch:z15.literal("disabled"),localExecution:z15.literal("disabled"),toolExposure:z15.literal("direct"),maxTurns:z15.literal(1)})});var AgentExecutionInstallationObservationSchema=z15.strictObject({schemaVersion:z15.literal(3),installationId:key3,installationRevisionId:key3,slotKey:z15.string().regex(/^[a-z0-9][a-z0-9_-]{0,63}$/),binding:AgentExecutionBindingSchema,identity:AgentExecutionGrantSchema.extend({decision:z15.enum(["ALLOW","DRAIN","DENY","UNKNOWN"]),observedAt:time}),checkedAt:time});var AgentExecutionBootstrapInputSchema=z15.strictObject({nativeStudio:AgentHostExecutionInputSchema.safeExtend({nativeToolAuthority:AgentHostNativeToolAuthoritySchema})});var task=AgentExecutionBootstrapInputSchema.shape.nativeStudio;var AgentExecutionBootstrapResultSchema=z16.strictObject({schemaVersion:z16.literal(1),protocol:z16.literal("NVS_EXECUTION_CONTEXT_V1"),executionId:task.shape.executionId,hostRequestId:task.shape.hostRequestId,inputDigest:z16.string().regex(/^[a-f0-9]{64}$/),task,guidance:AgentExecutionPermitSchema.shape.guidance,outputContract:z16.strictObject({version:z16.literal("NVS_HOST_REPORT_V1"),authoritative:z16.literal(false),instructions:z16.string().min(1).max(2e4)})});import{z as z18}from"zod";import{z as z17}from"zod";var key4=z17.string().trim().min(1).max(200);var ScopedSourceInputSchema=SourceInputMetadataSchema.extend({projectId:ProjectIdSchema,idempotencyKey:key4});var ScopedSourceUploadSchema=UploadSourceInputRequestSchema.extend({projectId:ProjectIdSchema,idempotencyKey:key4});var SourceReadSchema=SourceLibraryMediaSchema.extend({offsetBytes:z17.int().min(0).max(8388608).default(0),maxTextBytes:z17.int().min(4).max(65536).default(16384)});var SourceTextWindowSchema=SourceLibraryMediaSchema.extend({contentType:z17.enum(["text/plain","application/json"]),checksumSha256:z17.string().regex(/^[0-9a-f]{64}$/),totalBytes:z17.int().positive().max(8388608),offsetBytes:z17.int().nonnegative(),byteLength:z17.int().nonnegative().max(65536),nextOffsetBytes:z17.int().nonnegative().nullable(),text:z17.string().max(65536)});var InterfaceImageMetadataSchema=KeyframeMediaSchema.omit({contentBase64:true});var InterfacePosterMetadataSchema=InterfaceImageMetadataSchema.extend({contentType:z18.literal("image/png")});var InterfaceDownloadDescriptorSchema=z18.strictObject({humanLinks:HumanLinksSchema.optional(),method:z18.literal("GET"),path:z18.string().min(1).max(2048),tenantId:TenantIdSchema,authentication:z18.literal("BEARER_AND_TENANT_HEADER"),contentType:z18.enum(["video/mp4","image/png","application/json"]),checksumSha256:z18.string().regex(/^[0-9a-f]{64}$/),byteSize:z18.int().positive().max(128*1024*1024)});var tenantMediaDownloadPath="/v1/local-execution/tenant-media/download";var InterfaceDeliveryDownloadDescriptorSchema=z18.discriminatedUnion("method",[InterfaceDownloadDescriptorSchema,InterfaceDownloadDescriptorSchema.extend({method:z18.literal("POST"),path:z18.literal(tenantMediaDownloadPath),productionId:ProductionIdSchema,contentType:z18.literal("video/mp4"),body:z18.strictObject({tenantId:TenantIdSchema,projectId:ProjectIdSchema,representationId:ArtifactRepresentationIdSchema})})]);var SourceReadResultSchema=z18.union([SourceTextWindowSchema,SourceLibraryMediaSchema.extend(InterfaceImageMetadataSchema.shape).strict(),SourceLibraryMediaSchema.extend({contentType:z18.literal("video/mp4"),checksumSha256:z18.string().regex(/^[0-9a-f]{64}$/),byteSize:z18.int().positive().max(8388608),importOperation:z18.literal("imported-visual.register-source")}).strict()]);import{z as z19}from"zod";var StartReferencePreviewSchema=z19.strictObject({tenantId:TenantIdSchema,projectId:ProjectIdSchema,productionId:ProductionIdSchema,sourceArtifactId:ArtifactIdSchema,expectedBriefVersion:z19.int().positive(),idempotencyKey:z19.string().regex(/^[A-Za-z0-9_-]{8,80}$/)});var ReferencePreviewAdmissionSchema=z19.strictObject({semanticStatus:z19.literal("ACCEPTED"),operationId:OperationIdSchema,productionId:ProductionIdSchema,sourceArtifactId:ArtifactIdSchema,briefVersion:z19.int().positive()});var ReferencePreviewResultSchema=z19.strictObject({semanticStatus:z19.literal("SUCCESS"),sourceArtifactId:ArtifactIdSchema,representationId:ArtifactRepresentationIdSchema,contentType:z19.literal("image/png"),checksumSha256:z19.string().regex(/^[0-9a-f]{64}$/),width:z19.int().positive(),height:z19.int().positive(),byteSize:z19.int().positive(),contentBase64:z19.string().min(4)});var ReferencePreviewOperationInputSchema=z19.strictObject({tenantId:TenantIdSchema,projectId:ProjectIdSchema,productionId:ProductionIdSchema,operationId:OperationIdSchema});var ReferencePreviewReadResultSchema=z19.union([ReferencePreviewResultSchema,z19.strictObject({semanticStatus:z19.literal("ACCEPTED")})]);var ReferencePreviewCancelResultSchema=z19.union([z19.strictObject({semanticStatus:z19.literal("ACCEPTED")}),z19.strictObject({semanticStatus:z19.literal("NOT_FOUND")})]);import{z as z20}from"zod";var StudioCapabilitiesInputSchema=z20.strictObject({tenantId:TenantIdSchema,productionId:ProductionIdSchema.optional()});var StudioCapabilitiesSchema=z20.strictObject({semanticStatus:z20.literal("SUCCESS"),capabilities:z20.array(z20.strictObject({capability:z20.string().min(1).max(120),tool:z20.string().min(1).max(120).optional(),availability:z20.enum(["AVAILABLE","UNAVAILABLE"]),reason:z20.string().min(1).max(1e3).nullable()})).max(512)});var VideoOptionsSchema=z20.array(z20.strictObject({selection:ProviderSelectionSchema,profile:VideoProviderProfileSchema})).max(1600);import{z as z21}from"zod";var WorkspaceHealthSchema=z21.object({service:z21.string().min(1),status:z21.literal("ok")});import{z as z22}from"zod";var PrincipalKindSchema=z22.enum(["HUMAN","AGENT","SERVICE","WORKER"]);var PrincipalSchema=z22.object({id:PrincipalIdSchema,kind:PrincipalKindSchema,issuer:z22.string().trim().min(1),subject:z22.string().trim().min(1),displayName:z22.string().trim().min(1).nullable()});var TenantMembershipSchema=z22.object({tenantId:TenantIdSchema,principalId:PrincipalIdSchema});import{z as z23}from"zod";var TenantSchema=z23.object({id:TenantIdSchema,displayName:z23.string().trim().min(1).nullable(),createdAt:z23.iso.datetime({offset:true})});import{z as z24}from"zod";var Key=z24.string().regex(/^[a-z][a-z0-9_-]{0,39}$/);var Intent=z24.string().trim().min(1).max(600);var ExplorationScopeSchema=DirectorScopeSchema.extend({shotId:ShotIdSchema});var ExplorationBasisSchema=DirectorBasisSchema.safeExtend({shotId:ShotIdSchema,shotPlanningRevision:z24.int().positive()});var ExplorationContextInputSchema=z24.strictObject({scope:ExplorationScopeSchema,preparationIds:z24.array(PreparationIdSchema).max(6).default([])}).refine(v=>new Set(v.preparationIds).size===v.preparationIds.length,"Preparation IDs must be distinct");var ExplorationProfileIdentitySchema=KeyframeProviderProfileSchema.pick({id:true,adapterVersion:true,model:true,executionClass:true});var ExplorationOptionSchema=z24.strictObject({selection:ProviderSelectionSchema.nullable(),profile:z24.discriminatedUnion("mediaType",[KeyframeProviderProfileSchema,VideoProviderProfileSchema])});var Missing=z24.strictObject({semanticStatus:z24.literal("NEEDS_INPUT"),missingPrerequisites:z24.array(z24.enum(["ACTIVE_BRIEF","ACTIVE_STORY","ACTIVE_SCENE_SHOT_PLAN"])).min(1).max(3)});var ExplorationContextResultSchema=z24.discriminatedUnion("semanticStatus",[z24.strictObject({semanticStatus:z24.literal("SUCCESS"),advisory:z24.literal(true),basis:ExplorationBasisSchema,owner:DirectorContextResultSchema.options[0],preparations:z24.array(z24.strictObject({view:PreparationViewSchema,eligibleOptions:z24.array(ExplorationOptionSchema).max(24),eligibleOptionCount:z24.int().nonnegative(),optionsTruncated:z24.boolean()})).max(6)}),Missing]);var ImageDraft=KeyframeStartInputSchema.omit({idempotencyKey:true});var VideoDraft=VideoStartInputSchema.omit({idempotencyKey:true});var ExplorationCommandSchema=z24.strictObject({commandKey:Key,purpose:Intent,mediaType:z24.enum(["IMAGE","VIDEO"]),preparationId:PreparationIdSchema,contractId:ImageDraft.shape.contractId,contractFingerprint:ImageDraft.shape.contractFingerprint,selection:ProviderSelectionSchema.nullable(),profile:ExplorationProfileIdentitySchema});var ValidateExplorationPlanSchema=z24.strictObject({basis:ExplorationBasisSchema,plan:z24.strictObject({origin:z24.strictObject({kind:z24.literal("EXTERNAL_AGENT_HOST"),label:z24.string().trim().min(1).max(100)}),objective:Intent,comparisonCriteria:z24.array(Intent).min(1).max(8),unknowns:z24.array(z24.string().trim().min(1).max(300)).max(8),maximumGenerationCommands:z24.int().min(1).max(6),commands:z24.array(ExplorationCommandSchema).min(1).max(6)})}).refine(v=>new TextEncoder().encode(JSON.stringify(v)).byteLength<=1024*1024,"Exploration input exceeds the 1 MiB JSON budget");var ExplorationDraftSchema=z24.discriminatedUnion("mediaType",[z24.strictObject({commandKey:Key,mediaType:z24.literal("IMAGE"),request:ImageDraft}),z24.strictObject({commandKey:Key,mediaType:z24.literal("VIDEO"),request:VideoDraft})]);var ExplorationValidationResultSchema=z24.discriminatedUnion("semanticStatus",[z24.strictObject({semanticStatus:z24.literal("SUCCESS"),advisory:z24.literal(true),basis:ExplorationBasisSchema,plan:ValidateExplorationPlanSchema.shape.plan,generationDrafts:z24.array(ExplorationDraftSchema).min(1).max(6),limitations:z24.array(z24.enum(["ADMISSION_RECHECKS_BASIS_AND_PROVIDER","COMMAND_COUNT_IS_NOT_MONETARY_BUDGET","NO_AUTOMATIC_EXECUTION_OR_ACCEPTANCE","QUALITY_REQUIRES_EXACT_MEDIA_INSPECTION"])).length(4)}),Missing]);var ExplorationCompareInputSchema=z24.strictObject({scope:ExplorationScopeSchema,items:z24.array(z24.strictObject({label:Key,mediaType:z24.enum(["IMAGE","VIDEO"]),generationId:z24.uuid()})).min(2).max(6)});var ExplorationComparisonResultSchema=z24.strictObject({semanticStatus:z24.literal("SUCCESS"),advisory:z24.literal(true),scope:ExplorationScopeSchema,items:z24.array(z24.discriminatedUnion("mediaType",[z24.strictObject({label:Key,mediaType:z24.literal("IMAGE"),generation:KeyframeGenerationViewSchema,handoff:z24.strictObject({mediaRead:KeyframeReviewScopeSchema,reviewTarget:KeyframeReviewScopeSchema}).nullable()}),z24.strictObject({label:Key,mediaType:z24.literal("VIDEO"),generation:VideoGenerationViewSchema,handoff:z24.strictObject({mediaRead:VideoReviewScopeSchema,reviewTarget:VideoReviewScopeSchema}).nullable()})])).min(2).max(6),limitations:z24.tuple([z24.literal("OWNER_STATES_ARE_NOT_VISUAL_SCORES"),z24.literal("REVIEW_AND_ACCEPTANCE_REMAIN_EXPLICIT")])});import{z as z25}from"zod";var sha4=z25.string().regex(/^[0-9a-f]{64}$/);var FinalOutputReviewContextInputSchema=z25.strictObject({scope:DirectorScopeSchema,renderId:z25.uuid()});var FinalOutputReviewBasisSchema=FinalOutputReviewContextInputSchema.extend({contextFingerprint:sha4});var FinalOutputReviewContextResultSchema=z25.strictObject({semanticStatus:z25.literal("SUCCESS"),advisory:z25.literal(true),basis:FinalOutputReviewBasisSchema,ownerContext:DirectorContextResultSchema,deliveryTarget:DeliveryTargetSchema,deliverySnapshot:DeliverySnapshotSchema,validation:DeliveryValidationViewSchema.nullable(),manifest:RegisteredDeliveryManifestSchema.nullable(),limitations:z25.array(z25.enum(["OWNER_REVIEW_3_REMAINS_AUTHORITATIVE","NO_CALLER_SUPPLIED_DELIVERY_CHECKS","NO_IMPLICIT_MEDIA_OR_MODEL_CALL","READS_ARE_NOT_ATOMIC_OR_RESERVED"])).length(4)});import{z as z30}from"zod";import{z as z29}from"zod";import{z as z28}from"zod";import{z as z26}from"zod";var Text=z26.string().trim().min(1).max(600);var Method=z26.enum(["HUMAN","AI","CODE"]);var Key2=z26.string().regex(/^[a-z][a-z0-9_.:-]{0,99}$/);var CompositionAuthoringObligationsSchema=z26.strictObject({schemaVersion:z26.literal(1),basis:CompositionBasisPinSchema,productionRevision:z26.int().positive(),output:BriefContentSchema.pick({targetDurationSeconds:true,aspectRatio:true,outputProfile:true}),objective:BriefContentSchema.shape.objective,productPresentationGoal:BriefContentSchema.shape.productPresentationGoal,audience:BriefContentSchema.shape.audience,styleTone:BriefContentSchema.shape.styleTone,callToAction:BriefContentSchema.shape.callToAction,narrativeIntent:StoryContentSchema.shape.narrativeIntent,canonicalFacts:BriefContentSchema.shape.canonicalFacts,storyBeats:StoryContentSchema.shape.beats,storyFactualClaims:StoryContentSchema.shape.factualClaims,shot:ShotPlanEntrySchema.nullable(),obligationKeys:z26.array(Key2).min(1).max(384).refine(v=>new Set(v).size===v.length,"Obligation keys must be unique"),semantics:z26.literal("ACCEPTED_INTENT_NOT_OBSERVED_MEDIA")}).refine(v=>v.basis.shotId===null===(v.shot===null)&&(!v.shot||v.shot.shotId===v.basis.shotId),"Authoring Shot must match the exact planning basis");var MakingAlternativeSchema=z26.strictObject({alternativeId:z26.string().regex(/^[a-z][a-z0-9_-]{0,39}$/),title:z26.string().trim().min(1).max(120),method:z26.enum(["HUMAN","AI","CODE","HYBRID"]),contributions:z26.array(z26.strictObject({method:Method,role:z26.enum(["PRIMARY_VISUAL","VISUAL_LAYER"]),intent:Text})).min(1).max(6),rationale:Text,tradeoffs:z26.array(Text).max(6),obligationKeys:z26.array(Key2).min(1).max(384)}).superRefine((v,ctx)=>{const methods=new Set(v.contributions.map(c=>c.method));if(v.method==="HYBRID"?methods.size<2:methods.size!==1||!methods.has(v.method))ctx.addIssue({code:"custom",path:["contributions"],message:"Contributions must match the advisory making method"});if(new Set(v.contributions.map(c=>c.method+":"+c.role)).size!==v.contributions.length)ctx.addIssue({code:"custom",path:["contributions"],message:"Method/role contributions must be unique"});if(new Set(v.obligationKeys).size!==v.obligationKeys.length)ctx.addIssue({code:"custom",path:["obligationKeys"],message:"Obligation references must be unique"})});var ValidateCompositionMakingSchema=CompositionScopeSchema.extend({projectId:z26.uuid(),expectedProductionRevision:z26.int().positive(),basis:CompositionBasisPinSchema,proposal:z26.strictObject({origin:z26.strictObject({kind:z26.literal("EXTERNAL_AGENT_HOST"),label:z26.string().trim().min(1).max(100)}),makingIntent:z26.enum(["REAL_WORLD_CAPTURE","GENERATED_SCENE","PROGRAMMATIC_EXPLANATION"]),unknowns:z26.array(z26.string().trim().min(1).max(300)).max(8),alternatives:z26.array(MakingAlternativeSchema).min(1).max(3)})}).superRefine((v,ctx)=>{if(new Set(v.proposal.alternatives.map(a=>a.alternativeId)).size!==v.proposal.alternatives.length)ctx.addIssue({code:"custom",message:"Alternative IDs must be unique"});if(new TextEncoder().encode(JSON.stringify(v)).byteLength>131072)ctx.addIssue({code:"custom",message:"Making proposal exceeds the 128 KiB UTF-8 JSON budget"})});var CompositionMakingValidationSchema=CompositionScopeSchema.extend({semanticStatus:z26.literal("SUCCESS"),advisory:z26.literal(true),projectId:z26.uuid(),authoring:CompositionAuthoringObligationsSchema,proposal:ValidateCompositionMakingSchema.shape.proposal,limitations:z26.tuple([z26.literal("STRATEGY_IS_AGENT_ADVICE_NOT_CANONICAL_SELECTION"),z26.literal("SOURCE_METHOD_IS_NOT_PROVENANCE_OR_PROVIDER_ELIGIBILITY"),z26.literal("AUTHORING_AND_RENDER_RECHECK_CURRENT_BASIS"),z26.literal("INDEPENDENT_REVIEW_AND_DELIVERY_REMAIN_REQUIRED")])}).superRefine((v,ctx)=>{const required=new Set(v.authoring.obligationKeys);if(new Set(v.proposal.alternatives.map(a=>a.alternativeId)).size!==v.proposal.alternatives.length||v.proposal.alternatives.some(a=>a.obligationKeys.length!==required.size||a.obligationKeys.some(k=>!required.has(k))))ctx.addIssue({code:"custom",message:"Making result must retain unique alternatives and exact native obligation coverage"})});import{z as z27}from"zod";var CompositionAuthoringRequirementsSchema=z27.strictObject({videoFrameCache:z27.strictObject({profileId:z27.literal("HYPERFRAME_1080P30_FRAME_CACHE_V2"),media:z27.literal("MANAGED_MP4_H264_CFR30_SDR_YUV420P"),maxVideos:z27.literal(4),maxDimension:z27.literal(1920),maxPixels:z27.literal(2073600),maxSourceSeconds:z27.literal(60),playbackRate:z27.literal(1),loop:z27.literal(false),sourceOffset:z27.literal("ZERO_BASED_FRAME_ALIGNED"),srcPattern:z27.literal("/inputs/{inputName}.mp4"),attributes:z27.tuple([z27.literal("id"),z27.literal("src"),z27.literal("data-start"),z27.literal("data-duration")]),dynamicVideoSupported:z27.literal(false),nativePlaybackAndCanvasSamplingSupported:z27.literal(false)}).optional(),semantics:z27.literal("REQUIREMENTS_NOT_RUNTIME_OR_REVIEW_EVIDENCE"),dependencies:CompositionContentSchema.shape.dependencies,html:z27.strictObject({entrypoint:z27.literal("index.html"),stageSelector:z27.literal("#stage"),timelineRegistry:z27.literal("window.__timelines"),readinessPromise:z27.literal("window.__nativeReady"),gsapScript:z27.literal("/_native/gsap.min.js"),managedInputsScript:z27.literal("/native-inputs.js"),rootAttributes:z27.tuple([z27.literal("data-composition-id"),z27.literal("data-width"),z27.literal("data-height"),z27.literal("data-duration")]),timing:z27.literal("PAUSED_GSAP_TIMELINE_WITH_DURATION_MATCHING_LOCAL_CLOCK")})});var jsonSchema=z27.record(z27.string().max(120),z27.json());var CompositionAuthoringGuideSchema=z27.strictObject({inputTool:z27.literal("composition_put_input"),inputField:z27.literal("contentUtf8"),encoding:z27.literal("UTF8_JSON"),schemas:z27.strictObject({SOURCE:jsonSchema,DEPENDENCY_MANIFEST:jsonSchema,DEPENDENCY_LOCK:jsonSchema}),rendererRequirements:CompositionAuthoringRequirementsSchema.nullable(),dependencyInputs:z27.strictObject({dependencies:CompositionContentSchema.shape.dependencies,manifest:CompositionDependencyManifestSchema,lock:CompositionDependencyLockSchema}).nullable().optional(),validation:z27.literal("NATIVE_OWNER_RECHECKS_BYTES_BASIS_AND_SEMANTIC_REFINEMENTS")}).refine(v=>new TextEncoder().encode(JSON.stringify(v)).byteLength<=65536);var CreateCompositionSchema=SubmitCompositionSchema.safeExtend({compositionId:z28.null(),expectedVersion:z28.literal(0),previousVersionId:z28.null()});var ReviseCompositionSchema=SubmitCompositionSchema.safeExtend({compositionId:z28.uuid(),expectedVersion:z28.int().positive(),previousVersionId:z28.uuid()});var CompositionBriefQuerySchema=CompositionScopeSchema.extend({shotId:z28.uuid().nullable().default(null)});var CompositionAuthoringBriefSchema=CompositionScopeSchema.extend({projectId:z28.uuid(),productionRevision:z28.int().positive(),planningStatus:z28.enum(["READY","MISSING_PLANNING","STALE_PLANNING","INACTIVE"]),basis:CompositionBasisPinSchema.nullable(),briefContent:BriefContentSchema.nullable(),storyContent:StoryContentSchema.nullable(),shot:ShotPlanEntrySchema.nullable(),authoring:CompositionAuthoringObligationsSchema.nullable().optional()});var ValidateCompositionSchema=CompositionScopeSchema.extend({expectedProductionRevision:z28.int().positive(),basis:CompositionBasisPinSchema,content:CompositionContentSchema}).superRefine((v,ctx)=>{if(v.content.role==="PRIMARY_VISUAL"&&!v.basis.shotId)ctx.addIssue({code:"custom",path:["basis","shotId"],message:"Primary visual requires a planned Shot"})});var CompositionValidationReceiptSchema=z28.strictObject({authoringValidation:z28.literal("PASS"),basis:CompositionBasisPinSchema,productionRevision:z28.int().positive(),contentFingerprint:z28.string().regex(/^[0-9a-f]{64}$/),inputCount:z28.int().min(3).max(64),byteReadback:z28.literal("VERIFIED"),rendererValidation:z28.literal("NOT_EXECUTED"),renderAvailability:z28.enum(["AVAILABLE","UNAVAILABLE"]),nextActions:z28.array(z28.enum(["CREATE_COMPOSITION","REVISE_COMPOSITION"])).max(2)});var PutCompositionInputSchema=CompositionScopeSchema.extend({name:CompositionBindingSchema.shape.name,purpose:z28.enum(["SOURCE","DEPENDENCY_MANIFEST","DEPENDENCY_LOCK","DATA"]),declaredOrigin:CompositionBindingSchema.shape.declaredOrigin,executionClass:z28.enum(["LIVE","TEST_ONLY"]),contentUtf8:z28.string().min(1).max(8388608),idempotencyKey:z28.string().trim().min(1).max(200)}).superRefine((v,ctx)=>{if(v.purpose==="SOURCE"&&v.declaredOrigin!=="CODE")ctx.addIssue({code:"custom",path:["declaredOrigin"],message:"Programmatic source must retain CODE provenance"})});var CompositionInputReceiptSchema=z28.strictObject({binding:CompositionBindingSchema,projectId:z28.uuid(),contentType:z28.literal("application/json"),byteSize:z28.int().positive().max(8388608),executionClass:z28.enum(["LIVE","TEST_ONLY"]),inputStatus:z28.enum(["AVAILABLE","UNAVAILABLE"]),byteReadback:z28.literal("VERIFIED_AT_REGISTRATION")});var CompositionCapabilitySchema=z28.strictObject({capability:z28.string().min(1).max(80),tool:z28.string().nullable(),availability:z28.enum(["AVAILABLE","UNAVAILABLE"]),reason:z28.string().nullable()});var CompositionCapabilitiesSchema=z28.strictObject({provider:z28.literal("HYPERFRAME"),dialect:z28.literal("HYPERFRAME_HTML_GSAP_V1"),planningStatus:CompositionAuthoringBriefSchema.shape.planningStatus,capabilities:z28.array(CompositionCapabilitySchema).max(18),inputLimitsMiB:z28.strictObject({SOURCE:z28.literal(8),DEPENDENCY_MANIFEST:z28.literal(8),DEPENDENCY_LOCK:z28.literal(8),DATA:z28.literal(8),FONT:z28.literal(32),IMAGE:z28.literal(8),VIDEO:z28.literal(64)}),clockSemantics:z28.literal("RATIONAL_FPS_HALF_OPEN_FRAMES"),rendererValidation:z28.enum(["C3_PENDING","PER_REQUEST_CONFORMANCE"]),authoringGuide:CompositionAuthoringGuideSchema.optional()});var CompositionFailureSchema=z28.strictObject({semanticStatus:z28.enum(["INVALID_INPUT","NOT_FOUND","REVISION_CONFLICT","STALE_BASIS","BLOCKED","CAPABILITY_UNAVAILABLE","INTERNAL_OPERATIONAL_FAILURE"]),error:z28.strictObject({code:z28.string().max(80),message:z28.string().max(2e3)}),retryable:z28.boolean(),nextActions:z28.array(z28.string().max(80)).max(4),diagnostics:z28.array(z28.strictObject({code:z28.string().max(80),message:z28.string().max(2e3)})).max(32)});var ParameterValue=z29.strictObject({kind:z29.literal("PARAMETER_VALUE"),name:CompositionBindingSchema.shape.name,value:z29.union([z29.string().max(4e3),z29.number().finite(),z29.boolean()])});var Binding=CompositionBindingSchema.extend({purpose:z29.enum(["SOURCE","DATA","FONT","IMAGE","VIDEO"])});var CompositionRepairConsumerSchema=z29.discriminatedUnion("role",[z29.strictObject({role:z29.literal("PRIMARY_VISUAL"),clipOrdinal:z29.int().min(1).max(200)}),z29.strictObject({role:z29.literal("VISUAL_LAYER"),visualLayerId:z29.uuid()})]);var Consumers=z29.array(CompositionRepairConsumerSchema).min(1).max(208).refine(items=>new Set(items.map(i=>i.role==="PRIMARY_VISUAL"?i.role+i.clipOrdinal:i.role+i.visualLayerId)).size===items.length,"Coordinated consumers must be unique exact occurrences");var CompositionRepairPatchSchema=z29.discriminatedUnion("kind",[ParameterValue,z29.strictObject({kind:z29.literal("BINDING_REPLACE"),binding:Binding})]);var ReviseCompositionRepairActionSchema=z29.strictObject({kind:z29.literal("REVISE_COMPOSITION"),localityIndex:z29.int().min(0).max(207),patches:z29.array(CompositionRepairPatchSchema).min(1).max(16),coordinatedConsumers:Consumers.optional()}).superRefine((v,ctx)=>{const names=v.patches.map(p=>p.kind+":"+(p.kind==="PARAMETER_VALUE"?p.name:p.binding.name));if(new Set(names).size!==names.length)ctx.addIssue({code:"custom",message:"Local Composition patch targets must be unique"})});var CompositionRepairSubjectSchema=z29.strictObject({locality:CompositionFindingLocalitySchema,composition:CompositionViewSchema,render:CompositionRenderViewSchema});var{idempotencyKey,...revisionShape}=ReviseCompositionSchema.shape;var RevisionDraft=z29.strictObject(revisionShape).refine(v=>v.content.role!=="PRIMARY_VISUAL"||v.basis.shotId!==null,"Primary repair retains an exact planned Shot");var CompositionRepairHandoffSchema=z29.strictObject({kind:z29.literal("COMPOSITION_REVISE"),locality:CompositionFindingLocalitySchema,input:RevisionDraft,renderProfileId:z29.enum(["HYPERFRAME_1080P30_FULL_PAINT_V1","HYPERFRAME_1080P30_FRAME_CACHE_V2","HYPERFRAME_RGBA_PNG30_FULL_PAINT_V1"]),sourceReviewRequired:z29.boolean(),coordinatedConsumers:Consumers.optional()}).superRefine((v,ctx)=>{if(v.input.compositionId!==v.locality.compositionId||v.input.previousVersionId!==v.locality.compositionVersionId||v.input.expectedVersion!==v.locality.compositionVersion||v.input.content.role!==v.locality.role||v.coordinatedConsumers?.some(i=>i.role!==v.locality.role)||v.sourceReviewRequired!==(v.locality.role==="PRIMARY_VISUAL")||!(v.locality.role==="PRIMARY_VISUAL"?["HYPERFRAME_1080P30_FULL_PAINT_V1","HYPERFRAME_1080P30_FRAME_CACHE_V2"].includes(v.renderProfileId):v.renderProfileId==="HYPERFRAME_RGBA_PNG30_FULL_PAINT_V1"))ctx.addIssue({code:"custom",message:"Composition repair handoff must retain exact locality identity, role and original output profile"})});var text=z30.string().trim().min(1).max(2e3);var key5=z30.string().regex(/^[a-z][a-z0-9_-]{0,39}$/);var RepairStrategyContextInputSchema=z30.strictObject({scope:DirectorScopeSchema,findingId:z30.uuid()});var RepairStrategyBasisSchema=RepairStrategyContextInputSchema.extend({contextFingerprint:z30.string().regex(/^[0-9a-f]{64}$/)});var RepairStrategyActionSchema=z30.discriminatedUnion("kind",[ReviseCompositionRepairActionSchema,z30.strictObject({kind:z30.literal("TRIM_CLIP"),ordinal:z30.int().min(1).max(200),sourceInMs:z30.int().nonnegative().max(30150),sourceOutMs:z30.int().positive().max(30150)}),z30.strictObject({kind:z30.literal("REVISE_CAPTIONS"),content:CaptionContentSchema}),z30.strictObject({kind:z30.literal("ADJUST_TRANSITION"),ordinal:z30.int().min(2).max(200),transition:ClipTransitionSchema}),z30.strictObject({kind:z30.literal("ADJUST_AUDIO_COMPOSITION"),audio:TimelineAudioInputSchema}),z30.strictObject({kind:z30.literal("ACKNOWLEDGE_WARNINGS"),acknowledgements:z30.array(z30.strictObject({key:z30.string().min(1).max(220),reason:text})).min(1).max(300)}),z30.strictObject({kind:z30.literal("REGENERATE_SHOT"),shotId:z30.uuid()}),z30.strictObject({kind:z30.literal("REQUEST_HUMAN_INPUT"),question:text}),z30.strictObject({kind:z30.literal("REQUEST_CANONICAL_CHANGE"),requestedChange:text})]);var RepairStrategyAlternativeSchema=z30.strictObject({id:key5,rationale:text,whySmallerChangeInsufficient:text,action:RepairStrategyActionSchema});var ValidateRepairStrategySchema=z30.strictObject({basis:RepairStrategyBasisSchema,proposal:z30.strictObject({origin:z30.strictObject({kind:z30.literal("EXTERNAL_AGENT_HOST"),label:z30.string().trim().min(1).max(100)}),summary:text,alternatives:z30.array(RepairStrategyAlternativeSchema).min(1).max(6),selectedAlternativeId:key5})}).refine(v=>new TextEncoder().encode(JSON.stringify(v)).byteLength<=1024*1024,"Repair Strategy input exceeds the 1 MiB JSON budget");var RepairStrategyContextResultSchema=z30.strictObject({compositionRepairAvailable:z30.boolean().optional(),semanticStatus:z30.literal("SUCCESS"),advisory:z30.literal(true),basis:RepairStrategyBasisSchema,ownerContext:DirectorContextResultSchema,finding:RoughCutFindingViewSchema,reviewTarget:RoughCutReviewTargetSchema,finalReady:FinalReadyViewSchema,eligibility:z30.strictObject({ready:z30.boolean(),reasons:z30.array(z30.enum(["FINDING_NOT_OPEN","TARGET_STALE","MEDIA_UNAVAILABLE","PRODUCTION_UNAVAILABLE","REVIEW_CHANGED","FINDING_BASIS_CHANGED"])).max(6)})});var RepairStrategyHandoffSchema=z30.discriminatedUnion("kind",[CompositionRepairHandoffSchema,z30.strictObject({kind:z30.literal("TIMELINE_BUILD"),input:BuildTimelineShapeSchema.omit({idempotencyKey:true})}),z30.strictObject({kind:z30.literal("CAPTION_AUTHOR"),input:AuthorCaptionsSchema.omit({idempotencyKey:true})}),z30.strictObject({kind:z30.literal("FINAL_READY_DECIDE"),input:DecideFinalReadySchema.omit({idempotencyKey:true})}),z30.strictObject({kind:z30.literal("REGENERATION_INTENT"),preparationQuery:PreparationActiveInputSchema,admission:z30.literal("EXPLICIT_NATIVE_PREPARATION_AND_SELECTION_REQUIRED")}),z30.strictObject({kind:z30.literal("HUMAN_INPUT_INTENT"),question:text}),z30.strictObject({kind:z30.literal("CANONICAL_CHANGE_INTENT"),requestedChange:text})]);var RepairStrategyValidationResultSchema=z30.strictObject({semanticStatus:z30.literal("SUCCESS"),advisory:z30.literal(true),basis:RepairStrategyBasisSchema,proposal:ValidateRepairStrategySchema.shape.proposal,finding:RoughCutFindingViewSchema,alternatives:z30.array(z30.strictObject({alternativeId:key5,affectedScope:RoughCutFindingViewSchema.shape.affectedScope,handoff:RepairStrategyHandoffSchema,materialChange:z30.boolean(),preservedAcceptanceIds:z30.array(z30.uuid()).max(200),followUp:z30.array(z30.enum(["REVOKE_FINAL_READY_AND_REFRESH","REFRESH_TIMELINE_BASIS","ATTACH_NEW_CAPTION","REFRESH_AND_PREPARE_SHOT","EXPLICIT_VIDEO_GENERATION","REVIEW_1","SHOT_ACCEPTANCE","REBUILD_TIMELINE","ROUGH_CUT_RENDER","REVIEW_2","FINAL_READY_DECISION","AUTHORIZED_PLANNING_DECISION","COMPOSITION_REVISE","COMPOSITION_RENDER"])).max(10)})).min(1).max(6),selectedAlternativeId:key5,limitations:z30.tuple([z30.literal("NO_CANONICAL_REPAIR_LIFECYCLE_OR_WRITE"),z30.literal("READS_ARE_NOT_ATOMIC_OR_RESERVED"),z30.literal("CREATIVE_RATIONALE_IS_NOT_VERIFIED"),z30.literal("OWNER_RECHECKS_CAS_IDEMPOTENCY_AND_EXECUTION_CLASS"),z30.literal("MATERIAL_REPAIR_REQUIRES_NEW_OBSERVATION_AND_REVIEW")])}).superRefine((v,ctx)=>{const ids=v.alternatives.map(a=>a.alternativeId);const proposed=v.proposal.alternatives.map(a=>a.id);if(v.finding.id!==v.basis.findingId||v.finding.tenantId!==v.basis.scope.tenantId||v.finding.projectId!==v.basis.scope.projectId||v.finding.productionId!==v.basis.scope.productionId||v.selectedAlternativeId!==v.proposal.selectedAlternativeId||!ids.includes(v.selectedAlternativeId)||new Set(ids).size!==ids.length||ids.length!==proposed.length||ids.some(id7=>!proposed.includes(id7)))ctx.addIssue({code:"custom",message:"Repair validation must retain exact Finding and proposal selection"});for(const alternative of v.alternatives){const h=alternative.handoff;if("input"in h&&(h.input.tenantId!==v.basis.scope.tenantId||h.input.productionId!==v.basis.scope.productionId))ctx.addIssue({code:"custom",message:"Repair handoff must retain the exact native Tenant/Production scope"})}});import{z as z31}from"zod";var text2=z31.string().trim().min(1).max(2e3);var key6=z31.string().regex(/^[a-z][a-z0-9_-]{0,39}$/);var EditorContextInputSchema=z31.strictObject({scope:DirectorScopeSchema,timelineVersionId:z31.uuid()});var EditorBasisSchema=EditorContextInputSchema.extend({contextFingerprint:z31.string().regex(/^[0-9a-f]{64}$/)});var EditorAlternativeSchema=z31.strictObject({id:key6,rationale:text2,pacingIntent:text2,action:z31.discriminatedUnion("kind",[z31.strictObject({kind:z31.literal("BUILD_TIMELINE"),clips:BuildTimelineSchema.shape.clips}),z31.strictObject({kind:z31.literal("EDIT_GRAPHICS"),graphics:z31.array(TimelineGraphicInputSchema).min(1).max(8)}),z31.strictObject({kind:z31.literal("EDIT_VISUAL_LAYERS"),visualLayers:z31.array(TimelineVisualLayerInputSchema).min(1).max(8)}),z31.strictObject({kind:z31.literal("EDIT_AUDIO_COMPOSITION"),audio:TimelineAudioInputSchema}),z31.strictObject({kind:z31.literal("REVISE_CAPTIONS"),content:CaptionContentSchema}),z31.strictObject({kind:z31.literal("REQUEST_COMPOSITION_CAPABILITY"),concern:z31.enum(["TRANSITION","AUDIO_VISUAL_ALIGNMENT","VOICE_TIMING","CAPTION_RETIMING"]),requestedChange:text2}),z31.strictObject({kind:z31.literal("REQUEST_HUMAN_INPUT"),question:text2})])});var ValidateEditorProposalSchema=z31.strictObject({basis:EditorBasisSchema,proposal:z31.strictObject({origin:z31.strictObject({kind:z31.literal("EXTERNAL_AGENT_HOST"),label:z31.string().trim().min(1).max(100)}),summary:text2,alternatives:z31.array(EditorAlternativeSchema).min(1).max(6),selectedAlternativeId:key6})}).refine(v=>new TextEncoder().encode(JSON.stringify(v)).byteLength<=1024*1024,"Editor Intelligence input exceeds the 1 MiB JSON budget");var EditorContextResultSchema=z31.strictObject({semanticStatus:z31.literal("SUCCESS"),advisory:z31.literal(true),basis:EditorBasisSchema,ownerContext:DirectorContextResultSchema,timeline:TimelineViewSchema,timelineBasis:TimelineBasisSchema,finalReady:FinalReadyViewSchema,eligibility:z31.strictObject({ready:z31.boolean(),reasons:z31.array(z31.enum(["TIMELINE_NOT_CURRENT","TIMELINE_STALE","PRODUCTION_UNAVAILABLE","PLANNING_NOT_READY","CREATIVE_BASIS_CHANGED","NO_CURRENT_ACCEPTED_MEDIA","COMPOSITION_VERSION_UNSUPPORTED"])).max(7)})});var ReviewScope=z31.strictObject({kind:z31.literal("PRODUCTION"),interval:z31.strictObject({startMs:z31.literal(0),endMs:z31.int().positive().max(603e4)}),shotIds:z31.array(z31.uuid()).min(1).max(200),dimensions:z31.array(z31.enum(["PACING","ORDERING","CUT_CONTINUITY","PRODUCT_PRESENTATION","CAPTION_TIMING_VISIBILITY","AUDIO_VISUAL_ALIGNMENT","BASIC_MIX"])).min(4).max(7),requirement:z31.literal("COMPLETE_NEW_OUTPUT_INSPECTION")});var EditorHandoffSchema=z31.discriminatedUnion("kind",[z31.strictObject({kind:z31.literal("TIMELINE_BUILD"),input:BuildTimelineShapeSchema.omit({idempotencyKey:true}),preview:TimelineManifestReaderSchema,assemblyStatus:z31.enum(["DRAFT","ASSEMBLY_READY"]),changedOrdinals:z31.array(z31.int().positive().max(200)).max(200),changedGraphicArtifactIds:z31.array(z31.uuid()).max(8),changedAudioPurposes:z31.array(z31.enum(["VOICEOVER","MUSIC"])).max(2),preservedAcceptanceIds:z31.array(z31.uuid()).max(200),reviewScope:ReviewScope,followUp:z31.array(z31.enum(["NATIVE_TIMELINE_BUILD","COMPLETE_TIMELINE","ROUGH_CUT_RENDER","REVIEW_2","FINAL_READY_DECISION"])).min(4).max(5)}),z31.strictObject({kind:z31.literal("CAPTION_AUTHOR"),input:AuthorCaptionsSchema.omit({idempotencyKey:true}),attachment:z31.strictObject({expectedTimelineVersion:z31.int().positive(),preserveCurrentComposition:z31.literal(true),composition:z31.strictObject({schemaVersion:BuildTimelineShapeSchema.shape.schemaVersion,clips:BuildTimelineSchema.shape.clips,audio:BuildTimelineSchema.shape.audio.optional(),sourceSound:BuildTimelineShapeSchema.shape.sourceSound,graphics:BuildTimelineSchema.shape.graphics.optional(),visualLayers:BuildTimelineShapeSchema.shape.visualLayers})}),followUp:z31.tuple([z31.literal("NATIVE_CAPTION_AUTHOR"),z31.literal("ATTACH_NEW_CAPTION_TO_TIMELINE"),z31.literal("ROUGH_CUT_RENDER"),z31.literal("REVIEW_2"),z31.literal("FINAL_READY_DECISION")])}),z31.strictObject({kind:z31.literal("COMPOSITION_CAPABILITY_INTENT"),concern:z31.enum(["TRANSITION","AUDIO_VISUAL_ALIGNMENT","VOICE_TIMING","CAPTION_RETIMING"]),requestedChange:text2,admission:z31.literal("EXPLICIT_CANONICAL_CAPABILITY_REQUIRED")}),z31.strictObject({kind:z31.literal("HUMAN_INPUT_INTENT"),question:text2})]);var EditorValidationResultSchema=z31.strictObject({semanticStatus:z31.literal("SUCCESS"),advisory:z31.literal(true),basis:EditorBasisSchema,proposal:ValidateEditorProposalSchema.shape.proposal,alternatives:z31.array(z31.strictObject({alternativeId:key6,handoff:EditorHandoffSchema})).min(1).max(6),selectedAlternativeId:key6,limitations:z31.tuple([z31.literal("NO_TIMELINE_WRITE_RENDER_OR_PROVIDER_CALL"),z31.literal("READS_ARE_NOT_ATOMIC_OR_RESERVED"),z31.literal("CREATIVE_RATIONALE_IS_NOT_VERIFIED"),z31.literal("OWNER_RECHECKS_CAS_IDEMPOTENCY_AND_EXECUTION_CLASS"),z31.literal("EDIT_REQUIRES_NEW_OUTPUT_INSPECTION_AND_REVIEW")])});import{z as z32}from"zod";var scope={tenantId:z32.uuid(),productionId:z32.uuid()};var TemporalEvidenceTargetSchema=z32.strictObject({...scope,artifactId:z32.uuid(),representationId:z32.uuid(),checksumSha256:z32.string().regex(/^[0-9a-f]{64}$/)});var OriginalVideoReadSchema=TemporalEvidenceTargetSchema;var OriginalVideoResultSchema=z32.strictObject({source:TemporalEvidenceSourceSchema,contentType:z32.literal("video/mp4"),dataBase64:z32.string().min(4).max(4*Math.ceil(8*1024*1024/3)).regex(/^[A-Za-z0-9+/]+={0,2}$/)}).refine(v=>{const padding=v.dataBase64.endsWith("==")?2:v.dataBase64.endsWith("=")?1:0;return v.dataBase64.length%4===0&&v.source.byteSize<=8*1024*1024&&v.dataBase64.length/4*3-padding===v.source.byteSize},"Original video must match its exact bounded byte size");var TemporalEvidenceStartSchema=TemporalEvidenceTargetSchema.extend({profile:TemporalSamplingProfileSchema,expectedProductionRevision:z32.int().positive(),idempotencyKey:z32.string().trim().min(1).max(128),deviceId:z32.uuid().toLowerCase().optional()});var TemporalEvidenceGetSchema=z32.strictObject({...scope,evidenceId:z32.uuid()});var TemporalEvidenceAdmissionSchema=z32.strictObject({semanticStatus:z32.literal("ACCEPTED"),evidenceId:z32.uuid(),runtimeJobId:z32.uuid(),operationId:z32.string().min(1),source:TemporalEvidenceSourceSchema,planFingerprint:z32.string().regex(/^[0-9a-f]{64}$/),productionRevision:z32.int().positive()});var TemporalEvidenceOutputSchema=z32.strictObject({frameSetArtifactId:z32.uuid(),manifestRepresentationId:z32.uuid(),frameRepresentationIds:z32.array(z32.uuid()).min(1).max(64),contactSheetArtifactId:z32.uuid(),sheetRepresentationId:z32.uuid(),manifest:TemporalEvidenceManifestSchema,createdAt:z32.iso.datetime({offset:true})}).refine(v=>v.frameRepresentationIds.length===v.manifest.frames.length&&new Set(v.frameRepresentationIds).size===v.frameRepresentationIds.length,"Exact frame representations must be complete and unique");var TemporalEvidenceViewSchema=z32.strictObject({evidenceId:z32.uuid(),runtimeJobId:z32.uuid(),operationId:z32.string().min(1),source:TemporalEvidenceSourceSchema,planFingerprint:z32.string().regex(/^[0-9a-f]{64}$/),runtimeState:z32.enum(["PENDING","READY","RUNNING","WAITING","SUCCEEDED","FAILED","CANCELLED","SUPERSEDED"]),output:TemporalEvidenceOutputSchema.nullable()});var TemporalEvidenceMediaSchema=TemporalEvidenceGetSchema.extend({kind:z32.enum(["FRAME","SHEET","MANIFEST"]),ordinal:z32.int().nonnegative().max(63).optional()}).refine(v=>v.kind==="FRAME"?v.ordinal!==void 0:v.ordinal===void 0,"Only individual frames require an ordinal");var TemporalEvidenceImageSchema=TemporalEvidenceMediaSchema.safeExtend({kind:z32.enum(["FRAME","SHEET"])});var TemporalEvidenceImageMetadataSchema=TemporalEvidenceImageSchema.safeExtend({contentType:z32.literal("image/png"),checksumSha256:z32.string().regex(/^[0-9a-f]{64}$/),byteSize:z32.int().positive().max(16*1024*1024)});import{z as z33}from"zod";var Text2=z33.string().trim().min(1).max(1e3);var bounded=(value,bytes)=>new TextEncoder().encode(JSON.stringify(value)).byteLength<=bytes;var ExplorationComparisonCriterionSchema=z33.strictObject({key:ReviewEvidenceKeySchema,description:Text2,modality:z33.enum(["VISUAL","TEMPORAL"])});var ExplorationRecommendationContextInputSchema=ExplorationCompareInputSchema.extend({criteria:z33.array(ExplorationComparisonCriterionSchema).min(1).max(8)}).superRefine((v,c)=>{if(new Set(v.items.map(i=>i.mediaType)).size!==1)c.addIssue({code:"custom",message:"Recommendation compares one media type"});if(new Set(v.items.map(i=>i.label)).size!==v.items.length||new Set(v.items.map(i=>i.generationId.toLowerCase())).size!==v.items.length)c.addIssue({code:"custom",message:"Labels and generation identities must be distinct"});if(new Set(v.criteria.map(i=>i.key)).size!==v.criteria.length)c.addIssue({code:"custom",message:"Comparison criterion keys must be distinct"});if(v.items[0].mediaType==="IMAGE"&&v.criteria.some(i=>i.modality==="TEMPORAL"))c.addIssue({code:"custom",message:"Temporal comparison requires VIDEO"});if(!bounded(v,1024*1024))c.addIssue({code:"custom",message:"Recommendation input exceeds 1 MiB"})});var ExplorationRecommendationBasisSchema=z33.strictObject({input:ExplorationRecommendationContextInputSchema,contextFingerprint:z33.string().regex(/^[0-9a-f]{64}$/)});var ExplorationRecommendationCandidateSchema=z33.strictObject({label:ReviewEvidenceKeySchema,readiness:z33.enum(["REVIEWABLE","UNAVAILABLE"]),reasons:z33.array(z33.enum(["NO_CANDIDATE","STALE_BASIS","PRODUCTION_NOT_RUNNABLE","OUTPUT_NOT_INSPECTABLE"])).max(4),reviewContext:ReviewIntelligenceContextResultSchema.nullable()});var ExplorationRecommendationContextResultSchema=z33.strictObject({semanticStatus:z33.literal("SUCCESS"),advisory:z33.literal(true),basis:ExplorationRecommendationBasisSchema,comparison:ExplorationComparisonResultSchema,candidates:z33.array(ExplorationRecommendationCandidateSchema).min(2).max(6),limitations:z33.tuple([z33.literal("READS_ARE_NOT_ATOMIC_OR_RESERVED"),z33.literal("NO_IMPLICIT_MEDIA_OR_MODEL_CALL")])}).refine(v=>bounded(v,2*1024*1024),"Recommendation context exceeds 2 MiB");var ExplorationComparisonJudgmentSchema=z33.strictObject({label:ReviewEvidenceKeySchema,criterionKey:ReviewEvidenceKeySchema,judgment:z33.enum(["FAVORABLE","UNFAVORABLE","UNCERTAIN","NOT_OBSERVABLE"]),rationale:Text2,evidenceIds:z33.array(ReviewEvidenceKeySchema).max(16)});var ExplorationRecommendationDecisionSchema=z33.discriminatedUnion("kind",[z33.strictObject({kind:z33.literal("RECOMMEND"),label:ReviewEvidenceKeySchema,rationale:Text2,notSelected:z33.array(z33.strictObject({label:ReviewEvidenceKeySchema,reason:Text2})).min(1).max(5)}),z33.strictObject({kind:z33.literal("NO_RECOMMENDATION"),reason:Text2})]);var ValidateExplorationRecommendationSchema=z33.strictObject({basis:ExplorationRecommendationBasisSchema,proposal:z33.strictObject({origin:z33.strictObject({kind:z33.literal("EXTERNAL_AGENT_HOST"),label:z33.string().trim().min(1).max(100)}),summary:z33.string().trim().min(1).max(2e3),assessments:z33.array(z33.strictObject({label:ReviewEvidenceKeySchema,reviewProposal:ValidateReviewIntelligenceSchema.shape.proposal})).max(6),judgments:z33.array(ExplorationComparisonJudgmentSchema).max(48),decision:ExplorationRecommendationDecisionSchema,unknowns:z33.array(z33.string().trim().min(1).max(300)).max(8)})}).refine(v=>bounded(v,1024*1024),"Recommendation input exceeds 1 MiB");var ExplorationRecommendationValidationResultSchema=z33.strictObject({semanticStatus:z33.literal("SUCCESS"),advisory:z33.literal(true),basis:ExplorationRecommendationBasisSchema,origin:ValidateExplorationRecommendationSchema.shape.proposal.shape.origin,summary:z33.string(),judgments:z33.array(ExplorationComparisonJudgmentSchema).max(48),decision:ExplorationRecommendationDecisionSchema,unknowns:z33.array(z33.string()).max(8),reviews:z33.array(z33.strictObject({label:ReviewEvidenceKeySchema,validation:ReviewIntelligenceValidationResultSchema})).max(6),limitations:z33.tuple([z33.literal("HOST_PREFERENCE_IS_NOT_CANONICAL_SELECTION"),z33.literal("EVIDENCE_DECLARATIONS_ARE_NOT_ATTESTED_INSPECTION"),z33.literal("RULE_PREVIEWS_ARE_NOT_CANONICAL_REVIEWS"),z33.literal("EXPLICIT_RECORD_AND_SEPARATE_ACCEPTANCE_REQUIRED"),z33.literal("OWNER_RECHECKS_CURRENTNESS_CAS_AND_EXECUTION_CLASS")])}).refine(v=>bounded(v,4*1024*1024),"Recommendation result exceeds 4 MiB");import{z as z35}from"zod";import{z as z34}from"zod";var Review1FindingSchema=z34.strictObject({id:z34.uuid(),tenantId:TenantIdSchema,projectId:ProjectIdSchema,productionId:ProductionIdSchema,shotId:ShotIdSchema,mediaType:z34.enum(["IMAGE","VIDEO"]),framePurpose:z34.string().max(40).optional(),generationId:z34.uuid(),candidateId:z34.uuid(),reviewId:z34.uuid(),artifactId:z34.uuid(),representationId:z34.uuid(),checksumSha256:z34.string().regex(/^[0-9a-f]{64}$/),preparationId:z34.uuid(),contractId:z34.uuid(),contractFingerprint:z34.string().regex(/^[0-9a-f]{64}$/),executionClass:z34.enum(["LIVE","TEST_ONLY"]),requirement:z34.union([VideoReviewRequirementSchema,VisualRequirementSchema]),observation:z34.union([VideoObservationSchema,KeyframeObservationSchema]),blocking:z34.boolean(),severity:z34.enum(["BLOCKING","WARNING"]),basisFingerprint:z34.string().regex(/^[0-9a-f]{64}$/),createdAt:z34.iso.datetime({offset:true})}).superRefine((v,c)=>{if(v.requirement.key!==v.observation.key||v.blocking!==(v.severity==="BLOCKING"))c.addIssue({code:"custom",message:"Finding must bind its exact native obligation"})});var Review1FindingViewSchema=Review1FindingSchema.safeExtend({lifecycle:z34.enum(["OPEN","REMEDIATION_PLANNED","RESOLVED","SUPERSEDED"]),proofReviewId:z34.uuid().nullable()});var Review1RepairSourceSchema=z34.strictObject(Review1FindingSchema.shape).omit({id:true,createdAt:true}).superRefine((v,c)=>{if(v.requirement.key!==v.observation.key||v.blocking!==(v.severity==="BLOCKING"))c.addIssue({code:"custom",message:"Source must bind its exact native obligation"})});var Review1RepairSourceQuerySchema=z34.strictObject({tenantId:TenantIdSchema,projectId:ProjectIdSchema,productionId:ProductionIdSchema,mediaType:z34.enum(["IMAGE","VIDEO"]),generationId:z34.uuid(),reviewId:z34.uuid(),requirementKey:z34.string().min(1).max(220)});var sha5=z35.string().regex(/^[0-9a-f]{64}$/);var handoffs={REVISE_COMPOSITION:"COMPOSITION_REVISE",TRIM_CLIP:"TIMELINE_BUILD",ADJUST_TRANSITION:"TIMELINE_BUILD",ADJUST_AUDIO_COMPOSITION:"TIMELINE_BUILD",REVISE_CAPTIONS:"CAPTION_AUTHOR",ACKNOWLEDGE_WARNINGS:"FINAL_READY_DECIDE",REGENERATE_SHOT:"REGENERATION_INTENT",REQUEST_HUMAN_INPUT:"HUMAN_INPUT_INTENT",REQUEST_CANONICAL_CHANGE:"CANONICAL_CHANGE_INTENT"};var SemanticRepairBudgetSchema=z35.strictObject({maxSemanticAttempts:z35.int().min(1).max(20),maxElapsedMs:z35.int().min(1).max(864e5),currency:z35.literal("USD"),maxCostMicros:z35.int().min(0).max(1e9),maxConsecutiveNoImprovement:z35.int().min(1).max(20)});var RepairPlanScopeSchema=z35.strictObject({tenantId:TenantIdSchema,productionId:ProductionIdSchema,planId:z35.uuid()});var AuthorRepairPlanSchema=z35.strictObject({strategy:ValidateRepairStrategySchema,expectedProductionRevision:z35.int().positive(),expectedCaseVersion:z35.int().nonnegative(),budget:SemanticRepairBudgetSchema,idempotencyKey:z35.string().trim().min(1).max(200)}).superRefine((v,c)=>{const p=v.strategy.proposal;if(new Set(p.alternatives.map(a=>a.id)).size!==p.alternatives.length||!p.alternatives.some(a=>a.id===p.selectedAlternativeId))c.addIssue({code:"custom",message:"Repair authoring requires unique alternatives and an explicit selection"})});var RepairDecisionSchema=z35.strictObject({id:z35.uuid(),tenantId:TenantIdSchema,projectId:ProjectIdSchema,productionId:ProductionIdSchema,caseId:z35.uuid(),caseVersion:z35.int().positive(),basis:RepairStrategyBasisSchema,sourceReviewId:z35.uuid(),sourceRenderId:z35.uuid().nullable(),review1Source:Review1FindingSchema.optional(),sourceBasisFingerprint:sha5,affectedScopeFingerprint:sha5,obligationFingerprint:sha5,proposal:ValidateRepairStrategySchema.shape.proposal,selectedAlternativeId:z35.string().regex(/^[a-z][a-z0-9_-]{0,39}$/),handoff:RepairStrategyHandoffSchema,budget:SemanticRepairBudgetSchema,createdByPrincipalId:PrincipalIdSchema,createdAt:z35.iso.datetime({offset:true})}).superRefine((d,c)=>{if(d.sourceRenderId===null!==!!d.review1Source||d.review1Source&&(d.review1Source.id!==d.basis.findingId||d.review1Source.reviewId!==d.sourceReviewId||d.review1Source.tenantId!==d.tenantId||d.review1Source.projectId!==d.projectId||d.review1Source.productionId!==d.productionId||d.handoff.kind!=="REGENERATION_INTENT"))c.addIssue({code:"custom",message:"Repair must retain its native Review layer and source"});if(d.basis.scope.tenantId!==d.tenantId||d.basis.scope.productionId!==d.productionId||d.basis.scope.projectId!==d.projectId)c.addIssue({code:"custom",message:"Repair Decision scope must be exactly owned"});if(d.selectedAlternativeId!==d.proposal.selectedAlternativeId||new Set(d.proposal.alternatives.map(a=>a.id)).size!==d.proposal.alternatives.length||!d.proposal.alternatives.some(a=>a.id===d.selectedAlternativeId&&handoffs[a.action.kind]===d.handoff.kind))c.addIssue({code:"custom",message:"Repair Decision must bind the explicit selected alternative"})});var SemanticRepairAttemptSchema=z35.strictObject({id:z35.uuid(),planId:z35.uuid(),caseId:z35.uuid(),ordinal:z35.int().min(1).max(20),executionIdentity:z35.string().trim().min(1).max(200),strategyFingerprint:sha5,startedAt:z35.iso.datetime({offset:true}),reservedCostMicros:z35.int().min(0).max(1e9),chargedCostMicros:z35.int().min(0).max(1e9).nullable(),currency:z35.literal("USD"),outcome:z35.enum(["IN_FLIGHT","AWAITING_REVIEW","IMPROVED","NO_IMPROVEMENT","OPERATIONAL_FAILURE","WAIVED"])});var RecordRepairProofSchema=RepairPlanScopeSchema.extend({attemptId:z35.uuid(),renderId:z35.uuid(),reviewId:z35.uuid(),expectedProductionRevision:z35.int().positive(),idempotencyKey:z35.string().trim().min(1).max(200)});import{z as z36}from"zod";var AuthorReview1RepairSchema=z36.strictObject({tenantId:TenantIdSchema,projectId:ProjectIdSchema,productionId:ProductionIdSchema,mediaType:z36.enum(["IMAGE","VIDEO"]),generationId:z36.uuid(),reviewId:z36.uuid(),requirementKey:z36.string().min(1).max(220),reason:z36.string().trim().min(1).max(2e3),expectedProductionRevision:z36.int().positive(),expectedCaseVersion:z36.int().nonnegative(),budget:SemanticRepairBudgetSchema,idempotencyKey:z36.string().trim().min(1).max(200)});var RecordReview1RepairProofSchema=RepairPlanScopeSchema.extend({attemptId:z36.uuid(),generationId:z36.uuid(),reviewId:z36.uuid(),expectedProductionRevision:z36.int().positive(),idempotencyKey:z36.string().trim().min(1).max(200)});import{z as z37}from"zod";var ExecuteRepairSchema=RepairPlanScopeSchema.extend({expectedProductionRevision:z37.int().positive(),expectedCaseVersion:z37.int().positive(),idempotencyKey:z37.string().trim().min(1).max(200),generation:VideoStartInputSchema.omit({idempotencyKey:true}).optional(),keyframeGeneration:KeyframeStartInputSchema.omit({idempotencyKey:true}).optional()});var RepairAttemptEventSchema=z37.strictObject({id:z37.uuid(),attemptId:z37.uuid(),version:z37.int().positive(),outcome:SemanticRepairAttemptSchema.shape.outcome.exclude(["IN_FLIGHT"]),renderId:z37.uuid().nullable(),reviewId:z37.uuid().nullable(),generationId:z37.uuid().optional(),recordedAt:z37.iso.datetime({offset:true})});var RepairAttemptViewSchema=SemanticRepairAttemptSchema.extend({costQuote:GenerationCostQuoteSchema.optional(),events:z37.array(RepairAttemptEventSchema).max(40)});var RepairCaseViewSchema=z37.strictObject({id:z37.uuid(),version:z37.int().positive(),issueKey:z37.string().regex(/^[0-9a-f]{64}$/),budget:SemanticRepairBudgetSchema,openedAt:z37.iso.datetime({offset:true})});var RepairPlanViewSchema=z37.strictObject({review1Finding:Review1FindingViewSchema.optional(),decision:RepairDecisionSchema,repairCase:RepairCaseViewSchema,attempts:z37.array(RepairAttemptViewSchema).max(20)});var RepairAuthorReceiptSchema=z37.strictObject({semanticStatus:z37.literal("SUCCESS"),decision:RepairDecisionSchema,productionRevision:z37.int().positive()});var RepairExecutionReceiptSchema=z37.strictObject({costQuote:GenerationCostQuoteSchema.optional(),semanticStatus:z37.literal("ACCEPTED"),attempt:SemanticRepairAttemptSchema,decision:RepairDecisionSchema,productionRevision:z37.int().positive(),generation:ExecuteRepairSchema.shape.generation.nullable(),keyframeGeneration:ExecuteRepairSchema.shape.keyframeGeneration.nullable().optional()});var RepairProgressSchema=z37.strictObject({view:RepairPlanViewSchema,stage:z37.enum(["WAITING_INPUT","WAITING_GENERATION","WAITING_COMPOSITION_RENDER","WAITING_SOURCE_ACCEPTANCE","WAITING_RENDER","AWAITING_REVIEW","WAIVED","OPERATIONAL_FAILURE","IMPROVED","NO_IMPROVEMENT"]),renderId:z37.uuid().nullable(),generationId:z37.uuid().nullable()});var RepairProofReceiptSchema=z37.strictObject({semanticStatus:z37.literal("SUCCESS"),event:RepairAttemptEventSchema,productionRevision:z37.int().positive()});import{z as z38}from"zod";var EXTERNAL_EVENT_TYPES=["production.work_changed","production.started","production.failed","production.cancelled","finding.opened","artifact.created","shot.candidate_ready","shot.accepted","review.completed","rough_cut.ready","final_render.ready","approval.required","production.completed","delivery.validation_failed"];var ExternalEventTypeSchema=z38.enum(EXTERNAL_EVENT_TYPES);var LifecycleEventScopeSchema=z38.object({tenantId:TenantIdSchema,productionId:ProductionIdSchema}).strict();var ExternalLifecycleEventSchema=z38.object({schemaVersion:z38.literal(1),eventId:z38.uuid(),tenantId:TenantIdSchema,productionId:ProductionIdSchema,projectId:z38.uuid(),type:ExternalEventTypeSchema,target:z38.object({type:z38.string().min(1).max(60),id:z38.uuid()}).strict(),occurredAt:z38.iso.datetime(),basis:z38.object({productionRevision:z38.number().int().positive()}).strict(),payload:z38.object({sourceEventType:z38.string().min(1).max(100),artifactId:z38.uuid().optional(),candidateId:z38.uuid().optional(),reviewId:z38.uuid().optional(),findingId:z38.uuid().optional(),shotId:z38.uuid().optional(),manifestId:z38.uuid().optional(),validationId:z38.uuid().optional(),action:z38.string().max(40).optional(),result:z38.string().max(40).optional(),executionClass:z38.enum(["LIVE","TEST_ONLY"]).optional()}).strict()}).strict();var WebhookEndpointSchema=z38.url().max(2048).refine(value=>{const u=new URL(value);return u.protocol==="https:"&&!u.username&&!u.password&&!u.hash&&(!u.port||u.port==="443")&&!u.hostname.startsWith("[")});var ConfigureWebhookSchema=LifecycleEventScopeSchema.extend({subscriptionId:z38.uuid(),expectedRevision:z38.number().int().nonnegative(),idempotencyKey:z38.string().min(1).max(128),endpoint:WebhookEndpointSchema,eventTypes:z38.array(ExternalEventTypeSchema).min(1).max(EXTERNAL_EVENT_TYPES.length).refine(v=>new Set(v).size===v.length),signingSecret:z38.string().min(32).max(256)}).strict();var PrepareWebhookSecretSchema=LifecycleEventScopeSchema.extend({subscriptionId:z38.uuid(),secretRef:z38.uuid(),signingSecret:z38.string().min(32).max(256)}).strict();var WebhookSecretReferenceSchema=PrepareWebhookSecretSchema.omit({signingSecret:true});var ConfigureWebhookReferenceSchema=ConfigureWebhookSchema.omit({signingSecret:true}).extend({secretRef:z38.uuid()}).strict();var WebhookAvailabilitySchema=z38.discriminatedUnion("status",[z38.strictObject({status:z38.literal("AVAILABLE"),reason:z38.literal("SIGNING_STORAGE_READY")}),z38.strictObject({status:z38.literal("UNCONFIGURED"),reason:z38.literal("SIGNING_STORAGE_NOT_CONFIGURED")}),z38.strictObject({status:z38.literal("UNAVAILABLE"),reason:z38.literal("SIGNING_STORAGE_UNAVAILABLE")})]);var DisableWebhookSchema=LifecycleEventScopeSchema.extend({subscriptionId:z38.uuid(),expectedRevision:z38.number().int().positive(),idempotencyKey:z38.string().min(1).max(128)}).strict();var ReplayWebhookSchema=DisableWebhookSchema.extend({eventId:z38.uuid()}).strict();var QueryLifecycleEventsSchema=LifecycleEventScopeSchema.extend({kind:z38.enum(["subscriptions","events","deliveries","attempts"]),subscriptionId:z38.uuid().optional(),deliveryId:z38.uuid().optional(),after:z38.uuid().optional(),limit:z38.number().int().min(1).max(50).default(20)}).strict().refine(v=>v.kind!=="attempts"||!!v.deliveryId);var WebhookSubscriptionSchema=LifecycleEventScopeSchema.extend({subscriptionId:z38.uuid(),version:z38.number().int().positive(),revision:z38.number().int().positive(),state:z38.enum(["ACTIVE","DISABLED","DEGRADED"]),endpoint:WebhookEndpointSchema,eventTypes:z38.array(ExternalEventTypeSchema),updatedAt:z38.iso.datetime()}).strict();import{z as z39}from"zod";var WebhookReplayReceiptSchema=z39.strictObject({deliveryId:z39.uuid(),eventId:z39.uuid(),runtimeJobId:z39.uuid()});var WebhookDeliveryViewSchema=z39.strictObject({deliveryId:z39.uuid(),eventId:z39.uuid(),subscriptionId:z39.uuid(),subscriptionVersion:z39.int().positive(),replayNumber:z39.int().nonnegative(),runtimeJobId:z39.uuid(),lifecycle:z39.enum(["PENDING","READY","RUNNING","WAITING","SUCCEEDED","FAILED","CANCELLED","SUPERSEDED"]),runtimeAttempts:z39.int().nonnegative(),wakeAt:z39.iso.datetime({offset:true}).nullable()});var WebhookAttemptViewSchema=z39.strictObject({attemptId:z39.uuid(),runtimeAttemptId:z39.uuid(),outcome:z39.enum(["STARTED","ACKNOWLEDGED","TRANSIENT","PERMANENT","SKIPPED"]),responseStatus:z39.int().min(100).max(599).nullable(),startedAt:z39.iso.datetime({offset:true}),endedAt:z39.iso.datetime({offset:true}).nullable()});var page={next:z39.uuid().nullable()};var WebhookSubscriptionPageSchema=z39.strictObject({...page,items:z39.array(WebhookSubscriptionSchema).max(50)});var ExternalLifecycleEventPageSchema=z39.strictObject({...page,items:z39.array(ExternalLifecycleEventSchema).max(50)});var WebhookDeliveryPageSchema=z39.strictObject({...page,items:z39.array(WebhookDeliveryViewSchema).max(50)});var WebhookAttemptPageSchema=z39.strictObject({...page,items:z39.array(WebhookAttemptViewSchema).max(50)});var LifecycleEventCapabilitiesSchema=z39.strictObject({configuration:WebhookAvailabilitySchema,readinessScope:z39.literal("CURRENT_PROCESS_SIGNING_STORAGE"),deliveryConfirmation:z39.literal("READ_NATIVE_DELIVERIES_AND_ATTEMPTS"),eventTypes:z39.array(ExternalEventTypeSchema).max(14),unavailableNativeEvents:z39.array(z39.enum(["production.failed","production.cancelled","finding.opened"])).max(3),delivery:z39.literal("AT_LEAST_ONCE"),payload:z39.literal("QUERY_NOTIFICATION"),scope:z39.literal("PRODUCTION"),automaticOutboundAttempts:z39.literal(3),manualReplaysPerEvent:z39.literal(3),projectOnlyArtifacts:z39.literal("UNAVAILABLE"),orderingGuaranteed:z39.literal(false),signature:z39.literal("HMAC_SHA256_TIMESTAMP_DOT_EXACT_BODY")});import{z as z40}from"zod";var sha6=z40.string().regex(/^[0-9a-f]{64}$/);var CompositionSourceInspectSchema=CompositionGetSchema.extend({versionId:z40.uuid(),fingerprint:sha6,file:CompositionPathSchema.optional(),startLine:z40.int().min(1).max(8388609).default(1),lineLimit:z40.int().min(1).max(200).default(80)});var CompositionSourceInspectionSchema=z40.strictObject({composition:CompositionViewSchema,source:CompositionInputFactSchema,byteReadback:z40.literal("VERIFIED"),selection:z40.strictObject({file:CompositionPathSchema.nullable(),startLine:z40.int().positive(),lineLimit:z40.int().min(1).max(200)}),files:z40.array(z40.strictObject({path:CompositionPathSchema,contentType:z40.string().max(80),byteSize:z40.int().nonnegative().max(8388608),lineCount:z40.int().positive().max(8388609)})).min(1).max(128),window:z40.strictObject({file:CompositionPathSchema,startLine:z40.int().positive(),lines:z40.array(z40.strictObject({number:z40.int().positive(),text:z40.string().max(65536)})).max(200),hasMore:z40.boolean(),nextLine:z40.int().positive().nullable()}).nullable(),limitations:z40.tuple([z40.literal("SOURCE_INSPECTION_IS_NOT_OUTPUT_REVIEW"),z40.literal("READS_ARE_NOT_ATOMIC_OR_RESERVED")])});var SourceReviewContextInputSchema=z40.strictObject({scope:DirectorScopeSchema,source:CompositionSourceInspectSchema,renderId:z40.uuid().optional()}).refine(i=>i.scope.tenantId===i.source.tenantId&&i.scope.productionId===i.source.productionId,"Source Review retains exact Tenant/Production scope");var SourceReviewContextSchema=z40.strictObject({semanticStatus:z40.literal("SUCCESS"),advisory:z40.literal(true),basis:z40.strictObject({input:SourceReviewContextInputSchema,contextFingerprint:sha6}),ownerContext:DirectorContextResultSchema,source:CompositionSourceInspectionSchema,render:CompositionRenderViewSchema.nullable(),outputReviewTarget:ProgrammaticVideoReviewTargetSchema.nullable(),limitations:z40.tuple([z40.literal("SOURCE_REASONING_DOES_NOT_CERTIFY_OUTPUT_QUALITY"),z40.literal("INDEPENDENT_OUTPUT_REVIEW_AND_ACCEPTANCE_REQUIRED"),z40.literal("READS_ARE_NOT_ATOMIC_OR_RESERVED")])});import{z as z41}from"zod";var key7=z41.string().regex(/^[a-z][a-z0-9_-]{0,39}$/);var ProgrammaticCompareSchema=z41.strictObject({scope:ExplorationScopeSchema,items:z41.array(z41.strictObject({label:key7,renderId:z41.uuid()})).min(2).max(6)}).superRefine((i,c)=>{if(new Set(i.items.map(v=>v.label)).size!==i.items.length||new Set(i.items.map(v=>v.renderId.toLowerCase())).size!==i.items.length)c.addIssue({code:"custom",message:"Programmatic labels and exact renders must be distinct"})});var ProgrammaticComparisonSchema=z41.strictObject({semanticStatus:z41.literal("SUCCESS"),advisory:z41.literal(true),scope:ExplorationScopeSchema,selection:ProgrammaticCompareSchema.shape.items,items:z41.array(z41.strictObject({label:key7,sourceKind:z41.literal("PROGRAMMATIC"),composition:CompositionViewSchema,render:CompositionRenderViewSchema,reviewTarget:ProgrammaticVideoReviewTargetSchema.nullable()})).min(2).max(6),limitations:z41.tuple([z41.literal("OWNER_STATES_ARE_NOT_VISUAL_SCORES"),z41.literal("REVIEW_AND_ACCEPTANCE_REMAIN_EXPLICIT")])}).superRefine((v,c)=>{if(v.items.length!==v.selection.length||v.items.some((item,i)=>item.label!==v.selection[i].label||item.render.receipt.renderId!==v.selection[i].renderId))c.addIssue({code:"custom",message:"Programmatic comparison retains every exact selected label/render"});for(const item of v.items){const owner=item.composition.version,target2=item.reviewTarget;if(owner.tenantId!==v.scope.tenantId||owner.projectId!==v.scope.projectId||owner.productionId!==v.scope.productionId||owner.basis.shotId!==v.scope.shotId||owner.content.role!=="PRIMARY_VISUAL"||owner.id!==item.render.receipt.compositionVersionId||target2&&(target2.renderId!==item.render.receipt.renderId||target2.compositionVersionId!==owner.id||target2.tenantId!==v.scope.tenantId||target2.projectId!==v.scope.projectId||target2.productionId!==v.scope.productionId||target2.shotId!==v.scope.shotId))c.addIssue({code:"custom",message:"Programmatic comparison retains exact native source/output scope"})}}).refine(i=>new TextEncoder().encode(JSON.stringify(i)).byteLength<=2*1024*1024,"Programmatic comparison exceeds2MiB");var ProgrammaticRecommendationContextInputSchema=ProgrammaticCompareSchema.safeExtend({criteria:z41.array(ExplorationComparisonCriterionSchema).min(1).max(8)}).refine(i=>new Set(i.criteria.map(v=>v.key)).size===i.criteria.length,"Criteria must be distinct");var ProgrammaticRecommendationBasisSchema=z41.strictObject({input:ProgrammaticRecommendationContextInputSchema,contextFingerprint:z41.string().regex(/^[0-9a-f]{64}$/)});var ProgrammaticRecommendationContextSchema=z41.strictObject({semanticStatus:z41.literal("SUCCESS"),advisory:z41.literal(true),basis:ProgrammaticRecommendationBasisSchema,comparison:ProgrammaticComparisonSchema,candidates:z41.array(ExplorationRecommendationCandidateSchema).min(2).max(6),limitations:z41.tuple([z41.literal("READS_ARE_NOT_ATOMIC_OR_RESERVED"),z41.literal("NO_IMPLICIT_MEDIA_OR_MODEL_CALL")])}).superRefine((v,c)=>{if(JSON.stringify(v.basis.input.scope)!==JSON.stringify(v.comparison.scope)||JSON.stringify(v.basis.input.items)!==JSON.stringify(v.comparison.selection)||v.candidates.length!==v.comparison.items.length||v.candidates.some((candidate,i)=>candidate.label!==v.comparison.items[i].label))c.addIssue({code:"custom",message:"Programmatic Recommendation keeps exact comparison scope/selection"});for(const candidate of v.candidates){const target2=candidate.reviewContext?.reviewTarget;const item=v.comparison.items.find(i=>i.label===candidate.label);if(target2&&(target2.kind!=="PROGRAMMATIC"||target2.target.renderId!==item?.render.receipt.renderId||target2.target.compositionVersionId!==item.composition.version.id))c.addIssue({code:"custom",message:"Candidate assessment binds the exact native CODE output"})}}).refine(i=>new TextEncoder().encode(JSON.stringify(i)).byteLength<=2*1024*1024,"Programmatic recommendation context exceeds2MiB");var ValidateProgrammaticRecommendationSchema=z41.strictObject({basis:ProgrammaticRecommendationBasisSchema,proposal:ValidateExplorationRecommendationSchema.shape.proposal}).refine(i=>new TextEncoder().encode(JSON.stringify(i)).byteLength<=1024*1024,"Programmatic recommendation input exceeds1MiB");var ProgrammaticRecommendationValidationSchema=z41.strictObject({...ExplorationRecommendationValidationResultSchema.shape,basis:ProgrammaticRecommendationBasisSchema}).superRefine((v,c)=>{const s=v.basis.input.scope;for(const assessment of v.reviews){const item=v.basis.input.items.find(i=>i.label===assessment.label),draft=assessment.validation.recordDraft;if(!item||draft.kind!=="PROGRAMMATIC"||draft.input.renderId!==item.renderId||draft.input.tenantId!==s.tenantId||draft.input.productionId!==s.productionId||assessment.validation.basis.scope.projectId!==s.projectId)c.addIssue({code:"custom",message:"Recommendation review draft binds exact CODE output and scope"})}}).refine(i=>new TextEncoder().encode(JSON.stringify(i)).byteLength<=4*1024*1024,"Programmatic recommendation result exceeds4MiB");import{z as z42}from"zod";var CompositionRenderQuerySchema=CompositionScopeSchema.extend({limit:z42.int().min(1).max(24).default(12),next:ContinuationSchema.optional(),shotId:z42.uuid().optional(),role:z42.enum(["PRIMARY_VISUAL","VISUAL_LAYER"]).default("PRIMARY_VISUAL")});var CompositionRenderObservationSchema=z42.strictObject({render:CompositionRenderViewSchema,createdAt:z42.iso.datetime({offset:true}),version:z42.int().positive(),executionClass:z42.enum(["LIVE","TEST_ONLY"]),freshness:z42.enum(["CURRENT_BASIS","STALE_BASIS"]),available:z42.boolean(),review:z42.strictObject({result:z42.enum(["UNREVIEWED","PASS","WARNING","FAIL"]),reviewId:z42.uuid().nullable(),acceptanceId:z42.uuid().nullable(),accepted:z42.boolean()})}).superRefine((v,ctx)=>{if(!v.render.sourceIdentity||v.review.result==="UNREVIEWED"!==(v.review.reviewId===null)||v.review.accepted!==(v.review.acceptanceId!==null)||v.review.accepted&&(!v.review.acceptanceId||!v.review.reviewId||!v.available||v.freshness!=="CURRENT_BASIS"||!["PASS","WARNING"].includes(v.review.result)))ctx.addIssue({code:"custom",message:"Observation requires exact native source/Review/acceptance identity"})});var CompositionRenderPageSchema=z42.strictObject({items:z42.array(CompositionRenderObservationSchema).max(24),page:QueryPageInfoSchema}).refine(v=>new TextEncoder().encode(JSON.stringify(v)).byteLength<=4194304,"Render observation page exceeds 4 MiB");var CompositionRenderMediaDescriptorSchema=z42.strictObject({path:z42.string().regex(/^\/v1\/productions\/[0-9a-f-]{36}\/compositions\/renders\/[0-9a-f-]{36}\/media$/i),contentType:z42.literal("video/mp4"),checksumSha256:z42.string().regex(/^[0-9a-f]{64}$/),byteSize:z42.int().positive().max(134217728),authentication:z42.literal("BEARER_AND_TENANT_HEADER")});import{z as z43}from"zod";var CompositionSampleStartSchema=CompositionRenderGetSchema.extend({expectedProductionRevision:z43.int().positive(),profile:TemporalSamplingProfileSchema,idempotencyKey:z43.string().trim().min(1).max(128)});var CompositionObserveGetSchema=CompositionRenderGetSchema.extend({evidenceId:z43.uuid()});var RenderObservationIdentitySchema=z43.strictObject({renderId:z43.uuid(),compositionVersionId:z43.uuid(),artifactId:z43.uuid(),representationId:z43.uuid(),checksumSha256:z43.string().regex(/^[0-9a-f]{64}$/)});var CompositionSampleReceiptSchema=RenderObservationIdentitySchema.extend({evidence:TemporalEvidenceAdmissionSchema,nextActions:z43.tuple([z43.literal("READ_OBSERVATION")])});var CompositionFrameObservationSchema=z43.strictObject({ordinal:z43.int().nonnegative().max(63),frameIndex:z43.int().nonnegative().max(3599),timestampMs:z43.number().nonnegative().max(6e4),checksumSha256:z43.string().regex(/^[0-9a-f]{64}$/),representationId:z43.uuid(),diagnostic:z43.literal("FRAME_EVIDENCE_READY")});var CompositionObservationViewSchema=RenderObservationIdentitySchema.extend({evidence:TemporalEvidenceViewSchema,frames:z43.array(CompositionFrameObservationSchema).max(64),contactSheetArtifactId:z43.uuid().nullable(),nextActions:z43.array(z43.enum(["READ_OBSERVATION","READ_FRAME_MEDIA","REVISE_COMPOSITION","RENDER_REVISION"])).min(1).max(4)});var scope2={projectId:ProjectIdSchema,productionId:ProductionIdSchema};var ScopedAcceptBriefSchema=AcceptBriefRequestSchema.extend(scope2);var ScopedAcceptStorySchema=AcceptStoryRequestSchema.extend(scope2);var ScopedAcceptSceneShotPlanSchema=AcceptSceneShotPlanRequestSchema.extend(scope2);import{z as z44}from"zod";var id5=z44.uuid();var ActivateAgentExecutionSchema=AgentHostScopeSchema.extend({profileKey:z44.string().regex(/^[A-Za-z0-9_-]{1,160}$/),requestId:id5,bindingId:id5,expectedBindingRevision:z44.int().positive(),expectedConfigurationVersion:z44.int().positive(),clientId:id5,grantRef:id5,installationRevisionId:z44.string().regex(/^[A-Za-z0-9_-]{1,160}$/)});var AgentExecutionSelectionSchema=z44.strictObject({registration:AgentExecutionRegistrationViewSchema,grant:AgentExecutionGrantSchema,installationRevisionId:z44.string().regex(/^[A-Za-z0-9_-]{1,160}$/)}).refine(v=>v.grant.clientId===v.registration.clientId&&v.grant.registrationRevision===v.registration.registration.registrationRevision&&v.grant.resource===v.registration.registration.resource);import{z as z45}from"zod";var NativeToolAuthorityFailureSchema=z45.strictObject({semanticStatus:z45.enum(["INVALID_INPUT","NOT_FOUND","BLOCKED","REVISION_CONFLICT","CAPABILITY_UNAVAILABLE","INTERNAL_OPERATIONAL_FAILURE"]),error:z45.strictObject({code:z45.enum(["INVALID_INPUT","UNAUTHENTICATED","FORBIDDEN","NOT_FOUND","BINDING_UNAVAILABLE","REQUEST_CONFLICT","REVISION_CONFLICT","GRANT_CONFLICT","GRANT_EXPIRED","GRANT_REVOKED","PROOF_INVALID","PROOF_REPLAY","CHALLENGE_EXPIRED","PERMIT_UNAVAILABLE","QUALIFICATION_UNAVAILABLE","CREDENTIAL_INVALID","CREDENTIAL_EXPIRED","CREDENTIAL_UNAVAILABLE","CREDENTIAL_LIMIT","HOST_RUN_UNAVAILABLE","INTERNAL_OPERATIONAL_FAILURE"]),message:z45.literal("Native tool authority operation did not complete")})});import{z as z46}from"zod";var NativeToolGatewayDescriptorSchema=z46.strictObject({name:z46.string().regex(/^[a-z][a-z0-9_]{0,99}$/),inputSchemaFingerprint:z46.string().regex(/^[a-f0-9]{64}$/),scope:z46.enum(["PRODUCTION","PROJECT_READ"]),readOnly:z46.boolean()});var NativeToolGatewayManifestSchema=z46.strictObject({protocol:z46.literal("NATIVESTUDIO_NATIVE_MCP_V1"),policy:z46.literal("NVS_PROJECT_READ_PRODUCTION_WRITE_V1"),tools:z46.array(NativeToolGatewayDescriptorSchema).min(1).max(256)}).refine(v=>v.tools.every((tool,index)=>index===0||v.tools[index-1].name<tool.name));var NativeToolGatewayContractSchema=z46.strictObject({manifest:NativeToolGatewayManifestSchema,capabilityDigest:z46.string().regex(/^[a-f0-9]{64}$/)});import{z as z47}from"zod";var id6=z47.uuid().regex(/^[0-9a-f-]{36}$/);var sha7=z47.string().regex(/^[a-f0-9]{64}$/);var key8=z47.string().regex(/^[A-Za-z0-9_-]{1,160}$/);var NativeRuntimeQualificationSchema=z47.strictObject({protocol:z47.literal("NATIVESTUDIO_RUNTIME_TOOLS_V1"),runtimeKey:key8,installationId:key8,installationRevisionId:key8,resource:z47.url().max(2048),publicKeyFingerprint:sha7,bindingId:id6,configurationVersion:z47.int().positive(),selection:AgentHostSelectionSchema,capabilityDigest:sha7,executionClass:z47.enum(["LIVE","TEST_ONLY"]),transport:AgentHostInstallationTransportSchema.optional()});var NativeToolPermitSchema=z47.strictObject({proof:AgentHostNativeToolAuthoritySchema,input:AgentHostExecutionInputSchema,grant:NativeToolGrantViewSchema,qualification:NativeRuntimeQualificationSchema,requestedByPrincipalId:id6,createdAt:z47.iso.datetime({offset:true})}).refine(v=>v.proof.tenantId===v.input.tenantId&&v.proof.projectId===v.input.projectId&&v.proof.productionId===v.input.productionId&&v.proof.executionId===v.input.executionId&&v.proof.hostRequestId===v.input.hostRequestId&&v.grant.tenantId===v.input.tenantId&&v.grant.projectId===v.input.projectId&&v.grant.enabled&&v.grant.verifiedAt!==null&&v.proof.bindingId===v.grant.bindingId&&v.proof.configurationVersion===v.grant.configurationVersion&&v.qualification.runtimeKey===v.grant.runtimeKey&&v.qualification.installationId===v.grant.installationId&&v.qualification.installationRevisionId===v.grant.installationRevisionId&&v.qualification.resource===v.grant.resource&&v.qualification.bindingId===v.grant.bindingId&&v.qualification.configurationVersion===v.grant.configurationVersion&&v.qualification.capabilityDigest===v.proof.capabilityDigest&&v.qualification.executionClass===v.proof.executionClass&&(v.proof.transport===void 0?v.qualification.transport===void 0:v.qualification.transport?.protocol===v.proof.transport.protocol&&v.qualification.transport.installationId===v.proof.transport.installationId&&v.qualification.transport.installationRevisionId===v.proof.transport.installationRevisionId&&v.qualification.transport.slotKey===v.proof.transport.slotKey&&(v.proof.transport.protocol!=="AGENT_STACK_GENERIC_INSTALLATION_V3"||v.qualification.transport.protocol==="AGENT_STACK_GENERIC_INSTALLATION_V3"&&v.qualification.transport.contractDigest===v.proof.transport.contractDigest&&v.qualification.transport.capabilityDigest===v.proof.transport.capabilityDigest)&&v.proof.transport.installationId===v.grant.installationId&&v.proof.transport.installationRevisionId===v.grant.installationRevisionId)&&Date.parse(v.proof.expiresAt)<=Date.parse(v.grant.expiresAt));var NativeToolPermitGetSchema=AgentHostExecutionScopeSchema.extend({authorityRef:id6});var NativeExecutionProofClaimsSchema=AgentHostExecutionScopeSchema.extend({iss:key8,sub:key8,aud:z47.url().max(2048),grantId:id6,grantRevision:z47.int().positive(),installationRevisionId:key8,authorityRef:id6,executionId:id6,hostRequestId:id6,inputFingerprint:sha7,runKey:key8,jti:id6,iat:z47.int().nonnegative(),exp:z47.int().positive()}).refine(v=>v.exp>v.iat&&v.exp-v.iat<=60);var NativeToolCredentialExchangeSchema=NativeToolPermitGetSchema.extend({assertion:z47.string().regex(/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/).max(8192).meta({writeOnly:true})});var NativeToolCredentialMetadataSchema=NativeToolPermitGetSchema.extend({protocol:z47.literal("NATIVESTUDIO_NATIVE_CREDENTIAL_V1"),tokenId:id6,grantId:id6,grantRevision:z47.int().positive(),executionId:id6,hostRequestId:id6,runKey:key8,jti:id6,assertionFingerprint:sha7,tokenFingerprint:sha7,issuedAt:z47.iso.datetime({offset:true}),expiresAt:z47.iso.datetime({offset:true})});var NativeToolCredentialReplySchema=z47.strictObject({tokenType:z47.literal("Bearer"),accessToken:z47.string().regex(/^nvst_[0-9a-f-]{36}\.[A-Za-z0-9_-]{43}$/).meta({readOnly:true}),tokenId:id6,resource:z47.url().max(2048),expiresAt:z47.iso.datetime({offset:true})}).refine(v=>v.accessToken.startsWith(`nvst_${v.tokenId}.`));var NativeToolSessionSchema=NativeToolPermitGetSchema.extend({authorityProtocol:z47.literal("NVS_GENERIC_EXECUTION_V1").optional(),tokenId:id6,executionId:id6,hostRequestId:id6,grantId:id6,grantRevision:z47.int().positive(),runKey:key8,runtimePrincipalId:id6,approvedByPrincipalId:id6,requestedByPrincipalId:id6,capabilityDigest:sha7,resource:z47.url().max(2048),issuer:z47.url().max(2048),subject:z47.string().max(200),executionClass:z47.enum(["LIVE","TEST_ONLY"]),expiresAt:z47.iso.datetime({offset:true})});import{z as z48}from"zod";var CreateProductionRequestSchema=z48.strictObject({tenantId:TenantIdSchema,projectId:ProjectIdSchema,idempotencyKey:z48.string().trim().min(1).max(200)});var CreatedProductionResultSchema=CreatedProjectResultSchema;import{z as z49}from"zod";var sha8=z49.string().regex(/^[0-9a-f]{64}$/);var WavExportResultSchema=z49.strictObject({contentType:z49.literal("audio/wav"),checksumSha256:sha8,byteSize:z49.int().min(44).max(12582912),contentBase64:z49.string().min(60).max(16777216).regex(/^[A-Za-z0-9+/]+={0,2}$/)});var AudioExportResultSchema=WavExportResultSchema.extend({representationId:z49.uuid()});var CaptionExportResultSchema=z49.strictObject({contentType:z49.enum(["application/json","application/x-subrip"]),checksumSha256:sha8,representationId:z49.uuid(),text:z49.string().min(1).max(131072)});import{z as z50}from"zod";var tenant=TenantIdSchema.transform(v=>v.toLowerCase());var project=ProjectIdSchema.transform(v=>v.toLowerCase());var production=ProductionIdSchema.transform(v=>v.toLowerCase());var artifact=ArtifactIdSchema.transform(v=>v.toLowerCase());var representation=ArtifactRepresentationIdSchema.transform(v=>v.toLowerCase());var DiscoverableArtifactFamilySchema=z50.enum(["SOURCE","KEYFRAME_CANDIDATE","SHOT_CANDIDATE","COMPOSITION_RENDER_OUTPUT","ROUGH_CUT","FINAL_RENDER_OUTPUT","IMPORTED_VISUAL_ORIGINAL","IMPORTED_VISUAL_NORMALIZED","IMPORTED_VISUAL_POSTER","AUDIO","AUDIO_SOURCE_SYNC","CAPTION","CONTACT_SHEET"]);var DiscoveryContentTypeSchema=MediaBrowserContentTypeSchema;var ArtifactDiscoveryQuerySchema=z50.strictObject({tenantId:tenant,projectId:project.optional(),productionId:production.optional(),artifactId:artifact.optional(),mediaCategory:MediaCategorySchema.optional(),family:DiscoverableArtifactFamilySchema.optional(),search:z50.string().trim().min(1).max(200).optional(),lifecycle:z50.enum(["READY","ARCHIVED"]).default("READY"),limit:QueryLimitSchema,next:ContinuationSchema.optional()});var ArtifactDiscoveryMediaSchema=z50.strictObject({tenantId:tenant,projectId:project,artifactId:artifact,representationId:representation});var ArtifactMediaTicketRequestSchema=ArtifactDiscoveryMediaSchema.extend({download:z50.boolean().optional()});var ArtifactMediaTicketSchema=ArtifactDiscoveryMediaSchema.extend(MediaBrowserReadTicketSchema.shape);var ArtifactDiscoveryItemSchema=z50.strictObject({humanLinks:HumanLinksSchema.optional(),artifactId:ArtifactIdSchema,projectId:ProjectIdSchema,projectName:z50.string().min(1).max(500),projectLifecycle:ProjectSchema.shape.lifecycle.nullable().default(null),productionId:ProductionIdSchema.nullable(),representationId:ArtifactRepresentationIdSchema,family:DiscoverableArtifactFamilySchema,lifecycle:z50.enum(["READY","ARCHIVED"]),origin:z50.string().min(1).max(120),contentType:DiscoveryContentTypeSchema,checksumSha256:z50.string().regex(/^[a-f0-9]{64}$/),byteSize:z50.int().positive(),width:z50.int().positive().nullable(),height:z50.int().positive().nullable(),durationMs:z50.int().nonnegative().nullable(),createdAt:z50.iso.datetime({offset:true}),originalName:z50.string().max(255).nullable(),sourceKind:SourceLibraryItemSchema.shape.kind.nullable().default(null),executionClass:z50.enum(["LIVE","TEST_ONLY","UNKNOWN"]),mediaAvailable:z50.boolean(),sourceVersionId:z50.uuid().nullable(),normalizationId:z50.uuid().nullable()});var ArtifactDiscoveryPageSchema=z50.strictObject({items:z50.array(ArtifactDiscoveryItemSchema).max(100),page:QueryPageInfoSchema});import{z as z51}from"zod";var ExternalGrantQuerySchema=z51.strictObject({tenantId:z51.uuid()});var ExternalGrantPageSchema=z51.strictObject({items:z51.array(z51.strictObject({grantId:z51.uuid(),displayName:z51.string().max(100),scopes:z51.array(z51.enum(["nvs:read","nvs:write"])).min(1).max(2),expiresAt:z51.iso.datetime()})).max(100),possiblyTruncated:z51.boolean()});var ExternalAccessScopeSchema=z51.enum(["nvs:read","nvs:write"]);var ExternalAgentScopeSchema=z51.strictObject({tenantId:z51.uuid()});var redirect=z51.string().min(1).max(2048).superRefine((value,ctx)=>{try{const u=new URL(value);if(u.username||u.password||u.hash||!(u.protocol==="https:"||u.protocol==="http:"&&["127.0.0.1","[::1]"].includes(u.hostname)||u.protocol==="workbuddy:"))throw Error()}catch{ctx.addIssue({code:"custom",message:"Invalid registered callback"})}});var RegisterExternalClientSchema=ExternalAgentScopeSchema.extend({displayName:z51.string().trim().min(1).max(100),redirectUris:z51.array(redirect).min(1).max(16).refine(v=>new Set(v).size===v.length)});var DynamicExternalClientSchema=z51.object({client_name:z51.string().trim().min(1).max(100).default("External MCP client"),redirect_uris:z51.array(redirect).min(1).max(16).refine(v=>new Set(v).size===v.length),token_endpoint_auth_method:z51.literal("none").default("none"),grant_types:z51.array(z51.enum(["authorization_code","refresh_token"])).min(1).max(2).optional(),response_types:z51.array(z51.literal("code")).length(1).optional(),application_type:z51.enum(["native","web"]).optional()});var ExternalAuthorizationSchema=z51.strictObject({response_type:z51.literal("code"),client_id:z51.uuid(),redirect_uri:redirect,resource:z51.url().max(2048),scope:z51.string().max(100).refine(value=>{const scopes=value.split(" ");return scopes.includes("nvs:read")&&new Set(scopes).size===scopes.length&&scopes.every(s=>ExternalAccessScopeSchema.safeParse(s).success)}),state:z51.string().min(16).max(1024),code_challenge:z51.string().regex(/^[A-Za-z0-9_-]{43}$/),code_challenge_method:z51.literal("S256")});var commonToken={client_id:z51.uuid(),resource:z51.url().max(2048)};var ExternalTokenRequestSchema=z51.discriminatedUnion("grant_type",[z51.strictObject({...commonToken,grant_type:z51.literal("authorization_code"),code:z51.string().regex(/^nvsc_[A-Za-z0-9_-]{43}$/),redirect_uri:redirect,code_verifier:z51.string().regex(/^[A-Za-z0-9._~-]{43,128}$/)}),z51.strictObject({...commonToken,grant_type:z51.literal("refresh_token"),refresh_token:z51.string().regex(/^nvsr_[A-Za-z0-9_-]{43}$/)})]);var ExternalRevocationSchema=z51.strictObject({client_id:z51.uuid(),token:z51.string().regex(/^(nvsa_|nvsr_)[A-Za-z0-9_-]{43}$/),token_type_hint:z51.enum(["access_token","refresh_token"]).optional()});import{z as z52}from"zod";var WorkspaceScopeSchema=z52.strictObject({tenantId:TenantIdSchema});var WorkspaceViewSchema=HumanTenantSchema;var skillUrl=z52.url().max(4096).refine(value=>{try{const u=new URL(value);return value===value.trim()&&![...value].some(c=>c.charCodeAt(0)<=32||c.charCodeAt(0)===127)&&!u.username&&!u.password&&!/[?#]/.test(value)&&(u.protocol==="https:"||u.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(u.hostname))}catch{return false}});var PublicDownloadDescriptorSchema=z52.discriminatedUnion("status",[z52.strictObject({status:z52.literal("AVAILABLE"),url:skillUrl}),z52.strictObject({status:z52.enum(["UNCONFIGURED","UNAVAILABLE"]),url:z52.null()})]);var WorkspaceCallerSchema=z52.strictObject({humanLinks:HumanLinksSchema.optional(),tenantId:z52.uuid(),principalId:z52.uuid(),serverOrigin:z52.url().refine(value=>{const u=new URL(value);return u.origin===value&&!u.username&&!u.password&&!u.search&&!u.hash&&u.pathname==="/"&&(u.protocol==="https:"||u.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(u.hostname))}),skill:PublicDownloadDescriptorSchema,hostReleases:PublicDownloadDescriptorSchema});var WorkspacePageSchema=z52.strictObject({items:z52.array(WorkspaceViewSchema).max(100),possiblyTruncated:z52.boolean()});import{z as z53}from"zod";var TerminateProductionSchema=z53.strictObject({tenantId:TenantIdSchema,projectId:ProjectIdSchema,productionId:ProductionIdSchema,outcome:z53.enum(["FAILED","CANCELLED"]),expectedProductionRevision:z53.int().positive(),reason:z53.string().trim().min(1).max(1e3),idempotencyKey:z53.string().trim().min(1).max(200)});var ProductionTerminationReceiptSchema=z53.strictObject({decisionId:z53.uuid(),productionId:ProductionIdSchema,projectId:ProjectIdSchema,state:ProductionStateSchema});import{z as z54}from"zod";var text3=z54.string().trim().min(1).max(600);var key9=z54.string().regex(/^[a-z][a-z0-9_-]{0,39}$/);var Review1RepairSourceResultSchema=z54.strictObject({input:Review1RepairSourceQuerySchema,source:Review1RepairSourceSchema,productionRevision:z54.int().positive(),caseVersion:z54.int().nonnegative(),budget:SemanticRepairBudgetSchema.nullable()}).superRefine((v,c)=>{const fields=["tenantId","projectId","productionId","mediaType","generationId","reviewId"];if(fields.some(key10=>v.input[key10]!==v.source[key10])||v.input.requirementKey!==v.source.requirement.key)c.addIssue({code:"custom",message:"Native source must match the exact scoped Review obligation"})});var Review1RepairStrategyBasisSchema=z54.strictObject({input:Review1RepairSourceQuerySchema,contextFingerprint:z54.string().regex(/^[0-9a-f]{64}$/)});var Review1RepairStrategyContextSchema=z54.strictObject({semanticStatus:z54.literal("SUCCESS"),advisory:z54.literal(true),basis:Review1RepairStrategyBasisSchema,owner:Review1RepairSourceResultSchema});var ValidateReview1RepairStrategySchema=z54.strictObject({basis:Review1RepairStrategyBasisSchema,budget:SemanticRepairBudgetSchema.optional(),proposal:z54.strictObject({origin:z54.strictObject({kind:z54.literal("EXTERNAL_AGENT_HOST"),label:z54.string().trim().min(1).max(100)}),summary:text3,alternatives:z54.array(z54.strictObject({id:key9,rationale:text3,whySmallerChangeInsufficient:text3,action:z54.discriminatedUnion("kind",[z54.strictObject({kind:z54.literal("REGENERATE_SHOT")}),z54.strictObject({kind:z54.literal("REQUEST_HUMAN_INPUT"),question:text3}),z54.strictObject({kind:z54.literal("REQUEST_CANONICAL_CHANGE"),requestedChange:text3})])})).min(1).max(6),selectedAlternativeId:key9})}).refine(v=>new TextEncoder().encode(JSON.stringify(v)).byteLength<=1024*1024,"Review-1 strategy exceeds 1 MiB");var Review1RepairStrategyValidationSchema=z54.strictObject({semanticStatus:z54.literal("SUCCESS"),advisory:z54.literal(true),basis:Review1RepairStrategyBasisSchema,proposal:ValidateReview1RepairStrategySchema.shape.proposal,alternatives:z54.array(z54.strictObject({alternativeId:key9,handoff:z54.discriminatedUnion("kind",[z54.strictObject({kind:z54.literal("AUTHOR_REVIEW1_REPAIR"),input:AuthorReview1RepairSchema.omit({idempotencyKey:true})}),z54.strictObject({kind:z54.literal("HUMAN_INPUT_INTENT"),question:text3}),z54.strictObject({kind:z54.literal("CANONICAL_CHANGE_INTENT"),requestedChange:text3})])})).min(1).max(6),selectedAlternativeId:key9,followUp:z54.union([z54.tuple([]),z54.tuple([z54.literal("EXPLICIT_NATIVE_AUTHORING"),z54.literal("OWNER_BUDGET_AND_COST_ADMISSION"),z54.literal("EXPLICIT_NATIVE_EXECUTION"),z54.literal("INDEPENDENT_REVIEW_1_AND_NATIVE_PROOF")])])});import{z as z56}from"zod";import{z as z55}from"zod";var NavigationGroupIdSchema=z55.enum(["navigation","materials","planning","execution","review","delivery","local","administration","unclassified"]);var NavigationGroups=Object.freeze([{id:"navigation",title:"\u5BFC\u822A\u4E0E\u6062\u590D",description:"Locate Productions, inspect state and reconcile original Operations"},{id:"materials",title:"\u9879\u76EE\u4E0E\u7D20\u6750",description:"Projects, source material, references and Artifact discovery"},{id:"planning",title:"\u521B\u4F5C\u4E0E\u8BA1\u5212",description:"Brief, Story, Scenes, Shots and creative plans"},{id:"execution",title:"\u6267\u884C\u4E0E\u8FDB\u5EA6",description:"Generation, runtime Jobs, observation and cancellation"},{id:"review",title:"\u5BA1\u67E5\u4E0E\u4FEE\u590D",description:"Review targets, Findings, evidence and repair"},{id:"delivery",title:"\u88C5\u914D\u4E0E\u4EA4\u4ED8",description:"Timeline, composition, preview, rendering and delivery"},{id:"local",title:"\u672C\u5730\u6267\u884C",description:"Authorized local Runtime, media tools and Agent connections"},{id:"administration",title:"\u7BA1\u7406\u4E0E\u96C6\u6210",description:"Tenant integration, Providers and native authority configuration"},{id:"unclassified",title:"\u5F85\u5206\u7C7B\u80FD\u529B",description:"Registered capabilities awaiting explicit semantic classification"}]);var namespaces=[["navigation",/^nvs_open_execution$/],["local",/^(?:local_|device_|list_devices$)/],["administration",/^(?:provider_|tenant_|oauth_|credential_|native_tool_|agent_host_|webhook_)/],["review",/(?:^|_)(?:review|reviewer|finding|repair)(?:_|$)/],["navigation",/^(?:workspace_|studio_|operation_|production_(?:query|snapshot)|job_(?:get|query)|production_guidance_)/],["materials",/^(?:project_|source_|artifact_|reference_|visual_sequence_|imported_visual_|source_sync_)/],["planning",/^(?:brief_|story_|scene_|shot_|writer_|director_|exploration_|consistency_|voice_profile_|making_|sound_plan_|planning_|editor_)/],["delivery",/^(?:share_|timeline_|composition_|rough_cut_|final_|delivery_|caption_|audio_)/],["execution",/^(?:production_|keyframe_|video_|generation_|speech_|media_observation_|temporal_evidence_|lifecycle_)/]];function navigationGroup(tool){return namespaces.find(([,pattern])=>pattern.test(tool))?.[0]??"unclassified"}var NavigationProfile="contextual-v1";var NavigationProfileKey="io.nativestudio/discovery-profile";var NavigationToolNames=["studio_start","studio_capability_search","studio_capability_describe","studio_capability_groups","studio_navigate"];var Scope=z56.object({tenantId:TenantIdSchema,projectId:ProjectIdSchema.optional()});var ToolName=z56.string().regex(/^[a-zA-Z0-9_-]{1,120}$/);var StudioStartInputSchema=ProductionQueryInputSchema.extend({limit:z56.int().min(1).max(5).default(5)}).strict();var StudioStartSchema=z56.object({tenantId:TenantIdSchema,choices:ProductionQueryPageSchema.shape.items.max(5),page:ProductionQueryPageSchema.shape.page,selection:z56.enum(["NONE","ONE","CHOOSE"]),guidance:z56.literal("Select an explicit Production ID, then call studio_navigate. Never infer an ID.")}).strict();var CapabilitySummarySchema=z56.object({tool:ToolName,title:z56.string().max(500),description:z56.string().max(6e3),family:z56.string().min(1).max(120),group:NavigationGroupIdSchema.optional(),readOnly:z56.boolean(),registration:z56.literal("REGISTERED")}).strict();var CapabilitySearchInputSchema=Scope.extend({query:z56.string().trim().min(1).max(240),family:z56.string().regex(/^[a-z0-9_-]{1,120}$/).optional(),group:NavigationGroupIdSchema.optional(),limit:z56.int().min(1).max(8).default(5),next:z56.string().min(1).max(2048).optional()}).strict();var CapabilitySearchSchema=z56.object({tenantId:TenantIdSchema,catalogVersion:z56.string().regex(/^[a-f0-9]{64}$/),outcome:z56.enum(["MATCHES","AMBIGUOUS","NO_MATCH"]),candidates:z56.array(CapabilitySummarySchema.extend({matchedTerms:z56.array(z56.string().max(120)).max(24)})).max(8),page:z56.object({hasMore:z56.boolean(),next:z56.string().max(2048).nullable()}).strict(),guidance:z56.literal("Registration is not availability or authorization. Inspect the selected schema and native context before invoking its typed command.")}).strict();var CapabilityDescribeInputSchema=Scope.extend({tool:ToolName,schemaCursor:z56.string().min(1).max(2048).optional()}).strict();var JsonSchema=z56.record(z56.string(),z56.unknown());var PublicToolDefinitionSchema=z56.object({name:ToolName,title:z56.string().optional(),description:z56.string().optional(),inputSchema:JsonSchema,outputSchema:JsonSchema.optional(),annotations:JsonSchema.optional(),execution:JsonSchema.optional(),_meta:JsonSchema.optional(),icons:z56.array(JsonSchema).optional()}).strict();var CapabilityGroupsInputSchema=Scope.extend({includeDefinitions:z56.boolean().optional()}).strict();var CapabilityGroupsSchema=z56.object({tenantId:TenantIdSchema,catalogVersion:z56.string().regex(/^[a-f0-9]{64}$/),definitions:z56.array(PublicToolDefinitionSchema).max(6).optional(),groups:z56.array(z56.object({id:NavigationGroupIdSchema,title:z56.string().max(120),description:z56.string().max(500),count:z56.int().nonnegative(),readOnlyCount:z56.int().nonnegative()}).strict()).max(9)}).strict();var CapabilityDescribeSchema=CapabilitySummarySchema.extend({tenantId:TenantIdSchema,catalogVersion:z56.string().regex(/^[a-f0-9]{64}$/),outputContract:z56.enum(["DECLARED","NOT_DECLARED"]),schemaCursor:z56.string().min(1).max(2048),definition:PublicToolDefinitionSchema,guidance:z56.literal("Use this bounded definition as client-local schema metadata. Standard tools/list stays stable; commands revalidate authority and current state.")}).strict();var StudioNavigateInputSchema=Scope.extend({productionId:ProductionIdSchema,goal:z56.string().trim().min(1).max(240).optional(),actionLimit:z56.int().min(1).max(8).default(8).describe("Native action page size: 1\u20138 (default 8). Omit this field unless a smaller page is needed."),actionNext:z56.string().min(1).max(2048).optional().describe("Opaque actions.page.next; keep the same goal and actionLimit. Changed native state requires a fresh first page.")}).strict();import{z as z57}from"zod";var Evidence=z57.object({path:z57.string().min(1).max(120)}).strict();var StudioNavigationSchema=z57.object({tenantId:TenantIdSchema,projectId:ProjectIdSchema,productionId:ProductionIdSchema,evidence:z57.object({source:z57.literal("production_snapshot"),revision:z57.int().positive(),generatedAt:z57.iso.datetime({offset:true})}).strict(),state:ProductionSnapshotSchema.shape.state.extend({blockingReason:z57.string().max(1e3).nullable(),waitingReason:z57.string().max(1e3).nullable()}),stateReasonsTruncated:z57.object({blockingReason:z57.boolean(),waitingReason:z57.boolean()}).strict(),planning:ProductionSnapshotSchema.shape.planning,shots:ProductionSnapshotSchema.shape.shots,work:ProductionSnapshotSchema.shape.work,findings:ProductionSnapshotSchema.shape.findings,timeline:ProductionSnapshotSchema.shape.timeline.pick({currentVersion:true,stale:true}),final:ProductionSnapshotSchema.shape.final.pick({renderState:true,deliveryValidationState:true}),blockers:z57.object({total:z57.int().nonnegative(),truncated:z57.boolean(),items:z57.array(ProductionSnapshotSchema.shape.blockers.element.extend({evidence:Evidence})).max(10)}).strict(),actions:z57.object({total:z57.int().nonnegative(),truncated:z57.boolean(),items:z57.array(NextActionSchema.extend({tool:z57.string().min(1).max(120).nullable(),registration:z57.enum(["REGISTERED","NOT_ON_SURFACE"]),readOnly:z57.boolean().nullable(),purpose:z57.string().max(500).nullable(),group:NavigationGroupIdSchema.nullable(),context:z57.object({tenantId:TenantIdSchema,projectId:ProjectIdSchema,productionId:ProductionIdSchema,revision:z57.int().positive()}).strict(),inputHints:z57.object({knownInputs:z57.partialRecord(z57.enum(["tenantId","projectId","productionId","shotId","sceneId","findingId","operationId","artifactId"]),z57.string().min(1).max(2048)),schemaFingerprint:z57.string().regex(/^[a-f0-9]{64}$/).nullable(),requiredInputs:z57.array(z57.string()).max(128),missingInputs:z57.array(z57.string()).max(128),schemaInspectionRequired:z57.literal(true)}).strict().nullable(),recommendation:z57.array(z57.enum(["NATIVE_AVAILABLE","NATIVE_UNAVAILABLE","GOAL_MATCH","INSPECT_SCHEMA","NOT_ON_SURFACE"])).max(4),inspect:z57.object({tool:z57.literal("studio_capability_describe"),arguments:CapabilityDescribeInputSchema}).strict().nullable(),evidence:Evidence})).max(8),page:z57.object({hasMore:z57.boolean(),next:z57.string().max(2048).nullable()}).strict()}).strict(),operations:z57.object({total:z57.int().nonnegative(),truncated:z57.boolean(),items:z57.array(OperationSummarySchema.pick({id:true,productionId:true,semanticStatus:true,startedAt:true,updatedAt:true}).extend({inspect:z57.object({tool:z57.literal("operation_get"),arguments:z57.object({tenantId:TenantIdSchema,productionId:ProductionIdSchema,operationId:OperationSummarySchema.shape.id}).strict()}).strict().nullable(),targetCount:z57.int().nonnegative(),blockerCount:z57.int().nonnegative(),evidence:Evidence})).max(5)}).strict(),related:CapabilitySearchSchema.nullable(),guidance:z57.literal("Use native IDs and revision from this snapshot. An outstanding or unacknowledged write must be reconciled through its Operation; never replay it automatically. Commands revalidate current authority, prerequisites, revision and idempotency.")}).strict();import{z as z59}from"zod";import{z as z58}from"zod";var VoiceReferenceAudioSchema=z58.strictObject({audioVersionId:z58.uuid(),projectId:z58.uuid(),productionId:z58.uuid(),artifactId:z58.uuid(),representationId:z58.uuid(),checksumSha256:z58.string().regex(/^[a-f0-9]{64}$/),byteSize:z58.int().min(44).max(12582912),durationMs:z58.int().min(100).max(6e4),executionClass:z58.enum(["LIVE","TEST_ONLY"]),voiceProfile:VoiceProfileUseSchema.safeExtend({usage:z58.literal("AUDITION")})});var VoiceReferenceSchema=z58.strictObject({humanLinks:HumanLinksSchema.optional(),id:z58.uuid(),tenantId:TenantIdSchema,voiceProfileId:z58.uuid(),ref:VoiceProfileRefSchema,version:z58.int().positive(),audio:VoiceReferenceAudioSchema.nullable(),createdByPrincipalId:z58.uuid(),createdAt:z58.iso.datetime({offset:true})}).refine(v=>v.ref.ownerSystem==="native-video-studio"&&v.ref.ownerTenantRef===v.tenantId&&v.ref.voiceProfileRef===v.voiceProfileId&&(!v.audio||Object.entries(v.ref).every(([key10,value])=>v.audio.voiceProfile.ref[key10]===value)),"Reference selection must preserve its exact workspace voice identity");var VoiceReferenceGetSchema=z58.strictObject({tenantId:TenantIdSchema,voiceProfileId:z58.uuid(),referenceId:z58.uuid()});var VoiceProfileScopeSchema=z59.strictObject({tenantId:TenantIdSchema,voiceProfileId:z59.uuid()});var VoiceProfileBindingSchema=z59.strictObject({key:z59.string().regex(/^[a-z][a-z0-9_-]{0,63}$/),modelProfileId:ModelProfileIdSchema,modelProfileVersion:z59.int().positive(),voice:z59.string().min(1).max(100),languages:z59.array(VoiceLocaleSchema).min(1).max(16).refine(v=>new Set(v.map(s=>s.toLowerCase())).size===v.length),parameters:SpeechParametersSchema.default({}),nativeExecution:NativeSpeechExecutionSchema.optional()});var VoiceProfileContentSchema=z59.strictObject({displayName:z59.string().trim().min(1).max(100).regex(/^[^\p{Cc}]*$/u),description:z59.string().trim().max(1e3).default(""),style:z59.string().trim().max(400).default(""),origin:z59.enum(["PRESET","LICENSED_REFERENCE","CLONED_WITH_CONSENT"]),allowedUses:z59.array(z59.enum(["AUDITION","PRODUCTION"])).min(1).max(2).refine(v=>new Set(v).size===v.length).default(["AUDITION","PRODUCTION"]),expiresAt:z59.iso.datetime({offset:true}).optional(),rightsStatement:z59.string().trim().min(1).max(1e3).optional(),bindings:z59.array(VoiceProfileBindingSchema).min(1).max(8).refine(v=>new Set(v.map(b=>b.key)).size===v.length)});var command={tenantId:TenantIdSchema,idempotencyKey:z59.string().trim().min(1).max(200)};var revision={voiceProfileId:z59.uuid(),expectedRevision:z59.int().positive()};var VoiceProfileCommandSchema=z59.discriminatedUnion("action",[z59.strictObject({...command,action:z59.literal("CREATE"),content:VoiceProfileContentSchema}),z59.strictObject({...command,...revision,action:z59.literal("REVISE"),content:VoiceProfileContentSchema}),z59.strictObject({...command,...revision,action:z59.literal("PUBLISH")}),z59.strictObject({...command,...revision,action:z59.literal("SET_ENABLED"),enabled:z59.boolean()}),z59.strictObject({...command,...revision,action:z59.literal("SET_REFERENCE"),voiceProfileVersion:z59.int().positive(),audioVersionId:z59.uuid().nullable()})]);var VoiceProfileVersionQuerySchema=VoiceProfileScopeSchema.extend({version:z59.int().positive()});var VoiceProfileListSchema=z59.strictObject({tenantId:TenantIdSchema,search:z59.string().trim().max(100).optional(),status:z59.enum(["DRAFT","PUBLISHED","DISABLED"]).optional(),limit:z59.int().min(1).max(100).default(25),next:z59.string().min(1).max(4096).optional()});var VoiceProfileReceiptSchema=z59.strictObject({humanLinks:HumanLinksSchema.optional(),reference:VoiceReferenceSchema.optional(),semanticStatus:z59.literal("SUCCESS"),tenantId:TenantIdSchema,voiceProfileId:z59.uuid(),revision:z59.int().positive(),publishedVersion:z59.int().positive().nullable(),enabled:z59.boolean()});var VoiceProfileVersionSchema=z59.strictObject({humanLinks:HumanLinksSchema.optional(),ref:VoiceProfileRefSchema,content:VoiceProfileContentSchema,publishedByPrincipalId:z59.uuid(),publishedAt:z59.iso.datetime({offset:true})});var VoiceProfileSummarySchema=VoiceProfileReceiptSchema.omit({semanticStatus:true}).extend({displayName:z59.string().min(1).max(100),status:z59.enum(["DRAFT","PUBLISHED","DISABLED"]),updatedAt:z59.iso.datetime({offset:true})});var VoiceProfileViewSchema=VoiceProfileSummarySchema.extend({reference:VoiceReferenceSchema.nullable().default(null),draft:VoiceProfileContentSchema,draftDigest:z59.string().regex(/^[a-f0-9]{64}$/),published:VoiceProfileVersionSchema.nullable()});var VoiceProfilePageSchema=z59.strictObject({humanLinks:HumanLinksSchema.optional(),items:z59.array(VoiceProfileSummarySchema).max(100),next:z59.string().max(4096).nullable()});var VoiceProfileCreateSchema=VoiceProfileCommandSchema.options[0].omit({action:true});var VoiceProfileReviseSchema=VoiceProfileCommandSchema.options[1].omit({action:true});var VoiceProfilePublishSchema=VoiceProfileCommandSchema.options[2].omit({action:true});var VoiceProfileSetEnabledSchema=VoiceProfileCommandSchema.options[3].omit({action:true});var VoiceProfileSetReferenceSchema=VoiceProfileCommandSchema.options[4].omit({action:true});import{z as z60}from"zod";var sha9=z60.string().regex(/^[a-f0-9]{64}$/);var VoiceReviewAudioSchema=VoiceReferenceAudioSchema.omit({voiceProfile:true}).extend({voiceProfile:VoiceProfileUseSchema});var VoiceReviewScopeSchema=z60.strictObject({tenantId:TenantIdSchema,voiceProfileId:z60.uuid()});var VoiceReviewTargetQuerySchema=VoiceReviewScopeSchema.extend({audioVersionId:z60.uuid()});var VoiceReviewBasisSchema=z60.strictObject({reference:VoiceReferenceSchema.safeExtend({audio:VoiceReferenceAudioSchema}),candidate:VoiceReviewAudioSchema}).refine(v=>Object.entries(v.reference.ref).every(([key10,value])=>v.candidate.voiceProfile.ref[key10]===value),"Comparison must preserve the exact same voice identity");var VoiceIdentityObservationSchema=z60.strictObject({status:z60.enum(["MATCH","DIFFERENT","UNDETERMINED"]),confidence:z60.enum(["CLEAR","UNCERTAIN"]),observed:z60.string().trim().min(1).max(1800)});var VoiceNaturalnessObservationSchema=z60.strictObject({status:z60.enum(["NATURAL","NEEDS_WORK","NOT_ASSESSED"]),observed:z60.string().trim().min(1).max(1800)});var RecordVoiceReviewSchema=VoiceReviewTargetQuerySchema.extend({referenceId:z60.uuid(),basisFingerprint:sha9,expectedReviewVersion:z60.int().nonnegative(),idempotencyKey:z60.string().trim().min(1).max(200),actor:z60.enum(["HUMAN","EXTERNAL_AGENT"]),referenceListening:ListeningEvidenceSchema,candidateListening:ListeningEvidenceSchema,identity:VoiceIdentityObservationSchema,naturalness:VoiceNaturalnessObservationSchema});var VoiceReviewRecordSchema=VoiceReviewTargetQuerySchema.extend({id:z60.uuid(),version:z60.int().positive(),basis:VoiceReviewBasisSchema,basisFingerprint:sha9,actor:z60.enum(["HUMAN","EXTERNAL_AGENT"]),executionClass:z60.enum(["LIVE","TEST_ONLY"]),referenceListening:ListeningEvidenceSchema,candidateListening:ListeningEvidenceSchema,identity:VoiceIdentityObservationSchema,naturalness:VoiceNaturalnessObservationSchema,identityResult:z60.enum(["MATCH","DIFFERENT","UNDETERMINED"]),createdByPrincipalId:z60.uuid(),createdAt:z60.iso.datetime({offset:true})}).refine(v=>v.basis.reference.audio.audioVersionId!==v.basis.candidate.audioVersionId&&v.basis.reference.tenantId===v.tenantId&&v.basis.reference.voiceProfileId===v.voiceProfileId&&v.basis.candidate.audioVersionId===v.audioVersionId&&v.executionClass===([v.basis.reference.audio,v.basis.candidate].some(a=>a.executionClass==="TEST_ONLY")?"TEST_ONLY":"LIVE")&&v.identityResult===(v.identity.confidence==="CLEAR"?v.identity.status:"UNDETERMINED"),"Review must preserve exact comparison scope, execution class and independent result");var VoiceReviewStaleReasonSchema=z60.enum(["NO_REFERENCE","REFERENCE_CHANGED","REVIEW_SUPERSEDED","VOICE_UNAVAILABLE","AUDIO_UNAVAILABLE","IDENTITY_MISMATCH","SAME_AUDIO","TEST_ONLY"]);var VoiceReviewTargetSchema=VoiceReviewTargetQuerySchema.extend({humanLinks:HumanLinksSchema.optional(),basis:VoiceReviewBasisSchema.nullable(),basisFingerprint:sha9.nullable(),reviewVersion:z60.int().nonnegative(),eligible:z60.boolean(),staleReasons:z60.array(VoiceReviewStaleReasonSchema).max(8),latestReview:VoiceReviewRecordSchema.nullable()}).refine(v=>v.eligible===(v.staleReasons.length===0)&&(!v.eligible||!!v.basis&&!!v.basisFingerprint)&&v.basis===null===(v.basisFingerprint===null)&&(!v.basis||v.basis.reference.tenantId===v.tenantId&&v.basis.reference.voiceProfileId===v.voiceProfileId&&v.basis.candidate.audioVersionId===v.audioVersionId)&&v.reviewVersion===(v.latestReview?.version??0)&&(!v.latestReview||v.latestReview.tenantId===v.tenantId&&v.latestReview.voiceProfileId===v.voiceProfileId&&v.latestReview.audioVersionId===v.audioVersionId&&v.latestReview.basis.reference.id===v.basis?.reference.id),"Target projection must preserve exact scope and eligibility");var VoiceReviewGetSchema=VoiceReviewScopeSchema.extend({reviewId:z60.uuid()});var VoiceReviewViewSchema=z60.strictObject({humanLinks:HumanLinksSchema.optional(),review:VoiceReviewRecordSchema,current:z60.boolean(),staleReasons:z60.array(VoiceReviewStaleReasonSchema).max(8)}).refine(v=>v.current===(v.staleReasons.length===0),"Historical applicability must agree with currentness reasons");var VoiceReviewReceiptSchema=z60.strictObject({humanLinks:HumanLinksSchema.optional(),semanticStatus:z60.literal("SUCCESS"),review:VoiceReviewRecordSchema});import{z as z61}from"zod";var ProductionEventCursorSchema=z61.strictObject({v:z61.literal(1),t:z61.uuid(),p:z61.uuid(),e:z61.uuid(),n:z61.string().regex(/^(0|[1-9][0-9]{0,18})$/)});var ProductionFeedbackInputSchema=LifecycleEventScopeSchema.extend({operationId:OperationIdSchema.optional(),ifNoneMatch:z61.string().regex(/^[a-f0-9]{64}$/).optional()}).strict();var ProductionFeedbackSchema=LifecycleEventScopeSchema.extend({projectId:z61.uuid(),operationId:OperationIdSchema.nullable(),productionRevision:z61.int().positive(),state:ProductionStateSchema,semanticStatus:InterfaceSemanticStatusSchema,work:WorkSummarySchema,blockers:z61.array(z61.string().min(1).max(1e3)).max(100),nextActions:z61.array(NextActionSchema).max(50),media:z61.strictObject({previewReady:z61.boolean(),finalRenderReady:z61.boolean(),deliveryComplete:z61.boolean()}),humanLinks:HumanLinksSchema}).strict();var ProductionFeedbackResultSchema=LifecycleEventScopeSchema.extend({condition:z61.enum(["CURRENT","NOT_MODIFIED"]),etag:z61.string().regex(/^[a-f0-9]{64}$/),cursor:z61.string().min(1).max(4096),retryAfterMs:z61.int().min(1e3).max(3e4),feedback:ProductionFeedbackSchema.nullable()}).strict().refine(v=>v.condition==="CURRENT"===(v.feedback!==null));var ReadProductionEventsSchema=ProductionFeedbackInputSchema.extend({after:z61.string().min(1).max(4096).optional(),start:z61.enum(["CURRENT","BEGINNING"]).default("CURRENT"),limit:z61.int().min(1).max(50).default(20)}).strict();var ProductionEventReadSchema=z61.strictObject({items:z61.array(ExternalLifecycleEventSchema).max(50),nextCursor:z61.string().min(1).max(4096),watermark:z61.string().min(1).max(4096),hasMore:z61.boolean(),current:ProductionFeedbackResultSchema});import{z as z62}from"zod";var scope3=z62.strictObject({tenantId:z62.uuid().toLowerCase(),shareId:z62.uuid().toLowerCase()});var ShareCreateSchema=ArtifactDiscoveryMediaSchema.extend({shareId:z62.uuid().toLowerCase(),idempotencyKey:z62.string().min(1).max(128),title:z62.string().trim().min(1).max(160).default("Video"),expiresAt:z62.iso.datetime({offset:true}).optional()}).strict();var ShareGetSchema=scope3;var ShareRevokeSchema=scope3.extend({expectedRevision:z62.int().positive(),idempotencyKey:z62.string().min(1).max(128)}).strict();var ShareListSchema=z62.strictObject({tenantId:z62.uuid().toLowerCase(),projectId:z62.uuid().toLowerCase().optional(),artifactId:z62.uuid().toLowerCase().optional(),after:z62.uuid().toLowerCase().optional(),limit:z62.int().min(1).max(50).default(20)});var ShareViewSchema=ArtifactDiscoveryMediaSchema.extend({shareId:z62.uuid(),productionId:z62.uuid().nullable(),createdByPrincipalId:z62.uuid(),title:z62.string().min(1).max(160),purpose:z62.enum(["PREVIEW","ROUGH_CUT","FINAL_RENDER"]),contentType:z62.literal("video/mp4"),checksumSha256:z62.string().regex(/^[a-f0-9]{64}$/),byteSize:z62.int().positive().max(128*1024*1024),revision:z62.int().positive(),state:z62.enum(["PREPARING","ACTIVE","REVOKED","EXPIRED","AUTHORITY_REVOKED"]),createdAt:z62.iso.datetime({offset:true}),expiresAt:z62.iso.datetime({offset:true})}).strict();var ShareUrlSchema=z62.url().max(2048).refine(value=>{try{const u=new URL(value);return!u.username&&!u.password&&!u.search&&/^\/s\/[a-f0-9-]{36}$/.test(u.pathname)&&/^#key=[A-Za-z0-9_-]{43}$/.test(u.hash)&&(u.protocol==="https:"||u.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(u.hostname))}catch{return false}});var ShareLinkResultSchema=z62.strictObject({share:ShareViewSchema,url:ShareUrlSchema.nullable(),linkState:z62.enum(["AVAILABLE","UNCONFIGURED","UNAVAILABLE","NOT_ACTIVE"])}).refine(v=>v.linkState==="AVAILABLE"===(v.url!==null)).refine(v=>!v.url||v.share.state==="ACTIVE"&&new URL(v.url).pathname==="/s/"+v.share.shareId);var SharePageSchema=z62.strictObject({items:z62.array(ShareViewSchema).max(50),next:z62.uuid().nullable()});var SharePublicInputSchema=z62.strictObject({shareId:z62.uuid().toLowerCase(),secret:z62.string().regex(/^[A-Za-z0-9_-]{43}$/)});var intent=z63.strictObject({productionId:z63.uuid(),idempotencyKey:z63.string().trim().min(1).max(200),deviceId:z63.uuid().optional(),validationMode:DeviceRenderTargetSchema.shape.validationMode});var DeviceDiscoveryInputSchema=ProjectDeviceListInputSchema.omit({tenantId:true});var DeviceRenderIntentSchema=z63.discriminatedUnion("kind",[intent.extend({kind:z63.literal("preview"),profileId:RoughCutProfileIdSchema.optional()}),intent.extend({kind:z63.literal("final")})]);var DeviceRenderReadSchema=z63.strictObject({kind:z63.enum(["preview","final"]),productionId:z63.uuid(),renderId:z63.uuid()});var DeviceRenderDownloadSchema=DeviceRenderReadSchema.extend({role:z63.enum(["VIDEO","POSTER"])});var PreparedDeviceRenderSchema=z63.discriminatedUnion("kind",[z63.strictObject({kind:z63.literal("preview"),command:RoughCutStartSchema.extend({deviceExecution:DeviceRenderTargetSchema})}),z63.strictObject({kind:z63.literal("final"),command:FinalRenderStartSchema.extend({deviceExecution:DeviceRenderTargetSchema})})]);var DeviceRenderAdmissionSchema=z63.union([RoughCutAdmissionSchema.extend({deviceExecution:DeviceRenderReceiptSchema}),FinalRenderAdmissionSchema.extend({deviceExecution:DeviceRenderReceiptSchema})]);var NativeStudioDeviceRenders=class{constructor(caller){this.caller=caller}caller;list(raw,options){const input=DeviceDiscoveryInputSchema.parse(raw);return this.caller.call("devices.list",{...input,tenantId:this.caller.tenantId},options)}async prepare(raw,options){const input=DeviceRenderIntentSchema.parse(raw);const scope4={tenantId:this.caller.tenantId,productionId:input.productionId};const base={...scope4,idempotencyKey:input.idempotencyKey,deviceExecution:{mode:"tenant-device-only",...input.deviceId?{deviceId:input.deviceId}:{},...input.validationMode?{validationMode:input.validationMode}:{}}};if(input.kind==="final"){const e=await this.caller.call("final-render.eligibility",scope4,options);if(!e.renderable||!e.profile||!e.finalReady.selection)throw new NativeStudioSdkError("STALE_BASIS","STALE_BASIS","NO_WRITE");const selection=e.finalReady.selection;return PreparedDeviceRenderSchema.parse({kind:"final",command:{...base,selectionId:selection.id,expectedFinalReadyVersion:e.finalReady.version,timelineVersionId:selection.timelineVersionId,timelineFingerprint:selection.timelineFingerprint,expectedProductionRevision:e.productionRevision,profileId:e.profile.id,audioPolicy:e.profile.audioPolicy,captionPolicy:e.profile.captionPolicy}})}const[basis,current]=await Promise.all([this.caller.call("timeline.basis",scope4,options),this.caller.call("timeline.current",scope4,options)]);if(!basis.runnable||!current.isCurrent||current.assemblyStatus!=="ASSEMBLY_READY"||current.freshness!=="CURRENT_BASIS"||basis.currentTimelineVersion!==current.version.version)throw new NativeStudioSdkError("STALE_BASIS","STALE_BASIS","NO_WRITE");return PreparedDeviceRenderSchema.parse({kind:"preview",command:{...base,timelineVersionId:current.version.id,timelineFingerprint:current.version.fingerprint,expectedProductionRevision:basis.productionRevision,profileId:input.profileId??"PREVIEW_H264_480P_V1"}})}get(raw,options){const{kind,...input}=DeviceRenderReadSchema.parse(raw);return kind==="preview"?this.caller.call("rough-cut.get",input,options):this.caller.call("final-render.get",input,options)}async mediaTicket(raw,options){const{kind,...input}=DeviceRenderDownloadSchema.parse(raw);const result=kind==="preview"?await this.caller.call("rough-cut.media-ticket",input,options):await this.caller.call("final-render.media-ticket",input,options);if(result.ticket.object.tenantId!==this.caller.tenantId||result.ticket.method!=="GET"||result.ticket.object.role!==input.role)throw new NativeStudioSdkError("MEDIA_IDENTITY_MISMATCH","INTERNAL_OPERATIONAL_FAILURE","NO_WRITE");return result}async download(raw,options,expectedProjectId){const input=DeviceRenderDownloadSchema.parse(raw);const{role,...scope4}=input;const view=await this.get(scope4,options);const accepted="roughCut"in view?view.roughCut:view.finalOutput;const expected=role==="POSTER"?accepted?.poster:accepted;const failure=()=>new NativeStudioSdkError("MEDIA_IDENTITY_MISMATCH","INTERNAL_OPERATIONAL_FAILURE","NO_WRITE");if(!expected||expectedProjectId&&expectedProjectId!==view.projectId)throw failure();const media=await this.mediaTicket(input,options);if(media.ticket.object.projectId!==view.projectId||media.representationId!==expected.representationId||media.ticket.object.checksumSha256!==expected.checksumSha256||media.ticket.object.byteSize!==expected.byteSize)throw failure();const output=await downloadRenderObject(media.ticket,options);return{...output,representationId:media.representationId,renderId:media.renderId}}receipt(raw,options){const prepared=PreparedDeviceRenderSchema.parse(raw);return prepared.kind==="preview"?this.caller.call("rough-cut.admission-receipt",prepared.command,options):this.caller.call("final-render.admission-receipt",prepared.command,options)}start(raw,options){const prepared=PreparedDeviceRenderSchema.parse(raw);return prepared.kind==="preview"?this.caller.call("rough-cut.start",prepared.command,options):this.caller.call("final-render.start",prepared.command,options)}};import"zod";function descriptorOperation(input,output,request,expectedPath){return Object.freeze({...operation(input,output,request,[],{readOnly:true}),expectedPath})}function operation(input,output,request,identity2=[],options={}){return Object.freeze({input,output,request,identity:identity2,readOnly:options.readOnly,expectedPath:void 0,identityWhenPresent:options.identityWhenPresent??[]})}function path(...parts){return"/v1/"+parts.map(value=>encodeURIComponent(value)).join("/")}function pageQuery(input){return{limit:input.limit,next:input.next}}function mcpOperation(input,output,readOnly,identity2=[],expectedPath){return Object.freeze({input,output,request:null,readOnly,identity:identity2,expectedPath,identityWhenPresent:[]})}var post=(action,input,output,readOnly,identity2=[])=>operation(input,output,i=>({method:"POST",tenantId:i.tenantId,path:path("shares",action),body:i}),identity2,{readOnly});var target=["shareId","projectId","artifactId","representationId"].map(k=>[k,"share."+k]);var shareOperations={"share.create":post("create",ShareCreateSchema,ShareLinkResultSchema,false,target),"share.link":post("link",ShareGetSchema,ShareLinkResultSchema,false,[["shareId","share.shareId"]]),"share.get":post("get",ShareGetSchema,ShareViewSchema.nullable(),true,[["shareId","shareId"]]),"share.list":post("list",ShareListSchema,SharePageSchema,true,[["artifactId","items.*.artifactId"]]),"share.revoke":post("revoke",ShareRevokeSchema,ShareViewSchema,false,[["shareId","shareId"]]),"share.receipt":post("receipt",ShareCreateSchema,ShareViewSchema.nullable(),true,[...["shareId","projectId","artifactId","representationId"].map(k=>[k,k])])};import{z as z65}from"zod";function inputIssues(error,schema){const fields=new Set;const collect=node=>{if(node instanceof z65.ZodObject)Object.keys(node.shape).forEach(key10=>fields.add(key10));else if(node instanceof z65.ZodUnion)node.options.forEach(branch=>collect(branch))};collect(schema);const result=new Map;for(const issue of error.issues){const first=issue.path[0];const field=typeof first==="string"&&first.length<=120&&fields.has(first)?first:"$";const safe={field,code:issue.code};result.set(`${field}:${safe.code}`,safe);if(result.size>=8)break}return[...result.values()]}import{z as z66}from"zod";var success=z66.strictObject({semanticStatus:z66.literal("SUCCESS")});var deviceManagementOperations={"workspace.devices.list":operation(WorkspaceDeviceListInputSchema,WorkspaceDeviceListSchema,({tenantId,deviceId,after,limit})=>({method:"GET",tenantId,path:path("local-execution","devices"),query:{deviceId,after,limit}}),[["deviceId","items.*.deviceId"]],{readOnly:true}),"device.enroll":operation(EnrollLocalDeviceSchema,LocalDeviceViewSchema,i=>({method:"POST",tenantId:i.tenantId,path:path("local-execution","devices","enroll"),body:i}),[["tenantId","tenantId"],["publicKey","publicKey"],["label","label"],["platform","platform"],["runtimeVersion","runtimeVersion"]]),"device.revoke":operation(RevokeLocalDeviceSchema,success,i=>({method:"POST",tenantId:i.tenantId,path:path("local-execution","devices","revoke"),body:i})),"device.management-receipt":operation(ScopedLocalManagementReceiptSchema,LocalManagementReceiptSchema,i=>({method:"POST",tenantId:i.tenantId,path:path("local-execution","management-receipt"),body:i.command}),[],{readOnly:true})};import{createHash as createHash2}from"node:crypto";var identityFailure=()=>new NativeStudioSdkError("MEDIA_IDENTITY_MISMATCH","INTERNAL_OPERATIONAL_FAILURE","UNKNOWN");function checkTicket({endpoint,method,object},expected){const url=new URL(endpoint);if(method!=="PUT"||object.role!=="SOURCE"||object.tenantId!==expected.tenantId||object.projectId!==expected.projectId||object.byteSize!==expected.byteSize||object.checksumSha256!==expected.checksumSha256||url.pathname!==mediaObjectTransferPath||url.username||url.password||url.search||url.hash||url.protocol!=="https:"&&!(url.protocol==="http:"&&url.hostname==="127.0.0.1"))throw identityFailure();return url}async function upload(ticket,url,bytes,options){const timeout=AbortSignal.timeout(12e4);const signal=options.signal?AbortSignal.any([options.signal,timeout]):timeout;try{const result=await fetch(url,{method:"PUT",redirect:"error",headers:{authorization:"Bearer "+ticket.credential},body:new Uint8Array(bytes),signal});await result.body?.cancel();if(result.status===204)return}catch{}throw new NativeStudioSdkError("OBJECT_UPLOAD_UNCONFIRMED","BLOCKED","UNKNOWN")}var NativeStudioDirectSources=class{constructor(tenantId,transport){this.tenantId=tenantId;this.transport=transport}tenantId;transport;async importProjectSource(intent2,input,options={}){if(!(input instanceof Uint8Array)||input.length<1||input.length>8*1024*1024)sdkInputError();const bytes=Buffer.from(input);const result=DirectProjectSourceCommandSchema.safeParse({...intent2,metadata:{...intent2.metadata,tenantId:this.tenantId},byteSize:bytes.length,checksumSha256:createHash2("sha256").update(bytes).digest("hex")});if(!result.success)sdkInputError();const{projectId,...body}=result.data;const scope4={tenantId:this.tenantId,projectId};const endpoint=action=>path("projects",projectId,"source-artifacts","direct",action);const validate=receipt2=>{if(receipt2.state==="ACCEPTED"){const{artifact:artifact2,primaryRepresentation}=receipt2.registration;if(artifact2.tenantId!==scope4.tenantId||artifact2.projectId!==projectId||artifact2.productionId!==null||artifact2.lifecycle!=="READY"||primaryRepresentation.artifactId!==artifact2.id||primaryRepresentation.tenantId!==scope4.tenantId||primaryRepresentation.checksumSha256!==body.checksumSha256||primaryRepresentation.byteSize!==String(body.byteSize))throw identityFailure()}else if(receipt2.tenantId!==scope4.tenantId||receipt2.projectId!==projectId)throw identityFailure();return receipt2};const stage=await this.transport.json({method:"POST",tenantId:scope4.tenantId,path:endpoint("stage"),body},DirectProjectSourceStageSchema,options);if(stage.state!=="UPLOAD")return validate(stage);if(stage.tenantId!==scope4.tenantId||stage.projectId!==projectId)throw identityFailure();const url=checkTicket(stage.ticket,{...scope4,...body});if(!stage.uploaded)await upload(stage.ticket,url,bytes,options);const receipt=await this.transport.json({method:"POST",tenantId:scope4.tenantId,path:endpoint("submit"),body:{tenantId:scope4.tenantId,intakeId:stage.intakeId}},DirectProjectSourceSubmitSchema,options);if(receipt.state==="SUBMITTED"&&receipt.intakeId!==stage.intakeId)throw identityFailure();return validate(receipt)}async importOriginal(raw,input,options={}){const parsed=DirectOriginalCommandSchema.safeParse(raw);if(!parsed.success)sdkInputError();const command2=parsed.data;const{tenantId,projectId,productionId,shotId,source}=command2.input;if(tenantId!==this.tenantId||!(input instanceof Uint8Array)||input.length!==source.byteSize)sdkInputError();const bytes=Buffer.from(input);if(createHash2("sha256").update(bytes).digest("hex")!==source.checksumSha256)sdkInputError();const scope4={tenantId,projectId,productionId};const endpoint=action=>path("productions",productionId,"imported-visuals","originals","direct",action);const validate=receipt2=>{const value=receipt2.state==="ACCEPTED"?receipt2.original:receipt2;if(value.tenantId!==tenantId||value.projectId!==projectId||value.productionId!==productionId)throw identityFailure();if(receipt2.state==="ACCEPTED"){const{original}=receipt2;if(original.shotId!==shotId||original.metadata.checksumSha256!==source.checksumSha256||original.metadata.byteSize!==source.byteSize||command2.operation==="REVISE"&&(original.sourceId!==command2.input.sourceId||original.version!==command2.input.expectedVersion+1))throw identityFailure()}return receipt2};const stage=await this.transport.json({method:"POST",tenantId,path:endpoint("stage"),body:command2},DirectOriginalStageSchema,options);if(stage.state!=="UPLOAD")return validate(stage);if(stage.tenantId!==tenantId||stage.projectId!==projectId||stage.productionId!==productionId)throw identityFailure();const url=checkTicket(stage.ticket,{...scope4,...source});if(!stage.uploaded)await upload(stage.ticket,url,bytes,options);const receipt=await this.transport.json({method:"POST",tenantId,path:endpoint("submit"),body:{...scope4,intakeId:stage.intakeId}},DirectOriginalSubmitSchema,options);if(receipt.state==="SUBMITTED"&&receipt.intakeId!==stage.intakeId)throw identityFailure();return validate(receipt)}};var NativeStudioNavigationFacade=class{constructor(caller){this.caller=caller}caller;find(input,options){return this.caller.call("studio.start",input,options)}overview(input,options){return this.caller.call("studio.navigate",input,options)}next(input,options){return this.overview(input,options)}resume(input,options){return this.caller.call("operation.get",input,options)}groups(input={},options){return this.caller.call("studio.capability.groups",input,options)}search(input,options){return this.caller.call("studio.capability.search",input,options)}describe(input,options){return this.caller.call("studio.capability.describe",input,options)}};import{createHash as createHash7}from"node:crypto";import{createHash as createHash3}from"node:crypto";function assertExportBytes(value,captionFormat){const v=value;const bytes=v.contentBase64!==void 0?Buffer.from(v.contentBase64,"base64"):Buffer.from(v.text,"utf8");if(v.contentBase64!==void 0&&(bytes.toString("base64")!==v.contentBase64||bytes.length!==v.byteSize||bytes.toString("ascii",0,4)!=="RIFF"||bytes.toString("ascii",8,12)!=="WAVE")||bytes.length>(v.contentBase64!==void 0?12582912:131072)||captionFormat!==void 0&&v.contentType!==(captionFormat==="JSON"?"application/json":"application/x-subrip")||createHash3("sha256").update(bytes).digest("hex")!==v.checksumSha256)throw new NativeStudioSdkError("MEDIA_IDENTITY_MISMATCH","INTERNAL_OPERATIONAL_FAILURE","NO_WRITE")}import{createHash as createHash4}from"node:crypto";function assertPreviewBytes(value){const v=value;if(v.semanticStatus!=="SUCCESS")return;const data=v.contentBase64;if(typeof data!=="string"||data.length>4*Math.ceil(8*1024*1024/3))throw new NativeStudioSdkError("RESPONSE_INVALID","INTERNAL_OPERATIONAL_FAILURE","NO_WRITE");const bytes=Buffer.from(data,"base64");if(bytes.length!==v.byteSize||bytes.toString("base64")!==data||!bytes.subarray(0,8).equals(Buffer.from([137,80,78,71,13,10,26,10]))||createHash4("sha256").update(bytes).digest("hex")!==v.checksumSha256)throw new NativeStudioSdkError("MEDIA_IDENTITY_MISMATCH","INTERNAL_OPERATIONAL_FAILURE","NO_WRITE")}import{createHash as createHash5}from"node:crypto";function assertOriginalVideoBytes(value){const v=value;const bytes=Buffer.from(v.dataBase64,"base64");if(bytes.toString("base64")!==v.dataBase64||bytes.length!==v.source.byteSize||bytes.subarray(4,8).toString("ascii")!=="ftyp"||createHash5("sha256").update(bytes).digest("hex")!==v.source.checksumSha256)throw new NativeStudioSdkError("RESPONSE_INVALID","INTERNAL_OPERATIONAL_FAILURE","NO_WRITE")}import{z as z67}from"zod";var production2=z67.strictObject({tenantId:TenantIdSchema,productionId:ProductionIdSchema});var sourceUpload=UploadSourceInputRequestSchema.extend({projectId:ProjectIdSchema,idempotencyKey:z67.string().trim().min(1).max(200)});var projectProduction=(p,prod,suffix)=>path("projects",p,"productions",prod,suffix);var coreOperations={"workspace.get":operation(WorkspaceScopeSchema,WorkspaceViewSchema,i=>({method:"GET",path:path("workspace"),tenantId:i.tenantId})),"workspace.caller":operation(WorkspaceScopeSchema,WorkspaceCallerSchema,i=>({method:"GET",path:path("workspace","caller"),tenantId:i.tenantId}),[["tenantId","tenantId"]]),"workspace.query":operation(WorkspaceScopeSchema,WorkspacePageSchema,i=>({method:"GET",path:path("workspaces"),tenantId:i.tenantId})),"visual-sequence.start-registration":operation(RegisterVisualSequenceSchema,VisualSequenceRegistrationAdmissionSchema,i=>{const{tenantId,projectId,...body}=i;return{method:"POST",path:path("projects",projectId,"visual-sequences","jobs"),tenantId,body}}),"visual-sequence.register":operation(LegacyVisualSequenceRegistrationSchema,VisualSequenceViewSchema,i=>{const{tenantId,projectId,...body}=i;return{method:"POST",path:path("projects",projectId,"visual-sequences"),tenantId,body}},[["projectId","sequence.projectId"]]),"visual-sequence.get":operation(VisualSequenceGetSchema,VisualSequenceViewSchema,i=>({method:"GET",path:path("projects",i.projectId,"visual-sequences",i.artifactId),tenantId:i.tenantId}),[["artifactId","sequence.artifactId"]]),"visual-sequence.query":operation(VisualSequenceQuerySchema,VisualSequencePageSchema,i=>({method:"GET",path:path("projects",i.projectId,"visual-sequences"),tenantId:i.tenantId,query:pageQuery(i)})),"project.create":operation(CreateProjectRequestSchema,CreatedProjectResultSchema,input=>({method:"POST",path:path("projects"),tenantId:input.tenantId,body:input})),"production.create":operation(CreateProductionRequestSchema,CreatedProductionResultSchema,input=>({method:"POST",path:path("projects",input.projectId,"productions"),tenantId:input.tenantId,body:{idempotencyKey:input.idempotencyKey}}),[["projectId","project.id"]]),"production.terminate":operation(TerminateProductionSchema,ProductionTerminationReceiptSchema,input=>({method:"POST",path:path("projects",input.projectId,"productions",input.productionId,"terminate"),tenantId:input.tenantId,body:{outcome:input.outcome,expectedProductionRevision:input.expectedProductionRevision,reason:input.reason,idempotencyKey:input.idempotencyKey}}),[["productionId","productionId"],["projectId","projectId"]]),"project.query":operation(ProjectLibraryQuerySchema,ProjectLibraryPageSchema,input=>({method:"GET",path:path("projects"),tenantId:input.tenantId,query:pageQuery(input)})),"project.get":operation(ProjectLibraryScopeSchema,ProjectWorkspaceSchema,input=>({method:"GET",path:path("projects",input.projectId),tenantId:input.tenantId}),[["projectId","project.id"]]),"devices.list":operation(ProjectDeviceListInputSchema,ProjectDeviceListSchema,({tenantId,projectId,kind,deviceId})=>({method:"GET",path:path("local-execution","projects",projectId,"devices"),tenantId,query:{kind,deviceId}}),[["projectId","projectId"],["kind","kind"],["deviceId","items.*.deviceId"]],{readOnly:true}),"source.query":operation(SourceLibraryQuerySchema,SourceLibraryPageSchema,input=>({method:"GET",path:input.projectId?path("projects",input.projectId,"source-artifacts"):path("source-artifacts"),tenantId:input.tenantId,query:pageQuery(input)})),"source.ingest":operation(sourceUpload,ReadyArtifactRegistrationSchema,input=>{const{projectId,...body}=input;return{method:"POST",path:path("projects",projectId,"source-artifacts"),tenantId:input.tenantId,body}}),"source.text":operation(SourceReadSchema,SourceTextWindowSchema,input=>({method:"GET",path:path("projects",input.projectId,"source-artifacts",input.artifactId,"text"),tenantId:input.tenantId,query:{offsetBytes:input.offsetBytes,maxTextBytes:input.maxTextBytes}}),[["artifactId","artifactId"]]),"production.query":operation(ProductionQueryInputSchema.strict(),ProductionQueryPageSchema,input=>({method:"GET",path:path("productions"),tenantId:input.tenantId,query:{...pageQuery(input),projectId:input.projectId,search:input.search,attention:input.attention}})),"production.snapshot":operation(production2,ProductionSnapshotSchema,input=>({method:"GET",path:path("productions",input.productionId,"snapshot"),tenantId:input.tenantId})),"brief.accept":operation(ScopedAcceptBriefSchema,AcceptBriefResultSchema,input=>{const{projectId,productionId,...body}=input;return{method:"POST",path:projectProduction(projectId,productionId,"brief-versions"),tenantId:input.tenantId,body}}),"story.accept":operation(ScopedAcceptStorySchema,AcceptStoryResultSchema,input=>{const{projectId,productionId,...body}=input;return{method:"POST",path:projectProduction(projectId,productionId,"story-versions"),tenantId:input.tenantId,body}}),"scene-shot-plan.accept":operation(ScopedAcceptSceneShotPlanSchema,AcceptSceneShotPlanResultSchema,input=>{const{projectId,productionId,...body}=input;return{method:"POST",path:projectProduction(projectId,productionId,"scene-shot-plan-versions"),tenantId:input.tenantId,body}}),"story.query":operation(StoryQueryInputSchema.strict(),StoryQueryPageSchema,input=>({method:"GET",path:path("productions",input.productionId,"stories"),tenantId:input.tenantId,query:pageQuery(input)})),"story.active":operation(production2,StoryVersionSchema,input=>({method:"GET",path:path("productions",input.productionId,"stories","active"),tenantId:input.tenantId})),"scene-shot-plan.query":operation(SceneShotPlanQueryInputSchema.strict(),SceneShotPlanQueryPageSchema,input=>({method:"GET",path:path("productions",input.productionId,"scene-shot-plans"),tenantId:input.tenantId,query:pageQuery(input)})),"scene-shot-plan.active":operation(production2,SceneShotPlanVersionSchema,input=>({method:"GET",path:path("productions",input.productionId,"scene-shot-plans","active"),tenantId:input.tenantId})),"operation.query":operation(OperationQueryInputSchema.strict(),OperationQueryPageSchema,input=>({method:"GET",path:path("productions",input.productionId,"operations"),tenantId:input.tenantId,query:pageQuery(input)})),"operation.get":operation(production2.extend({operationId:OperationIdSchema}),OperationSummarySchema,input=>({method:"GET",path:path("productions",input.productionId,"operations",input.operationId),tenantId:input.tenantId}),[["operationId","id"]])};var reference=["tenantId","projectId","deviceId","fileId","versionId","checksumSha256","byteSize","contentType"];var deviceLibraryOperations={"device-library.query":operation(LocalLibraryProjectionQuerySchema,LocalLibraryProjectionPageSchema,({tenantId,projectId,deviceId,after,limit,search,mediaCategory})=>({method:"GET",tenantId,path:path("local-execution","projects",projectId,"devices",deviceId,"library"),query:{after:after??void 0,limit,search,mediaCategory}}),[["tenantId","items.*.reference.tenantId"],["projectId","items.*.reference.projectId"],["deviceId","items.*.reference.deviceId"]],{readOnly:true}),"device-library.admit":operation(LocalLibraryCommandSchema,LocalLibraryAdmissionSchema,({tenantId,productionId,...body})=>({method:"POST",tenantId,path:path("productions",productionId,"device-library","commands"),body:{tenantId,productionId,...body}}),[["tenantId","tenantId"],["projectId","projectId"],["productionId","productionId"],["requestId","requestId"],["accessRevision","accessRevision"],...reference.map(field=>[`reference.${field}`,`reference.${field}`])]),"device-library.receipt":operation(LocalLibraryCommandQuerySchema,LocalLibraryCommandStatusSchema.nullable(),({tenantId,projectId,productionId,requestId})=>({method:"GET",tenantId,path:path("productions",productionId,"device-library","commands",requestId),query:{projectId}}),[["tenantId","admission.tenantId"],["projectId","admission.projectId"],["productionId","admission.productionId"],["requestId","admission.requestId"],["tenantId","admission.reference.tenantId"],["projectId","admission.reference.projectId"]],{readOnly:true})};var navigationOperations={"studio.capability.groups":mcpOperation(CapabilityGroupsInputSchema,CapabilityGroupsSchema,true),"studio.start":mcpOperation(StudioStartInputSchema,StudioStartSchema,true),"studio.capability.search":mcpOperation(CapabilitySearchInputSchema,CapabilitySearchSchema,true),"studio.capability.describe":mcpOperation(CapabilityDescribeInputSchema,CapabilityDescribeSchema,true),"studio.navigate":mcpOperation(StudioNavigateInputSchema,StudioNavigationSchema,true,[["productionId","productionId"],["projectId","projectId"]])};function write(input,suffix){return operation(input,AgentHostBindingSchema,value=>({method:"POST",tenantId:value.tenantId,path:path("projects",value.projectId,"agent-host",...suffix),body:Object.fromEntries(Object.entries(value).filter(([key10])=>!["tenantId","projectId"].includes(key10)))}),[["bindingId","bindingId"]])}var agentHostOperations={"agent-host.get":operation(AgentHostScopeSchema,AgentHostCurrentSchema,value=>({method:"GET",tenantId:value.tenantId,path:path("projects",value.projectId,"agent-host")})),"agent-host.readiness":operation(AgentHostScopeSchema,AgentHostReadinessSchema,value=>({method:"GET",tenantId:value.tenantId,path:path("projects",value.projectId,"agent-host","readiness")})),"agent-host.history":operation(AgentHostHistoryQuerySchema,AgentHostHistoryPageSchema,value=>({method:"GET",tenantId:value.tenantId,path:path("projects",value.projectId,"agent-host","history"),query:{limit:value.limit,beforeVersion:value.beforeVersion}})),"agent-host.configure":write(ConfigureAgentHostSchema,[]),"agent-host.selection.update":write(UpdateAgentHostSelectionSchema,["selection"]),"agent-host.revoke":write(RevokeAgentHostSchema,["revoke"])};var route=(scope4,...suffix)=>path("projects",scope4.projectId,"productions",scope4.productionId,"agent-host-executions",...suffix);var mutation2=action=>operation(AgentHostExecutionGetSchema,AgentHostExecutionViewSchema,value=>({method:"POST",tenantId:value.tenantId,path:route(value,value.executionId,action),body:{}}),[["executionId","executionId"]]);var agentHostExecutionOperations={"agent-host-execution.start":operation(StartAgentHostExecutionSchema,AgentHostExecutionViewSchema,value=>({method:"POST",tenantId:value.tenantId,path:route(value),body:Object.fromEntries(Object.entries(value).filter(([key10])=>!["tenantId","projectId","productionId"].includes(key10)))}),[["requestId","requestId"],["bindingId","snapshot.binding.bindingId"],["studioInputArtifactId","snapshot.input.intake.artifactId"],["expectedProductionRevision","snapshot.input.productionRevision"],["expectedBindingRevision","snapshot.binding.revision"],["expectedConfigurationVersion","snapshot.binding.configurationVersion"]]),"agent-host-execution.get":operation(AgentHostExecutionGetSchema,AgentHostExecutionViewSchema,value=>({method:"GET",tenantId:value.tenantId,path:route(value,value.executionId)}),[["executionId","executionId"]]),"agent-host-execution.query":operation(AgentHostExecutionQuerySchema,AgentHostExecutionPageSchema,value=>({method:"GET",tenantId:value.tenantId,path:route(value),query:{limit:value.limit,beforeId:value.beforeId}})),"agent-host-execution.events":operation(AgentHostExecutionEventQuerySchema,AgentHostExecutionEventPageSchema,value=>({method:"GET",tenantId:value.tenantId,path:route(value,value.executionId,"events"),query:{limit:value.limit,beforeRevision:value.beforeRevision}}),[["executionId","items.*.executionId"]]),"agent-host-execution.dispatch":mutation2("dispatch"),"agent-host-execution.reconcile":mutation2("reconcile"),"agent-host-execution.cancel":mutation2("cancel")};var route2=(v,...suffix)=>path("projects",v.projectId,"native-tool-grants",...suffix);var nativeToolAuthorityOperations={"native-tool-grant.configure":operation(ConfigureNativeToolGrantSchema,NativeToolGrantViewSchema,v=>({method:"POST",tenantId:v.tenantId,path:route2(v),body:Object.fromEntries(Object.entries(v).filter(([k])=>!["tenantId","projectId"].includes(k)))}),[["bindingId","bindingId"],["expectedBindingRevision","bindingRevision"],["expectedConfigurationVersion","configurationVersion"],["runtimeKey","runtimeKey"],["installationId","installationId"],["installationRevisionId","installationRevisionId"],["publicKey.x","publicKey.x"],["publicKey.y","publicKey.y"]]),"native-tool-grant.get":operation(NativeToolGrantGetSchema,NativeToolGrantViewSchema,v=>({method:"GET",tenantId:v.tenantId,path:route2(v,v.grantId)}),[["grantId","grantId"]]),"native-tool-grant.revoke":operation(RevokeNativeToolGrantSchema,NativeToolGrantViewSchema,v=>({method:"POST",tenantId:v.tenantId,path:route2(v,v.grantId,"revoke"),body:{requestId:v.requestId,expectedRevision:v.expectedRevision}}),[["grantId","grantId"]])};function productionRead(input,output,suffix,query=()=>({}),identity2=[]){return operation(input,output,value=>({method:"GET",tenantId:value.tenantId,path:path("productions",value.productionId,...suffix(value)),query:query(value)}),identity2)}function productionWrite(input,output,suffix,options={}){return operation(input,output,value=>({method:"POST",tenantId:value.tenantId,path:path("productions",value.productionId,...suffix(value)),body:Object.fromEntries(Object.entries(value).filter(([key10])=>key10!=="productionId"&&(options.tenantInBody||key10!=="tenantId")&&!options.pathFields?.includes(key10)))}),options.identity,options.readOnly===void 0?{}:{readOnly:options.readOnly})}var compositionOperations={"composition.render.query":productionRead(CompositionRenderQuerySchema,CompositionRenderPageSchema,()=>["compositions","renders"],i=>({limit:i.limit,next:i.next,shotId:i.shotId,role:i.role}),[["shotId","items.*.render.sourceIdentity.shotId"],["role","items.*.render.sourceIdentity.role"]]),"composition.capabilities":productionRead(CompositionScopeSchema,CompositionCapabilitiesSchema,()=>["compositions","capabilities"]),"composition.brief":productionRead(CompositionBriefQuerySchema,CompositionAuthoringBriefSchema,()=>["compositions","brief"],i=>({...i.shotId?{shotId:i.shotId}:{}})),"composition.put-input":productionWrite(PutCompositionInputSchema,CompositionInputReceiptSchema,()=>["compositions","inputs"]),"composition.making.validate":productionWrite(ValidateCompositionMakingSchema,CompositionMakingValidationSchema,()=>["compositions","making","validate"],{readOnly:true,identity:[["projectId","projectId"],["expectedProductionRevision","authoring.productionRevision"],["basis.briefVersionId","authoring.basis.briefVersionId"],["basis.storyVersionId","authoring.basis.storyVersionId"],["basis.planVersionId","authoring.basis.planVersionId"],["basis.shotId","authoring.basis.shotId"],["proposal.makingIntent","proposal.makingIntent"]]}),"composition.validate":productionWrite(ValidateCompositionSchema,CompositionValidationReceiptSchema,()=>["compositions","validate"],{readOnly:true}),"composition.create":productionWrite(CreateCompositionSchema,CompositionReceiptSchema,()=>["compositions"]),"composition.revise":productionWrite(ReviseCompositionSchema,CompositionReceiptSchema,()=>["compositions","revise"],{identity:[["compositionId","version.compositionId"]]}),"composition.get":productionRead(CompositionGetSchema,CompositionViewSchema,i=>["compositions",i.compositionId],i=>({versionId:i.versionId}),[["compositionId","version.compositionId"],["versionId","version.id"]]),"composition.history":productionRead(CompositionHistorySchema,CompositionPageSchema,i=>["compositions",i.compositionId,"versions"],i=>({limit:i.limit,beforeVersion:i.beforeVersion}),[["compositionId","items.*.version.compositionId"]]),"composition.render":productionWrite(CompositionRenderStartSchema,CompositionRenderReceiptSchema,()=>["compositions","renders"],{identity:[["versionId","compositionVersionId"]]}),"composition.render.get":productionRead(CompositionRenderGetSchema,CompositionRenderViewSchema,i=>["compositions","renders",i.renderId],void 0,[["renderId","receipt.renderId"]]),"composition.render.cancel":productionWrite(CompositionRenderGetSchema,CompositionRenderCancellationSchema,i=>["compositions","renders",i.renderId,"cancel"],{pathFields:["renderId"]}),"composition.sample":productionWrite(CompositionSampleStartSchema,CompositionSampleReceiptSchema,()=>["compositions","samples"],{identity:[["renderId","renderId"]]}),"composition.observe":productionRead(CompositionObserveGetSchema,CompositionObservationViewSchema,i=>["compositions","renders",i.renderId,"observations",i.evidenceId],void 0,[["renderId","renderId"],["evidenceId","evidence.evidenceId"]])};var cancellation=InterfaceCancellationReceiptSchema;var assemblyOperations={"timeline.basis":productionRead(TimelineScopeSchema,TimelineBasisSchema,()=>["timeline","basis"]),"timeline.build":productionWrite(BuildTimelineSchema,TimelineBuildReceiptSchema,()=>["timeline"]),"timeline.current":productionRead(TimelineScopeSchema,TimelineViewSchema,()=>["timeline","current"]),"timeline.get":productionRead(TimelineGetSchema,TimelineViewSchema,i=>["timeline","versions",i.versionId],void 0,[["versionId","version.id"]]),"timeline.query":productionRead(TimelineQuerySchema,TimelinePageSchema,()=>["timeline","versions"],pageQuery),"rough-cut.admission-receipt":productionWrite(RoughCutStartSchema,RoughCutAdmissionSchema,()=>["rough-cuts","admission-receipt"],{tenantInBody:true,readOnly:true,identity:[["timelineVersionId","timelineVersionId"],["timelineFingerprint","timelineFingerprint"]]}),"rough-cut.start":productionWrite(RoughCutStartSchema,RoughCutAdmissionSchema,()=>["rough-cuts"],{tenantInBody:true,identity:[["timelineVersionId","timelineVersionId"],["timelineFingerprint","timelineFingerprint"]]}),"rough-cut.get":productionRead(RoughCutGetSchema,RoughCutViewSchema,i=>["rough-cuts",i.renderId],void 0,[["renderId","renderId"]]),"rough-cut.query":productionRead(RoughCutQuerySchema,RoughCutPageSchema,()=>["rough-cuts"],pageQuery),"rough-cut.cancel":productionWrite(RoughCutGetSchema,cancellation,i=>["rough-cuts",i.renderId,"cancel"],{pathFields:["renderId"]}),"rough-cut.review.target":productionRead(RoughCutReviewScopeSchema,RoughCutReviewTargetSchema,i=>["rough-cut-review",i.renderId],void 0,[["renderId","renderId"]]),"rough-cut.review.record":productionWrite(RecordRoughCutReviewSchema,RoughCutReviewReceiptSchema,i=>["rough-cut-review",i.renderId],{pathFields:["renderId"],identity:[["renderId","review.renderId"]]}),"rough-cut.review.query":productionRead(RoughCutReviewQuerySchema,RoughCutReviewPageSchema,i=>["rough-cut-review",i.renderId,"history"],pageQuery,[["renderId","items.*.renderId"]]),"rough-cut.finding.query":productionRead(RoughCutFindingQuerySchema,RoughCutFindingPageSchema,()=>["rough-cut-review","findings"],i=>({...pageQuery(i),renderId:i.renderId}),[["renderId","items.*.renderId"]]),"final-ready.get":productionRead(TimelineScopeSchema,FinalReadyViewSchema,()=>["final-ready"]),"final-ready.decide":productionWrite(DecideFinalReadySchema,FinalReadyReceiptSchema,()=>["final-ready","decisions"],{identity:[["renderId","decision.renderId"],["reviewId","decision.reviewId"]]}),"final-ready.revoke":productionWrite(RevokeFinalReadySchema,FinalReadyReceiptSchema,()=>["final-ready","revoke"]),"final-ready.query":productionRead(FinalReadyQuerySchema,FinalReadyPageSchema,()=>["final-ready","decisions"],pageQuery),"final-render.eligibility":productionRead(TimelineScopeSchema,FinalRenderEligibilitySchema,()=>["final-renders","eligibility"]),"final-render.admission-receipt":productionWrite(FinalRenderStartSchema,FinalRenderAdmissionSchema,()=>["final-renders","admission-receipt"],{tenantInBody:true,readOnly:true,identity:[["timelineVersionId","timelineVersionId"],["timelineFingerprint","timelineFingerprint"]]}),"final-render.start":productionWrite(FinalRenderStartSchema,FinalRenderAdmissionSchema,()=>["final-renders"],{tenantInBody:true,identity:[["selectionId","selectionId"],["timelineVersionId","timelineVersionId"],["timelineFingerprint","timelineFingerprint"]]}),"final-render.get":productionRead(FinalRenderGetSchema,FinalRenderViewSchema,i=>["final-renders",i.renderId],void 0,[["renderId","renderId"]]),"final-render.query":productionRead(FinalRenderQuerySchema,FinalRenderPageSchema,()=>["final-renders"],pageQuery),"final-render.cancel":productionWrite(FinalRenderGetSchema,cancellation,i=>["final-renders",i.renderId,"cancel"],{pathFields:["renderId"]})};var Context=EditorContextInputSchema.extend({tenantId:TenantIdSchema}).refine(i=>i.tenantId.toLowerCase()===i.scope.tenantId.toLowerCase());var Validate=ValidateEditorProposalSchema.safeExtend({tenantId:TenantIdSchema}).refine(i=>i.tenantId.toLowerCase()===i.basis.scope.tenantId.toLowerCase());var editorOperations={"editor.context":operation(Context,EditorContextResultSchema,i=>({method:"POST",tenantId:i.scope.tenantId,path:path("projects",i.scope.projectId,"productions",i.scope.productionId,"editor-intelligence","context"),body:{scope:i.scope,timelineVersionId:i.timelineVersionId}}),[["scope.tenantId","basis.scope.tenantId"],["scope.projectId","basis.scope.projectId"],["scope.productionId","basis.scope.productionId"],["timelineVersionId","timeline.version.id"]],{readOnly:true}),"editor.validate":operation(Validate,EditorValidationResultSchema,i=>({method:"POST",tenantId:i.basis.scope.tenantId,path:path("projects",i.basis.scope.projectId,"productions",i.basis.scope.productionId,"editor-intelligence","proposals","validate"),body:{basis:i.basis,proposal:i.proposal}}),[["basis.scope.tenantId","basis.scope.tenantId"],["basis.scope.projectId","basis.scope.projectId"],["basis.scope.productionId","basis.scope.productionId"],["basis.timelineVersionId","basis.timelineVersionId"],["basis.contextFingerprint","basis.contextFingerprint"]],{readOnly:true})};var Context2=ReviewIntelligenceContextInputSchema.extend({tenantId:TenantIdSchema}).refine(i=>i.tenantId.toLowerCase()===i.scope.tenantId.toLowerCase());var Validate2=ValidateReviewIntelligenceSchema.safeExtend({tenantId:TenantIdSchema}).refine(i=>i.tenantId.toLowerCase()===i.basis.scope.tenantId.toLowerCase());var FinalContext=FinalOutputReviewContextInputSchema.extend({tenantId:TenantIdSchema}).refine(i=>i.tenantId.toLowerCase()===i.scope.tenantId.toLowerCase());var reviewerOperations={"reviewer.final-output-context":operation(FinalContext,FinalOutputReviewContextResultSchema,i=>({method:"POST",tenantId:i.tenantId,path:path("projects",i.scope.projectId,"productions",i.scope.productionId,"review-intelligence","final-output","context"),body:{scope:i.scope,renderId:i.renderId}}),[["scope","basis.scope"],["renderId","basis.renderId"],["renderId","deliveryTarget.renderId"]],{readOnly:true}),"reviewer.context":operation(Context2,ReviewIntelligenceContextResultSchema,i=>({method:"POST",tenantId:i.scope.tenantId,path:path("projects",i.scope.projectId,"productions",i.scope.productionId,"review-intelligence","context"),body:{scope:i.scope,target:i.target}}),[["scope.tenantId","basis.scope.tenantId"],["scope.projectId","basis.scope.projectId"],["scope.productionId","basis.scope.productionId"],["target.kind","basis.target.kind"],["target.renderId","basis.target.renderId"],["target.generationId","basis.target.generationId"],["scope.tenantId","reviewTarget.target.tenantId"],["scope.projectId","reviewTarget.target.projectId"],["scope.productionId","reviewTarget.target.productionId"],["target.kind","reviewTarget.kind"],["target.renderId","reviewTarget.target.renderId"],["target.generationId","reviewTarget.target.generationId"]],{readOnly:true}),"reviewer.validate":operation(Validate2,ReviewIntelligenceValidationResultSchema,i=>({method:"POST",tenantId:i.basis.scope.tenantId,path:path("projects",i.basis.scope.projectId,"productions",i.basis.scope.productionId,"review-intelligence","proposals","validate"),body:{basis:i.basis,proposal:i.proposal}}),[["basis.scope.tenantId","basis.scope.tenantId"],["basis.scope.projectId","basis.scope.projectId"],["basis.scope.productionId","basis.scope.productionId"],["basis.target.kind","basis.target.kind"],["basis.target.renderId","basis.target.renderId"],["basis.target.generationId","basis.target.generationId"],["basis.contextFingerprint","basis.contextFingerprint"],["basis.scope.tenantId","recordDraft.input.tenantId"],["basis.scope.productionId","recordDraft.input.productionId"],["basis.target.kind","recordDraft.kind"],["basis.target.renderId","recordDraft.input.renderId"],["basis.target.generationId","recordDraft.input.generationId"]],{readOnly:true})};var Context3=RepairStrategyContextInputSchema.extend({tenantId:TenantIdSchema}).refine(i=>i.tenantId.toLowerCase()===i.scope.tenantId.toLowerCase());var Validate3=ValidateRepairStrategySchema.safeExtend({tenantId:TenantIdSchema}).refine(i=>i.tenantId.toLowerCase()===i.basis.scope.tenantId.toLowerCase());var Review1Validate=ValidateReview1RepairStrategySchema.safeExtend({tenantId:TenantIdSchema}).refine(i=>i.tenantId.toLowerCase()===i.basis.input.tenantId.toLowerCase());var repairStrategyOperations={"repair-strategy.review1.context":operation(Review1RepairSourceQuerySchema,Review1RepairStrategyContextSchema,i=>({method:"POST",tenantId:i.tenantId,path:path("projects",i.projectId,"productions",i.productionId,"repair-strategy","review1","context"),body:i}),[["tenantId","basis.input.tenantId"],["projectId","basis.input.projectId"],["productionId","basis.input.productionId"],["generationId","basis.input.generationId"],["reviewId","basis.input.reviewId"],["requirementKey","basis.input.requirementKey"]],{readOnly:true}),"repair-strategy.review1.validate":operation(Review1Validate,Review1RepairStrategyValidationSchema,i=>({method:"POST",tenantId:i.tenantId,path:path("projects",i.basis.input.projectId,"productions",i.basis.input.productionId,"repair-strategy","review1","proposals","validate"),body:{basis:i.basis,proposal:i.proposal,...i.budget?{budget:i.budget}:{}}}),[["basis","basis"],["proposal.selectedAlternativeId","selectedAlternativeId"]],{readOnly:true}),"repair-strategy.context":operation(Context3,RepairStrategyContextResultSchema,i=>({method:"POST",tenantId:i.scope.tenantId,path:path("projects",i.scope.projectId,"productions",i.scope.productionId,"repair-strategy","context"),body:{scope:i.scope,findingId:i.findingId}}),[["scope.tenantId","basis.scope.tenantId"],["scope.projectId","basis.scope.projectId"],["scope.productionId","basis.scope.productionId"],["findingId","finding.id"]],{readOnly:true}),"repair-strategy.validate":operation(Validate3,RepairStrategyValidationResultSchema,i=>({method:"POST",tenantId:i.basis.scope.tenantId,path:path("projects",i.basis.scope.projectId,"productions",i.basis.scope.productionId,"repair-strategy","proposals","validate"),body:{basis:i.basis,proposal:i.proposal}}),[["basis.scope.tenantId","basis.scope.tenantId"],["basis.scope.projectId","basis.scope.projectId"],["basis.scope.productionId","basis.scope.productionId"],["basis.findingId","finding.id"],["basis.contextFingerprint","basis.contextFingerprint"],["proposal.selectedAlternativeId","selectedAlternativeId"]],{readOnly:true})};var ownedRequest=(action,i)=>{const{projectId,...body}=i;return{method:"POST",tenantId:i.tenantId,path:path("projects",projectId,"productions",i.productionId,"repairs",action),body}};var Author=AuthorRepairPlanSchema.safeExtend({tenantId:TenantIdSchema}).refine(i=>i.tenantId.toLowerCase()===i.strategy.basis.scope.tenantId.toLowerCase());var canonicalRepairOperations={"canonical-repair.author-review1":operation(AuthorReview1RepairSchema,RepairAuthorReceiptSchema,i=>({method:"POST",tenantId:i.tenantId,path:path("projects",i.projectId,"productions",i.productionId,"repairs","author-review1"),body:i}),[["reviewId","decision.sourceReviewId"],["generationId","decision.review1Source.generationId"],["mediaType","decision.review1Source.mediaType"],["requirementKey","decision.review1Source.requirement.key"]]),"canonical-repair.proof-review1":operation(RecordReview1RepairProofSchema.extend({projectId:ProjectIdSchema}),RepairProofReceiptSchema,i=>ownedRequest("proof-review1",i),[["attemptId","event.attemptId"],["generationId","event.generationId"],["reviewId","event.reviewId"]]),"canonical-repair.author":operation(Author,RepairAuthorReceiptSchema,i=>{const{tenantId,...body}=i;const s=i.strategy.basis.scope;return{method:"POST",tenantId,path:path("projects",s.projectId,"productions",s.productionId,"repairs","author"),body}},[["strategy.basis.scope.tenantId","decision.tenantId"],["strategy.basis.scope.projectId","decision.projectId"],["strategy.basis.scope.productionId","decision.productionId"],["strategy.basis.findingId","decision.basis.findingId"],["strategy.basis.contextFingerprint","decision.basis.contextFingerprint"],["strategy.proposal.selectedAlternativeId","decision.selectedAlternativeId"]]),"canonical-repair.get":operation(RepairPlanScopeSchema.extend({projectId:ProjectIdSchema}),RepairPlanViewSchema,i=>ownedRequest("get",i),[["planId","decision.id"]],{readOnly:true}),"canonical-repair.execute":operation(ExecuteRepairSchema.extend({projectId:ProjectIdSchema}),RepairProgressSchema,i=>ownedRequest("execute",i),[["planId","view.decision.id"]]),"canonical-repair.proof":operation(RecordRepairProofSchema.extend({projectId:ProjectIdSchema}),RepairProofReceiptSchema,i=>ownedRequest("proof",i),[["attemptId","event.attemptId"],["renderId","event.renderId"],["reviewId","event.reviewId"]])};var programmaticReviewOperations={"programmatic-review.target":productionRead(ProgrammaticVideoReviewScopeSchema,ProgrammaticVideoReviewTargetSchema,i=>["video-review","programmatic",i.renderId],void 0,[["renderId","renderId"]]),"programmatic-review.record":productionWrite(RecordProgrammaticVideoReviewSchema,ProgrammaticVideoReviewReceiptSchema,i=>["video-review","programmatic",i.renderId],{pathFields:["renderId"],identity:[["renderId","review.renderId"],["representationId","review.representationId"],["checksumSha256","review.checksumSha256"]]}),"programmatic-review.query":productionRead(ProgrammaticVideoReviewQuerySchema,ProgrammaticVideoReviewPageSchema,i=>["video-review","programmatic",i.renderId,"history"],pageQuery,[["renderId","items.*.renderId"]]),"programmatic-review.decide":productionWrite(DecideProgrammaticShotSchema,ShotDecisionReceiptSchema.extend({decision:ProgrammaticShotAcceptanceDecisionSchema}),i=>["video-review","programmatic",i.renderId,"decisions"],{pathFields:["renderId"],identity:[["renderId","decision.renderId"],["reviewId","decision.reviewId"],["action","decision.action"]]})};var Context4=SourceReviewContextInputSchema.safeExtend({tenantId:TenantIdSchema}).refine(i=>i.tenantId.toLowerCase()===i.scope.tenantId.toLowerCase());var compositionSourceOperations={"composition.source.inspect":productionWrite(CompositionSourceInspectSchema,CompositionSourceInspectionSchema,()=>["compositions","source","inspect"],{readOnly:true,identity:[["compositionId","composition.version.compositionId"],["versionId","composition.version.id"],["fingerprint","composition.version.fingerprint"],["file","window.file"],["startLine","selection.startLine"]]}),"reviewer.source-context":operation(Context4,SourceReviewContextSchema,i=>({method:"POST",tenantId:i.scope.tenantId,path:path("projects",i.scope.projectId,"productions",i.scope.productionId,"review-intelligence","source","context"),body:{scope:i.scope,source:i.source,...i.renderId?{renderId:i.renderId}:{}}}),[["scope.tenantId","basis.input.scope.tenantId"],["scope.projectId","source.composition.version.projectId"],["scope.productionId","source.composition.version.productionId"],["source.compositionId","source.composition.version.compositionId"],["source.versionId","source.composition.version.id"],["source.fingerprint","source.composition.version.fingerprint"],["source.file","source.window.file"],["source.startLine","source.selection.startLine"],["renderId","render.receipt.renderId"]],{readOnly:true})};var Compare=ProgrammaticCompareSchema.safeExtend({tenantId:TenantIdSchema}).refine(i=>i.tenantId.toLowerCase()===i.scope.tenantId.toLowerCase());var Context5=ProgrammaticRecommendationContextInputSchema.safeExtend({tenantId:TenantIdSchema}).refine(i=>i.tenantId.toLowerCase()===i.scope.tenantId.toLowerCase());var Validate4=ValidateProgrammaticRecommendationSchema.safeExtend({tenantId:TenantIdSchema}).refine(i=>i.tenantId.toLowerCase()===i.basis.input.scope.tenantId.toLowerCase());var programmaticExplorationOperations={"exploration.programmatic.compare":operation(Compare,ProgrammaticComparisonSchema,i=>({method:"POST",tenantId:i.scope.tenantId,path:path("projects",i.scope.projectId,"productions",i.scope.productionId,"visual-exploration","programmatic","compare"),body:{scope:i.scope,items:i.items}}),[["scope.tenantId","scope.tenantId"],["scope.projectId","scope.projectId"],["scope.productionId","scope.productionId"],["scope.shotId","scope.shotId"],["items","selection"]],{readOnly:true}),"exploration.programmatic.recommendation.context":operation(Context5,ProgrammaticRecommendationContextSchema,i=>({method:"POST",tenantId:i.scope.tenantId,path:path("projects",i.scope.projectId,"productions",i.scope.productionId,"exploration-recommendation","programmatic","context"),body:{scope:i.scope,items:i.items,criteria:i.criteria}}),[["scope.tenantId","basis.input.scope.tenantId"],["scope.projectId","basis.input.scope.projectId"],["scope.productionId","basis.input.scope.productionId"],["scope.shotId","basis.input.scope.shotId"],["items","basis.input.items"]],{readOnly:true}),"exploration.programmatic.recommendation.validate":operation(Validate4,ProgrammaticRecommendationValidationSchema,i=>({method:"POST",tenantId:i.basis.input.scope.tenantId,path:path("projects",i.basis.input.scope.projectId,"productions",i.basis.input.scope.productionId,"exploration-recommendation","programmatic","proposals","validate"),body:{basis:i.basis,proposal:i.proposal}}),[["basis.contextFingerprint","basis.contextFingerprint"],["basis.input.scope.tenantId","basis.input.scope.tenantId"],["basis.input.scope.projectId","basis.input.scope.projectId"],["basis.input.scope.productionId","basis.input.scope.productionId"],["basis.input.items","basis.input.items"],["proposal.decision.kind","decision.kind"],["proposal.decision.label","decision.label"]],{readOnly:true})};var targetIdentity=prefix=>Object.keys(DeliveryTargetSchema.shape).map(key10=>["target."+key10,prefix+"."+key10]);var deliveryOperations={"delivery.policy.configure":productionWrite(ConfigureDeliveryPolicySchema,DeliveryPolicyReceiptSchema,()=>["deliveries","policy"],{tenantInBody:true}),"delivery.policy.get":productionRead(TimelineScopeSchema,DeliveryPolicyVersionSchema,()=>["deliveries","policy"]),"delivery.snapshot":productionRead(TimelineScopeSchema,DeliverySnapshotSchema,()=>["deliveries","snapshot"]),"delivery.target":productionRead(RoughCutGetSchema,DeliveryTargetSchema,i=>["deliveries","targets",i.renderId],void 0,[["renderId","renderId"]]),"delivery.start":productionWrite(StartDeliveryValidationSchema,DeliveryAdmissionSchema,()=>["deliveries"],{tenantInBody:true,identity:targetIdentity("target")}),"delivery.get":productionRead(DeliveryValidationGetSchema,DeliveryValidationViewSchema,i=>["deliveries",i.validationId],void 0,[["validationId","admission.validationId"]]),"delivery.approve":productionWrite(DecideDeliveryApprovalSchema,DeliveryDecisionReceiptSchema,i=>["deliveries",i.validationId,"approval"],{tenantInBody:true,pathFields:["validationId"],identity:[...targetIdentity("approval.target"),["reviewId","approval.reviewId"],["policyFingerprint","approval.policyFingerprint"],["action","approval.action"]]}),"delivery.cancel":productionWrite(DeliveryValidationGetSchema,cancellation,i=>["deliveries",i.validationId,"cancel"],{pathFields:["validationId"]}),"delivery.manifest":productionRead(DeliveryManifestGetSchema,RegisteredDeliveryManifestSchema,i=>["deliveries","manifests",i.manifestId],void 0,[["manifestId","link.id"]])};var prepare=PrepareShotRequestSchema.extend({projectId:ProjectIdSchema,productionId:ProductionIdSchema,shotId:ShotIdSchema});var shotPreparationOperations={"shot-preparation.prepare":operation(prepare,PrepareShotResultSchema,i=>({method:"POST",tenantId:i.tenantId,path:path("projects",i.projectId,"productions",i.productionId,"shots",i.shotId,"preparations"),body:Object.fromEntries(Object.entries(i).filter(([k])=>!["projectId","productionId","shotId"].includes(k)))}),[["projectId","preparation.basis.projectId"],["shotId","preparation.basis.shotId"],["expectedPlanVersionId","preparation.basis.planVersionId"],["expectedPlanVersion","preparation.basis.planVersion"],["expectedShotPlanningRevision","preparation.basis.shotPlanningRevision"],["target","preparation.target"]]),"shot-preparation.get":productionRead(PreparationGetInputSchema,PreparationViewSchema,i=>["shot-preparations",i.preparationId],void 0,[["preparationId","preparation.id"]]),"shot-preparation.active":productionRead(PreparationActiveInputSchema,PreparationViewSchema,i=>["shots",i.shotId,"preparations","active"],i=>({mediaType:i.mediaType}),[["shotId","preparation.basis.shotId"],["mediaType","preparation.target.mediaType"]]),"shot-preparation.query":productionRead(PreparationQueryInputSchema,PreparationQueryPageSchema,()=>["shot-preparations"],i=>({...pageQuery(i),shotId:i.shotId,mediaType:i.mediaType}),[["shotId","items.*.preparation.basis.shotId"],["mediaType","items.*.preparation.target.mediaType"]])};var generationOperations={"keyframe.device.quote":productionWrite(KeyframeStartInputSchema,GenerationCostQuoteSchema.nullable(),()=>["keyframe-generations","device","quote"],{tenantInBody:true,readOnly:true}),"keyframe.device.start":productionWrite(KeyframeDeviceStartInputSchema,KeyframeAdmissionSchema,()=>["keyframe-generations","device"],{tenantInBody:true,identity:[["contractId","contractId"]]}),"keyframe.start":productionWrite(KeyframeStartInputSchema,KeyframeAdmissionSchema,()=>["keyframe-generations"],{tenantInBody:true,identity:[["contractId","contractId"]]}),"keyframe.get":productionRead(KeyframeGetInputSchema,KeyframeGenerationViewSchema,i=>["keyframe-generations",i.generationId],void 0,[["generationId","generationId"]]),"keyframe.query":productionRead(KeyframeQueryInputSchema,KeyframeQueryPageSchema,()=>["keyframe-generations"],i=>({...pageQuery(i),shotId:i.shotId}),[["shotId","items.*.shotId"]]),"keyframe.cancel":productionWrite(KeyframeGetInputSchema,InterfaceCancellationReceiptSchema,i=>["keyframe-generations",i.generationId,"cancel"],{pathFields:["generationId"]}),"video.start":productionWrite(VideoStartInputSchema,VideoAdmissionSchema,()=>["video-generations"],{tenantInBody:true,identity:[["contractId","contractId"]]}),"video.device.quote":productionWrite(VideoStartInputSchema,GenerationCostQuoteSchema.nullable(),()=>["video-generations","device","quote"],{tenantInBody:true,readOnly:true}),"video.device.start":productionWrite(VideoDeviceStartInputSchema,VideoAdmissionSchema,()=>["video-generations","device"],{tenantInBody:true,identity:[["contractId","contractId"]]}),"video.get":productionRead(VideoGetInputSchema,VideoGenerationViewSchema,i=>["video-generations",i.generationId],void 0,[["generationId","generationId"]]),"video.query":productionRead(VideoQueryInputSchema,VideoQueryPageSchema,()=>["video-generations"],i=>({...pageQuery(i),shotId:i.shotId}),[["shotId","items.*.shotId"]]),"video.cancel":productionWrite(VideoGetInputSchema,InterfaceCancellationReceiptSchema,i=>["video-generations",i.generationId,"cancel"],{pathFields:["generationId"]})};var keyframeReviewOperations={"keyframe-review.target":productionRead(KeyframeReviewScopeSchema,KeyframeReviewTargetSchema,i=>["keyframe-review",i.generationId],void 0,[["generationId","generationId"]]),"keyframe-review.record":productionWrite(RecordKeyframeReviewSchema,KeyframeReviewReceiptSchema,i=>["keyframe-review",i.generationId],{pathFields:["generationId"],identity:[["generationId","review.generationId"],["candidateId","review.candidateId"],["representationId","review.representationId"],["checksumSha256","review.checksumSha256"]]}),"keyframe-review.query":productionRead(KeyframeReviewQuerySchema,KeyframeReviewPageSchema,i=>["keyframe-review",i.generationId,"history"],pageQuery,[["generationId","items.*.generationId"]]),"keyframe-review.decide":productionWrite(DecideKeyframeSchema,KeyframeDecisionReceiptSchema,i=>["keyframe-review",i.generationId,"decisions"],{pathFields:["generationId"],identity:[["generationId","decision.generationId"],["candidateId","decision.candidateId"],["reviewId","decision.reviewId"],["action","decision.action"]]}),"keyframe-reference.get":productionRead(KeyframeReferenceScopeSchema,KeyframeReferenceViewSchema,i=>["keyframe-review","references",i.shotId,i.framePurpose],void 0,[["shotId","shotId"],["framePurpose","framePurpose"]]),"keyframe-reference.query":productionRead(KeyframeDecisionQuerySchema,KeyframeDecisionPageSchema,i=>["keyframe-review","references",i.shotId,i.framePurpose,"history"],pageQuery,[["shotId","items.*.shotId"],["framePurpose","items.*.framePurpose"]]),"keyframe-reference.revoke":productionWrite(RevokeKeyframeSchema,KeyframeDecisionReceiptSchema,i=>["keyframe-review","references",i.shotId,i.framePurpose,"revoke"],{pathFields:["shotId","framePurpose"],identity:[["shotId","decision.shotId"],["framePurpose","decision.framePurpose"],["acceptanceId","decision.previousAcceptanceId"]]})};var videoReviewOperations={"video-review.target":productionRead(VideoReviewScopeSchema,VideoReviewTargetSchema,i=>["video-review",i.generationId],void 0,[["generationId","generationId"]]),"video-review.record":productionWrite(RecordVideoReviewSchema,VideoReviewReceiptSchema,i=>["video-review",i.generationId],{pathFields:["generationId"],identity:[["generationId","review.generationId"],["candidateId","review.candidateId"],["representationId","review.representationId"],["checksumSha256","review.checksumSha256"]]}),"video-review.query":productionRead(VideoReviewQuerySchema,VideoReviewPageSchema,i=>["video-review",i.generationId,"history"],pageQuery,[["generationId","items.*.generationId"]]),"video-review.decide":productionWrite(DecideVideoShotSchema,ShotDecisionReceiptSchema.extend({decision:GeneratedShotAcceptanceDecisionSchema}),i=>["video-review",i.generationId,"decisions"],{pathFields:["generationId"],identity:[["generationId","decision.generationId"],["candidateId","decision.candidateId"],["reviewId","decision.reviewId"],["action","decision.action"]]}),"shot-acceptance.get":productionRead(ShotAcceptanceScopeSchema,ShotAcceptanceViewSchema,i=>["video-review","shots",i.shotId,"acceptance"],void 0,[["shotId","shotId"]]),"shot-acceptance.query":productionRead(ShotDecisionQuerySchema,ShotDecisionPageSchema,i=>["video-review","shots",i.shotId,"decisions"],pageQuery,[["shotId","items.*.shotId"]]),"shot-acceptance.revoke":productionWrite(RevokeShotAcceptanceSchema,ShotDecisionReceiptSchema,i=>["video-review","shots",i.shotId,"revoke"],{pathFields:["shotId"],identity:[["shotId","decision.shotId"],["acceptanceId","decision.previousAcceptanceId"]]})};import{z as z68}from"zod";var providerOperations={"provider.model.get":operation(ProviderModelGetSchema,ProviderModelViewSchema,i=>({method:"GET",tenantId:i.tenantId,path:path("provider-models",i.id),query:{version:i.version}}),[["id","id"],["version","version"]]),"provider.model.query":operation(ProviderTenantInputSchema,ProviderModelPageSchema,i=>({method:"GET",tenantId:i.tenantId,path:path("provider-models")})),"provider.model.configure":operation(ConfigureProviderModelSchema,ProviderModelViewSchema,i=>({method:"POST",tenantId:i.tenantId,path:path("provider-models","configure"),body:i}),[["definition.profile.id","id"],["definition.profile.version","version"]]),"provider.model.disable":operation(DisableProviderModelSchema,z68.strictObject({disabled:z68.literal(true)}),i=>({method:"POST",tenantId:i.tenantId,path:path("provider-models","disable"),body:i})),"provider.configure":operation(ConfigureProviderInputSchema,ProviderConnectionViewSchema,i=>({method:"POST",tenantId:i.tenantId,path:path("provider-connections","configure"),body:i}),[["connectionId","connectionId"],["configuration","configuration"]]),"provider.query":operation(ProviderTenantInputSchema,ProviderConnectionPageSchema,i=>({method:"GET",tenantId:i.tenantId,path:path("provider-connections")})),"provider.models":operation(ProviderTenantInputSchema,ProviderModelsViewSchema,i=>({method:"GET",tenantId:i.tenantId,path:path("provider-connections","models")})),"provider.keyframe-default.set":operation(SetKeyframeDefaultSchema,ProviderDefaultViewSchema,i=>({method:"POST",tenantId:i.tenantId,path:path("provider-connections","keyframe-default"),body:i}),[["selection","selection"]]),"provider.disable":operation(ProviderConnectionCommandSchema,z68.strictObject({disabled:z68.literal(true)}),i=>({method:"POST",tenantId:i.tenantId,path:path("provider-connections","disable"),body:i})),"provider.revoke":operation(ProviderCredentialRevokeSchema,z68.strictObject({revoked:z68.literal(true)}),i=>({method:"POST",tenantId:i.tenantId,path:path("provider-connections","revoke"),body:i}))};import{z as z69}from"zod";var observationOperations={"media-observation.device.quote":productionWrite(QwenAsrDeviceQuoteInputSchema,QwenAsrCostQuoteSchema,()=>["media-observations","device","quote"],{readOnly:true}),"media-observation.device.start":productionWrite(QwenAsrDeviceStartSchema,QwenAsrDeviceAdmissionSchema,()=>["media-observations","device"]),"media-observation.device.get":productionRead(ObservationGetSchema,QwenAsrDeviceViewSchema,q=>["media-observations","device",q.observationId],void 0,[["observationId","observationId"]]),"media-observation.start-local":productionWrite(LocalObservationStartSchema,LocalObservationAdmissionSchema,()=>["media-observations","local"]),"media-observation.get-local":productionRead(ObservationGetSchema,LocalObservationViewSchema,q=>["media-observations","local",q.observationId],void 0,[["observationId","observationId"]]),"production-guidance.context":productionRead(ObservationScopeSchema,ProductionGuidanceContextSchema,()=>["media-observations","context"]),"media-observation.options":productionRead(ObservationScopeSchema,ObservationOptionsSchema,()=>["media-observations","options"]),"media-observation.start":productionWrite(ObservationStartSchema,ObservationAdmissionSchema,()=>["media-observations"]),"media-observation.get":productionRead(ObservationGetSchema,ObservationViewSchema,q=>["media-observations",q.observationId],void 0,[["observationId","observationId"]]),"media-observation.cancel":productionWrite(ObservationGetSchema,z69.strictObject({cancellationRequested:z69.boolean()}),q=>["media-observations",q.observationId,"cancel"],{pathFields:["observationId"]})};import{z as z70}from"zod";var speechOperations={"speech.device.quote":productionWrite(SpeechStartSchema,SpeechCostQuoteSchema.nullable(),()=>["speech-generations","device","quote"],{readOnly:true}),"speech.device.start":productionWrite(SpeechDeviceStartSchema,SpeechAdmissionSchema,()=>["speech-generations","device"]),"speech.start-local":productionWrite(LocalSpeechStartSchema,LocalSpeechAdmissionSchema,()=>["speech-generations","local"]),"speech.get-local":productionRead(SpeechGetSchema,LocalSpeechGenerationViewSchema,q=>["speech-generations","local",q.generationId],void 0,[["generationId","generationId"]]),"speech.options":productionRead(SpeechScopeSchema,SpeechOptionsSchema,()=>["speech-generations","options"]),"speech.start":productionWrite(SpeechStartSchema,SpeechAdmissionSchema,()=>["speech-generations"]),"speech.get":productionRead(SpeechGetSchema,SpeechGenerationViewSchema,q=>["speech-generations",q.generationId],void 0,[["generationId","generationId"]]),"speech.cancel":productionWrite(SpeechGetSchema,z70.strictObject({cancellationRequested:z70.boolean()}),q=>["speech-generations",q.generationId,"cancel"],{pathFields:["generationId"]})};var voiceProfileOperations={"voice-profile.set-reference":operation(VoiceProfileSetReferenceSchema,VoiceProfileReceiptSchema,({voiceProfileId,...body})=>({method:"POST",tenantId:body.tenantId,path:path("voice-profiles",voiceProfileId,"reference"),body}),[["voiceProfileId","voiceProfileId"]]),"voice-profile.reference":operation(VoiceReferenceGetSchema,VoiceReferenceSchema,i=>({method:"GET",tenantId:i.tenantId,path:path("voice-profiles",i.voiceProfileId,"references",i.referenceId)}),[["voiceProfileId","voiceProfileId"],["referenceId","id"]],{readOnly:true}),"voice-profile.create":operation(VoiceProfileCreateSchema,VoiceProfileReceiptSchema,i=>({method:"POST",tenantId:i.tenantId,path:path("voice-profiles"),body:i})),"voice-profile.revise":operation(VoiceProfileReviseSchema,VoiceProfileReceiptSchema,({voiceProfileId,...body})=>({method:"POST",tenantId:body.tenantId,path:path("voice-profiles",voiceProfileId,"draft"),body}),[["voiceProfileId","voiceProfileId"]]),"voice-profile.publish":operation(VoiceProfilePublishSchema,VoiceProfileReceiptSchema,({voiceProfileId,...body})=>({method:"POST",tenantId:body.tenantId,path:path("voice-profiles",voiceProfileId,"publish"),body}),[["voiceProfileId","voiceProfileId"]]),"voice-profile.set-enabled":operation(VoiceProfileSetEnabledSchema,VoiceProfileReceiptSchema,({voiceProfileId,...body})=>({method:"POST",tenantId:body.tenantId,path:path("voice-profiles",voiceProfileId,"availability"),body}),[["voiceProfileId","voiceProfileId"],["enabled","enabled"]]),"voice-profile.list":operation(VoiceProfileListSchema,VoiceProfilePageSchema,({tenantId,...query})=>({method:"GET",tenantId,path:path("voice-profiles"),query}),[],{readOnly:true}),"voice-profile.get":operation(VoiceProfileScopeSchema,VoiceProfileViewSchema,i=>({method:"GET",tenantId:i.tenantId,path:path("voice-profiles",i.voiceProfileId)}),[["voiceProfileId","voiceProfileId"]],{readOnly:true}),"voice-profile.version":operation(VoiceProfileVersionQuerySchema,VoiceProfileVersionSchema,i=>({method:"GET",tenantId:i.tenantId,path:path("voice-profiles",i.voiceProfileId,"versions",String(i.version))}),[["voiceProfileId","ref.voiceProfileRef"],["tenantId","ref.ownerTenantRef"],["version","ref.version"]],{readOnly:true})};var voiceReviewOperations={"voice-review.target":operation(VoiceReviewTargetQuerySchema,VoiceReviewTargetSchema,({tenantId,voiceProfileId,...query})=>({method:"GET",tenantId,path:path("voice-profiles",voiceProfileId,"review-target"),query}),[["voiceProfileId","voiceProfileId"],["audioVersionId","audioVersionId"]],{readOnly:true}),"voice-review.record":operation(RecordVoiceReviewSchema,VoiceReviewReceiptSchema,({voiceProfileId,...body})=>({method:"POST",tenantId:body.tenantId,path:path("voice-profiles",voiceProfileId,"reviews"),body}),[["voiceProfileId","review.voiceProfileId"],["audioVersionId","review.audioVersionId"],["referenceId","review.basis.reference.id"]]),"voice-review.get":operation(VoiceReviewGetSchema,VoiceReviewViewSchema,i=>({method:"GET",tenantId:i.tenantId,path:path("voice-profiles",i.voiceProfileId,"reviews",i.reviewId)}),[["voiceProfileId","review.voiceProfileId"],["reviewId","review.id"]],{readOnly:true})};var soundMakingPlanOperations={"sound-plan.context":productionRead(SoundPlanScopeSchema,SoundPlanContextSchema,()=>["sound-making-plan","context"],()=>({}),[["tenantId","tenantId"],["productionId","productionId"]]),"sound-plan.get":productionRead(SoundPlanGetSchema,SoundPlanViewSchema,()=>["sound-making-plan"],q=>({versionId:q.versionId}),[["tenantId","version.tenantId"],["productionId","version.productionId"],["versionId","version.id"]]),"sound-plan.validate":productionWrite(SoundPlanValidateSchema,SoundPlanValidationSchema,()=>["sound-making-plan","validate"],{readOnly:true}),"sound-plan.accept":productionWrite(SoundPlanAcceptSchema,SoundPlanReceiptSchema,()=>["sound-making-plan"],{identity:[["tenantId","version.tenantId"],["productionId","version.productionId"]]})};import{z as z71}from"zod";var post2=(input,output,action,identity2=[],readOnly=false)=>operation(input,output,i=>({method:"POST",tenantId:i.tenantId,path:path("lifecycle-events",action),body:i}),identity2,{readOnly});var lifecycleEventOperations={"production.feedback":post2(ProductionFeedbackInputSchema,ProductionFeedbackResultSchema,"feedback",[],true),"production.events.read":post2(ReadProductionEventsSchema,ProductionEventReadSchema,"read",[],true),"webhook.configure":post2(ConfigureWebhookSchema,WebhookSubscriptionSchema,"configure",[["subscriptionId","subscriptionId"]]),"webhook.secret.prepare":post2(PrepareWebhookSecretSchema,WebhookSecretReferenceSchema,"secret-prepare",[["subscriptionId","subscriptionId"],["secretRef","secretRef"]]),"webhook.configure-reference":post2(ConfigureWebhookReferenceSchema,WebhookSubscriptionSchema,"configure-reference",[["subscriptionId","subscriptionId"]]),"webhook.disable":post2(DisableWebhookSchema,WebhookSubscriptionSchema,"disable",[["subscriptionId","subscriptionId"]]),"webhook.replay":post2(ReplayWebhookSchema,WebhookReplayReceiptSchema,"replay",[["eventId","eventId"]]),"lifecycle-event.capabilities":post2(LifecycleEventScopeSchema,LifecycleEventCapabilitiesSchema,"capabilities",[],true),"lifecycle-event.subscriptions":post2(QueryLifecycleEventsSchema.safeExtend({kind:z71.literal("subscriptions")}),WebhookSubscriptionPageSchema,"query",[["subscriptionId","items.*.subscriptionId"]],true),"lifecycle-event.events":post2(QueryLifecycleEventsSchema.safeExtend({kind:z71.literal("events")}),ExternalLifecycleEventPageSchema,"query",[],true),"lifecycle-event.deliveries":post2(QueryLifecycleEventsSchema.safeExtend({kind:z71.literal("deliveries")}),WebhookDeliveryPageSchema,"query",[["subscriptionId","items.*.subscriptionId"],["deliveryId","items.*.deliveryId"]],true),"lifecycle-event.attempts":post2(QueryLifecycleEventsSchema.safeExtend({kind:z71.literal("attempts")}),WebhookAttemptPageSchema,"query",[],true)};var renderTicket=resource=>operation(TenantRenderMediaInputSchema,TenantRenderMediaTicketSchema,i=>({method:"GET",tenantId:i.tenantId,path:path("productions",i.productionId,resource,i.renderId,"media-ticket"),query:{role:i.role}}),[["renderId","renderId"],["role","role"],["role","ticket.object.role"]],{readOnly:true});var mediaDescriptorOperations={"rough-cut.media-ticket":renderTicket("rough-cuts"),"final-render.media-ticket":renderTicket("final-renders"),"composition.render.media-target":descriptorOperation(CompositionRenderGetSchema,CompositionRenderMediaDescriptorSchema,i=>({method:"GET",tenantId:i.tenantId,path:path("productions",i.productionId,"compositions","renders",i.renderId,"media-target")}),i=>path("productions",i.productionId,"compositions","renders",i.renderId,"media")),"delivery.download":descriptorOperation(TimelineScopeSchema,InterfaceDeliveryDownloadDescriptorSchema,i=>({method:"GET",tenantId:i.tenantId,path:path("productions",i.productionId,"deliveries","download")}),(i,o)=>o.method==="POST"?tenantMediaDownloadPath:path("productions",i.productionId,"deliveries","media")),"temporal-evidence.download":descriptorOperation(TemporalEvidenceMediaSchema,InterfaceDownloadDescriptorSchema,i=>({method:"GET",tenantId:i.tenantId,path:path("productions",i.productionId,"temporal-evidence",i.evidenceId,"media",i.kind,"descriptor"),query:i.kind==="FRAME"?{ordinal:i.ordinal}:{}}),i=>path("productions",i.productionId,"temporal-evidence",i.evidenceId,"media",i.kind)+(i.kind==="FRAME"?"?ordinal="+i.ordinal:"")),"video.options":operation(VideoOptionsInputSchema,VideoOptionsSchema,i=>({method:"GET",tenantId:i.tenantId,path:path("video-options")}),[],{readOnly:true})};var referencePreviewOperations={"studio.capabilities":mcpOperation(StudioCapabilitiesInputSchema,StudioCapabilitiesSchema,true),"reference-preview.start":operation(StartReferencePreviewSchema,ReferencePreviewAdmissionSchema,i=>{const{tenantId,productionId,...body}=i;return{method:"POST",tenantId,path:path("productions",productionId,"reference-previews"),body}},[["sourceArtifactId","sourceArtifactId"],["expectedBriefVersion","briefVersion"]],{readOnly:false}),"reference-preview.status":operation(ReferencePreviewOperationInputSchema,OperationSummarySchema,i=>({method:"GET",tenantId:i.tenantId,path:path("productions",i.productionId,"reference-previews",i.operationId,"status"),query:{projectId:i.projectId}}),[["operationId","id"]],{readOnly:true}),"reference-preview.get":operation(ReferencePreviewOperationInputSchema,ReferencePreviewReadResultSchema,i=>({method:"GET",tenantId:i.tenantId,path:path("productions",i.productionId,"reference-previews",i.operationId),query:{projectId:i.projectId}}),[],{readOnly:true}),"reference-preview.cancel":operation(ReferencePreviewOperationInputSchema,ReferencePreviewCancelResultSchema,i=>({method:"POST",tenantId:i.tenantId,path:path("productions",i.productionId,"reference-previews",i.operationId,"cancel"),body:{projectId:i.projectId}}),[],{readOnly:false})};var Context6=ExplorationContextInputSchema.safeExtend({tenantId:TenantIdSchema}).refine(i=>i.tenantId.toLowerCase()===i.scope.tenantId.toLowerCase());var Plan=ValidateExplorationPlanSchema.safeExtend({tenantId:TenantIdSchema}).refine(i=>i.tenantId.toLowerCase()===i.basis.tenantId.toLowerCase());var Compare2=ExplorationCompareInputSchema.extend({tenantId:TenantIdSchema}).refine(i=>i.tenantId.toLowerCase()===i.scope.tenantId.toLowerCase());var Recommendation=ExplorationRecommendationContextInputSchema.safeExtend({tenantId:TenantIdSchema}).refine(i=>i.tenantId.toLowerCase()===i.scope.tenantId.toLowerCase());var Validate5=ValidateExplorationRecommendationSchema.safeExtend({tenantId:TenantIdSchema}).refine(i=>i.tenantId.toLowerCase()===i.basis.input.scope.tenantId.toLowerCase());var route3=(s,family,...suffix)=>path("projects",s.projectId,"productions",s.productionId,family,...suffix);var ownerOperations={"exploration.context":operation(Context6,ExplorationContextResultSchema,i=>({method:"POST",tenantId:i.tenantId,path:route3(i.scope,"visual-exploration","context"),body:{scope:i.scope,preparationIds:i.preparationIds}}),[["scope.tenantId","basis.tenantId","SUCCESS"],["scope.projectId","basis.projectId","SUCCESS"],["scope.productionId","basis.productionId","SUCCESS"],["scope.shotId","basis.shotId","SUCCESS"]],{readOnly:true}),"exploration.plan.validate":operation(Plan,ExplorationValidationResultSchema,i=>({method:"POST",tenantId:i.tenantId,path:route3(i.basis,"visual-exploration","plans","validate"),body:{basis:i.basis,plan:i.plan}}),[["basis","basis","SUCCESS"]],{readOnly:true}),"exploration.compare":operation(Compare2,ExplorationComparisonResultSchema,i=>({method:"POST",tenantId:i.tenantId,path:route3(i.scope,"visual-exploration","compare"),body:{scope:i.scope,items:i.items}}),[["scope","scope"]],{readOnly:true}),"exploration.recommendation.context":operation(Recommendation,ExplorationRecommendationContextResultSchema,i=>({method:"POST",tenantId:i.tenantId,path:route3(i.scope,"exploration-recommendation","context"),body:{scope:i.scope,items:i.items,criteria:i.criteria}}),[["scope","basis.input.scope"],["items","basis.input.items"],["criteria","basis.input.criteria"]],{readOnly:true}),"exploration.recommendation.validate":operation(Validate5,ExplorationRecommendationValidationResultSchema,i=>({method:"POST",tenantId:i.tenantId,path:route3(i.basis.input.scope,"exploration-recommendation","proposals","validate"),body:{basis:i.basis,proposal:i.proposal}}),[["basis","basis"],["proposal.decision.kind","decision.kind"],["proposal.decision.label","decision.label"]],{readOnly:true})};var visualExplorationOperations=ownerOperations;import{z as z72}from"zod";var ownerOperations2={"imported-visual.query":productionRead(ImportedVisualOriginalQuerySchema,ImportedVisualOriginalPageSchema,()=>["imported-visuals","originals"],i=>({limit:i.limit,afterSourceId:i.afterSourceId,shotId:i.shotId}),[["shotId","items.*.shotId"]]),"imported-visual.register-source":productionWrite(LegacyImportedVisualProjectSourceSchema,ImportedVisualOriginalViewSchema,()=>["imported-visuals","originals","from-source"],{identity:[["projectId","projectId"],["shotId","shotId"]]}),"imported-visual.start-from-source":productionWrite(ImportedVisualFromProjectSourceSchema,DirectOriginalSubmitSchema,()=>["imported-visuals","originals","from-source","v1"]),"imported-visual.register":operation(LegacyImportedVisualUploadSchema,ImportedVisualOriginalViewSchema,i=>{const{contentBase64,tenantId,productionId,...fields}=i;return{method:"POST",tenantId,path:path("productions",productionId,"imported-visuals","originals","bytes"),importedVideo:{bytes:Buffer.from(contentBase64,"base64"),metadata:Buffer.from(JSON.stringify(fields)).toString("base64url")}}},[["shotId","shotId"]]),"imported-visual.revise":productionWrite(LegacyImportedVisualRevisionSchema,ImportedVisualOriginalViewSchema,i=>["imported-visuals","originals",i.sourceId,"revisions"],{pathFields:["sourceId"],identity:[["sourceId","sourceId"],["shotId","shotId"]]}),"imported-visual.original":productionRead(ImportedVisualOriginalGetSchema,ImportedVisualOriginalViewSchema,i=>["imported-visuals","originals",i.sourceId],i=>({version:i.version}),[["sourceId","sourceId"],["version","version"]]),"imported-visual.history":productionRead(ImportedVisualOriginalHistoryQuerySchema,ImportedVisualOriginalHistorySchema,i=>["imported-visuals","originals",i.sourceId,"history"],i=>({limit:i.limit,beforeVersion:i.beforeVersion}),[["sourceId","sourceId"],["sourceId","items.*.sourceId"]]),"imported-visual.normalize":productionWrite(ImportedVisualNormalizeStartSchema,ImportedVisualAdmissionSchema,()=>["imported-visuals","normalizations"],{identity:[["sourceId","sourceId"],["sourceVersionId","sourceVersionId"]]}),"imported-visual.get":productionRead(ImportedVisualGetSchema,ImportedVisualNormalizationViewSchema,i=>["imported-visuals","normalizations",i.normalizationId],void 0,[["normalizationId","normalizationId"]]),"imported-visual.review.target":productionRead(ImportedVisualGetSchema,ImportedVisualReviewTargetSchema,i=>["imported-visuals","normalizations",i.normalizationId,"review-target"],void 0,[["normalizationId","normalizationId"]]),"imported-visual.review.record":productionWrite(ImportedVisualReviewSchema,ImportedVideoReviewReceiptSchema,i=>["imported-visuals","normalizations",i.normalizationId,"reviews"],{pathFields:["normalizationId"],identity:[["normalizationId","review.normalizationId"],["representationId","review.representationId"],["checksumSha256","review.checksumSha256"]]}),"imported-visual.decide":productionWrite(ImportedVisualDecisionSchema,ShotDecisionReceiptSchema,i=>["imported-visuals","normalizations",i.normalizationId,"decisions"],{pathFields:["normalizationId"],identity:[["normalizationId","decision.normalizationId"],["reviewId","decision.reviewId"]]}),"imported-visual.cancel":productionWrite(ImportedVisualGetSchema,z72.strictObject({cancellationRequested:z72.boolean()}),i=>["imported-visuals","normalizations",i.normalizationId,"cancel"],{pathFields:["normalizationId"]})};var importedVisualOperations=ownerOperations2;var versionPath=i=>["source-sync-audios","shots",i.shotId,"versions",i.versionId];var ownerOperations3={"source-sync.start":productionWrite(SourceSyncRuntimeStartSchema,SourceSyncRuntimeAdmissionSchema,()=>["source-sync-audios","requests"]),"source-sync.get":productionRead(SourceSyncRuntimeScopeSchema,SourceSyncRuntimeViewSchema,i=>["source-sync-audios","requests",i.requestId],void 0,[["requestId","requestId"]]),"source-sync.cancel":productionWrite(SourceSyncRuntimeScopeSchema,ImportedVisualCancellationSchema,i=>["source-sync-audios","requests",i.requestId,"cancel"],{pathFields:["requestId"]}),"source-sync.audio":productionRead(SourceSyncAudioGetSchema,WavExportResultSchema,i=>[...versionPath(i),"audio"]),"source-sync.version":productionRead(SourceSyncAudioGetSchema,SourceSyncAudioViewSchema,versionPath,void 0,[["versionId","version.id"],["shotId","version.shotId"]]),"source-sync.review.target":productionRead(SourceSyncAudioGetSchema,SourceSyncReviewTargetSchema,i=>[...versionPath(i),"review-target"],void 0,[["versionId","version.id"],["shotId","version.shotId"]]),"source-sync.review.record":productionWrite(SourceSyncReviewInputSchema,SourceSyncReviewRecordSchema,i=>[...versionPath(i),"reviews"],{pathFields:["shotId","versionId"],identity:[["versionId","versionId"],["shotId","shotId"],["audio","audio"],["visual","visual"]]}),"source-sync.review.get":productionRead(SourceSyncReviewGetSchema,SourceSyncReviewRecordSchema,i=>[...versionPath(i),"reviews",i.reviewId],void 0,[["versionId","versionId"],["shotId","shotId"],["reviewId","id"]])};var sourceSyncOperations=ownerOperations3;var Writer=ValidateWriterProposalSchema.extend({tenantId:TenantIdSchema}).refine(i=>i.tenantId.toLowerCase()===i.basis.tenantId.toLowerCase());var Director=ValidateDirectorProposalSchema.safeExtend({tenantId:TenantIdSchema}).refine(i=>i.tenantId.toLowerCase()===i.basis.tenantId.toLowerCase());var projectProduction2=(scope4,...suffix)=>path("projects",scope4.projectId,"productions",scope4.productionId,...suffix);var planningIntelligenceOperations={"brief.active":operation(WriterScopeSchema,WriterBriefResultSchema,i=>({method:"GET",tenantId:i.tenantId,path:projectProduction2(i,"brief-versions","active")})),"writer.validate":operation(Writer,WriterValidationResultSchema,i=>({method:"POST",tenantId:i.tenantId,path:projectProduction2(i.basis,"writer-proposals","validate"),body:{basis:i.basis,proposal:i.proposal,...i.revisionReason?{revisionReason:i.revisionReason}:{}}}),[["basis","basis","SUCCESS"]],{readOnly:true}),"director.context":operation(DirectorScopeSchema,DirectorContextResultSchema,i=>({method:"GET",tenantId:i.tenantId,path:projectProduction2(i,"director","context")})),"director.validate":operation(Director,DirectorValidationResultSchema,i=>({method:"POST",tenantId:i.tenantId,path:projectProduction2(i.basis,"director-proposals","validate"),body:{basis:i.basis,proposal:i.proposal,...i.revisionReason?{revisionReason:i.revisionReason}:{}}}),[["basis","basis","SUCCESS"]],{readOnly:true}),"consistency-profile.get":productionRead(ConsistencyProfileScopeSchema,ConsistencyProfileViewSchema,()=>["consistency-profile"]),"consistency-profile.version":productionRead(ConsistencyProfileVersionQuerySchema,ConsistencyProfileVersionSchema,i=>["consistency-profile","versions",i.profileId],void 0,[["profileId","id"]]),"consistency-profile.configure":productionWrite(ConfigureConsistencyProfileSchema,ConsistencyProfileReceiptSchema,()=>["consistency-profile"],{tenantInBody:true})};var audioCaptionOperations={"caption.transcript_draft":productionWrite(CaptionTranscriptPlanSchema,CaptionTranscriptDraftSchema,()=>["captions","transcript-draft"],{readOnly:true}),"caption.author_transcript":productionWrite(AuthorTranscriptCaptionsSchema,CaptionReceiptSchema,()=>["captions","from-transcript"]),"audio.export":operation(AudioGetSchema,AudioExportResultSchema,i=>({method:"GET",tenantId:i.tenantId,path:path("productions",i.productionId,"audio",i.purpose,"versions",i.versionId,"export-data")}),[],{readOnly:true}),"caption.export":operation(CaptionExportSchema,CaptionExportResultSchema,i=>({method:"GET",tenantId:i.tenantId,path:path("productions",i.productionId,"captions","versions",i.versionId,"export-data"),query:{format:i.format}}),[],{readOnly:true}),"audio.basis":productionRead(AudioReadScopeSchema,AudioBasisSchema,i=>["audio",i.purpose,"basis"],void 0,[["purpose","purpose"]]),"audio.current":productionRead(AudioReadScopeSchema,AudioViewSchema,i=>["audio",i.purpose,"current"],void 0,[["purpose","version.purpose"]]),"audio.get":productionRead(AudioGetSchema,AudioViewSchema,i=>["audio",i.purpose,"versions",i.versionId],void 0,[["versionId","version.id"],["purpose","version.purpose"]]),"audio.query":productionRead(AudioQuerySchema,AudioPageSchema,i=>["audio",i.purpose,"versions"],pageQuery,[["purpose","items.*.version.purpose"]]),"audio.import":productionWrite(AudioImportRequestSchema,AudioReceiptSchema,i=>["audio",i.purpose],{pathFields:["purpose"],identity:[["purpose","version.purpose"]]}),"caption.basis":productionRead(CaptionScopeSchema,CaptionBasisSchema,()=>["captions","basis"]),"caption.current":productionRead(CaptionScopeSchema,CaptionViewSchema,()=>["captions","current"]),"caption.get":productionRead(CaptionGetSchema,CaptionViewSchema,i=>["captions","versions",i.versionId],void 0,[["versionId","version.id"]]),"caption.query":productionRead(CaptionQuerySchema,CaptionPageSchema,()=>["captions","versions"],pageQuery),"caption.author":productionWrite(AuthorCaptionsSchema,CaptionReceiptSchema,()=>["captions"])};var discoveryOperations={"artifact.query":operation(ArtifactDiscoveryQuerySchema,ArtifactDiscoveryPageSchema,input=>({method:"GET",tenantId:input.tenantId,path:path("artifact-discovery"),query:{...pageQuery(input),projectId:input.projectId,productionId:input.productionId,artifactId:input.artifactId,mediaCategory:input.mediaCategory,family:input.family,search:input.search,lifecycle:input.lifecycle}}),[["artifactId","items.*.artifactId"]])};var temporalEvidenceOperations={"temporal-evidence.read-video":productionWrite(OriginalVideoReadSchema,OriginalVideoResultSchema,()=>["temporal-evidence","original-video"],{tenantInBody:true,readOnly:true,identity:[["tenantId","source.tenantId"],["productionId","source.productionId"],["artifactId","source.artifactId"],["representationId","source.representationId"],["checksumSha256","source.checksumSha256"]]}),"temporal-evidence.target":productionWrite(TemporalEvidenceTargetSchema,TemporalEvidenceSourceSchema,()=>["temporal-evidence","target"],{tenantInBody:true,readOnly:true,identity:[["artifactId","artifactId"],["representationId","representationId"],["checksumSha256","checksumSha256"]]}),"temporal-evidence.start":productionWrite(TemporalEvidenceStartSchema,TemporalEvidenceAdmissionSchema,()=>["temporal-evidence"],{tenantInBody:true,identity:[["artifactId","source.artifactId"],["representationId","source.representationId"],["checksumSha256","source.checksumSha256"]]}),"temporal-evidence.get":productionRead(TemporalEvidenceGetSchema,TemporalEvidenceViewSchema,i=>["temporal-evidence",i.evidenceId],void 0,[["evidenceId","evidenceId"]]),"temporal-evidence.cancel":productionWrite(TemporalEvidenceGetSchema,cancellation,i=>["temporal-evidence",i.evidenceId,"cancel"],{pathFields:["evidenceId"]})};var scopeKeys=["tenantId","projectId","productionId"];function navigationResponseMatches(value){if(!value||typeof value!=="object")return true;const result=value;if(result.evidence?.source!=="production_snapshot")return true;if(!result.actions?.items||!result.operations?.items)return false;const same2=(a,b)=>typeof a==="string"&&typeof b==="string"&&a.toLowerCase()===b.toLowerCase();const hintsMatch=input=>!input||scopeKeys.every(key10=>input[key10]===void 0||same2(input[key10],result[key10]));return result.actions.items.every(action=>scopeKeys.every(key10=>same2(action.context[key10],result[key10]))&&action.context.revision===result.evidence.revision&&hintsMatch(action.inputHints?.knownInputs)&&hintsMatch(action.inspect?.arguments))&&result.operations.items.every(operation2=>hintsMatch(operation2.inspect?.arguments)&&(!operation2.inspect||operation2.inspect.arguments.operationId===operation2.id))}var envelopes=new Set(["choices","related","operations","items","project","production","productions","artifact","primaryRepresentation","relations","storyVersion","planVersion","version","manifest","timeline","basis","review","selection","decision","target","admission","policy","finalDelivery","receipt","render","evidence","source","sourceIdentity","preparation","link","body","latestReview","finalReady","approval","binding","snapshot","sequence","frames","frameOutput","acceptance","reference","candidate","connection","scope","profile","current","feedback","share","ownerContext","comparison","candidates","reviewContext","input","recordDraft","owner","output","result","briefVersion","deliveryTarget","deliverySnapshot","validation","preparations","view","generationDrafts","request","generation","handoff","mediaRead","reviewTarget","reviews"]);var uuid=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function same(left,right){if(Array.isArray(left)||Array.isArray(right))return Array.isArray(left)&&Array.isArray(right)&&left.length===right.length&&left.every((item,i)=>same(item,right[i]));if(left&&right&&typeof left==="object"&&typeof right==="object"){const a=left,b=right;const keys=Object.keys(a);return keys.length===Object.keys(b).length&&keys.every(key10=>Object.hasOwn(b,key10)&&same(a[key10],b[key10]))}return typeof left==="string"&&typeof right==="string"&&uuid.test(left)&&uuid.test(right)?left.toLowerCase()===right.toLowerCase():left===right}function scopeMatches(value,scope4,depth=0){if(!value||typeof value!=="object")return true;if(depth>12)return false;if(Array.isArray(value))return value.every(item=>scopeMatches(item,scope4,depth+1));const record=value;for(const key10 of["tenantId","projectId","productionId"])if(scope4[key10]!==void 0&&record[key10]!==void 0&&record[key10]!==null&&!same(record[key10],scope4[key10]))return false;return Object.entries(record).every(([key10,item])=>{if(key10==="feedback"&&item&&typeof item==="object"&&scope4.operationId!==void 0&&!same(item.operationId,scope4.operationId))return false;return!envelopes.has(key10)||scopeMatches(item,scope4,depth+1)})}function targetsMatch(value,parts,expected){if(!parts.length)return same(value,expected);const[part,...rest]=parts;if(part==="*")return Array.isArray(value)&&value.every(item=>targetsMatch(item,rest,expected));return!!value&&typeof value==="object"&&targetsMatch(value[part],rest,expected)}function deviceBound(request,result){const target2=request;const receipt=result?.deviceExecution;if(target2.mode===void 0)return receipt?.target==="TENANT_DEVICE"&&typeof result?.runtimeJobId==="string"&&(!target2.deviceId||same(target2.deviceId,receipt.deviceId));return!!receipt&&receipt.mode===target2.mode&&!!receipt.runtimeJobId&&(!target2.validationMode||target2.validationMode===receipt.validationMode)&&(!target2.deviceId||same(target2.deviceId,receipt.deviceId))}function deviceJobMatches(result){const value=result;return value?.runtimeJobId===void 0||value.deviceExecution?.runtimeJobId===void 0||same(value.runtimeJobId,value.deviceExecution.runtimeJobId)}function assertResponseBindings(result,input,identity2,method,pathOrBindings,additionalBindings=[]){if(result===null)return;const expectedPath=typeof pathOrBindings==="string"?pathOrBindings:void 0;const identityWhenPresent=typeof pathOrBindings==="string"||pathOrBindings===void 0?additionalBindings:pathOrBindings;const record=result;const basis=input.basis;const basisInput=basis?.input;const nested=input.scope??basis?.scope??basisInput?.scope??basis;if(input.deviceExecution!==void 0&&!deviceBound(input.deviceExecution,result)||!deviceJobMatches(result)||!scopeMatches(result,input)||!navigationResponseMatches(result)||nested!==void 0&&!scopeMatches(result,nested)||expectedPath!==void 0&&(typeof record?.path!=="string"||record.path.replace(/[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}/gi,id7=>id7.toLowerCase())!==expectedPath.replace(/[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}/gi,id7=>id7.toLowerCase()))||[...identity2,...identityWhenPresent.filter(([,target2])=>!!record&&Object.hasOwn(record,target2))].some(([key10,target2,whenStatus])=>{if(whenStatus!==void 0&&record?.semanticStatus!==whenStatus)return false;const expected=key10.split(".").reduce((value,field)=>value&&typeof value==="object"?value[field]:void 0,input);return expected!==void 0&&!targetsMatch(result,target2.split("."),expected)})||Array.isArray(record?.items)&&typeof input.limit==="number"&&record.items.length>input.limit)throw new NativeStudioSdkError("RESPONSE_SCOPE_MISMATCH","INTERNAL_OPERATIONAL_FAILURE",method==="POST"?"UNKNOWN":"NO_WRITE")}import{createHash as createHash6}from"node:crypto";import{z as z73}from"zod";var render=RoughCutGetSchema.omit({tenantId:true});var mediaInput=z73.discriminatedUnion("kind",[AudioGetSchema.omit({tenantId:true}).extend({kind:z73.literal("AUDIO")}),CaptionExportSchema.omit({tenantId:true}).extend({kind:z73.literal("CAPTION")}),ArtifactDiscoveryMediaSchema.omit({tenantId:true}).extend({kind:z73.literal("DISCOVERED_ARTIFACT"),contentType:DiscoveryContentTypeSchema}),AudioGetSchema.omit({tenantId:true}).extend({kind:z73.literal("AUDIO_WAV")}),CaptionGetSchema.omit({tenantId:true}).extend({kind:z73.enum(["CAPTION_JSON","CAPTION_SRT"])}),TemporalEvidenceGetSchema.omit({tenantId:true}).extend({kind:z73.literal("TEMPORAL_FRAME"),ordinal:z73.int().nonnegative().max(63)}),TemporalEvidenceGetSchema.omit({tenantId:true}).extend({kind:z73.enum(["TEMPORAL_SHEET","TEMPORAL_MANIFEST"])}),VideoGetInputSchema.omit({tenantId:true}).extend({kind:z73.enum(["VIDEO_GENERATION","VIDEO_GENERATION_POSTER"])}),render.extend({kind:z73.literal("CODE_VIDEO")}),render.extend({kind:z73.enum(["ROUGH_CUT_VIDEO","ROUGH_CUT_POSTER","FINAL_VIDEO","FINAL_POSTER"])}),TimelineScopeSchema.omit({tenantId:true}).extend({kind:z73.literal("DELIVERED_VIDEO")}),DeliveryManifestGetSchema.omit({tenantId:true}).extend({kind:z73.literal("DELIVERY_MANIFEST")})]);var expectedInput=z73.strictObject({checksumSha256:z73.string().regex(/^[0-9a-f]{64}$/),byteSize:z73.int().positive().max(128*1024*1024).optional()});async function readNativeMedia(transport,tenantId,raw,expected,options){if(!raw||raw.tenantId!==void 0&&(typeof raw.tenantId!=="string"||raw.tenantId.toLowerCase()!==tenantId.toLowerCase()))sdkInputError();const parsed=mediaInput.safeParse(Object.fromEntries(Object.entries(raw).filter(([key10])=>key10!=="tenantId"))),identity2=expectedInput.safeParse({checksumSha256:expected?.checksumSha256,byteSize:expected?.byteSize});if(!parsed.success||!identity2.success)sdkInputError();const input=parsed.data;let suffix,contentType;if(input.kind==="DISCOVERED_ARTIFACT"){suffix=[];contentType=input.contentType}else if(input.kind==="AUDIO"||input.kind==="AUDIO_WAV"){suffix=["audio",input.purpose,"versions",input.versionId,"export"];contentType="audio/wav"}else if("versionId"in input){suffix=["captions","versions",input.versionId,"export"];contentType=(input.kind==="CAPTION"?input.format==="JSON":input.kind==="CAPTION_JSON")?"application/json":"application/x-subrip"}else if("evidenceId"in input){const kind=input.kind==="TEMPORAL_FRAME"?"FRAME":input.kind==="TEMPORAL_SHEET"?"SHEET":"MANIFEST";if(!TemporalEvidenceMediaSchema.safeParse({tenantId,productionId:input.productionId,evidenceId:input.evidenceId,kind,...input.kind==="TEMPORAL_FRAME"?{ordinal:input.ordinal}:{}}).success)sdkInputError();suffix=["temporal-evidence",input.evidenceId,"media",kind];contentType=kind==="MANIFEST"?"application/json":"image/png"}else if("generationId"in input){suffix=["video-generations",input.generationId,input.kind==="VIDEO_GENERATION"?"media":"poster"];contentType=input.kind==="VIDEO_GENERATION"?"video/mp4":"image/png"}else if(input.kind==="DELIVERED_VIDEO"){suffix=["deliveries","media"];contentType="video/mp4"}else if(input.kind==="CODE_VIDEO"){suffix=["compositions","renders",input.renderId,"media"];contentType="video/mp4"}else if(input.kind==="DELIVERY_MANIFEST"){suffix=["deliveries","manifests",input.manifestId,"download"];contentType="application/json"}else{const poster=input.kind.endsWith("POSTER");suffix=[input.kind.startsWith("ROUGH_CUT")?"rough-cuts":"final-renders",input.renderId,poster?"poster":"media"];contentType=poster?"image/png":"video/mp4"}const result=await transport.binary({method:"GET",tenantId,path:input.kind==="DISCOVERED_ARTIFACT"?path("projects",input.projectId,"artifacts",input.artifactId,"representations",input.representationId,"media"):path("productions",input.productionId,...suffix),...input.kind==="TEMPORAL_FRAME"?{query:{ordinal:input.ordinal}}:{},...input.kind==="CAPTION"?{query:{format:input.format}}:{},...input.kind==="CAPTION_JSON"||input.kind==="CAPTION_SRT"?{query:{format:input.kind==="CAPTION_JSON"?"JSON":"SRT"}}:{}},[contentType],Math.min(identity2.data.byteSize??128*1024*1024,input.kind==="AUDIO"||input.kind==="AUDIO_WAV"?12582912:input.kind.startsWith("CAPTION")?131072:128*1024*1024),options);const checksumSha256=createHash6("sha256").update(result.bytes).digest("hex");if(checksumSha256!==identity2.data.checksumSha256||identity2.data.byteSize!==void 0&&result.bytes.byteLength!==identity2.data.byteSize||result.etag&&result.etag!==`"${checksumSha256}"`)throw new NativeStudioSdkError("MEDIA_IDENTITY_MISMATCH","INTERNAL_OPERATIONAL_FAILURE","NO_WRITE");return{...result,checksumSha256}}var identity=TenantMediaDownloadSchema.extend({checksumSha256:LocalDigestSchema,byteSize:MediaObjectVersionSchema.shape.byteSize});async function readImmutableMedia(transport,tenantId,raw,options={}){if(!raw||Object.hasOwn(raw,"tenantId"))sdkInputError();const input=identity.safeParse({...raw,tenantId});if(!input.success)sdkInputError();const{checksumSha256,byteSize,...scope4}=input.data;const timeout=AbortSignal.timeout(12e4);const signal=options.signal?AbortSignal.any([options.signal,timeout]):timeout;const ticket=await transport.json({method:"POST",readOnly:true,tenantId,path:tenantMediaDownloadPath,body:scope4},MediaObjectTicketSchema,{signal});if(ticket.method!=="GET"||ticket.object.tenantId!==scope4.tenantId||ticket.object.projectId!==scope4.projectId||ticket.object.checksumSha256!==checksumSha256||ticket.object.byteSize!==byteSize)throw new NativeStudioSdkError("MEDIA_IDENTITY_MISMATCH","INTERNAL_OPERATIONAL_FAILURE","NO_WRITE");return{...await downloadImmutableObject(ticket,{signal}),representationId:scope4.representationId}}var nativeFailureCodes=new Set([...NativeToolAuthorityFailureSchema.shape.error.shape.code.options,"REQUEST_CONFLICT","HOST_UNAVAILABLE","CREDENTIAL_UNAVAILABLE","CREDENTIAL_SCOPE_MISMATCH","BINDING_REVOKED","UNAUTHENTICATED","FORBIDDEN","NOT_FOUND","INVALID_INPUT","REVISION_CONFLICT","STALE_BASIS","BLOCKED","CAPABILITY_UNAVAILABLE","PROVIDER_UNAVAILABLE","BUDGET_BLOCKED","CANCELLED","SUPERSEDED","INTERNAL_OPERATIONAL_FAILURE","IDEMPOTENCY_CONFLICT","INPUT_UNAVAILABLE","AUDIO_UNAVAILABLE","CAPTION_UNAVAILABLE","TEST_EVIDENCE_DENIED","CONFLICT","INVALID_MEDIA","LEASE_LOST","SOURCE_UNAVAILABLE","TOOL_AUTHORITY_UNAVAILABLE","ACTIVE_EXECUTION_EXISTS","BINDING_UNAVAILABLE","PROVIDER_CAPABILITY_UNAVAILABLE","REPLAY_EXHAUSTED","RESYNC_REQUIRED"]);var statuses={400:["INVALID_INPUT"],413:["INVALID_INPUT"],415:["INVALID_INPUT"],401:["BLOCKED"],403:["BLOCKED"],404:["NOT_FOUND"],409:["REVISION_CONFLICT","STALE_BASIS","BLOCKED","CAPABILITY_UNAVAILABLE","BUDGET_BLOCKED","CANCELLED","SUPERSEDED"],422:["INVALID_INPUT"],429:["BUDGET_BLOCKED","PROVIDER_UNAVAILABLE"]};function failureOutcome(write2,status,declared){if(!write2)return"NO_WRITE";if(declared==="NO_WRITE"||declared==="UNKNOWN"||declared==="REJECTED")return declared;return["INVALID_INPUT","NOT_FOUND","BLOCKED","REVISION_CONFLICT","STALE_BASIS","BUDGET_BLOCKED"].includes(status)?"REJECTED":"UNKNOWN"}async function nativeFailure(response,signal){try{if(response.headers.get("content-type")?.split(";")[0]?.trim()!=="application/json")return null;const bytes=await boundedResponseBytes(response,64*1024,signal);const raw=JSON.parse(new TextDecoder("utf-8",{fatal:true}).decode(bytes));if(!raw||typeof raw!=="object"||Array.isArray(raw))return null;const record=raw;const status=InterfaceSemanticStatusSchema.safeParse(record.semanticStatus);if(!status.success||!(statuses[response.status]??(response.status>=500?["INTERNAL_OPERATIONAL_FAILURE","PROVIDER_UNAVAILABLE","CAPABILITY_UNAVAILABLE"]:[])).includes(status.data))return null;const error=record.error;const code=error&&typeof error==="object"?error.code:void 0;const known=typeof code==="string"&&nativeFailureCodes.has(code);return{semanticStatus:status.data,code:known?code:status.data,outcome:error&&typeof error==="object"&&!Array.isArray(error)&&(known||error.outcome==="UNKNOWN")?error.outcome:void 0}}catch{return null}finally{void response.body?.cancel().catch(()=>{})}}var NativeStudioHttpTransport=class{constructor(config){this.config=config;try{this.origin=new URL(config.baseUrl);if(this.origin.username||this.origin.password||this.origin.search||this.origin.hash||this.origin.pathname!=="/"||this.origin.protocol!=="https:"&&!(this.origin.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(this.origin.hostname)))sdkInputError()}catch{sdkInputError()}this.timeout=config.timeoutMs??3e4;this.jsonLimit=config.maxJsonBytes??18*1024*1024;if(!Number.isSafeInteger(this.timeout)||this.timeout<1||this.timeout>3e5||!Number.isSafeInteger(this.jsonLimit)||this.jsonLimit<1024||this.jsonLimit>32*1024*1024)sdkInputError()}config;origin;timeout;jsonLimit;async response(request,options){const write2=request.method==="POST"&&!request.readOnly;if(!request.path.startsWith("/v1/")||request.path.includes("?")||request.path.includes("#")||request.path.includes(".."))sdkInputError();const url=new URL(request.path,this.origin);if(url.origin!==this.origin.origin||!url.pathname.startsWith("/v1/")||!["GET","POST"].includes(request.method)||!TenantIdSchema.safeParse(request.tenantId).success)sdkInputError();for(const[key10,value]of Object.entries(request.query??{}))if(value!==void 0)url.searchParams.set(key10,String(value));let body;try{if(request.importedVideo){const v=request.importedVideo;if(request.method!=="POST"||request.body!==void 0||!/^\/v1\/productions\/[a-f0-9-]{36}\/imported-visuals\/originals\/bytes$/i.test(request.path)||!(v.bytes instanceof Uint8Array)||v.bytes.length<32||v.bytes.length>128*1024*1024||!/^[A-Za-z0-9_-]+$/.test(v.metadata)||v.metadata.length>8192)sdkInputError();body=new Uint8Array(v.bytes)}else body=request.body===void 0?void 0:JSON.stringify(request.body);if(typeof body==="string"&&new TextEncoder().encode(body).byteLength>18*1024*1024)sdkInputError()}catch{sdkInputError()}const timeout=AbortSignal.timeout(this.timeout);const signal=options.signal?AbortSignal.any([options.signal,timeout]):timeout;if(signal.aborted)throw new NativeStudioSdkError("REQUEST_ABORTED","BLOCKED","NO_WRITE");let authorization;if(request.authentication==="runtime-proof"){if(request.method!=="POST"||!/^\/v1\/projects\/[0-9a-f-]{36}\/(?:native-tool-grants\/[0-9a-f-]{36}\/(?:proof|status)|productions\/[0-9a-f-]{36}\/native-tool-credentials\/exchange)$/.test(request.path))sdkInputError()}else{try{authorization=await abortable(Promise.resolve().then(()=>this.config.authorization(signal)),signal)}catch{throw new NativeStudioSdkError(signal.aborted?"REQUEST_ABORTED":"UNAUTHENTICATED","BLOCKED","NO_WRITE")}if(typeof authorization!=="string"||!/^Bearer [A-Za-z0-9._~+/-]+={0,2}$/.test(authorization)||authorization.length>16384)throw new NativeStudioSdkError("UNAUTHENTICATED","BLOCKED","NO_WRITE")}if(signal.aborted)throw new NativeStudioSdkError("REQUEST_ABORTED","BLOCKED","NO_WRITE");try{const pending=Promise.resolve().then(()=>(this.config.fetch??fetch)(url,{method:request.method,redirect:"error",cache:"no-store",signal,headers:{...authorization===void 0?{}:{authorization},"x-native-tenant-id":request.tenantId,accept:"application/json",...request.body===void 0?{}:{"content-type":"application/json"},...request.importedVideo?{"content-type":"video/mp4","x-native-import-metadata":request.importedVideo.metadata}:{}},...body===void 0?{}:{body}}));void pending.then(late=>{if(signal.aborted)void late.body?.cancel().catch(()=>{})},()=>{});const response=await abortable(pending,signal);if(!response.ok){const status=response.status;const native=await nativeFailure(response,signal);const code=status===401?"UNAUTHENTICATED":status===403?"FORBIDDEN":status===404?"NOT_FOUND":status===400||status===413||status===415||status===422?"INVALID_INPUT":status===409?"REVISION_CONFLICT":"HTTP_FAILURE";const semanticStatus=status===401||status===403?"BLOCKED":status===404?"NOT_FOUND":status===400||status===413||status===415||status===422?"INVALID_INPUT":status===409?"REVISION_CONFLICT":"INTERNAL_OPERATIONAL_FAILURE";throw new NativeStudioSdkError(native?.code??code,native?.semanticStatus??semanticStatus,failureOutcome(write2,native?.semanticStatus??semanticStatus,native?.outcome),status)}return{response,signal}}catch(error){if(error instanceof NativeStudioSdkError)throw error;throw new NativeStudioSdkError(write2?"OUTCOME_UNKNOWN":signal.aborted?"REQUEST_ABORTED":"TRANSPORT_UNAVAILABLE","INTERNAL_OPERATIONAL_FAILURE",write2?"UNKNOWN":"NO_WRITE")}}async json(request,schema,options={}){const limit=options.maxJsonBytes??this.jsonLimit;if(!Number.isSafeInteger(limit)||limit<1024||limit>this.jsonLimit)sdkInputError();const{response,signal}=await this.response(request,options);try{const contentType=response.headers.get("content-type")?.split(";")[0]?.trim();if(contentType!=="application/json"){void response.body?.cancel().catch(()=>{});throw new Error}const bytes=await boundedResponseBytes(response,limit,signal);return schema.parse(JSON.parse(new TextDecoder("utf-8",{fatal:true}).decode(bytes)))}catch(error){if(error instanceof NativeStudioSdkError)throw new NativeStudioSdkError(error.code,error.semanticStatus,request.method==="POST"&&!request.readOnly?"UNKNOWN":"NO_WRITE",error.status);throw new NativeStudioSdkError("RESPONSE_INVALID","INTERNAL_OPERATIONAL_FAILURE",request.method==="POST"&&!request.readOnly?"UNKNOWN":"NO_WRITE")}}async binary(request,contentTypes,limit,options={}){if(request.method!=="GET"||!Number.isSafeInteger(limit)||limit<1||limit>128*1024*1024)sdkInputError();const{response,signal}=await this.response(request,options);const contentType=response.headers.get("content-type")?.split(";")[0]?.trim()??"";if(!contentTypes.includes(contentType)){await response.body?.cancel().catch(()=>{});throw new NativeStudioSdkError("RESPONSE_INVALID","INTERNAL_OPERATIONAL_FAILURE","NO_WRITE")}try{return{bytes:await boundedResponseBytes(response,limit,signal),contentType,etag:response.headers.get("etag")}}catch(error){throw new NativeStudioSdkError(error instanceof NativeStudioSdkError?error.code:signal.aborted?"REQUEST_ABORTED":"RESPONSE_INVALID","INTERNAL_OPERATIONAL_FAILURE","NO_WRITE")}}};var sdkOperations=Object.freeze({...coreOperations,...deviceManagementOperations,...deviceLibraryOperations,...navigationOperations,...discoveryOperations,...agentHostOperations,...agentHostExecutionOperations,...nativeToolAuthorityOperations,...compositionOperations,...assemblyOperations,...editorOperations,...reviewerOperations,...repairStrategyOperations,...canonicalRepairOperations,...programmaticReviewOperations,...compositionSourceOperations,...programmaticExplorationOperations,...deliveryOperations,...shotPreparationOperations,...generationOperations,...keyframeReviewOperations,...videoReviewOperations,...providerOperations,...speechOperations,...voiceProfileOperations,...shareOperations,...voiceReviewOperations,...observationOperations,...soundMakingPlanOperations,...lifecycleEventOperations,...temporalEvidenceOperations,...audioCaptionOperations,...planningIntelligenceOperations,...importedVisualOperations,...sourceSyncOperations,...visualExplorationOperations,...referencePreviewOperations,...mediaDescriptorOperations});var NativeStudioAgentClient=class{deviceRenders=new NativeStudioDeviceRenders(this);navigation=new NativeStudioNavigationFacade(this);tenantId;directSources;transport;constructor(config){const tenant2=TenantIdSchema.safeParse(config.tenantId);if(!tenant2.success)sdkInputError();this.tenantId=tenant2.data.toLowerCase();this.transport=new NativeStudioHttpTransport(config);this.directSources=new NativeStudioDirectSources(this.tenantId,this.transport)}async call(key10,raw,options={}){if(!Object.hasOwn(sdkOperations,key10)||!raw||typeof raw!=="object"||Array.isArray(raw))sdkInputError();if(raw.tenantId!==void 0&&(typeof raw.tenantId!=="string"||raw.tenantId.toLowerCase()!==this.tenantId))sdkInputError();const spec=sdkOperations[key10];if(spec.request===null)throw new NativeStudioSdkError("CAPABILITY_UNAVAILABLE","CAPABILITY_UNAVAILABLE","NO_WRITE");const parsed=spec.input.safeParse({...raw,tenantId:this.tenantId});if(!parsed.success)sdkInputError(inputIssues(parsed.error,spec.input));if((key10==="rough-cut.start"||key10==="final-render.start")&&"deviceExecution"in parsed.data&&DeviceRenderTargetSchema.safeParse(parsed.data.deviceExecution).data?.validationMode){try{const advertised=await this.transport.json({method:"GET",tenantId:this.tenantId,path:path("local-execution","tenant-media","capabilities")},TenantMediaCapabilitySchema,options);if(advertised.tenantId!==this.tenantId)throw Error()}catch{throw new NativeStudioSdkError("CAPABILITY_UNAVAILABLE","BLOCKED","NO_WRITE")}}const request=spec.request(parsed.data);const result=await this.transport.json({...request,readOnly:spec.readOnly},spec.output,options);assertManagementReceipt(key10,parsed.data,result);assertResponseBindings(result,parsed.data,spec.identity,spec.readOnly?"GET":request.method,spec.expectedPath?spec.expectedPath(parsed.data,result):void 0,spec.identityWhenPresent);if(key10==="temporal-evidence.read-video")assertOriginalVideoBytes(result);if(key10==="reference-preview.get")assertPreviewBytes(result);if(key10==="source-sync.audio"||key10==="audio.export"||key10==="caption.export")assertExportBytes(result,key10==="caption.export"&&"format"in parsed.data?String(parsed.data.format):void 0);return result}async sourceMedia(raw,options={},expected){if(Object.hasOwn(raw,"tenantId"))sdkInputError();const parsed=SourceLibraryMediaSchema.safeParse({...raw,tenantId:this.tenantId});if(!parsed.success)sdkInputError();const input=parsed.data;const result=await this.transport.binary({method:"GET",tenantId:this.tenantId,path:path("projects",input.projectId,"source-artifacts",input.artifactId,"media")},["image/png","image/jpeg","image/webp","text/plain","application/json"],8*1024*1024,options);const checksumSha256=createHash7("sha256").update(result.bytes).digest("hex");if(result.etag&&result.etag!==`"${checksumSha256}"`||expected&&(expected.checksumSha256!==checksumSha256||expected.byteSize!==result.bytes.byteLength))throw new NativeStudioSdkError("MEDIA_IDENTITY_MISMATCH","INTERNAL_OPERATIONAL_FAILURE","NO_WRITE");return{...result,checksumSha256}}media(input,expected,options={}){return readNativeMedia(this.transport,this.tenantId,input,expected,options)}immutableMedia(input,options={}){return readImmutableMedia(this.transport,this.tenantId,input,options)}async keyframeMedia(raw,expected,options={}){if(!raw||Object.hasOwn(raw,"tenantId")||!/^[a-f0-9]{64}$/.test(expected?.checksumSha256??"")||expected?.byteSize!==void 0&&(!Number.isSafeInteger(expected.byteSize)||expected.byteSize<1||expected.byteSize>8*1024*1024))sdkInputError();const parsed=KeyframeGetInputSchema.safeParse({...raw,tenantId:this.tenantId});if(!parsed.success)sdkInputError();const i=parsed.data,value=await this.transport.json({method:"GET",tenantId:this.tenantId,path:path("productions",i.productionId,"keyframe-generations",i.generationId,"media")},KeyframeMediaSchema,options);const bytes=Buffer.from(value.contentBase64,"base64"),checksumSha256=createHash7("sha256").update(bytes).digest("hex");if(bytes.toString("base64")!==value.contentBase64||bytes.length!==value.byteSize||checksumSha256!==value.checksumSha256||checksumSha256!==expected.checksumSha256||expected.byteSize!==void 0&&bytes.length!==expected.byteSize)throw new NativeStudioSdkError("MEDIA_IDENTITY_MISMATCH","INTERNAL_OPERATIONAL_FAILURE","NO_WRITE");return{bytes,checksumSha256,contentType:value.contentType}}};function schemaNode(value,root){if(root.$schema!==void 0&&root.$schema!=="https://json-schema.org/draft/2020-12/schema")return null;const seen=new Set;const scoped=node=>["$id","$anchor","$dynamicAnchor","$dynamicRef","$recursiveAnchor","$recursiveRef","$vocabulary"].some(key10=>key10 in node);while(value&&typeof value==="object"&&!Array.isArray(value)){const node=value;if(scoped(node))return null;if("$ref"in node&&typeof node.$ref!=="string")return null;if(typeof node.$ref!=="string")return node;if(seen.has(value)||!node.$ref.startsWith("#/"))return null;seen.add(value);let target2=root;for(const part of node.$ref.slice(2).split("/")){const key10=part.replaceAll("~1","/").replaceAll("~0","~");if(!target2||typeof target2!=="object"||!Object.hasOwn(target2,key10))return null;if(scoped(target2))return null;target2=target2[key10]}value=target2}return null}import{z as z74}from"zod";var definitions=new WeakMap;function inputDefinition(name,input){let names=definitions.get(input);if(!names){names=new Map;definitions.set(input,names)}let definition=names.get(name);if(!definition){try{definition={name,inputSchema:z74.toJSONSchema(input,{io:"input",reused:"ref"})};if(Buffer.byteLength(JSON.stringify(definition))>160*1024)throw Error()}catch{throw new NativeStudioSdkError("CAPABILITY_UNAVAILABLE","BLOCKED","NO_WRITE")}names.set(name,definition)}return definition}import{createHash as createHash8}from"node:crypto";import{z as z75}from"zod";var Input=z75.discriminatedUnion("kind",[KeyframeGetInputSchema.extend({kind:z75.literal("KEYFRAME")}),VideoGetInputSchema.extend({kind:z75.literal("VIDEO_POSTER")}),RoughCutGetSchema.extend({kind:z75.enum(["ROUGH_CUT_POSTER","FINAL_POSTER"])})]);var sdkImageMediaTools={KEYFRAME:"keyframe_media",VIDEO_POSTER:"video_poster",ROUGH_CUT_POSTER:"rough_cut_poster",FINAL_POSTER:"final_render_poster"};var Identity=z75.strictObject({checksumSha256:z75.string().regex(/^[0-9a-f]{64}$/),byteSize:z75.int().positive().max(16*1024*1024).optional()});var Metadata=KeyframeMediaSchema.omit({contentBase64:true});async function readMcpImageMedia(config,raw,expected,options){if(!raw||raw.tenantId!==void 0&&(typeof raw.tenantId!=="string"||raw.tenantId.toLowerCase()!==config.tenantId))sdkInputError();const input=Input.safeParse({...raw,tenantId:config.tenantId}),identity2=Identity.safeParse(expected);if(!input.success||!identity2.success)sdkInputError();const{kind,...argumentsInput}=input.data;const timeout=AbortSignal.timeout(config.timeoutMs),signal=options.signal?AbortSignal.any([timeout,options.signal]):timeout;if(signal.aborted)throw new NativeStudioSdkError("REQUEST_ABORTED","BLOCKED","NO_WRITE");let response;try{response=await abortable(config.client.callTool({name:sdkImageMediaTools[kind],arguments:argumentsInput},{signal,timeout:config.timeoutMs}),signal)}catch{throw new NativeStudioSdkError(signal.aborted?"REQUEST_ABORTED":"TRANSPORT_UNAVAILABLE","INTERNAL_OPERATIONAL_FAILURE","NO_WRITE")}try{if(Buffer.byteLength(JSON.stringify(response),"utf8")>config.maxJsonBytes)throw Error();const envelope2=z75.object({semanticStatus:InterfaceSemanticStatusSchema,data:z75.unknown().optional(),error:z75.object({code:z75.string()}).optional()}).parse(response.structuredContent);if(response.isError||envelope2.semanticStatus!=="SUCCESS"){const status=["SUCCESS","ACCEPTED"].includes(envelope2.semanticStatus)?"INTERNAL_OPERATIONAL_FAILURE":envelope2.semanticStatus;throw new NativeStudioSdkError(envelope2.error&&nativeFailureCodes.has(envelope2.error.code)?envelope2.error.code:status,status,"NO_WRITE")}const metadata=Metadata.parse(envelope2.data),images=response.content.filter(c=>c.type==="image");if(images.length!==1||response.content.length!==1)throw Error();const block=images[0],bytes=Buffer.from(block.data,"base64"),checksumSha256=createHash8("sha256").update(bytes).digest("hex");if(bytes.toString("base64")!==block.data||bytes.length!==metadata.byteSize||block.mimeType!==metadata.contentType||checksumSha256!==metadata.checksumSha256||checksumSha256!==identity2.data.checksumSha256||identity2.data.byteSize!==void 0&&bytes.length!==identity2.data.byteSize)throw new NativeStudioSdkError("MEDIA_IDENTITY_MISMATCH","INTERNAL_OPERATIONAL_FAILURE","NO_WRITE");return{...metadata,bytes}}catch(error){if(error instanceof NativeStudioSdkError)throw error;throw new NativeStudioSdkError("RESPONSE_INVALID","INTERNAL_OPERATIONAL_FAILURE","NO_WRITE")}}var sdkMcpTools=Object.freeze({"workspace.devices.list":"workspace_devices_list","device.enroll":"device_enroll","device.revoke":"device_revoke","device.management-receipt":"device_management_receipt","workspace.get":"workspace_get","workspace.caller":"workspace_caller","workspace.query":"workspace_query","device-library.query":"device_library_query","device-library.admit":"device_library_admit","device-library.receipt":"device_library_receipt","devices.list":"list_devices","studio.capability.groups":"studio_capability_groups","studio.start":"studio_start","studio.capability.search":"studio_capability_search","studio.capability.describe":"studio_capability_describe","studio.navigate":"studio_navigate","sound-plan.context":"sound_plan_context","sound-plan.get":"sound_plan_get","sound-plan.validate":"sound_plan_validate","sound-plan.accept":"sound_plan_accept","media-observation.options":"media_observation_options","media-observation.start":"media_observation_start","media-observation.start-local":"media_observation_start_local","media-observation.get-local":"media_observation_get_local","media-observation.device.quote":"media_observation_device_quote","media-observation.device.start":"media_observation_device_start","media-observation.device.get":"media_observation_device_get","media-observation.get":"media_observation_get","media-observation.cancel":"media_observation_cancel","production-guidance.context":"production_guidance_context","speech.options":"speech_options","provider.model.get":"provider_model_get","speech.start":"speech_start","speech.device.quote":"speech_device_quote","speech.device.start":"speech_device_start","speech.start-local":"speech_start_local","speech.get-local":"speech_get_local","speech.get":"speech_get","speech.cancel":"speech_cancel","provider.model.query":"provider_model_catalog_query","provider.model.configure":"provider_model_configure","provider.model.disable":"provider_model_disable","artifact.query":"artifact_discovery_query","imported-visual.query":"imported_visual_query","imported-visual.start-from-source":"imported_visual_start_from_source","imported-visual.review.target":"imported_visual_review_target","imported-visual.review.record":"imported_visual_review","source-sync.review.target":"source_sync_review_target","source-sync.review.record":"source_sync_review","source-sync.review.get":"source_sync_review_get","temporal-evidence.read-video":"temporal_evidence_read_video","temporal-evidence.target":"temporal_evidence_target","temporal-evidence.start":"temporal_evidence_start","temporal-evidence.get":"temporal_evidence_get","temporal-evidence.cancel":"temporal_evidence_cancel","visual-sequence.register":"visual_sequence_register","visual-sequence.start-registration":"visual_sequence_start_registration","visual-sequence.get":"visual_sequence_get","visual-sequence.query":"visual_sequence_query","project.create":"project_create","production.create":"production_create","production.terminate":"production_terminate","project.query":"project_query","project.get":"project_get","source.query":"source_query","source.ingest":"source_ingest","source.text":"source_read","production.query":"production_query","production.snapshot":"production_snapshot","brief.accept":"brief_accept","story.accept":"story_accept","scene-shot-plan.accept":"scene_shot_plan_accept","story.query":"story_query","story.active":"story_active","scene-shot-plan.query":"scene_shot_plan_query","scene-shot-plan.active":"scene_shot_plan_active","operation.query":"operation_query","operation.get":"operation_get","agent-host.get":"agent_host_binding_get","agent-host.readiness":"agent_host_readiness","agent-host.history":"agent_host_binding_history","agent-host.configure":null,"agent-host.selection.update":"agent_host_selection_update","agent-host.revoke":"agent_host_binding_revoke","agent-host-execution.start":"agent_host_execution_start","agent-host-execution.get":"agent_host_execution_get","agent-host-execution.query":"agent_host_execution_query","agent-host-execution.events":"agent_host_execution_events","agent-host-execution.dispatch":"agent_host_execution_dispatch","agent-host-execution.reconcile":"agent_host_execution_reconcile","agent-host-execution.cancel":"agent_host_execution_cancel","native-tool-grant.configure":"native_tool_grant_configure","native-tool-grant.get":"native_tool_grant_get","native-tool-grant.revoke":"native_tool_grant_revoke","composition.capabilities":"composition_capabilities","composition.brief":"composition_brief","composition.put-input":"composition_put_input","composition.making.validate":"composition_making_validate","composition.validate":"composition_validate","composition.create":"composition_create","composition.revise":"composition_revise","composition.get":"composition_get","composition.history":"composition_history","composition.render":"composition_render","composition.render.get":"composition_render_get","composition.render.query":"composition_render_query","composition.render.cancel":"composition_render_cancel","composition.sample":"composition_sample","composition.observe":"composition_observe","timeline.basis":"timeline_basis","timeline.build":"timeline_build","timeline.current":"timeline_current","timeline.get":"timeline_get","timeline.query":"timeline_query","rough-cut.start":"rough_cut_start","rough-cut.admission-receipt":"rough_cut_admission_receipt","rough-cut.get":"rough_cut_get","rough-cut.query":"rough_cut_query","rough-cut.cancel":"rough_cut_cancel","rough-cut.media-ticket":"rough_cut_media_ticket","rough-cut.review.target":"rough_cut_review_target","rough-cut.review.record":"rough_cut_review_record","rough-cut.review.query":"rough_cut_review_query","rough-cut.finding.query":"rough_cut_finding_query","final-ready.get":"final_ready_get","final-ready.decide":"final_ready_decide","final-ready.revoke":"final_ready_revoke","final-ready.query":"final_ready_query","final-render.eligibility":"final_render_eligibility","final-render.start":"final_render_start","final-render.admission-receipt":"final_render_admission_receipt","final-render.get":"final_render_get","final-render.query":"final_render_query","final-render.cancel":"final_render_cancel","final-render.media-ticket":"final_render_media_ticket","editor.context":"editor_context","editor.validate":"editor_validate","reviewer.final-output-context":"reviewer_final_output_context","reviewer.context":"reviewer_context","reviewer.validate":"reviewer_proposal_validate","repair-strategy.review1.context":"repair_strategy_review1_context","repair-strategy.review1.validate":"repair_strategy_review1_validate","repair-strategy.context":"repair_strategy_context","repair-strategy.validate":"repair_strategy_validate","canonical-repair.author":"repair_author","canonical-repair.author-review1":"repair_author_review1","canonical-repair.proof-review1":"repair_proof_review1","canonical-repair.get":"repair_get","canonical-repair.execute":"repair_execute","canonical-repair.proof":"repair_proof","programmatic-review.target":"composition_review_target","programmatic-review.record":"composition_review_record","programmatic-review.query":"composition_review_query","programmatic-review.decide":"composition_acceptance_decide","composition.source.inspect":"composition_source_inspect","reviewer.source-context":"reviewer_source_context","exploration.programmatic.compare":"exploration_programmatic_compare","exploration.programmatic.recommendation.context":"exploration_programmatic_recommendation_context","exploration.programmatic.recommendation.validate":"exploration_programmatic_recommendation_validate","delivery.policy.configure":"delivery_configure","delivery.policy.get":"delivery_policy","delivery.snapshot":"delivery_snapshot","delivery.target":"delivery_target","delivery.start":"delivery_start","delivery.get":"delivery_get","delivery.approve":"delivery_approve","delivery.cancel":"delivery_cancel","delivery.manifest":"delivery_manifest","shot-preparation.prepare":"shot_prepare","shot-preparation.get":"shot_preparation_get","shot-preparation.active":"shot_preparation_active","shot-preparation.query":"shot_preparation_query","keyframe.start":"keyframe_start","keyframe.device.quote":"keyframe_device_quote","keyframe.device.start":"keyframe_device_start","keyframe.get":"keyframe_get","imported-visual.register-source":"imported_visual_register_source","imported-visual.register":"imported_visual_register","imported-visual.revise":"imported_visual_revise","imported-visual.original":"imported_visual_original","imported-visual.history":"imported_visual_history","imported-visual.normalize":"imported_visual_normalize","imported-visual.get":"imported_visual_get","imported-visual.decide":"imported_visual_decide","imported-visual.cancel":"imported_visual_cancel","source-sync.start":"source_sync_start","source-sync.get":"source_sync_get","source-sync.cancel":"source_sync_cancel","source-sync.version":"source_sync_version","exploration.context":"exploration_context","exploration.plan.validate":"exploration_plan_validate","exploration.compare":"exploration_compare","exploration.recommendation.context":"exploration_recommendation_context","exploration.recommendation.validate":"exploration_recommendation_validate","composition.render.media-target":"composition_render_media","delivery.download":"delivery_download","temporal-evidence.download":"temporal_evidence_download","video.options":"video_options","studio.capabilities":"studio_capabilities","reference-preview.start":"reference_preview_start","reference-preview.status":"reference_preview_status","reference-preview.get":"reference_preview_get","reference-preview.cancel":"reference_preview_cancel","brief.active":"brief_active","writer.validate":"writer_proposal_validate","director.context":"director_context","director.validate":"director_proposal_validate","consistency-profile.get":"consistency_profile_get","share.create":"share_create","share.get":"share_get","share.list":"share_list","share.revoke":"share_revoke","share.link":"share_link","share.receipt":"share_receipt","voice-profile.create":"voice_profile_create","voice-profile.revise":"voice_profile_revise","voice-profile.publish":"voice_profile_publish","voice-profile.set-enabled":"voice_profile_set_enabled","voice-profile.list":"voice_profile_list","voice-profile.get":"voice_profile_get","voice-profile.version":"voice_profile_version","voice-profile.set-reference":"voice_profile_set_reference","voice-profile.reference":"voice_profile_reference","voice-review.target":"voice_review_target","voice-review.record":"voice_review_record","voice-review.get":"voice_review_get","consistency-profile.version":"consistency_profile_version","consistency-profile.configure":"consistency_profile_configure","audio.export":"audio_export","caption.export":"caption_export","source-sync.audio":"source_sync_audio","audio.basis":"audio_basis","audio.current":"audio_current","audio.get":"audio_get","audio.query":"audio_query","audio.import":"audio_import","caption.basis":"caption_basis","caption.current":"caption_current","caption.get":"caption_get","caption.query":"caption_query","caption.author":"caption_author","caption.transcript_draft":"caption_transcript_draft","caption.author_transcript":"caption_author_transcript","keyframe.query":"keyframe_query","keyframe.cancel":"keyframe_cancel","video.start":"video_start","video.device.quote":"video_device_quote","video.device.start":"video_device_start","video.get":"video_get","video.query":"video_query","video.cancel":"video_cancel","keyframe-review.target":"keyframe_review_target","keyframe-review.record":"keyframe_review_record","keyframe-review.query":"keyframe_review_query","keyframe-review.decide":"keyframe_reference_decide","keyframe-reference.get":"keyframe_reference_get","keyframe-reference.query":"keyframe_reference_query","keyframe-reference.revoke":"keyframe_reference_revoke","video-review.target":"video_review_target","video-review.record":"video_review_record","video-review.query":"video_review_query","video-review.decide":"shot_acceptance_decide","shot-acceptance.get":"shot_acceptance_get","shot-acceptance.query":"shot_acceptance_query","shot-acceptance.revoke":"shot_acceptance_revoke","provider.configure":null,"provider.query":"provider_connection_query","provider.models":"provider_model_query","provider.keyframe-default.set":"provider_keyframe_default_set","provider.disable":"provider_connection_disable","provider.revoke":"provider_credential_revoke","webhook.configure":null,"webhook.secret.prepare":null,"webhook.configure-reference":"webhook_configure","webhook.disable":"webhook_disable","webhook.replay":"webhook_replay","production.feedback":"production_feedback","production.events.read":"production_events_read","lifecycle-event.capabilities":"lifecycle_events_capabilities","lifecycle-event.subscriptions":"lifecycle_events_query","lifecycle-event.events":"lifecycle_events_query","lifecycle-event.deliveries":"lifecycle_events_query","lifecycle-event.attempts":"lifecycle_events_query"});var nestedScope=new Set(["writer.validate","exploration.context","exploration.plan.validate","exploration.compare","exploration.recommendation.context","exploration.recommendation.validate","director.validate","editor.context","editor.validate","reviewer.final-output-context","reviewer.context","reviewer.validate","reviewer.source-context","repair-strategy.context","repair-strategy.validate","repair-strategy.review1.validate","exploration.programmatic.compare","exploration.programmatic.recommendation.context","exploration.programmatic.recommendation.validate","canonical-repair.author"]);var projectInPath=new Set(["canonical-repair.proof-review1","canonical-repair.get","canonical-repair.execute","canonical-repair.proof"]);function sdkMcpInput(key10,input){return Object.fromEntries(Object.entries(input).filter(([k])=>!(k==="tenantId"&&nestedScope.has(key10))&&!(k==="projectId"&&projectInPath.has(key10))))}import{createHash as createHash9}from"node:crypto";import{z as z76}from"zod";var expectedSchema=z76.strictObject({checksumSha256:z76.string().regex(/^[a-f0-9]{64}$/),byteSize:z76.int().positive().max(16*1024*1024).optional()});async function readMcpEvidenceImage(config,raw,expected,options){if(!raw||raw.tenantId!==void 0&&(typeof raw.tenantId!=="string"||raw.tenantId.toLowerCase()!==config.tenantId))sdkInputError();const input=TemporalEvidenceImageSchema.safeParse({...raw,tenantId:config.tenantId}),identity2=expectedSchema.safeParse({checksumSha256:expected?.checksumSha256,byteSize:expected?.byteSize});if(!input.success||!identity2.success)sdkInputError();const deadline=AbortSignal.timeout(config.timeoutMs),signal=options.signal?AbortSignal.any([options.signal,deadline]):deadline;if(signal.aborted)throw new NativeStudioSdkError("REQUEST_ABORTED","BLOCKED","NO_WRITE");let reply;try{reply=await abortable(config.client.callTool({name:"temporal_evidence_read_image",arguments:input.data},{signal,timeout:config.timeoutMs}),signal)}catch{throw new NativeStudioSdkError(signal.aborted?"REQUEST_ABORTED":"TRANSPORT_UNAVAILABLE","INTERNAL_OPERATIONAL_FAILURE","NO_WRITE")}try{if(Buffer.byteLength(JSON.stringify(reply),"utf8")>config.maxJsonBytes)throw Error();const texts=reply.content.filter(block2=>block2.type==="text"),images=reply.content.filter(block2=>block2.type==="image");const carrier=reply.structuredContent!==void 0?reply.structuredContent:texts.length===1?JSON.parse(texts[0].text):void 0;const envelope2=z76.object({semanticStatus:InterfaceSemanticStatusSchema,data:z76.unknown().optional(),error:z76.object({code:z76.string()}).optional()}).parse(carrier);if(reply.isError)throw new NativeStudioSdkError(envelope2.error&&nativeFailureCodes.has(envelope2.error.code)?envelope2.error.code:envelope2.semanticStatus,envelope2.semanticStatus==="SUCCESS"||envelope2.semanticStatus==="ACCEPTED"?"INTERNAL_OPERATIONAL_FAILURE":envelope2.semanticStatus,"REJECTED");if(envelope2.semanticStatus!=="SUCCESS"||images.length!==1||(reply.structuredContent!==void 0?reply.content.length!==1||texts.length!==0:reply.content.length!==2||texts.length!==1))throw Error();const metadata=TemporalEvidenceImageMetadataSchema.parse(envelope2.data);assertResponseBindings(metadata,input.data,[["evidenceId","evidenceId"],["kind","kind"],["ordinal","ordinal"]],"GET");const block=images[0],bytes=Buffer.from(block.data,"base64"),checksumSha256=createHash9("sha256").update(bytes).digest("hex");if(block.mimeType!==metadata.contentType||bytes.toString("base64")!==block.data||bytes.byteLength!==metadata.byteSize||checksumSha256!==metadata.checksumSha256||checksumSha256!==identity2.data.checksumSha256||identity2.data.byteSize!==void 0&&bytes.byteLength!==identity2.data.byteSize)throw new NativeStudioSdkError("MEDIA_IDENTITY_MISMATCH","INTERNAL_OPERATIONAL_FAILURE","NO_WRITE");return{...metadata,bytes}}catch(e){if(e instanceof NativeStudioSdkError)throw e;throw new NativeStudioSdkError("RESPONSE_INVALID","INTERNAL_OPERATIONAL_FAILURE","NO_WRITE")}}import{createHash as createHash10}from"node:crypto";import{z as z77}from"zod";var inputSchema=z77.discriminatedUnion("kind",[AudioGetSchema.extend({kind:z77.literal("AUDIO_WAV")}),CaptionGetSchema.extend({kind:z77.enum(["CAPTION_JSON","CAPTION_SRT"])}),SourceSyncAudioGetSchema.extend({kind:z77.literal("SOURCE_SYNC_WAV")})]);var expectedSchema2=z77.strictObject({checksumSha256:z77.string().regex(/^[0-9a-f]{64}$/),byteSize:z77.int().positive().max(12582912).optional()});var outputSchema=z77.strictObject({semanticStatus:z77.literal("SUCCESS"),data:z77.strictObject({contentType:z77.enum(["audio/wav","application/json","application/x-subrip"]),checksumSha256:z77.string().regex(/^[0-9a-f]{64}$/),representationId:z77.uuid().optional(),byteSize:z77.int().positive().max(12582912).optional(),contentBase64:z77.string().max(16777216).optional(),text:z77.string().max(131072).optional()})});async function readMcpAuxiliaryMedia(config,raw,expected,options){if(!raw||raw.tenantId!==void 0&&(typeof raw.tenantId!=="string"||raw.tenantId.toLowerCase()!==config.tenantId))sdkInputError();const parsed=inputSchema.safeParse({...raw,tenantId:config.tenantId}),identity2=expectedSchema2.safeParse(expected);if(!parsed.success||!identity2.success)sdkInputError();const{kind,...arguments_}=parsed.data;const name=kind==="AUDIO_WAV"?"audio_export":kind==="SOURCE_SYNC_WAV"?"source_sync_audio":"caption_export";const contentType=kind.endsWith("WAV")?"audio/wav":kind==="CAPTION_JSON"?"application/json":"application/x-subrip";const deadline=AbortSignal.timeout(config.timeoutMs),signal=options.signal?AbortSignal.any([options.signal,deadline]):deadline;if(signal.aborted)throw new NativeStudioSdkError("REQUEST_ABORTED","BLOCKED","NO_WRITE");let reply;try{reply=await abortable(config.client.callTool({name,arguments:{...arguments_,...kind.startsWith("CAPTION")?{format:kind==="CAPTION_JSON"?"JSON":"SRT"}:{}}},{signal,timeout:config.timeoutMs}),signal)}catch{throw new NativeStudioSdkError(signal.aborted?"REQUEST_ABORTED":"TRANSPORT_UNAVAILABLE","INTERNAL_OPERATIONAL_FAILURE","NO_WRITE")}try{if(Buffer.byteLength(JSON.stringify(reply),"utf8")>config.maxJsonBytes||reply.isError)throw Error();const texts=reply.content.filter(x=>x.type==="text");const result=outputSchema.parse(reply.structuredContent??(texts.length===1?JSON.parse(texts[0].text):void 0)).data;const wav=contentType==="audio/wav";if(result.contentType!==contentType||(wav?result.text!==void 0||result.contentBase64===void 0:result.contentBase64!==void 0||result.text===void 0))throw Error();const bytes=wav?Buffer.from(result.contentBase64,"base64"):Buffer.from(result.text,"utf8");const checksumSha256=createHash10("sha256").update(bytes).digest("hex");if(wav&&bytes.toString("base64")!==result.contentBase64||bytes.length>(wav?12582912:131072)||checksumSha256!==result.checksumSha256||checksumSha256!==identity2.data.checksumSha256||result.byteSize!==void 0&&bytes.length!==result.byteSize||identity2.data.byteSize!==void 0&&bytes.length!==identity2.data.byteSize)throw new NativeStudioSdkError("MEDIA_IDENTITY_MISMATCH","INTERNAL_OPERATIONAL_FAILURE","NO_WRITE");return{bytes,contentType,checksumSha256,etag:null}}catch(error){if(error instanceof NativeStudioSdkError)throw error;throw new NativeStudioSdkError("RESPONSE_INVALID","INTERNAL_OPERATIONAL_FAILURE","NO_WRITE")}}import{createHash as createHash11}from"node:crypto";import{z as z78}from"zod";var inputSchema2=z78.discriminatedUnion("kind",[KeyframeGetInputSchema.extend({kind:z78.literal("KEYFRAME")}),VideoGetInputSchema.extend({kind:z78.literal("VIDEO_POSTER")}),RoughCutGetSchema.extend({kind:z78.literal("ROUGH_CUT_POSTER")}),FinalRenderGetSchema.extend({kind:z78.literal("FINAL_POSTER")}),ReferencePreviewOperationInputSchema.extend({kind:z78.literal("REFERENCE_PREVIEW")})]);var sdkMcpImageTools=Object.freeze({KEYFRAME:"keyframe_media",VIDEO_POSTER:"video_poster",ROUGH_CUT_POSTER:"rough_cut_poster",FINAL_POSTER:"final_render_poster",REFERENCE_PREVIEW:"reference_preview_get"});var identitySchema=z78.strictObject({checksumSha256:z78.string().regex(/^[a-f0-9]{64}$/),byteSize:z78.int().positive().max(16*1024*1024).optional()});var metadataSchema=z78.strictObject({contentType:z78.enum(["image/png","image/jpeg","image/webp"]),checksumSha256:identitySchema.shape.checksumSha256,byteSize:z78.int().positive().max(16*1024*1024)});async function readMcpImage(config,raw,expected,options){if(!raw||raw.tenantId!==void 0&&(typeof raw.tenantId!=="string"||raw.tenantId.toLowerCase()!==config.tenantId))sdkInputError();const input=inputSchema2.safeParse({...raw,tenantId:config.tenantId}),identity2=identitySchema.safeParse(expected);if(!input.success||!identity2.success)sdkInputError();const{kind,...arguments_}=input.data;const deadline=AbortSignal.timeout(config.timeoutMs),signal=options.signal?AbortSignal.any([options.signal,deadline]):deadline;if(signal.aborted)throw new NativeStudioSdkError("REQUEST_ABORTED","BLOCKED","NO_WRITE");let reply;try{reply=await abortable(config.client.callTool({name:sdkMcpImageTools[kind],arguments:arguments_},{signal,timeout:config.timeoutMs}),signal)}catch{throw new NativeStudioSdkError(signal.aborted?"REQUEST_ABORTED":"TRANSPORT_UNAVAILABLE","INTERNAL_OPERATIONAL_FAILURE","NO_WRITE")}try{if(Buffer.byteLength(JSON.stringify(reply),"utf8")>config.maxJsonBytes)throw Error();const texts=reply.content.filter(b=>b.type==="text"),images=reply.content.filter(b=>b.type==="image");const carrier=reply.structuredContent??(texts.length===1?JSON.parse(texts[0].text):void 0);const envelope2=z78.object({semanticStatus:InterfaceSemanticStatusSchema,data:z78.unknown().optional(),error:z78.object({code:z78.string()}).optional()}).parse(carrier);if(reply.isError)throw new NativeStudioSdkError(envelope2.error&&nativeFailureCodes.has(envelope2.error.code)?envelope2.error.code:"RESPONSE_INVALID",envelope2.semanticStatus==="SUCCESS"?"INTERNAL_OPERATIONAL_FAILURE":envelope2.semanticStatus,"NO_WRITE");if(envelope2.semanticStatus!=="SUCCESS"||images.length!==1||reply.content.length!==(kind==="REFERENCE_PREVIEW"?2:1)||texts.length!==(kind==="REFERENCE_PREVIEW"?1:0))throw Error();const metadata=kind==="REFERENCE_PREVIEW"?ReferencePreviewResultSchema.parse(envelope2.data):metadataSchema.parse(envelope2.data);const block=images[0],bytes=Buffer.from(block.data,"base64"),checksumSha256=createHash11("sha256").update(bytes).digest("hex");if(block.mimeType!==metadata.contentType||bytes.toString("base64")!==block.data||bytes.length>(kind==="KEYFRAME"?8:16)*1024*1024||bytes.length!==metadata.byteSize||checksumSha256!==metadata.checksumSha256||checksumSha256!==identity2.data.checksumSha256||identity2.data.byteSize!==void 0&&bytes.length!==identity2.data.byteSize||"contentBase64"in metadata&&metadata.contentBase64!==block.data)throw new NativeStudioSdkError("MEDIA_IDENTITY_MISMATCH","INTERNAL_OPERATIONAL_FAILURE","NO_WRITE");return{bytes,contentType:metadata.contentType,checksumSha256,etag:null}}catch(error){if(error instanceof NativeStudioSdkError)throw error;throw new NativeStudioSdkError("RESPONSE_INVALID","INTERNAL_OPERATIONAL_FAILURE","NO_WRITE")}}var NativeStudioMcpClient=class{constructor(config){this.config=config;const tenant2=TenantIdSchema.safeParse(config.tenantId);if(!tenant2.success||typeof config.client?.callTool!=="function")sdkInputError();this.tenantId=tenant2.data.toLowerCase();this.timeout=config.timeoutMs??3e4;this.limit=config.maxJsonBytes??16*1024*1024;if(!Number.isSafeInteger(this.timeout)||this.timeout<1||this.timeout>3e5||!Number.isSafeInteger(this.limit)||this.limit<1024||this.limit>32*1024*1024)sdkInputError()}config;deviceRenders=new NativeStudioDeviceRenders(this);navigation=new NativeStudioNavigationFacade(this);tenantId;timeout;limit;imageMedia(input,expected,options={}){return readMcpImageMedia({...this.config,tenantId:this.tenantId,timeoutMs:this.timeout,maxJsonBytes:this.limit},input,expected,options)}evidenceImage(input,expected,options={}){return readMcpEvidenceImage({...this.config,tenantId:this.tenantId,timeoutMs:this.timeout,maxJsonBytes:this.limit},input,expected,options)}auxiliaryMedia(input,expected,options={}){return readMcpAuxiliaryMedia({...this.config,tenantId:this.tenantId,timeoutMs:this.timeout,maxJsonBytes:this.limit},input,expected,options)}image(input,expected,options={}){return readMcpImage({...this.config,tenantId:this.tenantId,timeoutMs:this.timeout,maxJsonBytes:this.limit},input,expected,options)}async call(key10,raw,options={}){if(!Object.hasOwn(sdkOperations,key10)||!raw||typeof raw!=="object"||Array.isArray(raw))sdkInputError();if(raw.tenantId!==void 0&&(typeof raw.tenantId!=="string"||raw.tenantId.toLowerCase()!==this.tenantId))sdkInputError();const limit=options.maxJsonBytes??this.limit;if(!Number.isSafeInteger(limit)||limit<1024||limit>this.limit)sdkInputError();const tool=sdkMcpTools[key10];if(tool===null)throw new NativeStudioSdkError("CAPABILITY_UNAVAILABLE","CAPABILITY_UNAVAILABLE","NO_WRITE");const spec=sdkOperations[key10],parsed=spec.input.safeParse({...raw,tenantId:this.tenantId});if(!parsed.success)sdkInputError(inputIssues(parsed.error,spec.input));const input=parsed.data;if(Buffer.byteLength(JSON.stringify(input),"utf8")>18*1024*1024)sdkInputError();const request=spec.request===null?{method:spec.readOnly?"GET":"POST"}:spec.request(input);const write2=request.method==="POST"&&!spec.readOnly,outcome=write2?"UNKNOWN":"NO_WRITE";const signal=options.signal?AbortSignal.any([options.signal,AbortSignal.timeout(this.timeout)]):AbortSignal.timeout(this.timeout);if(signal.aborted)throw new NativeStudioSdkError("REQUEST_ABORTED","BLOCKED","NO_WRITE");if((key10==="rough-cut.start"||key10==="final-render.start")&&"deviceExecution"in input&&input.deviceExecution){const target2=DeviceRenderTargetSchema.parse(input.deviceExecution);const description=await this.navigation.describe({tool},{signal});const root=description.definition.inputSchema;const properties=schemaNode(root,root)?.properties;const policy=properties&&typeof properties==="object"?properties.deviceExecution:void 0;const policyFields=schemaNode(policy,root)?.properties;if(!schemaNode(policy,root)||target2.validationMode&&(!policyFields||typeof policyFields!=="object"||!Object.hasOwn(policyFields,"validationMode")))throw new NativeStudioSdkError("CAPABILITY_UNAVAILABLE","BLOCKED","NO_WRITE")}const definition=inputDefinition(tool,spec.input);let result;try{result=await abortable(this.config.client.callTool({name:tool,arguments:sdkMcpInput(key10,input)},{signal,timeout:this.timeout,toolDefinition:definition}),signal)}catch{throw new NativeStudioSdkError(write2?"OUTCOME_UNKNOWN":signal.aborted?"REQUEST_ABORTED":"TRANSPORT_UNAVAILABLE","INTERNAL_OPERATIONAL_FAILURE",outcome)}let value;try{if(Buffer.byteLength(JSON.stringify(result),"utf8")>limit)throw new Error;if("structuredContent"in result&&result.structuredContent!==void 0)value=result.structuredContent;else if("content"in result&&result.content.length===1&&result.content[0]?.type==="text")value=JSON.parse(result.content[0].text);else throw new Error}catch{throw new NativeStudioSdkError("RESPONSE_INVALID","INTERNAL_OPERATIONAL_FAILURE",outcome)}const envelope2=value&&typeof value==="object"&&!Array.isArray(value)?value:{};if("isError"in result&&result.isError){const status=InterfaceSemanticStatusSchema.safeParse(envelope2.semanticStatus);const semantic=status.success&&!["SUCCESS","ACCEPTED","NO_CHANGE"].includes(status.data)?status.data:"INTERNAL_OPERATIONAL_FAILURE";const error=envelope2.error&&typeof envelope2.error==="object"&&!Array.isArray(envelope2.error)?envelope2.error:void 0;const code=error?.code;const valid=status.success&&!["SUCCESS","ACCEPTED","NO_CHANGE"].includes(status.data);const known=valid&&typeof code==="string"&&nativeFailureCodes.has(code);throw new NativeStudioSdkError(known&&typeof code==="string"?code:semantic,semantic,failureOutcome(write2,semantic,valid&&error?.outcome==="UNKNOWN"?"UNKNOWN":known?error?.outcome:void 0))}if(envelope2.semanticStatus==="NOT_FOUND"&&envelope2.data===void 0)throw new NativeStudioSdkError("NOT_FOUND","NOT_FOUND",write2?"REJECTED":"NO_WRITE");const schema=spec.output;for(const candidate of[value,envelope2.data,envelope2.data&&typeof envelope2.data==="object"&&!Array.isArray(envelope2.data)?{...envelope2.data,semanticStatus:envelope2.semanticStatus}:void 0]){const parsedOutput=schema.safeParse(candidate);if(parsedOutput.success){if(key10==="reference-preview.get")assertPreviewBytes(parsedOutput.data);if(key10==="temporal-evidence.read-video")assertOriginalVideoBytes(parsedOutput.data);if(key10==="audio.export"||key10==="caption.export"||key10==="source-sync.audio")assertExportBytes(parsedOutput.data,key10==="caption.export"&&"format"in input?String(input.format):void 0);assertManagementReceipt(key10,input,parsedOutput.data);assertResponseBindings(parsedOutput.data,input,spec.identity,write2?"POST":"GET",spec.expectedPath?spec.expectedPath(input,parsedOutput.data):void 0,spec.identityWhenPresent);return parsedOutput.data}}throw new NativeStudioSdkError("RESPONSE_INVALID","INTERNAL_OPERATIONAL_FAILURE",outcome)}};var NativeStudioNavigationClient=class{constructor(config){this.config=config;if(typeof config.client?.callTool!=="function")sdkInputError();this.native=new NativeStudioMcpClient({...config,client:{callTool:async(params,options)=>{const definition=this.definitions.get(params.name);const result=await config.client.callTool(params,{...options,...definition?{toolDefinition:definition}:{}});if(params.name==="studio_capability_describe"&&!result.isError){const parsed=CapabilityDescribeSchema.safeParse(result.structuredContent);const projectId=params.arguments?.projectId;if(parsed.success&&parsed.data.tenantId.toLowerCase()===config.tenantId.toLowerCase()&&parsed.data.tool===params.arguments?.tool){this.contexts.set(parsed.data.schemaCursor,{tool:parsed.data.tool,...typeof projectId==="string"?{projectId}:{}});if(this.contexts.size>32)this.contexts.delete(this.contexts.keys().next().value)}}return result}}})}config;native;definitions=new Map;contexts=new Map;async entrypoints(options={}){const value=await this.native.call("studio.capability.groups",{includeDefinitions:true},options);const tools=value.definitions;const names=new Set([...NavigationToolNames,"nvs_open_execution"]);if(!tools||tools.some(tool=>!names.has(tool.name)||tool.inputSchema.type!=="object")||new Set(tools.map(tool=>tool.name)).size!==tools.length||Buffer.byteLength(JSON.stringify(tools))>160*1024||NavigationToolNames.some(name=>!tools.some(tool=>tool.name===name)))this.invalid();this.definitions.clear();this.contexts.clear();for(const tool of tools)this.remember(tool);return{tools}}async selectedSchema(reference2,expectedTool,options={}){if(!reference2||reference2.length>2048||!/^[a-zA-Z0-9_-]{1,120}$/.test(expectedTool))sdkInputError();const context=this.contexts.get(reference2);if(context&&context.tool!==expectedTool)this.invalid();const projectId=options.projectId??context?.projectId;const description=await this.native.call("studio.capability.describe",{tool:expectedTool,schemaCursor:reference2,...projectId?{projectId}:{}},options);const definition=description.definition;if(definition.name!==expectedTool)this.invalid();const selected=definition;this.remember(selected);return{tools:[selected]}}remember(tool){if(!PublicToolDefinitionSchema.safeParse(tool).success||tool.inputSchema?.type!=="object"||Buffer.byteLength(JSON.stringify(tool))>160*1024)this.invalid();this.definitions.delete(tool.name);this.definitions.set(tool.name,structuredClone(tool));if(this.definitions.size>32)this.definitions.delete(this.definitions.keys().next().value)}invalid(){throw new NativeStudioSdkError("RESPONSE_INVALID","INTERNAL_OPERATIONAL_FAILURE","NO_WRITE")}};var sdkCarrierDifferences={"studio.capabilities":{kind:"MCP_DISCOVERY",role:"Configured MCP capability inventory"},"studio.start":{kind:"MCP_DISCOVERY",role:"Progressive MCP entry navigation"},"studio.navigate":{kind:"MCP_DISCOVERY",role:"Progressive MCP context navigation"},"studio.capability.groups":{kind:"MCP_DISCOVERY",role:"MCP tool groups"},"studio.capability.search":{kind:"MCP_DISCOVERY",role:"MCP tool search"},"studio.capability.describe":{kind:"MCP_DISCOVERY",role:"MCP tool schemas"},"agent-host.configure":{kind:"PRIVATE_HTTP",role:"Private host configuration credential injection"},"provider.configure":{kind:"PRIVATE_HTTP",role:"Private provider credential injection"},"webhook.configure":{kind:"PRIVATE_HTTP",role:"Private signing-secret configuration; models use webhook.configure-reference"},"webhook.secret.prepare":{kind:"PRIVATE_HTTP",role:"Private caller-bound signing-secret preparation"}};function assertCarrierCoverage(operations,differences){const expected=Object.entries(operations).filter(([key10,value])=>value.request===null||sdkMcpTools[key10]===null).map(([key10])=>key10).sort();if(JSON.stringify(expected)!==JSON.stringify(Object.keys(differences).sort()))throw Error("SDK carrier inventory is incomplete")}var NativeStudioRuntimeAuthorityClient=class{tenantId;origin;transport;constructor(config){const tenant2=TenantIdSchema.safeParse(config.tenantId);if(!tenant2.success)sdkInputError();this.tenantId=tenant2.data.toLowerCase();if(config.maxJsonBytes!==void 0&&config.maxJsonBytes>65536)sdkInputError();try{this.origin=new URL(config.baseUrl);if(this.origin.protocol!=="https:")sdkInputError()}catch{sdkInputError()}this.transport=new NativeStudioHttpTransport({...config,maxJsonBytes:config.maxJsonBytes??65536,authorization:()=>{throw new Error("Runtime proof has no bearer credential")}})}input(schema,raw){if(!raw||typeof raw!=="object"||Array.isArray(raw))sdkInputError();const record=raw;if(record.tenantId!==void 0&&(typeof record.tenantId!=="string"||record.tenantId.toLowerCase()!==this.tenantId))sdkInputError();const parsed=schema.safeParse({...record,tenantId:this.tenantId});if(!parsed.success)sdkInputError();return parsed.data}resource(projectId,resource){if(resource!==new URL(`/mcp/native/v1/projects/${projectId}`,this.origin).href)throw new NativeStudioSdkError("RESPONSE_SCOPE_MISMATCH","INTERNAL_OPERATIONAL_FAILURE","UNKNOWN")}async prove(raw,options={}){const value=this.input(NativeRuntimeProofRequestSchema,raw),result=await this.transport.json({method:"POST",tenantId:this.tenantId,path:path("projects",value.projectId,"native-tool-grants",value.grantId,"proof"),body:{assertion:value.assertion},authentication:"runtime-proof"},NativeToolGrantViewSchema,options);assertResponseBindings(result,value,[["grantId","grantId"]],"POST");this.resource(value.projectId,result.resource);return result}async status(raw,options={}){const value=this.input(NativeRuntimeProofRequestSchema,raw);try{const result=await this.transport.json({method:"POST",tenantId:this.tenantId,path:path("projects",value.projectId,"native-tool-grants",value.grantId,"status"),body:{assertion:value.assertion},authentication:"runtime-proof"},NativeToolGrantViewSchema,options);assertResponseBindings(result,value,[["grantId","grantId"]],"POST");this.resource(value.projectId,result.resource);return result}catch(error){if(error instanceof NativeStudioSdkError)throw new NativeStudioSdkError(error.code,error.semanticStatus,"NO_WRITE",error.status);throw error}}async exchange(raw,options={}){const value=this.input(NativeToolCredentialExchangeSchema,raw),result=await this.transport.json({method:"POST",tenantId:this.tenantId,path:path("projects",value.projectId,"productions",value.productionId,"native-tool-credentials","exchange"),body:{authorityRef:value.authorityRef,assertion:value.assertion},authentication:"runtime-proof"},NativeToolCredentialReplySchema,options);this.resource(value.projectId,result.resource);if(!result.accessToken.startsWith(`nvst_${result.tokenId}.`))throw new NativeStudioSdkError("RESPONSE_SCOPE_MISMATCH","INTERNAL_OPERATIONAL_FAILURE","UNKNOWN");return result}};import{setTimeout as delay}from"node:timers/promises";async function*queryPages(client,key10,input,options={}){const maxPages=options.maxPages??50,maxItems=options.maxItems??1e3;if(!Number.isSafeInteger(maxPages)||maxPages<1||maxPages>500||!Number.isSafeInteger(maxItems)||maxItems<1||maxItems>1e4)sdkInputError();const seen=new Set;let next=input.next,count=0;if(next)seen.add(next);for(let pageNumber=0;pageNumber<maxPages;pageNumber++){const page2=await client.call(key10,{...input,...next===void 0?{}:{next}},options);count+=page2.items.length;if(count>maxItems)throw new NativeStudioSdkError("OBSERVATION_LIMIT","WAITING_INPUT","NO_WRITE");if(page2.page.hasMore&&(!page2.page.next||seen.has(page2.page.next)))throw new NativeStudioSdkError("CONTINUATION_INVALID","INTERNAL_OPERATIONAL_FAILURE","NO_WRITE");yield page2;if(!page2.page.hasMore)return;next=page2.page.next;seen.add(next)}throw new NativeStudioSdkError("OBSERVATION_LIMIT","WAITING_INPUT","NO_WRITE")}async function waitForOperation(client,input,options={}){const maxPolls=options.maxPolls??60,timeoutMs=options.timeoutMs??9e4,intervalMs=options.intervalMs??1e3;const adaptive=options.intervalMs===void 0;let previous,pause=intervalMs;if(!Number.isSafeInteger(maxPolls)||maxPolls<1||maxPolls>1e3||!Number.isSafeInteger(timeoutMs)||timeoutMs<1||timeoutMs>18e5||!Number.isSafeInteger(intervalMs)||intervalMs<10||intervalMs>1e4)sdkInputError();const deadline=AbortSignal.timeout(timeoutMs),signal=options.signal?AbortSignal.any([options.signal,deadline]):deadline;try{for(let poll=0;poll<maxPolls;poll++){signal.throwIfAborted();const result=await abortable(client.call("operation.get",input,{signal}),signal);signal.throwIfAborted();if(!["ACCEPTED","WAITING_PROVIDER","RETRYING"].includes(result.semanticStatus))return result;const progress=JSON.stringify([result.semanticStatus,result.targets,result.work,result.blockers,result.nextActions]);pause=adaptive&&progress===previous?Math.min(5e3,pause*2):intervalMs;previous=progress;if(poll<maxPolls-1)await delay(pause,void 0,{signal})}}catch(error){if(!deadline.aborted||options.signal?.aborted)throw error}throw new NativeStudioSdkError("OBSERVATION_LIMIT","WAITING_INPUT","NO_WRITE")}import{setTimeout as delay2}from"node:timers/promises";async function*observeProduction(client,input,options={}){const polls=options.maxPolls??60,timeout=options.timeoutMs??3e5,events=options.maxEvents??1e3,byteLimit=options.maxBytes??2*1024*1024;for(const[n,max]of[[polls,1e3],[timeout,18e5],[events,1e4],[byteLimit,16*1024*1024]])if(!Number.isSafeInteger(n)||n<1||n>max)sdkInputError();if(byteLimit<1024)sdkInputError();const controller=new AbortController;const timer=setTimeout(()=>controller.abort(),timeout);const signal=options.signal?AbortSignal.any([options.signal,controller.signal]):controller.signal;let after=input.after,etag=input.ifNoneMatch,count=0,bytes=0,unchanged=0;try{for(let n=0;n<polls;n++){signal.throwIfAborted();const page2=ProductionEventReadSchema.parse(await abortable(client.call("production.events.read",{...input,...after?{after}:{},...etag?{ifNoneMatch:etag}:{}},{signal,maxJsonBytes:128*1024}),signal));signal.throwIfAborted();count+=page2.items.length;bytes+=Buffer.byteLength(JSON.stringify(page2));if(count>events||bytes>byteLimit)throw new NativeStudioSdkError("OBSERVATION_LIMIT","WAITING_INPUT","NO_WRITE");if(page2.hasMore&&(page2.nextCursor===after||page2.items.length===0))throw new NativeStudioSdkError("CONTINUATION_INVALID","INTERNAL_OPERATIONAL_FAILURE","NO_WRITE");yield page2;after=page2.nextCursor;etag=page2.current.etag;unchanged=page2.items.length===0&&page2.current.condition==="NOT_MODIFIED"?unchanged+1:0;if(n+1<polls&&!page2.hasMore)await delay2(Math.min(3e4,page2.current.retryAfterMs*2**Math.min(unchanged,3)),void 0,{signal})}}catch(error){if(!controller.signal.aborted||options.signal?.aborted)throw error;throw new NativeStudioSdkError("OBSERVATION_LIMIT","WAITING_INPUT","NO_WRITE")}finally{clearTimeout(timer);controller.abort()}}import{createHmac,timingSafeEqual}from"node:crypto";function verifyWebhookNotification(input){const match=/^t=([1-9][0-9]{0,11}),v1=([a-f0-9]{64})$/.exec(input.signature);const now=input.now??Date.now();if(!(input.body instanceof Uint8Array)||input.body.length>128*1024||!match||!Number.isSafeInteger(now)||Math.abs(now/1e3-Number(match[1]))>300||typeof input.secret!=="string"||input.secret.length<32||input.secret.length>256||input.eventVersion!=="1"||!/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/.test(input.deliveryId))throw Error("WEBHOOK_INVALID");const expected=createHmac("sha256",input.secret).update(match[1]+".").update(input.body).digest();if(!timingSafeEqual(expected,Buffer.from(match[2],"hex")))throw Error("WEBHOOK_INVALID");try{const event=ExternalLifecycleEventSchema.parse(JSON.parse(new TextDecoder("utf-8",{fatal:true}).decode(input.body)));if(event.eventId!==input.eventId)throw Error();return event}catch{throw Error("WEBHOOK_INVALID")}}export{NavigationGroupIdSchema,NavigationGroups,navigationGroup,NavigationProfile,NavigationProfileKey,NavigationToolNames,CapabilityGroupsSchema,CapabilityDescribeSchema,DeviceDiscoveryInputSchema,DeviceRenderIntentSchema,DeviceRenderReadSchema,DeviceRenderDownloadSchema,PreparedDeviceRenderSchema,DeviceRenderAdmissionSchema,NativeStudioDeviceRenders,NativeStudioNavigationFacade,sdkOperations,NativeStudioAgentClient,sdkImageMediaTools,sdkMcpTools,NativeStudioMcpClient,NativeStudioNavigationClient,sdkCarrierDifferences,assertCarrierCoverage,NativeStudioRuntimeAuthorityClient,queryPages,waitForOperation,observeProduction,verifyWebhookNotification};
|