@nativestudio/cli 0.3.0-rc.2 → 0.3.0-rc.20
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 +37 -8
- package/LICENSE +201 -21
- package/components/runtime.json +33 -4
- package/components/runtime.tgz +0 -0
- package/dist/_chunks/chunk-27KI24GK.js +1 -0
- package/dist/_chunks/{chunk-C33A2DW4.js → chunk-3TOXIJ7K.js} +1 -1
- package/dist/_chunks/chunk-4M2SOMSN.js +1 -0
- package/dist/_chunks/chunk-4PAVWOPA.js +1 -0
- package/dist/_chunks/chunk-6EZX2TRX.js +1 -0
- package/dist/_chunks/chunk-7I7ARCY7.js +1 -0
- package/dist/_chunks/chunk-7P2NA6TH.js +1 -0
- package/dist/_chunks/chunk-AFNJRZLJ.js +1 -0
- package/dist/_chunks/chunk-APNZQZFB.js +1 -0
- package/dist/_chunks/chunk-D74NHT4I.js +45 -0
- package/dist/_chunks/chunk-DLW42PJ6.js +1 -0
- package/dist/_chunks/chunk-ELUJ44BO.js +1 -0
- package/dist/_chunks/chunk-FVY3PLG7.js +1 -0
- package/dist/_chunks/chunk-GLAF74UU.js +1 -0
- package/dist/_chunks/chunk-HBDPYWMI.js +1 -0
- package/dist/_chunks/chunk-IYDHDLTR.js +1 -0
- package/dist/_chunks/chunk-K35CWLDH.js +1 -0
- package/dist/_chunks/chunk-KOCUZ3AE.js +1 -0
- package/dist/_chunks/chunk-L3QA7FLZ.js +1 -0
- package/dist/_chunks/chunk-LBK42NHW.js +1 -0
- package/dist/_chunks/chunk-MLZ3ZPGU.js +1 -0
- package/dist/_chunks/chunk-NG4BDFEY.js +1 -0
- package/dist/_chunks/chunk-OSO6KRE2.js +1 -0
- package/dist/_chunks/{chunk-VDNNFVTZ.js → chunk-OW6R4MAQ.js} +1 -1
- package/dist/_chunks/chunk-QE7O57PQ.js +1 -0
- package/dist/_chunks/chunk-QGK6G6YS.js +1 -0
- package/dist/_chunks/chunk-QK4XPVKT.js +1 -0
- package/dist/_chunks/chunk-ROGOASYF.js +1 -0
- package/dist/_chunks/chunk-TT7IA5HB.js +1 -0
- package/dist/_chunks/chunk-UYKCN5DU.js +1 -0
- package/dist/_chunks/chunk-WTJVS2VS.js +1 -0
- package/dist/_chunks/chunk-XUSVNPR5.js +1 -0
- package/dist/_chunks/component-contract-KXK7WIUI.js +1 -0
- package/dist/_chunks/component-preflight-WECLCZLF.js +1 -0
- package/dist/_chunks/connect-7TJDWXV4.js +1 -0
- package/dist/_chunks/device-management-TLRUMZL5.js +1 -0
- package/dist/_chunks/device-preflight-C7FFUXI2.js +1 -0
- package/dist/_chunks/devices-inventory-BZF53UAU.js +1 -0
- package/dist/_chunks/devices-main-V3YHCB2C.js +1 -0
- package/dist/_chunks/files-JJ6YOULB.js +1 -0
- package/dist/_chunks/host-component-Q5IHRHRI.js +1 -0
- package/dist/_chunks/host-help-7BGYR4ET.js +1 -0
- package/dist/_chunks/host-main-JLIBRHC2.js +1 -0
- package/dist/_chunks/http-profile-3VVSWYA5.js +1 -0
- package/dist/_chunks/library-main-ATRFEAVN.js +1 -0
- package/dist/_chunks/local-main-KTYCLHDA.js +1 -0
- package/dist/_chunks/local-mcp-ISMU6ADI.js +1 -0
- package/dist/_chunks/main-MOZS2EK3.js +2 -0
- package/dist/_chunks/mcp-M2SO3J2H.js +1 -0
- package/dist/_chunks/oauth-RPME2XYB.js +1 -0
- package/dist/_chunks/observe-entry-E6DFHIMW.js +1 -0
- package/dist/_chunks/remote-client-T75C45JO.js +1 -0
- package/dist/_chunks/render-main-OGCO2LX4.js +1 -0
- package/dist/_chunks/series-main-FBERVYWG.js +1 -0
- package/dist/_chunks/source-import-55JJ26AA.js +1 -0
- package/dist/_chunks/src-V2K52JDH.js +1 -0
- package/dist/_chunks/stdio-main-HNLJCG45.js +1 -0
- package/dist/_chunks/workspace-main-3P56DSEQ.js +1 -0
- package/dist/_types/cli/local/desktop-contract.d.ts +1981 -22
- package/dist/_types/cli/local/desktop-device-contract.d.ts +807 -0
- package/dist/_types/cli/local/desktop-device-navigation.d.ts +3 -0
- package/dist/_types/cli/local/desktop-device-owner.d.ts +273 -0
- package/dist/_types/cli/local/desktop-device-state.d.ts +455 -0
- package/dist/_types/cli/local/desktop-library.d.ts +853 -0
- package/dist/_types/cli/local/desktop-owner.d.ts +787 -4
- package/dist/_types/cli/local/ledger.d.ts +76 -20
- package/dist/_types/cli/local/manager.d.ts +1233 -49
- package/dist/_types/cli/local/mcp-tools.d.ts +313 -54
- package/dist/_types/cli/local/releases.d.ts +30 -7
- package/dist/_types/cli/local-management.d.ts +9 -2
- package/dist/_types/cli/local-navigation.d.ts +1 -0
- 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 +143 -11
- package/dist/_types/contracts/audio.d.ts +166 -0
- package/dist/_types/contracts/component-status.d.ts +241 -0
- package/dist/_types/contracts/composition-authoring.d.ts +8 -8
- package/dist/_types/contracts/composition-frame-render.d.ts +4 -4
- package/dist/_types/contracts/composition-observation.d.ts +1 -1
- package/dist/_types/contracts/composition-render-base.d.ts +5 -4
- package/dist/_types/contracts/composition-render.d.ts +8 -8
- package/dist/_types/contracts/composition-repair.d.ts +10 -10
- package/dist/_types/contracts/composition-source-review.d.ts +13 -13
- package/dist/_types/contracts/consistency-profile.d.ts +102 -6
- package/dist/_types/contracts/continuity-evaluation.d.ts +1 -1
- package/dist/_types/contracts/delivery-completion.d.ts +1 -1
- package/dist/_types/contracts/delivery-manifest.d.ts +25 -11729
- package/dist/_types/contracts/delivery-operations.d.ts +207 -3915
- package/dist/_types/contracts/delivery-summary.d.ts +4 -4
- package/dist/_types/contracts/delivery-validation.d.ts +25 -2
- package/dist/_types/contracts/device-onboarding.d.ts +35 -0
- package/dist/_types/contracts/device-render.d.ts +113 -0
- package/dist/_types/contracts/editor-intelligence.d.ts +392 -2531
- package/dist/_types/contracts/enterprise-brand.d.ts +302 -0
- package/dist/_types/contracts/exploration-recommendation.d.ts +263 -11607
- package/dist/_types/contracts/external-agent-access.d.ts +4 -6
- 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 +24 -24
- package/dist/_types/contracts/final-render.d.ts +1742 -6949
- package/dist/_types/contracts/human-identity.d.ts +13 -0
- package/dist/_types/contracts/human-links.d.ts +58 -0
- package/dist/_types/contracts/index.d.ts +26 -0
- package/dist/_types/contracts/interface/common.d.ts +18 -0
- package/dist/_types/contracts/interface/execution-output.d.ts +9 -6
- package/dist/_types/contracts/interface/media-output.d.ts +118 -0
- package/dist/_types/contracts/interface/operation.d.ts +30 -0
- package/dist/_types/contracts/interface/production-snapshot.d.ts +81 -199
- package/dist/_types/contracts/interface/query.d.ts +60 -0
- package/dist/_types/contracts/keyframe-generation.d.ts +31 -2
- package/dist/_types/contracts/keyframe-review.d.ts +7 -7
- package/dist/_types/contracts/lifecycle-event-projections.d.ts +17 -2
- package/dist/_types/contracts/lifecycle-events.d.ts +54 -2
- package/dist/_types/contracts/local-execution/agent-component-status.d.ts +109 -0
- package/dist/_types/contracts/local-execution/agent-context.d.ts +385 -0
- package/dist/_types/contracts/local-execution/agent-evidence.d.ts +79 -0
- package/dist/_types/contracts/local-execution/agent-grant.d.ts +31 -0
- package/dist/_types/contracts/local-execution/agent-review.d.ts +529 -71
- package/dist/_types/contracts/local-execution/audio-profile.d.ts +6 -0
- package/dist/_types/contracts/local-execution/common.d.ts +12 -11
- package/dist/_types/contracts/local-execution/completion.d.ts +41 -45
- package/dist/_types/contracts/local-execution/components.d.ts +45 -0
- package/dist/_types/contracts/local-execution/cpu-preparation.d.ts +46 -0
- package/dist/_types/contracts/local-execution/cpu-resources.d.ts +55 -0
- package/dist/_types/contracts/local-execution/cpu-speech-job.d.ts +70 -0
- package/dist/_types/contracts/local-execution/cpu-speech.d.ts +161 -0
- package/dist/_types/contracts/local-execution/descriptor.d.ts +38 -0
- package/dist/_types/contracts/local-execution/device-authority.d.ts +31 -0
- package/dist/_types/contracts/local-execution/device-inventory.d.ts +108 -0
- package/dist/_types/contracts/local-execution/device-workspace.d.ts +11 -0
- package/dist/_types/contracts/local-execution/device.d.ts +24 -55
- package/dist/_types/contracts/local-execution/enrollment-credential.d.ts +141 -0
- package/dist/_types/contracts/local-execution/enrollment-handoff.d.ts +44 -0
- package/dist/_types/contracts/local-execution/external-generation.d.ts +199 -0
- package/dist/_types/contracts/local-execution/index.d.ts +36 -0
- package/dist/_types/contracts/local-execution/ipc.d.ts +2809 -231
- package/dist/_types/contracts/local-execution/library-command.d.ts +620 -0
- package/dist/_types/contracts/local-execution/library-result.d.ts +428 -0
- package/dist/_types/contracts/local-execution/library.d.ts +873 -0
- package/dist/_types/contracts/local-execution/lifecycle.d.ts +262 -48
- package/dist/_types/contracts/local-execution/local-navigation.d.ts +304 -67
- package/dist/_types/contracts/local-execution/management.d.ts +407 -0
- package/dist/_types/contracts/local-execution/media-recipe.d.ts +207 -0
- package/dist/_types/contracts/local-execution/media-validation-request.d.ts +232 -0
- package/dist/_types/contracts/local-execution/media-validation.d.ts +262 -0
- package/dist/_types/contracts/local-execution/object-transfer.d.ts +155 -0
- package/dist/_types/contracts/local-execution/offline.d.ts +59 -0
- package/dist/_types/contracts/local-execution/preview.d.ts +177 -3561
- package/dist/_types/contracts/local-execution/processor-capability.d.ts +49 -0
- package/dist/_types/contracts/local-execution/processor-direct.d.ts +290 -0
- package/dist/_types/contracts/local-execution/processor-recipes.d.ts +1194 -0
- package/dist/_types/contracts/local-execution/processor-toolchain.d.ts +47 -0
- package/dist/_types/contracts/local-execution/processor.d.ts +6424 -0
- package/dist/_types/contracts/local-execution/project-source-direct.d.ts +201 -0
- package/dist/_types/contracts/local-execution/qwen-tts.d.ts +31 -0
- package/dist/_types/contracts/local-execution/recognition.d.ts +170 -0
- package/dist/_types/contracts/local-execution/speech.d.ts +95 -0
- package/dist/_types/contracts/local-execution/tool-selection.d.ts +71 -5
- package/dist/_types/contracts/local-execution/whisper.d.ts +24 -0
- package/dist/_types/contracts/local-execution/work.d.ts +124 -3402
- package/dist/_types/contracts/local-execution/workspace.d.ts +141 -0
- package/dist/_types/contracts/mcp-capabilities.d.ts +16 -0
- package/dist/_types/contracts/media-category.d.ts +11 -0
- package/dist/_types/contracts/media-observation.d.ts +930 -9
- package/dist/_types/contracts/native-speech-model.d.ts +53 -0
- package/dist/_types/contracts/native-speech-options.d.ts +25 -0
- 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 +28 -8
- package/dist/_types/contracts/navigation-groups.d.ts +2 -2
- package/dist/_types/contracts/navigation.d.ts +78 -25
- package/dist/_types/contracts/observation-profile.d.ts +3 -3
- package/dist/_types/contracts/production-creation.d.ts +30 -0
- package/dist/_types/contracts/production-feedback.d.ts +452 -0
- package/dist/_types/contracts/production.d.ts +30 -0
- package/dist/_types/contracts/programmatic-composition.d.ts +24 -24
- package/dist/_types/contracts/programmatic-exploration.d.ts +362 -5999
- package/dist/_types/contracts/programmatic-video-review.d.ts +5 -5
- package/dist/_types/contracts/project-library.d.ts +30 -0
- package/dist/_types/contracts/project.d.ts +30 -0
- package/dist/_types/contracts/provider-catalog.d.ts +3 -3
- package/dist/_types/contracts/provider-models.d.ts +209 -8
- package/dist/_types/contracts/provider.d.ts +66 -1
- package/dist/_types/contracts/reference-preview.d.ts +20 -0
- package/dist/_types/contracts/render-readiness.d.ts +175 -0
- package/dist/_types/contracts/repair-lifecycle.d.ts +64 -396
- package/dist/_types/contracts/repair-plan.d.ts +18 -100
- package/dist/_types/contracts/repair-strategy.d.ts +163 -4478
- package/dist/_types/contracts/review-intelligence-final-output.d.ts +418 -8150
- package/dist/_types/contracts/review-intelligence.d.ts +455 -11423
- package/dist/_types/contracts/review1-repair-source.d.ts +6 -6
- package/dist/_types/contracts/review1-repair-strategy.d.ts +4 -4
- package/dist/_types/contracts/rough-cut-manifest.d.ts +27 -7
- package/dist/_types/contracts/rough-cut-profile.d.ts +12 -3
- package/dist/_types/contracts/rough-cut-review.d.ts +144 -12495
- package/dist/_types/contracts/rough-cut.d.ts +1170 -5673
- package/dist/_types/contracts/series-canon.d.ts +97 -0
- package/dist/_types/contracts/series-character.d.ts +23 -0
- package/dist/_types/contracts/series-improvement.d.ts +1639 -0
- package/dist/_types/contracts/series-standard.d.ts +1641 -0
- package/dist/_types/contracts/shares.d.ts +135 -0
- package/dist/_types/contracts/shot-preparation-basis.d.ts +2 -2
- package/dist/_types/contracts/shot-preparation.d.ts +4 -4
- package/dist/_types/contracts/sound-making-plan.d.ts +210 -2
- package/dist/_types/contracts/speech-cost.d.ts +96 -0
- package/dist/_types/contracts/speech-parameters.d.ts +39 -0
- package/dist/_types/contracts/speech.d.ts +603 -23
- package/dist/_types/contracts/temporal-evidence-operation.d.ts +2 -1
- package/dist/_types/contracts/timeline-audio.d.ts +20 -4
- package/dist/_types/contracts/timeline-manifest.d.ts +40 -8
- package/dist/_types/contracts/timeline-source-sound.d.ts +42 -4
- package/dist/_types/contracts/timeline-v2.d.ts +124 -16
- package/dist/_types/contracts/timeline-version-reader.d.ts +288 -40
- package/dist/_types/contracts/timeline-visual-layers.d.ts +124 -16
- package/dist/_types/contracts/timeline.d.ts +50 -4850
- package/dist/_types/contracts/transcription.d.ts +1 -1
- package/dist/_types/contracts/video-generation.d.ts +35 -2
- package/dist/_types/contracts/video-review.d.ts +7 -7
- package/dist/_types/contracts/visual-exploration.d.ts +3 -3
- package/dist/_types/contracts/visual-layer-render.d.ts +298 -47
- package/dist/_types/contracts/visual-sequence.d.ts +22 -0
- package/dist/_types/contracts/voice-consistency.d.ts +183 -0
- package/dist/_types/contracts/voice-profile/contracts.d.ts +821 -0
- package/dist/_types/contracts/voice-profile/identity.d.ts +27 -0
- package/dist/_types/contracts/voice-profile/interface.d.ts +89 -0
- package/dist/_types/contracts/voice-profile/reference.d.ts +106 -0
- package/dist/_types/contracts/voice-review.d.ts +1194 -0
- package/dist/_types/contracts/workspace.d.ts +83 -0
- package/dist/_types/sdk/errors.d.ts +9 -3
- package/dist/_types/sdk/local-runtime/components.d.ts +2 -0
- package/dist/_types/sdk/local-runtime/device-client.d.ts +181 -19
- package/dist/_types/sdk/local-runtime/library.d.ts +268 -0
- package/dist/_types/sdk/local-runtime/workspace.d.ts +186 -0
- package/dist/_types/sdk/local-runtime-client.d.ts +1934 -96
- package/dist/entry.js +1 -1
- package/dist/local-management.js +1 -1
- package/dist/local-navigation.js +1 -1
- package/dist/native/helper.exe +0 -0
- package/dist/native/helper.json +1 -0
- package/package.json +2 -8
- package/README.md +0 -95
- package/dist/_chunks/chunk-66CUOZVI.js +0 -1
- package/dist/_chunks/chunk-6NVIN2NI.js +0 -1
- package/dist/_chunks/chunk-7S3DJ2QE.js +0 -1
- package/dist/_chunks/chunk-BVSTJQJI.js +0 -1
- package/dist/_chunks/chunk-C753RRRA.js +0 -1
- package/dist/_chunks/chunk-E57YVMQ4.js +0 -1
- package/dist/_chunks/chunk-GJ7BZJLW.js +0 -1
- package/dist/_chunks/chunk-HLKERZIE.js +0 -1
- package/dist/_chunks/chunk-K6LVS2IN.js +0 -1
- package/dist/_chunks/chunk-KHKUJXQX.js +0 -1
- package/dist/_chunks/chunk-PUNG4ND7.js +0 -1
- package/dist/_chunks/chunk-VC3ODN3M.js +0 -1
- package/dist/_chunks/chunk-VPYAXWXY.js +0 -1
- package/dist/_chunks/files-FZEK2ZZJ.js +0 -1
- package/dist/_chunks/local-main-NLFS74Q4.js +0 -1
- package/dist/_chunks/local-mcp-OLHBBVNN.js +0 -1
- package/dist/_chunks/main-VRIQTI6R.js +0 -2
- package/dist/_chunks/mcp-EIMXNRH3.js +0 -1
- package/dist/_chunks/oauth-F7EZGVME.js +0 -1
- package/dist/_chunks/project-connect-MXM7IY55.js +0 -1
- package/dist/_chunks/src-7F6ZEU3U.js +0 -1
- package/dist/_chunks/stdio-main-KOGQ5OWF.js +0 -1
- package/dist/native/Bootstrap.ps1 +0 -90
- package/dist/native/JobNative.cs +0 -127
- package/dist/native/JobRunner.cs +0 -360
- package/dist/native/NativeMain.cs +0 -146
- package/dist/native/PipeBridge.cs +0 -260
- package/dist/native/PrivateAccess.cs +0 -152
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{ComponentStatusSchema,CpuSpeechCapabilitySchema,CpuSpeechInputSchema,CpuSpeechInstallationSchema,DeviceEnrollmentScopeSchema,EnrollLocalDeviceSchema,KeyframeObservationSchema,LegacyCaptionRenderStyleSchema,LocalDeviceManagementCommandSchema,LocalDevicePlatformSchema,LocalDeviceViewSchema,LocalDigestSchema,LocalFinalRenderAdmissionSchema,LocalIdSchema,LocalLeaseBindingSchema,LocalLibraryCallSchema,LocalLibraryCapabilitySchema,LocalLibraryGetSchema,LocalLibraryImportSchema,LocalLibraryItemSchema,LocalLibraryPageSchema,LocalLibraryProjectionPageSchema,LocalLibraryProjectionSchema,LocalLibraryReadReplySchema,LocalLibraryUsageSchema,LocalManagementReceiptSchema,LocalPackageVersionSchema,LocalPreviewAdmissionSchema,LocalProjectScopeSchema,LocalRevisionSchema,LocalTimeSchema,LocalWhisperToolSelectionSchema,LocalWorkScopeSchema,RegularCaptionRenderStyleSchema,ReviewEvidenceMediaSchema,ReviewIntelligenceBasisSchema,ReviewIntelligenceContextResultSchema,RevokeLocalDeviceSchema,RoughCutRequirementSchema,StartLocalFinalRenderSchema,StartLocalPreviewSchema,TenantProcessorKindSchema,ValidateReviewIntelligenceSchema,VideoReviewRequirementSchema,VisualRequirementSchema,assertManagementReceipt,canonicalLocalJson,checkedManagementReceipt,kokoroCpuProfile,mediaCategoryOf}from"./chunk-APNZQZFB.js";import{fail,localSocketPath,privateAccess,privateDirectory,read,sha256,sha512}from"./chunk-DLW42PJ6.js";import{CapabilityVersionMismatchSchema}from"./chunk-WTJVS2VS.js";import{NativeStudioSdkError}from"./chunk-TT7IA5HB.js";import{z}from"zod";var HYPERFRAME_RENDER_PROFILE={id:"HYPERFRAME_1080P30_FULL_PAINT_V1",adapter:"native-hyperframe-v1",engine:"0.8.134",producer:"0.8.134",gsap:"3.15.0",node:"v24.21.0",browser:"Google Chrome for Testing 154.0.8037.57",browserSha256:"60c03e8882f4bb47459a905ede1074e1e746c5b765e437c288e460320540a8a3",ffmpeg:"ffmpeg version 8.0.1-3ubuntu2 Copyright (c) 2000-2025 the FFmpeg developers",maxFrames:360,timeoutMs:6e5,maxRssBytes:3221225472,maxScratchBytes:3221225472,maxOutputBytes:134217728,maxCpuMs:6e5,capture:"PNG_SOFTWARE_SCREENSHOT_FULL_PAINT",encode:"H264_YUV420P_CRF18_THREADS2_NO_AUDIO"};var HYPERFRAME_ALPHA_RENDER_PROFILE={...HYPERFRAME_RENDER_PROFILE,id:"HYPERFRAME_RGBA_PNG30_FULL_PAINT_V1",adapter:"native-hyperframe-alpha-v1",encode:"RGBA_PNG_SEQUENCE_30_V1",maxOutputBytes:67108864,maxDecodedBytes:536870912};var HYPERFRAME_CACHED_RENDER_PROFILE={...HYPERFRAME_RENDER_PROFILE,id:"HYPERFRAME_1080P30_FRAME_CACHE_V2",adapter:"native-hyperframe-cache-v2",encode:"H264_YUV420P_CRF18_VERYFAST_THREADS2_NO_AUDIO"};var executable=z.strictObject({path:z.string().min(1).max(4096),digest:LocalDigestSchema});var LocalManagedMediaReuseSchema=z.strictObject({schemaVersion:z.literal(1),ffmpeg:executable,ffprobe:executable});var mediaTools={ffmpeg:executable,ffprobe:executable};var LocalCompositionBrowserSelectionSchema=executable.extend({digest:z.literal(HYPERFRAME_CACHED_RENDER_PROFILE.browserSha256)});var LocalInstalledToolSelectionSchema=z.strictObject({mode:z.literal("INSTALLED"),...mediaTools,compositionBrowser:LocalCompositionBrowserSelectionSchema.optional(),whisper:LocalWhisperToolSelectionSchema.optional(),cpuSpeech:CpuSpeechInstallationSchema.optional()});var LocalToolSelectionSchema=z.discriminatedUnion("mode",[z.strictObject({mode:z.literal("MANAGED"),...mediaTools,cpuSpeech:CpuSpeechInstallationSchema.optional()}),LocalInstalledToolSelectionSchema]);import{z as z2}from"zod";var LocalRuntimeDescriptorSchema=z2.strictObject({protocol:z2.literal("NVS_RUNTIME_DESCRIPTOR_V1"),version:LocalPackageVersionSchema,node:z2.strictObject({major:z2.literal(24),minMinor:z2.literal(12)}),platform:LocalDevicePlatformSchema,ipcProtocol:z2.literal("NVS_LOCAL_IPC_V1"),workProtocol:z2.enum(["NVS_LOCAL_WORK_V1","NVS_LOCAL_WORK_V2"]),journalSchema:z2.literal(1),rendererDigest:LocalDigestSchema,profileDigest:LocalDigestSchema,compatibleRenderers:z2.array(z2.strictObject({rendererDigest:LocalDigestSchema,profileDigest:LocalDigestSchema})).max(4).optional()});var LocalReleaseAssetSchema=z2.strictObject({url:z2.string().url().max(2048),byteSize:z2.int().positive().max(256*1024*1024),sha512:z2.string().length(128).regex(/^[0-9a-f]{128}$/)});import{z as z4}from"zod";import{z as z3}from"zod";var RuntimeCaptionAssets={"NotoSansSC.ttf":LegacyCaptionRenderStyleSchema.shape.fontSha256.value,"NativeStudioSC-Regular.ttf":RegularCaptionRenderStyleSchema.shape.fontSha256.value,"OFL.txt":"092c580f54ee69841e94731e91f63f5d2d2a793550f4827cec485656e462f1bd"};var LocalComponentBytesSchema=z3.strictObject({byteSize:z3.int().positive().max(64*1024*1024),sha512:z3.string().length(128).regex(/^[0-9a-f]{128}$/)});var LocalRuntimeComponentSchema=LocalComponentBytesSchema.extend({protocol:z3.literal("NVS_PRODUCT_COMPONENT_V2"),version:LocalPackageVersionSchema,descriptor:LocalRuntimeDescriptorSchema.omit({platform:true}),resources:z3.strictObject({captions:LocalComponentBytesSchema})}).refine(v=>v.version===v.descriptor.version);var LocalSessionConnectorSchema=z4.strictObject({protocol:z4.literal("NVS_LOCAL_CONNECTOR_V1"),stateDirectory:z4.string().min(1).max(4096),credential:z4.string().length(43).regex(/^[A-Za-z0-9_-]{43}$/),expiresAt:LocalTimeSchema,tenantId:z4.uuid(),deviceId:z4.uuid()});var LocalManagementInventorySchema=z4.strictObject({runtimeRevision:z4.int().positive(),descriptor:LocalRuntimeDescriptorSchema,activeProcesses:z4.int().nonnegative(),pendingExecutions:z4.int().nonnegative(),pendingRequests:z4.int().nonnegative(),pendingRenderers:z4.array(LocalDigestSchema).max(64)});var LocalReleaseSchema=z4.strictObject({descriptor:LocalRuntimeDescriptorSchema,package:LocalReleaseAssetSchema,tools:z4.strictObject({ffmpeg:LocalReleaseAssetSchema.extend({sha256:LocalDigestSchema}),ffprobe:LocalReleaseAssetSchema.extend({sha256:LocalDigestSchema})}).nullable(),resources:z4.strictObject({captions:LocalReleaseAssetSchema.extend({byteSize:LocalComponentBytesSchema.shape.byteSize})}).optional()});var LocalBundledReleaseSchema=LocalReleaseSchema.extend({package:LocalComponentBytesSchema.extend({source:z4.literal("CLI")})});var LocalReleaseCatalogueSchema=z4.strictObject({protocol:z4.literal("NVS_LOCAL_RELEASE_CATALOGUE_V1"),issuedAt:LocalTimeSchema,expiresAt:LocalTimeSchema,releases:z4.array(LocalReleaseSchema).min(1).max(32)}).refine(v=>Date.parse(v.expiresAt)>Date.parse(v.issuedAt)&&Date.parse(v.expiresAt)-Date.parse(v.issuedAt)<=7*864e5&&new Set(v.releases.map(r=>[r.descriptor.version,r.descriptor.platform.os,r.descriptor.platform.architecture].join(":"))).size===v.releases.length);var LocalSignedCatalogueSchema=z4.strictObject({catalogue:LocalReleaseCatalogueSchema,signature:z4.string().length(86).regex(/^[A-Za-z0-9_-]{85}[AQgw]$/)});var LocalToolChoiceSchema=z4.discriminatedUnion("mode",[z4.strictObject({mode:z4.literal("MANAGED"),cpuSpeech:CpuSpeechInstallationSchema.optional(),reuseMedia:LocalManagedMediaReuseSchema.optional()}),LocalInstalledToolSelectionSchema.extend({captionAssetsDirectory:z4.string().min(1).max(4096).optional()})]);var LocalUpdatePlanSchema=z4.strictObject({protocol:z4.literal("NVS_LOCAL_UPDATE_PLAN_V1"),planId:LocalIdSchema,installationRevision:z4.int().nonnegative(),runtimeRevision:z4.int().positive().nullable(),catalogueFingerprint:LocalDigestSchema.nullable(),trustFingerprint:LocalDigestSchema.optional(),release:z4.union([LocalReleaseSchema,LocalBundledReleaseSchema]),toolSelection:LocalToolChoiceSchema.optional(),fingerprint:LocalDigestSchema,createdAt:LocalTimeSchema,expiresAt:LocalTimeSchema});var LocalClientNextActionSchema=z4.strictObject({surface:z4.enum(["CLI","LOCAL_IPC","REMOTE"]),operation:z4.enum(["runtime.status","local.configure","local.install","local.start","local.connect","local.grant","local.status","local.doctor","local.stop","local.update.check","local.update.prepare","local.update.apply","local.update.reconcile","execution.inspect","rough_cut_get","operation_get"]),availability:z4.enum(["AVAILABLE","BLOCKED"]),reason:z4.enum(["READY","INSTALL_REQUIRED","AUTHORIZATION_REQUIRED","VERSION_INCOMPATIBLE","UPDATE_AVAILABLE","RECOVERY_REQUIRED","USER_APPROVAL_REQUIRED","TRUST_REQUIRED","UNAVAILABLE"])});import{z as z11}from"zod";import{z as z10}from"zod";import{z as z5}from"zod";var LocalOfflineSnapshotSchema=z5.strictObject({projectId:z5.uuid(),title:z5.string().min(1).max(200),savedAt:LocalTimeSchema,expiresAt:LocalTimeSchema,productions:z5.array(z5.strictObject({id:z5.uuid(),title:z5.string().max(200)})).max(40),possiblyTruncated:z5.boolean()}).refine(v=>new TextEncoder().encode(JSON.stringify(v)).length<=8192);var text=z5.string().max(4e3).refine(v=>new TextEncoder().encode(JSON.stringify(v)).length<=8192);var LocalOfflineCallSchema=z5.discriminatedUnion("action",[z5.strictObject({action:z5.enum(["list","forget"]),key:LocalDigestSchema}),z5.strictObject({action:z5.literal("retain"),key:LocalDigestSchema,snapshot:LocalOfflineSnapshotSchema}),z5.strictObject({action:z5.literal("draft"),key:LocalDigestSchema,projectId:z5.uuid(),text,expectedRevision:z5.int().nonnegative()})]);var LocalOfflinePageSchema=z5.strictObject({historical:z5.literal(true),items:z5.array(z5.strictObject({snapshot:LocalOfflineSnapshotSchema,draft:z5.strictObject({text,revision:z5.int().nonnegative()})})).max(3)});import{z as z7}from"zod";import{z as z6}from"zod";var QualifiedLocalAgentVersionSchema=z6.enum(["0.164.0","0.165.0"]);var LocalAgentGrantSchema=z6.strictObject({protocol:z6.literal("NVS_CODEX_REVIEW_GRANT_V1"),binary:z6.string().min(1).max(4096).refine(v=>/^(?:\/|[A-Za-z]:[\\/])/.test(v)),binaryDigest:z6.string().regex(/^[a-f0-9]{64}$/),version:QualifiedLocalAgentVersionSchema,model:z6.string().regex(/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,99}$/),reasoningEffort:z6.enum(["low","medium","high","xhigh"]).optional(),reviewerLabel:z6.string().trim().min(1).max(100),inference:z6.literal("REMOTE_OPENAI"),remoteUseApproved:z6.literal(true),imageDisclosureApproved:z6.literal(true).optional(),mediaDisclosureApproved:z6.literal(true).optional(),projects:z6.array(LocalProjectScopeSchema).min(1).max(100),expiresAt:z6.iso.datetime({offset:true})});var LocalAgentMediaInputSchema=z7.strictObject({profile:z7.literal("NVS_AGENT_DERIVED_EVIDENCE_V1"),contentType:z7.enum(["image/png","image/jpeg","image/webp","video/mp4"]),byteSize:z7.int().positive().max(134217728),width:z7.int().positive().max(4096),height:z7.int().positive().max(4096),durationMs:z7.int().positive().max(6e4).optional(),frameRate:z7.union([z7.literal(24),z7.literal(30)]).optional(),hasAudio:z7.boolean().optional()}).refine(v=>v.contentType==="video/mp4"?!!v.durationMs&&!!v.frameRate:!v.durationMs&&!v.frameRate&&v.hasAudio===void 0);var sha=z7.string().regex(/^[a-f0-9]{64}$/);var LocalAgentEvidenceReceiptSchema=z7.strictObject({protocol:z7.literal("NVS_AGENT_DERIVED_EVIDENCE_V1"),draftId:z7.uuid(),media:ReviewEvidenceMediaSchema,ffmpegDigest:sha,ffprobeDigest:sha,attachment:z7.strictObject({checksumSha256:sha,byteSize:z7.int().positive().max(8388608),width:z7.int().positive().max(4096),height:z7.int().positive().max(4096)}),timestampsMs:z7.array(z7.number().nonnegative().max(6e4)).max(6),audio:z7.strictObject({sampleRateHz:z7.literal(48e3),channels:z7.literal(1),samples:z7.int().positive().max(2881024),peak:z7.number().min(0).max(1),rms:z7.number().min(0).max(1),clippedSamples:z7.int().nonnegative().max(2881024)}).nullable(),limitations:z7.tuple([z7.literal("SAMPLED_FRAMES_ARE_NOT_FULL_PLAYBACK"),z7.literal("AUDIO_STATISTICS_ARE_NOT_LISTENING_OR_TRANSCRIPTION")])});var LocalAgentDiscoverySchema=z7.strictObject({candidate:z7.strictObject({binary:z7.string().min(1).max(4096),binaryDigest:sha,version:z7.string().regex(/^\d+\.\d+\.\d+$/),qualified:z7.boolean()}).nullable(),configured:LocalAgentGrantSchema.nullable()});import{z as z8}from"zod";var LocalResourcePolicySchema=z8.strictObject({acceptNewWork:z8.boolean().default(true),mode:z8.enum(["CONTINUOUS","IDLE_ONLY"]).default("CONTINUOUS"),idleAfterSeconds:z8.int().min(30).max(3600).default(300),maxConcurrentJobs:z8.int().min(1).max(2).default(1),cpuCores:z8.union([z8.literal(1),z8.literal(2)]).default(2),memoryMiB:z8.int().min(512).max(4096).default(4096),cacheQuotaBytes:z8.int().min(512*1024*1024).max(32*1024*1024*1024).default(1024*1024*1024)});var LocalResourceSettingsSchema=z8.strictObject({revision:z8.int().nonnegative(),policy:LocalResourcePolicySchema});var LocalExecutionProgressSchema=z8.strictObject({stage:z8.enum(["WAITING","DOWNLOADING","EXECUTING","UPLOADING","AWAITING_ACCEPTANCE","COMPLETE","RECOVERY_REQUIRED","FENCED"]),downloadedBytes:z8.int().nonnegative(),sourceBytes:z8.int().nonnegative(),uploadedBytes:z8.int().nonnegative(),outputBytes:z8.int().nonnegative(),lastError:z8.strictObject({code:z8.string().regex(/^[A-Z][A-Z0-9_]{0,79}$/),observedAt:LocalTimeSchema}).nullable()});var LocalStorageInspectionSchema=z8.strictObject({cacheBytes:z8.int().nonnegative(),protectedBytes:z8.int().nonnegative(),reclaimableBytes:z8.int().nonnegative(),transferBytes:z8.int().nonnegative(),journalBytes:z8.int().nonnegative(),reviewBytes:z8.int().nonnegative().optional(),ownerStagingBytes:z8.int().nonnegative().optional(),availableDiskBytes:z8.int().nonnegative(),quotaBytes:z8.int().positive(),overQuota:z8.boolean()});var LocalWorkspaceInspectionSchema=z8.strictObject({settings:LocalResourceSettingsSchema,storage:LocalStorageInspectionSchema,scheduling:z8.strictObject({state:z8.enum(["READY","PAUSED","WAITING_FOR_IDLE","AT_CAPACITY","DRAINING"]),activeJobs:z8.int().nonnegative(),idleObservationCurrent:z8.boolean()})});var LocalDiagnosticsSchema=z8.strictObject({protocol:z8.literal("NVS_LOCAL_DIAGNOSTICS_V1"),createdAt:LocalTimeSchema,runtimeVersion:z8.string().min(1).max(80),runtimeRevision:LocalRevisionSchema,settings:LocalResourceSettingsSchema,storage:LocalStorageInspectionSchema,recordCounts:z8.record(z8.string().regex(/^[A-Z_]{1,40}$/),z8.int().nonnegative()),failures:z8.array(z8.strictObject({taskFingerprint:z8.string().regex(/^[a-f0-9]{64}$/),code:z8.string().regex(/^[A-Z][A-Z0-9_]{0,79}$/),observedAt:LocalTimeSchema})).max(32)});import{z as z9}from"zod";var sha2=z9.string().regex(/^[a-f0-9]{64}$/);var qualifiedVersion=QualifiedLocalAgentVersionSchema;var LocalAgentSnapshotSchema=z9.strictObject({basis:ReviewIntelligenceBasisSchema,productionRevision:z9.int().positive(),reviewVersion:z9.int().nonnegative(),executionClass:z9.enum(["LIVE","TEST_ONLY"]),media:ReviewEvidenceMediaSchema,requirements:z9.array(z9.union([VisualRequirementSchema,VideoReviewRequirementSchema,RoughCutRequirementSchema])).min(1).max(64),evidence:LocalAgentMediaInputSchema.optional(),image:z9.strictObject({contentType:z9.literal("image/png"),byteSize:z9.int().positive().max(8388608),width:z9.int().positive().max(4096),height:z9.int().positive().max(4096)}).optional()}).refine(v=>!v.image||!v.evidence&&v.basis.target.kind==="IMAGE").refine(v=>v.basis.target.kind==="IMAGE"||!v.evidence||v.evidence.contentType==="video/mp4").refine(v=>new TextEncoder().encode(JSON.stringify(v)).length<=32768).refine(v=>new Set(v.requirements.map(r=>r.key)).size===v.requirements.length);var LocalAgentProbeSchema=z9.strictObject({configured:z9.boolean(),available:z9.boolean(),reason:z9.enum(["GRANT_REQUIRED","READY","RUNTIME_UNAVAILABLE","GRANT_EXPIRED"]),grantFingerprint:sha2.nullable(),inference:z9.literal("REMOTE_OPENAI")});var LocalAgentPlanSchema=z9.strictObject({protocol:z9.enum(["NVS_LOCAL_AGENT_REVIEW_V1","NVS_LOCAL_AGENT_REVIEW_V2"]),id:z9.uuid(),grantFingerprint:sha2,snapshot:LocalAgentSnapshotSchema,expiresAt:z9.iso.datetime({offset:true}),fingerprint:sha2});var LocalAgentMetadataAnswerSchema=z9.strictObject({summary:z9.string().trim().min(1).max(1500),observations:z9.array(z9.strictObject({key:z9.string().min(1).max(220),observed:z9.string().trim().min(1).max(1e3)})).min(1).max(64)});var LocalAgentPixelAnswerSchema=z9.strictObject({summary:z9.string().trim().min(1).max(1500),imageReadback:z9.string().trim().min(1).max(800),observations:z9.array(KeyframeObservationSchema.omit({region:true}).extend({key:z9.string().min(1).max(220)})).min(1).max(64)});var LocalAgentAnswerSchema=z9.union([LocalAgentMetadataAnswerSchema,LocalAgentPixelAnswerSchema]).refine(v=>new TextEncoder().encode(JSON.stringify(v)).length<=96*1024);var LocalAgentImageReceiptSchema=z9.strictObject({protocol:z9.literal("NVS_LOCAL_AGENT_IMAGE_V1"),draftId:z9.uuid(),media:ReviewEvidenceMediaSchema,byteSize:z9.int().positive().max(8388608),contentType:z9.literal("image/png"),width:z9.int().positive().max(4096),height:z9.int().positive().max(4096)});var LocalAgentReviewViewSchema=z9.strictObject({plan:LocalAgentPlanSchema,revision:z9.int().positive(),phase:z9.enum(["PREPARED","RUNNING","RESULT_PENDING","UNKNOWN"]),answer:LocalAgentAnswerSchema.nullable(),imageReceipt:LocalAgentImageReceiptSchema.optional(),evidenceReceipt:LocalAgentEvidenceReceiptSchema.optional(),provenance:z9.strictObject({adapter:z9.enum(["CODEX_METADATA_V1","CODEX_MEDIA_V2"]),binaryDigest:sha2,version:qualifiedVersion,model:z9.string().max(100),reasoningEffort:z9.enum(["low","medium","high","xhigh"]).optional(),reviewerLabel:z9.string().max(100),inference:z9.literal("REMOTE_OPENAI"),evidence:z9.enum(["METADATA_ONLY","IMAGE_PIXELS","VIDEO_FRAMES"])})}).refine(v=>{const image=v.plan.snapshot.image,receipt=v.imageReceipt;if(receipt&&(!image||receipt.draftId!==v.plan.id||canonicalLocalJson(receipt.media)!==canonicalLocalJson(v.plan.snapshot.media)||canonicalLocalJson({contentType:receipt.contentType,byteSize:receipt.byteSize,width:receipt.width,height:receipt.height})!==canonicalLocalJson(image)))return false;if(v.phase==="RESULT_PENDING"!==!!v.answer)return false;const derived=v.plan.snapshot.evidence,receipt2=v.evidenceReceipt;if(v.provenance.adapter!==(derived?"CODEX_MEDIA_V2":"CODEX_METADATA_V1"))return false;if(receipt2&&(!derived||receipt2.draftId!==v.plan.id||canonicalLocalJson(receipt2.media)!==canonicalLocalJson(v.plan.snapshot.media)))return false;if(v.answer&&!!(image||derived)!=="imageReadback"in v.answer)return false;const pixels=v.phase==="RESULT_PENDING"&&!!(image||derived);return v.provenance.evidence===(pixels?derived?.contentType==="video/mp4"?"VIDEO_FRAMES":"IMAGE_PIXELS":"METADATA_ONLY")&&(!pixels||(derived?!!receipt2:!!receipt))});function localAgentSnapshotFromContext(raw,includeImage=false){const c=ReviewIntelligenceContextResultSchema.parse(raw);if(c.reviewTarget.kind!=="IMAGE"||c.basis.target.kind!=="IMAGE"||c.ownerContext.semanticStatus!=="SUCCESS")throw Error("LOCAL_AGENT_CONTEXT_UNAVAILABLE");const t=c.reviewTarget.target,scope=c.basis.scope;if(!t.runtimeSucceeded||t.candidate.availability!=="AVAILABLE"||t.candidate.freshness!=="CURRENT_BASIS"||!t.productionRunnable||t.freshness!=="CURRENT_BASIS"||t.generationId!==c.basis.target.generationId||t.tenantId!==scope.tenantId||t.projectId!==scope.projectId||t.productionId!==scope.productionId||c.ownerContext.basis.tenantId!==scope.tenantId||c.ownerContext.basis.projectId!==scope.projectId||c.ownerContext.basis.productionId!==scope.productionId)throw Error("LOCAL_AGENT_CONTEXT_UNAVAILABLE");return LocalAgentSnapshotSchema.parse({basis:c.basis,productionRevision:c.ownerContext.basis.productionRevision,reviewVersion:t.reviewVersion,executionClass:t.executionClass,media:{artifactId:t.candidate.artifactId,representationId:t.candidate.representationId,checksumSha256:t.candidate.checksumSha256},requirements:t.requirements,...includeImage?{image:{contentType:t.candidate.contentType,byteSize:t.candidate.byteSize,width:t.candidate.width,height:t.candidate.height}}:{}})}function localAgentNativeProposal(raw){const v=LocalAgentReviewViewSchema.parse(raw);if(v.plan.snapshot.basis.target.kind!=="IMAGE"||v.plan.snapshot.evidence)throw Error("LOCAL_AGENT_MEDIA_PROPOSAL_REQUIRED");if(v.phase!=="RESULT_PENDING"||!v.answer)throw Error("LOCAL_AGENT_RESULT_UNAVAILABLE");const keys=new Set(v.answer.observations.map(o=>o.key));if(keys.size!==v.answer.observations.length||keys.size!==v.plan.snapshot.requirements.length||v.plan.snapshot.requirements.some(r=>!keys.has(r.key)))throw Error("LOCAL_AGENT_RESULT_UNAVAILABLE");const p=v.provenance;const pixels=p.evidence==="IMAGE_PIXELS";return ValidateReviewIntelligenceSchema.parse({basis:v.plan.snapshot.basis,proposal:{origin:{kind:"EXTERNAL_AGENT_HOST",label:p.reviewerLabel},summary:`${pixels?"IMAGE_PIXELS":"METADATA_ONLY; no visual inspection"}. Codex ${p.version}; model ${p.model}; effort ${p.reasoningEffort??"DEFAULT"}; binary ${p.binaryDigest}; draft ${v.plan.id}; plan ${v.plan.fingerprint}. ${v.answer.summary}`,evidence:pixels?[{id:"original_image",label:"Verified ORIGINAL PNG attachment",producer:"EXTERNAL_AGENT_HOST",kind:"IMAGE_PIXELS",media:v.plan.snapshot.media}]:[],review:{kind:"IMAGE",observations:v.answer.observations.map(o=>({...o,status:pixels&&"status"in o?o.status:"NOT_OBSERVABLE",confidence:pixels&&"confidence"in o?o.confidence:"UNCERTAIN",evidenceIds:pixels?["original_image"]:[]}))}}})}var LocalExecutionListInputSchema=LocalProjectScopeSchema.extend({after:z10.string().length(64).regex(/^[0-9a-f]{64}$/).nullable().default(null),limit:z10.int().min(1).max(16).default(8),includeCompleted:z10.boolean().optional(),includeProgress:z10.boolean().optional()});var LocalExecutionInspectInputSchema=LocalWorkScopeSchema.extend({includeProgress:z10.boolean().optional()});var LocalIpcCallSchema=z10.discriminatedUnion("operation",[z10.strictObject({operation:z10.literal("library.capability")}),z10.strictObject({operation:z10.literal("library.call"),input:LocalLibraryCallSchema}),z10.strictObject({operation:z10.literal("agent.discover"),binary:z10.string().min(1).max(4096).optional()}),z10.strictObject({operation:z10.literal("offline.workspace"),input:LocalOfflineCallSchema}),z10.strictObject({operation:z10.literal("workspace.inspect")}),z10.strictObject({operation:z10.literal("workspace.configure"),policy:LocalResourcePolicySchema,expectedRevision:z10.int().nonnegative()}),z10.strictObject({operation:z10.literal("workspace.activity"),idleSeconds:z10.int().min(0).max(86400),observedAt:z10.iso.datetime()}),z10.strictObject({operation:z10.literal("storage.clean")}),z10.strictObject({operation:z10.literal("diagnostics.read")}),z10.strictObject({operation:z10.literal("agent.grant"),grant:LocalAgentGrantSchema,approval:z10.string().regex(/^[a-f0-9]{64}$/)}),z10.strictObject({operation:z10.literal("agent.probe")}),z10.strictObject({operation:z10.literal("agent.revoke"),approval:z10.string().regex(/^[a-f0-9]{64}$/)}),z10.strictObject({operation:z10.literal("agent.prepare"),snapshot:LocalAgentSnapshotSchema}),z10.strictObject({operation:z10.literal("agent.start"),id:z10.uuid(),expectedRevision:LocalRevisionSchema,approval:z10.string().regex(/^[a-f0-9]{64}$/)}),z10.strictObject({operation:z10.literal("agent.inspect"),id:z10.uuid()}),z10.strictObject({operation:z10.literal("runtime.status"),includeDevice:z10.literal(true).optional()}),z10.strictObject({operation:z10.literal("runtime.doctor")}),z10.strictObject({operation:z10.literal("runtime.inventory")}),z10.strictObject({operation:z10.literal("session.issue"),tenantId:z10.uuid(),deviceId:z10.uuid(),expiresAt:z10.iso.datetime({offset:true})}),z10.strictObject({operation:z10.literal("runtime.stop"),expectedRuntimeRevision:LocalRevisionSchema}),z10.strictObject({operation:z10.literal("execution.inspect"),input:LocalExecutionInspectInputSchema}),z10.strictObject({operation:z10.literal("execution.list"),input:LocalExecutionListInputSchema}),z10.strictObject({operation:z10.literal("update.check")}),z10.strictObject({operation:z10.literal("update.prepare"),targetVersion:LocalPackageVersionSchema,expectedRuntimeRevision:LocalRevisionSchema}),z10.strictObject({operation:z10.literal("update.apply"),planId:LocalIdSchema,targetVersion:LocalPackageVersionSchema,expectedRuntimeRevision:LocalRevisionSchema})]);var LocalNextActionSchema=z10.strictObject({call:LocalIpcCallSchema,availability:z10.enum(["AVAILABLE","BLOCKED"]),reason:z10.enum(["READY","INSTALL_REQUIRED","AUTHORIZATION_REQUIRED","VERSION_INCOMPATIBLE","UPDATE_AVAILABLE","RECOVERY_REQUIRED"])});var LocalIpcRequestSchema=z10.strictObject({protocol:z10.literal("NVS_LOCAL_IPC_V1"),requestId:LocalIdSchema,call:LocalIpcCallSchema});var LocalVersionReportSchema=z10.strictObject({component:z10.enum(["CLI","SDK","MCP","RUNTIME","MEDIA_TOOLS"]),installedVersion:LocalPackageVersionSchema.nullable(),runningVersion:LocalPackageVersionSchema.nullable(),availableVersion:LocalPackageVersionSchema.nullable(),executablePath:z10.string().min(1).max(4096).nullable(),installOwner:z10.enum(["NPM_GLOBAL","PROJECT","NPX","MANAGED","TARBALL","UNKNOWN"])});var LocalRuntimeStatusSchema=z10.strictObject({protocol:z10.literal("NVS_LOCAL_IPC_V1"),runtimeRevision:LocalRevisionSchema,state:z10.enum(["IDLE","EXECUTING","DRAINING","RECOVERY_REQUIRED"]),journalSchemaVersion:z10.literal(1),workProtocols:z10.array(z10.enum(["NVS_LOCAL_WORK_V1","NVS_LOCAL_WORK_V2"])).min(1).max(2),versions:z10.array(LocalVersionReportSchema).max(8),deviceAuthority:z10.strictObject({tenantId:z10.uuid(),deviceId:z10.uuid(),origin:z10.url()}).optional(),capabilityMismatch:CapabilityVersionMismatchSchema.optional(),deviceCapabilities:z10.strictObject({deviceRevision:LocalRevisionSchema,tenantMediaValidation:z10.boolean(),tenantMediaProcessing:z10.boolean(),processorCapabilities:z10.array(TenantProcessorKindSchema).max(TenantProcessorKindSchema.options.length)}).optional(),nextActions:z10.array(LocalNextActionSchema).max(8)});var LocalDoctorReportSchema=z10.strictObject({mode:z10.enum(["MANAGED","INSTALLED"]),availability:z10.enum(["AVAILABLE","UNAVAILABLE"]),reason:z10.enum(["QUALIFIED_PROCESS_TOOLS","MANAGED_TOOLS_MISSING","TOOL_QUALIFICATION_FAILED"]),nativeExecutionReady:z10.boolean(),executionProfiles:z10.array(z10.enum(["ROUGH_CUT_PREVIEW_V1","STUDIO_MEDIA_V2","AUDIO_MEDIA_V1"])).max(3).optional(),tools:z10.array(z10.strictObject({name:z10.enum(["FFMPEG","FFPROBE"]),path:z10.string().min(1).max(4096),version:z10.string().min(1).max(200),digest:z10.string().regex(/^[0-9a-f]{64}$/)})).max(2)});var LocalExecutionInspectionSchema=z10.strictObject({binding:LocalLeaseBindingSchema,revision:LocalRevisionSchema,phase:z10.enum(["STAGED","RUNNING","RECOVERY_REQUIRED","OUTPUT_PENDING","RECEIPT_RECORDED","FENCED"]),checkpoint:z10.enum(["ADOPTED","SOURCES_READY","PROCESS_STARTED","OUTPUT_STAGED"]),progress:LocalExecutionProgressSchema.optional()});var LocalExecutionPageSchema=z10.strictObject({items:z10.array(LocalExecutionInspectionSchema).max(16),nextCursor:z10.string().length(64).regex(/^[0-9a-f]{64}$/).nullable()});var LocalIpcErrorCodeSchema=z10.enum(["FORBIDDEN","INVALID_INPUT","FRAME_LIMIT","BUSY","AUTHORIZATION_REQUIRED","REVISION_CONFLICT","CAPABILITY_UNAVAILABLE","INTERNAL_OPERATIONAL_FAILURE","AGENT_APPROVAL_REQUIRED","AGENT_RUNTIME_UNAVAILABLE","AGENT_LOGIN_REQUIRED","AGENT_VERSION_UNQUALIFIED","AGENT_GRANT_REQUIRED","AGENT_OUTCOME_UNKNOWN","AGENT_IMAGE_REQUIRED","AGENT_IMAGE_INVALID","AGENT_IMAGE_BUDGET_EXCEEDED","AGENT_IMAGE_AUTHORIZATION_REQUIRED","CACHE_QUOTA_EXCEEDED","LIBRARY_NOT_FOUND","LIBRARY_CONFLICT","LIBRARY_BYTES_INVALID","LIBRARY_ACCESS_DENIED","LIBRARY_SYNC_REQUIRED","LIBRARY_SYNC_UNAVAILABLE","LIBRARY_QUOTA_EXCEEDED"]);var LocalIpcResponseSchema=z10.discriminatedUnion("semanticStatus",[z10.strictObject({protocol:z10.literal("NVS_LOCAL_IPC_V1"),requestId:LocalIdSchema,semanticStatus:z10.literal("SUCCESS"),data:z10.union([LocalLibraryCapabilitySchema,LocalLibraryUsageSchema,LocalLibraryItemSchema,LocalLibraryPageSchema,LocalLibraryProjectionSchema,LocalLibraryProjectionPageSchema,LocalLibraryReadReplySchema,LocalWorkspaceInspectionSchema,LocalDiagnosticsSchema,LocalOfflinePageSchema,LocalRuntimeStatusSchema,LocalDoctorReportSchema,LocalExecutionInspectionSchema.nullable(),z10.strictObject({state:z10.literal("DRAINING"),inventory:LocalManagementInventorySchema.optional(),backupPath:z10.string().min(1).max(4096).optional()}),LocalSessionConnectorSchema,LocalManagementInventorySchema,LocalExecutionPageSchema,LocalAgentProbeSchema,LocalAgentDiscoverySchema,LocalAgentReviewViewSchema])}),z10.strictObject({protocol:z10.literal("NVS_LOCAL_IPC_V1"),requestId:LocalIdSchema.nullable(),semanticStatus:z10.enum(["BLOCKED","INVALID_INPUT"]),error:z10.strictObject({code:LocalIpcErrorCodeSchema})})]);var LocalMcpToolNameSchema=z11.enum(["local_navigate","local_capability_describe","local_runtime_status","local_execution_list","local_execution_inspect","local_update_check","local_library_list","local_library_get"]);var LocalMcpActionSchema=z11.strictObject({tool:LocalMcpToolNameSchema,arguments:z11.record(z11.string(),z11.unknown()),availability:z11.enum(["AVAILABLE","BLOCKED"]).optional(),reason:z11.string().max(100).optional()});var LocalMcpNavigationSchema=z11.strictObject({location:z11.literal("LOCAL"),state:z11.enum(["UNAVAILABLE","IDLE","EXECUTING","DRAINING","RECOVERY_REQUIRED"]),deviceAuthority:LocalRuntimeStatusSchema.shape.deviceAuthority,groups:z11.array(z11.strictObject({id:z11.string().max(40),label:z11.string().max(100),tools:z11.array(LocalMcpToolNameSchema).max(6)})).max(4),nextActions:z11.array(z11.union([LocalMcpActionSchema,LocalClientNextActionSchema])).max(16)});var LocalMcpExecutionPageSchema=LocalExecutionPageSchema.extend({nextActions:z11.array(LocalMcpActionSchema).max(16)});var LocalMcpInspectionSchema=z11.strictObject({location:z11.literal("LOCAL"),execution:LocalExecutionInspectionSchema.nullable(),nextActions:z11.array(LocalMcpActionSchema).max(4)});var LocalMcpUpdateSchema=z11.strictObject({location:z11.literal("LOCAL"),running:z11.array(LocalVersionReportSchema).max(8),available:z11.array(LocalRuntimeDescriptorSchema).max(32),nextActions:z11.array(LocalClientNextActionSchema).max(4)});var LocalMcpDescriptionSchema=z11.strictObject({location:z11.literal("LOCAL"),tool:LocalMcpToolNameSchema,schema:z11.object({name:LocalMcpToolNameSchema,description:z11.string(),inputSchema:z11.record(z11.string(),z11.unknown())}).passthrough()});var LocalMcpFailureSchema=z11.strictObject({semanticStatus:z11.enum(["BLOCKED","INVALID_INPUT"]),error:z11.strictObject({code:z11.enum(["AUTHORIZATION_REQUIRED","FORBIDDEN","LOCAL_RUNTIME_UNAVAILABLE","RELEASE_UNAVAILABLE","VERSION_INCOMPATIBLE","INVALID_INPUT","LOCAL_CAPABILITY_UNAVAILABLE"]),outcome:z11.literal("NO_WRITE")}),nextActions:z11.array(LocalClientNextActionSchema).max(4)});var LocalMcpOutputSchemas={local_library_list:LocalLibraryProjectionPageSchema.extend({location:z11.literal("LOCAL")}),local_library_get:z11.strictObject({location:z11.literal("LOCAL"),item:LocalLibraryProjectionSchema.nullable()}),local_navigate:LocalMcpNavigationSchema,local_capability_describe:LocalMcpDescriptionSchema,local_runtime_status:LocalRuntimeStatusSchema.omit({nextActions:true}).extend({nextActions:z11.array(LocalMcpActionSchema).max(8)}),local_execution_list:LocalMcpExecutionPageSchema,local_execution_inspect:LocalMcpInspectionSchema,local_update_check:LocalMcpUpdateSchema};import{z as z12}from"zod";var uuid=z12.uuid().transform(value=>value.toLowerCase());var AgentComponentScopeSchema=DeviceEnrollmentScopeSchema.extend({tenantId:uuid,principalId:uuid,grantId:uuid});var AgentComponentStatusSchema=ComponentStatusSchema.extend({component:z12.literal("HOST_RUNTIME"),source:z12.literal("OWNED_INSTALLATION_IPC"),componentHome:z12.string().min(1).max(4096),initialized:z12.boolean(),installationRevision:z12.int().nonnegative(),installedVersion:z12.string().min(1).max(120).nullable(),runningVersion:z12.string().min(1).max(120).nullable(),loginService:z12.enum(["NONE","REGISTERED","STALE","INCOMPLETE","UNKNOWN"]),lastRequestId:z12.uuid().nullable(),deviceId:z12.uuid().nullable(),capabilityMismatch:CapabilityVersionMismatchSchema.optional()});import{z as z14}from"zod";function localAgentMediaSnapshot(raw){const c=ReviewIntelligenceContextResultSchema.parse(raw),r=c.reviewTarget,t=r.target,scope=c.basis.scope;if(c.ownerContext.semanticStatus!=="SUCCESS"||!t.productionRunnable||t.freshness!=="CURRENT_BASIS"||t.tenantId!==scope.tenantId||t.projectId!==scope.projectId||t.productionId!==scope.productionId||c.ownerContext.basis.tenantId!==scope.tenantId||c.ownerContext.basis.projectId!==scope.projectId||c.ownerContext.basis.productionId!==scope.productionId||r.kind!==c.basis.target.kind)throw Error("LOCAL_AGENT_CONTEXT_UNAVAILABLE");let media,descriptor;if(r.kind==="ROUGH_CUT"){if(!r.target.inspectable||c.basis.target.kind!=="ROUGH_CUT"||r.target.renderId!==c.basis.target.renderId)throw Error("LOCAL_AGENT_CONTEXT_UNAVAILABLE");media=r.target.basis;descriptor={...r.target.technical,contentType:"video/mp4"}}else if(r.kind==="PROGRAMMATIC"){if(!r.target.runtimeSucceeded||r.target.media.availability!=="AVAILABLE"||c.basis.target.kind!=="PROGRAMMATIC"||r.target.renderId!==c.basis.target.renderId)throw Error("LOCAL_AGENT_CONTEXT_UNAVAILABLE");media=r.target.media;descriptor=r.target.media}else{if(!r.target.runtimeSucceeded||r.target.candidate.availability!=="AVAILABLE"||r.target.candidate.freshness!=="CURRENT_BASIS"||!("generationId"in c.basis.target)||r.target.generationId!==c.basis.target.generationId)throw Error("LOCAL_AGENT_CONTEXT_UNAVAILABLE");media=r.target.candidate;descriptor=r.target.candidate}const video=descriptor.contentType==="video/mp4";return LocalAgentSnapshotSchema.parse({basis:c.basis,productionRevision:c.ownerContext.basis.productionRevision,reviewVersion:t.reviewVersion,executionClass:t.executionClass,media:{artifactId:media.artifactId,representationId:media.representationId,checksumSha256:media.checksumSha256},requirements:t.requirements,evidence:{profile:"NVS_AGENT_DERIVED_EVIDENCE_V1",contentType:descriptor.contentType,byteSize:descriptor.byteSize,width:descriptor.width,height:descriptor.height,...video&&"durationMs"in descriptor?{durationMs:descriptor.durationMs,frameRate:descriptor.frameRate,hasAudio:descriptor.hasAudio}:{}}})}function localAgentMediaProposal(raw){const v=LocalAgentReviewViewSchema.parse(raw),s=v.plan.snapshot;if(!s.evidence)return localAgentNativeProposal(v);if(v.phase!=="RESULT_PENDING"||!v.answer||!v.evidenceReceipt||s.basis.target.kind==="ROUGH_CUT")throw Error("LOCAL_AGENT_FULL_TEMPORAL_INSPECTION_REQUIRED");const video=s.evidence.contentType==="video/mp4",p=v.provenance,id=video?"sampled_frames":"normalized_image";const observations=v.answer.observations.map(o=>{const requirement=s.requirements.find(r=>r.key===o.key);if(!requirement)throw Error("LOCAL_AGENT_RESULT_UNAVAILABLE");const sound="family"in requirement&&requirement.family==="SOUND"||/^(audio|sound):/.test(requirement.key);return{...o,status:video||!("status"in o)?"NOT_OBSERVABLE":o.status,confidence:video||!("confidence"in o)?"UNCERTAIN":o.confidence,observed:video?sound?"This draft has no listening evidence.":"Sampled frames are advisory. This draft has no playback coverage.":o.observed,evidenceIds:video&&sound?[]:[id],..."interval"in requirement&&requirement.interval?{interval:requirement.interval}:{}}});return ValidateReviewIntelligenceSchema.parse({basis:s.basis,proposal:{origin:{kind:"EXTERNAL_AGENT_HOST",label:p.reviewerLabel},summary:`Advisory ${video?"sampled frame observations. Full playback, listening and transcription are unavailable":"normalized original image"}. ${p.inference} via ${p.adapter} using Codex ${p.version}, model ${p.model}, effort ${p.reasoningEffort??"DEFAULT"}, binary ${p.binaryDigest}. Source ${s.media.checksumSha256}, attachment ${v.evidenceReceipt.attachment.checksumSha256}, draft ${v.plan.id}, plan ${v.plan.fingerprint}. ${v.answer.summary}`,evidence:observations.some(o=>o.evidenceIds.length)?[{id,label:video?"Ordered verified source frame samples":"Verified normalized source image",producer:"EXTERNAL_AGENT_HOST",media:s.media,...video?{kind:"VIDEO_FRAMES",timestampsMs:v.evidenceReceipt.timestampsMs}:{kind:"IMAGE_PIXELS"}}]:[],review:{kind:s.basis.target.kind,observations}}})}import{z as z13}from"zod";var CpuSpeechPrepareInputSchema=z13.strictObject({profileId:z13.literal(kokoroCpuProfile.id).default(kokoroCpuProfile.id),voiceIds:z13.array(CpuSpeechInputSchema.shape.voiceId).min(1).max(8).refine(v=>new Set(v).size===v.length).default([0,45])});var CpuSpeechPreparedSchema=z13.strictObject({semanticStatus:z13.literal("PREPARED"),selection:CpuSpeechInstallationSchema,capability:CpuSpeechCapabilitySchema,reused:z13.strictObject({engine:z13.boolean(),model:z13.boolean()})});function localBudget(timeoutMs,parent,ceiling=6e4){if(!Number.isInteger(timeoutMs)||timeoutMs<1||timeoutMs>ceiling)throw Error("LOCAL_DEADLINE_INVALID");const controller=new AbortController,timer=setTimeout(()=>controller.abort(),timeoutMs);return{signal:parent?AbortSignal.any([parent,controller.signal]):controller.signal,close:()=>clearTimeout(timer)}}async function localAbortable(work,signal){if(signal.aborted)void work.catch(()=>{});signal.throwIfAborted();return new Promise((resolve,reject)=>{const abort=()=>reject(Error("LOCAL_DEADLINE"));signal.addEventListener("abort",abort,{once:true});work.then(v=>{signal.removeEventListener("abort",abort);resolve(v)},e=>{signal.removeEventListener("abort",abort);reject(e)});if(signal.aborted)abort()})}var NativeStudioLocalDeviceClient=class{constructor(options){this.options=options;const u=new URL(options.baseUrl);if(u.username||u.password||u.search||u.hash||u.pathname!=="/"||u.protocol!=="https:"&&!(u.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(u.hostname)))throw new NativeStudioSdkError("INVALID_INPUT","INVALID_INPUT","NO_WRITE");this.origin=u.origin}options;origin;async command(route,raw,input,output,signal,readOnly=false,validate){let started=false;const budget=localBudget(15e3,signal);try{const i=input.parse(raw);if((i.tenantId??i.input?.tenantId)!==this.options.tenantId)throw Error();budget.signal.throwIfAborted();const authorization=await localAbortable(Promise.resolve().then(()=>this.options.authorization()),budget.signal);if(authorization!==authorization.trim()||!/^Bearer [A-Za-z0-9._~-]{1,8192}$/.test(authorization))throw Error();const body=JSON.stringify(i);if(Buffer.byteLength(body)>65536)throw Error();budget.signal.throwIfAborted();started=true;const r=await fetch(this.origin+"/v1/local-execution/"+route,{method:"POST",headers:{authorization,"content-type":"application/json","x-native-tenant-id":this.options.tenantId},body,redirect:"error",signal:budget.signal});if(!r.ok){await r.body?.cancel();throw new NativeStudioSdkError(r.status===403||r.status===401?"FORBIDDEN":"LOCAL_COMMAND_REFUSED","BLOCKED",readOnly?"NO_WRITE":r.status>=500?"UNKNOWN":"REJECTED",r.status)}const parts=[];let size=0;for await(const b of r.body??[]){size+=b.length;if(size>262144)throw Error();parts.push(b)}const value=output.parse(JSON.parse(Buffer.concat(parts).toString()));validate?.(i,value);if(value&&typeof value==="object"){const result=value,request4=i;for(const key of["tenantId","projectId","deviceId"])if(key in result&&key in request4&&result[key]!==request4[key])throw Error()}return value}catch(e){if(e instanceof NativeStudioSdkError)throw e;throw new NativeStudioSdkError(started?readOnly?"LOCAL_QUERY_UNAVAILABLE":"LOCAL_COMMAND_UNKNOWN":"INVALID_INPUT",started?"BLOCKED":"INVALID_INPUT",started&&!readOnly?"UNKNOWN":"NO_WRITE")}finally{budget.close()}}enroll(input,signal){return this.command("devices/enroll",input,EnrollLocalDeviceSchema,LocalDeviceViewSchema,signal,false,(original,result)=>assertManagementReceipt("device.enroll",original,result))}async managementReceipt(input,signal){const parsedInput=LocalDeviceManagementCommandSchema.safeParse(input);if(!parsedInput.success)throw new NativeStudioSdkError("INVALID_INPUT","INVALID_INPUT","NO_WRITE");const parsed=parsedInput.data;const value=await this.command("management-receipt",input,LocalDeviceManagementCommandSchema,LocalManagementReceiptSchema,signal,true);return checkedManagementReceipt(parsed,value)}revokeDevice(input,signal){return this.command("devices/revoke",input,RevokeLocalDeviceSchema,z14.strictObject({semanticStatus:z14.literal("SUCCESS")}),signal)}startPreview(input,signal){return this.command("previews",input,StartLocalPreviewSchema,LocalPreviewAdmissionSchema,signal)}startFinal(input,signal){return this.command("final-renders",input,StartLocalFinalRenderSchema,LocalFinalRenderAdmissionSchema,signal)}};import{randomUUID,createHash}from"node:crypto";import{request}from"node:http";import{z as z15}from"zod";import{constants}from"node:fs";import{open,realpath}from"node:fs/promises";async function checkedLocalDirectory(path){await privateDirectory(path);return realpath(path)}async function readLocalCredential(path,maximum=32768){await privateAccess(path,"file");const file=await open(path,constants.O_RDONLY|constants.O_NOFOLLOW);try{const stat=await file.stat();if(!stat.isFile()||stat.nlink!==1||process.platform!=="win32"&&(stat.uid!==process.getuid?.()||stat.mode&63)||stat.size>maximum)throw Error("LOCAL_CREDENTIAL_INVALID");const bytes=Buffer.alloc(Math.min(maximum+1,stat.size+1));let used=0;while(used<bytes.length){const part=await file.read(bytes,used,bytes.length-used,null);if(!part.bytesRead)break;used+=part.bytesRead}if(used>stat.size)throw Error("LOCAL_CREDENTIAL_INVALID");if(used>maximum)throw Error("LOCAL_CREDENTIAL_INVALID");return bytes.subarray(0,used)}finally{await file.close()}}async function stageAgentImage(options,view,input,signal){const budget=localBudget(view.plan.snapshot.evidence?18e4:options.timeoutMs??1e4,signal,view.plan.snapshot.evidence?18e4:6e4);let dispatched=false;try{budget.signal.throwIfAborted();if(input.byteLength>134217728)throw Error();const bytes=Buffer.from(input),snapshot=view.plan.snapshot,id=z15.uuid().parse(view.plan.id),requestId=randomUUID();if(!snapshot.image&&!snapshot.evidence||bytes.length!==(snapshot.evidence??snapshot.image).byteSize||bytes.length>(snapshot.evidence?134217728:8388608)||createHash("sha256").update(bytes).digest("hex")!==snapshot.media.checksumSha256)throw Error();const root=await checkedLocalDirectory(options.stateDirectory),path=localSocketPath(root);await privateAccess(path,"pipe");const auth=await localAbortable(Promise.resolve().then(options.authorization),budget.signal);budget.signal.throwIfAborted();if(!/^Bearer [A-Za-z0-9_-]{43}$/.test(auth))throw Error();const reply=await new Promise((resolve,reject)=>{const req=request({socketPath:path,path:"/ipc/v1/agent-images/"+id,method:"PUT",signal:budget.signal,headers:{authorization:auth,"content-type":snapshot.evidence?"application/octet-stream":"image/png","content-length":bytes.length,"x-nvs-request-id":requestId}},res=>{let size=0;const chunks=[];res.on("error",reject);res.on("aborted",()=>reject(Error()));res.on("data",b=>{size+=b.length;if(size>262144)req.destroy(Error());else chunks.push(b)});res.on("end",()=>{try{resolve(JSON.parse(Buffer.concat(chunks).toString()))}catch{reject(Error())}})});req.on("error",reject);dispatched=true;req.end(bytes)});const response=LocalIpcResponseSchema.parse(reply);if(response.requestId!==requestId&&!(response.requestId===null&&response.semanticStatus!=="SUCCESS"&&["BUSY","FORBIDDEN"].includes(response.error.code)))throw Error();if(response.semanticStatus!=="SUCCESS")throw new NativeStudioSdkError(response.error.code,response.semanticStatus,response.error.code==="INTERNAL_OPERATIONAL_FAILURE"?"UNKNOWN":"REJECTED");const v=LocalAgentReviewViewSchema.parse(response.data),receipt=v.evidenceReceipt??v.imageReceipt;if(v.plan.id!==id||canonicalLocalJson(v.plan)!==canonicalLocalJson(view.plan)||v.revision<view.revision||v.phase!=="PREPARED"||!receipt||receipt.draftId!==id||canonicalLocalJson(receipt.media)!==canonicalLocalJson(snapshot.media)||!snapshot.evidence&&canonicalLocalJson({contentType:v.imageReceipt?.contentType,byteSize:v.imageReceipt?.byteSize,width:v.imageReceipt?.width,height:v.imageReceipt?.height})!==canonicalLocalJson(snapshot.image))throw Error();return v}catch(e){if(e instanceof NativeStudioSdkError)throw e;throw new NativeStudioSdkError("LOCAL_AGENT_IMAGE_TRANSFER_FAILED","BLOCKED",dispatched?"UNKNOWN":"NO_WRITE")}finally{budget.close()}}var NativeStudioLocalWorkspaceClient=class{constructor(client){this.client=client}client;async offline(raw,signal){return LocalOfflinePageSchema.parse(await this.client.call({operation:"offline.workspace",input:LocalOfflineCallSchema.parse(raw)},signal))}async inspect(signal){return LocalWorkspaceInspectionSchema.parse(await this.client.call({operation:"workspace.inspect"},signal))}async configure(raw,expectedRevision,signal){const policy=LocalResourcePolicySchema.parse(raw);return LocalWorkspaceInspectionSchema.parse(await this.client.call({operation:"workspace.configure",policy,expectedRevision},signal))}async observeActivity(idleSeconds,observedAt,signal){return LocalWorkspaceInspectionSchema.parse(await this.client.call({operation:"workspace.activity",idleSeconds,observedAt},signal))}async clean(signal){return LocalWorkspaceInspectionSchema.parse(await this.client.call({operation:"storage.clean"},signal))}async diagnostics(signal){return LocalDiagnosticsSchema.parse(await this.client.call({operation:"diagnostics.read"},signal))}};import{Readable as Readable2}from"node:stream";import{createHash as createHash2}from"node:crypto";import{request as request2}from"node:http";async function libraryTransport(options,input,signal){const budget=localBudget(18e4,signal,18e4);let started=false;try{const root=await checkedLocalDirectory(options.stateDirectory),socketPath=localSocketPath(root);await privateAccess(socketPath,"pipe");const authorization=await localAbortable(Promise.resolve().then(()=>options.authorization()),budget.signal);if(!/^Bearer [A-Za-z0-9_-]{43}$/.test(authorization))throw Error();budget.signal.throwIfAborted();const response=await new Promise((resolve,reject)=>{const req=request2({socketPath,method:input.method,path:input.path,signal:budget.signal,headers:{authorization,...input.headers}},resolve);req.on("error",reject);started=true;if(input.body){input.body.once("error",error=>req.destroy(error));input.body.pipe(req)}else req.end()});return{response,close:()=>{budget.close();response.destroy();input.body?.destroy()}}}catch(error){budget.close();input.body?.destroy();if(error instanceof NativeStudioSdkError)throw error;throw new NativeStudioSdkError("LOCAL_RUNTIME_UNAVAILABLE","BLOCKED",started&&input.method==="PUT"?"UNKNOWN":"NO_WRITE")}}import{Readable}from"node:stream";var libraryRange=/^bytes=(?:[0-9]+-[0-9]*|-[0-9]+)$/;function expectedRange(range,total){if(!range)return{length:total,header:void 0};const match=/^bytes=(\d*)-(\d*)$/.exec(range);if(!match||!total)throw new NativeStudioSdkError("LIBRARY_RANGE_INVALID","INVALID_INPUT","NO_WRITE",416);const start=match[1]?Number(match[1]):Math.max(0,total-Number(match[2]));const end=match[1]&&match[2]?Math.min(total-1,Number(match[2])):total-1;if(!Number.isSafeInteger(start)||!Number.isSafeInteger(end)||start<0||start>=total||end<start)throw new NativeStudioSdkError("LIBRARY_RANGE_INVALID","INVALID_INPUT","NO_WRITE",416);return{length:end-start+1,header:`bytes ${start}-${end}/${total}`}}async function readLibraryMedia(options,raw,input={},signal){const value=LocalLibraryGetSchema.parse(raw),method=input.method??"GET";if(method!=="GET"&&method!=="HEAD")throw new NativeStudioSdkError("INVALID_INPUT","INVALID_INPUT","NO_WRITE");if(input.range!==void 0&&(input.range.length>100||!libraryRange.test(input.range)))throw new NativeStudioSdkError("LIBRARY_RANGE_INVALID","INVALID_INPUT","NO_WRITE",416);const expected=expectedRange(input.range,value.reference.byteSize);const header=Buffer.from(JSON.stringify(value)).toString("base64url");if(header.length>3072)throw new NativeStudioSdkError("INVALID_INPUT","INVALID_INPUT","NO_WRITE");const transfer=await libraryTransport(options,{method,path:"/ipc/v1/library/read",headers:{"x-nvs-library-read":header,...input.range?{range:input.range}:{}}},signal);const{response}=transfer;try{if(response.statusCode===416)throw new NativeStudioSdkError("LIBRARY_RANGE_INVALID","INVALID_INPUT","NO_WRITE",416);const status=response.statusCode,contentLength=Number(response.headers["content-length"]);if(![200,206].includes(status??0)||!Number.isSafeInteger(contentLength)||contentLength<0||contentLength>value.reference.byteSize||response.headers["content-type"]!==value.reference.contentType)throw Error();const contentRange=response.headers["content-range"];if(status===206){if(!input.range||contentRange!==expected.header||contentLength!==expected.length)throw Error()}else if(input.range||contentRange||contentLength!==value.reference.byteSize)throw Error();const stream=Readable.from((async function*(){let size=0;try{for await(const bytes of response){size+=bytes.length;if(size>contentLength||method==="HEAD")throw Error();yield bytes}if(method!=="HEAD"&&size!==contentLength)throw Error()}finally{transfer.close()}})());stream.once("close",transfer.close);return{stream,contentType:value.reference.contentType,byteSize:value.reference.byteSize,contentLength,httpStatus:status,...contentRange?{contentRange:String(contentRange)}:{}}}catch(error){transfer.close();if(error instanceof NativeStudioSdkError)throw error;throw new NativeStudioSdkError("LOCAL_LIBRARY_MEDIA_INVALID","BLOCKED","NO_WRITE")}}var NativeStudioLocalLibraryClient=class{constructor(client){this.client=client}client;async capability(signal){return LocalLibraryCapabilitySchema.parse(await this.client.call({operation:"library.capability"},signal))}async call(raw,signal){const input=LocalLibraryCallSchema.parse(raw),data=await this.client.call({operation:"library.call",input},signal);const schema=input.action==="list"?LocalLibraryPageSchema:input.action==="scoped-list"?LocalLibraryProjectionPageSchema:input.action==="scoped-get"?LocalLibraryProjectionSchema.nullable():input.action==="usage"?LocalLibraryUsageSchema:input.action==="read"?LocalLibraryReadReplySchema:["get","import-receipt"].includes(input.action)?LocalLibraryItemSchema.nullable():LocalLibraryItemSchema;const result=schema.parse(data);if(result&&"items"in result&&"limit"in input&&result.items.length>input.limit)throw new NativeStudioSdkError("LOCAL_SCOPE_INVALID","BLOCKED","NO_WRITE");if((input.action==="list"||input.action==="scoped-list")&&result&&"items"in result){for(const item of result.items){const label=input.action==="list"&&"title"in item?item.title:"metadata"in item?item.metadata?.label:void 0;if(input.mediaCategory&&mediaCategoryOf(item.reference.contentType)!==input.mediaCategory||input.search&&!label?.toLowerCase().includes(input.search.toLowerCase()))throw new NativeStudioSdkError("LOCAL_SCOPE_INVALID","BLOCKED","NO_WRITE")}}if(input.action==="read"){const value=LocalLibraryReadReplySchema.parse(result),bytes=Buffer.from(value.contentBase64,"base64");const length=Math.min(input.length,Math.max(0,input.reference.byteSize-input.offset));if(value.offset!==input.offset||bytes.toString("base64")!==value.contentBase64||bytes.length!==length||value.complete!==input.offset+length>=input.reference.byteSize)throw new NativeStudioSdkError("LOCAL_LIBRARY_MEDIA_INVALID","BLOCKED","NO_WRITE")}const refs=result&&typeof result==="object"&&"items"in result?result.items.map(item=>item.reference):result&&typeof result==="object"&&"reference"in result?[result.reference]:[];for(const ref of refs){if("reference"in input&&canonicalLocalJson(ref)!==canonicalLocalJson(input.reference)||"tenantId"in input&&(ref.tenantId!==input.tenantId||input.projectId!==void 0&&ref.projectId!==input.projectId||ref.deviceId!==input.deviceId))throw new NativeStudioSdkError("LOCAL_SCOPE_INVALID","BLOCKED","NO_WRITE")}if("ownerKey"in input&&input.ownerKey&&result&&typeof result==="object"){const owned="items"in result?result.items:"ownerKey"in result?[result]:[];if(owned.some(item=>"ownerKey"in item&&item.ownerKey!==input.ownerKey))throw new NativeStudioSdkError("LOCAL_SCOPE_INVALID","BLOCKED","NO_WRITE")}return result}async import(raw,bytes,signal){const input=LocalLibraryImportSchema.parse(raw),header=Buffer.from(JSON.stringify(input)).toString("base64url");if(header.length>3072)throw new NativeStudioSdkError("INVALID_INPUT","INVALID_INPUT","NO_WRITE");const body=Readable2.from((async function*(){let count=0;const hash=createHash2("sha256");for await(const chunk of bytes){const part=Buffer.from(chunk);count+=part.length;if(count>input.reference.byteSize)throw Error("LOCAL_FILE_CHANGED");hash.update(part);yield part}if(count!==input.reference.byteSize||hash.digest("hex")!==input.reference.checksumSha256)throw Error("LOCAL_FILE_CHANGED")})());const transfer=await libraryTransport(this.client.options,{method:"PUT",path:"/ipc/v1/library/import",body,headers:{"x-nvs-request-id":input.requestId,"x-nvs-library-import":header,"content-type":"application/octet-stream","content-length":input.reference.byteSize}},signal);try{let size=0;const parts=[];for await(const part of transfer.response){size+=part.length;if(size>262144)throw Error();parts.push(part)}const reply=LocalIpcResponseSchema.parse(JSON.parse(Buffer.concat(parts).toString()));if(reply.semanticStatus!=="SUCCESS")throw new NativeStudioSdkError(reply.error.code,reply.semanticStatus,reply.error.code==="INTERNAL_OPERATIONAL_FAILURE"?"UNKNOWN":"REJECTED");const item=LocalLibraryItemSchema.parse(reply.data);if(reply.requestId!==input.requestId||canonicalLocalJson(item.reference)!==canonicalLocalJson(input.reference)||item.ownerKey!==input.ownerKey||item.title!==input.title)throw Error();return item}catch(error){if(error instanceof NativeStudioSdkError)throw error;throw new NativeStudioSdkError("LOCAL_LIBRARY_IMPORT_UNKNOWN","BLOCKED","UNKNOWN")}finally{transfer.close()}}media(raw,input={},signal){return readLibraryMedia(this.client.options,raw,input,signal)}};import{randomUUID as randomUUID2}from"node:crypto";import{request as request3}from"node:http";var NativeStudioLocalRuntimeClient=class _NativeStudioLocalRuntimeClient{constructor(options){this.options=options}options;workspace=new NativeStudioLocalWorkspaceClient(this);library=new NativeStudioLocalLibraryClient(this);static async fromConnector(path){const initial=LocalSessionConnectorSchema.parse(JSON.parse((await readLocalCredential(path)).toString()));return new _NativeStudioLocalRuntimeClient({stateDirectory:initial.stateDirectory,device:{tenantId:initial.tenantId,deviceId:initial.deviceId},authorization:async()=>{const current=LocalSessionConnectorSchema.parse(JSON.parse((await readLocalCredential(path)).toString()));if(current.stateDirectory!==initial.stateDirectory||current.tenantId!==initial.tenantId||current.deviceId!==initial.deviceId||Date.parse(current.expiresAt)>Date.parse(initial.expiresAt)||Date.parse(current.expiresAt)<=Date.now())throw Error("LOCAL_AUTHORIZATION_REQUIRED");return"Bearer "+current.credential}})}async call(call,signal){let started=false;const budget=localBudget(this.options.timeoutMs??(["runtime.doctor","agent.probe","agent.grant","agent.start"].includes(call.operation)?6e4:3e4),signal);const readOnly=["runtime.status","runtime.doctor","runtime.inventory","execution.inspect","execution.list","update.check","agent.probe","agent.discover","agent.inspect","workspace.inspect","diagnostics.read","library.capability"].includes(call.operation)||call.operation==="library.call"&&["list","get","usage","read","import-receipt","scoped-list","scoped-get","sync"].includes(call.input.action);try{const input=LocalIpcRequestSchema.parse({protocol:"NVS_LOCAL_IPC_V1",requestId:randomUUID2(),call});const root=await checkedLocalDirectory(this.options.stateDirectory);const path=localSocketPath(root);await privateAccess(path,"pipe");budget.signal.throwIfAborted();const auth=await localAbortable(Promise.resolve().then(()=>this.options.authorization()),budget.signal);budget.signal.throwIfAborted();if(auth.length!==50||!/^Bearer [A-Za-z0-9_-]{43}$/.test(auth))throw Error();const body=JSON.stringify(input);const reply=await new Promise((resolve,reject)=>{const abort=budget.signal;const req=request3({socketPath:path,method:"POST",path:"/ipc/v1",signal:abort,headers:{authorization:auth,"content-type":"application/json","content-length":Buffer.byteLength(body)}},res=>{const chunks=[];let length=0;res.on("error",reject);res.on("aborted",()=>reject(Error()));res.on("data",b=>{length+=b.length;if(length>256*1024)req.destroy(Error());else chunks.push(b)});res.on("end",()=>{try{resolve(JSON.parse(Buffer.concat(chunks).toString()))}catch{reject(Error())}})});req.on("error",reject);started=true;req.end(body)});const value=LocalIpcResponseSchema.parse(reply);if(value.requestId!==input.requestId&&!(value.requestId===null&&value.semanticStatus!=="SUCCESS"&&["FORBIDDEN","BUSY","INVALID_INPUT"].includes(value.error.code)))throw Error();if(value.semanticStatus!=="SUCCESS")throw new NativeStudioSdkError(value.error.code,value.semanticStatus,readOnly?"NO_WRITE":value.error.code==="INTERNAL_OPERATIONAL_FAILURE"?"UNKNOWN":"REJECTED");if(value.requestId!==input.requestId)throw Error();return value.data}catch(error){if(error instanceof NativeStudioSdkError)throw error;throw new NativeStudioSdkError("LOCAL_RUNTIME_UNAVAILABLE","BLOCKED",started&&!readOnly?"UNKNOWN":"NO_WRITE")}finally{budget.close()}}response(schema,raw){const result=schema.safeParse(raw);if(!result.success)throw new NativeStudioSdkError("LOCAL_RESPONSE_INVALID","BLOCKED","NO_WRITE");return result.data}async status(signal,includeDevice=false){const value=this.response(LocalRuntimeStatusSchema,await this.call({operation:"runtime.status",...includeDevice||this.options.device?{includeDevice:true}:{}},signal));if(this.options.device&&(value.deviceAuthority?.tenantId!==this.options.device.tenantId||value.deviceAuthority.deviceId!==this.options.device.deviceId))throw new NativeStudioSdkError("LOCAL_SCOPE_INVALID","BLOCKED","NO_WRITE");return value}async doctor(signal){return this.response(LocalDoctorReportSchema,await this.call({operation:"runtime.doctor"},signal))}async inventory(signal){return this.response(LocalManagementInventorySchema,await this.call({operation:"runtime.inventory"},signal))}async grantAgent(raw,approval){return this.response(LocalAgentProbeSchema,await this.call({operation:"agent.grant",grant:LocalAgentGrantSchema.parse(raw),approval}))}async revokeAgent(approval){return this.response(LocalAgentProbeSchema,await this.call({operation:"agent.revoke",approval}))}async probeAgent(){return this.response(LocalAgentProbeSchema,await this.call({operation:"agent.probe"}))}async discoverAgent(binary){return this.response(LocalAgentDiscoverySchema,await this.call({operation:"agent.discover",...binary?{binary}:{}}))}async prepareAgentReview(snapshot){const input=LocalAgentSnapshotSchema.parse(snapshot);const v=this.response(LocalAgentReviewViewSchema,await this.call({operation:"agent.prepare",snapshot:input}));if(canonicalLocalJson(v.plan.snapshot)!==canonicalLocalJson(input))throw new NativeStudioSdkError("LOCAL_RESPONSE_INVALID","BLOCKED","UNKNOWN");return v}async startAgentReview(id,expectedRevision,approval){const v=this.response(LocalAgentReviewViewSchema,await this.call({operation:"agent.start",id,expectedRevision,approval}));if(v.plan.id!==id||v.plan.fingerprint!==approval)throw new NativeStudioSdkError("LOCAL_RESPONSE_INVALID","BLOCKED","UNKNOWN");return v}async stageAgentImage(id,bytes,signal){const budget=localBudget(18e4,signal,18e4);try{return await stageAgentImage(this.options,await this.inspectAgentReview(id,budget.signal),bytes,budget.signal)}finally{budget.close()}}async inspectAgentReview(id,signal){const v=this.response(LocalAgentReviewViewSchema,await this.call({operation:"agent.inspect",id},signal));if(v.plan.id!==id)throw new NativeStudioSdkError("LOCAL_RESPONSE_INVALID","BLOCKED","NO_WRITE");return v}async executions(input,signal){const i=LocalExecutionListInputSchema.parse(input);if(this.options.device&&this.options.device.tenantId!==i.tenantId)throw new NativeStudioSdkError("FORBIDDEN","BLOCKED","NO_WRITE");const page=this.response(LocalExecutionPageSchema,await this.call({operation:"execution.list",input:i},signal));if(page.items.some(e=>e.binding.tenantId!==i.tenantId||e.binding.projectId!==i.projectId))throw new NativeStudioSdkError("LOCAL_SCOPE_INVALID","BLOCKED","NO_WRITE");return page}async inspect(raw,signal){const input=LocalExecutionInspectInputSchema.parse(raw);if(this.options.device&&this.options.device.tenantId!==input.tenantId)throw new NativeStudioSdkError("FORBIDDEN","BLOCKED","NO_WRITE");const value=this.response(LocalExecutionInspectionSchema.nullable(),await this.call({operation:"execution.inspect",input},signal));if(value&&["tenantId","projectId","productionId","runtimeJobId"].some(k=>value.binding[k]!==input[k]))throw new NativeStudioSdkError("LOCAL_SCOPE_INVALID","BLOCKED","NO_WRITE");return value}};function newerVersion(candidate,current){const parse=v=>{const core=v.split("+")[0],i=core.indexOf("-");return{parts:(i<0?core:core.slice(0,i)).split(".").map(BigInt),pre:i<0?null:core.slice(i+1).split(".")}};const a=parse(candidate),b=parse(current);for(let i=0;i<3;i++){if(a.parts[i]!==b.parts[i])return a.parts[i]>b.parts[i]}if(!a.pre||!b.pre)return!a.pre&&!!b.pre;for(let i=0;i<Math.max(a.pre.length,b.pre.length);i++){const x=a.pre[i],y=b.pre[i];if(x===y)continue;if(x===void 0||y===void 0)return y===void 0;const xn=/^\d+$/.test(x),yn=/^\d+$/.test(y);if(xn&&yn)return BigInt(x)>BigInt(y);if(xn!==yn)return!xn;return x>y}return false}import{createPublicKey,verify}from"node:crypto";function endpoint(raw){const u=new URL(raw);if(u.username||u.password||u.search||u.hash||u.protocol!=="https:"&&!(u.protocol==="http:"&&["127.0.0.1","localhost","[::1]"].includes(u.hostname)))fail("RELEASE_ORIGIN_INVALID");return u}async function fetchBytes(raw,maximum,origin,signal=AbortSignal.timeout(3e4)){const u=endpoint(raw);if(u.origin!==origin)fail("RELEASE_ORIGIN_INVALID");let r;try{r=await fetch(u,{redirect:"error",signal,headers:{accept:"application/octet-stream","user-agent":"NativeStudioDependencyClient"}})}catch{fail(signal.aborted?"RELEASE_TIMEOUT":"RELEASE_UNAVAILABLE")}const length=r.headers.get("content-length");if(!r.ok||length!==null&&(!/^[0-9]+$/.test(length)||Number(length)>maximum)){void r.body?.cancel().catch(()=>{});fail(r.status===403?"RELEASE_ACCESS_DENIED":r.status===404?"RELEASE_NOT_PUBLISHED":r.ok?"RELEASE_LIMIT":"RELEASE_UNAVAILABLE")}const reader=r.body?.getReader(),parts=[];let size=0;try{if(reader)while(true){const part=await reader.read();if(part.done)break;size+=part.value.byteLength;if(size>maximum)fail("RELEASE_LIMIT");parts.push(part.value)}return Buffer.concat(parts)}catch(error){if(error instanceof Error&&"code"in error&&error.code==="RELEASE_LIMIT")throw error;fail(signal.aborted?"RELEASE_TIMEOUT":"RELEASE_UNAVAILABLE")}finally{void reader?.cancel().catch(()=>{});reader?.releaseLock()}}async function catalogue(trust,signal){if(!trust.catalogueUrl||!trust.publicKeyFile&&!trust.publicKey)fail("DEPENDENCY_CHANNEL_REQUIRED");const origin=endpoint(trust.catalogueUrl).origin;const bytes=await fetchBytes(trust.catalogueUrl,65536,origin,signal??AbortSignal.timeout(3e4));let signed;try{signed=LocalSignedCatalogueSchema.parse(JSON.parse(bytes.toString()))}catch{fail("RELEASE_METADATA_INVALID")}const key=createPublicKey(trust.publicKeyFile?(await read(trust.publicKeyFile,16384)).toString():trust.publicKey);if(key.asymmetricKeyType!=="ed25519"||!verify(null,Buffer.from(canonicalLocalJson(signed.catalogue)),key,Buffer.from(signed.signature,"base64url")))fail("RELEASE_SIGNATURE_INVALID");const now=Date.now();if(Date.parse(signed.catalogue.issuedAt)>now||Date.parse(signed.catalogue.expiresAt)<=now)fail("RELEASE_EXPIRED");for(const release of signed.catalogue.releases){for(const a of[release.package,...release.tools?Object.values(release.tools):[],...release.resources?Object.values(release.resources):[]])if(endpoint(a.url).origin!==origin)fail("RELEASE_ORIGIN_INVALID")}return{signed,fingerprint:sha256(canonicalLocalJson(signed.catalogue)),origin,trustFingerprint:sha256(canonicalLocalJson({catalogueUrl:endpoint(trust.catalogueUrl).href,publicKey:key.export({type:"spki",format:"der"}).toString("base64")}))}}function select(signed,version,rejected=[]){if(version==="latest"){const candidates=signed.catalogue.releases.filter(r2=>!rejected.includes(r2.descriptor.version)&&r2.descriptor.platform.os===process.platform&&r2.descriptor.platform.architecture===process.arch&&Number(process.versions.node.split(".")[0])===r2.descriptor.node.major&&Number(process.versions.node.split(".")[1])>=r2.descriptor.node.minMinor);const latest=candidates.reduce((a,b)=>!a||newerVersion(b.descriptor.version,a.descriptor.version)?b:a,void 0);if(!latest)fail("VERSION_INCOMPATIBLE");version=latest.descriptor.version}const r=signed.catalogue.releases.find(r2=>r2.descriptor.version===version&&r2.descriptor.platform.os===process.platform&&r2.descriptor.platform.architecture===process.arch);if(!r)fail("VERSION_INCOMPATIBLE");const[major,minor]=process.versions.node.split(".").map(Number);if(major!==r.descriptor.node.major||minor<r.descriptor.node.minMinor)fail("NODE_VERSION_INCOMPATIBLE");return r}async function asset(a,origin){const bytes=await fetchBytes(a.url,a.byteSize,origin,AbortSignal.timeout(12e4));if(bytes.length!==a.byteSize||sha512(bytes)!==a.sha512)fail("RELEASE_INTEGRITY_INVALID");return bytes}export{LocalOfflineCallSchema,LocalOfflinePageSchema,LocalAgentGrantSchema,LocalAgentDiscoverySchema,LocalCompositionBrowserSelectionSchema,LocalToolSelectionSchema,LocalRuntimeDescriptorSchema,RuntimeCaptionAssets,LocalRuntimeComponentSchema,LocalManagementInventorySchema,LocalReleaseSchema,LocalToolChoiceSchema,LocalUpdatePlanSchema,LocalResourcePolicySchema,LocalWorkspaceInspectionSchema,LocalDiagnosticsSchema,LocalAgentSnapshotSchema,LocalAgentProbeSchema,LocalAgentReviewViewSchema,localAgentSnapshotFromContext,LocalExecutionListInputSchema,LocalExecutionInspectInputSchema,LocalRuntimeStatusSchema,LocalDoctorReportSchema,LocalMcpFailureSchema,LocalMcpOutputSchemas,localAgentMediaSnapshot,localAgentMediaProposal,AgentComponentScopeSchema,AgentComponentStatusSchema,CpuSpeechPrepareInputSchema,CpuSpeechPreparedSchema,NativeStudioLocalDeviceClient,NativeStudioLocalRuntimeClient,newerVersion,endpoint,catalogue,select,asset};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{privateAccess,privateDirectory,write}from"./chunk-DLW42PJ6.js";import{secureEndpoint}from"./chunk-KOCUZ3AE.js";import{randomBytes}from"node:crypto";import{open,unlink,constants}from"node:fs/promises";import{dirname,resolve}from"node:path";var FileOAuthProvider=class _FileOAuthProvider{constructor(path,data){this.path=path;this.data=data}path;data;static async create(path,resource,redirect,scope){secureEndpoint(resource);secureEndpoint(redirect);if(!["nvs:read","nvs:read nvs:write"].includes(scope))throw Error();if(process.platform==="win32")await privateDirectory(dirname(resolve(path)));const data={version:1,resource,redirect,scope,state:randomBytes(24).toString("base64url")};await write(resolve(path),JSON.stringify(data),true);return new _FileOAuthProvider(path,data)}static async load(path){if(process.platform==="win32")await privateAccess(resolve(path),"file");const file=await open(path,constants.O_RDONLY|constants.O_NOFOLLOW|constants.O_NONBLOCK);let data;try{const stat=await file.stat();if(!stat.isFile()||stat.nlink!==1||process.platform!=="win32"&&(stat.uid!==process.getuid?.()||(stat.mode&63)!==0)||stat.size>65536)throw Error();const bytes=Buffer.alloc(65537);const{bytesRead}=await file.read(bytes,0,bytes.length,0);if(bytesRead>65536)throw Error();data=JSON.parse(bytes.subarray(0,bytesRead).toString("utf8"))}finally{await file.close()}if(![1,2].includes(data.version)||typeof data.state!=="string"||data.state.length<16)throw Error();if(data.pendingExchange!==void 0&&!["CODE","REFRESH"].includes(data.pendingExchange))throw Error();if(data.version===2!==(data.pendingExchange!==void 0))throw Error();secureEndpoint(data.resource);secureEndpoint(data.redirect);if(!["nvs:read","nvs:read nvs:write"].includes(data.scope))throw Error();return new _FileOAuthProvider(path,data)}async save(){if(process.platform==="win32")await privateDirectory(dirname(resolve(this.path)));await write(resolve(this.path),JSON.stringify(this.data))}get redirectUrl(){return this.data.redirect}get clientMetadata(){return{client_name:"NativeStudio CLI",redirect_uris:[this.data.redirect],token_endpoint_auth_method:"none",grant_types:["authorization_code","refresh_token"],response_types:["code"],scope:this.data.scope,application_type:"native"}}state(){return this.data.state}clientInformation(){return this.data.client}async saveClientInformation(value){this.data.client=value;await this.save()}tokens(){return this.data.token}async saveTokens(value){const metadataOnly=this.data.pendingExchange==="REFRESH"&&value.access_token===this.data.token?.access_token&&value.refresh_token===this.data.token?.refresh_token;this.data.token=value;if(!metadataOnly){this.data.expiresAt=Date.now()+(value.expires_in??600)*1e3;this.data.version=1;delete this.data.pendingExchange}await this.save()}async redirectToAuthorization(url){this.data.authorizationUrl=url.href;await this.save()}async saveCodeVerifier(value){this.data.verifier=value;await this.save()}codeVerifier(){if(!this.data.verifier)throw Error();return this.data.verifier}async saveDiscoveryState(value){this.data.discovery=value;await this.save()}discoveryState(){return this.data.discovery}};async function withProfileLock(path,action){if(process.platform==="win32")await privateDirectory(dirname(resolve(path)));const file=await open(path+".lock","wx",384);try{return await action()}finally{await file.close();await unlink(path+".lock")}}export{FileOAuthProvider,withProfileLock};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{tenantConnection}from"./chunk-27KI24GK.js";import{FileOAuthProvider,withProfileLock}from"./chunk-7I7ARCY7.js";import{remoteResponse,secureEndpoint}from"./chunk-KOCUZ3AE.js";import{NativeStudioSdkError}from"./chunk-TT7IA5HB.js";async function apiMetadata(url,signal){let response;try{response=await remoteResponse(url,{headers:{accept:"application/json"},signal:signal?AbortSignal.any([signal,AbortSignal.timeout(5e3)]):AbortSignal.timeout(5e3)});if(!response.ok)return void 0;const parts=[];let size=0;for await(const part of response.body??[]){size+=part.byteLength;if(size>16384)return void 0;parts.push(part)}const data=JSON.parse(Buffer.concat(parts).toString());return data&&typeof data==="object"&&!Array.isArray(data)?data:void 0}catch{signal?.throwIfAborted();return void 0}finally{await response?.body?.cancel().catch(()=>{})}}async function profileHttpOrigin(path,resource,signal){signal?.throwIfAborted();return withProfileLock(path,async()=>{const provider=await FileOAuthProvider.load(path);signal?.throwIfAborted();const deny=()=>{throw new NativeStudioSdkError("API_ORIGIN_UNTRUSTED","BLOCKED","NO_WRITE")};if(provider.data.resource!==resource)deny();if(provider.data.pendingExchange)throw new NativeStudioSdkError("OAUTH_OUTCOME_UNKNOWN","BLOCKED","UNKNOWN");tenantConnection(resource);const endpoint=secureEndpoint(resource);const metadataUrl=endpoint.origin+"/.well-known/oauth-protected-resource"+endpoint.pathname;const fresh=await apiMetadata(metadataUrl,signal);signal?.throwIfAborted();if(fresh&&fresh.resource!==resource)deny();const metadata=fresh??provider.data.discovery?.resourceMetadata;const configured=metadata?.nativestudio_api_origin;if(configured===void 0){if(fresh&&provider.data.discovery){const saved={...provider.data.discovery.resourceMetadata,resource};Reflect.deleteProperty(saved,"nativestudio_api_origin");provider.data.discovery.resourceMetadata=saved;provider.data.discovery.resourceMetadataUrl=metadataUrl;await provider.save()}return endpoint.origin}try{if(typeof configured!=="string")return deny();const sourceUrl=metadata===fresh?metadataUrl:provider.data.discovery?.resourceMetadataUrl;if(typeof sourceUrl!=="string"||secureEndpoint(sourceUrl).origin!==endpoint.origin||metadata?.resource!==resource||configured.length>2048)deny();const api=secureEndpoint(configured);if(api.pathname!=="/"||endpoint.protocol==="https:"&&api.protocol!=="https:")deny();if(metadata===fresh&&provider.data.discovery){provider.data.discovery.resourceMetadata={...provider.data.discovery.resourceMetadata,resource,nativestudio_api_origin:api.origin};provider.data.discovery.resourceMetadataUrl=metadataUrl;await provider.save()}return api.origin}catch{return deny()}})}export{profileHttpOrigin};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{DesktopDeviceScopeSchema,DesktopDeviceStateSchema}from"./chunk-IYDHDLTR.js";import{canonicalLocalJson}from"./chunk-APNZQZFB.js";import{directory,entries,fail,privateAccess,read,sha256,write}from"./chunk-DLW42PJ6.js";import{join}from"node:path";var recordRoot=(home,scope)=>join(home,"devices",sha256(canonicalLocalJson(scope)));var DesktopDeviceRecords=class _DesktopDeviceRecords{constructor(root,scope){this.root=root;this.scope=scope}root;scope;static async open(home,raw){const scope=DesktopDeviceScopeSchema.parse(raw);return new _DesktopDeviceRecords(await directory(recordRoot(home,scope)),scope)}static async inspect(home,raw){const scope=DesktopDeviceScopeSchema.parse(raw);const root=recordRoot(home,scope);try{await privateAccess(join(home,"devices"),"directory");await privateAccess(root,"directory")}catch(error){if(error.code==="ENOENT")return null;throw error}return new _DesktopDeviceRecords(root,scope).current()}async current(){const names=(await entries(this.root)).filter(n=>/^\d{12}\.json$/.test(n)).sort();let state={revision:0,scope:this.scope,enrollment:null,device:null,previews:[],connectorId:null,connection:null,pending:null};for(const[index,name]of names.entries()){const next=DesktopDeviceStateSchema.parse(JSON.parse((await read(join(this.root,name),262144,true)).toString()));if(next.revision!==index+1||canonicalLocalJson(next.scope)!==canonicalLocalJson(this.scope))fail("DEVICE_HISTORY_INVALID");state=next}return state}async save(before,fields){if((await this.current()).revision!==before.revision)fail("REVISION_CONFLICT");const next=DesktopDeviceStateSchema.parse({...before,...fields,revision:before.revision+1});try{await write(join(this.root,String(next.revision).padStart(12,"0")+".json"),canonicalLocalJson(next),true)}catch(e){if(e.code==="EEXIST")fail("REVISION_CONFLICT");throw e}return next}keyPath(){return join(this.root,"device-key.json")}connectorPath(id){return join(this.root,id+".connector.json")}};async function desktopDeviceConnector(home,scope){const records=await DesktopDeviceRecords.open(home,scope),state=await records.current();if(!state.connectorId)fail("LOCAL_AUTHORIZATION_REQUIRED");return records.connectorPath(state.connectorId)}export{DesktopDeviceRecords,desktopDeviceConnector};
|