@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
@@ -1 +0,0 @@
1
- import{LocalCompositionBrowserSelectionSchema,LocalDoctorReportSchema,LocalManagementInventorySchema,LocalRuntimeComponentSchema,LocalRuntimeDescriptorSchema,LocalToolChoiceSchema,LocalToolSelectionSchema,LocalUpdatePlanSchema,NativeStudioLocalRuntimeClient,RuntimeCaptionAssets,asset,catalogue,newerVersion,select}from"./chunk-6EZX2TRX.js";import{canonicalLocalJson,importedNormalizationValidationProfile,localLibraryProfile,referenceThumbnailProfile,tenantRenderValidationProfile,whisperCppRecognitionProfile}from"./chunk-APNZQZFB.js";import{assertExecutable,digestPrivateFile,directory,entries,fail,localSocketPath,optional,privateAccess,read,runtimeLoginProtocol,sha256,sha512,verifyBackup,write}from"./chunk-DLW42PJ6.js";import{z}from"zod";import{constants,createReadStream}from"node:fs";import{open,realpath}from"node:fs/promises";import{isAbsolute}from"node:path";import{createHash}from"node:crypto";var InstalledToolPathsSchema=z.strictObject({mode:z.literal("INSTALLED").optional(),ffmpeg:z.string().min(1).max(4096),ffprobe:z.string().min(1).max(4096),compositionBrowser:z.string().min(1).max(4096).optional(),captionAssetsDirectory:z.string().min(1).max(4096).optional(),whisper:z.strictObject({binary:z.string().min(1).max(4096),model:z.string().min(1).max(4096)}).optional()});async function toolPreference(previous,cloud,explicit){if(explicit)return LocalToolChoiceSchema.parse(explicit);const raw=previous?JSON.parse((await read(previous,32768)).toString()):cloud?JSON.parse((await read(cloud,32768)).toString()).tools:null;const selected=raw?LocalToolSelectionSchema.parse(raw):null;return selected?.mode==="INSTALLED"?{...selected,mode:"INSTALLED"}:{mode:"MANAGED",...selected?.cpuSpeech?{cpuSpeech:selected.cpuSpeech}:{}}}async function captureInstalledTools(input,host=process){const paths=InstalledToolPathsSchema.parse(input);if(paths.compositionBrowser&&(host.platform!=="linux"||host.arch!=="x64"))fail("COMPOSITION_BROWSER_PLATFORM_UNAVAILABLE");if(paths.whisper&&(host.platform!=="darwin"||host.arch!=="arm64"))fail("LOCAL_PROFILE_UNAVAILABLE");async function capture(candidate,executable=true){if(!isAbsolute(candidate))fail("TOOL_PATH_INVALID");const path=await realpath(candidate);if(executable)await assertExecutable(path);const file=await open(path,constants.O_RDONLY|constants.O_NOFOLLOW|constants.O_NONBLOCK);try{const before=await file.stat();if(!before.isFile()||before.size<1||before.size>256*1024*1024)fail("TOOL_PATH_INVALID");const h=createHash("sha256");let count=0;for await(const chunk of createReadStream(path,{fd:file.fd,autoClose:false})){count+=chunk.length;if(count>before.size)fail("TOOL_CHANGED");h.update(chunk)}const after=await file.stat();if(count!==before.size||after.size!==before.size||after.mtimeMs!==before.mtimeMs)fail("TOOL_CHANGED");return{path,digest:h.digest("hex")}}finally{await file.close()}}const compositionBrowser=paths.compositionBrowser?await capture(paths.compositionBrowser):void 0;if(compositionBrowser&&!LocalCompositionBrowserSelectionSchema.safeParse(compositionBrowser).success)fail("COMPOSITION_BROWSER_INTEGRITY_INVALID");const model=paths.whisper?await capture(paths.whisper.model,false):void 0;if(model&&model.digest!==whisperCppRecognitionProfile.modelSha256)fail("LOCAL_ASR_IDENTITY_MISMATCH");const binary=paths.whisper?await capture(paths.whisper.binary):void 0;if(paths.captionAssetsDirectory&&!isAbsolute(paths.captionAssetsDirectory))fail("CAPTION_ASSET_LOCATION_INVALID");return LocalToolChoiceSchema.parse({mode:"INSTALLED",ffmpeg:await capture(paths.ffmpeg),ffprobe:await capture(paths.ffprobe),...compositionBrowser?{compositionBrowser}:{},...paths.captionAssetsDirectory?{captionAssetsDirectory:await realpath(paths.captionAssetsDirectory)}:{},...binary&&model?{whisper:{binaryPath:binary.path,binarySha256:binary.digest,modelPath:model.path}}:{}})}import{constants as constants2}from"node:fs";import{open as open2}from"node:fs/promises";import{createHash as createHash2}from"node:crypto";async function bytesAt(base,name,maximum){const f=await open2(new URL(name,base),constants2.O_RDONLY|constants2.O_NOFOLLOW|constants2.O_NONBLOCK);try{const stat=await f.stat();if(!stat.isFile()||stat.size<1||stat.size>maximum)fail("BUNDLED_COMPONENT_INVALID");const bytes=Buffer.alloc(stat.size+1);let used=0;while(used<bytes.length){const{bytesRead}=await f.read(bytes,used,bytes.length-used,null);if(!bytesRead)break;used+=bytesRead}if(used!==stat.size)fail("BUNDLED_COMPONENT_CHANGED");return bytes.subarray(0,used)}finally{await f.close()}}async function readEmbeddedRuntime(base,manifestDigest){const raw=await bytesAt(base,"components/runtime.json",32768);if(sha256(raw)!==manifestDigest)fail("BUNDLED_COMPONENT_CHANGED");const component=LocalRuntimeComponentSchema.parse(JSON.parse(raw.toString()));const product=JSON.parse((await bytesAt(base,"package.json",32768)).toString());if(product.name!=="@nativestudio/cli"||product.version!==component.version)fail("BUNDLED_COMPONENT_IDENTITY_INVALID");const bytes=await bytesAt(base,"components/runtime.tgz",64*1024*1024);if(bytes.length!==component.byteSize||createHash2("sha512").update(bytes).digest("hex")!==component.sha512)fail("BUNDLED_COMPONENT_INTEGRITY_INVALID");const descriptor=LocalRuntimeDescriptorSchema.parse({...component.descriptor,platform:{os:process.platform,architecture:process.arch}});return{component,bytes,descriptor,trustFingerprint:manifestDigest}}async function embeddedRuntime(version){if(false)return null;const base=new URL(".",import.meta.resolve("@nativestudio/cli/package.json"));const value=await readEmbeddedRuntime(base,"d142c923fafc6e8047cd28ec08824e284817c7895dfd3d519c472ca56420b136");return version&&version!=="latest"&&version!==value.component.version?null:value}async function installationSource(c,version,bundled,dependencies){if(!bundled){const trusted2=await catalogue(c);return{release:select(trusted2.signed,version,c.rejectedVersions),origin:trusted2.origin,catalogueFingerprint:trusted2.fingerprint,trustFingerprint:trusted2.trustFingerprint,expiresAt:trusted2.signed.catalogue.expiresAt}}const core=await embeddedRuntime(version);if(!core||c.rejectedVersions.includes(core.descriptor.version))fail("BUNDLED_VERSION_UNAVAILABLE");const[major,minor]=process.versions.node.split(".").map(Number);if(major!==core.descriptor.node.major||minor<core.descriptor.node.minMinor)fail("NODE_VERSION_INCOMPATIBLE");const trusted=dependencies?await catalogue(c):null;const remote=trusted?select(trusted.signed,core.descriptor.version):null;if(remote&&(remote.package.sha512!==core.component.sha512||remote.package.byteSize!==core.component.byteSize||canonicalLocalJson(remote.descriptor)!==canonicalLocalJson(core.descriptor)||remote.resources&&(remote.resources.captions.sha512!==core.component.resources.captions.sha512||remote.resources.captions.byteSize!==core.component.resources.captions.byteSize)))fail("BUNDLED_COMPONENT_RELEASE_MISMATCH");return{release:{descriptor:core.descriptor,package:{source:"CLI",byteSize:core.component.byteSize,sha512:core.component.sha512},tools:remote?.tools??null,...remote?.resources?{resources:remote.resources}:{}},origin:trusted?.origin??"",catalogueFingerprint:trusted?.fingerprint??null,trustFingerprint:trusted?sha256(canonicalLocalJson([core.trustFingerprint,trusted.trustFingerprint])):core.trustFingerprint,expiresAt:trusted?.signed.catalogue.expiresAt??new Date(Date.now()+18e5).toISOString()}}async function approvedSource(c,plan){const source=await installationSource(c,plan.release.descriptor.version,"source"in plan.release.package,plan.catalogueFingerprint!==null);if(Date.parse(plan.expiresAt)<=Date.now()||source.trustFingerprint!==plan.trustFingerprint||canonicalLocalJson(source.release)!==canonicalLocalJson(plan.release))fail("PLAN_CHANGED");return source}function needsDependencyChannel(c,choice,haveCaptions=false){return!!choice&&(choice.mode==="MANAGED"&&!choice.reuseMedia||choice.mode==="INSTALLED"&&!choice.captionAssetsDirectory&&!haveCaptions&&!!c.catalogueUrl&&!!c.publicKeyFile)}var requiredRuntimeFiles=["package.json","dist/entry.js","dist/supervisor.mjs","dist/parent-lifetime.mjs","dist/execution-identity.json"];var allowedRuntimeFiles=new Set([...requiredRuntimeFiles,"README.md","LICENSE","dist/THIRD_PARTY_NOTICES.md","dist/BUNDLED_DEPENDENCIES.json","dist/agent-supervisor.mjs","dist/kokoro-worker.mjs","dist/capture.mjs","dist/hyperframe.manifest.json","dist/hyperframe.runtime.iife.js","dist/hyperframe-gsap.js","dist/hyperframe-dependencies.json","dist/hyperframe-notices.txt","dist/captions/NotoSansSC.ttf","dist/captions/NativeStudioSC-Regular.ttf","dist/captions/OFL.txt",...["helper.exe","helper.json"].map(name=>"dist/native/"+name)]);import{spawn}from"node:child_process";import{open as open3}from"node:fs/promises";import{dirname,join,delimiter}from"node:path";import{z as z2}from"zod";var runtimeEnvironment=()=>({...Object.fromEntries(["HOME","USER","LOGNAME","TMPDIR","CODEX_HOME","SystemRoot","SYSTEMROOT","USERPROFILE","LOCALAPPDATA","APPDATA","TEMP","TMP"].flatMap(k=>process.env[k]?[[k,process.env[k]]]:[])),PATH:dirname(process.execPath)+(process.platform==="win32"?"":delimiter+["/usr/bin","/bin"].join(delimiter)),LANG:"C",LC_ALL:"C",UV_THREADPOOL_SIZE:"2",NVS_INSTALL_OWNER:"MANAGED"});async function verifySlot(root,slot){if(requiredRuntimeFiles.some(name=>!Object.hasOwn(slot.files,name)))fail("SLOT_FILES_MISSING");for(const[name,hash]of Object.entries(slot.files)){if(!allowedRuntimeFiles.has(name))fail("SLOT_PATH_INVALID");if(await digestPrivateFile(join(root,name),64*1024*1024)!==hash)fail("SLOT_INTEGRITY_INVALID")}}async function probeEntry(root,option,args=[]){return new Promise((resolve,reject)=>{const child=spawn(process.execPath,["--max-old-space-size=256",join(root,"dist/entry.js"),option,...args],{env:runtimeEnvironment(),stdio:["ignore","pipe","ignore"],shell:false});const parts=[];let size=0;const timer=setTimeout(()=>child.kill("SIGKILL"),1e4);child.stdout.on("data",b=>{size+=b.length;if(size>65536)child.kill("SIGKILL");else parts.push(b)});child.on("error",reject);child.on("close",code=>{clearTimeout(timer);if(code!==0||size>65536)reject(Error("Runtime descriptor unavailable"));else resolve(Buffer.concat(parts))})})}async function probeProfile(root,slot,option,profile){await verifySlot(root,slot);try{const digest=(await probeEntry(root,option)).toString().trim();return digest===sha256(canonicalLocalJson(profile))}catch{return false}}function probeTenantMediaValidation(root,slot){return probeProfile(root,slot,"--tenant-media-validation-profile",tenantRenderValidationProfile)}function probeTenantMediaProcessing(root,slot){return probeProfile(root,slot,"--tenant-media-processing-profile",importedNormalizationValidationProfile)}function probeReferenceThumbnail(root,slot){return probeProfile(root,slot,"--reference-thumbnail-profile",referenceThumbnailProfile)}async function probeLocalLibrary(root,slot){await verifySlot(root,slot);try{return(await probeEntry(root,"--local-library-profile")).toString().trim()===sha256(canonicalLocalJson(localLibraryProfile))}catch{return false}}async function probeTenantComposition(root,slot){if(process.platform!=="linux"||process.arch!=="x64"||!slot.toolsConfigPath)return false;const selected=LocalToolSelectionSchema.parse(JSON.parse((await read(slot.toolsConfigPath,32768)).toString()));if(selected.mode!=="INSTALLED"||!selected.compositionBrowser)return false;await verifySlot(root,slot);try{const result=await probeEntry(root,"--tenant-composition-capability",["--tools-config",slot.toolsConfigPath]);return result.toString().trim()===selected.compositionBrowser.digest}catch{return false}}async function probeTenantSpeech(root,slot){if(process.platform!=="darwin")return false;await verifySlot(root,slot);try{return/^[a-f0-9]{64}$/.test((await probeEntry(root,"--tenant-speech-capability")).toString().trim())}catch{return false}}async function probeTenantTranscription(root,slot){if(process.platform!=="darwin"||process.arch!=="arm64"||!slot.toolsConfigPath)return false;await verifySlot(root,slot);try{return/^[a-f0-9]{64}$/.test((await probeEntry(root,"--tenant-transcription-capability",["--tools-config",slot.toolsConfigPath])).toString().trim())}catch{return false}}async function probeTenantQwenGeneration(root,slot,kind){await verifySlot(root,slot);return probeEntry(root,`--tenant-qwen-${kind}-capability`).then(value=>value.toString().trim()==="QWEN_"+kind.toUpperCase()+"_V1",()=>false)}async function probe(root,expected){const bytes=await probeEntry(root,"--describe");const descriptor=LocalRuntimeDescriptorSchema.parse(JSON.parse(bytes.toString()));if(canonicalLocalJson(descriptor)!==canonicalLocalJson(expected))fail("RUNTIME_DESCRIPTOR_MISMATCH");return descriptor}function supportsLoginService(root){return probeEntry(root,"--login-protocol").then(output=>output.toString().trim()===runtimeLoginProtocol,()=>false)}async function ownerClient(stateDirectory){await directory(stateDirectory);return new NativeStudioLocalRuntimeClient({stateDirectory,authorization:async()=>"Bearer "+(await read(join(stateDirectory,"control-token"),128)).toString()})}async function runningInventory(client,root,slot){const inventory=await client.inventory(),status=await client.status();if(canonicalLocalJson(inventory.descriptor)!==canonicalLocalJson(slot.descriptor)||status.versions.find(v=>v.component==="RUNTIME")?.executablePath!==join(root,"dist/entry.js"))fail("RUNTIME_ALREADY_RUNNING");return inventory}async function launch(root,slot,stateDirectory,cloudConfig,toolsConfig){await verifySlot(root,slot);await probe(root,slot.descriptor);await directory(stateDirectory);const existing=await ownerClient(stateDirectory);try{return await runningInventory(existing,root,slot)}catch(e){if(e instanceof Error&&e.message.includes("RUNTIME_ALREADY_RUNNING"))throw e}const log=await open3(join(stateDirectory,"runtime-process.log"),"a",384);const child=spawn(process.execPath,["--max-old-space-size=256",join(root,"dist/entry.js"),"serve","--state-dir",stateDirectory,...cloudConfig?["--cloud-config",cloudConfig]:[],...toolsConfig?["--tools-config",toolsConfig]:[]],{env:runtimeEnvironment(),detached:true,windowsHide:true,stdio:["ignore",log.fd,log.fd],shell:false});let spawnError=false;child.once("error",()=>{spawnError=true});child.unref();await log.close();const deadline=Date.now()+15e3;while(Date.now()<deadline){if(spawnError||child.exitCode!==null)fail("RUNTIME_START_FAILED");try{return await runningInventory(existing,root,slot)}catch{}await new Promise(r=>setTimeout(r,100))}child.kill("SIGTERM");fail("RUNTIME_START_UNCONFIRMED")}async function waitStopped(stateDirectory){const client=await ownerClient(stateDirectory),deadline=Date.now()+1e4;while(Date.now()<deadline){try{await client.inventory()}catch{const{lstat:lstat3}=await import("node:fs/promises");try{if(process.platform!=="win32")await lstat3(localSocketPath(stateDirectory))}catch(e){if(e.code==="ENOENT")return}const{createConnection}=await import("node:net");const closed=await new Promise(resolve=>{const s=createConnection(localSocketPath(stateDirectory));s.once("connect",()=>{s.destroy();resolve(false)});s.once("error",e=>resolve(["ECONNREFUSED","ENOENT"].includes(e.code??"")));s.setTimeout(300,()=>{s.destroy();resolve(false)})});if(closed)return}await new Promise(r=>setTimeout(r,100))}fail("RUNTIME_STOP_UNCONFIRMED")}async function socketAbsent(stateDirectory){const{createConnection}=await import("node:net");return new Promise(resolve=>{const socket=createConnection(localSocketPath(stateDirectory));socket.once("connect",()=>{socket.destroy();resolve(false)});socket.once("error",error=>resolve(["ECONNREFUSED","ENOENT"].includes(error.code??"")));socket.setTimeout(500,()=>{socket.destroy();resolve(false)})})}async function probeTools(root,stateDirectory,selection){const{execFile}=await import("node:child_process");const diagnostic=z2.strictObject({tool:z2.enum(["FFMPEG","FFPROBE"]),stage:z2.enum(["IDENTITY","VERSION","ENCODERS","DECODERS","FILTERS","DEMUXERS","MUXERS","FINAL_IDENTITY"]),cause:z2.enum(["IDENTITY_INVALID","VERSION_INVALID","CAPABILITY_MISSING","PROCESS_FAILED","TIMEOUT","CANCELLED"])});const failures=[];for(let attempt=0;attempt<2;attempt++){const result=await new Promise((resolve,reject)=>execFile(process.execPath,["--max-old-space-size=256",join(root,"dist/entry.js"),"--qualify-tools","--state-dir",stateDirectory,"--tools-config",selection],{env:runtimeEnvironment(),timeout:5e4,maxBuffer:65536},(error,stdout,stderr)=>error?reject(Error("Tool probe failed")):resolve({stdout,stderr})));const report=LocalDoctorReportSchema.parse(JSON.parse(result.stdout));let failure;for(const line of result.stderr.split("\n")){try{const parsed=diagnostic.safeParse(JSON.parse(line).toolProbe);if(parsed.success)failure=parsed.data}catch{}}if(failure)failures.push(failure);if(failures.length)await write(join(stateDirectory,"tool-qualification.json"),JSON.stringify({checkedAt:new Date().toISOString(),availability:report.availability,failures}));if(report.availability==="AVAILABLE")return report;if(!failure||!["TIMEOUT","PROCESS_FAILED"].includes(failure.cause))break}fail("TOOL_QUALIFICATION_FAILED")}import{constants as constants3}from"node:fs";import{open as open4,chmod}from"node:fs/promises";import{join as join2,isAbsolute as isAbsolute2}from"node:path";import{gunzipSync}from"node:zlib";function packageFiles(bytes,allowed2,directories){const data=gunzipSync(bytes,{maxOutputLength:64*1024*1024});const files=new Map;let offset=0;while(offset+512<=data.length){const header=data.subarray(offset,offset+512);if(header.every(b=>b===0)){if(!data.subarray(offset).every(b=>b===0))fail("PACKAGE_FORMAT_INVALID");break}const text=(a,b)=>header.subarray(a,b).toString().replace(/\0.*$/s,"");const number=(a,b)=>{const v=text(a,b).trim();if(!/^[0-7]+$/.test(v))fail("PACKAGE_FORMAT_INVALID");return parseInt(v,8)};const sum=number(148,156);let actual=0;for(let i=0;i<512;i++)actual+=i>=148&&i<156?32:header[i];if(actual!==sum||!text(257,263).startsWith("ustar"))fail("PACKAGE_FORMAT_INVALID");const prefix=text(345,500),path=(prefix?prefix+"/":"")+text(0,100),size=number(124,136),kind=text(156,157);if(!Number.isSafeInteger(size)||size<0||offset+512+size>data.length)fail("PACKAGE_FORMAT_INVALID");if(kind==="5"){if(!directories.test(path)||size!==0)fail("PACKAGE_PATH_INVALID")}else{if(kind!=="0"&&kind!=="")fail("PACKAGE_LINK_OR_METADATA_REFUSED");if(!path.startsWith("package/")||!allowed2.has(path.slice(8))||files.has(path.slice(8)))fail("PACKAGE_PATH_INVALID");files.set(path.slice(8),data.subarray(offset+512,offset+512+size))}offset+=512+Math.ceil(size/512)*512}return files}var names=Object.keys(RuntimeCaptionAssets);var allowed=new Set(names.map(n=>"dist/captions/"+n));async function captionDirectory(path){if(!isAbsolute2(path))fail("CAPTION_ASSET_LOCATION_INVALID");const files=new Map;for(const name of names){const f=await open4(join2(path,name),constants3.O_RDONLY|constants3.O_NOFOLLOW|constants3.O_NONBLOCK);try{const s=await f.stat();if(!s.isFile()||s.size<1||s.size>20*1024*1024)fail("CAPTION_ASSET_INVALID");const bytes=Buffer.alloc(s.size+1);let used=0;while(used<bytes.length){const part=await f.read(bytes,used,bytes.length-used,null);if(!part.bytesRead)break;used+=part.bytesRead}if(used!==s.size||sha256(bytes.subarray(0,used))!==RuntimeCaptionAssets[name])fail("CAPTION_ASSET_INVALID");files.set("dist/captions/"+name,bytes.subarray(0,used))}finally{await f.close()}}return files}async function verifyCaptionDirectory(path){await captionDirectory(path)}async function managedCaptions(ledger,resource,origin){const path=join2(await directory(join2(ledger.root,"resources")),resource.sha512+".tgz");let bytes;let downloaded=false;try{bytes=await read(path,resource.byteSize)}catch(e){if(e.code!=="ENOENT")throw e;bytes=await asset(resource,origin);downloaded=true}if(bytes.length!==resource.byteSize||sha512(bytes)!==resource.sha512)fail("CAPTION_RESOURCE_INTEGRITY_INVALID");const files=packageFiles(bytes,allowed,/^package(?:\/dist(?:\/captions)?)?\/?$/);if(files.size!==names.length)fail("CAPTION_ASSET_INVALID");for(const name of names)if(sha256(files.get("dist/captions/"+name))!==RuntimeCaptionAssets[name])fail("CAPTION_ASSET_INVALID");if(downloaded){try{await write(path,bytes,true)}catch(e){if(e.code!=="EEXIST")throw e;const existing=await read(path,resource.byteSize);if(existing.length!==resource.byteSize||sha512(existing)!==resource.sha512)fail("CAPTION_RESOURCE_INTEGRITY_INVALID")}}return files}async function stageResources(ledger,candidate,previous,plan,origin){const root=ledger.slotPath(candidate);const present=[...allowed].filter(p=>candidate.files[p]);if(present.length){await captionDirectory(join2(root,"dist/captions"));return candidate}const choice=plan.toolSelection;let files;if(choice?.mode==="INSTALLED"&&choice.captionAssetsDirectory)files=await captionDirectory(choice.captionAssetsDirectory);else if(previous&&[...allowed].some(p=>previous.files[p]))files=await captionDirectory(join2(ledger.slotPath(previous),"dist/captions"));else if(plan.release.resources)files=await managedCaptions(ledger,plan.release.resources.captions,origin);if(!files)return candidate;await directory(join2(root,"dist/captions"));const hashes={...candidate.files};for(const[path,bytes]of files){await write(join2(root,path),bytes,true);await chmod(join2(root,path),256);hashes[path]=sha256(bytes)}return{...candidate,files:hashes}}async function verifyManagedMedia(previous,reuse){if(!previous)fail("MANAGED_TOOLS_UNAVAILABLE");const current=LocalToolSelectionSchema.parse(JSON.parse((await read(previous,32768)).toString()));if(current.mode!=="MANAGED"||canonicalLocalJson({schemaVersion:1,ffmpeg:current.ffmpeg,ffprobe:current.ffprobe})!==canonicalLocalJson(reuse))fail("MANAGED_TOOLS_CHANGED");const files=await captureInstalledTools({ffmpeg:reuse.ffmpeg.path,ffprobe:reuse.ffprobe.path});if(files.mode!=="INSTALLED"||canonicalLocalJson(files.ffmpeg)!==canonicalLocalJson(reuse.ffmpeg)||canonicalLocalJson(files.ffprobe)!==canonicalLocalJson(reuse.ffprobe))fail("MANAGED_TOOLS_CHANGED");return{mode:"MANAGED",ffmpeg:current.ffmpeg,ffprobe:current.ffprobe}}import{randomUUID}from"node:crypto";import{lstat}from"node:fs/promises";import{join as join3}from"node:path";function toolIdentity(tools){return[tools.ffmpeg.digest,tools.ffprobe.digest,...tools.cpuSpeech?[canonicalLocalJson({...tools.cpuSpeech,voiceIds:[...tools.cpuSpeech.voiceIds].sort((a,b)=>a-b)})]:[],...tools.mode==="INSTALLED"&&tools.compositionBrowser?[tools.compositionBrowser.digest]:[],...tools.mode==="INSTALLED"&&tools.whisper?[tools.whisper.binarySha256,whisperCppRecognitionProfile.modelSha256]:[]].join(":")}async function identity(path,cloud){if(!path)return null;const raw=JSON.parse((await read(path,32768)).toString());const tools=LocalToolSelectionSchema.parse(cloud?raw.tools:raw);return toolIdentity(tools)}async function effective(path,cloud){return path?identity(path,false):identity(cloud,true)}function supportedRenderer(expected,digest){return expected.rendererDigest===digest||!!expected.compatibleRenderers?.some(r=>r.rendererDigest===digest)}async function assertPendingCompatible(raw,expected,previous,next,cloud){const i=LocalManagementInventorySchema.parse(raw);if(i.pendingRenderers.some(d=>!supportedRenderer(expected,d)))fail("NATIVE_RECOVERY_REQUIRED");if(i.pendingExecutions+i.pendingRequests===0)return;if(i.descriptor.profileDigest!==expected.profileDigest&&!expected.compatibleRenderers?.some(r=>r.profileDigest===i.descriptor.profileDigest))fail("NATIVE_RECOVERY_REQUIRED");const before=await effective(previous,cloud);const after=await effective(next,cloud);if(!before||before!==after)fail("NATIVE_RECOVERY_REQUIRED")}async function assertPendingToolIdentity(raw,previous,cloud,next){const i=LocalManagementInventorySchema.parse(raw);if(i.pendingExecutions+i.pendingRequests>0&&await effective(previous,cloud)!==next)fail("NATIVE_RECOVERY_REQUIRED")}async function assertNoStoppedJournal(state){for(const suffix of["","-wal","-shm","-journal"]){try{await lstat(join3(state,"journal.sqlite"+suffix))}catch(e){if(e.code==="ENOENT")continue;throw e}fail("RUNTIME_STATUS_REQUIRED")}}async function prepareInstallation(manager,version,raw,bundled=false){const c=await manager.configuration(),current=(await manager.ledger.current()).value;if(current.transition)fail("ACTIVATION_IN_PROGRESS");const explicit=raw===void 0?void 0:LocalToolChoiceSchema.parse(raw),source=await installationSource(c,version,bundled,needsDependencyChannel(c,explicit,Object.entries(RuntimeCaptionAssets).every(([name,hash])=>current.active?.files["dist/captions/"+name]===hash))),release=source.release,preference=await toolPreference(current.active?.toolsConfigPath??null,c.cloudConfigFile,explicit),toolSelection=explicit||preference.mode==="INSTALLED"||release.tools?preference:void 0;if(toolSelection?.mode==="MANAGED"){if(toolSelection.reuseMedia)await verifyManagedMedia(current.active?.toolsConfigPath??null,toolSelection.reuseMedia);else if(!release.tools)fail("MANAGED_TOOLS_UNAVAILABLE")}let runtimeRevision=null;try{const inventory=await(await ownerClient(c.stateDirectory)).inventory();runtimeRevision=inventory.runtimeRevision;const previous=current.active?.toolsConfigPath??null;await assertPendingCompatible(inventory,release.descriptor,previous,previous,c.cloudConfigFile);const desired=preference.mode==="INSTALLED"?preference:preference.reuseMedia??release.tools;if(desired)await assertPendingToolIdentity(inventory,previous,c.cloudConfigFile,preference.mode==="INSTALLED"?toolIdentity(preference):preference.reuseMedia?toolIdentity({mode:"MANAGED",ffmpeg:preference.reuseMedia.ffmpeg,ffprobe:preference.reuseMedia.ffprobe,...preference.cpuSpeech?{cpuSpeech:preference.cpuSpeech}:{}}):release.tools.ffmpeg.sha256+":"+release.tools.ffprobe.sha256+(preference.cpuSpeech?":"+canonicalLocalJson({...preference.cpuSpeech,voiceIds:[...preference.cpuSpeech.voiceIds].sort((a,b)=>a-b)}):""))}catch(e){if(e instanceof Error&&e.message.includes("NATIVE_RECOVERY_REQUIRED"))throw e;if(!await socketAbsent(c.stateDirectory))fail("RUNTIME_STATUS_REQUIRED");await assertNoStoppedJournal(c.stateDirectory)}const body={protocol:"NVS_LOCAL_UPDATE_PLAN_V1",planId:randomUUID(),installationRevision:current.revision,runtimeRevision,catalogueFingerprint:source.catalogueFingerprint,trustFingerprint:source.trustFingerprint,release,...toolSelection?{toolSelection}:{},createdAt:new Date().toISOString(),expiresAt:new Date(Math.min(Date.now()+18e5,Date.parse(source.expiresAt))).toISOString()};const plan=LocalUpdatePlanSchema.parse({...body,fingerprint:sha256(canonicalLocalJson(body))});await write(join3(manager.ledger.root,"plans",plan.planId+".json"),canonicalLocalJson(plan),true);return plan}import{randomUUID as randomUUID2}from"node:crypto";import{join as join4,dirname as dirname2}from"node:path";import{z as z3}from"zod";async function grant(manager,raw,output){const i=z3.strictObject({tenantId:z3.uuid(),deviceId:z3.uuid(),expiresAt:z3.iso.datetime({offset:true})}).parse(raw);const c=await manager.configuration(),client=await ownerClient(c.stateDirectory);await directory(dirname2(output));const connector=await client.call({operation:"session.issue",...i});await write(output,canonicalLocalJson(connector),true);await write(join4(manager.ledger.root,"grants",randomUUID2()+".json"),canonicalLocalJson({...i,output}),true);return{granted:true,tenantId:i.tenantId,deviceId:i.deviceId,expiresAt:i.expiresAt}}async function reconnect(manager){const{entries:entries2}=await import("./files-JJ6YOULB.js"),c=await manager.configuration(),client=await ownerClient(c.stateDirectory);let renewed=0,blocked=0;for(const name of await entries2(join4(manager.ledger.root,"grants"))){if(!/^[0-9a-f-]{36}\.json$/.test(name))continue;try{const g=z3.strictObject({tenantId:z3.uuid(),deviceId:z3.uuid(),expiresAt:z3.iso.datetime({offset:true}),output:z3.string().min(1)}).parse(await optional(join4(manager.ledger.root,"grants",name)));if(Date.parse(g.expiresAt)<=Date.now())continue;const connector=await client.call({operation:"session.issue",tenantId:g.tenantId,deviceId:g.deviceId,expiresAt:g.expiresAt});await write(g.output,canonicalLocalJson(connector));renewed++}catch{blocked++}}return{renewed,blocked}}import{randomUUID as randomUUID4}from"node:crypto";import{join as join9}from"node:path";import{z as z5}from"zod";import{z as z4}from"zod";import{join as join5}from"node:path";var slotSchema=z4.strictObject({id:z4.uuid(),descriptor:LocalRuntimeDescriptorSchema,toolsConfigPath:z4.string().nullable().default(null),files:z4.record(z4.string().min(1).max(100),z4.string().regex(/^[0-9a-f]{64}$/))});var transitionSchema=z4.strictObject({id:z4.uuid(),planId:z4.uuid(),fingerprint:z4.string().regex(/^[0-9a-f]{64}$/),phase:z4.enum(["STAGING","STAGED","DRAINING","ACTIVATING","VERIFYING","ROLLBACK_REQUIRED"]),previous:slotSchema.nullable(),candidate:slotSchema.nullable(),backupPath:z4.string().nullable(),failedPhase:z4.enum(["STAGING","STAGED","DRAINING","ACTIVATING","VERIFYING","ROLLBACK_REQUIRED"]).nullable().default(null)});var installationSchema=z4.strictObject({revision:z4.int().nonnegative(),active:slotSchema.nullable(),transition:transitionSchema.nullable()});var recordSchema=z4.strictObject({previous:z4.string().nullable(),value:installationSchema,digest:z4.string().regex(/^[0-9a-f]{64}$/)});var InstallationLedger=class _InstallationLedger{constructor(root){this.root=root}root;static async open(path){const root=await directory(path);for(const name of["revisions","plans","slots","grants"])await directory(join5(root,name));return new _InstallationLedger(root)}static async openExisting(root){try{await privateAccess(root,"directory");await privateAccess(join5(root,"revisions"),"directory")}catch(error){if(error.code==="ENOENT")return null;throw error}return new _InstallationLedger(root)}current(){return this.load()}async hadCompletedVersion(version){let found=false;await this.load(entry=>{if(!entry.transition&&entry.active?.descriptor.version===version)found=true});return found}async load(visit){const names2=(await entries(join5(this.root,"revisions"))).filter(n=>/^\d{12}\.json$/.test(n)).sort();let previous=null,value={revision:0,active:null,transition:null};for(const[i,name]of names2.entries()){const raw=JSON.parse((await read(join5(this.root,"revisions",name),262144,true)).toString());const r=recordSchema.parse(raw);const expected=sha256(canonicalLocalJson({previous:raw.previous,value:raw.value}));if(r.value.revision!==i+1||r.previous!==previous||r.digest!==expected)fail("INSTALLATION_HISTORY_INVALID");previous=r.digest;value=r.value;visit?.(value)}return{value,digest:previous}}async commit(expected,next){const current=await this.current();if(current.value.revision!==expected.revision)fail("REVISION_CONFLICT");const value=installationSchema.parse({...next,revision:expected.revision+1});const record={previous:current.digest,value,digest:sha256(canonicalLocalJson({previous:current.digest,value}))};try{await write(join5(this.root,"revisions",String(value.revision).padStart(12,"0")+".json"),canonicalLocalJson(record),true)}catch(e){if(e.code==="EEXIST")fail("REVISION_CONFLICT");throw e}return value}slotPath(slot){return join5(this.root,"slots",slot.id)}};import{randomUUID as randomUUID3}from"node:crypto";import{chmod as chmod3}from"node:fs/promises";import{join as join7}from"node:path";import{chmod as chmod2}from"node:fs/promises";import{join as join6}from"node:path";async function unpack(bytes,root,expectedVersion){const files=packageFiles(bytes,allowedRuntimeFiles,/^package(?:\/dist(?:\/(?:native|captions))?)?\/?$/);if(!requiredRuntimeFiles.every(p=>files.has(p)))fail("PACKAGE_FILES_MISSING");const manifest=JSON.parse(files.get("package.json").toString());const deps=manifest.dependencies;if(manifest.name!=="@nativestudio/local-runtime"||manifest.version!==expectedVersion||manifest.type!=="module"||Object.keys(deps??{}).length||Object.keys(manifest.optionalDependencies??{}).length||["preinstall","install","postinstall","prepare"].some(name=>Object.hasOwn(manifest.scripts??{},name))||!["dist/entry.js","./dist/entry.js"].includes(manifest.bin?.["nvs-runtime"]??"")||Object.keys(manifest.bin??{}).length!==1)fail("PACKAGE_IDENTITY_INVALID");const hashes={};await directory(join6(root,"dist"));if([...files.keys()].some(p=>p.startsWith("dist/native/")))await directory(join6(root,"dist/native"));if([...files.keys()].some(p=>p.startsWith("dist/captions/")))await directory(join6(root,"dist/captions"));for(const[path,contents]of files){await write(join6(root,path),contents,true);await chmod2(join6(root,path),path.endsWith("entry.js")?320:256);hashes[path]=sha256(contents)}return hashes}async function stage(ledger,release,origin){const id=randomUUID3(),root=await directory(join7(ledger.root,"slots",id));const bundled=await embeddedRuntime(release.descriptor.version);if(bundled&&(bundled.component.byteSize!==release.package.byteSize||bundled.component.sha512!==release.package.sha512))fail("BUNDLED_COMPONENT_RELEASE_MISMATCH");if("source"in release.package&&!bundled)fail("BUNDLED_VERSION_UNAVAILABLE");const bytes=bundled?.bytes??("url"in release.package?await asset(release.package,origin):fail("BUNDLED_VERSION_UNAVAILABLE")),files=await unpack(bytes,root,release.descriptor.version);const slot={id,files,descriptor:release.descriptor,toolsConfigPath:null};await probe(root,slot.descriptor);return slot}async function managedTools(release,origin,stateDirectory,selectionId,cpuSpeech){if(!release.tools)return null;const result={};for(const name of["ffmpeg","ffprobe"]){const a=release.tools[name],dir=await directory(join7(stateDirectory,"tools",a.sha256)),path2=join7(dir,name+(process.platform==="win32"?".exe":""));try{if(sha256(await read(path2,256*1024*1024))!==a.sha256)fail("TOOL_INTEGRITY_INVALID")}catch(e){if(e.code!=="ENOENT")throw e;const bytes=await asset(a,origin);if(sha256(bytes)!==a.sha256)fail("TOOL_INTEGRITY_INVALID");await write(path2,bytes,true);await chmod3(path2,320)}result[name]={path:path2,digest:a.sha256}}const selection={mode:"MANAGED",ffmpeg:result.ffmpeg,ffprobe:result.ffprobe,...cpuSpeech?{cpuSpeech}:{}};const path=join7(await directory(join7(stateDirectory,"tool-selections")),selectionId+".json");await write(path,JSON.stringify(selection));return path}async function selectedTools(release,origin,state,slotId,cloudConfig,previousSelection,explicit){const preference=await toolPreference(previousSelection,cloudConfig,explicit);if(preference.mode==="INSTALLED"){const path=join7(await directory(join7(state,"tool-selections")),slotId+".json");const selection={...preference};delete selection.captionAssetsDirectory;await write(path,JSON.stringify(selection),true);return path}if(preference.mode==="MANAGED"&&preference.reuseMedia){const media=await verifyManagedMedia(previousSelection,preference.reuseMedia);const path=join7(await directory(join7(state,"tool-selections")),slotId+".json");await write(path,JSON.stringify({...media,...preference.cpuSpeech?{cpuSpeech:preference.cpuSpeech}:{}}),true);return path}if(explicit?.mode==="MANAGED"&&!release.tools)fail("MANAGED_TOOLS_UNAVAILABLE");return await managedTools(release,origin,state,slotId,preference.cpuSpeech)??previousSelection}import{lstat as lstat2,opendir}from"node:fs/promises";import{join as join8}from"node:path";async function containsLibraryFiles(root){let visited=0;async function walk(path,depth){if(depth>8||++visited>1e4)fail("NATIVE_RECOVERY_REQUIRED");const info=await lstat2(path);if(info.isFile()){await privateAccess(path,"file");return true}if(!info.isDirectory()||info.isSymbolicLink())fail("NATIVE_RECOVERY_REQUIRED");await privateAccess(path,"directory");const directory2=await opendir(path,{bufferSize:16});for await(const entry of directory2)if(await walk(join8(path,entry.name),depth+1))return true;return false}const library=join8(root,"library");try{await lstat2(library)}catch(error){if(error.code==="ENOENT")return false;throw error}try{return await walk(library,0)}catch(error){if(error.code==="ENOENT")fail("NATIVE_RECOVERY_REQUIRED");throw error}}async function assertLibraryCompatible(configuration,root,slot){let configured=false;if(configuration.cloudConfigFile){try{const value=JSON.parse((await read(configuration.cloudConfigFile,32768)).toString());if(!value||typeof value!=="object"||Array.isArray(value))fail("NATIVE_RECOVERY_REQUIRED");const capabilities=value.processorCapabilities;if(capabilities!==void 0&&!Array.isArray(capabilities))fail("NATIVE_RECOVERY_REQUIRED");configured=Array.isArray(capabilities)&&capabilities.some(kind=>kind==="LOCAL_MEDIA_INSPECT"||kind==="LOCAL_MEDIA_PUBLISH")}catch(error){if(error instanceof SyntaxError)fail("NATIVE_RECOVERY_REQUIRED");throw error}}if(!configured&&!await containsLibraryFiles(configuration.stateDirectory))return;if(!await probeLocalLibrary(root,slot))fail("NATIVE_RECOVERY_REQUIRED")}var configurationSchema=z5.strictObject({stateDirectory:z5.string().min(1).max(4096),catalogueUrl:z5.string().url().nullable().default(null),publicKeyFile:z5.string().min(1).max(4096).nullable().default(null),cloudConfigFile:z5.string().nullable().default(null),notifications:z5.boolean().default(true),rejectedVersions:z5.array(LocalRuntimeDescriptorSchema.shape.version).max(64).default([])}).refine(c=>!!c.catalogueUrl===!!c.publicKeyFile,"Release channel requires URL and key together");var LocalInstallationManager=class _LocalInstallationManager{constructor(ledger){this.ledger=ledger}ledger;static async open(root){return new _LocalInstallationManager(await InstallationLedger.open(root))}static async openExisting(root){const ledger=await InstallationLedger.openExisting(root);return ledger?new _LocalInstallationManager(ledger):null}async configure(raw,options={}){const c=configurationSchema.parse(raw);c.stateDirectory=await directory(c.stateDirectory);await write(join9(this.ledger.root,"configuration.json"),canonicalLocalJson(c),options.ifAbsent);return{configured:true}}async configuration(){const value=await optional(join9(this.ledger.root,"configuration.json"));if(!value)fail("CONFIGURATION_REQUIRED");return configurationSchema.parse(value)}async status(){const s=(await this.ledger.current()).value;let c;try{c=await this.configuration()}catch(error){if(error instanceof Error&&error.message.includes("CONFIGURATION_REQUIRED"))return{protocol:"NVS_LOCAL_INSTALLATION_STATUS_V1",revision:s.revision,activeVersion:s.active?.descriptor.version??null,running:null,phase:s.transition?.phase??"IDLE",nextActions:[{surface:"CLI",operation:"local.configure",availability:"AVAILABLE",reason:"INSTALL_REQUIRED"}]};throw error}let running=null;try{running=await(await ownerClient(c.stateDirectory)).status()}catch{}return{protocol:"NVS_LOCAL_INSTALLATION_STATUS_V1",revision:s.revision,activeVersion:s.active?.descriptor.version??null,entryPath:s.active?join9(this.ledger.slotPath(s.active),"dist/entry.js"):null,installOwner:"MANAGED",phase:s.transition?.phase??"IDLE",running,nextActions:[{surface:"CLI",operation:s.transition?"local.update.reconcile":s.active?"local.start":"local.install",availability:"AVAILABLE",reason:s.transition?"RECOVERY_REQUIRED":s.active?"READY":"INSTALL_REQUIRED"}]}}async reject(version){LocalRuntimeDescriptorSchema.shape.version.parse(version);const c=await this.configuration();await this.configure({...c,rejectedVersions:[...new Set([...c.rejectedVersions,version])]});return{rejected:true,version,selectedVersion:(await this.ledger.current()).value.active?.descriptor.version??null}}async check(){const c=await this.configuration();if(!c.catalogueUrl)return{installation:await this.status(),channel:"UNCONFIGURED",available:[],notifications:c.notifications,rejectedVersions:c.rejectedVersions};const v=await catalogue(c);return{installation:await this.status(),catalogueFingerprint:v.fingerprint,available:v.signed.catalogue.releases.filter(r=>r.descriptor.platform.os===process.platform&&r.descriptor.platform.architecture===process.arch).map(r=>r.descriptor),notifications:c.notifications,rejectedVersions:c.rejectedVersions}}prepare(version,choice){return prepareInstallation(this,version,choice)}prepareBundled(version,choice){return prepareInstallation(this,version,choice,true)}async plan(id){if(!z5.uuid().safeParse(id).success)fail("PLAN_INVALID");const p=LocalUpdatePlanSchema.parse(JSON.parse((await read(join9(this.ledger.root,"plans",id+".json"))).toString()));const{fingerprint,...body}=p;if(sha256(canonicalLocalJson(body))!==fingerprint)fail("PLAN_CHANGED");return p}async transition(s,phase,patch={}){if(!s.transition)fail("TRANSITION_REQUIRED");return this.ledger.commit(s,{active:s.active,transition:{...s.transition,...patch,phase}})}async apply(id,approval){const plan=await this.plan(id),c=await this.configuration();if(approval!==plan.fingerprint)fail("USER_APPROVAL_REQUIRED");const source=await approvedSource(c,plan);let s=(await this.ledger.current()).value;if(s.revision!==plan.installationRevision||s.transition)fail("REVISION_CONFLICT");if(plan.runtimeRevision!==null){const i=await(await ownerClient(c.stateDirectory)).inventory();if(i.runtimeRevision!==plan.runtimeRevision||i.pendingRenderers.some(d=>!supportedRenderer(plan.release.descriptor,d)))fail("REVISION_CONFLICT")}if(plan.runtimeRevision===null){if(!await socketAbsent(c.stateDirectory))fail("REVISION_CONFLICT");await assertNoStoppedJournal(c.stateDirectory)}s=await this.ledger.commit(s,{active:s.active,transition:{id:randomUUID4(),planId:id,fingerprint:approval,phase:"STAGING",previous:s.active,candidate:null,backupPath:null,failedPhase:null}});try{let candidate=await stage(this.ledger,plan.release,source.origin);candidate=await stageResources(this.ledger,candidate,s.active,plan,source.origin);await assertLibraryCompatible(c,this.ledger.slotPath(candidate),candidate);const tools=await selectedTools(plan.release,source.origin,c.stateDirectory,candidate.id,c.cloudConfigFile,s.active?.toolsConfigPath??null,plan.toolSelection);candidate={...candidate,toolsConfigPath:tools};if(tools)await probeTools(this.ledger.slotPath(candidate),c.stateDirectory,tools);s=await this.transition(s,"STAGED",{candidate});if(plan.runtimeRevision!==null){const client=await ownerClient(c.stateDirectory),i=await client.inventory();if(i.runtimeRevision!==plan.runtimeRevision||i.pendingRenderers.some(d=>!supportedRenderer(candidate.descriptor,d)))fail("REVISION_CONFLICT");await assertPendingCompatible(i,candidate.descriptor,s.active?.toolsConfigPath??null,tools,c.cloudConfigFile);await assertLibraryCompatible(c,this.ledger.slotPath(candidate),candidate);s=await this.transition(s,"DRAINING");const result=await client.call({operation:"runtime.stop",expectedRuntimeRevision:plan.runtimeRevision});if(!result||typeof result!=="object"||!("backupPath"in result)||typeof result.backupPath!=="string")fail("JOURNAL_BACKUP_REQUIRED");await verifyBackup(result.backupPath,c.stateDirectory);s=await this.transition(s,"ACTIVATING",{backupPath:result.backupPath});await waitStopped(c.stateDirectory);await assertPendingCompatible("inventory"in result?result.inventory:null,candidate.descriptor,s.active?.toolsConfigPath??null,tools,c.cloudConfigFile)}else{if(!await socketAbsent(c.stateDirectory))fail("REVISION_CONFLICT");await assertNoStoppedJournal(c.stateDirectory);s=await this.transition(s,"ACTIVATING")}await assertLibraryCompatible(c,this.ledger.slotPath(candidate),candidate);s=await this.ledger.commit(s,{active:candidate,transition:{...s.transition,phase:"VERIFYING"}});await this.startSlot(candidate,c);s=await this.ledger.commit(s,{active:candidate,transition:null});await this.reconnect();return{activated:true,revision:s.revision,version:candidate.descriptor.version}}catch(error){const actual=(await this.ledger.current()).value;if(actual.transition?.planId===id)await this.transition(actual,"ROLLBACK_REQUIRED",{failedPhase:actual.transition.phase});throw error}}async startSlot(slot,c){await assertLibraryCompatible(c,this.ledger.slotPath(slot),slot);return launch(this.ledger.slotPath(slot),slot,c.stateDirectory,c.cloudConfigFile??void 0,slot.toolsConfigPath??void 0)}async start(){const s=(await this.ledger.current()).value;if(s.transition)fail("ACTIVATION_IN_PROGRESS");if(!s.active)fail("INSTALL_REQUIRED");const c=await this.configuration(),inventory=await this.startSlot(s.active,c);const clients=await this.reconnect();let updateNotice={status:"DISABLED"};if(c.notifications&&c.catalogueUrl){try{const v=await catalogue(c,AbortSignal.timeout(1500));updateNotice={status:"CHECKED",versions:v.signed.catalogue.releases.filter(r=>r.descriptor.platform.os===process.platform&&r.descriptor.platform.architecture===process.arch&&newerVersion(r.descriptor.version,s.active.descriptor.version)&&!c.rejectedVersions.includes(r.descriptor.version)).map(r=>r.descriptor.version)}}catch{updateNotice={status:"UNAVAILABLE"}}}return{...inventory,clients,updateNotice}}async stop(){const c=await this.configuration(),client=await ownerClient(c.stateDirectory),i=await client.inventory();const result=await client.call({operation:"runtime.stop",expectedRuntimeRevision:i.runtimeRevision});await waitStopped(c.stateDirectory);return result}async reconcile(id,approval){const s=(await this.ledger.current()).value,c=await this.configuration();if(!s.transition||s.transition.planId!==id||s.transition.fingerprint!==approval)fail("USER_APPROVAL_REQUIRED");if(s.active?.id===s.transition.previous?.id&&["STAGING","STAGED"].includes(s.transition.failedPhase??s.transition.phase)){const next2=await this.ledger.commit(s,{active:s.transition.previous,transition:null});return{rolledBack:true,revision:next2.revision,version:next2.active?.descriptor.version??null}}const candidate=s.transition.candidate;if(candidate){await assertLibraryCompatible(c,this.ledger.slotPath(candidate),candidate);try{const i=await runningInventory(await ownerClient(c.stateDirectory),this.ledger.slotPath(candidate),candidate);if(canonicalLocalJson(i.descriptor)===canonicalLocalJson(candidate.descriptor)){await verifySlot(this.ledger.slotPath(candidate),candidate);const next2=await this.ledger.commit(s,{active:candidate,transition:null});await this.reconnect();return{recovered:true,revision:next2.revision,version:candidate.descriptor.version}}}catch{}}const previous=s.transition.previous;if(previous)await assertLibraryCompatible(c,this.ledger.slotPath(previous),previous);await waitStopped(c.stateDirectory);const next=await this.ledger.commit(s,{active:previous,transition:null});if(previous)await this.startSlot(previous,c);await this.reconnect();return{rolledBack:true,revision:next.revision,version:previous?.descriptor.version??null}}grant(raw,output){return grant(this,raw,output)}reconnect(){return reconnect(this)}};export{InstalledToolPathsSchema,toolPreference,captureInstalledTools,embeddedRuntime,installationSource,runtimeEnvironment,verifySlot,probeTenantMediaValidation,probeTenantMediaProcessing,probeReferenceThumbnail,probeLocalLibrary,probeTenantComposition,probeTenantSpeech,probeTenantTranscription,probeTenantQwenGeneration,supportsLoginService,ownerClient,waitStopped,socketAbsent,verifyCaptionDirectory,LocalInstallationManager};
@@ -1 +0,0 @@
1
- import{embeddedRuntime,runtimeEnvironment,toolPreference,verifySlot}from"./chunk-ELUJ44BO.js";import{CpuSpeechPrepareInputSchema,CpuSpeechPreparedSchema,LocalToolSelectionSchema}from"./chunk-6EZX2TRX.js";import{canonicalLocalJson}from"./chunk-APNZQZFB.js";import{directory,fail,read,write}from"./chunk-DLW42PJ6.js";import{spawn}from"node:child_process";import{randomUUID}from"node:crypto";import{join}from"node:path";import{unlink}from"node:fs/promises";async function assertCpuPreparationCurrent(manager,original,planRevision=original.revision){const current=(await manager.ledger.current()).value;const configuration=await manager.configuration();if(current.revision!==original.revision||planRevision!==original.revision||canonicalLocalJson(configuration)!==canonicalLocalJson(original.configuration))fail("REVISION_CONFLICT")}async function prepareInstalledCpuSpeech(manager,raw){const input=CpuSpeechPrepareInputSchema.parse(raw),current=(await manager.ledger.current()).value;if(current.transition)fail("ACTIVATION_IN_PROGRESS");if(!current.active)fail("INSTALLATION_REQUIRED");const slot=current.active,root=manager.ledger.slotPath(slot),configuration=await manager.configuration();const context={revision:current.revision,configuration};await verifySlot(root,slot);const file=join(await directory(join(manager.ledger.root,"preparations")),randomUUID()+".json");await write(file,JSON.stringify(input),true);try{const prepared=await new Promise((resolve,reject)=>{const child=spawn(process.execPath,["--max-old-space-size=256",join(root,"dist/entry.js"),"--prepare-cpu-speech","--state-dir",configuration.stateDirectory,"--input-config",file],{env:runtimeEnvironment(),stdio:["ignore","pipe","pipe","ipc"],shell:false});const parts=[],errors=[];let used=0,errorBytes=0,killed=false;const timer=setTimeout(()=>{killed=true;child.kill("SIGTERM")},23e4);const kill=setTimeout(()=>{killed=true;child.kill("SIGKILL")},235e3);const abort=()=>{killed=true;child.kill("SIGTERM")};process.once("SIGINT",abort);process.once("SIGTERM",abort);child.stdout.on("data",chunk=>{used+=chunk.length;if(used>32768)child.kill("SIGTERM");else parts.push(chunk)});child.stderr.on("data",chunk=>{errorBytes+=chunk.length;if(errorBytes>4096)child.kill("SIGTERM");else errors.push(chunk)});child.once("error",reject);child.once("close",code=>{clearTimeout(timer);clearTimeout(kill);process.off("SIGINT",abort);process.off("SIGTERM",abort);try{if(killed)fail("CPU_PREPARATION_CANCELLED");if(code!==0||used>32768||errorBytes>4096){const last=Buffer.concat(errors).toString().trim().split("\n").at(-1);let reason;try{reason=JSON.parse(last??"{}").error?.code}catch{}if(reason==="CPU_BZIP2_REQUIRED")fail("CPU_BZIP2_REQUIRED");if(reason==="CPU_SPEECH_PLATFORM_UNAVAILABLE")fail("CPU_SPEECH_PLATFORM_UNAVAILABLE");fail("CPU_PREPARATION_FAILED")}resolve(CpuSpeechPreparedSchema.parse(JSON.parse(Buffer.concat(parts).toString())))}catch(error){reject(error)}})});await assertCpuPreparationCurrent(manager,context);const previous=await toolPreference(slot.toolsConfigPath,configuration.cloudConfigFile);const existing=slot.toolsConfigPath?LocalToolSelectionSchema.parse(JSON.parse((await read(slot.toolsConfigPath,32768)).toString())):null;const reuseMedia=previous.mode==="MANAGED"&&existing?.mode==="MANAGED"?{schemaVersion:1,ffmpeg:existing.ffmpeg,ffprobe:existing.ffprobe}:void 0;const choice={...previous,cpuSpeech:prepared.selection,...reuseMedia?{reuseMedia}:{}};const plan=await embeddedRuntime(slot.descriptor.version)?await manager.prepareBundled(slot.descriptor.version,choice):await manager.prepare(slot.descriptor.version,choice);await assertCpuPreparationCurrent(manager,context,plan.installationRevision);return{semanticStatus:"PREPARED",capability:prepared.capability,reused:prepared.reused,plan}}finally{await unlink(file).catch(error=>{if(error.code!=="ENOENT")throw error})}}export{prepareInstalledCpuSpeech};
@@ -1 +0,0 @@
1
- import{probeLocalLibrary,probeTenantQwenGeneration,probeTenantSpeech,probeTenantTranscription}from"./chunk-ELUJ44BO.js";import{LocalToolSelectionSchema}from"./chunk-6EZX2TRX.js";import{LocalDeviceTransportConfigurationSchema,canonicalLocalJson}from"./chunk-APNZQZFB.js";import{directory,fail,read,write}from"./chunk-DLW42PJ6.js";import{generateKeyPairSync}from"node:crypto";import{dirname,join,sep}from"node:path";import{z}from"zod";async function generateDeviceKey(output){await directory(dirname(output));const key=generateKeyPairSync("ec",{namedCurve:"prime256v1"});await write(output,JSON.stringify(key.privateKey.export({format:"jwk"})),true);return{publicKey:key.publicKey.export({format:"jwk"}),privateKeyFile:output}}async function connectDevice(manager,raw){const schema=LocalDeviceTransportConfigurationSchema.safeExtend({compositionBrowser:z.never().optional(),macSpeechIdentity:z.never().optional(),whisperIdentity:z.never().optional(),whisperTools:z.never().optional(),qwenIdentities:z.never().optional(),tools:LocalToolSelectionSchema.optional()});const input=schema.parse(raw),c=await manager.configuration();await read(input.privateKeyFile,16384);const active=(await manager.ledger.current()).value.active;if(input.processorCapabilities?.some(kind=>kind==="LOCAL_MEDIA_INSPECT"||kind==="LOCAL_MEDIA_PUBLISH")&&(!active||!await probeLocalLibrary(manager.ledger.slotPath(active),active)))fail("LOCAL_PROFILE_UNAVAILABLE");if(input.processorCapabilities?.includes("SPEECH_SYNTHESIZE")&&(!active||!await probeTenantSpeech(manager.ledger.slotPath(active),active)))fail("LOCAL_PROFILE_UNAVAILABLE");if(input.processorCapabilities?.includes("TRANSCRIBE_AUDIO")&&(!active||!await probeTenantTranscription(manager.ledger.slotPath(active),active)))fail("LOCAL_PROFILE_UNAVAILABLE");const qwenProcessors=[["KEYFRAME_GENERATE","keyframe"],["VIDEO_GENERATE","video"],["SPEECH_EXTERNAL_QWEN","speech"],["TRANSCRIBE_EXTERNAL_QWEN","asr"]];const selectedQwen=qwenProcessors.filter(([processor])=>input.processorCapabilities?.includes(processor));if(selectedQwen.some(([,kind])=>kind!=="speech")!==Boolean(input.qwenDeviceCredentials?.length))fail("LOCAL_PROFILE_UNAVAILABLE");for(const[,kind]of selectedQwen){if(!active||!await probeTenantQwenGeneration(manager.ledger.slotPath(active),active,kind))fail("LOCAL_PROFILE_UNAVAILABLE")}for(const credential of input.qwenDeviceCredentials??[]){if(credential.tenantId!==input.tenantId)fail("LOCAL_PROFILE_UNAVAILABLE");(await read(credential.privateKeyFile,4096)).fill(0)}const actual=active?.toolsConfigPath?LocalToolSelectionSchema.parse(JSON.parse((await read(active.toolsConfigPath,32768)).toString())):c.cloudConfigFile?LocalToolSelectionSchema.parse(JSON.parse((await read(c.cloudConfigFile,32768)).toString()).tools):null;if(input.tools&&active&&(!actual||canonicalLocalJson(input.tools)!==canonicalLocalJson(actual)))fail("TOOL_SELECTION_PLAN_REQUIRED");let tools=input.tools;if(!tools){const selected=(await manager.ledger.current()).value.active?.toolsConfigPath;if(!selected)fail("MANAGED_TOOLS_REQUIRED");tools=LocalToolSelectionSchema.parse(JSON.parse((await read(selected,32768)).toString()))}if(tools.mode==="MANAGED"&&!tools.ffmpeg.path.startsWith(join(c.stateDirectory,"tools")+sep))fail("MANAGED_TOOLS_REQUIRED");const file=join(c.stateDirectory,"cloud-device.json");const cloudTools=active?{mode:tools.mode,ffmpeg:tools.ffmpeg,ffprobe:tools.ffprobe}:tools;await write(file,canonicalLocalJson({...input,tools:cloudTools}));await manager.configure({...c,cloudConfigFile:file});return{connected:true,deviceId:input.deviceId,tenantId:input.tenantId,nextActions:[{surface:"CLI",operation:"local.stop",availability:"AVAILABLE",reason:"READY"},{surface:"CLI",operation:"local.start",availability:"AVAILABLE",reason:"READY"}]}}export{generateDeviceKey,connectDevice};
@@ -1 +0,0 @@
1
- import{DeviceEnrollmentScopeSchema,LocalDeviceTransportConfigurationSchema,LocalDeviceViewSchema,LocalFinalRenderAdmissionSchema,LocalManagementCommandSchema,LocalManagementResultSchema,LocalPreviewAdmissionSchema,StartLocalFinalRenderSchema,StartLocalPreviewSchema}from"./chunk-APNZQZFB.js";import{z}from"zod";var DesktopDeviceScopeSchema=DeviceEnrollmentScopeSchema;var digest=z.string().regex(/^[a-f0-9]{64}$/);var DesktopDeviceCallSchema=z.discriminatedUnion("action",[z.strictObject({action:z.literal("inspect")}),z.strictObject({action:z.literal("prove")}),z.strictObject({action:z.literal("media-validation-capability")}),z.strictObject({action:z.literal("media-processing-capability")}),z.strictObject({action:z.literal("connect"),expectedRevision:z.int().nonnegative(),installationFingerprint:digest.optional()}),z.strictObject({action:z.literal("remember-enable"),expectedRevision:z.int().nonnegative(),installationFingerprint:digest}),z.strictObject({action:z.literal("connection-recover")}),z.strictObject({action:z.literal("enroll"),label:z.string().trim().min(1).max(120),expectedRevision:z.int().nonnegative().optional(),bindWorkspaceMember:z.literal(true).optional(),agentEnrollment:z.literal(true).optional()}),z.strictObject({action:z.literal("revoke")}),z.strictObject({action:z.literal("preview"),input:StartLocalPreviewSchema.omit({tenantId:true,placement:true,idempotencyKey:true}),mode:z.enum(["local-only","local-preferred"])}),z.strictObject({action:z.literal("final"),input:StartLocalFinalRenderSchema.omit({tenantId:true,placement:true,idempotencyKey:true}),mode:z.enum(["local-only","local-preferred"])}),z.strictObject({action:z.literal("dispatch"),fingerprint:digest}),z.strictObject({action:z.literal("record"),fingerprint:digest,result:LocalManagementResultSchema}),z.strictObject({action:z.literal("refused"),fingerprint:digest})]);var DesktopDeviceRequestSchema=z.strictObject({operation:z.literal("device"),scope:DesktopDeviceScopeSchema,call:DesktopDeviceCallSchema});var DesktopDeviceStateSchema=z.strictObject({revision:z.int().nonnegative(),scope:DesktopDeviceScopeSchema,enrollment:LocalManagementCommandSchema.options[0].shape.input.nullable(),device:LocalDeviceViewSchema.nullable(),previews:z.array(z.union([LocalPreviewAdmissionSchema,LocalFinalRenderAdmissionSchema])).max(20),connectorId:z.uuid().nullable(),connection:z.strictObject({phase:z.enum(["CONNECTING","READY","CONNECTED"]),expiresAt:z.iso.datetime(),tenantMediaProcessing:z.literal(true).optional(),processorCapabilities:LocalDeviceTransportConfigurationSchema.shape.processorCapabilities,deviceRevision:z.int().positive(),tenantMediaValidation:z.literal(true).optional()}).nullable().default(null),pending:z.strictObject({command:LocalManagementCommandSchema,fingerprint:digest,phase:z.enum(["PREPARED","SENDING","REFUSED"]),agentEnrollment:z.literal(true).optional()}).nullable()});var DesktopDeviceViewSchema=DesktopDeviceStateSchema.omit({scope:true,enrollment:true,connectorId:true,pending:true,device:true}).extend({installation:z.strictObject({version:z.string().min(1).max(100),fingerprint:digest,workProtocol:z.enum(["NVS_LOCAL_WORK_V1","NVS_LOCAL_WORK_V2"]).optional()}).nullable().optional(),automaticConnection:z.boolean().optional(),device:z.strictObject({deviceId:z.uuid(),label:z.string().max(120),revision:z.int().positive(),revokedAt:z.iso.datetime().nullable()}).nullable(),pending:z.strictObject({kind:z.enum(["ENROLL","REVOKE_DEVICE","PREVIEW","FINAL_RENDER"]),phase:z.enum(["PREPARED","SENDING","REFUSED"]),fingerprint:digest,agentEnrollment:z.literal(true).optional()}).nullable()});var DesktopDeviceReplySchema=z.strictObject({view:DesktopDeviceViewSchema,command:LocalManagementCommandSchema.optional(),mediaValidationSupported:z.boolean().optional(),mediaProcessingSupported:z.boolean().optional(),localLibrarySupported:z.boolean().optional(),compositionProcessingSupported:z.boolean().optional()});export{DesktopDeviceScopeSchema,DesktopDeviceRequestSchema,DesktopDeviceStateSchema,DesktopDeviceReplySchema};
@@ -1 +0,0 @@
1
- import{desktopAutomation,desktopInstallationIdentity}from"./chunk-MLZ3ZPGU.js";import{LocalInstallationManager,ownerClient,socketAbsent}from"./chunk-ELUJ44BO.js";import{LocalLibraryCallSchema,LocalLibraryGetSchema,LocalLibraryImportSchema,LocalLibraryItemSchema,LocalLibraryPageSchema,LocalLibraryProjectionPageSchema,LocalLibraryProjectionSchema,LocalLibraryReadReplySchema,LocalLibraryReferenceSchema,LocalLibraryUsageSchema}from"./chunk-APNZQZFB.js";import{LocalClientError,fail}from"./chunk-DLW42PJ6.js";import{NativeStudioSdkError}from"./chunk-TT7IA5HB.js";import{z}from"zod";import{isAbsolute}from"node:path";import{constants}from"node:fs";import{open}from"node:fs/promises";import{createHash}from"node:crypto";var same=(a,b)=>a.dev===b.dev&&a.ino===b.ino&&a.size===b.size&&a.mtimeMs===b.mtimeMs&&a.ctimeMs===b.ctimeMs;async function captureLibraryImport(path,seed){const file2=await open(path,constants.O_RDONLY|constants.O_NOFOLLOW).catch(()=>{throw new NativeStudioSdkError("LOCAL_LIBRARY_FILE_UNAVAILABLE","INVALID_INPUT","NO_WRITE")});try{const before=await file2.stat(),hash=createHash("sha256");if(!before.isFile()||before.size>128*1024*1024)fail("LOCAL_LIBRARY_FILE_INVALID");let size=0;for await(const bytes of file2.createReadStream({autoClose:false,start:0})){size+=bytes.length;if(size>before.size)fail("LOCAL_LIBRARY_FILE_CHANGED");hash.update(bytes)}if(size!==before.size||!same(before,await file2.stat()))fail("LOCAL_LIBRARY_FILE_CHANGED");const{tenantId,projectId,deviceId,contentType,...fields}=seed;return LocalLibraryImportSchema.parse({...fields,reference:{tenantId,projectId,deviceId,fileId:seed.requestId,versionId:seed.requestId,contentType,byteSize:size,checksumSha256:hash.digest("hex")}})}catch(error){if(error instanceof NativeStudioSdkError)throw error;throw new NativeStudioSdkError(error instanceof LocalClientError?error.code:"LOCAL_LIBRARY_FILE_UNAVAILABLE","INVALID_INPUT","NO_WRITE")}finally{await file2.close()}}async function importLibraryFile(library,path,raw){const input=LocalLibraryImportSchema.parse(raw),file2=await open(path,constants.O_RDONLY|constants.O_NOFOLLOW).catch(()=>{throw new NativeStudioSdkError("LOCAL_LIBRARY_FILE_UNAVAILABLE","INVALID_INPUT","NO_WRITE")});let dispatched=false;try{const before=await file2.stat();if(!before.isFile()||before.size!==input.reference.byteSize)fail("LOCAL_LIBRARY_FILE_CHANGED");dispatched=true;const result=await library.import(input,file2.createReadStream({autoClose:false,start:0}));if(!same(before,await file2.stat()))fail("LOCAL_LIBRARY_IMPORT_UNKNOWN");return result}catch(error){if(error instanceof NativeStudioSdkError)throw error;throw new NativeStudioSdkError(error instanceof LocalClientError?error.code:"LOCAL_LIBRARY_IMPORT_UNAVAILABLE","BLOCKED",dispatched?"UNKNOWN":"NO_WRITE")}finally{await file2.close()}}var file=z.string().min(1).max(4096).refine(isAbsolute);var DesktopLibraryImportSeedSchema=LocalLibraryImportSchema.omit({reference:true}).extend({...LocalLibraryReferenceSchema.pick({tenantId:true,projectId:true,deviceId:true,contentType:true}).shape});var DesktopLibraryRequestSchema=z.strictObject({operation:z.literal("library"),call:LocalLibraryCallSchema});var DesktopLibraryImportRequestSchema=z.strictObject({operation:z.literal("library-import"),input:LocalLibraryImportSchema,file});var DesktopLibraryPrepareRequestSchema=z.strictObject({operation:z.literal("library-import-prepare"),seed:DesktopLibraryImportSeedSchema,file});var DesktopLibraryMediaRequestSchema=z.strictObject({operation:z.literal("library-media"),input:LocalLibraryGetSchema,method:z.enum(["GET","HEAD"]).default("GET"),range:z.string().min(1).max(100).optional()});var DesktopLibraryReplySchema=z.union([LocalLibraryItemSchema.nullable(),LocalLibraryPageSchema,LocalLibraryProjectionPageSchema,LocalLibraryProjectionSchema,LocalLibraryUsageSchema,LocalLibraryReadReplySchema]);async function client(home){const manager=await LocalInstallationManager.open(home),config=await manager.configuration();if(!(await manager.status()).running){const policy=await desktopAutomation(home),installation=await desktopInstallationIdentity(manager);if(!policy?.enabled||policy.installationFingerprint!==installation?.fingerprint||!await socketAbsent(config.stateDirectory))fail("RUNTIME_STATUS_REQUIRED");await manager.start()}return ownerClient(config.stateDirectory)}async function runDesktopLibraryRequest(home,raw){const input=DesktopLibraryRequestSchema.parse(raw);return(await client(home)).library.call(input.call)}async function prepareDesktopLibraryImport(raw){const input=DesktopLibraryPrepareRequestSchema.parse(raw);return DesktopLibraryImportRequestSchema.parse({operation:"library-import",file:input.file,input:await captureLibraryImport(input.file,input.seed)})}async function runDesktopLibraryImport(home,raw){const input=DesktopLibraryImportRequestSchema.parse(raw);return importLibraryFile((await client(home)).library,input.file,input.input)}async function runDesktopLibraryMedia(home,raw){const input=DesktopLibraryMediaRequestSchema.parse(raw);return(await client(home)).library.media(input.input,{method:input.method,...input.range?{range:input.range}:{}})}export{DesktopLibraryImportSeedSchema,DesktopLibraryRequestSchema,DesktopLibraryImportRequestSchema,DesktopLibraryPrepareRequestSchema,DesktopLibraryMediaRequestSchema,DesktopLibraryReplySchema,runDesktopLibraryRequest,prepareDesktopLibraryImport,runDesktopLibraryImport,runDesktopLibraryMedia};
@@ -1 +0,0 @@
1
- import{selectedProject}from"./chunk-OSO6KRE2.js";import{profileAuthorization}from"./chunk-3TOXIJ7K.js";import{connectRemoteMcp}from"./chunk-GLAF74UU.js";import{profileHttpOrigin}from"./chunk-7P2NA6TH.js";import{clientHome,loadConnection,readAccount,requireAccount}from"./chunk-27KI24GK.js";import{NativeStudioSdkError}from"./chunk-TT7IA5HB.js";import{z}from"zod";async function resolveCaller(env,explicitProject,workspaceOnly=false){const home=await clientHome(env),account=await readAccount(home);const saved=await loadConnection(env);const assertCurrent=async()=>{const latest=await loadConnection(env),current=await readAccount(home);if(latest?.profile!==saved?.profile||latest?.resource!==saved?.resource||account?.epoch!==current?.epoch||account?.state!==current?.state||account?.principalId!==current?.principalId||account?.workspaceId!==current?.workspaceId||account?.serverOrigin!==current?.serverOrigin)throw new NativeStudioSdkError("FORBIDDEN","BLOCKED","NO_WRITE");if(latest?.exchangeUnresolved)throw new NativeStudioSdkError("OAUTH_OUTCOME_UNKNOWN","BLOCKED","UNKNOWN");if(account&&!saved)requireAccount(current)};if(saved){const auth=await profileAuthorization(saved.profile);if(auth.resource!==saved.resource)throw new NativeStudioSdkError("FORBIDDEN","BLOCKED","NO_WRITE");const projectId=workspaceOnly?void 0:await selectedProject(saved,env,explicitProject);const c=await connectRemoteMcp(saved.resource,auth.authorization,saved.tenantId);try{const caller=await c.studio.call("workspace.caller",{});if(caller.tenantId!==saved.tenantId||account&&(account.principalId!==caller.principalId||account.serverOrigin!==caller.serverOrigin))throw new NativeStudioSdkError("FORBIDDEN","BLOCKED","NO_WRITE");if(projectId){const selected=await c.studio.call("project.get",{projectId});if(selected.project.id!==projectId||selected.project.tenantId!==caller.tenantId)throw new NativeStudioSdkError("FORBIDDEN","BLOCKED","NO_WRITE")}await assertCurrent();return{tenantId:caller.tenantId,principalId:caller.principalId,serverOrigin:caller.serverOrigin,home,projectId,resource:saved.resource,profile:saved.profile,assertCurrent}}finally{await c.close().catch(()=>{})}}if(!account)return null;const human=requireAccount(account);if(!human.workspaceId||!workspaceOnly&&!(explicitProject??human.projectId))throw new NativeStudioSdkError("PROJECT_SELECTION_REQUIRED","BLOCKED","NO_WRITE");return{home,tenantId:human.workspaceId,projectId:workspaceOnly?void 0:z.uuid().parse(explicitProject??human.projectId),principalId:human.principalId,serverOrigin:human.serverOrigin,resource:void 0,profile:void 0,assertCurrent}}async function localCaller(env,explicitProject){const caller=await resolveCaller(env,explicitProject);if(!caller)return null;if(!caller.projectId)throw new NativeStudioSdkError("PROJECT_SELECTION_REQUIRED","BLOCKED","NO_WRITE");return{...caller,projectId:caller.projectId}}function workspaceCaller(env){return resolveCaller(env,void 0,true)}async function callerOriginMatches(origin,caller){if(origin===caller.serverOrigin)return true;if(!caller.resource||!caller.profile)return false;return origin===new URL(caller.resource).origin||origin===await profileHttpOrigin(caller.profile,caller.resource)}export{localCaller,workspaceCaller,callerOriginMatches};
@@ -1 +0,0 @@
1
- import{workspaceProject}from"./chunk-UYKCN5DU.js";import{profileAuthorization}from"./chunk-3TOXIJ7K.js";import{readCredential}from"./chunk-QGK6G6YS.js";import{connectRemoteMcp}from"./chunk-GLAF74UU.js";import{clientHome,loadConnection,readAccount,tenantConnection}from"./chunk-27KI24GK.js";import{sha256}from"./chunk-DLW42PJ6.js";import{NativeStudioSdkError}from"./chunk-TT7IA5HB.js";import{z}from"zod";async function selectedProject(scope,env,explicit){if(explicit)return z.uuid().parse(explicit);const selected=await workspaceProject(scope,env);if(selected)return selected;const account=await readAccount(await clientHome(env));const projectId=explicit??(account?.workspaceId===scope.tenantId?account.projectId:null);if(!projectId)throw new NativeStudioSdkError("PROJECT_SELECTION_REQUIRED","BLOCKED","NO_WRITE");return z.uuid().parse(projectId)}async function renderConnection(env,signal,write=true,projectId){const scope=await loadConnection(env);if(!scope||write&&!scope.scope.split(/\s+/).includes("nvs:write"))throw new NativeStudioSdkError("AUTHORIZATION_REQUIRED","BLOCKED","NO_WRITE");const auth=await profileAuthorization(scope.profile,signal);if(auth.resource!==scope.resource)throw new NativeStudioSdkError("FORBIDDEN","BLOCKED","NO_WRITE");const selected=await selectedProject(scope,env,projectId);return{externalCredential:false,scope:{...scope,projectId:selected},...await connectRemoteMcp(scope.resource,auth.authorization,scope.tenantId)}}async function callerRenderConnection(env,flags,write=true){const url=flags.get("--mcp-url");if(!url&&!flags.has("--token-file"))return renderConnection(env,void 0,write,flags.get("--project"));if(!url||!flags.has("--token-file"))throw new NativeStudioSdkError("AUTHORIZATION_REQUIRED","BLOCKED","NO_WRITE");const scope=tenantConnection(url),auth=await readCredential(flags,env);return{externalCredential:true,scope:{...scope,projectId:await selectedProject(scope,env,flags.get("--project")),profile:"grant:"+sha256(auth)},...await connectRemoteMcp(scope.resource,auth,scope.tenantId)}}async function renderReceiptScope(studio,scope){const[caller,status]=await Promise.all([studio.call("workspace.caller",{}),studio.call("workspace.status",{})]);if(caller.tenantId!==scope.tenantId||status.tenantId!==scope.tenantId)throw new NativeStudioSdkError("FORBIDDEN","BLOCKED","NO_WRITE");if(!status.agentGrantId)throw new NativeStudioSdkError("AUTHORIZATION_REQUIRED","BLOCKED","NO_WRITE");return{resource:scope.resource,tenantId:scope.tenantId,projectId:scope.projectId,principalId:caller.principalId,grantId:status.agentGrantId}}export{selectedProject,renderConnection,callerRenderConnection,renderReceiptScope};
@@ -1 +0,0 @@
1
- import{LocalExecutionInspectInputSchema,LocalExecutionListInputSchema,LocalMcpOutputSchemas,NativeStudioLocalRuntimeClient,catalogue}from"./chunk-6EZX2TRX.js";import{LocalLibraryGetSchema,LocalLibraryProjectionPageSchema,LocalLibraryProjectionQuerySchema}from"./chunk-APNZQZFB.js";import{fail,optional}from"./chunk-DLW42PJ6.js";import{z}from"zod";import{join}from"node:path";var localTools={local_library_list:{description:"Read bounded metadata projections of this device library in an explicitly authorized Project. No paths, bytes, import or native admission.",input:LocalLibraryProjectionQuerySchema},local_library_get:{description:"Read metadata for one exact authorized local-file version. This does not inspect/decode bytes or create a Job.",input:LocalLibraryGetSchema.omit({ownerKey:true})},local_navigate:{description:"Local execution entry. Discover Project-scoped Runtime progress, recovery and updates. Native writes remain with the cloud owner.",input:z.strictObject({intent:z.string().max(500).optional()})},local_capability_describe:{description:"Inspect the exact public schema for a local capability. Standard discovery stays stable; each call validates current Runtime authority.",input:z.strictObject({tool:z.enum(["local_runtime_status","local_execution_list","local_execution_inspect","local_update_check","local_library_list","local_library_get"])})},local_runtime_status:{description:"Read current authorized local Runtime status. Does not start, stop or mutate native work.",input:z.strictObject({})},local_execution_list:{description:"List a bounded page of pending local execution identities in one authorized Project, then inspect an exact native Job.",input:LocalExecutionListInputSchema},local_execution_inspect:{description:"Inspect one exact native Job in the authorized Project. Native Job/Attempt identity remains authoritative.",input:LocalExecutionInspectInputSchema},local_update_check:{description:"Read signed compatible release metadata only. No executable download, approval, installation or restart.",input:z.strictObject({})}};var LocalMcpTools=class _LocalMcpTools{constructor(client,home,library=false){this.client=client;this.home=home;this.library=library}client;home;library;static async open(connector,home,library=false){const client=await NativeStudioLocalRuntimeClient.fromConnector(connector);let enabled=false;if(library){try{enabled=(await client.library.capability()).available}catch{}}return new _LocalMcpTools(client,home,enabled)}get names(){return Object.keys(localTools).filter(name=>this.library||!name.startsWith("local_library_"))}schema(name){if(!this.names.includes(name))fail("CAPABILITY_UNAVAILABLE");return{name,description:localTools[name].description,inputSchema:z.toJSONSchema(localTools[name].input,{io:"input"}),outputSchema:z.toJSONSchema(LocalMcpOutputSchemas[name],{io:"output",reused:"ref"}),annotations:{readOnlyHint:true,destructiveHint:false,openWorldHint:name==="local_update_check"}}}async call(name,raw,signal){return LocalMcpOutputSchemas[name].parse(await this.invoke(name,raw,signal))}async invoke(name,raw,signal){const input=localTools[name].input.parse(raw);if(name==="local_library_list"){if(!this.library)fail("CAPABILITY_UNAVAILABLE");return{location:"LOCAL",...LocalLibraryProjectionPageSchema.parse(await this.client.library.call({...input,action:"scoped-list"},signal))}}if(name==="local_library_get"){if(!this.library)fail("CAPABILITY_UNAVAILABLE");return{location:"LOCAL",item:await this.client.library.call({...input,action:"scoped-get"},signal)}}if(name==="local_capability_describe")return{location:"LOCAL",tool:input.tool,schema:this.schema(input.tool)};if(name==="local_navigate"){let status;try{status=await this.client.status(signal,true)}catch{return{location:"LOCAL",state:"UNAVAILABLE",groups:[],nextActions:[{surface:"CLI",operation:"local.grant",availability:"BLOCKED",reason:"AUTHORIZATION_REQUIRED"}]}}return{location:"LOCAL",state:status.state,...status.deviceAuthority?{deviceAuthority:status.deviceAuthority}:{},groups:[...this.library?[{id:"library",label:"Scoped local media metadata",tools:["local_library_list","local_library_get"]}]:[],{id:"execution",label:"Local execution and recovery",tools:["local_runtime_status","local_execution_list","local_execution_inspect"]},{id:"versions",label:"Versions and updates",tools:["local_update_check"]}],nextActions:[{tool:"local_capability_describe",arguments:{tool:"local_execution_list"},availability:"AVAILABLE",reason:"READY"},...status.state==="RECOVERY_REQUIRED"?[{surface:"CLI",operation:"local.status",availability:"AVAILABLE",reason:"RECOVERY_REQUIRED"}]:[]]}}if(name==="local_runtime_status")return{...await this.client.status(signal),nextActions:[{tool:"local_capability_describe",arguments:{tool:"local_execution_list"}}]};if(name==="local_execution_list"){const page=await this.client.executions(LocalExecutionListInputSchema.parse(input),signal);return{...page,nextActions:page.items.map(item=>({tool:"local_execution_inspect",arguments:{tenantId:item.binding.tenantId,projectId:item.binding.projectId,productionId:item.binding.productionId,runtimeJobId:item.binding.runtimeJobId}}))}}if(name==="local_execution_inspect")return{location:"LOCAL",execution:await this.client.inspect(LocalExecutionInspectInputSchema.parse(input),signal),nextActions:[]};if(name==="local_update_check"){const current=await this.client.status(signal);const raw2=await optional(join(this.home,"configuration.json"));const config=z.object({catalogueUrl:z.string().url(),publicKeyFile:z.string()}).parse(raw2);const v=await catalogue(config,signal);return{location:"LOCAL",running:current.versions,available:v.signed.catalogue.releases.filter(r=>r.descriptor.platform.os===process.platform&&r.descriptor.platform.architecture===process.arch).map(r=>r.descriptor),nextActions:[{surface:"CLI",operation:"local.update.prepare",availability:"BLOCKED",reason:"USER_APPROVAL_REQUIRED"}]}}fail("CAPABILITY_UNAVAILABLE")}};export{localTools,LocalMcpTools};
@@ -1 +0,0 @@
1
- import{connectDevice,generateDeviceKey}from"./chunk-HBDPYWMI.js";import{canResumeDesktop,desktopAutomation,desktopInstallationIdentity,rememberDesktopAutomation}from"./chunk-MLZ3ZPGU.js";import{LocalInstallationManager,probeLocalLibrary,probeReferenceThumbnail,probeTenantComposition,probeTenantMediaProcessing,probeTenantMediaValidation,probeTenantSpeech,probeTenantTranscription,socketAbsent}from"./chunk-ELUJ44BO.js";import{DesktopDeviceRecords}from"./chunk-AFNJRZLJ.js";import{DesktopDeviceReplySchema,DesktopDeviceRequestSchema}from"./chunk-IYDHDLTR.js";import{LocalDeviceChallengeSchema,LocalDeviceSessionSchema,LocalDeviceTransportConfigurationSchema,LocalDeviceViewSchema,LocalFinalRenderAdmissionSchema,LocalManagementCommandSchema,LocalPreviewAdmissionSchema,canonicalLocalJson,processorFamilies}from"./chunk-APNZQZFB.js";import{fail,read,sha256}from"./chunk-DLW42PJ6.js";import{createPrivateKey as createPrivateKey2,createPublicKey,randomUUID as randomUUID3}from"node:crypto";import{randomUUID}from"node:crypto";async function desktopDeviceCapabilities(manager){const active=(await manager.ledger.current()).value.active;if(!active)fail("INSTALL_REQUIRED");const root=manager.ledger.slotPath(active);const validation=await probeTenantMediaValidation(root,active);const processing=await probeTenantMediaProcessing(root,active);const processors=processing?Object.keys(processorFamilies).filter(kind=>!["COMPOSITION_RENDER","LOCAL_MEDIA_INSPECT","LOCAL_MEDIA_PUBLISH","SPEECH_SYNTHESIZE","TRANSCRIBE_AUDIO","KEYFRAME_GENERATE","VIDEO_GENERATE","SPEECH_EXTERNAL_QWEN","REFERENCE_PREVIEW","TRANSCRIBE_EXTERNAL_QWEN"].includes(kind)):[];if(processing){if(await probeReferenceThumbnail(root,active))processors.push("REFERENCE_PREVIEW");if(await probeLocalLibrary(root,active))processors.push("LOCAL_MEDIA_INSPECT","LOCAL_MEDIA_PUBLISH");if(await probeTenantComposition(root,active))processors.push("COMPOSITION_RENDER");if(await probeTenantSpeech(root,active))processors.push("SPEECH_SYNTHESIZE");if(await probeTenantTranscription(root,active))processors.push("TRANSCRIBE_AUDIO")}return{...validation?{tenantMediaValidation:true}:{},...processors.length?{tenantMediaProcessing:true,processorCapabilities:processors.sort()}:{}}}async function connectDesktopDevice(records,manager,s,expectedRevision){if(s.revision!==expectedRevision)fail("DEVICE_PLAN_CHANGED");if(s.connection?.phase==="CONNECTING")fail("DEVICE_CONNECTION_RECOVERY_REQUIRED");if(!s.device||s.device.revokedAt)fail("DEVICE_ENROLLMENT_REQUIRED");const capabilities=await desktopDeviceCapabilities(manager);const c=await manager.configuration();const previous=c.cloudConfigFile?JSON.parse((await read(c.cloudConfigFile,32768)).toString()):null;if(previous&&(previous.endpoint!==s.scope.origin||previous.tenantId!==s.scope.tenantId||previous.deviceId!==s.device.deviceId))fail("DEVICE_CONNECTION_CONFLICT");const running=(await manager.status()).running;if(!running&&!await socketAbsent(c.stateDirectory))fail("DEVICE_CONNECTION_RECOVERY_REQUIRED");const matches=value=>{const saved=value;return saved?.deviceRevision===s.device.revision&&saved.tenantMediaValidation===capabilities.tenantMediaValidation&&saved.tenantMediaProcessing===capabilities.tenantMediaProcessing&&canonicalLocalJson(saved.processorCapabilities??null)===canonicalLocalJson(capabilities.processorCapabilities??null)};const reuse=running&&matches(previous)&&matches(s.connection);const expiresAt=new Date(Date.now()+24*36e5).toISOString();s=await records.save(s,{connection:{phase:"CONNECTING",expiresAt,deviceRevision:s.device.revision,...capabilities}});if(!reuse){if(running)await manager.stop();await connectDevice(manager,{endpoint:s.scope.origin,tenantId:s.scope.tenantId,deviceId:s.device.deviceId,deviceRevision:s.device.revision,privateKeyFile:records.keyPath(),platform:s.device.platform,...capabilities});await manager.start()}const id=randomUUID();await manager.grant({tenantId:s.scope.tenantId,deviceId:s.device.deviceId,expiresAt},records.connectorPath(id));return records.save(s,{connectorId:id,connection:{...s.connection,phase:"CONNECTED"}})}async function recoverDesktopConnection(records,manager,s){if(s.connection?.phase!=="CONNECTING")return s;const c=await manager.configuration(),running=(await manager.status()).running;if(!running){if(!await socketAbsent(c.stateDirectory))fail("DEVICE_CONNECTION_RECOVERY_REQUIRED");return records.save(s,{connection:null,connectorId:null})}if(!c.cloudConfigFile||!s.device||s.device.revokedAt)fail("DEVICE_CONNECTION_RECOVERY_REQUIRED");const raw=JSON.parse((await read(c.cloudConfigFile,32768)).toString());const{tools:_tools,...transport}=raw;void _tools;const actual=LocalDeviceTransportConfigurationSchema.parse(transport);if(actual.endpoint!==s.scope.origin||actual.deviceId!==s.device.deviceId||actual.tenantId!==s.scope.tenantId||actual.deviceRevision!==s.connection.deviceRevision||actual.deviceRevision!==s.device.revision||actual.tenantMediaValidation!==s.connection.tenantMediaValidation||actual.tenantMediaProcessing!==s.connection.tenantMediaProcessing||canonicalLocalJson(actual.processorCapabilities??null)!==canonicalLocalJson(s.connection.processorCapabilities??null))fail("DEVICE_CONNECTION_RECOVERY_REQUIRED");return records.save(s,{connection:{...s.connection,phase:"READY"},connectorId:null})}import{createPrivateKey,sign,randomUUID as randomUUID2}from"node:crypto";async function proveDesktopDevice(records){const state=await records.current(),d=state.device;if(!d)fail("DEVICE_ENROLLMENT_REQUIRED");async function request(action,input){const response=await fetch(state.scope.origin+"/v1/local-execution/devices/"+action,{method:"POST",redirect:"error",headers:{"content-type":"application/json"},body:JSON.stringify(input),signal:AbortSignal.timeout(15e3)});if(!response.ok){await response.body?.cancel();fail("DEVICE_PROOF_UNAVAILABLE")}const chunks=[];let size=0;for await(const bytes of response.body??[]){size+=bytes.length;if(size>16384)fail("DEVICE_PROOF_INVALID");chunks.push(bytes)}return JSON.parse(Buffer.concat(chunks).toString())}const scope={tenantId:d.tenantId,deviceId:d.deviceId,deviceRevision:d.revision};const started=performance.now();const challenge=LocalDeviceChallengeSchema.parse(await request("challenge",scope));if(challenge.tenantId!==d.tenantId||challenge.deviceId!==d.deviceId||challenge.deviceRevision!==d.revision||Date.parse(challenge.expiresAt)-Date.parse(challenge.issuedAt)<=performance.now()-started)fail("DEVICE_PROOF_INVALID");const key=createPrivateKey({key:JSON.parse((await read(records.keyPath(),16384)).toString()),format:"jwk"});const header=Buffer.from(JSON.stringify({alg:"ES256",typ:"nvs-local-device+jwt"})).toString("base64url");const iat=Math.floor(Date.parse(challenge.issuedAt)/1e3),claims=Buffer.from(JSON.stringify({protocol:"NVS_LOCAL_DEVICE_PROOF_V1",...scope,challengeId:challenge.challengeId,audience:challenge.audience,jti:randomUUID2(),iat,exp:iat+30})).toString("base64url");const unsigned=header+"."+claims;const assertion=unsigned+"."+sign("sha256",Buffer.from(unsigned),{key,dsaEncoding:"ieee-p1363"}).toString("base64url");const result=LocalDeviceSessionSchema.parse(await request("prove",{...scope,challengeId:challenge.challengeId,assertion}));if(result.tenantId!==d.tenantId||result.deviceId!==d.deviceId)fail("DEVICE_PROOF_INVALID")}var fingerprint=v=>sha256(canonicalLocalJson(v));function view(s){return{revision:s.revision,device:s.device?{deviceId:s.device.deviceId,label:s.device.label,revision:s.device.revision,revokedAt:s.device.revokedAt}:null,previews:s.previews,connection:s.connection,pending:s.pending?{kind:s.pending.command.kind,phase:s.pending.phase,fingerprint:s.pending.fingerprint,...s.pending.agentEnrollment&&{agentEnrollment:true}}:null}}function accepted(s,result){const command=s.pending.command,i=command.input;if(command.kind==="ENROLL"){const d=LocalDeviceViewSchema.parse(result);if(d.tenantId!==i.tenantId||d.enrolledByPrincipalId!==s.scope.principalId||d.label!==command.input.label||d.runtimeVersion!==command.input.runtimeVersion||canonicalLocalJson(d.publicKey)!==canonicalLocalJson(command.input.publicKey)||canonicalLocalJson(d.platform)!==canonicalLocalJson(command.input.platform)||d.revokedAt)fail("DEVICE_RESULT_INVALID");return{device:d}}if(command.kind==="REVOKE_DEVICE"){if(result?.semanticStatus!=="SUCCESS"||!s.device)fail("DEVICE_RESULT_INVALID");return{device:{...s.device,revision:s.device.revision+1,revokedAt:new Date().toISOString()},connectorId:null,connection:null}}const p=(command.kind==="FINAL_RENDER"?LocalFinalRenderAdmissionSchema:LocalPreviewAdmissionSchema).parse(result),input=command.input;if(p.productionId!==input.productionId||p.timelineVersionId!==input.timelineVersionId||p.timelineFingerprint!==input.timelineFingerprint||canonicalLocalJson(p.placement.policy)!==canonicalLocalJson(input.placement))fail("DEVICE_RESULT_INVALID");return{previews:[p,...s.previews.filter(v=>v.renderId!==p.renderId)].slice(0,20)}}async function runDesktopDeviceRequest(home,raw,policy){const request=DesktopDeviceRequestSchema.parse(raw),call=request.call;const records=await DesktopDeviceRecords.open(home,request.scope),manager=await LocalInstallationManager.open(home);let s=await records.current();if(s.pending&&policy&&!policy.allowedPendingKinds.includes(s.pending.command.kind))fail("DEVICE_COMMAND_UNSUPPORTED");const installation=await desktopInstallationIdentity(manager);let automatic=await desktopAutomation(home);const publicView=()=>({...view(s),installation,automaticConnection:canResumeDesktop(automatic,s,installation)});const processingSupported=async()=>{const active=(await manager.ledger.current()).value.active;return!!active&&await probeTenantMediaProcessing(manager.ledger.slotPath(active),active)};const librarySupported=async()=>{const active=(await manager.ledger.current()).value.active;return!!active&&await probeLocalLibrary(manager.ledger.slotPath(active),active)};const compositionSupported=async()=>{const active=(await manager.ledger.current()).value.active;return!!active&&await probeTenantComposition(manager.ledger.slotPath(active),active)};if(call.action==="media-processing-capability")return DesktopDeviceReplySchema.parse({view:publicView(),mediaProcessingSupported:await processingSupported(),localLibrarySupported:await librarySupported(),compositionProcessingSupported:await compositionSupported()});if(call.action==="media-validation-capability"){const active=(await manager.ledger.current()).value.active;const supported=!!active&&await probeTenantMediaValidation(manager.ledger.slotPath(active),active);return DesktopDeviceReplySchema.parse({view:publicView(),mediaValidationSupported:supported})}if(call.action==="inspect")return DesktopDeviceReplySchema.parse({view:publicView(),...s.pending?{command:s.pending.command}:{}});if(call.action==="dispatch"||call.action==="record"||call.action==="refused"){if(!s.pending||s.pending.fingerprint!==call.fingerprint)fail("DEVICE_PLAN_CHANGED");if(call.action==="dispatch"){if(s.pending.phase!=="PREPARED")fail("DEVICE_OUTCOME_UNKNOWN");const command2=s.pending.command;s=await records.save(s,{pending:{...s.pending,phase:"SENDING"}});return DesktopDeviceReplySchema.parse({view:publicView(),command:command2})}if(s.pending.phase!=="SENDING")fail("DEVICE_PLAN_CHANGED");s=await records.save(s,call.action==="record"?{...accepted(s,call.result),pending:null}:{pending:{...s.pending,phase:"REFUSED"}});return DesktopDeviceReplySchema.parse({view:publicView()})}if(s.pending?.phase==="SENDING")fail("DEVICE_OUTCOME_UNKNOWN");if(call.action==="remember-enable"){if(s.revision!==call.expectedRevision)fail("DEVICE_PLAN_CHANGED");automatic=await rememberDesktopAutomation(home,s,installation,call.installationFingerprint);return DesktopDeviceReplySchema.parse({view:publicView()})}if(call.action==="prove"){await proveDesktopDevice(records);return DesktopDeviceReplySchema.parse({view:publicView()})}if(call.action==="connect"){if(call.installationFingerprint&&call.installationFingerprint!==installation?.fingerprint)fail("DEVICE_PLAN_CHANGED");s=await connectDesktopDevice(records,manager,s,call.expectedRevision);return DesktopDeviceReplySchema.parse({view:publicView()})}if(call.action==="connection-recover"){s=await recoverDesktopConnection(records,manager,s);return DesktopDeviceReplySchema.parse({view:publicView()})}let command;if(call.action==="enroll"){if(s.device)fail("DEVICE_ALREADY_ENROLLED");if(call.expectedRevision!==void 0&&s.revision!==call.expectedRevision)fail("DEVICE_PLAN_CHANGED");const active=(await manager.ledger.current()).value.active;if(!active)fail("INSTALL_REQUIRED");let publicKey;try{const key=createPrivateKey2({key:JSON.parse((await read(records.keyPath(),16384)).toString()),format:"jwk"});publicKey=createPublicKey(key).export({format:"jwk"})}catch(e){if(e.code!=="ENOENT")throw e;publicKey=(await generateDeviceKey(records.keyPath())).publicKey}command={kind:"ENROLL",input:{tenantId:s.scope.tenantId,requestId:randomUUID3(),...call.bindWorkspaceMember||call.agentEnrollment?{expectedPrincipalId:s.scope.principalId}:{},label:call.label,platform:active.descriptor.platform,runtimeVersion:active.descriptor.version,publicKey}}}else{const d=s.device;if(!d)fail("DEVICE_ENROLLMENT_REQUIRED");if(call.action==="preview"||call.action==="final"){if(d.revokedAt)fail("LOCAL_AUTHORIZATION_REQUIRED");command={kind:call.action==="final"?"FINAL_RENDER":"PREVIEW",input:{...call.input,tenantId:s.scope.tenantId,placement:{mode:call.mode,deviceId:d.deviceId},idempotencyKey:"desktop:"+randomUUID3()}}}else{if(call.action!=="revoke"||d.revokedAt)fail("LOCAL_AUTHORIZATION_REQUIRED");command={kind:"REVOKE_DEVICE",input:{tenantId:s.scope.tenantId,deviceId:d.deviceId,requestId:randomUUID3(),expectedRevision:d.revision}}}}const parsed=LocalManagementCommandSchema.parse(command);s=await records.save(s,{...parsed.kind==="ENROLL"?{enrollment:parsed.input}:{},pending:{command:parsed,fingerprint:fingerprint(parsed),phase:"PREPARED",...call.action==="enroll"&&call.agentEnrollment&&{agentEnrollment:true}}});return DesktopDeviceReplySchema.parse({view:publicView(),command:parsed})}async function desktopDevicePending(home,scope){return(await(await DesktopDeviceRecords.open(home,scope)).current()).pending?.command??null}export{runDesktopDeviceRequest,desktopDevicePending};
@@ -1 +0,0 @@
1
- import{profileAuthorization}from"./chunk-3TOXIJ7K.js";import{connectRemoteMcp}from"./chunk-GLAF74UU.js";import{clientHome,loadConnection}from"./chunk-27KI24GK.js";import{optional,write}from"./chunk-DLW42PJ6.js";import{NativeStudioSdkError}from"./chunk-TT7IA5HB.js";import{join}from"node:path";import{z}from"zod";var selection=z.strictObject({version:z.literal(1),tenantId:z.uuid(),resource:z.url(),projectId:z.uuid()});async function workspaceProject(scope,env){const value=await optional(join(await clientHome(env),"selection.json"));if(value===null)return null;const parsed=selection.safeParse(value);if(!parsed.success)throw new NativeStudioSdkError("PROJECT_SELECTION_INVALID","BLOCKED","NO_WRITE");return parsed.data.tenantId===scope.tenantId&&(!scope.resource||parsed.data.resource===scope.resource)?parsed.data.projectId:null}async function workspaceCommand(argv,env){const[command,...args]=argv;if(!["workspaces","workspace","projects","project"].includes(command??""))return null;let connection;try{connection=await loadConnection(env)}catch(error){if(error instanceof NativeStudioSdkError&&error.code==="CONNECTION_ACCOUNT_MISMATCH")return null;throw error}if(!connection)return null;const flags=new Map;for(let i=0;i<args.length;i+=2){const key=args[i],value=args[i+1];if(!key||!value||value.startsWith("--")||flags.has(key)||!["--id","--limit","--next"].includes(key))throw Error();flags.set(key,value)}if(command==="projects"?flags.has("--id"):command==="workspaces"?flags.size>0:flags.size!==1||!flags.has("--id"))throw Error();const auth=await profileAuthorization(connection.profile);const remote=await connectRemoteMcp(connection.resource,auth.authorization,connection.tenantId);try{if(command==="workspaces"){const page=await remote.studio.call("workspace.query",{});return{exitCode:0,output:{semanticStatus:"SUCCESS",workspaces:page.items}}}if(command==="projects"){const page=await remote.studio.call("project.query",{...flags.has("--limit")?{limit:z.coerce.number().int().min(1).max(100).parse(flags.get("--limit"))}:{},...flags.has("--next")?{next:flags.get("--next")}:{}});return{exitCode:0,output:{semanticStatus:"SUCCESS",...page}}}const id=z.uuid().parse(flags.get("--id"));if(command==="workspace"){if(id!==connection.tenantId)throw new NativeStudioSdkError("FORBIDDEN","BLOCKED","NO_WRITE");const value2=await remote.studio.call("workspace.get",{});return{exitCode:0,output:{semanticStatus:"SUCCESS",workspaceId:value2.id}}}const value=await remote.studio.call("project.get",{projectId:id});await write(join(await clientHome(env),"selection.json"),JSON.stringify({version:1,tenantId:connection.tenantId,resource:connection.resource,projectId:value.project.id}));return{exitCode:0,output:{semanticStatus:"SUCCESS",project:value.project}}}finally{await remote.close().catch(()=>{})}}export{workspaceProject,workspaceCommand};
@@ -1 +0,0 @@
1
- import{z}from"zod";var CapabilityVersionSchema=z.string().regex(/^[a-f0-9]{64}$/);var CapabilityVersionMismatchSchema=z.strictObject({kind:z.enum(["CAPABILITY_DEFINITION","MEDIA_PROFILE","RENDERER","VALIDATION_PROFILE","PROCESSOR_PROFILE","LOCAL_LIBRARY_PROFILE"]),expectedVersion:CapabilityVersionSchema,actualVersion:CapabilityVersionSchema,recovery:z.enum(["REDISCOVER_CAPABILITY","CHECK_DEVICE_RELEASE"])});var InterfaceSemanticStatusSchema=z.enum(["SUCCESS","ACCEPTED","NO_CHANGE","INVALID_INPUT","NOT_FOUND","REVISION_CONFLICT","STALE_BASIS","BLOCKED","WAITING_PROVIDER","WAITING_INPUT","RETRYING","CAPABILITY_UNAVAILABLE","PROVIDER_UNAVAILABLE","BUDGET_BLOCKED","CANCELLED","SUPERSEDED","INTERNAL_OPERATIONAL_FAILURE"]);var ActionAvailabilitySchema=z.enum(["AVAILABLE","UNAVAILABLE"]);var NextActionSchema=z.object({capability:z.string().min(1).max(120),targetType:z.string().min(1).max(80),targetId:z.string().min(1).max(2048),availability:ActionAvailabilitySchema,reason:z.string().min(1).max(1e3).nullable()});var ContinuationSchema=z.string().min(1).max(8192);var QueryLimitSchema=z.int().min(1).max(100).default(20);var QueryPageInfoSchema=z.object({hasMore:z.boolean(),next:ContinuationSchema.nullable()});var WorkSummarySchema=z.object({total:z.int().nonnegative(),pending:z.int().nonnegative(),ready:z.int().nonnegative(),running:z.int().nonnegative(),waiting:z.int().nonnegative(),succeeded:z.int().nonnegative(),failed:z.int().nonnegative(),cancelled:z.int().nonnegative(),superseded:z.int().nonnegative(),attempts:z.int().nonnegative()});import{z as z2}from"zod";var TenantIdSchema=z2.uuid().brand();var PrincipalIdSchema=z2.uuid().brand();var ProjectIdSchema=z2.uuid().brand();var ProductionIdSchema=z2.uuid().brand();var ArtifactIdSchema=z2.uuid().brand();var ArtifactRepresentationIdSchema=z2.uuid().brand();var ArtifactRelationIdSchema=z2.uuid().brand();var BriefIdSchema=z2.uuid().brand();var BriefVersionIdSchema=z2.uuid().brand();var StoryIdSchema=z2.uuid().brand();var StoryVersionIdSchema=z2.uuid().brand();var SceneShotPlanIdSchema=z2.uuid().brand();var SceneShotPlanVersionIdSchema=z2.uuid().brand();var SceneIdSchema=z2.uuid().brand();var ShotIdSchema=z2.uuid().brand();var ContinuityEdgeIdSchema=z2.uuid().brand();var RuntimeJobIdSchema=z2.uuid().brand();var OperationIdSchema=z2.string().regex(/^op_[A-Za-z0-9_-]+$/).max(2048).brand();var RuntimeJobAttemptIdSchema=z2.uuid().brand();var OutboxEventIdSchema=z2.uuid().brand();import{z as z3}from"zod";var uuid="[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}";var page=new RegExp(`^/(?:projects(?:/${uuid})?|artifacts|productions/${uuid}(?:/(?:artifacts|delivery|history))?|settings/voices(?:/${uuid}(?:/versions/[1-9][0-9]*)?)?)$`);var HumanLinkScopeSchema=z3.strictObject({tenantId:z3.uuid(),projectId:z3.uuid().optional(),productionId:z3.uuid().optional(),artifactId:z3.uuid().optional(),representationId:z3.uuid().optional(),delivery:z3.boolean().optional(),voices:z3.boolean().optional(),voiceProfileId:z3.uuid().optional(),voiceProfileVersion:z3.int().positive().optional()}).refine(s=>!!s.artifactId===!!s.representationId&&(!s.delivery||!!s.productionId)&&(s.voiceProfileVersion===void 0||!!s.voiceProfileId));var HumanLinkSchema=z3.strictObject({rel:z3.enum(["workspace","project","production","artifact","delivery","voice_profile"]),href:z3.url().max(2048)}).refine(({rel,href})=>{try{const u=new URL(href),q=u.searchParams,parts=u.pathname.split("/"),pathId=parts[1]==="settings"?parts[3]:parts[2];return u.href===href&&!u.username&&!u.password&&!href.includes("#")&&(u.protocol==="https:"||u.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(u.hostname))&&page.test(u.pathname)&&(!pathId||z3.uuid().safeParse(pathId).success)&&(parts[4]!=="versions"||z3.int().positive().safeParse(Number(parts[5])).success)&&new Set(q.keys()).size===q.size&&[...q].every(([key,value])=>["workspace","artifact","representation"].includes(key)&&z3.uuid().safeParse(value).success)&&q.has("workspace")&&q.has("artifact")===q.has("representation")&&(rel==="artifact"?u.pathname.endsWith("/artifacts")&&q.has("artifact"):!q.has("artifact")&&(rel==="workspace"?u.pathname==="/projects":rel==="project"?new RegExp(`^/projects/${uuid}$`).test(u.pathname):rel==="voice_profile"?u.pathname.startsWith("/settings/voices"):rel==="production"?new RegExp(`^/productions/${uuid}$`).test(u.pathname):u.pathname.endsWith("/delivery")))}catch{return false}});var HumanLinksSchema=z3.discriminatedUnion("status",[z3.strictObject({status:z3.literal("AVAILABLE"),items:z3.array(HumanLinkSchema).min(1).max(4)}),z3.strictObject({status:z3.enum(["UNCONFIGURED","UNAVAILABLE"]),items:z3.array(HumanLinkSchema).max(0)})]);import{z as z4}from"zod";var DeliveryOutputProfileSchema=z4.enum(["MP4_H264_1080P","MP4_H264_720P","MP4_H264_480P"]);var finalProfileIds={MP4_H264_1080P:"FINAL_H264_1080P_V1",MP4_H264_720P:"FINAL_H264_720P_V1",MP4_H264_480P:"FINAL_H264_480P_V1"};import{z as z7}from"zod";import{z as z6}from"zod";import{z as z5}from"zod";var ProductionLifecycleSchema=z5.enum(["ACTIVE","COMPLETED","FAILED","CANCELLED"]);var ProductionPhaseSchema=z5.enum(["INTAKE","PLANNING","PREPARING_GENERATION","GENERATING","SHOT_REVIEW","ASSEMBLING","ROUGH_CUT_REVIEW","FINAL_READY","FINAL_RENDERING","DELIVERY_VALIDATION"]);var ProductionConditionSchema=z5.enum(["RUNNABLE","RUNNING","WAITING_PROVIDER","WAITING_HUMAN","BLOCKED","RETRYING"]);var CreateProductionInputSchema=z5.object({tenantId:TenantIdSchema,projectId:ProjectIdSchema,principalId:PrincipalIdSchema});var ProductionStateSchema=z5.object({lifecycle:ProductionLifecycleSchema,phase:ProductionPhaseSchema,condition:ProductionConditionSchema,revision:z5.int().positive(),blockingReason:z5.string().min(1).nullable(),waitingReason:z5.string().min(1).nullable()});var ProductionSchema=z5.object({humanLinks:HumanLinksSchema.optional(),id:ProductionIdSchema,tenantId:TenantIdSchema,projectId:ProjectIdSchema,state:ProductionStateSchema,activeBriefVersion:z5.int().positive().nullable().default(null),activeStoryVersion:z5.int().positive().nullable().default(null),activeSceneShotPlanVersion:z5.int().positive().nullable().default(null),createdByPrincipalId:PrincipalIdSchema,createdAt:z5.iso.datetime({offset:true}),updatedAt:z5.iso.datetime({offset:true})});var ProjectLifecycleSchema=z6.enum(["ACTIVE","ARCHIVED"]);var CreateProjectInputSchema=z6.object({tenantId:TenantIdSchema,principalId:PrincipalIdSchema,idempotencyKey:z6.string().trim().min(1).max(200),name:z6.string().trim().min(1).max(200)});var CreateProjectRequestSchema=CreateProjectInputSchema.omit({principalId:true}).strict();var ProjectSchema=z6.object({id:ProjectIdSchema,tenantId:TenantIdSchema,name:z6.string().min(1),lifecycle:ProjectLifecycleSchema,defaultActiveProductionId:ProductionIdSchema.nullable(),revision:z6.int().positive(),createdByPrincipalId:PrincipalIdSchema,createdAt:z6.iso.datetime({offset:true}),updatedAt:z6.iso.datetime({offset:true})});var CreatedProjectResultSchema=z6.object({project:ProjectSchema,production:ProductionSchema});var ProjectLibraryQuerySchema=z7.strictObject({tenantId:TenantIdSchema,limit:QueryLimitSchema,next:ContinuationSchema.optional()});var ProjectLibraryScopeSchema=z7.strictObject({tenantId:TenantIdSchema,projectId:ProjectIdSchema});var ProjectLibraryPageSchema=z7.strictObject({items:z7.array(ProjectSchema).max(100),page:QueryPageInfoSchema});var ProjectWorkspaceSchema=z7.strictObject({project:ProjectSchema,productions:z7.array(ProductionSchema).max(100),possiblyTruncated:z7.boolean()});var SourceLibraryQuerySchema=ProjectLibraryQuerySchema.extend({projectId:ProjectIdSchema.optional()});var SourceLibraryItemSchema=z7.strictObject({artifactId:z7.uuid(),representationId:z7.uuid(),projectId:ProjectIdSchema,kind:z7.enum(["REFERENCE_IMAGE","REFERENCE_VIDEO","PRODUCT_INFORMATION"]),originalName:z7.string().max(255),checksumSha256:z7.string().regex(/^[0-9a-f]{64}$/),contentType:z7.enum(["image/png","image/jpeg","image/webp","text/plain","application/json","video/mp4"]),byteSize:z7.int().positive().max(8388608),width:z7.int().positive().nullable(),height:z7.int().positive().nullable(),createdAt:z7.iso.datetime({offset:true})});var SourceLibraryPageSchema=z7.strictObject({items:z7.array(SourceLibraryItemSchema).max(100),page:QueryPageInfoSchema});var SourceLibraryMediaSchema=ProjectLibraryScopeSchema.extend({artifactId:z7.uuid()});var StudioInputContentSchema=z7.strictObject({schemaVersion:z7.literal(1),productionId:z7.uuid(),projectTitle:z7.string().trim().min(1).max(200),name:z7.string().trim().max(300),intent:z7.string().trim().min(1).max(2e3),aspectRatio:z7.enum(["16:9","9:16"]),targetDurationSeconds:z7.int().min(30).max(60),outputProfile:DeliveryOutputProfileSchema,sourceArtifactIds:z7.array(z7.uuid()).max(12)});import{z as z8}from"zod";var HumanEmailSchema=z8.string().trim().max(254).toLowerCase().pipe(z8.email()).refine(v=>/^[\x21-\x7e]+$/.test(v),"Use an ASCII email address");var HumanPasswordSchema=z8.string().max(512).superRefine((v,c)=>{const points=[...v];const control=points.some(c2=>c2.codePointAt(0)<32||c2.codePointAt(0)===127);if(points.length<15||points.length>128||control)c.addIssue({code:"custom",message:"Password must contain 15\u2013128 characters"})});var HumanCodePurposeSchema=z8.enum(["REGISTER","RESET_PASSWORD","LINK_EMAIL"]);var HumanCodeRequestSchema=z8.strictObject({email:HumanEmailSchema,purpose:HumanCodePurposeSchema});var HumanCodeRequestedSchema=z8.strictObject({accepted:z8.literal(true),challengeId:z8.uuid(),retryAfterSeconds:z8.literal(60),expiresInSeconds:z8.literal(600)});var proof={challengeId:z8.uuid(),email:HumanEmailSchema,code:z8.string().regex(/^\d{6}$/),password:HumanPasswordSchema};var HumanRegisterSchema=z8.strictObject({...proof,displayName:z8.string().trim().min(1).max(80)});var HumanResetSchema=z8.strictObject(proof);var HumanLoginSchema=z8.strictObject({email:HumanEmailSchema,password:z8.string().max(512),rememberMe:z8.boolean().optional()});var HumanTenantSchema=z8.strictObject({id:z8.uuid(),displayName:z8.string().max(200)});var HumanAccountSchema=z8.strictObject({principalId:z8.uuid(),displayName:z8.string().max(200),email:HumanEmailSchema.nullable(),tenants:z8.array(HumanTenantSchema).max(100)});var HumanDesktopSessionSchema=z8.strictObject({tenantId:z8.uuid(),scopeKey:z8.string().regex(/^[a-f0-9]{64}$/),expiresAt:z8.int().positive(),sessionExpiresAt:z8.int().positive().optional(),rememberMe:z8.boolean(),account:HumanAccountSchema.omit({tenants:true})}).refine(({rememberMe,expiresAt,sessionExpiresAt})=>sessionExpiresAt===void 0||rememberMe&&sessionExpiresAt>=expiresAt,"Desktop persistence requires consent and the session deadline");var ShortHumanSessionSchema=z8.strictObject({accessToken:z8.string().regex(/^nvsh_[A-Za-z0-9_-]{43}$/),expiresAt:z8.iso.datetime(),account:HumanAccountSchema});var HumanRefreshTokenSchema=z8.string().regex(/^nvshr_[A-Za-z0-9_-]{43}$/);var HumanRefreshSchema=z8.strictObject({refreshToken:HumanRefreshTokenSchema});var HumanSessionSchema=ShortHumanSessionSchema.extend({refreshToken:HumanRefreshTokenSchema.optional(),sessionId:z8.uuid().optional(),sessionExpiresAt:z8.iso.datetime().optional()}).refine(session=>{const{refreshToken,sessionId,sessionExpiresAt,expiresAt}=session;if(!refreshToken)return sessionId===void 0&&sessionExpiresAt===void 0;return!!sessionId&&!!sessionExpiresAt&&Date.parse(expiresAt)<=Date.parse(sessionExpiresAt)},"Persistent session requires its exact identity and absolute expiry");var HumanIdentityAvailabilitySchema=z8.strictObject({passwordLogin:z8.boolean(),emailVerification:z8.boolean()});var HumanIdentityFailureSchema=z8.strictObject({code:z8.enum(["INVALID_INPUT","INVALID_CREDENTIALS","INVALID_CODE","RATE_LIMITED","MAIL_UNAVAILABLE","UNAVAILABLE","UNAUTHENTICATED","CONFLICT"])});var CliAccountRedirectSchema=z8.string().max(256).refine(value=>{try{const url=new URL(value);return url.protocol==="http:"&&url.hostname==="127.0.0.1"&&Number(url.port)>0&&!url.username&&!url.password&&!url.search&&!url.hash&&/^\/account-callback\/[a-f0-9-]{36}$/.test(url.pathname)&&url.href===value}catch{return false}},"Owned loopback account callback required");var proofKey=z8.string().regex(/^[A-Za-z0-9_-]{43}$/);var CliAccountRequestIdSchema=z8.uuid();var CliAccountStartSchema=z8.strictObject({redirectUri:CliAccountRedirectSchema,state:proofKey,codeChallenge:proofKey});var CliAccountStartedSchema=z8.strictObject({requestId:z8.uuid(),expiresAt:z8.iso.datetime()});var CliAccountPreviewSchema=CliAccountStartedSchema.extend({redirectUri:CliAccountRedirectSchema});var CliAccountDecisionSchema=z8.strictObject({requestId:z8.uuid(),approved:z8.boolean(),expectedPrincipalId:z8.uuid()});var CliAccountExchangeSchema=z8.strictObject({requestId:z8.uuid(),code:proofKey,codeVerifier:proofKey,redirectUri:CliAccountRedirectSchema});var CliAccountSessionSchema=ShortHumanSessionSchema.extend({credentialPurpose:z8.literal("CLI_ACCOUNT")});var CliAccountIdentitySchema=z8.strictObject({credentialPurpose:z8.literal("CLI_ACCOUNT"),account:HumanAccountSchema});export{TenantIdSchema,PrincipalIdSchema,ProjectIdSchema,ProductionIdSchema,ArtifactIdSchema,ArtifactRepresentationIdSchema,ArtifactRelationIdSchema,BriefIdSchema,BriefVersionIdSchema,StoryIdSchema,StoryVersionIdSchema,SceneShotPlanIdSchema,SceneShotPlanVersionIdSchema,SceneIdSchema,ShotIdSchema,ContinuityEdgeIdSchema,OperationIdSchema,HumanLinksSchema,DeliveryOutputProfileSchema,finalProfileIds,CapabilityVersionSchema,CapabilityVersionMismatchSchema,InterfaceSemanticStatusSchema,NextActionSchema,ContinuationSchema,QueryLimitSchema,QueryPageInfoSchema,WorkSummarySchema,HumanTenantSchema,CliAccountStartSchema,CliAccountStartedSchema,CliAccountExchangeSchema,CliAccountSessionSchema,CliAccountIdentitySchema,ProductionStateSchema,ProductionSchema,CreateProjectRequestSchema,ProjectSchema,CreatedProjectResultSchema,ProjectLibraryQuerySchema,ProjectLibraryScopeSchema,ProjectLibraryPageSchema,ProjectWorkspaceSchema,SourceLibraryQuerySchema,SourceLibraryItemSchema,SourceLibraryPageSchema,SourceLibraryMediaSchema,StudioInputContentSchema};
@@ -1 +0,0 @@
1
- import{ComponentCommandSchema,HostComponentRequestSchema}from"./chunk-QE7O57PQ.js";import"./chunk-4M2SOMSN.js";import"./chunk-L3QA7FLZ.js";import"./chunk-MLZ3ZPGU.js";import"./chunk-ELUJ44BO.js";import"./chunk-IYDHDLTR.js";import"./chunk-6EZX2TRX.js";import"./chunk-APNZQZFB.js";import"./chunk-DLW42PJ6.js";import"./chunk-WTJVS2VS.js";import"./chunk-TT7IA5HB.js";export{ComponentCommandSchema,HostComponentRequestSchema};
@@ -1 +0,0 @@
1
- import{assertComponentConfiguration,componentDevice,observeComponent}from"./chunk-LBK42NHW.js";import{observeLoginHost}from"./chunk-D74NHT4I.js";import"./chunk-QE7O57PQ.js";import{desktopRuntimeChannel}from"./chunk-4PAVWOPA.js";import"./chunk-4M2SOMSN.js";import"./chunk-L3QA7FLZ.js";import"./chunk-MLZ3ZPGU.js";import{captureInstalledTools,installationSource,verifyCaptionDirectory}from"./chunk-ELUJ44BO.js";import"./chunk-AFNJRZLJ.js";import"./chunk-IYDHDLTR.js";import{LocalToolSelectionSchema}from"./chunk-6EZX2TRX.js";import"./chunk-APNZQZFB.js";import"./chunk-7I7ARCY7.js";import{LocalClientError,assertExecutable,read}from"./chunk-DLW42PJ6.js";import"./chunk-WTJVS2VS.js";import"./chunk-KOCUZ3AE.js";import"./chunk-TT7IA5HB.js";import{realpath}from"node:fs/promises";import{delimiter,isAbsolute,join}from"node:path";function reason(error,fallback){return error instanceof LocalClientError&&/^[A-Z][A-Z0-9_]{0,79}$/.test(error.code)?error.code:fallback}async function toolPath(name,explicit){const path=process.platform==="win32"?name+".exe":name;const choices=explicit?[explicit]:(process.env.PATH??"").split(delimiter).filter(isAbsolute).slice(0,64).map(root=>join(root,path));for(const candidate of choices){if(!isAbsolute(candidate))continue;try{const actual=await realpath(candidate);await assertExecutable(actual);return actual}catch{}}}async function componentPreflight(home,scope,call,manager,receipts){const observedAt=new Date().toISOString();const platform={os:process.platform,architecture:process.arch,node:process.versions.node};const configuration=manager&&await assertComponentConfiguration(manager,scope);const installation=manager&&(await manager.ledger.current()).value;const last=manager&&(await receipts.snapshot()).latest;const status=(body,exitCode=0)=>({exitCode,output:{protocol:"NVS_HOST_PREFLIGHT_V1",observedAt,kind:call.kind,platform,componentHome:home,installationRevision:installation?.revision??0,installedVersion:installation?.active?.descriptor.version??null,...body}});const blocked=(reasonCode,nextAction,facts2={})=>status({state:"BLOCKED",reasonCode,nextAction,...facts2},4);if(last?.phase==="SENDING")return blocked(last.reasonCode,{surface:"HOST_COMPONENT",action:"observe-original",requestId:last.command.requestId});if(installation?.transition)return blocked("INSTALLATION_RECOVERY_REQUIRED",{surface:"HOST_COMPONENT",action:"reconcile-install",planId:installation.transition.planId,fingerprint:installation.transition.fingerprint,expectedRevision:installation.revision});if(last?.outcome==="UNKNOWN")return blocked(last.reasonCode,{surface:"HOST_COMPONENT",action:"receipt",requestId:last.command.requestId});if(process.platform!=="win32"&&Buffer.byteLength(join(home,"rt","runtime.sock"))>100)return blocked("SOCKET_PATH_TOO_LONG",{surface:"HOST_OWNER",action:"SELECT_PRIVATE_HOME"});const login=await observeLoginHost().then(state=>({state,reasonCode:state==="UNAVAILABLE"?"LOGIN_SERVICE_UNAVAILABLE":null}),error=>({state:"UNAVAILABLE",reasonCode:reason(error,"LOGIN_SERVICE_UNAVAILABLE")}));const host={loginService:login};if(call.source==="SIGNED_CHANNEL"&&call.version==="latest")return blocked("EXACT_RELEASE_VERSION_REQUIRED",{surface:"HOST_OWNER",action:"SELECT_EXACT_RELEASE"},host);const configured=configuration?.catalogueUrl&&configuration.publicKeyFile?{catalogueUrl:configuration.catalogueUrl,publicKeyFile:configuration.publicKeyFile}:null;let trust={...configured??{},rejectedVersions:configuration?.rejectedVersions??[]};const bundled=call.source==="BUNDLED";const fullMedia=call.kind!=="library";const active=installation?.active;const pinned=fullMedia&&active?.toolsConfigPath&&!call.tools?LocalToolSelectionSchema.parse(JSON.parse((await read(active.toolsConfigPath,32768)).toString())):null;const activeCaptions=active&&manager?join(manager.ledger.slotPath(active),"dist/captions"):void 0;const captionPath=call.tools?.captionAssetsDirectory??activeCaptions;let localCaptions=false;if(fullMedia&&captionPath){try{await verifyCaptionDirectory(captionPath);localCaptions=true}catch(error){if(call.tools?.captionAssetsDirectory)return blocked(reason(error,"CAPTION_ASSET_UNAVAILABLE"),{surface:"HOST_OWNER",action:"PROVIDE_MATCHING_CAPTION_ASSETS"},host)}}const[ffmpeg,ffprobe]=fullMedia?await Promise.all([toolPath("ffmpeg",call.tools?.ffmpeg??pinned?.ffmpeg.path),toolPath("ffprobe",call.tools?.ffprobe??pinned?.ffprobe.path)]):[void 0,void 0];const missingTools=[!ffmpeg&&"FFMPEG",!ffprobe&&"FFPROBE"].filter(name=>name!==false);let release;try{if(call.channel&&(!bundled||fullMedia&&(!localCaptions||missingTools.length))){const{value}=desktopRuntimeChannel({...call.channel,protocol:"NVS_DESKTOP_RUNTIME_CHANNEL_V1"});if(configured&&(configured.catalogueUrl!==value.catalogueUrl||(await read(configured.publicKeyFile,16384)).toString().trim()!==value.publicKey.trim()))return blocked("DEPENDENCY_CHANNEL_CHANGED",{surface:"HOST_OWNER",action:"CHECK_CONFIGURED_RELEASE_CHANNEL"},host);if(!configured)trust={...trust,catalogueUrl:value.catalogueUrl,publicKey:value.publicKey}}const dependencyChannel=fullMedia&&(!localCaptions||missingTools.length>0)&&!!trust.catalogueUrl;release=(await installationSource(trust,call.version,bundled,dependencyChannel)).release}catch(error){return blocked(reason(error,"RELEASE_OBSERVATION_UNAVAILABLE"),{surface:"HOST_OWNER",action:"CHECK_RELEASE_SOURCE"},host)}const facts={...host,release:{version:release.descriptor.version,source:call.source,node:release.descriptor.node,sha512:release.package.sha512}};let tools;if(fullMedia){const explicitMissing=call.tools?.ffmpeg&&!ffmpeg||call.tools?.ffprobe&&!ffprobe;const mediaSource=ffmpeg&&ffprobe?"INSTALLED":!explicitMissing&&release.tools?"SIGNED_CHANNEL":"MISSING";const canReuseCaptions=localCaptions&&(!call.tools?.captionAssetsDirectory||mediaSource==="INSTALLED");const captionSource=canReuseCaptions?"INSTALLED":release.resources?.captions?"SIGNED_CHANNEL":"MISSING";const dependencies={mediaSource,captionSource,missingTools:mediaSource==="MISSING"?missingTools:[]};if(mediaSource==="MISSING"||captionSource==="MISSING")return blocked("MEDIA_DEPENDENCIES_REQUIRED",{surface:"HOST_OWNER",action:"PROVIDE_MATCHING_DEPENDENCIES"},{...facts,dependencies});try{tools=ffmpeg&&ffprobe?await captureInstalledTools({mode:"INSTALLED",ffmpeg,ffprobe,...call.tools?.captionAssetsDirectory&&{captionAssetsDirectory:captionPath}}):{mode:"MANAGED"}}catch(error){return blocked(reason(error,"TOOL_IDENTITY_UNAVAILABLE"),{surface:"HOST_OWNER",action:"CHECK_INSTALLED_TOOLS"},{...facts,dependencies})}if(pinned&&(tools.mode!=="INSTALLED"||tools.ffmpeg.digest!==pinned.ffmpeg.digest||tools.ffprobe.digest!==pinned.ffprobe.digest))return blocked("INSTALLED_TOOL_IDENTITY_CHANGED",{surface:"HOST_OWNER",action:"CHECK_INSTALLED_TOOLS"},{...facts,dependencies});Object.assign(facts,{dependencies})}if(!manager||!configured&&!!trust.catalogueUrl)return status({...facts,state:"INITIALIZATION_REQUIRED",reasonCode:manager?"DEPENDENCY_CHANNEL_CONFIGURATION_REQUIRED":"COMPONENT_NOT_INITIALIZED",nextAction:{surface:"HOST_COMPONENT",call:{action:"initialize"},includeOriginalChannel:!!trust.catalogueUrl}});if(!active||active.descriptor.version!==release.descriptor.version||fullMedia&&(!active.toolsConfigPath||!localCaptions||!!call.tools))return status({...facts,state:"INSTALL_PLAN_REQUIRED",reasonCode:"PIN_CURRENT_INSTALLATION_PLAN",nextAction:{surface:"HOST_COMPONENT",call:{action:"install-plan",version:release.descriptor.version,source:call.source,...tools&&{tools}}}});const device=await componentDevice(home,scope);const component=await observeComponent(home,scope,manager,receipts);if(device&&component.liveness.state==="STOPPED")return status({...facts,component,state:"START_REQUIRED",reasonCode:"OWNED_RUNTIME_STOPPED",nextAction:{surface:"HOST_COMPONENT",action:"start",expectedRevision:component.installationRevision}});return status({...facts,component,state:device?"VERIFY_DEVICE":"ENROLLMENT_REQUIRED",reasonCode:device?"CHECK_DEVICE_HEARTBEAT_AND_TASK":"INSPECT_ORIGINAL_ENROLLMENT",nextAction:device?{surface:"MCP",tool:"studio_capability_query",arguments:{tenantId:scope.tenantId,tool:"device_status",arguments:{tenantId:scope.tenantId,deviceId:device.deviceId}}}:{surface:"HOST_ENROLLMENT",call:{action:"inspect"}}})}export{componentPreflight};
@@ -1 +0,0 @@
1
- import{loginLink,openLoginBrowser}from"./chunk-OW6R4MAQ.js";import{profileAuthorization,runOAuthCommand}from"./chunk-3TOXIJ7K.js";import"./chunk-QGK6G6YS.js";import{clientHome,connectionError,loadConnection,readAccount,saveConnection,tenantConnection}from"./chunk-27KI24GK.js";import{FileOAuthProvider}from"./chunk-7I7ARCY7.js";import"./chunk-DLW42PJ6.js";import"./chunk-WTJVS2VS.js";import"./chunk-KOCUZ3AE.js";import{NativeStudioSdkError}from"./chunk-TT7IA5HB.js";import{randomUUID,timingSafeEqual}from"node:crypto";import{createServer}from"node:http";import{join}from"node:path";async function runConnect(argv,environment,hooks={}){if(argv[0]!=="connect")throw Error();const options=new Map;for(let i=1;i<argv.length;i+=2){const key=argv[i],value=argv[i+1];if(!key||!["--mcp-url","--scope","--timeout-ms","--browser"].includes(key)||!value||value.startsWith("--")||options.has(key))throw Error();options.set(key,value)}const root=await clientHome(environment,true),account=await readAccount(root);const explicit=options.get("--mcp-url");if(!explicit&&!account?.workspaceId)connectionError("ACCOUNT_WORKSPACE_SELECTION_REQUIRED");const resource=tenantConnection(explicit??new URL("/mcp/external/v1/tenants/"+account.workspaceId,account.serverOrigin).href);const scope=options.get("--scope")??"nvs:read nvs:write";if(!["nvs:read","nvs:read nvs:write"].includes(scope))throw Error();const browser=options.get("--browser")??"auto";if(!["auto","manual"].includes(browser))throw Error();const timeout=options.get("--timeout-ms")??"180000";if(!/^\d+$/.test(timeout)||Number(timeout)<1e3||Number(timeout)>3e5)throw Error();const signal=AbortSignal.timeout(Number(timeout));const profile=`profile-${randomUUID()}.json`;const path=join(root,profile),callbackPath=`/callback/${randomUUID()}`;if(account&&(account.state!=="ACTIVE"||account.workspaceId!==resource.tenantId))connectionError("ACCOUNT_WORKSPACE_SELECTION_REQUIRED");if(!explicit){let saved=null;try{saved=await loadConnection(environment)}catch(error){if(!(error instanceof NativeStudioSdkError)||error.code!=="CONNECTION_ACCOUNT_MISMATCH")throw error}if(saved?.resource===resource.resource&&saved.scope===scope&&!saved.exchangeUnresolved){await profileAuthorization(saved.profile,signal);return{exitCode:0,output:{semanticStatus:"SUCCESS",connected:true,resource:saved.resource,tenantId:saved.tenantId,scope,reused:true}}}}let provider,receiving=false,redeeming=false;let finish;const callback=new Promise(resolve=>{finish=resolve});const server=createServer({maxHeaderSize:8192,requestTimeout:5e3,headersTimeout:5e3},(req,res)=>{res.setHeader("cache-control","no-store");res.setHeader("content-type","text/plain; charset=utf-8");res.setHeader("x-content-type-options","nosniff");const address=server.address();const host=address&&typeof address!=="string"?`127.0.0.1:${address.port}`:"";if(req.method!=="GET"||req.headers.host!==host||req.headers.origin||!req.url||req.url.length>4096||!req.url.startsWith(callbackPath+"?")||!provider||receiving){res.writeHead(400).end("Invalid authorization callback.");return}const url=new URL(req.url,`http://${host}`),state=url.searchParams.get("state");const expected=provider.data.state;const issuer=provider.data.discovery?.authorizationServerMetadata?.issuer??provider.data.discovery?.authorizationServerUrl;if(!state||Buffer.byteLength(state)!==Buffer.byteLength(expected)||!timingSafeEqual(Buffer.from(state),Buffer.from(expected))||url.searchParams.getAll("state").length!==1||url.pathname!==callbackPath||url.searchParams.getAll("iss").length!==1||url.searchParams.get("iss")!==issuer||(url.searchParams.has("error")?url.searchParams.has("code"):url.searchParams.getAll("code").length!==1||!url.searchParams.get("code"))){res.writeHead(400).end("Invalid authorization callback.");return}receiving=true;res.end("Authorization received. Return to NativeStudio CLI for the result.");finish(url.searchParams.has("error")?null:url.href)});server.maxConnections=8;const expired=()=>finish(null);signal.addEventListener("abort",expired,{once:true});try{await new Promise((resolve,reject)=>{server.once("error",reject);server.listen(0,"127.0.0.1",resolve)});const address=server.address();if(!address||typeof address==="string")throw Error();const redirect=`http://127.0.0.1:${address.port}${callbackPath}`;await runOAuthCommand(["auth-start","--profile",path,"--mcp-url",resource.resource,"--callback",redirect,"--scope",scope],empty(),signal);provider=await FileOAuthProvider.load(path);if(!provider.data.authorizationUrl)throw Error();signal.throwIfAborted();if(hooks.authorize)await hooks.authorize(provider.data.authorizationUrl,signal);else if(browser==="manual")loginLink(provider.data.authorizationUrl);else await openLoginBrowser(provider.data.authorizationUrl,signal);const received=await callback;if(!received)connectionError(signal.aborted?"LOGIN_TIMED_OUT":"LOGIN_DENIED");async function*input(){yield Buffer.from(JSON.stringify({callbackUrl:received}))}redeeming=true;await runOAuthCommand(["auth-complete","--profile",path,"--input","-"],input(),signal);const credentials=await saveConnection(root,profile,account?.epoch).catch(()=>{throw new NativeStudioSdkError("AUTHORIZED_CONNECTION_NOT_SELECTED","INTERNAL_OPERATIONAL_FAILURE","UNKNOWN")});return{exitCode:0,output:{semanticStatus:"SUCCESS",connected:true,credentialPurpose:"TENANT_MCP",...resource,scope:credentials.scope,requestedScope:scope,nextSteps:["nvs status","nvs find --query <intent>","nvs mcp"]}}}catch(error){if(!redeeming&&signal.aborted)connectionError("LOGIN_TIMED_OUT");throw error}finally{signal.removeEventListener("abort",expired);server.closeAllConnections();await new Promise(resolve=>server.close(()=>resolve()))}}async function*empty(){}export{runConnect};
@@ -1 +0,0 @@
1
- import{profileAuthorization}from"./chunk-3TOXIJ7K.js";import{readCredential,readInput}from"./chunk-QGK6G6YS.js";import{connectRemoteMcp}from"./chunk-GLAF74UU.js";import"./chunk-2UYKJ6YN.js";import"./chunk-APNZQZFB.js";import{defaultConnection,tenantConnection}from"./chunk-27KI24GK.js";import"./chunk-7I7ARCY7.js";import"./chunk-DLW42PJ6.js";import{CapabilityVersionSchema}from"./chunk-WTJVS2VS.js";import"./chunk-KOCUZ3AE.js";import{NativeStudioSdkError}from"./chunk-TT7IA5HB.js";var operations={status:"device.status",enroll:"device.enroll","enrollment-issue":"device.enrollment.issue","enrollment-lookup":"device.enrollment.lookup",revoke:"device.revoke",receipt:"device.management-receipt"};async function deviceManagementCommand(action,args,env,stdin){if(!action||!Object.hasOwn(operations,action))throw Error();const flags=new Map;for(let i=0;i<args.length;i+=2){const key=args[i],value=args[i+1];if(!key||!["--input","--profile","--mcp-url","--token-file","--token-env","--capability-version"].includes(key)||!value||value.startsWith("--")||flags.has(key))throw Error();flags.set(key,value)}if(!flags.has("--input"))throw Error();const capabilityVersion=CapabilityVersionSchema.optional().parse(flags.get("--capability-version"));await defaultConnection(flags,env,true);const profile=flags.get("--profile");if(profile&&["--mcp-url","--token-file","--token-env"].some(k=>flags.has(k)))throw Error();const token=profile?await profileAuthorization(profile):null;const resource=token?.resource??flags.get("--mcp-url");if(!resource)throw Error();const scope=tenantConnection(resource);const raw=await readInput(flags.get("--input"),stdin);const nested=action==="receipt"?raw.input:raw;if(nested?.tenantId!==void 0&&String(nested.tenantId).toLowerCase()!==scope.tenantId.toLowerCase())throw new NativeStudioSdkError("FORBIDDEN","BLOCKED","NO_WRITE");const authorization=token?.authorization??await readCredential(flags,env);const connection=await connectRemoteMcp(scope.resource,authorization,scope.tenantId);try{const key=operations[action];const input=action==="receipt"?{command:raw}:{...raw,tenantId:scope.tenantId};const command=input;const output=capabilityVersion?await connection.studio.call(key,command,{capabilityVersion}):await connection.studio.call(key,command);return{exitCode:0,output}}finally{await connection.close().catch(()=>{})}}export{deviceManagementCommand};
@@ -1 +0,0 @@
1
- import{callerOriginMatches,workspaceCaller}from"./chunk-NG4BDFEY.js";import{renderConnection}from"./chunk-OSO6KRE2.js";import"./chunk-UYKCN5DU.js";import{LocalInstallationManager,ownerClient,probeLocalLibrary,probeReferenceThumbnail,probeTenantComposition,probeTenantMediaProcessing,probeTenantMediaValidation,probeTenantQwenGeneration,probeTenantSpeech,probeTenantTranscription,verifySlot}from"./chunk-ELUJ44BO.js";import{DesktopDeviceRecords}from"./chunk-AFNJRZLJ.js";import"./chunk-IYDHDLTR.js";import{LocalToolSelectionSchema}from"./chunk-6EZX2TRX.js";import"./chunk-3TOXIJ7K.js";import"./chunk-QGK6G6YS.js";import"./chunk-GLAF74UU.js";import"./chunk-2UYKJ6YN.js";import{DeviceDiscoveryInputSchema,LocalDeviceTransportConfigurationSchema}from"./chunk-APNZQZFB.js";import"./chunk-7P2NA6TH.js";import"./chunk-27KI24GK.js";import"./chunk-7I7ARCY7.js";import{LocalClientError,read}from"./chunk-DLW42PJ6.js";import"./chunk-WTJVS2VS.js";import"./chunk-KOCUZ3AE.js";import{NativeStudioSdkError}from"./chunk-TT7IA5HB.js";import{z}from"zod";var transportSchema=LocalDeviceTransportConfigurationSchema.safeExtend({tools:LocalToolSelectionSchema.optional()});var nextSteps={ACCOUNT_LOGIN_REQUIRED:"nvs login --server <Studio-origin>",TENANT_CONNECTION_REQUIRED:"nvs connect --mcp-url <tenant-connection-url>",ACCOUNT_REVOCATION_UNCONFIRMED:"nvs logout",PROJECT_SELECTION_REQUIRED:"Run nvs workspaces, nvs projects, then nvs project --id <project-id>",INSTALL_REQUIRED:"Configure the Runtime, check signed releases, then prepare nvs local install --version <exact>",INSTALLATION_RECOVERY_REQUIRED:"Inspect nvs local status, then reconcile the original installation plan",CONFIGURATION_REQUIRED:"nvs local configure --input <private-json>",DEVICE_ENROLLMENT_REQUIRED:"nvs local cloud --action enroll with the approved owner input",DEVICE_RECEIPT_REQUIRED:"nvs local cloud --action receipt with the original management command",PROJECT_CONNECTION_REQUIRED:"nvs connect",DEVICE_AUTHORITY_UNCONFIRMED:"Check the current workspace membership, device proof and revocation",DEVICE_CONNECTION_REQUIRED:"nvs local connect --input <private-device-config>",DEVICE_CONNECTION_RECOVERY_REQUIRED:"Inspect the original device connection and Runtime status",DEVICE_OFFLINE:"Inspect nvs local status, then start the configured Runtime if stopped",DEVICE_BUSY:"Wait for available capacity, then recheck this device",RUNTIME_QUALIFICATION_REQUIRED:"Check the signed Runtime slot and the approved tools",DEVICE_CAPABILITY_UNCONFIRMED:"Check the configured action, tool or provider prerequisites and the current heartbeat",PROJECT_QUERY_UNAVAILABLE:"Check the selected Project connection, then retry this read"};async function qualified(kind,root,slot,validator){if(kind==="library")return true;if(kind==="preview"||kind==="final")return validator?probeTenantMediaValidation(root,slot):true;if(!await probeTenantMediaProcessing(root,slot))return false;switch(kind){case"REFERENCE_PREVIEW":return probeReferenceThumbnail(root,slot);case"LOCAL_MEDIA_INSPECT":case"LOCAL_MEDIA_PUBLISH":return probeLocalLibrary(root,slot);case"COMPOSITION_RENDER":return probeTenantComposition(root,slot);case"SPEECH_SYNTHESIZE":return probeTenantSpeech(root,slot);case"TRANSCRIBE_AUDIO":return probeTenantTranscription(root,slot);case"KEYFRAME_GENERATE":return probeTenantQwenGeneration(root,slot,"keyframe");case"VIDEO_GENERATE":return probeTenantQwenGeneration(root,slot,"video");case"SPEECH_EXTERNAL_QWEN":return probeTenantQwenGeneration(root,slot,"speech");case"TRANSCRIBE_EXTERNAL_QWEN":return probeTenantQwenGeneration(root,slot,"asr");default:return true}}async function devicePreflight(raw,env,explicitProject){const kind=DeviceDiscoveryInputSchema.shape.kind.parse(raw);const context={};const blocked=reason=>({exitCode:4,output:{semanticStatus:"BLOCKED",kind,...context,error:{code:reason,outcome:"NO_WRITE"},nextStep:nextSteps[reason]}});let caller;try{caller=await workspaceCaller(env)}catch(error){if(error.code==="ENOENT")return blocked("ACCOUNT_LOGIN_REQUIRED");if(error instanceof NativeStudioSdkError){if(error.code==="TENANT_CONNECTION_REQUIRED")return blocked("TENANT_CONNECTION_REQUIRED");if(error.code==="ACCOUNT_LOGIN_REQUIRED")return blocked("ACCOUNT_LOGIN_REQUIRED");if(error.code==="ACCOUNT_LOGOUT_OUTCOME_UNKNOWN")return blocked("ACCOUNT_REVOCATION_UNCONFIRMED");if(error.code==="PROJECT_SELECTION_REQUIRED")return blocked("PROJECT_SELECTION_REQUIRED")}throw error}if(!caller)return blocked("ACCOUNT_LOGIN_REQUIRED");const{home,tenantId,principalId,serverOrigin}=caller;const projectId=explicitProject?z.uuid().parse(explicitProject):void 0;Object.assign(context,{tenantId,projectId});const manager=await LocalInstallationManager.openExisting(home);if(!manager)return blocked("INSTALL_REQUIRED");const{active,transition}=(await manager.ledger.current()).value;if(transition)return blocked("INSTALLATION_RECOVERY_REQUIRED");if(!active)return blocked("INSTALL_REQUIRED");const slotRoot=manager.ledger.slotPath(active);await verifySlot(slotRoot,active);const records=await DesktopDeviceRecords.inspect(home,{origin:serverOrigin,tenantId,principalId});const pending=records?.pending?.command;if(records?.pending?.phase==="SENDING"&&(pending?.kind==="ENROLL"||pending?.kind==="REVOKE_DEVICE"))return blocked("DEVICE_RECEIPT_REQUIRED");if(records?.connection?.phase==="CONNECTING")return blocked("DEVICE_CONNECTION_RECOVERY_REQUIRED");const config=await manager.configuration().catch(error=>{if(error instanceof LocalClientError&&error.code==="CONFIGURATION_REQUIRED")return null;throw error});if(!config)return blocked("CONFIGURATION_REQUIRED");let transport=null;try{if(config.cloudConfigFile)transport=transportSchema.parse(JSON.parse((await read(config.cloudConfigFile,32768)).toString()))}catch(error){if(error.code==="ENOENT")return blocked("DEVICE_CONNECTION_REQUIRED");if(error instanceof SyntaxError||error instanceof z.ZodError)return blocked("DEVICE_CONNECTION_RECOVERY_REQUIRED");throw error}const endpoint=transport?new URL(transport.endpoint):null;const current=endpoint&&await callerOriginMatches(endpoint.origin,caller)&&!endpoint.username&&!endpoint.password&&transport?.tenantId===tenantId?transport:null;const deviceId=records?.device?.deviceId??current?.deviceId;if(!deviceId)return blocked("DEVICE_ENROLLMENT_REQUIRED");context.deviceId=deviceId;const configured=current?.deviceId===deviceId&&current.tenantId===tenantId;if(!configured||!current)return blocked("DEVICE_CONNECTION_REQUIRED");if(!projectId){const local=await ownerClient(config.stateDirectory);const status=await local.status(void 0,true).catch(()=>null);if(!status)return blocked("DEVICE_OFFLINE");if(status.deviceAuthority?.tenantId!==tenantId||status.deviceAuthority.deviceId!==deviceId)return blocked("DEVICE_AUTHORITY_UNCONFIRMED");if(status.state==="DRAINING")return blocked("DEVICE_BUSY");if(status.state==="RECOVERY_REQUIRED")return blocked("DEVICE_CONNECTION_RECOVERY_REQUIRED");const capabilities=status.deviceCapabilities;if(!capabilities)return blocked("DEVICE_CAPABILITY_UNCONFIRMED");if(capabilities.deviceRevision!==current.deviceRevision)return blocked("DEVICE_CONNECTION_RECOVERY_REQUIRED");if(kind==="preview"||kind==="final"){const doctor=await local.doctor().catch(()=>null);if(!doctor?.nativeExecutionReady||!doctor.executionProfiles?.includes("STUDIO_MEDIA_V2"))return blocked("RUNTIME_QUALIFICATION_REQUIRED");if(current.tenantMediaValidation&&!capabilities.tenantMediaValidation)return blocked("DEVICE_CAPABILITY_UNCONFIRMED")}if(kind!=="preview"&&kind!=="final"&&kind!=="library"){const configuredKinds=current.processorCapabilities??[];if(!current.tenantMediaProcessing||!configuredKinds.includes(kind)||!capabilities.tenantMediaProcessing||!capabilities.processorCapabilities.includes(kind))return blocked("DEVICE_CAPABILITY_UNCONFIRMED")}if(!await qualified(kind,slotRoot,active,!!current?.tenantMediaValidation))return blocked("RUNTIME_QUALIFICATION_REQUIRED");await caller.assertCurrent();return{exitCode:0,output:{semanticStatus:"SUCCESS",kind,tenantId,deviceId,availability:status.state==="EXECUTING"?"BUSY":"AVAILABLE"}}}const conn=await renderConnection(env,void 0,false,projectId).catch(error=>{if(error instanceof NativeStudioSdkError&&error.code==="AUTHORIZATION_REQUIRED")return null;throw error});if(!conn)return blocked("PROJECT_CONNECTION_REQUIRED");try{if(conn.scope.tenantId!==tenantId||conn.scope.projectId!==projectId||(caller.resource?conn.scope.resource!==caller.resource:new URL(conn.scope.resource).origin!==serverOrigin))return blocked("PROJECT_CONNECTION_REQUIRED");const page=await conn.studio.deviceRenders.list({kind,projectId,deviceId}).catch(error=>{if(error instanceof NativeStudioSdkError)return null;throw error});await caller.assertCurrent();if(!page||page.truncated)return blocked("PROJECT_QUERY_UNAVAILABLE");const candidate=page.items[0];if(!candidate)return blocked("DEVICE_AUTHORITY_UNCONFIRMED");if(!configured)return blocked("DEVICE_CONNECTION_REQUIRED");if(candidate.availability==="OFFLINE")return blocked("DEVICE_OFFLINE");if(candidate.availability==="BUSY")return blocked("DEVICE_BUSY");if(candidate.availability==="UNQUALIFIED")return blocked(await qualified(kind,slotRoot,active,!!page.validationMode)?"DEVICE_CAPABILITY_UNCONFIRMED":"RUNTIME_QUALIFICATION_REQUIRED");return{exitCode:0,output:{semanticStatus:"SUCCESS",kind,tenantId,projectId,deviceId,availability:candidate.availability,validationMode:page.validationMode}}}finally{await conn.close().catch(()=>{})}}export{devicePreflight};
@@ -1 +0,0 @@
1
- import{profileAuthorization}from"./chunk-3TOXIJ7K.js";import{readCredential}from"./chunk-QGK6G6YS.js";import{connectRemoteMcp}from"./chunk-GLAF74UU.js";import"./chunk-2UYKJ6YN.js";import{WorkspaceDeviceListInputSchema}from"./chunk-APNZQZFB.js";import{defaultConnection,tenantConnection}from"./chunk-27KI24GK.js";import"./chunk-7I7ARCY7.js";import"./chunk-DLW42PJ6.js";import"./chunk-WTJVS2VS.js";import"./chunk-KOCUZ3AE.js";import"./chunk-TT7IA5HB.js";var query=WorkspaceDeviceListInputSchema.omit({tenantId:true});async function deviceInventoryCommand(args,env){const flags=new Map;for(let i=0;i<args.length;i+=2){const key=args[i],value=args[i+1];if(!key||!["--device","--after","--limit","--profile","--mcp-url","--token-file","--token-env"].includes(key)||!value||value.startsWith("--")||flags.has(key))throw Error();flags.set(key,value)}const input=query.parse({...flags.has("--device")&&{deviceId:flags.get("--device")},...flags.has("--after")&&{after:flags.get("--after")},...flags.has("--limit")&&{limit:Number(flags.get("--limit"))}});await defaultConnection(flags,env,true);const profile=flags.get("--profile");if(profile&&["--mcp-url","--token-file","--token-env"].some(key=>flags.has(key)))throw Error();const token=profile?await profileAuthorization(profile):null;const resource=token?.resource??flags.get("--mcp-url");if(!resource)throw Error();const scope=tenantConnection(resource);const authorization=token?.authorization??await readCredential(flags,env);const connection=await connectRemoteMcp(scope.resource,authorization,scope.tenantId);try{const output=await connection.studio.call("workspace.devices.list",{...input,tenantId:scope.tenantId});return{exitCode:0,output}}finally{await connection.close().catch(()=>{})}}export{deviceInventoryCommand};
@@ -1 +0,0 @@
1
- import{callerRenderConnection}from"./chunk-OSO6KRE2.js";import"./chunk-UYKCN5DU.js";import"./chunk-3TOXIJ7K.js";import"./chunk-QGK6G6YS.js";import"./chunk-GLAF74UU.js";import"./chunk-2UYKJ6YN.js";import{DeviceDiscoveryInputSchema}from"./chunk-APNZQZFB.js";import"./chunk-27KI24GK.js";import"./chunk-7I7ARCY7.js";import"./chunk-DLW42PJ6.js";import"./chunk-WTJVS2VS.js";import"./chunk-KOCUZ3AE.js";import"./chunk-TT7IA5HB.js";var query=DeviceDiscoveryInputSchema.pick({kind:true,deviceId:true});async function devicesCommand(argv,env,stdin=process.stdin){const[action,...args]=argv;if(action==="inventory")return(await import("./devices-inventory-BZF53UAU.js")).deviceInventoryCommand(args,env);if(action!=="list")return(await import("./device-management-TLRUMZL5.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};
@@ -1 +0,0 @@
1
- import{LocalClientError,digestPrivateFile,directory,entries,fail,optional,read,sha256,sha512,verifyBackup,write}from"./chunk-DLW42PJ6.js";export{LocalClientError,digestPrivateFile,directory,entries,fail,optional,read,sha256,sha512,verifyBackup,write};
@@ -1 +0,0 @@
1
- import{ComponentReceipts,componentHome,initializeComponent,observeComponent,observeLoginService,withComponentLock}from"./chunk-LBK42NHW.js";import{runLoginService}from"./chunk-D74NHT4I.js";import"./chunk-QE7O57PQ.js";import"./chunk-4PAVWOPA.js";import"./chunk-4M2SOMSN.js";import"./chunk-L3QA7FLZ.js";import"./chunk-MLZ3ZPGU.js";import{InstalledToolPathsSchema,LocalInstallationManager,captureInstalledTools}from"./chunk-ELUJ44BO.js";import"./chunk-AFNJRZLJ.js";import"./chunk-IYDHDLTR.js";import"./chunk-6EZX2TRX.js";import"./chunk-APNZQZFB.js";import"./chunk-7I7ARCY7.js";import{LocalClientError,fail}from"./chunk-DLW42PJ6.js";import"./chunk-WTJVS2VS.js";import"./chunk-KOCUZ3AE.js";import"./chunk-TT7IA5HB.js";var ok=output=>({exitCode:0,output});var acknowledged=output=>({exitCode:output.phase==="COMPLETE"?0:2,output});async function serviceFingerprint(home){const service=await observeLoginService(home);if(!("fingerprint"in service)||!service.fingerprint||!("supervision"in service)||service.supervision!=="EXPLICIT_RECOVERY")fail("COMPONENT_SERVICE_UNCONFIRMED");return service.fingerprint}async function applyComponentCommand(manager,command,before){const home=manager.ledger.root;switch(command.action){case"apply":case"rollback":{if(command.action==="rollback"){const plan=await manager.plan(command.planId),version=plan.release.descriptor.version;if(version===before.installedVersion||!await manager.ledger.hadCompletedVersion(version))fail("COMPONENT_ROLLBACK_VERSION_UNAVAILABLE")}await manager.apply(command.planId,command.fingerprint);return"COMPONENT_VERSION_ACTIVATED"}case"reconcile-install":await manager.reconcile(command.planId,command.fingerprint);return"COMPONENT_INSTALLATION_RECONCILED";case"service-enable":await runLoginService("service-enable",home,command.fingerprint,"EXPLICIT_RECOVERY");return"COMPONENT_SERVICE_REGISTERED";case"start":if(before.loginService==="REGISTERED")await runLoginService("service-start",home,await serviceFingerprint(home));else await manager.start();return"COMPONENT_STARTED";case"stop":if(before.loginService!=="NONE")await runLoginService("service-disable",home,await serviceFingerprint(home));if((await manager.status()).running)await manager.stop();return"COMPONENT_STOPPED";case"recover":if(before.readiness.state==="READY")return"COMPONENT_HEALTHY";if(before.loginService==="REGISTERED")await runLoginService("service-restart",home,await serviceFingerprint(home));else{if(before.liveness.state==="ALIVE")await manager.stop();await manager.start()}return"COMPONENT_RECOVERED"}}function outcomeObserved(command,current){switch(command.action){case"stop":return current.liveness.state==="STOPPED"&&current.loginService==="NONE";case"service-enable":return current.loginService==="REGISTERED";case"reconcile-install":return true;default:return current.readiness.state==="READY"}}function reason(error){return error instanceof LocalClientError&&/^[A-Z][A-Z0-9_]{0,79}$/.test(error.code)?error.code:"COMPONENT_ACTION_UNAVAILABLE"}async function runHostComponent(parent,{scope,call}){const target=await componentHome(parent,scope,call.action==="initialize"),home=target.home,receipts=new ComponentReceipts(home);if(call.action==="initialize")return withComponentLock(home,async()=>{const manager2=await initializeComponent(home,scope,call.channel);return ok(await observeComponent(home,scope,manager2,receipts))});if(call.action==="receipt")return ok({receipt:target.claimed?await receipts.find(call.requestId):null});const manager=target.claimed?await LocalInstallationManager.openExisting(home):null;const observe=()=>observeComponent(home,scope,manager,receipts);if(call.action==="status")return ok(await observe());if(call.action==="preflight")return(await import("./component-preflight-WECLCZLF.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};
@@ -1 +0,0 @@
1
- import{HostComponentRequestSchema}from"./chunk-QE7O57PQ.js";import{HostEnrollmentRequestSchema}from"./chunk-K35CWLDH.js";import"./chunk-4M2SOMSN.js";import"./chunk-L3QA7FLZ.js";import"./chunk-ROGOASYF.js";import"./chunk-HBDPYWMI.js";import"./chunk-MLZ3ZPGU.js";import"./chunk-ELUJ44BO.js";import"./chunk-AFNJRZLJ.js";import"./chunk-IYDHDLTR.js";import"./chunk-6EZX2TRX.js";import"./chunk-APNZQZFB.js";import"./chunk-DLW42PJ6.js";import"./chunk-WTJVS2VS.js";import"./chunk-TT7IA5HB.js";import{z}from"zod";var protocol="NVS_EXTERNAL_HOST_V1";var requests={component:HostComponentRequestSchema,enrollment:HostEnrollmentRequestSchema};function hostOverview(deviceActions){return{exitCode:0,output:{protocol,agentRuntime:"EXTERNAL",commands:["host component --input <private-json|-> [--home <private-parent-home>]","host enrollment --input <private-json|-> [--home <component-home>]","host device --input <json|-> [--home <private-client-home>]"],actions:[...deviceActions],help:["host component help [<action>]","host enrollment help [<action>]"],guidance:"Use workspace_caller and workspace_status on your tenant MCP for component scope. Use host component help preflight for the read-only host check for library, preview or final. Prepare enrollment with authority OAUTH_AGENT and send its invoke on the same MCP. Pass the ticket by private input and read the original lookup after an interrupted reply."}}}function hostActionHelp(command,action){const request=requests[command],options=request.shape.call.options;const actions=options.map(option=>option.shape.action.value);const selected=action&&options.find(option=>option.shape.action.value===action);const invalid=action!==void 0&&!selected;return{exitCode:invalid?2:0,output:{protocol,command:"host "+command,actions,help:"host "+command+" help <action>",...invalid&&{semanticStatus:"INVALID_INPUT",error:{code:"INVALID_INPUT",outcome:"NO_WRITE"}},...selected&&{action,inputSchema:z.toJSONSchema(z.strictObject({scope:request.shape.scope,call:selected}),{io:"input"})}}}}export{hostActionHelp,hostOverview};
@@ -1 +0,0 @@
1
- import{HostEnrollmentRequestSchema,runHostEnrollment}from"./chunk-K35CWLDH.js";import{runDesktopDeviceRequest}from"./chunk-ROGOASYF.js";import"./chunk-HBDPYWMI.js";import"./chunk-MLZ3ZPGU.js";import"./chunk-ELUJ44BO.js";import"./chunk-AFNJRZLJ.js";import{DesktopDeviceRequestSchema}from"./chunk-IYDHDLTR.js";import"./chunk-6EZX2TRX.js";import{readInput}from"./chunk-QGK6G6YS.js";import"./chunk-APNZQZFB.js";import{LocalClientError}from"./chunk-DLW42PJ6.js";import"./chunk-WTJVS2VS.js";import"./chunk-TT7IA5HB.js";import{homedir}from"node:os";import{join,resolve}from"node:path";var actions=new Set(["inspect","enroll","revoke","dispatch","record","refused","prove","connect","connection-recover","media-validation-capability","media-processing-capability"]);var helpFlags=["help","--help"];async function runHostCli(argv,stdin=process.stdin){let entered=false;let mutation=false;try{if(!argv.length||argv.length===1&&helpFlags.includes(argv[0]))return(await import("./host-help-7BGYR4ET.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-7BGYR4ET.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-KXK7WIUI.js");const request2=HostComponentRequestSchema.parse(raw);entered=true;mutation=!["status","preflight","receipt","service-plan"].includes(request2.call.action);return await(await import("./host-component-Q5IHRHRI.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};
@@ -1 +0,0 @@
1
- import{profileHttpOrigin}from"./chunk-7P2NA6TH.js";import"./chunk-27KI24GK.js";import"./chunk-7I7ARCY7.js";import"./chunk-DLW42PJ6.js";import"./chunk-WTJVS2VS.js";import"./chunk-KOCUZ3AE.js";import"./chunk-TT7IA5HB.js";export{profileHttpOrigin};
@@ -1 +0,0 @@
1
- import{localCaller}from"./chunk-NG4BDFEY.js";import{renderConnection}from"./chunk-OSO6KRE2.js";import"./chunk-UYKCN5DU.js";import{DesktopLibraryImportSeedSchema,prepareDesktopLibraryImport,runDesktopLibraryImport,runDesktopLibraryRequest}from"./chunk-L3QA7FLZ.js";import"./chunk-MLZ3ZPGU.js";import"./chunk-ELUJ44BO.js";import{DesktopDeviceRecords}from"./chunk-AFNJRZLJ.js";import"./chunk-IYDHDLTR.js";import"./chunk-6EZX2TRX.js";import"./chunk-3TOXIJ7K.js";import{readInput}from"./chunk-QGK6G6YS.js";import"./chunk-GLAF74UU.js";import"./chunk-2UYKJ6YN.js";import{LocalDeviceViewSchema,LocalManagementCommandSchema}from"./chunk-APNZQZFB.js";import"./chunk-7P2NA6TH.js";import"./chunk-27KI24GK.js";import"./chunk-7I7ARCY7.js";import{fail,sha256}from"./chunk-DLW42PJ6.js";import"./chunk-WTJVS2VS.js";import"./chunk-KOCUZ3AE.js";import{NativeStudioSdkError}from"./chunk-TT7IA5HB.js";import{homedir}from"node:os";import{join,resolve,basename}from"node:path";async function libraryImportContext(home,raw,enrollment){const caller=await localCaller({...process.env,NATIVESTUDIO_CLIENT_HOME:home},typeof raw.projectId==="string"?raw.projectId:void 0);if(!caller){if(!["tenantId","projectId","deviceId","ownerKey"].every(key=>raw[key]))fail("ACCOUNT_LOGIN_REQUIRED");return{}}const{serverOrigin,tenantId,principalId,projectId}=caller;const ownerKey=sha256(JSON.stringify([serverOrigin,tenantId,principalId]));const denied=()=>{throw new NativeStudioSdkError("FORBIDDEN","BLOCKED","NO_WRITE")};if(raw.tenantId!==void 0&&raw.tenantId!==tenantId||raw.projectId!==void 0&&raw.projectId!==projectId||raw.ownerKey!==void 0&&raw.ownerKey!==ownerKey)denied();const record=await DesktopDeviceRecords.inspect(home,{origin:serverOrigin,tenantId,principalId});if(record?.device&&(record.device.enrolledByPrincipalId!==principalId||record.device.tenantId!==tenantId))denied();if(record?.pending?.phase==="SENDING")fail("DEVICE_RECEIPT_REQUIRED");let deviceId=record?.device?.deviceId;if(!deviceId&&enrollment!==void 0){const command=LocalManagementCommandSchema.parse(enrollment);if(command.kind!=="ENROLL"||command.input.tenantId!==tenantId)denied();const env={...process.env,NATIVESTUDIO_CLIENT_HOME:home};const c=await renderConnection(env,void 0,false,projectId);try{if(c.scope.profile!==caller.profile||c.scope.resource!==caller.resource)denied();const receipt=await c.studio.call("device.management-receipt",{command});if(!receipt.result)fail("DEVICE_RECEIPT_REQUIRED");const device=LocalDeviceViewSchema.parse(receipt.result);if(device.enrolledByPrincipalId!==principalId||device.tenantId!==tenantId)denied();deviceId=device.deviceId}finally{await c.close().catch(()=>{})}}if(!deviceId)fail("DEVICE_SETUP_REQUIRED");if(raw.deviceId!==void 0&&raw.deviceId!==deviceId)denied();await caller.assertCurrent();return{tenantId,projectId,deviceId,ownerKey,assertCurrent:caller.assertCurrent}}async function runLocalLibrary(argv,stdin){const[action,...args]=argv,flags=new Map;for(let i=0;i<args.length;i+=2){const name=args[i],value=args[i+1];if(!name||!["--home","--input","--file","--enrollment"].includes(name)||!value||value.startsWith("--")||flags.has(name))throw Error();flags.set(name,value)}if(!action||!["import","list","get","read","access","sync","resume-access","import-receipt","usage"].includes(action)||!flags.has("--input")||flags.get("--input")==="-"&&flags.get("--enrollment")==="-"||action!=="import"&&(flags.has("--file")||flags.has("--enrollment")))throw Error();const home=resolve(flags.get("--home")??process.env.NATIVESTUDIO_CLIENT_HOME??join(homedir(),".nativestudio/client"));const raw=await readInput(flags.get("--input"),stdin);if(action!=="import")return{exitCode:0,output:await runDesktopLibraryRequest(home,{operation:"library",call:{...raw,action}})};const file=flags.get("--file");if(!file)throw Error();const enrollment=flags.has("--enrollment")?await readInput(flags.get("--enrollment"),stdin):void 0;const{assertCurrent,...defaults}=await libraryImportContext(home,raw,enrollment);const seed=DesktopLibraryImportSeedSchema.parse({...defaults,title:basename(file),contentType:"application/octet-stream",...raw});const request=await prepareDesktopLibraryImport({operation:"library-import-prepare",file:resolve(file),seed});await assertCurrent?.();return{exitCode:0,output:await runDesktopLibraryImport(home,request)}}export{runLocalLibrary};
@@ -1 +0,0 @@
1
- import{loginCommand,runLoginService}from"./chunk-D74NHT4I.js";import{prepareInstalledCpuSpeech}from"./chunk-FVY3PLG7.js";import{connectDevice,generateDeviceKey}from"./chunk-HBDPYWMI.js";import{LocalInstallationManager,captureInstalledTools,ownerClient}from"./chunk-ELUJ44BO.js";import{LocalAgentGrantSchema,NativeStudioLocalDeviceClient,localAgentMediaProposal,localAgentMediaSnapshot,localAgentSnapshotFromContext}from"./chunk-6EZX2TRX.js";import{readCredential,readInput}from"./chunk-QGK6G6YS.js";import{localCliVersion}from"./chunk-2UYKJ6YN.js";import{EnrollLocalDeviceSchema,LocalManagementCommandSchema,NativeStudioAgentClient,RevokeLocalDeviceSchema,StartLocalFinalRenderSchema,StartLocalPreviewSchema,canonicalLocalJson}from"./chunk-APNZQZFB.js";import"./chunk-7I7ARCY7.js";import{LocalClientError}from"./chunk-DLW42PJ6.js";import"./chunk-WTJVS2VS.js";import"./chunk-KOCUZ3AE.js";import{NativeStudioSdkError}from"./chunk-TT7IA5HB.js";import{homedir as homedir2}from"node:os";import{join as join2,resolve as resolve2}from"node:path";function preparationGuidance(code){const steps={DEPENDENCY_CHANNEL_REQUIRED:["Read workspace_caller.hostReleases (CLI: call workspace.caller); use its exact configured URL, not an inferred path.","Configure the advertised catalogueUrl/publicKey through local configure; never accept an unsigned catalogue or invent a trust key."],MANAGED_TOOLS_UNAVAILABLE:["This exact signed release has no qualified managed media executables. Install the required tools using the host's authorized package manager or official vendor.","Use local tools-prepare --version <resolved-runtime-version> --input <private-json> with mode INSTALLED and absolute ffmpeg/ffprobe paths. Missing fonts/browser remain separate capabilities."],RELEASE_NOT_PUBLISHED:["Ask the release operator to publish matching exact-version dependencies. Preserve this CLI/Runtime identity; do not substitute another version's bytes."],RELEASE_METADATA_INVALID:["Reject malformed release metadata; ask the operator to check the exact signed catalogue URL. Do not treat a discovery page as a catalogue."],RELEASE_ACCESS_DENIED:["The public download edge denied access. Inspect its safe status; for Cloudflare 1010, identify your actual application with a descriptive User-Agent. Do not disable TLS or copy a browser session."],RELEASE_TIMEOUT:["The read deadline ended. An unknown installation apply must be reconciled from its original plan, never replayed blindly."],RELEASE_SIGNATURE_INVALID:["Reject these bytes. Verify the configured operator URL/public key; do not rotate trust to make verification pass."],RELEASE_EXPIRED:["Ask the operator to renew the approved inventory; never ignore expiry or alter the host clock."],BUNDLED_COMPONENT_RELEASE_MISMATCH:["The catalogue does not match the code/resources inside this CLI. Keep the original installation plan; ask the operator for its matching release."],LOGIN_SERVICE_RUNTIME_UPDATE_REQUIRED:["Activate a Runtime with login startup support through the existing exact-version installation plan."],LOGIN_SERVICE_REPLACE_REQUIRED:["Read local service-status and disable the existing registration using its original fingerprint. Then approve the current service plan."],LOGIN_SERVICE_OS_UNCONFIRMED:["Read local service-status and check the current user's native service manager. Keep the original approval fingerprint for reconciliation."],LOGIN_SERVICE_DISABLE_PENDING:["Read local service-status and complete service-disable using the original fingerprint."]};return steps[code]}import{homedir}from"node:os";import{join,resolve}from"node:path";import{createHash}from"node:crypto";async function runLocalAgentCli(argv,stdin){try{const[command,...rest]=argv,flags=new Map;for(let n=0;n<rest.length;n+=2){const k=rest[n],v=rest[n+1];if(!k||!["--home","--input","--approve","--id","--revision","--evidence","--origin","--token-file"].includes(k)||!v||v.startsWith("--")||flags.has(k))throw Error();flags.set(k,v)}const need=k=>{const v=flags.get(k);if(!v)throw Error();return v};if(command==="agent-grant-plan"){const grant=LocalAgentGrantSchema.parse(await readInput(need("--input"),stdin));const disclosures=["review metadata",...grant.imageDisclosureApproved?["original image pixels"]:[],...grant.mediaDisclosureApproved?["normalized image pixels or sampled video frames and technical audio statistics"]:[]];return{exitCode:0,output:{grant,fingerprint:createHash("sha256").update(canonicalLocalJson(grant)).digest("hex"),note:`Approving this fingerprint permits remote OpenAI inference for these Projects until expiry and allows disclosure of ${disclosures.join(", ")}. Preview does not invoke a model.`}}}const evidence=flags.get("--evidence");if(evidence&&!["IMAGE_PIXELS","METADATA_ONLY","MEDIA"].includes(evidence))throw Error();const manager=await LocalInstallationManager.open(resolve(flags.get("--home")??join(homedir(),".nativestudio","client")));const client=await ownerClient((await manager.configuration()).stateDirectory);const studioFor=tenantId=>new NativeStudioAgentClient({baseUrl:need("--origin"),tenantId,authorization:()=>readCredential(flags,process.env)});let output;switch(command){case"agent-grant":output=await client.grantAgent(await readInput(need("--input"),stdin),need("--approve"));break;case"agent-revoke":output=await client.revokeAgent(need("--approve"));break;case"agent-probe":output=await client.probeAgent();break;case"review-prepare":{const context=await readInput(need("--input"),stdin);output=await client.prepareAgentReview(evidence==="MEDIA"?localAgentMediaSnapshot(context):localAgentSnapshotFromContext(context,evidence==="IMAGE_PIXELS"));break}case"review-image-fetch":{const view=await client.inspectAgentReview(need("--id")),snapshot=view.plan.snapshot;if(!snapshot.image||snapshot.basis.target.kind!=="IMAGE")throw Error();const studio=studioFor(snapshot.basis.scope.tenantId);const media=await studio.keyframeMedia({productionId:snapshot.basis.scope.productionId,generationId:snapshot.basis.target.generationId},{checksumSha256:snapshot.media.checksumSha256,byteSize:snapshot.image.byteSize});if(media.contentType!==snapshot.image.contentType)throw Error();output=await client.stageAgentImage(view.plan.id,media.bytes);break}case"review-media-fetch":{const view=await client.inspectAgentReview(need("--id"));const{basis,evidence:expected,media}=view.plan.snapshot;if(!expected)throw Error();if(view.evidenceReceipt){output=view;break}if(view.phase!=="PREPARED")throw Error();const source=await studioFor(basis.scope.tenantId).immutableMedia({projectId:basis.scope.projectId,representationId:media.representationId,checksumSha256:media.checksumSha256,byteSize:expected.byteSize});output=await client.stageAgentImage(view.plan.id,source.bytes);break}case"review-start":output=await client.startAgentReview(need("--id"),Number(need("--revision")),need("--approve"));break;case"review-inspect":output=await client.inspectAgentReview(need("--id"));break;case"review-proposal":output=localAgentMediaProposal(await client.inspectAgentReview(need("--id")));break;default:throw Error()}return{exitCode:0,output}}catch(e){const known=e instanceof NativeStudioSdkError;return{exitCode:2,output:{semanticStatus:"BLOCKED",error:{code:known?e.code:"INVALID_INPUT",outcome:known?e.outcome:"NO_WRITE"}}}}}async function runLocalCli(argv,stdin=process.stdin){let mutation=false;try{const[command,...rest]=argv,options=new Map;if(command==="library"){mutation=["import","access","resume-access"].includes(rest[0]??"");return await(await import("./library-main-ATRFEAVN.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-C7FFUXI2.js")).devicePreflight(options.get("--kind"),{...process.env,...options.has("--home")&&{NATIVESTUDIO_CLIENT_HOME:resolve2(options.get("--home"))}},options.get("--project"))}if(command?.startsWith("agent-")||command?.startsWith("review-"))return runLocalAgentCli(argv,stdin);const allowed=["--home","--input","--version","--plan","--approve","--output","--origin","--token-file","--action"];for(let i=0;i<rest.length;i+=2){const k=rest[i],v=rest[i+1];if(!k||!allowed.includes(k)||!v||v.startsWith("--")||options.has(k))throw Error();options.set(k,v)}if(command==="help"||!command)return{exitCode:0,output:{namespace:"nvs local",commands:["configure --input <private-json>","keygen --output <new-private-device-key>","cloud --action enroll|revoke-device|preview|final|receipt --origin <cloud-origin> --token-file <member-token> --input <json>","connect --input <private-device-config>","version","install|update-prepare --version <exact|latest> \u2014 uses this CLI's bundled code; update CLI first for newer code; latest resolves once into an exact saved plan","speech-prepare --input <json with optional voiceIds> \u2014 prepare pinned CPU speech resources and return the original tools update plan","tools-prepare --version <exact|latest> --input <private-json with mode MANAGED or INSTALLED, exact ffmpeg/ffprobe paths, optional compositionBrowser and captionAssetsDirectory>","update-check","update-reject --version <exact>","update-apply --plan <uuid> --approve <fingerprint>","update-reconcile --plan <uuid> --approve <fingerprint>","start","status","service-plan|service-status [--home <private-client-home>] \u2014 inspect optional user-login startup without changing it","service-enable|service-start|service-disable --approve <service-fingerprint> [--home <private-client-home>] \u2014 register, start or remove this installation's user-login service","device-preflight --kind preview|final|<processor-kind> [--project <uuid>] [--home <private-client-home>] \u2014 read current setup and action qualification","doctor","stop","grant --input <scopes-expiry-json> --output <new-private-connector>","mcp [--connector <private-file>] [--with-library]","library import|list|get|read|access|sync|resume-access|import-receipt|usage --input <json|-> [--file <exact-media>] [--home <client-home>] \u2014 private Owner library; import never uploads","agent-grant-plan|agent-probe|agent-grant|agent-revoke \u2014 installed Codex CLI with explicitly authorized remote OpenAI inference","review-prepare --input <private-context> [--evidence METADATA_ONLY|IMAGE_PIXELS|MEDIA]","review-media-fetch --id <draft> --origin <cloud-origin> --token-file <member-token> \u2014 read exact stored bytes for a MEDIA draft","review-image-fetch|review-inspect|review-proposal \u2014 use --id <draft>","review-start --id <draft> --revision <current> --approve <plan-fingerprint>"],note:"Release check and update planning only inspect metadata. speech-prepare explicitly fetches optional CPU resources. Apply uses the exact saved fingerprint. MCP disconnect does not stop Runtime."}};if(command==="version")return{exitCode:0,output:await localCliVersion()};const required=key=>{const v=options.get(key);if(!v)throw Error();return v};if(command==="keygen")return{exitCode:0,output:await generateDeviceKey(resolve2(required("--output")))};if(command==="cloud"){const input=await readInput(required("--input"),stdin);const action=required("--action");const tenantId=action==="receipt"?LocalManagementCommandSchema.parse(input).input.tenantId:input.tenantId;if(typeof tenantId!=="string")throw Error();const client=new NativeStudioLocalDeviceClient({baseUrl:required("--origin"),tenantId,authorization:()=>readCredential(new Map([["--token-file",required("--token-file")]]),process.env)});const output2=action==="enroll"?await client.enroll(EnrollLocalDeviceSchema.parse(input)):action==="revoke-device"?await client.revokeDevice(RevokeLocalDeviceSchema.parse(input)):action==="preview"?await client.startPreview(StartLocalPreviewSchema.parse(input)):action==="final"?await client.startFinal(StartLocalFinalRenderSchema.parse(input)):action==="receipt"?await client.managementReceipt(LocalManagementCommandSchema.parse(input)):void 0;if(!output2)throw Error();return{exitCode:0,output:output2}}const home=resolve2(options.get("--home")??process.env.NATIVESTUDIO_CLIENT_HOME??join2(homedir2(),".nativestudio","client"));if(loginCommand(command)){mutation=["service-enable","service-start","service-disable"].includes(command);if([...options.keys()].some(key=>key!=="--home"&&(!mutation||key!=="--approve")))throw Error();return{exitCode:0,output:await runLoginService(command,home,options.get("--approve"))}}const manager=await LocalInstallationManager.open(home);let output;mutation=["configure","speech-prepare","connect","start","stop","grant","update-apply","update-reconcile","update-reject"].includes(command??"");switch(command){case"connect":output=await connectDevice(manager,await readInput(required("--input"),stdin));break;case"configure":output=await manager.configure(await readInput(required("--input"),stdin));break;case"status":output=await manager.status();break;case"update-reject":output=await manager.reject(required("--version"));break;case"update-check":output=await manager.check();break;case"install":case"update-prepare":output=await manager.prepareBundled(required("--version"));break;case"speech-prepare":output=await prepareInstalledCpuSpeech(manager,await readInput(required("--input"),stdin));break;case"tools-prepare":{const raw=await readInput(required("--input"),stdin);const choice=raw.mode==="INSTALLED"?await captureInstalledTools(raw):raw;output=await manager.prepareBundled(required("--version"),choice)}break;case"update-apply":output=await manager.apply(required("--plan"),required("--approve"));break;case"update-reconcile":output=await manager.reconcile(required("--plan"),required("--approve"));break;case"start":output=await manager.start();break;case"stop":output=await manager.stop();break;case"doctor":output=await(await ownerClient((await manager.configuration()).stateDirectory)).doctor();break;case"grant":output=await manager.grant(await readInput(required("--input"),stdin),resolve2(required("--output")));break;default:throw Error()}return{exitCode:0,output}}catch(e){const known=e instanceof LocalClientError?e.code:e instanceof NativeStudioSdkError?e.code:"INVALID_INPUT";return{exitCode:2,output:{semanticStatus:"BLOCKED",...preparationGuidance(known)?{nextSteps:preparationGuidance(known)}:{},error:{code:known,outcome:e instanceof NativeStudioSdkError?e.outcome:mutation&&!["USER_APPROVAL_REQUIRED","PLAN_CHANGED","REVISION_CONFLICT","INSTALL_REQUIRED","CONFIGURATION_REQUIRED","DEVICE_CONNECTION_REQUIRED","LOGIN_SERVICE_PLAN_CHANGED","LOGIN_SERVICE_REPLACE_REQUIRED","LOGIN_SERVICE_DISABLE_PENDING","LOGIN_SERVICE_RUNTIME_UPDATE_REQUIRED","LOGIN_SERVICE_PLATFORM_UNSUPPORTED","LOGIN_SERVICE_USER_REQUIRED"].includes(known)?"UNKNOWN":"NO_WRITE"}}}}}export{runLocalCli};
@@ -1 +0,0 @@
1
- import{workspaceCaller}from"./chunk-NG4BDFEY.js";import{StdioLines}from"./chunk-JFC6ZIGA.js";import"./chunk-OSO6KRE2.js";import"./chunk-UYKCN5DU.js";import{LocalMcpTools,localTools}from"./chunk-QK4XPVKT.js";import{desktopDeviceConnector}from"./chunk-AFNJRZLJ.js";import"./chunk-IYDHDLTR.js";import{LocalMcpFailureSchema}from"./chunk-6EZX2TRX.js";import"./chunk-3TOXIJ7K.js";import"./chunk-QGK6G6YS.js";import"./chunk-GLAF74UU.js";import{localCliVersion}from"./chunk-2UYKJ6YN.js";import"./chunk-APNZQZFB.js";import"./chunk-7P2NA6TH.js";import"./chunk-27KI24GK.js";import"./chunk-7I7ARCY7.js";import"./chunk-DLW42PJ6.js";import"./chunk-WTJVS2VS.js";import"./chunk-KOCUZ3AE.js";import{NativeStudioSdkError}from"./chunk-TT7IA5HB.js";import{z}from"zod";import{homedir}from"node:os";import{join,resolve}from"node:path";import{deserializeMessage,SUPPORTED_PROTOCOL_VERSIONS,LATEST_PROTOCOL_VERSION,serializeMessage,isJSONRPCRequest,isJSONRPCNotification}from"@modelcontextprotocol/client";async function selectedConnector(home,env){const caller=await workspaceCaller(env);if(!caller)throw new NativeStudioSdkError("AUTHORIZATION_REQUIRED","BLOCKED","NO_WRITE");return desktopDeviceConnector(home,{origin:caller.serverOrigin,tenantId:caller.tenantId,principalId:caller.principalId})}async function serveLocalMcp(tools,input,output){const identity=await localCliVersion();const visible=[...tools.names??Object.keys(localTools).filter(name=>!name.startsWith("local_library_"))].sort(),pending=new Map;let initialized=false,closed=false;const frames=new StdioLines(65536);let finish;const ended=new Promise(resolve2=>{finish=resolve2});const send=message=>{if(closed)return;if(output.writableLength>512*1024){close(1);return}output.write(serializeMessage(message))};const error=(id,code,message)=>send({jsonrpc:"2.0",id,error:{code,message}});async function dispatch(r){if(pending.has(r.id)||pending.size>=8){error(r.id,-32e3,"Local request capacity unavailable");return}const abort=new AbortController;const timer=setTimeout(()=>abort.abort(),3e4);pending.set(r.id,abort);try{let result;if(r.method==="initialize"){if(initialized)throw Error();const v=r.params?.protocolVersion;if(typeof v!=="string")throw Error();const protocol=SUPPORTED_PROTOCOL_VERSIONS.includes(v)?v:LATEST_PROTOCOL_VERSION;initialized=true;result={protocolVersion:protocol,serverInfo:{name:"native-studio-local",version:identity.version},capabilities:{tools:{}},instructions:"Use local_navigate and local_capability_describe for scoped guidance. The standard tool list stays stable. Local tools inspect scoped mechanics. Use nvs mcp for workspace, Project and render business actions. Cloud owns native admission. Updates require a human CLI approval; MCP cannot stop or replace Runtime."}}else if(!initialized)throw Error();else if(r.method==="ping")result={};else if(r.method==="tools/list"){if(r.params?.cursor!==void 0)throw Error();result={tools:visible.map(name=>tools.schema(name))}}else if(r.method==="tools/call"){const name=r.params?.name;if(typeof name!=="string"||!visible.includes(name))throw Error();let data;try{data=await tools.call(name,r.params?.arguments??{},abort.signal)}catch(cause){const code=cause instanceof z.ZodError?"INVALID_INPUT":cause instanceof NativeStudioSdkError&&["AUTHORIZATION_REQUIRED","FORBIDDEN","LOCAL_RUNTIME_UNAVAILABLE"].includes(cause.code)?cause.code:"LOCAL_CAPABILITY_UNAVAILABLE";const failure=LocalMcpFailureSchema.parse({semanticStatus:code==="INVALID_INPUT"?"INVALID_INPUT":"BLOCKED",error:{code,outcome:"NO_WRITE"},nextActions:[{surface:"CLI",operation:"local.status",availability:"AVAILABLE",reason:code==="FORBIDDEN"||code==="AUTHORIZATION_REQUIRED"?"AUTHORIZATION_REQUIRED":"UNAVAILABLE"}]});send({jsonrpc:"2.0",id:r.id,result:{isError:true,content:[{type:"text",text:JSON.stringify(failure)}],structuredContent:failure}});return}result={content:[{type:"text",text:JSON.stringify(data)}],structuredContent:data}}else{error(r.id,-32601,"Local method unavailable");return}send({jsonrpc:"2.0",id:r.id,result})}catch{error(r.id,-32602,"Local capability unavailable or authorization required")}finally{clearTimeout(timer);pending.delete(r.id)}}function onData(b){try{frames.push(b,line=>{const message=deserializeMessage(line.toString());if(isJSONRPCRequest(message))void dispatch(message);else if(isJSONRPCNotification(message)){if(message.method==="notifications/cancelled"){const id=message.params?.requestId;if(typeof id==="string"||typeof id==="number")pending.get(id)?.abort()}}else throw Error();return!closed})}catch{close(1)}}function close(code=0){if(closed)return;closed=true;for(const abort of pending.values())abort.abort();input.off("data",onData);finish(code)}input.on("data",onData);input.once("end",()=>close(frames.incomplete?1:0));input.once("error",()=>close(1));output.once("error",()=>close(1));return{closed:ended,close:async()=>close()}}async function runLocalMcp(argv){try{const flags=new Map;const library=argv.includes("--with-library");if(argv.filter(k=>k==="--with-library").length>1)throw Error();argv=argv.filter(k=>k!=="--with-library");for(let i=0;i<argv.length;i+=2){const k=argv[i],v=argv[i+1];if(!k||!["--connector","--home"].includes(k)||!v||flags.has(k))throw Error();flags.set(k,v)}const home=resolve(flags.get("--home")??process.env.NATIVESTUDIO_CLIENT_HOME??join(homedir(),".nativestudio","client"));const env={...process.env,NATIVESTUDIO_CLIENT_HOME:home};const connector=flags.get("--connector")??await selectedConnector(home,env);const tools=await LocalMcpTools.open(resolve(connector),home,library);const service=await serveLocalMcp(tools,process.stdin,process.stdout);return await service.closed}catch{process.stderr.write("Local MCP needs a current device connector. Use nvs mcp for workspace, Project and render business tools.\n");return 2}}export{runLocalMcp,serveLocalMcp};