@nativestudio/cli 0.0.0-stage → 0.3.0-rc.2

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.
Files changed (206) hide show
  1. package/COMPATIBILITY.json +20 -0
  2. package/LICENSE +21 -0
  3. package/README.md +94 -2
  4. package/components/runtime.json +6 -0
  5. package/components/runtime.tgz +0 -0
  6. package/dist/BUNDLED_DEPENDENCIES.json +1 -0
  7. package/dist/_chunks/chunk-2UYKJ6YN.js +1 -0
  8. package/dist/_chunks/chunk-66CUOZVI.js +1 -0
  9. package/dist/_chunks/chunk-6NVIN2NI.js +1 -0
  10. package/dist/_chunks/chunk-7S3DJ2QE.js +1 -0
  11. package/dist/_chunks/chunk-BVSTJQJI.js +1 -0
  12. package/dist/_chunks/chunk-C33A2DW4.js +1 -0
  13. package/dist/_chunks/chunk-C753RRRA.js +1 -0
  14. package/dist/_chunks/chunk-E57YVMQ4.js +1 -0
  15. package/dist/_chunks/chunk-GJ7BZJLW.js +1 -0
  16. package/dist/_chunks/chunk-HLKERZIE.js +1 -0
  17. package/dist/_chunks/chunk-JFC6ZIGA.js +1 -0
  18. package/dist/_chunks/chunk-K6LVS2IN.js +1 -0
  19. package/dist/_chunks/chunk-KHKUJXQX.js +1 -0
  20. package/dist/_chunks/chunk-PUNG4ND7.js +1 -0
  21. package/dist/_chunks/chunk-VC3ODN3M.js +1 -0
  22. package/dist/_chunks/chunk-VDNNFVTZ.js +3 -0
  23. package/dist/_chunks/chunk-VPYAXWXY.js +1 -0
  24. package/dist/_chunks/files-FZEK2ZZJ.js +1 -0
  25. package/dist/_chunks/local-main-NLFS74Q4.js +1 -0
  26. package/dist/_chunks/local-mcp-OLHBBVNN.js +1 -0
  27. package/dist/_chunks/main-VRIQTI6R.js +2 -0
  28. package/dist/_chunks/mcp-EIMXNRH3.js +1 -0
  29. package/dist/_chunks/oauth-F7EZGVME.js +1 -0
  30. package/dist/_chunks/project-connect-MXM7IY55.js +1 -0
  31. package/dist/_chunks/src-7F6ZEU3U.js +1 -0
  32. package/dist/_chunks/stdio-main-KOGQ5OWF.js +1 -0
  33. package/dist/_types/cli/local/desktop-channel.d.ts +18 -0
  34. package/dist/_types/cli/local/desktop-contract.d.ts +281 -0
  35. package/dist/_types/cli/local/desktop-node.d.ts +1 -0
  36. package/dist/_types/cli/local/desktop-owner.d.ts +34 -0
  37. package/dist/_types/cli/local/ledger.d.ts +309 -0
  38. package/dist/_types/cli/local/manager.d.ts +620 -0
  39. package/dist/_types/cli/local/mcp-tools.d.ts +419 -0
  40. package/dist/_types/cli/local/releases.d.ts +101 -0
  41. package/dist/_types/cli/local-management.d.ts +12 -0
  42. package/dist/_types/cli/local-navigation.d.ts +3 -0
  43. package/dist/_types/contracts/accepted-shot.d.ts +27 -0
  44. package/dist/_types/contracts/accepted-visual-source.d.ts +120 -0
  45. package/dist/_types/contracts/agent-execution-lifecycle.d.ts +749 -0
  46. package/dist/_types/contracts/agent-execution-oauth.d.ts +71 -0
  47. package/dist/_types/contracts/agent-execution-registration.d.ts +240 -0
  48. package/dist/_types/contracts/agent-execution-selection.d.ts +107 -0
  49. package/dist/_types/contracts/agent-host-execution.d.ts +706 -0
  50. package/dist/_types/contracts/agent-host-generic-transport.d.ts +12 -0
  51. package/dist/_types/contracts/agent-host.d.ts +226 -0
  52. package/dist/_types/contracts/artifact-discovery.d.ts +170 -0
  53. package/dist/_types/contracts/artifact.d.ts +188 -0
  54. package/dist/_types/contracts/audio.d.ts +331 -0
  55. package/dist/_types/contracts/brief.d.ts +178 -0
  56. package/dist/_types/contracts/caption-render.d.ts +20 -0
  57. package/dist/_types/contracts/caption-transcript.d.ts +102 -0
  58. package/dist/_types/contracts/captions.d.ts +420 -0
  59. package/dist/_types/contracts/clip-framing.d.ts +14 -0
  60. package/dist/_types/contracts/clip-transition.d.ts +6 -0
  61. package/dist/_types/contracts/composition-authoring-guide.d.ts +160 -0
  62. package/dist/_types/contracts/composition-authoring.d.ts +744 -0
  63. package/dist/_types/contracts/composition-finding-locality.d.ts +24 -0
  64. package/dist/_types/contracts/composition-frame-render.d.ts +226 -0
  65. package/dist/_types/contracts/composition-making.d.ts +390 -0
  66. package/dist/_types/contracts/composition-observation.d.ts +239 -0
  67. package/dist/_types/contracts/composition-render-base.d.ts +292 -0
  68. package/dist/_types/contracts/composition-render-observation.d.ts +278 -0
  69. package/dist/_types/contracts/composition-render.d.ts +406 -0
  70. package/dist/_types/contracts/composition-repair.d.ts +451 -0
  71. package/dist/_types/contracts/composition-source-review.d.ts +1042 -0
  72. package/dist/_types/contracts/consistency-profile.d.ts +845 -0
  73. package/dist/_types/contracts/continuity-evaluation.d.ts +48 -0
  74. package/dist/_types/contracts/delivery-completion.d.ts +210 -0
  75. package/dist/_types/contracts/delivery-manifest.d.ts +11776 -0
  76. package/dist/_types/contracts/delivery-operations.d.ts +5009 -0
  77. package/dist/_types/contracts/delivery-output-profile.d.ts +12 -0
  78. package/dist/_types/contracts/delivery-summary.d.ts +220 -0
  79. package/dist/_types/contracts/delivery-validation.d.ts +183 -0
  80. package/dist/_types/contracts/director-proposal.d.ts +1067 -0
  81. package/dist/_types/contracts/editor-intelligence.d.ts +5751 -0
  82. package/dist/_types/contracts/exploration-recommendation.d.ts +11863 -0
  83. package/dist/_types/contracts/external-agent-access.d.ts +95 -0
  84. package/dist/_types/contracts/final-ready.d.ts +301 -0
  85. package/dist/_types/contracts/final-render-profile.d.ts +59 -0
  86. package/dist/_types/contracts/final-render.d.ts +8181 -0
  87. package/dist/_types/contracts/foundation.d.ts +1 -0
  88. package/dist/_types/contracts/generation-contract.d.ts +268 -0
  89. package/dist/_types/contracts/generation-cost.d.ts +70 -0
  90. package/dist/_types/contracts/health.d.ts +6 -0
  91. package/dist/_types/contracts/human-identity.d.ts +149 -0
  92. package/dist/_types/contracts/hyperframe-profile.d.ts +5 -0
  93. package/dist/_types/contracts/ids.d.ts +41 -0
  94. package/dist/_types/contracts/index.d.ts +122 -0
  95. package/dist/_types/contracts/interface/common.d.ts +56 -0
  96. package/dist/_types/contracts/interface/execution-output.d.ts +99 -0
  97. package/dist/_types/contracts/interface/index.d.ts +7 -0
  98. package/dist/_types/contracts/interface/media-output.d.ts +62 -0
  99. package/dist/_types/contracts/interface/operation.d.ts +61 -0
  100. package/dist/_types/contracts/interface/output.d.ts +15 -0
  101. package/dist/_types/contracts/interface/production-snapshot.d.ts +832 -0
  102. package/dist/_types/contracts/interface/query.d.ts +315 -0
  103. package/dist/_types/contracts/keyframe-generation.d.ts +349 -0
  104. package/dist/_types/contracts/keyframe-reference.d.ts +31 -0
  105. package/dist/_types/contracts/keyframe-review.d.ts +753 -0
  106. package/dist/_types/contracts/lifecycle-event-projections.d.ts +191 -0
  107. package/dist/_types/contracts/lifecycle-events.d.ts +156 -0
  108. package/dist/_types/contracts/listening-evidence.d.ts +37 -0
  109. package/dist/_types/contracts/local-execution/agent-review.d.ts +560 -0
  110. package/dist/_types/contracts/local-execution/canonical.d.ts +2 -0
  111. package/dist/_types/contracts/local-execution/common.d.ts +48 -0
  112. package/dist/_types/contracts/local-execution/completion.d.ts +128 -0
  113. package/dist/_types/contracts/local-execution/device.d.ts +134 -0
  114. package/dist/_types/contracts/local-execution/index.d.ts +11 -0
  115. package/dist/_types/contracts/local-execution/ipc.d.ts +1202 -0
  116. package/dist/_types/contracts/local-execution/lifecycle.d.ts +347 -0
  117. package/dist/_types/contracts/local-execution/local-navigation.d.ts +710 -0
  118. package/dist/_types/contracts/local-execution/preview.d.ts +3663 -0
  119. package/dist/_types/contracts/local-execution/tool-selection.d.ts +15 -0
  120. package/dist/_types/contracts/local-execution/work.d.ts +3441 -0
  121. package/dist/_types/contracts/matrix-parameter-rule.d.ts +23 -0
  122. package/dist/_types/contracts/media-export.d.ts +23 -0
  123. package/dist/_types/contracts/media-observation.d.ts +1159 -0
  124. package/dist/_types/contracts/model-capability-matrix.d.ts +118 -0
  125. package/dist/_types/contracts/native-tool-authority-failure.d.ts +38 -0
  126. package/dist/_types/contracts/native-tool-authority.d.ts +110 -0
  127. package/dist/_types/contracts/native-tool-execution.d.ts +287 -0
  128. package/dist/_types/contracts/native-tool-gateway.d.ts +41 -0
  129. package/dist/_types/contracts/native-video-audio.d.ts +62 -0
  130. package/dist/_types/contracts/navigation-context.d.ts +253 -0
  131. package/dist/_types/contracts/navigation-groups.d.ts +51 -0
  132. package/dist/_types/contracts/navigation.d.ts +238 -0
  133. package/dist/_types/contracts/observation-profile.d.ts +99 -0
  134. package/dist/_types/contracts/planning-input.d.ts +177 -0
  135. package/dist/_types/contracts/principal.d.ts +26 -0
  136. package/dist/_types/contracts/production-creation.d.ts +66 -0
  137. package/dist/_types/contracts/production-termination.d.ts +51 -0
  138. package/dist/_types/contracts/production.d.ts +111 -0
  139. package/dist/_types/contracts/programmatic-composition.d.ts +762 -0
  140. package/dist/_types/contracts/programmatic-exploration.d.ts +7459 -0
  141. package/dist/_types/contracts/programmatic-video-review.d.ts +894 -0
  142. package/dist/_types/contracts/project-library.d.ts +173 -0
  143. package/dist/_types/contracts/project.d.ts +93 -0
  144. package/dist/_types/contracts/provider-catalog.d.ts +421 -0
  145. package/dist/_types/contracts/provider-models.d.ts +3380 -0
  146. package/dist/_types/contracts/provider.d.ts +142 -0
  147. package/dist/_types/contracts/reference-preview.d.ts +36 -0
  148. package/dist/_types/contracts/repair-lifecycle.d.ts +2896 -0
  149. package/dist/_types/contracts/repair-plan.d.ts +728 -0
  150. package/dist/_types/contracts/repair-strategy.d.ts +5751 -0
  151. package/dist/_types/contracts/review-intelligence-evidence.d.ts +136 -0
  152. package/dist/_types/contracts/review-intelligence-final-output.d.ts +8705 -0
  153. package/dist/_types/contracts/review-intelligence.d.ts +11543 -0
  154. package/dist/_types/contracts/review1-repair-source.d.ts +452 -0
  155. package/dist/_types/contracts/review1-repair-strategy.d.ts +491 -0
  156. package/dist/_types/contracts/review1-repair.d.ts +36 -0
  157. package/dist/_types/contracts/rough-cut-manifest.d.ts +347 -0
  158. package/dist/_types/contracts/rough-cut-profile.d.ts +37 -0
  159. package/dist/_types/contracts/rough-cut-review.d.ts +12819 -0
  160. package/dist/_types/contracts/rough-cut.d.ts +5862 -0
  161. package/dist/_types/contracts/scene-shot-plan.d.ts +882 -0
  162. package/dist/_types/contracts/sdk-discovery.d.ts +66 -0
  163. package/dist/_types/contracts/shot-direction.d.ts +113 -0
  164. package/dist/_types/contracts/shot-preparation-basis.d.ts +356 -0
  165. package/dist/_types/contracts/shot-preparation.d.ts +2285 -0
  166. package/dist/_types/contracts/shot-sound-instruction.d.ts +58 -0
  167. package/dist/_types/contracts/sound-making-plan.d.ts +1585 -0
  168. package/dist/_types/contracts/source-sound-policy.d.ts +10 -0
  169. package/dist/_types/contracts/source-workspace.d.ts +62 -0
  170. package/dist/_types/contracts/speech.d.ts +424 -0
  171. package/dist/_types/contracts/story.d.ts +98 -0
  172. package/dist/_types/contracts/temporal-evidence-operation.d.ts +379 -0
  173. package/dist/_types/contracts/temporal-evidence-reference.d.ts +18 -0
  174. package/dist/_types/contracts/temporal-evidence.d.ts +248 -0
  175. package/dist/_types/contracts/tenant.d.ts +7 -0
  176. package/dist/_types/contracts/timeline-audio.d.ts +97 -0
  177. package/dist/_types/contracts/timeline-graphics.d.ts +80 -0
  178. package/dist/_types/contracts/timeline-manifest.d.ts +702 -0
  179. package/dist/_types/contracts/timeline-source-sound.d.ts +352 -0
  180. package/dist/_types/contracts/timeline-v2.d.ts +1263 -0
  181. package/dist/_types/contracts/timeline-version-reader.d.ts +2945 -0
  182. package/dist/_types/contracts/timeline-visual-layers.d.ts +1245 -0
  183. package/dist/_types/contracts/timeline.d.ts +4942 -0
  184. package/dist/_types/contracts/transcription.d.ts +80 -0
  185. package/dist/_types/contracts/video-generation.d.ts +643 -0
  186. package/dist/_types/contracts/video-review.d.ts +1871 -0
  187. package/dist/_types/contracts/visual-exploration.d.ts +1586 -0
  188. package/dist/_types/contracts/visual-layer-render.d.ts +2777 -0
  189. package/dist/_types/contracts/visual-layer.d.ts +112 -0
  190. package/dist/_types/contracts/visual-sequence.d.ts +121 -0
  191. package/dist/_types/contracts/writer-proposal.d.ts +268 -0
  192. package/dist/_types/sdk/errors.d.ts +9 -0
  193. package/dist/_types/sdk/local-runtime/device-client.d.ts +77 -0
  194. package/dist/_types/sdk/local-runtime-client.d.ts +932 -0
  195. package/dist/entry.js +2 -0
  196. package/dist/local-management.d.ts +1 -0
  197. package/dist/local-management.js +1 -0
  198. package/dist/local-navigation.d.ts +1 -0
  199. package/dist/local-navigation.js +1 -0
  200. package/dist/native/Bootstrap.ps1 +90 -0
  201. package/dist/native/JobNative.cs +127 -0
  202. package/dist/native/JobRunner.cs +360 -0
  203. package/dist/native/NativeMain.cs +146 -0
  204. package/dist/native/PipeBridge.cs +260 -0
  205. package/dist/native/PrivateAccess.cs +152 -0
  206. package/package.json +33 -3
