@nativestudio/cli 0.3.0-rc.16 → 0.3.0-rc.19
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 +11 -11
- package/components/runtime.json +7 -7
- package/components/runtime.tgz +0 -0
- package/dist/_chunks/chunk-226SBV53.js +1 -0
- package/dist/_chunks/{chunk-TWC3NXFA.js → chunk-27KI24GK.js} +1 -1
- package/dist/_chunks/chunk-2GV47BUV.js +1 -0
- package/dist/_chunks/chunk-2MKMGMA4.js +1 -0
- package/dist/_chunks/{chunk-FX5UVDTH.js → chunk-3TOXIJ7K.js} +1 -1
- package/dist/_chunks/{chunk-RT77PT3A.js → chunk-4NCE337I.js} +1 -1
- package/dist/_chunks/{chunk-EML7OS3I.js → chunk-5G3AJAKI.js} +1 -1
- package/dist/_chunks/chunk-5TKBEFRX.js +1 -0
- package/dist/_chunks/chunk-67QDMD7M.js +1 -0
- package/dist/_chunks/{chunk-SKAVQ4UW.js → chunk-7I7ARCY7.js} +1 -1
- package/dist/_chunks/{chunk-UMCOLDHH.js → chunk-7P2NA6TH.js} +1 -1
- package/dist/_chunks/{chunk-LOYAGAAN.js → chunk-AIR7YOFU.js} +1 -1
- package/dist/_chunks/chunk-BZPQB66Z.js +1 -0
- package/dist/_chunks/chunk-CTCEGOC7.js +1 -0
- package/dist/_chunks/chunk-DLW42PJ6.js +1 -0
- package/dist/_chunks/{chunk-MT5XZ67U.js → chunk-GQ32ZQTM.js} +1 -1
- package/dist/_chunks/{chunk-SRB5ZFKO.js → chunk-H46NB5FL.js} +1 -1
- package/dist/_chunks/{chunk-35XQP7RY.js → chunk-HIBT6NXN.js} +1 -1
- package/dist/_chunks/chunk-IF6AUKH3.js +1 -0
- package/dist/_chunks/{chunk-PYUYK3FV.js → chunk-J2IYRUVM.js} +1 -1
- package/dist/_chunks/{chunk-XVQWVJWD.js → chunk-JL4MUI7K.js} +1 -1
- package/dist/_chunks/chunk-LZPPTW2K.js +1 -0
- package/dist/_chunks/{chunk-5LSB6HDP.js → chunk-PAIJRAJB.js} +1 -1
- package/dist/_chunks/chunk-QGK6G6YS.js +1 -0
- package/dist/_chunks/{chunk-BGH3Y5UX.js → chunk-TIHGZGU3.js} +1 -1
- package/dist/_chunks/chunk-TT7IA5HB.js +1 -0
- package/dist/_chunks/chunk-UITIQHVU.js +45 -0
- package/dist/_chunks/chunk-WTJVS2VS.js +1 -0
- package/dist/_chunks/chunk-WXEERCXN.js +1 -0
- package/dist/_chunks/component-contract-HETXQ2J4.js +1 -0
- package/dist/_chunks/connect-7TJDWXV4.js +1 -0
- package/dist/_chunks/device-management-NP7HAXRU.js +1 -0
- package/dist/_chunks/device-preflight-QAPMMHWK.js +1 -0
- package/dist/_chunks/devices-inventory-WZ3QAPTS.js +1 -0
- package/dist/_chunks/devices-main-XKRRLX5B.js +1 -0
- package/dist/_chunks/files-JJ6YOULB.js +1 -0
- package/dist/_chunks/host-component-H3Q7TU5Y.js +1 -0
- package/dist/_chunks/host-help-SBXGX457.js +1 -0
- package/dist/_chunks/host-main-VUEGUFTU.js +1 -0
- package/dist/_chunks/http-profile-3VVSWYA5.js +1 -0
- package/dist/_chunks/library-main-4BQ2J73H.js +1 -0
- package/dist/_chunks/local-main-GBC2HPD4.js +1 -0
- package/dist/_chunks/local-mcp-FXHB3CKF.js +1 -0
- package/dist/_chunks/main-R7DV24KT.js +2 -0
- package/dist/_chunks/mcp-6D4KHCCL.js +1 -0
- package/dist/_chunks/oauth-RPME2XYB.js +1 -0
- package/dist/_chunks/observe-entry-NKXTUZYF.js +1 -0
- package/dist/_chunks/remote-client-TIFVZEGG.js +1 -0
- package/dist/_chunks/render-main-KMP4SMK7.js +1 -0
- package/dist/_chunks/source-import-YYRII5FQ.js +1 -0
- package/dist/_chunks/src-IX5ZVGZS.js +1 -0
- package/dist/_chunks/stdio-main-HNLJCG45.js +1 -0
- package/dist/_chunks/workspace-main-LD56MMI6.js +1 -0
- package/dist/_types/cli/local/desktop-contract.d.ts +9 -3
- package/dist/_types/cli/local/desktop-device-contract.d.ts +18 -3
- package/dist/_types/cli/local/desktop-device-owner.d.ts +4 -1
- package/dist/_types/cli/local/desktop-device-state.d.ts +10 -4
- package/dist/_types/cli/local/desktop-owner.d.ts +13 -11
- package/dist/_types/cli/local/ledger.d.ts +2 -0
- package/dist/_types/cli/local/manager.d.ts +12 -6
- package/dist/_types/cli/local/mcp-tools.d.ts +21 -4
- package/dist/_types/contracts/component-status.d.ts +241 -0
- package/dist/_types/contracts/composition-source-review.d.ts +1 -1
- package/dist/_types/contracts/delivery-completion.d.ts +1 -1
- package/dist/_types/contracts/delivery-operations.d.ts +5 -5
- package/dist/_types/contracts/delivery-summary.d.ts +1 -1
- package/dist/_types/contracts/delivery-validation.d.ts +3 -3
- package/dist/_types/contracts/device-onboarding.d.ts +12 -6
- package/dist/_types/contracts/device-render.d.ts +14 -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/final-render.d.ts +1 -1
- package/dist/_types/contracts/index.d.ts +4 -0
- package/dist/_types/contracts/interface/common.d.ts +18 -0
- package/dist/_types/contracts/interface/production-snapshot.d.ts +1 -1
- package/dist/_types/contracts/keyframe-review.d.ts +6 -6
- package/dist/_types/contracts/local-execution/agent-component-status.d.ts +109 -0
- package/dist/_types/contracts/local-execution/agent-context.d.ts +4 -4
- package/dist/_types/contracts/local-execution/agent-review.d.ts +7 -7
- package/dist/_types/contracts/local-execution/device-inventory.d.ts +12 -6
- package/dist/_types/contracts/local-execution/device.d.ts +2 -1
- 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/index.d.ts +3 -0
- package/dist/_types/contracts/local-execution/ipc.d.ts +43 -9
- package/dist/_types/contracts/local-execution/library-result.d.ts +4 -0
- package/dist/_types/contracts/local-execution/local-navigation.d.ts +25 -8
- package/dist/_types/contracts/local-execution/management.d.ts +5 -2
- package/dist/_types/contracts/local-execution/media-validation.d.ts +2 -2
- package/dist/_types/contracts/local-execution/preview.d.ts +1 -0
- package/dist/_types/contracts/local-execution/processor-capability.d.ts +8 -0
- package/dist/_types/contracts/local-execution/processor-recipes.d.ts +29 -0
- package/dist/_types/contracts/local-execution/processor.d.ts +73 -3
- package/dist/_types/contracts/local-execution/workspace.d.ts +1 -1
- package/dist/_types/contracts/mcp-capabilities.d.ts +16 -0
- package/dist/_types/contracts/navigation-context.d.ts +22 -2
- package/dist/_types/contracts/navigation.d.ts +13 -0
- package/dist/_types/contracts/programmatic-exploration.d.ts +8 -8
- package/dist/_types/contracts/programmatic-video-review.d.ts +5 -5
- package/dist/_types/contracts/reference-preview.d.ts +1 -0
- package/dist/_types/contracts/repair-lifecycle.d.ts +12 -12
- package/dist/_types/contracts/repair-plan.d.ts +2 -2
- package/dist/_types/contracts/review-intelligence-final-output.d.ts +3 -3
- package/dist/_types/contracts/review-intelligence.d.ts +5 -5
- 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/video-review.d.ts +6 -6
- package/dist/_types/sdk/errors.d.ts +3 -2
- package/dist/_types/sdk/local-runtime/device-client.d.ts +2 -2
- package/dist/_types/sdk/local-runtime-client.d.ts +29 -16
- 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-B7BQERMR.js +0 -1
- package/dist/_chunks/chunk-CW67UB2I.js +0 -1
- package/dist/_chunks/chunk-HAOCQVMU.js +0 -1
- package/dist/_chunks/chunk-HTUTYIRU.js +0 -1
- package/dist/_chunks/chunk-JLQCUXCT.js +0 -1
- package/dist/_chunks/chunk-RUPH3HZ2.js +0 -1
- package/dist/_chunks/chunk-TQIJBUSP.js +0 -1
- package/dist/_chunks/chunk-U5FT4VBR.js +0 -1
- package/dist/_chunks/chunk-U6ZG2G7W.js +0 -1
- package/dist/_chunks/chunk-VLEWCWYF.js +0 -1
- package/dist/_chunks/chunk-WAADGZEV.js +0 -1
- package/dist/_chunks/connect-OY623MMA.js +0 -1
- package/dist/_chunks/device-management-ELAPFWM2.js +0 -1
- package/dist/_chunks/device-preflight-27RDJVBU.js +0 -1
- package/dist/_chunks/devices-inventory-2XEJPPO5.js +0 -1
- package/dist/_chunks/devices-main-UMF3ZBHA.js +0 -1
- package/dist/_chunks/files-72BEXD7E.js +0 -1
- package/dist/_chunks/host-main-WYTVTQ4Z.js +0 -1
- package/dist/_chunks/http-profile-D65WSTZU.js +0 -1
- package/dist/_chunks/library-main-L7SY7V7L.js +0 -1
- package/dist/_chunks/local-main-7FONRY6F.js +0 -1
- package/dist/_chunks/local-mcp-ELFJBJG6.js +0 -1
- package/dist/_chunks/main-XWUYQQ32.js +0 -2
- package/dist/_chunks/mcp-ACNG635V.js +0 -1
- package/dist/_chunks/oauth-QBJ62PIA.js +0 -1
- package/dist/_chunks/observe-entry-3CHBX74Y.js +0 -1
- package/dist/_chunks/remote-client-WIZVKP3O.js +0 -1
- package/dist/_chunks/render-main-ZXYQ7EV5.js +0 -1
- package/dist/_chunks/source-import-ZWR26CMU.js +0 -1
- package/dist/_chunks/src-TR4JNPGI.js +0 -1
- package/dist/_chunks/stdio-main-QQLYSRD4.js +0 -1
- package/dist/_chunks/workspace-main-NYDAQGB4.js +0 -1
|
@@ -2,6 +2,7 @@ import { NativeStudioLocalWorkspaceClient } from "./local-runtime/workspace.js";
|
|
|
2
2
|
import { NativeStudioLocalLibraryClient } from "./local-runtime/library.js";
|
|
3
3
|
import { type LocalIpcRequest, type LocalWorkScope } from "../contracts/local-execution/index.js";
|
|
4
4
|
import { type LocalAgentSnapshot } from "../contracts/local-execution/index.js";
|
|
5
|
+
export { DeviceEnrollmentReceiptSchema, deviceEnrollmentSigningInput, AgentComponentScopeSchema, AgentComponentStatusSchema, LocalRuntimeStatusSchema, type AgentComponentScope, type AgentComponentStatus, } from "../contracts/local-execution/index.js";
|
|
5
6
|
export declare class NativeStudioLocalRuntimeClient {
|
|
6
7
|
readonly options: {
|
|
7
8
|
stateDirectory: string;
|
|
@@ -210,7 +211,7 @@ export declare class NativeStudioLocalRuntimeClient {
|
|
|
210
211
|
summary: string;
|
|
211
212
|
imageReadback: string;
|
|
212
213
|
observations: {
|
|
213
|
-
status: "
|
|
214
|
+
status: "NOT_APPLICABLE" | "SATISFIED" | "VIOLATED" | "NOT_OBSERVABLE";
|
|
214
215
|
confidence: "CLEAR" | "UNCERTAIN";
|
|
215
216
|
observed: string;
|
|
216
217
|
key: string;
|
|
@@ -781,11 +782,17 @@ export declare class NativeStudioLocalRuntimeClient {
|
|
|
781
782
|
deviceId: string;
|
|
782
783
|
origin: string;
|
|
783
784
|
} | undefined;
|
|
785
|
+
capabilityMismatch?: {
|
|
786
|
+
kind: "CAPABILITY_DEFINITION" | "MEDIA_PROFILE" | "RENDERER" | "VALIDATION_PROFILE" | "PROCESSOR_PROFILE" | "LOCAL_LIBRARY_PROFILE";
|
|
787
|
+
expectedVersion: string;
|
|
788
|
+
actualVersion: string;
|
|
789
|
+
recovery: "REDISCOVER_CAPABILITY" | "CHECK_DEVICE_RELEASE";
|
|
790
|
+
} | undefined;
|
|
784
791
|
deviceCapabilities?: {
|
|
785
792
|
deviceRevision: number;
|
|
786
793
|
tenantMediaValidation: boolean;
|
|
787
794
|
tenantMediaProcessing: boolean;
|
|
788
|
-
processorCapabilities: ("KEYFRAME_GENERATE" | "VIDEO_GENERATE" | "SPEECH_SYNTHESIZE" | "SPEECH_EXTERNAL_QWEN" | "TEMPORAL_SAMPLE" | "DELIVERY_VALIDATE" | "COMPOSITION_RENDER" | "IMPORTED_VISUAL_NORMALIZE" | "SOURCE_SYNC_AUDIO" | "IMPORT_ORIGINAL" | "LOCAL_MEDIA_INSPECT" | "LOCAL_MEDIA_PUBLISH" | "IMPORT_PROJECT_SOURCE" | "REGISTER_VISUAL_SEQUENCE" | "SPEECH_SYNTHESIZE_CPU" | "TRANSCRIBE_AUDIO" | "TRANSCRIBE_EXTERNAL_QWEN")[];
|
|
795
|
+
processorCapabilities: ("KEYFRAME_GENERATE" | "VIDEO_GENERATE" | "SPEECH_SYNTHESIZE" | "SPEECH_EXTERNAL_QWEN" | "TEMPORAL_SAMPLE" | "DELIVERY_VALIDATE" | "COMPOSITION_RENDER" | "IMPORTED_VISUAL_NORMALIZE" | "SOURCE_SYNC_AUDIO" | "IMPORT_ORIGINAL" | "LOCAL_MEDIA_INSPECT" | "LOCAL_MEDIA_PUBLISH" | "IMPORT_PROJECT_SOURCE" | "REGISTER_VISUAL_SEQUENCE" | "REFERENCE_PREVIEW" | "SPEECH_SYNTHESIZE_CPU" | "TRANSCRIBE_AUDIO" | "TRANSCRIBE_EXTERNAL_QWEN")[];
|
|
789
796
|
} | undefined;
|
|
790
797
|
} | {
|
|
791
798
|
binding: {
|
|
@@ -800,10 +807,10 @@ export declare class NativeStudioLocalRuntimeClient {
|
|
|
800
807
|
toolchainFingerprint: string;
|
|
801
808
|
};
|
|
802
809
|
revision: number;
|
|
803
|
-
phase: "RUNNING" | "
|
|
810
|
+
phase: "RUNNING" | "FENCED" | "RECOVERY_REQUIRED" | "STAGED" | "OUTPUT_PENDING" | "RECEIPT_RECORDED";
|
|
804
811
|
checkpoint: "ADOPTED" | "SOURCES_READY" | "PROCESS_STARTED" | "OUTPUT_STAGED";
|
|
805
812
|
progress?: {
|
|
806
|
-
stage: "WAITING" | "COMPLETE" | "RECOVERY_REQUIRED" | "DOWNLOADING" | "EXECUTING" | "UPLOADING" | "AWAITING_ACCEPTANCE"
|
|
813
|
+
stage: "WAITING" | "COMPLETE" | "FENCED" | "RECOVERY_REQUIRED" | "DOWNLOADING" | "EXECUTING" | "UPLOADING" | "AWAITING_ACCEPTANCE";
|
|
807
814
|
downloadedBytes: number;
|
|
808
815
|
sourceBytes: number;
|
|
809
816
|
uploadedBytes: number;
|
|
@@ -1106,10 +1113,10 @@ export declare class NativeStudioLocalRuntimeClient {
|
|
|
1106
1113
|
toolchainFingerprint: string;
|
|
1107
1114
|
};
|
|
1108
1115
|
revision: number;
|
|
1109
|
-
phase: "RUNNING" | "
|
|
1116
|
+
phase: "RUNNING" | "FENCED" | "RECOVERY_REQUIRED" | "STAGED" | "OUTPUT_PENDING" | "RECEIPT_RECORDED";
|
|
1110
1117
|
checkpoint: "ADOPTED" | "SOURCES_READY" | "PROCESS_STARTED" | "OUTPUT_STAGED";
|
|
1111
1118
|
progress?: {
|
|
1112
|
-
stage: "WAITING" | "COMPLETE" | "RECOVERY_REQUIRED" | "DOWNLOADING" | "EXECUTING" | "UPLOADING" | "AWAITING_ACCEPTANCE"
|
|
1119
|
+
stage: "WAITING" | "COMPLETE" | "FENCED" | "RECOVERY_REQUIRED" | "DOWNLOADING" | "EXECUTING" | "UPLOADING" | "AWAITING_ACCEPTANCE";
|
|
1113
1120
|
downloadedBytes: number;
|
|
1114
1121
|
sourceBytes: number;
|
|
1115
1122
|
uploadedBytes: number;
|
|
@@ -1602,11 +1609,17 @@ export declare class NativeStudioLocalRuntimeClient {
|
|
|
1602
1609
|
deviceId: string;
|
|
1603
1610
|
origin: string;
|
|
1604
1611
|
} | undefined;
|
|
1612
|
+
capabilityMismatch?: {
|
|
1613
|
+
kind: "CAPABILITY_DEFINITION" | "MEDIA_PROFILE" | "RENDERER" | "VALIDATION_PROFILE" | "PROCESSOR_PROFILE" | "LOCAL_LIBRARY_PROFILE";
|
|
1614
|
+
expectedVersion: string;
|
|
1615
|
+
actualVersion: string;
|
|
1616
|
+
recovery: "REDISCOVER_CAPABILITY" | "CHECK_DEVICE_RELEASE";
|
|
1617
|
+
} | undefined;
|
|
1605
1618
|
deviceCapabilities?: {
|
|
1606
1619
|
deviceRevision: number;
|
|
1607
1620
|
tenantMediaValidation: boolean;
|
|
1608
1621
|
tenantMediaProcessing: boolean;
|
|
1609
|
-
processorCapabilities: ("KEYFRAME_GENERATE" | "VIDEO_GENERATE" | "SPEECH_SYNTHESIZE" | "SPEECH_EXTERNAL_QWEN" | "TEMPORAL_SAMPLE" | "DELIVERY_VALIDATE" | "COMPOSITION_RENDER" | "IMPORTED_VISUAL_NORMALIZE" | "SOURCE_SYNC_AUDIO" | "IMPORT_ORIGINAL" | "LOCAL_MEDIA_INSPECT" | "LOCAL_MEDIA_PUBLISH" | "IMPORT_PROJECT_SOURCE" | "REGISTER_VISUAL_SEQUENCE" | "SPEECH_SYNTHESIZE_CPU" | "TRANSCRIBE_AUDIO" | "TRANSCRIBE_EXTERNAL_QWEN")[];
|
|
1622
|
+
processorCapabilities: ("KEYFRAME_GENERATE" | "VIDEO_GENERATE" | "SPEECH_SYNTHESIZE" | "SPEECH_EXTERNAL_QWEN" | "TEMPORAL_SAMPLE" | "DELIVERY_VALIDATE" | "COMPOSITION_RENDER" | "IMPORTED_VISUAL_NORMALIZE" | "SOURCE_SYNC_AUDIO" | "IMPORT_ORIGINAL" | "LOCAL_MEDIA_INSPECT" | "LOCAL_MEDIA_PUBLISH" | "IMPORT_PROJECT_SOURCE" | "REGISTER_VISUAL_SEQUENCE" | "REFERENCE_PREVIEW" | "SPEECH_SYNTHESIZE_CPU" | "TRANSCRIBE_AUDIO" | "TRANSCRIBE_EXTERNAL_QWEN")[];
|
|
1610
1623
|
} | undefined;
|
|
1611
1624
|
}>;
|
|
1612
1625
|
doctor(signal?: AbortSignal): Promise<{
|
|
@@ -1883,7 +1896,7 @@ export declare class NativeStudioLocalRuntimeClient {
|
|
|
1883
1896
|
summary: string;
|
|
1884
1897
|
imageReadback: string;
|
|
1885
1898
|
observations: {
|
|
1886
|
-
status: "
|
|
1899
|
+
status: "NOT_APPLICABLE" | "SATISFIED" | "VIOLATED" | "NOT_OBSERVABLE";
|
|
1887
1900
|
confidence: "CLEAR" | "UNCERTAIN";
|
|
1888
1901
|
observed: string;
|
|
1889
1902
|
key: string;
|
|
@@ -2126,7 +2139,7 @@ export declare class NativeStudioLocalRuntimeClient {
|
|
|
2126
2139
|
summary: string;
|
|
2127
2140
|
imageReadback: string;
|
|
2128
2141
|
observations: {
|
|
2129
|
-
status: "
|
|
2142
|
+
status: "NOT_APPLICABLE" | "SATISFIED" | "VIOLATED" | "NOT_OBSERVABLE";
|
|
2130
2143
|
confidence: "CLEAR" | "UNCERTAIN";
|
|
2131
2144
|
observed: string;
|
|
2132
2145
|
key: string;
|
|
@@ -2369,7 +2382,7 @@ export declare class NativeStudioLocalRuntimeClient {
|
|
|
2369
2382
|
summary: string;
|
|
2370
2383
|
imageReadback: string;
|
|
2371
2384
|
observations: {
|
|
2372
|
-
status: "
|
|
2385
|
+
status: "NOT_APPLICABLE" | "SATISFIED" | "VIOLATED" | "NOT_OBSERVABLE";
|
|
2373
2386
|
confidence: "CLEAR" | "UNCERTAIN";
|
|
2374
2387
|
observed: string;
|
|
2375
2388
|
key: string;
|
|
@@ -2612,7 +2625,7 @@ export declare class NativeStudioLocalRuntimeClient {
|
|
|
2612
2625
|
summary: string;
|
|
2613
2626
|
imageReadback: string;
|
|
2614
2627
|
observations: {
|
|
2615
|
-
status: "
|
|
2628
|
+
status: "NOT_APPLICABLE" | "SATISFIED" | "VIOLATED" | "NOT_OBSERVABLE";
|
|
2616
2629
|
confidence: "CLEAR" | "UNCERTAIN";
|
|
2617
2630
|
observed: string;
|
|
2618
2631
|
key: string;
|
|
@@ -2688,10 +2701,10 @@ export declare class NativeStudioLocalRuntimeClient {
|
|
|
2688
2701
|
toolchainFingerprint: string;
|
|
2689
2702
|
};
|
|
2690
2703
|
revision: number;
|
|
2691
|
-
phase: "RUNNING" | "
|
|
2704
|
+
phase: "RUNNING" | "FENCED" | "RECOVERY_REQUIRED" | "STAGED" | "OUTPUT_PENDING" | "RECEIPT_RECORDED";
|
|
2692
2705
|
checkpoint: "ADOPTED" | "SOURCES_READY" | "PROCESS_STARTED" | "OUTPUT_STAGED";
|
|
2693
2706
|
progress?: {
|
|
2694
|
-
stage: "WAITING" | "COMPLETE" | "RECOVERY_REQUIRED" | "DOWNLOADING" | "EXECUTING" | "UPLOADING" | "AWAITING_ACCEPTANCE"
|
|
2707
|
+
stage: "WAITING" | "COMPLETE" | "FENCED" | "RECOVERY_REQUIRED" | "DOWNLOADING" | "EXECUTING" | "UPLOADING" | "AWAITING_ACCEPTANCE";
|
|
2695
2708
|
downloadedBytes: number;
|
|
2696
2709
|
sourceBytes: number;
|
|
2697
2710
|
uploadedBytes: number;
|
|
@@ -2719,10 +2732,10 @@ export declare class NativeStudioLocalRuntimeClient {
|
|
|
2719
2732
|
toolchainFingerprint: string;
|
|
2720
2733
|
};
|
|
2721
2734
|
revision: number;
|
|
2722
|
-
phase: "RUNNING" | "
|
|
2735
|
+
phase: "RUNNING" | "FENCED" | "RECOVERY_REQUIRED" | "STAGED" | "OUTPUT_PENDING" | "RECEIPT_RECORDED";
|
|
2723
2736
|
checkpoint: "ADOPTED" | "SOURCES_READY" | "PROCESS_STARTED" | "OUTPUT_STAGED";
|
|
2724
2737
|
progress?: {
|
|
2725
|
-
stage: "WAITING" | "COMPLETE" | "RECOVERY_REQUIRED" | "DOWNLOADING" | "EXECUTING" | "UPLOADING" | "AWAITING_ACCEPTANCE"
|
|
2738
|
+
stage: "WAITING" | "COMPLETE" | "FENCED" | "RECOVERY_REQUIRED" | "DOWNLOADING" | "EXECUTING" | "UPLOADING" | "AWAITING_ACCEPTANCE";
|
|
2726
2739
|
downloadedBytes: number;
|
|
2727
2740
|
sourceBytes: number;
|
|
2728
2741
|
uploadedBytes: number;
|
|
@@ -2750,7 +2763,7 @@ export { NativeStudioLocalWorkspaceClient } from "./local-runtime/workspace.js";
|
|
|
2750
2763
|
export * from "./local-runtime/library.js";
|
|
2751
2764
|
export { LocalOfflineCallSchema, LocalOfflinePageSchema, } from "../contracts/local-execution/index.js";
|
|
2752
2765
|
export { LocalResourcePolicySchema, LocalResourceSettingsSchema, LocalWorkspaceInspectionSchema, LocalStorageInspectionSchema, LocalExecutionProgressSchema, LocalExecutionInspectInputSchema, LocalDiagnosticsSchema, } from "../contracts/local-execution/index.js";
|
|
2753
|
-
export { importedNormalizationValidationProfile, tenantRenderValidationProfile, whisperCppRecognitionProfile, } from "../contracts/local-execution/index.js";
|
|
2766
|
+
export { importedNormalizationValidationProfile, referenceThumbnailProfile, tenantRenderValidationProfile, whisperCppRecognitionProfile, } from "../contracts/local-execution/index.js";
|
|
2754
2767
|
export { processorFamilies } from "../contracts/local-execution/index.js";
|
|
2755
2768
|
export type { TenantProcessorKind } from "../contracts/local-execution/index.js";
|
|
2756
2769
|
export * from "./local-runtime/components.js";
|
package/dist/entry.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
if(process.argv[2]==="observe"){process.exitCode=await(await import("./_chunks/observe-entry-
|
|
2
|
+
if(process.argv[2]==="observe"){process.exitCode=await(await import("./_chunks/observe-entry-NKXTUZYF.js")).runObservationEntry(process.argv.slice(3))}else if(process.argv[2]==="host"){const{runHostCli}=await import("./_chunks/host-main-VUEGUFTU.js");const result=await runHostCli(process.argv.slice(3));process.stdout.write(JSON.stringify(result.output)+"\n");process.exitCode=result.exitCode}else if(process.argv[2]==="local"){if(process.argv[3]==="mcp"){const{runLocalMcp}=await import("./_chunks/local-mcp-FXHB3CKF.js");process.exitCode=await runLocalMcp(process.argv.slice(4))}else{const{runLocalCli}=await import("./_chunks/local-main-GBC2HPD4.js");const result=await runLocalCli(process.argv.slice(3));process.stdout.write(JSON.stringify(result.output)+"\n");process.exitCode=result.exitCode}}else if(process.argv[2]==="mcp"){const{runMcpStdio}=await import("./_chunks/stdio-main-HNLJCG45.js");process.exitCode=await runMcpStdio(process.argv.slice(3),process.env)}else{const{runRemoteCli}=await import("./_chunks/main-R7DV24KT.js");const result=await runRemoteCli(process.argv.slice(2));process.stdout.write(JSON.stringify(result.output)+"\n");process.exitCode=result.exitCode}
|
package/dist/local-management.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{desktopDevicePending,runDesktopDeviceRequest}from"./_chunks/chunk-B7BQERMR.js";import{DesktopLibraryImportRequestSchema,DesktopLibraryImportSeedSchema,DesktopLibraryMediaRequestSchema,DesktopLibraryPrepareRequestSchema,DesktopLibraryReplySchema,DesktopLibraryRequestSchema,prepareDesktopLibraryImport,runDesktopLibraryImport,runDesktopLibraryMedia,runDesktopLibraryRequest}from"./_chunks/chunk-35XQP7RY.js";import{desktopAutomation,desktopInstallationIdentity,disableDesktopAutomation}from"./_chunks/chunk-PYUYK3FV.js";import{prepareInstalledCpuSpeech}from"./_chunks/chunk-LOYAGAAN.js";import"./_chunks/chunk-MT5XZ67U.js";import{LocalInstallationManager,captureInstalledTools,ownerClient,socketAbsent,toolPreference,waitStopped}from"./_chunks/chunk-U6ZG2G7W.js";import{DesktopDeviceReplySchema,DesktopDeviceRequestSchema,DesktopDeviceScopeSchema,desktopDeviceConnector}from"./_chunks/chunk-JLQCUXCT.js";import{CpuSpeechPrepareInputSchema,LocalAgentDiscoverySchema,LocalAgentGrantSchema,LocalAgentProbeSchema,LocalAgentReviewViewSchema,LocalAgentSnapshotSchema,LocalDiagnosticsSchema,LocalOfflineCallSchema,LocalOfflinePageSchema,LocalReleaseSchema,LocalResourcePolicySchema,LocalRuntimeDescriptorSchema,LocalToolSelectionSchema,LocalWorkspaceInspectionSchema,catalogue,endpoint,newerVersion}from"./_chunks/chunk-VLEWCWYF.js";import{canonicalLocalJson}from"./_chunks/chunk-WAADGZEV.js";import{LocalClientError,atomicMove,directory,entries,fail,optional,read,sha256,write}from"./_chunks/chunk-RUPH3HZ2.js";import"./_chunks/chunk-HAOCQVMU.js";import{NativeStudioSdkError}from"./_chunks/chunk-HTUTYIRU.js";import{z as z7}from"zod";import{z}from"zod";import{join,sep}from"node:path";var StoragePlanSchema=z.strictObject({id:z.uuid(),mode:z.enum(["BACKUP","MIGRATE"]),source:z.string().min(1),destination:z.string().min(1),installationRevision:z.int().nonnegative(),installationFingerprint:z.string().regex(/^[a-f0-9]{64}$/),runtimeRevision:z.int().positive(),revision:z.int().nonnegative().default(0),phase:z.enum(["PREPARED","DRAINING","COPYING","COPIED","VERIFYING","COMPLETE","CANCELLED"]),fingerprint:z.string().regex(/^[a-f0-9]{64}$/),expiresAt:z.iso.datetime(),bytes:z.int().nonnegative().default(0)});var recordSchema=z.strictObject({plan:StoragePlanSchema,previous:z.string().regex(/^[a-f0-9]{64}$/).nullable(),digest:z.string().regex(/^[a-f0-9]{64}$/)});var phases=["PREPARED","DRAINING","COPYING","COPIED","VERIFYING","COMPLETE"];var terminal=phase=>["COMPLETE","CANCELLED"].includes(phase);var advances=(before,after)=>before===after||!terminal(before)&&(after==="CANCELLED"||phases.indexOf(after)===phases.indexOf(before)+1);async function storageInstallationIdentity(slot,source,destination){const tools=slot.toolsConfigPath?LocalToolSelectionSchema.parse(JSON.parse((await read(slot.toolsConfigPath,32768)).toString())):null;if(tools?.mode==="MANAGED"){for(const name of["ffmpeg","ffprobe"])for(const root of[source,destination])if(tools[name].path.startsWith(root+sep)){tools[name].path="{state}"+tools[name].path.slice(root.length);break}}return sha256(canonicalLocalJson({descriptor:slot.descriptor,files:slot.files,tools}))}function intent(p){return{id:p.id,mode:p.mode,source:p.source,destination:p.destination,installationRevision:p.installationRevision,installationFingerprint:p.installationFingerprint,runtimeRevision:p.runtimeRevision,expiresAt:p.expiresAt}}async function history(root,id2){const path=await directory(join(root,z.uuid().parse(id2)));let plan=null;let digest4=null;const names=(await entries(path)).filter(n=>/^\d{8}\.json$/.test(n)).sort();for(const[index,name]of names.entries()){const record=recordSchema.parse(JSON.parse((await read(join(path,name))).toString())),next=record.plan;if(next.id!==id2||next.revision!==index+1||next.fingerprint!==sha256(canonicalLocalJson(intent(next)))||record.previous!==digest4||record.digest!==sha256(canonicalLocalJson({plan:next,previous:digest4}))||!plan&&next.phase!=="PREPARED"||plan&&(plan.fingerprint!==next.fingerprint||!advances(plan.phase,next.phase)))fail("STORAGE_HISTORY_INVALID");plan=next;digest4=record.digest}return{plan,digest:digest4}}async function readStoragePlan(root,id2){return(await history(root,id2)).plan}async function saveStoragePlan(root,expected,phase,extra={}){const current=await history(root,expected.id),actual=current.plan;if((actual?.revision??0)!==expected.revision)fail("REVISION_CONFLICT");if(actual&&canonicalLocalJson(actual)!==canonicalLocalJson(expected))fail("PLAN_CHANGED");const next=StoragePlanSchema.parse({...expected,...extra,phase,revision:expected.revision+1});if(next.fingerprint!==sha256(canonicalLocalJson(intent(next))))fail("PLAN_CHANGED");if(!actual&&phase!=="PREPARED"||actual&&!advances(actual.phase,phase))fail("PLAN_CHANGED");const file=join(root,next.id,String(next.revision).padStart(8,"0")+".json");try{const body={plan:next,previous:current.digest};await write(file,canonicalLocalJson({...body,digest:sha256(canonicalLocalJson(body))}),true)}catch(e){if(e.code==="EEXIST")fail("REVISION_CONFLICT");throw e}return next}import{z as z2}from"zod";import{lstat as lstat2,realpath}from"node:fs/promises";import{randomUUID}from"node:crypto";import{join as join3,resolve,sep as sep3}from"node:path";import{constants,createReadStream}from"node:fs";import{open,readdir,lstat,statfs,chmod,unlink}from"node:fs/promises";import{join as join2,relative,sep as sep2}from"node:path";import{createHash}from"node:crypto";async function digestFile(path){const file=await open(path,constants.O_RDONLY|constants.O_NOFOLLOW);try{const before=await file.stat(),hash=createHash("sha256");if(!before.isFile()||before.nlink!==1||before.size>512*1024**2||process.platform!=="win32"&&(before.uid!==process.getuid?.()||before.mode&63))fail("STORAGE_FILE_INVALID");let bytes=0;for await(const chunk of createReadStream(path,{fd:file.fd,autoClose:false})){bytes+=chunk.length;if(bytes>before.size)fail("STORAGE_FILE_CHANGED");hash.update(chunk)}const after=await file.stat();if(bytes!==before.size||before.mtimeMs!==after.mtimeMs||before.ino!==after.ino)fail("STORAGE_FILE_CHANGED");return{bytes,sha256:hash.digest("hex"),mode:before.mode&448}}finally{await file.close()}}async function storageFiles(root){const files=[];async function walk(path,depth){if(depth>8)fail("STORAGE_FILE_LIMIT");for(const item of await readdir(path,{withFileTypes:true})){const source=join2(path,item.name),name=relative(root,source);if(path===root&&!["journal.sqlite","journal.sqlite-wal","cache","staging","tools","agent-images","agent-evidence","agent-reviews","library"].includes(item.name))continue;const info=await lstat(source);if(info.isSymbolicLink()||!info.isFile()&&!info.isDirectory())fail("STORAGE_FILE_INVALID");if(info.isDirectory())await walk(source,depth+1);else{if(files.length>=5e4)fail("STORAGE_FILE_LIMIT");const value=await digestFile(source);files.push({name,bytes:value.bytes,sha256:value.sha256})}}}await walk(root,0);return files.sort((a,b)=>a.name.localeCompare(b.name))}async function copyStorage(source,destination){if(destination===source||destination.startsWith(source+sep2)||source.startsWith(destination+sep2))fail("STORAGE_LOCATION_INVALID");await directory(destination);const files=await storageFiles(source),total=files.reduce((n,f)=>n+f.bytes,0);const fs=await statfs(destination);if(fs.bavail*fs.bsize<total+256*1024**2)fail("STORAGE_SPACE_REQUIRED");for(const item of files){const original=join2(source,item.name),target=join2(destination,item.name);const parent=target.slice(0,target.lastIndexOf(sep2));await directory(parent);try{const existing=await digestFile(target);if(existing.sha256!==item.sha256||existing.bytes!==item.bytes)fail("STORAGE_COPY_CONFLICT");continue}catch(error){if(error.code!=="ENOENT")throw error}const temporary=target+".copy-part";try{await digestFile(temporary);await unlink(temporary)}catch(error){if(error.code!=="ENOENT")throw error}const input=await open(original,constants.O_RDONLY|constants.O_NOFOLLOW),output=await open(temporary,"wx",384);try{for await(const bytes of createReadStream(original,{fd:input.fd,autoClose:false}))await output.writeFile(bytes);await output.sync()}finally{await input.close();await output.close()}const copied=await digestFile(temporary),before=await digestFile(original);if(copied.sha256!==item.sha256||before.sha256!==item.sha256||copied.bytes!==item.bytes)fail("STORAGE_COPY_INVALID");await chmod(temporary,before.mode);await atomicMove(temporary,target,true)}return{files,total}}var id=z2.uuid();var digest=z2.string().regex(/^[a-f0-9]{64}$/);var planSchema=StoragePlanSchema;var DesktopStorageRequestSchema=z2.strictObject({operation:z2.literal("storage"),call:z2.discriminatedUnion("action",[z2.strictObject({action:z2.literal("status")}),z2.strictObject({action:z2.literal("prepare"),mode:z2.enum(["BACKUP","MIGRATE"]),destination:z2.string().min(1).max(4096)}),z2.strictObject({action:z2.enum(["execute","recover","abandon"]),id,fingerprint:digest})])});var viewSchema=planSchema.omit({source:true,destination:true,runtimeRevision:true,installationRevision:true});var DesktopStorageReplySchema=viewSchema.nullable();function present(plan){if(!plan)return null;const{source,destination,runtimeRevision,installationRevision,...view}=plan;void source;void destination;void runtimeRevision;void installationRevision;return DesktopStorageReplySchema.parse(view)}async function runDesktopStorageRequest(home,raw){const{call}=DesktopStorageRequestSchema.parse(raw),manager=await LocalInstallationManager.open(home);const root=await directory(join3(home,"storage-plans"));const pointer=await optional(join3(root,"current.json"));const prior=pointer?await readStoragePlan(root,id.parse(pointer)):null;if(call.action==="status")return present(prior);let config=await manager.configuration(),installation=(await manager.ledger.current()).value;let plan;const save=async(phase,extra={})=>{plan=await saveStoragePlan(root,plan,phase,extra)};if(call.action==="prepare"){if(!installation.active||installation.transition)fail("RECOVERY_REQUIRED");if(prior&&!["COMPLETE","CANCELLED"].includes(prior.phase))fail("RECOVERY_REQUIRED");const selected=resolve(call.destination),info=await lstat2(selected);if(!info.isDirectory()||info.isSymbolicLink()||process.platform!=="win32"&&info.uid!==process.getuid?.())fail("STORAGE_LOCATION_INVALID");const destination=await realpath(selected);if(destination===config.stateDirectory||destination.startsWith(config.stateDirectory+sep3))fail("STORAGE_LOCATION_INVALID");const inventory=await(await ownerClient(config.stateDirectory)).inventory();const body={id:randomUUID(),mode:call.mode,source:config.stateDirectory,destination:join3(destination,"NVS-"+randomUUID().replaceAll("-","").slice(0,16)),installationRevision:installation.revision,runtimeRevision:inventory.runtimeRevision,expiresAt:new Date(Date.now()+18e5).toISOString()};if(call.mode==="MIGRATE"&&process.platform!=="win32"&&Buffer.byteLength(join3(body.destination,"runtime.sock"))>100)fail("SOCKET_PATH_TOO_LONG");const frozen={...body,installationFingerprint:await storageInstallationIdentity(installation.active,body.source,body.destination)};plan=planSchema.parse({...frozen,fingerprint:sha256(canonicalLocalJson(frozen)),phase:"PREPARED"});await save("PREPARED");await write(join3(root,"current.json"),canonicalLocalJson(plan.id));return present(plan)}plan=await readStoragePlan(root,call.id);if(!plan||plan.fingerprint!==call.fingerprint)fail("PLAN_CHANGED");if(["COMPLETE","CANCELLED"].includes(plan.phase))return present(plan);if(call.action==="abandon"){await save("CANCELLED");return present(plan)}if(!installation.active||installation.transition)fail("RECOVERY_REQUIRED");if(await storageInstallationIdentity(installation.active,plan.source,plan.destination)!==plan.installationFingerprint)fail("PLAN_CHANGED");if(config.stateDirectory!==plan.source&&!(plan.mode==="MIGRATE"&&config.stateDirectory===plan.destination))fail("PLAN_CHANGED");if(plan.phase==="PREPARED"){if(Date.parse(plan.expiresAt)<=Date.now()||installation.revision!==plan.installationRevision)fail("PLAN_CHANGED");const client=await ownerClient(plan.source),inventory=await client.inventory();if(inventory.runtimeRevision!==plan.runtimeRevision)fail("REVISION_CONFLICT");await save("DRAINING");await manager.stop()}if(plan.phase==="DRAINING"){await waitStopped(plan.source);if(!await socketAbsent(plan.source))fail("RECOVERY_REQUIRED");await save("COPYING")}if(plan.phase==="COPYING"){if(!await socketAbsent(plan.source))fail("RECOVERY_REQUIRED");const copied=await copyStorage(plan.source,plan.destination);await write(join3(plan.destination,"backup-manifest.json"),canonicalLocalJson({protocol:"NVS_STORAGE_COPY_V1",planId:plan.id,...copied}));await save("COPIED",{bytes:copied.total})}if(plan.phase==="COPIED"){if(plan.mode==="MIGRATE"){if(installation.active.toolsConfigPath){const tools=LocalToolSelectionSchema.parse(JSON.parse((await read(installation.active.toolsConfigPath,32768)).toString()));if(tools.mode==="MANAGED"){for(const name of["ffmpeg","ffprobe"]){if(tools[name].path.startsWith(plan.source+sep3))tools[name].path=plan.destination+tools[name].path.slice(plan.source.length);else if(!tools[name].path.startsWith(plan.destination+sep3)||installation.active.toolsConfigPath!==join3(root,plan.id+"-tools.json"))fail("PLAN_CHANGED")}const toolsConfigPath=join3(root,plan.id+"-tools.json");await write(toolsConfigPath,canonicalLocalJson(tools));if(installation.active.toolsConfigPath!==toolsConfigPath)await manager.ledger.commit(installation,{active:{...installation.active,toolsConfigPath},transition:null})}}await manager.configure({...config,stateDirectory:plan.destination});await disableDesktopAutomation(home)}await save("VERIFYING")}if(plan.phase==="VERIFYING"){await manager.start();config=await manager.configuration();const inventory=await(await ownerClient(config.stateDirectory)).inventory();installation=(await manager.ledger.current()).value;if(canonicalLocalJson(inventory.descriptor)!==canonicalLocalJson(installation.active.descriptor))fail("STORAGE_COPY_INVALID");await save("COMPLETE")}return present(plan)}import{z as z3}from"zod";var DesktopOfflineRequestSchema=z3.strictObject({operation:z3.literal("offline"),call:LocalOfflineCallSchema});var DesktopOfflineReplySchema=LocalOfflinePageSchema;async function runDesktopOfflineRequest(home,raw){const{call}=DesktopOfflineRequestSchema.parse(raw),manager=await LocalInstallationManager.open(home),c=await manager.configuration();if(!(await manager.status()).running){const policy=await desktopAutomation(home),installation=await desktopInstallationIdentity(manager);if(!policy?.enabled||policy.installationFingerprint!==installation?.fingerprint||!await socketAbsent(c.stateDirectory))fail("RUNTIME_STATUS_REQUIRED");await manager.start()}const client=await ownerClient(c.stateDirectory);return LocalOfflinePageSchema.parse(await client.call({operation:"offline.workspace",input:call}))}import{z as z4}from"zod";import{join as join4}from"node:path";import{unlink as unlink2}from"node:fs/promises";var sha=z4.string().regex(/^[a-f0-9]{64}$/);var historyItem=z4.strictObject({id:z4.uuid(),projectId:z4.uuid(),productionId:z4.uuid(),kind:z4.enum(["IMAGE","VIDEO","ROUGH_CUT","PROGRAMMATIC"]),mediaFileId:z4.uuid().optional()});var stateSchema=z4.strictObject({grantFingerprint:sha.nullable(),pendingGrant:sha.nullable(),history:z4.array(historyItem).max(200)});var DesktopAgentRequestSchema=z4.strictObject({operation:z4.literal("agent"),scope:DesktopDeviceScopeSchema,call:z4.discriminatedUnion("action",[z4.strictObject({action:z4.literal("discover"),binary:z4.string().min(1).max(4096).optional()}),z4.strictObject({action:z4.literal("probe")}),z4.strictObject({action:z4.literal("grant"),grant:LocalAgentGrantSchema,approval:sha}),z4.strictObject({action:z4.literal("revoke")}),z4.strictObject({action:z4.literal("prepare"),snapshot:LocalAgentSnapshotSchema}),z4.strictObject({action:z4.literal("stage"),id:z4.uuid(),mediaFileId:z4.uuid().optional()}),z4.strictObject({action:z4.literal("start"),id:z4.uuid(),expectedRevision:z4.int().positive(),approval:sha}),z4.strictObject({action:z4.literal("inspect"),id:z4.uuid()})])});var DesktopAgentReplySchema=z4.strictObject({probe:LocalAgentProbeSchema.optional(),discovery:LocalAgentDiscoverySchema.optional(),review:LocalAgentReviewViewSchema.optional(),history:z4.array(historyItem.omit({mediaFileId:true}).extend({pendingMedia:z4.boolean()})).max(200),pendingGrant:z4.boolean()});async function runDesktopAgentRequest(home,raw){const{scope,call}=DesktopAgentRequestSchema.parse(raw),root=await directory(join4(home,"agent-owner",sha256(canonicalLocalJson(scope)))),path=join4(root,"current.json");let state=stateSchema.parse(await optional(path)??{grantFingerprint:null,pendingGrant:null,history:[]});const manager=await LocalInstallationManager.open(home),client=await ownerClient((await manager.configuration()).stateDirectory);const save=async value=>{state=stateSchema.parse({...state,...value});await write(path,canonicalLocalJson(state))};const result=fields=>DesktopAgentReplySchema.parse({...fields,history:state.history.map(({mediaFileId,...r})=>{return{...r,pendingMedia:!!mediaFileId}}),pendingGrant:!!state.pendingGrant});if(call.action==="discover"){const discovery=await client.discoverAgent(call.binary);const fp=discovery.configured?sha256(canonicalLocalJson(discovery.configured)):null;if(state.pendingGrant&&state.pendingGrant===fp)await save({grantFingerprint:fp,pendingGrant:null});return result({discovery:{...discovery,configured:fp===state.grantFingerprint?discovery.configured:null}})}if(call.action==="probe"){const probe=await client.probeAgent();if(state.pendingGrant&&probe.grantFingerprint===state.pendingGrant)await save({grantFingerprint:state.pendingGrant,pendingGrant:null});return result({probe:probe.grantFingerprint===state.grantFingerprint?probe:{...probe,available:false,configured:false,reason:"GRANT_REQUIRED",grantFingerprint:null}})}if(call.action==="grant"){if(state.pendingGrant)fail("AGENT_OUTCOME_UNKNOWN");if(call.grant.projects.some(p=>p.tenantId!==scope.tenantId)||sha256(canonicalLocalJson(call.grant))!==call.approval)fail("AGENT_APPROVAL_REQUIRED");await save({pendingGrant:call.approval});let probe;try{probe=await client.grantAgent(call.grant,call.approval)}catch(e){if(e instanceof NativeStudioSdkError&&["NO_WRITE","REJECTED"].includes(e.outcome))await save({pendingGrant:null});throw e}await save({pendingGrant:null,grantFingerprint:call.approval});return result({probe})}if(call.action==="revoke"){const probe=await client.probeAgent();if(!state.grantFingerprint||probe.grantFingerprint!==state.grantFingerprint)fail("AGENT_APPROVAL_REQUIRED");const revoked=await client.revokeAgent(state.grantFingerprint);await save({grantFingerprint:null,pendingGrant:null});return result({probe:revoked})}if(call.action==="prepare"){if(state.history.length>=200)fail("QUERY_LIMIT");if(state.pendingGrant||!state.grantFingerprint||call.snapshot.basis.scope.tenantId!==scope.tenantId)fail("AGENT_APPROVAL_REQUIRED");const review=await client.prepareAgentReview(call.snapshot);if(review.plan.grantFingerprint!==state.grantFingerprint)fail("AGENT_APPROVAL_REQUIRED");const s2=review.plan.snapshot.basis.scope;await save({history:[{id:review.plan.id,projectId:s2.projectId,productionId:s2.productionId,kind:review.plan.snapshot.basis.target.kind},...state.history]});return result({review})}const entry=state.history.find(h=>h.id===call.id);if(!entry)fail("AGENT_APPROVAL_REQUIRED");const original=await client.inspectAgentReview(call.id),s=original.plan.snapshot.basis.scope;if(s.tenantId!==scope.tenantId||s.projectId!==entry.projectId||s.productionId!==entry.productionId)fail("AGENT_APPROVAL_REQUIRED");const staged=!!(original.imageReceipt||original.evidenceReceipt);if(staged&&entry.mediaFileId){const file=join4(home,"agent-import",entry.mediaFileId+".bin");try{const bytes=await read(file,134217728);if(sha256(bytes)!==original.plan.snapshot.media.checksumSha256)fail("AGENT_IMAGE_INVALID");await unlink2(file)}catch(e){if(e.code!=="ENOENT")throw e}await save({history:state.history.map(h=>{if(h.id!==call.id)return h;const{mediaFileId,...item}=h;void mediaFileId;return item})})}if(call.action==="inspect"||call.action==="stage"&&staged)return result({review:original});if(call.action==="stage"){const mediaFileId=call.mediaFileId??entry.mediaFileId;if(!mediaFileId)fail("AGENT_IMAGE_REQUIRED");await save({history:state.history.map(h=>h.id===call.id?{...h,mediaFileId}:h)});const file=join4(home,"agent-import",mediaFileId+".bin"),bytes=await read(file,134217728);const review=await client.stageAgentImage(call.id,bytes);await unlink2(file);await save({history:state.history.map(h=>{if(h.id!==call.id)return h;const{mediaFileId:_id,...rest}=h;void _id;return rest})});return result({review})}if(state.pendingGrant||original.plan.grantFingerprint!==state.grantFingerprint)fail("AGENT_APPROVAL_REQUIRED");return result({review:await client.startAgentReview(call.id,call.expectedRevision,call.approval)})}import{z as z5}from"zod";var digest2=z5.string().regex(/^[a-f0-9]{64}$/);var DesktopBootstrapRequestSchema=z5.strictObject({operation:z5.literal("bootstrap"),call:z5.discriminatedUnion("action",[z5.strictObject({action:z5.literal("prepare")}),z5.strictObject({action:z5.literal("apply"),id:z5.uuid(),fingerprint:digest2})])});var DesktopBootstrapReplySchema=z5.strictObject({id:z5.uuid(),fingerprint:digest2,version:z5.string().min(1).max(80),host:z5.string().min(1).max(512),bytes:z5.int().positive(),expiresAt:z5.iso.datetime(),installed:z5.boolean()});import{z as z6}from"zod";var DesktopWorkspaceRequestSchema=z6.strictObject({operation:z6.literal("workspace"),call:z6.discriminatedUnion("action",[z6.strictObject({action:z6.enum(["inspect","clean","diagnostics"])}),z6.strictObject({action:z6.literal("configure"),policy:LocalResourcePolicySchema,expectedRevision:z6.int().nonnegative()}),z6.strictObject({action:z6.literal("activity"),idleSeconds:z6.int().min(0).max(86400),observedAt:z6.iso.datetime()})])});var DesktopWorkspaceReplySchema=z6.union([LocalWorkspaceInspectionSchema,LocalDiagnosticsSchema]);async function runDesktopWorkspaceRequest(home,raw){const request=DesktopWorkspaceRequestSchema.parse(raw);const manager=await LocalInstallationManager.open(home);const config=await manager.configuration();const client=await ownerClient(config.stateDirectory);const input=request.call;switch(input.action){case"inspect":return client.workspace.inspect();case"clean":return client.workspace.clean();case"diagnostics":return client.workspace.diagnostics();case"configure":return client.workspace.configure(input.policy,input.expectedRevision);case"activity":return client.workspace.observeActivity(input.idleSeconds,input.observedAt)}}var version=LocalRuntimeDescriptorSchema.shape.version;var fingerprint=z7.string().regex(/^[a-f0-9]{64}$/);var DesktopRuntimeChannelSchema=z7.strictObject({protocol:z7.literal("NVS_DESKTOP_RUNTIME_CHANNEL_V1"),catalogueUrl:z7.string().url().max(4096),publicKey:z7.string().min(32).max(16384)});var DesktopOwnerRequestSchema=z7.discriminatedUnion("operation",[DesktopLibraryRequestSchema,DesktopLibraryImportRequestSchema,DesktopLibraryPrepareRequestSchema,DesktopDeviceRequestSchema,DesktopWorkspaceRequestSchema,DesktopStorageRequestSchema,DesktopOfflineRequestSchema,DesktopAgentRequestSchema,DesktopBootstrapRequestSchema,z7.strictObject({operation:z7.literal("speech-prepare"),input:CpuSpeechPrepareInputSchema}),z7.strictObject({operation:z7.enum(["status","start","stop","check","configuration","recovery"])}),z7.strictObject({operation:z7.enum(["prepare","reject"]),version}),z7.strictObject({operation:z7.literal("tools-prepare"),version,choice:z7.discriminatedUnion("mode",[z7.strictObject({mode:z7.literal("MANAGED")}),z7.strictObject({mode:z7.literal("INSTALLED"),ffmpeg:z7.string().min(1).max(4096),ffprobe:z7.string().min(1).max(4096),compositionBrowser:z7.string().min(1).max(4096).optional()})])}),z7.strictObject({operation:z7.literal("configure"),channelFingerprint:fingerprint}),z7.strictObject({operation:z7.enum(["apply","recover"]),planId:z7.uuid(),fingerprint})]);var DesktopRuntimeStatusSchema=z7.strictObject({protocol:z7.literal("NVS_DESKTOP_RUNTIME_STATUS_V1"),state:z7.enum(["RUNNING","STOPPED","UNAVAILABLE","INSTALL_REQUIRED"]),activeVersion:version.nullable(),phase:z7.string().regex(/^[A-Z_]{1,64}$/),toolMode:z7.enum(["MANAGED","INSTALLED"]).nullable().optional(),speech:z7.strictObject({voiceIds:CpuSpeechPrepareInputSchema.shape.voiceIds}).optional()});var DesktopUpdateCheckSchema=z7.strictObject({protocol:z7.literal("NVS_DESKTOP_RUNTIME_UPDATES_V1"),activeVersion:version.nullable(),versions:z7.array(z7.strictObject({version,rejected:z7.boolean()})).max(128),notifications:z7.boolean()});var DesktopOwnerPlanSchema=z7.strictObject({protocol:z7.literal("NVS_DESKTOP_OWNER_PLAN_V1"),plan:z7.strictObject({kind:z7.enum(["APPLY","RECOVER"]),toolMode:z7.enum(["MANAGED","INSTALLED"]).optional(),planId:z7.uuid(),fingerprint,version,previousVersion:version.nullable(),expiresAt:z7.iso.datetime(),phase:z7.string().regex(/^[A-Z_]{1,64}$/)}).nullable()});var DesktopChannelInfoSchema=z7.strictObject({protocol:z7.literal("NVS_DESKTOP_CHANNEL_INFO_V1"),configured:z7.boolean(),source:z7.enum(["EXISTING","BUNDLED","UNAVAILABLE"]),host:z7.string().max(512).nullable(),channelFingerprint:fingerprint.nullable()});var desktopOwnerResponses={library:DesktopLibraryReplySchema,"library-import":DesktopLibraryReplySchema,"library-import-prepare":DesktopLibraryImportRequestSchema,device:DesktopDeviceReplySchema,workspace:DesktopWorkspaceReplySchema,storage:DesktopStorageReplySchema,offline:DesktopOfflineReplySchema,agent:DesktopAgentReplySchema,bootstrap:DesktopBootstrapReplySchema,status:DesktopRuntimeStatusSchema,start:DesktopRuntimeStatusSchema,stop:DesktopRuntimeStatusSchema,configure:DesktopRuntimeStatusSchema,apply:DesktopRuntimeStatusSchema,recover:DesktopRuntimeStatusSchema,reject:DesktopRuntimeStatusSchema,check:DesktopUpdateCheckSchema,configuration:DesktopChannelInfoSchema,prepare:DesktopOwnerPlanSchema,"tools-prepare":DesktopOwnerPlanSchema,"speech-prepare":DesktopOwnerPlanSchema,recovery:DesktopOwnerPlanSchema};async function desktopRuntimeStatus(manager){const status=await manager.status();const stopped=!status.running&&status.activeVersion?await socketAbsent((await manager.configuration()).stateDirectory):false;const active=(await manager.ledger.current()).value.active;const tools=active?.toolsConfigPath?await toolPreference(active.toolsConfigPath,null):null;return DesktopRuntimeStatusSchema.parse({protocol:"NVS_DESKTOP_RUNTIME_STATUS_V1",state:status.running?"RUNNING":stopped?"STOPPED":status.activeVersion?"UNAVAILABLE":"INSTALL_REQUIRED",activeVersion:status.activeVersion,phase:status.phase,toolMode:tools?.mode??null,...tools?.cpuSpeech?{speech:{voiceIds:tools.cpuSpeech.voiceIds}}:{}})}import{createPublicKey}from"node:crypto";import{join as join5}from"node:path";function desktopRuntimeChannel(raw){const channel=DesktopRuntimeChannelSchema.parse(raw);const url=endpoint(channel.catalogueUrl),key=createPublicKey(channel.publicKey);if(key.asymmetricKeyType!=="ed25519"||channel.publicKey.replace(/\r\n/g,"\n").trim()!==key.export({type:"spki",format:"pem"}).toString().trim())fail("RELEASE_SIGNATURE_INVALID");const value={...channel,catalogueUrl:url.href,publicKey:key.export({type:"spki",format:"pem"}).toString()};return{value,host:url.host,fingerprint:sha256(canonicalLocalJson(value))}}async function desktopChannelInfo(manager,bundled){let channel,configured=false;try{const config=await manager.configuration();if(!config.catalogueUrl||!config.publicKeyFile)fail("DEPENDENCY_CHANNEL_REQUIRED");channel=desktopRuntimeChannel({protocol:"NVS_DESKTOP_RUNTIME_CHANNEL_V1",catalogueUrl:config.catalogueUrl,publicKey:(await read(config.publicKeyFile,16384)).toString()});configured=true}catch(error){if(!(error instanceof LocalClientError&&["CONFIGURATION_REQUIRED","DEPENDENCY_CHANNEL_REQUIRED"].includes(error.code)))throw error;if(bundled!==void 0)channel=desktopRuntimeChannel(bundled)}return DesktopChannelInfoSchema.parse({protocol:"NVS_DESKTOP_CHANNEL_INFO_V1",configured,source:configured?"EXISTING":channel?"BUNDLED":"UNAVAILABLE",host:channel?.host??null,channelFingerprint:channel?.fingerprint??null})}async function configureDesktopChannel(manager,expectedFingerprint,bundled){const info=await desktopChannelInfo(manager,bundled);if(!info.channelFingerprint)fail("DESKTOP_CHANNEL_REQUIRED");if(info.channelFingerprint!==expectedFingerprint)fail("DESKTOP_CHANNEL_CHANGED");if(info.configured)return;let existing;try{existing=await manager.configuration()}catch(e){if(!(e instanceof LocalClientError&&e.code==="CONFIGURATION_REQUIRED"))throw e}const stateDirectory=existing?.stateDirectory??join5(manager.ledger.root,"runtime-state");if(process.platform!=="win32"&&Buffer.byteLength(join5(stateDirectory,"runtime.sock"))>100)fail("SOCKET_PATH_TOO_LONG");const channel=desktopRuntimeChannel(bundled),publicKeyFile=join5(manager.ledger.root,"desktop-release-"+channel.fingerprint+".pem");try{await write(publicKeyFile,channel.value.publicKey,true)}catch(error){if(error.code!=="EEXIST")throw error;if((await read(publicKeyFile,16384)).toString()!==channel.value.publicKey)fail("DESKTOP_CHANNEL_CHANGED")}try{await manager.configure({...existing,stateDirectory,catalogueUrl:channel.value.catalogueUrl,publicKeyFile,notifications:true},{ifAbsent:!existing})}catch(error){if(error.code==="EEXIST")fail("DESKTOP_CHANNEL_CHANGED");throw error}}import{z as z8}from"zod";import{join as join6}from"node:path";import{randomUUID as randomUUID2}from"node:crypto";var digest3=z8.string().regex(/^[a-f0-9]{64}$/);var intentSchema=z8.strictObject({id:z8.uuid(),channel:z8.strictObject({protocol:z8.literal("NVS_DESKTOP_RUNTIME_CHANNEL_V1"),catalogueUrl:z8.string().url(),publicKey:z8.string()}),release:LocalReleaseSchema,installationRevision:z8.int().nonnegative(),expiresAt:z8.iso.datetime()});async function runDesktopBootstrap(home,raw,bundled){const{call}=DesktopBootstrapRequestSchema.parse(raw),manager=await LocalInstallationManager.open(home),root=await directory(join6(home,"bootstrap-plans"));let intent2,fingerprint2;if(call.action==="prepare"){const info=await desktopChannelInfo(manager,bundled);if(!info.channelFingerprint)fail("DESKTOP_CHANNEL_REQUIRED");const configuration=info.configured?await manager.configuration():null;if(configuration&&!configuration.publicKeyFile)fail("DESKTOP_CHANNEL_CHANGED");const channel=desktopRuntimeChannel(configuration?{protocol:"NVS_DESKTOP_RUNTIME_CHANNEL_V1",catalogueUrl:configuration.catalogueUrl,publicKey:(await read(configuration.publicKeyFile,16384)).toString()}:bundled);const publicKeyFile=join6(root,channel.fingerprint+".pem");try{await write(publicKeyFile,channel.value.publicKey,true)}catch(e){if(e.code!=="EEXIST"||(await read(publicKeyFile,16384)).toString()!==channel.value.publicKey)throw e}const trusted=await catalogue({catalogueUrl:channel.value.catalogueUrl,publicKeyFile});const candidates=trusted.signed.catalogue.releases.filter(r=>r.descriptor.workProtocol==="NVS_LOCAL_WORK_V2"&&r.descriptor.platform.os===process.platform&&r.descriptor.platform.architecture===process.arch&&!!r.tools);const release=candidates.reduce((a,b)=>!a||newerVersion(b.descriptor.version,a.descriptor.version)?b:a,null);if(!release)fail("LOCAL_PROFILE_UNAVAILABLE");intent2=intentSchema.parse({id:randomUUID2(),channel:channel.value,release,installationRevision:(await manager.ledger.current()).value.revision,expiresAt:new Date(Math.min(Date.now()+18e5,Date.parse(trusted.signed.catalogue.expiresAt))).toISOString()});fingerprint2=sha256(canonicalLocalJson(intent2));await write(join6(root,intent2.id+".json"),canonicalLocalJson({intent:intent2,fingerprint:fingerprint2}),true)}else{const saved=z8.strictObject({intent:intentSchema,fingerprint:digest3}).parse(JSON.parse((await read(join6(root,call.id+".json"),131072)).toString()));intent2=saved.intent;fingerprint2=saved.fingerprint;if(fingerprint2!==call.fingerprint||fingerprint2!==sha256(canonicalLocalJson(intent2))||intent2.id!==call.id)fail("PLAN_CHANGED");const receiptFile=join6(root,intent2.id+".installation.json");const receipt=z8.strictObject({id:z8.uuid(),fingerprint:digest3}).nullable().parse(await optional(receiptFile));if(receipt){const state=(await manager.ledger.current()).value;if(state.transition){if(state.transition.planId!==receipt.id)fail("RECOVERY_REQUIRED");await manager.reconcile(receipt.id,receipt.fingerprint)}}else{if(Date.parse(intent2.expiresAt)<=Date.now()||(await manager.ledger.current()).value.revision!==intent2.installationRevision)fail("PLAN_CHANGED");const trust=desktopRuntimeChannel(intent2.channel);await configureDesktopChannel(manager,trust.fingerprint,intent2.channel);const plan=await manager.prepare(intent2.release.descriptor.version,{mode:"MANAGED"});if(canonicalLocalJson(plan.release)!==canonicalLocalJson(intent2.release))fail("PLAN_CHANGED");await write(receiptFile,canonicalLocalJson({id:plan.planId,fingerprint:plan.fingerprint}),true);await manager.apply(plan.planId,plan.fingerprint)}const installed=(await manager.ledger.current()).value;if(installed.transition||canonicalLocalJson(installed.active?.descriptor)!==canonicalLocalJson(intent2.release.descriptor))fail("RECOVERY_REQUIRED");const configuration=await manager.configuration(),report=await(await ownerClient(configuration.stateDirectory)).doctor();if(!report.executionProfiles?.includes("STUDIO_MEDIA_V2"))fail("LOCAL_PROFILE_UNAVAILABLE");if((await desktopRuntimeStatus(manager)).state!=="RUNNING")fail("RECOVERY_REQUIRED")}return DesktopBootstrapReplySchema.parse({id:intent2.id,fingerprint:fingerprint2,version:intent2.release.descriptor.version,host:new URL(intent2.channel.catalogueUrl).host,bytes:intent2.release.package.byteSize+Object.values(intent2.release.tools??{}).reduce((sum,a)=>sum+a.byteSize,0),expiresAt:intent2.expiresAt,installed:call.action==="apply"})}async function runDesktopOwnerRequest(home,raw,bundledChannel){const request=DesktopOwnerRequestSchema.parse(raw),manager=await LocalInstallationManager.open(home);let result;switch(request.operation){case"library":result=await runDesktopLibraryRequest(home,request);break;case"library-import":result=await runDesktopLibraryImport(home,request);break;case"library-import-prepare":result=await prepareDesktopLibraryImport(request);break;case"bootstrap":result=await runDesktopBootstrap(home,request,bundledChannel);break;case"agent":result=await runDesktopAgentRequest(home,request);break;case"offline":result=await runDesktopOfflineRequest(home,request);break;case"storage":result=await runDesktopStorageRequest(home,request);break;case"workspace":result=await runDesktopWorkspaceRequest(home,request);break;case"device":result=await runDesktopDeviceRequest(home,request);break;case"status":case"start":case"stop":if(request.operation==="start")await manager.start();if(request.operation==="stop"){await disableDesktopAutomation(home);await manager.stop()}result=await desktopRuntimeStatus(manager);break;case"configuration":result=await desktopChannelInfo(manager,bundledChannel);break;case"configure":await configureDesktopChannel(manager,request.channelFingerprint,bundledChannel);result=await desktopRuntimeStatus(manager);break;case"check":{const checked=await manager.check();result={protocol:"NVS_DESKTOP_RUNTIME_UPDATES_V1",activeVersion:checked.installation.activeVersion,versions:checked.available.map(v=>({version:v.version,rejected:checked.rejectedVersions.includes(v.version)})),notifications:checked.notifications};break}case"speech-prepare":{const prepared=await prepareInstalledCpuSpeech(manager,request.input),plan=prepared.plan;result={protocol:"NVS_DESKTOP_OWNER_PLAN_V1",plan:{kind:"APPLY",toolMode:plan.toolSelection?.mode,planId:plan.planId,fingerprint:plan.fingerprint,version:plan.release.descriptor.version,previousVersion:(await manager.status()).activeVersion,expiresAt:plan.expiresAt,phase:"PREPARED"}};break}case"prepare":case"tools-prepare":{const choice=request.operation==="tools-prepare"?request.choice.mode==="MANAGED"?request.choice:await captureInstalledTools(request.choice):void 0;const plan=await manager.prepare(request.version,choice);result={protocol:"NVS_DESKTOP_OWNER_PLAN_V1",plan:{kind:"APPLY",...choice?{toolMode:choice.mode}:{},planId:plan.planId,fingerprint:plan.fingerprint,version:plan.release.descriptor.version,previousVersion:(await manager.status()).activeVersion,expiresAt:plan.expiresAt,phase:"PREPARED"}};break}case"recovery":{const current=(await manager.ledger.current()).value,transition=current.transition;let plan=null;if(transition){const original=await manager.plan(transition.planId);if(original.fingerprint!==transition.fingerprint)fail("PLAN_CHANGED");plan={kind:"RECOVER",planId:original.planId,fingerprint:original.fingerprint,version:original.release.descriptor.version,previousVersion:transition.previous?.descriptor.version??null,expiresAt:original.expiresAt,phase:transition.phase}}result={protocol:"NVS_DESKTOP_OWNER_PLAN_V1",plan};break}case"apply":case"recover":if(request.operation==="apply")await manager.apply(request.planId,request.fingerprint);else await manager.reconcile(request.planId,request.fingerprint);result=await desktopRuntimeStatus(manager);break;case"reject":await manager.reject(request.version);result=await desktopRuntimeStatus(manager);break}return desktopOwnerResponses[request.operation].parse(result)}import{lstat as lstat3,readFile,chmod as chmod2}from"node:fs/promises";import{join as join7,isAbsolute,dirname}from"node:path";async function verifiedSource(source,expected,limit){if(!isAbsolute(source)||!/^[a-f0-9]{64}$/.test(expected))fail("DESKTOP_DISTRIBUTION_INVALID");const stat=await lstat3(source);if(!stat.isFile()||stat.isSymbolicLink()||stat.size>limit)fail("DESKTOP_DISTRIBUTION_INVALID");const bytes=await readFile(source);if(bytes.length>limit||sha256(bytes)!==expected)fail("DESKTOP_DISTRIBUTION_INVALID");return bytes}async function retain(target,bytes,expected,limit,mode){try{if(sha256(await read(target,limit))!==expected)fail("DESKTOP_DISTRIBUTION_INVALID")}catch(error){if(error.code!=="ENOENT")throw error;try{await write(target,bytes,true)}catch(error2){if(error2.code!=="EEXIST")throw error2}if(sha256(await read(target,limit))!==expected)fail("DESKTOP_DISTRIBUTION_INVALID")}await chmod2(target,mode)}async function materializeDesktopNode(home,source,expected,licenseDigest){const bytes=await verifiedSource(source,expected,160*1024*1024);const license=licenseDigest?await verifiedSource(join7(dirname(source),"LICENSE.txt"),licenseDigest,2*1024*1024):null;const base=await directory(join7(await directory(home),"nodes",expected)),target=join7(base,process.platform==="win32"?"node.exe":"node");if(license)await retain(join7(base,"LICENSE.txt"),license,licenseDigest,2*1024*1024,256);await retain(target,bytes,expected,160*1024*1024,320);return target}async function runLocalManagement(home,operation){if(!["status","start","stop"].includes(operation))throw Error("INVALID_INPUT");const manager=await LocalInstallationManager.open(home);if(operation==="start")await manager.start();if(operation==="stop")await manager.stop();return desktopRuntimeStatus(manager)}export{DesktopDeviceReplySchema,DesktopDeviceScopeSchema,DesktopLibraryImportRequestSchema,DesktopLibraryImportSeedSchema,DesktopLibraryMediaRequestSchema,DesktopLibraryPrepareRequestSchema,DesktopLibraryReplySchema,DesktopLibraryRequestSchema,DesktopOwnerRequestSchema,desktopDeviceConnector,desktopDevicePending,desktopOwnerResponses,desktopRuntimeChannel,materializeDesktopNode,prepareDesktopLibraryImport,runDesktopLibraryMedia,runDesktopOwnerRequest,runLocalManagement};
|
|
1
|
+
import{prepareInstalledCpuSpeech}from"./_chunks/chunk-AIR7YOFU.js";import{configureDesktopChannel,desktopChannelInfo,desktopRuntimeChannel}from"./_chunks/chunk-2GV47BUV.js";import{DesktopBootstrapReplySchema,DesktopBootstrapRequestSchema,DesktopOwnerRequestSchema,DesktopRuntimeStatusSchema,desktopOwnerResponses,runDesktopAgentRequest,runDesktopOfflineRequest,runDesktopStorageRequest,runDesktopWorkspaceRequest}from"./_chunks/chunk-WXEERCXN.js";import{DesktopLibraryImportRequestSchema,DesktopLibraryImportSeedSchema,DesktopLibraryMediaRequestSchema,DesktopLibraryPrepareRequestSchema,DesktopLibraryReplySchema,DesktopLibraryRequestSchema,prepareDesktopLibraryImport,runDesktopLibraryImport,runDesktopLibraryMedia,runDesktopLibraryRequest}from"./_chunks/chunk-HIBT6NXN.js";import{desktopDevicePending,runDesktopDeviceRequest}from"./_chunks/chunk-67QDMD7M.js";import"./_chunks/chunk-GQ32ZQTM.js";import{disableDesktopAutomation}from"./_chunks/chunk-J2IYRUVM.js";import{LocalInstallationManager,captureInstalledTools,ownerClient,socketAbsent,toolPreference}from"./_chunks/chunk-IF6AUKH3.js";import{desktopDeviceConnector}from"./_chunks/chunk-BZPQB66Z.js";import{DesktopDeviceReplySchema,DesktopDeviceScopeSchema}from"./_chunks/chunk-5TKBEFRX.js";import{LocalReleaseSchema,catalogue,newerVersion}from"./_chunks/chunk-CTCEGOC7.js";import{canonicalLocalJson}from"./_chunks/chunk-LZPPTW2K.js";import{directory,fail,optional,read,sha256,write}from"./_chunks/chunk-DLW42PJ6.js";import"./_chunks/chunk-WTJVS2VS.js";import"./_chunks/chunk-TT7IA5HB.js";async function desktopRuntimeStatus(manager){const status=await manager.status();const stopped=!status.running&&status.activeVersion?await socketAbsent((await manager.configuration()).stateDirectory):false;const active=(await manager.ledger.current()).value.active;const tools=active?.toolsConfigPath?await toolPreference(active.toolsConfigPath,null):null;return DesktopRuntimeStatusSchema.parse({protocol:"NVS_DESKTOP_RUNTIME_STATUS_V1",state:status.running?"RUNNING":stopped?"STOPPED":status.activeVersion?"UNAVAILABLE":"INSTALL_REQUIRED",activeVersion:status.activeVersion,phase:status.phase,toolMode:tools?.mode??null,...tools?.cpuSpeech?{speech:{voiceIds:tools.cpuSpeech.voiceIds}}:{}})}import{z}from"zod";import{join}from"node:path";import{randomUUID}from"node:crypto";var digest=z.string().regex(/^[a-f0-9]{64}$/);var intentSchema=z.strictObject({id:z.uuid(),channel:z.strictObject({protocol:z.literal("NVS_DESKTOP_RUNTIME_CHANNEL_V1"),catalogueUrl:z.string().url(),publicKey:z.string()}),release:LocalReleaseSchema,installationRevision:z.int().nonnegative(),expiresAt:z.iso.datetime()});async function runDesktopBootstrap(home,raw,bundled){const{call}=DesktopBootstrapRequestSchema.parse(raw),manager=await LocalInstallationManager.open(home),root=await directory(join(home,"bootstrap-plans"));let intent,fingerprint;if(call.action==="prepare"){const info=await desktopChannelInfo(manager,bundled);if(!info.channelFingerprint)fail("DESKTOP_CHANNEL_REQUIRED");const configuration=info.configured?await manager.configuration():null;if(configuration&&!configuration.publicKeyFile)fail("DESKTOP_CHANNEL_CHANGED");const channel=desktopRuntimeChannel(configuration?{protocol:"NVS_DESKTOP_RUNTIME_CHANNEL_V1",catalogueUrl:configuration.catalogueUrl,publicKey:(await read(configuration.publicKeyFile,16384)).toString()}:bundled);const publicKeyFile=join(root,channel.fingerprint+".pem");try{await write(publicKeyFile,channel.value.publicKey,true)}catch(e){if(e.code!=="EEXIST"||(await read(publicKeyFile,16384)).toString()!==channel.value.publicKey)throw e}const trusted=await catalogue({catalogueUrl:channel.value.catalogueUrl,publicKeyFile});const candidates=trusted.signed.catalogue.releases.filter(r=>r.descriptor.workProtocol==="NVS_LOCAL_WORK_V2"&&r.descriptor.platform.os===process.platform&&r.descriptor.platform.architecture===process.arch&&!!r.tools);const release=candidates.reduce((a,b)=>!a||newerVersion(b.descriptor.version,a.descriptor.version)?b:a,null);if(!release)fail("LOCAL_PROFILE_UNAVAILABLE");intent=intentSchema.parse({id:randomUUID(),channel:channel.value,release,installationRevision:(await manager.ledger.current()).value.revision,expiresAt:new Date(Math.min(Date.now()+18e5,Date.parse(trusted.signed.catalogue.expiresAt))).toISOString()});fingerprint=sha256(canonicalLocalJson(intent));await write(join(root,intent.id+".json"),canonicalLocalJson({intent,fingerprint}),true)}else{const saved=z.strictObject({intent:intentSchema,fingerprint:digest}).parse(JSON.parse((await read(join(root,call.id+".json"),131072)).toString()));intent=saved.intent;fingerprint=saved.fingerprint;if(fingerprint!==call.fingerprint||fingerprint!==sha256(canonicalLocalJson(intent))||intent.id!==call.id)fail("PLAN_CHANGED");const receiptFile=join(root,intent.id+".installation.json");const receipt=z.strictObject({id:z.uuid(),fingerprint:digest}).nullable().parse(await optional(receiptFile));if(receipt){const state=(await manager.ledger.current()).value;if(state.transition){if(state.transition.planId!==receipt.id)fail("RECOVERY_REQUIRED");await manager.reconcile(receipt.id,receipt.fingerprint)}}else{if(Date.parse(intent.expiresAt)<=Date.now()||(await manager.ledger.current()).value.revision!==intent.installationRevision)fail("PLAN_CHANGED");const trust=desktopRuntimeChannel(intent.channel);await configureDesktopChannel(manager,trust.fingerprint,intent.channel);const plan=await manager.prepare(intent.release.descriptor.version,{mode:"MANAGED"});if(canonicalLocalJson(plan.release)!==canonicalLocalJson(intent.release))fail("PLAN_CHANGED");await write(receiptFile,canonicalLocalJson({id:plan.planId,fingerprint:plan.fingerprint}),true);await manager.apply(plan.planId,plan.fingerprint)}const installed=(await manager.ledger.current()).value;if(installed.transition||canonicalLocalJson(installed.active?.descriptor)!==canonicalLocalJson(intent.release.descriptor))fail("RECOVERY_REQUIRED");const configuration=await manager.configuration(),report=await(await ownerClient(configuration.stateDirectory)).doctor();if(!report.executionProfiles?.includes("STUDIO_MEDIA_V2"))fail("LOCAL_PROFILE_UNAVAILABLE");if((await desktopRuntimeStatus(manager)).state!=="RUNNING")fail("RECOVERY_REQUIRED")}return DesktopBootstrapReplySchema.parse({id:intent.id,fingerprint,version:intent.release.descriptor.version,host:new URL(intent.channel.catalogueUrl).host,bytes:intent.release.package.byteSize+Object.values(intent.release.tools??{}).reduce((sum,a)=>sum+a.byteSize,0),expiresAt:intent.expiresAt,installed:call.action==="apply"})}async function runDesktopOwnerRequest(home,raw,bundledChannel){const request=DesktopOwnerRequestSchema.parse(raw),manager=await LocalInstallationManager.open(home);let result;switch(request.operation){case"library":result=await runDesktopLibraryRequest(home,request);break;case"library-import":result=await runDesktopLibraryImport(home,request);break;case"library-import-prepare":result=await prepareDesktopLibraryImport(request);break;case"bootstrap":result=await runDesktopBootstrap(home,request,bundledChannel);break;case"agent":result=await runDesktopAgentRequest(home,request);break;case"offline":result=await runDesktopOfflineRequest(home,request);break;case"storage":result=await runDesktopStorageRequest(home,request);break;case"workspace":result=await runDesktopWorkspaceRequest(home,request);break;case"device":result=await runDesktopDeviceRequest(home,request);break;case"status":case"start":case"stop":if(request.operation==="start")await manager.start();if(request.operation==="stop"){await disableDesktopAutomation(home);await manager.stop()}result=await desktopRuntimeStatus(manager);break;case"configuration":result=await desktopChannelInfo(manager,bundledChannel);break;case"configure":await configureDesktopChannel(manager,request.channelFingerprint,bundledChannel);result=await desktopRuntimeStatus(manager);break;case"check":{const checked=await manager.check();result={protocol:"NVS_DESKTOP_RUNTIME_UPDATES_V1",activeVersion:checked.installation.activeVersion,versions:checked.available.map(v=>({version:v.version,rejected:checked.rejectedVersions.includes(v.version)})),notifications:checked.notifications};break}case"speech-prepare":{const prepared=await prepareInstalledCpuSpeech(manager,request.input),plan=prepared.plan;result={protocol:"NVS_DESKTOP_OWNER_PLAN_V1",plan:{kind:"APPLY",toolMode:plan.toolSelection?.mode,planId:plan.planId,fingerprint:plan.fingerprint,version:plan.release.descriptor.version,previousVersion:(await manager.status()).activeVersion,expiresAt:plan.expiresAt,phase:"PREPARED"}};break}case"prepare":case"tools-prepare":{const choice=request.operation==="tools-prepare"?request.choice.mode==="MANAGED"?request.choice:await captureInstalledTools(request.choice):void 0;const plan=await manager.prepare(request.version,choice);result={protocol:"NVS_DESKTOP_OWNER_PLAN_V1",plan:{kind:"APPLY",...choice?{toolMode:choice.mode}:{},planId:plan.planId,fingerprint:plan.fingerprint,version:plan.release.descriptor.version,previousVersion:(await manager.status()).activeVersion,expiresAt:plan.expiresAt,phase:"PREPARED"}};break}case"recovery":{const current=(await manager.ledger.current()).value,transition=current.transition;let plan=null;if(transition){const original=await manager.plan(transition.planId);if(original.fingerprint!==transition.fingerprint)fail("PLAN_CHANGED");plan={kind:"RECOVER",planId:original.planId,fingerprint:original.fingerprint,version:original.release.descriptor.version,previousVersion:transition.previous?.descriptor.version??null,expiresAt:original.expiresAt,phase:transition.phase}}result={protocol:"NVS_DESKTOP_OWNER_PLAN_V1",plan};break}case"apply":case"recover":if(request.operation==="apply")await manager.apply(request.planId,request.fingerprint);else await manager.reconcile(request.planId,request.fingerprint);result=await desktopRuntimeStatus(manager);break;case"reject":await manager.reject(request.version);result=await desktopRuntimeStatus(manager);break}return desktopOwnerResponses[request.operation].parse(result)}import{lstat,readFile,chmod}from"node:fs/promises";import{join as join2,isAbsolute,dirname}from"node:path";async function verifiedSource(source,expected,limit){if(!isAbsolute(source)||!/^[a-f0-9]{64}$/.test(expected))fail("DESKTOP_DISTRIBUTION_INVALID");const stat=await lstat(source);if(!stat.isFile()||stat.isSymbolicLink()||stat.size>limit)fail("DESKTOP_DISTRIBUTION_INVALID");const bytes=await readFile(source);if(bytes.length>limit||sha256(bytes)!==expected)fail("DESKTOP_DISTRIBUTION_INVALID");return bytes}async function retain(target,bytes,expected,limit,mode){try{if(sha256(await read(target,limit))!==expected)fail("DESKTOP_DISTRIBUTION_INVALID")}catch(error){if(error.code!=="ENOENT")throw error;try{await write(target,bytes,true)}catch(error2){if(error2.code!=="EEXIST")throw error2}if(sha256(await read(target,limit))!==expected)fail("DESKTOP_DISTRIBUTION_INVALID")}await chmod(target,mode)}async function materializeDesktopNode(home,source,expected,licenseDigest){const bytes=await verifiedSource(source,expected,160*1024*1024);const license=licenseDigest?await verifiedSource(join2(dirname(source),"LICENSE.txt"),licenseDigest,2*1024*1024):null;const base=await directory(join2(await directory(home),"nodes",expected)),target=join2(base,process.platform==="win32"?"node.exe":"node");if(license)await retain(join2(base,"LICENSE.txt"),license,licenseDigest,2*1024*1024,256);await retain(target,bytes,expected,160*1024*1024,320);return target}async function runLocalManagement(home,operation){if(!["status","start","stop"].includes(operation))throw Error("INVALID_INPUT");const manager=await LocalInstallationManager.open(home);if(operation==="start")await manager.start();if(operation==="stop")await manager.stop();return desktopRuntimeStatus(manager)}export{DesktopDeviceReplySchema,DesktopDeviceScopeSchema,DesktopLibraryImportRequestSchema,DesktopLibraryImportSeedSchema,DesktopLibraryMediaRequestSchema,DesktopLibraryPrepareRequestSchema,DesktopLibraryReplySchema,DesktopLibraryRequestSchema,DesktopOwnerRequestSchema,desktopDeviceConnector,desktopDevicePending,desktopOwnerResponses,desktopRuntimeChannel,materializeDesktopNode,prepareDesktopLibraryImport,runDesktopLibraryMedia,runDesktopOwnerRequest,runLocalManagement};
|
package/dist/local-navigation.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LocalMcpTools}from"./_chunks/chunk-
|
|
1
|
+
import{LocalMcpTools}from"./_chunks/chunk-JL4MUI7K.js";import{desktopDeviceConnector}from"./_chunks/chunk-BZPQB66Z.js";import{DesktopDeviceScopeSchema}from"./_chunks/chunk-5TKBEFRX.js";import"./_chunks/chunk-CTCEGOC7.js";import"./_chunks/chunk-LZPPTW2K.js";import"./_chunks/chunk-DLW42PJ6.js";import"./_chunks/chunk-WTJVS2VS.js";import"./_chunks/chunk-TT7IA5HB.js";async function openDesktopDeviceTools(raw,home){const scope=DesktopDeviceScopeSchema.parse(raw);return LocalMcpTools.open(await desktopDeviceConnector(home,scope),home)}export{LocalMcpTools,openDesktopDeviceTools};
|
package/package.json
CHANGED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{canResumeDesktop,desktopAutomation,desktopInstallationIdentity,rememberDesktopAutomation}from"./chunk-PYUYK3FV.js";import{connectDevice,generateDeviceKey}from"./chunk-MT5XZ67U.js";import{LocalInstallationManager,probeLocalLibrary,probeTenantComposition,probeTenantMediaProcessing,probeTenantMediaValidation,probeTenantSpeech,probeTenantTranscription,socketAbsent}from"./chunk-U6ZG2G7W.js";import{DesktopDeviceRecords,DesktopDeviceReplySchema,DesktopDeviceRequestSchema}from"./chunk-JLQCUXCT.js";import{LocalDeviceChallengeSchema,LocalDeviceSessionSchema,LocalDeviceTransportConfigurationSchema,LocalDeviceViewSchema,LocalFinalRenderAdmissionSchema,LocalManagementCommandSchema,LocalPreviewAdmissionSchema,canonicalLocalJson,processorFamilies}from"./chunk-WAADGZEV.js";import{fail,read,sha256}from"./chunk-RUPH3HZ2.js";import{createPrivateKey as createPrivateKey2,createPublicKey,randomUUID as randomUUID3}from"node:crypto";import{randomUUID}from"node:crypto";async function desktopDeviceCapabilities(manager){const active=(await manager.ledger.current()).value.active;if(!active)fail("INSTALL_REQUIRED");const root=manager.ledger.slotPath(active);const validation=await probeTenantMediaValidation(root,active);const processing=await probeTenantMediaProcessing(root,active);const processors=processing?Object.keys(processorFamilies).filter(kind=>!["COMPOSITION_RENDER","LOCAL_MEDIA_INSPECT","LOCAL_MEDIA_PUBLISH","SPEECH_SYNTHESIZE","TRANSCRIBE_AUDIO","KEYFRAME_GENERATE","VIDEO_GENERATE","SPEECH_EXTERNAL_QWEN","TRANSCRIBE_EXTERNAL_QWEN"].includes(kind)):[];if(processing){if(await probeLocalLibrary(root,active))processors.push("LOCAL_MEDIA_INSPECT","LOCAL_MEDIA_PUBLISH");if(await probeTenantComposition(root,active))processors.push("COMPOSITION_RENDER");if(await probeTenantSpeech(root,active))processors.push("SPEECH_SYNTHESIZE");if(await probeTenantTranscription(root,active))processors.push("TRANSCRIBE_AUDIO")}return{...validation?{tenantMediaValidation:true}:{},...processors.length?{tenantMediaProcessing:true,processorCapabilities:processors.sort()}:{}}}async function connectDesktopDevice(records,manager,s,expectedRevision){if(s.revision!==expectedRevision)fail("DEVICE_PLAN_CHANGED");if(s.connection?.phase==="CONNECTING")fail("DEVICE_CONNECTION_RECOVERY_REQUIRED");if(!s.device||s.device.revokedAt)fail("DEVICE_ENROLLMENT_REQUIRED");const capabilities=await desktopDeviceCapabilities(manager);const c=await manager.configuration();const previous=c.cloudConfigFile?JSON.parse((await read(c.cloudConfigFile,32768)).toString()):null;if(previous&&(previous.endpoint!==s.scope.origin||previous.tenantId!==s.scope.tenantId||previous.deviceId!==s.device.deviceId))fail("DEVICE_CONNECTION_CONFLICT");const running=(await manager.status()).running;if(!running&&!await socketAbsent(c.stateDirectory))fail("DEVICE_CONNECTION_RECOVERY_REQUIRED");const matches=value=>{const saved=value;return saved?.deviceRevision===s.device.revision&&saved.tenantMediaValidation===capabilities.tenantMediaValidation&&saved.tenantMediaProcessing===capabilities.tenantMediaProcessing&&canonicalLocalJson(saved.processorCapabilities??null)===canonicalLocalJson(capabilities.processorCapabilities??null)};const reuse=running&&matches(previous)&&matches(s.connection);const expiresAt=new Date(Date.now()+24*36e5).toISOString();s=await records.save(s,{connection:{phase:"CONNECTING",expiresAt,deviceRevision:s.device.revision,...capabilities}});if(!reuse){if(running)await manager.stop();await connectDevice(manager,{endpoint:s.scope.origin,tenantId:s.scope.tenantId,deviceId:s.device.deviceId,deviceRevision:s.device.revision,privateKeyFile:records.keyPath(),platform:s.device.platform,...capabilities});await manager.start()}const id=randomUUID();await manager.grant({tenantId:s.scope.tenantId,deviceId:s.device.deviceId,expiresAt},records.connectorPath(id));return records.save(s,{connectorId:id,connection:{...s.connection,phase:"CONNECTED"}})}async function recoverDesktopConnection(records,manager,s){if(s.connection?.phase!=="CONNECTING")return s;const c=await manager.configuration(),running=(await manager.status()).running;if(!running){if(!await socketAbsent(c.stateDirectory))fail("DEVICE_CONNECTION_RECOVERY_REQUIRED");return records.save(s,{connection:null,connectorId:null})}if(!c.cloudConfigFile||!s.device||s.device.revokedAt)fail("DEVICE_CONNECTION_RECOVERY_REQUIRED");const raw=JSON.parse((await read(c.cloudConfigFile,32768)).toString());const{tools:_tools,...transport}=raw;void _tools;const actual=LocalDeviceTransportConfigurationSchema.parse(transport);if(actual.endpoint!==s.scope.origin||actual.deviceId!==s.device.deviceId||actual.tenantId!==s.scope.tenantId||actual.deviceRevision!==s.connection.deviceRevision||actual.deviceRevision!==s.device.revision||actual.tenantMediaValidation!==s.connection.tenantMediaValidation||actual.tenantMediaProcessing!==s.connection.tenantMediaProcessing||canonicalLocalJson(actual.processorCapabilities??null)!==canonicalLocalJson(s.connection.processorCapabilities??null))fail("DEVICE_CONNECTION_RECOVERY_REQUIRED");return records.save(s,{connection:{...s.connection,phase:"READY"},connectorId:null})}import{createPrivateKey,sign,randomUUID as randomUUID2}from"node:crypto";async function proveDesktopDevice(records){const state=await records.current(),d=state.device;if(!d)fail("DEVICE_ENROLLMENT_REQUIRED");async function request(action,input){const response=await fetch(state.scope.origin+"/v1/local-execution/devices/"+action,{method:"POST",redirect:"error",headers:{"content-type":"application/json"},body:JSON.stringify(input),signal:AbortSignal.timeout(15e3)});if(!response.ok){await response.body?.cancel();fail("DEVICE_PROOF_UNAVAILABLE")}const chunks=[];let size=0;for await(const bytes of response.body??[]){size+=bytes.length;if(size>16384)fail("DEVICE_PROOF_INVALID");chunks.push(bytes)}return JSON.parse(Buffer.concat(chunks).toString())}const scope={tenantId:d.tenantId,deviceId:d.deviceId,deviceRevision:d.revision};const started=performance.now();const challenge=LocalDeviceChallengeSchema.parse(await request("challenge",scope));if(challenge.tenantId!==d.tenantId||challenge.deviceId!==d.deviceId||challenge.deviceRevision!==d.revision||Date.parse(challenge.expiresAt)-Date.parse(challenge.issuedAt)<=performance.now()-started)fail("DEVICE_PROOF_INVALID");const key=createPrivateKey({key:JSON.parse((await read(records.keyPath(),16384)).toString()),format:"jwk"});const header=Buffer.from(JSON.stringify({alg:"ES256",typ:"nvs-local-device+jwt"})).toString("base64url");const iat=Math.floor(Date.parse(challenge.issuedAt)/1e3),claims=Buffer.from(JSON.stringify({protocol:"NVS_LOCAL_DEVICE_PROOF_V1",...scope,challengeId:challenge.challengeId,audience:challenge.audience,jti:randomUUID2(),iat,exp:iat+30})).toString("base64url");const unsigned=header+"."+claims;const assertion=unsigned+"."+sign("sha256",Buffer.from(unsigned),{key,dsaEncoding:"ieee-p1363"}).toString("base64url");const result=LocalDeviceSessionSchema.parse(await request("prove",{...scope,challengeId:challenge.challengeId,assertion}));if(result.tenantId!==d.tenantId||result.deviceId!==d.deviceId)fail("DEVICE_PROOF_INVALID")}var fingerprint=v=>sha256(canonicalLocalJson(v));function view(s){return{revision:s.revision,device:s.device?{deviceId:s.device.deviceId,label:s.device.label,revision:s.device.revision,revokedAt:s.device.revokedAt}:null,previews:s.previews,connection:s.connection,pending:s.pending?{kind:s.pending.command.kind,phase:s.pending.phase,fingerprint:s.pending.fingerprint}:null}}function accepted(s,result){const command=s.pending.command,i=command.input;if(command.kind==="ENROLL"){const d=LocalDeviceViewSchema.parse(result);if(d.tenantId!==i.tenantId||d.enrolledByPrincipalId!==s.scope.principalId||d.label!==command.input.label||d.runtimeVersion!==command.input.runtimeVersion||canonicalLocalJson(d.publicKey)!==canonicalLocalJson(command.input.publicKey)||canonicalLocalJson(d.platform)!==canonicalLocalJson(command.input.platform)||d.revokedAt)fail("DEVICE_RESULT_INVALID");return{device:d}}if(command.kind==="REVOKE_DEVICE"){if(result?.semanticStatus!=="SUCCESS"||!s.device)fail("DEVICE_RESULT_INVALID");return{device:{...s.device,revision:s.device.revision+1,revokedAt:new Date().toISOString()},connectorId:null,connection:null}}const p=(command.kind==="FINAL_RENDER"?LocalFinalRenderAdmissionSchema:LocalPreviewAdmissionSchema).parse(result),input=command.input;if(p.productionId!==input.productionId||p.timelineVersionId!==input.timelineVersionId||p.timelineFingerprint!==input.timelineFingerprint||canonicalLocalJson(p.placement.policy)!==canonicalLocalJson(input.placement))fail("DEVICE_RESULT_INVALID");return{previews:[p,...s.previews.filter(v=>v.renderId!==p.renderId)].slice(0,20)}}async function runDesktopDeviceRequest(home,raw,policy){const request=DesktopDeviceRequestSchema.parse(raw),call=request.call;const records=await DesktopDeviceRecords.open(home,request.scope),manager=await LocalInstallationManager.open(home);let s=await records.current();if(s.pending&&policy&&!policy.allowedPendingKinds.includes(s.pending.command.kind))fail("DEVICE_COMMAND_UNSUPPORTED");const installation=await desktopInstallationIdentity(manager);let automatic=await desktopAutomation(home);const publicView=()=>({...view(s),installation,automaticConnection:canResumeDesktop(automatic,s,installation)});const processingSupported=async()=>{const active=(await manager.ledger.current()).value.active;return!!active&&await probeTenantMediaProcessing(manager.ledger.slotPath(active),active)};const librarySupported=async()=>{const active=(await manager.ledger.current()).value.active;return!!active&&await probeLocalLibrary(manager.ledger.slotPath(active),active)};const compositionSupported=async()=>{const active=(await manager.ledger.current()).value.active;return!!active&&await probeTenantComposition(manager.ledger.slotPath(active),active)};if(call.action==="media-processing-capability")return DesktopDeviceReplySchema.parse({view:publicView(),mediaProcessingSupported:await processingSupported(),localLibrarySupported:await librarySupported(),compositionProcessingSupported:await compositionSupported()});if(call.action==="media-validation-capability"){const active=(await manager.ledger.current()).value.active;const supported=!!active&&await probeTenantMediaValidation(manager.ledger.slotPath(active),active);return DesktopDeviceReplySchema.parse({view:publicView(),mediaValidationSupported:supported})}if(call.action==="inspect")return DesktopDeviceReplySchema.parse({view:publicView(),...s.pending?{command:s.pending.command}:{}});if(call.action==="dispatch"||call.action==="record"||call.action==="refused"){if(!s.pending||s.pending.fingerprint!==call.fingerprint)fail("DEVICE_PLAN_CHANGED");if(call.action==="dispatch"){if(s.pending.phase!=="PREPARED")fail("DEVICE_OUTCOME_UNKNOWN");const command2=s.pending.command;s=await records.save(s,{pending:{...s.pending,phase:"SENDING"}});return DesktopDeviceReplySchema.parse({view:publicView(),command:command2})}if(s.pending.phase!=="SENDING")fail("DEVICE_PLAN_CHANGED");s=await records.save(s,call.action==="record"?{...accepted(s,call.result),pending:null}:{pending:{...s.pending,phase:"REFUSED"}});return DesktopDeviceReplySchema.parse({view:publicView()})}if(s.pending?.phase==="SENDING")fail("DEVICE_OUTCOME_UNKNOWN");if(call.action==="remember-enable"){if(s.revision!==call.expectedRevision)fail("DEVICE_PLAN_CHANGED");automatic=await rememberDesktopAutomation(home,s,installation,call.installationFingerprint);return DesktopDeviceReplySchema.parse({view:publicView()})}if(call.action==="prove"){await proveDesktopDevice(records);return DesktopDeviceReplySchema.parse({view:publicView()})}if(call.action==="connect"){if(call.installationFingerprint&&call.installationFingerprint!==installation?.fingerprint)fail("DEVICE_PLAN_CHANGED");s=await connectDesktopDevice(records,manager,s,call.expectedRevision);return DesktopDeviceReplySchema.parse({view:publicView()})}if(call.action==="connection-recover"){s=await recoverDesktopConnection(records,manager,s);return DesktopDeviceReplySchema.parse({view:publicView()})}let command;if(call.action==="enroll"){if(s.device)fail("DEVICE_ALREADY_ENROLLED");const active=(await manager.ledger.current()).value.active;if(!active)fail("INSTALL_REQUIRED");let publicKey;try{const key=createPrivateKey2({key:JSON.parse((await read(records.keyPath(),16384)).toString()),format:"jwk"});publicKey=createPublicKey(key).export({format:"jwk"})}catch(e){if(e.code!=="ENOENT")throw e;publicKey=(await generateDeviceKey(records.keyPath())).publicKey}command={kind:"ENROLL",input:{tenantId:s.scope.tenantId,requestId:randomUUID3(),label:call.label,platform:active.descriptor.platform,runtimeVersion:active.descriptor.version,publicKey}}}else{const d=s.device;if(!d)fail("DEVICE_ENROLLMENT_REQUIRED");if(call.action==="preview"||call.action==="final"){if(d.revokedAt)fail("LOCAL_AUTHORIZATION_REQUIRED");command={kind:call.action==="final"?"FINAL_RENDER":"PREVIEW",input:{...call.input,tenantId:s.scope.tenantId,placement:{mode:call.mode,deviceId:d.deviceId},idempotencyKey:"desktop:"+randomUUID3()}}}else{if(call.action!=="revoke"||d.revokedAt)fail("LOCAL_AUTHORIZATION_REQUIRED");command={kind:"REVOKE_DEVICE",input:{tenantId:s.scope.tenantId,deviceId:d.deviceId,requestId:randomUUID3(),expectedRevision:d.revision}}}}const parsed=LocalManagementCommandSchema.parse(command);s=await records.save(s,{...parsed.kind==="ENROLL"?{enrollment:parsed.input}:{},pending:{command:parsed,fingerprint:fingerprint(parsed),phase:"PREPARED"}});return DesktopDeviceReplySchema.parse({view:publicView(),command:parsed})}async function desktopDevicePending(home,scope){return(await(await DesktopDeviceRecords.open(home,scope)).current()).pending?.command??null}export{runDesktopDeviceRequest,desktopDevicePending};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{ContinuationSchema,DeliveryOutputProfileSchema,PrincipalIdSchema,ProductionIdSchema,ProductionSchema,ProjectIdSchema,QueryLimitSchema,QueryPageInfoSchema,TenantIdSchema}from"./chunk-HAOCQVMU.js";import{z as z2}from"zod";import{z}from"zod";var ProjectLifecycleSchema=z.enum(["ACTIVE","ARCHIVED"]);var CreateProjectInputSchema=z.object({tenantId:TenantIdSchema,principalId:PrincipalIdSchema,idempotencyKey:z.string().trim().min(1).max(200),name:z.string().trim().min(1).max(200)});var CreateProjectRequestSchema=CreateProjectInputSchema.omit({principalId:true}).strict();var ProjectSchema=z.object({id:ProjectIdSchema,tenantId:TenantIdSchema,name:z.string().min(1),lifecycle:ProjectLifecycleSchema,defaultActiveProductionId:ProductionIdSchema.nullable(),revision:z.int().positive(),createdByPrincipalId:PrincipalIdSchema,createdAt:z.iso.datetime({offset:true}),updatedAt:z.iso.datetime({offset:true})});var CreatedProjectResultSchema=z.object({project:ProjectSchema,production:ProductionSchema});var ProjectLibraryQuerySchema=z2.strictObject({tenantId:TenantIdSchema,limit:QueryLimitSchema,next:ContinuationSchema.optional()});var ProjectLibraryScopeSchema=z2.strictObject({tenantId:TenantIdSchema,projectId:ProjectIdSchema});var ProjectLibraryPageSchema=z2.strictObject({items:z2.array(ProjectSchema).max(100),page:QueryPageInfoSchema});var ProjectWorkspaceSchema=z2.strictObject({project:ProjectSchema,productions:z2.array(ProductionSchema).max(100),possiblyTruncated:z2.boolean()});var SourceLibraryQuerySchema=ProjectLibraryQuerySchema.extend({projectId:ProjectIdSchema.optional()});var SourceLibraryItemSchema=z2.strictObject({artifactId:z2.uuid(),representationId:z2.uuid(),projectId:ProjectIdSchema,kind:z2.enum(["REFERENCE_IMAGE","REFERENCE_VIDEO","PRODUCT_INFORMATION"]),originalName:z2.string().max(255),checksumSha256:z2.string().regex(/^[0-9a-f]{64}$/),contentType:z2.enum(["image/png","image/jpeg","image/webp","text/plain","application/json","video/mp4"]),byteSize:z2.int().positive().max(8388608),width:z2.int().positive().nullable(),height:z2.int().positive().nullable(),createdAt:z2.iso.datetime({offset:true})});var SourceLibraryPageSchema=z2.strictObject({items:z2.array(SourceLibraryItemSchema).max(100),page:QueryPageInfoSchema});var SourceLibraryMediaSchema=ProjectLibraryScopeSchema.extend({artifactId:z2.uuid()});var StudioInputContentSchema=z2.strictObject({schemaVersion:z2.literal(1),productionId:z2.uuid(),projectTitle:z2.string().trim().min(1).max(200),name:z2.string().trim().max(300),intent:z2.string().trim().min(1).max(2e3),aspectRatio:z2.enum(["16:9","9:16"]),targetDurationSeconds:z2.int().min(30).max(60),outputProfile:DeliveryOutputProfileSchema,sourceArtifactIds:z2.array(z2.uuid()).max(12)});import{z as z3}from"zod";var HumanEmailSchema=z3.string().trim().max(254).toLowerCase().pipe(z3.email()).refine(v=>/^[\x21-\x7e]+$/.test(v),"Use an ASCII email address");var HumanPasswordSchema=z3.string().max(512).superRefine((v,c)=>{const points=[...v];const control=points.some(c2=>c2.codePointAt(0)<32||c2.codePointAt(0)===127);if(points.length<15||points.length>128||control)c.addIssue({code:"custom",message:"Password must contain 15\u2013128 characters"})});var HumanCodePurposeSchema=z3.enum(["REGISTER","RESET_PASSWORD","LINK_EMAIL"]);var HumanCodeRequestSchema=z3.strictObject({email:HumanEmailSchema,purpose:HumanCodePurposeSchema});var HumanCodeRequestedSchema=z3.strictObject({accepted:z3.literal(true),challengeId:z3.uuid(),retryAfterSeconds:z3.literal(60),expiresInSeconds:z3.literal(600)});var proof={challengeId:z3.uuid(),email:HumanEmailSchema,code:z3.string().regex(/^\d{6}$/),password:HumanPasswordSchema};var HumanRegisterSchema=z3.strictObject({...proof,displayName:z3.string().trim().min(1).max(80)});var HumanResetSchema=z3.strictObject(proof);var HumanLoginSchema=z3.strictObject({email:HumanEmailSchema,password:z3.string().max(512),rememberMe:z3.boolean().optional()});var HumanTenantSchema=z3.strictObject({id:z3.uuid(),displayName:z3.string().max(200)});var HumanAccountSchema=z3.strictObject({principalId:z3.uuid(),displayName:z3.string().max(200),email:HumanEmailSchema.nullable(),tenants:z3.array(HumanTenantSchema).max(100)});var HumanDesktopSessionSchema=z3.strictObject({tenantId:z3.uuid(),scopeKey:z3.string().regex(/^[a-f0-9]{64}$/),expiresAt:z3.int().positive(),sessionExpiresAt:z3.int().positive().optional(),rememberMe:z3.boolean(),account:HumanAccountSchema.omit({tenants:true})}).refine(({rememberMe,expiresAt,sessionExpiresAt})=>sessionExpiresAt===void 0||rememberMe&&sessionExpiresAt>=expiresAt,"Desktop persistence requires consent and the session deadline");var ShortHumanSessionSchema=z3.strictObject({accessToken:z3.string().regex(/^nvsh_[A-Za-z0-9_-]{43}$/),expiresAt:z3.iso.datetime(),account:HumanAccountSchema});var HumanRefreshTokenSchema=z3.string().regex(/^nvshr_[A-Za-z0-9_-]{43}$/);var HumanRefreshSchema=z3.strictObject({refreshToken:HumanRefreshTokenSchema});var HumanSessionSchema=ShortHumanSessionSchema.extend({refreshToken:HumanRefreshTokenSchema.optional(),sessionId:z3.uuid().optional(),sessionExpiresAt:z3.iso.datetime().optional()}).refine(session=>{const{refreshToken,sessionId,sessionExpiresAt,expiresAt}=session;if(!refreshToken)return sessionId===void 0&&sessionExpiresAt===void 0;return!!sessionId&&!!sessionExpiresAt&&Date.parse(expiresAt)<=Date.parse(sessionExpiresAt)},"Persistent session requires its exact identity and absolute expiry");var HumanIdentityAvailabilitySchema=z3.strictObject({passwordLogin:z3.boolean(),emailVerification:z3.boolean()});var HumanIdentityFailureSchema=z3.strictObject({code:z3.enum(["INVALID_INPUT","INVALID_CREDENTIALS","INVALID_CODE","RATE_LIMITED","MAIL_UNAVAILABLE","UNAVAILABLE","UNAUTHENTICATED","CONFLICT"])});var CliAccountRedirectSchema=z3.string().max(256).refine(value=>{try{const url=new URL(value);return url.protocol==="http:"&&url.hostname==="127.0.0.1"&&Number(url.port)>0&&!url.username&&!url.password&&!url.search&&!url.hash&&/^\/account-callback\/[a-f0-9-]{36}$/.test(url.pathname)&&url.href===value}catch{return false}},"Owned loopback account callback required");var proofKey=z3.string().regex(/^[A-Za-z0-9_-]{43}$/);var CliAccountRequestIdSchema=z3.uuid();var CliAccountStartSchema=z3.strictObject({redirectUri:CliAccountRedirectSchema,state:proofKey,codeChallenge:proofKey});var CliAccountStartedSchema=z3.strictObject({requestId:z3.uuid(),expiresAt:z3.iso.datetime()});var CliAccountPreviewSchema=CliAccountStartedSchema.extend({redirectUri:CliAccountRedirectSchema});var CliAccountDecisionSchema=z3.strictObject({requestId:z3.uuid(),approved:z3.boolean(),expectedPrincipalId:z3.uuid()});var CliAccountExchangeSchema=z3.strictObject({requestId:z3.uuid(),code:proofKey,codeVerifier:proofKey,redirectUri:CliAccountRedirectSchema});var CliAccountSessionSchema=ShortHumanSessionSchema.extend({credentialPurpose:z3.literal("CLI_ACCOUNT")});var CliAccountIdentitySchema=z3.strictObject({credentialPurpose:z3.literal("CLI_ACCOUNT"),account:HumanAccountSchema});export{CreateProjectRequestSchema,ProjectSchema,CreatedProjectResultSchema,ProjectLibraryQuerySchema,ProjectLibraryScopeSchema,ProjectLibraryPageSchema,ProjectWorkspaceSchema,SourceLibraryQuerySchema,SourceLibraryItemSchema,SourceLibraryPageSchema,SourceLibraryMediaSchema,StudioInputContentSchema,HumanTenantSchema,CliAccountStartSchema,CliAccountStartedSchema,CliAccountExchangeSchema,CliAccountSessionSchema,CliAccountIdentitySchema};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{z}from"zod";var TenantIdSchema=z.uuid().brand();var PrincipalIdSchema=z.uuid().brand();var ProjectIdSchema=z.uuid().brand();var ProductionIdSchema=z.uuid().brand();var ArtifactIdSchema=z.uuid().brand();var ArtifactRepresentationIdSchema=z.uuid().brand();var ArtifactRelationIdSchema=z.uuid().brand();var BriefIdSchema=z.uuid().brand();var BriefVersionIdSchema=z.uuid().brand();var StoryIdSchema=z.uuid().brand();var StoryVersionIdSchema=z.uuid().brand();var SceneShotPlanIdSchema=z.uuid().brand();var SceneShotPlanVersionIdSchema=z.uuid().brand();var SceneIdSchema=z.uuid().brand();var ShotIdSchema=z.uuid().brand();var ContinuityEdgeIdSchema=z.uuid().brand();var RuntimeJobIdSchema=z.uuid().brand();var OperationIdSchema=z.string().regex(/^op_[A-Za-z0-9_-]+$/).max(2048).brand();var RuntimeJobAttemptIdSchema=z.uuid().brand();var OutboxEventIdSchema=z.uuid().brand();import{z as z2}from"zod";var uuid="[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}";var page=new RegExp(`^/(?:projects(?:/${uuid})?|artifacts|productions/${uuid}(?:/(?:artifacts|delivery|history))?|settings/voices(?:/${uuid}(?:/versions/[1-9][0-9]*)?)?)$`);var HumanLinkScopeSchema=z2.strictObject({tenantId:z2.uuid(),projectId:z2.uuid().optional(),productionId:z2.uuid().optional(),artifactId:z2.uuid().optional(),representationId:z2.uuid().optional(),delivery:z2.boolean().optional(),voices:z2.boolean().optional(),voiceProfileId:z2.uuid().optional(),voiceProfileVersion:z2.int().positive().optional()}).refine(s=>!!s.artifactId===!!s.representationId&&(!s.delivery||!!s.productionId)&&(s.voiceProfileVersion===void 0||!!s.voiceProfileId));var HumanLinkSchema=z2.strictObject({rel:z2.enum(["workspace","project","production","artifact","delivery","voice_profile"]),href:z2.url().max(2048)}).refine(({rel,href})=>{try{const u=new URL(href),q=u.searchParams,parts=u.pathname.split("/"),pathId=parts[1]==="settings"?parts[3]:parts[2];return u.href===href&&!u.username&&!u.password&&!href.includes("#")&&(u.protocol==="https:"||u.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(u.hostname))&&page.test(u.pathname)&&(!pathId||z2.uuid().safeParse(pathId).success)&&(parts[4]!=="versions"||z2.int().positive().safeParse(Number(parts[5])).success)&&new Set(q.keys()).size===q.size&&[...q].every(([key,value])=>["workspace","artifact","representation"].includes(key)&&z2.uuid().safeParse(value).success)&&q.has("workspace")&&q.has("artifact")===q.has("representation")&&(rel==="artifact"?u.pathname.endsWith("/artifacts")&&q.has("artifact"):!q.has("artifact")&&(rel==="workspace"?u.pathname==="/projects":rel==="project"?new RegExp(`^/projects/${uuid}$`).test(u.pathname):rel==="voice_profile"?u.pathname.startsWith("/settings/voices"):rel==="production"?new RegExp(`^/productions/${uuid}$`).test(u.pathname):u.pathname.endsWith("/delivery")))}catch{return false}});var HumanLinksSchema=z2.discriminatedUnion("status",[z2.strictObject({status:z2.literal("AVAILABLE"),items:z2.array(HumanLinkSchema).min(1).max(4)}),z2.strictObject({status:z2.enum(["UNCONFIGURED","UNAVAILABLE"]),items:z2.array(HumanLinkSchema).max(0)})]);import{z as z3}from"zod";var DeliveryOutputProfileSchema=z3.enum(["MP4_H264_1080P","MP4_H264_720P","MP4_H264_480P"]);var finalProfileIds={MP4_H264_1080P:"FINAL_H264_1080P_V1",MP4_H264_720P:"FINAL_H264_720P_V1",MP4_H264_480P:"FINAL_H264_480P_V1"};import{z as z4}from"zod";var InterfaceSemanticStatusSchema=z4.enum(["SUCCESS","ACCEPTED","NO_CHANGE","INVALID_INPUT","NOT_FOUND","REVISION_CONFLICT","STALE_BASIS","BLOCKED","WAITING_PROVIDER","WAITING_INPUT","RETRYING","CAPABILITY_UNAVAILABLE","PROVIDER_UNAVAILABLE","BUDGET_BLOCKED","CANCELLED","SUPERSEDED","INTERNAL_OPERATIONAL_FAILURE"]);var ActionAvailabilitySchema=z4.enum(["AVAILABLE","UNAVAILABLE"]);var NextActionSchema=z4.object({capability:z4.string().min(1).max(120),targetType:z4.string().min(1).max(80),targetId:z4.string().min(1).max(2048),availability:ActionAvailabilitySchema,reason:z4.string().min(1).max(1e3).nullable()});var ContinuationSchema=z4.string().min(1).max(8192);var QueryLimitSchema=z4.int().min(1).max(100).default(20);var QueryPageInfoSchema=z4.object({hasMore:z4.boolean(),next:ContinuationSchema.nullable()});var WorkSummarySchema=z4.object({total:z4.int().nonnegative(),pending:z4.int().nonnegative(),ready:z4.int().nonnegative(),running:z4.int().nonnegative(),waiting:z4.int().nonnegative(),succeeded:z4.int().nonnegative(),failed:z4.int().nonnegative(),cancelled:z4.int().nonnegative(),superseded:z4.int().nonnegative(),attempts:z4.int().nonnegative()});import{z as z5}from"zod";var ProductionLifecycleSchema=z5.enum(["ACTIVE","COMPLETED","FAILED","CANCELLED"]);var ProductionPhaseSchema=z5.enum(["INTAKE","PLANNING","PREPARING_GENERATION","GENERATING","SHOT_REVIEW","ASSEMBLING","ROUGH_CUT_REVIEW","FINAL_READY","FINAL_RENDERING","DELIVERY_VALIDATION"]);var ProductionConditionSchema=z5.enum(["RUNNABLE","RUNNING","WAITING_PROVIDER","WAITING_HUMAN","BLOCKED","RETRYING"]);var CreateProductionInputSchema=z5.object({tenantId:TenantIdSchema,projectId:ProjectIdSchema,principalId:PrincipalIdSchema});var ProductionStateSchema=z5.object({lifecycle:ProductionLifecycleSchema,phase:ProductionPhaseSchema,condition:ProductionConditionSchema,revision:z5.int().positive(),blockingReason:z5.string().min(1).nullable(),waitingReason:z5.string().min(1).nullable()});var ProductionSchema=z5.object({humanLinks:HumanLinksSchema.optional(),id:ProductionIdSchema,tenantId:TenantIdSchema,projectId:ProjectIdSchema,state:ProductionStateSchema,activeBriefVersion:z5.int().positive().nullable().default(null),activeStoryVersion:z5.int().positive().nullable().default(null),activeSceneShotPlanVersion:z5.int().positive().nullable().default(null),createdByPrincipalId:PrincipalIdSchema,createdAt:z5.iso.datetime({offset:true}),updatedAt:z5.iso.datetime({offset:true})});export{TenantIdSchema,PrincipalIdSchema,ProjectIdSchema,ProductionIdSchema,ArtifactIdSchema,ArtifactRepresentationIdSchema,ArtifactRelationIdSchema,BriefIdSchema,BriefVersionIdSchema,StoryIdSchema,StoryVersionIdSchema,SceneShotPlanIdSchema,SceneShotPlanVersionIdSchema,SceneIdSchema,ShotIdSchema,ContinuityEdgeIdSchema,OperationIdSchema,HumanLinksSchema,DeliveryOutputProfileSchema,finalProfileIds,InterfaceSemanticStatusSchema,NextActionSchema,ContinuationSchema,QueryLimitSchema,QueryPageInfoSchema,WorkSummarySchema,ProductionStateSchema,ProductionSchema};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
var NativeStudioSdkError=class extends Error{constructor(code,semanticStatus,outcome,status=null,issues=[]){super(`NativeStudio ${code}`);this.code=code;this.semanticStatus=semanticStatus;this.outcome=outcome;this.status=status;this.issues=issues;this.name="NativeStudioSdkError"}code;semanticStatus;outcome;status;issues};function sdkInputError(issues=[]){throw new NativeStudioSdkError("INVALID_INPUT","INVALID_INPUT","NO_WRITE",null,issues)}export{NativeStudioSdkError,sdkInputError};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{LocalDeviceTransportConfigurationSchema,LocalDeviceViewSchema,LocalFinalRenderAdmissionSchema,LocalManagementCommandSchema,LocalManagementResultSchema,LocalPreviewAdmissionSchema,StartLocalFinalRenderSchema,StartLocalPreviewSchema,canonicalLocalJson}from"./chunk-WAADGZEV.js";import{directory,entries,fail,privateAccess,read,sha256,write}from"./chunk-RUPH3HZ2.js";import{z}from"zod";var DesktopDeviceScopeSchema=z.strictObject({origin:z.url().refine(value=>{const u=new URL(value);return u.origin===value&&(u.protocol==="https:"||u.protocol==="http:"&&["127.0.0.1","localhost","[::1]"].includes(u.hostname))}),tenantId:z.uuid(),principalId:z.uuid()});var digest=z.string().regex(/^[a-f0-9]{64}$/);var DesktopDeviceCallSchema=z.discriminatedUnion("action",[z.strictObject({action:z.literal("inspect")}),z.strictObject({action:z.literal("prove")}),z.strictObject({action:z.literal("media-validation-capability")}),z.strictObject({action:z.literal("media-processing-capability")}),z.strictObject({action:z.literal("connect"),expectedRevision:z.int().nonnegative(),installationFingerprint:digest.optional()}),z.strictObject({action:z.literal("remember-enable"),expectedRevision:z.int().nonnegative(),installationFingerprint:digest}),z.strictObject({action:z.literal("connection-recover")}),z.strictObject({action:z.literal("enroll"),label:z.string().trim().min(1).max(120)}),z.strictObject({action:z.literal("revoke")}),z.strictObject({action:z.literal("preview"),input:StartLocalPreviewSchema.omit({tenantId:true,placement:true,idempotencyKey:true}),mode:z.enum(["local-only","local-preferred"])}),z.strictObject({action:z.literal("final"),input:StartLocalFinalRenderSchema.omit({tenantId:true,placement:true,idempotencyKey:true}),mode:z.enum(["local-only","local-preferred"])}),z.strictObject({action:z.literal("dispatch"),fingerprint:digest}),z.strictObject({action:z.literal("record"),fingerprint:digest,result:LocalManagementResultSchema}),z.strictObject({action:z.literal("refused"),fingerprint:digest})]);var DesktopDeviceRequestSchema=z.strictObject({operation:z.literal("device"),scope:DesktopDeviceScopeSchema,call:DesktopDeviceCallSchema});var DesktopDeviceStateSchema=z.strictObject({revision:z.int().nonnegative(),scope:DesktopDeviceScopeSchema,enrollment:LocalManagementCommandSchema.options[0].shape.input.nullable(),device:LocalDeviceViewSchema.nullable(),previews:z.array(z.union([LocalPreviewAdmissionSchema,LocalFinalRenderAdmissionSchema])).max(20),connectorId:z.uuid().nullable(),connection:z.strictObject({phase:z.enum(["CONNECTING","READY","CONNECTED"]),expiresAt:z.iso.datetime(),tenantMediaProcessing:z.literal(true).optional(),processorCapabilities:LocalDeviceTransportConfigurationSchema.shape.processorCapabilities,deviceRevision:z.int().positive(),tenantMediaValidation:z.literal(true).optional()}).nullable().default(null),pending:z.strictObject({command:LocalManagementCommandSchema,fingerprint:digest,phase:z.enum(["PREPARED","SENDING","REFUSED"])}).nullable()});var DesktopDeviceViewSchema=DesktopDeviceStateSchema.omit({scope:true,enrollment:true,connectorId:true,pending:true,device:true}).extend({installation:z.strictObject({version:z.string().min(1).max(100),fingerprint:digest,workProtocol:z.enum(["NVS_LOCAL_WORK_V1","NVS_LOCAL_WORK_V2"]).optional()}).nullable().optional(),automaticConnection:z.boolean().optional(),device:z.strictObject({deviceId:z.uuid(),label:z.string().max(120),revision:z.int().positive(),revokedAt:z.iso.datetime().nullable()}).nullable(),pending:z.strictObject({kind:z.enum(["ENROLL","REVOKE_DEVICE","PREVIEW","FINAL_RENDER"]),phase:z.enum(["PREPARED","SENDING","REFUSED"]),fingerprint:digest}).nullable()});var DesktopDeviceReplySchema=z.strictObject({view:DesktopDeviceViewSchema,command:LocalManagementCommandSchema.optional(),mediaValidationSupported:z.boolean().optional(),mediaProcessingSupported:z.boolean().optional(),localLibrarySupported:z.boolean().optional(),compositionProcessingSupported:z.boolean().optional()});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{DesktopDeviceScopeSchema,DesktopDeviceRequestSchema,DesktopDeviceReplySchema,DesktopDeviceRecords,desktopDeviceConnector};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{lstat as lstat2,mkdir,open,rename,link,unlink}from"node:fs/promises";import{dirname,isAbsolute as isAbsolute2,join as join2}from"node:path";import{createHash as createHash2}from"node:crypto";import{spawn}from"node:child_process";import{once}from"node:events";import{readFile,realpath,lstat}from"node:fs/promises";import{createHash,randomUUID}from"node:crypto";import{fileURLToPath}from"node:url";import{join,isAbsolute}from"node:path";var executable;var assetDirectory;async function windowsHelper(){if(process.platform!=="win32"||process.arch!=="x64")throw Error("WINDOWS_PLATFORM_REQUIRED");return executable??=bootstrap().catch(error=>{executable=void 0;throw error})}async function bootstrap(){const directory2=assetDirectory??fileURLToPath(new URL("./dist/native/",import.meta.resolve("@nativestudio/cli/package.json")));const read2=async(name,maximum)=>{const path=join(directory2,name),stat=await lstat(path);if(!stat.isFile()||stat.isSymbolicLink()||stat.nlink!==1||stat.size<1||stat.size>maximum)throw Error("WINDOWS_HELPER_INVALID");const bytes2=await readFile(path);if(bytes2.length!==stat.size)throw Error("WINDOWS_HELPER_INVALID");return bytes2};const m=JSON.parse((await read2("helper.json",4096)).toString());const bytes=await read2("helper.exe",2*1024*1024);if(m.protocol!=="NVS_WINDOWS_HELPER_V1"||m.format!=="PE_AMD64_NETFRAMEWORK48"||m.byteSize!==bytes.length||!/^[a-f0-9]{64}$/.test(m.sha256)||createHash("sha256").update(bytes).digest("hex")!==m.sha256)throw Error("WINDOWS_HELPER_INVALID");return realpath(join(directory2,"helper.exe"))}var service;async function connection(){return service??=(async()=>{const child=spawn(await windowsHelper(),["service",String(process.pid)],{shell:false,windowsHide:true,stdio:["pipe","pipe","pipe"]});const pending=new Map;let bytes=Buffer.alloc(0),stderr=0;const close=()=>{for(const item of pending.values()){clearTimeout(item.timer);item.reject(Error("WINDOWS_HELPER_UNAVAILABLE"))}pending.clear();service=void 0};child.stdout.on("data",part=>{bytes=Buffer.concat([bytes,part]);if(bytes.length>2*1024*1024)return child.kill();for(;;){const end=bytes.indexOf(10);if(end<0)break;const line=bytes.subarray(0,end);bytes=bytes.subarray(end+1);try{const value=JSON.parse(line.toString());const item=pending.get(value.id);if(!item)continue;pending.delete(value.id);clearTimeout(item.timer);if(value.ok)item.resolve(value.data);else item.reject(Error(["EXISTS","RESOURCE_BUDGET_EXCEEDED"].includes(value.error??"")?value.error:"WINDOWS_ACCESS_DENIED"))}catch{child.kill()}}});child.stderr.on("data",b=>{if((stderr+=b.length)>65536)child.kill()});child.on("error",close);child.on("close",close);child.stdin.on("error",close);await once(child,"spawn");child.unref();child.stdout.unref();child.stderr.unref();child.stdin.unref();return{child,pending}})().catch(error=>{service=void 0;throw error})}async function windowsRequest(request,timeoutMs=1e4,signal){signal?.throwIfAborted();const{child,pending}=await connection();signal?.throwIfAborted();if(child.exitCode!==null||child.signalCode!==null||child.stdin.destroyed)throw Error("WINDOWS_HELPER_UNAVAILABLE");if(pending.size>=32)throw Error("WINDOWS_HELPER_BUSY");const id=randomUUID(),data=JSON.stringify({...request,id});if(Buffer.byteLength(data)>1024*1024)throw Error("WINDOWS_HELPER_INPUT_LIMIT");return new Promise((resolve,reject)=>{const abort=()=>{child.stdin.write(JSON.stringify({operation:"cancel",target:id})+"\n")};const timer=setTimeout(()=>{abort();pending.delete(id);signal?.removeEventListener("abort",abort);reject(Error("WINDOWS_HELPER_TIMEOUT"))},timeoutMs);pending.set(id,{timer,resolve:v=>{signal?.removeEventListener("abort",abort);resolve(v)},reject:e=>{signal?.removeEventListener("abort",abort);reject(e)}});signal?.addEventListener("abort",abort,{once:true});child.stdin.write(data+"\n");if(signal?.aborted)abort()})}function localSocketPath(root,platform=process.platform){if(platform!=="win32")return join2(root,"runtime.sock");return"\\\\.\\pipe\\nvs-"+createHash2("sha256").update(root.toLowerCase()).digest("hex")}async function privateAccess(path,kind){if(process.platform==="win32"){if(kind!=="pipe")await lstat2(path);await windowsRequest({operation:"check",path,kind});return}const s=await lstat2(path);if(s.isSymbolicLink()||s.uid!==process.getuid?.()||s.mode&63||(kind==="directory"?!s.isDirectory():kind==="pipe"?!s.isSocket():!s.isFile()))throw Error("LOCAL_PERMISSIONS_INVALID")}async function privateDirectory(path,create=false){if(!isAbsolute2(path)||!["win32","darwin","linux"].includes(process.platform))throw Error("LOCAL_LOCATION_INVALID");if(process.platform==="win32")await windowsRequest({operation:create?"directory":"check",path,kind:"directory"});else{if(create)await mkdir(path,{recursive:true,mode:448});await privateAccess(path,"directory")}}async function syncDirectory(path){if(process.platform==="win32")return;const d=await open(path,"r");try{await d.sync()}finally{await d.close()}}async function atomicMove(source,target,exclusive=false){if(dirname(source)!==dirname(target))throw Error("LOCAL_ATOMIC_MOVE_INVALID");if(process.platform==="win32"){try{await windowsRequest({operation:"move",source,target,exclusive})}catch(error){if(error.message==="EXISTS")throw Object.assign(Error("EXISTS"),{code:"EEXIST"});throw error}}else{if(exclusive){await link(source,target);await unlink(source)}else await rename(source,target);await syncDirectory(dirname(target))}}async function assertExecutable(path){const s=await lstat2(path);if(!isAbsolute2(path)||!s.isFile()||s.isSymbolicLink()||s.nlink!==1)throw Error("LOCAL_EXECUTABLE_INVALID");if(process.platform==="win32"){if(!path.toLowerCase().endsWith(".exe"))throw Error("LOCAL_EXECUTABLE_INVALID");await windowsRequest({operation:"executable",path})}else if(!(s.mode&73)||s.mode&18)throw Error("LOCAL_EXECUTABLE_INVALID")}import{spawn as spawn2}from"node:child_process";import{Duplex}from"node:stream";import{constants}from"node:fs";import{open as open2,realpath as realpath2,rename as rename2,unlink as unlink2,link as link2,readdir}from"node:fs/promises";import{isAbsolute as isAbsolute3,join as join3,dirname as dirname2}from"node:path";import{randomUUID as randomUUID2,createHash as createHash3}from"node:crypto";var sha256=v=>createHash3("sha256").update(v).digest("hex");var sha512=v=>createHash3("sha512").update(v).digest("hex");var LocalClientError=class extends Error{constructor(code){super("NativeStudio local "+code);this.code=code}code};function fail(code){throw new LocalClientError(code)}async function directory(path){if(!isAbsolute3(path))fail("LOCATION_UNSUPPORTED");try{await privateDirectory(path,true)}catch{fail("PRIVATE_LOCATION_REQUIRED")}const root=await realpath2(path);if(/(?:^|[\\/])(?:node_modules|_npx)(?:[\\/]|$)/.test(root))fail("PRIVATE_LOCATION_REQUIRED");return root}async function read(path,maximum=65536,ledger=false){try{await privateAccess(path,"file")}catch(e){if(e.code==="ENOENT")throw e;fail("PRIVATE_FILE_REQUIRED")}const f=await open2(path,constants.O_RDONLY|constants.O_NOFOLLOW);try{const s=await f.stat();if(!s.isFile()||process.platform!=="win32"&&(s.uid!==process.getuid?.()||s.mode&63)||s.size>maximum||(ledger?s.nlink>2:s.nlink!==1))fail("PRIVATE_FILE_REQUIRED");const bytes=Buffer.alloc(Math.min(maximum+1,s.size+1));let used=0;while(used<bytes.length){const part=await f.read(bytes,used,bytes.length-used,null);if(!part.bytesRead)break;used+=part.bytesRead}if(used>s.size)fail("FILE_CHANGED");if(used>maximum)fail("FILE_LIMIT");return bytes.subarray(0,used)}finally{await f.close()}}async function write(path,value,exclusive=false){const temporary=join3(dirname2(path),".tmp-"+randomUUID2());const f=await open2(temporary,"wx",384);try{await f.writeFile(value);await f.sync()}finally{await f.close()}try{if(process.platform==="win32")await atomicMove(temporary,path,exclusive);else if(exclusive)await link2(temporary,path);else{try{await read(path,64*1024*1024)}catch(e){if(e.code!=="ENOENT")throw e}await rename2(temporary,path)}}finally{await unlink2(temporary).catch(e=>{if(e.code!=="ENOENT")throw e})}await syncDirectory(dirname2(path))}async function entries(path){const values=await readdir(path);if(values.length>1e4)fail("HISTORY_LIMIT");return values}async function optional(path){try{return JSON.parse((await read(path)).toString())}catch(e){if(e.code==="ENOENT")return null;throw e}}async function verifyBackup(path,stateDirectory){const base=await realpath2(join3(stateDirectory,"backups")),actual=await realpath2(path);if(dirname2(actual)!==base||!/[0-9a-f-]{36}\.sqlite$/.test(actual))fail("JOURNAL_BACKUP_REQUIRED");try{await privateAccess(actual,"file")}catch{fail("JOURNAL_BACKUP_REQUIRED")}const f=await open2(actual,constants.O_RDONLY|constants.O_NOFOLLOW);try{const stat=await f.stat(),header=Buffer.alloc(16);if(!stat.isFile()||stat.nlink!==1||process.platform!=="win32"&&(stat.uid!==process.getuid?.()||stat.mode&63)||stat.size<100)fail("JOURNAL_BACKUP_REQUIRED");const n=await f.read(header,0,16,0);if(n.bytesRead!==16||header.toString()!=="SQLite format 3\0")fail("JOURNAL_BACKUP_REQUIRED")}finally{await f.close()}}export{localSocketPath,privateAccess,privateDirectory,atomicMove,assertExecutable,sha256,sha512,LocalClientError,fail,directory,read,write,entries,optional,verifyBackup};
|