@nativestudio/cli 0.3.0-rc.20 → 0.3.0-rc.27

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 (201) hide show
  1. package/COMPATIBILITY.json +11 -11
  2. package/components/runtime.json +7 -7
  3. package/components/runtime.tgz +0 -0
  4. package/dist/_chunks/backup-retirement-5OTAYZYN.js +1 -0
  5. package/dist/_chunks/caller-DPHTMOBN.js +1 -0
  6. package/dist/_chunks/{chunk-MLZ3ZPGU.js → chunk-24ZFLWWU.js} +1 -1
  7. package/dist/_chunks/chunk-25WUWVDK.js +1 -0
  8. package/dist/_chunks/{chunk-QGK6G6YS.js → chunk-4UQRT3ZH.js} +1 -1
  9. package/dist/_chunks/chunk-6MYLFBLH.js +1 -0
  10. package/dist/_chunks/chunk-6YVGVNEH.js +1 -0
  11. package/dist/_chunks/{chunk-4PAVWOPA.js → chunk-7TXIHIZ5.js} +1 -1
  12. package/dist/_chunks/chunk-A3MJERGH.js +1 -0
  13. package/dist/_chunks/{chunk-DLW42PJ6.js → chunk-AZQLZA47.js} +1 -1
  14. package/dist/_chunks/{chunk-QE7O57PQ.js → chunk-BNGPPUA3.js} +1 -1
  15. package/dist/_chunks/chunk-CBJIFAHD.js +1 -0
  16. package/dist/_chunks/chunk-CUCC4RFF.js +1 -0
  17. package/dist/_chunks/{chunk-GLAF74UU.js → chunk-DBOQPJLY.js} +1 -1
  18. package/dist/_chunks/chunk-DEXSJABJ.js +1 -0
  19. package/dist/_chunks/chunk-EOWXXTEF.js +1 -0
  20. package/dist/_chunks/chunk-EPH3TRYV.js +1 -0
  21. package/dist/_chunks/chunk-EYOGMJW2.js +1 -0
  22. package/dist/_chunks/{chunk-LBK42NHW.js → chunk-FRZDYDOP.js} +1 -1
  23. package/dist/_chunks/chunk-IKJ6VNJ6.js +1 -0
  24. package/dist/_chunks/chunk-ISPIV2P6.js +1 -0
  25. package/dist/_chunks/chunk-IYYCCA44.js +1 -0
  26. package/dist/_chunks/chunk-KAW7T5TR.js +1 -0
  27. package/dist/_chunks/chunk-KGS6SI5Y.js +1 -0
  28. package/dist/_chunks/chunk-LNKE3Z3X.js +1 -0
  29. package/dist/_chunks/{chunk-XUSVNPR5.js → chunk-LRIVN74V.js} +1 -1
  30. package/dist/_chunks/chunk-LVVSTKDW.js +1 -0
  31. package/dist/_chunks/chunk-LZAC64FB.js +1 -0
  32. package/dist/_chunks/chunk-M32FI2OA.js +1 -0
  33. package/dist/_chunks/chunk-N4ORSVTY.js +1 -0
  34. package/dist/_chunks/{chunk-KOCUZ3AE.js → chunk-NEZ7IY5E.js} +1 -1
  35. package/dist/_chunks/{chunk-K35CWLDH.js → chunk-NW3ODW7Y.js} +1 -1
  36. package/dist/_chunks/chunk-NX4JWZWV.js +1 -0
  37. package/dist/_chunks/chunk-PC54RQIE.js +1 -0
  38. package/dist/_chunks/chunk-Q7MTMC6D.js +1 -0
  39. package/dist/_chunks/chunk-QCBLU6D6.js +1 -0
  40. package/dist/_chunks/chunk-QLHMJUBH.js +1 -0
  41. package/dist/_chunks/{chunk-D74NHT4I.js → chunk-RASQZMYI.js} +2 -2
  42. package/dist/_chunks/chunk-RRYZZBXN.js +1 -0
  43. package/dist/_chunks/chunk-SCLI4ALP.js +1 -0
  44. package/dist/_chunks/chunk-SCOSFTMM.js +1 -0
  45. package/dist/_chunks/chunk-UFUFQA5U.js +1 -0
  46. package/dist/_chunks/chunk-UOYNCE7I.js +1 -0
  47. package/dist/_chunks/{chunk-OW6R4MAQ.js → chunk-USOV7NK4.js} +1 -1
  48. package/dist/_chunks/chunk-VJ4SCIR5.js +1 -0
  49. package/dist/_chunks/chunk-VKXFHOAR.js +1 -0
  50. package/dist/_chunks/chunk-VXANXYQL.js +1 -0
  51. package/dist/_chunks/chunk-XMZKBILZ.js +1 -0
  52. package/dist/_chunks/chunk-Z44SK6DZ.js +1 -0
  53. package/dist/_chunks/component-contract-B6VKGV2V.js +1 -0
  54. package/dist/_chunks/component-preflight-FYYYXV6C.js +1 -0
  55. package/dist/_chunks/connect-75RAY2SE.js +1 -0
  56. package/dist/_chunks/device-management-JGV4YU7S.js +1 -0
  57. package/dist/_chunks/device-preflight-ZPWOMGHI.js +1 -0
  58. package/dist/_chunks/device-provider-inspection-C4IRVW3V.js +1 -0
  59. package/dist/_chunks/devices-inventory-OAY2HON2.js +1 -0
  60. package/dist/_chunks/devices-main-6PDXFRE2.js +1 -0
  61. package/dist/_chunks/files-G2HINGMA.js +1 -0
  62. package/dist/_chunks/host-component-W5DIBO65.js +1 -0
  63. package/dist/_chunks/host-help-AYTWACIM.js +1 -0
  64. package/dist/_chunks/host-main-E34OH232.js +1 -0
  65. package/dist/_chunks/http-profile-BFWO2A2T.js +1 -0
  66. package/dist/_chunks/library-main-BDS4ANNF.js +1 -0
  67. package/dist/_chunks/local-main-EF3Y6EHU.js +1 -0
  68. package/dist/_chunks/local-mcp-ME7ZQBUT.js +1 -0
  69. package/dist/_chunks/main-7Q5Y5MVK.js +2 -0
  70. package/dist/_chunks/mcp-VEJ6GVUK.js +1 -0
  71. package/dist/_chunks/model-cleanup-22VY6NWS.js +1 -0
  72. package/dist/_chunks/model-management-RZ4LQYMW.js +1 -0
  73. package/dist/_chunks/model-plan-retirement-4V2J3AUA.js +1 -0
  74. package/dist/_chunks/model-retention-F4WNSTJO.js +1 -0
  75. package/dist/_chunks/model-slot-retirement-KL6MVDGL.js +1 -0
  76. package/dist/_chunks/oauth-Z26E4LJQ.js +1 -0
  77. package/dist/_chunks/observe-entry-ZV26WLCP.js +1 -0
  78. package/dist/_chunks/provider-change-U34UP6ER.js +1 -0
  79. package/dist/_chunks/remote-client-6F6KRJA6.js +1 -0
  80. package/dist/_chunks/render-main-ID5JWWKY.js +1 -0
  81. package/dist/_chunks/source-import-YW6YEMEN.js +1 -0
  82. package/dist/_chunks/src-36KAJDK4.js +1 -0
  83. package/dist/_chunks/stdio-main-YR5TITX2.js +1 -0
  84. package/dist/_chunks/workspace-main-ZFR7ZY3R.js +1 -0
  85. package/dist/_types/cli/local/desktop-contract.d.ts +349 -40
  86. package/dist/_types/cli/local/desktop-device-contract.d.ts +89 -78
  87. package/dist/_types/cli/local/desktop-device-owner.d.ts +14 -14
  88. package/dist/_types/cli/local/desktop-device-state.d.ts +13 -8
  89. package/dist/_types/cli/local/desktop-owner.d.ts +130 -30
  90. package/dist/_types/cli/local/ledger.d.ts +285 -0
  91. package/dist/_types/cli/local/lifecycle-gates.d.ts +8 -0
  92. package/dist/_types/cli/local/manager.d.ts +11 -1107
  93. package/dist/_types/cli/local/mcp-tools.d.ts +3 -0
  94. package/dist/_types/contracts/artifact.d.ts +2 -0
  95. package/dist/_types/contracts/component-status.d.ts +9 -0
  96. package/dist/_types/contracts/device-openai-asr.d.ts +479 -0
  97. package/dist/_types/contracts/device-render.d.ts +6 -0
  98. package/dist/_types/contracts/external-agent-access.d.ts +7 -0
  99. package/dist/_types/contracts/index.d.ts +3 -0
  100. package/dist/_types/contracts/interface/media-output.d.ts +4 -1
  101. package/dist/_types/contracts/interface/operation.d.ts +103 -0
  102. package/dist/_types/contracts/interface/production-snapshot.d.ts +64 -0
  103. package/dist/_types/contracts/interface/query.d.ts +63 -0
  104. package/dist/_types/contracts/lifecycle-event-projections.d.ts +2 -2
  105. package/dist/_types/contracts/local-execution/backup-retirement.d.ts +162 -0
  106. package/dist/_types/contracts/local-execution/claim-resolution.d.ts +1470 -0
  107. package/dist/_types/contracts/local-execution/components.d.ts +1 -1
  108. package/dist/_types/contracts/local-execution/cpu-preparation.d.ts +23 -0
  109. package/dist/_types/contracts/local-execution/credential-request.d.ts +20 -0
  110. package/dist/_types/contracts/local-execution/external-generation.d.ts +59 -2
  111. package/dist/_types/contracts/local-execution/index.d.ts +12 -0
  112. package/dist/_types/contracts/local-execution/ipc.d.ts +27 -0
  113. package/dist/_types/contracts/local-execution/library-command.d.ts +303 -5
  114. package/dist/_types/contracts/local-execution/library-result.d.ts +217 -3
  115. package/dist/_types/contracts/local-execution/lifecycle.d.ts +35 -0
  116. package/dist/_types/contracts/local-execution/local-navigation.d.ts +3 -0
  117. package/dist/_types/contracts/local-execution/management.d.ts +12 -12
  118. package/dist/_types/contracts/local-execution/model-cleanup.d.ts +60 -0
  119. package/dist/_types/contracts/local-execution/model-inspection.d.ts +365 -0
  120. package/dist/_types/contracts/local-execution/openai-asr.d.ts +105 -0
  121. package/dist/_types/contracts/local-execution/openai-realtime-speech.d.ts +151 -0
  122. package/dist/_types/contracts/local-execution/preview.d.ts +15 -4
  123. package/dist/_types/contracts/local-execution/processor-capability.d.ts +6 -0
  124. package/dist/_types/contracts/local-execution/processor-direct.d.ts +140 -4
  125. package/dist/_types/contracts/local-execution/processor-outcomes.d.ts +145 -0
  126. package/dist/_types/contracts/local-execution/processor-recipes.d.ts +163 -3
  127. package/dist/_types/contracts/local-execution/processor.d.ts +2422 -322
  128. package/dist/_types/contracts/local-execution/project-source-direct.d.ts +1 -0
  129. package/dist/_types/contracts/local-execution/provider-inspection.d.ts +58 -0
  130. package/dist/_types/contracts/local-execution/provider-release.d.ts +53 -0
  131. package/dist/_types/contracts/local-execution/provider-selection.d.ts +58 -0
  132. package/dist/_types/contracts/local-execution/recognition.d.ts +30 -0
  133. package/dist/_types/contracts/local-execution/speech.d.ts +1 -1
  134. package/dist/_types/contracts/local-execution/versions.d.ts +2 -0
  135. package/dist/_types/contracts/media-observation.d.ts +56 -0
  136. package/dist/_types/contracts/native-speech-http.d.ts +15 -0
  137. package/dist/_types/contracts/navigation-context.d.ts +193 -1
  138. package/dist/_types/contracts/navigation-groups.d.ts +1 -1
  139. package/dist/_types/contracts/navigation.d.ts +3 -1
  140. package/dist/_types/contracts/observation-profile.d.ts +12 -0
  141. package/dist/_types/contracts/openai-asr.d.ts +55 -0
  142. package/dist/_types/contracts/provider-catalog.d.ts +44 -0
  143. package/dist/_types/contracts/provider-models.d.ts +115 -3
  144. package/dist/_types/contracts/provider.d.ts +93 -7
  145. package/dist/_types/contracts/render-readiness.d.ts +74 -1
  146. package/dist/_types/contracts/repair-strategy.d.ts +1 -1
  147. package/dist/_types/contracts/sound-making-plan.d.ts +41 -0
  148. package/dist/_types/contracts/source-workspace.d.ts +2 -0
  149. package/dist/_types/contracts/speech-cost.d.ts +129 -0
  150. package/dist/_types/contracts/speech.d.ts +50 -0
  151. package/dist/_types/contracts/transcription.d.ts +11 -0
  152. package/dist/_types/sdk/local-runtime/components.d.ts +6 -0
  153. package/dist/_types/sdk/local-runtime-client.d.ts +35 -23
  154. package/dist/entry.js +1 -1
  155. package/dist/local-management.js +1 -1
  156. package/dist/local-navigation.js +1 -1
  157. package/package.json +3 -2
  158. package/dist/_chunks/chunk-27KI24GK.js +0 -1
  159. package/dist/_chunks/chunk-3TOXIJ7K.js +0 -1
  160. package/dist/_chunks/chunk-4M2SOMSN.js +0 -1
  161. package/dist/_chunks/chunk-6EZX2TRX.js +0 -1
  162. package/dist/_chunks/chunk-7I7ARCY7.js +0 -1
  163. package/dist/_chunks/chunk-7P2NA6TH.js +0 -1
  164. package/dist/_chunks/chunk-AFNJRZLJ.js +0 -1
  165. package/dist/_chunks/chunk-APNZQZFB.js +0 -1
  166. package/dist/_chunks/chunk-ELUJ44BO.js +0 -1
  167. package/dist/_chunks/chunk-FVY3PLG7.js +0 -1
  168. package/dist/_chunks/chunk-HBDPYWMI.js +0 -1
  169. package/dist/_chunks/chunk-IYDHDLTR.js +0 -1
  170. package/dist/_chunks/chunk-L3QA7FLZ.js +0 -1
  171. package/dist/_chunks/chunk-NG4BDFEY.js +0 -1
  172. package/dist/_chunks/chunk-OSO6KRE2.js +0 -1
  173. package/dist/_chunks/chunk-QK4XPVKT.js +0 -1
  174. package/dist/_chunks/chunk-ROGOASYF.js +0 -1
  175. package/dist/_chunks/chunk-UYKCN5DU.js +0 -1
  176. package/dist/_chunks/chunk-WTJVS2VS.js +0 -1
  177. package/dist/_chunks/component-contract-KXK7WIUI.js +0 -1
  178. package/dist/_chunks/component-preflight-WECLCZLF.js +0 -1
  179. package/dist/_chunks/connect-7TJDWXV4.js +0 -1
  180. package/dist/_chunks/device-management-TLRUMZL5.js +0 -1
  181. package/dist/_chunks/device-preflight-C7FFUXI2.js +0 -1
  182. package/dist/_chunks/devices-inventory-BZF53UAU.js +0 -1
  183. package/dist/_chunks/devices-main-V3YHCB2C.js +0 -1
  184. package/dist/_chunks/files-JJ6YOULB.js +0 -1
  185. package/dist/_chunks/host-component-Q5IHRHRI.js +0 -1
  186. package/dist/_chunks/host-help-7BGYR4ET.js +0 -1
  187. package/dist/_chunks/host-main-JLIBRHC2.js +0 -1
  188. package/dist/_chunks/http-profile-3VVSWYA5.js +0 -1
  189. package/dist/_chunks/library-main-ATRFEAVN.js +0 -1
  190. package/dist/_chunks/local-main-KTYCLHDA.js +0 -1
  191. package/dist/_chunks/local-mcp-ISMU6ADI.js +0 -1
  192. package/dist/_chunks/main-MOZS2EK3.js +0 -2
  193. package/dist/_chunks/mcp-M2SO3J2H.js +0 -1
  194. package/dist/_chunks/oauth-RPME2XYB.js +0 -1
  195. package/dist/_chunks/observe-entry-E6DFHIMW.js +0 -1
  196. package/dist/_chunks/remote-client-T75C45JO.js +0 -1
  197. package/dist/_chunks/render-main-OGCO2LX4.js +0 -1
  198. package/dist/_chunks/source-import-55JJ26AA.js +0 -1
  199. package/dist/_chunks/src-V2K52JDH.js +0 -1
  200. package/dist/_chunks/stdio-main-HNLJCG45.js +0 -1
  201. package/dist/_chunks/workspace-main-3P56DSEQ.js +0 -1
