@nativestudio/cli 0.3.0-rc.2 → 0.3.0-rc.21

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 (283) hide show
  1. package/COMPATIBILITY.json +37 -8
  2. package/LICENSE +201 -21
  3. package/components/runtime.json +33 -4
  4. package/components/runtime.tgz +0 -0
  5. package/dist/_chunks/chunk-27KI24GK.js +1 -0
  6. package/dist/_chunks/chunk-2S7FI3HF.js +1 -0
  7. package/dist/_chunks/chunk-3RNDOAQI.js +1 -0
  8. package/dist/_chunks/{chunk-C33A2DW4.js → chunk-3TOXIJ7K.js} +1 -1
  9. package/dist/_chunks/chunk-4AD4PNUX.js +1 -0
  10. package/dist/_chunks/chunk-5Y7J2OYL.js +45 -0
  11. package/dist/_chunks/chunk-76E5R3OC.js +1 -0
  12. package/dist/_chunks/chunk-7I7ARCY7.js +1 -0
  13. package/dist/_chunks/chunk-7IVAYDU3.js +1 -0
  14. package/dist/_chunks/chunk-7P2NA6TH.js +1 -0
  15. package/dist/_chunks/chunk-DLW42PJ6.js +1 -0
  16. package/dist/_chunks/chunk-DMA53YVU.js +1 -0
  17. package/dist/_chunks/chunk-ETK7GYCB.js +1 -0
  18. package/dist/_chunks/chunk-FFXSXE3G.js +1 -0
  19. package/dist/_chunks/chunk-H4FH6STZ.js +1 -0
  20. package/dist/_chunks/chunk-KOCUZ3AE.js +1 -0
  21. package/dist/_chunks/chunk-LDBXGRCQ.js +1 -0
  22. package/dist/_chunks/chunk-LTNJ45JP.js +1 -0
  23. package/dist/_chunks/chunk-MZWEFYHE.js +1 -0
  24. package/dist/_chunks/{chunk-VDNNFVTZ.js → chunk-OW6R4MAQ.js} +1 -1
  25. package/dist/_chunks/chunk-PQCA4X5H.js +1 -0
  26. package/dist/_chunks/chunk-QGK6G6YS.js +1 -0
  27. package/dist/_chunks/chunk-SM2I7TJ3.js +1 -0
  28. package/dist/_chunks/chunk-TT7IA5HB.js +1 -0
  29. package/dist/_chunks/chunk-VXYZCCCQ.js +1 -0
  30. package/dist/_chunks/chunk-VYCNG6TR.js +1 -0
  31. package/dist/_chunks/chunk-WLQMICJN.js +1 -0
  32. package/dist/_chunks/chunk-WTJVS2VS.js +1 -0
  33. package/dist/_chunks/chunk-X5MVC46N.js +1 -0
  34. package/dist/_chunks/chunk-X5PBZTKX.js +1 -0
  35. package/dist/_chunks/chunk-ZMJYBUS3.js +1 -0
  36. package/dist/_chunks/chunk-ZYXHPTT2.js +1 -0
  37. package/dist/_chunks/component-contract-2JHTRTOB.js +1 -0
  38. package/dist/_chunks/component-preflight-6OWDQAZT.js +1 -0
  39. package/dist/_chunks/connect-7TJDWXV4.js +1 -0
  40. package/dist/_chunks/device-management-JPS4HG34.js +1 -0
  41. package/dist/_chunks/device-preflight-GTQ67H7C.js +1 -0
  42. package/dist/_chunks/devices-inventory-E6ZLXCVR.js +1 -0
  43. package/dist/_chunks/devices-main-2BMCANKU.js +1 -0
  44. package/dist/_chunks/files-JJ6YOULB.js +1 -0
  45. package/dist/_chunks/host-component-ZYQ5ETVL.js +1 -0
  46. package/dist/_chunks/host-help-VNLA3YOV.js +1 -0
  47. package/dist/_chunks/host-main-KLWW7R47.js +1 -0
  48. package/dist/_chunks/http-profile-3VVSWYA5.js +1 -0
  49. package/dist/_chunks/library-main-3WWH7UYV.js +1 -0
  50. package/dist/_chunks/local-main-5BW63USP.js +1 -0
  51. package/dist/_chunks/local-mcp-AARKBDU5.js +1 -0
  52. package/dist/_chunks/main-LGYJ3ZCN.js +2 -0
  53. package/dist/_chunks/mcp-BLSK636Q.js +1 -0
  54. package/dist/_chunks/oauth-RPME2XYB.js +1 -0
  55. package/dist/_chunks/observe-entry-JVZAMB7N.js +1 -0
  56. package/dist/_chunks/remote-client-25Z65VJU.js +1 -0
  57. package/dist/_chunks/render-main-6Z3DKCWL.js +1 -0
  58. package/dist/_chunks/series-main-FBERVYWG.js +1 -0
  59. package/dist/_chunks/source-import-PNMCMTK7.js +1 -0
  60. package/dist/_chunks/src-7HSJFRVQ.js +1 -0
  61. package/dist/_chunks/stdio-main-HNLJCG45.js +1 -0
  62. package/dist/_chunks/workspace-main-QX5JGEMR.js +1 -0
  63. package/dist/_types/cli/local/desktop-contract.d.ts +1981 -22
  64. package/dist/_types/cli/local/desktop-device-contract.d.ts +807 -0
  65. package/dist/_types/cli/local/desktop-device-navigation.d.ts +3 -0
  66. package/dist/_types/cli/local/desktop-device-owner.d.ts +273 -0
  67. package/dist/_types/cli/local/desktop-device-state.d.ts +455 -0
  68. package/dist/_types/cli/local/desktop-library.d.ts +853 -0
  69. package/dist/_types/cli/local/desktop-owner.d.ts +787 -4
  70. package/dist/_types/cli/local/ledger.d.ts +76 -20
  71. package/dist/_types/cli/local/manager.d.ts +1233 -49
  72. package/dist/_types/cli/local/mcp-tools.d.ts +313 -54
  73. package/dist/_types/cli/local/releases.d.ts +30 -7
  74. package/dist/_types/cli/local-management.d.ts +9 -2
  75. package/dist/_types/cli/local-navigation.d.ts +1 -0
  76. package/dist/_types/contracts/agent-execution-lifecycle.d.ts +55 -43
  77. package/dist/_types/contracts/agent-execution-oauth.d.ts +2 -2
  78. package/dist/_types/contracts/agent-execution-registration.d.ts +59 -15
  79. package/dist/_types/contracts/agent-execution-selection.d.ts +7 -7
  80. package/dist/_types/contracts/agent-host-contract.d.ts +189 -0
  81. package/dist/_types/contracts/agent-host-execution.d.ts +92 -61
  82. package/dist/_types/contracts/agent-host-generic-transport.d.ts +4 -4
  83. package/dist/_types/contracts/agent-host-legacy-release.d.ts +31 -0
  84. package/dist/_types/contracts/agent-host-protocol.d.ts +71 -0
  85. package/dist/_types/contracts/agent-host-wire.d.ts +263 -0
  86. package/dist/_types/contracts/agent-host.d.ts +126 -65
  87. package/dist/_types/contracts/artifact-discovery.d.ts +143 -11
  88. package/dist/_types/contracts/audio.d.ts +166 -0
  89. package/dist/_types/contracts/component-status.d.ts +241 -0
  90. package/dist/_types/contracts/composition-authoring.d.ts +8 -8
  91. package/dist/_types/contracts/composition-frame-render.d.ts +4 -4
  92. package/dist/_types/contracts/composition-observation.d.ts +1 -1
  93. package/dist/_types/contracts/composition-render-base.d.ts +5 -4
  94. package/dist/_types/contracts/composition-render.d.ts +8 -8
  95. package/dist/_types/contracts/composition-repair.d.ts +10 -10
  96. package/dist/_types/contracts/composition-source-review.d.ts +13 -13
  97. package/dist/_types/contracts/consistency-profile.d.ts +102 -6
  98. package/dist/_types/contracts/continuity-evaluation.d.ts +1 -1
  99. package/dist/_types/contracts/delivery-completion.d.ts +1 -1
  100. package/dist/_types/contracts/delivery-manifest.d.ts +25 -11729
  101. package/dist/_types/contracts/delivery-operations.d.ts +207 -3915
  102. package/dist/_types/contracts/delivery-summary.d.ts +4 -4
  103. package/dist/_types/contracts/delivery-validation.d.ts +25 -2
  104. package/dist/_types/contracts/device-onboarding.d.ts +35 -0
  105. package/dist/_types/contracts/device-render.d.ts +113 -0
  106. package/dist/_types/contracts/editor-intelligence.d.ts +392 -2531
  107. package/dist/_types/contracts/enterprise-brand.d.ts +302 -0
  108. package/dist/_types/contracts/exploration-recommendation.d.ts +263 -11607
  109. package/dist/_types/contracts/external-agent-access.d.ts +4 -6
  110. package/dist/_types/contracts/federation-event-link-receiver.d.ts +200 -0
  111. package/dist/_types/contracts/federation-event-link.d.ts +485 -0
  112. package/dist/_types/contracts/federation-result.d.ts +239 -0
  113. package/dist/_types/contracts/final-ready.d.ts +24 -24
  114. package/dist/_types/contracts/final-render.d.ts +1742 -6949
  115. package/dist/_types/contracts/human-identity.d.ts +13 -0
  116. package/dist/_types/contracts/human-links.d.ts +58 -0
  117. package/dist/_types/contracts/index.d.ts +26 -0
  118. package/dist/_types/contracts/interface/common.d.ts +18 -0
  119. package/dist/_types/contracts/interface/execution-output.d.ts +9 -6
  120. package/dist/_types/contracts/interface/media-output.d.ts +118 -0
  121. package/dist/_types/contracts/interface/operation.d.ts +89 -0
  122. package/dist/_types/contracts/interface/production-snapshot.d.ts +106 -199
  123. package/dist/_types/contracts/interface/query.d.ts +85 -0
  124. package/dist/_types/contracts/keyframe-generation.d.ts +31 -2
  125. package/dist/_types/contracts/keyframe-review.d.ts +7 -7
  126. package/dist/_types/contracts/lifecycle-event-projections.d.ts +19 -4
  127. package/dist/_types/contracts/lifecycle-events.d.ts +54 -2
  128. package/dist/_types/contracts/local-execution/agent-component-status.d.ts +109 -0
  129. package/dist/_types/contracts/local-execution/agent-context.d.ts +385 -0
  130. package/dist/_types/contracts/local-execution/agent-evidence.d.ts +79 -0
  131. package/dist/_types/contracts/local-execution/agent-grant.d.ts +31 -0
  132. package/dist/_types/contracts/local-execution/agent-review.d.ts +529 -71
  133. package/dist/_types/contracts/local-execution/audio-profile.d.ts +6 -0
  134. package/dist/_types/contracts/local-execution/common.d.ts +12 -11
  135. package/dist/_types/contracts/local-execution/completion.d.ts +41 -45
  136. package/dist/_types/contracts/local-execution/components.d.ts +45 -0
  137. package/dist/_types/contracts/local-execution/cpu-preparation.d.ts +46 -0
  138. package/dist/_types/contracts/local-execution/cpu-resources.d.ts +55 -0
  139. package/dist/_types/contracts/local-execution/cpu-speech-job.d.ts +70 -0
  140. package/dist/_types/contracts/local-execution/cpu-speech.d.ts +161 -0
  141. package/dist/_types/contracts/local-execution/descriptor.d.ts +38 -0
  142. package/dist/_types/contracts/local-execution/device-authority.d.ts +31 -0
  143. package/dist/_types/contracts/local-execution/device-inventory.d.ts +108 -0
  144. package/dist/_types/contracts/local-execution/device-workspace.d.ts +11 -0
  145. package/dist/_types/contracts/local-execution/device.d.ts +24 -55
  146. package/dist/_types/contracts/local-execution/enrollment-credential.d.ts +141 -0
  147. package/dist/_types/contracts/local-execution/enrollment-handoff.d.ts +44 -0
  148. package/dist/_types/contracts/local-execution/external-generation.d.ts +199 -0
  149. package/dist/_types/contracts/local-execution/index.d.ts +36 -0
  150. package/dist/_types/contracts/local-execution/ipc.d.ts +2809 -231
  151. package/dist/_types/contracts/local-execution/library-command.d.ts +620 -0
  152. package/dist/_types/contracts/local-execution/library-result.d.ts +428 -0
  153. package/dist/_types/contracts/local-execution/library.d.ts +873 -0
  154. package/dist/_types/contracts/local-execution/lifecycle.d.ts +262 -48
  155. package/dist/_types/contracts/local-execution/local-navigation.d.ts +304 -67
  156. package/dist/_types/contracts/local-execution/management.d.ts +407 -0
  157. package/dist/_types/contracts/local-execution/media-recipe.d.ts +207 -0
  158. package/dist/_types/contracts/local-execution/media-validation-request.d.ts +232 -0
  159. package/dist/_types/contracts/local-execution/media-validation.d.ts +262 -0
  160. package/dist/_types/contracts/local-execution/object-transfer.d.ts +155 -0
  161. package/dist/_types/contracts/local-execution/offline.d.ts +59 -0
  162. package/dist/_types/contracts/local-execution/preview.d.ts +177 -3561
  163. package/dist/_types/contracts/local-execution/processor-capability.d.ts +49 -0
  164. package/dist/_types/contracts/local-execution/processor-direct.d.ts +290 -0
  165. package/dist/_types/contracts/local-execution/processor-recipes.d.ts +1194 -0
  166. package/dist/_types/contracts/local-execution/processor-toolchain.d.ts +47 -0
  167. package/dist/_types/contracts/local-execution/processor.d.ts +6424 -0
  168. package/dist/_types/contracts/local-execution/project-source-direct.d.ts +201 -0
  169. package/dist/_types/contracts/local-execution/qwen-tts.d.ts +31 -0
  170. package/dist/_types/contracts/local-execution/recognition.d.ts +170 -0
  171. package/dist/_types/contracts/local-execution/speech.d.ts +95 -0
  172. package/dist/_types/contracts/local-execution/tool-selection.d.ts +71 -5
  173. package/dist/_types/contracts/local-execution/whisper.d.ts +24 -0
  174. package/dist/_types/contracts/local-execution/work.d.ts +124 -3402
  175. package/dist/_types/contracts/local-execution/workspace.d.ts +141 -0
  176. package/dist/_types/contracts/mcp-capabilities.d.ts +16 -0
  177. package/dist/_types/contracts/media-category.d.ts +11 -0
  178. package/dist/_types/contracts/media-observation.d.ts +930 -9
  179. package/dist/_types/contracts/native-speech-model.d.ts +53 -0
  180. package/dist/_types/contracts/native-speech-options.d.ts +25 -0
  181. package/dist/_types/contracts/native-tool-authority.d.ts +25 -21
  182. package/dist/_types/contracts/native-tool-execution.d.ts +60 -39
  183. package/dist/_types/contracts/navigation-context.d.ts +76 -8
  184. package/dist/_types/contracts/navigation-groups.d.ts +2 -2
  185. package/dist/_types/contracts/navigation.d.ts +79 -26
  186. package/dist/_types/contracts/observation-profile.d.ts +3 -3
  187. package/dist/_types/contracts/production-creation.d.ts +30 -0
  188. package/dist/_types/contracts/production-feedback.d.ts +452 -0
  189. package/dist/_types/contracts/production.d.ts +30 -0
  190. package/dist/_types/contracts/programmatic-composition.d.ts +24 -24
  191. package/dist/_types/contracts/programmatic-exploration.d.ts +362 -5999
  192. package/dist/_types/contracts/programmatic-video-review.d.ts +5 -5
  193. package/dist/_types/contracts/project-library.d.ts +30 -0
  194. package/dist/_types/contracts/project.d.ts +30 -0
  195. package/dist/_types/contracts/provider-catalog.d.ts +3 -3
  196. package/dist/_types/contracts/provider-models.d.ts +209 -8
  197. package/dist/_types/contracts/provider.d.ts +66 -1
  198. package/dist/_types/contracts/reference-preview.d.ts +20 -0
  199. package/dist/_types/contracts/render-readiness.d.ts +175 -0
  200. package/dist/_types/contracts/repair-lifecycle.d.ts +64 -396
  201. package/dist/_types/contracts/repair-plan.d.ts +18 -100
  202. package/dist/_types/contracts/repair-strategy.d.ts +163 -4478
  203. package/dist/_types/contracts/review-intelligence-final-output.d.ts +418 -8150
  204. package/dist/_types/contracts/review-intelligence.d.ts +455 -11423
  205. package/dist/_types/contracts/review1-repair-source.d.ts +6 -6
  206. package/dist/_types/contracts/review1-repair-strategy.d.ts +4 -4
  207. package/dist/_types/contracts/rough-cut-manifest.d.ts +27 -7
  208. package/dist/_types/contracts/rough-cut-profile.d.ts +12 -3
  209. package/dist/_types/contracts/rough-cut-review.d.ts +144 -12495
  210. package/dist/_types/contracts/rough-cut.d.ts +1170 -5673
  211. package/dist/_types/contracts/series-canon.d.ts +97 -0
  212. package/dist/_types/contracts/series-character.d.ts +23 -0
  213. package/dist/_types/contracts/series-improvement.d.ts +1639 -0
  214. package/dist/_types/contracts/series-standard.d.ts +1641 -0
  215. package/dist/_types/contracts/shares.d.ts +135 -0
  216. package/dist/_types/contracts/shot-preparation-basis.d.ts +2 -2
  217. package/dist/_types/contracts/shot-preparation.d.ts +4 -4
  218. package/dist/_types/contracts/sound-making-plan.d.ts +210 -2
  219. package/dist/_types/contracts/speech-cost.d.ts +96 -0
  220. package/dist/_types/contracts/speech-parameters.d.ts +39 -0
  221. package/dist/_types/contracts/speech.d.ts +603 -23
  222. package/dist/_types/contracts/temporal-evidence-operation.d.ts +2 -1
  223. package/dist/_types/contracts/timeline-audio.d.ts +20 -4
  224. package/dist/_types/contracts/timeline-manifest.d.ts +40 -8
  225. package/dist/_types/contracts/timeline-source-sound.d.ts +42 -4
  226. package/dist/_types/contracts/timeline-v2.d.ts +124 -16
  227. package/dist/_types/contracts/timeline-version-reader.d.ts +288 -40
  228. package/dist/_types/contracts/timeline-visual-layers.d.ts +124 -16
  229. package/dist/_types/contracts/timeline.d.ts +50 -4850
  230. package/dist/_types/contracts/transcription.d.ts +1 -1
  231. package/dist/_types/contracts/video-generation.d.ts +35 -2
  232. package/dist/_types/contracts/video-review.d.ts +7 -7
  233. package/dist/_types/contracts/visual-exploration.d.ts +3 -3
  234. package/dist/_types/contracts/visual-layer-render.d.ts +298 -47
  235. package/dist/_types/contracts/visual-sequence.d.ts +22 -0
  236. package/dist/_types/contracts/voice-consistency.d.ts +183 -0
  237. package/dist/_types/contracts/voice-profile/contracts.d.ts +821 -0
  238. package/dist/_types/contracts/voice-profile/identity.d.ts +27 -0
  239. package/dist/_types/contracts/voice-profile/interface.d.ts +89 -0
  240. package/dist/_types/contracts/voice-profile/reference.d.ts +106 -0
  241. package/dist/_types/contracts/voice-review.d.ts +1194 -0
  242. package/dist/_types/contracts/workspace.d.ts +83 -0
  243. package/dist/_types/sdk/errors.d.ts +9 -3
  244. package/dist/_types/sdk/local-runtime/components.d.ts +2 -0
  245. package/dist/_types/sdk/local-runtime/device-client.d.ts +181 -19
  246. package/dist/_types/sdk/local-runtime/library.d.ts +268 -0
  247. package/dist/_types/sdk/local-runtime/workspace.d.ts +186 -0
  248. package/dist/_types/sdk/local-runtime-client.d.ts +1934 -96
  249. package/dist/entry.js +1 -1
  250. package/dist/local-management.js +1 -1
  251. package/dist/local-navigation.js +1 -1
  252. package/dist/native/helper.exe +0 -0
  253. package/dist/native/helper.json +1 -0
  254. package/package.json +2 -8
  255. package/README.md +0 -95
  256. package/dist/_chunks/chunk-66CUOZVI.js +0 -1
  257. package/dist/_chunks/chunk-6NVIN2NI.js +0 -1
  258. package/dist/_chunks/chunk-7S3DJ2QE.js +0 -1
  259. package/dist/_chunks/chunk-BVSTJQJI.js +0 -1
  260. package/dist/_chunks/chunk-C753RRRA.js +0 -1
  261. package/dist/_chunks/chunk-E57YVMQ4.js +0 -1
  262. package/dist/_chunks/chunk-GJ7BZJLW.js +0 -1
  263. package/dist/_chunks/chunk-HLKERZIE.js +0 -1
  264. package/dist/_chunks/chunk-K6LVS2IN.js +0 -1
  265. package/dist/_chunks/chunk-KHKUJXQX.js +0 -1
  266. package/dist/_chunks/chunk-PUNG4ND7.js +0 -1
  267. package/dist/_chunks/chunk-VC3ODN3M.js +0 -1
  268. package/dist/_chunks/chunk-VPYAXWXY.js +0 -1
  269. package/dist/_chunks/files-FZEK2ZZJ.js +0 -1
  270. package/dist/_chunks/local-main-NLFS74Q4.js +0 -1
  271. package/dist/_chunks/local-mcp-OLHBBVNN.js +0 -1
  272. package/dist/_chunks/main-VRIQTI6R.js +0 -2
  273. package/dist/_chunks/mcp-EIMXNRH3.js +0 -1
  274. package/dist/_chunks/oauth-F7EZGVME.js +0 -1
  275. package/dist/_chunks/project-connect-MXM7IY55.js +0 -1
  276. package/dist/_chunks/src-7F6ZEU3U.js +0 -1
  277. package/dist/_chunks/stdio-main-KOGQ5OWF.js +0 -1
  278. package/dist/native/Bootstrap.ps1 +0 -90
  279. package/dist/native/JobNative.cs +0 -127
  280. package/dist/native/JobRunner.cs +0 -360
  281. package/dist/native/NativeMain.cs +0 -146
  282. package/dist/native/PipeBridge.cs +0 -260
  283. package/dist/native/PrivateAccess.cs +0 -152
@@ -0,0 +1 @@
1
+ import{DesktopDeviceScopeSchema}from"./chunk-SM2I7TJ3.js";import{canonicalLocalJson}from"./chunk-2S7FI3HF.js";import{fail,optional,read,sha256,write}from"./chunk-DLW42PJ6.js";import{join}from"node:path";import{z}from"zod";var digest=z.string().regex(/^[a-f0-9]{64}$/);var DesktopAutomationSchema=z.strictObject({enabled:z.boolean(),scope:DesktopDeviceScopeSchema,deviceId:z.uuid(),deviceRevision:z.int().positive(),installationFingerprint:digest});async function desktopInstallationIdentity(manager){const active=(await manager.ledger.current()).value.active;if(!active)return null;const tools=active.toolsConfigPath?JSON.parse((await read(active.toolsConfigPath,32768)).toString()):null;return{version:active.descriptor.version,workProtocol:active.descriptor.workProtocol,fingerprint:sha256(canonicalLocalJson({descriptor:active.descriptor,files:active.files,tools}))}}async function desktopAutomation(home){const value=await optional(join(home,"desktop-execution-policy.json"));return value?DesktopAutomationSchema.parse(value):null}function canResumeDesktop(policy,state,installation){if(!policy?.enabled||!installation||!state.device||policy.installationFingerprint!==installation.fingerprint||canonicalLocalJson(policy.scope)!==canonicalLocalJson(state.scope)||policy.deviceId!==state.device.deviceId||policy.deviceRevision!==state.device.revision)return false;return state.device.revokedAt===null}async function rememberDesktopAutomation(home,state,installation,expectedFingerprint){if(!installation||installation.fingerprint!==expectedFingerprint||!state.device)fail("DEVICE_PLAN_CHANGED");const value=DesktopAutomationSchema.parse({enabled:true,scope:state.scope,deviceId:state.device.deviceId,deviceRevision:state.device.revision,installationFingerprint:expectedFingerprint});await write(join(home,"desktop-execution-policy.json"),canonicalLocalJson(value));return value}async function disableDesktopAutomation(home){const policy=await desktopAutomation(home);if(policy)await write(join(home,"desktop-execution-policy.json"),canonicalLocalJson({...policy,enabled:false}))}export{desktopInstallationIdentity,desktopAutomation,canResumeDesktop,rememberDesktopAutomation,disableDesktopAutomation};
@@ -1,3 +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:
1
+ import{secureEndpoint}from"./chunk-KOCUZ3AE.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
2
  ${url}
