@nativestudio/cli 0.3.0-rc.21 → 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 (200) 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-MZWEFYHE.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-7IVAYDU3.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-ZYXHPTT2.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-76E5R3OC.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-ZMJYBUS3.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-X5PBZTKX.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-LTNJ45JP.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-5Y7J2OYL.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 +44 -0
  102. package/dist/_types/contracts/interface/production-snapshot.d.ts +39 -0
  103. package/dist/_types/contracts/interface/query.d.ts +38 -0
  104. package/dist/_types/contracts/local-execution/backup-retirement.d.ts +162 -0
  105. package/dist/_types/contracts/local-execution/claim-resolution.d.ts +1470 -0
  106. package/dist/_types/contracts/local-execution/components.d.ts +1 -1
  107. package/dist/_types/contracts/local-execution/cpu-preparation.d.ts +23 -0
  108. package/dist/_types/contracts/local-execution/credential-request.d.ts +20 -0
  109. package/dist/_types/contracts/local-execution/external-generation.d.ts +59 -2
  110. package/dist/_types/contracts/local-execution/index.d.ts +12 -0
  111. package/dist/_types/contracts/local-execution/ipc.d.ts +27 -0
  112. package/dist/_types/contracts/local-execution/library-command.d.ts +303 -5
  113. package/dist/_types/contracts/local-execution/library-result.d.ts +217 -3
  114. package/dist/_types/contracts/local-execution/lifecycle.d.ts +35 -0
  115. package/dist/_types/contracts/local-execution/local-navigation.d.ts +3 -0
  116. package/dist/_types/contracts/local-execution/management.d.ts +12 -12
  117. package/dist/_types/contracts/local-execution/model-cleanup.d.ts +60 -0
  118. package/dist/_types/contracts/local-execution/model-inspection.d.ts +365 -0
  119. package/dist/_types/contracts/local-execution/openai-asr.d.ts +105 -0
  120. package/dist/_types/contracts/local-execution/openai-realtime-speech.d.ts +151 -0
  121. package/dist/_types/contracts/local-execution/preview.d.ts +15 -4
  122. package/dist/_types/contracts/local-execution/processor-capability.d.ts +6 -0
  123. package/dist/_types/contracts/local-execution/processor-direct.d.ts +140 -4
  124. package/dist/_types/contracts/local-execution/processor-outcomes.d.ts +145 -0
  125. package/dist/_types/contracts/local-execution/processor-recipes.d.ts +163 -3
  126. package/dist/_types/contracts/local-execution/processor.d.ts +2422 -322
  127. package/dist/_types/contracts/local-execution/project-source-direct.d.ts +1 -0
  128. package/dist/_types/contracts/local-execution/provider-inspection.d.ts +58 -0
  129. package/dist/_types/contracts/local-execution/provider-release.d.ts +53 -0
  130. package/dist/_types/contracts/local-execution/provider-selection.d.ts +58 -0
  131. package/dist/_types/contracts/local-execution/recognition.d.ts +30 -0
  132. package/dist/_types/contracts/local-execution/speech.d.ts +1 -1
  133. package/dist/_types/contracts/local-execution/versions.d.ts +2 -0
  134. package/dist/_types/contracts/media-observation.d.ts +56 -0
  135. package/dist/_types/contracts/native-speech-http.d.ts +15 -0
  136. package/dist/_types/contracts/navigation-context.d.ts +144 -0
  137. package/dist/_types/contracts/navigation-groups.d.ts +1 -1
  138. package/dist/_types/contracts/navigation.d.ts +2 -0
  139. package/dist/_types/contracts/observation-profile.d.ts +12 -0
  140. package/dist/_types/contracts/openai-asr.d.ts +55 -0
  141. package/dist/_types/contracts/provider-catalog.d.ts +44 -0
  142. package/dist/_types/contracts/provider-models.d.ts +115 -3
  143. package/dist/_types/contracts/provider.d.ts +93 -7
  144. package/dist/_types/contracts/render-readiness.d.ts +74 -1
  145. package/dist/_types/contracts/repair-strategy.d.ts +1 -1
  146. package/dist/_types/contracts/sound-making-plan.d.ts +41 -0
  147. package/dist/_types/contracts/source-workspace.d.ts +2 -0
  148. package/dist/_types/contracts/speech-cost.d.ts +129 -0
  149. package/dist/_types/contracts/speech.d.ts +50 -0
  150. package/dist/_types/contracts/transcription.d.ts +11 -0
  151. package/dist/_types/sdk/local-runtime/components.d.ts +6 -0
  152. package/dist/_types/sdk/local-runtime-client.d.ts +35 -23
  153. package/dist/entry.js +1 -1
  154. package/dist/local-management.js +1 -1
  155. package/dist/local-navigation.js +1 -1
  156. package/package.json +3 -2
  157. package/dist/_chunks/chunk-27KI24GK.js +0 -1
  158. package/dist/_chunks/chunk-2S7FI3HF.js +0 -1
  159. package/dist/_chunks/chunk-3RNDOAQI.js +0 -1
  160. package/dist/_chunks/chunk-3TOXIJ7K.js +0 -1
  161. package/dist/_chunks/chunk-4AD4PNUX.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-DMA53YVU.js +0 -1
  165. package/dist/_chunks/chunk-ETK7GYCB.js +0 -1
  166. package/dist/_chunks/chunk-FFXSXE3G.js +0 -1
  167. package/dist/_chunks/chunk-H4FH6STZ.js +0 -1
  168. package/dist/_chunks/chunk-LDBXGRCQ.js +0 -1
  169. package/dist/_chunks/chunk-PQCA4X5H.js +0 -1
  170. package/dist/_chunks/chunk-SM2I7TJ3.js +0 -1
  171. package/dist/_chunks/chunk-VXYZCCCQ.js +0 -1
  172. package/dist/_chunks/chunk-VYCNG6TR.js +0 -1
  173. package/dist/_chunks/chunk-WLQMICJN.js +0 -1
  174. package/dist/_chunks/chunk-WTJVS2VS.js +0 -1
  175. package/dist/_chunks/chunk-X5MVC46N.js +0 -1
  176. package/dist/_chunks/component-contract-2JHTRTOB.js +0 -1
  177. package/dist/_chunks/component-preflight-6OWDQAZT.js +0 -1
  178. package/dist/_chunks/connect-7TJDWXV4.js +0 -1
  179. package/dist/_chunks/device-management-JPS4HG34.js +0 -1
  180. package/dist/_chunks/device-preflight-GTQ67H7C.js +0 -1
  181. package/dist/_chunks/devices-inventory-E6ZLXCVR.js +0 -1
  182. package/dist/_chunks/devices-main-2BMCANKU.js +0 -1
  183. package/dist/_chunks/files-JJ6YOULB.js +0 -1
  184. package/dist/_chunks/host-component-ZYQ5ETVL.js +0 -1
  185. package/dist/_chunks/host-help-VNLA3YOV.js +0 -1
  186. package/dist/_chunks/host-main-KLWW7R47.js +0 -1
  187. package/dist/_chunks/http-profile-3VVSWYA5.js +0 -1
  188. package/dist/_chunks/library-main-3WWH7UYV.js +0 -1
  189. package/dist/_chunks/local-main-5BW63USP.js +0 -1
  190. package/dist/_chunks/local-mcp-AARKBDU5.js +0 -1
  191. package/dist/_chunks/main-LGYJ3ZCN.js +0 -2
  192. package/dist/_chunks/mcp-BLSK636Q.js +0 -1
  193. package/dist/_chunks/oauth-RPME2XYB.js +0 -1
  194. package/dist/_chunks/observe-entry-JVZAMB7N.js +0 -1
  195. package/dist/_chunks/remote-client-25Z65VJU.js +0 -1
  196. package/dist/_chunks/render-main-6Z3DKCWL.js +0 -1
  197. package/dist/_chunks/source-import-PNMCMTK7.js +0 -1
  198. package/dist/_chunks/src-7HSJFRVQ.js +0 -1
  199. package/dist/_chunks/stdio-main-HNLJCG45.js +0 -1
  200. package/dist/_chunks/workspace-main-QX5JGEMR.js +0 -1