@@ -0,0 +1 @@
1
+ import{ContinuationSchema,DeliveryOutputProfileSchema,PrincipalIdSchema,ProductionIdSchema,ProductionSchema,ProjectIdSchema,QueryLimitSchema,QueryPageInfoSchema,TenantIdSchema}from"./chunk-M32FI2OA.js";import{z as z2}from"zod";import{z}from"zod";var ProjectLifecycleSchema=z.enum(["ACTIVE","ARCHIVED"]);var CreateProjectInputSchema=z.object({tenantId:TenantIdSchema,principalId:PrincipalIdSchema,idempotencyKey:z.string().trim().min(1).max(200),name:z.string().trim().min(1).max(200)});var CreateProjectRequestSchema=CreateProjectInputSchema.omit({principalId:true}).strict();var ProjectSchema=z.object({id:ProjectIdSchema,tenantId:TenantIdSchema,name:z.string().min(1),lifecycle:ProjectLifecycleSchema,defaultActiveProductionId:ProductionIdSchema.nullable(),revision:z.int().positive(),createdByPrincipalId:PrincipalIdSchema,createdAt:z.iso.datetime({offset:true}),updatedAt:z.iso.datetime({offset:true})});var CreatedProjectResultSchema=z.object({project:ProjectSchema,production:ProductionSchema});var ProjectLibraryQuerySchema=z2.strictObject({tenantId:TenantIdSchema,limit:QueryLimitSchema,next:ContinuationSchema.optional()});var ProjectLibraryScopeSchema=z2.strictObject({tenantId:TenantIdSchema,projectId:ProjectIdSchema});var ProjectLibraryPageSchema=z2.strictObject({items:z2.array(ProjectSchema).max(100),page:QueryPageInfoSchema});var ProjectWorkspaceSchema=z2.strictObject({project:ProjectSchema,productions:z2.array(ProductionSchema).max(100),possiblyTruncated:z2.boolean()});var SourceLibraryQuerySchema=ProjectLibraryQuerySchema.extend({projectId:ProjectIdSchema.optional()});var SourceLibraryItemSchema=z2.strictObject({artifactId:z2.uuid(),representationId:z2.uuid(),projectId:ProjectIdSchema,kind:z2.enum(["REFERENCE_IMAGE","REFERENCE_VIDEO","PRODUCT_INFORMATION"]),originalName:z2.string().max(255),checksumSha256:z2.string().regex(/^[0-9a-f]{64}$/),contentType:z2.enum(["image/png","image/jpeg","image/webp","text/plain","application/json","video/mp4"]),byteSize:z2.int().positive().max(128*1024*1024),width:z2.int().positive().nullable(),height:z2.int().positive().nullable(),createdAt:z2.iso.datetime({offset:true})}).refine(value=>value.kind==="REFERENCE_VIDEO"&&value.contentType==="video/mp4"?true:value.byteSize<=8*1024*1024,{message:"Video SOURCE is limited to 128 MiB; other SOURCE kinds remain limited to 8 MiB"});var SourceLibraryPageSchema=z2.strictObject({items:z2.array(SourceLibraryItemSchema).max(100),page:QueryPageInfoSchema});var SourceLibraryMediaSchema=ProjectLibraryScopeSchema.extend({artifactId:z2.uuid()});var StudioInputContentSchema=z2.strictObject({schemaVersion:z2.literal(1),productionId:z2.uuid(),projectTitle:z2.string().trim().min(1).max(200),name:z2.string().trim().max(300),intent:z2.string().trim().min(1).max(2e3),aspectRatio:z2.enum(["16:9","9:16"]),targetDurationSeconds:z2.int().min(30).max(60),outputProfile:DeliveryOutputProfileSchema,sourceArtifactIds:z2.array(z2.uuid()).max(12)});export{CreateProjectRequestSchema,ProjectSchema,CreatedProjectResultSchema,ProjectLibraryQuerySchema,ProjectLibraryScopeSchema,ProjectLibraryPageSchema,ProjectWorkspaceSchema,SourceLibraryQuerySchema,SourceLibraryItemSchema,SourceLibraryPageSchema,SourceLibraryMediaSchema,StudioInputContentSchema};
@@ -0,0 +1 @@
1
+ import{ComponentCommandSchema,HostComponentRequestSchema}from"./chunk-BNGPPUA3.js";import"./chunk-VXANXYQL.js";import"./chunk-SCLI4ALP.js";import"./chunk-EYOGMJW2.js";import"./chunk-IYYCCA44.js";import"./chunk-24ZFLWWU.js";import"./chunk-LNKE3Z3X.js";import"./chunk-NX4JWZWV.js";import"./chunk-25WUWVDK.js";import"./chunk-LZAC64FB.js";import"./chunk-A3MJERGH.js";import"./chunk-6MYLFBLH.js";import"./chunk-QCBLU6D6.js";import"./chunk-QLHMJUBH.js";import"./chunk-DEXSJABJ.js";import"./chunk-KGS6SI5Y.js";import"./chunk-KAW7T5TR.js";import"./chunk-6YVGVNEH.js";import"./chunk-N4ORSVTY.js";import"./chunk-RRYZZBXN.js";import"./chunk-LVVSTKDW.js";import"./chunk-EPH3TRYV.js";import"./chunk-VKXFHOAR.js";import"./chunk-EOWXXTEF.js";import"./chunk-XMZKBILZ.js";import"./chunk-UOYNCE7I.js";import"./chunk-AZQLZA47.js";import"./chunk-Z44SK6DZ.js";import"./chunk-M32FI2OA.js";import"./chunk-TT7IA5HB.js";export{ComponentCommandSchema,HostComponentRequestSchema};
@@ -0,0 +1 @@
1
+ import{assertComponentConfiguration,componentDevice,observeComponent}from"./chunk-FRZDYDOP.js";import{observeLoginHost}from"./chunk-RASQZMYI.js";import"./chunk-BNGPPUA3.js";import{desktopRuntimeChannel}from"./chunk-7TXIHIZ5.js";import"./chunk-VXANXYQL.js";import"./chunk-SCLI4ALP.js";import"./chunk-EYOGMJW2.js";import"./chunk-IYYCCA44.js";import"./chunk-24ZFLWWU.js";import"./chunk-LNKE3Z3X.js";import"./chunk-NX4JWZWV.js";import"./chunk-25WUWVDK.js";import"./chunk-LZAC64FB.js";import{installationSource,verifyCaptionDirectory}from"./chunk-A3MJERGH.js";import"./chunk-6MYLFBLH.js";import"./chunk-QCBLU6D6.js";import{captureInstalledTools}from"./chunk-QLHMJUBH.js";import"./chunk-DEXSJABJ.js";import"./chunk-KGS6SI5Y.js";import"./chunk-KAW7T5TR.js";import"./chunk-6YVGVNEH.js";import"./chunk-N4ORSVTY.js";import"./chunk-RRYZZBXN.js";import"./chunk-LVVSTKDW.js";import"./chunk-EPH3TRYV.js";import"./chunk-VKXFHOAR.js";import"./chunk-EOWXXTEF.js";import"./chunk-XMZKBILZ.js";import{LocalToolSelectionSchema}from"./chunk-UOYNCE7I.js";import"./chunk-CBJIFAHD.js";import{LocalClientError,assertExecutable,read}from"./chunk-AZQLZA47.js";import"./chunk-Z44SK6DZ.js";import"./chunk-M32FI2OA.js";import"./chunk-NEZ7IY5E.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-USOV7NK4.js";import{oauthStartDiscovery,profileAuthorization,runOAuthCommand,startOAuthProfile}from"./chunk-UFUFQA5U.js";import"./chunk-4UQRT3ZH.js";import{accountError,loadConnection,readAccount,requireAccount,saveConnection,tenantConnection}from"./chunk-ISPIV2P6.js";import{OAuthBindingSchema,clientHome,connectionError}from"./chunk-CBJIFAHD.js";import"./chunk-AZQLZA47.js";import"./chunk-Z44SK6DZ.js";import"./chunk-M32FI2OA.js";import{boundedRemoteFetch,secureEndpoint}from"./chunk-NEZ7IY5E.js";import{NativeStudioSdkError}from"./chunk-TT7IA5HB.js";import{randomUUID,timingSafeEqual}from"node:crypto";import{createServer}from"node:http";import{join}from"node:path";import{z}from"zod";async function accountMcpConnection(value,signal){const account=requireAccount(value);const tenantId=account.workspaceId;if(!tenantId)accountError("ACCOUNT_WORKSPACE_SELECTION_REQUIRED");const url=new URL("/api/cli-account/mcp-connection",account.serverOrigin);url.searchParams.set("tenantId",tenantId);let response;try{response=await boundedRemoteFetch(8192,signal)(url,{cache:"no-store",credentials:"omit",headers:{authorization:"Bearer "+account.accessToken,accept:"application/json"}})}catch{signal.throwIfAborted();accountError("ACCOUNT_MCP_CONNECTION_UNAVAILABLE")}if(response.status===404)return null;if(response.status===401)accountError("ACCOUNT_SESSION_EXPIRED_OR_REVOKED");if(!response.ok)accountError("ACCOUNT_MCP_CONNECTION_REJECTED");try{if(!response.headers.get("content-type")?.startsWith("application/json"))throw Error();const{resource,...binding}=z.discriminatedUnion("mode",[OAuthBindingSchema.options[0].extend({resource:z.url().max(2048)}),OAuthBindingSchema.options[1].extend({resource:z.url().max(2048)})]).parse(await response.json());const connection=tenantConnection(resource);const issuer=secureEndpoint(binding.issuer);if(connection.resource!==resource||connection.tenantId!==tenantId||binding.mode==="shared"&&(issuer.protocol!=="https:"||new URL(resource).protocol!=="https:"))throw Error();return{resource,binding}}catch{accountError("ACCOUNT_MCP_CONNECTION_INVALID")}}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 requested=options.get("--scope");if(requested&&!["nvs:read","nvs:read nvs:write"].includes(requested))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 route=!explicit&&account?await accountMcpConnection(account,signal):null;const resource=tenantConnection(explicit??route?.resource??new URL("/mcp/external/v1/tenants/"+account.workspaceId,account.serverOrigin).href);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");const sharedDiscovery=route?.binding.mode==="shared"?await oauthStartDiscovery(resource.resource,requested,route.binding,signal):void 0;const scope=sharedDiscovery?.scope??requested??"nvs:read nvs:write";if(!explicit){let saved=null;try{saved=await loadConnection(environment)}catch(error){if(!(error instanceof NativeStudioSdkError)||error.code!=="CONNECTION_ACCOUNT_MISMATCH")throw error}const sameRoute=saved?.resource===resource.resource&&(!route||saved.issuer===route.binding.issuer)&&(route?.binding.mode==="shared"?saved.publicClientId===route.binding.clientId:saved.publicClientId===void 0);if(saved&&sameRoute&&saved.exchangeUnresolved)throw new NativeStudioSdkError("OAUTH_OUTCOME_UNKNOWN","INTERNAL_OPERATIONAL_FAILURE","UNKNOWN");if(saved&&sameRoute&&saved.requestedScope===scope&&!saved.reauthorizationRequired&&!saved.exchangeUnresolved){try{await profileAuthorization(saved.profile,signal);const current=await loadConnection(environment);if(current?.profile!==saved.profile)connectionError("ACCOUNT_CHANGED_DURING_CONNECTION");return{exitCode:0,output:{semanticStatus:"SUCCESS",connected:true,resource:saved.resource,tenantId:saved.tenantId,scope:current.scope,requestedScope:scope,reused:true}}}catch(error){if(!(error instanceof NativeStudioSdkError)||!["OAUTH_INVALID_GRANT","OAUTH_REAUTHORIZATION_REQUIRED"].includes(error.code))throw error}}}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}`;const discovery=sharedDiscovery??await oauthStartDiscovery(resource.resource,requested,route?.binding,signal);provider=await startOAuthProfile(path,resource.resource,redirect,discovery,signal);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:discovery.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()))}}export{runConnect};
@@ -0,0 +1 @@
1
+ import{profileAuthorization}from"./chunk-UFUFQA5U.js";import{readCredential,readInput}from"./chunk-4UQRT3ZH.js";import{connectRemoteMcp}from"./chunk-DBOQPJLY.js";import"./chunk-2UYKJ6YN.js";import"./chunk-XMZKBILZ.js";import"./chunk-UOYNCE7I.js";import{defaultConnection,tenantConnection}from"./chunk-ISPIV2P6.js";import"./chunk-CBJIFAHD.js";import"./chunk-AZQLZA47.js";import"./chunk-Z44SK6DZ.js";import{CapabilityVersionSchema}from"./chunk-M32FI2OA.js";import"./chunk-NEZ7IY5E.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-SCOSFTMM.js";import{renderConnection}from"./chunk-Q7MTMC6D.js";import"./chunk-VJ4SCIR5.js";import{probeTenantOpenAiAsr,probeTenantOpenAiRealtimeSpeech}from"./chunk-LZAC64FB.js";import{LocalInstallationManager}from"./chunk-A3MJERGH.js";import"./chunk-QLHMJUBH.js";import"./chunk-KAW7T5TR.js";import{ownerClient,probeLocalLibrary,probeReferenceThumbnail,probeTenantComposition,probeTenantMediaProcessing,probeTenantMediaValidation,probeTenantQwenGeneration,probeTenantSpeech,probeTenantTranscription,verifySlot}from"./chunk-6YVGVNEH.js";import"./chunk-LVVSTKDW.js";import{DesktopDeviceRecords}from"./chunk-EPH3TRYV.js";import"./chunk-VKXFHOAR.js";import"./chunk-EOWXXTEF.js";import"./chunk-UFUFQA5U.js";import"./chunk-4UQRT3ZH.js";import"./chunk-DBOQPJLY.js";import"./chunk-2UYKJ6YN.js";import{DeviceDiscoveryInputSchema}from"./chunk-XMZKBILZ.js";import{LocalDeviceTransportConfigurationSchema,LocalToolSelectionSchema}from"./chunk-UOYNCE7I.js";import"./chunk-IKJ6VNJ6.js";import"./chunk-ISPIV2P6.js";import"./chunk-CBJIFAHD.js";import{LocalClientError,read}from"./chunk-AZQLZA47.js";import"./chunk-Z44SK6DZ.js";import"./chunk-M32FI2OA.js";import"./chunk-NEZ7IY5E.js";import{NativeStudioSdkError}from"./chunk-TT7IA5HB.js";import{z}from"zod";async function localCapacityIssue(client){const snapshot=await client.workspace.inspect().catch(()=>null);if(!snapshot)return"DEVICE_CAPACITY_UNCONFIRMED";const{scheduling,settings,storage}=snapshot;if(scheduling.state==="DRAINING")return"DEVICE_BUSY";if(!settings.policy.acceptNewWork||scheduling.state==="PAUSED")return"DEVICE_PAUSED";if(scheduling.state==="WAITING_FOR_IDLE")return"DEVICE_WAITING_FOR_IDLE";if(scheduling.state==="AT_CAPACITY"||scheduling.activeJobs>=settings.policy.maxConcurrentJobs)return"DEVICE_BUSY";if(storage.quotaBytes!==settings.policy.cacheQuotaBytes)return"DEVICE_CAPACITY_UNCONFIRMED";if(storage.availableDiskBytes<1024**3||storage.overQuota||storage.cacheBytes+storage.transferBytes>settings.policy.cacheQuotaBytes)return"DEVICE_STORAGE_CAPACITY_UNAVAILABLE";return null}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",DEVICE_PAUSED:"Resume new work in the local Runtime resource settings, then recheck",DEVICE_WAITING_FOR_IDLE:"Wait for the configured idle interval, then recheck",DEVICE_STORAGE_CAPACITY_UNAVAILABLE:"Inspect local storage and cache quota; reclaim only unpinned data",DEVICE_CAPACITY_UNCONFIRMED:"Inspect the running Runtime resource settings and retry this read",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_OPENAI":return probeTenantOpenAiAsr(root,slot);case"SPEECH_EXTERNAL_OPENAI_REALTIME":return probeTenantOpenAiRealtimeSpeech(root,slot);case"TRANSCRIBE_EXTERNAL_QWEN":return probeTenantQwenGeneration(root,slot,"asr");default:return true}}async function cpuSpeechSelected(slot,legacy){const selected=slot.toolsConfigPath?LocalToolSelectionSchema.parse(JSON.parse((await read(slot.toolsConfigPath,32768)).toString())):legacy;return!!selected?.cpuSpeech}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||status.deviceAuthority.origin!==endpoint.origin)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==="SPEECH_SYNTHESIZE_CPU"){if(!await cpuSpeechSelected(active,current.tools))return blocked("RUNTIME_QUALIFICATION_REQUIRED");if(!capabilities.tenantMediaProcessing||!capabilities.processorCapabilities.includes(kind))return blocked("DEVICE_CAPABILITY_UNCONFIRMED");const doctor=await local.doctor().catch(()=>null);if(!doctor?.nativeExecutionReady||!doctor.executionProfiles?.includes("AUDIO_MEDIA_V1"))return blocked("RUNTIME_QUALIFICATION_REQUIRED")}else{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")}if(kind!=="library"){const issue=await localCapacityIssue(local);if(issue)return blocked(issue)}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"){if(kind==="SPEECH_SYNTHESIZE_CPU")return blocked(await cpuSpeechSelected(active,current.tools)?"DEVICE_CAPABILITY_UNCONFIRMED":"RUNTIME_QUALIFICATION_REQUIRED");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{DesktopProviderInspectRequestSchema,inspectDeviceProviders}from"./chunk-NX4JWZWV.js";import"./chunk-25WUWVDK.js";import"./chunk-LZAC64FB.js";import"./chunk-A3MJERGH.js";import"./chunk-QLHMJUBH.js";import"./chunk-KAW7T5TR.js";import"./chunk-6YVGVNEH.js";import"./chunk-LVVSTKDW.js";import"./chunk-EPH3TRYV.js";import"./chunk-VKXFHOAR.js";import"./chunk-EOWXXTEF.js";import"./chunk-XMZKBILZ.js";import"./chunk-UOYNCE7I.js";import"./chunk-AZQLZA47.js";import"./chunk-Z44SK6DZ.js";import"./chunk-M32FI2OA.js";import"./chunk-TT7IA5HB.js";export{DesktopProviderInspectRequestSchema,inspectDeviceProviders};
@@ -0,0 +1 @@
1
+ import{profileAuthorization}from"./chunk-UFUFQA5U.js";import{readCredential}from"./chunk-4UQRT3ZH.js";import{connectRemoteMcp}from"./chunk-DBOQPJLY.js";import"./chunk-2UYKJ6YN.js";import"./chunk-XMZKBILZ.js";import{WorkspaceDeviceListInputSchema}from"./chunk-UOYNCE7I.js";import{defaultConnection,tenantConnection}from"./chunk-ISPIV2P6.js";import"./chunk-CBJIFAHD.js";import"./chunk-AZQLZA47.js";import"./chunk-Z44SK6DZ.js";import"./chunk-M32FI2OA.js";import"./chunk-NEZ7IY5E.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-Q7MTMC6D.js";import"./chunk-VJ4SCIR5.js";import"./chunk-UFUFQA5U.js";import"./chunk-4UQRT3ZH.js";import"./chunk-DBOQPJLY.js";import"./chunk-2UYKJ6YN.js";import{DeviceDiscoveryInputSchema}from"./chunk-XMZKBILZ.js";import"./chunk-UOYNCE7I.js";import"./chunk-ISPIV2P6.js";import"./chunk-CBJIFAHD.js";import"./chunk-AZQLZA47.js";import"./chunk-Z44SK6DZ.js";import"./chunk-M32FI2OA.js";import"./chunk-NEZ7IY5E.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-OAY2HON2.js")).deviceInventoryCommand(args,env);if(action!=="list")return(await import("./device-management-JGV4YU7S.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-AZQLZA47.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-FRZDYDOP.js";import{runLoginService}from"./chunk-RASQZMYI.js";import"./chunk-BNGPPUA3.js";import"./chunk-7TXIHIZ5.js";import"./chunk-VXANXYQL.js";import"./chunk-SCLI4ALP.js";import"./chunk-EYOGMJW2.js";import"./chunk-IYYCCA44.js";import"./chunk-24ZFLWWU.js";import"./chunk-LNKE3Z3X.js";import"./chunk-NX4JWZWV.js";import"./chunk-25WUWVDK.js";import"./chunk-LZAC64FB.js";import{LocalInstallationManager}from"./chunk-A3MJERGH.js";import"./chunk-6MYLFBLH.js";import"./chunk-QCBLU6D6.js";import{InstalledToolPathsSchema,captureInstalledTools}from"./chunk-QLHMJUBH.js";import"./chunk-DEXSJABJ.js";import"./chunk-KGS6SI5Y.js";import"./chunk-KAW7T5TR.js";import"./chunk-6YVGVNEH.js";import"./chunk-N4ORSVTY.js";import"./chunk-RRYZZBXN.js";import"./chunk-LVVSTKDW.js";import"./chunk-EPH3TRYV.js";import"./chunk-VKXFHOAR.js";import"./chunk-EOWXXTEF.js";import"./chunk-XMZKBILZ.js";import"./chunk-UOYNCE7I.js";import"./chunk-CBJIFAHD.js";import{LocalClientError,fail}from"./chunk-AZQLZA47.js";import"./chunk-Z44SK6DZ.js";import"./chunk-M32FI2OA.js";import"./chunk-NEZ7IY5E.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-FYYYXV6C.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-BNGPPUA3.js";import{HostEnrollmentRequestSchema}from"./chunk-NW3ODW7Y.js";import"./chunk-VXANXYQL.js";import"./chunk-SCLI4ALP.js";import"./chunk-PC54RQIE.js";import"./chunk-EYOGMJW2.js";import"./chunk-IYYCCA44.js";import"./chunk-24ZFLWWU.js";import"./chunk-LNKE3Z3X.js";import"./chunk-NX4JWZWV.js";import"./chunk-25WUWVDK.js";import"./chunk-LZAC64FB.js";import"./chunk-A3MJERGH.js";import"./chunk-6MYLFBLH.js";import"./chunk-QCBLU6D6.js";import"./chunk-QLHMJUBH.js";import"./chunk-DEXSJABJ.js";import"./chunk-KGS6SI5Y.js";import"./chunk-KAW7T5TR.js";import"./chunk-6YVGVNEH.js";import"./chunk-N4ORSVTY.js";import"./chunk-RRYZZBXN.js";import"./chunk-LVVSTKDW.js";import"./chunk-EPH3TRYV.js";import"./chunk-VKXFHOAR.js";import"./chunk-EOWXXTEF.js";import"./chunk-XMZKBILZ.js";import"./chunk-UOYNCE7I.js";import"./chunk-AZQLZA47.js";import"./chunk-Z44SK6DZ.js";import"./chunk-M32FI2OA.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-NW3ODW7Y.js";import{runDesktopDeviceRequest}from"./chunk-PC54RQIE.js";import"./chunk-IYYCCA44.js";import"./chunk-24ZFLWWU.js";import"./chunk-LNKE3Z3X.js";import"./chunk-25WUWVDK.js";import"./chunk-LZAC64FB.js";import"./chunk-A3MJERGH.js";import"./chunk-QLHMJUBH.js";import"./chunk-KAW7T5TR.js";import"./chunk-6YVGVNEH.js";import"./chunk-LVVSTKDW.js";import{DesktopDeviceRequestSchema}from"./chunk-EPH3TRYV.js";import"./chunk-VKXFHOAR.js";import"./chunk-EOWXXTEF.js";import{readInput}from"./chunk-4UQRT3ZH.js";import"./chunk-XMZKBILZ.js";import"./chunk-UOYNCE7I.js";import{LocalClientError}from"./chunk-AZQLZA47.js";import"./chunk-Z44SK6DZ.js";import"./chunk-M32FI2OA.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-AYTWACIM.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-AYTWACIM.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-B6VKGV2V.js");const request2=HostComponentRequestSchema.parse(raw);entered=true;mutation=!["status","preflight","receipt","service-plan"].includes(request2.call.action);return await(await import("./host-component-W5DIBO65.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-IKJ6VNJ6.js";import"./chunk-ISPIV2P6.js";import"./chunk-CBJIFAHD.js";import"./chunk-AZQLZA47.js";import"./chunk-Z44SK6DZ.js";import"./chunk-M32FI2OA.js";import"./chunk-NEZ7IY5E.js";import"./chunk-TT7IA5HB.js";export{profileHttpOrigin};
@@ -0,0 +1 @@
1
+ import{localCaller}from"./chunk-SCOSFTMM.js";import{renderConnection}from"./chunk-Q7MTMC6D.js";import"./chunk-VJ4SCIR5.js";import{DesktopLibraryImportSeedSchema,prepareDesktopLibraryImport,runDesktopLibraryImport,runDesktopLibraryRequest}from"./chunk-SCLI4ALP.js";import"./chunk-24ZFLWWU.js";import"./chunk-A3MJERGH.js";import"./chunk-QLHMJUBH.js";import"./chunk-KAW7T5TR.js";import"./chunk-6YVGVNEH.js";import"./chunk-LVVSTKDW.js";import{DesktopDeviceRecords}from"./chunk-EPH3TRYV.js";import"./chunk-VKXFHOAR.js";import"./chunk-EOWXXTEF.js";import"./chunk-UFUFQA5U.js";import{readInput}from"./chunk-4UQRT3ZH.js";import"./chunk-DBOQPJLY.js";import"./chunk-2UYKJ6YN.js";import"./chunk-XMZKBILZ.js";import{LocalDeviceViewSchema,LocalManagementCommandSchema}from"./chunk-UOYNCE7I.js";import"./chunk-IKJ6VNJ6.js";import"./chunk-ISPIV2P6.js";import"./chunk-CBJIFAHD.js";import{fail,sha256}from"./chunk-AZQLZA47.js";import"./chunk-Z44SK6DZ.js";import"./chunk-M32FI2OA.js";import"./chunk-NEZ7IY5E.js";import{NativeStudioSdkError}from"./chunk-TT7IA5HB.js";import{homedir}from"node:os";import{join,resolve,basename,extname}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:extname(file).toLowerCase()===".wav"?"audio/wav":"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-RASQZMYI.js";import{connectDevice,generateDeviceKey}from"./chunk-LNKE3Z3X.js";import"./chunk-25WUWVDK.js";import"./chunk-LZAC64FB.js";import{LocalInstallationManager}from"./chunk-A3MJERGH.js";import{prepareInstalledCpuSpeech}from"./chunk-QCBLU6D6.js";import{captureInstalledTools}from"./chunk-QLHMJUBH.js";import"./chunk-KAW7T5TR.js";import{ownerClient}from"./chunk-6YVGVNEH.js";import"./chunk-LVVSTKDW.js";import"./chunk-VKXFHOAR.js";import{NativeStudioLocalDeviceClient}from"./chunk-EOWXXTEF.js";import{readCredential,readInput}from"./chunk-4UQRT3ZH.js";import{localCliVersion}from"./chunk-2UYKJ6YN.js";import{NativeStudioAgentClient}from"./chunk-XMZKBILZ.js";import{EnrollLocalDeviceSchema,LocalAgentGrantSchema,LocalManagementCommandSchema,RevokeLocalDeviceSchema,StartLocalFinalRenderSchema,StartLocalPreviewSchema,canonicalLocalJson,localAgentMediaProposal,localAgentMediaSnapshot,localAgentSnapshotFromContext}from"./chunk-UOYNCE7I.js";import"./chunk-CBJIFAHD.js";import{LocalClientError}from"./chunk-AZQLZA47.js";import"./chunk-Z44SK6DZ.js";import"./chunk-M32FI2OA.js";import"./chunk-NEZ7IY5E.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={PROVIDER_CHANGE_APPROVAL_REQUIRED:["Use local providers-prepare --input <private-selection.json> or --action detach, then providers-apply with the exact approval fingerprint."],PROVIDER_INVENTORY_NOT_PROVEN:["Start the current Runtime and activate a version supporting the explicit provider-work inventory; do not infer safety from an absent or old response."],PROVIDER_INVENTORY_INVALID:["The original provider-work inventory did not validate. Preserve the journal and original receipts; diagnose the exact record through the authorized device owner before retrying."],PROVIDER_INVENTORY_BUSY:["The bounded inventory was busy. Retry when the device is idle without changing the existing provider connection."],DEVICE_CONNECTION_RECOVERY_REQUIRED:["Inspect the original device connection and Runtime state. Run nvs host device --input <private scope/call with action connection-recover> to reconcile the original connection before reconnecting; do not replay the change."],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-BDS4ANNF.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-ZPWOMGHI.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","--slot","--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","models-inspect [--home <private-client-home>] \u2014 inspect selected pinned model identities and integrity without writes","providers-prepare --input <private-selection.json> | --action detach \u2014 inspect exact external selections and prepare owner approval","providers-apply --input <same-private-selection.json> | --action detach --approve <fingerprint> \u2014 drain and verify original work, then load approved configuration","providers-inspect [--home <private-client-home>] \u2014 inspect saved provider selections, private file availability and running acknowledgement; never sends provider requests","model-slot-retire-prepare --slot <uuid> \u2014 inspect a historical inactive slot reference retirement; never deletes","model-slot-retire-apply --slot <uuid> --approve <fingerprint> \u2014 release only the approved historical slot reference","model-plan-retire-prepare --plan <uuid> \u2014 inspect irrevocably superseded plan reference retirement; never deletes","model-plan-retire-apply --plan <uuid> --approve <fingerprint> \u2014 record exact approved retirement; retain original plan and files","models-retention [--home <private-client-home>] \u2014 inspect historical and saved-plan resource references; never deletes","backup-retire-prepare|backup-retire-apply --input <json with remove and retain backup UUIDs> [--approve <fingerprint>] \u2014 retire only a backup fully covered by the retained snapshot","model-cleanup-prepare|model-cleanup-apply --input <JSON kind and digest> [--approve <fingerprint>] \u2014 remove only an approved unreferenced managed CPU resource","model-whisper-prepare --input <private-json with expectedRevision, binary, model> \u2014 select pinned Whisper on supported installed tools; apply separately","model-disable-prepare --action CPU_SPEECH|WHISPER \u2014 prepare an exact selection-only deactivation plan; apply separately","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|service-restart --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(command==="providers-prepare"||command==="providers-apply"){mutation=command==="providers-apply";const allowed2=["--home","--input","--action",...mutation?["--approve"]:[]];if([...options.keys()].some(key=>!allowed2.includes(key))||options.has("--input")===options.has("--action"))throw Error();if(options.has("--action")&&options.get("--action")!=="detach")throw Error();const source=options.has("--input")?{mode:"FILE",path:resolve2(required("--input"))}:{mode:"DETACH"};const caller=await(await import("./caller-DPHTMOBN.js")).workspaceCaller({...process.env,NATIVESTUDIO_CLIENT_HOME:home});if(!caller)throw new LocalClientError("ACCOUNT_LOGIN_REQUIRED","NO_WRITE");const scope={origin:caller.serverOrigin,tenantId:caller.tenantId,principalId:caller.principalId};await caller.assertCurrent();const providers=await import("./provider-change-U34UP6ER.js");return{exitCode:0,output:mutation?await providers.applyDeviceProviderChange(home,scope,source,required("--approve"),caller.assertCurrent):await providers.prepareDeviceProviderChange(home,scope,source)}}if(command==="providers-inspect"){if([...options.keys()].some(key=>key!=="--home"))throw Error();return{exitCode:0,output:await(await import("./device-provider-inspection-C4IRVW3V.js")).inspectDeviceProviders(home)}}if(loginCommand(command)){mutation=["service-enable","service-start","service-disable","service-restart"].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"))}}if(["backup-retire-prepare","backup-retire-apply","model-cleanup-prepare","model-cleanup-apply"].includes(command)){mutation=command.endsWith("-apply");const permitted=["--home","--input",...mutation?["--approve"]:[]];if([...options.keys()].some(key=>!permitted.includes(key)))throw Error();const manager2=await LocalInstallationManager.openExisting(home);if(!manager2)throw new LocalClientError("INSTALL_REQUIRED","NO_WRITE");const input=await readInput(required("--input"),stdin);if(command.startsWith("model-cleanup-")){const cleanup=await import("./model-cleanup-22VY6NWS.js");return{exitCode:0,output:mutation?await cleanup.applyModelCleanup(manager2,input,required("--approve")):await cleanup.prepareModelCleanup(manager2,input)}}const retirement=await import("./backup-retirement-5OTAYZYN.js");return{exitCode:0,output:mutation?await retirement.applyBackupRetirement(manager2,input,required("--approve")):await retirement.prepareBackupRetirement(manager2,input)}}if(command==="model-slot-retire-prepare"||command==="model-slot-retire-apply"){mutation=command==="model-slot-retire-apply";const permitted=["--home","--slot",...mutation?["--approve"]:[]];if([...options.keys()].some(key=>!permitted.includes(key)))throw Error();const manager2=await LocalInstallationManager.openExisting(home);if(!manager2)throw new LocalClientError("INSTALL_REQUIRED","NO_WRITE");const retirement=await import("./model-slot-retirement-KL6MVDGL.js");return{exitCode:0,output:mutation?await retirement.applyModelSlotRetirement(manager2,required("--slot"),required("--approve")):await retirement.prepareModelSlotRetirement(manager2,required("--slot"))}}if(command==="model-plan-retire-prepare"||command==="model-plan-retire-apply"){mutation=command==="model-plan-retire-apply";const permitted=["--home","--plan",...mutation?["--approve"]:[]];if([...options.keys()].some(key=>!permitted.includes(key)))throw Error();const manager2=await LocalInstallationManager.openExisting(home);if(!manager2)throw new LocalClientError("INSTALL_REQUIRED","NO_WRITE");const retirement=await import("./model-plan-retirement-4V2J3AUA.js");return{exitCode:0,output:mutation?await retirement.applyModelPlanRetirement(manager2,required("--plan"),required("--approve")):await retirement.prepareModelPlanRetirement(manager2,required("--plan"))}}if(command==="models-inspect"||command==="models-retention"||command==="model-disable-prepare"||command==="model-whisper-prepare"){const allowed2=command==="model-disable-prepare"?["--home","--action"]:command==="model-whisper-prepare"?["--home","--input"]:["--home"];if([...options.keys()].some(key=>!allowed2.includes(key)))throw Error();const manager2=await LocalInstallationManager.openExisting(home);if(command==="models-retention")return{exitCode:0,output:await(await import("./model-retention-F4WNSTJO.js")).inspectModelRetention(manager2)};const models=await import("./model-management-RZ4LQYMW.js");if(command==="models-inspect")return{exitCode:0,output:await models.inspectInstalledModels(manager2)};if(!manager2)throw new LocalClientError("INSTALL_REQUIRED","NO_WRITE");if(command==="model-whisper-prepare")return{exitCode:0,output:await models.prepareWhisperModel(manager2,await readInput(required("--input"),stdin))};return{exitCode:0,output:await models.prepareModelDisable(manager2,required("--action"))}}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:e instanceof LocalClientError&&e.outcome?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{StdioLines}from"./chunk-JFC6ZIGA.js";import{workspaceCaller}from"./chunk-SCOSFTMM.js";import"./chunk-Q7MTMC6D.js";import"./chunk-VJ4SCIR5.js";import{LocalMcpTools,localTools}from"./chunk-CUCC4RFF.js";import{desktopDeviceConnector}from"./chunk-EPH3TRYV.js";import"./chunk-VKXFHOAR.js";import"./chunk-EOWXXTEF.js";import"./chunk-UFUFQA5U.js";import"./chunk-4UQRT3ZH.js";import"./chunk-DBOQPJLY.js";import{localCliVersion}from"./chunk-2UYKJ6YN.js";import"./chunk-XMZKBILZ.js";import{LocalMcpFailureSchema}from"./chunk-UOYNCE7I.js";import"./chunk-IKJ6VNJ6.js";import"./chunk-ISPIV2P6.js";import"./chunk-CBJIFAHD.js";import"./chunk-AZQLZA47.js";import"./chunk-Z44SK6DZ.js";import"./chunk-M32FI2OA.js";import"./chunk-NEZ7IY5E.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-USOV7NK4.js";import{readInput}from"./chunk-4UQRT3ZH.js";import{NativeStudioAccountClient,accountError,accountServerOrigin,connectionStatus,defaultConnection,readAccount,requireAccount,saveAccount,withAccountLock}from"./chunk-ISPIV2P6.js";import{clientHome}from"./chunk-CBJIFAHD.js";import{write}from"./chunk-AZQLZA47.js";import"./chunk-Z44SK6DZ.js";import"./chunk-M32FI2OA.js";import"./chunk-NEZ7IY5E.js";import{NativeStudioSdkError}from"./chunk-TT7IA5HB.js";var aliases={find:"studio.start",overview:"studio.navigate",next:"studio.navigate","next-actions":"studio.next-actions",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"},"next-actions":{"--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","--schema-view":"schemaView"},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}function resourceExitCode(key,output){if(key!=="resource.use"&&key!=="resource.use-receipt"&&key!=="resource.delivery-observe")return void 0;if(!output||typeof output!=="object")return 1;if(key==="resource.delivery-observe"){const state=output.state;if(state==="NOT_FOUND")return 3;return["RESERVED","AWAITING_BYTES","BYTES_VERIFIED","SUBMITTED","USED"].includes(String(state))?0:1}switch(output.status){case"CONFIRMED":return 0;case"NOT_FOUND":return 3;case"BLOCKED":case"PENDING":return 4;default:return 1}}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-75RAY2SE.js")).runConnect(argv,environment);if(argv[0]==="login")return await runAccountLogin(argv,environment);if(argv[0]==="render")return await(await import("./render-main-ID5JWWKY.js")).renderCommand(argv.slice(1),environment,stdin);if(argv[0]==="devices")return await(await import("./devices-main-6PDXFRE2.js")).devicesCommand(argv.slice(1),environment,stdin);if(argv[0]==="import")return await(await import("./source-import-YW6YEMEN.js")).importSourceCommand(argv.slice(1),environment,stdin);if(AccountCommands.has(argv[0]??"")){const business=await(await import("./workspace-main-ZFR7ZY3R.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-Z26E4LJQ.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 next-actions --production <uuid> [--limit <1..8>] [--next <cursor>] \u2014 compact native action page","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 resource.discover|resource.describe|resource.use|resource.use-receipt|resource.delivery-ingress|resource.delivery-observe --input <json|-> \u2014 ResourceSDK control; actual bytes use the private data plane","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-36KAJDK4.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-6F6KRJA6.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:resourceExitCode(key,output)??(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-DBOQPJLY.js";import"./chunk-2UYKJ6YN.js";import"./chunk-XMZKBILZ.js";import"./chunk-UOYNCE7I.js";import"./chunk-Z44SK6DZ.js";import"./chunk-M32FI2OA.js";import"./chunk-NEZ7IY5E.js";import"./chunk-TT7IA5HB.js";export{connectRemoteMcp};
@@ -0,0 +1 @@
1
+ import{inspectModelRetention}from"./chunk-DEXSJABJ.js";import"./chunk-KGS6SI5Y.js";import"./chunk-KAW7T5TR.js";import{runtimeEnvironment,socketAbsent,verifySlot}from"./chunk-6YVGVNEH.js";import"./chunk-N4ORSVTY.js";import"./chunk-RRYZZBXN.js";import{withConfiguredLifecycle}from"./chunk-LVVSTKDW.js";import"./chunk-EOWXXTEF.js";import{LocalModelCleanupInputSchema,LocalModelCleanupPlanSchema,LocalModelCleanupReceiptSchema,LocalStoppedJournalEvidenceSchema,canonicalLocalJson}from"./chunk-UOYNCE7I.js";import{digestPrivateFile,fail,privateAccess,sha256,syncDirectory,withModelPreparationGate}from"./chunk-AZQLZA47.js";import"./chunk-M32FI2OA.js";import"./chunk-TT7IA5HB.js";import{lstat,readdir,realpath,rm}from"node:fs/promises";import{dirname,join as join2,relative,sep}from"node:path";import{spawn}from"node:child_process";import{join}from"node:path";async function withStoppedJournalGuard(root,slot,stateDirectory,work){await verifySlot(root,slot);const child=spawn(process.execPath,["--max-old-space-size=256",join(root,"dist/entry.js"),"--hold-stopped-journal","--state-dir",stateDirectory],{env:runtimeEnvironment(),stdio:["ignore","ignore","ignore","ipc"],shell:false});let closed=false;const exited=new Promise(resolve=>{const finish=()=>{closed=true;resolve()};child.once("exit",finish);child.once("error",finish)});const assertHeld=()=>{if(closed||!child.connected||child.exitCode!==null||child.signalCode!==null)fail("JOURNAL_OWNER_NOT_PROVEN")};try{const evidence=await new Promise((resolve,reject)=>{const timer=setTimeout(()=>reject(Error("JOURNAL_OWNER_NOT_PROVEN")),6e4);const finish=error=>{clearTimeout(timer);if(error)reject(error)};child.once("message",message=>{clearTimeout(timer);try{resolve(LocalStoppedJournalEvidenceSchema.parse(message))}catch(error){reject(error)}});child.once("error",finish);child.once("exit",()=>finish(Error("JOURNAL_OWNER_NOT_PROVEN")))}).catch(()=>fail("JOURNAL_OWNER_NOT_PROVEN","NO_WRITE"));assertHeld();return await work(evidence,assertHeld)}finally{if(child.connected)child.disconnect();const timer=setTimeout(()=>child.kill("SIGKILL"),5e3);await exited;clearTimeout(timer)}}function idle(deps){return deps?.state==="INSPECTED"&&deps.pendingExecutions===0&&deps.pendingRequests===0&&deps.pendingProviderWork===0}var protectedBlockers=new Set(["INSTALLATION_TRANSITION","RUNTIME_RUNNING","PENDING_WORK","RUNTIME_STATE_UNCONFIRMED","LIFECYCLE_GATE_STALE","LIFECYCLE_GATE_UNCONFIRMED"]);async function resourceEvidence(root,target){const category={CPU_ENGINE:"engines",CPU_MODEL:"models",CPU_DOWNLOAD:"downloads"}[target.kind];const parent=join2(root,"cpu-speech",category);for(const directory of[join2(root,"cpu-speech"),parent]){await privateAccess(directory,"directory");if(await realpath(directory)!==directory)fail("MODEL_CLEANUP_NOT_PROVEN","NO_WRITE")}const path=join2(parent,target.digest+(target.kind==="CPU_DOWNLOAD"?".archive":""));const rows=[];let byteSize=0;async function walk(selected,depth){if(depth>10||rows.length>=1024)fail("MODEL_CLEANUP_LIMIT","NO_WRITE");const before=await lstat(selected,{bigint:true});const name=relative(path,selected).split(sep).join("/");if(before.isSymbolicLink()||await realpath(selected)!==selected)fail("MODEL_CLEANUP_NOT_PROVEN","NO_WRITE");if(before.isDirectory()&&(depth>0||target.kind!=="CPU_DOWNLOAD")){await privateAccess(selected,"directory");rows.push([name,"directory"]);for(const entry of(await readdir(selected)).sort())await walk(join2(selected,entry),depth+1)}else if(before.isFile()&&before.nlink===1n&&(depth>0||target.kind==="CPU_DOWNLOAD")){const size=Number(before.size);byteSize+=size;if(byteSize>512*1024*1024)fail("MODEL_CLEANUP_LIMIT","NO_WRITE");rows.push([name,size,await digestPrivateFile(selected,512*1024*1024)])}else fail("MODEL_CLEANUP_NOT_PROVEN","NO_WRITE");const after=await lstat(selected,{bigint:true});if(before.dev!==after.dev||before.ino!==after.ino||before.size!==after.size||before.mtimeNs!==after.mtimeNs||before.ctimeNs!==after.ctimeNs||before.nlink!==after.nlink)fail("REVISION_CONFLICT","NO_WRITE")}await walk(path,0);return{path,byteSize,resourceFingerprint:sha256(canonicalLocalJson(rows))}}async function cleanup(manager,raw,approval){const target=LocalModelCleanupInputSchema.parse(raw);return withConfiguredLifecycle(manager,async()=>{const config=await manager.configuration();const history=await manager.ledger.current();if(!history.value.active||history.value.transition||!await socketAbsent(config.stateDirectory))fail("MODEL_CLEANUP_NOT_PROVEN","NO_WRITE");const active=history.value.active;return withModelPreparationGate(config.stateDirectory,()=>withStoppedJournalGuard(manager.ledger.slotPath(active),active,config.stateDirectory,async(evidence,assertHeld)=>{const report=await inspectModelRetention(manager);if(report.preparationEntries!==1||report.cleanupBlockers.some(v=>protectedBlockers.has(v))||!idle(evidence.recoveryDependencies)||report.backups.some(v=>!idle(v.recoveryDependencies)))fail("MODEL_RECOVERY_DEPENDENCIES_NOT_CLEARED","NO_WRITE");const item=report.resources.find(v=>v.kind===target.kind&&v.digest===target.digest);if(!item||item.protectedBy.length)fail("MODEL_STILL_REFERENCED","NO_WRITE");const resource=await resourceEvidence(config.stateDirectory,target);const body={protocol:"NVS_LOCAL_MODEL_CLEANUP_V1",target,installationRevision:history.value.revision,byteSize:resource.byteSize,resourceFingerprint:resource.resourceFingerprint,journalFingerprint:sha256(canonicalLocalJson(evidence)),backupFingerprint:sha256(canonicalLocalJson(report.backups))};const plan=LocalModelCleanupPlanSchema.parse({...body,fingerprint:sha256(canonicalLocalJson({...body,installationDigest:history.digest,configuration:config}))});assertHeld();if((await manager.ledger.current()).digest!==history.digest||canonicalLocalJson(await manager.configuration())!==canonicalLocalJson(config)||!await socketAbsent(config.stateDirectory))fail("REVISION_CONFLICT","NO_WRITE");if(approval===void 0)return plan;if(approval!==plan.fingerprint)fail("USER_APPROVAL_REQUIRED","NO_WRITE");const again=await resourceEvidence(config.stateDirectory,target);if(again.resourceFingerprint!==resource.resourceFingerprint||again.byteSize!==resource.byteSize)fail("REVISION_CONFLICT","NO_WRITE");assertHeld();await rm(resource.path,{recursive:target.kind!=="CPU_DOWNLOAD"});await syncDirectory(dirname(resource.path));return LocalModelCleanupReceiptSchema.parse({semanticStatus:"REMOVED",plan,reclaimedBytes:resource.byteSize})}))})}var prepareModelCleanup=(manager,raw)=>cleanup(manager,raw);var applyModelCleanup=(manager,raw,approval)=>cleanup(manager,raw,approval);export{applyModelCleanup,prepareModelCleanup};
@@ -0,0 +1 @@
1
+ import{inspectInstalledModels,modelDisableChoice,prepareModelDisable,prepareWhisperModel,whisperModelChoice}from"./chunk-6MYLFBLH.js";import"./chunk-QCBLU6D6.js";import"./chunk-QLHMJUBH.js";import"./chunk-6YVGVNEH.js";import"./chunk-EOWXXTEF.js";import"./chunk-UOYNCE7I.js";import"./chunk-AZQLZA47.js";import"./chunk-M32FI2OA.js";import"./chunk-TT7IA5HB.js";export{inspectInstalledModels,modelDisableChoice,prepareModelDisable,prepareWhisperModel,whisperModelChoice};
@@ -0,0 +1 @@
1
+ import{applyModelPlanRetirement,prepareModelPlanRetirement,verifyModelPlanRetirement}from"./chunk-N4ORSVTY.js";import"./chunk-LVVSTKDW.js";import"./chunk-EOWXXTEF.js";import"./chunk-UOYNCE7I.js";import"./chunk-AZQLZA47.js";import"./chunk-M32FI2OA.js";import"./chunk-TT7IA5HB.js";export{applyModelPlanRetirement,prepareModelPlanRetirement,verifyModelPlanRetirement};
@@ -0,0 +1 @@
1
+ import{inspectModelRetention}from"./chunk-DEXSJABJ.js";import"./chunk-KGS6SI5Y.js";import"./chunk-KAW7T5TR.js";import"./chunk-6YVGVNEH.js";import"./chunk-N4ORSVTY.js";import"./chunk-RRYZZBXN.js";import"./chunk-LVVSTKDW.js";import"./chunk-EOWXXTEF.js";import"./chunk-UOYNCE7I.js";import"./chunk-AZQLZA47.js";import"./chunk-M32FI2OA.js";import"./chunk-TT7IA5HB.js";export{inspectModelRetention};
@@ -0,0 +1 @@
1
+ import{applyModelSlotRetirement,prepareModelSlotRetirement,verifyModelSlotRetirement}from"./chunk-RRYZZBXN.js";import"./chunk-LVVSTKDW.js";import"./chunk-EOWXXTEF.js";import"./chunk-UOYNCE7I.js";import"./chunk-AZQLZA47.js";import"./chunk-M32FI2OA.js";import"./chunk-TT7IA5HB.js";export{applyModelSlotRetirement,prepareModelSlotRetirement,verifyModelSlotRetirement};
@@ -0,0 +1 @@
1
+ import{profileAuthorization,runOAuthCommand,startOAuthProfile}from"./chunk-UFUFQA5U.js";import"./chunk-4UQRT3ZH.js";import"./chunk-CBJIFAHD.js";import"./chunk-AZQLZA47.js";import"./chunk-NEZ7IY5E.js";import"./chunk-TT7IA5HB.js";export{profileAuthorization,runOAuthCommand,startOAuthProfile};
@@ -0,0 +1 @@
1
+ import{withRemoteClient}from"./chunk-LRIVN74V.js";import{readInput}from"./chunk-4UQRT3ZH.js";import{observeProduction}from"./chunk-XMZKBILZ.js";import"./chunk-UOYNCE7I.js";import"./chunk-ISPIV2P6.js";import"./chunk-CBJIFAHD.js";import"./chunk-AZQLZA47.js";import"./chunk-Z44SK6DZ.js";import"./chunk-M32FI2OA.js";import"./chunk-NEZ7IY5E.js";import{NativeStudioSdkError}from"./chunk-TT7IA5HB.js";async function runObservationCli(argv,emit,signal,environment=process.env,stdin=process.stdin){const lifetime=new AbortController;let timer;const observationSignal=AbortSignal.any([signal,lifetime.signal]);try{const options=new Map;const allowed=["--input","--tenant","--profile","--origin","--mcp-url","--token-env","--token-file","--transport","--max-polls","--timeout-ms","--max-events","--max-bytes"];for(let n=0;n<argv.length;n+=2){const key=argv[n],value=argv[n+1];if(!key||!allowed.includes(key)||!value||value.startsWith("--")||options.has(key))throw Error();options.set(key,value)}if(!options.has("--input"))throw Error();const number=key=>{const value=options.get(key);if(value!==void 0&&!/^[1-9][0-9]{0,8}$/.test(value))throw Error();return value===void 0?{}:{[key.slice(2).replace(/-([a-z])/g,(_,x)=>x.toUpperCase())]:Number(value)}};const limits=Object.assign({},...["--max-polls","--timeout-ms","--max-events","--max-bytes"].map(number));const timeout=Number(options.get("--timeout-ms")??3e5);if(!Number.isSafeInteger(timeout)||timeout<1||timeout>18e5)throw Error();timer=setTimeout(()=>lifetime.abort(),timeout);const input=await readInput(options.get("--input"),stdin,false,observationSignal);if(typeof input.productionId!=="string")throw Error();const productionId=input.productionId;await withRemoteClient(options,environment,false,async client=>{for await(const page of observeProduction(client,{...input,productionId},{...limits,signal:observationSignal})){observationSignal.throwIfAborted();await emit({kind:"production.events",data:page},observationSignal)}},{signal:observationSignal,maxJsonBytes:128*1024});await emit({kind:"observation.ended",reason:"POLL_LIMIT",nativeWorkCancelled:false},observationSignal);return 0}catch(error){if(signal.aborted)return 130;if(lifetime.signal.aborted)return 0;const e=error instanceof NativeStudioSdkError?error:null;await emit({kind:"observation.ended",reason:lifetime.signal.aborted?"OBSERVATION_LIMIT":e?.code??"INVALID_INPUT",outcome:e?.outcome??"NO_WRITE",nativeWorkCancelled:false},observationSignal).catch(()=>{});return lifetime.signal.aborted||e?.code==="OBSERVATION_LIMIT"?0:e?4:2}finally{if(timer)clearTimeout(timer);lifetime.abort()}}async function runObservationEntry(argv){const controller=new AbortController;const stop=()=>controller.abort();process.on("SIGINT",stop);process.on("SIGTERM",stop);try{return await runObservationCli(argv,(value,writeSignal)=>new Promise((resolve,reject)=>{if(writeSignal.aborted){reject(writeSignal.reason);return}const aborted=()=>{cleanup();reject(writeSignal.reason)};const failed=error=>{cleanup();controller.abort();reject(error)};const cleanup=()=>{writeSignal.removeEventListener("abort",aborted);process.stdout.off("error",failed)};writeSignal.addEventListener("abort",aborted,{once:true});process.stdout.once("error",failed);process.stdout.write(JSON.stringify(value)+"\n",error=>{cleanup();if(error)reject(error);else resolve()})}),controller.signal)}finally{controller.abort();process.stdin.pause();process.off("SIGINT",stop);process.off("SIGTERM",stop)}}export{runObservationEntry};
@@ -0,0 +1 @@
1
+ import{DesktopProviderChangeRequestSchema,applyDeviceProviderChange,prepareDeviceProviderChange}from"./chunk-EYOGMJW2.js";import"./chunk-IYYCCA44.js";import"./chunk-24ZFLWWU.js";import"./chunk-LNKE3Z3X.js";import"./chunk-25WUWVDK.js";import"./chunk-LZAC64FB.js";import"./chunk-A3MJERGH.js";import"./chunk-QLHMJUBH.js";import"./chunk-KAW7T5TR.js";import"./chunk-6YVGVNEH.js";import"./chunk-LVVSTKDW.js";import"./chunk-EPH3TRYV.js";import"./chunk-VKXFHOAR.js";import"./chunk-EOWXXTEF.js";import"./chunk-XMZKBILZ.js";import"./chunk-UOYNCE7I.js";import"./chunk-AZQLZA47.js";import"./chunk-Z44SK6DZ.js";import"./chunk-M32FI2OA.js";import"./chunk-TT7IA5HB.js";export{DesktopProviderChangeRequestSchema,applyDeviceProviderChange,prepareDeviceProviderChange};
@@ -0,0 +1 @@
1
+ import{withRemoteClient}from"./chunk-LRIVN74V.js";import"./chunk-4UQRT3ZH.js";import"./chunk-XMZKBILZ.js";import"./chunk-UOYNCE7I.js";import"./chunk-ISPIV2P6.js";import"./chunk-CBJIFAHD.js";import"./chunk-AZQLZA47.js";import"./chunk-Z44SK6DZ.js";import"./chunk-M32FI2OA.js";import"./chunk-NEZ7IY5E.js";import"./chunk-TT7IA5HB.js";export{withRemoteClient};
@@ -0,0 +1 @@
1
+ import{callerRenderConnection,renderReceiptScope}from"./chunk-Q7MTMC6D.js";import"./chunk-VJ4SCIR5.js";import"./chunk-UFUFQA5U.js";import{readInput}from"./chunk-4UQRT3ZH.js";import"./chunk-DBOQPJLY.js";import"./chunk-2UYKJ6YN.js";import{DeviceRenderDownloadSchema,DeviceRenderIntentSchema,DeviceRenderReadSchema,DeviceRenderReceiptHandoffSchema,PreparedDeviceRenderSchema,renderDeviceSelection}from"./chunk-XMZKBILZ.js";import"./chunk-UOYNCE7I.js";import"./chunk-ISPIV2P6.js";import{clientHome}from"./chunk-CBJIFAHD.js";import{directory,optional,sha256,write}from"./chunk-AZQLZA47.js";import"./chunk-Z44SK6DZ.js";import{CapabilityVersionMismatchSchema,InterfaceSemanticStatusSchema}from"./chunk-M32FI2OA.js";import"./chunk-NEZ7IY5E.js";import{NativeStudioSdkError}from"./chunk-TT7IA5HB.js";import{z}from"zod";import{join,resolve}from"node:path";async function assertRenderProject(studio,scope,productionId,options){const snapshot=await studio.call("production.snapshot",{productionId},options);if(snapshot.tenantId!==scope.tenantId||snapshot.projectId!==scope.projectId||snapshot.productionId!==productionId)throw new NativeStudioSdkError("FORBIDDEN","BLOCKED","NO_WRITE")}var receipt=z.strictObject({scope:z.string(),intent:DeviceRenderIntentSchema,prepared:PreparedDeviceRenderSchema});var savedRenderFailure=z.strictObject({code:z.string().regex(/^[A-Z][A-Z0-9_]{0,119}$/),outcome:z.enum(["NO_WRITE","REJECTED"]),semanticStatus:InterfaceSemanticStatusSchema,details:CapabilityVersionMismatchSchema.optional()});function requestPrefix(root,scope,requestId){const binding=scope.resource+"#"+sha256(scope.profile)+"#"+scope.projectId;return{binding,prefix:join(root,sha256(binding+"\n"+requestId))}}async function findRequest(root,conn,requestId){const legacy=requestPrefix(root,conn.scope,requestId);if(!conn.externalCredential)return{...legacy,saved:await optional(legacy.prefix+".request.json")};const{principalId,grantId}=await renderReceiptScope(conn.studio,conn.scope);const current=requestPrefix(root,{...conn.scope,profile:`oauth-grant:${principalId}/${grantId}`},requestId);const saved=await optional(current.prefix+".request.json");if(saved!==null)return{...current,saved};const old=await optional(legacy.prefix+".request.json");return old===null?{...current,saved:null}:{...legacy,saved:old}}function unknownReceipt(productionId,idempotencyKey){return{exitCode:1,output:{semanticStatus:"BLOCKED",error:{code:"OUTCOME_UNKNOWN",outcome:"UNKNOWN"},idempotencyKey,productionId,nextAction:"Read the original receipt with the same request or its prepared command."}}}async function readNativeReceipt(conn,prepared,prefix){try{return{exitCode:0,output:await conn.studio.deviceRenders.receipt(prepared)}}catch(error){if(!(error instanceof NativeStudioSdkError)||!["NOT_FOUND","OUTCOME_UNKNOWN","TRANSPORT_UNAVAILABLE","REQUEST_ABORTED"].includes(error.code))throw error;if(error.code==="NOT_FOUND"&&prefix){const failure=savedRenderFailure.safeParse(await optional(prefix+".failure.json").catch(()=>null));if(failure.success){const{code,outcome,semanticStatus,details}=failure.data;throw new NativeStudioSdkError(code,semanticStatus,outcome,null,[],details)}}return unknownReceipt(prepared.command.productionId,prepared.command.idempotencyKey)}}async function readTransferredReceipt(flags,env,stdin){if([...flags.keys()].some(key=>!["--input","--mcp-url","--token-file"].includes(key)))throw Error();const{scope,prepared}=DeviceRenderReceiptHandoffSchema.parse(await readInput(flags.get("--input"),stdin,true));if(prepared.command.tenantId!==scope.tenantId)throw Error();const conn=await callerRenderConnection(env,new Map([...flags,["--project",scope.projectId]]),false);try{if(conn.scope.resource!==scope.resource||conn.scope.tenantId!==scope.tenantId)throw new NativeStudioSdkError("FORBIDDEN","BLOCKED","NO_WRITE");const verified=await renderReceiptScope(conn.studio,conn.scope);if(verified.principalId!==scope.principalId||verified.grantId!==scope.grantId)throw new NativeStudioSdkError("FORBIDDEN","BLOCKED","NO_WRITE");await assertRenderProject(conn.studio,verified,prepared.command.productionId);return await readNativeReceipt(conn,prepared)}finally{await conn.close().catch(()=>{})}}async function readRenderSetup(kind,flags,env){const allowed=["--kind","--production","--project","--mcp-url","--token-file",kind==="receipt"?"--request":"--device"];if([...flags.keys()].some(key=>!allowed.includes(key)))throw Error();const renderKind=DeviceRenderReadSchema.shape.kind.parse(flags.get("--kind"));const productionId=z.uuid().parse(flags.get("--production"));const requestId=kind==="receipt"?z.uuid().parse(flags.get("--request")):void 0;const deviceId=z.uuid().optional().parse(flags.get("--device"));const conn=await callerRenderConnection(env,flags,false);const{scope,studio}=conn;try{await assertRenderProject(studio,scope,productionId);if(requestId){const home=await clientHome(env).catch(error=>{if(error.code==="ENOENT")return null;throw error});if(!home)return unknownReceipt(productionId,requestId);const{binding,prefix,saved}=await findRequest(join(home,"renders"),conn,requestId);if(!saved)return unknownReceipt(productionId,requestId);const{scope:savedScope,intent,prepared}=receipt.parse(saved);if(savedScope!==binding||intent.kind!==renderKind||prepared.kind!==renderKind||intent.productionId!==productionId||prepared.command.productionId!==productionId||prepared.command.tenantId!==scope.tenantId||intent.idempotencyKey!==requestId||prepared.command.idempotencyKey!==requestId||prepared.command.deviceExecution.deviceId!==intent.deviceId||prepared.command.deviceExecution.validationMode!==intent.validationMode)throw new NativeStudioSdkError("REVISION_CONFLICT","REVISION_CONFLICT","NO_WRITE");return await readNativeReceipt(conn,prepared,prefix)}const[basis,candidates]=await Promise.all([studio.deviceRenders.basis({kind:renderKind,productionId}),studio.deviceRenders.list({kind:renderKind,projectId:scope.projectId,deviceId})]);const{state}=renderDeviceSelection(candidates,deviceId);const eligible=basis.basis!==null&&state==="AVAILABLE";const selectionBlocker=state==="DEVICE_SELECTION_REQUIRED"||state==="INCOMPLETE_INVENTORY"?[state]:[];return{exitCode:eligible?0:4,output:{semanticStatus:eligible?"SUCCESS":"BLOCKED",productionId,...basis,blockers:[...basis.blockers,...selectionBlocker],eligible,candidates,deviceStatus:state==="INCOMPLETE_INVENTORY"?"INCONCLUSIVE":state==="UNAVAILABLE"?"UNAVAILABLE":"AVAILABLE"}}}finally{await conn.close().catch(()=>{})}}async function renderCommand(argv,env,stdin=process.stdin){const[kind,...args]=argv,flags=new Map;for(let i=0;i<args.length;i+=2){const k=args[i],v=args[i+1];if(!k||!v||v.startsWith("--")||flags.has(k)||!["--production","--project","--request","--device","--profile-id","--validation-mode","--kind","--render","--role","--output","--mcp-url","--token-file","--input"].includes(k))throw Error();flags.set(k,v)}if(flags.has("--input")){if(kind!=="receipt")throw Error();return readTransferredReceipt(flags,env,stdin)}if(kind==="eligibility"||kind==="receipt")return readRenderSetup(kind,flags,env);if(kind==="status"||kind==="download"){const allowed=new Set(["--kind","--project","--production","--render","--mcp-url","--token-file",...kind==="download"?["--role","--output"]:[]]);if(Array.from(flags.keys()).some(key=>!allowed.has(key)))throw Error();const input=DeviceRenderReadSchema.parse({kind:flags.get("--kind"),productionId:flags.get("--production"),renderId:flags.get("--render")});const conn2=await callerRenderConnection(env,flags,false);try{if(kind==="status"){const view=await conn2.studio.deviceRenders.get(input);if(view.projectId!==conn2.scope.projectId)throw new NativeStudioSdkError("FORBIDDEN","BLOCKED","NO_WRITE");return{exitCode:0,output:view}}const filename=flags.get("--output");if(!filename)throw Error();const request=DeviceRenderDownloadSchema.parse({...input,role:flags.get("--role")??"VIDEO"});const output=await conn2.studio.deviceRenders.download(request,void 0,conn2.scope.projectId);if(output.object.projectId!==conn2.scope.projectId)throw new NativeStudioSdkError("FORBIDDEN","BLOCKED","NO_WRITE");await write(resolve(filename),output.bytes,true);return{exitCode:0,output:{semanticStatus:"SUCCESS",renderId:output.renderId,representationId:output.representationId,byteSize:output.object.byteSize,checksumSha256:output.object.checksumSha256}}}finally{await conn2.close().catch(()=>{})}}if(["--kind","--render","--role","--output"].some(key=>flags.has(key)))throw Error();const intent=DeviceRenderIntentSchema.parse({kind,productionId:flags.get("--production"),idempotencyKey:z.uuid().parse(flags.get("--request")),...flags.has("--device")?{deviceId:flags.get("--device")}:{},...flags.has("--profile-id")?{profileId:flags.get("--profile-id")}:{},...flags.has("--validation-mode")?{validationMode:flags.get("--validation-mode")}:{}});const conn=await callerRenderConnection(env,flags);try{await assertRenderProject(conn.studio,conn.scope,intent.productionId);const root=await directory(join(await clientHome(env,true),"renders"));const{binding,prefix,saved:previous}=await findRequest(root,conn,intent.idempotencyKey);if(previous){const old=receipt.parse(previous);if(old.scope!==binding||JSON.stringify(old.intent)!==JSON.stringify(intent))throw new NativeStudioSdkError("REVISION_CONFLICT","REVISION_CONFLICT","NO_WRITE");const result=await optional(prefix+".result.json");if(result)return{exitCode:0,output:result};return await readNativeReceipt(conn,old.prepared,prefix)}const prepared=await conn.studio.deviceRenders.prepare(intent);try{await write(prefix+".request.json",JSON.stringify({scope:binding,intent,prepared}),true)}catch(error){if(error.code!=="EEXIST")throw error;return unknownReceipt(intent.productionId,intent.idempotencyKey)}let output;try{output=await conn.studio.deviceRenders.start(prepared)}catch(e){if(e instanceof NativeStudioSdkError&&e.outcome!=="UNKNOWN")await write(prefix+".failure.json",JSON.stringify({code:e.code,outcome:e.outcome,semanticStatus:e.semanticStatus,...e.capabilityMismatch&&{details:e.capabilityMismatch}}),true).catch(()=>{});throw e}try{await write(prefix+".result.json",JSON.stringify(output),true)}catch{throw new NativeStudioSdkError("OUTCOME_UNKNOWN","BLOCKED","UNKNOWN")}return{exitCode:0,output}}finally{await conn.close().catch(()=>{})}}export{renderCommand};
@@ -0,0 +1 @@
1
+ import{profileAuthorization}from"./chunk-UFUFQA5U.js";import{readCredential,readInput}from"./chunk-4UQRT3ZH.js";import{NativeStudioAgentClient}from"./chunk-XMZKBILZ.js";import"./chunk-UOYNCE7I.js";import{profileHttpOrigin}from"./chunk-IKJ6VNJ6.js";import{defaultConnection,tenantConnection}from"./chunk-ISPIV2P6.js";import"./chunk-CBJIFAHD.js";import"./chunk-AZQLZA47.js";import"./chunk-Z44SK6DZ.js";import"./chunk-M32FI2OA.js";import"./chunk-NEZ7IY5E.js";import"./chunk-TT7IA5HB.js";import{constants,open}from"node:fs/promises";async function sourceBytes(path,maxBytes){const file=await open(path,constants.O_RDONLY|constants.O_NOFOLLOW);try{const stat=await file.stat();if(!stat.isFile()||stat.size<1||stat.size>maxBytes)throw Error();const bytes=Buffer.alloc(stat.size);let offset=0;while(offset<bytes.length){const{bytesRead}=await file.read(bytes,offset,bytes.length-offset,offset);if(!bytesRead)throw Error();offset+=bytesRead}if((await file.read(Buffer.alloc(1),0,1,offset)).bytesRead)throw Error();return bytes}finally{await file.close()}}async function importSourceCommand([kind,...args],env,stdin){if(kind!=="project"&&kind!=="original")throw Error();const flags=new Map;for(let index=0;index<args.length;index+=2){const name=args[index],value=args[index+1];if(!name||!value||value.startsWith("--")||flags.has(name)||!["--input","--file","--tenant","--origin","--mcp-url","--profile","--token-env","--token-file"].includes(name))throw Error();flags.set(name,value)}await defaultConnection(flags,env,true);const profile=flags.get("--profile");if(profile?["--origin","--mcp-url","--token-env","--token-file"].some(key=>flags.has(key)):flags.has("--origin")===flags.has("--mcp-url"))throw Error();const connected=profile?await profileAuthorization(profile):null;const resource=connected?.resource??flags.get("--mcp-url");const scope=resource?tenantConnection(resource):null;if(scope&&flags.has("--tenant")&&flags.get("--tenant")!==scope.tenantId)throw Error();const input=flags.get("--input"),file=flags.get("--file"),tenantId=scope?.tenantId??flags.get("--tenant"),baseUrl=flags.get("--origin")??(connected&&profile?await profileHttpOrigin(profile,connected.resource):resource?new URL(resource).origin:void 0);if(!input||!file||!tenantId||!baseUrl)throw Error();const authorization=connected?.authorization??await readCredential(flags,env);const studio=new NativeStudioAgentClient({tenantId,baseUrl,authorization:()=>authorization});const intent=await readInput(input,stdin);const metadata=typeof intent==="object"&&intent!==null&&"metadata"in intent?intent.metadata:null;const video=typeof metadata==="object"&&metadata!==null&&"kind"in metadata&&metadata.kind==="REFERENCE_VIDEO";const bytes=await sourceBytes(file,(kind==="original"||video?128:8)*1024*1024);const receipt=kind==="project"?await studio.directSources.importProjectSource(intent,bytes):await studio.directSources.importOriginal(intent,bytes);if(receipt.state==="SUBMITTED")return{exitCode:0,output:receipt};const output="registration"in receipt?{artifactId:receipt.registration.artifact.id,representationId:receipt.registration.primaryRepresentation.id}:{artifactId:receipt.original.artifactId,representationId:receipt.original.representationId,sourceId:receipt.original.sourceId,version:receipt.original.version};return{exitCode:0,output:{state:receipt.state,...output}}}export{importSourceCommand};
@@ -0,0 +1 @@
1
+ import{CapabilityDescribeSchema,CapabilityGroupsSchema,CapabilityInvocationInputSchema,CapabilityInvocationOutputSchema,DeviceDiscoveryInputSchema,DeviceRenderAdmissionSchema,DeviceRenderDownloadSchema,DeviceRenderIntentSchema,DeviceRenderReadSchema,DeviceRenderReceiptHandoffSchema,McpEntryToolNames,NativeStudioAgentClient,NativeStudioDeviceRenders,NativeStudioMcpClient,NativeStudioNavigationClient,NativeStudioNavigationFacade,NativeStudioResourceDataClient,NativeStudioResourceDeliveryAdmissionError,NativeStudioRuntimeAuthorityClient,NavigationGroupIdSchema,NavigationGroups,NavigationProfile,NavigationProfileKey,NavigationToolNames,PreparedDeviceRenderSchema,assertCarrierCoverage,issueDeviceEnrollment,lookupDeviceEnrollment,navigationGroup,observeProduction,queryPages,readFederationLifecycleResult,recoverDeviceEnrollment,renderDeviceSelection,sdkCarrierDifferences,sdkImageMediaTools,sdkMcpTools,sdkOperations,submitDeviceEnrollment,validateDeviceEnrollmentHandoff,verifyWebhookNotification,waitForOperation}from"./chunk-XMZKBILZ.js";import{DeviceEnrollmentHandoffSchema,DeviceEnrollmentObservationSchema,DeviceEnrollmentScopeSchema,DeviceEnrollmentTicketSchema,DeviceStatusInputSchema,DeviceStatusSchema,FinalRenderViewSchema,LocalLibraryAdmissionSchema,LocalLibraryCommandQuerySchema,LocalLibraryCommandSchema,LocalLibraryCommandStatusSchema,LocalLibraryProjectionPageSchema,LocalLibraryProjectionQuerySchema,LocalLibraryReferenceSchema,ProjectDeviceListSchema,RoughCutViewSchema,TenantRenderMediaTicketSchema,WorkspaceDeviceListInputSchema,WorkspaceDeviceListSchema,WorkspaceStatusSchema}from"./chunk-UOYNCE7I.js";import"./chunk-Z44SK6DZ.js";import{CapabilityVersionMismatchSchema,CapabilityVersionSchema,InterfaceSemanticStatusSchema}from"./chunk-M32FI2OA.js";import{NativeStudioSdkError,sdkInputError}from"./chunk-TT7IA5HB.js";export{CapabilityDescribeSchema,CapabilityGroupsSchema,CapabilityInvocationInputSchema,CapabilityInvocationOutputSchema,CapabilityVersionMismatchSchema,CapabilityVersionSchema,DeviceDiscoveryInputSchema,DeviceEnrollmentHandoffSchema,DeviceEnrollmentObservationSchema,DeviceEnrollmentScopeSchema,DeviceEnrollmentTicketSchema,DeviceRenderAdmissionSchema,DeviceRenderDownloadSchema,DeviceRenderIntentSchema,DeviceRenderReadSchema,DeviceRenderReceiptHandoffSchema,DeviceStatusInputSchema,DeviceStatusSchema,FinalRenderViewSchema,InterfaceSemanticStatusSchema,LocalLibraryAdmissionSchema,LocalLibraryCommandQuerySchema,LocalLibraryCommandSchema,LocalLibraryCommandStatusSchema,LocalLibraryProjectionPageSchema,LocalLibraryProjectionQuerySchema,LocalLibraryReferenceSchema,McpEntryToolNames,NativeStudioAgentClient,NativeStudioDeviceRenders,NativeStudioMcpClient,NativeStudioNavigationClient,NativeStudioNavigationFacade,NativeStudioResourceDataClient,NativeStudioResourceDeliveryAdmissionError,NativeStudioRuntimeAuthorityClient,NativeStudioSdkError,NavigationGroupIdSchema,NavigationGroups,NavigationProfile,NavigationProfileKey,NavigationToolNames,PreparedDeviceRenderSchema,ProjectDeviceListSchema,RoughCutViewSchema,TenantRenderMediaTicketSchema,WorkspaceDeviceListInputSchema,WorkspaceDeviceListSchema,WorkspaceStatusSchema,assertCarrierCoverage,issueDeviceEnrollment,lookupDeviceEnrollment,navigationGroup,observeProduction,queryPages,readFederationLifecycleResult,recoverDeviceEnrollment,renderDeviceSelection,sdkCarrierDifferences,sdkImageMediaTools,sdkInputError,sdkMcpTools,sdkOperations,submitDeviceEnrollment,validateDeviceEnrollmentHandoff,verifyWebhookNotification,waitForOperation};
@@ -0,0 +1 @@
1
+ import{StdioLines}from"./chunk-JFC6ZIGA.js";import{readCredential}from"./chunk-4UQRT3ZH.js";import{defaultConnection}from"./chunk-ISPIV2P6.js";import{FileOAuthProvider}from"./chunk-CBJIFAHD.js";import"./chunk-AZQLZA47.js";import"./chunk-Z44SK6DZ.js";import"./chunk-M32FI2OA.js";import{secureEndpoint}from"./chunk-NEZ7IY5E.js";import"./chunk-TT7IA5HB.js";async function stdioRelayConfig(argv,environment){const options=new Map;for(let i=0;i<argv.length;i+=2){const key=argv[i],value=argv[i+1];if(!key||!["--profile","--mcp-url","--token-env","--token-file","--timeout-ms","--discovery"].includes(key)||!value||value.startsWith("--")||options.has(key))throw Error();options.set(key,value)}await defaultConnection(options,environment,false);const discovery=options.get("--discovery");if(discovery!==void 0&&discovery!=="contextual-v1")throw Error();const timeout=options.get("--timeout-ms")??"30000";if(!/^\d+$/.test(timeout))throw Error();const timeoutMs=Number(timeout);if(!Number.isSafeInteger(timeoutMs)||timeoutMs<100||timeoutMs>3e5)throw Error();const profile=options.get("--profile");let endpoint,read;if(profile){if(options.has("--mcp-url")||options.has("--token-env")||options.has("--token-file"))throw Error();endpoint=secureEndpoint((await FileOAuthProvider.load(profile)).data.resource);read=async signal=>{const{profileAuthorization}=await import("./oauth-Z26E4LJQ.js");const value=await profileAuthorization(profile,signal);if(secureEndpoint(value.resource).href!==endpoint.href)throw Error();return value.authorization}}else{if(!options.has("--mcp-url"))throw Error();endpoint=secureEndpoint(options.get("--mcp-url"));await readCredential(options,environment);read=()=>readCredential(options,environment)}let tail=Promise.resolve();return{endpoint,timeoutMs,...discovery?{discovery}:{},authorization(signal){const current=tail.then(()=>{signal.throwIfAborted();return read(signal)});tail=current.catch(()=>{});return current}}}import{isJSONRPCResultResponse}from"@modelcontextprotocol/client";var StdioContextualMenu=class{clear(){}request(request){return request}response(request,message){if(request.method!=="initialize"||!isJSONRPCResultResponse(message))return message;return{...message,result:{...message.result,instructions:["Navigation guidance: standard tools/list is stable. Begin with workspace_caller, then discover missing capabilities with studio_capability_groups/search/describe. Execute discovered reads through studio_capability_query and writes through studio_capability_invoke, passing the original complete input under arguments. Capability names such as studio_start and studio_navigate are targets, not additional menu tools. Describe never installs tools. Follow native evidence, inspect links and exact original request identities; reconcile uncertain writes without replay.",...typeof message.result.instructions==="string"?[message.result.instructions]:[]].join("\n")}}}};import{StreamableHTTPClientTransport,deserializeMessage,serializeMessage,isJSONRPCRequest,isJSONRPCNotification,isJSONRPCResultResponse as isJSONRPCResultResponse2,isJSONRPCErrorResponse}from"@modelcontextprotocol/client";var STDIO_RESPONSE_LIMIT=32*1024*1024;function stdioRelayFetch(config,shutdown){return async(input,init)=>{const target=new URL(input instanceof Request?input.url:String(input));if(target.href!==config.endpoint.href)throw Error();const signal=AbortSignal.any([shutdown,...init?.signal?[init.signal]:[],AbortSignal.timeout(config.timeoutMs)]);const authorization=await config.authorization(signal);signal.throwIfAborted();const headers=new Headers(init?.headers);headers.set("authorization",authorization);const response=await fetch(input,{...init,headers,signal,redirect:"error"});if(!response.body)return response;const declared=response.headers.get("content-length");if(declared&&(!/^\d+$/.test(declared)||Number(declared)>STDIO_RESPONSE_LIMIT)){await response.body.cancel();throw Error()}const reader=response.body.getReader();let size=0;const body=new ReadableStream({async pull(controller){try{const part=await reader.read();if(part.done){reader.releaseLock();controller.close();return}size+=part.value.byteLength;if(size>STDIO_RESPONSE_LIMIT){await reader.cancel();throw Error()}controller.enqueue(part.value)}catch(error){controller.error(error)}},async cancel(reason){await reader.cancel(reason);reader.releaseLock()}});return new Response(body,{status:response.status,statusText:response.statusText,headers:response.headers})}}var inputLimit=18*1024*1024;var concurrency=32;async function serveRemoteMcpStdio(config,input,output){const shutdown=new AbortController;const pending=new Map;const transport=new StreamableHTTPClientTransport(config.endpoint,{fetch:stdioRelayFetch(config,shutdown.signal),onInsufficientScope:"throw",reconnectionOptions:{maxRetries:0,maxReconnectionDelay:1,initialReconnectionDelay:1,reconnectionDelayGrowFactor:1}});const lines=new StdioLines(inputLimit);let queuedBytes=0,sends=0,stopped=false;let finish;const closed=new Promise(resolve=>{finish=resolve});const menu=config.discovery==="contextual-v1"?new StdioContextualMenu:void 0;function discard(id){const item=pending.get(id);if(item)clearTimeout(item.timer);pending.delete(id);return item}function write(message){if(stopped)return;const frame=serializeMessage(message);const bytes=Buffer.byteLength(frame);if(bytes>STDIO_RESPONSE_LIMIT||queuedBytes+bytes>STDIO_RESPONSE_LIMIT){void close(1);return}queuedBytes+=bytes;output.write(frame,error=>{queuedBytes-=bytes;if(error)void close(1)})}function fail(id,noWrite=false){const item=discard(id);item?.abort.abort();write({jsonrpc:"2.0",id,error:{code:-32603,message:"Remote MCP request unavailable",data:{semanticStatus:"INTERNAL_OPERATIONAL_FAILURE",outcome:noWrite?"NO_WRITE":"UNKNOWN"}}})}async function forward(message){if(isJSONRPCNotification(message)&&message.method==="notifications/cancelled"){const id=message.params?.requestId;if(typeof id==="string"||typeof id==="number")discard(id)?.abort.abort();if((transport.protocolVersion??"")>="2026-07-28")return}const request=isJSONRPCRequest(message)?message:null;if(request&&(pending.has(request.id)||pending.size>=concurrency||sends>=concurrency)){if(pending.has(request.id)){void close(2);return}fail(request.id,true);return}if(!request&&sends>=concurrency){void close(2);return}if(request){const version=request.method==="initialize"?request.params?.protocolVersion:request.params?._meta?.["io.modelcontextprotocol/protocolVersion"];if(typeof version==="string")transport.setProtocolVersion(version);const abort=new AbortController;const timer=setTimeout(()=>{if(pending.has(request.id))fail(request.id)},config.timeoutMs);timer.unref();pending.set(request.id,{abort,timer,request})}sends++;try{await transport.send(request&&menu?menu.request(request):message,request?{requestSignal:pending.get(request.id).abort.signal,onRequestStreamEnd:()=>{if(pending.has(request.id))fail(request.id)}}:{requestSignal:shutdown.signal})}catch{if(request&&pending.has(request.id))fail(request.id)}finally{sends--}}transport.onmessage=message=>{if(isJSONRPCResultResponse2(message)||isJSONRPCErrorResponse(message)){if(message.id===void 0)return;const item=discard(message.id);if(!item)return;if(item.request.method==="initialize"&&isJSONRPCResultResponse2(message)&&typeof message.result.protocolVersion==="string")transport.setProtocolVersion(message.result.protocolVersion);if(menu)message=menu.response(item.request,message)}if(isJSONRPCNotification(message)&&message.method==="notifications/tools/list_changed")menu?.clear();write(message)};transport.onerror=()=>{};function data(chunk){if(stopped)return;const bytes=Buffer.isBuffer(chunk)?chunk:Buffer.from(chunk);try{lines.push(bytes,line=>{void forward(deserializeMessage(new TextDecoder("utf-8",{fatal:true}).decode(line)));return!stopped})}catch{void close(2)}}function end(){void close(lines.incomplete?2:0)}function streamError(){void close(1)}async function close(code=0){if(stopped)return;stopped=true;shutdown.abort();for(const item of pending.values()){clearTimeout(item.timer);item.abort.abort()}pending.clear();menu?.clear();lines.clear();input.off("data",data).off("end",end).off("error",streamError);input.pause();output.off("error",streamError);try{await transport.close()}catch{code||=1}finish(code)}await transport.start();input.on("data",data).once("end",end).once("error",streamError);output.once("error",streamError);return{close,closed}}async function runMcpStdio(argv,environment){try{const config=await stdioRelayConfig(argv,environment);const handle=await serveRemoteMcpStdio(config,process.stdin,process.stdout);const stop=()=>{void handle.close()};process.once("SIGINT",stop);process.once("SIGTERM",stop);const code=await handle.closed;process.off("SIGINT",stop);process.off("SIGTERM",stop);if(code)process.stderr.write("NativeStudio MCP stdio connection failed.\n");return code}catch{process.stderr.write("NativeStudio MCP stdio configuration failed; run nvs status and nvs connect after account sign-in, or use explicit credentials.\n");return 2}}export{runMcpStdio};
@@ -0,0 +1 @@
1
+ import{workspaceCommand,workspaceProject}from"./chunk-VJ4SCIR5.js";import"./chunk-UFUFQA5U.js";import"./chunk-4UQRT3ZH.js";import"./chunk-DBOQPJLY.js";import"./chunk-2UYKJ6YN.js";import"./chunk-XMZKBILZ.js";import"./chunk-UOYNCE7I.js";import"./chunk-ISPIV2P6.js";import"./chunk-CBJIFAHD.js";import"./chunk-AZQLZA47.js";import"./chunk-Z44SK6DZ.js";import"./chunk-M32FI2OA.js";import"./chunk-NEZ7IY5E.js";import"./chunk-TT7IA5HB.js";export{workspaceCommand,workspaceProject};