3
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{connectDevice,generateDeviceKey}from"./chunk-H4FH6STZ.js";import{canResumeDesktop,desktopAutomation,desktopInstallationIdentity,rememberDesktopAutomation}from"./chunk-MZWEFYHE.js";import{LocalInstallationManager,probeLocalLibrary,probeReferenceThumbnail,probeTenantComposition,probeTenantMediaProcessing,probeTenantMediaValidation,probeTenantSpeech,probeTenantTranscription,socketAbsent}from"./chunk-FFXSXE3G.js";import{DesktopDeviceRecords}from"./chunk-ETK7GYCB.js";import{DesktopDeviceReplySchema,DesktopDeviceRequestSchema}from"./chunk-SM2I7TJ3.js";import{LocalDeviceChallengeSchema,LocalDeviceSessionSchema,LocalDeviceTransportConfigurationSchema,LocalDeviceViewSchema,LocalFinalRenderAdmissionSchema,LocalManagementCommandSchema,LocalPreviewAdmissionSchema,canonicalLocalJson,processorFamilies}from"./chunk-2S7FI3HF.js";import{fail,read,sha256}from"./chunk-DLW42PJ6.js";import{createPrivateKey as createPrivateKey2,createPublicKey,randomUUID as randomUUID3}from"node:crypto";import{randomUUID}from"node:crypto";async function desktopDeviceCapabilities(manager){const active=(await manager.ledger.current()).value.active;if(!active)fail("INSTALL_REQUIRED");const root=manager.ledger.slotPath(active);const validation=await probeTenantMediaValidation(root,active);const processing=await probeTenantMediaProcessing(root,active);const processors=processing?Object.keys(processorFamilies).filter(kind=>!["COMPOSITION_RENDER","LOCAL_MEDIA_INSPECT","LOCAL_MEDIA_PUBLISH","SPEECH_SYNTHESIZE","TRANSCRIBE_AUDIO","KEYFRAME_GENERATE","VIDEO_GENERATE","SPEECH_EXTERNAL_QWEN","REFERENCE_PREVIEW","TRANSCRIBE_EXTERNAL_QWEN"].includes(kind)):[];if(processing){if(await probeReferenceThumbnail(root,active))processors.push("REFERENCE_PREVIEW");if(await probeLocalLibrary(root,active))processors.push("LOCAL_MEDIA_INSPECT","LOCAL_MEDIA_PUBLISH");if(await probeTenantComposition(root,active))processors.push("COMPOSITION_RENDER");if(await probeTenantSpeech(root,active))processors.push("SPEECH_SYNTHESIZE");if(await probeTenantTranscription(root,active))processors.push("TRANSCRIBE_AUDIO")}return{...validation?{tenantMediaValidation:true}:{},...processors.length?{tenantMediaProcessing:true,processorCapabilities:processors.sort()}:{}}}async function connectDesktopDevice(records,manager,s,expectedRevision){if(s.revision!==expectedRevision)fail("DEVICE_PLAN_CHANGED");if(s.connection?.phase==="CONNECTING")fail("DEVICE_CONNECTION_RECOVERY_REQUIRED");if(!s.device||s.device.revokedAt)fail("DEVICE_ENROLLMENT_REQUIRED");const capabilities=await desktopDeviceCapabilities(manager);const c=await manager.configuration();const previous=c.cloudConfigFile?JSON.parse((await read(c.cloudConfigFile,32768)).toString()):null;if(previous&&(previous.endpoint!==s.scope.origin||previous.tenantId!==s.scope.tenantId||previous.deviceId!==s.device.deviceId))fail("DEVICE_CONNECTION_CONFLICT");const running=(await manager.status()).running;if(!running&&!await socketAbsent(c.stateDirectory))fail("DEVICE_CONNECTION_RECOVERY_REQUIRED");const matches=value=>{const saved=value;return saved?.deviceRevision===s.device.revision&&saved.tenantMediaValidation===capabilities.tenantMediaValidation&&saved.tenantMediaProcessing===capabilities.tenantMediaProcessing&&canonicalLocalJson(saved.processorCapabilities??null)===canonicalLocalJson(capabilities.processorCapabilities??null)};const reuse=running&&matches(previous)&&matches(s.connection);const expiresAt=new Date(Date.now()+24*36e5).toISOString();s=await records.save(s,{connection:{phase:"CONNECTING",expiresAt,deviceRevision:s.device.revision,...capabilities}});if(!reuse){if(running)await manager.stop();await connectDevice(manager,{endpoint:s.scope.origin,tenantId:s.scope.tenantId,deviceId:s.device.deviceId,deviceRevision:s.device.revision,privateKeyFile:records.keyPath(),platform:s.device.platform,...capabilities});await manager.start()}const id=randomUUID();await manager.grant({tenantId:s.scope.tenantId,deviceId:s.device.deviceId,expiresAt},records.connectorPath(id));return records.save(s,{connectorId:id,connection:{...s.connection,phase:"CONNECTED"}})}async function recoverDesktopConnection(records,manager,s){if(s.connection?.phase!=="CONNECTING")return s;const c=await manager.configuration(),running=(await manager.status()).running;if(!running){if(!await socketAbsent(c.stateDirectory))fail("DEVICE_CONNECTION_RECOVERY_REQUIRED");return records.save(s,{connection:null,connectorId:null})}if(!c.cloudConfigFile||!s.device||s.device.revokedAt)fail("DEVICE_CONNECTION_RECOVERY_REQUIRED");const raw=JSON.parse((await read(c.cloudConfigFile,32768)).toString());const{tools:_tools,...transport}=raw;void _tools;const actual=LocalDeviceTransportConfigurationSchema.parse(transport);if(actual.endpoint!==s.scope.origin||actual.deviceId!==s.device.deviceId||actual.tenantId!==s.scope.tenantId||actual.deviceRevision!==s.connection.deviceRevision||actual.deviceRevision!==s.device.revision||actual.tenantMediaValidation!==s.connection.tenantMediaValidation||actual.tenantMediaProcessing!==s.connection.tenantMediaProcessing||canonicalLocalJson(actual.processorCapabilities??null)!==canonicalLocalJson(s.connection.processorCapabilities??null))fail("DEVICE_CONNECTION_RECOVERY_REQUIRED");return records.save(s,{connection:{...s.connection,phase:"READY"},connectorId:null})}import{createPrivateKey,sign,randomUUID as randomUUID2}from"node:crypto";async function proveDesktopDevice(records){const state=await records.current(),d=state.device;if(!d)fail("DEVICE_ENROLLMENT_REQUIRED");async function request(action,input){const response=await fetch(state.scope.origin+"/v1/local-execution/devices/"+action,{method:"POST",redirect:"error",headers:{"content-type":"application/json"},body:JSON.stringify(input),signal:AbortSignal.timeout(15e3)});if(!response.ok){await response.body?.cancel();fail("DEVICE_PROOF_UNAVAILABLE")}const chunks=[];let size=0;for await(const bytes of response.body??[]){size+=bytes.length;if(size>16384)fail("DEVICE_PROOF_INVALID");chunks.push(bytes)}return JSON.parse(Buffer.concat(chunks).toString())}const scope={tenantId:d.tenantId,deviceId:d.deviceId,deviceRevision:d.revision};const started=performance.now();const challenge=LocalDeviceChallengeSchema.parse(await request("challenge",scope));if(challenge.tenantId!==d.tenantId||challenge.deviceId!==d.deviceId||challenge.deviceRevision!==d.revision||Date.parse(challenge.expiresAt)-Date.parse(challenge.issuedAt)<=performance.now()-started)fail("DEVICE_PROOF_INVALID");const key=createPrivateKey({key:JSON.parse((await read(records.keyPath(),16384)).toString()),format:"jwk"});const header=Buffer.from(JSON.stringify({alg:"ES256",typ:"nvs-local-device+jwt"})).toString("base64url");const iat=Math.floor(Date.parse(challenge.issuedAt)/1e3),claims=Buffer.from(JSON.stringify({protocol:"NVS_LOCAL_DEVICE_PROOF_V1",...scope,challengeId:challenge.challengeId,audience:challenge.audience,jti:randomUUID2(),iat,exp:iat+30})).toString("base64url");const unsigned=header+"."+claims;const assertion=unsigned+"."+sign("sha256",Buffer.from(unsigned),{key,dsaEncoding:"ieee-p1363"}).toString("base64url");const result=LocalDeviceSessionSchema.parse(await request("prove",{...scope,challengeId:challenge.challengeId,assertion}));if(result.tenantId!==d.tenantId||result.deviceId!==d.deviceId)fail("DEVICE_PROOF_INVALID")}var fingerprint=v=>sha256(canonicalLocalJson(v));function view(s){return{revision:s.revision,device:s.device?{deviceId:s.device.deviceId,label:s.device.label,revision:s.device.revision,revokedAt:s.device.revokedAt}:null,previews:s.previews,connection:s.connection,pending:s.pending?{kind:s.pending.command.kind,phase:s.pending.phase,fingerprint:s.pending.fingerprint,...s.pending.agentEnrollment&&{agentEnrollment:true}}:null}}function accepted(s,result){const command=s.pending.command,i=command.input;if(command.kind==="ENROLL"){const d=LocalDeviceViewSchema.parse(result);if(d.tenantId!==i.tenantId||d.enrolledByPrincipalId!==s.scope.principalId||d.label!==command.input.label||d.runtimeVersion!==command.input.runtimeVersion||canonicalLocalJson(d.publicKey)!==canonicalLocalJson(command.input.publicKey)||canonicalLocalJson(d.platform)!==canonicalLocalJson(command.input.platform)||d.revokedAt)fail("DEVICE_RESULT_INVALID");return{device:d}}if(command.kind==="REVOKE_DEVICE"){if(result?.semanticStatus!=="SUCCESS"||!s.device)fail("DEVICE_RESULT_INVALID");return{device:{...s.device,revision:s.device.revision+1,revokedAt:new Date().toISOString()},connectorId:null,connection:null}}const p=(command.kind==="FINAL_RENDER"?LocalFinalRenderAdmissionSchema:LocalPreviewAdmissionSchema).parse(result),input=command.input;if(p.productionId!==input.productionId||p.timelineVersionId!==input.timelineVersionId||p.timelineFingerprint!==input.timelineFingerprint||canonicalLocalJson(p.placement.policy)!==canonicalLocalJson(input.placement))fail("DEVICE_RESULT_INVALID");return{previews:[p,...s.previews.filter(v=>v.renderId!==p.renderId)].slice(0,20)}}async function runDesktopDeviceRequest(home,raw,policy){const request=DesktopDeviceRequestSchema.parse(raw),call=request.call;const records=await DesktopDeviceRecords.open(home,request.scope),manager=await LocalInstallationManager.open(home);let s=await records.current();if(s.pending&&policy&&!policy.allowedPendingKinds.includes(s.pending.command.kind))fail("DEVICE_COMMAND_UNSUPPORTED");const installation=await desktopInstallationIdentity(manager);let automatic=await desktopAutomation(home);const publicView=()=>({...view(s),installation,automaticConnection:canResumeDesktop(automatic,s,installation)});const processingSupported=async()=>{const active=(await manager.ledger.current()).value.active;return!!active&&await probeTenantMediaProcessing(manager.ledger.slotPath(active),active)};const librarySupported=async()=>{const active=(await manager.ledger.current()).value.active;return!!active&&await probeLocalLibrary(manager.ledger.slotPath(active),active)};const compositionSupported=async()=>{const active=(await manager.ledger.current()).value.active;return!!active&&await probeTenantComposition(manager.ledger.slotPath(active),active)};if(call.action==="media-processing-capability")return DesktopDeviceReplySchema.parse({view:publicView(),mediaProcessingSupported:await processingSupported(),localLibrarySupported:await librarySupported(),compositionProcessingSupported:await compositionSupported()});if(call.action==="media-validation-capability"){const active=(await manager.ledger.current()).value.active;const supported=!!active&&await probeTenantMediaValidation(manager.ledger.slotPath(active),active);return DesktopDeviceReplySchema.parse({view:publicView(),mediaValidationSupported:supported})}if(call.action==="inspect")return DesktopDeviceReplySchema.parse({view:publicView(),...s.pending?{command:s.pending.command}:{}});if(call.action==="dispatch"||call.action==="record"||call.action==="refused"){if(!s.pending||s.pending.fingerprint!==call.fingerprint)fail("DEVICE_PLAN_CHANGED");if(call.action==="dispatch"){if(s.pending.phase!=="PREPARED")fail("DEVICE_OUTCOME_UNKNOWN");const command2=s.pending.command;s=await records.save(s,{pending:{...s.pending,phase:"SENDING"}});return DesktopDeviceReplySchema.parse({view:publicView(),command:command2})}if(s.pending.phase!=="SENDING")fail("DEVICE_PLAN_CHANGED");s=await records.save(s,call.action==="record"?{...accepted(s,call.result),pending:null}:{pending:{...s.pending,phase:"REFUSED"}});return DesktopDeviceReplySchema.parse({view:publicView()})}if(s.pending?.phase==="SENDING")fail("DEVICE_OUTCOME_UNKNOWN");if(call.action==="remember-enable"){if(s.revision!==call.expectedRevision)fail("DEVICE_PLAN_CHANGED");automatic=await rememberDesktopAutomation(home,s,installation,call.installationFingerprint);return DesktopDeviceReplySchema.parse({view:publicView()})}if(call.action==="prove"){await proveDesktopDevice(records);return DesktopDeviceReplySchema.parse({view:publicView()})}if(call.action==="connect"){if(call.installationFingerprint&&call.installationFingerprint!==installation?.fingerprint)fail("DEVICE_PLAN_CHANGED");s=await connectDesktopDevice(records,manager,s,call.expectedRevision);return DesktopDeviceReplySchema.parse({view:publicView()})}if(call.action==="connection-recover"){s=await recoverDesktopConnection(records,manager,s);return DesktopDeviceReplySchema.parse({view:publicView()})}let command;if(call.action==="enroll"){if(s.device)fail("DEVICE_ALREADY_ENROLLED");if(call.expectedRevision!==void 0&&s.revision!==call.expectedRevision)fail("DEVICE_PLAN_CHANGED");const active=(await manager.ledger.current()).value.active;if(!active)fail("INSTALL_REQUIRED");let publicKey;try{const key=createPrivateKey2({key:JSON.parse((await read(records.keyPath(),16384)).toString()),format:"jwk"});publicKey=createPublicKey(key).export({format:"jwk"})}catch(e){if(e.code!=="ENOENT")throw e;publicKey=(await generateDeviceKey(records.keyPath())).publicKey}command={kind:"ENROLL",input:{tenantId:s.scope.tenantId,requestId:randomUUID3(),...call.bindWorkspaceMember||call.agentEnrollment?{expectedPrincipalId:s.scope.principalId}:{},label:call.label,platform:active.descriptor.platform,runtimeVersion:active.descriptor.version,publicKey}}}else{const d=s.device;if(!d)fail("DEVICE_ENROLLMENT_REQUIRED");if(call.action==="preview"||call.action==="final"){if(d.revokedAt)fail("LOCAL_AUTHORIZATION_REQUIRED");command={kind:call.action==="final"?"FINAL_RENDER":"PREVIEW",input:{...call.input,tenantId:s.scope.tenantId,placement:{mode:call.mode,deviceId:d.deviceId},idempotencyKey:"desktop:"+randomUUID3()}}}else{if(call.action!=="revoke"||d.revokedAt)fail("LOCAL_AUTHORIZATION_REQUIRED");command={kind:"REVOKE_DEVICE",input:{tenantId:s.scope.tenantId,deviceId:d.deviceId,requestId:randomUUID3(),expectedRevision:d.revision}}}}const parsed=LocalManagementCommandSchema.parse(command);s=await records.save(s,{...parsed.kind==="ENROLL"?{enrollment:parsed.input}:{},pending:{command:parsed,fingerprint:fingerprint(parsed),phase:"PREPARED",...call.action==="enroll"&&call.agentEnrollment&&{agentEnrollment:true}}});return DesktopDeviceReplySchema.parse({view:publicView(),command:parsed})}async function desktopDevicePending(home,scope){return(await(await DesktopDeviceRecords.open(home,scope)).current()).pending?.command??null}export{runDesktopDeviceRequest,desktopDevicePending};
@@ -0,0 +1 @@
1
+ import{privateAccess}from"./chunk-DLW42PJ6.js";import{open,constants}from"node:fs/promises";import{resolve}from"node:path";var limit=18*1024*1024;async function readInput(path,stdin,privateInput=false,signal){signal?.throwIfAborted();let bytes;if(path==="-"){const chunks=[];let size=0;const iterator=stdin[Symbol.asyncIterator]();try{while(true){signal?.throwIfAborted();let stopped;const pending=iterator.next();if(signal?.aborted){void pending.catch(()=>{});signal.throwIfAborted()}const next=signal?await Promise.race([pending,new Promise((_,reject)=>{stopped=()=>reject(signal.reason);signal.addEventListener("abort",stopped,{once:true})})]).finally(()=>{if(stopped)signal.removeEventListener("abort",stopped)}):await pending;if(next.done)break;size+=next.value.byteLength;if(size>limit)throw Error();chunks.push(Buffer.from(next.value))}}finally{void iterator.return?.().catch(()=>{})}bytes=chunks.length===1?chunks[0]:Buffer.concat(chunks,size)}else{if(privateInput&&process.platform==="win32")await privateAccess(resolve(path),"file");const handle=await open(path,constants.O_RDONLY|constants.O_NOFOLLOW|constants.O_NONBLOCK);try{const stat=await handle.stat();if(!stat.isFile()||stat.size>limit||privateInput&&process.platform!=="win32"&&((stat.mode&63)!==0||process.getuid&&stat.uid!==process.getuid()))throw Error();bytes=Buffer.alloc(stat.size+1);let used=0;while(used<bytes.byteLength){signal?.throwIfAborted();const read=await handle.read(bytes,used,bytes.byteLength-used,null);if(!read.bytesRead)break;used+=read.bytesRead}if(used!==stat.size)throw Error();bytes=bytes.subarray(0,used)}finally{await handle.close()}}signal?.throwIfAborted();const value=JSON.parse(new TextDecoder("utf-8",{fatal:true}).decode(bytes));if(!value||typeof value!=="object"||Array.isArray(value))throw Error();return value}async function readCredential(options,environment){if(options.has("--token-file")===options.has("--token-env"))throw Error();let token;const key=options.get("--token-env");if(key){if(!/^[A-Z][A-Z0-9_]{0,127}$/.test(key))throw Error();token=environment[key]??""}else{if(process.platform==="win32")await privateAccess(resolve(options.get("--token-file")),"file");const handle=await open(options.get("--token-file"),constants.O_RDONLY|constants.O_NOFOLLOW|constants.O_NONBLOCK);try{const stat=await handle.stat();if(!stat.isFile()||process.platform!=="win32"&&(stat.mode&63)!==0||stat.size>8192)throw Error();const bytes=Buffer.alloc(8193);const{bytesRead}=await handle.read(bytes,0,bytes.length,0);if(bytesRead>8192)throw Error();token=bytes.subarray(0,bytesRead).toString("utf8").trim()}finally{await handle.close()}}if(!/^[A-Za-z0-9._~-]{1,8192}$/.test(token))throw Error();return"Bearer "+token}export{readInput,readCredential};
@@ -0,0 +1 @@
1
+ import{DeviceEnrollmentScopeSchema,LocalDeviceTransportConfigurationSchema,LocalDeviceViewSchema,LocalFinalRenderAdmissionSchema,LocalManagementCommandSchema,LocalManagementResultSchema,LocalPreviewAdmissionSchema,StartLocalFinalRenderSchema,StartLocalPreviewSchema}from"./chunk-2S7FI3HF.js";import{z}from"zod";var DesktopDeviceScopeSchema=DeviceEnrollmentScopeSchema;var digest=z.string().regex(/^[a-f0-9]{64}$/);var DesktopDeviceCallSchema=z.discriminatedUnion("action",[z.strictObject({action:z.literal("inspect")}),z.strictObject({action:z.literal("prove")}),z.strictObject({action:z.literal("media-validation-capability")}),z.strictObject({action:z.literal("media-processing-capability")}),z.strictObject({action:z.literal("connect"),expectedRevision:z.int().nonnegative(),installationFingerprint:digest.optional()}),z.strictObject({action:z.literal("remember-enable"),expectedRevision:z.int().nonnegative(),installationFingerprint:digest}),z.strictObject({action:z.literal("connection-recover")}),z.strictObject({action:z.literal("enroll"),label:z.string().trim().min(1).max(120),expectedRevision:z.int().nonnegative().optional(),bindWorkspaceMember:z.literal(true).optional(),agentEnrollment:z.literal(true).optional()}),z.strictObject({action:z.literal("revoke")}),z.strictObject({action:z.literal("preview"),input:StartLocalPreviewSchema.omit({tenantId:true,placement:true,idempotencyKey:true}),mode:z.enum(["local-only","local-preferred"])}),z.strictObject({action:z.literal("final"),input:StartLocalFinalRenderSchema.omit({tenantId:true,placement:true,idempotencyKey:true}),mode:z.enum(["local-only","local-preferred"])}),z.strictObject({action:z.literal("dispatch"),fingerprint:digest}),z.strictObject({action:z.literal("record"),fingerprint:digest,result:LocalManagementResultSchema}),z.strictObject({action:z.literal("refused"),fingerprint:digest})]);var DesktopDeviceRequestSchema=z.strictObject({operation:z.literal("device"),scope:DesktopDeviceScopeSchema,call:DesktopDeviceCallSchema});var DesktopDeviceStateSchema=z.strictObject({revision:z.int().nonnegative(),scope:DesktopDeviceScopeSchema,enrollment:LocalManagementCommandSchema.options[0].shape.input.nullable(),device:LocalDeviceViewSchema.nullable(),previews:z.array(z.union([LocalPreviewAdmissionSchema,LocalFinalRenderAdmissionSchema])).max(20),connectorId:z.uuid().nullable(),connection:z.strictObject({phase:z.enum(["CONNECTING","READY","CONNECTED"]),expiresAt:z.iso.datetime(),tenantMediaProcessing:z.literal(true).optional(),processorCapabilities:LocalDeviceTransportConfigurationSchema.shape.processorCapabilities,deviceRevision:z.int().positive(),tenantMediaValidation:z.literal(true).optional()}).nullable().default(null),pending:z.strictObject({command:LocalManagementCommandSchema,fingerprint:digest,phase:z.enum(["PREPARED","SENDING","REFUSED"]),agentEnrollment:z.literal(true).optional()}).nullable()});var DesktopDeviceViewSchema=DesktopDeviceStateSchema.omit({scope:true,enrollment:true,connectorId:true,pending:true,device:true}).extend({installation:z.strictObject({version:z.string().min(1).max(100),fingerprint:digest,workProtocol:z.enum(["NVS_LOCAL_WORK_V1","NVS_LOCAL_WORK_V2"]).optional()}).nullable().optional(),automaticConnection:z.boolean().optional(),device:z.strictObject({deviceId:z.uuid(),label:z.string().max(120),revision:z.int().positive(),revokedAt:z.iso.datetime().nullable()}).nullable(),pending:z.strictObject({kind:z.enum(["ENROLL","REVOKE_DEVICE","PREVIEW","FINAL_RENDER"]),phase:z.enum(["PREPARED","SENDING","REFUSED"]),fingerprint:digest,agentEnrollment:z.literal(true).optional()}).nullable()});var DesktopDeviceReplySchema=z.strictObject({view:DesktopDeviceViewSchema,command:LocalManagementCommandSchema.optional(),mediaValidationSupported:z.boolean().optional(),mediaProcessingSupported:z.boolean().optional(),localLibrarySupported:z.boolean().optional(),compositionProcessingSupported:z.boolean().optional()});export{DesktopDeviceScopeSchema,DesktopDeviceRequestSchema,DesktopDeviceStateSchema,DesktopDeviceReplySchema};
@@ -0,0 +1 @@
1
+ var NativeStudioSdkError=class extends Error{constructor(code,semanticStatus,outcome,status=null,issues=[],capabilityMismatch){super(`NativeStudio ${code}`);this.code=code;this.semanticStatus=semanticStatus;this.outcome=outcome;this.status=status;this.issues=issues;this.capabilityMismatch=capabilityMismatch;this.name="NativeStudioSdkError"}code;semanticStatus;outcome;status;issues;capabilityMismatch};function sdkInputError(issues=[]){throw new NativeStudioSdkError("INVALID_INPUT","INVALID_INPUT","NO_WRITE",null,issues)}export{NativeStudioSdkError,sdkInputError};
@@ -0,0 +1 @@
1
+ import{embeddedRuntime,runtimeEnvironment,toolPreference,verifySlot}from"./chunk-FFXSXE3G.js";import{CpuSpeechPrepareInputSchema,CpuSpeechPreparedSchema,LocalToolSelectionSchema}from"./chunk-LDBXGRCQ.js";import{canonicalLocalJson}from"./chunk-2S7FI3HF.js";import{directory,fail,read,write}from"./chunk-DLW42PJ6.js";import{spawn}from"node:child_process";import{randomUUID}from"node:crypto";import{join}from"node:path";import{unlink}from"node:fs/promises";async function assertCpuPreparationCurrent(manager,original,planRevision=original.revision){const current=(await manager.ledger.current()).value;const configuration=await manager.configuration();if(current.revision!==original.revision||planRevision!==original.revision||canonicalLocalJson(configuration)!==canonicalLocalJson(original.configuration))fail("REVISION_CONFLICT")}async function prepareInstalledCpuSpeech(manager,raw){const input=CpuSpeechPrepareInputSchema.parse(raw),current=(await manager.ledger.current()).value;if(current.transition)fail("ACTIVATION_IN_PROGRESS");if(!current.active)fail("INSTALLATION_REQUIRED");const slot=current.active,root=manager.ledger.slotPath(slot),configuration=await manager.configuration();const context={revision:current.revision,configuration};await verifySlot(root,slot);const file=join(await directory(join(manager.ledger.root,"preparations")),randomUUID()+".json");await write(file,JSON.stringify(input),true);try{const prepared=await new Promise((resolve,reject)=>{const child=spawn(process.execPath,["--max-old-space-size=256",join(root,"dist/entry.js"),"--prepare-cpu-speech","--state-dir",configuration.stateDirectory,"--input-config",file],{env:runtimeEnvironment(),stdio:["ignore","pipe","pipe","ipc"],shell:false});const parts=[],errors=[];let used=0,errorBytes=0,killed=false;const timer=setTimeout(()=>{killed=true;child.kill("SIGTERM")},23e4);const kill=setTimeout(()=>{killed=true;child.kill("SIGKILL")},235e3);const abort=()=>{killed=true;child.kill("SIGTERM")};process.once("SIGINT",abort);process.once("SIGTERM",abort);child.stdout.on("data",chunk=>{used+=chunk.length;if(used>32768)child.kill("SIGTERM");else parts.push(chunk)});child.stderr.on("data",chunk=>{errorBytes+=chunk.length;if(errorBytes>4096)child.kill("SIGTERM");else errors.push(chunk)});child.once("error",reject);child.once("close",code=>{clearTimeout(timer);clearTimeout(kill);process.off("SIGINT",abort);process.off("SIGTERM",abort);try{if(killed)fail("CPU_PREPARATION_CANCELLED");if(code!==0||used>32768||errorBytes>4096){const last=Buffer.concat(errors).toString().trim().split("\n").at(-1);let reason;try{reason=JSON.parse(last??"{}").error?.code}catch{}if(reason==="CPU_BZIP2_REQUIRED")fail("CPU_BZIP2_REQUIRED");if(reason==="CPU_SPEECH_PLATFORM_UNAVAILABLE")fail("CPU_SPEECH_PLATFORM_UNAVAILABLE");fail("CPU_PREPARATION_FAILED")}resolve(CpuSpeechPreparedSchema.parse(JSON.parse(Buffer.concat(parts).toString())))}catch(error){reject(error)}})});await assertCpuPreparationCurrent(manager,context);const previous=await toolPreference(slot.toolsConfigPath,configuration.cloudConfigFile);const existing=slot.toolsConfigPath?LocalToolSelectionSchema.parse(JSON.parse((await read(slot.toolsConfigPath,32768)).toString())):null;const reuseMedia=previous.mode==="MANAGED"&&existing?.mode==="MANAGED"?{schemaVersion:1,ffmpeg:existing.ffmpeg,ffprobe:existing.ffprobe}:void 0;const choice={...previous,cpuSpeech:prepared.selection,...reuseMedia?{reuseMedia}:{}};const plan=await embeddedRuntime(slot.descriptor.version)?await manager.prepareBundled(slot.descriptor.version,choice):await manager.prepare(slot.descriptor.version,choice);await assertCpuPreparationCurrent(manager,context,plan.installationRevision);return{semanticStatus:"PREPARED",capability:prepared.capability,reused:prepared.reused,plan}}finally{await unlink(file).catch(error=>{if(error.code!=="ENOENT")throw error})}}export{prepareInstalledCpuSpeech};
@@ -0,0 +1 @@
1
+ import{profileAuthorization}from"./chunk-3TOXIJ7K.js";import{connectRemoteMcp}from"./chunk-76E5R3OC.js";import{clientHome,loadConnection}from"./chunk-27KI24GK.js";import{optional,write}from"./chunk-DLW42PJ6.js";import{NativeStudioSdkError}from"./chunk-TT7IA5HB.js";import{join}from"node:path";import{z}from"zod";var selection=z.strictObject({version:z.literal(1),tenantId:z.uuid(),resource:z.url(),projectId:z.uuid()});async function workspaceProject(scope,env){const value=await optional(join(await clientHome(env),"selection.json"));if(value===null)return null;const parsed=selection.safeParse(value);if(!parsed.success)throw new NativeStudioSdkError("PROJECT_SELECTION_INVALID","BLOCKED","NO_WRITE");return parsed.data.tenantId===scope.tenantId&&(!scope.resource||parsed.data.resource===scope.resource)?parsed.data.projectId:null}async function workspaceCommand(argv,env){const[command,...args]=argv;if(!["workspaces","workspace","projects","project"].includes(command??""))return null;let connection;try{connection=await loadConnection(env)}catch(error){if(error instanceof NativeStudioSdkError&&error.code==="CONNECTION_ACCOUNT_MISMATCH")return null;throw error}if(!connection)return null;const flags=new Map;for(let i=0;i<args.length;i+=2){const key=args[i],value=args[i+1];if(!key||!value||value.startsWith("--")||flags.has(key)||!["--id","--limit","--next"].includes(key))throw Error();flags.set(key,value)}if(command==="projects"?flags.has("--id"):command==="workspaces"?flags.size>0:flags.size!==1||!flags.has("--id"))throw Error();const auth=await profileAuthorization(connection.profile);const remote=await connectRemoteMcp(connection.resource,auth.authorization,connection.tenantId);try{if(command==="workspaces"){const page=await remote.studio.call("workspace.query",{});return{exitCode:0,output:{semanticStatus:"SUCCESS",workspaces:page.items}}}if(command==="projects"){const page=await remote.studio.call("project.query",{...flags.has("--limit")?{limit:z.coerce.number().int().min(1).max(100).parse(flags.get("--limit"))}:{},...flags.has("--next")?{next:flags.get("--next")}:{}});return{exitCode:0,output:{semanticStatus:"SUCCESS",...page}}}const id=z.uuid().parse(flags.get("--id"));if(command==="workspace"){if(id!==connection.tenantId)throw new NativeStudioSdkError("FORBIDDEN","BLOCKED","NO_WRITE");const value2=await remote.studio.call("workspace.get",{});return{exitCode:0,output:{semanticStatus:"SUCCESS",workspaceId:value2.id}}}const value=await remote.studio.call("project.get",{projectId:id});await write(join(await clientHome(env),"selection.json"),JSON.stringify({version:1,tenantId:connection.tenantId,resource:connection.resource,projectId:value.project.id}));return{exitCode:0,output:{semanticStatus:"SUCCESS",project:value.project}}}finally{await remote.close().catch(()=>{})}}export{workspaceProject,workspaceCommand};
@@ -0,0 +1 @@
1
+ import{DesktopLibraryImportRequestSchema,DesktopLibraryPrepareRequestSchema,DesktopLibraryReplySchema,DesktopLibraryRequestSchema}from"./chunk-DMA53YVU.js";import{desktopAutomation,desktopInstallationIdentity,disableDesktopAutomation}from"./chunk-MZWEFYHE.js";import{LocalInstallationManager,ownerClient,socketAbsent,waitStopped}from"./chunk-FFXSXE3G.js";import{DesktopDeviceReplySchema,DesktopDeviceRequestSchema,DesktopDeviceScopeSchema}from"./chunk-SM2I7TJ3.js";import{CpuSpeechPrepareInputSchema,LocalAgentDiscoverySchema,LocalAgentGrantSchema,LocalAgentProbeSchema,LocalAgentReviewViewSchema,LocalAgentSnapshotSchema,LocalDiagnosticsSchema,LocalOfflineCallSchema,LocalOfflinePageSchema,LocalResourcePolicySchema,LocalRuntimeDescriptorSchema,LocalToolSelectionSchema,LocalWorkspaceInspectionSchema}from"./chunk-LDBXGRCQ.js";import{canonicalLocalJson}from"./chunk-2S7FI3HF.js";import{atomicMove,directory,entries,fail,optional,read,sha256,write}from"./chunk-DLW42PJ6.js";import{NativeStudioSdkError}from"./chunk-TT7IA5HB.js";import{z as z7}from"zod";import{z}from"zod";import{join,sep}from"node:path";var StoragePlanSchema=z.strictObject({id:z.uuid(),mode:z.enum(["BACKUP","MIGRATE"]),source:z.string().min(1),destination:z.string().min(1),installationRevision:z.int().nonnegative(),installationFingerprint:z.string().regex(/^[a-f0-9]{64}$/),runtimeRevision:z.int().positive(),revision:z.int().nonnegative().default(0),phase:z.enum(["PREPARED","DRAINING","COPYING","COPIED","VERIFYING","COMPLETE","CANCELLED"]),fingerprint:z.string().regex(/^[a-f0-9]{64}$/),expiresAt:z.iso.datetime(),bytes:z.int().nonnegative().default(0)});var recordSchema=z.strictObject({plan:StoragePlanSchema,previous:z.string().regex(/^[a-f0-9]{64}$/).nullable(),digest:z.string().regex(/^[a-f0-9]{64}$/)});var phases=["PREPARED","DRAINING","COPYING","COPIED","VERIFYING","COMPLETE"];var terminal=phase=>["COMPLETE","CANCELLED"].includes(phase);var advances=(before,after)=>before===after||!terminal(before)&&(after==="CANCELLED"||phases.indexOf(after)===phases.indexOf(before)+1);async function storageInstallationIdentity(slot,source,destination){const tools=slot.toolsConfigPath?LocalToolSelectionSchema.parse(JSON.parse((await read(slot.toolsConfigPath,32768)).toString())):null;if(tools?.mode==="MANAGED"){for(const name of["ffmpeg","ffprobe"])for(const root of[source,destination])if(tools[name].path.startsWith(root+sep)){tools[name].path="{state}"+tools[name].path.slice(root.length);break}}return sha256(canonicalLocalJson({descriptor:slot.descriptor,files:slot.files,tools}))}function intent(p){return{id:p.id,mode:p.mode,source:p.source,destination:p.destination,installationRevision:p.installationRevision,installationFingerprint:p.installationFingerprint,runtimeRevision:p.runtimeRevision,expiresAt:p.expiresAt}}async function history(root,id2){const path=await directory(join(root,z.uuid().parse(id2)));let plan=null;let digest3=null;const names=(await entries(path)).filter(n=>/^\d{8}\.json$/.test(n)).sort();for(const[index,name]of names.entries()){const record=recordSchema.parse(JSON.parse((await read(join(path,name))).toString())),next=record.plan;if(next.id!==id2||next.revision!==index+1||next.fingerprint!==sha256(canonicalLocalJson(intent(next)))||record.previous!==digest3||record.digest!==sha256(canonicalLocalJson({plan:next,previous:digest3}))||!plan&&next.phase!=="PREPARED"||plan&&(plan.fingerprint!==next.fingerprint||!advances(plan.phase,next.phase)))fail("STORAGE_HISTORY_INVALID");plan=next;digest3=record.digest}return{plan,digest:digest3}}async function readStoragePlan(root,id2){return(await history(root,id2)).plan}async function saveStoragePlan(root,expected,phase,extra={}){const current=await history(root,expected.id),actual=current.plan;if((actual?.revision??0)!==expected.revision)fail("REVISION_CONFLICT");if(actual&&canonicalLocalJson(actual)!==canonicalLocalJson(expected))fail("PLAN_CHANGED");const next=StoragePlanSchema.parse({...expected,...extra,phase,revision:expected.revision+1});if(next.fingerprint!==sha256(canonicalLocalJson(intent(next))))fail("PLAN_CHANGED");if(!actual&&phase!=="PREPARED"||actual&&!advances(actual.phase,phase))fail("PLAN_CHANGED");const file=join(root,next.id,String(next.revision).padStart(8,"0")+".json");try{const body={plan:next,previous:current.digest};await write(file,canonicalLocalJson({...body,digest:sha256(canonicalLocalJson(body))}),true)}catch(e){if(e.code==="EEXIST")fail("REVISION_CONFLICT");throw e}return next}import{z as z2}from"zod";import{lstat as lstat2,realpath}from"node:fs/promises";import{randomUUID}from"node:crypto";import{join as join3,resolve,sep as sep3}from"node:path";import{constants,createReadStream}from"node:fs";import{open,readdir,lstat,statfs,chmod,unlink}from"node:fs/promises";import{join as join2,relative,sep as sep2}from"node:path";import{createHash}from"node:crypto";async function digestFile(path){const file=await open(path,constants.O_RDONLY|constants.O_NOFOLLOW);try{const before=await file.stat(),hash=createHash("sha256");if(!before.isFile()||before.nlink!==1||before.size>512*1024**2||process.platform!=="win32"&&(before.uid!==process.getuid?.()||before.mode&63))fail("STORAGE_FILE_INVALID");let bytes=0;for await(const chunk of createReadStream(path,{fd:file.fd,autoClose:false})){bytes+=chunk.length;if(bytes>before.size)fail("STORAGE_FILE_CHANGED");hash.update(chunk)}const after=await file.stat();if(bytes!==before.size||before.mtimeMs!==after.mtimeMs||before.ino!==after.ino)fail("STORAGE_FILE_CHANGED");return{bytes,sha256:hash.digest("hex"),mode:before.mode&448}}finally{await file.close()}}async function storageFiles(root){const files=[];async function walk(path,depth){if(depth>8)fail("STORAGE_FILE_LIMIT");for(const item of await readdir(path,{withFileTypes:true})){const source=join2(path,item.name),name=relative(root,source);if(path===root&&!["journal.sqlite","journal.sqlite-wal","cache","staging","tools","agent-images","agent-evidence","agent-reviews","library"].includes(item.name))continue;const info=await lstat(source);if(info.isSymbolicLink()||!info.isFile()&&!info.isDirectory())fail("STORAGE_FILE_INVALID");if(info.isDirectory())await walk(source,depth+1);else{if(files.length>=5e4)fail("STORAGE_FILE_LIMIT");const value=await digestFile(source);files.push({name,bytes:value.bytes,sha256:value.sha256})}}}await walk(root,0);return files.sort((a,b)=>a.name.localeCompare(b.name))}async function copyStorage(source,destination){if(destination===source||destination.startsWith(source+sep2)||source.startsWith(destination+sep2))fail("STORAGE_LOCATION_INVALID");await directory(destination);const files=await storageFiles(source),total=files.reduce((n,f)=>n+f.bytes,0);const fs=await statfs(destination);if(fs.bavail*fs.bsize<total+256*1024**2)fail("STORAGE_SPACE_REQUIRED");for(const item of files){const original=join2(source,item.name),target=join2(destination,item.name);const parent=target.slice(0,target.lastIndexOf(sep2));await directory(parent);try{const existing=await digestFile(target);if(existing.sha256!==item.sha256||existing.bytes!==item.bytes)fail("STORAGE_COPY_CONFLICT");continue}catch(error){if(error.code!=="ENOENT")throw error}const temporary=target+".copy-part";try{await digestFile(temporary);await unlink(temporary)}catch(error){if(error.code!=="ENOENT")throw error}const input=await open(original,constants.O_RDONLY|constants.O_NOFOLLOW),output=await open(temporary,"wx",384);try{for await(const bytes of createReadStream(original,{fd:input.fd,autoClose:false}))await output.writeFile(bytes);await output.sync()}finally{await input.close();await output.close()}const copied=await digestFile(temporary),before=await digestFile(original);if(copied.sha256!==item.sha256||before.sha256!==item.sha256||copied.bytes!==item.bytes)fail("STORAGE_COPY_INVALID");await chmod(temporary,before.mode);await atomicMove(temporary,target,true)}return{files,total}}var id=z2.uuid();var digest=z2.string().regex(/^[a-f0-9]{64}$/);var planSchema=StoragePlanSchema;var DesktopStorageRequestSchema=z2.strictObject({operation:z2.literal("storage"),call:z2.discriminatedUnion("action",[z2.strictObject({action:z2.literal("status")}),z2.strictObject({action:z2.literal("prepare"),mode:z2.enum(["BACKUP","MIGRATE"]),destination:z2.string().min(1).max(4096)}),z2.strictObject({action:z2.enum(["execute","recover","abandon"]),id,fingerprint:digest})])});var viewSchema=planSchema.omit({source:true,destination:true,runtimeRevision:true,installationRevision:true});var DesktopStorageReplySchema=viewSchema.nullable();function present(plan){if(!plan)return null;const{source,destination,runtimeRevision,installationRevision,...view}=plan;void source;void destination;void runtimeRevision;void installationRevision;return DesktopStorageReplySchema.parse(view)}async function runDesktopStorageRequest(home,raw){const{call}=DesktopStorageRequestSchema.parse(raw),manager=await LocalInstallationManager.open(home);const root=await directory(join3(home,"storage-plans"));const pointer=await optional(join3(root,"current.json"));const prior=pointer?await readStoragePlan(root,id.parse(pointer)):null;if(call.action==="status")return present(prior);let config=await manager.configuration(),installation=(await manager.ledger.current()).value;let plan;const save=async(phase,extra={})=>{plan=await saveStoragePlan(root,plan,phase,extra)};if(call.action==="prepare"){if(!installation.active||installation.transition)fail("RECOVERY_REQUIRED");if(prior&&!["COMPLETE","CANCELLED"].includes(prior.phase))fail("RECOVERY_REQUIRED");const selected=resolve(call.destination),info=await lstat2(selected);if(!info.isDirectory()||info.isSymbolicLink()||process.platform!=="win32"&&info.uid!==process.getuid?.())fail("STORAGE_LOCATION_INVALID");const destination=await realpath(selected);if(destination===config.stateDirectory||destination.startsWith(config.stateDirectory+sep3))fail("STORAGE_LOCATION_INVALID");const inventory=await(await ownerClient(config.stateDirectory)).inventory();const body={id:randomUUID(),mode:call.mode,source:config.stateDirectory,destination:join3(destination,"NVS-"+randomUUID().replaceAll("-","").slice(0,16)),installationRevision:installation.revision,runtimeRevision:inventory.runtimeRevision,expiresAt:new Date(Date.now()+18e5).toISOString()};if(call.mode==="MIGRATE"&&process.platform!=="win32"&&Buffer.byteLength(join3(body.destination,"runtime.sock"))>100)fail("SOCKET_PATH_TOO_LONG");const frozen={...body,installationFingerprint:await storageInstallationIdentity(installation.active,body.source,body.destination)};plan=planSchema.parse({...frozen,fingerprint:sha256(canonicalLocalJson(frozen)),phase:"PREPARED"});await save("PREPARED");await write(join3(root,"current.json"),canonicalLocalJson(plan.id));return present(plan)}plan=await readStoragePlan(root,call.id);if(!plan||plan.fingerprint!==call.fingerprint)fail("PLAN_CHANGED");if(["COMPLETE","CANCELLED"].includes(plan.phase))return present(plan);if(call.action==="abandon"){await save("CANCELLED");return present(plan)}if(!installation.active||installation.transition)fail("RECOVERY_REQUIRED");if(await storageInstallationIdentity(installation.active,plan.source,plan.destination)!==plan.installationFingerprint)fail("PLAN_CHANGED");if(config.stateDirectory!==plan.source&&!(plan.mode==="MIGRATE"&&config.stateDirectory===plan.destination))fail("PLAN_CHANGED");if(plan.phase==="PREPARED"){if(Date.parse(plan.expiresAt)<=Date.now()||installation.revision!==plan.installationRevision)fail("PLAN_CHANGED");const client=await ownerClient(plan.source),inventory=await client.inventory();if(inventory.runtimeRevision!==plan.runtimeRevision)fail("REVISION_CONFLICT");await save("DRAINING");await manager.stop()}if(plan.phase==="DRAINING"){await waitStopped(plan.source);if(!await socketAbsent(plan.source))fail("RECOVERY_REQUIRED");await save("COPYING")}if(plan.phase==="COPYING"){if(!await socketAbsent(plan.source))fail("RECOVERY_REQUIRED");const copied=await copyStorage(plan.source,plan.destination);await write(join3(plan.destination,"backup-manifest.json"),canonicalLocalJson({protocol:"NVS_STORAGE_COPY_V1",planId:plan.id,...copied}));await save("COPIED",{bytes:copied.total})}if(plan.phase==="COPIED"){if(plan.mode==="MIGRATE"){if(installation.active.toolsConfigPath){const tools=LocalToolSelectionSchema.parse(JSON.parse((await read(installation.active.toolsConfigPath,32768)).toString()));if(tools.mode==="MANAGED"){for(const name of["ffmpeg","ffprobe"]){if(tools[name].path.startsWith(plan.source+sep3))tools[name].path=plan.destination+tools[name].path.slice(plan.source.length);else if(!tools[name].path.startsWith(plan.destination+sep3)||installation.active.toolsConfigPath!==join3(root,plan.id+"-tools.json"))fail("PLAN_CHANGED")}const toolsConfigPath=join3(root,plan.id+"-tools.json");await write(toolsConfigPath,canonicalLocalJson(tools));if(installation.active.toolsConfigPath!==toolsConfigPath)await manager.ledger.commit(installation,{active:{...installation.active,toolsConfigPath},transition:null})}}await manager.configure({...config,stateDirectory:plan.destination});await disableDesktopAutomation(home)}await save("VERIFYING")}if(plan.phase==="VERIFYING"){await manager.start();config=await manager.configuration();const inventory=await(await ownerClient(config.stateDirectory)).inventory();installation=(await manager.ledger.current()).value;if(canonicalLocalJson(inventory.descriptor)!==canonicalLocalJson(installation.active.descriptor))fail("STORAGE_COPY_INVALID");await save("COMPLETE")}return present(plan)}import{z as z3}from"zod";var DesktopOfflineRequestSchema=z3.strictObject({operation:z3.literal("offline"),call:LocalOfflineCallSchema});var DesktopOfflineReplySchema=LocalOfflinePageSchema;async function runDesktopOfflineRequest(home,raw){const{call}=DesktopOfflineRequestSchema.parse(raw),manager=await LocalInstallationManager.open(home),c=await manager.configuration();if(!(await manager.status()).running){const policy=await desktopAutomation(home),installation=await desktopInstallationIdentity(manager);if(!policy?.enabled||policy.installationFingerprint!==installation?.fingerprint||!await socketAbsent(c.stateDirectory))fail("RUNTIME_STATUS_REQUIRED");await manager.start()}const client=await ownerClient(c.stateDirectory);return LocalOfflinePageSchema.parse(await client.call({operation:"offline.workspace",input:call}))}import{z as z4}from"zod";import{join as join4}from"node:path";import{unlink as unlink2}from"node:fs/promises";var sha=z4.string().regex(/^[a-f0-9]{64}$/);var historyItem=z4.strictObject({id:z4.uuid(),projectId:z4.uuid(),productionId:z4.uuid(),kind:z4.enum(["IMAGE","VIDEO","ROUGH_CUT","PROGRAMMATIC"]),mediaFileId:z4.uuid().optional()});var stateSchema=z4.strictObject({grantFingerprint:sha.nullable(),pendingGrant:sha.nullable(),history:z4.array(historyItem).max(200)});var DesktopAgentRequestSchema=z4.strictObject({operation:z4.literal("agent"),scope:DesktopDeviceScopeSchema,call:z4.discriminatedUnion("action",[z4.strictObject({action:z4.literal("discover"),binary:z4.string().min(1).max(4096).optional()}),z4.strictObject({action:z4.literal("probe")}),z4.strictObject({action:z4.literal("grant"),grant:LocalAgentGrantSchema,approval:sha}),z4.strictObject({action:z4.literal("revoke")}),z4.strictObject({action:z4.literal("prepare"),snapshot:LocalAgentSnapshotSchema}),z4.strictObject({action:z4.literal("stage"),id:z4.uuid(),mediaFileId:z4.uuid().optional()}),z4.strictObject({action:z4.literal("start"),id:z4.uuid(),expectedRevision:z4.int().positive(),approval:sha}),z4.strictObject({action:z4.literal("inspect"),id:z4.uuid()})])});var DesktopAgentReplySchema=z4.strictObject({probe:LocalAgentProbeSchema.optional(),discovery:LocalAgentDiscoverySchema.optional(),review:LocalAgentReviewViewSchema.optional(),history:z4.array(historyItem.omit({mediaFileId:true}).extend({pendingMedia:z4.boolean()})).max(200),pendingGrant:z4.boolean()});async function runDesktopAgentRequest(home,raw){const{scope,call}=DesktopAgentRequestSchema.parse(raw),root=await directory(join4(home,"agent-owner",sha256(canonicalLocalJson(scope)))),path=join4(root,"current.json");let state=stateSchema.parse(await optional(path)??{grantFingerprint:null,pendingGrant:null,history:[]});const manager=await LocalInstallationManager.open(home),client=await ownerClient((await manager.configuration()).stateDirectory);const save=async value=>{state=stateSchema.parse({...state,...value});await write(path,canonicalLocalJson(state))};const result=fields=>DesktopAgentReplySchema.parse({...fields,history:state.history.map(({mediaFileId,...r})=>{return{...r,pendingMedia:!!mediaFileId}}),pendingGrant:!!state.pendingGrant});if(call.action==="discover"){const discovery=await client.discoverAgent(call.binary);const fp=discovery.configured?sha256(canonicalLocalJson(discovery.configured)):null;if(state.pendingGrant&&state.pendingGrant===fp)await save({grantFingerprint:fp,pendingGrant:null});return result({discovery:{...discovery,configured:fp===state.grantFingerprint?discovery.configured:null}})}if(call.action==="probe"){const probe=await client.probeAgent();if(state.pendingGrant&&probe.grantFingerprint===state.pendingGrant)await save({grantFingerprint:state.pendingGrant,pendingGrant:null});return result({probe:probe.grantFingerprint===state.grantFingerprint?probe:{...probe,available:false,configured:false,reason:"GRANT_REQUIRED",grantFingerprint:null}})}if(call.action==="grant"){if(state.pendingGrant)fail("AGENT_OUTCOME_UNKNOWN");if(call.grant.projects.some(p=>p.tenantId!==scope.tenantId)||sha256(canonicalLocalJson(call.grant))!==call.approval)fail("AGENT_APPROVAL_REQUIRED");await save({pendingGrant:call.approval});let probe;try{probe=await client.grantAgent(call.grant,call.approval)}catch(e){if(e instanceof NativeStudioSdkError&&["NO_WRITE","REJECTED"].includes(e.outcome))await save({pendingGrant:null});throw e}await save({pendingGrant:null,grantFingerprint:call.approval});return result({probe})}if(call.action==="revoke"){const probe=await client.probeAgent();if(!state.grantFingerprint||probe.grantFingerprint!==state.grantFingerprint)fail("AGENT_APPROVAL_REQUIRED");const revoked=await client.revokeAgent(state.grantFingerprint);await save({grantFingerprint:null,pendingGrant:null});return result({probe:revoked})}if(call.action==="prepare"){if(state.history.length>=200)fail("QUERY_LIMIT");if(state.pendingGrant||!state.grantFingerprint||call.snapshot.basis.scope.tenantId!==scope.tenantId)fail("AGENT_APPROVAL_REQUIRED");const review=await client.prepareAgentReview(call.snapshot);if(review.plan.grantFingerprint!==state.grantFingerprint)fail("AGENT_APPROVAL_REQUIRED");const s2=review.plan.snapshot.basis.scope;await save({history:[{id:review.plan.id,projectId:s2.projectId,productionId:s2.productionId,kind:review.plan.snapshot.basis.target.kind},...state.history]});return result({review})}const entry=state.history.find(h=>h.id===call.id);if(!entry)fail("AGENT_APPROVAL_REQUIRED");const original=await client.inspectAgentReview(call.id),s=original.plan.snapshot.basis.scope;if(s.tenantId!==scope.tenantId||s.projectId!==entry.projectId||s.productionId!==entry.productionId)fail("AGENT_APPROVAL_REQUIRED");const staged=!!(original.imageReceipt||original.evidenceReceipt);if(staged&&entry.mediaFileId){const file=join4(home,"agent-import",entry.mediaFileId+".bin");try{const bytes=await read(file,134217728);if(sha256(bytes)!==original.plan.snapshot.media.checksumSha256)fail("AGENT_IMAGE_INVALID");await unlink2(file)}catch(e){if(e.code!=="ENOENT")throw e}await save({history:state.history.map(h=>{if(h.id!==call.id)return h;const{mediaFileId,...item}=h;void mediaFileId;return item})})}if(call.action==="inspect"||call.action==="stage"&&staged)return result({review:original});if(call.action==="stage"){const mediaFileId=call.mediaFileId??entry.mediaFileId;if(!mediaFileId)fail("AGENT_IMAGE_REQUIRED");await save({history:state.history.map(h=>h.id===call.id?{...h,mediaFileId}:h)});const file=join4(home,"agent-import",mediaFileId+".bin"),bytes=await read(file,134217728);const review=await client.stageAgentImage(call.id,bytes);await unlink2(file);await save({history:state.history.map(h=>{if(h.id!==call.id)return h;const{mediaFileId:_id,...rest}=h;void _id;return rest})});return result({review})}if(state.pendingGrant||original.plan.grantFingerprint!==state.grantFingerprint)fail("AGENT_APPROVAL_REQUIRED");return result({review:await client.startAgentReview(call.id,call.expectedRevision,call.approval)})}import{z as z5}from"zod";var digest2=z5.string().regex(/^[a-f0-9]{64}$/);var DesktopBootstrapRequestSchema=z5.strictObject({operation:z5.literal("bootstrap"),call:z5.discriminatedUnion("action",[z5.strictObject({action:z5.literal("prepare")}),z5.strictObject({action:z5.literal("apply"),id:z5.uuid(),fingerprint:digest2})])});var DesktopBootstrapReplySchema=z5.strictObject({id:z5.uuid(),fingerprint:digest2,version:z5.string().min(1).max(80),host:z5.string().min(1).max(512),bytes:z5.int().positive(),expiresAt:z5.iso.datetime(),installed:z5.boolean()});import{z as z6}from"zod";var DesktopWorkspaceRequestSchema=z6.strictObject({operation:z6.literal("workspace"),call:z6.discriminatedUnion("action",[z6.strictObject({action:z6.enum(["inspect","clean","diagnostics"])}),z6.strictObject({action:z6.literal("configure"),policy:LocalResourcePolicySchema,expectedRevision:z6.int().nonnegative()}),z6.strictObject({action:z6.literal("activity"),idleSeconds:z6.int().min(0).max(86400),observedAt:z6.iso.datetime()})])});var DesktopWorkspaceReplySchema=z6.union([LocalWorkspaceInspectionSchema,LocalDiagnosticsSchema]);async function runDesktopWorkspaceRequest(home,raw){const request=DesktopWorkspaceRequestSchema.parse(raw);const manager=await LocalInstallationManager.open(home);const config=await manager.configuration();const client=await ownerClient(config.stateDirectory);const input=request.call;switch(input.action){case"inspect":return client.workspace.inspect();case"clean":return client.workspace.clean();case"diagnostics":return client.workspace.diagnostics();case"configure":return client.workspace.configure(input.policy,input.expectedRevision);case"activity":return client.workspace.observeActivity(input.idleSeconds,input.observedAt)}}var version=LocalRuntimeDescriptorSchema.shape.version;var fingerprint=z7.string().regex(/^[a-f0-9]{64}$/);var DesktopRuntimeChannelSchema=z7.strictObject({protocol:z7.literal("NVS_DESKTOP_RUNTIME_CHANNEL_V1"),catalogueUrl:z7.string().url().max(4096),publicKey:z7.string().min(32).max(16384)});var DesktopOwnerRequestSchema=z7.discriminatedUnion("operation",[DesktopLibraryRequestSchema,DesktopLibraryImportRequestSchema,DesktopLibraryPrepareRequestSchema,DesktopDeviceRequestSchema,DesktopWorkspaceRequestSchema,DesktopStorageRequestSchema,DesktopOfflineRequestSchema,DesktopAgentRequestSchema,DesktopBootstrapRequestSchema,z7.strictObject({operation:z7.literal("speech-prepare"),input:CpuSpeechPrepareInputSchema}),z7.strictObject({operation:z7.enum(["status","start","stop","check","configuration","recovery"])}),z7.strictObject({operation:z7.enum(["prepare","reject"]),version}),z7.strictObject({operation:z7.literal("tools-prepare"),version,choice:z7.discriminatedUnion("mode",[z7.strictObject({mode:z7.literal("MANAGED")}),z7.strictObject({mode:z7.literal("INSTALLED"),ffmpeg:z7.string().min(1).max(4096),ffprobe:z7.string().min(1).max(4096),compositionBrowser:z7.string().min(1).max(4096).optional()})])}),z7.strictObject({operation:z7.literal("configure"),channelFingerprint:fingerprint}),z7.strictObject({operation:z7.enum(["apply","recover"]),planId:z7.uuid(),fingerprint})]);var DesktopRuntimeStatusSchema=z7.strictObject({protocol:z7.literal("NVS_DESKTOP_RUNTIME_STATUS_V1"),state:z7.enum(["RUNNING","STOPPED","UNAVAILABLE","INSTALL_REQUIRED"]),activeVersion:version.nullable(),phase:z7.string().regex(/^[A-Z_]{1,64}$/),toolMode:z7.enum(["MANAGED","INSTALLED"]).nullable().optional(),speech:z7.strictObject({voiceIds:CpuSpeechPrepareInputSchema.shape.voiceIds}).optional()});var DesktopUpdateCheckSchema=z7.strictObject({protocol:z7.literal("NVS_DESKTOP_RUNTIME_UPDATES_V1"),activeVersion:version.nullable(),versions:z7.array(z7.strictObject({version,rejected:z7.boolean()})).max(128),notifications:z7.boolean()});var DesktopOwnerPlanSchema=z7.strictObject({protocol:z7.literal("NVS_DESKTOP_OWNER_PLAN_V1"),plan:z7.strictObject({kind:z7.enum(["APPLY","RECOVER"]),toolMode:z7.enum(["MANAGED","INSTALLED"]).optional(),planId:z7.uuid(),fingerprint,version,previousVersion:version.nullable(),expiresAt:z7.iso.datetime(),phase:z7.string().regex(/^[A-Z_]{1,64}$/)}).nullable()});var DesktopChannelInfoSchema=z7.strictObject({protocol:z7.literal("NVS_DESKTOP_CHANNEL_INFO_V1"),configured:z7.boolean(),source:z7.enum(["EXISTING","BUNDLED","UNAVAILABLE"]),host:z7.string().max(512).nullable(),channelFingerprint:fingerprint.nullable()});var desktopOwnerResponses={library:DesktopLibraryReplySchema,"library-import":DesktopLibraryReplySchema,"library-import-prepare":DesktopLibraryImportRequestSchema,device:DesktopDeviceReplySchema,workspace:DesktopWorkspaceReplySchema,storage:DesktopStorageReplySchema,offline:DesktopOfflineReplySchema,agent:DesktopAgentReplySchema,bootstrap:DesktopBootstrapReplySchema,status:DesktopRuntimeStatusSchema,start:DesktopRuntimeStatusSchema,stop:DesktopRuntimeStatusSchema,configure:DesktopRuntimeStatusSchema,apply:DesktopRuntimeStatusSchema,recover:DesktopRuntimeStatusSchema,reject:DesktopRuntimeStatusSchema,check:DesktopUpdateCheckSchema,configuration:DesktopChannelInfoSchema,prepare:DesktopOwnerPlanSchema,"tools-prepare":DesktopOwnerPlanSchema,"speech-prepare":DesktopOwnerPlanSchema,recovery:DesktopOwnerPlanSchema};export{runDesktopStorageRequest,runDesktopOfflineRequest,runDesktopAgentRequest,DesktopBootstrapRequestSchema,DesktopBootstrapReplySchema,runDesktopWorkspaceRequest,DesktopRuntimeChannelSchema,DesktopOwnerRequestSchema,DesktopRuntimeStatusSchema,DesktopChannelInfoSchema,desktopOwnerResponses};
@@ -0,0 +1 @@
1
+ import{z}from"zod";var CapabilityVersionSchema=z.string().regex(/^[a-f0-9]{64}$/);var CapabilityVersionMismatchSchema=z.strictObject({kind:z.enum(["CAPABILITY_DEFINITION","MEDIA_PROFILE","RENDERER","VALIDATION_PROFILE","PROCESSOR_PROFILE","LOCAL_LIBRARY_PROFILE"]),expectedVersion:CapabilityVersionSchema,actualVersion:CapabilityVersionSchema,recovery:z.enum(["REDISCOVER_CAPABILITY","CHECK_DEVICE_RELEASE"])});var InterfaceSemanticStatusSchema=z.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=z.enum(["AVAILABLE","UNAVAILABLE"]);var NextActionSchema=z.object({capability:z.string().min(1).max(120),targetType:z.string().min(1).max(80),targetId:z.string().min(1).max(2048),availability:ActionAvailabilitySchema,reason:z.string().min(1).max(1e3).nullable()});var ContinuationSchema=z.string().min(1).max(8192);var QueryLimitSchema=z.int().min(1).max(100).default(20);var QueryPageInfoSchema=z.object({hasMore:z.boolean(),next:ContinuationSchema.nullable()});var WorkSummarySchema=z.object({total:z.int().nonnegative(),pending:z.int().nonnegative(),ready:z.int().nonnegative(),running:z.int().nonnegative(),waiting:z.int().nonnegative(),succeeded:z.int().nonnegative(),failed:z.int().nonnegative(),cancelled:z.int().nonnegative(),superseded:z.int().nonnegative(),attempts:z.int().nonnegative()});import{z as z2}from"zod";var TenantIdSchema=z2.uuid().brand();var PrincipalIdSchema=z2.uuid().brand();var ProjectIdSchema=z2.uuid().brand();var ProductionIdSchema=z2.uuid().brand();var ArtifactIdSchema=z2.uuid().brand();var ArtifactRepresentationIdSchema=z2.uuid().brand();var ArtifactRelationIdSchema=z2.uuid().brand();var BriefIdSchema=z2.uuid().brand();var BriefVersionIdSchema=z2.uuid().brand();var StoryIdSchema=z2.uuid().brand();var StoryVersionIdSchema=z2.uuid().brand();var SceneShotPlanIdSchema=z2.uuid().brand();var SceneShotPlanVersionIdSchema=z2.uuid().brand();var SceneIdSchema=z2.uuid().brand();var ShotIdSchema=z2.uuid().brand();var ContinuityEdgeIdSchema=z2.uuid().brand();var RuntimeJobIdSchema=z2.uuid().brand();var OperationIdSchema=z2.string().regex(/^op_[A-Za-z0-9_-]+$/).max(2048).brand();var RuntimeJobAttemptIdSchema=z2.uuid().brand();var OutboxEventIdSchema=z2.uuid().brand();import{z as z3}from"zod";var uuid="[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}";var page=new RegExp(`^/(?:projects(?:/${uuid})?|artifacts|productions/${uuid}(?:/(?:artifacts|delivery|history))?|settings/voices(?:/${uuid}(?:/versions/[1-9][0-9]*)?)?)$`);var HumanLinkScopeSchema=z3.strictObject({tenantId:z3.uuid(),projectId:z3.uuid().optional(),productionId:z3.uuid().optional(),artifactId:z3.uuid().optional(),representationId:z3.uuid().optional(),delivery:z3.boolean().optional(),voices:z3.boolean().optional(),voiceProfileId:z3.uuid().optional(),voiceProfileVersion:z3.int().positive().optional()}).refine(s=>!!s.artifactId===!!s.representationId&&(!s.delivery||!!s.productionId)&&(s.voiceProfileVersion===void 0||!!s.voiceProfileId));var HumanLinkSchema=z3.strictObject({rel:z3.enum(["workspace","project","production","artifact","delivery","voice_profile"]),href:z3.url().max(2048)}).refine(({rel,href})=>{try{const u=new URL(href),q=u.searchParams,parts=u.pathname.split("/"),pathId=parts[1]==="settings"?parts[3]:parts[2];return u.href===href&&!u.username&&!u.password&&!href.includes("#")&&(u.protocol==="https:"||u.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(u.hostname))&&page.test(u.pathname)&&(!pathId||z3.uuid().safeParse(pathId).success)&&(parts[4]!=="versions"||z3.int().positive().safeParse(Number(parts[5])).success)&&new Set(q.keys()).size===q.size&&[...q].every(([key,value])=>["workspace","artifact","representation"].includes(key)&&z3.uuid().safeParse(value).success)&&q.has("workspace")&&q.has("artifact")===q.has("representation")&&(rel==="artifact"?u.pathname.endsWith("/artifacts")&&q.has("artifact"):!q.has("artifact")&&(rel==="workspace"?u.pathname==="/projects":rel==="project"?new RegExp(`^/projects/${uuid}$`).test(u.pathname):rel==="voice_profile"?u.pathname.startsWith("/settings/voices"):rel==="production"?new RegExp(`^/productions/${uuid}$`).test(u.pathname):u.pathname.endsWith("/delivery")))}catch{return false}});var HumanLinksSchema=z3.discriminatedUnion("status",[z3.strictObject({status:z3.literal("AVAILABLE"),items:z3.array(HumanLinkSchema).min(1).max(4)}),z3.strictObject({status:z3.enum(["UNCONFIGURED","UNAVAILABLE"]),items:z3.array(HumanLinkSchema).max(0)})]);import{z as z4}from"zod";var DeliveryOutputProfileSchema=z4.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 z7}from"zod";import{z as z6}from"zod";import{z as z5}from"zod";var ProductionLifecycleSchema=z5.enum(["ACTIVE","COMPLETED","FAILED","CANCELLED"]);var ProductionPhaseSchema=z5.enum(["INTAKE","PLANNING","PREPARING_GENERATION","GENERATING","SHOT_REVIEW","ASSEMBLING","ROUGH_CUT_REVIEW","FINAL_READY","FINAL_RENDERING","DELIVERY_VALIDATION"]);var ProductionConditionSchema=z5.enum(["RUNNABLE","RUNNING","WAITING_PROVIDER","WAITING_HUMAN","BLOCKED","RETRYING"]);var CreateProductionInputSchema=z5.object({tenantId:TenantIdSchema,projectId:ProjectIdSchema,principalId:PrincipalIdSchema});var ProductionStateSchema=z5.object({lifecycle:ProductionLifecycleSchema,phase:ProductionPhaseSchema,condition:ProductionConditionSchema,revision:z5.int().positive(),blockingReason:z5.string().min(1).nullable(),waitingReason:z5.string().min(1).nullable()});var ProductionSchema=z5.object({humanLinks:HumanLinksSchema.optional(),id:ProductionIdSchema,tenantId:TenantIdSchema,projectId:ProjectIdSchema,state:ProductionStateSchema,activeBriefVersion:z5.int().positive().nullable().default(null),activeStoryVersion:z5.int().positive().nullable().default(null),activeSceneShotPlanVersion:z5.int().positive().nullable().default(null),createdByPrincipalId:PrincipalIdSchema,createdAt:z5.iso.datetime({offset:true}),updatedAt:z5.iso.datetime({offset:true})});var ProjectLifecycleSchema=z6.enum(["ACTIVE","ARCHIVED"]);var CreateProjectInputSchema=z6.object({tenantId:TenantIdSchema,principalId:PrincipalIdSchema,idempotencyKey:z6.string().trim().min(1).max(200),name:z6.string().trim().min(1).max(200)});var CreateProjectRequestSchema=CreateProjectInputSchema.omit({principalId:true}).strict();var ProjectSchema=z6.object({id:ProjectIdSchema,tenantId:TenantIdSchema,name:z6.string().min(1),lifecycle:ProjectLifecycleSchema,defaultActiveProductionId:ProductionIdSchema.nullable(),revision:z6.int().positive(),createdByPrincipalId:PrincipalIdSchema,createdAt:z6.iso.datetime({offset:true}),updatedAt:z6.iso.datetime({offset:true})});var CreatedProjectResultSchema=z6.object({project:ProjectSchema,production:ProductionSchema});var ProjectLibraryQuerySchema=z7.strictObject({tenantId:TenantIdSchema,limit:QueryLimitSchema,next:ContinuationSchema.optional()});var ProjectLibraryScopeSchema=z7.strictObject({tenantId:TenantIdSchema,projectId:ProjectIdSchema});var ProjectLibraryPageSchema=z7.strictObject({items:z7.array(ProjectSchema).max(100),page:QueryPageInfoSchema});var ProjectWorkspaceSchema=z7.strictObject({project:ProjectSchema,productions:z7.array(ProductionSchema).max(100),possiblyTruncated:z7.boolean()});var SourceLibraryQuerySchema=ProjectLibraryQuerySchema.extend({projectId:ProjectIdSchema.optional()});var SourceLibraryItemSchema=z7.strictObject({artifactId:z7.uuid(),representationId:z7.uuid(),projectId:ProjectIdSchema,kind:z7.enum(["REFERENCE_IMAGE","REFERENCE_VIDEO","PRODUCT_INFORMATION"]),originalName:z7.string().max(255),checksumSha256:z7.string().regex(/^[0-9a-f]{64}$/),contentType:z7.enum(["image/png","image/jpeg","image/webp","text/plain","application/json","video/mp4"]),byteSize:z7.int().positive().max(8388608),width:z7.int().positive().nullable(),height:z7.int().positive().nullable(),createdAt:z7.iso.datetime({offset:true})});var SourceLibraryPageSchema=z7.strictObject({items:z7.array(SourceLibraryItemSchema).max(100),page:QueryPageInfoSchema});var SourceLibraryMediaSchema=ProjectLibraryScopeSchema.extend({artifactId:z7.uuid()});var StudioInputContentSchema=z7.strictObject({schemaVersion:z7.literal(1),productionId:z7.uuid(),projectTitle:z7.string().trim().min(1).max(200),name:z7.string().trim().max(300),intent:z7.string().trim().min(1).max(2e3),aspectRatio:z7.enum(["16:9","9:16"]),targetDurationSeconds:z7.int().min(30).max(60),outputProfile:DeliveryOutputProfileSchema,sourceArtifactIds:z7.array(z7.uuid()).max(12)});import{z as z8}from"zod";var HumanEmailSchema=z8.string().trim().max(254).toLowerCase().pipe(z8.email()).refine(v=>/^[\x21-\x7e]+$/.test(v),"Use an ASCII email address");var HumanPasswordSchema=z8.string().max(512).superRefine((v,c)=>{const points=[...v];const control=points.some(c2=>c2.codePointAt(0)<32||c2.codePointAt(0)===127);if(points.length<15||points.length>128||control)c.addIssue({code:"custom",message:"Password must contain 15\u2013128 characters"})});var HumanCodePurposeSchema=z8.enum(["REGISTER","RESET_PASSWORD","LINK_EMAIL"]);var HumanCodeRequestSchema=z8.strictObject({email:HumanEmailSchema,purpose:HumanCodePurposeSchema});var HumanCodeRequestedSchema=z8.strictObject({accepted:z8.literal(true),challengeId:z8.uuid(),retryAfterSeconds:z8.literal(60),expiresInSeconds:z8.literal(600)});var proof={challengeId:z8.uuid(),email:HumanEmailSchema,code:z8.string().regex(/^\d{6}$/),password:HumanPasswordSchema};var HumanRegisterSchema=z8.strictObject({...proof,displayName:z8.string().trim().min(1).max(80)});var HumanResetSchema=z8.strictObject(proof);var HumanLoginSchema=z8.strictObject({email:HumanEmailSchema,password:z8.string().max(512),rememberMe:z8.boolean().optional()});var HumanTenantSchema=z8.strictObject({id:z8.uuid(),displayName:z8.string().max(200)});var HumanAccountSchema=z8.strictObject({principalId:z8.uuid(),displayName:z8.string().max(200),email:HumanEmailSchema.nullable(),tenants:z8.array(HumanTenantSchema).max(100)});var HumanDesktopSessionSchema=z8.strictObject({tenantId:z8.uuid(),scopeKey:z8.string().regex(/^[a-f0-9]{64}$/),expiresAt:z8.int().positive(),sessionExpiresAt:z8.int().positive().optional(),rememberMe:z8.boolean(),account:HumanAccountSchema.omit({tenants:true})}).refine(({rememberMe,expiresAt,sessionExpiresAt})=>sessionExpiresAt===void 0||rememberMe&&sessionExpiresAt>=expiresAt,"Desktop persistence requires consent and the session deadline");var ShortHumanSessionSchema=z8.strictObject({accessToken:z8.string().regex(/^nvsh_[A-Za-z0-9_-]{43}$/),expiresAt:z8.iso.datetime(),account:HumanAccountSchema});var HumanRefreshTokenSchema=z8.string().regex(/^nvshr_[A-Za-z0-9_-]{43}$/);var HumanRefreshSchema=z8.strictObject({refreshToken:HumanRefreshTokenSchema});var HumanSessionSchema=ShortHumanSessionSchema.extend({refreshToken:HumanRefreshTokenSchema.optional(),sessionId:z8.uuid().optional(),sessionExpiresAt:z8.iso.datetime().optional()}).refine(session=>{const{refreshToken,sessionId,sessionExpiresAt,expiresAt}=session;if(!refreshToken)return sessionId===void 0&&sessionExpiresAt===void 0;return!!sessionId&&!!sessionExpiresAt&&Date.parse(expiresAt)<=Date.parse(sessionExpiresAt)},"Persistent session requires its exact identity and absolute expiry");var HumanIdentityAvailabilitySchema=z8.strictObject({passwordLogin:z8.boolean(),emailVerification:z8.boolean()});var HumanIdentityFailureSchema=z8.strictObject({code:z8.enum(["INVALID_INPUT","INVALID_CREDENTIALS","INVALID_CODE","RATE_LIMITED","MAIL_UNAVAILABLE","UNAVAILABLE","UNAUTHENTICATED","CONFLICT"])});var CliAccountRedirectSchema=z8.string().max(256).refine(value=>{try{const url=new URL(value);return url.protocol==="http:"&&url.hostname==="127.0.0.1"&&Number(url.port)>0&&!url.username&&!url.password&&!url.search&&!url.hash&&/^\/account-callback\/[a-f0-9-]{36}$/.test(url.pathname)&&url.href===value}catch{return false}},"Owned loopback account callback required");var proofKey=z8.string().regex(/^[A-Za-z0-9_-]{43}$/);var CliAccountRequestIdSchema=z8.uuid();var CliAccountStartSchema=z8.strictObject({redirectUri:CliAccountRedirectSchema,state:proofKey,codeChallenge:proofKey});var CliAccountStartedSchema=z8.strictObject({requestId:z8.uuid(),expiresAt:z8.iso.datetime()});var CliAccountPreviewSchema=CliAccountStartedSchema.extend({redirectUri:CliAccountRedirectSchema});var CliAccountDecisionSchema=z8.strictObject({requestId:z8.uuid(),approved:z8.boolean(),expectedPrincipalId:z8.uuid()});var CliAccountExchangeSchema=z8.strictObject({requestId:z8.uuid(),code:proofKey,codeVerifier:proofKey,redirectUri:CliAccountRedirectSchema});var CliAccountSessionSchema=ShortHumanSessionSchema.extend({credentialPurpose:z8.literal("CLI_ACCOUNT")});var CliAccountIdentitySchema=z8.strictObject({credentialPurpose:z8.literal("CLI_ACCOUNT"),account:HumanAccountSchema});export{TenantIdSchema,PrincipalIdSchema,ProjectIdSchema,ProductionIdSchema,ArtifactIdSchema,ArtifactRepresentationIdSchema,ArtifactRelationIdSchema,BriefIdSchema,BriefVersionIdSchema,StoryIdSchema,StoryVersionIdSchema,SceneShotPlanIdSchema,SceneShotPlanVersionIdSchema,SceneIdSchema,ShotIdSchema,ContinuityEdgeIdSchema,OperationIdSchema,HumanLinksSchema,DeliveryOutputProfileSchema,finalProfileIds,CapabilityVersionSchema,CapabilityVersionMismatchSchema,InterfaceSemanticStatusSchema,NextActionSchema,ContinuationSchema,QueryLimitSchema,QueryPageInfoSchema,WorkSummarySchema,HumanTenantSchema,CliAccountStartSchema,CliAccountStartedSchema,CliAccountExchangeSchema,CliAccountSessionSchema,CliAccountIdentitySchema,ProductionStateSchema,ProductionSchema,CreateProjectRequestSchema,ProjectSchema,CreatedProjectResultSchema,ProjectLibraryQuerySchema,ProjectLibraryScopeSchema,ProjectLibraryPageSchema,ProjectWorkspaceSchema,SourceLibraryQuerySchema,SourceLibraryItemSchema,SourceLibraryPageSchema,SourceLibraryMediaSchema,StudioInputContentSchema};
@@ -0,0 +1 @@
1
+ import{selectedProject}from"./chunk-3RNDOAQI.js";import{profileAuthorization}from"./chunk-3TOXIJ7K.js";import{connectRemoteMcp}from"./chunk-76E5R3OC.js";import{profileHttpOrigin}from"./chunk-7P2NA6TH.js";import{clientHome,loadConnection,readAccount,requireAccount}from"./chunk-27KI24GK.js";import{NativeStudioSdkError}from"./chunk-TT7IA5HB.js";import{z}from"zod";async function resolveCaller(env,explicitProject,workspaceOnly=false){const home=await clientHome(env),account=await readAccount(home);const saved=await loadConnection(env);const assertCurrent=async()=>{const latest=await loadConnection(env),current=await readAccount(home);if(latest?.profile!==saved?.profile||latest?.resource!==saved?.resource||account?.epoch!==current?.epoch||account?.state!==current?.state||account?.principalId!==current?.principalId||account?.workspaceId!==current?.workspaceId||account?.serverOrigin!==current?.serverOrigin)throw new NativeStudioSdkError("FORBIDDEN","BLOCKED","NO_WRITE");if(latest?.exchangeUnresolved)throw new NativeStudioSdkError("OAUTH_OUTCOME_UNKNOWN","BLOCKED","UNKNOWN");if(account&&!saved)requireAccount(current)};if(saved){const auth=await profileAuthorization(saved.profile);if(auth.resource!==saved.resource)throw new NativeStudioSdkError("FORBIDDEN","BLOCKED","NO_WRITE");const projectId=workspaceOnly?void 0:await selectedProject(saved,env,explicitProject);const c=await connectRemoteMcp(saved.resource,auth.authorization,saved.tenantId);try{const caller=await c.studio.call("workspace.caller",{});if(caller.tenantId!==saved.tenantId||account&&(account.principalId!==caller.principalId||account.serverOrigin!==caller.serverOrigin))throw new NativeStudioSdkError("FORBIDDEN","BLOCKED","NO_WRITE");if(projectId){const selected=await c.studio.call("project.get",{projectId});if(selected.project.id!==projectId||selected.project.tenantId!==caller.tenantId)throw new NativeStudioSdkError("FORBIDDEN","BLOCKED","NO_WRITE")}await assertCurrent();return{tenantId:caller.tenantId,principalId:caller.principalId,serverOrigin:caller.serverOrigin,home,projectId,resource:saved.resource,profile:saved.profile,assertCurrent}}finally{await c.close().catch(()=>{})}}if(!account)return null;const human=requireAccount(account);if(!human.workspaceId||!workspaceOnly&&!(explicitProject??human.projectId))throw new NativeStudioSdkError("PROJECT_SELECTION_REQUIRED","BLOCKED","NO_WRITE");return{home,tenantId:human.workspaceId,projectId:workspaceOnly?void 0:z.uuid().parse(explicitProject??human.projectId),principalId:human.principalId,serverOrigin:human.serverOrigin,resource:void 0,profile:void 0,assertCurrent}}async function localCaller(env,explicitProject){const caller=await resolveCaller(env,explicitProject);if(!caller)return null;if(!caller.projectId)throw new NativeStudioSdkError("PROJECT_SELECTION_REQUIRED","BLOCKED","NO_WRITE");return{...caller,projectId:caller.projectId}}function workspaceCaller(env){return resolveCaller(env,void 0,true)}async function callerOriginMatches(origin,caller){if(origin===caller.serverOrigin)return true;if(!caller.resource||!caller.profile)return false;return origin===new URL(caller.resource).origin||origin===await profileHttpOrigin(caller.profile,caller.resource)}export{localCaller,workspaceCaller,callerOriginMatches};
@@ -0,0 +1 @@
1
+ import{readCredential}from"./chunk-QGK6G6YS.js";import{NativeStudioAgentClient}from"./chunk-2S7FI3HF.js";import{defaultConnection}from"./chunk-27KI24GK.js";async function withRemoteClient(options,environment,httpOnly,action,budgets={}){budgets.signal?.throwIfAborted();await defaultConnection(options,environment,true);budgets.signal?.throwIfAborted();if(!options.has("--tenant")||(options.has("--profile")?["--origin","--mcp-url","--token-file","--token-env"].some(k=>options.has(k)):options.has("--origin")===options.has("--mcp-url")))throw Error();const transport=options.get("--transport");if(transport&&!["http","mcp"].includes(transport))throw Error();if(!options.has("--profile")&&transport&&transport!==(options.has("--origin")?"http":"mcp"))throw Error();const profile=options.has("--profile")?await(await import("./oauth-RPME2XYB.js")).profileAuthorization(options.get("--profile"),budgets.signal):null;const authorization=profile?.authorization??await readCredential(options,environment);budgets.signal?.throwIfAborted();const profileHttp=profile&&(transport==="http"||!transport&&httpOnly);if(!profileHttp&&(profile||options.has("--mcp-url"))){if(httpOnly)throw Error();const connection=await(await import("./mcp-BLSK636Q.js")).connectRemoteMcp(profile?.resource??options.get("--mcp-url"),authorization,options.get("--tenant"),budgets);try{budgets.signal?.throwIfAborted();return await action(connection.studio)}finally{await connection.close()}}const baseUrl=profileHttp?await(await import("./http-profile-3VVSWYA5.js")).profileHttpOrigin(options.get("--profile"),profile.resource,budgets.signal):options.get("--origin");budgets.signal?.throwIfAborted();return action(new NativeStudioAgentClient({tenantId:options.get("--tenant"),baseUrl,authorization:()=>authorization,...budgets.maxJsonBytes?{maxJsonBytes:budgets.maxJsonBytes}:{}}))}export{withRemoteClient};
@@ -0,0 +1 @@
1
+ import{runLoginService}from"./chunk-5Y7J2OYL.js";import{ComponentCommandSchema}from"./chunk-ZYXHPTT2.js";import{configureDesktopChannel,desktopRuntimeChannel}from"./chunk-7IVAYDU3.js";import{LocalInstallationManager,socketAbsent}from"./chunk-FFXSXE3G.js";import{DesktopDeviceRecords}from"./chunk-ETK7GYCB.js";import{AgentComponentScopeSchema,AgentComponentStatusSchema,LocalRuntimeStatusSchema}from"./chunk-LDBXGRCQ.js";import{LocalDeviceTransportConfigurationSchema,canonicalLocalJson}from"./chunk-2S7FI3HF.js";import{directory,entries,fail,optional,privateAccess,sha256,write}from"./chunk-DLW42PJ6.js";import{join}from"node:path";import{realpath}from"node:fs/promises";var namespace=scope=>sha256(canonicalLocalJson(scope)).slice(0,24);function deviceScope(scope){return{origin:scope.origin,tenantId:scope.tenantId,principalId:scope.principalId}}async function privateRoot(path){try{await privateAccess(path,"directory");return await realpath(path)}catch(error){if(error.code==="ENOENT")return void 0;throw error}}async function componentHome(parent,scope,initialize){const canonical=initialize?await directory(parent):await privateRoot(parent)??parent;const base=join(canonical,"components"),home=join(base,namespace(scope)),marker=join(home,"component-owner.json");const checked=await privateRoot(base);if(checked&&checked!==base)fail("COMPONENT_OWNER_CONFLICT");const existing=checked&&await privateRoot(home);if(existing&&existing!==home)fail("COMPONENT_OWNER_CONFLICT");let saved=existing?await optional(marker):null;if(!saved&&initialize){if(await directory(base)!==base||await directory(home)!==home)fail("COMPONENT_OWNER_CONFLICT");if((await entries(home)).length)fail("COMPONENT_OWNER_CONFLICT");try{await write(marker,canonicalLocalJson(scope),true)}catch(error){if(error.code!=="EEXIST")throw error}saved=await optional(marker)}if(!saved&&existing&&(await entries(home)).length)fail("COMPONENT_OWNER_CONFLICT");if(saved&&canonicalLocalJson(AgentComponentScopeSchema.parse(saved))!==canonicalLocalJson(scope))fail("COMPONENT_OWNER_CONFLICT");return{home,claimed:saved!==null}}async function initializeComponent(home,scope,channel){const stateDirectory=join(home,"rt");if(process.platform!=="win32"&&Buffer.byteLength(join(stateDirectory,"runtime.sock"))>100)fail("SOCKET_PATH_TOO_LONG");const manager=await LocalInstallationManager.open(home);if(!await optional(join(home,"configuration.json")))await manager.configure({stateDirectory},{ifAbsent:true});await assertComponentConfiguration(manager,scope);if(channel!==void 0){const trusted=desktopRuntimeChannel({...channel,protocol:"NVS_DESKTOP_RUNTIME_CHANNEL_V1"});await configureDesktopChannel(manager,trusted.fingerprint,trusted.value)}return manager}async function componentDevice(home,scope){return(await DesktopDeviceRecords.inspect(home,deviceScope(scope)))?.device??null}async function assertComponentConfiguration(manager,scope){const{root}=manager.ledger;const configuration=await manager.configuration();if(configuration.stateDirectory!==join(root,"rt")||await privateRoot(configuration.stateDirectory)!==configuration.stateDirectory)fail("COMPONENT_CONFIGURATION_CONFLICT");if(configuration.cloudConfigFile){const cloud=configuration.cloudConfigFile;if(cloud!==join(configuration.stateDirectory,"cloud-device.json"))fail("COMPONENT_CONFIGURATION_CONFLICT");const raw=await optional(cloud),device=await componentDevice(root,scope);if(!raw||typeof raw!=="object"||!("tools"in raw)||!device)fail("COMPONENT_CONFIGURATION_CONFLICT");const{tools:_tools,...transport}=raw;void _tools;const actual=LocalDeviceTransportConfigurationSchema.parse(transport);const privateKeyFile=join(root,"devices",sha256(canonicalLocalJson(deviceScope(scope))),"device-key.json");if(actual.endpoint!==scope.origin||actual.tenantId!==scope.tenantId||actual.deviceId!==device.deviceId||actual.deviceRevision!==device.revision||actual.privateKeyFile!==privateKeyFile)fail("COMPONENT_CONFIGURATION_CONFLICT")}return configuration}import{opendir}from"node:fs/promises";import{join as join2}from"node:path";import{z}from"zod";var event=z.strictObject({at:z.iso.datetime(),reasonCode:z.string().regex(/^[A-Z][A-Z0-9_]{0,79}$/)});var receipt=event.extend({command:ComponentCommandSchema,phase:z.enum(["SENDING","COMPLETE","DEGRADED"]),outcome:z.enum(["UNKNOWN","OBSERVED","SUCCESS"]),installationRevision:z.int().nonnegative(),runningVersion:z.string().min(1).max(120).nullable()});var head=z.strictObject({requestId:z.uuid(),lastSuccess:event.nullable(),lastFailure:event.nullable()});var at=()=>new Date().toISOString();var print=command=>sha256(canonicalLocalJson(command));async function withComponentLock(root,work){const locks=join2(root,"control-locks");if(await directory(locks)!==locks)fail("COMPONENT_OWNER_CONFLICT");const file=generation=>join2(locks,String(generation).padStart(12,"0")+".json");let previous=0;for await(const entry of await opendir(locks)){if(/^\d{12}\.json$/.test(entry.name))previous=Math.max(previous,Number(entry.name.slice(0,12)))}if(previous&&!await optional(file(previous)+".released")){const owner=z.strictObject({pid:z.int().positive()}).parse(await optional(file(previous)));try{process.kill(owner.pid,0);fail("COMPONENT_BUSY","NO_WRITE")}catch(error){if(error.code!=="ESRCH")fail("COMPONENT_BUSY","NO_WRITE")}}const current=file(previous+1);try{await write(current,canonicalLocalJson({pid:process.pid}),true)}catch(error){if(error.code==="EEXIST")fail("COMPONENT_BUSY","NO_WRITE");throw error}try{return await work()}finally{await write(current+".released","true",true)}}var ComponentReceipts=class{constructor(root){this.root=root}root;path(requestId){return join2(this.root,"request-"+z.uuid().parse(requestId).toLowerCase()+".json")}async find(requestId){const result=receipt.nullable().parse(await optional(this.path(requestId)));if(result&&result.command.requestId.toLowerCase()!==requestId.toLowerCase())fail("COMPONENT_RECEIPT_INVALID");return result}async original(command){const result=await this.find(command.requestId);if(result&&print(command)!==print(result.command))fail("COMPONENT_REQUEST_CONFLICT","NO_WRITE");return result}async snapshot(){const state=head.nullable().parse(await optional(join2(this.root,"head.json")));const latest=state&&await this.find(state.requestId);if(state&&!latest)fail("COMPONENT_RECEIPT_INVALID");const eventOf=value=>({at:value.at,reasonCode:value.reasonCode});return{latest,lastSuccess:latest?.phase==="COMPLETE"?eventOf(latest):state?.lastSuccess??null,lastFailure:latest?.phase==="DEGRADED"?eventOf(latest):state?.lastFailure??null}}async begin(command,runningVersion){const{latest,lastSuccess,lastFailure}=await this.snapshot();if(latest?.phase==="SENDING")fail("COMPONENT_ORIGINAL_OUTCOME_UNKNOWN");const value=receipt.parse({command,phase:"SENDING",outcome:"UNKNOWN",reasonCode:"COMPONENT_ACTION_SENDING",installationRevision:command.expectedRevision,runningVersion,at:at()});await write(this.path(command.requestId),canonicalLocalJson(value),true);await write(join2(this.root,"head.json"),canonicalLocalJson({requestId:command.requestId,lastSuccess,lastFailure}));return value}async finish(original,result){if(original.phase!=="SENDING")return original;const value=receipt.parse({...original,...result,at:at()});await write(this.path(original.command.requestId),canonicalLocalJson(value));return value}};async function observeLoginService(home){const result=await runLoginService("service-status",home);if(!("registration"in result))fail("COMPONENT_SERVICE_UNCONFIRMED");return result}async function observeComponent(home,scope,manager,receipts){const configuration=manager&&await assertComponentConfiguration(manager,scope);const installation=manager&&await manager.status(),observed=installation&&LocalRuntimeStatusSchema.safeParse(installation.running).data;const version=observed&&installation&&"entryPath"in installation?observed.versions.find(entry=>entry.component==="RUNTIME"&&entry.runningVersion===installation.activeVersion&&entry.installOwner==="MANAGED"&&entry.executablePath===installation.entryPath):void 0;const stopped=!observed&&configuration&&await socketAbsent(configuration.stateDirectory);const service=manager&&installation?.activeVersion?await observeLoginService(home):null;const loginService=!service||!("fingerprint"in service)?"NONE":"supervision"in service&&service.supervision==="EXPLICIT_RECOVERY"?service.registration==="REGISTERED"?service.binding==="CURRENT"?"REGISTERED":"STALE":["ABSENT","INCOMPLETE"].includes(service.registration)?"INCOMPLETE":"UNKNOWN":"UNKNOWN";const{latest,lastSuccess,lastFailure}=await receipts.snapshot();const device=manager&&await componentDevice(home,scope);const at2=new Date().toISOString();const ready=version&&observed&&!observed.capabilityMismatch&&["IDLE","EXECUTING"].includes(observed.state)&&installation?.phase==="IDLE";const reason=version?"OWNED_RUNTIME_RESPONDING":stopped?"OWNED_RUNTIME_STOPPED":manager?"OWNED_RUNTIME_UNCONFIRMED":"COMPONENT_NOT_INITIALIZED";const event2=value=>value?{state:"OBSERVED",...value}:{state:"NONE"};return AgentComponentStatusSchema.parse({protocol:"NVS_COMPONENT_STATUS_V1",component:"HOST_RUNTIME",source:"OWNED_INSTALLATION_IPC",observedAt:at2,componentHome:home,initialized:!!manager,installationRevision:installation?.revision??0,installedVersion:installation?.activeVersion??null,runningVersion:version?.runningVersion??null,loginService,deviceId:device?.deviceId??null,...version&&observed?.capabilityMismatch&&{capabilityMismatch:observed.capabilityMismatch},liveness:{state:version?"ALIVE":stopped?"STOPPED":"UNKNOWN",reasonCode:reason,at:manager?at2:null},readiness:{state:ready?"READY":manager?"BLOCKED":"UNKNOWN",reasonCode:version&&observed?.capabilityMismatch?"CAPABILITY_VERSION_MISMATCH":ready||!version?reason:"OWNED_RUNTIME_RECOVERY_REQUIRED",at:manager?at2:null},lastRequestId:latest?.command.requestId??null,lastSuccess:event2(lastSuccess),lastFailure:event2(lastFailure),queueDepth:{state:"NOT_APPLICABLE"},nextRetry:{state:"NONE"}})}export{componentHome,initializeComponent,componentDevice,assertComponentConfiguration,withComponentLock,ComponentReceipts,observeLoginService,observeComponent};
@@ -0,0 +1 @@
1
+ import{DesktopRuntimeChannelSchema}from"./chunk-WLQMICJN.js";import{InstalledToolPathsSchema}from"./chunk-FFXSXE3G.js";import{AgentComponentScopeSchema,LocalRuntimeDescriptorSchema,LocalToolChoiceSchema}from"./chunk-LDBXGRCQ.js";import{z}from"zod";var digest=z.string().regex(/^[0-9a-f]{64}$/);var version=LocalRuntimeDescriptorSchema.shape.version;var revision=z.int().nonnegative();var request={requestId:z.uuid(),expectedRevision:revision};var planRequest={...request,planId:z.uuid(),fingerprint:digest};var planSelection={version,source:z.enum(["BUNDLED","SIGNED_CHANNEL"]).default("BUNDLED"),tools:z.union([LocalToolChoiceSchema,InstalledToolPathsSchema]).optional()};var componentChannel=DesktopRuntimeChannelSchema.extend({protocol:z.enum(["NVS_RUNTIME_RELEASE_CHANNEL_V1","NVS_DESKTOP_RUNTIME_CHANNEL_V1"])});var selectionVersion=z.union([version,z.literal("latest")]);var ComponentCommandSchema=z.discriminatedUnion("action",[z.strictObject({action:z.literal("apply"),...planRequest}),z.strictObject({action:z.literal("rollback"),...planRequest}),z.strictObject({action:z.literal("reconcile-install"),...planRequest}),z.strictObject({action:z.literal("start"),...request}),z.strictObject({action:z.literal("stop"),...request}),z.strictObject({action:z.literal("recover"),...request}),z.strictObject({action:z.literal("service-enable"),...request,fingerprint:digest})]);var HostComponentRequestSchema=z.strictObject({scope:AgentComponentScopeSchema,call:z.discriminatedUnion("action",[z.strictObject({action:z.literal("initialize"),channel:componentChannel.optional()}),z.strictObject({action:z.literal("status")}),z.strictObject({action:z.literal("preflight"),kind:z.enum(["library","preview","final"]),source:planSelection.source,version:selectionVersion.default("latest"),channel:componentChannel.optional(),tools:InstalledToolPathsSchema.pick({ffmpeg:true,ffprobe:true,captionAssetsDirectory:true}).partial().optional()}),z.strictObject({action:z.literal("receipt"),requestId:z.uuid()}),z.strictObject({action:z.literal("observe-original"),requestId:z.uuid()}),z.strictObject({action:z.literal("install-plan"),...planSelection,version:selectionVersion.describe("Use latest for the code bundled in this CLI. SIGNED_CHANNEL requires an exact version.")}),z.strictObject({action:z.literal("rollback-plan"),...planSelection}),z.strictObject({action:z.literal("service-plan")}),...ComponentCommandSchema.options])});export{ComponentCommandSchema,HostComponentRequestSchema};
@@ -0,0 +1 @@
1
+ import{ComponentCommandSchema,HostComponentRequestSchema}from"./chunk-ZYXHPTT2.js";import"./chunk-WLQMICJN.js";import"./chunk-DMA53YVU.js";import"./chunk-MZWEFYHE.js";import"./chunk-FFXSXE3G.js";import"./chunk-SM2I7TJ3.js";import"./chunk-LDBXGRCQ.js";import"./chunk-2S7FI3HF.js";import"./chunk-DLW42PJ6.js";import"./chunk-WTJVS2VS.js";import"./chunk-TT7IA5HB.js";export{ComponentCommandSchema,HostComponentRequestSchema};
@@ -0,0 +1 @@
1
+ import{assertComponentConfiguration,componentDevice,observeComponent}from"./chunk-ZMJYBUS3.js";import{observeLoginHost}from"./chunk-5Y7J2OYL.js";import"./chunk-ZYXHPTT2.js";import{desktopRuntimeChannel}from"./chunk-7IVAYDU3.js";import"./chunk-WLQMICJN.js";import"./chunk-DMA53YVU.js";import"./chunk-MZWEFYHE.js";import{captureInstalledTools,installationSource,verifyCaptionDirectory}from"./chunk-FFXSXE3G.js";import"./chunk-ETK7GYCB.js";import"./chunk-SM2I7TJ3.js";import{LocalToolSelectionSchema}from"./chunk-LDBXGRCQ.js";import"./chunk-2S7FI3HF.js";import"./chunk-7I7ARCY7.js";import{LocalClientError,assertExecutable,read}from"./chunk-DLW42PJ6.js";import"./chunk-WTJVS2VS.js";import"./chunk-KOCUZ3AE.js";import"./chunk-TT7IA5HB.js";import{realpath}from"node:fs/promises";import{delimiter,isAbsolute,join}from"node:path";function reason(error,fallback){return error instanceof LocalClientError&&/^[A-Z][A-Z0-9_]{0,79}$/.test(error.code)?error.code:fallback}async function toolPath(name,explicit){const path=process.platform==="win32"?name+".exe":name;const choices=explicit?[explicit]:(process.env.PATH??"").split(delimiter).filter(isAbsolute).slice(0,64).map(root=>join(root,path));for(const candidate of choices){if(!isAbsolute(candidate))continue;try{const actual=await realpath(candidate);await assertExecutable(actual);return actual}catch{}}}async function componentPreflight(home,scope,call,manager,receipts){const observedAt=new Date().toISOString();const platform={os:process.platform,architecture:process.arch,node:process.versions.node};const configuration=manager&&await assertComponentConfiguration(manager,scope);const installation=manager&&(await manager.ledger.current()).value;const last=manager&&(await receipts.snapshot()).latest;const status=(body,exitCode=0)=>({exitCode,output:{protocol:"NVS_HOST_PREFLIGHT_V1",observedAt,kind:call.kind,platform,componentHome:home,installationRevision:installation?.revision??0,installedVersion:installation?.active?.descriptor.version??null,...body}});const blocked=(reasonCode,nextAction,facts2={})=>status({state:"BLOCKED",reasonCode,nextAction,...facts2},4);if(last?.phase==="SENDING")return blocked(last.reasonCode,{surface:"HOST_COMPONENT",action:"observe-original",requestId:last.command.requestId});if(installation?.transition)return blocked("INSTALLATION_RECOVERY_REQUIRED",{surface:"HOST_COMPONENT",action:"reconcile-install",planId:installation.transition.planId,fingerprint:installation.transition.fingerprint,expectedRevision:installation.revision});if(last?.outcome==="UNKNOWN")return blocked(last.reasonCode,{surface:"HOST_COMPONENT",action:"receipt",requestId:last.command.requestId});if(process.platform!=="win32"&&Buffer.byteLength(join(home,"rt","runtime.sock"))>100)return blocked("SOCKET_PATH_TOO_LONG",{surface:"HOST_OWNER",action:"SELECT_PRIVATE_HOME"});const login=await observeLoginHost().then(state=>({state,reasonCode:state==="UNAVAILABLE"?"LOGIN_SERVICE_UNAVAILABLE":null}),error=>({state:"UNAVAILABLE",reasonCode:reason(error,"LOGIN_SERVICE_UNAVAILABLE")}));const host={loginService:login};if(call.source==="SIGNED_CHANNEL"&&call.version==="latest")return blocked("EXACT_RELEASE_VERSION_REQUIRED",{surface:"HOST_OWNER",action:"SELECT_EXACT_RELEASE"},host);const configured=configuration?.catalogueUrl&&configuration.publicKeyFile?{catalogueUrl:configuration.catalogueUrl,publicKeyFile:configuration.publicKeyFile}:null;let trust={...configured??{},rejectedVersions:configuration?.rejectedVersions??[]};const bundled=call.source==="BUNDLED";const fullMedia=call.kind!=="library";const active=installation?.active;const pinned=fullMedia&&active?.toolsConfigPath&&!call.tools?LocalToolSelectionSchema.parse(JSON.parse((await read(active.toolsConfigPath,32768)).toString())):null;const activeCaptions=active&&manager?join(manager.ledger.slotPath(active),"dist/captions"):void 0;const captionPath=call.tools?.captionAssetsDirectory??activeCaptions;let localCaptions=false;if(fullMedia&&captionPath){try{await verifyCaptionDirectory(captionPath);localCaptions=true}catch(error){if(call.tools?.captionAssetsDirectory)return blocked(reason(error,"CAPTION_ASSET_UNAVAILABLE"),{surface:"HOST_OWNER",action:"PROVIDE_MATCHING_CAPTION_ASSETS"},host)}}const[ffmpeg,ffprobe]=fullMedia?await Promise.all([toolPath("ffmpeg",call.tools?.ffmpeg??pinned?.ffmpeg.path),toolPath("ffprobe",call.tools?.ffprobe??pinned?.ffprobe.path)]):[void 0,void 0];const missingTools=[!ffmpeg&&"FFMPEG",!ffprobe&&"FFPROBE"].filter(name=>name!==false);let release;try{if(call.channel&&(!bundled||fullMedia&&(!localCaptions||missingTools.length))){const{value}=desktopRuntimeChannel({...call.channel,protocol:"NVS_DESKTOP_RUNTIME_CHANNEL_V1"});if(configured&&(configured.catalogueUrl!==value.catalogueUrl||(await read(configured.publicKeyFile,16384)).toString().trim()!==value.publicKey.trim()))return blocked("DEPENDENCY_CHANNEL_CHANGED",{surface:"HOST_OWNER",action:"CHECK_CONFIGURED_RELEASE_CHANNEL"},host);if(!configured)trust={...trust,catalogueUrl:value.catalogueUrl,publicKey:value.publicKey}}const dependencyChannel=fullMedia&&(!localCaptions||missingTools.length>0)&&!!trust.catalogueUrl;release=(await installationSource(trust,call.version,bundled,dependencyChannel)).release}catch(error){return blocked(reason(error,"RELEASE_OBSERVATION_UNAVAILABLE"),{surface:"HOST_OWNER",action:"CHECK_RELEASE_SOURCE"},host)}const facts={...host,release:{version:release.descriptor.version,source:call.source,node:release.descriptor.node,sha512:release.package.sha512}};let tools;if(fullMedia){const explicitMissing=call.tools?.ffmpeg&&!ffmpeg||call.tools?.ffprobe&&!ffprobe;const mediaSource=ffmpeg&&ffprobe?"INSTALLED":!explicitMissing&&release.tools?"SIGNED_CHANNEL":"MISSING";const canReuseCaptions=localCaptions&&(!call.tools?.captionAssetsDirectory||mediaSource==="INSTALLED");const captionSource=canReuseCaptions?"INSTALLED":release.resources?.captions?"SIGNED_CHANNEL":"MISSING";const dependencies={mediaSource,captionSource,missingTools:mediaSource==="MISSING"?missingTools:[]};if(mediaSource==="MISSING"||captionSource==="MISSING")return blocked("MEDIA_DEPENDENCIES_REQUIRED",{surface:"HOST_OWNER",action:"PROVIDE_MATCHING_DEPENDENCIES"},{...facts,dependencies});try{tools=ffmpeg&&ffprobe?await captureInstalledTools({mode:"INSTALLED",ffmpeg,ffprobe,...call.tools?.captionAssetsDirectory&&{captionAssetsDirectory:captionPath}}):{mode:"MANAGED"}}catch(error){return blocked(reason(error,"TOOL_IDENTITY_UNAVAILABLE"),{surface:"HOST_OWNER",action:"CHECK_INSTALLED_TOOLS"},{...facts,dependencies})}if(pinned&&(tools.mode!=="INSTALLED"||tools.ffmpeg.digest!==pinned.ffmpeg.digest||tools.ffprobe.digest!==pinned.ffprobe.digest))return blocked("INSTALLED_TOOL_IDENTITY_CHANGED",{surface:"HOST_OWNER",action:"CHECK_INSTALLED_TOOLS"},{...facts,dependencies});Object.assign(facts,{dependencies})}if(!manager||!configured&&!!trust.catalogueUrl)return status({...facts,state:"INITIALIZATION_REQUIRED",reasonCode:manager?"DEPENDENCY_CHANNEL_CONFIGURATION_REQUIRED":"COMPONENT_NOT_INITIALIZED",nextAction:{surface:"HOST_COMPONENT",call:{action:"initialize"},includeOriginalChannel:!!trust.catalogueUrl}});if(!active||active.descriptor.version!==release.descriptor.version||fullMedia&&(!active.toolsConfigPath||!localCaptions||!!call.tools))return status({...facts,state:"INSTALL_PLAN_REQUIRED",reasonCode:"PIN_CURRENT_INSTALLATION_PLAN",nextAction:{surface:"HOST_COMPONENT",call:{action:"install-plan",version:release.descriptor.version,source:call.source,...tools&&{tools}}}});const device=await componentDevice(home,scope);const component=await observeComponent(home,scope,manager,receipts);if(device&&component.liveness.state==="STOPPED")return status({...facts,component,state:"START_REQUIRED",reasonCode:"OWNED_RUNTIME_STOPPED",nextAction:{surface:"HOST_COMPONENT",action:"start",expectedRevision:component.installationRevision}});return status({...facts,component,state:device?"VERIFY_DEVICE":"ENROLLMENT_REQUIRED",reasonCode:device?"CHECK_DEVICE_HEARTBEAT_AND_TASK":"INSPECT_ORIGINAL_ENROLLMENT",nextAction:device?{surface:"MCP",tool:"studio_capability_query",arguments:{tenantId:scope.tenantId,tool:"device_status",arguments:{tenantId:scope.tenantId,deviceId:device.deviceId}}}:{surface:"HOST_ENROLLMENT",call:{action:"inspect"}}})}export{componentPreflight};
@@ -0,0 +1 @@
1
+ import{loginLink,openLoginBrowser}from"./chunk-OW6R4MAQ.js";import{profileAuthorization,runOAuthCommand}from"./chunk-3TOXIJ7K.js";import"./chunk-QGK6G6YS.js";import{clientHome,connectionError,loadConnection,readAccount,saveConnection,tenantConnection}from"./chunk-27KI24GK.js";import{FileOAuthProvider}from"./chunk-7I7ARCY7.js";import"./chunk-DLW42PJ6.js";import"./chunk-WTJVS2VS.js";import"./chunk-KOCUZ3AE.js";import{NativeStudioSdkError}from"./chunk-TT7IA5HB.js";import{randomUUID,timingSafeEqual}from"node:crypto";import{createServer}from"node:http";import{join}from"node:path";async function runConnect(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 root=await clientHome(environment,true),account=await readAccount(root);const explicit=options.get("--mcp-url");if(!explicit&&!account?.workspaceId)connectionError("ACCOUNT_WORKSPACE_SELECTION_REQUIRED");const resource=tenantConnection(explicit??new URL("/mcp/external/v1/tenants/"+account.workspaceId,account.serverOrigin).href);const scope=options.get("--scope")??"nvs:read nvs:write";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 profile=`profile-${randomUUID()}.json`;const path=join(root,profile),callbackPath=`/callback/${randomUUID()}`;if(account&&(account.state!=="ACTIVE"||account.workspaceId!==resource.tenantId))connectionError("ACCOUNT_WORKSPACE_SELECTION_REQUIRED");if(!explicit){let saved=null;try{saved=await loadConnection(environment)}catch(error){if(!(error instanceof NativeStudioSdkError)||error.code!=="CONNECTION_ACCOUNT_MISMATCH")throw error}if(saved?.resource===resource.resource&&saved.scope===scope&&!saved.exchangeUnresolved){await profileAuthorization(saved.profile,signal);return{exitCode:0,output:{semanticStatus:"SUCCESS",connected:true,resource:saved.resource,tenantId:saved.tenantId,scope,reused:true}}}}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("AUTHORIZED_CONNECTION_NOT_SELECTED","INTERNAL_OPERATIONAL_FAILURE","UNKNOWN")});return{exitCode:0,output:{semanticStatus:"SUCCESS",connected:true,credentialPurpose:"TENANT_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{runConnect};
@@ -0,0 +1 @@
1
+ import{profileAuthorization}from"./chunk-3TOXIJ7K.js";import{readCredential,readInput}from"./chunk-QGK6G6YS.js";import{connectRemoteMcp}from"./chunk-76E5R3OC.js";import"./chunk-2UYKJ6YN.js";import"./chunk-2S7FI3HF.js";import{defaultConnection,tenantConnection}from"./chunk-27KI24GK.js";import"./chunk-7I7ARCY7.js";import"./chunk-DLW42PJ6.js";import{CapabilityVersionSchema}from"./chunk-WTJVS2VS.js";import"./chunk-KOCUZ3AE.js";import{NativeStudioSdkError}from"./chunk-TT7IA5HB.js";var operations={status:"device.status",enroll:"device.enroll","enrollment-issue":"device.enrollment.issue","enrollment-lookup":"device.enrollment.lookup",revoke:"device.revoke",receipt:"device.management-receipt"};async function deviceManagementCommand(action,args,env,stdin){if(!action||!Object.hasOwn(operations,action))throw Error();const flags=new Map;for(let i=0;i<args.length;i+=2){const key=args[i],value=args[i+1];if(!key||!["--input","--profile","--mcp-url","--token-file","--token-env","--capability-version"].includes(key)||!value||value.startsWith("--")||flags.has(key))throw Error();flags.set(key,value)}if(!flags.has("--input"))throw Error();const capabilityVersion=CapabilityVersionSchema.optional().parse(flags.get("--capability-version"));await defaultConnection(flags,env,true);const profile=flags.get("--profile");if(profile&&["--mcp-url","--token-file","--token-env"].some(k=>flags.has(k)))throw Error();const token=profile?await profileAuthorization(profile):null;const resource=token?.resource??flags.get("--mcp-url");if(!resource)throw Error();const scope=tenantConnection(resource);const raw=await readInput(flags.get("--input"),stdin);const nested=action==="receipt"?raw.input:raw;if(nested?.tenantId!==void 0&&String(nested.tenantId).toLowerCase()!==scope.tenantId.toLowerCase())throw new NativeStudioSdkError("FORBIDDEN","BLOCKED","NO_WRITE");const authorization=token?.authorization??await readCredential(flags,env);const connection=await connectRemoteMcp(scope.resource,authorization,scope.tenantId);try{const key=operations[action];const input=action==="receipt"?{command:raw}:{...raw,tenantId:scope.tenantId};const command=input;const output=capabilityVersion?await connection.studio.call(key,command,{capabilityVersion}):await connection.studio.call(key,command);return{exitCode:0,output}}finally{await connection.close().catch(()=>{})}}export{deviceManagementCommand};
@@ -0,0 +1 @@
1
+ import{callerOriginMatches,workspaceCaller}from"./chunk-X5MVC46N.js";import{renderConnection}from"./chunk-3RNDOAQI.js";import"./chunk-VYCNG6TR.js";import{LocalInstallationManager,ownerClient,probeLocalLibrary,probeReferenceThumbnail,probeTenantComposition,probeTenantMediaProcessing,probeTenantMediaValidation,probeTenantQwenGeneration,probeTenantSpeech,probeTenantTranscription,verifySlot}from"./chunk-FFXSXE3G.js";import{DesktopDeviceRecords}from"./chunk-ETK7GYCB.js";import"./chunk-SM2I7TJ3.js";import{LocalToolSelectionSchema}from"./chunk-LDBXGRCQ.js";import"./chunk-3TOXIJ7K.js";import"./chunk-QGK6G6YS.js";import"./chunk-76E5R3OC.js";import"./chunk-2UYKJ6YN.js";import{DeviceDiscoveryInputSchema,LocalDeviceTransportConfigurationSchema}from"./chunk-2S7FI3HF.js";import"./chunk-7P2NA6TH.js";import"./chunk-27KI24GK.js";import"./chunk-7I7ARCY7.js";import{LocalClientError,read}from"./chunk-DLW42PJ6.js";import"./chunk-WTJVS2VS.js";import"./chunk-KOCUZ3AE.js";import{NativeStudioSdkError}from"./chunk-TT7IA5HB.js";import{z}from"zod";var transportSchema=LocalDeviceTransportConfigurationSchema.safeExtend({tools:LocalToolSelectionSchema.optional()});var nextSteps={ACCOUNT_LOGIN_REQUIRED:"nvs login --server <Studio-origin>",TENANT_CONNECTION_REQUIRED:"nvs connect --mcp-url <tenant-connection-url>",ACCOUNT_REVOCATION_UNCONFIRMED:"nvs logout",PROJECT_SELECTION_REQUIRED:"Run nvs workspaces, nvs projects, then nvs project --id <project-id>",INSTALL_REQUIRED:"Configure the Runtime, check signed releases, then prepare nvs local install --version <exact>",INSTALLATION_RECOVERY_REQUIRED:"Inspect nvs local status, then reconcile the original installation plan",CONFIGURATION_REQUIRED:"nvs local configure --input <private-json>",DEVICE_ENROLLMENT_REQUIRED:"nvs local cloud --action enroll with the approved owner input",DEVICE_RECEIPT_REQUIRED:"nvs local cloud --action receipt with the original management command",PROJECT_CONNECTION_REQUIRED:"nvs connect",DEVICE_AUTHORITY_UNCONFIRMED:"Check the current workspace membership, device proof and revocation",DEVICE_CONNECTION_REQUIRED:"nvs local connect --input <private-device-config>",DEVICE_CONNECTION_RECOVERY_REQUIRED:"Inspect the original device connection and Runtime status",DEVICE_OFFLINE:"Inspect nvs local status, then start the configured Runtime if stopped",DEVICE_BUSY:"Wait for available capacity, then recheck this device",RUNTIME_QUALIFICATION_REQUIRED:"Check the signed Runtime slot and the approved tools",DEVICE_CAPABILITY_UNCONFIRMED:"Check the configured action, tool or provider prerequisites and the current heartbeat",PROJECT_QUERY_UNAVAILABLE:"Check the selected Project connection, then retry this read"};async function qualified(kind,root,slot,validator){if(kind==="library")return true;if(kind==="preview"||kind==="final")return validator?probeTenantMediaValidation(root,slot):true;if(!await probeTenantMediaProcessing(root,slot))return false;switch(kind){case"REFERENCE_PREVIEW":return probeReferenceThumbnail(root,slot);case"LOCAL_MEDIA_INSPECT":case"LOCAL_MEDIA_PUBLISH":return probeLocalLibrary(root,slot);case"COMPOSITION_RENDER":return probeTenantComposition(root,slot);case"SPEECH_SYNTHESIZE":return probeTenantSpeech(root,slot);case"TRANSCRIBE_AUDIO":return probeTenantTranscription(root,slot);case"KEYFRAME_GENERATE":return probeTenantQwenGeneration(root,slot,"keyframe");case"VIDEO_GENERATE":return probeTenantQwenGeneration(root,slot,"video");case"SPEECH_EXTERNAL_QWEN":return probeTenantQwenGeneration(root,slot,"speech");case"TRANSCRIBE_EXTERNAL_QWEN":return probeTenantQwenGeneration(root,slot,"asr");default:return true}}async function devicePreflight(raw,env,explicitProject){const kind=DeviceDiscoveryInputSchema.shape.kind.parse(raw);const context={};const blocked=reason=>({exitCode:4,output:{semanticStatus:"BLOCKED",kind,...context,error:{code:reason,outcome:"NO_WRITE"},nextStep:nextSteps[reason]}});let caller;try{caller=await workspaceCaller(env)}catch(error){if(error.code==="ENOENT")return blocked("ACCOUNT_LOGIN_REQUIRED");if(error instanceof NativeStudioSdkError){if(error.code==="TENANT_CONNECTION_REQUIRED")return blocked("TENANT_CONNECTION_REQUIRED");if(error.code==="ACCOUNT_LOGIN_REQUIRED")return blocked("ACCOUNT_LOGIN_REQUIRED");if(error.code==="ACCOUNT_LOGOUT_OUTCOME_UNKNOWN")return blocked("ACCOUNT_REVOCATION_UNCONFIRMED");if(error.code==="PROJECT_SELECTION_REQUIRED")return blocked("PROJECT_SELECTION_REQUIRED")}throw error}if(!caller)return blocked("ACCOUNT_LOGIN_REQUIRED");const{home,tenantId,principalId,serverOrigin}=caller;const projectId=explicitProject?z.uuid().parse(explicitProject):void 0;Object.assign(context,{tenantId,projectId});const manager=await LocalInstallationManager.openExisting(home);if(!manager)return blocked("INSTALL_REQUIRED");const{active,transition}=(await manager.ledger.current()).value;if(transition)return blocked("INSTALLATION_RECOVERY_REQUIRED");if(!active)return blocked("INSTALL_REQUIRED");const slotRoot=manager.ledger.slotPath(active);await verifySlot(slotRoot,active);const records=await DesktopDeviceRecords.inspect(home,{origin:serverOrigin,tenantId,principalId});const pending=records?.pending?.command;if(records?.pending?.phase==="SENDING"&&(pending?.kind==="ENROLL"||pending?.kind==="REVOKE_DEVICE"))return blocked("DEVICE_RECEIPT_REQUIRED");if(records?.connection?.phase==="CONNECTING")return blocked("DEVICE_CONNECTION_RECOVERY_REQUIRED");const config=await manager.configuration().catch(error=>{if(error instanceof LocalClientError&&error.code==="CONFIGURATION_REQUIRED")return null;throw error});if(!config)return blocked("CONFIGURATION_REQUIRED");let transport=null;try{if(config.cloudConfigFile)transport=transportSchema.parse(JSON.parse((await read(config.cloudConfigFile,32768)).toString()))}catch(error){if(error.code==="ENOENT")return blocked("DEVICE_CONNECTION_REQUIRED");if(error instanceof SyntaxError||error instanceof z.ZodError)return blocked("DEVICE_CONNECTION_RECOVERY_REQUIRED");throw error}const endpoint=transport?new URL(transport.endpoint):null;const current=endpoint&&await callerOriginMatches(endpoint.origin,caller)&&!endpoint.username&&!endpoint.password&&transport?.tenantId===tenantId?transport:null;const deviceId=records?.device?.deviceId??current?.deviceId;if(!deviceId)return blocked("DEVICE_ENROLLMENT_REQUIRED");context.deviceId=deviceId;const configured=current?.deviceId===deviceId&&current.tenantId===tenantId;if(!configured||!current)return blocked("DEVICE_CONNECTION_REQUIRED");if(!projectId){const local=await ownerClient(config.stateDirectory);const status=await local.status(void 0,true).catch(()=>null);if(!status)return blocked("DEVICE_OFFLINE");if(status.deviceAuthority?.tenantId!==tenantId||status.deviceAuthority.deviceId!==deviceId)return blocked("DEVICE_AUTHORITY_UNCONFIRMED");if(status.state==="DRAINING")return blocked("DEVICE_BUSY");if(status.state==="RECOVERY_REQUIRED")return blocked("DEVICE_CONNECTION_RECOVERY_REQUIRED");const capabilities=status.deviceCapabilities;if(!capabilities)return blocked("DEVICE_CAPABILITY_UNCONFIRMED");if(capabilities.deviceRevision!==current.deviceRevision)return blocked("DEVICE_CONNECTION_RECOVERY_REQUIRED");if(kind==="preview"||kind==="final"){const doctor=await local.doctor().catch(()=>null);if(!doctor?.nativeExecutionReady||!doctor.executionProfiles?.includes("STUDIO_MEDIA_V2"))return blocked("RUNTIME_QUALIFICATION_REQUIRED");if(current.tenantMediaValidation&&!capabilities.tenantMediaValidation)return blocked("DEVICE_CAPABILITY_UNCONFIRMED")}if(kind!=="preview"&&kind!=="final"&&kind!=="library"){const configuredKinds=current.processorCapabilities??[];if(!current.tenantMediaProcessing||!configuredKinds.includes(kind)||!capabilities.tenantMediaProcessing||!capabilities.processorCapabilities.includes(kind))return blocked("DEVICE_CAPABILITY_UNCONFIRMED")}if(!await qualified(kind,slotRoot,active,!!current?.tenantMediaValidation))return blocked("RUNTIME_QUALIFICATION_REQUIRED");await caller.assertCurrent();return{exitCode:0,output:{semanticStatus:"SUCCESS",kind,tenantId,deviceId,availability:status.state==="EXECUTING"?"BUSY":"AVAILABLE"}}}const conn=await renderConnection(env,void 0,false,projectId).catch(error=>{if(error instanceof NativeStudioSdkError&&error.code==="AUTHORIZATION_REQUIRED")return null;throw error});if(!conn)return blocked("PROJECT_CONNECTION_REQUIRED");try{if(conn.scope.tenantId!==tenantId||conn.scope.projectId!==projectId||(caller.resource?conn.scope.resource!==caller.resource:new URL(conn.scope.resource).origin!==serverOrigin))return blocked("PROJECT_CONNECTION_REQUIRED");const page=await conn.studio.deviceRenders.list({kind,projectId,deviceId}).catch(error=>{if(error instanceof NativeStudioSdkError)return null;throw error});await caller.assertCurrent();if(!page||page.truncated)return blocked("PROJECT_QUERY_UNAVAILABLE");const candidate=page.items[0];if(!candidate)return blocked("DEVICE_AUTHORITY_UNCONFIRMED");if(!configured)return blocked("DEVICE_CONNECTION_REQUIRED");if(candidate.availability==="OFFLINE")return blocked("DEVICE_OFFLINE");if(candidate.availability==="BUSY")return blocked("DEVICE_BUSY");if(candidate.availability==="UNQUALIFIED")return blocked(await qualified(kind,slotRoot,active,!!page.validationMode)?"DEVICE_CAPABILITY_UNCONFIRMED":"RUNTIME_QUALIFICATION_REQUIRED");return{exitCode:0,output:{semanticStatus:"SUCCESS",kind,tenantId,projectId,deviceId,availability:candidate.availability,validationMode:page.validationMode}}}finally{await conn.close().catch(()=>{})}}export{devicePreflight};
@@ -0,0 +1 @@
1
+ import{profileAuthorization}from"./chunk-3TOXIJ7K.js";import{readCredential}from"./chunk-QGK6G6YS.js";import{connectRemoteMcp}from"./chunk-76E5R3OC.js";import"./chunk-2UYKJ6YN.js";import{WorkspaceDeviceListInputSchema}from"./chunk-2S7FI3HF.js";import{defaultConnection,tenantConnection}from"./chunk-27KI24GK.js";import"./chunk-7I7ARCY7.js";import"./chunk-DLW42PJ6.js";import"./chunk-WTJVS2VS.js";import"./chunk-KOCUZ3AE.js";import"./chunk-TT7IA5HB.js";var query=WorkspaceDeviceListInputSchema.omit({tenantId:true});async function deviceInventoryCommand(args,env){const flags=new Map;for(let i=0;i<args.length;i+=2){const key=args[i],value=args[i+1];if(!key||!["--device","--after","--limit","--profile","--mcp-url","--token-file","--token-env"].includes(key)||!value||value.startsWith("--")||flags.has(key))throw Error();flags.set(key,value)}const input=query.parse({...flags.has("--device")&&{deviceId:flags.get("--device")},...flags.has("--after")&&{after:flags.get("--after")},...flags.has("--limit")&&{limit:Number(flags.get("--limit"))}});await defaultConnection(flags,env,true);const profile=flags.get("--profile");if(profile&&["--mcp-url","--token-file","--token-env"].some(key=>flags.has(key)))throw Error();const token=profile?await profileAuthorization(profile):null;const resource=token?.resource??flags.get("--mcp-url");if(!resource)throw Error();const scope=tenantConnection(resource);const authorization=token?.authorization??await readCredential(flags,env);const connection=await connectRemoteMcp(scope.resource,authorization,scope.tenantId);try{const output=await connection.studio.call("workspace.devices.list",{...input,tenantId:scope.tenantId});return{exitCode:0,output}}finally{await connection.close().catch(()=>{})}}export{deviceInventoryCommand};
@@ -0,0 +1 @@
1
+ import{callerRenderConnection}from"./chunk-3RNDOAQI.js";import"./chunk-VYCNG6TR.js";import"./chunk-3TOXIJ7K.js";import"./chunk-QGK6G6YS.js";import"./chunk-76E5R3OC.js";import"./chunk-2UYKJ6YN.js";import{DeviceDiscoveryInputSchema}from"./chunk-2S7FI3HF.js";import"./chunk-27KI24GK.js";import"./chunk-7I7ARCY7.js";import"./chunk-DLW42PJ6.js";import"./chunk-WTJVS2VS.js";import"./chunk-KOCUZ3AE.js";import"./chunk-TT7IA5HB.js";var query=DeviceDiscoveryInputSchema.pick({kind:true,deviceId:true});async function devicesCommand(argv,env,stdin=process.stdin){const[action,...args]=argv;if(action==="inventory")return(await import("./devices-inventory-E6ZLXCVR.js")).deviceInventoryCommand(args,env);if(action!=="list")return(await import("./device-management-JPS4HG34.js")).deviceManagementCommand(action,args,env,stdin);const flags=new Map;for(let i=0;i<args.length;i+=2){const name=args[i],value=args[i+1];if(!name||!["--kind","--device","--project","--mcp-url","--token-file"].includes(name)||!value||value.startsWith("--")||flags.has(name))throw Error();flags.set(name,value)}const input=query.parse({kind:flags.get("--kind"),...flags.has("--device")&&{deviceId:flags.get("--device")}});const conn=await callerRenderConnection(env,flags,false);try{const output=await conn.studio.deviceRenders.list({...input,projectId:conn.scope.projectId});return{exitCode:0,output}}finally{await conn.close().catch(()=>{})}}export{devicesCommand};
@@ -0,0 +1 @@
1
+ import{LocalClientError,digestPrivateFile,directory,entries,fail,optional,read,sha256,sha512,verifyBackup,write}from"./chunk-DLW42PJ6.js";export{LocalClientError,digestPrivateFile,directory,entries,fail,optional,read,sha256,sha512,verifyBackup,write};
@@ -0,0 +1 @@
1
+ import{ComponentReceipts,componentHome,initializeComponent,observeComponent,observeLoginService,withComponentLock}from"./chunk-ZMJYBUS3.js";import{runLoginService}from"./chunk-5Y7J2OYL.js";import"./chunk-ZYXHPTT2.js";import"./chunk-7IVAYDU3.js";import"./chunk-WLQMICJN.js";import"./chunk-DMA53YVU.js";import"./chunk-MZWEFYHE.js";import{InstalledToolPathsSchema,LocalInstallationManager,captureInstalledTools}from"./chunk-FFXSXE3G.js";import"./chunk-ETK7GYCB.js";import"./chunk-SM2I7TJ3.js";import"./chunk-LDBXGRCQ.js";import"./chunk-2S7FI3HF.js";import"./chunk-7I7ARCY7.js";import{LocalClientError,fail}from"./chunk-DLW42PJ6.js";import"./chunk-WTJVS2VS.js";import"./chunk-KOCUZ3AE.js";import"./chunk-TT7IA5HB.js";var ok=output=>({exitCode:0,output});var acknowledged=output=>({exitCode:output.phase==="COMPLETE"?0:2,output});async function serviceFingerprint(home){const service=await observeLoginService(home);if(!("fingerprint"in service)||!service.fingerprint||!("supervision"in service)||service.supervision!=="EXPLICIT_RECOVERY")fail("COMPONENT_SERVICE_UNCONFIRMED");return service.fingerprint}async function applyComponentCommand(manager,command,before){const home=manager.ledger.root;switch(command.action){case"apply":case"rollback":{if(command.action==="rollback"){const plan=await manager.plan(command.planId),version=plan.release.descriptor.version;if(version===before.installedVersion||!await manager.ledger.hadCompletedVersion(version))fail("COMPONENT_ROLLBACK_VERSION_UNAVAILABLE")}await manager.apply(command.planId,command.fingerprint);return"COMPONENT_VERSION_ACTIVATED"}case"reconcile-install":await manager.reconcile(command.planId,command.fingerprint);return"COMPONENT_INSTALLATION_RECONCILED";case"service-enable":await runLoginService("service-enable",home,command.fingerprint,"EXPLICIT_RECOVERY");return"COMPONENT_SERVICE_REGISTERED";case"start":if(before.loginService==="REGISTERED")await runLoginService("service-start",home,await serviceFingerprint(home));else await manager.start();return"COMPONENT_STARTED";case"stop":if(before.loginService!=="NONE")await runLoginService("service-disable",home,await serviceFingerprint(home));if((await manager.status()).running)await manager.stop();return"COMPONENT_STOPPED";case"recover":if(before.readiness.state==="READY")return"COMPONENT_HEALTHY";if(before.loginService==="REGISTERED")await runLoginService("service-restart",home,await serviceFingerprint(home));else{if(before.liveness.state==="ALIVE")await manager.stop();await manager.start()}return"COMPONENT_RECOVERED"}}function outcomeObserved(command,current){switch(command.action){case"stop":return current.liveness.state==="STOPPED"&&current.loginService==="NONE";case"service-enable":return current.loginService==="REGISTERED";case"reconcile-install":return true;default:return current.readiness.state==="READY"}}function reason(error){return error instanceof LocalClientError&&/^[A-Z][A-Z0-9_]{0,79}$/.test(error.code)?error.code:"COMPONENT_ACTION_UNAVAILABLE"}async function runHostComponent(parent,{scope,call}){const target=await componentHome(parent,scope,call.action==="initialize"),home=target.home,receipts=new ComponentReceipts(home);if(call.action==="initialize")return withComponentLock(home,async()=>{const manager2=await initializeComponent(home,scope,call.channel);return ok(await observeComponent(home,scope,manager2,receipts))});if(call.action==="receipt")return ok({receipt:target.claimed?await receipts.find(call.requestId):null});const manager=target.claimed?await LocalInstallationManager.openExisting(home):null;const observe=()=>observeComponent(home,scope,manager,receipts);if(call.action==="status")return ok(await observe());if(call.action==="preflight")return(await import("./component-preflight-6OWDQAZT.js")).componentPreflight(home,scope,call,manager,receipts);if(!manager)fail("COMPONENT_INITIALIZATION_REQUIRED","NO_WRITE");if(call.action==="service-plan"){await observe();return ok(await runLoginService("service-plan",home,void 0,"EXPLICIT_RECOVERY"))}if(call.action==="install-plan"||call.action==="rollback-plan"){if(call.source==="SIGNED_CHANNEL"&&call.version==="latest")fail("EXACT_RELEASE_VERSION_REQUIRED","NO_WRITE");return withComponentLock(home,async()=>{const before=await observe();if(call.action==="rollback-plan"&&(call.version===before.installedVersion||!await manager.ledger.hadCompletedVersion(call.version)))fail("COMPONENT_ROLLBACK_VERSION_UNAVAILABLE","NO_WRITE");const paths=InstalledToolPathsSchema.safeParse(call.tools);const tools=paths.success?await captureInstalledTools(paths.data):call.tools;return ok(call.source==="SIGNED_CHANNEL"?await manager.prepare(call.version,tools):await manager.prepareBundled(call.version,tools))})}if(call.action==="observe-original")return withComponentLock(home,async()=>{const original=await receipts.find(call.requestId);if(!original)fail("COMPONENT_RECEIPT_NOT_FOUND");if(original.phase!=="SENDING")return ok(original);const current=await observe();const command=original.command;const observed=command.expectedRevision===current.installationRevision&&["start","stop","recover","service-enable"].includes(command.action)&&outcomeObserved(command,current);return ok(await receipts.finish(original,{phase:observed?"COMPLETE":"DEGRADED",outcome:observed?"OBSERVED":"UNKNOWN",reasonCode:observed?"COMPONENT_STATE_OBSERVED":"COMPONENT_ORIGINAL_OUTCOME_UNKNOWN",installationRevision:current.installationRevision,runningVersion:current.runningVersion}))});return withComponentLock(home,async()=>{const replay=await receipts.original(call);if(replay)return acknowledged(replay);const before=await observe();if(call.expectedRevision!==before.installationRevision)fail("REVISION_CONFLICT","NO_WRITE");if(call.action==="recover"&&before.capabilityMismatch)return{exitCode:2,output:{semanticStatus:"CAPABILITY_UNAVAILABLE",error:{code:"CAPABILITY_VERSION_MISMATCH",outcome:"NO_WRITE",details:before.capabilityMismatch}}};if(before.liveness.state==="UNKNOWN"||before.loginService==="UNKNOWN")fail("COMPONENT_OWNERSHIP_UNCONFIRMED","NO_WRITE");if(before.loginService==="INCOMPLETE"&&call.action!=="stop")fail("COMPONENT_SERVICE_NEEDS_STOP","NO_WRITE");const{latest}=await receipts.snapshot();if(call.action==="recover"&&before.readiness.state!=="READY"&&latest?.command.action==="recover"&&latest.phase==="DEGRADED")fail("COMPONENT_RECOVERY_EXHAUSTED","NO_WRITE");const original=await receipts.begin(call,before.runningVersion);let reasonCode,after,phase="DEGRADED";try{reasonCode=await applyComponentCommand(manager,call,before);after=await observe();if(outcomeObserved(call,after))phase="COMPLETE";else reasonCode=call.action==="recover"?"COMPONENT_RESTART_INEFFECTIVE":"COMPONENT_RESULT_UNCONFIRMED"}catch(error){reasonCode=reason(error);after=await observe().catch(()=>before)}return acknowledged(await receipts.finish(original,{phase,outcome:phase==="COMPLETE"?"SUCCESS":"UNKNOWN",reasonCode,installationRevision:after.installationRevision,runningVersion:after.runningVersion}))})}export{runHostComponent};
@@ -0,0 +1 @@
1
+ import{HostComponentRequestSchema}from"./chunk-ZYXHPTT2.js";import{HostEnrollmentRequestSchema}from"./chunk-LTNJ45JP.js";import"./chunk-WLQMICJN.js";import"./chunk-DMA53YVU.js";import"./chunk-PQCA4X5H.js";import"./chunk-H4FH6STZ.js";import"./chunk-MZWEFYHE.js";import"./chunk-FFXSXE3G.js";import"./chunk-ETK7GYCB.js";import"./chunk-SM2I7TJ3.js";import"./chunk-LDBXGRCQ.js";import"./chunk-2S7FI3HF.js";import"./chunk-DLW42PJ6.js";import"./chunk-WTJVS2VS.js";import"./chunk-TT7IA5HB.js";import{z}from"zod";var protocol="NVS_EXTERNAL_HOST_V1";var requests={component:HostComponentRequestSchema,enrollment:HostEnrollmentRequestSchema};function hostOverview(deviceActions){return{exitCode:0,output:{protocol,agentRuntime:"EXTERNAL",commands:["host component --input <private-json|-> [--home <private-parent-home>]","host enrollment --input <private-json|-> [--home <component-home>]","host device --input <json|-> [--home <private-client-home>]"],actions:[...deviceActions],help:["host component help [<action>]","host enrollment help [<action>]"],guidance:"Use workspace_caller and workspace_status on your tenant MCP for component scope. Use host component help preflight for the read-only host check for library, preview or final. Prepare enrollment with authority OAUTH_AGENT and send its invoke on the same MCP. Pass the ticket by private input and read the original lookup after an interrupted reply."}}}function hostActionHelp(command,action){const request=requests[command],options=request.shape.call.options;const actions=options.map(option=>option.shape.action.value);const selected=action&&options.find(option=>option.shape.action.value===action);const invalid=action!==void 0&&!selected;return{exitCode:invalid?2:0,output:{protocol,command:"host "+command,actions,help:"host "+command+" help <action>",...invalid&&{semanticStatus:"INVALID_INPUT",error:{code:"INVALID_INPUT",outcome:"NO_WRITE"}},...selected&&{action,inputSchema:z.toJSONSchema(z.strictObject({scope:request.shape.scope,call:selected}),{io:"input"})}}}}export{hostActionHelp,hostOverview};
@@ -0,0 +1 @@
1
+ import{HostEnrollmentRequestSchema,runHostEnrollment}from"./chunk-LTNJ45JP.js";import{runDesktopDeviceRequest}from"./chunk-PQCA4X5H.js";import"./chunk-H4FH6STZ.js";import"./chunk-MZWEFYHE.js";import"./chunk-FFXSXE3G.js";import"./chunk-ETK7GYCB.js";import{DesktopDeviceRequestSchema}from"./chunk-SM2I7TJ3.js";import"./chunk-LDBXGRCQ.js";import{readInput}from"./chunk-QGK6G6YS.js";import"./chunk-2S7FI3HF.js";import{LocalClientError}from"./chunk-DLW42PJ6.js";import"./chunk-WTJVS2VS.js";import"./chunk-TT7IA5HB.js";import{homedir}from"node:os";import{join,resolve}from"node:path";var actions=new Set(["inspect","enroll","revoke","dispatch","record","refused","prove","connect","connection-recover","media-validation-capability","media-processing-capability"]);var helpFlags=["help","--help"];async function runHostCli(argv,stdin=process.stdin){let entered=false;let mutation=false;try{if(!argv.length||argv.length===1&&helpFlags.includes(argv[0]))return(await import("./host-help-VNLA3YOV.js")).hostOverview(actions);const[command,...rest]=argv,options=new Map;if(command!=="device"&&command!=="enrollment"&&command!=="component")throw Error();if(command!=="device"&&rest.length<=2&&helpFlags.includes(rest[0]??""))return(await import("./host-help-VNLA3YOV.js")).hostActionHelp(command,rest[1]);for(let i=0;i<rest.length;i+=2){const key=rest[i],value=rest[i+1];if(!key||!["--input","--home"].includes(key)||!value||value.startsWith("--")||options.has(key))throw Error();options.set(key,value)}const file=options.get("--input");if(!file)throw Error();const home=resolve(options.get("--home")??process.env.NATIVESTUDIO_CLIENT_HOME??join(homedir(),".nativestudio/client"));const raw=await readInput(file,stdin,command!=="device");if(command==="component"){const{HostComponentRequestSchema}=await import("./component-contract-2JHTRTOB.js");const request2=HostComponentRequestSchema.parse(raw);entered=true;mutation=!["status","preflight","receipt","service-plan"].includes(request2.call.action);return await(await import("./host-component-ZYQ5ETVL.js")).runHostComponent(home,request2)}if(command==="enrollment"){const request2=HostEnrollmentRequestSchema.parse(raw);entered=true;mutation=request2.call.action!=="inspect";return{exitCode:0,output:await runHostEnrollment(home,request2)}}const request=DesktopDeviceRequestSchema.parse(raw);if(!actions.has(request.call.action))throw Error();mutation=!["inspect","media-validation-capability","media-processing-capability"].includes(request.call.action);entered=true;const output=await runDesktopDeviceRequest(home,request,{allowedPendingKinds:["ENROLL","REVOKE_DEVICE"]});return{exitCode:0,output}}catch(error){const code=error instanceof LocalClientError?error.code:!entered?"INVALID_INPUT":"INTERNAL_OPERATIONAL_FAILURE";const knownRefusal=error instanceof LocalClientError&&error.outcome==="NO_WRITE";const uncertain=!knownRefusal&&(entered&&mutation&&code!=="DEVICE_COMMAND_UNSUPPORTED"||/(?:UNKNOWN|RECOVERY_REQUIRED|PROOF_UNAVAILABLE)/.test(code)||code==="INTERNAL_OPERATIONAL_FAILURE");return{exitCode:2,output:{semanticStatus:!uncertain&&["INVALID_INPUT","REVISION_CONFLICT"].includes(code)?code:"BLOCKED",error:{code,outcome:uncertain?"UNKNOWN":"NO_WRITE"}}}}}export{runHostCli};
@@ -0,0 +1 @@
1
+ import{profileHttpOrigin}from"./chunk-7P2NA6TH.js";import"./chunk-27KI24GK.js";import"./chunk-7I7ARCY7.js";import"./chunk-DLW42PJ6.js";import"./chunk-WTJVS2VS.js";import"./chunk-KOCUZ3AE.js";import"./chunk-TT7IA5HB.js";export{profileHttpOrigin};
@@ -0,0 +1 @@
1
+ import{localCaller}from"./chunk-X5MVC46N.js";import{renderConnection}from"./chunk-3RNDOAQI.js";import"./chunk-VYCNG6TR.js";import{DesktopLibraryImportSeedSchema,prepareDesktopLibraryImport,runDesktopLibraryImport,runDesktopLibraryRequest}from"./chunk-DMA53YVU.js";import"./chunk-MZWEFYHE.js";import"./chunk-FFXSXE3G.js";import{DesktopDeviceRecords}from"./chunk-ETK7GYCB.js";import"./chunk-SM2I7TJ3.js";import"./chunk-LDBXGRCQ.js";import"./chunk-3TOXIJ7K.js";import{readInput}from"./chunk-QGK6G6YS.js";import"./chunk-76E5R3OC.js";import"./chunk-2UYKJ6YN.js";import{LocalDeviceViewSchema,LocalManagementCommandSchema}from"./chunk-2S7FI3HF.js";import"./chunk-7P2NA6TH.js";import"./chunk-27KI24GK.js";import"./chunk-7I7ARCY7.js";import{fail,sha256}from"./chunk-DLW42PJ6.js";import"./chunk-WTJVS2VS.js";import"./chunk-KOCUZ3AE.js";import{NativeStudioSdkError}from"./chunk-TT7IA5HB.js";import{homedir}from"node:os";import{join,resolve,basename}from"node:path";async function libraryImportContext(home,raw,enrollment){const caller=await localCaller({...process.env,NATIVESTUDIO_CLIENT_HOME:home},typeof raw.projectId==="string"?raw.projectId:void 0);if(!caller){if(!["tenantId","projectId","deviceId","ownerKey"].every(key=>raw[key]))fail("ACCOUNT_LOGIN_REQUIRED");return{}}const{serverOrigin,tenantId,principalId,projectId}=caller;const ownerKey=sha256(JSON.stringify([serverOrigin,tenantId,principalId]));const denied=()=>{throw new NativeStudioSdkError("FORBIDDEN","BLOCKED","NO_WRITE")};if(raw.tenantId!==void 0&&raw.tenantId!==tenantId||raw.projectId!==void 0&&raw.projectId!==projectId||raw.ownerKey!==void 0&&raw.ownerKey!==ownerKey)denied();const record=await DesktopDeviceRecords.inspect(home,{origin:serverOrigin,tenantId,principalId});if(record?.device&&(record.device.enrolledByPrincipalId!==principalId||record.device.tenantId!==tenantId))denied();if(record?.pending?.phase==="SENDING")fail("DEVICE_RECEIPT_REQUIRED");let deviceId=record?.device?.deviceId;if(!deviceId&&enrollment!==void 0){const command=LocalManagementCommandSchema.parse(enrollment);if(command.kind!=="ENROLL"||command.input.tenantId!==tenantId)denied();const env={...process.env,NATIVESTUDIO_CLIENT_HOME:home};const c=await renderConnection(env,void 0,false,projectId);try{if(c.scope.profile!==caller.profile||c.scope.resource!==caller.resource)denied();const receipt=await c.studio.call("device.management-receipt",{command});if(!receipt.result)fail("DEVICE_RECEIPT_REQUIRED");const device=LocalDeviceViewSchema.parse(receipt.result);if(device.enrolledByPrincipalId!==principalId||device.tenantId!==tenantId)denied();deviceId=device.deviceId}finally{await c.close().catch(()=>{})}}if(!deviceId)fail("DEVICE_SETUP_REQUIRED");if(raw.deviceId!==void 0&&raw.deviceId!==deviceId)denied();await caller.assertCurrent();return{tenantId,projectId,deviceId,ownerKey,assertCurrent:caller.assertCurrent}}async function runLocalLibrary(argv,stdin){const[action,...args]=argv,flags=new Map;for(let i=0;i<args.length;i+=2){const name=args[i],value=args[i+1];if(!name||!["--home","--input","--file","--enrollment"].includes(name)||!value||value.startsWith("--")||flags.has(name))throw Error();flags.set(name,value)}if(!action||!["import","list","get","read","access","sync","resume-access","import-receipt","usage"].includes(action)||!flags.has("--input")||flags.get("--input")==="-"&&flags.get("--enrollment")==="-"||action!=="import"&&(flags.has("--file")||flags.has("--enrollment")))throw Error();const home=resolve(flags.get("--home")??process.env.NATIVESTUDIO_CLIENT_HOME??join(homedir(),".nativestudio/client"));const raw=await readInput(flags.get("--input"),stdin);if(action!=="import")return{exitCode:0,output:await runDesktopLibraryRequest(home,{operation:"library",call:{...raw,action}})};const file=flags.get("--file");if(!file)throw Error();const enrollment=flags.has("--enrollment")?await readInput(flags.get("--enrollment"),stdin):void 0;const{assertCurrent,...defaults}=await libraryImportContext(home,raw,enrollment);const seed=DesktopLibraryImportSeedSchema.parse({...defaults,title:basename(file),contentType:"application/octet-stream",...raw});const request=await prepareDesktopLibraryImport({operation:"library-import-prepare",file:resolve(file),seed});await assertCurrent?.();return{exitCode:0,output:await runDesktopLibraryImport(home,request)}}export{runLocalLibrary};
@@ -0,0 +1 @@
1
+ import{loginCommand,runLoginService}from"./chunk-5Y7J2OYL.js";import{prepareInstalledCpuSpeech}from"./chunk-VXYZCCCQ.js";import{connectDevice,generateDeviceKey}from"./chunk-H4FH6STZ.js";import{LocalInstallationManager,captureInstalledTools,ownerClient}from"./chunk-FFXSXE3G.js";import{LocalAgentGrantSchema,NativeStudioLocalDeviceClient,localAgentMediaProposal,localAgentMediaSnapshot,localAgentSnapshotFromContext}from"./chunk-LDBXGRCQ.js";import{readCredential,readInput}from"./chunk-QGK6G6YS.js";import{localCliVersion}from"./chunk-2UYKJ6YN.js";import{EnrollLocalDeviceSchema,LocalManagementCommandSchema,NativeStudioAgentClient,RevokeLocalDeviceSchema,StartLocalFinalRenderSchema,StartLocalPreviewSchema,canonicalLocalJson}from"./chunk-2S7FI3HF.js";import"./chunk-7I7ARCY7.js";import{LocalClientError}from"./chunk-DLW42PJ6.js";import"./chunk-WTJVS2VS.js";import"./chunk-KOCUZ3AE.js";import{NativeStudioSdkError}from"./chunk-TT7IA5HB.js";import{homedir as homedir2}from"node:os";import{join as join2,resolve as resolve2}from"node:path";function preparationGuidance(code){const steps={DEPENDENCY_CHANNEL_REQUIRED:["Read workspace_caller.hostReleases (CLI: call workspace.caller); use its exact configured URL, not an inferred path.","Configure the advertised catalogueUrl/publicKey through local configure; never accept an unsigned catalogue or invent a trust key."],MANAGED_TOOLS_UNAVAILABLE:["This exact signed release has no qualified managed media executables. Install the required tools using the host's authorized package manager or official vendor.","Use local tools-prepare --version <resolved-runtime-version> --input <private-json> with mode INSTALLED and absolute ffmpeg/ffprobe paths. Missing fonts/browser remain separate capabilities."],RELEASE_NOT_PUBLISHED:["Ask the release operator to publish matching exact-version dependencies. Preserve this CLI/Runtime identity; do not substitute another version's bytes."],RELEASE_METADATA_INVALID:["Reject malformed release metadata; ask the operator to check the exact signed catalogue URL. Do not treat a discovery page as a catalogue."],RELEASE_ACCESS_DENIED:["The public download edge denied access. Inspect its safe status; for Cloudflare 1010, identify your actual application with a descriptive User-Agent. Do not disable TLS or copy a browser session."],RELEASE_TIMEOUT:["The read deadline ended. An unknown installation apply must be reconciled from its original plan, never replayed blindly."],RELEASE_SIGNATURE_INVALID:["Reject these bytes. Verify the configured operator URL/public key; do not rotate trust to make verification pass."],RELEASE_EXPIRED:["Ask the operator to renew the approved inventory; never ignore expiry or alter the host clock."],BUNDLED_COMPONENT_RELEASE_MISMATCH:["The catalogue does not match the code/resources inside this CLI. Keep the original installation plan; ask the operator for its matching release."],LOGIN_SERVICE_RUNTIME_UPDATE_REQUIRED:["Activate a Runtime with login startup support through the existing exact-version installation plan."],LOGIN_SERVICE_REPLACE_REQUIRED:["Read local service-status and disable the existing registration using its original fingerprint. Then approve the current service plan."],LOGIN_SERVICE_OS_UNCONFIRMED:["Read local service-status and check the current user's native service manager. Keep the original approval fingerprint for reconciliation."],LOGIN_SERVICE_DISABLE_PENDING:["Read local service-status and complete service-disable using the original fingerprint."]};return steps[code]}import{homedir}from"node:os";import{join,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));const disclosures=["review metadata",...grant.imageDisclosureApproved?["original image pixels"]:[],...grant.mediaDisclosureApproved?["normalized image pixels or sampled video frames and technical audio statistics"]:[]];return{exitCode:0,output:{grant,fingerprint:createHash("sha256").update(canonicalLocalJson(grant)).digest("hex"),note:`Approving this fingerprint permits remote OpenAI inference for these Projects until expiry and allows disclosure of ${disclosures.join(", ")}. Preview does not invoke a model.`}}}const evidence=flags.get("--evidence");if(evidence&&!["IMAGE_PIXELS","METADATA_ONLY","MEDIA"].includes(evidence))throw Error();const manager=await LocalInstallationManager.open(resolve(flags.get("--home")??join(homedir(),".nativestudio","client")));const client=await ownerClient((await manager.configuration()).stateDirectory);const studioFor=tenantId=>new NativeStudioAgentClient({baseUrl:need("--origin"),tenantId,authorization:()=>readCredential(flags,process.env)});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":{const context=await readInput(need("--input"),stdin);output=await client.prepareAgentReview(evidence==="MEDIA"?localAgentMediaSnapshot(context):localAgentSnapshotFromContext(context,evidence==="IMAGE_PIXELS"));break}case"review-image-fetch":{const view=await client.inspectAgentReview(need("--id")),snapshot=view.plan.snapshot;if(!snapshot.image||snapshot.basis.target.kind!=="IMAGE")throw Error();const studio=studioFor(snapshot.basis.scope.tenantId);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-media-fetch":{const view=await client.inspectAgentReview(need("--id"));const{basis,evidence:expected,media}=view.plan.snapshot;if(!expected)throw Error();if(view.evidenceReceipt){output=view;break}if(view.phase!=="PREPARED")throw Error();const source=await studioFor(basis.scope.tenantId).immutableMedia({projectId:basis.scope.projectId,representationId:media.representationId,checksumSha256:media.checksumSha256,byteSize:expected.byteSize});output=await client.stageAgentImage(view.plan.id,source.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=localAgentMediaProposal(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==="library"){mutation=["import","access","resume-access"].includes(rest[0]??"");return await(await import("./library-main-3WWH7UYV.js")).runLocalLibrary(rest,stdin)}if(command==="device-preflight"){for(let i=0;i<rest.length;i+=2){const name=rest[i],value=rest[i+1];if(!name||!["--kind","--home","--project"].includes(name)||!value||value.startsWith("--")||options.has(name))throw Error();options.set(name,value)}return(await import("./device-preflight-GTQ67H7C.js")).devicePreflight(options.get("--kind"),{...process.env,...options.has("--home")&&{NATIVESTUDIO_CLIENT_HOME:resolve2(options.get("--home"))}},options.get("--project"))}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|revoke-device|preview|final|receipt --origin <cloud-origin> --token-file <member-token> --input <json>","connect --input <private-device-config>","version","install|update-prepare --version <exact|latest> \u2014 uses this CLI's bundled code; update CLI first for newer code; latest resolves once into an exact saved plan","speech-prepare --input <json with optional voiceIds> \u2014 prepare pinned CPU speech resources and return the original tools update plan","tools-prepare --version <exact|latest> --input <private-json with mode MANAGED or INSTALLED, exact ffmpeg/ffprobe paths, optional compositionBrowser and captionAssetsDirectory>","update-check","update-reject --version <exact>","update-apply --plan <uuid> --approve <fingerprint>","update-reconcile --plan <uuid> --approve <fingerprint>","start","status","service-plan|service-status [--home <private-client-home>] \u2014 inspect optional user-login startup without changing it","service-enable|service-start|service-disable --approve <service-fingerprint> [--home <private-client-home>] \u2014 register, start or remove this installation's user-login service","device-preflight --kind preview|final|<processor-kind> [--project <uuid>] [--home <private-client-home>] \u2014 read current setup and action qualification","doctor","stop","grant --input <scopes-expiry-json> --output <new-private-connector>","mcp [--connector <private-file>] [--with-library]","library import|list|get|read|access|sync|resume-access|import-receipt|usage --input <json|-> [--file <exact-media>] [--home <client-home>] \u2014 private Owner library; import never uploads","agent-grant-plan|agent-probe|agent-grant|agent-revoke \u2014 installed Codex CLI with explicitly authorized remote OpenAI inference","review-prepare --input <private-context> [--evidence METADATA_ONLY|IMAGE_PIXELS|MEDIA]","review-media-fetch --id <draft> --origin <cloud-origin> --token-file <member-token> \u2014 read exact stored bytes for a MEDIA draft","review-image-fetch|review-inspect|review-proposal \u2014 use --id <draft>","review-start --id <draft> --revision <current> --approve <plan-fingerprint>"],note:"Release check and update planning only inspect metadata. speech-prepare explicitly fetches optional CPU resources. Apply uses the exact saved fingerprint. 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);const action=required("--action");const tenantId=action==="receipt"?LocalManagementCommandSchema.parse(input).input.tenantId:input.tenantId;if(typeof tenantId!=="string")throw Error();const client=new NativeStudioLocalDeviceClient({baseUrl:required("--origin"),tenantId,authorization:()=>readCredential(new Map([["--token-file",required("--token-file")]]),process.env)});const output2=action==="enroll"?await client.enroll(EnrollLocalDeviceSchema.parse(input)):action==="revoke-device"?await client.revokeDevice(RevokeLocalDeviceSchema.parse(input)):action==="preview"?await client.startPreview(StartLocalPreviewSchema.parse(input)):action==="final"?await client.startFinal(StartLocalFinalRenderSchema.parse(input)):action==="receipt"?await client.managementReceipt(LocalManagementCommandSchema.parse(input)):void 0;if(!output2)throw Error();return{exitCode:0,output:output2}}const home=resolve2(options.get("--home")??process.env.NATIVESTUDIO_CLIENT_HOME??join2(homedir2(),".nativestudio","client"));if(loginCommand(command)){mutation=["service-enable","service-start","service-disable"].includes(command);if([...options.keys()].some(key=>key!=="--home"&&(!mutation||key!=="--approve")))throw Error();return{exitCode:0,output:await runLoginService(command,home,options.get("--approve"))}}const manager=await LocalInstallationManager.open(home);let output;mutation=["configure","speech-prepare","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.prepareBundled(required("--version"));break;case"speech-prepare":output=await prepareInstalledCpuSpeech(manager,await readInput(required("--input"),stdin));break;case"tools-prepare":{const raw=await readInput(required("--input"),stdin);const choice=raw.mode==="INSTALLED"?await captureInstalledTools(raw):raw;output=await manager.prepareBundled(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",...preparationGuidance(known)?{nextSteps:preparationGuidance(known)}:{},error:{code:known,outcome:e instanceof NativeStudioSdkError?e.outcome:mutation&&!["USER_APPROVAL_REQUIRED","PLAN_CHANGED","REVISION_CONFLICT","INSTALL_REQUIRED","CONFIGURATION_REQUIRED","DEVICE_CONNECTION_REQUIRED","LOGIN_SERVICE_PLAN_CHANGED","LOGIN_SERVICE_REPLACE_REQUIRED","LOGIN_SERVICE_DISABLE_PENDING","LOGIN_SERVICE_RUNTIME_UPDATE_REQUIRED","LOGIN_SERVICE_PLATFORM_UNSUPPORTED","LOGIN_SERVICE_USER_REQUIRED"].includes(known)?"UNKNOWN":"NO_WRITE"}}}}}export{runLocalCli};
@@ -0,0 +1 @@
1
+ import{workspaceCaller}from"./chunk-X5MVC46N.js";import{StdioLines}from"./chunk-JFC6ZIGA.js";import"./chunk-3RNDOAQI.js";import"./chunk-VYCNG6TR.js";import{LocalMcpTools,localTools}from"./chunk-4AD4PNUX.js";import{desktopDeviceConnector}from"./chunk-ETK7GYCB.js";import"./chunk-SM2I7TJ3.js";import{LocalMcpFailureSchema}from"./chunk-LDBXGRCQ.js";import"./chunk-3TOXIJ7K.js";import"./chunk-QGK6G6YS.js";import"./chunk-76E5R3OC.js";import{localCliVersion}from"./chunk-2UYKJ6YN.js";import"./chunk-2S7FI3HF.js";import"./chunk-7P2NA6TH.js";import"./chunk-27KI24GK.js";import"./chunk-7I7ARCY7.js";import"./chunk-DLW42PJ6.js";import"./chunk-WTJVS2VS.js";import"./chunk-KOCUZ3AE.js";import{NativeStudioSdkError}from"./chunk-TT7IA5HB.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 selectedConnector(home,env){const caller=await workspaceCaller(env);if(!caller)throw new NativeStudioSdkError("AUTHORIZATION_REQUIRED","BLOCKED","NO_WRITE");return desktopDeviceConnector(home,{origin:caller.serverOrigin,tenantId:caller.tenantId,principalId:caller.principalId})}async function serveLocalMcp(tools,input,output){const identity=await localCliVersion();const visible=[...tools.names??Object.keys(localTools).filter(name=>!name.startsWith("local_library_"))].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. Use nvs mcp for workspace, Project and render business actions. Cloud owns native admission. 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(name=>tools.schema(name))}}else if(r.method==="tools/call"){const name=r.params?.name;if(typeof name!=="string"||!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;const library=argv.includes("--with-library");if(argv.filter(k=>k==="--with-library").length>1)throw Error();argv=argv.filter(k=>k!=="--with-library");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 home=resolve(flags.get("--home")??process.env.NATIVESTUDIO_CLIENT_HOME??join(homedir(),".nativestudio","client"));const env={...process.env,NATIVESTUDIO_CLIENT_HOME:home};const connector=flags.get("--connector")??await selectedConnector(home,env);const tools=await LocalMcpTools.open(resolve(connector),home,library);const service=await serveLocalMcp(tools,process.stdin,process.stdout);return await service.closed}catch{process.stderr.write("Local MCP needs a current device connector. Use nvs mcp for workspace, Project and render business tools.\n");return 2}}export{runLocalMcp,serveLocalMcp};
@@ -0,0 +1,2 @@
1
+ import{loginLink,openLoginBrowser}from"./chunk-OW6R4MAQ.js";import{readInput}from"./chunk-QGK6G6YS.js";import{NativeStudioAccountClient,accountError,accountServerOrigin,clientHome,connectionStatus,defaultConnection,readAccount,requireAccount,saveAccount,withAccountLock}from"./chunk-27KI24GK.js";import"./chunk-7I7ARCY7.js";import{write}from"./chunk-DLW42PJ6.js";import"./chunk-WTJVS2VS.js";import"./chunk-KOCUZ3AE.js";import{NativeStudioSdkError}from"./chunk-TT7IA5HB.js";var aliases={find:"studio.start",overview:"studio.navigate",next:"studio.navigate",resume:"operation.get",skill:"workspace.caller"};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"},skill:{}};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"&&kind!=="skill")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))};const result=await call(forwarded,input?stdin:generated());return kind==="skill"&&result.exitCode===0?{...result,output:result.output.skill}:result}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:account.workspaceId===id?account.projectId:null,epoch:account.workspaceId===id?account.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});return{exitCode:0,output:{semanticStatus:"SUCCESS",project:value.project,connectionPage:`${account.serverOrigin}/projects/${projectId}/settings`,nextSteps:["Use the existing workspace connection; run nvs connect if this workspace is not connected.","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("./connect-7TJDWXV4.js")).runConnect(argv,environment);if(argv[0]==="login")return await runAccountLogin(argv,environment);if(argv[0]==="render")return await(await import("./render-main-6Z3DKCWL.js")).renderCommand(argv.slice(1),environment,stdin);if(argv[0]==="devices")return await(await import("./devices-main-2BMCANKU.js")).devicesCommand(argv.slice(1),environment,stdin);if(argv[0]==="import")return await(await import("./source-import-PNMCMTK7.js")).importSourceCommand(argv.slice(1),environment,stdin);if(AccountCommands.has(argv[0]??"")){const business=await(await import("./workspace-main-QX5JGEMR.js")).workspaceCommand(argv,environment);return business??await runAccountCommand(argv,environment)}if(argv.length===1&&argv[0]==="status")return await connectionStatus(environment);if(argv[0]==="series")return await(await import("./series-main-FBERVYWG.js")).runSeriesCli(argv.slice(1),stdin,(args2,input2)=>runRemoteCli(args2,environment,input2));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-RPME2XYB.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 (authorizes the selected workspace once; supports its Projects and devices)","nvs status","nvs skill \u2014 read the configured SKILL download URL through the existing connection","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 <workspace-connection-url>] \u2014 authorize the workspace once for its Projects and devices","status","observe --input <scope-json|-> [--max-polls <1..1000>] [--timeout-ms <1..1800000>] \u2014 bounded JSON Lines feedback/events; Ctrl-C ends observation only","skill \u2014 read the configured SKILL download URL/status; no automatic download","find --query <text> [--project <uuid>]","overview | next --production <uuid> [--goal <text>]","resume --production <uuid> --operation <op_original>","series help \u2014 list and read project series, publish, bind and recover original receipts","capabilities [groups | search --query <text> --group <group> | describe --tool <name>]","call <operation> with --capability-version <sha256> \u2014 require the described definition on member MCP","devices inventory [--device <uuid>] [--after <uuid>] [--limit <1..50>] [--mcp-url <workspace-url> --token-file <private-file>] \u2014 read Workspace device registration and connection facts; no project required","devices list --kind preview|final|library|<processor-kind> [--project <uuid>] [--device <uuid>] [--mcp-url <workspace-url> --token-file <private-file>] \u2014 read candidates for this Project task; connection alone does not imply eligibility","devices status --input <json|-> \u2014 read an owned node by deviceId on the saved tenant connection","devices enrollment-issue|enrollment-lookup --input <json|-> \u2014 issue or read the OAuth agent's original enrollment","devices enroll|revoke|receipt --input <json|-> \u2014 uses the saved tenant OAuth and original native command","render preview|final --production <uuid> --request <stable-uuid> [--project <uuid>] [--device <uuid>] [--validation-mode TENANT_TRUSTED_VALIDATOR] \u2014 tenant device only; saves original receipt","render eligibility --kind preview|final --production <uuid> [--project <uuid>] [--device <uuid>] \u2014 read current Production basis and device qualification","render receipt --kind preview|final --production <uuid> --request <original-uuid> [--project <uuid>] \u2014 query the original native admission without resubmitting","render receipt --input <private-json|-> \u2014 read a NVS_RENDER_RECEIPT_V1 handoff with the same authorized grant","render status|download --kind preview|final --production <uuid> --render <uuid> [--project <uuid>] [--output <file>]","mcp \u2014 connect the Agent using the private saved connection","local help \u2014 installed Runtime, scoped local MCP, explicit exact-version updates","host help \u2014 own an execution component, enroll through the existing MCP session and inspect per-action JSON schemas offline"],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|->","import project|original --input <intent.json|-> --file <media> --tenant <uuid> --origin <https-origin> --token-file <private-file>"],note:"No automatic write retry. Transport abort does not cancel native Jobs."}};const{CapabilityVersionSchema,NativeStudioMcpClient,sdkOperations,sdkMcpTools,sdkCarrierDifferences,assertCarrierCoverage}=await import("./src-7HSJFRVQ.js");if(argv.length===1&&argv[0]==="operations"){assertCarrierCoverage(sdkOperations,sdkCarrierDifferences);return{exitCode:0,output:{operations:Object.entries(sdkOperations).map(([name2,spec])=>({name:name2,readOnly:spec.readOnly??null,http:spec.request!==null,mcp:sdkMcpTools[name2],carrierDifference:Object.hasOwn(sdkCarrierDifferences,name2)?sdkCarrierDifferences[name2]:null}))}}}const[command,name,...args]=argv;if(command!=="call"||!name||!Object.hasOwn(sdkOperations,name))throw Error();if(name==="rough-cut.media-ticket"||name==="final-render.media-ticket")throw Error();const options=new Map;const allowed=["--input","--tenant","--origin","--mcp-url","--token-env","--token-file","--profile","--transport","--capability-version"];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)}if(!options.has("--input"))throw Error();const key=name;const capabilityVersion=CapabilityVersionSchema.optional().parse(options.get("--capability-version"));const httpOnly=sdkMcpTools[key]===null;const versionUnavailable=()=>new NativeStudioSdkError("CAPABILITY_UNAVAILABLE","CAPABILITY_UNAVAILABLE","NO_WRITE");if(capabilityVersion&&(httpOnly||options.has("--origin")||options.get("--transport")==="http"))throw versionUnavailable();const privateInput=["provider.configure","webhook.configure","webhook.secret.prepare"].includes(key);await defaultConnection(options,environment,true);const input=await readInput(options.get("--input"),stdin,privateInput);const output=await(await import("./remote-client-25Z65VJU.js")).withRemoteClient(options,environment,httpOnly,studio=>{const command2=input;if(!capabilityVersion)return studio.call(key,command2);if(!(studio instanceof NativeStudioMcpClient))throw versionUnavailable();return studio.call(key,command2,{capabilityVersion})});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>"],CONNECTION_ACCOUNT_MISMATCH:["nvs whoami","nvs workspaces","nvs project --id <project-id>","nvs connect --mcp-url <workspace-connection-url>"],ACCOUNT_PROJECT_SELECTION_REQUIRED:["nvs whoami","nvs workspace --id <workspace-id>","nvs project --id <project-id>"],AUTHORIZED_CONNECTION_NOT_SELECTED:["Authorization may exist. Inspect Web grants; select the intended account/workspace 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?.issues.length?{issues:e.issues}:{},...e?.capabilityMismatch?{details:e.capabilityMismatch}:{}},...e&&accountRecovery[e.code]?{nextSteps:accountRecovery[e.code]}:{},...["TENANT_CONNECTION_REQUIRED","OAUTH_OUTCOME_UNKNOWN"].includes(e?.code??"")?{nextSteps:["nvs connect --mcp-url <workspace-connection-url>","nvs help"]}:{}}}}}export{runRemoteCli};
@@ -0,0 +1 @@
1
+ import{connectRemoteMcp}from"./chunk-76E5R3OC.js";import"./chunk-2UYKJ6YN.js";import"./chunk-2S7FI3HF.js";import"./chunk-WTJVS2VS.js";import"./chunk-KOCUZ3AE.js";import"./chunk-TT7IA5HB.js";export{connectRemoteMcp};
@@ -0,0 +1 @@
1
+ import{profileAuthorization,runOAuthCommand}from"./chunk-3TOXIJ7K.js";import"./chunk-QGK6G6YS.js";import"./chunk-7I7ARCY7.js";import"./chunk-DLW42PJ6.js";import"./chunk-KOCUZ3AE.js";import"./chunk-TT7IA5HB.js";export{profileAuthorization,runOAuthCommand};