@@ -1 +0,0 @@
1
- import{workspaceProject}from"./chunk-VYCNG6TR.js";import{profileAuthorization}from"./chunk-3TOXIJ7K.js";import{readCredential}from"./chunk-QGK6G6YS.js";import{connectRemoteMcp}from"./chunk-76E5R3OC.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{readInput}from"./chunk-QGK6G6YS.js";import{FileOAuthProvider,withProfileLock}from"./chunk-7I7ARCY7.js";import{remoteFetch,remoteResponse}from"./chunk-KOCUZ3AE.js";import{NativeStudioSdkError}from"./chunk-TT7IA5HB.js";import{auth}from"@modelcontextprotocol/client";import{extractWWWAuthenticateParams}from"@modelcontextprotocol/client";async function oauthResourceMetadataUrl(resource,signal){const response=await remoteResponse(resource,{method:"GET",headers:{accept:"application/json, text/event-stream"},...signal?{signal}:{}});try{if(response.status===401)return extractWWWAuthenticateParams(response).resourceMetadataUrl;if(![200,204,405,406].includes(response.status))throw Error();return void 0}finally{await response.body?.cancel()}}function uncertainExchange(){throw new NativeStudioSdkError("OAUTH_OUTCOME_UNKNOWN","INTERNAL_OPERATIONAL_FAILURE","UNKNOWN")}async function beginExchange(provider,kind){if(provider.data.pendingExchange)uncertainExchange();provider.data.version=2;provider.data.pendingExchange=kind;await provider.save()}async function runOAuthCommand(argv,stdin,signal){const fetchFn=(input,init)=>remoteFetch(input,{...init,...signal?{signal:AbortSignal.any([signal,...init?.signal?[init.signal]:[]])}:{}});const[command,...args]=argv,options=new Map;for(let i=0;i<args.length;i+=2){const key=args[i],value=args[i+1];if(!key||!["--profile","--mcp-url","--callback","--scope","--input"].includes(key)||!value||value.startsWith("--")||options.has(key))throw Error();options.set(key,value)}const path=options.get("--profile");if(!path)throw Error();return withProfileLock(path,async()=>{if(command==="auth-start"){if(!options.has("--mcp-url")||!options.has("--callback")||options.has("--input"))throw Error();const provider2=await FileOAuthProvider.create(path,options.get("--mcp-url"),options.get("--callback"),options.get("--scope")??"nvs:read nvs:write");const resourceMetadataUrl=await oauthResourceMetadataUrl(provider2.data.resource,signal);await auth(provider2,{serverUrl:provider2.data.resource,scope:provider2.data.scope,...resourceMetadataUrl?{resourceMetadataUrl}:{},fetchFn});return{exitCode:0,output:{semanticStatus:"NEEDS_INPUT",authorizationUrl:provider2.data.authorizationUrl,profileSaved:true}}}if(!options.has("--input")||options.size!==2||command!=="auth-complete")throw Error();const provider=await FileOAuthProvider.load(path),raw=await readInput(options.get("--input"),stdin);if(typeof raw.callbackUrl!=="string"||Object.keys(raw).some(k=>k!=="callbackUrl"))throw Error();const url=new URL(raw.callbackUrl),expected=new URL(provider.data.redirect);if(url.origin!==expected.origin||url.pathname!==expected.pathname||url.searchParams.getAll("code").length!==1||url.searchParams.getAll("state").length!==1||url.searchParams.getAll("iss").length!==1||url.searchParams.get("state")!==provider.data.state)throw Error();const code=url.searchParams.get("code"),iss=url.searchParams.get("iss");const issuer=provider.data.discovery?.authorizationServerMetadata?.issuer??provider.data.discovery?.authorizationServerUrl;if(issuer&&issuer!==iss)throw Error();await beginExchange(provider,"CODE");try{const result=await auth(provider,{serverUrl:provider.data.resource,authorizationCode:code,iss,fetchFn});if(result!=="AUTHORIZED"||provider.data.pendingExchange||!provider.data.token)uncertainExchange()}catch{uncertainExchange()}return{exitCode:0,output:{semanticStatus:"SUCCESS",connected:true,expiresAt:provider.data.expiresAt}}})}async function profileAuthorization(path,signal){signal?.throwIfAborted();return withProfileLock(path,async()=>{const provider=await FileOAuthProvider.load(path);signal?.throwIfAborted();if(provider.data.pendingExchange)uncertainExchange();if(!provider.data.token)throw Error();if(!provider.data.expiresAt||provider.data.expiresAt<Date.now()+3e4){await beginExchange(provider,"REFRESH");try{const result=await auth(provider,{serverUrl:provider.data.resource,fetchFn:(input,init)=>remoteFetch(input,{...init,...signal?{signal:AbortSignal.any([signal,...init?.signal?[init.signal]:[]])}:{}})});if(result!=="AUTHORIZED"||provider.data.pendingExchange)uncertainExchange()}catch{uncertainExchange()}}return{resource:provider.data.resource,authorization:"Bearer "+provider.data.token.access_token}})}export{runOAuthCommand,profileAuthorization};
@@ -1 +0,0 @@
1
- import{LocalExecutionInspectInputSchema,LocalExecutionListInputSchema,LocalMcpOutputSchemas,NativeStudioLocalRuntimeClient,catalogue}from"./chunk-LDBXGRCQ.js";import{LocalLibraryGetSchema,LocalLibraryProjectionPageSchema,LocalLibraryProjectionQuerySchema}from"./chunk-2S7FI3HF.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{privateAccess,privateDirectory,write}from"./chunk-DLW42PJ6.js";import{secureEndpoint}from"./chunk-KOCUZ3AE.js";import{randomBytes}from"node:crypto";import{open,unlink,constants}from"node:fs/promises";import{dirname,resolve}from"node:path";var FileOAuthProvider=class _FileOAuthProvider{constructor(path,data){this.path=path;this.data=data}path;data;static async create(path,resource,redirect,scope){secureEndpoint(resource);secureEndpoint(redirect);if(!["nvs:read","nvs:read nvs:write"].includes(scope))throw Error();if(process.platform==="win32")await privateDirectory(dirname(resolve(path)));const data={version:1,resource,redirect,scope,state:randomBytes(24).toString("base64url")};await write(resolve(path),JSON.stringify(data),true);return new _FileOAuthProvider(path,data)}static async load(path){if(process.platform==="win32")await privateAccess(resolve(path),"file");const file=await open(path,constants.O_RDONLY|constants.O_NOFOLLOW|constants.O_NONBLOCK);let data;try{const stat=await file.stat();if(!stat.isFile()||stat.nlink!==1||process.platform!=="win32"&&(stat.uid!==process.getuid?.()||(stat.mode&63)!==0)||stat.size>65536)throw Error();const bytes=Buffer.alloc(65537);const{bytesRead}=await file.read(bytes,0,bytes.length,0);if(bytesRead>65536)throw Error();data=JSON.parse(bytes.subarray(0,bytesRead).toString("utf8"))}finally{await file.close()}if(![1,2].includes(data.version)||typeof data.state!=="string"||data.state.length<16)throw Error();if(data.pendingExchange!==void 0&&!["CODE","REFRESH"].includes(data.pendingExchange))throw Error();if(data.version===2!==(data.pendingExchange!==void 0))throw Error();secureEndpoint(data.resource);secureEndpoint(data.redirect);if(!["nvs:read","nvs:read nvs:write"].includes(data.scope))throw Error();return new _FileOAuthProvider(path,data)}async save(){if(process.platform==="win32")await privateDirectory(dirname(resolve(this.path)));await write(resolve(this.path),JSON.stringify(this.data))}get redirectUrl(){return this.data.redirect}get clientMetadata(){return{client_name:"NativeStudio CLI",redirect_uris:[this.data.redirect],token_endpoint_auth_method:"none",grant_types:["authorization_code","refresh_token"],response_types:["code"],scope:this.data.scope,application_type:"native"}}state(){return this.data.state}clientInformation(){return this.data.client}async saveClientInformation(value){this.data.client=value;await this.save()}tokens(){return this.data.token}async saveTokens(value){const metadataOnly=this.data.pendingExchange==="REFRESH"&&value.access_token===this.data.token?.access_token&&value.refresh_token===this.data.token?.refresh_token;this.data.token=value;if(!metadataOnly){this.data.expiresAt=Date.now()+(value.expires_in??600)*1e3;this.data.version=1;delete this.data.pendingExchange}await this.save()}async redirectToAuthorization(url){this.data.authorizationUrl=url.href;await this.save()}async saveCodeVerifier(value){this.data.verifier=value;await this.save()}codeVerifier(){if(!this.data.verifier)throw Error();return this.data.verifier}async saveDiscoveryState(value){this.data.discovery=value;await this.save()}discoveryState(){return this.data.discovery}};async function withProfileLock(path,action){if(process.platform==="win32")await privateDirectory(dirname(resolve(path)));const file=await open(path+".lock","wx",384);try{return await action()}finally{await file.close();await unlink(path+".lock")}}export{FileOAuthProvider,withProfileLock};
@@ -1 +0,0 @@
1
- import{tenantConnection}from"./chunk-27KI24GK.js";import{FileOAuthProvider,withProfileLock}from"./chunk-7I7ARCY7.js";import{remoteResponse,secureEndpoint}from"./chunk-KOCUZ3AE.js";import{NativeStudioSdkError}from"./chunk-TT7IA5HB.js";async function apiMetadata(url,signal){let response;try{response=await remoteResponse(url,{headers:{accept:"application/json"},signal:signal?AbortSignal.any([signal,AbortSignal.timeout(5e3)]):AbortSignal.timeout(5e3)});if(!response.ok)return void 0;const parts=[];let size=0;for await(const part of response.body??[]){size+=part.byteLength;if(size>16384)return void 0;parts.push(part)}const data=JSON.parse(Buffer.concat(parts).toString());return data&&typeof data==="object"&&!Array.isArray(data)?data:void 0}catch{signal?.throwIfAborted();return void 0}finally{await response?.body?.cancel().catch(()=>{})}}async function profileHttpOrigin(path,resource,signal){signal?.throwIfAborted();return withProfileLock(path,async()=>{const provider=await FileOAuthProvider.load(path);signal?.throwIfAborted();const deny=()=>{throw new NativeStudioSdkError("API_ORIGIN_UNTRUSTED","BLOCKED","NO_WRITE")};if(provider.data.resource!==resource)deny();if(provider.data.pendingExchange)throw new NativeStudioSdkError("OAUTH_OUTCOME_UNKNOWN","BLOCKED","UNKNOWN");tenantConnection(resource);const endpoint=secureEndpoint(resource);const metadataUrl=endpoint.origin+"/.well-known/oauth-protected-resource"+endpoint.pathname;const fresh=await apiMetadata(metadataUrl,signal);signal?.throwIfAborted();if(fresh&&fresh.resource!==resource)deny();const metadata=fresh??provider.data.discovery?.resourceMetadata;const configured=metadata?.nativestudio_api_origin;if(configured===void 0){if(fresh&&provider.data.discovery){const saved={...provider.data.discovery.resourceMetadata,resource};Reflect.deleteProperty(saved,"nativestudio_api_origin");provider.data.discovery.resourceMetadata=saved;provider.data.discovery.resourceMetadataUrl=metadataUrl;await provider.save()}return endpoint.origin}try{if(typeof configured!=="string")return deny();const sourceUrl=metadata===fresh?metadataUrl:provider.data.discovery?.resourceMetadataUrl;if(typeof sourceUrl!=="string"||secureEndpoint(sourceUrl).origin!==endpoint.origin||metadata?.resource!==resource||configured.length>2048)deny();const api=secureEndpoint(configured);if(api.pathname!=="/"||endpoint.protocol==="https:"&&api.protocol!=="https:")deny();if(metadata===fresh&&provider.data.discovery){provider.data.discovery.resourceMetadata={...provider.data.discovery.resourceMetadata,resource,nativestudio_api_origin:api.origin};provider.data.discovery.resourceMetadataUrl=metadataUrl;await provider.save()}return api.origin}catch{return deny()}})}export{profileHttpOrigin};
@@ -1 +0,0 @@
1
- import{desktopAutomation,desktopInstallationIdentity}from"./chunk-MZWEFYHE.js";import{LocalInstallationManager,ownerClient,socketAbsent}from"./chunk-FFXSXE3G.js";import{LocalLibraryCallSchema,LocalLibraryGetSchema,LocalLibraryImportSchema,LocalLibraryItemSchema,LocalLibraryPageSchema,LocalLibraryProjectionPageSchema,LocalLibraryProjectionSchema,LocalLibraryReadReplySchema,LocalLibraryReferenceSchema,LocalLibraryUsageSchema}from"./chunk-2S7FI3HF.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{DesktopDeviceScopeSchema,DesktopDeviceStateSchema}from"./chunk-SM2I7TJ3.js";import{canonicalLocalJson}from"./chunk-2S7FI3HF.js";import{directory,entries,fail,privateAccess,read,sha256,write}from"./chunk-DLW42PJ6.js";import{join}from"node:path";var recordRoot=(home,scope)=>join(home,"devices",sha256(canonicalLocalJson(scope)));var DesktopDeviceRecords=class _DesktopDeviceRecords{constructor(root,scope){this.root=root;this.scope=scope}root;scope;static async open(home,raw){const scope=DesktopDeviceScopeSchema.parse(raw);return new _DesktopDeviceRecords(await directory(recordRoot(home,scope)),scope)}static async inspect(home,raw){const scope=DesktopDeviceScopeSchema.parse(raw);const root=recordRoot(home,scope);try{await privateAccess(join(home,"devices"),"directory");await privateAccess(root,"directory")}catch(error){if(error.code==="ENOENT")return null;throw error}return new _DesktopDeviceRecords(root,scope).current()}async current(){const names=(await entries(this.root)).filter(n=>/^\d{12}\.json$/.test(n)).sort();let state={revision:0,scope:this.scope,enrollment:null,device:null,previews:[],connectorId:null,connection:null,pending:null};for(const[index,name]of names.entries()){const next=DesktopDeviceStateSchema.parse(JSON.parse((await read(join(this.root,name),262144,true)).toString()));if(next.revision!==index+1||canonicalLocalJson(next.scope)!==canonicalLocalJson(this.scope))fail("DEVICE_HISTORY_INVALID");state=next}return state}async save(before,fields){if((await this.current()).revision!==before.revision)fail("REVISION_CONFLICT");const next=DesktopDeviceStateSchema.parse({...before,...fields,revision:before.revision+1});try{await write(join(this.root,String(next.revision).padStart(12,"0")+".json"),canonicalLocalJson(next),true)}catch(e){if(e.code==="EEXIST")fail("REVISION_CONFLICT");throw e}return next}keyPath(){return join(this.root,"device-key.json")}connectorPath(id){return join(this.root,id+".connector.json")}};async function desktopDeviceConnector(home,scope){const records=await DesktopDeviceRecords.open(home,scope),state=await records.current();if(!state.connectorId)fail("LOCAL_AUTHORIZATION_REQUIRED");return records.connectorPath(state.connectorId)}export{DesktopDeviceRecords,desktopDeviceConnector};
@@ -1 +0,0 @@
1
- import{LocalCompositionBrowserSelectionSchema,LocalDoctorReportSchema,LocalManagementInventorySchema,LocalRuntimeComponentSchema,LocalRuntimeDescriptorSchema,LocalToolChoiceSchema,LocalToolSelectionSchema,LocalUpdatePlanSchema,NativeStudioLocalRuntimeClient,RuntimeCaptionAssets,asset,catalogue,newerVersion,select}from"./chunk-LDBXGRCQ.js";import{canonicalLocalJson,importedNormalizationValidationProfile,localLibraryProfile,referenceThumbnailProfile,tenantRenderValidationProfile,whisperCppRecognitionProfile}from"./chunk-2S7FI3HF.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,"10aa0eb038db144460d7c32c810aebff985d299095375007e7c44f005e901c09");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{probeLocalLibrary,probeTenantQwenGeneration,probeTenantSpeech,probeTenantTranscription}from"./chunk-FFXSXE3G.js";import{LocalToolSelectionSchema}from"./chunk-LDBXGRCQ.js";import{LocalDeviceTransportConfigurationSchema,canonicalLocalJson}from"./chunk-2S7FI3HF.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{ComponentStatusSchema,CpuSpeechCapabilitySchema,CpuSpeechInputSchema,CpuSpeechInstallationSchema,DeviceEnrollmentScopeSchema,EnrollLocalDeviceSchema,KeyframeObservationSchema,LegacyCaptionRenderStyleSchema,LocalDeviceManagementCommandSchema,LocalDevicePlatformSchema,LocalDeviceViewSchema,LocalDigestSchema,LocalFinalRenderAdmissionSchema,LocalIdSchema,LocalLeaseBindingSchema,LocalLibraryCallSchema,LocalLibraryCapabilitySchema,LocalLibraryGetSchema,LocalLibraryImportSchema,LocalLibraryItemSchema,LocalLibraryPageSchema,LocalLibraryProjectionPageSchema,LocalLibraryProjectionSchema,LocalLibraryReadReplySchema,LocalLibraryUsageSchema,LocalManagementReceiptSchema,LocalPackageVersionSchema,LocalPreviewAdmissionSchema,LocalProjectScopeSchema,LocalRevisionSchema,LocalTimeSchema,LocalWhisperToolSelectionSchema,LocalWorkScopeSchema,RegularCaptionRenderStyleSchema,ReviewEvidenceMediaSchema,ReviewIntelligenceBasisSchema,ReviewIntelligenceContextResultSchema,RevokeLocalDeviceSchema,RoughCutRequirementSchema,StartLocalFinalRenderSchema,StartLocalPreviewSchema,TenantProcessorKindSchema,ValidateReviewIntelligenceSchema,VideoReviewRequirementSchema,VisualRequirementSchema,assertManagementReceipt,canonicalLocalJson,checkedManagementReceipt,kokoroCpuProfile,mediaCategoryOf}from"./chunk-2S7FI3HF.js";import{fail,localSocketPath,privateAccess,privateDirectory,read,sha256,sha512}from"./chunk-DLW42PJ6.js";import{CapabilityVersionMismatchSchema}from"./chunk-WTJVS2VS.js";import{NativeStudioSdkError}from"./chunk-TT7IA5HB.js";import{z}from"zod";var HYPERFRAME_RENDER_PROFILE={id:"HYPERFRAME_1080P30_FULL_PAINT_V1",adapter:"native-hyperframe-v1",engine:"0.8.134",producer:"0.8.134",gsap:"3.15.0",node:"v24.21.0",browser:"Google Chrome for Testing 154.0.8037.57",browserSha256:"60c03e8882f4bb47459a905ede1074e1e746c5b765e437c288e460320540a8a3",ffmpeg:"ffmpeg version 8.0.1-3ubuntu2 Copyright (c) 2000-2025 the FFmpeg developers",maxFrames:360,timeoutMs:6e5,maxRssBytes:3221225472,maxScratchBytes:3221225472,maxOutputBytes:134217728,maxCpuMs:6e5,capture:"PNG_SOFTWARE_SCREENSHOT_FULL_PAINT",encode:"H264_YUV420P_CRF18_THREADS2_NO_AUDIO"};var HYPERFRAME_ALPHA_RENDER_PROFILE={...HYPERFRAME_RENDER_PROFILE,id:"HYPERFRAME_RGBA_PNG30_FULL_PAINT_V1",adapter:"native-hyperframe-alpha-v1",encode:"RGBA_PNG_SEQUENCE_30_V1",maxOutputBytes:67108864,maxDecodedBytes:536870912};var HYPERFRAME_CACHED_RENDER_PROFILE={...HYPERFRAME_RENDER_PROFILE,id:"HYPERFRAME_1080P30_FRAME_CACHE_V2",adapter:"native-hyperframe-cache-v2",encode:"H264_YUV420P_CRF18_VERYFAST_THREADS2_NO_AUDIO"};var executable=z.strictObject({path:z.string().min(1).max(4096),digest:LocalDigestSchema});var LocalManagedMediaReuseSchema=z.strictObject({schemaVersion:z.literal(1),ffmpeg:executable,ffprobe:executable});var mediaTools={ffmpeg:executable,ffprobe:executable};var LocalCompositionBrowserSelectionSchema=executable.extend({digest:z.literal(HYPERFRAME_CACHED_RENDER_PROFILE.browserSha256)});var LocalInstalledToolSelectionSchema=z.strictObject({mode:z.literal("INSTALLED"),...mediaTools,compositionBrowser:LocalCompositionBrowserSelectionSchema.optional(),whisper:LocalWhisperToolSelectionSchema.optional(),cpuSpeech:CpuSpeechInstallationSchema.optional()});var LocalToolSelectionSchema=z.discriminatedUnion("mode",[z.strictObject({mode:z.literal("MANAGED"),...mediaTools,cpuSpeech:CpuSpeechInstallationSchema.optional()}),LocalInstalledToolSelectionSchema]);import{z as z2}from"zod";var LocalRuntimeDescriptorSchema=z2.strictObject({protocol:z2.literal("NVS_RUNTIME_DESCRIPTOR_V1"),version:LocalPackageVersionSchema,node:z2.strictObject({major:z2.literal(24),minMinor:z2.literal(12)}),platform:LocalDevicePlatformSchema,ipcProtocol:z2.literal("NVS_LOCAL_IPC_V1"),workProtocol:z2.enum(["NVS_LOCAL_WORK_V1","NVS_LOCAL_WORK_V2"]),journalSchema:z2.literal(1),rendererDigest:LocalDigestSchema,profileDigest:LocalDigestSchema,compatibleRenderers:z2.array(z2.strictObject({rendererDigest:LocalDigestSchema,profileDigest:LocalDigestSchema})).max(4).optional()});var LocalReleaseAssetSchema=z2.strictObject({url:z2.string().url().max(2048),byteSize:z2.int().positive().max(256*1024*1024),sha512:z2.string().length(128).regex(/^[0-9a-f]{128}$/)});import{z as z4}from"zod";import{z as z3}from"zod";var RuntimeCaptionAssets={"NotoSansSC.ttf":LegacyCaptionRenderStyleSchema.shape.fontSha256.value,"NativeStudioSC-Regular.ttf":RegularCaptionRenderStyleSchema.shape.fontSha256.value,"OFL.txt":"092c580f54ee69841e94731e91f63f5d2d2a793550f4827cec485656e462f1bd"};var LocalComponentBytesSchema=z3.strictObject({byteSize:z3.int().positive().max(64*1024*1024),sha512:z3.string().length(128).regex(/^[0-9a-f]{128}$/)});var LocalRuntimeComponentSchema=LocalComponentBytesSchema.extend({protocol:z3.literal("NVS_PRODUCT_COMPONENT_V2"),version:LocalPackageVersionSchema,descriptor:LocalRuntimeDescriptorSchema.omit({platform:true}),resources:z3.strictObject({captions:LocalComponentBytesSchema})}).refine(v=>v.version===v.descriptor.version);var LocalSessionConnectorSchema=z4.strictObject({protocol:z4.literal("NVS_LOCAL_CONNECTOR_V1"),stateDirectory:z4.string().min(1).max(4096),credential:z4.string().length(43).regex(/^[A-Za-z0-9_-]{43}$/),expiresAt:LocalTimeSchema,tenantId:z4.uuid(),deviceId:z4.uuid()});var LocalManagementInventorySchema=z4.strictObject({runtimeRevision:z4.int().positive(),descriptor:LocalRuntimeDescriptorSchema,activeProcesses:z4.int().nonnegative(),pendingExecutions:z4.int().nonnegative(),pendingRequests:z4.int().nonnegative(),pendingRenderers:z4.array(LocalDigestSchema).max(64)});var LocalReleaseSchema=z4.strictObject({descriptor:LocalRuntimeDescriptorSchema,package:LocalReleaseAssetSchema,tools:z4.strictObject({ffmpeg:LocalReleaseAssetSchema.extend({sha256:LocalDigestSchema}),ffprobe:LocalReleaseAssetSchema.extend({sha256:LocalDigestSchema})}).nullable(),resources:z4.strictObject({captions:LocalReleaseAssetSchema.extend({byteSize:LocalComponentBytesSchema.shape.byteSize})}).optional()});var LocalBundledReleaseSchema=LocalReleaseSchema.extend({package:LocalComponentBytesSchema.extend({source:z4.literal("CLI")})});var LocalReleaseCatalogueSchema=z4.strictObject({protocol:z4.literal("NVS_LOCAL_RELEASE_CATALOGUE_V1"),issuedAt:LocalTimeSchema,expiresAt:LocalTimeSchema,releases:z4.array(LocalReleaseSchema).min(1).max(32)}).refine(v=>Date.parse(v.expiresAt)>Date.parse(v.issuedAt)&&Date.parse(v.expiresAt)-Date.parse(v.issuedAt)<=7*864e5&&new Set(v.releases.map(r=>[r.descriptor.version,r.descriptor.platform.os,r.descriptor.platform.architecture].join(":"))).size===v.releases.length);var LocalSignedCatalogueSchema=z4.strictObject({catalogue:LocalReleaseCatalogueSchema,signature:z4.string().length(86).regex(/^[A-Za-z0-9_-]{85}[AQgw]$/)});var LocalToolChoiceSchema=z4.discriminatedUnion("mode",[z4.strictObject({mode:z4.literal("MANAGED"),cpuSpeech:CpuSpeechInstallationSchema.optional(),reuseMedia:LocalManagedMediaReuseSchema.optional()}),LocalInstalledToolSelectionSchema.extend({captionAssetsDirectory:z4.string().min(1).max(4096).optional()})]);var LocalUpdatePlanSchema=z4.strictObject({protocol:z4.literal("NVS_LOCAL_UPDATE_PLAN_V1"),planId:LocalIdSchema,installationRevision:z4.int().nonnegative(),runtimeRevision:z4.int().positive().nullable(),catalogueFingerprint:LocalDigestSchema.nullable(),trustFingerprint:LocalDigestSchema.optional(),release:z4.union([LocalReleaseSchema,LocalBundledReleaseSchema]),toolSelection:LocalToolChoiceSchema.optional(),fingerprint:LocalDigestSchema,createdAt:LocalTimeSchema,expiresAt:LocalTimeSchema});var LocalClientNextActionSchema=z4.strictObject({surface:z4.enum(["CLI","LOCAL_IPC","REMOTE"]),operation:z4.enum(["runtime.status","local.configure","local.install","local.start","local.connect","local.grant","local.status","local.doctor","local.stop","local.update.check","local.update.prepare","local.update.apply","local.update.reconcile","execution.inspect","rough_cut_get","operation_get"]),availability:z4.enum(["AVAILABLE","BLOCKED"]),reason:z4.enum(["READY","INSTALL_REQUIRED","AUTHORIZATION_REQUIRED","VERSION_INCOMPATIBLE","UPDATE_AVAILABLE","RECOVERY_REQUIRED","USER_APPROVAL_REQUIRED","TRUST_REQUIRED","UNAVAILABLE"])});import{z as z11}from"zod";import{z as z10}from"zod";import{z as z5}from"zod";var LocalOfflineSnapshotSchema=z5.strictObject({projectId:z5.uuid(),title:z5.string().min(1).max(200),savedAt:LocalTimeSchema,expiresAt:LocalTimeSchema,productions:z5.array(z5.strictObject({id:z5.uuid(),title:z5.string().max(200)})).max(40),possiblyTruncated:z5.boolean()}).refine(v=>new TextEncoder().encode(JSON.stringify(v)).length<=8192);var text=z5.string().max(4e3).refine(v=>new TextEncoder().encode(JSON.stringify(v)).length<=8192);var LocalOfflineCallSchema=z5.discriminatedUnion("action",[z5.strictObject({action:z5.enum(["list","forget"]),key:LocalDigestSchema}),z5.strictObject({action:z5.literal("retain"),key:LocalDigestSchema,snapshot:LocalOfflineSnapshotSchema}),z5.strictObject({action:z5.literal("draft"),key:LocalDigestSchema,projectId:z5.uuid(),text,expectedRevision:z5.int().nonnegative()})]);var LocalOfflinePageSchema=z5.strictObject({historical:z5.literal(true),items:z5.array(z5.strictObject({snapshot:LocalOfflineSnapshotSchema,draft:z5.strictObject({text,revision:z5.int().nonnegative()})})).max(3)});import{z as z7}from"zod";import{z as z6}from"zod";var QualifiedLocalAgentVersionSchema=z6.enum(["0.164.0","0.165.0"]);var LocalAgentGrantSchema=z6.strictObject({protocol:z6.literal("NVS_CODEX_REVIEW_GRANT_V1"),binary:z6.string().min(1).max(4096).refine(v=>/^(?:\/|[A-Za-z]:[\\/])/.test(v)),binaryDigest:z6.string().regex(/^[a-f0-9]{64}$/),version:QualifiedLocalAgentVersionSchema,model:z6.string().regex(/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,99}$/),reasoningEffort:z6.enum(["low","medium","high","xhigh"]).optional(),reviewerLabel:z6.string().trim().min(1).max(100),inference:z6.literal("REMOTE_OPENAI"),remoteUseApproved:z6.literal(true),imageDisclosureApproved:z6.literal(true).optional(),mediaDisclosureApproved:z6.literal(true).optional(),projects:z6.array(LocalProjectScopeSchema).min(1).max(100),expiresAt:z6.iso.datetime({offset:true})});var LocalAgentMediaInputSchema=z7.strictObject({profile:z7.literal("NVS_AGENT_DERIVED_EVIDENCE_V1"),contentType:z7.enum(["image/png","image/jpeg","image/webp","video/mp4"]),byteSize:z7.int().positive().max(134217728),width:z7.int().positive().max(4096),height:z7.int().positive().max(4096),durationMs:z7.int().positive().max(6e4).optional(),frameRate:z7.union([z7.literal(24),z7.literal(30)]).optional(),hasAudio:z7.boolean().optional()}).refine(v=>v.contentType==="video/mp4"?!!v.durationMs&&!!v.frameRate:!v.durationMs&&!v.frameRate&&v.hasAudio===void 0);var sha=z7.string().regex(/^[a-f0-9]{64}$/);var LocalAgentEvidenceReceiptSchema=z7.strictObject({protocol:z7.literal("NVS_AGENT_DERIVED_EVIDENCE_V1"),draftId:z7.uuid(),media:ReviewEvidenceMediaSchema,ffmpegDigest:sha,ffprobeDigest:sha,attachment:z7.strictObject({checksumSha256:sha,byteSize:z7.int().positive().max(8388608),width:z7.int().positive().max(4096),height:z7.int().positive().max(4096)}),timestampsMs:z7.array(z7.number().nonnegative().max(6e4)).max(6),audio:z7.strictObject({sampleRateHz:z7.literal(48e3),channels:z7.literal(1),samples:z7.int().positive().max(2881024),peak:z7.number().min(0).max(1),rms:z7.number().min(0).max(1),clippedSamples:z7.int().nonnegative().max(2881024)}).nullable(),limitations:z7.tuple([z7.literal("SAMPLED_FRAMES_ARE_NOT_FULL_PLAYBACK"),z7.literal("AUDIO_STATISTICS_ARE_NOT_LISTENING_OR_TRANSCRIPTION")])});var LocalAgentDiscoverySchema=z7.strictObject({candidate:z7.strictObject({binary:z7.string().min(1).max(4096),binaryDigest:sha,version:z7.string().regex(/^\d+\.\d+\.\d+$/),qualified:z7.boolean()}).nullable(),configured:LocalAgentGrantSchema.nullable()});import{z as z8}from"zod";var LocalResourcePolicySchema=z8.strictObject({acceptNewWork:z8.boolean().default(true),mode:z8.enum(["CONTINUOUS","IDLE_ONLY"]).default("CONTINUOUS"),idleAfterSeconds:z8.int().min(30).max(3600).default(300),maxConcurrentJobs:z8.int().min(1).max(2).default(1),cpuCores:z8.union([z8.literal(1),z8.literal(2)]).default(2),memoryMiB:z8.int().min(512).max(4096).default(4096),cacheQuotaBytes:z8.int().min(512*1024*1024).max(32*1024*1024*1024).default(1024*1024*1024)});var LocalResourceSettingsSchema=z8.strictObject({revision:z8.int().nonnegative(),policy:LocalResourcePolicySchema});var LocalExecutionProgressSchema=z8.strictObject({stage:z8.enum(["WAITING","DOWNLOADING","EXECUTING","UPLOADING","AWAITING_ACCEPTANCE","COMPLETE","RECOVERY_REQUIRED","FENCED"]),downloadedBytes:z8.int().nonnegative(),sourceBytes:z8.int().nonnegative(),uploadedBytes:z8.int().nonnegative(),outputBytes:z8.int().nonnegative(),lastError:z8.strictObject({code:z8.string().regex(/^[A-Z][A-Z0-9_]{0,79}$/),observedAt:LocalTimeSchema}).nullable()});var LocalStorageInspectionSchema=z8.strictObject({cacheBytes:z8.int().nonnegative(),protectedBytes:z8.int().nonnegative(),reclaimableBytes:z8.int().nonnegative(),transferBytes:z8.int().nonnegative(),journalBytes:z8.int().nonnegative(),reviewBytes:z8.int().nonnegative().optional(),ownerStagingBytes:z8.int().nonnegative().optional(),availableDiskBytes:z8.int().nonnegative(),quotaBytes:z8.int().positive(),overQuota:z8.boolean()});var LocalWorkspaceInspectionSchema=z8.strictObject({settings:LocalResourceSettingsSchema,storage:LocalStorageInspectionSchema,scheduling:z8.strictObject({state:z8.enum(["READY","PAUSED","WAITING_FOR_IDLE","AT_CAPACITY","DRAINING"]),activeJobs:z8.int().nonnegative(),idleObservationCurrent:z8.boolean()})});var LocalDiagnosticsSchema=z8.strictObject({protocol:z8.literal("NVS_LOCAL_DIAGNOSTICS_V1"),createdAt:LocalTimeSchema,runtimeVersion:z8.string().min(1).max(80),runtimeRevision:LocalRevisionSchema,settings:LocalResourceSettingsSchema,storage:LocalStorageInspectionSchema,recordCounts:z8.record(z8.string().regex(/^[A-Z_]{1,40}$/),z8.int().nonnegative()),failures:z8.array(z8.strictObject({taskFingerprint:z8.string().regex(/^[a-f0-9]{64}$/),code:z8.string().regex(/^[A-Z][A-Z0-9_]{0,79}$/),observedAt:LocalTimeSchema})).max(32)});import{z as z9}from"zod";var sha2=z9.string().regex(/^[a-f0-9]{64}$/);var qualifiedVersion=QualifiedLocalAgentVersionSchema;var LocalAgentSnapshotSchema=z9.strictObject({basis:ReviewIntelligenceBasisSchema,productionRevision:z9.int().positive(),reviewVersion:z9.int().nonnegative(),executionClass:z9.enum(["LIVE","TEST_ONLY"]),media:ReviewEvidenceMediaSchema,requirements:z9.array(z9.union([VisualRequirementSchema,VideoReviewRequirementSchema,RoughCutRequirementSchema])).min(1).max(64),evidence:LocalAgentMediaInputSchema.optional(),image:z9.strictObject({contentType:z9.literal("image/png"),byteSize:z9.int().positive().max(8388608),width:z9.int().positive().max(4096),height:z9.int().positive().max(4096)}).optional()}).refine(v=>!v.image||!v.evidence&&v.basis.target.kind==="IMAGE").refine(v=>v.basis.target.kind==="IMAGE"||!v.evidence||v.evidence.contentType==="video/mp4").refine(v=>new TextEncoder().encode(JSON.stringify(v)).length<=32768).refine(v=>new Set(v.requirements.map(r=>r.key)).size===v.requirements.length);var LocalAgentProbeSchema=z9.strictObject({configured:z9.boolean(),available:z9.boolean(),reason:z9.enum(["GRANT_REQUIRED","READY","RUNTIME_UNAVAILABLE","GRANT_EXPIRED"]),grantFingerprint:sha2.nullable(),inference:z9.literal("REMOTE_OPENAI")});var LocalAgentPlanSchema=z9.strictObject({protocol:z9.enum(["NVS_LOCAL_AGENT_REVIEW_V1","NVS_LOCAL_AGENT_REVIEW_V2"]),id:z9.uuid(),grantFingerprint:sha2,snapshot:LocalAgentSnapshotSchema,expiresAt:z9.iso.datetime({offset:true}),fingerprint:sha2});var LocalAgentMetadataAnswerSchema=z9.strictObject({summary:z9.string().trim().min(1).max(1500),observations:z9.array(z9.strictObject({key:z9.string().min(1).max(220),observed:z9.string().trim().min(1).max(1e3)})).min(1).max(64)});var LocalAgentPixelAnswerSchema=z9.strictObject({summary:z9.string().trim().min(1).max(1500),imageReadback:z9.string().trim().min(1).max(800),observations:z9.array(KeyframeObservationSchema.omit({region:true}).extend({key:z9.string().min(1).max(220)})).min(1).max(64)});var LocalAgentAnswerSchema=z9.union([LocalAgentMetadataAnswerSchema,LocalAgentPixelAnswerSchema]).refine(v=>new TextEncoder().encode(JSON.stringify(v)).length<=96*1024);var LocalAgentImageReceiptSchema=z9.strictObject({protocol:z9.literal("NVS_LOCAL_AGENT_IMAGE_V1"),draftId:z9.uuid(),media:ReviewEvidenceMediaSchema,byteSize:z9.int().positive().max(8388608),contentType:z9.literal("image/png"),width:z9.int().positive().max(4096),height:z9.int().positive().max(4096)});var LocalAgentReviewViewSchema=z9.strictObject({plan:LocalAgentPlanSchema,revision:z9.int().positive(),phase:z9.enum(["PREPARED","RUNNING","RESULT_PENDING","UNKNOWN"]),answer:LocalAgentAnswerSchema.nullable(),imageReceipt:LocalAgentImageReceiptSchema.optional(),evidenceReceipt:LocalAgentEvidenceReceiptSchema.optional(),provenance:z9.strictObject({adapter:z9.enum(["CODEX_METADATA_V1","CODEX_MEDIA_V2"]),binaryDigest:sha2,version:qualifiedVersion,model:z9.string().max(100),reasoningEffort:z9.enum(["low","medium","high","xhigh"]).optional(),reviewerLabel:z9.string().max(100),inference:z9.literal("REMOTE_OPENAI"),evidence:z9.enum(["METADATA_ONLY","IMAGE_PIXELS","VIDEO_FRAMES"])})}).refine(v=>{const image=v.plan.snapshot.image,receipt=v.imageReceipt;if(receipt&&(!image||receipt.draftId!==v.plan.id||canonicalLocalJson(receipt.media)!==canonicalLocalJson(v.plan.snapshot.media)||canonicalLocalJson({contentType:receipt.contentType,byteSize:receipt.byteSize,width:receipt.width,height:receipt.height})!==canonicalLocalJson(image)))return false;if(v.phase==="RESULT_PENDING"!==!!v.answer)return false;const derived=v.plan.snapshot.evidence,receipt2=v.evidenceReceipt;if(v.provenance.adapter!==(derived?"CODEX_MEDIA_V2":"CODEX_METADATA_V1"))return false;if(receipt2&&(!derived||receipt2.draftId!==v.plan.id||canonicalLocalJson(receipt2.media)!==canonicalLocalJson(v.plan.snapshot.media)))return false;if(v.answer&&!!(image||derived)!=="imageReadback"in v.answer)return false;const pixels=v.phase==="RESULT_PENDING"&&!!(image||derived);return v.provenance.evidence===(pixels?derived?.contentType==="video/mp4"?"VIDEO_FRAMES":"IMAGE_PIXELS":"METADATA_ONLY")&&(!pixels||(derived?!!receipt2:!!receipt))});function localAgentSnapshotFromContext(raw,includeImage=false){const c=ReviewIntelligenceContextResultSchema.parse(raw);if(c.reviewTarget.kind!=="IMAGE"||c.basis.target.kind!=="IMAGE"||c.ownerContext.semanticStatus!=="SUCCESS")throw Error("LOCAL_AGENT_CONTEXT_UNAVAILABLE");const t=c.reviewTarget.target,scope=c.basis.scope;if(!t.runtimeSucceeded||t.candidate.availability!=="AVAILABLE"||t.candidate.freshness!=="CURRENT_BASIS"||!t.productionRunnable||t.freshness!=="CURRENT_BASIS"||t.generationId!==c.basis.target.generationId||t.tenantId!==scope.tenantId||t.projectId!==scope.projectId||t.productionId!==scope.productionId||c.ownerContext.basis.tenantId!==scope.tenantId||c.ownerContext.basis.projectId!==scope.projectId||c.ownerContext.basis.productionId!==scope.productionId)throw Error("LOCAL_AGENT_CONTEXT_UNAVAILABLE");return LocalAgentSnapshotSchema.parse({basis:c.basis,productionRevision:c.ownerContext.basis.productionRevision,reviewVersion:t.reviewVersion,executionClass:t.executionClass,media:{artifactId:t.candidate.artifactId,representationId:t.candidate.representationId,checksumSha256:t.candidate.checksumSha256},requirements:t.requirements,...includeImage?{image:{contentType:t.candidate.contentType,byteSize:t.candidate.byteSize,width:t.candidate.width,height:t.candidate.height}}:{}})}function localAgentNativeProposal(raw){const v=LocalAgentReviewViewSchema.parse(raw);if(v.plan.snapshot.basis.target.kind!=="IMAGE"||v.plan.snapshot.evidence)throw Error("LOCAL_AGENT_MEDIA_PROPOSAL_REQUIRED");if(v.phase!=="RESULT_PENDING"||!v.answer)throw Error("LOCAL_AGENT_RESULT_UNAVAILABLE");const keys=new Set(v.answer.observations.map(o=>o.key));if(keys.size!==v.answer.observations.length||keys.size!==v.plan.snapshot.requirements.length||v.plan.snapshot.requirements.some(r=>!keys.has(r.key)))throw Error("LOCAL_AGENT_RESULT_UNAVAILABLE");const p=v.provenance;const pixels=p.evidence==="IMAGE_PIXELS";return ValidateReviewIntelligenceSchema.parse({basis:v.plan.snapshot.basis,proposal:{origin:{kind:"EXTERNAL_AGENT_HOST",label:p.reviewerLabel},summary:`${pixels?"IMAGE_PIXELS":"METADATA_ONLY; no visual inspection"}. Codex ${p.version}; model ${p.model}; effort ${p.reasoningEffort??"DEFAULT"}; binary ${p.binaryDigest}; draft ${v.plan.id}; plan ${v.plan.fingerprint}. ${v.answer.summary}`,evidence:pixels?[{id:"original_image",label:"Verified ORIGINAL PNG attachment",producer:"EXTERNAL_AGENT_HOST",kind:"IMAGE_PIXELS",media:v.plan.snapshot.media}]:[],review:{kind:"IMAGE",observations:v.answer.observations.map(o=>({...o,status:pixels&&"status"in o?o.status:"NOT_OBSERVABLE",confidence:pixels&&"confidence"in o?o.confidence:"UNCERTAIN",evidenceIds:pixels?["original_image"]:[]}))}}})}var LocalExecutionListInputSchema=LocalProjectScopeSchema.extend({after:z10.string().length(64).regex(/^[0-9a-f]{64}$/).nullable().default(null),limit:z10.int().min(1).max(16).default(8),includeCompleted:z10.boolean().optional(),includeProgress:z10.boolean().optional()});var LocalExecutionInspectInputSchema=LocalWorkScopeSchema.extend({includeProgress:z10.boolean().optional()});var LocalIpcCallSchema=z10.discriminatedUnion("operation",[z10.strictObject({operation:z10.literal("library.capability")}),z10.strictObject({operation:z10.literal("library.call"),input:LocalLibraryCallSchema}),z10.strictObject({operation:z10.literal("agent.discover"),binary:z10.string().min(1).max(4096).optional()}),z10.strictObject({operation:z10.literal("offline.workspace"),input:LocalOfflineCallSchema}),z10.strictObject({operation:z10.literal("workspace.inspect")}),z10.strictObject({operation:z10.literal("workspace.configure"),policy:LocalResourcePolicySchema,expectedRevision:z10.int().nonnegative()}),z10.strictObject({operation:z10.literal("workspace.activity"),idleSeconds:z10.int().min(0).max(86400),observedAt:z10.iso.datetime()}),z10.strictObject({operation:z10.literal("storage.clean")}),z10.strictObject({operation:z10.literal("diagnostics.read")}),z10.strictObject({operation:z10.literal("agent.grant"),grant:LocalAgentGrantSchema,approval:z10.string().regex(/^[a-f0-9]{64}$/)}),z10.strictObject({operation:z10.literal("agent.probe")}),z10.strictObject({operation:z10.literal("agent.revoke"),approval:z10.string().regex(/^[a-f0-9]{64}$/)}),z10.strictObject({operation:z10.literal("agent.prepare"),snapshot:LocalAgentSnapshotSchema}),z10.strictObject({operation:z10.literal("agent.start"),id:z10.uuid(),expectedRevision:LocalRevisionSchema,approval:z10.string().regex(/^[a-f0-9]{64}$/)}),z10.strictObject({operation:z10.literal("agent.inspect"),id:z10.uuid()}),z10.strictObject({operation:z10.literal("runtime.status"),includeDevice:z10.literal(true).optional()}),z10.strictObject({operation:z10.literal("runtime.doctor")}),z10.strictObject({operation:z10.literal("runtime.inventory")}),z10.strictObject({operation:z10.literal("session.issue"),tenantId:z10.uuid(),deviceId:z10.uuid(),expiresAt:z10.iso.datetime({offset:true})}),z10.strictObject({operation:z10.literal("runtime.stop"),expectedRuntimeRevision:LocalRevisionSchema}),z10.strictObject({operation:z10.literal("execution.inspect"),input:LocalExecutionInspectInputSchema}),z10.strictObject({operation:z10.literal("execution.list"),input:LocalExecutionListInputSchema}),z10.strictObject({operation:z10.literal("update.check")}),z10.strictObject({operation:z10.literal("update.prepare"),targetVersion:LocalPackageVersionSchema,expectedRuntimeRevision:LocalRevisionSchema}),z10.strictObject({operation:z10.literal("update.apply"),planId:LocalIdSchema,targetVersion:LocalPackageVersionSchema,expectedRuntimeRevision:LocalRevisionSchema})]);var LocalNextActionSchema=z10.strictObject({call:LocalIpcCallSchema,availability:z10.enum(["AVAILABLE","BLOCKED"]),reason:z10.enum(["READY","INSTALL_REQUIRED","AUTHORIZATION_REQUIRED","VERSION_INCOMPATIBLE","UPDATE_AVAILABLE","RECOVERY_REQUIRED"])});var LocalIpcRequestSchema=z10.strictObject({protocol:z10.literal("NVS_LOCAL_IPC_V1"),requestId:LocalIdSchema,call:LocalIpcCallSchema});var LocalVersionReportSchema=z10.strictObject({component:z10.enum(["CLI","SDK","MCP","RUNTIME","MEDIA_TOOLS"]),installedVersion:LocalPackageVersionSchema.nullable(),runningVersion:LocalPackageVersionSchema.nullable(),availableVersion:LocalPackageVersionSchema.nullable(),executablePath:z10.string().min(1).max(4096).nullable(),installOwner:z10.enum(["NPM_GLOBAL","PROJECT","NPX","MANAGED","TARBALL","UNKNOWN"])});var LocalRuntimeStatusSchema=z10.strictObject({protocol:z10.literal("NVS_LOCAL_IPC_V1"),runtimeRevision:LocalRevisionSchema,state:z10.enum(["IDLE","EXECUTING","DRAINING","RECOVERY_REQUIRED"]),journalSchemaVersion:z10.literal(1),workProtocols:z10.array(z10.enum(["NVS_LOCAL_WORK_V1","NVS_LOCAL_WORK_V2"])).min(1).max(2),versions:z10.array(LocalVersionReportSchema).max(8),deviceAuthority:z10.strictObject({tenantId:z10.uuid(),deviceId:z10.uuid(),origin:z10.url()}).optional(),capabilityMismatch:CapabilityVersionMismatchSchema.optional(),deviceCapabilities:z10.strictObject({deviceRevision:LocalRevisionSchema,tenantMediaValidation:z10.boolean(),tenantMediaProcessing:z10.boolean(),processorCapabilities:z10.array(TenantProcessorKindSchema).max(TenantProcessorKindSchema.options.length)}).optional(),nextActions:z10.array(LocalNextActionSchema).max(8)});var LocalDoctorReportSchema=z10.strictObject({mode:z10.enum(["MANAGED","INSTALLED"]),availability:z10.enum(["AVAILABLE","UNAVAILABLE"]),reason:z10.enum(["QUALIFIED_PROCESS_TOOLS","MANAGED_TOOLS_MISSING","TOOL_QUALIFICATION_FAILED"]),nativeExecutionReady:z10.boolean(),executionProfiles:z10.array(z10.enum(["ROUGH_CUT_PREVIEW_V1","STUDIO_MEDIA_V2","AUDIO_MEDIA_V1"])).max(3).optional(),tools:z10.array(z10.strictObject({name:z10.enum(["FFMPEG","FFPROBE"]),path:z10.string().min(1).max(4096),version:z10.string().min(1).max(200),digest:z10.string().regex(/^[0-9a-f]{64}$/)})).max(2)});var LocalExecutionInspectionSchema=z10.strictObject({binding:LocalLeaseBindingSchema,revision:LocalRevisionSchema,phase:z10.enum(["STAGED","RUNNING","RECOVERY_REQUIRED","OUTPUT_PENDING","RECEIPT_RECORDED","FENCED"]),checkpoint:z10.enum(["ADOPTED","SOURCES_READY","PROCESS_STARTED","OUTPUT_STAGED"]),progress:LocalExecutionProgressSchema.optional()});var LocalExecutionPageSchema=z10.strictObject({items:z10.array(LocalExecutionInspectionSchema).max(16),nextCursor:z10.string().length(64).regex(/^[0-9a-f]{64}$/).nullable()});var LocalIpcErrorCodeSchema=z10.enum(["FORBIDDEN","INVALID_INPUT","FRAME_LIMIT","BUSY","AUTHORIZATION_REQUIRED","REVISION_CONFLICT","CAPABILITY_UNAVAILABLE","INTERNAL_OPERATIONAL_FAILURE","AGENT_APPROVAL_REQUIRED","AGENT_RUNTIME_UNAVAILABLE","AGENT_LOGIN_REQUIRED","AGENT_VERSION_UNQUALIFIED","AGENT_GRANT_REQUIRED","AGENT_OUTCOME_UNKNOWN","AGENT_IMAGE_REQUIRED","AGENT_IMAGE_INVALID","AGENT_IMAGE_BUDGET_EXCEEDED","AGENT_IMAGE_AUTHORIZATION_REQUIRED","CACHE_QUOTA_EXCEEDED","LIBRARY_NOT_FOUND","LIBRARY_CONFLICT","LIBRARY_BYTES_INVALID","LIBRARY_ACCESS_DENIED","LIBRARY_SYNC_REQUIRED","LIBRARY_SYNC_UNAVAILABLE","LIBRARY_QUOTA_EXCEEDED"]);var LocalIpcResponseSchema=z10.discriminatedUnion("semanticStatus",[z10.strictObject({protocol:z10.literal("NVS_LOCAL_IPC_V1"),requestId:LocalIdSchema,semanticStatus:z10.literal("SUCCESS"),data:z10.union([LocalLibraryCapabilitySchema,LocalLibraryUsageSchema,LocalLibraryItemSchema,LocalLibraryPageSchema,LocalLibraryProjectionSchema,LocalLibraryProjectionPageSchema,LocalLibraryReadReplySchema,LocalWorkspaceInspectionSchema,LocalDiagnosticsSchema,LocalOfflinePageSchema,LocalRuntimeStatusSchema,LocalDoctorReportSchema,LocalExecutionInspectionSchema.nullable(),z10.strictObject({state:z10.literal("DRAINING"),inventory:LocalManagementInventorySchema.optional(),backupPath:z10.string().min(1).max(4096).optional()}),LocalSessionConnectorSchema,LocalManagementInventorySchema,LocalExecutionPageSchema,LocalAgentProbeSchema,LocalAgentDiscoverySchema,LocalAgentReviewViewSchema])}),z10.strictObject({protocol:z10.literal("NVS_LOCAL_IPC_V1"),requestId:LocalIdSchema.nullable(),semanticStatus:z10.enum(["BLOCKED","INVALID_INPUT"]),error:z10.strictObject({code:LocalIpcErrorCodeSchema})})]);var LocalMcpToolNameSchema=z11.enum(["local_navigate","local_capability_describe","local_runtime_status","local_execution_list","local_execution_inspect","local_update_check","local_library_list","local_library_get"]);var LocalMcpActionSchema=z11.strictObject({tool:LocalMcpToolNameSchema,arguments:z11.record(z11.string(),z11.unknown()),availability:z11.enum(["AVAILABLE","BLOCKED"]).optional(),reason:z11.string().max(100).optional()});var LocalMcpNavigationSchema=z11.strictObject({location:z11.literal("LOCAL"),state:z11.enum(["UNAVAILABLE","IDLE","EXECUTING","DRAINING","RECOVERY_REQUIRED"]),deviceAuthority:LocalRuntimeStatusSchema.shape.deviceAuthority,groups:z11.array(z11.strictObject({id:z11.string().max(40),label:z11.string().max(100),tools:z11.array(LocalMcpToolNameSchema).max(6)})).max(4),nextActions:z11.array(z11.union([LocalMcpActionSchema,LocalClientNextActionSchema])).max(16)});var LocalMcpExecutionPageSchema=LocalExecutionPageSchema.extend({nextActions:z11.array(LocalMcpActionSchema).max(16)});var LocalMcpInspectionSchema=z11.strictObject({location:z11.literal("LOCAL"),execution:LocalExecutionInspectionSchema.nullable(),nextActions:z11.array(LocalMcpActionSchema).max(4)});var LocalMcpUpdateSchema=z11.strictObject({location:z11.literal("LOCAL"),running:z11.array(LocalVersionReportSchema).max(8),available:z11.array(LocalRuntimeDescriptorSchema).max(32),nextActions:z11.array(LocalClientNextActionSchema).max(4)});var LocalMcpDescriptionSchema=z11.strictObject({location:z11.literal("LOCAL"),tool:LocalMcpToolNameSchema,schema:z11.object({name:LocalMcpToolNameSchema,description:z11.string(),inputSchema:z11.record(z11.string(),z11.unknown())}).passthrough()});var LocalMcpFailureSchema=z11.strictObject({semanticStatus:z11.enum(["BLOCKED","INVALID_INPUT"]),error:z11.strictObject({code:z11.enum(["AUTHORIZATION_REQUIRED","FORBIDDEN","LOCAL_RUNTIME_UNAVAILABLE","RELEASE_UNAVAILABLE","VERSION_INCOMPATIBLE","INVALID_INPUT","LOCAL_CAPABILITY_UNAVAILABLE"]),outcome:z11.literal("NO_WRITE")}),nextActions:z11.array(LocalClientNextActionSchema).max(4)});var LocalMcpOutputSchemas={local_library_list:LocalLibraryProjectionPageSchema.extend({location:z11.literal("LOCAL")}),local_library_get:z11.strictObject({location:z11.literal("LOCAL"),item:LocalLibraryProjectionSchema.nullable()}),local_navigate:LocalMcpNavigationSchema,local_capability_describe:LocalMcpDescriptionSchema,local_runtime_status:LocalRuntimeStatusSchema.omit({nextActions:true}).extend({nextActions:z11.array(LocalMcpActionSchema).max(8)}),local_execution_list:LocalMcpExecutionPageSchema,local_execution_inspect:LocalMcpInspectionSchema,local_update_check:LocalMcpUpdateSchema};import{z as z12}from"zod";var uuid=z12.uuid().transform(value=>value.toLowerCase());var AgentComponentScopeSchema=DeviceEnrollmentScopeSchema.extend({tenantId:uuid,principalId:uuid,grantId:uuid});var AgentComponentStatusSchema=ComponentStatusSchema.extend({component:z12.literal("HOST_RUNTIME"),source:z12.literal("OWNED_INSTALLATION_IPC"),componentHome:z12.string().min(1).max(4096),initialized:z12.boolean(),installationRevision:z12.int().nonnegative(),installedVersion:z12.string().min(1).max(120).nullable(),runningVersion:z12.string().min(1).max(120).nullable(),loginService:z12.enum(["NONE","REGISTERED","STALE","INCOMPLETE","UNKNOWN"]),lastRequestId:z12.uuid().nullable(),deviceId:z12.uuid().nullable(),capabilityMismatch:CapabilityVersionMismatchSchema.optional()});import{z as z14}from"zod";function localAgentMediaSnapshot(raw){const c=ReviewIntelligenceContextResultSchema.parse(raw),r=c.reviewTarget,t=r.target,scope=c.basis.scope;if(c.ownerContext.semanticStatus!=="SUCCESS"||!t.productionRunnable||t.freshness!=="CURRENT_BASIS"||t.tenantId!==scope.tenantId||t.projectId!==scope.projectId||t.productionId!==scope.productionId||c.ownerContext.basis.tenantId!==scope.tenantId||c.ownerContext.basis.projectId!==scope.projectId||c.ownerContext.basis.productionId!==scope.productionId||r.kind!==c.basis.target.kind)throw Error("LOCAL_AGENT_CONTEXT_UNAVAILABLE");let media,descriptor;if(r.kind==="ROUGH_CUT"){if(!r.target.inspectable||c.basis.target.kind!=="ROUGH_CUT"||r.target.renderId!==c.basis.target.renderId)throw Error("LOCAL_AGENT_CONTEXT_UNAVAILABLE");media=r.target.basis;descriptor={...r.target.technical,contentType:"video/mp4"}}else if(r.kind==="PROGRAMMATIC"){if(!r.target.runtimeSucceeded||r.target.media.availability!=="AVAILABLE"||c.basis.target.kind!=="PROGRAMMATIC"||r.target.renderId!==c.basis.target.renderId)throw Error("LOCAL_AGENT_CONTEXT_UNAVAILABLE");media=r.target.media;descriptor=r.target.media}else{if(!r.target.runtimeSucceeded||r.target.candidate.availability!=="AVAILABLE"||r.target.candidate.freshness!=="CURRENT_BASIS"||!("generationId"in c.basis.target)||r.target.generationId!==c.basis.target.generationId)throw Error("LOCAL_AGENT_CONTEXT_UNAVAILABLE");media=r.target.candidate;descriptor=r.target.candidate}const video=descriptor.contentType==="video/mp4";return LocalAgentSnapshotSchema.parse({basis:c.basis,productionRevision:c.ownerContext.basis.productionRevision,reviewVersion:t.reviewVersion,executionClass:t.executionClass,media:{artifactId:media.artifactId,representationId:media.representationId,checksumSha256:media.checksumSha256},requirements:t.requirements,evidence:{profile:"NVS_AGENT_DERIVED_EVIDENCE_V1",contentType:descriptor.contentType,byteSize:descriptor.byteSize,width:descriptor.width,height:descriptor.height,...video&&"durationMs"in descriptor?{durationMs:descriptor.durationMs,frameRate:descriptor.frameRate,hasAudio:descriptor.hasAudio}:{}}})}function localAgentMediaProposal(raw){const v=LocalAgentReviewViewSchema.parse(raw),s=v.plan.snapshot;if(!s.evidence)return localAgentNativeProposal(v);if(v.phase!=="RESULT_PENDING"||!v.answer||!v.evidenceReceipt||s.basis.target.kind==="ROUGH_CUT")throw Error("LOCAL_AGENT_FULL_TEMPORAL_INSPECTION_REQUIRED");const video=s.evidence.contentType==="video/mp4",p=v.provenance,id=video?"sampled_frames":"normalized_image";const observations=v.answer.observations.map(o=>{const requirement=s.requirements.find(r=>r.key===o.key);if(!requirement)throw Error("LOCAL_AGENT_RESULT_UNAVAILABLE");const sound="family"in requirement&&requirement.family==="SOUND"||/^(audio|sound):/.test(requirement.key);return{...o,status:video||!("status"in o)?"NOT_OBSERVABLE":o.status,confidence:video||!("confidence"in o)?"UNCERTAIN":o.confidence,observed:video?sound?"This draft has no listening evidence.":"Sampled frames are advisory. This draft has no playback coverage.":o.observed,evidenceIds:video&&sound?[]:[id],..."interval"in requirement&&requirement.interval?{interval:requirement.interval}:{}}});return ValidateReviewIntelligenceSchema.parse({basis:s.basis,proposal:{origin:{kind:"EXTERNAL_AGENT_HOST",label:p.reviewerLabel},summary:`Advisory ${video?"sampled frame observations. Full playback, listening and transcription are unavailable":"normalized original image"}. ${p.inference} via ${p.adapter} using Codex ${p.version}, model ${p.model}, effort ${p.reasoningEffort??"DEFAULT"}, binary ${p.binaryDigest}. Source ${s.media.checksumSha256}, attachment ${v.evidenceReceipt.attachment.checksumSha256}, draft ${v.plan.id}, plan ${v.plan.fingerprint}. ${v.answer.summary}`,evidence:observations.some(o=>o.evidenceIds.length)?[{id,label:video?"Ordered verified source frame samples":"Verified normalized source image",producer:"EXTERNAL_AGENT_HOST",media:s.media,...video?{kind:"VIDEO_FRAMES",timestampsMs:v.evidenceReceipt.timestampsMs}:{kind:"IMAGE_PIXELS"}}]:[],review:{kind:s.basis.target.kind,observations}}})}import{z as z13}from"zod";var CpuSpeechPrepareInputSchema=z13.strictObject({profileId:z13.literal(kokoroCpuProfile.id).default(kokoroCpuProfile.id),voiceIds:z13.array(CpuSpeechInputSchema.shape.voiceId).min(1).max(8).refine(v=>new Set(v).size===v.length).default([0,45])});var CpuSpeechPreparedSchema=z13.strictObject({semanticStatus:z13.literal("PREPARED"),selection:CpuSpeechInstallationSchema,capability:CpuSpeechCapabilitySchema,reused:z13.strictObject({engine:z13.boolean(),model:z13.boolean()})});function localBudget(timeoutMs,parent,ceiling=6e4){if(!Number.isInteger(timeoutMs)||timeoutMs<1||timeoutMs>ceiling)throw Error("LOCAL_DEADLINE_INVALID");const controller=new AbortController,timer=setTimeout(()=>controller.abort(),timeoutMs);return{signal:parent?AbortSignal.any([parent,controller.signal]):controller.signal,close:()=>clearTimeout(timer)}}async function localAbortable(work,signal){if(signal.aborted)void work.catch(()=>{});signal.throwIfAborted();return new Promise((resolve,reject)=>{const abort=()=>reject(Error("LOCAL_DEADLINE"));signal.addEventListener("abort",abort,{once:true});work.then(v=>{signal.removeEventListener("abort",abort);resolve(v)},e=>{signal.removeEventListener("abort",abort);reject(e)});if(signal.aborted)abort()})}var NativeStudioLocalDeviceClient=class{constructor(options){this.options=options;const u=new URL(options.baseUrl);if(u.username||u.password||u.search||u.hash||u.pathname!=="/"||u.protocol!=="https:"&&!(u.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(u.hostname)))throw new NativeStudioSdkError("INVALID_INPUT","INVALID_INPUT","NO_WRITE");this.origin=u.origin}options;origin;async command(route,raw,input,output,signal,readOnly=false,validate){let started=false;const budget=localBudget(15e3,signal);try{const i=input.parse(raw);if((i.tenantId??i.input?.tenantId)!==this.options.tenantId)throw Error();budget.signal.throwIfAborted();const authorization=await localAbortable(Promise.resolve().then(()=>this.options.authorization()),budget.signal);if(authorization!==authorization.trim()||!/^Bearer [A-Za-z0-9._~-]{1,8192}$/.test(authorization))throw Error();const body=JSON.stringify(i);if(Buffer.byteLength(body)>65536)throw Error();budget.signal.throwIfAborted();started=true;const r=await fetch(this.origin+"/v1/local-execution/"+route,{method:"POST",headers:{authorization,"content-type":"application/json","x-native-tenant-id":this.options.tenantId},body,redirect:"error",signal:budget.signal});if(!r.ok){await r.body?.cancel();throw new NativeStudioSdkError(r.status===403||r.status===401?"FORBIDDEN":"LOCAL_COMMAND_REFUSED","BLOCKED",readOnly?"NO_WRITE":r.status>=500?"UNKNOWN":"REJECTED",r.status)}const parts=[];let size=0;for await(const b of r.body??[]){size+=b.length;if(size>262144)throw Error();parts.push(b)}const value=output.parse(JSON.parse(Buffer.concat(parts).toString()));validate?.(i,value);if(value&&typeof value==="object"){const result=value,request4=i;for(const key of["tenantId","projectId","deviceId"])if(key in result&&key in request4&&result[key]!==request4[key])throw Error()}return value}catch(e){if(e instanceof NativeStudioSdkError)throw e;throw new NativeStudioSdkError(started?readOnly?"LOCAL_QUERY_UNAVAILABLE":"LOCAL_COMMAND_UNKNOWN":"INVALID_INPUT",started?"BLOCKED":"INVALID_INPUT",started&&!readOnly?"UNKNOWN":"NO_WRITE")}finally{budget.close()}}enroll(input,signal){return this.command("devices/enroll",input,EnrollLocalDeviceSchema,LocalDeviceViewSchema,signal,false,(original,result)=>assertManagementReceipt("device.enroll",original,result))}async managementReceipt(input,signal){const parsedInput=LocalDeviceManagementCommandSchema.safeParse(input);if(!parsedInput.success)throw new NativeStudioSdkError("INVALID_INPUT","INVALID_INPUT","NO_WRITE");const parsed=parsedInput.data;const value=await this.command("management-receipt",input,LocalDeviceManagementCommandSchema,LocalManagementReceiptSchema,signal,true);return checkedManagementReceipt(parsed,value)}revokeDevice(input,signal){return this.command("devices/revoke",input,RevokeLocalDeviceSchema,z14.strictObject({semanticStatus:z14.literal("SUCCESS")}),signal)}startPreview(input,signal){return this.command("previews",input,StartLocalPreviewSchema,LocalPreviewAdmissionSchema,signal)}startFinal(input,signal){return this.command("final-renders",input,StartLocalFinalRenderSchema,LocalFinalRenderAdmissionSchema,signal)}};import{randomUUID,createHash}from"node:crypto";import{request}from"node:http";import{z as z15}from"zod";import{constants}from"node:fs";import{open,realpath}from"node:fs/promises";async function checkedLocalDirectory(path){await privateDirectory(path);return realpath(path)}async function readLocalCredential(path,maximum=32768){await privateAccess(path,"file");const file=await open(path,constants.O_RDONLY|constants.O_NOFOLLOW);try{const stat=await file.stat();if(!stat.isFile()||stat.nlink!==1||process.platform!=="win32"&&(stat.uid!==process.getuid?.()||stat.mode&63)||stat.size>maximum)throw Error("LOCAL_CREDENTIAL_INVALID");const bytes=Buffer.alloc(Math.min(maximum+1,stat.size+1));let used=0;while(used<bytes.length){const part=await file.read(bytes,used,bytes.length-used,null);if(!part.bytesRead)break;used+=part.bytesRead}if(used>stat.size)throw Error("LOCAL_CREDENTIAL_INVALID");if(used>maximum)throw Error("LOCAL_CREDENTIAL_INVALID");return bytes.subarray(0,used)}finally{await file.close()}}async function stageAgentImage(options,view,input,signal){const budget=localBudget(view.plan.snapshot.evidence?18e4:options.timeoutMs??1e4,signal,view.plan.snapshot.evidence?18e4:6e4);let dispatched=false;try{budget.signal.throwIfAborted();if(input.byteLength>134217728)throw Error();const bytes=Buffer.from(input),snapshot=view.plan.snapshot,id=z15.uuid().parse(view.plan.id),requestId=randomUUID();if(!snapshot.image&&!snapshot.evidence||bytes.length!==(snapshot.evidence??snapshot.image).byteSize||bytes.length>(snapshot.evidence?134217728:8388608)||createHash("sha256").update(bytes).digest("hex")!==snapshot.media.checksumSha256)throw Error();const root=await checkedLocalDirectory(options.stateDirectory),path=localSocketPath(root);await privateAccess(path,"pipe");const auth=await localAbortable(Promise.resolve().then(options.authorization),budget.signal);budget.signal.throwIfAborted();if(!/^Bearer [A-Za-z0-9_-]{43}$/.test(auth))throw Error();const reply=await new Promise((resolve,reject)=>{const req=request({socketPath:path,path:"/ipc/v1/agent-images/"+id,method:"PUT",signal:budget.signal,headers:{authorization:auth,"content-type":snapshot.evidence?"application/octet-stream":"image/png","content-length":bytes.length,"x-nvs-request-id":requestId}},res=>{let size=0;const chunks=[];res.on("error",reject);res.on("aborted",()=>reject(Error()));res.on("data",b=>{size+=b.length;if(size>262144)req.destroy(Error());else chunks.push(b)});res.on("end",()=>{try{resolve(JSON.parse(Buffer.concat(chunks).toString()))}catch{reject(Error())}})});req.on("error",reject);dispatched=true;req.end(bytes)});const response=LocalIpcResponseSchema.parse(reply);if(response.requestId!==requestId&&!(response.requestId===null&&response.semanticStatus!=="SUCCESS"&&["BUSY","FORBIDDEN"].includes(response.error.code)))throw Error();if(response.semanticStatus!=="SUCCESS")throw new NativeStudioSdkError(response.error.code,response.semanticStatus,response.error.code==="INTERNAL_OPERATIONAL_FAILURE"?"UNKNOWN":"REJECTED");const v=LocalAgentReviewViewSchema.parse(response.data),receipt=v.evidenceReceipt??v.imageReceipt;if(v.plan.id!==id||canonicalLocalJson(v.plan)!==canonicalLocalJson(view.plan)||v.revision<view.revision||v.phase!=="PREPARED"||!receipt||receipt.draftId!==id||canonicalLocalJson(receipt.media)!==canonicalLocalJson(snapshot.media)||!snapshot.evidence&&canonicalLocalJson({contentType:v.imageReceipt?.contentType,byteSize:v.imageReceipt?.byteSize,width:v.imageReceipt?.width,height:v.imageReceipt?.height})!==canonicalLocalJson(snapshot.image))throw Error();return v}catch(e){if(e instanceof NativeStudioSdkError)throw e;throw new NativeStudioSdkError("LOCAL_AGENT_IMAGE_TRANSFER_FAILED","BLOCKED",dispatched?"UNKNOWN":"NO_WRITE")}finally{budget.close()}}var NativeStudioLocalWorkspaceClient=class{constructor(client){this.client=client}client;async offline(raw,signal){return LocalOfflinePageSchema.parse(await this.client.call({operation:"offline.workspace",input:LocalOfflineCallSchema.parse(raw)},signal))}async inspect(signal){return LocalWorkspaceInspectionSchema.parse(await this.client.call({operation:"workspace.inspect"},signal))}async configure(raw,expectedRevision,signal){const policy=LocalResourcePolicySchema.parse(raw);return LocalWorkspaceInspectionSchema.parse(await this.client.call({operation:"workspace.configure",policy,expectedRevision},signal))}async observeActivity(idleSeconds,observedAt,signal){return LocalWorkspaceInspectionSchema.parse(await this.client.call({operation:"workspace.activity",idleSeconds,observedAt},signal))}async clean(signal){return LocalWorkspaceInspectionSchema.parse(await this.client.call({operation:"storage.clean"},signal))}async diagnostics(signal){return LocalDiagnosticsSchema.parse(await this.client.call({operation:"diagnostics.read"},signal))}};import{Readable as Readable2}from"node:stream";import{createHash as createHash2}from"node:crypto";import{request as request2}from"node:http";async function libraryTransport(options,input,signal){const budget=localBudget(18e4,signal,18e4);let started=false;try{const root=await checkedLocalDirectory(options.stateDirectory),socketPath=localSocketPath(root);await privateAccess(socketPath,"pipe");const authorization=await localAbortable(Promise.resolve().then(()=>options.authorization()),budget.signal);if(!/^Bearer [A-Za-z0-9_-]{43}$/.test(authorization))throw Error();budget.signal.throwIfAborted();const response=await new Promise((resolve,reject)=>{const req=request2({socketPath,method:input.method,path:input.path,signal:budget.signal,headers:{authorization,...input.headers}},resolve);req.on("error",reject);started=true;if(input.body){input.body.once("error",error=>req.destroy(error));input.body.pipe(req)}else req.end()});return{response,close:()=>{budget.close();response.destroy();input.body?.destroy()}}}catch(error){budget.close();input.body?.destroy();if(error instanceof NativeStudioSdkError)throw error;throw new NativeStudioSdkError("LOCAL_RUNTIME_UNAVAILABLE","BLOCKED",started&&input.method==="PUT"?"UNKNOWN":"NO_WRITE")}}import{Readable}from"node:stream";var libraryRange=/^bytes=(?:[0-9]+-[0-9]*|-[0-9]+)$/;function expectedRange(range,total){if(!range)return{length:total,header:void 0};const match=/^bytes=(\d*)-(\d*)$/.exec(range);if(!match||!total)throw new NativeStudioSdkError("LIBRARY_RANGE_INVALID","INVALID_INPUT","NO_WRITE",416);const start=match[1]?Number(match[1]):Math.max(0,total-Number(match[2]));const end=match[1]&&match[2]?Math.min(total-1,Number(match[2])):total-1;if(!Number.isSafeInteger(start)||!Number.isSafeInteger(end)||start<0||start>=total||end<start)throw new NativeStudioSdkError("LIBRARY_RANGE_INVALID","INVALID_INPUT","NO_WRITE",416);return{length:end-start+1,header:`bytes ${start}-${end}/${total}`}}async function readLibraryMedia(options,raw,input={},signal){const value=LocalLibraryGetSchema.parse(raw),method=input.method??"GET";if(method!=="GET"&&method!=="HEAD")throw new NativeStudioSdkError("INVALID_INPUT","INVALID_INPUT","NO_WRITE");if(input.range!==void 0&&(input.range.length>100||!libraryRange.test(input.range)))throw new NativeStudioSdkError("LIBRARY_RANGE_INVALID","INVALID_INPUT","NO_WRITE",416);const expected=expectedRange(input.range,value.reference.byteSize);const header=Buffer.from(JSON.stringify(value)).toString("base64url");if(header.length>3072)throw new NativeStudioSdkError("INVALID_INPUT","INVALID_INPUT","NO_WRITE");const transfer=await libraryTransport(options,{method,path:"/ipc/v1/library/read",headers:{"x-nvs-library-read":header,...input.range?{range:input.range}:{}}},signal);const{response}=transfer;try{if(response.statusCode===416)throw new NativeStudioSdkError("LIBRARY_RANGE_INVALID","INVALID_INPUT","NO_WRITE",416);const status=response.statusCode,contentLength=Number(response.headers["content-length"]);if(![200,206].includes(status??0)||!Number.isSafeInteger(contentLength)||contentLength<0||contentLength>value.reference.byteSize||response.headers["content-type"]!==value.reference.contentType)throw Error();const contentRange=response.headers["content-range"];if(status===206){if(!input.range||contentRange!==expected.header||contentLength!==expected.length)throw Error()}else if(input.range||contentRange||contentLength!==value.reference.byteSize)throw Error();const stream=Readable.from((async function*(){let size=0;try{for await(const bytes of response){size+=bytes.length;if(size>contentLength||method==="HEAD")throw Error();yield bytes}if(method!=="HEAD"&&size!==contentLength)throw Error()}finally{transfer.close()}})());stream.once("close",transfer.close);return{stream,contentType:value.reference.contentType,byteSize:value.reference.byteSize,contentLength,httpStatus:status,...contentRange?{contentRange:String(contentRange)}:{}}}catch(error){transfer.close();if(error instanceof NativeStudioSdkError)throw error;throw new NativeStudioSdkError("LOCAL_LIBRARY_MEDIA_INVALID","BLOCKED","NO_WRITE")}}var NativeStudioLocalLibraryClient=class{constructor(client){this.client=client}client;async capability(signal){return LocalLibraryCapabilitySchema.parse(await this.client.call({operation:"library.capability"},signal))}async call(raw,signal){const input=LocalLibraryCallSchema.parse(raw),data=await this.client.call({operation:"library.call",input},signal);const schema=input.action==="list"?LocalLibraryPageSchema:input.action==="scoped-list"?LocalLibraryProjectionPageSchema:input.action==="scoped-get"?LocalLibraryProjectionSchema.nullable():input.action==="usage"?LocalLibraryUsageSchema:input.action==="read"?LocalLibraryReadReplySchema:["get","import-receipt"].includes(input.action)?LocalLibraryItemSchema.nullable():LocalLibraryItemSchema;const result=schema.parse(data);if(result&&"items"in result&&"limit"in input&&result.items.length>input.limit)throw new NativeStudioSdkError("LOCAL_SCOPE_INVALID","BLOCKED","NO_WRITE");if((input.action==="list"||input.action==="scoped-list")&&result&&"items"in result){for(const item of result.items){const label=input.action==="list"&&"title"in item?item.title:"metadata"in item?item.metadata?.label:void 0;if(input.mediaCategory&&mediaCategoryOf(item.reference.contentType)!==input.mediaCategory||input.search&&!label?.toLowerCase().includes(input.search.toLowerCase()))throw new NativeStudioSdkError("LOCAL_SCOPE_INVALID","BLOCKED","NO_WRITE")}}if(input.action==="read"){const value=LocalLibraryReadReplySchema.parse(result),bytes=Buffer.from(value.contentBase64,"base64");const length=Math.min(input.length,Math.max(0,input.reference.byteSize-input.offset));if(value.offset!==input.offset||bytes.toString("base64")!==value.contentBase64||bytes.length!==length||value.complete!==input.offset+length>=input.reference.byteSize)throw new NativeStudioSdkError("LOCAL_LIBRARY_MEDIA_INVALID","BLOCKED","NO_WRITE")}const refs=result&&typeof result==="object"&&"items"in result?result.items.map(item=>item.reference):result&&typeof result==="object"&&"reference"in result?[result.reference]:[];for(const ref of refs){if("reference"in input&&canonicalLocalJson(ref)!==canonicalLocalJson(input.reference)||"tenantId"in input&&(ref.tenantId!==input.tenantId||input.projectId!==void 0&&ref.projectId!==input.projectId||ref.deviceId!==input.deviceId))throw new NativeStudioSdkError("LOCAL_SCOPE_INVALID","BLOCKED","NO_WRITE")}if("ownerKey"in input&&input.ownerKey&&result&&typeof result==="object"){const owned="items"in result?result.items:"ownerKey"in result?[result]:[];if(owned.some(item=>"ownerKey"in item&&item.ownerKey!==input.ownerKey))throw new NativeStudioSdkError("LOCAL_SCOPE_INVALID","BLOCKED","NO_WRITE")}return result}async import(raw,bytes,signal){const input=LocalLibraryImportSchema.parse(raw),header=Buffer.from(JSON.stringify(input)).toString("base64url");if(header.length>3072)throw new NativeStudioSdkError("INVALID_INPUT","INVALID_INPUT","NO_WRITE");const body=Readable2.from((async function*(){let count=0;const hash=createHash2("sha256");for await(const chunk of bytes){const part=Buffer.from(chunk);count+=part.length;if(count>input.reference.byteSize)throw Error("LOCAL_FILE_CHANGED");hash.update(part);yield part}if(count!==input.reference.byteSize||hash.digest("hex")!==input.reference.checksumSha256)throw Error("LOCAL_FILE_CHANGED")})());const transfer=await libraryTransport(this.client.options,{method:"PUT",path:"/ipc/v1/library/import",body,headers:{"x-nvs-request-id":input.requestId,"x-nvs-library-import":header,"content-type":"application/octet-stream","content-length":input.reference.byteSize}},signal);try{let size=0;const parts=[];for await(const part of transfer.response){size+=part.length;if(size>262144)throw Error();parts.push(part)}const reply=LocalIpcResponseSchema.parse(JSON.parse(Buffer.concat(parts).toString()));if(reply.semanticStatus!=="SUCCESS")throw new NativeStudioSdkError(reply.error.code,reply.semanticStatus,reply.error.code==="INTERNAL_OPERATIONAL_FAILURE"?"UNKNOWN":"REJECTED");const item=LocalLibraryItemSchema.parse(reply.data);if(reply.requestId!==input.requestId||canonicalLocalJson(item.reference)!==canonicalLocalJson(input.reference)||item.ownerKey!==input.ownerKey||item.title!==input.title)throw Error();return item}catch(error){if(error instanceof NativeStudioSdkError)throw error;throw new NativeStudioSdkError("LOCAL_LIBRARY_IMPORT_UNKNOWN","BLOCKED","UNKNOWN")}finally{transfer.close()}}media(raw,input={},signal){return readLibraryMedia(this.client.options,raw,input,signal)}};import{randomUUID as randomUUID2}from"node:crypto";import{request as request3}from"node:http";var NativeStudioLocalRuntimeClient=class _NativeStudioLocalRuntimeClient{constructor(options){this.options=options}options;workspace=new NativeStudioLocalWorkspaceClient(this);library=new NativeStudioLocalLibraryClient(this);static async fromConnector(path){const initial=LocalSessionConnectorSchema.parse(JSON.parse((await readLocalCredential(path)).toString()));return new _NativeStudioLocalRuntimeClient({stateDirectory:initial.stateDirectory,device:{tenantId:initial.tenantId,deviceId:initial.deviceId},authorization:async()=>{const current=LocalSessionConnectorSchema.parse(JSON.parse((await readLocalCredential(path)).toString()));if(current.stateDirectory!==initial.stateDirectory||current.tenantId!==initial.tenantId||current.deviceId!==initial.deviceId||Date.parse(current.expiresAt)>Date.parse(initial.expiresAt)||Date.parse(current.expiresAt)<=Date.now())throw Error("LOCAL_AUTHORIZATION_REQUIRED");return"Bearer "+current.credential}})}async call(call,signal){let started=false;const budget=localBudget(this.options.timeoutMs??(["runtime.doctor","agent.probe","agent.grant","agent.start"].includes(call.operation)?6e4:3e4),signal);const readOnly=["runtime.status","runtime.doctor","runtime.inventory","execution.inspect","execution.list","update.check","agent.probe","agent.discover","agent.inspect","workspace.inspect","diagnostics.read","library.capability"].includes(call.operation)||call.operation==="library.call"&&["list","get","usage","read","import-receipt","scoped-list","scoped-get","sync"].includes(call.input.action);try{const input=LocalIpcRequestSchema.parse({protocol:"NVS_LOCAL_IPC_V1",requestId:randomUUID2(),call});const root=await checkedLocalDirectory(this.options.stateDirectory);const path=localSocketPath(root);await privateAccess(path,"pipe");budget.signal.throwIfAborted();const auth=await localAbortable(Promise.resolve().then(()=>this.options.authorization()),budget.signal);budget.signal.throwIfAborted();if(auth.length!==50||!/^Bearer [A-Za-z0-9_-]{43}$/.test(auth))throw Error();const body=JSON.stringify(input);const reply=await new Promise((resolve,reject)=>{const abort=budget.signal;const req=request3({socketPath:path,method:"POST",path:"/ipc/v1",signal:abort,headers:{authorization:auth,"content-type":"application/json","content-length":Buffer.byteLength(body)}},res=>{const chunks=[];let length=0;res.on("error",reject);res.on("aborted",()=>reject(Error()));res.on("data",b=>{length+=b.length;if(length>256*1024)req.destroy(Error());else chunks.push(b)});res.on("end",()=>{try{resolve(JSON.parse(Buffer.concat(chunks).toString()))}catch{reject(Error())}})});req.on("error",reject);started=true;req.end(body)});const value=LocalIpcResponseSchema.parse(reply);if(value.requestId!==input.requestId&&!(value.requestId===null&&value.semanticStatus!=="SUCCESS"&&["FORBIDDEN","BUSY","INVALID_INPUT"].includes(value.error.code)))throw Error();if(value.semanticStatus!=="SUCCESS")throw new NativeStudioSdkError(value.error.code,value.semanticStatus,readOnly?"NO_WRITE":value.error.code==="INTERNAL_OPERATIONAL_FAILURE"?"UNKNOWN":"REJECTED");if(value.requestId!==input.requestId)throw Error();return value.data}catch(error){if(error instanceof NativeStudioSdkError)throw error;throw new NativeStudioSdkError("LOCAL_RUNTIME_UNAVAILABLE","BLOCKED",started&&!readOnly?"UNKNOWN":"NO_WRITE")}finally{budget.close()}}response(schema,raw){const result=schema.safeParse(raw);if(!result.success)throw new NativeStudioSdkError("LOCAL_RESPONSE_INVALID","BLOCKED","NO_WRITE");return result.data}async status(signal,includeDevice=false){const value=this.response(LocalRuntimeStatusSchema,await this.call({operation:"runtime.status",...includeDevice||this.options.device?{includeDevice:true}:{}},signal));if(this.options.device&&(value.deviceAuthority?.tenantId!==this.options.device.tenantId||value.deviceAuthority.deviceId!==this.options.device.deviceId))throw new NativeStudioSdkError("LOCAL_SCOPE_INVALID","BLOCKED","NO_WRITE");return value}async doctor(signal){return this.response(LocalDoctorReportSchema,await this.call({operation:"runtime.doctor"},signal))}async inventory(signal){return this.response(LocalManagementInventorySchema,await this.call({operation:"runtime.inventory"},signal))}async grantAgent(raw,approval){return this.response(LocalAgentProbeSchema,await this.call({operation:"agent.grant",grant:LocalAgentGrantSchema.parse(raw),approval}))}async revokeAgent(approval){return this.response(LocalAgentProbeSchema,await this.call({operation:"agent.revoke",approval}))}async probeAgent(){return this.response(LocalAgentProbeSchema,await this.call({operation:"agent.probe"}))}async discoverAgent(binary){return this.response(LocalAgentDiscoverySchema,await this.call({operation:"agent.discover",...binary?{binary}:{}}))}async prepareAgentReview(snapshot){const input=LocalAgentSnapshotSchema.parse(snapshot);const v=this.response(LocalAgentReviewViewSchema,await this.call({operation:"agent.prepare",snapshot:input}));if(canonicalLocalJson(v.plan.snapshot)!==canonicalLocalJson(input))throw new NativeStudioSdkError("LOCAL_RESPONSE_INVALID","BLOCKED","UNKNOWN");return v}async startAgentReview(id,expectedRevision,approval){const v=this.response(LocalAgentReviewViewSchema,await this.call({operation:"agent.start",id,expectedRevision,approval}));if(v.plan.id!==id||v.plan.fingerprint!==approval)throw new NativeStudioSdkError("LOCAL_RESPONSE_INVALID","BLOCKED","UNKNOWN");return v}async stageAgentImage(id,bytes,signal){const budget=localBudget(18e4,signal,18e4);try{return await stageAgentImage(this.options,await this.inspectAgentReview(id,budget.signal),bytes,budget.signal)}finally{budget.close()}}async inspectAgentReview(id,signal){const v=this.response(LocalAgentReviewViewSchema,await this.call({operation:"agent.inspect",id},signal));if(v.plan.id!==id)throw new NativeStudioSdkError("LOCAL_RESPONSE_INVALID","BLOCKED","NO_WRITE");return v}async executions(input,signal){const i=LocalExecutionListInputSchema.parse(input);if(this.options.device&&this.options.device.tenantId!==i.tenantId)throw new NativeStudioSdkError("FORBIDDEN","BLOCKED","NO_WRITE");const page=this.response(LocalExecutionPageSchema,await this.call({operation:"execution.list",input:i},signal));if(page.items.some(e=>e.binding.tenantId!==i.tenantId||e.binding.projectId!==i.projectId))throw new NativeStudioSdkError("LOCAL_SCOPE_INVALID","BLOCKED","NO_WRITE");return page}async inspect(raw,signal){const input=LocalExecutionInspectInputSchema.parse(raw);if(this.options.device&&this.options.device.tenantId!==input.tenantId)throw new NativeStudioSdkError("FORBIDDEN","BLOCKED","NO_WRITE");const value=this.response(LocalExecutionInspectionSchema.nullable(),await this.call({operation:"execution.inspect",input},signal));if(value&&["tenantId","projectId","productionId","runtimeJobId"].some(k=>value.binding[k]!==input[k]))throw new NativeStudioSdkError("LOCAL_SCOPE_INVALID","BLOCKED","NO_WRITE");return value}};function newerVersion(candidate,current){const parse=v=>{const core=v.split("+")[0],i=core.indexOf("-");return{parts:(i<0?core:core.slice(0,i)).split(".").map(BigInt),pre:i<0?null:core.slice(i+1).split(".")}};const a=parse(candidate),b=parse(current);for(let i=0;i<3;i++){if(a.parts[i]!==b.parts[i])return a.parts[i]>b.parts[i]}if(!a.pre||!b.pre)return!a.pre&&!!b.pre;for(let i=0;i<Math.max(a.pre.length,b.pre.length);i++){const x=a.pre[i],y=b.pre[i];if(x===y)continue;if(x===void 0||y===void 0)return y===void 0;const xn=/^\d+$/.test(x),yn=/^\d+$/.test(y);if(xn&&yn)return BigInt(x)>BigInt(y);if(xn!==yn)return!xn;return x>y}return false}import{createPublicKey,verify}from"node:crypto";function endpoint(raw){const u=new URL(raw);if(u.username||u.password||u.search||u.hash||u.protocol!=="https:"&&!(u.protocol==="http:"&&["127.0.0.1","localhost","[::1]"].includes(u.hostname)))fail("RELEASE_ORIGIN_INVALID");return u}async function fetchBytes(raw,maximum,origin,signal=AbortSignal.timeout(3e4)){const u=endpoint(raw);if(u.origin!==origin)fail("RELEASE_ORIGIN_INVALID");let r;try{r=await fetch(u,{redirect:"error",signal,headers:{accept:"application/octet-stream","user-agent":"NativeStudioDependencyClient"}})}catch{fail(signal.aborted?"RELEASE_TIMEOUT":"RELEASE_UNAVAILABLE")}const length=r.headers.get("content-length");if(!r.ok||length!==null&&(!/^[0-9]+$/.test(length)||Number(length)>maximum)){void r.body?.cancel().catch(()=>{});fail(r.status===403?"RELEASE_ACCESS_DENIED":r.status===404?"RELEASE_NOT_PUBLISHED":r.ok?"RELEASE_LIMIT":"RELEASE_UNAVAILABLE")}const reader=r.body?.getReader(),parts=[];let size=0;try{if(reader)while(true){const part=await reader.read();if(part.done)break;size+=part.value.byteLength;if(size>maximum)fail("RELEASE_LIMIT");parts.push(part.value)}return Buffer.concat(parts)}catch(error){if(error instanceof Error&&"code"in error&&error.code==="RELEASE_LIMIT")throw error;fail(signal.aborted?"RELEASE_TIMEOUT":"RELEASE_UNAVAILABLE")}finally{void reader?.cancel().catch(()=>{});reader?.releaseLock()}}async function catalogue(trust,signal){if(!trust.catalogueUrl||!trust.publicKeyFile&&!trust.publicKey)fail("DEPENDENCY_CHANNEL_REQUIRED");const origin=endpoint(trust.catalogueUrl).origin;const bytes=await fetchBytes(trust.catalogueUrl,65536,origin,signal??AbortSignal.timeout(3e4));let signed;try{signed=LocalSignedCatalogueSchema.parse(JSON.parse(bytes.toString()))}catch{fail("RELEASE_METADATA_INVALID")}const key=createPublicKey(trust.publicKeyFile?(await read(trust.publicKeyFile,16384)).toString():trust.publicKey);if(key.asymmetricKeyType!=="ed25519"||!verify(null,Buffer.from(canonicalLocalJson(signed.catalogue)),key,Buffer.from(signed.signature,"base64url")))fail("RELEASE_SIGNATURE_INVALID");const now=Date.now();if(Date.parse(signed.catalogue.issuedAt)>now||Date.parse(signed.catalogue.expiresAt)<=now)fail("RELEASE_EXPIRED");for(const release of signed.catalogue.releases){for(const a of[release.package,...release.tools?Object.values(release.tools):[],...release.resources?Object.values(release.resources):[]])if(endpoint(a.url).origin!==origin)fail("RELEASE_ORIGIN_INVALID")}return{signed,fingerprint:sha256(canonicalLocalJson(signed.catalogue)),origin,trustFingerprint:sha256(canonicalLocalJson({catalogueUrl:endpoint(trust.catalogueUrl).href,publicKey:key.export({type:"spki",format:"der"}).toString("base64")}))}}function select(signed,version,rejected=[]){if(version==="latest"){const candidates=signed.catalogue.releases.filter(r2=>!rejected.includes(r2.descriptor.version)&&r2.descriptor.platform.os===process.platform&&r2.descriptor.platform.architecture===process.arch&&Number(process.versions.node.split(".")[0])===r2.descriptor.node.major&&Number(process.versions.node.split(".")[1])>=r2.descriptor.node.minMinor);const latest=candidates.reduce((a,b)=>!a||newerVersion(b.descriptor.version,a.descriptor.version)?b:a,void 0);if(!latest)fail("VERSION_INCOMPATIBLE");version=latest.descriptor.version}const r=signed.catalogue.releases.find(r2=>r2.descriptor.version===version&&r2.descriptor.platform.os===process.platform&&r2.descriptor.platform.architecture===process.arch);if(!r)fail("VERSION_INCOMPATIBLE");const[major,minor]=process.versions.node.split(".").map(Number);if(major!==r.descriptor.node.major||minor<r.descriptor.node.minMinor)fail("NODE_VERSION_INCOMPATIBLE");return r}async function asset(a,origin){const bytes=await fetchBytes(a.url,a.byteSize,origin,AbortSignal.timeout(12e4));if(bytes.length!==a.byteSize||sha512(bytes)!==a.sha512)fail("RELEASE_INTEGRITY_INVALID");return bytes}export{LocalOfflineCallSchema,LocalOfflinePageSchema,LocalAgentGrantSchema,LocalAgentDiscoverySchema,LocalCompositionBrowserSelectionSchema,LocalToolSelectionSchema,LocalRuntimeDescriptorSchema,RuntimeCaptionAssets,LocalRuntimeComponentSchema,LocalManagementInventorySchema,LocalReleaseSchema,LocalToolChoiceSchema,LocalUpdatePlanSchema,LocalResourcePolicySchema,LocalWorkspaceInspectionSchema,LocalDiagnosticsSchema,LocalAgentSnapshotSchema,LocalAgentProbeSchema,LocalAgentReviewViewSchema,localAgentSnapshotFromContext,LocalExecutionListInputSchema,LocalExecutionInspectInputSchema,LocalRuntimeStatusSchema,LocalDoctorReportSchema,LocalMcpFailureSchema,LocalMcpOutputSchemas,localAgentMediaSnapshot,localAgentMediaProposal,AgentComponentScopeSchema,AgentComponentStatusSchema,CpuSpeechPrepareInputSchema,CpuSpeechPreparedSchema,NativeStudioLocalDeviceClient,NativeStudioLocalRuntimeClient,newerVersion,endpoint,catalogue,select,asset};
@@ -1 +0,0 @@
1
- import{connectDevice,generateDeviceKey}from"./chunk-H4FH6STZ.js";import{canResumeDesktop,desktopAutomation,desktopInstallationIdentity,rememberDesktopAutomation}from"./chunk-MZWEFYHE.js";import{LocalInstallationManager,probeLocalLibrary,probeReferenceThumbnail,probeTenantComposition,probeTenantMediaProcessing,probeTenantMediaValidation,probeTenantSpeech,probeTenantTranscription,socketAbsent}from"./chunk-FFXSXE3G.js";import{DesktopDeviceRecords}from"./chunk-ETK7GYCB.js";import{DesktopDeviceReplySchema,DesktopDeviceRequestSchema}from"./chunk-SM2I7TJ3.js";import{LocalDeviceChallengeSchema,LocalDeviceSessionSchema,LocalDeviceTransportConfigurationSchema,LocalDeviceViewSchema,LocalFinalRenderAdmissionSchema,LocalManagementCommandSchema,LocalPreviewAdmissionSchema,canonicalLocalJson,processorFamilies}from"./chunk-2S7FI3HF.js";import{fail,read,sha256}from"./chunk-DLW42PJ6.js";import{createPrivateKey as createPrivateKey2,createPublicKey,randomUUID as randomUUID3}from"node:crypto";import{randomUUID}from"node:crypto";async function desktopDeviceCapabilities(manager){const active=(await manager.ledger.current()).value.active;if(!active)fail("INSTALL_REQUIRED");const root=manager.ledger.slotPath(active);const validation=await probeTenantMediaValidation(root,active);const processing=await probeTenantMediaProcessing(root,active);const processors=processing?Object.keys(processorFamilies).filter(kind=>!["COMPOSITION_RENDER","LOCAL_MEDIA_INSPECT","LOCAL_MEDIA_PUBLISH","SPEECH_SYNTHESIZE","TRANSCRIBE_AUDIO","KEYFRAME_GENERATE","VIDEO_GENERATE","SPEECH_EXTERNAL_QWEN","REFERENCE_PREVIEW","TRANSCRIBE_EXTERNAL_QWEN"].includes(kind)):[];if(processing){if(await probeReferenceThumbnail(root,active))processors.push("REFERENCE_PREVIEW");if(await probeLocalLibrary(root,active))processors.push("LOCAL_MEDIA_INSPECT","LOCAL_MEDIA_PUBLISH");if(await probeTenantComposition(root,active))processors.push("COMPOSITION_RENDER");if(await probeTenantSpeech(root,active))processors.push("SPEECH_SYNTHESIZE");if(await probeTenantTranscription(root,active))processors.push("TRANSCRIBE_AUDIO")}return{...validation?{tenantMediaValidation:true}:{},...processors.length?{tenantMediaProcessing:true,processorCapabilities:processors.sort()}:{}}}async function connectDesktopDevice(records,manager,s,expectedRevision){if(s.revision!==expectedRevision)fail("DEVICE_PLAN_CHANGED");if(s.connection?.phase==="CONNECTING")fail("DEVICE_CONNECTION_RECOVERY_REQUIRED");if(!s.device||s.device.revokedAt)fail("DEVICE_ENROLLMENT_REQUIRED");const capabilities=await desktopDeviceCapabilities(manager);const c=await manager.configuration();const previous=c.cloudConfigFile?JSON.parse((await read(c.cloudConfigFile,32768)).toString()):null;if(previous&&(previous.endpoint!==s.scope.origin||previous.tenantId!==s.scope.tenantId||previous.deviceId!==s.device.deviceId))fail("DEVICE_CONNECTION_CONFLICT");const running=(await manager.status()).running;if(!running&&!await socketAbsent(c.stateDirectory))fail("DEVICE_CONNECTION_RECOVERY_REQUIRED");const matches=value=>{const saved=value;return saved?.deviceRevision===s.device.revision&&saved.tenantMediaValidation===capabilities.tenantMediaValidation&&saved.tenantMediaProcessing===capabilities.tenantMediaProcessing&&canonicalLocalJson(saved.processorCapabilities??null)===canonicalLocalJson(capabilities.processorCapabilities??null)};const reuse=running&&matches(previous)&&matches(s.connection);const expiresAt=new Date(Date.now()+24*36e5).toISOString();s=await records.save(s,{connection:{phase:"CONNECTING",expiresAt,deviceRevision:s.device.revision,...capabilities}});if(!reuse){if(running)await manager.stop();await connectDevice(manager,{endpoint:s.scope.origin,tenantId:s.scope.tenantId,deviceId:s.device.deviceId,deviceRevision:s.device.revision,privateKeyFile:records.keyPath(),platform:s.device.platform,...capabilities});await manager.start()}const id=randomUUID();await manager.grant({tenantId:s.scope.tenantId,deviceId:s.device.deviceId,expiresAt},records.connectorPath(id));return records.save(s,{connectorId:id,connection:{...s.connection,phase:"CONNECTED"}})}async function recoverDesktopConnection(records,manager,s){if(s.connection?.phase!=="CONNECTING")return s;const c=await manager.configuration(),running=(await manager.status()).running;if(!running){if(!await socketAbsent(c.stateDirectory))fail("DEVICE_CONNECTION_RECOVERY_REQUIRED");return records.save(s,{connection:null,connectorId:null})}if(!c.cloudConfigFile||!s.device||s.device.revokedAt)fail("DEVICE_CONNECTION_RECOVERY_REQUIRED");const raw=JSON.parse((await read(c.cloudConfigFile,32768)).toString());const{tools:_tools,...transport}=raw;void _tools;const actual=LocalDeviceTransportConfigurationSchema.parse(transport);if(actual.endpoint!==s.scope.origin||actual.deviceId!==s.device.deviceId||actual.tenantId!==s.scope.tenantId||actual.deviceRevision!==s.connection.deviceRevision||actual.deviceRevision!==s.device.revision||actual.tenantMediaValidation!==s.connection.tenantMediaValidation||actual.tenantMediaProcessing!==s.connection.tenantMediaProcessing||canonicalLocalJson(actual.processorCapabilities??null)!==canonicalLocalJson(s.connection.processorCapabilities??null))fail("DEVICE_CONNECTION_RECOVERY_REQUIRED");return records.save(s,{connection:{...s.connection,phase:"READY"},connectorId:null})}import{createPrivateKey,sign,randomUUID as randomUUID2}from"node:crypto";async function proveDesktopDevice(records){const state=await records.current(),d=state.device;if(!d)fail("DEVICE_ENROLLMENT_REQUIRED");async function request(action,input){const response=await fetch(state.scope.origin+"/v1/local-execution/devices/"+action,{method:"POST",redirect:"error",headers:{"content-type":"application/json"},body:JSON.stringify(input),signal:AbortSignal.timeout(15e3)});if(!response.ok){await response.body?.cancel();fail("DEVICE_PROOF_UNAVAILABLE")}const chunks=[];let size=0;for await(const bytes of response.body??[]){size+=bytes.length;if(size>16384)fail("DEVICE_PROOF_INVALID");chunks.push(bytes)}return JSON.parse(Buffer.concat(chunks).toString())}const scope={tenantId:d.tenantId,deviceId:d.deviceId,deviceRevision:d.revision};const started=performance.now();const challenge=LocalDeviceChallengeSchema.parse(await request("challenge",scope));if(challenge.tenantId!==d.tenantId||challenge.deviceId!==d.deviceId||challenge.deviceRevision!==d.revision||Date.parse(challenge.expiresAt)-Date.parse(challenge.issuedAt)<=performance.now()-started)fail("DEVICE_PROOF_INVALID");const key=createPrivateKey({key:JSON.parse((await read(records.keyPath(),16384)).toString()),format:"jwk"});const header=Buffer.from(JSON.stringify({alg:"ES256",typ:"nvs-local-device+jwt"})).toString("base64url");const iat=Math.floor(Date.parse(challenge.issuedAt)/1e3),claims=Buffer.from(JSON.stringify({protocol:"NVS_LOCAL_DEVICE_PROOF_V1",...scope,challengeId:challenge.challengeId,audience:challenge.audience,jti:randomUUID2(),iat,exp:iat+30})).toString("base64url");const unsigned=header+"."+claims;const assertion=unsigned+"."+sign("sha256",Buffer.from(unsigned),{key,dsaEncoding:"ieee-p1363"}).toString("base64url");const result=LocalDeviceSessionSchema.parse(await request("prove",{...scope,challengeId:challenge.challengeId,assertion}));if(result.tenantId!==d.tenantId||result.deviceId!==d.deviceId)fail("DEVICE_PROOF_INVALID")}var fingerprint=v=>sha256(canonicalLocalJson(v));function view(s){return{revision:s.revision,device:s.device?{deviceId:s.device.deviceId,label:s.device.label,revision:s.device.revision,revokedAt:s.device.revokedAt}:null,previews:s.previews,connection:s.connection,pending:s.pending?{kind:s.pending.command.kind,phase:s.pending.phase,fingerprint:s.pending.fingerprint,...s.pending.agentEnrollment&&{agentEnrollment:true}}:null}}function accepted(s,result){const command=s.pending.command,i=command.input;if(command.kind==="ENROLL"){const d=LocalDeviceViewSchema.parse(result);if(d.tenantId!==i.tenantId||d.enrolledByPrincipalId!==s.scope.principalId||d.label!==command.input.label||d.runtimeVersion!==command.input.runtimeVersion||canonicalLocalJson(d.publicKey)!==canonicalLocalJson(command.input.publicKey)||canonicalLocalJson(d.platform)!==canonicalLocalJson(command.input.platform)||d.revokedAt)fail("DEVICE_RESULT_INVALID");return{device:d}}if(command.kind==="REVOKE_DEVICE"){if(result?.semanticStatus!=="SUCCESS"||!s.device)fail("DEVICE_RESULT_INVALID");return{device:{...s.device,revision:s.device.revision+1,revokedAt:new Date().toISOString()},connectorId:null,connection:null}}const p=(command.kind==="FINAL_RENDER"?LocalFinalRenderAdmissionSchema:LocalPreviewAdmissionSchema).parse(result),input=command.input;if(p.productionId!==input.productionId||p.timelineVersionId!==input.timelineVersionId||p.timelineFingerprint!==input.timelineFingerprint||canonicalLocalJson(p.placement.policy)!==canonicalLocalJson(input.placement))fail("DEVICE_RESULT_INVALID");return{previews:[p,...s.previews.filter(v=>v.renderId!==p.renderId)].slice(0,20)}}async function runDesktopDeviceRequest(home,raw,policy){const request=DesktopDeviceRequestSchema.parse(raw),call=request.call;const records=await DesktopDeviceRecords.open(home,request.scope),manager=await LocalInstallationManager.open(home);let s=await records.current();if(s.pending&&policy&&!policy.allowedPendingKinds.includes(s.pending.command.kind))fail("DEVICE_COMMAND_UNSUPPORTED");const installation=await desktopInstallationIdentity(manager);let automatic=await desktopAutomation(home);const publicView=()=>({...view(s),installation,automaticConnection:canResumeDesktop(automatic,s,installation)});const processingSupported=async()=>{const active=(await manager.ledger.current()).value.active;return!!active&&await probeTenantMediaProcessing(manager.ledger.slotPath(active),active)};const librarySupported=async()=>{const active=(await manager.ledger.current()).value.active;return!!active&&await probeLocalLibrary(manager.ledger.slotPath(active),active)};const compositionSupported=async()=>{const active=(await manager.ledger.current()).value.active;return!!active&&await probeTenantComposition(manager.ledger.slotPath(active),active)};if(call.action==="media-processing-capability")return DesktopDeviceReplySchema.parse({view:publicView(),mediaProcessingSupported:await processingSupported(),localLibrarySupported:await librarySupported(),compositionProcessingSupported:await compositionSupported()});if(call.action==="media-validation-capability"){const active=(await manager.ledger.current()).value.active;const supported=!!active&&await probeTenantMediaValidation(manager.ledger.slotPath(active),active);return DesktopDeviceReplySchema.parse({view:publicView(),mediaValidationSupported:supported})}if(call.action==="inspect")return DesktopDeviceReplySchema.parse({view:publicView(),...s.pending?{command:s.pending.command}:{}});if(call.action==="dispatch"||call.action==="record"||call.action==="refused"){if(!s.pending||s.pending.fingerprint!==call.fingerprint)fail("DEVICE_PLAN_CHANGED");if(call.action==="dispatch"){if(s.pending.phase!=="PREPARED")fail("DEVICE_OUTCOME_UNKNOWN");const command2=s.pending.command;s=await records.save(s,{pending:{...s.pending,phase:"SENDING"}});return DesktopDeviceReplySchema.parse({view:publicView(),command:command2})}if(s.pending.phase!=="SENDING")fail("DEVICE_PLAN_CHANGED");s=await records.save(s,call.action==="record"?{...accepted(s,call.result),pending:null}:{pending:{...s.pending,phase:"REFUSED"}});return DesktopDeviceReplySchema.parse({view:publicView()})}if(s.pending?.phase==="SENDING")fail("DEVICE_OUTCOME_UNKNOWN");if(call.action==="remember-enable"){if(s.revision!==call.expectedRevision)fail("DEVICE_PLAN_CHANGED");automatic=await rememberDesktopAutomation(home,s,installation,call.installationFingerprint);return DesktopDeviceReplySchema.parse({view:publicView()})}if(call.action==="prove"){await proveDesktopDevice(records);return DesktopDeviceReplySchema.parse({view:publicView()})}if(call.action==="connect"){if(call.installationFingerprint&&call.installationFingerprint!==installation?.fingerprint)fail("DEVICE_PLAN_CHANGED");s=await connectDesktopDevice(records,manager,s,call.expectedRevision);return DesktopDeviceReplySchema.parse({view:publicView()})}if(call.action==="connection-recover"){s=await recoverDesktopConnection(records,manager,s);return DesktopDeviceReplySchema.parse({view:publicView()})}let command;if(call.action==="enroll"){if(s.device)fail("DEVICE_ALREADY_ENROLLED");if(call.expectedRevision!==void 0&&s.revision!==call.expectedRevision)fail("DEVICE_PLAN_CHANGED");const active=(await manager.ledger.current()).value.active;if(!active)fail("INSTALL_REQUIRED");let publicKey;try{const key=createPrivateKey2({key:JSON.parse((await read(records.keyPath(),16384)).toString()),format:"jwk"});publicKey=createPublicKey(key).export({format:"jwk"})}catch(e){if(e.code!=="ENOENT")throw e;publicKey=(await generateDeviceKey(records.keyPath())).publicKey}command={kind:"ENROLL",input:{tenantId:s.scope.tenantId,requestId:randomUUID3(),...call.bindWorkspaceMember||call.agentEnrollment?{expectedPrincipalId:s.scope.principalId}:{},label:call.label,platform:active.descriptor.platform,runtimeVersion:active.descriptor.version,publicKey}}}else{const d=s.device;if(!d)fail("DEVICE_ENROLLMENT_REQUIRED");if(call.action==="preview"||call.action==="final"){if(d.revokedAt)fail("LOCAL_AUTHORIZATION_REQUIRED");command={kind:call.action==="final"?"FINAL_RENDER":"PREVIEW",input:{...call.input,tenantId:s.scope.tenantId,placement:{mode:call.mode,deviceId:d.deviceId},idempotencyKey:"desktop:"+randomUUID3()}}}else{if(call.action!=="revoke"||d.revokedAt)fail("LOCAL_AUTHORIZATION_REQUIRED");command={kind:"REVOKE_DEVICE",input:{tenantId:s.scope.tenantId,deviceId:d.deviceId,requestId:randomUUID3(),expectedRevision:d.revision}}}}const parsed=LocalManagementCommandSchema.parse(command);s=await records.save(s,{...parsed.kind==="ENROLL"?{enrollment:parsed.input}:{},pending:{command:parsed,fingerprint:fingerprint(parsed),phase:"PREPARED",...call.action==="enroll"&&call.agentEnrollment&&{agentEnrollment:true}}});return DesktopDeviceReplySchema.parse({view:publicView(),command:parsed})}async function desktopDevicePending(home,scope){return(await(await DesktopDeviceRecords.open(home,scope)).current()).pending?.command??null}export{runDesktopDeviceRequest,desktopDevicePending};
@@ -1 +0,0 @@
1
- import{DeviceEnrollmentScopeSchema,LocalDeviceTransportConfigurationSchema,LocalDeviceViewSchema,LocalFinalRenderAdmissionSchema,LocalManagementCommandSchema,LocalManagementResultSchema,LocalPreviewAdmissionSchema,StartLocalFinalRenderSchema,StartLocalPreviewSchema}from"./chunk-2S7FI3HF.js";import{z}from"zod";var DesktopDeviceScopeSchema=DeviceEnrollmentScopeSchema;var digest=z.string().regex(/^[a-f0-9]{64}$/);var DesktopDeviceCallSchema=z.discriminatedUnion("action",[z.strictObject({action:z.literal("inspect")}),z.strictObject({action:z.literal("prove")}),z.strictObject({action:z.literal("media-validation-capability")}),z.strictObject({action:z.literal("media-processing-capability")}),z.strictObject({action:z.literal("connect"),expectedRevision:z.int().nonnegative(),installationFingerprint:digest.optional()}),z.strictObject({action:z.literal("remember-enable"),expectedRevision:z.int().nonnegative(),installationFingerprint:digest}),z.strictObject({action:z.literal("connection-recover")}),z.strictObject({action:z.literal("enroll"),label:z.string().trim().min(1).max(120),expectedRevision:z.int().nonnegative().optional(),bindWorkspaceMember:z.literal(true).optional(),agentEnrollment:z.literal(true).optional()}),z.strictObject({action:z.literal("revoke")}),z.strictObject({action:z.literal("preview"),input:StartLocalPreviewSchema.omit({tenantId:true,placement:true,idempotencyKey:true}),mode:z.enum(["local-only","local-preferred"])}),z.strictObject({action:z.literal("final"),input:StartLocalFinalRenderSchema.omit({tenantId:true,placement:true,idempotencyKey:true}),mode:z.enum(["local-only","local-preferred"])}),z.strictObject({action:z.literal("dispatch"),fingerprint:digest}),z.strictObject({action:z.literal("record"),fingerprint:digest,result:LocalManagementResultSchema}),z.strictObject({action:z.literal("refused"),fingerprint:digest})]);var DesktopDeviceRequestSchema=z.strictObject({operation:z.literal("device"),scope:DesktopDeviceScopeSchema,call:DesktopDeviceCallSchema});var DesktopDeviceStateSchema=z.strictObject({revision:z.int().nonnegative(),scope:DesktopDeviceScopeSchema,enrollment:LocalManagementCommandSchema.options[0].shape.input.nullable(),device:LocalDeviceViewSchema.nullable(),previews:z.array(z.union([LocalPreviewAdmissionSchema,LocalFinalRenderAdmissionSchema])).max(20),connectorId:z.uuid().nullable(),connection:z.strictObject({phase:z.enum(["CONNECTING","READY","CONNECTED"]),expiresAt:z.iso.datetime(),tenantMediaProcessing:z.literal(true).optional(),processorCapabilities:LocalDeviceTransportConfigurationSchema.shape.processorCapabilities,deviceRevision:z.int().positive(),tenantMediaValidation:z.literal(true).optional()}).nullable().default(null),pending:z.strictObject({command:LocalManagementCommandSchema,fingerprint:digest,phase:z.enum(["PREPARED","SENDING","REFUSED"]),agentEnrollment:z.literal(true).optional()}).nullable()});var DesktopDeviceViewSchema=DesktopDeviceStateSchema.omit({scope:true,enrollment:true,connectorId:true,pending:true,device:true}).extend({installation:z.strictObject({version:z.string().min(1).max(100),fingerprint:digest,workProtocol:z.enum(["NVS_LOCAL_WORK_V1","NVS_LOCAL_WORK_V2"]).optional()}).nullable().optional(),automaticConnection:z.boolean().optional(),device:z.strictObject({deviceId:z.uuid(),label:z.string().max(120),revision:z.int().positive(),revokedAt:z.iso.datetime().nullable()}).nullable(),pending:z.strictObject({kind:z.enum(["ENROLL","REVOKE_DEVICE","PREVIEW","FINAL_RENDER"]),phase:z.enum(["PREPARED","SENDING","REFUSED"]),fingerprint:digest,agentEnrollment:z.literal(true).optional()}).nullable()});var DesktopDeviceReplySchema=z.strictObject({view:DesktopDeviceViewSchema,command:LocalManagementCommandSchema.optional(),mediaValidationSupported:z.boolean().optional(),mediaProcessingSupported:z.boolean().optional(),localLibrarySupported:z.boolean().optional(),compositionProcessingSupported:z.boolean().optional()});export{DesktopDeviceScopeSchema,DesktopDeviceRequestSchema,DesktopDeviceStateSchema,DesktopDeviceReplySchema};
@@ -1 +0,0 @@
1
- import{embeddedRuntime,runtimeEnvironment,toolPreference,verifySlot}from"./chunk-FFXSXE3G.js";import{CpuSpeechPrepareInputSchema,CpuSpeechPreparedSchema,LocalToolSelectionSchema}from"./chunk-LDBXGRCQ.js";import{canonicalLocalJson}from"./chunk-2S7FI3HF.js";import{directory,fail,read,write}from"./chunk-DLW42PJ6.js";import{spawn}from"node:child_process";import{randomUUID}from"node:crypto";import{join}from"node:path";import{unlink}from"node:fs/promises";async function assertCpuPreparationCurrent(manager,original,planRevision=original.revision){const current=(await manager.ledger.current()).value;const configuration=await manager.configuration();if(current.revision!==original.revision||planRevision!==original.revision||canonicalLocalJson(configuration)!==canonicalLocalJson(original.configuration))fail("REVISION_CONFLICT")}async function prepareInstalledCpuSpeech(manager,raw){const input=CpuSpeechPrepareInputSchema.parse(raw),current=(await manager.ledger.current()).value;if(current.transition)fail("ACTIVATION_IN_PROGRESS");if(!current.active)fail("INSTALLATION_REQUIRED");const slot=current.active,root=manager.ledger.slotPath(slot),configuration=await manager.configuration();const context={revision:current.revision,configuration};await verifySlot(root,slot);const file=join(await directory(join(manager.ledger.root,"preparations")),randomUUID()+".json");await write(file,JSON.stringify(input),true);try{const prepared=await new Promise((resolve,reject)=>{const child=spawn(process.execPath,["--max-old-space-size=256",join(root,"dist/entry.js"),"--prepare-cpu-speech","--state-dir",configuration.stateDirectory,"--input-config",file],{env:runtimeEnvironment(),stdio:["ignore","pipe","pipe","ipc"],shell:false});const parts=[],errors=[];let used=0,errorBytes=0,killed=false;const timer=setTimeout(()=>{killed=true;child.kill("SIGTERM")},23e4);const kill=setTimeout(()=>{killed=true;child.kill("SIGKILL")},235e3);const abort=()=>{killed=true;child.kill("SIGTERM")};process.once("SIGINT",abort);process.once("SIGTERM",abort);child.stdout.on("data",chunk=>{used+=chunk.length;if(used>32768)child.kill("SIGTERM");else parts.push(chunk)});child.stderr.on("data",chunk=>{errorBytes+=chunk.length;if(errorBytes>4096)child.kill("SIGTERM");else errors.push(chunk)});child.once("error",reject);child.once("close",code=>{clearTimeout(timer);clearTimeout(kill);process.off("SIGINT",abort);process.off("SIGTERM",abort);try{if(killed)fail("CPU_PREPARATION_CANCELLED");if(code!==0||used>32768||errorBytes>4096){const last=Buffer.concat(errors).toString().trim().split("\n").at(-1);let reason;try{reason=JSON.parse(last??"{}").error?.code}catch{}if(reason==="CPU_BZIP2_REQUIRED")fail("CPU_BZIP2_REQUIRED");if(reason==="CPU_SPEECH_PLATFORM_UNAVAILABLE")fail("CPU_SPEECH_PLATFORM_UNAVAILABLE");fail("CPU_PREPARATION_FAILED")}resolve(CpuSpeechPreparedSchema.parse(JSON.parse(Buffer.concat(parts).toString())))}catch(error){reject(error)}})});await assertCpuPreparationCurrent(manager,context);const previous=await toolPreference(slot.toolsConfigPath,configuration.cloudConfigFile);const existing=slot.toolsConfigPath?LocalToolSelectionSchema.parse(JSON.parse((await read(slot.toolsConfigPath,32768)).toString())):null;const reuseMedia=previous.mode==="MANAGED"&&existing?.mode==="MANAGED"?{schemaVersion:1,ffmpeg:existing.ffmpeg,ffprobe:existing.ffprobe}:void 0;const choice={...previous,cpuSpeech:prepared.selection,...reuseMedia?{reuseMedia}:{}};const plan=await embeddedRuntime(slot.descriptor.version)?await manager.prepareBundled(slot.descriptor.version,choice):await manager.prepare(slot.descriptor.version,choice);await assertCpuPreparationCurrent(manager,context,plan.installationRevision);return{semanticStatus:"PREPARED",capability:prepared.capability,reused:prepared.reused,plan}}finally{await unlink(file).catch(error=>{if(error.code!=="ENOENT")throw error})}}export{prepareInstalledCpuSpeech};
@@ -1 +0,0 @@
1
- import{profileAuthorization}from"./chunk-3TOXIJ7K.js";import{connectRemoteMcp}from"./chunk-76E5R3OC.js";import{clientHome,loadConnection}from"./chunk-27KI24GK.js";import{optional,write}from"./chunk-DLW42PJ6.js";import{NativeStudioSdkError}from"./chunk-TT7IA5HB.js";import{join}from"node:path";import{z}from"zod";var selection=z.strictObject({version:z.literal(1),tenantId:z.uuid(),resource:z.url(),projectId:z.uuid()});async function workspaceProject(scope,env){const value=await optional(join(await clientHome(env),"selection.json"));if(value===null)return null;const parsed=selection.safeParse(value);if(!parsed.success)throw new NativeStudioSdkError("PROJECT_SELECTION_INVALID","BLOCKED","NO_WRITE");return parsed.data.tenantId===scope.tenantId&&(!scope.resource||parsed.data.resource===scope.resource)?parsed.data.projectId:null}async function workspaceCommand(argv,env){const[command,...args]=argv;if(!["workspaces","workspace","projects","project"].includes(command??""))return null;let connection;try{connection=await loadConnection(env)}catch(error){if(error instanceof NativeStudioSdkError&&error.code==="CONNECTION_ACCOUNT_MISMATCH")return null;throw error}if(!connection)return null;const flags=new Map;for(let i=0;i<args.length;i+=2){const key=args[i],value=args[i+1];if(!key||!value||value.startsWith("--")||flags.has(key)||!["--id","--limit","--next"].includes(key))throw Error();flags.set(key,value)}if(command==="projects"?flags.has("--id"):command==="workspaces"?flags.size>0:flags.size!==1||!flags.has("--id"))throw Error();const auth=await profileAuthorization(connection.profile);const remote=await connectRemoteMcp(connection.resource,auth.authorization,connection.tenantId);try{if(command==="workspaces"){const page=await remote.studio.call("workspace.query",{});return{exitCode:0,output:{semanticStatus:"SUCCESS",workspaces:page.items}}}if(command==="projects"){const page=await remote.studio.call("project.query",{...flags.has("--limit")?{limit:z.coerce.number().int().min(1).max(100).parse(flags.get("--limit"))}:{},...flags.has("--next")?{next:flags.get("--next")}:{}});return{exitCode:0,output:{semanticStatus:"SUCCESS",...page}}}const id=z.uuid().parse(flags.get("--id"));if(command==="workspace"){if(id!==connection.tenantId)throw new NativeStudioSdkError("FORBIDDEN","BLOCKED","NO_WRITE");const value2=await remote.studio.call("workspace.get",{});return{exitCode:0,output:{semanticStatus:"SUCCESS",workspaceId:value2.id}}}const value=await remote.studio.call("project.get",{projectId:id});await write(join(await clientHome(env),"selection.json"),JSON.stringify({version:1,tenantId:connection.tenantId,resource:connection.resource,projectId:value.project.id}));return{exitCode:0,output:{semanticStatus:"SUCCESS",project:value.project}}}finally{await remote.close().catch(()=>{})}}export{workspaceProject,workspaceCommand};
@@ -1 +0,0 @@
1
- import{DesktopLibraryImportRequestSchema,DesktopLibraryPrepareRequestSchema,DesktopLibraryReplySchema,DesktopLibraryRequestSchema}from"./chunk-DMA53YVU.js";import{desktopAutomation,desktopInstallationIdentity,disableDesktopAutomation}from"./chunk-MZWEFYHE.js";import{LocalInstallationManager,ownerClient,socketAbsent,waitStopped}from"./chunk-FFXSXE3G.js";import{DesktopDeviceReplySchema,DesktopDeviceRequestSchema,DesktopDeviceScopeSchema}from"./chunk-SM2I7TJ3.js";import{CpuSpeechPrepareInputSchema,LocalAgentDiscoverySchema,LocalAgentGrantSchema,LocalAgentProbeSchema,LocalAgentReviewViewSchema,LocalAgentSnapshotSchema,LocalDiagnosticsSchema,LocalOfflineCallSchema,LocalOfflinePageSchema,LocalResourcePolicySchema,LocalRuntimeDescriptorSchema,LocalToolSelectionSchema,LocalWorkspaceInspectionSchema}from"./chunk-LDBXGRCQ.js";import{canonicalLocalJson}from"./chunk-2S7FI3HF.js";import{atomicMove,directory,entries,fail,optional,read,sha256,write}from"./chunk-DLW42PJ6.js";import{NativeStudioSdkError}from"./chunk-TT7IA5HB.js";import{z as z7}from"zod";import{z}from"zod";import{join,sep}from"node:path";var StoragePlanSchema=z.strictObject({id:z.uuid(),mode:z.enum(["BACKUP","MIGRATE"]),source:z.string().min(1),destination:z.string().min(1),installationRevision:z.int().nonnegative(),installationFingerprint:z.string().regex(/^[a-f0-9]{64}$/),runtimeRevision:z.int().positive(),revision:z.int().nonnegative().default(0),phase:z.enum(["PREPARED","DRAINING","COPYING","COPIED","VERIFYING","COMPLETE","CANCELLED"]),fingerprint:z.string().regex(/^[a-f0-9]{64}$/),expiresAt:z.iso.datetime(),bytes:z.int().nonnegative().default(0)});var recordSchema=z.strictObject({plan:StoragePlanSchema,previous:z.string().regex(/^[a-f0-9]{64}$/).nullable(),digest:z.string().regex(/^[a-f0-9]{64}$/)});var phases=["PREPARED","DRAINING","COPYING","COPIED","VERIFYING","COMPLETE"];var terminal=phase=>["COMPLETE","CANCELLED"].includes(phase);var advances=(before,after)=>before===after||!terminal(before)&&(after==="CANCELLED"||phases.indexOf(after)===phases.indexOf(before)+1);async function storageInstallationIdentity(slot,source,destination){const tools=slot.toolsConfigPath?LocalToolSelectionSchema.parse(JSON.parse((await read(slot.toolsConfigPath,32768)).toString())):null;if(tools?.mode==="MANAGED"){for(const name of["ffmpeg","ffprobe"])for(const root of[source,destination])if(tools[name].path.startsWith(root+sep)){tools[name].path="{state}"+tools[name].path.slice(root.length);break}}return sha256(canonicalLocalJson({descriptor:slot.descriptor,files:slot.files,tools}))}function intent(p){return{id:p.id,mode:p.mode,source:p.source,destination:p.destination,installationRevision:p.installationRevision,installationFingerprint:p.installationFingerprint,runtimeRevision:p.runtimeRevision,expiresAt:p.expiresAt}}async function history(root,id2){const path=await directory(join(root,z.uuid().parse(id2)));let plan=null;let digest3=null;const names=(await entries(path)).filter(n=>/^\d{8}\.json$/.test(n)).sort();for(const[index,name]of names.entries()){const record=recordSchema.parse(JSON.parse((await read(join(path,name))).toString())),next=record.plan;if(next.id!==id2||next.revision!==index+1||next.fingerprint!==sha256(canonicalLocalJson(intent(next)))||record.previous!==digest3||record.digest!==sha256(canonicalLocalJson({plan:next,previous:digest3}))||!plan&&next.phase!=="PREPARED"||plan&&(plan.fingerprint!==next.fingerprint||!advances(plan.phase,next.phase)))fail("STORAGE_HISTORY_INVALID");plan=next;digest3=record.digest}return{plan,digest:digest3}}async function readStoragePlan(root,id2){return(await history(root,id2)).plan}async function saveStoragePlan(root,expected,phase,extra={}){const current=await history(root,expected.id),actual=current.plan;if((actual?.revision??0)!==expected.revision)fail("REVISION_CONFLICT");if(actual&&canonicalLocalJson(actual)!==canonicalLocalJson(expected))fail("PLAN_CHANGED");const next=StoragePlanSchema.parse({...expected,...extra,phase,revision:expected.revision+1});if(next.fingerprint!==sha256(canonicalLocalJson(intent(next))))fail("PLAN_CHANGED");if(!actual&&phase!=="PREPARED"||actual&&!advances(actual.phase,phase))fail("PLAN_CHANGED");const file=join(root,next.id,String(next.revision).padStart(8,"0")+".json");try{const body={plan:next,previous:current.digest};await write(file,canonicalLocalJson({...body,digest:sha256(canonicalLocalJson(body))}),true)}catch(e){if(e.code==="EEXIST")fail("REVISION_CONFLICT");throw e}return next}import{z as z2}from"zod";import{lstat as lstat2,realpath}from"node:fs/promises";import{randomUUID}from"node:crypto";import{join as join3,resolve,sep as sep3}from"node:path";import{constants,createReadStream}from"node:fs";import{open,readdir,lstat,statfs,chmod,unlink}from"node:fs/promises";import{join as join2,relative,sep as sep2}from"node:path";import{createHash}from"node:crypto";async function digestFile(path){const file=await open(path,constants.O_RDONLY|constants.O_NOFOLLOW);try{const before=await file.stat(),hash=createHash("sha256");if(!before.isFile()||before.nlink!==1||before.size>512*1024**2||process.platform!=="win32"&&(before.uid!==process.getuid?.()||before.mode&63))fail("STORAGE_FILE_INVALID");let bytes=0;for await(const chunk of createReadStream(path,{fd:file.fd,autoClose:false})){bytes+=chunk.length;if(bytes>before.size)fail("STORAGE_FILE_CHANGED");hash.update(chunk)}const after=await file.stat();if(bytes!==before.size||before.mtimeMs!==after.mtimeMs||before.ino!==after.ino)fail("STORAGE_FILE_CHANGED");return{bytes,sha256:hash.digest("hex"),mode:before.mode&448}}finally{await file.close()}}async function storageFiles(root){const files=[];async function walk(path,depth){if(depth>8)fail("STORAGE_FILE_LIMIT");for(const item of await readdir(path,{withFileTypes:true})){const source=join2(path,item.name),name=relative(root,source);if(path===root&&!["journal.sqlite","journal.sqlite-wal","cache","staging","tools","agent-images","agent-evidence","agent-reviews","library"].includes(item.name))continue;const info=await lstat(source);if(info.isSymbolicLink()||!info.isFile()&&!info.isDirectory())fail("STORAGE_FILE_INVALID");if(info.isDirectory())await walk(source,depth+1);else{if(files.length>=5e4)fail("STORAGE_FILE_LIMIT");const value=await digestFile(source);files.push({name,bytes:value.bytes,sha256:value.sha256})}}}await walk(root,0);return files.sort((a,b)=>a.name.localeCompare(b.name))}async function copyStorage(source,destination){if(destination===source||destination.startsWith(source+sep2)||source.startsWith(destination+sep2))fail("STORAGE_LOCATION_INVALID");await directory(destination);const files=await storageFiles(source),total=files.reduce((n,f)=>n+f.bytes,0);const fs=await statfs(destination);if(fs.bavail*fs.bsize<total+256*1024**2)fail("STORAGE_SPACE_REQUIRED");for(const item of files){const original=join2(source,item.name),target=join2(destination,item.name);const parent=target.slice(0,target.lastIndexOf(sep2));await directory(parent);try{const existing=await digestFile(target);if(existing.sha256!==item.sha256||existing.bytes!==item.bytes)fail("STORAGE_COPY_CONFLICT");continue}catch(error){if(error.code!=="ENOENT")throw error}const temporary=target+".copy-part";try{await digestFile(temporary);await unlink(temporary)}catch(error){if(error.code!=="ENOENT")throw error}const input=await open(original,constants.O_RDONLY|constants.O_NOFOLLOW),output=await open(temporary,"wx",384);try{for await(const bytes of createReadStream(original,{fd:input.fd,autoClose:false}))await output.writeFile(bytes);await output.sync()}finally{await input.close();await output.close()}const copied=await digestFile(temporary),before=await digestFile(original);if(copied.sha256!==item.sha256||before.sha256!==item.sha256||copied.bytes!==item.bytes)fail("STORAGE_COPY_INVALID");await chmod(temporary,before.mode);await atomicMove(temporary,target,true)}return{files,total}}var id=z2.uuid();var digest=z2.string().regex(/^[a-f0-9]{64}$/);var planSchema=StoragePlanSchema;var DesktopStorageRequestSchema=z2.strictObject({operation:z2.literal("storage"),call:z2.discriminatedUnion("action",[z2.strictObject({action:z2.literal("status")}),z2.strictObject({action:z2.literal("prepare"),mode:z2.enum(["BACKUP","MIGRATE"]),destination:z2.string().min(1).max(4096)}),z2.strictObject({action:z2.enum(["execute","recover","abandon"]),id,fingerprint:digest})])});var viewSchema=planSchema.omit({source:true,destination:true,runtimeRevision:true,installationRevision:true});var DesktopStorageReplySchema=viewSchema.nullable();function present(plan){if(!plan)return null;const{source,destination,runtimeRevision,installationRevision,...view}=plan;void source;void destination;void runtimeRevision;void installationRevision;return DesktopStorageReplySchema.parse(view)}async function runDesktopStorageRequest(home,raw){const{call}=DesktopStorageRequestSchema.parse(raw),manager=await LocalInstallationManager.open(home);const root=await directory(join3(home,"storage-plans"));const pointer=await optional(join3(root,"current.json"));const prior=pointer?await readStoragePlan(root,id.parse(pointer)):null;if(call.action==="status")return present(prior);let config=await manager.configuration(),installation=(await manager.ledger.current()).value;let plan;const save=async(phase,extra={})=>{plan=await saveStoragePlan(root,plan,phase,extra)};if(call.action==="prepare"){if(!installation.active||installation.transition)fail("RECOVERY_REQUIRED");if(prior&&!["COMPLETE","CANCELLED"].includes(prior.phase))fail("RECOVERY_REQUIRED");const selected=resolve(call.destination),info=await lstat2(selected);if(!info.isDirectory()||info.isSymbolicLink()||process.platform!=="win32"&&info.uid!==process.getuid?.())fail("STORAGE_LOCATION_INVALID");const destination=await realpath(selected);if(destination===config.stateDirectory||destination.startsWith(config.stateDirectory+sep3))fail("STORAGE_LOCATION_INVALID");const inventory=await(await ownerClient(config.stateDirectory)).inventory();const body={id:randomUUID(),mode:call.mode,source:config.stateDirectory,destination:join3(destination,"NVS-"+randomUUID().replaceAll("-","").slice(0,16)),installationRevision:installation.revision,runtimeRevision:inventory.runtimeRevision,expiresAt:new Date(Date.now()+18e5).toISOString()};if(call.mode==="MIGRATE"&&process.platform!=="win32"&&Buffer.byteLength(join3(body.destination,"runtime.sock"))>100)fail("SOCKET_PATH_TOO_LONG");const frozen={...body,installationFingerprint:await storageInstallationIdentity(installation.active,body.source,body.destination)};plan=planSchema.parse({...frozen,fingerprint:sha256(canonicalLocalJson(frozen)),phase:"PREPARED"});await save("PREPARED");await write(join3(root,"current.json"),canonicalLocalJson(plan.id));return present(plan)}plan=await readStoragePlan(root,call.id);if(!plan||plan.fingerprint!==call.fingerprint)fail("PLAN_CHANGED");if(["COMPLETE","CANCELLED"].includes(plan.phase))return present(plan);if(call.action==="abandon"){await save("CANCELLED");return present(plan)}if(!installation.active||installation.transition)fail("RECOVERY_REQUIRED");if(await storageInstallationIdentity(installation.active,plan.source,plan.destination)!==plan.installationFingerprint)fail("PLAN_CHANGED");if(config.stateDirectory!==plan.source&&!(plan.mode==="MIGRATE"&&config.stateDirectory===plan.destination))fail("PLAN_CHANGED");if(plan.phase==="PREPARED"){if(Date.parse(plan.expiresAt)<=Date.now()||installation.revision!==plan.installationRevision)fail("PLAN_CHANGED");const client=await ownerClient(plan.source),inventory=await client.inventory();if(inventory.runtimeRevision!==plan.runtimeRevision)fail("REVISION_CONFLICT");await save("DRAINING");await manager.stop()}if(plan.phase==="DRAINING"){await waitStopped(plan.source);if(!await socketAbsent(plan.source))fail("RECOVERY_REQUIRED");await save("COPYING")}if(plan.phase==="COPYING"){if(!await socketAbsent(plan.source))fail("RECOVERY_REQUIRED");const copied=await copyStorage(plan.source,plan.destination);await write(join3(plan.destination,"backup-manifest.json"),canonicalLocalJson({protocol:"NVS_STORAGE_COPY_V1",planId:plan.id,...copied}));await save("COPIED",{bytes:copied.total})}if(plan.phase==="COPIED"){if(plan.mode==="MIGRATE"){if(installation.active.toolsConfigPath){const tools=LocalToolSelectionSchema.parse(JSON.parse((await read(installation.active.toolsConfigPath,32768)).toString()));if(tools.mode==="MANAGED"){for(const name of["ffmpeg","ffprobe"]){if(tools[name].path.startsWith(plan.source+sep3))tools[name].path=plan.destination+tools[name].path.slice(plan.source.length);else if(!tools[name].path.startsWith(plan.destination+sep3)||installation.active.toolsConfigPath!==join3(root,plan.id+"-tools.json"))fail("PLAN_CHANGED")}const toolsConfigPath=join3(root,plan.id+"-tools.json");await write(toolsConfigPath,canonicalLocalJson(tools));if(installation.active.toolsConfigPath!==toolsConfigPath)await manager.ledger.commit(installation,{active:{...installation.active,toolsConfigPath},transition:null})}}await manager.configure({...config,stateDirectory:plan.destination});await disableDesktopAutomation(home)}await save("VERIFYING")}if(plan.phase==="VERIFYING"){await manager.start();config=await manager.configuration();const inventory=await(await ownerClient(config.stateDirectory)).inventory();installation=(await manager.ledger.current()).value;if(canonicalLocalJson(inventory.descriptor)!==canonicalLocalJson(installation.active.descriptor))fail("STORAGE_COPY_INVALID");await save("COMPLETE")}return present(plan)}import{z as z3}from"zod";var DesktopOfflineRequestSchema=z3.strictObject({operation:z3.literal("offline"),call:LocalOfflineCallSchema});var DesktopOfflineReplySchema=LocalOfflinePageSchema;async function runDesktopOfflineRequest(home,raw){const{call}=DesktopOfflineRequestSchema.parse(raw),manager=await LocalInstallationManager.open(home),c=await manager.configuration();if(!(await manager.status()).running){const policy=await desktopAutomation(home),installation=await desktopInstallationIdentity(manager);if(!policy?.enabled||policy.installationFingerprint!==installation?.fingerprint||!await socketAbsent(c.stateDirectory))fail("RUNTIME_STATUS_REQUIRED");await manager.start()}const client=await ownerClient(c.stateDirectory);return LocalOfflinePageSchema.parse(await client.call({operation:"offline.workspace",input:call}))}import{z as z4}from"zod";import{join as join4}from"node:path";import{unlink as unlink2}from"node:fs/promises";var sha=z4.string().regex(/^[a-f0-9]{64}$/);var historyItem=z4.strictObject({id:z4.uuid(),projectId:z4.uuid(),productionId:z4.uuid(),kind:z4.enum(["IMAGE","VIDEO","ROUGH_CUT","PROGRAMMATIC"]),mediaFileId:z4.uuid().optional()});var stateSchema=z4.strictObject({grantFingerprint:sha.nullable(),pendingGrant:sha.nullable(),history:z4.array(historyItem).max(200)});var DesktopAgentRequestSchema=z4.strictObject({operation:z4.literal("agent"),scope:DesktopDeviceScopeSchema,call:z4.discriminatedUnion("action",[z4.strictObject({action:z4.literal("discover"),binary:z4.string().min(1).max(4096).optional()}),z4.strictObject({action:z4.literal("probe")}),z4.strictObject({action:z4.literal("grant"),grant:LocalAgentGrantSchema,approval:sha}),z4.strictObject({action:z4.literal("revoke")}),z4.strictObject({action:z4.literal("prepare"),snapshot:LocalAgentSnapshotSchema}),z4.strictObject({action:z4.literal("stage"),id:z4.uuid(),mediaFileId:z4.uuid().optional()}),z4.strictObject({action:z4.literal("start"),id:z4.uuid(),expectedRevision:z4.int().positive(),approval:sha}),z4.strictObject({action:z4.literal("inspect"),id:z4.uuid()})])});var DesktopAgentReplySchema=z4.strictObject({probe:LocalAgentProbeSchema.optional(),discovery:LocalAgentDiscoverySchema.optional(),review:LocalAgentReviewViewSchema.optional(),history:z4.array(historyItem.omit({mediaFileId:true}).extend({pendingMedia:z4.boolean()})).max(200),pendingGrant:z4.boolean()});async function runDesktopAgentRequest(home,raw){const{scope,call}=DesktopAgentRequestSchema.parse(raw),root=await directory(join4(home,"agent-owner",sha256(canonicalLocalJson(scope)))),path=join4(root,"current.json");let state=stateSchema.parse(await optional(path)??{grantFingerprint:null,pendingGrant:null,history:[]});const manager=await LocalInstallationManager.open(home),client=await ownerClient((await manager.configuration()).stateDirectory);const save=async value=>{state=stateSchema.parse({...state,...value});await write(path,canonicalLocalJson(state))};const result=fields=>DesktopAgentReplySchema.parse({...fields,history:state.history.map(({mediaFileId,...r})=>{return{...r,pendingMedia:!!mediaFileId}}),pendingGrant:!!state.pendingGrant});if(call.action==="discover"){const discovery=await client.discoverAgent(call.binary);const fp=discovery.configured?sha256(canonicalLocalJson(discovery.configured)):null;if(state.pendingGrant&&state.pendingGrant===fp)await save({grantFingerprint:fp,pendingGrant:null});return result({discovery:{...discovery,configured:fp===state.grantFingerprint?discovery.configured:null}})}if(call.action==="probe"){const probe=await client.probeAgent();if(state.pendingGrant&&probe.grantFingerprint===state.pendingGrant)await save({grantFingerprint:state.pendingGrant,pendingGrant:null});return result({probe:probe.grantFingerprint===state.grantFingerprint?probe:{...probe,available:false,configured:false,reason:"GRANT_REQUIRED",grantFingerprint:null}})}if(call.action==="grant"){if(state.pendingGrant)fail("AGENT_OUTCOME_UNKNOWN");if(call.grant.projects.some(p=>p.tenantId!==scope.tenantId)||sha256(canonicalLocalJson(call.grant))!==call.approval)fail("AGENT_APPROVAL_REQUIRED");await save({pendingGrant:call.approval});let probe;try{probe=await client.grantAgent(call.grant,call.approval)}catch(e){if(e instanceof NativeStudioSdkError&&["NO_WRITE","REJECTED"].includes(e.outcome))await save({pendingGrant:null});throw e}await save({pendingGrant:null,grantFingerprint:call.approval});return result({probe})}if(call.action==="revoke"){const probe=await client.probeAgent();if(!state.grantFingerprint||probe.grantFingerprint!==state.grantFingerprint)fail("AGENT_APPROVAL_REQUIRED");const revoked=await client.revokeAgent(state.grantFingerprint);await save({grantFingerprint:null,pendingGrant:null});return result({probe:revoked})}if(call.action==="prepare"){if(state.history.length>=200)fail("QUERY_LIMIT");if(state.pendingGrant||!state.grantFingerprint||call.snapshot.basis.scope.tenantId!==scope.tenantId)fail("AGENT_APPROVAL_REQUIRED");const review=await client.prepareAgentReview(call.snapshot);if(review.plan.grantFingerprint!==state.grantFingerprint)fail("AGENT_APPROVAL_REQUIRED");const s2=review.plan.snapshot.basis.scope;await save({history:[{id:review.plan.id,projectId:s2.projectId,productionId:s2.productionId,kind:review.plan.snapshot.basis.target.kind},...state.history]});return result({review})}const entry=state.history.find(h=>h.id===call.id);if(!entry)fail("AGENT_APPROVAL_REQUIRED");const original=await client.inspectAgentReview(call.id),s=original.plan.snapshot.basis.scope;if(s.tenantId!==scope.tenantId||s.projectId!==entry.projectId||s.productionId!==entry.productionId)fail("AGENT_APPROVAL_REQUIRED");const staged=!!(original.imageReceipt||original.evidenceReceipt);if(staged&&entry.mediaFileId){const file=join4(home,"agent-import",entry.mediaFileId+".bin");try{const bytes=await read(file,134217728);if(sha256(bytes)!==original.plan.snapshot.media.checksumSha256)fail("AGENT_IMAGE_INVALID");await unlink2(file)}catch(e){if(e.code!=="ENOENT")throw e}await save({history:state.history.map(h=>{if(h.id!==call.id)return h;const{mediaFileId,...item}=h;void mediaFileId;return item})})}if(call.action==="inspect"||call.action==="stage"&&staged)return result({review:original});if(call.action==="stage"){const mediaFileId=call.mediaFileId??entry.mediaFileId;if(!mediaFileId)fail("AGENT_IMAGE_REQUIRED");await save({history:state.history.map(h=>h.id===call.id?{...h,mediaFileId}:h)});const file=join4(home,"agent-import",mediaFileId+".bin"),bytes=await read(file,134217728);const review=await client.stageAgentImage(call.id,bytes);await unlink2(file);await save({history:state.history.map(h=>{if(h.id!==call.id)return h;const{mediaFileId:_id,...rest}=h;void _id;return rest})});return result({review})}if(state.pendingGrant||original.plan.grantFingerprint!==state.grantFingerprint)fail("AGENT_APPROVAL_REQUIRED");return result({review:await client.startAgentReview(call.id,call.expectedRevision,call.approval)})}import{z as z5}from"zod";var digest2=z5.string().regex(/^[a-f0-9]{64}$/);var DesktopBootstrapRequestSchema=z5.strictObject({operation:z5.literal("bootstrap"),call:z5.discriminatedUnion("action",[z5.strictObject({action:z5.literal("prepare")}),z5.strictObject({action:z5.literal("apply"),id:z5.uuid(),fingerprint:digest2})])});var DesktopBootstrapReplySchema=z5.strictObject({id:z5.uuid(),fingerprint:digest2,version:z5.string().min(1).max(80),host:z5.string().min(1).max(512),bytes:z5.int().positive(),expiresAt:z5.iso.datetime(),installed:z5.boolean()});import{z as z6}from"zod";var DesktopWorkspaceRequestSchema=z6.strictObject({operation:z6.literal("workspace"),call:z6.discriminatedUnion("action",[z6.strictObject({action:z6.enum(["inspect","clean","diagnostics"])}),z6.strictObject({action:z6.literal("configure"),policy:LocalResourcePolicySchema,expectedRevision:z6.int().nonnegative()}),z6.strictObject({action:z6.literal("activity"),idleSeconds:z6.int().min(0).max(86400),observedAt:z6.iso.datetime()})])});var DesktopWorkspaceReplySchema=z6.union([LocalWorkspaceInspectionSchema,LocalDiagnosticsSchema]);async function runDesktopWorkspaceRequest(home,raw){const request=DesktopWorkspaceRequestSchema.parse(raw);const manager=await LocalInstallationManager.open(home);const config=await manager.configuration();const client=await ownerClient(config.stateDirectory);const input=request.call;switch(input.action){case"inspect":return client.workspace.inspect();case"clean":return client.workspace.clean();case"diagnostics":return client.workspace.diagnostics();case"configure":return client.workspace.configure(input.policy,input.expectedRevision);case"activity":return client.workspace.observeActivity(input.idleSeconds,input.observedAt)}}var version=LocalRuntimeDescriptorSchema.shape.version;var fingerprint=z7.string().regex(/^[a-f0-9]{64}$/);var DesktopRuntimeChannelSchema=z7.strictObject({protocol:z7.literal("NVS_DESKTOP_RUNTIME_CHANNEL_V1"),catalogueUrl:z7.string().url().max(4096),publicKey:z7.string().min(32).max(16384)});var DesktopOwnerRequestSchema=z7.discriminatedUnion("operation",[DesktopLibraryRequestSchema,DesktopLibraryImportRequestSchema,DesktopLibraryPrepareRequestSchema,DesktopDeviceRequestSchema,DesktopWorkspaceRequestSchema,DesktopStorageRequestSchema,DesktopOfflineRequestSchema,DesktopAgentRequestSchema,DesktopBootstrapRequestSchema,z7.strictObject({operation:z7.literal("speech-prepare"),input:CpuSpeechPrepareInputSchema}),z7.strictObject({operation:z7.enum(["status","start","stop","check","configuration","recovery"])}),z7.strictObject({operation:z7.enum(["prepare","reject"]),version}),z7.strictObject({operation:z7.literal("tools-prepare"),version,choice:z7.discriminatedUnion("mode",[z7.strictObject({mode:z7.literal("MANAGED")}),z7.strictObject({mode:z7.literal("INSTALLED"),ffmpeg:z7.string().min(1).max(4096),ffprobe:z7.string().min(1).max(4096),compositionBrowser:z7.string().min(1).max(4096).optional()})])}),z7.strictObject({operation:z7.literal("configure"),channelFingerprint:fingerprint}),z7.strictObject({operation:z7.enum(["apply","recover"]),planId:z7.uuid(),fingerprint})]);var DesktopRuntimeStatusSchema=z7.strictObject({protocol:z7.literal("NVS_DESKTOP_RUNTIME_STATUS_V1"),state:z7.enum(["RUNNING","STOPPED","UNAVAILABLE","INSTALL_REQUIRED"]),activeVersion:version.nullable(),phase:z7.string().regex(/^[A-Z_]{1,64}$/),toolMode:z7.enum(["MANAGED","INSTALLED"]).nullable().optional(),speech:z7.strictObject({voiceIds:CpuSpeechPrepareInputSchema.shape.voiceIds}).optional()});var DesktopUpdateCheckSchema=z7.strictObject({protocol:z7.literal("NVS_DESKTOP_RUNTIME_UPDATES_V1"),activeVersion:version.nullable(),versions:z7.array(z7.strictObject({version,rejected:z7.boolean()})).max(128),notifications:z7.boolean()});var DesktopOwnerPlanSchema=z7.strictObject({protocol:z7.literal("NVS_DESKTOP_OWNER_PLAN_V1"),plan:z7.strictObject({kind:z7.enum(["APPLY","RECOVER"]),toolMode:z7.enum(["MANAGED","INSTALLED"]).optional(),planId:z7.uuid(),fingerprint,version,previousVersion:version.nullable(),expiresAt:z7.iso.datetime(),phase:z7.string().regex(/^[A-Z_]{1,64}$/)}).nullable()});var DesktopChannelInfoSchema=z7.strictObject({protocol:z7.literal("NVS_DESKTOP_CHANNEL_INFO_V1"),configured:z7.boolean(),source:z7.enum(["EXISTING","BUNDLED","UNAVAILABLE"]),host:z7.string().max(512).nullable(),channelFingerprint:fingerprint.nullable()});var desktopOwnerResponses={library:DesktopLibraryReplySchema,"library-import":DesktopLibraryReplySchema,"library-import-prepare":DesktopLibraryImportRequestSchema,device:DesktopDeviceReplySchema,workspace:DesktopWorkspaceReplySchema,storage:DesktopStorageReplySchema,offline:DesktopOfflineReplySchema,agent:DesktopAgentReplySchema,bootstrap:DesktopBootstrapReplySchema,status:DesktopRuntimeStatusSchema,start:DesktopRuntimeStatusSchema,stop:DesktopRuntimeStatusSchema,configure:DesktopRuntimeStatusSchema,apply:DesktopRuntimeStatusSchema,recover:DesktopRuntimeStatusSchema,reject:DesktopRuntimeStatusSchema,check:DesktopUpdateCheckSchema,configuration:DesktopChannelInfoSchema,prepare:DesktopOwnerPlanSchema,"tools-prepare":DesktopOwnerPlanSchema,"speech-prepare":DesktopOwnerPlanSchema,recovery:DesktopOwnerPlanSchema};export{runDesktopStorageRequest,runDesktopOfflineRequest,runDesktopAgentRequest,DesktopBootstrapRequestSchema,DesktopBootstrapReplySchema,runDesktopWorkspaceRequest,DesktopRuntimeChannelSchema,DesktopOwnerRequestSchema,DesktopRuntimeStatusSchema,DesktopChannelInfoSchema,desktopOwnerResponses};
@@ -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};