@@ -0,0 +1 @@
1
+ import{KeyframeObservationSchema,NativeRuntimePublicKeySchema,ReviewEvidenceMediaSchema,ReviewIntelligenceBasisSchema,ReviewIntelligenceContextResultSchema,RoughCutAdmissionSchema,RoughCutManifestReaderSchema,RoughCutStartSchema,RoughCutTechnicalSchema,ValidateReviewIntelligenceSchema,VisualRequirementSchema}from"./chunk-HLKERZIE.js";import{OperationIdSchema}from"./chunk-VPYAXWXY.js";import{fail,localSocketPath,privateAccess,privateDirectory,read,sha256,sha512}from"./chunk-66CUOZVI.js";import{NativeStudioSdkError}from"./chunk-6NVIN2NI.js";import{z as z2}from"zod";import{z}from"zod";var LocalIdSchema=z.uuid().transform(v=>v.toLowerCase());var LocalDigestSchema=z.string().length(64).regex(/^[0-9a-f]{64}$/);var LocalRevisionSchema=z.int().positive();var LocalTimeSchema=z.iso.datetime({offset:true});var LocalPackageVersionSchema=z.string().max(120).regex(/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-(?:0|[1-9]\d*|\d*[A-Za-z-][0-9A-Za-z-]*)(?:\.(?:0|[1-9]\d*|\d*[A-Za-z-][0-9A-Za-z-]*))*)?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/).refine(v=>v===v.trim());var LocalProjectScopeSchema=z.strictObject({tenantId:LocalIdSchema,projectId:LocalIdSchema});var LocalWorkScopeSchema=LocalProjectScopeSchema.extend({productionId:LocalIdSchema,runtimeJobId:LocalIdSchema});var LocalPlacementPolicySchema=z.discriminatedUnion("mode",[z.strictObject({mode:z.literal("local-only"),deviceId:LocalIdSchema}),z.strictObject({mode:z.literal("local-preferred"),deviceId:LocalIdSchema}),z.strictObject({mode:z.literal("cloud-only")})]);var LocalPlacementAvailabilitySchema=z.discriminatedUnion("status",[z.strictObject({status:z.literal("AVAILABLE"),deviceId:LocalIdSchema}),z.strictObject({status:z.literal("UNAVAILABLE"),deviceId:LocalIdSchema,reason:z.enum(["OFFLINE","UNQUALIFIED","BUSY"])}),z.strictObject({status:z.literal("DENIED"),reason:z.enum(["FORBIDDEN","APPROVAL_REQUIRED","INVALID_INPUT"])})]);var LocalDevicePlatformSchema=z2.strictObject({os:z2.enum(["darwin","linux","win32"]),architecture:z2.enum(["x64","arm64"])});var EnrollLocalDeviceSchema=z2.strictObject({tenantId:LocalIdSchema,requestId:LocalIdSchema,label:z2.string().trim().min(1).max(120),platform:LocalDevicePlatformSchema,runtimeVersion:LocalPackageVersionSchema,publicKey:NativeRuntimePublicKeySchema});var LocalDeviceViewSchema=EnrollLocalDeviceSchema.omit({requestId:true}).extend({deviceId:LocalIdSchema,revision:LocalRevisionSchema,enrolledByPrincipalId:LocalIdSchema,createdAt:LocalTimeSchema,verifiedAt:LocalTimeSchema.nullable(),revokedAt:LocalTimeSchema.nullable()}).refine(v=>[v.verifiedAt,v.revokedAt].every(time=>time===null||Date.parse(time)>=Date.parse(v.createdAt)));var LocalDeviceChallengeSchema=z2.strictObject({tenantId:LocalIdSchema,deviceId:LocalIdSchema,deviceRevision:LocalRevisionSchema,challengeId:LocalIdSchema,audience:z2.string().min(1).max(2048),issuedAt:LocalTimeSchema,expiresAt:LocalTimeSchema}).refine(v=>{const ttl=Date.parse(v.expiresAt)-Date.parse(v.issuedAt);return ttl>0&&ttl<=3e5});var LocalDeviceProofClaimsSchema=z2.strictObject({protocol:z2.literal("NVS_LOCAL_DEVICE_PROOF_V1"),tenantId:LocalIdSchema,deviceId:LocalIdSchema,deviceRevision:LocalRevisionSchema,challengeId:LocalIdSchema,audience:z2.string().min(1).max(2048),jti:LocalIdSchema,iat:z2.int().nonnegative(),exp:z2.int().positive()}).refine(v=>v.exp>v.iat&&v.exp-v.iat<=60);var ProveLocalDeviceSchema=z2.strictObject({tenantId:LocalIdSchema,deviceId:LocalIdSchema,deviceRevision:LocalRevisionSchema,challengeId:LocalIdSchema,assertion:z2.string().max(4096).regex(/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/).meta({writeOnly:true})});var GrantLocalDeviceSchema=LocalProjectScopeSchema.extend({requestId:LocalIdSchema,deviceId:LocalIdSchema,deviceRevision:LocalRevisionSchema,expectedRevision:z2.int().nonnegative(),expiresAt:LocalTimeSchema,capability:z2.literal("ROUGH_CUT_PREVIEW_V1")});var LocalDeviceGrantSchema=GrantLocalDeviceSchema.omit({requestId:true,expectedRevision:true}).extend({grantId:LocalIdSchema,revision:LocalRevisionSchema,approvedByPrincipalId:LocalIdSchema,createdAt:LocalTimeSchema,revokedAt:LocalTimeSchema.nullable()}).refine(v=>Date.parse(v.expiresAt)>Date.parse(v.createdAt));var RevokeLocalDeviceGrantSchema=LocalProjectScopeSchema.extend({grantId:LocalIdSchema,requestId:LocalIdSchema,expectedRevision:LocalRevisionSchema});var RevokeLocalDeviceSchema=z2.strictObject({tenantId:LocalIdSchema,deviceId:LocalIdSchema,requestId:LocalIdSchema,expectedRevision:LocalRevisionSchema});import{z as z4}from"zod";import{z as z3}from"zod";var LocalExecutionProfileSchema=z3.strictObject({kind:z3.literal("ROUGH_CUT_PREVIEW_V1"),profileId:z3.literal("PREVIEW_H264_480P_V1"),contractDigest:LocalDigestSchema});var LocalToolchainSchema=z3.strictObject({platform:LocalDevicePlatformSchema,rendererVersion:LocalPackageVersionSchema,rendererDigest:LocalDigestSchema,ffmpeg:z3.strictObject({version:z3.string().min(1).max(160),binaryDigest:LocalDigestSchema}),ffprobe:z3.strictObject({version:z3.string().min(1).max(160),binaryDigest:LocalDigestSchema}),profile:LocalExecutionProfileSchema});var LocalFrozenWorkSchema=LocalWorkScopeSchema.extend({protocol:z3.literal("NVS_LOCAL_WORK_V1"),operationId:OperationIdSchema,renderId:LocalIdSchema,productionRevision:LocalRevisionSchema,executionClass:z3.enum(["LIVE","TEST_ONLY"]),policy:LocalPlacementPolicySchema,profile:LocalExecutionProfileSchema,manifest:RoughCutManifestReaderSchema,manifestFingerprint:LocalDigestSchema,sources:z3.array(z3.strictObject({artifactId:LocalIdSchema,representationId:LocalIdSchema,checksumSha256:LocalDigestSchema,byteSize:z3.int().positive(),contentType:z3.string().min(1).max(100)})).min(1).max(512)}).superRefine((v,ctx)=>{const t=v.manifest.timeline;if(t.tenantId!==v.tenantId||t.projectId!==v.projectId||t.productionId!==v.productionId||t.executionClass!==v.executionClass)ctx.addIssue({code:"custom",message:"Frozen manifest scope/class mismatch"});if(new Set(v.sources.map(s=>s.representationId)).size!==v.sources.length)ctx.addIssue({code:"custom",message:"Duplicate source representation"})});var LocalLeaseBindingSchema=LocalWorkScopeSchema.extend({attemptId:LocalIdSchema,assignmentRevision:LocalRevisionSchema,workerId:z3.string().min(1).max(200),workFingerprint:LocalDigestSchema,toolchainFingerprint:LocalDigestSchema});var target=z3.discriminatedUnion("kind",[z3.strictObject({kind:z3.literal("DEVICE"),deviceId:LocalIdSchema,deviceRevision:LocalRevisionSchema,grantId:LocalIdSchema,grantRevision:LocalRevisionSchema}),z3.strictObject({kind:z3.literal("SERVER")})]);var LocalExecutionLeaseSchema=LocalLeaseBindingSchema.extend({target,issuedAt:LocalTimeSchema,expiresAt:LocalTimeSchema}).refine(v=>Date.parse(v.expiresAt)>Date.parse(v.issuedAt));var LocalWorkAssignmentSchema=z3.strictObject({work:LocalFrozenWorkSchema,lease:LocalExecutionLeaseSchema,toolchain:LocalToolchainSchema}).superRefine(({work,lease,toolchain},ctx)=>{if(["tenantId","projectId","productionId","runtimeJobId"].some(k=>work[k]!==lease[k]))ctx.addIssue({code:"custom",message:"Assignment work scope mismatch"});const p=work.policy,t=lease.target;if(p.mode==="cloud-only"&&t.kind!=="SERVER"||p.mode==="local-only"&&t.kind!=="DEVICE"||t.kind==="DEVICE"&&(p.mode==="cloud-only"||p.deviceId!==t.deviceId))ctx.addIssue({code:"custom",message:"Assignment contradicts placement policy"});if(work.profile.contractDigest!==toolchain.profile.contractDigest)ctx.addIssue({code:"custom",message:"Unqualified execution profile"})});var StartLocalPreviewSchema=RoughCutStartSchema.extend({placement:LocalPlacementPolicySchema});var LocalDeviceScopeSchema=z4.strictObject({tenantId:LocalIdSchema,deviceId:LocalIdSchema});var LocalDeviceSessionSchema=z4.strictObject({...LocalDeviceScopeSchema.shape,expiresAt:LocalTimeSchema,credential:z4.string().length(43).regex(/^[A-Za-z0-9_-]+$/).meta({writeOnly:true})});var LocalDeviceHeartbeatSchema=LocalDeviceScopeSchema.extend({toolchain:LocalToolchainSchema,available:z4.boolean()});var ClaimLocalPreviewSchema=LocalProjectScopeSchema.extend({requestId:LocalIdSchema,deviceId:LocalIdSchema});var LocalOutputStageSchema=LocalLeaseBindingSchema.extend({uploadRequestId:LocalIdSchema,role:z4.enum(["VIDEO","POSTER"]),checksumSha256:LocalDigestSchema,byteSize:z4.int().positive().max(128*1024*1024)});var LocalOutputTicketSchema=z4.strictObject({receiptId:LocalIdSchema,role:z4.enum(["VIDEO","POSTER"]),checksumSha256:LocalDigestSchema,byteSize:z4.int().positive(),uploaded:z4.boolean()});var LocalSourceRequestSchema=LocalLeaseBindingSchema.extend({representationId:LocalIdSchema});var LocalProofChallengeRequestSchema=LocalDeviceScopeSchema.extend({deviceRevision:z4.int().positive()});var LocalPreviewPlacementViewSchema=z4.strictObject({target:z4.enum(["DEVICE","SERVER"]),reason:z4.enum(["LOCAL_AVAILABLE","CLOUD_ONLY","OFFLINE","UNQUALIFIED","BUSY","LEASE_RECOVERY"]),policy:LocalPlacementPolicySchema});var LocalDeviceTransportConfigurationSchema=z4.strictObject({endpoint:z4.string().url().max(2048),tenantId:LocalIdSchema,deviceId:LocalIdSchema,deviceRevision:z4.int().positive(),projects:z4.array(LocalProjectScopeSchema).min(1).max(20),privateKeyFile:z4.string().min(1).max(4096),platform:LocalDevicePlatformSchema});var LocalPreviewAdmissionSchema=RoughCutAdmissionSchema.extend({placement:LocalPreviewPlacementViewSchema});var LocalClaimReceiptSchema=z4.strictObject({found:z4.boolean(),assignment:LocalWorkAssignmentSchema.nullable()});var LocalWorkStateSchema=z4.strictObject({binding:LocalLeaseBindingSchema,status:z4.enum(["ACTIVE","FENCED","OUTCOME_UNKNOWN"]),assignment:LocalWorkAssignmentSchema.nullable()});import{z as z9}from"zod";import{z as z6}from"zod";import{z as z5}from"zod";var executable=z5.strictObject({path:z5.string().min(1).max(4096),digest:LocalDigestSchema});var LocalToolSelectionSchema=z5.strictObject({mode:z5.enum(["MANAGED","INSTALLED"]),ffmpeg:executable,ffprobe:executable});var LocalRuntimeDescriptorSchema=z6.strictObject({protocol:z6.literal("NVS_RUNTIME_DESCRIPTOR_V1"),version:LocalPackageVersionSchema,node:z6.strictObject({major:z6.literal(24),minMinor:z6.literal(12)}),platform:LocalDevicePlatformSchema,ipcProtocol:z6.literal("NVS_LOCAL_IPC_V1"),workProtocol:z6.literal("NVS_LOCAL_WORK_V1"),journalSchema:z6.literal(1),rendererDigest:LocalDigestSchema,profileDigest:LocalDigestSchema});var LocalSessionConnectorSchema=z6.strictObject({protocol:z6.literal("NVS_LOCAL_CONNECTOR_V1"),stateDirectory:z6.string().min(1).max(4096),credential:z6.string().length(43).regex(/^[A-Za-z0-9_-]{43}$/),expiresAt:LocalTimeSchema,projects:z6.array(LocalProjectScopeSchema).min(1).max(100)});var LocalManagementInventorySchema=z6.strictObject({runtimeRevision:z6.int().positive(),descriptor:LocalRuntimeDescriptorSchema,activeProcesses:z6.int().nonnegative(),pendingExecutions:z6.int().nonnegative(),pendingRequests:z6.int().nonnegative(),pendingRenderers:z6.array(LocalDigestSchema).max(64)});var LocalReleaseAssetSchema=z6.strictObject({url:z6.string().url().max(2048),byteSize:z6.int().positive().max(256*1024*1024),sha512:z6.string().length(128).regex(/^[0-9a-f]{128}$/)});var LocalReleaseSchema=z6.strictObject({descriptor:LocalRuntimeDescriptorSchema,package:LocalReleaseAssetSchema,tools:z6.strictObject({ffmpeg:LocalReleaseAssetSchema.extend({sha256:LocalDigestSchema}),ffprobe:LocalReleaseAssetSchema.extend({sha256:LocalDigestSchema})}).nullable()});var LocalReleaseCatalogueSchema=z6.strictObject({protocol:z6.literal("NVS_LOCAL_RELEASE_CATALOGUE_V1"),issuedAt:LocalTimeSchema,expiresAt:LocalTimeSchema,releases:z6.array(LocalReleaseSchema).min(1).max(32)}).refine(v=>Date.parse(v.expiresAt)>Date.parse(v.issuedAt)&&Date.parse(v.expiresAt)-Date.parse(v.issuedAt)<=7*864e5&&new Set(v.releases.map(r=>[r.descriptor.version,r.descriptor.platform.os,r.descriptor.platform.architecture].join(":"))).size===v.releases.length);var LocalSignedCatalogueSchema=z6.strictObject({catalogue:LocalReleaseCatalogueSchema,signature:z6.string().length(86).regex(/^[A-Za-z0-9_-]{85}[AQgw]$/)});var LocalToolChoiceSchema=z6.discriminatedUnion("mode",[z6.strictObject({mode:z6.literal("MANAGED")}),LocalToolSelectionSchema.extend({mode:z6.literal("INSTALLED")})]);var LocalUpdatePlanSchema=z6.strictObject({protocol:z6.literal("NVS_LOCAL_UPDATE_PLAN_V1"),planId:LocalIdSchema,installationRevision:z6.int().nonnegative(),runtimeRevision:z6.int().positive().nullable(),catalogueFingerprint:LocalDigestSchema,trustFingerprint:LocalDigestSchema.optional(),release:LocalReleaseSchema,toolSelection:LocalToolChoiceSchema.optional(),fingerprint:LocalDigestSchema,createdAt:LocalTimeSchema,expiresAt:LocalTimeSchema});var LocalClientNextActionSchema=z6.strictObject({surface:z6.enum(["CLI","LOCAL_IPC","REMOTE"]),operation:z6.enum(["runtime.status","local.configure","local.install","local.start","local.connect","local.grant","local.status","local.doctor","local.stop","local.update.check","local.update.prepare","local.update.apply","local.update.reconcile","execution.inspect","rough_cut_get","operation_get"]),availability:z6.enum(["AVAILABLE","BLOCKED"]),reason:z6.enum(["READY","INSTALL_REQUIRED","AUTHORIZATION_REQUIRED","VERSION_INCOMPATIBLE","UPDATE_AVAILABLE","RECOVERY_REQUIRED","USER_APPROVAL_REQUIRED","TRUST_REQUIRED","UNAVAILABLE"])});import{z as z8}from"zod";import{z as z7}from"zod";function canonicalLocalJson(value){if(value===null||typeof value==="string"||typeof value==="boolean")return JSON.stringify(value);if(typeof value==="number"&&Number.isFinite(value))return JSON.stringify(value);if(Array.isArray(value))return"["+value.map(canonicalLocalJson).join(",")+"]";if(typeof value==="object")return"{"+Object.entries(value).filter(([,v])=>v!==void 0).sort(([a],[b])=>a<b?-1:a>b?1:0).map(([k,v])=>JSON.stringify(k)+":"+canonicalLocalJson(v)).join(",")+"}";throw new Error("Fingerprint input must be finite JSON data")}var sha=z7.string().regex(/^[a-f0-9]{64}$/);var qualifiedVersion=z7.enum(["0.164.0","0.165.0"]);var LocalAgentGrantSchema=z7.strictObject({protocol:z7.literal("NVS_CODEX_REVIEW_GRANT_V1"),binary:z7.string().min(1).max(4096).startsWith("/"),binaryDigest:sha,version:qualifiedVersion,model:z7.string().regex(/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,99}$/),reasoningEffort:z7.enum(["low","medium","high","xhigh"]).optional(),reviewerLabel:z7.string().trim().min(1).max(100),inference:z7.literal("REMOTE_OPENAI"),remoteUseApproved:z7.literal(true),imageDisclosureApproved:z7.literal(true).optional(),projects:z7.array(LocalProjectScopeSchema).min(1).max(100),expiresAt:z7.iso.datetime({offset:true})});var LocalAgentSnapshotSchema=z7.strictObject({basis:ReviewIntelligenceBasisSchema.extend({target:z7.strictObject({kind:z7.literal("IMAGE"),generationId:z7.uuid()})}),productionRevision:z7.int().positive(),reviewVersion:z7.int().nonnegative(),executionClass:z7.enum(["LIVE","TEST_ONLY"]),media:ReviewEvidenceMediaSchema,requirements:z7.array(VisualRequirementSchema).min(1).max(64),image:z7.strictObject({contentType:z7.literal("image/png"),byteSize:z7.int().positive().max(8388608),width:z7.int().positive().max(4096),height:z7.int().positive().max(4096)}).optional()}).refine(v=>new TextEncoder().encode(JSON.stringify(v)).length<=32768).refine(v=>new Set(v.requirements.map(r=>r.key)).size===v.requirements.length);var LocalAgentProbeSchema=z7.strictObject({configured:z7.boolean(),available:z7.boolean(),reason:z7.enum(["GRANT_REQUIRED","READY","RUNTIME_UNAVAILABLE","GRANT_EXPIRED"]),grantFingerprint:sha.nullable(),inference:z7.literal("REMOTE_OPENAI")});var LocalAgentPlanSchema=z7.strictObject({protocol:z7.literal("NVS_LOCAL_AGENT_REVIEW_V1"),id:z7.uuid(),grantFingerprint:sha,snapshot:LocalAgentSnapshotSchema,expiresAt:z7.iso.datetime({offset:true}),fingerprint:sha});var LocalAgentMetadataAnswerSchema=z7.strictObject({summary:z7.string().trim().min(1).max(1500),observations:z7.array(z7.strictObject({key:z7.string().min(1).max(200),observed:z7.string().trim().min(1).max(1e3)})).min(1).max(64)});var LocalAgentPixelAnswerSchema=z7.strictObject({summary:z7.string().trim().min(1).max(1500),imageReadback:z7.string().trim().min(1).max(800),observations:z7.array(KeyframeObservationSchema.omit({region:true})).min(1).max(64)});var LocalAgentAnswerSchema=z7.union([LocalAgentMetadataAnswerSchema,LocalAgentPixelAnswerSchema]).refine(v=>new TextEncoder().encode(JSON.stringify(v)).length<=96*1024);var LocalAgentImageReceiptSchema=z7.strictObject({protocol:z7.literal("NVS_LOCAL_AGENT_IMAGE_V1"),draftId:z7.uuid(),media:ReviewEvidenceMediaSchema,byteSize:z7.int().positive().max(8388608),contentType:z7.literal("image/png"),width:z7.int().positive().max(4096),height:z7.int().positive().max(4096)});var LocalAgentReviewViewSchema=z7.strictObject({plan:LocalAgentPlanSchema,revision:z7.int().positive(),phase:z7.enum(["PREPARED","RUNNING","RESULT_PENDING","UNKNOWN"]),answer:LocalAgentAnswerSchema.nullable(),imageReceipt:LocalAgentImageReceiptSchema.optional(),provenance:z7.strictObject({adapter:z7.literal("CODEX_METADATA_V1"),binaryDigest:sha,version:qualifiedVersion,model:z7.string().max(100),reasoningEffort:z7.enum(["low","medium","high","xhigh"]).optional(),reviewerLabel:z7.string().max(100),inference:z7.literal("REMOTE_OPENAI"),evidence:z7.enum(["METADATA_ONLY","IMAGE_PIXELS"])})}).refine(v=>{const image=v.plan.snapshot.image,receipt=v.imageReceipt;if(receipt&&(!image||receipt.draftId!==v.plan.id||canonicalLocalJson(receipt.media)!==canonicalLocalJson(v.plan.snapshot.media)||canonicalLocalJson({contentType:receipt.contentType,byteSize:receipt.byteSize,width:receipt.width,height:receipt.height})!==canonicalLocalJson(image)))return false;if(v.phase==="RESULT_PENDING"!==!!v.answer)return false;if(v.answer&&!!image!=="imageReadback"in v.answer)return false;const pixels=v.phase==="RESULT_PENDING"&&!!image;return v.provenance.evidence===(pixels?"IMAGE_PIXELS":"METADATA_ONLY")&&(!pixels||!!receipt)});function localAgentSnapshotFromContext(raw,includeImage=false){const c=ReviewIntelligenceContextResultSchema.parse(raw);if(c.reviewTarget.kind!=="IMAGE"||c.basis.target.kind!=="IMAGE"||c.ownerContext.semanticStatus!=="SUCCESS")throw Error("LOCAL_AGENT_CONTEXT_UNAVAILABLE");const t=c.reviewTarget.target,scope=c.basis.scope;if(!t.runtimeSucceeded||t.candidate.availability!=="AVAILABLE"||t.candidate.freshness!=="CURRENT_BASIS"||!t.productionRunnable||t.freshness!=="CURRENT_BASIS"||t.generationId!==c.basis.target.generationId||t.tenantId!==scope.tenantId||t.projectId!==scope.projectId||t.productionId!==scope.productionId||c.ownerContext.basis.tenantId!==scope.tenantId||c.ownerContext.basis.projectId!==scope.projectId||c.ownerContext.basis.productionId!==scope.productionId)throw Error("LOCAL_AGENT_CONTEXT_UNAVAILABLE");return LocalAgentSnapshotSchema.parse({basis:c.basis,productionRevision:c.ownerContext.basis.productionRevision,reviewVersion:t.reviewVersion,executionClass:t.executionClass,media:{artifactId:t.candidate.artifactId,representationId:t.candidate.representationId,checksumSha256:t.candidate.checksumSha256},requirements:t.requirements,...includeImage?{image:{contentType:t.candidate.contentType,byteSize:t.candidate.byteSize,width:t.candidate.width,height:t.candidate.height}}:{}})}function localAgentNativeProposal(raw){const v=LocalAgentReviewViewSchema.parse(raw);if(v.phase!=="RESULT_PENDING"||!v.answer)throw Error("LOCAL_AGENT_RESULT_UNAVAILABLE");const keys=new Set(v.answer.observations.map(o=>o.key));if(keys.size!==v.answer.observations.length||keys.size!==v.plan.snapshot.requirements.length||v.plan.snapshot.requirements.some(r=>!keys.has(r.key)))throw Error("LOCAL_AGENT_RESULT_UNAVAILABLE");const p=v.provenance;const pixels=p.evidence==="IMAGE_PIXELS";return ValidateReviewIntelligenceSchema.parse({basis:v.plan.snapshot.basis,proposal:{origin:{kind:"EXTERNAL_AGENT_HOST",label:p.reviewerLabel},summary:`${pixels?"IMAGE_PIXELS":"METADATA_ONLY; no visual inspection"}. Codex ${p.version}; model ${p.model}; effort ${p.reasoningEffort??"DEFAULT"}; binary ${p.binaryDigest}; draft ${v.plan.id}; plan ${v.plan.fingerprint}. ${v.answer.summary}`,evidence:pixels?[{id:"original_image",label:"Verified ORIGINAL PNG attachment",producer:"EXTERNAL_AGENT_HOST",kind:"IMAGE_PIXELS",media:v.plan.snapshot.media}]:[],review:{kind:"IMAGE",observations:v.answer.observations.map(o=>({...o,status:pixels&&"status"in o?o.status:"NOT_OBSERVABLE",confidence:pixels&&"confidence"in o?o.confidence:"UNCERTAIN",evidenceIds:pixels?["original_image"]:[]}))}}})}var projectInput=LocalProjectScopeSchema;var LocalExecutionListInputSchema=LocalProjectScopeSchema.extend({after:z8.string().length(64).regex(/^[0-9a-f]{64}$/).nullable().default(null),limit:z8.int().min(1).max(16).default(8)});var LocalIpcCallSchema=z8.discriminatedUnion("operation",[z8.strictObject({operation:z8.literal("agent.grant"),grant:LocalAgentGrantSchema,approval:z8.string().regex(/^[a-f0-9]{64}$/)}),z8.strictObject({operation:z8.literal("agent.probe")}),z8.strictObject({operation:z8.literal("agent.revoke"),approval:z8.string().regex(/^[a-f0-9]{64}$/)}),z8.strictObject({operation:z8.literal("agent.prepare"),snapshot:LocalAgentSnapshotSchema}),z8.strictObject({operation:z8.literal("agent.start"),id:z8.uuid(),expectedRevision:LocalRevisionSchema,approval:z8.string().regex(/^[a-f0-9]{64}$/)}),z8.strictObject({operation:z8.literal("agent.inspect"),id:z8.uuid()}),z8.strictObject({operation:z8.literal("runtime.status")}),z8.strictObject({operation:z8.literal("runtime.doctor")}),z8.strictObject({operation:z8.literal("runtime.inventory")}),z8.strictObject({operation:z8.literal("session.issue"),projects:z8.array(projectInput).min(1).max(100),expiresAt:z8.iso.datetime({offset:true})}),z8.strictObject({operation:z8.literal("runtime.stop"),expectedRuntimeRevision:LocalRevisionSchema}),z8.strictObject({operation:z8.literal("execution.inspect"),input:LocalWorkScopeSchema}),z8.strictObject({operation:z8.literal("execution.list"),input:LocalExecutionListInputSchema}),z8.strictObject({operation:z8.literal("update.check")}),z8.strictObject({operation:z8.literal("update.prepare"),targetVersion:LocalPackageVersionSchema,expectedRuntimeRevision:LocalRevisionSchema}),z8.strictObject({operation:z8.literal("update.apply"),planId:LocalIdSchema,targetVersion:LocalPackageVersionSchema,expectedRuntimeRevision:LocalRevisionSchema})]);var LocalNextActionSchema=z8.strictObject({call:LocalIpcCallSchema,availability:z8.enum(["AVAILABLE","BLOCKED"]),reason:z8.enum(["READY","INSTALL_REQUIRED","AUTHORIZATION_REQUIRED","VERSION_INCOMPATIBLE","UPDATE_AVAILABLE","RECOVERY_REQUIRED"])});var LocalIpcRequestSchema=z8.strictObject({protocol:z8.literal("NVS_LOCAL_IPC_V1"),requestId:LocalIdSchema,call:LocalIpcCallSchema});var LocalVersionReportSchema=z8.strictObject({component:z8.enum(["CLI","SDK","MCP","RUNTIME","MEDIA_TOOLS"]),installedVersion:LocalPackageVersionSchema.nullable(),runningVersion:LocalPackageVersionSchema.nullable(),availableVersion:LocalPackageVersionSchema.nullable(),executablePath:z8.string().min(1).max(4096).nullable(),installOwner:z8.enum(["NPM_GLOBAL","PROJECT","NPX","MANAGED","TARBALL","UNKNOWN"])});var LocalRuntimeStatusSchema=z8.strictObject({protocol:z8.literal("NVS_LOCAL_IPC_V1"),runtimeRevision:LocalRevisionSchema,state:z8.enum(["IDLE","EXECUTING","DRAINING","RECOVERY_REQUIRED"]),journalSchemaVersion:z8.literal(1),workProtocols:z8.array(z8.literal("NVS_LOCAL_WORK_V1")).min(1).max(1),versions:z8.array(LocalVersionReportSchema).max(8),authorizedProjects:z8.array(projectInput).max(100),nextActions:z8.array(LocalNextActionSchema).max(8)});var LocalDoctorReportSchema=z8.strictObject({mode:z8.enum(["MANAGED","INSTALLED"]),availability:z8.enum(["AVAILABLE","UNAVAILABLE"]),reason:z8.enum(["QUALIFIED_PROCESS_TOOLS","MANAGED_TOOLS_MISSING","TOOL_QUALIFICATION_FAILED"]),nativeExecutionReady:z8.boolean(),tools:z8.array(z8.strictObject({name:z8.enum(["FFMPEG","FFPROBE"]),path:z8.string().min(1).max(4096),version:z8.string().min(1).max(200),digest:z8.string().regex(/^[0-9a-f]{64}$/)})).max(2)});var LocalExecutionInspectionSchema=z8.strictObject({binding:LocalLeaseBindingSchema,revision:LocalRevisionSchema,phase:z8.enum(["STAGED","RUNNING","RECOVERY_REQUIRED","OUTPUT_PENDING","RECEIPT_RECORDED","FENCED"]),checkpoint:z8.enum(["ADOPTED","SOURCES_READY","PROCESS_STARTED","OUTPUT_STAGED"])});var LocalExecutionPageSchema=z8.strictObject({items:z8.array(LocalExecutionInspectionSchema).max(16),nextCursor:z8.string().length(64).regex(/^[0-9a-f]{64}$/).nullable()});var LocalIpcErrorCodeSchema=z8.enum(["FORBIDDEN","INVALID_INPUT","FRAME_LIMIT","BUSY","AUTHORIZATION_REQUIRED","REVISION_CONFLICT","CAPABILITY_UNAVAILABLE","INTERNAL_OPERATIONAL_FAILURE","AGENT_APPROVAL_REQUIRED","AGENT_GRANT_REQUIRED","AGENT_OUTCOME_UNKNOWN","AGENT_IMAGE_REQUIRED","AGENT_IMAGE_INVALID","AGENT_IMAGE_BUDGET_EXCEEDED","AGENT_IMAGE_AUTHORIZATION_REQUIRED"]);var LocalIpcResponseSchema=z8.discriminatedUnion("semanticStatus",[z8.strictObject({protocol:z8.literal("NVS_LOCAL_IPC_V1"),requestId:LocalIdSchema,semanticStatus:z8.literal("SUCCESS"),data:z8.union([LocalRuntimeStatusSchema,LocalDoctorReportSchema,LocalExecutionInspectionSchema.nullable(),z8.strictObject({state:z8.literal("DRAINING"),inventory:LocalManagementInventorySchema.optional(),backupPath:z8.string().min(1).max(4096).optional()}),LocalSessionConnectorSchema,LocalManagementInventorySchema,LocalExecutionPageSchema,LocalAgentProbeSchema,LocalAgentReviewViewSchema])}),z8.strictObject({protocol:z8.literal("NVS_LOCAL_IPC_V1"),requestId:LocalIdSchema.nullable(),semanticStatus:z8.enum(["BLOCKED","INVALID_INPUT"]),error:z8.strictObject({code:LocalIpcErrorCodeSchema})})]);var LocalMcpToolNameSchema=z9.enum(["local_navigate","local_capability_describe","local_runtime_status","local_execution_list","local_execution_inspect","local_update_check"]);var LocalMcpActionSchema=z9.strictObject({tool:LocalMcpToolNameSchema,arguments:z9.record(z9.string(),z9.unknown()),availability:z9.enum(["AVAILABLE","BLOCKED"]).optional(),reason:z9.string().max(100).optional()});var LocalMcpNavigationSchema=z9.strictObject({location:z9.literal("LOCAL"),state:z9.enum(["UNAVAILABLE","IDLE","EXECUTING","DRAINING","RECOVERY_REQUIRED"]),authorizedProjects:z9.array(LocalProjectScopeSchema).max(100).optional(),groups:z9.array(z9.strictObject({id:z9.string().max(40),label:z9.string().max(100),tools:z9.array(LocalMcpToolNameSchema).max(6)})).max(4),nextActions:z9.array(z9.union([LocalMcpActionSchema,LocalClientNextActionSchema])).max(16)});var LocalMcpExecutionPageSchema=LocalExecutionPageSchema.extend({nextActions:z9.array(LocalMcpActionSchema).max(16)});var LocalMcpInspectionSchema=z9.strictObject({location:z9.literal("LOCAL"),execution:LocalExecutionInspectionSchema.nullable(),nextActions:z9.array(LocalMcpActionSchema).max(4)});var LocalMcpUpdateSchema=z9.strictObject({location:z9.literal("LOCAL"),running:z9.array(LocalVersionReportSchema).max(8),available:z9.array(LocalRuntimeDescriptorSchema).max(32),nextActions:z9.array(LocalClientNextActionSchema).max(4)});var LocalMcpDescriptionSchema=z9.strictObject({location:z9.literal("LOCAL"),tool:LocalMcpToolNameSchema,schema:z9.object({name:LocalMcpToolNameSchema,description:z9.string(),inputSchema:z9.record(z9.string(),z9.unknown())}).passthrough()});var LocalMcpFailureSchema=z9.strictObject({semanticStatus:z9.enum(["BLOCKED","INVALID_INPUT"]),error:z9.strictObject({code:z9.enum(["AUTHORIZATION_REQUIRED","FORBIDDEN","LOCAL_RUNTIME_UNAVAILABLE","RELEASE_UNAVAILABLE","VERSION_INCOMPATIBLE","INVALID_INPUT","LOCAL_CAPABILITY_UNAVAILABLE"]),outcome:z9.literal("NO_WRITE")}),nextActions:z9.array(LocalClientNextActionSchema).max(4)});var LocalMcpOutputSchemas={local_navigate:LocalMcpNavigationSchema,local_capability_describe:LocalMcpDescriptionSchema,local_runtime_status:LocalRuntimeStatusSchema.omit({nextActions:true}).extend({nextActions:z9.array(LocalMcpActionSchema).max(8)}),local_execution_list:LocalMcpExecutionPageSchema,local_execution_inspect:LocalMcpInspectionSchema,local_update_check:LocalMcpUpdateSchema};import{z as z11}from"zod";function localBudget(timeoutMs,parent){if(!Number.isInteger(timeoutMs)||timeoutMs<1||timeoutMs>6e4)throw Error("LOCAL_DEADLINE_INVALID");const controller=new AbortController,timer=setTimeout(()=>controller.abort(),timeoutMs);return{signal:parent?AbortSignal.any([parent,controller.signal]):controller.signal,close:()=>clearTimeout(timer)}}async function localAbortable(work,signal){if(signal.aborted)void work.catch(()=>{});signal.throwIfAborted();return new Promise((resolve,reject)=>{const abort=()=>reject(Error("LOCAL_DEADLINE"));signal.addEventListener("abort",abort,{once:true});work.then(v=>{signal.removeEventListener("abort",abort);resolve(v)},e=>{signal.removeEventListener("abort",abort);reject(e)});if(signal.aborted)abort()})}import{z as z10}from"zod";var output=z10.discriminatedUnion("role",[z10.strictObject({role:z10.literal("VIDEO"),receiptId:LocalIdSchema,checksumSha256:LocalDigestSchema,byteSize:z10.int().positive().max(128*1024*1024),contentType:z10.literal("video/mp4")}),z10.strictObject({role:z10.literal("POSTER"),receiptId:LocalIdSchema,checksumSha256:LocalDigestSchema,byteSize:z10.int().positive().max(2*1024*1024),contentType:z10.literal("image/png")})]);var LocalCompletionSubmissionSchema=LocalLeaseBindingSchema.extend({requestId:LocalIdSchema,outputs:z10.array(output).length(2),technical:RoughCutTechnicalSchema}).superRefine((v,ctx)=>{const video=v.outputs.find(o=>o.role==="VIDEO");if(new Set(v.outputs.map(o=>o.role)).size!==2||new Set(v.outputs.map(o=>o.receiptId)).size!==2||!video||video.checksumSha256!==v.technical.checksumSha256||video.byteSize!==v.technical.byteSize)ctx.addIssue({code:"custom",message:"Exact video/poster receipts required"})});var LocalVerifiedUploadSchema=z10.strictObject({binding:LocalLeaseBindingSchema,output,verifiedAt:LocalTimeSchema});var LocalCompletionReceiptSchema=LocalLeaseBindingSchema.extend({submissionFingerprint:LocalDigestSchema.optional(),semanticStatus:z10.literal("SUCCESS"),requestId:LocalIdSchema,renderId:LocalIdSchema,operationId:OperationIdSchema,artifactId:LocalIdSchema,videoRepresentationId:LocalIdSchema,posterRepresentationId:LocalIdSchema,checksumSha256:LocalDigestSchema,acceptedAt:LocalTimeSchema});var GetLocalCompletionReceiptSchema=LocalLeaseBindingSchema.pick({tenantId:true,projectId:true,productionId:true,runtimeJobId:true}).extend({requestId:LocalIdSchema});var NativeStudioLocalDeviceClient=class{constructor(options){this.options=options;const u=new URL(options.baseUrl);if(u.username||u.password||u.search||u.hash||u.pathname!=="/"||u.protocol!=="https:"&&!(u.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(u.hostname)))throw new NativeStudioSdkError("INVALID_INPUT","INVALID_INPUT","NO_WRITE");this.origin=u.origin}options;origin;async command(route,raw,input,output2,signal){let started=false;const budget=localBudget(15e3,signal);try{const i=input.parse(raw);if(i.tenantId!==this.options.tenantId)throw Error();budget.signal.throwIfAborted();const authorization=await localAbortable(Promise.resolve().then(()=>this.options.authorization()),budget.signal);if(authorization!==authorization.trim()||!/^Bearer [A-Za-z0-9._~-]{1,8192}$/.test(authorization))throw Error();const body=JSON.stringify(i);if(Buffer.byteLength(body)>65536)throw Error();budget.signal.throwIfAborted();started=true;const r=await fetch(this.origin+"/v1/local-execution/"+route,{method:"POST",headers:{authorization,"content-type":"application/json"},body,redirect:"error",signal:budget.signal});if(!r.ok){await r.body?.cancel();throw new NativeStudioSdkError(r.status===403||r.status===401?"FORBIDDEN":"LOCAL_COMMAND_REFUSED","BLOCKED",r.status>=500?"UNKNOWN":"REJECTED",r.status)}const parts=[];let size=0;for await(const b of r.body??[]){size+=b.length;if(size>262144)throw Error();parts.push(b)}const value=output2.parse(JSON.parse(Buffer.concat(parts).toString()));if(value&&typeof value==="object"){const result=value,request3=i;for(const key of["tenantId","projectId","deviceId"])if(key in result&&key in request3&&result[key]!==request3[key])throw Error()}return value}catch(e){if(e instanceof NativeStudioSdkError)throw e;throw new NativeStudioSdkError(started?"LOCAL_COMMAND_UNKNOWN":"INVALID_INPUT",started?"BLOCKED":"INVALID_INPUT",started?"UNKNOWN":"NO_WRITE")}finally{budget.close()}}enroll(input,signal){return this.command("devices/enroll",input,EnrollLocalDeviceSchema,LocalDeviceViewSchema,signal)}grant(input,signal){return this.command("devices/grant",input,GrantLocalDeviceSchema,LocalDeviceGrantSchema,signal)}revokeDevice(input,signal){return this.command("devices/revoke",input,RevokeLocalDeviceSchema,z11.strictObject({semanticStatus:z11.literal("SUCCESS")}),signal)}revokeGrant(input,signal){return this.command("devices/revoke-grant",input,RevokeLocalDeviceGrantSchema,z11.strictObject({semanticStatus:z11.literal("SUCCESS")}),signal)}startPreview(input,signal){return this.command("previews",input,StartLocalPreviewSchema,LocalPreviewAdmissionSchema,signal)}};import{randomUUID,createHash}from"node:crypto";import{request}from"node:http";import{z as z12}from"zod";import{constants}from"node:fs";import{open,realpath}from"node:fs/promises";async function checkedLocalDirectory(path){await privateDirectory(path);return realpath(path)}async function readLocalCredential(path,maximum=32768){await privateAccess(path,"file");const file=await open(path,constants.O_RDONLY|constants.O_NOFOLLOW);try{const stat=await file.stat();if(!stat.isFile()||stat.nlink!==1||process.platform!=="win32"&&(stat.uid!==process.getuid?.()||stat.mode&63)||stat.size>maximum)throw Error("LOCAL_CREDENTIAL_INVALID");const bytes=Buffer.alloc(Math.min(maximum+1,stat.size+1));let used=0;while(used<bytes.length){const part=await file.read(bytes,used,bytes.length-used,null);if(!part.bytesRead)break;used+=part.bytesRead}if(used>stat.size)throw Error("LOCAL_CREDENTIAL_INVALID");if(used>maximum)throw Error("LOCAL_CREDENTIAL_INVALID");return bytes.subarray(0,used)}finally{await file.close()}}async function stageAgentImage(options,view,input,signal){const budget=localBudget(options.timeoutMs??1e4,signal);let dispatched=false;try{budget.signal.throwIfAborted();if(input.byteLength>8388608)throw Error();const bytes=Buffer.from(input),snapshot=view.plan.snapshot,id=z12.uuid().parse(view.plan.id),requestId=randomUUID();if(!snapshot.image||bytes.length!==snapshot.image.byteSize||bytes.length>8388608||createHash("sha256").update(bytes).digest("hex")!==snapshot.media.checksumSha256)throw Error();const root=await checkedLocalDirectory(options.stateDirectory),path=localSocketPath(root);await privateAccess(path,"pipe");const auth=await localAbortable(Promise.resolve().then(options.authorization),budget.signal);budget.signal.throwIfAborted();if(!/^Bearer [A-Za-z0-9_-]{43}$/.test(auth))throw Error();const reply=await new Promise((resolve,reject)=>{const req=request({socketPath:path,path:"/ipc/v1/agent-images/"+id,method:"PUT",signal:budget.signal,headers:{authorization:auth,"content-type":"image/png","content-length":bytes.length,"x-nvs-request-id":requestId}},res=>{let size=0;const chunks=[];res.on("error",reject);res.on("aborted",()=>reject(Error()));res.on("data",b=>{size+=b.length;if(size>262144)req.destroy(Error());else chunks.push(b)});res.on("end",()=>{try{resolve(JSON.parse(Buffer.concat(chunks).toString()))}catch{reject(Error())}})});req.on("error",reject);dispatched=true;req.end(bytes)});const response=LocalIpcResponseSchema.parse(reply);if(response.requestId!==requestId&&!(response.requestId===null&&response.semanticStatus!=="SUCCESS"&&["BUSY","FORBIDDEN"].includes(response.error.code)))throw Error();if(response.semanticStatus!=="SUCCESS")throw new NativeStudioSdkError(response.error.code,response.semanticStatus,response.error.code==="INTERNAL_OPERATIONAL_FAILURE"?"UNKNOWN":"REJECTED");const v=LocalAgentReviewViewSchema.parse(response.data),receipt=v.imageReceipt;if(v.plan.id!==id||canonicalLocalJson(v.plan)!==canonicalLocalJson(view.plan)||v.revision<view.revision||v.phase!=="PREPARED"||!receipt||receipt.draftId!==id||canonicalLocalJson(receipt.media)!==canonicalLocalJson(snapshot.media)||canonicalLocalJson({contentType:receipt.contentType,byteSize:receipt.byteSize,width:receipt.width,height:receipt.height})!==canonicalLocalJson(snapshot.image))throw Error();return v}catch(e){if(e instanceof NativeStudioSdkError)throw e;throw new NativeStudioSdkError("LOCAL_AGENT_IMAGE_TRANSFER_FAILED","BLOCKED",dispatched?"UNKNOWN":"NO_WRITE")}finally{budget.close()}}import{randomUUID as randomUUID2}from"node:crypto";import{request as request2}from"node:http";var NativeStudioLocalRuntimeClient=class _NativeStudioLocalRuntimeClient{constructor(options){this.options=options}options;static async fromConnector(path){const initial=LocalSessionConnectorSchema.parse(JSON.parse((await readLocalCredential(path)).toString()));return new _NativeStudioLocalRuntimeClient({stateDirectory:initial.stateDirectory,projects:initial.projects,authorization:async()=>{const current=LocalSessionConnectorSchema.parse(JSON.parse((await readLocalCredential(path)).toString()));if(current.stateDirectory!==initial.stateDirectory||canonicalLocalJson(current.projects)!==canonicalLocalJson(initial.projects)||Date.parse(current.expiresAt)>Date.parse(initial.expiresAt)||Date.parse(current.expiresAt)<=Date.now())throw Error("LOCAL_AUTHORIZATION_REQUIRED");return"Bearer "+current.credential}})}async call(call,signal){let started=false;const budget=localBudget(this.options.timeoutMs??(["runtime.doctor","agent.probe","agent.grant","agent.start"].includes(call.operation)?6e4:1e4),signal);const readOnly=["runtime.status","runtime.doctor","runtime.inventory","execution.inspect","execution.list","update.check","agent.probe","agent.inspect"].includes(call.operation);try{const input=LocalIpcRequestSchema.parse({protocol:"NVS_LOCAL_IPC_V1",requestId:randomUUID2(),call});const root=await checkedLocalDirectory(this.options.stateDirectory);const path=localSocketPath(root);await privateAccess(path,"pipe");budget.signal.throwIfAborted();const auth=await localAbortable(Promise.resolve().then(()=>this.options.authorization()),budget.signal);budget.signal.throwIfAborted();if(auth.length!==50||!/^Bearer [A-Za-z0-9_-]{43}$/.test(auth))throw Error();const body=JSON.stringify(input);const reply=await new Promise((resolve,reject)=>{const abort=budget.signal;const req=request2({socketPath:path,method:"POST",path:"/ipc/v1",signal:abort,headers:{authorization:auth,"content-type":"application/json","content-length":Buffer.byteLength(body)}},res=>{const chunks=[];let length=0;res.on("error",reject);res.on("aborted",()=>reject(Error()));res.on("data",b=>{length+=b.length;if(length>256*1024)req.destroy(Error());else chunks.push(b)});res.on("end",()=>{try{resolve(JSON.parse(Buffer.concat(chunks).toString()))}catch{reject(Error())}})});req.on("error",reject);started=true;req.end(body)});const value=LocalIpcResponseSchema.parse(reply);if(value.requestId!==input.requestId&&!(value.requestId===null&&value.semanticStatus!=="SUCCESS"&&["FORBIDDEN","BUSY","INVALID_INPUT"].includes(value.error.code)))throw Error();if(value.semanticStatus!=="SUCCESS")throw new NativeStudioSdkError(value.error.code,value.semanticStatus,readOnly?"NO_WRITE":value.error.code==="INTERNAL_OPERATIONAL_FAILURE"?"UNKNOWN":"REJECTED");if(value.requestId!==input.requestId)throw Error();return value.data}catch(error){if(error instanceof NativeStudioSdkError)throw error;throw new NativeStudioSdkError("LOCAL_RUNTIME_UNAVAILABLE","BLOCKED",started&&!readOnly?"UNKNOWN":"NO_WRITE")}finally{budget.close()}}response(schema,raw){const result=schema.safeParse(raw);if(!result.success)throw new NativeStudioSdkError("LOCAL_RESPONSE_INVALID","BLOCKED","NO_WRITE");return result.data}async status(signal){const value=this.response(LocalRuntimeStatusSchema,await this.call({operation:"runtime.status"},signal));if(this.options.projects&&value.authorizedProjects.some(p=>!this.options.projects.some(q=>q.tenantId===p.tenantId&&q.projectId===p.projectId)))throw new NativeStudioSdkError("LOCAL_SCOPE_INVALID","BLOCKED","NO_WRITE");return value}async doctor(signal){return this.response(LocalDoctorReportSchema,await this.call({operation:"runtime.doctor"},signal))}async inventory(signal){return this.response(LocalManagementInventorySchema,await this.call({operation:"runtime.inventory"},signal))}async grantAgent(raw,approval){return this.response(LocalAgentProbeSchema,await this.call({operation:"agent.grant",grant:LocalAgentGrantSchema.parse(raw),approval}))}async revokeAgent(approval){return this.response(LocalAgentProbeSchema,await this.call({operation:"agent.revoke",approval}))}async probeAgent(){return this.response(LocalAgentProbeSchema,await this.call({operation:"agent.probe"}))}async prepareAgentReview(snapshot){const input=LocalAgentSnapshotSchema.parse(snapshot);const v=this.response(LocalAgentReviewViewSchema,await this.call({operation:"agent.prepare",snapshot:input}));if(canonicalLocalJson(v.plan.snapshot)!==canonicalLocalJson(input))throw new NativeStudioSdkError("LOCAL_RESPONSE_INVALID","BLOCKED","UNKNOWN");return v}async startAgentReview(id,expectedRevision,approval){const v=this.response(LocalAgentReviewViewSchema,await this.call({operation:"agent.start",id,expectedRevision,approval}));if(v.plan.id!==id||v.plan.fingerprint!==approval)throw new NativeStudioSdkError("LOCAL_RESPONSE_INVALID","BLOCKED","UNKNOWN");return v}async stageAgentImage(id,bytes,signal){const budget=localBudget(this.options.timeoutMs??1e4,signal);try{return await stageAgentImage(this.options,await this.inspectAgentReview(id,budget.signal),bytes,budget.signal)}finally{budget.close()}}async inspectAgentReview(id,signal){const v=this.response(LocalAgentReviewViewSchema,await this.call({operation:"agent.inspect",id},signal));if(v.plan.id!==id)throw new NativeStudioSdkError("LOCAL_RESPONSE_INVALID","BLOCKED","NO_WRITE");return v}async executions(input,signal){const i=LocalExecutionListInputSchema.parse(input);if(this.options.projects&&!this.options.projects.some(p=>p.tenantId===i.tenantId&&p.projectId===i.projectId))throw new NativeStudioSdkError("FORBIDDEN","BLOCKED","NO_WRITE");const page=this.response(LocalExecutionPageSchema,await this.call({operation:"execution.list",input:i},signal));if(page.items.some(e=>e.binding.tenantId!==i.tenantId||e.binding.projectId!==i.projectId))throw new NativeStudioSdkError("LOCAL_SCOPE_INVALID","BLOCKED","NO_WRITE");return page}async inspect(raw,signal){const input=LocalWorkScopeSchema.parse(raw);if(this.options.projects&&!this.options.projects.some(p=>p.tenantId===input.tenantId&&p.projectId===input.projectId))throw new NativeStudioSdkError("FORBIDDEN","BLOCKED","NO_WRITE");const value=this.response(LocalExecutionInspectionSchema.nullable(),await this.call({operation:"execution.inspect",input},signal));if(value&&["tenantId","projectId","productionId","runtimeJobId"].some(k=>value.binding[k]!==input[k]))throw new NativeStudioSdkError("LOCAL_SCOPE_INVALID","BLOCKED","NO_WRITE");return value}};import{createPublicKey,verify}from"node:crypto";function endpoint(raw){const u=new URL(raw);if(u.username||u.password||u.search||u.hash||u.protocol!=="https:"&&!(u.protocol==="http:"&&["127.0.0.1","localhost","[::1]"].includes(u.hostname)))fail("RELEASE_ORIGIN_INVALID");return u}async function fetchBytes(raw,maximum,origin,signal=AbortSignal.timeout(3e4)){const u=endpoint(raw);if(u.origin!==origin)fail("RELEASE_ORIGIN_INVALID");const r=await fetch(u,{redirect:"error",signal,headers:{accept:"application/octet-stream"}});if(!r.ok||Number(r.headers.get("content-length"))>maximum){await r.body?.cancel();fail("RELEASE_UNAVAILABLE")}const parts=[];let size=0;for await(const part of r.body??[]){size+=part.byteLength;if(size>maximum){await r.body?.cancel().catch(()=>{});fail("RELEASE_LIMIT")}parts.push(part)}return Buffer.concat(parts)}async function catalogue(trust,signal){const origin=endpoint(trust.catalogueUrl).origin;const bytes=await fetchBytes(trust.catalogueUrl,65536,origin,signal??AbortSignal.timeout(3e4));const signed=LocalSignedCatalogueSchema.parse(JSON.parse(bytes.toString()));const key=createPublicKey((await read(trust.publicKeyFile,16384)).toString());if(key.asymmetricKeyType!=="ed25519"||!verify(null,Buffer.from(canonicalLocalJson(signed.catalogue)),key,Buffer.from(signed.signature,"base64url")))fail("RELEASE_SIGNATURE_INVALID");const now=Date.now();if(Date.parse(signed.catalogue.issuedAt)>now||Date.parse(signed.catalogue.expiresAt)<=now)fail("RELEASE_EXPIRED");for(const release of signed.catalogue.releases){for(const a of[release.package,...release.tools?Object.values(release.tools):[]])if(endpoint(a.url).origin!==origin)fail("RELEASE_ORIGIN_INVALID")}return{signed,fingerprint:sha256(canonicalLocalJson(signed.catalogue)),origin,trustFingerprint:sha256(canonicalLocalJson({catalogueUrl:endpoint(trust.catalogueUrl).href,publicKey:key.export({type:"spki",format:"der"}).toString("base64")}))}}function select(signed,version){const r=signed.catalogue.releases.find(r2=>r2.descriptor.version===version&&r2.descriptor.platform.os===process.platform&&r2.descriptor.platform.architecture===process.arch);if(!r)fail("VERSION_INCOMPATIBLE");const[major,minor]=process.versions.node.split(".").map(Number);if(major!==r.descriptor.node.major||minor<r.descriptor.node.minMinor)fail("NODE_VERSION_INCOMPATIBLE");return r}async function asset(a,origin){const bytes=await fetchBytes(a.url,a.byteSize,origin,AbortSignal.timeout(12e4));if(bytes.length!==a.byteSize||sha512(bytes)!==a.sha512)fail("RELEASE_INTEGRITY_INVALID");return bytes}export{LocalWorkScopeSchema,EnrollLocalDeviceSchema,GrantLocalDeviceSchema,RevokeLocalDeviceGrantSchema,RevokeLocalDeviceSchema,LocalToolSelectionSchema,LocalRuntimeDescriptorSchema,LocalManagementInventorySchema,LocalToolChoiceSchema,LocalUpdatePlanSchema,canonicalLocalJson,LocalAgentGrantSchema,localAgentSnapshotFromContext,localAgentNativeProposal,LocalExecutionListInputSchema,LocalDoctorReportSchema,StartLocalPreviewSchema,LocalDeviceTransportConfigurationSchema,LocalMcpFailureSchema,LocalMcpOutputSchemas,NativeStudioLocalDeviceClient,NativeStudioLocalRuntimeClient,endpoint,catalogue,select,asset};
@@ -0,0 +1 @@
1
+ function secureEndpoint(endpoint){const url=new URL(endpoint);if(url.username||url.password||url.search||url.hash||!(url.protocol==="https:"||url.protocol==="http:"&&["127.0.0.1","localhost","[::1]"].includes(url.hostname)))throw Error();return url}var remoteResponse=(input,init)=>fetch(input,{...init,redirect:"error",signal:init?.signal?AbortSignal.any([init.signal,AbortSignal.timeout(3e4)]):AbortSignal.timeout(3e4)});var remoteFetch=async(input,init)=>{const response=await remoteResponse(input,init);if(!response.body)return response;const reader=response.body.getReader(),chunks=[];let size=0;try{while(true){const part=await reader.read();if(part.done)break;size+=part.value.byteLength;if(size>32*1024*1024){await reader.cancel();throw Error()}chunks.push(part.value)}}finally{reader.releaseLock()}return new Response(Buffer.concat(chunks),{status:response.status,headers:response.headers})};export{secureEndpoint,remoteResponse,remoteFetch};
@@ -0,0 +1 @@
1
+ import{LocalExecutionListInputSchema,LocalMcpOutputSchemas,LocalWorkScopeSchema,NativeStudioLocalRuntimeClient,catalogue}from"./chunk-KHKUJXQX.js";import{fail,optional}from"./chunk-66CUOZVI.js";import{NativeStudioSdkError}from"./chunk-6NVIN2NI.js";import{z}from"zod";import{join}from"node:path";var localTools={local_navigate:{description:"Local execution entry. Discover Project-scoped Runtime progress, recovery and updates. Native writes remain with the cloud owner.",input:z.strictObject({intent:z.string().max(500).optional()})},local_capability_describe:{description:"Inspect the exact public schema for a local capability. Standard discovery stays stable; each call validates current Runtime authority.",input:z.strictObject({tool:z.enum(["local_runtime_status","local_execution_list","local_execution_inspect","local_update_check"])})},local_runtime_status:{description:"Read current authorized local Runtime status. Does not start, stop or mutate native work.",input:z.strictObject({})},local_execution_list:{description:"List a bounded page of pending local execution identities in one authorized Project, then inspect an exact native Job.",input:LocalExecutionListInputSchema},local_execution_inspect:{description:"Inspect one exact native Job in the authorized Project. Native Job/Attempt identity remains authoritative.",input:LocalWorkScopeSchema},local_update_check:{description:"Read signed compatible release metadata only. No executable download, approval, installation or restart.",input:z.strictObject({})}};var LocalMcpTools=class _LocalMcpTools{constructor(client,home){this.client=client;this.home=home}client;home;static async open(connector,home){return new _LocalMcpTools(await NativeStudioLocalRuntimeClient.fromConnector(connector),home)}schema(name){return{name,description:localTools[name].description,inputSchema:z.toJSONSchema(localTools[name].input,{io:"input"}),outputSchema:z.toJSONSchema(LocalMcpOutputSchemas[name],{io:"input"}),annotations:{readOnlyHint:true,destructiveHint:false,openWorldHint:name==="local_update_check"}}}async call(name,raw,signal){return LocalMcpOutputSchemas[name].parse(await this.invoke(name,raw,signal))}async invoke(name,raw,signal){const input=localTools[name].input.parse(raw);if(name==="local_capability_describe")return{location:"LOCAL",tool:input.tool,schema:this.schema(input.tool)};if(name==="local_navigate"){let status;try{status=await this.client.status(signal)}catch{return{location:"LOCAL",state:"UNAVAILABLE",groups:[],nextActions:[{surface:"CLI",operation:"local.grant",availability:"BLOCKED",reason:"AUTHORIZATION_REQUIRED"}]}}return{location:"LOCAL",state:status.state,authorizedProjects:status.authorizedProjects,groups:[{id:"execution",label:"Local execution and recovery",tools:["local_runtime_status","local_execution_list","local_execution_inspect"]},{id:"versions",label:"Versions and updates",tools:["local_update_check"]}],nextActions:[{tool:"local_capability_describe",arguments:{tool:"local_execution_list"},availability:"AVAILABLE",reason:"READY"},...status.state==="RECOVERY_REQUIRED"?[{surface:"CLI",operation:"local.status",availability:"AVAILABLE",reason:"RECOVERY_REQUIRED"}]:[]]}}if(name==="local_runtime_status")return{...await this.client.status(signal),nextActions:[{tool:"local_capability_describe",arguments:{tool:"local_execution_list"}}]};if(name==="local_execution_list"){const page=await this.client.executions(LocalExecutionListInputSchema.parse(input),signal);return{...page,nextActions:page.items.map(item=>({tool:"local_execution_inspect",arguments:{tenantId:item.binding.tenantId,projectId:item.binding.projectId,productionId:item.binding.productionId,runtimeJobId:item.binding.runtimeJobId}}))}}if(name==="local_execution_inspect")return{location:"LOCAL",execution:await this.client.inspect(LocalWorkScopeSchema.parse(input),signal),nextActions:[]};if(name==="local_update_check"){const current=await this.client.status(signal);if(!current.authorizedProjects.length)throw new NativeStudioSdkError("AUTHORIZATION_REQUIRED","BLOCKED","NO_WRITE");const raw2=await optional(join(this.home,"configuration.json"));const config=z.object({catalogueUrl:z.string().url(),publicKeyFile:z.string()}).parse(raw2);const v=await catalogue(config,signal);return{location:"LOCAL",running:current.versions,available:v.signed.catalogue.releases.filter(r=>r.descriptor.platform.os===process.platform&&r.descriptor.platform.architecture===process.arch).map(r=>r.descriptor),nextActions:[{surface:"CLI",operation:"local.update.prepare",availability:"BLOCKED",reason:"USER_APPROVAL_REQUIRED"}]}}fail("CAPABILITY_UNAVAILABLE")}};export{localTools,LocalMcpTools};
@@ -0,0 +1,3 @@
1
+ import{secureEndpoint}from"./chunk-PUNG4ND7.js";import{spawn}from"node:child_process";import{join,isAbsolute}from"node:path";function loginLink(url){secureEndpoint(url.split("?")[0]);process.stderr.write(`Authorize NativeStudio in your browser:
2
+ ${url}
3
+ `)}async function openLoginBrowser(url,signal){loginLink(url);let executable,args;if(process.platform==="darwin"){executable="/usr/bin/open";args=[url]}else if(process.platform==="linux"){executable="/usr/bin/xdg-open";args=[url]}else if(process.platform==="win32"&&process.env.SystemRoot&&isAbsolute(process.env.SystemRoot)){executable=join(process.env.SystemRoot,"System32","rundll32.exe");args=["url.dll,FileProtocolHandler",url]}else return;await new Promise(resolve=>{const child=spawn(executable,args,{shell:false,stdio:"ignore",windowsHide:true});const done=()=>{clearTimeout(timer);signal.removeEventListener("abort",stop);resolve()};const stop=()=>{child.kill();done()};const timer=setTimeout(stop,3e3);child.once("error",done);child.once("exit",done);signal.addEventListener("abort",stop,{once:true});if(signal.aborted)stop()})}export{loginLink,openLoginBrowser};
@@ -0,0 +1 @@
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 DeliveryOutputProfileSchema=z2.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 z3}from"zod";var InterfaceSemanticStatusSchema=z3.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=z3.enum(["AVAILABLE","UNAVAILABLE"]);var NextActionSchema=z3.object({capability:z3.string().min(1).max(120),targetType:z3.string().min(1).max(80),targetId:z3.string().min(1).max(2048),availability:ActionAvailabilitySchema,reason:z3.string().min(1).max(1e3).nullable()});var ContinuationSchema=z3.string().min(1).max(8192);var QueryLimitSchema=z3.int().min(1).max(100).default(20);var QueryPageInfoSchema=z3.object({hasMore:z3.boolean(),next:ContinuationSchema.nullable()});var WorkSummarySchema=z3.object({total:z3.int().nonnegative(),pending:z3.int().nonnegative(),ready:z3.int().nonnegative(),running:z3.int().nonnegative(),waiting:z3.int().nonnegative(),succeeded:z3.int().nonnegative(),failed:z3.int().nonnegative(),cancelled:z3.int().nonnegative(),superseded:z3.int().nonnegative(),attempts:z3.int().nonnegative()});export{TenantIdSchema,PrincipalIdSchema,ProjectIdSchema,ProductionIdSchema,ArtifactIdSchema,ArtifactRepresentationIdSchema,ArtifactRelationIdSchema,BriefIdSchema,BriefVersionIdSchema,StoryIdSchema,StoryVersionIdSchema,SceneShotPlanIdSchema,SceneShotPlanVersionIdSchema,SceneIdSchema,ShotIdSchema,ContinuityEdgeIdSchema,OperationIdSchema,DeliveryOutputProfileSchema,finalProfileIds,InterfaceSemanticStatusSchema,NextActionSchema,ContinuationSchema,QueryLimitSchema,QueryPageInfoSchema,WorkSummarySchema};
@@ -0,0 +1 @@
1
+ import{LocalClientError,directory,entries,fail,optional,read,sha256,sha512,verifyBackup,write}from"./chunk-66CUOZVI.js";export{LocalClientError,directory,entries,fail,optional,read,sha256,sha512,verifyBackup,write};
@@ -0,0 +1 @@
1
+ import{LocalInstallationManager,captureInstalledTools,ownerClient}from"./chunk-K6LVS2IN.js";import{localCliVersion}from"./chunk-2UYKJ6YN.js";import{EnrollLocalDeviceSchema,GrantLocalDeviceSchema,LocalAgentGrantSchema,LocalDeviceTransportConfigurationSchema,LocalToolSelectionSchema,NativeStudioLocalDeviceClient,RevokeLocalDeviceGrantSchema,RevokeLocalDeviceSchema,StartLocalPreviewSchema,canonicalLocalJson,localAgentNativeProposal,localAgentSnapshotFromContext}from"./chunk-KHKUJXQX.js";import{NativeStudioAgentClient}from"./chunk-E57YVMQ4.js";import"./chunk-GJ7BZJLW.js";import"./chunk-HLKERZIE.js";import"./chunk-VPYAXWXY.js";import{readCredential,readInput}from"./chunk-BVSTJQJI.js";import{LocalClientError,directory,fail,read,write}from"./chunk-66CUOZVI.js";import{NativeStudioSdkError}from"./chunk-6NVIN2NI.js";import{generateKeyPairSync}from"node:crypto";import{dirname,join,sep}from"node:path";async function generateDeviceKey(output){await directory(dirname(output));const key=generateKeyPairSync("ec",{namedCurve:"prime256v1"});await write(output,JSON.stringify(key.privateKey.export({format:"jwk"})),true);return{publicKey:key.publicKey.export({format:"jwk"}),privateKeyFile:output}}async function connectDevice(manager,raw){const schema=LocalDeviceTransportConfigurationSchema.extend({tools:LocalToolSelectionSchema.optional()});const input=schema.parse(raw),c=await manager.configuration();await read(input.privateKeyFile,16384);const active=(await manager.ledger.current()).value.active;const actual=active?.toolsConfigPath?LocalToolSelectionSchema.parse(JSON.parse((await read(active.toolsConfigPath,32768)).toString())):c.cloudConfigFile?LocalToolSelectionSchema.parse(JSON.parse((await read(c.cloudConfigFile,32768)).toString()).tools):null;if(input.tools&&active&&(!actual||canonicalLocalJson(input.tools)!==canonicalLocalJson(actual)))fail("TOOL_SELECTION_PLAN_REQUIRED");let tools=input.tools;if(!tools){const selected=(await manager.ledger.current()).value.active?.toolsConfigPath;if(!selected)fail("MANAGED_TOOLS_REQUIRED");tools=LocalToolSelectionSchema.parse(JSON.parse((await read(selected,32768)).toString()))}if(tools.mode==="MANAGED"&&!tools.ffmpeg.path.startsWith(join(c.stateDirectory,"tools")+sep))fail("MANAGED_TOOLS_REQUIRED");const file=join(c.stateDirectory,"cloud-device.json");await write(file,canonicalLocalJson({...input,tools}));await manager.configure({...c,cloudConfigFile:file});return{connected:true,deviceId:input.deviceId,projects:input.projects,nextActions:[{surface:"CLI",operation:"local.stop",availability:"AVAILABLE",reason:"READY"},{surface:"CLI",operation:"local.start",availability:"AVAILABLE",reason:"READY"}]}}import{homedir as homedir2}from"node:os";import{join as join3,resolve as resolve2}from"node:path";import{homedir}from"node:os";import{join as join2,resolve}from"node:path";import{createHash}from"node:crypto";async function runLocalAgentCli(argv,stdin){try{const[command,...rest]=argv,flags=new Map;for(let n=0;n<rest.length;n+=2){const k=rest[n],v=rest[n+1];if(!k||!["--home","--input","--approve","--id","--revision","--evidence","--origin","--token-file"].includes(k)||!v||v.startsWith("--")||flags.has(k))throw Error();flags.set(k,v)}const need=k=>{const v=flags.get(k);if(!v)throw Error();return v};if(command==="agent-grant-plan"){const grant=LocalAgentGrantSchema.parse(await readInput(need("--input"),stdin));return{exitCode:0,output:{grant,fingerprint:createHash("sha256").update(canonicalLocalJson(grant)).digest("hex"),note:"Explicitly approves remote OpenAI inference/use for these Projects until expiry. Does not invoke a model."}}}if(flags.has("--evidence")&&!["IMAGE_PIXELS","METADATA_ONLY"].includes(need("--evidence")))throw Error();const manager=await LocalInstallationManager.open(resolve(flags.get("--home")??join2(homedir(),".nativestudio","client")));const client=await ownerClient((await manager.configuration()).stateDirectory);let output;switch(command){case"agent-grant":output=await client.grantAgent(await readInput(need("--input"),stdin),need("--approve"));break;case"agent-revoke":output=await client.revokeAgent(need("--approve"));break;case"agent-probe":output=await client.probeAgent();break;case"review-prepare":output=await client.prepareAgentReview(localAgentSnapshotFromContext(await readInput(need("--input"),stdin),flags.get("--evidence")==="IMAGE_PIXELS"));break;case"review-image-fetch":{const view=await client.inspectAgentReview(need("--id")),snapshot=view.plan.snapshot;if(!snapshot.image)throw Error();const studio=new NativeStudioAgentClient({baseUrl:need("--origin"),tenantId:snapshot.basis.scope.tenantId,authorization:()=>readCredential(flags,process.env)});const media=await studio.keyframeMedia({productionId:snapshot.basis.scope.productionId,generationId:snapshot.basis.target.generationId},{checksumSha256:snapshot.media.checksumSha256,byteSize:snapshot.image.byteSize});if(media.contentType!==snapshot.image.contentType)throw Error();output=await client.stageAgentImage(view.plan.id,media.bytes);break}case"review-start":output=await client.startAgentReview(need("--id"),Number(need("--revision")),need("--approve"));break;case"review-inspect":output=await client.inspectAgentReview(need("--id"));break;case"review-proposal":output=localAgentNativeProposal(await client.inspectAgentReview(need("--id")));break;default:throw Error()}return{exitCode:0,output}}catch(e){const known=e instanceof NativeStudioSdkError;return{exitCode:2,output:{semanticStatus:"BLOCKED",error:{code:known?e.code:"INVALID_INPUT",outcome:known?e.outcome:"NO_WRITE"}}}}}async function runLocalCli(argv,stdin=process.stdin){let mutation=false;try{const[command,...rest]=argv,options=new Map;if(command?.startsWith("agent-")||command?.startsWith("review-"))return runLocalAgentCli(argv,stdin);const allowed=["--home","--input","--version","--plan","--approve","--output","--origin","--token-file","--action"];for(let i=0;i<rest.length;i+=2){const k=rest[i],v=rest[i+1];if(!k||!allowed.includes(k)||!v||v.startsWith("--")||options.has(k))throw Error();options.set(k,v)}if(command==="help"||!command)return{exitCode:0,output:{namespace:"nvs local",commands:["configure --input <private-json>","keygen --output <new-private-device-key>","cloud --action enroll|grant|revoke-device|revoke-grant|preview --origin <cloud-origin> --token-file <member-token> --input <json>","connect --input <private-device-config>","version","install|update-prepare --version <exact>","tools-prepare --version <exact> --input <private-json with mode MANAGED or INSTALLED and exact ffmpeg/ffprobe paths>","update-check","update-reject --version <exact>","update-apply --plan <uuid> --approve <fingerprint>","update-reconcile --plan <uuid> --approve <fingerprint>","start","status","doctor","stop","grant --input <scopes-expiry-json> --output <new-private-connector>","mcp --connector <private-file>","agent-grant-plan|agent-probe|agent-grant|agent-revoke|review-prepare|review-image-fetch|review-start|review-inspect|review-proposal \u2014 see --input private JSON and exact --approve"],note:"Check/prepare do not download executables. Apply requires exact approval. MCP disconnect does not stop Runtime."}};if(command==="version")return{exitCode:0,output:await localCliVersion()};const required=key=>{const v=options.get(key);if(!v)throw Error();return v};if(command==="keygen")return{exitCode:0,output:await generateDeviceKey(resolve2(required("--output")))};if(command==="cloud"){const input=await readInput(required("--input"),stdin);if(typeof input.tenantId!=="string")throw Error();const client=new NativeStudioLocalDeviceClient({baseUrl:required("--origin"),tenantId:input.tenantId,authorization:()=>readCredential(new Map([["--token-file",required("--token-file")]]),process.env)});const action=required("--action");const output2=action==="enroll"?await client.enroll(EnrollLocalDeviceSchema.parse(input)):action==="grant"?await client.grant(GrantLocalDeviceSchema.parse(input)):action==="revoke-device"?await client.revokeDevice(RevokeLocalDeviceSchema.parse(input)):action==="revoke-grant"?await client.revokeGrant(RevokeLocalDeviceGrantSchema.parse(input)):action==="preview"?await client.startPreview(StartLocalPreviewSchema.parse(input)):void 0;if(!output2)throw Error();return{exitCode:0,output:output2}}const manager=await LocalInstallationManager.open(resolve2(options.get("--home")??join3(homedir2(),".nativestudio","client")));let output;mutation=["configure","connect","start","stop","grant","update-apply","update-reconcile","update-reject"].includes(command??"");switch(command){case"connect":output=await connectDevice(manager,await readInput(required("--input"),stdin));break;case"configure":output=await manager.configure(await readInput(required("--input"),stdin));break;case"status":output=await manager.status();break;case"update-reject":output=await manager.reject(required("--version"));break;case"update-check":output=await manager.check();break;case"install":case"update-prepare":output=await manager.prepare(required("--version"));break;case"tools-prepare":{const raw=await readInput(required("--input"),stdin);const choice=raw.mode==="INSTALLED"?await captureInstalledTools(raw):raw;output=await manager.prepare(required("--version"),choice)}break;case"update-apply":output=await manager.apply(required("--plan"),required("--approve"));break;case"update-reconcile":output=await manager.reconcile(required("--plan"),required("--approve"));break;case"start":output=await manager.start();break;case"stop":output=await manager.stop();break;case"doctor":output=await(await ownerClient((await manager.configuration()).stateDirectory)).doctor();break;case"grant":output=await manager.grant(await readInput(required("--input"),stdin),resolve2(required("--output")));break;default:throw Error()}return{exitCode:0,output}}catch(e){const known=e instanceof LocalClientError?e.code:e instanceof NativeStudioSdkError?e.code:"INVALID_INPUT";return{exitCode:2,output:{semanticStatus:"BLOCKED",error:{code:known,outcome:e instanceof NativeStudioSdkError?e.outcome:mutation&&!["USER_APPROVAL_REQUIRED","PLAN_CHANGED","REVISION_CONFLICT","INSTALL_REQUIRED","CONFIGURATION_REQUIRED"].includes(known)?"UNKNOWN":"NO_WRITE"}}}}}export{runLocalCli};
@@ -0,0 +1 @@
1
+ import{StdioLines}from"./chunk-JFC6ZIGA.js";import{LocalMcpTools,localTools}from"./chunk-VC3ODN3M.js";import{localCliVersion}from"./chunk-2UYKJ6YN.js";import{LocalMcpFailureSchema}from"./chunk-KHKUJXQX.js";import"./chunk-HLKERZIE.js";import"./chunk-VPYAXWXY.js";import"./chunk-66CUOZVI.js";import{NativeStudioSdkError}from"./chunk-6NVIN2NI.js";import{z}from"zod";import{homedir}from"node:os";import{join,resolve}from"node:path";import{deserializeMessage,SUPPORTED_PROTOCOL_VERSIONS,LATEST_PROTOCOL_VERSION,serializeMessage,isJSONRPCRequest,isJSONRPCNotification}from"@modelcontextprotocol/client";async function serveLocalMcp(tools,input,output){const identity=await localCliVersion();const visible=Object.keys(localTools).sort(),pending=new Map;let initialized=false,closed=false;const frames=new StdioLines(65536);let finish;const ended=new Promise(resolve2=>{finish=resolve2});const send=message=>{if(closed)return;if(output.writableLength>512*1024){close(1);return}output.write(serializeMessage(message))};const error=(id,code,message)=>send({jsonrpc:"2.0",id,error:{code,message}});async function dispatch(r){if(pending.has(r.id)||pending.size>=8){error(r.id,-32e3,"Local request capacity unavailable");return}const abort=new AbortController;const timer=setTimeout(()=>abort.abort(),3e4);pending.set(r.id,abort);try{let result;if(r.method==="initialize"){if(initialized)throw Error();const v=r.params?.protocolVersion;if(typeof v!=="string")throw Error();const protocol=SUPPORTED_PROTOCOL_VERSIONS.includes(v)?v:LATEST_PROTOCOL_VERSION;initialized=true;result={protocolVersion:protocol,serverInfo:{name:"native-studio-local",version:identity.version},capabilities:{tools:{}},instructions:"Use local_navigate and local_capability_describe for scoped guidance. The standard tool list stays stable. Local tools inspect scoped mechanics. Cloud owns native business commands. Updates require a human CLI approval; MCP cannot stop or replace Runtime."}}else if(!initialized)throw Error();else if(r.method==="ping")result={};else if(r.method==="tools/list"){if(r.params?.cursor!==void 0)throw Error();result={tools:visible.map(n=>tools.schema(n))}}else if(r.method==="tools/call"){const name=r.params?.name;if(typeof name!=="string"||!Object.hasOwn(localTools,name)||!visible.includes(name))throw Error();let data;try{data=await tools.call(name,r.params?.arguments??{},abort.signal)}catch(cause){const code=cause instanceof z.ZodError?"INVALID_INPUT":cause instanceof NativeStudioSdkError&&["AUTHORIZATION_REQUIRED","FORBIDDEN","LOCAL_RUNTIME_UNAVAILABLE"].includes(cause.code)?cause.code:"LOCAL_CAPABILITY_UNAVAILABLE";const failure=LocalMcpFailureSchema.parse({semanticStatus:code==="INVALID_INPUT"?"INVALID_INPUT":"BLOCKED",error:{code,outcome:"NO_WRITE"},nextActions:[{surface:"CLI",operation:"local.status",availability:"AVAILABLE",reason:code==="FORBIDDEN"||code==="AUTHORIZATION_REQUIRED"?"AUTHORIZATION_REQUIRED":"UNAVAILABLE"}]});send({jsonrpc:"2.0",id:r.id,result:{isError:true,content:[{type:"text",text:JSON.stringify(failure)}],structuredContent:failure}});return}result={content:[{type:"text",text:JSON.stringify(data)}],structuredContent:data}}else{error(r.id,-32601,"Local method unavailable");return}send({jsonrpc:"2.0",id:r.id,result})}catch{error(r.id,-32602,"Local capability unavailable or authorization required")}finally{clearTimeout(timer);pending.delete(r.id)}}function onData(b){try{frames.push(b,line=>{const message=deserializeMessage(line.toString());if(isJSONRPCRequest(message))void dispatch(message);else if(isJSONRPCNotification(message)){if(message.method==="notifications/cancelled"){const id=message.params?.requestId;if(typeof id==="string"||typeof id==="number")pending.get(id)?.abort()}}else throw Error();return!closed})}catch{close(1)}}function close(code=0){if(closed)return;closed=true;for(const abort of pending.values())abort.abort();input.off("data",onData);finish(code)}input.on("data",onData);input.once("end",()=>close(frames.incomplete?1:0));input.once("error",()=>close(1));output.once("error",()=>close(1));return{closed:ended,close:async()=>close()}}async function runLocalMcp(argv){try{const flags=new Map;for(let i=0;i<argv.length;i+=2){const k=argv[i],v=argv[i+1];if(!k||!["--connector","--home"].includes(k)||!v||flags.has(k))throw Error();flags.set(k,v)}const connector=flags.get("--connector");if(!connector)throw Error();const tools=await LocalMcpTools.open(resolve(connector),resolve(flags.get("--home")??join(homedir(),".nativestudio","client")));const service=await serveLocalMcp(tools,process.stdin,process.stdout);return await service.closed}catch{process.stderr.write("NativeStudio local MCP requires a private Project connector; use nvs local grant.\n");return 2}}export{runLocalMcp,serveLocalMcp};
@@ -0,0 +1,2 @@
1
+ import{loginLink,openLoginBrowser}from"./chunk-VDNNFVTZ.js";import{NativeStudioAccountClient,accountError,accountServerOrigin,clientHome,connectionStatus,defaultConnection,readAccount,requireAccount,saveAccount,withAccountLock}from"./chunk-C753RRRA.js";import"./chunk-GJ7BZJLW.js";import"./chunk-VPYAXWXY.js";import"./chunk-7S3DJ2QE.js";import"./chunk-PUNG4ND7.js";import{readCredential,readInput}from"./chunk-BVSTJQJI.js";import{write}from"./chunk-66CUOZVI.js";import{NativeStudioSdkError}from"./chunk-6NVIN2NI.js";var aliases={find:"studio.start",overview:"studio.navigate",next:"studio.navigate",resume:"operation.get"};var auth=new Set(["--tenant","--origin","--mcp-url","--profile","--token-env","--token-file"]);var fields={find:{"--query":"search","--project":"projectId","--limit":"limit","--next":"next","--attention":"attention"},overview:{"--production":"productionId","--project":"projectId","--goal":"goal","--limit":"actionLimit","--next":"actionNext"},next:{"--production":"productionId","--project":"projectId","--goal":"goal","--limit":"actionLimit","--next":"actionNext"},resume:{"--production":"productionId","--operation":"operationId"},search:{"--query":"query","--project":"projectId","--group":"group","--family":"family","--limit":"limit","--next":"next"},describe:{"--tool":"tool","--project":"projectId","--reference":"schemaCursor"},groups:{"--project":"projectId"}};var NavigationCliCommands=new Set([...Object.keys(aliases),"capabilities"]);async function runNavigationCli(argv,stdin,call){const kind=argv[0]==="capabilities"?argv[1]?.startsWith("--")||!argv[1]?"groups":argv[1]:argv[0];const operation=argv[0]==="capabilities"?{groups:"studio.capability.groups",search:"studio.capability.search",describe:"studio.capability.describe"}[kind]:aliases[kind];const offset=argv[0]==="capabilities"&&argv[1]===kind?2:1;if(!operation||!fields[kind])throw Error("INVALID_INPUT");const forwarded=["call",operation],body={},seen=new Set;let input;for(let i=offset;i<argv.length;i+=2){const flag=argv[i],value=argv[i+1];if(!value||value.startsWith("--")||seen.has(flag))throw Error("INVALID_INPUT");seen.add(flag);if(auth.has(flag))forwarded.push(flag,value);else if(flag==="--input")input=value;else{const key=fields[kind][flag];if(!key)throw Error("INVALID_INPUT");body[key]=flag==="--limit"?Number(value):value}}if(input&&Object.keys(body).length)throw Error("INVALID_INPUT");forwarded.push("--input",input??"-");const generated=async function*(){yield Buffer.from(JSON.stringify(body))};return call(forwarded,input?stdin:generated())}import{randomBytes,randomUUID,createHash,timingSafeEqual}from"node:crypto";import{createServer}from"node:http";import{join}from"node:path";async function accountSignals(timeout,run){const cancelled=new AbortController,signal=AbortSignal.any([AbortSignal.timeout(timeout),cancelled.signal]);const stop=()=>cancelled.abort();process.once("SIGINT",stop);process.once("SIGTERM",stop);try{return await run(signal)}finally{process.off("SIGINT",stop);process.off("SIGTERM",stop)}}async function runAccountLogin(argv,environment,hooks={}){const options=new Map;for(let i=1;i<argv.length;i+=2){const key=argv[i],value=argv[i+1];if(!key||!["--server","--browser","--timeout-ms"].includes(key)||!value||value.startsWith("--")||options.has(key))accountError("ACCOUNT_LOGIN_INPUT_INVALID");options.set(key,value)}const configured=options.get("--server")??environment.NATIVESTUDIO_STUDIO_ORIGIN;if(!configured)return{exitCode:2,output:{semanticStatus:"NEEDS_INPUT",error:{code:"ACCOUNT_SERVER_REQUIRED",outcome:"NO_WRITE"},nextSteps:["nvs login --server <Studio-origin> (no Project required)"]}};const origin=accountServerOrigin(configured),browser=options.get("--browser")??"auto",timeout=options.get("--timeout-ms")??"180000";if(!["auto","manual"].includes(browser)||!/^\d+$/.test(timeout)||Number(timeout)<1e3||Number(timeout)>3e5)accountError("ACCOUNT_LOGIN_INPUT_INVALID");const root=await clientHome(environment,true);return withAccountLock(root,()=>accountSignals(Number(timeout),async signal=>{if((await readAccount(root))?.state==="REVOKE_PENDING")accountError("ACCOUNT_LOGOUT_OUTCOME_UNKNOWN","UNKNOWN");const client=new NativeStudioAccountClient({serverOrigin:origin});await client.metadata(signal);const verifier=randomBytes(32).toString("base64url"),state=randomBytes(32).toString("base64url"),path="/account-callback/"+randomUUID();let finish,receiving=false,sent=false;const callback=new Promise(done=>{finish=done});const server=createServer({maxHeaderSize:8192,headersTimeout:5e3,requestTimeout:5e3},(req,res)=>{res.setHeader("cache-control","no-store");res.setHeader("content-type","text/plain; charset=utf-8");res.setHeader("x-content-type-options","nosniff");const address=server.address(),host=address&&typeof address!=="string"?`127.0.0.1:${address.port}`:"";if(receiving||req.method!=="GET"||req.headers.host!==host||req.headers.origin||!req.url||!req.url.startsWith(path+"?")||req.url.length>2048){res.writeHead(400).end("Invalid account callback.");return}const url=new URL(req.url,`http://${host}`),received=url.searchParams.get("state");const keys=[...url.searchParams.keys()];if(url.pathname!==path||new Set(keys).size!==keys.length||keys.some(k=>!["state","iss","code","error"].includes(k))||!received||Buffer.byteLength(received)!==Buffer.byteLength(state)||!timingSafeEqual(Buffer.from(received),Buffer.from(state))||url.searchParams.get("iss")!==origin||(url.searchParams.has("error")?url.searchParams.get("error")!=="access_denied"||url.searchParams.has("code"):!/^[A-Za-z0-9_-]{43}$/.test(url.searchParams.get("code")??""))){res.writeHead(400).end("Invalid account callback.");return}receiving=true;res.end("Account confirmation received. Return to NativeStudio CLI.");finish(url.searchParams.get("code"))});server.maxConnections=8;const expired=()=>finish(null);signal.addEventListener("abort",expired,{once:true});const attempt=join(root,"account-login-attempt.json");let attemptFile;try{await new Promise((done,fail)=>{server.once("error",fail);server.listen(0,"127.0.0.1",done)});const address=server.address();if(!address||typeof address==="string")throw Error();const redirectUri=`http://127.0.0.1:${address.port}${path}`;const started=await client.start({redirectUri,state,codeChallenge:createHash("sha256").update(verifier).digest("base64url")},signal);const url=`${origin}/cli-authorize?requestId=${started.requestId}`;signal.throwIfAborted();if(hooks.authorize)await hooks.authorize(url,signal);else{process.stderr.write(`CLI account login request: ${started.requestId}
2
+ `);if(browser==="manual")loginLink(url);else await openLoginBrowser(url,signal)}const code=await callback;if(!code)accountError(signal.aborted?signal.reason?.name==="TimeoutError"?"ACCOUNT_LOGIN_TIMED_OUT":"ACCOUNT_LOGIN_CANCELLED":"ACCOUNT_LOGIN_DENIED");const marker={version:1,serverOrigin:origin,requestId:started.requestId,state:"EXCHANGE_UNRESOLVED"};attemptFile=join(root,`account-login-attempt-${started.requestId}.json`);await write(attemptFile,JSON.stringify(marker),true);await write(attempt,JSON.stringify(marker));signal.throwIfAborted();sent=true;const session=await client.exchange({requestId:started.requestId,redirectUri,code,codeVerifier:verifier},signal);if(Date.parse(session.expiresAt)<=Date.now()||Date.parse(session.expiresAt)>Date.now()+36e5+3e4)accountError("ACCOUNT_SESSION_INVALID","UNKNOWN");await saveAccount(root,{version:1,epoch:randomUUID(),state:"ACTIVE",serverOrigin:origin,accessToken:session.accessToken,expiresAt:session.expiresAt,principalId:session.account.principalId,workspaceId:null,projectId:null});await write(attempt,JSON.stringify({...marker,state:"COMPLETED"}));await write(attemptFile,JSON.stringify({...marker,state:"COMPLETED"}));return{exitCode:0,output:{semanticStatus:"SUCCESS",authenticated:true,credentialPurpose:"CLI_ACCOUNT",serverOrigin:origin,expiresAt:session.expiresAt,account:session.account,nextSteps:["nvs workspaces","nvs workspace --id <workspace-id>","nvs projects"]}}}catch(error){if(sent){if(error instanceof NativeStudioSdkError&&error.outcome!=="UNKNOWN"){await write(attempt,JSON.stringify({version:1,state:"REJECTED"}));if(attemptFile)await write(attemptFile,JSON.stringify({version:1,state:"REJECTED"}));throw error}accountError("ACCOUNT_LOGIN_OUTCOME_UNKNOWN","UNKNOWN")}if(error instanceof NativeStudioSdkError&&error.outcome==="UNKNOWN")accountError("ACCOUNT_LOGIN_OUTCOME_UNKNOWN","UNKNOWN");if(signal.aborted)accountError(signal.reason?.name==="TimeoutError"?"ACCOUNT_LOGIN_TIMED_OUT":"ACCOUNT_LOGIN_CANCELLED");throw error}finally{signal.removeEventListener("abort",expired);server.closeAllConnections();await new Promise(done=>server.close(()=>done()))}}))}import{randomUUID as randomUUID2}from"node:crypto";import{z}from"zod";var AccountCommands=new Set(["whoami","workspaces","workspace","projects","project","logout"]);async function runAccountCommand(argv,environment){const command=argv[0],options=new Map;for(let i=1;i<argv.length;i+=2){const key=argv[i],value=argv[i+1];if(!key||!["--id","--limit","--next"].includes(key)||!value||value.startsWith("--")||options.has(key))accountError("ACCOUNT_COMMAND_INPUT_INVALID");options.set(key,value)}if(["workspace","project"].includes(command??"")?options.size!==1||!options.has("--id"):command==="projects"?options.has("--id"):options.size!==0)accountError("ACCOUNT_COMMAND_INPUT_INVALID");const root=await clientHome(environment,true);return withAccountLock(root,()=>accountSignals(15e3,async signal=>{const stored=await readAccount(root);if(command==="logout"){if(!stored||stored.state==="SIGNED_OUT")return{exitCode:0,output:{semanticStatus:"SUCCESS",authenticated:false,changed:false}};const client2=new NativeStudioAccountClient({serverOrigin:stored.serverOrigin,accessToken:stored.accessToken});const pending={...stored,state:"REVOKE_PENDING",workspaceId:null,projectId:null};await saveAccount(root,pending);try{await client2.logout(signal);await saveAccount(root,{...pending,state:"SIGNED_OUT",accessToken:null})}catch{accountError("ACCOUNT_LOGOUT_OUTCOME_UNKNOWN","UNKNOWN")}return{exitCode:0,output:{semanticStatus:"SUCCESS",authenticated:false,changed:true,nextSteps:["nvs login --server <Studio-origin>"]}}}const account=requireAccount(stored),client=new NativeStudioAccountClient({serverOrigin:account.serverOrigin,accessToken:account.accessToken});if(command==="whoami"||command==="workspaces"||command==="workspace"){const value2=await client.me(signal);if(value2.account.principalId!==account.principalId)accountError("ACCOUNT_IDENTITY_MISMATCH");if(command==="workspace"){const id=z.uuid().parse(options.get("--id"));if(!value2.account.tenants.some(t=>t.id===id))accountError("WORKSPACE_NOT_AUTHORIZED");await saveAccount(root,{...account,workspaceId:id,projectId:null,epoch:randomUUID2()});return{exitCode:0,output:{semanticStatus:"SUCCESS",workspaceId:id,nextSteps:["nvs projects"]}}}return{exitCode:0,output:{semanticStatus:"SUCCESS",authenticated:true,credentialPurpose:"CLI_ACCOUNT",verification:"LIVE_NATIVE_ACCOUNT",...command==="workspaces"?{workspaces:value2.account.tenants}:{account:value2.account,workspaceId:account.workspaceId,projectId:account.projectId,expiresAt:account.expiresAt},nextSteps:["nvs workspace --id <workspace-id>"]}}}if(!account.workspaceId)accountError("WORKSPACE_SELECTION_REQUIRED");if(command==="projects"){const limit=options.has("--limit")?z.coerce.number().int().min(1).max(100).parse(options.get("--limit")):void 0;const value2=await client.projects({tenantId:account.workspaceId,limit,next:options.get("--next")},signal);if(value2.items.some(p=>p.tenantId!==account.workspaceId))accountError("ACCOUNT_RESPONSE_SCOPE_MISMATCH");return{exitCode:0,output:{semanticStatus:"SUCCESS",...value2,nextSteps:["nvs project --id <project-id>"]}}}if(command!=="project")accountError("ACCOUNT_COMMAND_INPUT_INVALID");const projectId=z.uuid().parse(options.get("--id")),value=await client.project({tenantId:account.workspaceId,projectId},signal);if(value.project.id!==projectId||value.project.tenantId!==account.workspaceId)accountError("ACCOUNT_RESPONSE_SCOPE_MISMATCH");if(value.project.lifecycle!=="ACTIVE")accountError("PROJECT_ARCHIVED");await saveAccount(root,{...account,projectId,epoch:randomUUID2()});return{exitCode:0,output:{semanticStatus:"SUCCESS",project:value.project,connectionPage:`${account.serverOrigin}/projects/${projectId}/settings`,nextSteps:["Open connectionPage, then explicitly authorize this Project using nvs connect.","nvs status"]}}}))}var exits={SUCCESS:0,ACCEPTED:0,INVALID_INPUT:2,NOT_FOUND:3,BLOCKED:4,CAPABILITY_UNAVAILABLE:4,REVISION_CONFLICT:5};async function runRemoteCli(argv,environment=process.env,stdin=process.stdin){try{if(argv[0]==="connect")return await(await import("./project-connect-MXM7IY55.js")).runProjectConnect(argv,environment);if(argv[0]==="login"){if(argv.includes("--mcp-url")){const{runProjectConnect}=await import("./project-connect-MXM7IY55.js");const result=await runProjectConnect(["connect",...argv.slice(1)],environment);return{...result,output:{...result.output,deprecated:{code:"PROJECT_AUTH_IS_CONNECT",replacement:"nvs connect --mcp-url <project-connection-url>",note:"This legacy spelling authorizes one project; it does not establish a CLI account session."}}}}return await runAccountLogin(argv,environment)}if(AccountCommands.has(argv[0]??""))return await runAccountCommand(argv,environment);if(argv.length===1&&argv[0]==="status")return await connectionStatus(environment);if(NavigationCliCommands.has(argv[0]??""))return await runNavigationCli(argv,stdin,(args2,input2)=>runRemoteCli(args2,environment,input2));if(["auth-start","auth-complete"].includes(argv[0]??""))return await(await import("./oauth-F7EZGVME.js")).runOAuthCommand(argv,stdin);if(!argv.length||argv.length===1&&["help","--help"].includes(argv[0]))return{exitCode:0,output:{product:"NativeStudio CLI",start:["nvs login --server <Studio-origin> \u2014 sign in/register your account in the browser; no project required.","nvs workspaces; nvs workspace --id <id>; nvs projects; nvs project --id <id>","nvs connect --mcp-url <project-connection-url> (project authorization; read-only by default)","nvs status","nvs find --query <intent>"],navigation:["nvs capabilities","nvs overview --production <uuid>","nvs next --production <uuid>","nvs resume --production <uuid> --operation <op_original>"],agentConnection:{command:"nvs",args:["mcp"],note:"Uses the private saved connection; no token in Agent configuration."},commands:["login --server <Studio-origin> | whoami | logout \u2014 independent account session","workspaces | workspace --id <id> | projects [--limit <n>] [--next <cursor>] | project --id <id>","connect --mcp-url <project-connection-url> \u2014 project authorization after account sign-in","status","find --query <text> [--project <uuid>]","overview | next --production <uuid> [--goal <text>]","resume --production <uuid> --operation <op_original>","capabilities [groups | search --query <text> --group <group> | describe --tool <name>]","mcp \u2014 connect the Agent using the private saved connection","local help \u2014 installed Runtime, scoped local MCP, explicit exact-version updates"],advanced:["operations","mcp --profile <private-file> | --mcp-url <endpoint> --token-env <NAME>|--token-file <private-file>","call <operation> --input <file|-> --tenant <uuid> --token-env <NAME> --origin <https-origin>","call <operation> --input <file|-> --tenant <uuid> --token-file <private-file> --mcp-url <https-endpoint>","auth-start --profile <new-private-file> --mcp-url <resource> --callback <receiver-url>","auth-complete --profile <private-file> --input <callback-json-file|->","call <operation> --profile <private-file> --tenant <uuid> --input <file|->"],note:"No automatic write retry. Transport abort does not cancel native Jobs."}};const{NativeStudioAgentClient,sdkOperations}=await import("./src-7F6ZEU3U.js");if(argv.length===1&&argv[0]==="operations")return{exitCode:0,output:{operations:Object.entries(sdkOperations).map(([name2,spec])=>({name:name2,readOnly:spec.readOnly??null,http:spec.request!==null}))}};const[command,name,...args]=argv;if(command!=="call"||!name||!Object.hasOwn(sdkOperations,name))throw Error();const options=new Map;const allowed=["--input","--tenant","--origin","--mcp-url","--token-env","--token-file","--profile"];for(let i=0;i<args.length;i+=2){const key2=args[i],value=args[i+1];if(!key2||!allowed.includes(key2)||!value||value.startsWith("--")||options.has(key2))throw Error();options.set(key2,value)}await defaultConnection(options,environment,true);if(!options.has("--input")||!options.has("--tenant")||(options.has("--profile")?options.has("--origin")||options.has("--mcp-url")||options.has("--token-file")||options.has("--token-env"):options.has("--origin")===options.has("--mcp-url")))throw Error();const key=name;const input=await readInput(options.get("--input"),stdin);const profile=options.has("--profile")?await(await import("./oauth-F7EZGVME.js")).profileAuthorization(options.get("--profile")):null;const authorization=profile?.authorization??await readCredential(options,environment);const tenantId=options.get("--tenant");let output;if(profile||options.has("--mcp-url")){const{connectRemoteMcp}=await import("./mcp-EIMXNRH3.js");const connection=await connectRemoteMcp(profile?.resource??options.get("--mcp-url"),authorization,tenantId);try{output=await connection.studio.call(key,input)}finally{await connection.close()}}else{const studio=new NativeStudioAgentClient({tenantId,baseUrl:options.get("--origin"),authorization:()=>authorization});output=await studio.call(key,input)}const status=output?.semanticStatus;return{exitCode:status?exits[status]??1:0,output}}catch(error){const e=error instanceof NativeStudioSdkError?error:null;const accountRecovery={ACCOUNT_LOGIN_OUTCOME_UNKNOWN:["Start a fresh nvs login --server <Studio-origin>; never replay the old exchange."],ACCOUNT_LOGOUT_OUTCOME_UNKNOWN:["Retry nvs logout explicitly; local account use remains locked."],ACCOUNT_LOGIN_REQUIRED:["nvs login --server <Studio-origin>"],ACCOUNT_SESSION_EXPIRED_OR_REVOKED:["nvs login --server <Studio-origin>"],WORKSPACE_SELECTION_REQUIRED:["nvs workspaces","nvs workspace --id <workspace-id>"],PROJECT_CONNECTION_ACCOUNT_MISMATCH:["nvs whoami","nvs workspaces","nvs project --id <project-id>","nvs connect --mcp-url <project-connection-url>"],ACCOUNT_PROJECT_SELECTION_REQUIRED:["nvs whoami","nvs workspace --id <workspace-id>","nvs project --id <project-id>"],PROJECT_AUTHORIZED_CONNECTION_NOT_SELECTED:["Authorization may exist. Inspect Web grants; select the intended account/project before creating a fresh connection."]};return{exitCode:e?exits[e.semanticStatus]??1:2,output:{semanticStatus:e?.semanticStatus??"INVALID_INPUT",error:{code:e?.code??"INVALID_INPUT",outcome:e?.outcome??"NO_WRITE"},...e&&accountRecovery[e.code]?{nextSteps:accountRecovery[e.code]}:{},...["PROJECT_CONNECTION_REQUIRED","OAUTH_OUTCOME_UNKNOWN"].includes(e?.code??"")?{nextSteps:["nvs connect --mcp-url <project-connection-url>","nvs help"]}:{}}}}}export{runRemoteCli};
@@ -0,0 +1 @@
1
+ import{localCliVersion}from"./chunk-2UYKJ6YN.js";import{NativeStudioMcpClient}from"./chunk-E57YVMQ4.js";import"./chunk-GJ7BZJLW.js";import"./chunk-HLKERZIE.js";import"./chunk-VPYAXWXY.js";import{remoteFetch,secureEndpoint}from"./chunk-PUNG4ND7.js";import{NativeStudioSdkError}from"./chunk-6NVIN2NI.js";import{Client,StreamableHTTPClientTransport}from"@modelcontextprotocol/client";async function connectRemoteMcp(endpoint,authorization,tenantId){const url=secureEndpoint(endpoint);const client=new Client({name:"native-studio-remote-cli",version:(await localCliVersion()).version},{versionNegotiation:{mode:"auto"}});try{const transport=new StreamableHTTPClientTransport(url,{requestInit:{headers:{authorization}},fetch:remoteFetch});await client.connect(transport);return{studio:new NativeStudioMcpClient({tenantId,client}),close:()=>client.close()}}catch{await client.close();throw new NativeStudioSdkError("TRANSPORT_UNAVAILABLE","INTERNAL_OPERATIONAL_FAILURE","NO_WRITE")}}export{connectRemoteMcp};
@@ -0,0 +1 @@
1
+ import{profileAuthorization,runOAuthCommand}from"./chunk-C33A2DW4.js";import"./chunk-7S3DJ2QE.js";import"./chunk-PUNG4ND7.js";import"./chunk-BVSTJQJI.js";import"./chunk-66CUOZVI.js";import"./chunk-6NVIN2NI.js";export{profileAuthorization,runOAuthCommand};
@@ -0,0 +1 @@
1
+ import{loginLink,openLoginBrowser}from"./chunk-VDNNFVTZ.js";import{clientHome,connectionError,projectConnection,readAccount,saveConnection}from"./chunk-C753RRRA.js";import"./chunk-GJ7BZJLW.js";import"./chunk-VPYAXWXY.js";import{runOAuthCommand}from"./chunk-C33A2DW4.js";import{FileOAuthProvider}from"./chunk-7S3DJ2QE.js";import"./chunk-PUNG4ND7.js";import"./chunk-BVSTJQJI.js";import"./chunk-66CUOZVI.js";import{NativeStudioSdkError}from"./chunk-6NVIN2NI.js";import{randomUUID,timingSafeEqual}from"node:crypto";import{createServer}from"node:http";import{join}from"node:path";async function runProjectConnect(argv,environment,hooks={}){if(argv[0]!=="connect")throw Error();const options=new Map;for(let i=1;i<argv.length;i+=2){const key=argv[i],value=argv[i+1];if(!key||!["--mcp-url","--scope","--timeout-ms","--browser"].includes(key)||!value||value.startsWith("--")||options.has(key))throw Error();options.set(key,value)}const resource=projectConnection(options.get("--mcp-url")??"");const scope=options.get("--scope")??"nvs:read";if(!["nvs:read","nvs:read nvs:write"].includes(scope))throw Error();const browser=options.get("--browser")??"auto";if(!["auto","manual"].includes(browser))throw Error();const timeout=options.get("--timeout-ms")??"180000";if(!/^\d+$/.test(timeout)||Number(timeout)<1e3||Number(timeout)>3e5)throw Error();const signal=AbortSignal.timeout(Number(timeout));const root=await clientHome(environment,true),profile=`profile-${randomUUID()}.json`;const path=join(root,profile),callbackPath=`/callback/${randomUUID()}`;const account=await readAccount(root);if(account&&(account.state!=="ACTIVE"||Date.parse(account.expiresAt)<=Date.now()||account.workspaceId!==resource.tenantId||account.projectId!==resource.projectId))connectionError("ACCOUNT_PROJECT_SELECTION_REQUIRED");let provider,receiving=false,redeeming=false;let finish;const callback=new Promise(resolve=>{finish=resolve});const server=createServer({maxHeaderSize:8192,requestTimeout:5e3,headersTimeout:5e3},(req,res)=>{res.setHeader("cache-control","no-store");res.setHeader("content-type","text/plain; charset=utf-8");res.setHeader("x-content-type-options","nosniff");const address=server.address();const host=address&&typeof address!=="string"?`127.0.0.1:${address.port}`:"";if(req.method!=="GET"||req.headers.host!==host||req.headers.origin||!req.url||req.url.length>4096||!req.url.startsWith(callbackPath+"?")||!provider||receiving){res.writeHead(400).end("Invalid authorization callback.");return}const url=new URL(req.url,`http://${host}`),state=url.searchParams.get("state");const expected=provider.data.state;const issuer=provider.data.discovery?.authorizationServerMetadata?.issuer??provider.data.discovery?.authorizationServerUrl;if(!state||Buffer.byteLength(state)!==Buffer.byteLength(expected)||!timingSafeEqual(Buffer.from(state),Buffer.from(expected))||url.searchParams.getAll("state").length!==1||url.pathname!==callbackPath||url.searchParams.getAll("iss").length!==1||url.searchParams.get("iss")!==issuer||(url.searchParams.has("error")?url.searchParams.has("code"):url.searchParams.getAll("code").length!==1||!url.searchParams.get("code"))){res.writeHead(400).end("Invalid authorization callback.");return}receiving=true;res.end("Authorization received. Return to NativeStudio CLI for the result.");finish(url.searchParams.has("error")?null:url.href)});server.maxConnections=8;const expired=()=>finish(null);signal.addEventListener("abort",expired,{once:true});try{await new Promise((resolve,reject)=>{server.once("error",reject);server.listen(0,"127.0.0.1",resolve)});const address=server.address();if(!address||typeof address==="string")throw Error();const redirect=`http://127.0.0.1:${address.port}${callbackPath}`;await runOAuthCommand(["auth-start","--profile",path,"--mcp-url",resource.resource,"--callback",redirect,"--scope",scope],empty(),signal);provider=await FileOAuthProvider.load(path);if(!provider.data.authorizationUrl)throw Error();signal.throwIfAborted();if(hooks.authorize)await hooks.authorize(provider.data.authorizationUrl,signal);else if(browser==="manual")loginLink(provider.data.authorizationUrl);else await openLoginBrowser(provider.data.authorizationUrl,signal);const received=await callback;if(!received)connectionError(signal.aborted?"LOGIN_TIMED_OUT":"LOGIN_DENIED");async function*input(){yield Buffer.from(JSON.stringify({callbackUrl:received}))}redeeming=true;await runOAuthCommand(["auth-complete","--profile",path,"--input","-"],input(),signal);const credentials=await saveConnection(root,profile,account?.epoch).catch(()=>{throw new NativeStudioSdkError("PROJECT_AUTHORIZED_CONNECTION_NOT_SELECTED","INTERNAL_OPERATIONAL_FAILURE","UNKNOWN")});return{exitCode:0,output:{semanticStatus:"SUCCESS",connected:true,credentialPurpose:"PROJECT_MCP",...resource,scope:credentials.scope,requestedScope:scope,nextSteps:["nvs status","nvs find --query <intent>","nvs mcp"]}}}catch(error){if(!redeeming&&signal.aborted)connectionError("LOGIN_TIMED_OUT");throw error}finally{signal.removeEventListener("abort",expired);server.closeAllConnections();await new Promise(resolve=>server.close(()=>resolve()))}}async function*empty(){}export{runProjectConnect};
@@ -0,0 +1 @@
1
+ import{CapabilityDescribeSchema,CapabilityGroupsSchema,NativeStudioAgentClient,NativeStudioMcpClient,NativeStudioNavigationClient,NativeStudioNavigationFacade,NativeStudioRuntimeAuthorityClient,NavigationGroupIdSchema,NavigationGroups,NavigationProfile,NavigationProfileKey,NavigationToolNames,navigationGroup,queryPages,sdkImageMediaTools,sdkMcpTools,sdkOperations,waitForOperation}from"./chunk-E57YVMQ4.js";import"./chunk-GJ7BZJLW.js";import"./chunk-HLKERZIE.js";import"./chunk-VPYAXWXY.js";import{NativeStudioSdkError,sdkInputError}from"./chunk-6NVIN2NI.js";export{CapabilityDescribeSchema,CapabilityGroupsSchema,NativeStudioAgentClient,NativeStudioMcpClient,NativeStudioNavigationClient,NativeStudioNavigationFacade,NativeStudioRuntimeAuthorityClient,NativeStudioSdkError,NavigationGroupIdSchema,NavigationGroups,NavigationProfile,NavigationProfileKey,NavigationToolNames,navigationGroup,queryPages,sdkImageMediaTools,sdkInputError,sdkMcpTools,sdkOperations,waitForOperation};
@@ -0,0 +1 @@
1
+ import{defaultConnection}from"./chunk-C753RRRA.js";import{StdioLines}from"./chunk-JFC6ZIGA.js";import"./chunk-GJ7BZJLW.js";import"./chunk-VPYAXWXY.js";import{FileOAuthProvider}from"./chunk-7S3DJ2QE.js";import{secureEndpoint}from"./chunk-PUNG4ND7.js";import{readCredential}from"./chunk-BVSTJQJI.js";import"./chunk-66CUOZVI.js";import"./chunk-6NVIN2NI.js";async function stdioRelayConfig(argv,environment){const options=new Map;for(let i=0;i<argv.length;i+=2){const key=argv[i],value=argv[i+1];if(!key||!["--profile","--mcp-url","--token-env","--token-file","--timeout-ms","--discovery"].includes(key)||!value||value.startsWith("--")||options.has(key))throw Error();options.set(key,value)}await defaultConnection(options,environment,false);const discovery=options.get("--discovery");if(discovery!==void 0&&discovery!=="contextual-v1")throw Error();const timeout=options.get("--timeout-ms")??"30000";if(!/^\d+$/.test(timeout))throw Error();const timeoutMs=Number(timeout);if(!Number.isSafeInteger(timeoutMs)||timeoutMs<100||timeoutMs>3e5)throw Error();const profile=options.get("--profile");let endpoint,read;if(profile){if(options.has("--mcp-url")||options.has("--token-env")||options.has("--token-file"))throw Error();endpoint=secureEndpoint((await FileOAuthProvider.load(profile)).data.resource);read=async signal=>{const{profileAuthorization}=await import("./oauth-F7EZGVME.js");const value=await profileAuthorization(profile,signal);if(secureEndpoint(value.resource).href!==endpoint.href)throw Error();return value.authorization}}else{if(!options.has("--mcp-url"))throw Error();endpoint=secureEndpoint(options.get("--mcp-url"));await readCredential(options,environment);read=()=>readCredential(options,environment)}let tail=Promise.resolve();return{endpoint,timeoutMs,...discovery?{discovery}:{},authorization(signal){const current=tail.then(()=>{signal.throwIfAborted();return read(signal)});tail=current.catch(()=>{});return current}}}import{isJSONRPCResultResponse}from"@modelcontextprotocol/client";var StdioContextualMenu=class{clear(){}request(request){return request}response(request,message){if(request.method!=="initialize"||!isJSONRPCResultResponse(message))return message;return{...message,result:{...message.result,instructions:["Navigation guidance: standard tools/list is stable. Use studio_start, studio_navigate and studio_capability_groups; describe returns a bounded public definition, not a tool-menu change. Follow native evidence and exact typed commands.",...typeof message.result.instructions==="string"?[message.result.instructions]:[]].join("\n")}}}};import{StreamableHTTPClientTransport,deserializeMessage,serializeMessage,isJSONRPCRequest,isJSONRPCNotification,isJSONRPCResultResponse as isJSONRPCResultResponse2,isJSONRPCErrorResponse}from"@modelcontextprotocol/client";var STDIO_RESPONSE_LIMIT=32*1024*1024;function stdioRelayFetch(config,shutdown){return async(input,init)=>{const target=new URL(input instanceof Request?input.url:String(input));if(target.href!==config.endpoint.href)throw Error();const signal=AbortSignal.any([shutdown,...init?.signal?[init.signal]:[],AbortSignal.timeout(config.timeoutMs)]);const authorization=await config.authorization(signal);signal.throwIfAborted();const headers=new Headers(init?.headers);headers.set("authorization",authorization);const response=await fetch(input,{...init,headers,signal,redirect:"error"});if(!response.body)return response;const declared=response.headers.get("content-length");if(declared&&(!/^\d+$/.test(declared)||Number(declared)>STDIO_RESPONSE_LIMIT)){await response.body.cancel();throw Error()}const reader=response.body.getReader();let size=0;const body=new ReadableStream({async pull(controller){try{const part=await reader.read();if(part.done){reader.releaseLock();controller.close();return}size+=part.value.byteLength;if(size>STDIO_RESPONSE_LIMIT){await reader.cancel();throw Error()}controller.enqueue(part.value)}catch(error){controller.error(error)}},async cancel(reason){await reader.cancel(reason);reader.releaseLock()}});return new Response(body,{status:response.status,statusText:response.statusText,headers:response.headers})}}var inputLimit=18*1024*1024;var concurrency=32;async function serveRemoteMcpStdio(config,input,output){const shutdown=new AbortController;const pending=new Map;const transport=new StreamableHTTPClientTransport(config.endpoint,{fetch:stdioRelayFetch(config,shutdown.signal),onInsufficientScope:"throw",reconnectionOptions:{maxRetries:0,maxReconnectionDelay:1,initialReconnectionDelay:1,reconnectionDelayGrowFactor:1}});const lines=new StdioLines(inputLimit);let queuedBytes=0,sends=0,stopped=false;let finish;const closed=new Promise(resolve=>{finish=resolve});const menu=config.discovery==="contextual-v1"?new StdioContextualMenu:void 0;function discard(id){const item=pending.get(id);if(item)clearTimeout(item.timer);pending.delete(id);return item}function write(message){if(stopped)return;const frame=serializeMessage(message);const bytes=Buffer.byteLength(frame);if(bytes>STDIO_RESPONSE_LIMIT||queuedBytes+bytes>STDIO_RESPONSE_LIMIT){void close(1);return}queuedBytes+=bytes;output.write(frame,error=>{queuedBytes-=bytes;if(error)void close(1)})}function fail(id,noWrite=false){const item=discard(id);item?.abort.abort();write({jsonrpc:"2.0",id,error:{code:-32603,message:"Remote MCP request unavailable",data:{semanticStatus:"INTERNAL_OPERATIONAL_FAILURE",outcome:noWrite?"NO_WRITE":"UNKNOWN"}}})}async function forward(message){if(isJSONRPCNotification(message)&&message.method==="notifications/cancelled"){const id=message.params?.requestId;if(typeof id==="string"||typeof id==="number")discard(id)?.abort.abort();if((transport.protocolVersion??"")>="2026-07-28")return}const request=isJSONRPCRequest(message)?message:null;if(request&&(pending.has(request.id)||pending.size>=concurrency||sends>=concurrency)){if(pending.has(request.id)){void close(2);return}fail(request.id,true);return}if(!request&&sends>=concurrency){void close(2);return}if(request){const version=request.method==="initialize"?request.params?.protocolVersion:request.params?._meta?.["io.modelcontextprotocol/protocolVersion"];if(typeof version==="string")transport.setProtocolVersion(version);const abort=new AbortController;const timer=setTimeout(()=>{if(pending.has(request.id))fail(request.id)},config.timeoutMs);timer.unref();pending.set(request.id,{abort,timer,request})}sends++;try{await transport.send(request&&menu?menu.request(request):message,request?{requestSignal:pending.get(request.id).abort.signal,onRequestStreamEnd:()=>{if(pending.has(request.id))fail(request.id)}}:{requestSignal:shutdown.signal})}catch{if(request&&pending.has(request.id))fail(request.id)}finally{sends--}}transport.onmessage=message=>{if(isJSONRPCResultResponse2(message)||isJSONRPCErrorResponse(message)){if(message.id===void 0)return;const item=discard(message.id);if(!item)return;if(item.request.method==="initialize"&&isJSONRPCResultResponse2(message)&&typeof message.result.protocolVersion==="string")transport.setProtocolVersion(message.result.protocolVersion);if(menu)message=menu.response(item.request,message)}if(isJSONRPCNotification(message)&&message.method==="notifications/tools/list_changed")menu?.clear();write(message)};transport.onerror=()=>{};function data(chunk){if(stopped)return;const bytes=Buffer.isBuffer(chunk)?chunk:Buffer.from(chunk);try{lines.push(bytes,line=>{void forward(deserializeMessage(new TextDecoder("utf-8",{fatal:true}).decode(line)));return!stopped})}catch{void close(2)}}function end(){void close(lines.incomplete?2:0)}function streamError(){void close(1)}async function close(code=0){if(stopped)return;stopped=true;shutdown.abort();for(const item of pending.values()){clearTimeout(item.timer);item.abort.abort()}pending.clear();menu?.clear();lines.clear();input.off("data",data).off("end",end).off("error",streamError);input.pause();output.off("error",streamError);try{await transport.close()}catch{code||=1}finish(code)}await transport.start();input.on("data",data).once("end",end).once("error",streamError);output.once("error",streamError);return{close,closed}}async function runMcpStdio(argv,environment){try{const config=await stdioRelayConfig(argv,environment);const handle=await serveRemoteMcpStdio(config,process.stdin,process.stdout);const stop=()=>{void handle.close()};process.once("SIGINT",stop);process.once("SIGTERM",stop);const code=await handle.closed;process.off("SIGINT",stop);process.off("SIGTERM",stop);if(code)process.stderr.write("NativeStudio MCP stdio connection failed.\n");return code}catch{process.stderr.write("NativeStudio MCP stdio configuration failed; run nvs status and nvs connect after account sign-in, or use explicit credentials.\n");return 2}}export{runMcpStdio};
@@ -0,0 +1,18 @@
1
+ import type { LocalInstallationManager } from "./manager.js";
2
+ export declare function desktopRuntimeChannel(raw: unknown): {
3
+ value: {
4
+ catalogueUrl: string;
5
+ publicKey: string;
6
+ protocol: "NVS_DESKTOP_RUNTIME_CHANNEL_V1";
7
+ };
8
+ host: string;
9
+ fingerprint: string;
10
+ };
11
+ export declare function desktopChannelInfo(manager: LocalInstallationManager, bundled?: unknown): Promise<{
12
+ protocol: "NVS_DESKTOP_CHANNEL_INFO_V1";
13
+ configured: boolean;
14
+ source: "UNAVAILABLE" | "EXISTING" | "BUNDLED";
15
+ host: string | null;
16
+ channelFingerprint: string | null;
17
+ }>;
18
+ export declare function configureDesktopChannel(manager: LocalInstallationManager, expectedFingerprint: string, bundled?: unknown): Promise<void>;
@@ -0,0 +1,281 @@
1
+ import { z } from "zod";
2
+ export declare const DesktopRuntimeChannelSchema: z.ZodObject<{
3
+ protocol: z.ZodLiteral<"NVS_DESKTOP_RUNTIME_CHANNEL_V1">;
4
+ catalogueUrl: z.ZodString;
5
+ publicKey: z.ZodString;
6
+ }, z.core.$strict>;
7
+ export declare const DesktopOwnerRequestSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{
8
+ operation: z.ZodEnum<{
9
+ check: "check";
10
+ status: "status";
11
+ configuration: "configuration";
12
+ start: "start";
13
+ stop: "stop";
14
+ recovery: "recovery";
15
+ }>;
16
+ }, z.core.$strict>, z.ZodObject<{
17
+ operation: z.ZodEnum<{
18
+ prepare: "prepare";
19
+ reject: "reject";
20
+ }>;
21
+ version: z.ZodString;
22
+ }, z.core.$strict>, z.ZodObject<{
23
+ operation: z.ZodLiteral<"tools-prepare">;
24
+ version: z.ZodString;
25
+ choice: z.ZodDiscriminatedUnion<[z.ZodObject<{
26
+ mode: z.ZodLiteral<"MANAGED">;
27
+ }, z.core.$strict>, z.ZodObject<{
28
+ mode: z.ZodLiteral<"INSTALLED">;
29
+ ffmpeg: z.ZodString;
30
+ ffprobe: z.ZodString;
31
+ }, z.core.$strict>], "mode">;
32
+ }, z.core.$strict>, z.ZodObject<{
33
+ operation: z.ZodLiteral<"configure">;
34
+ channelFingerprint: z.ZodString;
35
+ }, z.core.$strict>, z.ZodObject<{
36
+ operation: z.ZodEnum<{
37
+ apply: "apply";
38
+ recover: "recover";
39
+ }>;
40
+ planId: z.ZodUUID;
41
+ fingerprint: z.ZodString;
42
+ }, z.core.$strict>], "operation">;
43
+ export declare const DesktopRuntimeStatusSchema: z.ZodObject<{
44
+ protocol: z.ZodLiteral<"NVS_DESKTOP_RUNTIME_STATUS_V1">;
45
+ state: z.ZodEnum<{
46
+ UNAVAILABLE: "UNAVAILABLE";
47
+ RUNNING: "RUNNING";
48
+ INSTALL_REQUIRED: "INSTALL_REQUIRED";
49
+ STOPPED: "STOPPED";
50
+ }>;
51
+ activeVersion: z.ZodNullable<z.ZodString>;
52
+ phase: z.ZodString;
53
+ toolMode: z.ZodOptional<z.ZodNullable<z.ZodEnum<{
54
+ MANAGED: "MANAGED";
55
+ INSTALLED: "INSTALLED";
56
+ }>>>;
57
+ }, z.core.$strict>;
58
+ export declare const DesktopUpdateCheckSchema: z.ZodObject<{
59
+ protocol: z.ZodLiteral<"NVS_DESKTOP_RUNTIME_UPDATES_V1">;
60
+ activeVersion: z.ZodNullable<z.ZodString>;
61
+ versions: z.ZodArray<z.ZodObject<{
62
+ version: z.ZodString;
63
+ rejected: z.ZodBoolean;
64
+ }, z.core.$strict>>;
65
+ notifications: z.ZodBoolean;
66
+ }, z.core.$strict>;
67
+ export declare const DesktopOwnerPlanSchema: z.ZodObject<{
68
+ protocol: z.ZodLiteral<"NVS_DESKTOP_OWNER_PLAN_V1">;
69
+ plan: z.ZodNullable<z.ZodObject<{
70
+ kind: z.ZodEnum<{
71
+ APPLY: "APPLY";
72
+ RECOVER: "RECOVER";
73
+ }>;
74
+ toolMode: z.ZodOptional<z.ZodEnum<{
75
+ MANAGED: "MANAGED";
76
+ INSTALLED: "INSTALLED";
77
+ }>>;
78
+ planId: z.ZodUUID;
79
+ fingerprint: z.ZodString;
80
+ version: z.ZodString;
81
+ previousVersion: z.ZodNullable<z.ZodString>;
82
+ expiresAt: z.ZodISODateTime;
83
+ phase: z.ZodString;
84
+ }, z.core.$strict>>;
85
+ }, z.core.$strict>;
86
+ export declare const DesktopChannelInfoSchema: z.ZodObject<{
87
+ protocol: z.ZodLiteral<"NVS_DESKTOP_CHANNEL_INFO_V1">;
88
+ configured: z.ZodBoolean;
89
+ source: z.ZodEnum<{
90
+ UNAVAILABLE: "UNAVAILABLE";
91
+ EXISTING: "EXISTING";
92
+ BUNDLED: "BUNDLED";
93
+ }>;
94
+ host: z.ZodNullable<z.ZodString>;
95
+ channelFingerprint: z.ZodNullable<z.ZodString>;
96
+ }, z.core.$strict>;
97
+ export declare const desktopOwnerResponses: {
98
+ readonly status: z.ZodObject<{
99
+ protocol: z.ZodLiteral<"NVS_DESKTOP_RUNTIME_STATUS_V1">;
100
+ state: z.ZodEnum<{
101
+ UNAVAILABLE: "UNAVAILABLE";
102
+ RUNNING: "RUNNING";
103
+ INSTALL_REQUIRED: "INSTALL_REQUIRED";
104
+ STOPPED: "STOPPED";
105
+ }>;
106
+ activeVersion: z.ZodNullable<z.ZodString>;
107
+ phase: z.ZodString;
108
+ toolMode: z.ZodOptional<z.ZodNullable<z.ZodEnum<{
109
+ MANAGED: "MANAGED";
110
+ INSTALLED: "INSTALLED";
111
+ }>>>;
112
+ }, z.core.$strict>;
113
+ readonly start: z.ZodObject<{
114
+ protocol: z.ZodLiteral<"NVS_DESKTOP_RUNTIME_STATUS_V1">;
115
+ state: z.ZodEnum<{
116
+ UNAVAILABLE: "UNAVAILABLE";
117
+ RUNNING: "RUNNING";
118
+ INSTALL_REQUIRED: "INSTALL_REQUIRED";
119
+ STOPPED: "STOPPED";
120
+ }>;
121
+ activeVersion: z.ZodNullable<z.ZodString>;
122
+ phase: z.ZodString;
123
+ toolMode: z.ZodOptional<z.ZodNullable<z.ZodEnum<{
124
+ MANAGED: "MANAGED";
125
+ INSTALLED: "INSTALLED";
126
+ }>>>;
127
+ }, z.core.$strict>;
128
+ readonly stop: z.ZodObject<{
129
+ protocol: z.ZodLiteral<"NVS_DESKTOP_RUNTIME_STATUS_V1">;
130
+ state: z.ZodEnum<{
131
+ UNAVAILABLE: "UNAVAILABLE";
132
+ RUNNING: "RUNNING";
133
+ INSTALL_REQUIRED: "INSTALL_REQUIRED";
134
+ STOPPED: "STOPPED";
135
+ }>;
136
+ activeVersion: z.ZodNullable<z.ZodString>;
137
+ phase: z.ZodString;
138
+ toolMode: z.ZodOptional<z.ZodNullable<z.ZodEnum<{
139
+ MANAGED: "MANAGED";
140
+ INSTALLED: "INSTALLED";
141
+ }>>>;
142
+ }, z.core.$strict>;
143
+ readonly configure: z.ZodObject<{
144
+ protocol: z.ZodLiteral<"NVS_DESKTOP_RUNTIME_STATUS_V1">;
145
+ state: z.ZodEnum<{
146
+ UNAVAILABLE: "UNAVAILABLE";
147
+ RUNNING: "RUNNING";
148
+ INSTALL_REQUIRED: "INSTALL_REQUIRED";
149
+ STOPPED: "STOPPED";
150
+ }>;
151
+ activeVersion: z.ZodNullable<z.ZodString>;
152
+ phase: z.ZodString;
153
+ toolMode: z.ZodOptional<z.ZodNullable<z.ZodEnum<{
154
+ MANAGED: "MANAGED";
155
+ INSTALLED: "INSTALLED";
156
+ }>>>;
157
+ }, z.core.$strict>;
158
+ readonly apply: z.ZodObject<{
159
+ protocol: z.ZodLiteral<"NVS_DESKTOP_RUNTIME_STATUS_V1">;
160
+ state: z.ZodEnum<{
161
+ UNAVAILABLE: "UNAVAILABLE";
162
+ RUNNING: "RUNNING";
163
+ INSTALL_REQUIRED: "INSTALL_REQUIRED";
164
+ STOPPED: "STOPPED";
165
+ }>;
166
+ activeVersion: z.ZodNullable<z.ZodString>;
167
+ phase: z.ZodString;
168
+ toolMode: z.ZodOptional<z.ZodNullable<z.ZodEnum<{
169
+ MANAGED: "MANAGED";
170
+ INSTALLED: "INSTALLED";
171
+ }>>>;
172
+ }, z.core.$strict>;
173
+ readonly recover: z.ZodObject<{
174
+ protocol: z.ZodLiteral<"NVS_DESKTOP_RUNTIME_STATUS_V1">;
175
+ state: z.ZodEnum<{
176
+ UNAVAILABLE: "UNAVAILABLE";
177
+ RUNNING: "RUNNING";
178
+ INSTALL_REQUIRED: "INSTALL_REQUIRED";
179
+ STOPPED: "STOPPED";
180
+ }>;
181
+ activeVersion: z.ZodNullable<z.ZodString>;
182
+ phase: z.ZodString;
183
+ toolMode: z.ZodOptional<z.ZodNullable<z.ZodEnum<{
184
+ MANAGED: "MANAGED";
185
+ INSTALLED: "INSTALLED";
186
+ }>>>;
187
+ }, z.core.$strict>;
188
+ readonly reject: z.ZodObject<{
189
+ protocol: z.ZodLiteral<"NVS_DESKTOP_RUNTIME_STATUS_V1">;
190
+ state: z.ZodEnum<{
191
+ UNAVAILABLE: "UNAVAILABLE";
192
+ RUNNING: "RUNNING";
193
+ INSTALL_REQUIRED: "INSTALL_REQUIRED";
194
+ STOPPED: "STOPPED";
195
+ }>;
196
+ activeVersion: z.ZodNullable<z.ZodString>;
197
+ phase: z.ZodString;
198
+ toolMode: z.ZodOptional<z.ZodNullable<z.ZodEnum<{
199
+ MANAGED: "MANAGED";
200
+ INSTALLED: "INSTALLED";
201
+ }>>>;
202
+ }, z.core.$strict>;
203
+ readonly check: z.ZodObject<{
204
+ protocol: z.ZodLiteral<"NVS_DESKTOP_RUNTIME_UPDATES_V1">;
205
+ activeVersion: z.ZodNullable<z.ZodString>;
206
+ versions: z.ZodArray<z.ZodObject<{
207
+ version: z.ZodString;
208
+ rejected: z.ZodBoolean;
209
+ }, z.core.$strict>>;
210
+ notifications: z.ZodBoolean;
211
+ }, z.core.$strict>;
212
+ readonly configuration: z.ZodObject<{
213
+ protocol: z.ZodLiteral<"NVS_DESKTOP_CHANNEL_INFO_V1">;
214
+ configured: z.ZodBoolean;
215
+ source: z.ZodEnum<{
216
+ UNAVAILABLE: "UNAVAILABLE";
217
+ EXISTING: "EXISTING";
218
+ BUNDLED: "BUNDLED";
219
+ }>;
220
+ host: z.ZodNullable<z.ZodString>;
221
+ channelFingerprint: z.ZodNullable<z.ZodString>;
222
+ }, z.core.$strict>;
223
+ readonly prepare: z.ZodObject<{
224
+ protocol: z.ZodLiteral<"NVS_DESKTOP_OWNER_PLAN_V1">;
225
+ plan: z.ZodNullable<z.ZodObject<{
226
+ kind: z.ZodEnum<{
227
+ APPLY: "APPLY";
228
+ RECOVER: "RECOVER";
229
+ }>;
230
+ toolMode: z.ZodOptional<z.ZodEnum<{
231
+ MANAGED: "MANAGED";
232
+ INSTALLED: "INSTALLED";
233
+ }>>;
234
+ planId: z.ZodUUID;
235
+ fingerprint: z.ZodString;
236
+ version: z.ZodString;
237
+ previousVersion: z.ZodNullable<z.ZodString>;
238
+ expiresAt: z.ZodISODateTime;
239
+ phase: z.ZodString;
240
+ }, z.core.$strict>>;
241
+ }, z.core.$strict>;
242
+ readonly "tools-prepare": z.ZodObject<{
243
+ protocol: z.ZodLiteral<"NVS_DESKTOP_OWNER_PLAN_V1">;
244
+ plan: z.ZodNullable<z.ZodObject<{
245
+ kind: z.ZodEnum<{
246
+ APPLY: "APPLY";
247
+ RECOVER: "RECOVER";
248
+ }>;
249
+ toolMode: z.ZodOptional<z.ZodEnum<{
250
+ MANAGED: "MANAGED";
251
+ INSTALLED: "INSTALLED";
252
+ }>>;
253
+ planId: z.ZodUUID;
254
+ fingerprint: z.ZodString;
255
+ version: z.ZodString;
256
+ previousVersion: z.ZodNullable<z.ZodString>;
257
+ expiresAt: z.ZodISODateTime;
258
+ phase: z.ZodString;
259
+ }, z.core.$strict>>;
260
+ }, z.core.$strict>;
261
+ readonly recovery: z.ZodObject<{
262
+ protocol: z.ZodLiteral<"NVS_DESKTOP_OWNER_PLAN_V1">;
263
+ plan: z.ZodNullable<z.ZodObject<{
264
+ kind: z.ZodEnum<{
265
+ APPLY: "APPLY";
266
+ RECOVER: "RECOVER";
267
+ }>;
268
+ toolMode: z.ZodOptional<z.ZodEnum<{
269
+ MANAGED: "MANAGED";
270
+ INSTALLED: "INSTALLED";
271
+ }>>;
272
+ planId: z.ZodUUID;
273
+ fingerprint: z.ZodString;
274
+ version: z.ZodString;
275
+ previousVersion: z.ZodNullable<z.ZodString>;
276
+ expiresAt: z.ZodISODateTime;
277
+ phase: z.ZodString;
278
+ }, z.core.$strict>>;
279
+ }, z.core.$strict>;
280
+ };
281
+ export type DesktopOwnerPlan = z.infer<typeof DesktopOwnerPlanSchema>["plan"];
@@ -0,0 +1 @@
1
+ export declare function materializeDesktopNode(home: string, source: string, expected: string, licenseDigest?: string): Promise<string>;