@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,24 +1,24 @@
1
1
  {
2
2
  "protocol": "NVS_PRODUCT_COMPATIBILITY_V1",
3
3
  "product": "@nativestudio/cli",
4
- "version": "0.3.0-rc.21",
4
+ "version": "0.3.0-rc.27",
5
5
  "source": {
6
- "head": "f54d283727f4868da9493fef91d466de35a4d837",
7
- "fileDigest": "dc04621c3cced1e96fefd731a32bae2f95364056bb828aabf46d7f22c5b85956",
6
+ "head": "ce2ac327e479f80c28d4f63b77011617dc30515c",
7
+ "fileDigest": "a00ad29c402778f07c0b921148aadaf23e9c3ffc935547bfcb2aa5fd7d5d8cfa",
8
8
  "dirty": false,
9
- "remoteMainHead": "f54d283727f4868da9493fef91d466de35a4d837"
9
+ "remoteMainHead": "ce2ac327e479f80c28d4f63b77011617dc30515c"
10
10
  },
11
11
  "node": ">=24.12 <25",
12
12
  "discoveryProfile": "contextual-v1",
13
13
  "accountProtocol": "NVS_CLI_ACCOUNT_V1",
14
14
  "component": {
15
15
  "protocol": "NVS_PRODUCT_COMPONENT_V2",
16
- "version": "0.3.0-rc.21",
17
- "byteSize": 3351261,
18
- "sha512": "f19614ffdc7f37b874309b8cbc48ee6b4428e623b85b19c1d63b6315bf19bb275170331e5b2c11af24e61a3bf0151f028de8d776cc6b06f9168c42d39256bf41",
16
+ "version": "0.3.0-rc.27",
17
+ "byteSize": 3396115,
18
+ "sha512": "805ae422a9e5a466b7dfa6e5dcc766a359fe0907a2fe96f8bce9e3baea37d7a34c7452d5a248b2a649a6e18d8c88be929e453fdba7dbf807b9637753754c7128",
19
19
  "descriptor": {
20
20
  "protocol": "NVS_RUNTIME_DESCRIPTOR_V1",
21
- "version": "0.3.0-rc.21",
21
+ "version": "0.3.0-rc.27",
22
22
  "node": {
23
23
  "major": 24,
24
24
  "minMinor": 12
@@ -26,15 +26,15 @@
26
26
  "ipcProtocol": "NVS_LOCAL_IPC_V1",
27
27
  "workProtocol": "NVS_LOCAL_WORK_V2",
28
28
  "journalSchema": 1,
29
- "rendererDigest": "a93cf499546133a210e2c9613df2f6163952e8c21476b3e5ff4806d1551d4dc1",
29
+ "rendererDigest": "6fd5f79e6e034b8102af4356c9d9e809903c8693520cebe10d730cb18b59534f",
30
30
  "profileDigest": "9c66c6384e7c5b63a182f8ad0cde0e2713c933d7c5319eb803b5059a84b9750e",
31
31
  "compatibleRenderers": [
32
32
  {
33
- "rendererDigest": "968bcf4ded43670e3d43e2a56a4964d55417e6c65e86fb73d22edd1ed75d16bb",
33
+ "rendererDigest": "89e9eae67062b04589eebe526e47a02e0fcddd1ae99fd4f17245fdf8fe211f55",
34
34
  "profileDigest": "bd6aa2bab59851c87f1176c3ef951564467bb42dc577f2f62844e8744be06a87"
35
35
  },
36
36
  {
37
- "rendererDigest": "96cc41de8a1af268f8750d74f8b3ad9ea01620526ca08752e9bb0b03aab490e3",
37
+ "rendererDigest": "eaa6d1228b833d6bc91f1dc418a8c743a22ff6bd12191afbcd78b024d6b30866",
38
38
  "profileDigest": "7c1379a543fb3cf43cc87bfa571cd1994a5c82a6b1fc3b3cce75e23b13e8a4fc"
39
39
  }
40
40
  ]
@@ -1,11 +1,11 @@
1
1
  {
2
2
  "protocol": "NVS_PRODUCT_COMPONENT_V2",
3
- "version": "0.3.0-rc.21",
4
- "byteSize": 3351261,
5
- "sha512": "f19614ffdc7f37b874309b8cbc48ee6b4428e623b85b19c1d63b6315bf19bb275170331e5b2c11af24e61a3bf0151f028de8d776cc6b06f9168c42d39256bf41",
3
+ "version": "0.3.0-rc.27",
4
+ "byteSize": 3396115,
5
+ "sha512": "805ae422a9e5a466b7dfa6e5dcc766a359fe0907a2fe96f8bce9e3baea37d7a34c7452d5a248b2a649a6e18d8c88be929e453fdba7dbf807b9637753754c7128",
6
6
  "descriptor": {
7
7
  "protocol": "NVS_RUNTIME_DESCRIPTOR_V1",
8
- "version": "0.3.0-rc.21",
8
+ "version": "0.3.0-rc.27",
9
9
  "node": {
10
10
  "major": 24,
11
11
  "minMinor": 12
@@ -13,15 +13,15 @@
13
13
  "ipcProtocol": "NVS_LOCAL_IPC_V1",
14
14
  "workProtocol": "NVS_LOCAL_WORK_V2",
15
15
  "journalSchema": 1,
16
- "rendererDigest": "a93cf499546133a210e2c9613df2f6163952e8c21476b3e5ff4806d1551d4dc1",
16
+ "rendererDigest": "6fd5f79e6e034b8102af4356c9d9e809903c8693520cebe10d730cb18b59534f",
17
17
  "profileDigest": "9c66c6384e7c5b63a182f8ad0cde0e2713c933d7c5319eb803b5059a84b9750e",
18
18
  "compatibleRenderers": [
19
19
  {
20
- "rendererDigest": "968bcf4ded43670e3d43e2a56a4964d55417e6c65e86fb73d22edd1ed75d16bb",
20
+ "rendererDigest": "89e9eae67062b04589eebe526e47a02e0fcddd1ae99fd4f17245fdf8fe211f55",
21
21
  "profileDigest": "bd6aa2bab59851c87f1176c3ef951564467bb42dc577f2f62844e8744be06a87"
22
22
  },
23
23
  {
24
- "rendererDigest": "96cc41de8a1af268f8750d74f8b3ad9ea01620526ca08752e9bb0b03aab490e3",
24
+ "rendererDigest": "eaa6d1228b833d6bc91f1dc418a8c743a22ff6bd12191afbcd78b024d6b30866",
25
25
  "profileDigest": "7c1379a543fb3cf43cc87bfa571cd1994a5c82a6b1fc3b3cce75e23b13e8a4fc"
26
26
  }
27
27
  ]
Binary file
@@ -0,0 +1 @@
1
+ import{inspectRecoveryBackups}from"./chunk-KGS6SI5Y.js";import{probeBackupCoverage}from"./chunk-KAW7T5TR.js";import{socketAbsent}from"./chunk-6YVGVNEH.js";import{withConfiguredLifecycle}from"./chunk-LVVSTKDW.js";import"./chunk-EOWXXTEF.js";import{LocalBackupRetirementPlanSchema,LocalBackupRetirementReceiptSchema,canonicalLocalJson}from"./chunk-UOYNCE7I.js";import{fail,privateAccess,sha256,syncDirectory}from"./chunk-AZQLZA47.js";import"./chunk-M32FI2OA.js";import"./chunk-TT7IA5HB.js";import{lstat,realpath,unlink}from"node:fs/promises";import{basename,join}from"node:path";import{z}from"zod";var inputSchema=z.strictObject({remove:z.uuid(),retain:z.uuid()}).refine(v=>v.remove!==v.retain);async function identity(path){await privateAccess(path,"file");if(await realpath(path)!==path)fail("BACKUP_RETIREMENT_NOT_PROVEN","NO_WRITE");const s=await lstat(path,{bigint:true});if(!s.isFile()||s.isSymbolicLink()||s.nlink!==1n)fail("BACKUP_RETIREMENT_NOT_PROVEN","NO_WRITE");for(const suffix of["-wal","-shm","-journal"]){try{await lstat(path+suffix);fail("BACKUP_RETIREMENT_NOT_PROVEN","NO_WRITE")}catch(error){if(error.code!=="ENOENT")throw error}}return{dev:s.dev,ino:s.ino,size:s.size,mtime:s.mtimeNs,ctime:s.ctimeNs,links:s.nlink}}function same(a,b){return Object.keys(a).every(k=>a[k]===b[k])}async function basis(manager,raw){const input=inputSchema.parse(raw),c=await manager.configuration();const history=await manager.ledger.recoveryBackupReferences();if(!history.value.active||history.value.transition||!await socketAbsent(c.stateDirectory))fail("BACKUP_RETIREMENT_NOT_PROVEN","NO_WRITE");const directory=join(c.stateDirectory,"backups");await privateAccess(directory,"directory");if(await realpath(directory)!==directory)fail("BACKUP_RETIREMENT_NOT_PROVEN","NO_WRITE");const removeName=input.remove+".sqlite",retainName=input.retain+".sqlite";if([...history.paths].some(path=>basename(path).toLowerCase()===removeName.toLowerCase()))fail("BACKUP_STILL_REFERENCED","NO_WRITE");const removePath=join(directory,removeName),retainPath=join(directory,retainName);const beforeRemove=await identity(removePath),beforeRetain=await identity(retainPath);const reports=await inspectRecoveryBackups(manager.ledger.slotPath(history.value.active),history.value.active,c.stateDirectory,[removeName,retainName],null,true);const remove=reports.find(r=>r.id===input.remove),retain=reports.find(r=>r.id===input.retain);if(!remove||!retain||!remove.recordSetFingerprint||!retain.recordSetFingerprint||retain.recordCount<remove.recordCount||retain.epoch<remove.epoch)fail("BACKUP_REPLACEMENT_NOT_EQUIVALENT","NO_WRITE");const equivalent=remove.recordSetFingerprint===retain.recordSetFingerprint;if(!equivalent){const proof=await probeBackupCoverage(manager.ledger.slotPath(history.value.active),history.value.active,c.stateDirectory,removePath,retainPath);if(!proof.covered||proof.remove.sha256!==remove.sha256||proof.retain.sha256!==retain.sha256||proof.remove.recordSetFingerprint!==remove.recordSetFingerprint||proof.retain.recordSetFingerprint!==retain.recordSetFingerprint)fail("BACKUP_REPLACEMENT_NOT_EQUIVALENT","NO_WRITE")}const snapshot=r=>({id:r.id,sha256:r.sha256,byteSize:r.byteSize,epoch:r.epoch});const body={protocol:"NVS_LOCAL_BACKUP_RETIREMENT_V1",installationRevision:history.value.revision,remove:snapshot(remove),retain:snapshot(retain),recordSetFingerprint:remove.recordSetFingerprint,...equivalent?{}:{coverage:"COVERED",retainedRecordSetFingerprint:retain.recordSetFingerprint}};const plan=LocalBackupRetirementPlanSchema.parse({...body,fingerprint:sha256(canonicalLocalJson({...body,installationDigest:history.digest,configuration:c}))});async function assertCurrent(){if(!same(beforeRemove,await identity(removePath))||!same(beforeRetain,await identity(retainPath))||(await manager.ledger.current()).digest!==history.digest||canonicalLocalJson(await manager.configuration())!==canonicalLocalJson(c)||!await socketAbsent(c.stateDirectory))fail("REVISION_CONFLICT","NO_WRITE")}await assertCurrent();return{plan,removePath,directory,assertCurrent}}function prepareBackupRetirement(manager,raw){return withConfiguredLifecycle(manager,async()=>(await basis(manager,raw)).plan)}function applyBackupRetirement(manager,raw,approval){return withConfiguredLifecycle(manager,async()=>{const{plan,removePath,directory,assertCurrent}=await basis(manager,raw);if(plan.fingerprint!==approval)fail("USER_APPROVAL_REQUIRED","NO_WRITE");await assertCurrent();await unlink(removePath);await syncDirectory(directory);return LocalBackupRetirementReceiptSchema.parse({semanticStatus:"RETIRED",plan,reclaimedBytes:plan.remove.byteSize})})}export{applyBackupRetirement,prepareBackupRetirement};
@@ -0,0 +1 @@
1
+ import{callerOriginMatches,localCaller,workspaceCaller}from"./chunk-SCOSFTMM.js";import"./chunk-Q7MTMC6D.js";import"./chunk-VJ4SCIR5.js";import"./chunk-UFUFQA5U.js";import"./chunk-4UQRT3ZH.js";import"./chunk-DBOQPJLY.js";import"./chunk-2UYKJ6YN.js";import"./chunk-XMZKBILZ.js";import"./chunk-UOYNCE7I.js";import"./chunk-IKJ6VNJ6.js";import"./chunk-ISPIV2P6.js";import"./chunk-CBJIFAHD.js";import"./chunk-AZQLZA47.js";import"./chunk-Z44SK6DZ.js";import"./chunk-M32FI2OA.js";import"./chunk-NEZ7IY5E.js";import"./chunk-TT7IA5HB.js";export{callerOriginMatches,localCaller,workspaceCaller};
@@ -1 +1 @@
1
- import{DesktopDeviceScopeSchema}from"./chunk-SM2I7TJ3.js";import{canonicalLocalJson}from"./chunk-2S7FI3HF.js";import{fail,optional,read,sha256,write}from"./chunk-DLW42PJ6.js";import{join}from"node:path";import{z}from"zod";var digest=z.string().regex(/^[a-f0-9]{64}$/);var DesktopAutomationSchema=z.strictObject({enabled:z.boolean(),scope:DesktopDeviceScopeSchema,deviceId:z.uuid(),deviceRevision:z.int().positive(),installationFingerprint:digest});async function desktopInstallationIdentity(manager){const active=(await manager.ledger.current()).value.active;if(!active)return null;const tools=active.toolsConfigPath?JSON.parse((await read(active.toolsConfigPath,32768)).toString()):null;return{version:active.descriptor.version,workProtocol:active.descriptor.workProtocol,fingerprint:sha256(canonicalLocalJson({descriptor:active.descriptor,files:active.files,tools}))}}async function desktopAutomation(home){const value=await optional(join(home,"desktop-execution-policy.json"));return value?DesktopAutomationSchema.parse(value):null}function canResumeDesktop(policy,state,installation){if(!policy?.enabled||!installation||!state.device||policy.installationFingerprint!==installation.fingerprint||canonicalLocalJson(policy.scope)!==canonicalLocalJson(state.scope)||policy.deviceId!==state.device.deviceId||policy.deviceRevision!==state.device.revision)return false;return state.device.revokedAt===null}async function rememberDesktopAutomation(home,state,installation,expectedFingerprint){if(!installation||installation.fingerprint!==expectedFingerprint||!state.device)fail("DEVICE_PLAN_CHANGED");const value=DesktopAutomationSchema.parse({enabled:true,scope:state.scope,deviceId:state.device.deviceId,deviceRevision:state.device.revision,installationFingerprint:expectedFingerprint});await write(join(home,"desktop-execution-policy.json"),canonicalLocalJson(value));return value}async function disableDesktopAutomation(home){const policy=await desktopAutomation(home);if(policy)await write(join(home,"desktop-execution-policy.json"),canonicalLocalJson({...policy,enabled:false}))}export{desktopInstallationIdentity,desktopAutomation,canResumeDesktop,rememberDesktopAutomation,disableDesktopAutomation};
1
+ import{DesktopDeviceScopeSchema}from"./chunk-EPH3TRYV.js";import{canonicalLocalJson}from"./chunk-UOYNCE7I.js";import{fail,optional,read,sha256,write}from"./chunk-AZQLZA47.js";import{join}from"node:path";import{z}from"zod";var digest=z.string().regex(/^[a-f0-9]{64}$/);var DesktopAutomationSchema=z.strictObject({enabled:z.boolean(),scope:DesktopDeviceScopeSchema,deviceId:z.uuid(),deviceRevision:z.int().positive(),installationFingerprint:digest});async function desktopInstallationIdentity(manager){const active=(await manager.ledger.current()).value.active;if(!active)return null;const tools=active.toolsConfigPath?JSON.parse((await read(active.toolsConfigPath,32768)).toString()):null;return{version:active.descriptor.version,workProtocol:active.descriptor.workProtocol,fingerprint:sha256(canonicalLocalJson({descriptor:active.descriptor,files:active.files,tools}))}}async function desktopAutomation(home){const value=await optional(join(home,"desktop-execution-policy.json"));return value?DesktopAutomationSchema.parse(value):null}function canResumeDesktop(policy,state,installation){if(!policy?.enabled||!installation||!state.device||policy.installationFingerprint!==installation.fingerprint||canonicalLocalJson(policy.scope)!==canonicalLocalJson(state.scope)||policy.deviceId!==state.device.deviceId||policy.deviceRevision!==state.device.revision)return false;return state.device.revokedAt===null}async function rememberDesktopAutomation(home,state,installation,expectedFingerprint){if(!installation||installation.fingerprint!==expectedFingerprint||!state.device)fail("DEVICE_PLAN_CHANGED");const value=DesktopAutomationSchema.parse({enabled:true,scope:state.scope,deviceId:state.device.deviceId,deviceRevision:state.device.revision,installationFingerprint:expectedFingerprint});await write(join(home,"desktop-execution-policy.json"),canonicalLocalJson(value));return value}async function disableDesktopAutomation(home){const policy=await desktopAutomation(home);if(policy)await write(join(home,"desktop-execution-policy.json"),canonicalLocalJson({...policy,enabled:false}))}export{desktopInstallationIdentity,desktopAutomation,canResumeDesktop,rememberDesktopAutomation,disableDesktopAutomation};
@@ -0,0 +1 @@
1
+ import{probeTenantOpenAiAsr,probeTenantOpenAiRealtimeSpeech}from"./chunk-LZAC64FB.js";import{probeTenantQwenGeneration}from"./chunk-6YVGVNEH.js";import{canonicalLocalJson}from"./chunk-UOYNCE7I.js";import{fail,read}from"./chunk-AZQLZA47.js";import{isAbsolute}from"node:path";var openAiRoutes={TRANSCRIBE_EXTERNAL_OPENAI:probeTenantOpenAiAsr,SPEECH_EXTERNAL_OPENAI_REALTIME:probeTenantOpenAiRealtimeSpeech};var routes=[["KEYFRAME_GENERATE","keyframe"],["VIDEO_GENERATE","video"],["SPEECH_EXTERNAL_QWEN","speech"],["TRANSCRIBE_EXTERNAL_QWEN","asr"]];function externalProviderKinds(kinds){return[...routes.filter(([kind])=>kinds?.includes(kind)).map(([kind])=>kind),...Object.keys(openAiRoutes).filter(kind=>kinds?.includes(kind))]}function hasProviderSelection(raw){if(!raw||typeof raw!=="object")return false;const value=raw;return value.qwenDeviceCredentials!==void 0||Array.isArray(value.processorCapabilities)&&externalProviderKinds(value.processorCapabilities).length>0}async function providerCredentialFileState(privateKeyFile){if(!isAbsolute(privateKeyFile))return"UNAVAILABLE";let bytes;try{bytes=await read(privateKeyFile,4096)}catch(error){return error.code==="ENOENT"?"MISSING":"UNAVAILABLE"}try{return/^[!-~]{8,4096}$/.test(bytes.toString("utf8").trim())?"READABLE":"UNAVAILABLE"}finally{bytes.fill(0)}}async function validateProviderSelection(manager,active,input){const selected=routes.filter(([processor])=>input.processorCapabilities?.includes(processor));if(selected.some(([,kind])=>kind!=="speech")!==Boolean(input.qwenDeviceCredentials?.length))fail("LOCAL_PROFILE_UNAVAILABLE");const seen=new Set;for(const credential of input.qwenDeviceCredentials??[]){const{privateKeyFile,...scope}=credential;const identity=canonicalLocalJson(scope);if(scope.tenantId!==input.tenantId||!isAbsolute(privateKeyFile)||seen.has(identity))fail("PROVIDER_CREDENTIAL_UNAVAILABLE");seen.add(identity);if(await providerCredentialFileState(privateKeyFile)!=="READABLE")fail("PROVIDER_CREDENTIAL_UNAVAILABLE")}for(const[,kind]of selected){if(!active||!await probeTenantQwenGeneration(manager.ledger.slotPath(active),active,kind))fail("LOCAL_PROFILE_UNAVAILABLE")}for(const[kind,probe]of Object.entries(openAiRoutes)){if(!input.processorCapabilities?.includes(kind))continue;if(!active||!await probe(manager.ledger.slotPath(active),active))fail("LOCAL_PROFILE_UNAVAILABLE")}}export{externalProviderKinds,hasProviderSelection,providerCredentialFileState,validateProviderSelection};
@@ -1 +1 @@
1
- import{privateAccess}from"./chunk-DLW42PJ6.js";import{open,constants}from"node:fs/promises";import{resolve}from"node:path";var limit=18*1024*1024;async function readInput(path,stdin,privateInput=false,signal){signal?.throwIfAborted();let bytes;if(path==="-"){const chunks=[];let size=0;const iterator=stdin[Symbol.asyncIterator]();try{while(true){signal?.throwIfAborted();let stopped;const pending=iterator.next();if(signal?.aborted){void pending.catch(()=>{});signal.throwIfAborted()}const next=signal?await Promise.race([pending,new Promise((_,reject)=>{stopped=()=>reject(signal.reason);signal.addEventListener("abort",stopped,{once:true})})]).finally(()=>{if(stopped)signal.removeEventListener("abort",stopped)}):await pending;if(next.done)break;size+=next.value.byteLength;if(size>limit)throw Error();chunks.push(Buffer.from(next.value))}}finally{void iterator.return?.().catch(()=>{})}bytes=chunks.length===1?chunks[0]:Buffer.concat(chunks,size)}else{if(privateInput&&process.platform==="win32")await privateAccess(resolve(path),"file");const handle=await open(path,constants.O_RDONLY|constants.O_NOFOLLOW|constants.O_NONBLOCK);try{const stat=await handle.stat();if(!stat.isFile()||stat.size>limit||privateInput&&process.platform!=="win32"&&((stat.mode&63)!==0||process.getuid&&stat.uid!==process.getuid()))throw Error();bytes=Buffer.alloc(stat.size+1);let used=0;while(used<bytes.byteLength){signal?.throwIfAborted();const read=await handle.read(bytes,used,bytes.byteLength-used,null);if(!read.bytesRead)break;used+=read.bytesRead}if(used!==stat.size)throw Error();bytes=bytes.subarray(0,used)}finally{await handle.close()}}signal?.throwIfAborted();const value=JSON.parse(new TextDecoder("utf-8",{fatal:true}).decode(bytes));if(!value||typeof value!=="object"||Array.isArray(value))throw Error();return value}async function readCredential(options,environment){if(options.has("--token-file")===options.has("--token-env"))throw Error();let token;const key=options.get("--token-env");if(key){if(!/^[A-Z][A-Z0-9_]{0,127}$/.test(key))throw Error();token=environment[key]??""}else{if(process.platform==="win32")await privateAccess(resolve(options.get("--token-file")),"file");const handle=await open(options.get("--token-file"),constants.O_RDONLY|constants.O_NOFOLLOW|constants.O_NONBLOCK);try{const stat=await handle.stat();if(!stat.isFile()||process.platform!=="win32"&&(stat.mode&63)!==0||stat.size>8192)throw Error();const bytes=Buffer.alloc(8193);const{bytesRead}=await handle.read(bytes,0,bytes.length,0);if(bytesRead>8192)throw Error();token=bytes.subarray(0,bytesRead).toString("utf8").trim()}finally{await handle.close()}}if(!/^[A-Za-z0-9._~-]{1,8192}$/.test(token))throw Error();return"Bearer "+token}export{readInput,readCredential};
1
+ import{privateAccess}from"./chunk-AZQLZA47.js";import{open,constants}from"node:fs/promises";import{resolve}from"node:path";var limit=18*1024*1024;async function readInput(path,stdin,privateInput=false,signal){signal?.throwIfAborted();let bytes;if(path==="-"){const chunks=[];let size=0;const iterator=stdin[Symbol.asyncIterator]();try{while(true){signal?.throwIfAborted();let stopped;const pending=iterator.next();if(signal?.aborted){void pending.catch(()=>{});signal.throwIfAborted()}const next=signal?await Promise.race([pending,new Promise((_,reject)=>{stopped=()=>reject(signal.reason);signal.addEventListener("abort",stopped,{once:true})})]).finally(()=>{if(stopped)signal.removeEventListener("abort",stopped)}):await pending;if(next.done)break;size+=next.value.byteLength;if(size>limit)throw Error();chunks.push(Buffer.from(next.value))}}finally{void iterator.return?.().catch(()=>{})}bytes=chunks.length===1?chunks[0]:Buffer.concat(chunks,size)}else{if(privateInput&&process.platform==="win32")await privateAccess(resolve(path),"file");const handle=await open(path,constants.O_RDONLY|constants.O_NOFOLLOW|constants.O_NONBLOCK);try{const stat=await handle.stat();if(!stat.isFile()||stat.size>limit||privateInput&&process.platform!=="win32"&&((stat.mode&63)!==0||process.getuid&&stat.uid!==process.getuid()))throw Error();bytes=Buffer.alloc(stat.size+1);let used=0;while(used<bytes.byteLength){signal?.throwIfAborted();const read=await handle.read(bytes,used,bytes.byteLength-used,null);if(!read.bytesRead)break;used+=read.bytesRead}if(used!==stat.size)throw Error();bytes=bytes.subarray(0,used)}finally{await handle.close()}}signal?.throwIfAborted();const value=JSON.parse(new TextDecoder("utf-8",{fatal:true}).decode(bytes));if(!value||typeof value!=="object"||Array.isArray(value))throw Error();return value}async function readCredential(options,environment){if(options.has("--token-file")===options.has("--token-env"))throw Error();let token;const key=options.get("--token-env");if(key){if(!/^[A-Z][A-Z0-9_]{0,127}$/.test(key))throw Error();token=environment[key]??""}else{if(process.platform==="win32")await privateAccess(resolve(options.get("--token-file")),"file");const handle=await open(options.get("--token-file"),constants.O_RDONLY|constants.O_NOFOLLOW|constants.O_NONBLOCK);try{const stat=await handle.stat();if(!stat.isFile()||process.platform!=="win32"&&(stat.mode&63)!==0||stat.size>8192)throw Error();const bytes=Buffer.alloc(8193);const{bytesRead}=await handle.read(bytes,0,bytes.length,0);if(bytesRead>8192)throw Error();token=bytes.subarray(0,bytesRead).toString("utf8").trim()}finally{await handle.close()}}if(!/^[A-Za-z0-9._~-]{1,8192}$/.test(token))throw Error();return"Bearer "+token}export{readInput,readCredential};
@@ -0,0 +1 @@
1
+ import{assertCpuPreparationCurrent}from"./chunk-QCBLU6D6.js";import{captureWhisperSelection,embeddedRuntime}from"./chunk-QLHMJUBH.js";import{probeSelectedModels,verifySlot}from"./chunk-6YVGVNEH.js";import{LocalManagedModelSchema,LocalModelDisablePlanSchema,LocalModelInventorySchema,LocalToolChoiceSchema,LocalToolSelectionSchema,LocalWhisperPrepareInputSchema,LocalWhisperPreparePlanSchema,canonicalLocalJson,cpuSpeechResources,kokoroCpuProfile,whisperCppRecognitionProfile}from"./chunk-UOYNCE7I.js";import{fail,read}from"./chunk-AZQLZA47.js";async function selected(path){return path?LocalToolSelectionSchema.parse(JSON.parse((await read(path,32768)).toString())):null}async function inspectInstalledModels(manager){const current=manager?(await manager.ledger.current()).value:null;if(current?.transition)fail("ACTIVATION_IN_PROGRESS");const slot=current?.active;const tools=await selected(slot?.toolsConfigPath);const cpu=tools?.cpuSpeech;const whisper=tools?.mode==="INSTALLED"?tools.whisper:void 0;const checked=manager&&slot&&(cpu||whisper)?await probeSelectedModels(manager.ledger.slotPath(slot),slot):null;if(manager&&current&&((await manager.ledger.current()).value.revision!==current.revision||canonicalLocalJson(await selected(slot?.toolsConfigPath))!==canonicalLocalJson(tools)))fail("REVISION_CONFLICT");return LocalModelInventorySchema.parse({protocol:"NVS_LOCAL_MODEL_INVENTORY_V1",installationRevision:current?.revision??0,runtimeVersion:slot?.descriptor.version??null,models:[{model:"CPU_SPEECH",profileId:kokoroCpuProfile.id,engineVersion:kokoroCpuProfile.engineVersion,modelDigest:kokoroCpuProfile.modelDigest,platformSupported:cpuSpeechResources.engines.some(engine=>engine.platform===process.platform+"-"+process.arch),selected:!!cpu,integrity:cpu?checked?.CPU_SPEECH&&checked.CPU_SPEECH!=="NOT_SELECTED"?checked.CPU_SPEECH:"NOT_PROVEN":"NOT_SELECTED",voiceIds:cpu?.voiceIds??[]},{model:"WHISPER",profileId:whisperCppRecognitionProfile.id,sourceRevision:whisperCppRecognitionProfile.sourceRevision,modelDigest:whisperCppRecognitionProfile.modelSha256,platformSupported:process.platform==="darwin"&&process.arch==="arm64",selected:!!whisper,integrity:whisper?checked?.WHISPER&&checked.WHISPER!=="NOT_SELECTED"?checked.WHISPER:"NOT_PROVEN":"NOT_SELECTED"}]})}function modelDisableChoice(tools,raw){const model=LocalManagedModelSchema.parse(raw);if(model==="CPU_SPEECH"&&!tools.cpuSpeech||model==="WHISPER"&&(tools.mode!=="INSTALLED"||!tools.whisper))fail("MODEL_NOT_SELECTED","NO_WRITE");if(tools.mode==="MANAGED")return LocalToolChoiceSchema.parse({mode:"MANAGED",reuseMedia:{schemaVersion:1,ffmpeg:tools.ffmpeg,ffprobe:tools.ffprobe}});const choice={...tools};if(model==="CPU_SPEECH")delete choice.cpuSpeech;else delete choice.whisper;return LocalToolChoiceSchema.parse(choice)}async function prepareModelSelection(manager,expectedRevision,choose){const current=(await manager.ledger.current()).value;if(expectedRevision!==void 0&&current.revision!==expectedRevision)fail("REVISION_CONFLICT","NO_WRITE");if(current.transition)fail("ACTIVATION_IN_PROGRESS","NO_WRITE");if(!current.active)fail("INSTALL_REQUIRED","NO_WRITE");const slot=current.active;const context={revision:current.revision,configuration:await manager.configuration()};await verifySlot(manager.ledger.slotPath(slot),slot);const tools=await selected(slot.toolsConfigPath);if(!tools)fail("MODEL_NOT_SELECTED","NO_WRITE");const choice=await choose(tools);await assertCpuPreparationCurrent(manager,context);if(canonicalLocalJson(await selected(slot.toolsConfigPath))!==canonicalLocalJson(tools))fail("REVISION_CONFLICT");const plan=await(await embeddedRuntime(slot.descriptor.version)?manager.prepareBundled(slot.descriptor.version,choice):manager.prepare(slot.descriptor.version,choice));await assertCpuPreparationCurrent(manager,context,plan.installationRevision);if(canonicalLocalJson(await selected(slot.toolsConfigPath))!==canonicalLocalJson(tools))fail("REVISION_CONFLICT");return{semanticStatus:"PREPARED",planId:plan.planId,fingerprint:plan.fingerprint,version:plan.release.descriptor.version,expiresAt:plan.expiresAt}}async function prepareModelDisable(manager,raw,expectedRevision){const model=LocalManagedModelSchema.parse(raw);const plan=await prepareModelSelection(manager,expectedRevision,async tools=>modelDisableChoice(tools,model));return LocalModelDisablePlanSchema.parse({...plan,model,removal:"DEACTIVATE_SELECTION_ONLY"})}function whisperModelChoice(tools,whisper){if(tools.mode!=="INSTALLED")fail("INSTALLED_TOOLS_REQUIRED","NO_WRITE");return LocalToolChoiceSchema.parse({...tools,whisper})}async function prepareWhisperModel(manager,raw){const input=LocalWhisperPrepareInputSchema.parse(raw);const plan=await prepareModelSelection(manager,input.expectedRevision,async tools=>{if(tools.mode!=="INSTALLED")fail("INSTALLED_TOOLS_REQUIRED","NO_WRITE");return whisperModelChoice(tools,await captureWhisperSelection(input))});return LocalWhisperPreparePlanSchema.parse({...plan,model:"WHISPER",selection:"PREPARE_PINNED_SELECTION"})}export{inspectInstalledModels,modelDisableChoice,prepareModelDisable,whisperModelChoice,prepareWhisperModel};
@@ -0,0 +1 @@
1
+ import{NativeStudioLocalRuntimeClient}from"./chunk-EOWXXTEF.js";import{LocalDoctorReportSchema,LocalModelIntegrityReportSchema,LocalRuntimeDescriptorSchema,LocalToolSelectionSchema,canonicalLocalJson,importedNormalizationValidationProfile,localLibraryProfile,referenceThumbnailProfile,tenantRenderValidationProfile}from"./chunk-UOYNCE7I.js";import{digestPrivateFile,directory,fail,localSocketPath,read,runtimeLoginProtocol,sha256,write}from"./chunk-AZQLZA47.js";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}from"node:fs/promises";import{dirname,join,delimiter}from"node:path";import{z}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=[],timeoutMs=1e4){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"),timeoutMs);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 probeSelectedModels(root,slot){if(!slot.toolsConfigPath)return null;await verifySlot(root,slot);try{const bytes=await probeEntry(root,"--inspect-selected-models",["--tools-config",slot.toolsConfigPath],3e4);return LocalModelIntegrityReportSchema.parse(JSON.parse(bytes.toString()))}catch{return null}}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 open(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}=await import("node:fs/promises");try{if(process.platform!=="win32")await lstat(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=z.strictObject({tool:z.enum(["FFMPEG","FFPROBE"]),stage:z.enum(["IDENTITY","VERSION","ENCODERS","DECODERS","FILTERS","DEMUXERS","MUXERS","FINAL_IDENTITY"]),cause:z.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")}export{requiredRuntimeFiles,allowedRuntimeFiles,runtimeEnvironment,verifySlot,probeEntry,probeTenantMediaValidation,probeTenantMediaProcessing,probeReferenceThumbnail,probeLocalLibrary,probeTenantComposition,probeTenantSpeech,probeTenantTranscription,probeTenantQwenGeneration,probeSelectedModels,probe,supportsLoginService,ownerClient,runningInventory,launch,waitStopped,socketAbsent,probeTools};
@@ -1 +1 @@
1
- import{DesktopChannelInfoSchema,DesktopRuntimeChannelSchema}from"./chunk-WLQMICJN.js";import{endpoint}from"./chunk-LDBXGRCQ.js";import{canonicalLocalJson}from"./chunk-2S7FI3HF.js";import{LocalClientError,fail,read,sha256,write}from"./chunk-DLW42PJ6.js";import{createPublicKey}from"node:crypto";import{join}from"node:path";function desktopRuntimeChannel(raw){const channel=DesktopRuntimeChannelSchema.parse(raw);const url=endpoint(channel.catalogueUrl),key=createPublicKey(channel.publicKey);if(key.asymmetricKeyType!=="ed25519"||channel.publicKey.replace(/\r\n/g,"\n").trim()!==key.export({type:"spki",format:"pem"}).toString().trim())fail("RELEASE_SIGNATURE_INVALID");const value={...channel,catalogueUrl:url.href,publicKey:key.export({type:"spki",format:"pem"}).toString()};return{value,host:url.host,fingerprint:sha256(canonicalLocalJson(value))}}async function desktopChannelInfo(manager,bundled){let channel,configured=false;try{const config=await manager.configuration();if(!config.catalogueUrl||!config.publicKeyFile)fail("DEPENDENCY_CHANNEL_REQUIRED");channel=desktopRuntimeChannel({protocol:"NVS_DESKTOP_RUNTIME_CHANNEL_V1",catalogueUrl:config.catalogueUrl,publicKey:(await read(config.publicKeyFile,16384)).toString()});configured=true}catch(error){if(!(error instanceof LocalClientError&&["CONFIGURATION_REQUIRED","DEPENDENCY_CHANNEL_REQUIRED"].includes(error.code)))throw error;if(bundled!==void 0)channel=desktopRuntimeChannel(bundled)}return DesktopChannelInfoSchema.parse({protocol:"NVS_DESKTOP_CHANNEL_INFO_V1",configured,source:configured?"EXISTING":channel?"BUNDLED":"UNAVAILABLE",host:channel?.host??null,channelFingerprint:channel?.fingerprint??null})}async function configureDesktopChannel(manager,expectedFingerprint,bundled){const info=await desktopChannelInfo(manager,bundled);if(!info.channelFingerprint)fail("DESKTOP_CHANNEL_REQUIRED");if(info.channelFingerprint!==expectedFingerprint)fail("DESKTOP_CHANNEL_CHANGED");if(info.configured)return;let existing;try{existing=await manager.configuration()}catch(e){if(!(e instanceof LocalClientError&&e.code==="CONFIGURATION_REQUIRED"))throw e}const stateDirectory=existing?.stateDirectory??join(manager.ledger.root,"runtime-state");if(process.platform!=="win32"&&Buffer.byteLength(join(stateDirectory,"runtime.sock"))>100)fail("SOCKET_PATH_TOO_LONG");const channel=desktopRuntimeChannel(bundled),publicKeyFile=join(manager.ledger.root,"desktop-release-"+channel.fingerprint+".pem");try{await write(publicKeyFile,channel.value.publicKey,true)}catch(error){if(error.code!=="EEXIST")throw error;if((await read(publicKeyFile,16384)).toString()!==channel.value.publicKey)fail("DESKTOP_CHANNEL_CHANGED")}try{await manager.configure({...existing,stateDirectory,catalogueUrl:channel.value.catalogueUrl,publicKeyFile,notifications:true},{ifAbsent:!existing})}catch(error){if(error.code==="EEXIST")fail("DESKTOP_CHANNEL_CHANGED");throw error}}export{desktopRuntimeChannel,desktopChannelInfo,configureDesktopChannel};
1
+ import{DesktopChannelInfoSchema,DesktopRuntimeChannelSchema}from"./chunk-VXANXYQL.js";import{endpoint}from"./chunk-VKXFHOAR.js";import{canonicalLocalJson}from"./chunk-UOYNCE7I.js";import{LocalClientError,fail,read,sha256,write}from"./chunk-AZQLZA47.js";import{createPublicKey}from"node:crypto";import{join}from"node:path";function desktopRuntimeChannel(raw){const channel=DesktopRuntimeChannelSchema.parse(raw);const url=endpoint(channel.catalogueUrl),key=createPublicKey(channel.publicKey);if(key.asymmetricKeyType!=="ed25519"||channel.publicKey.replace(/\r\n/g,"\n").trim()!==key.export({type:"spki",format:"pem"}).toString().trim())fail("RELEASE_SIGNATURE_INVALID");const value={...channel,catalogueUrl:url.href,publicKey:key.export({type:"spki",format:"pem"}).toString()};return{value,host:url.host,fingerprint:sha256(canonicalLocalJson(value))}}async function desktopChannelInfo(manager,bundled){let channel,configured=false;try{const config=await manager.configuration();if(!config.catalogueUrl||!config.publicKeyFile)fail("DEPENDENCY_CHANNEL_REQUIRED");channel=desktopRuntimeChannel({protocol:"NVS_DESKTOP_RUNTIME_CHANNEL_V1",catalogueUrl:config.catalogueUrl,publicKey:(await read(config.publicKeyFile,16384)).toString()});configured=true}catch(error){if(!(error instanceof LocalClientError&&["CONFIGURATION_REQUIRED","DEPENDENCY_CHANNEL_REQUIRED"].includes(error.code)))throw error;if(bundled!==void 0)channel=desktopRuntimeChannel(bundled)}return DesktopChannelInfoSchema.parse({protocol:"NVS_DESKTOP_CHANNEL_INFO_V1",configured,source:configured?"EXISTING":channel?"BUNDLED":"UNAVAILABLE",host:channel?.host??null,channelFingerprint:channel?.fingerprint??null})}async function configureDesktopChannel(manager,expectedFingerprint,bundled){const info=await desktopChannelInfo(manager,bundled);if(!info.channelFingerprint)fail("DESKTOP_CHANNEL_REQUIRED");if(info.channelFingerprint!==expectedFingerprint)fail("DESKTOP_CHANNEL_CHANGED");if(info.configured)return;let existing;try{existing=await manager.configuration()}catch(e){if(!(e instanceof LocalClientError&&e.code==="CONFIGURATION_REQUIRED"))throw e}const stateDirectory=existing?.stateDirectory??join(manager.ledger.root,"runtime-state");if(process.platform!=="win32"&&Buffer.byteLength(join(stateDirectory,"runtime.sock"))>100)fail("SOCKET_PATH_TOO_LONG");const channel=desktopRuntimeChannel(bundled),publicKeyFile=join(manager.ledger.root,"desktop-release-"+channel.fingerprint+".pem");try{await write(publicKeyFile,channel.value.publicKey,true)}catch(error){if(error.code!=="EEXIST")throw error;if((await read(publicKeyFile,16384)).toString()!==channel.value.publicKey)fail("DESKTOP_CHANNEL_CHANGED")}try{await manager.configure({...existing,stateDirectory,catalogueUrl:channel.value.catalogueUrl,publicKeyFile,notifications:true},{ifAbsent:!existing})}catch(error){if(error.code==="EEXIST")fail("DESKTOP_CHANNEL_CHANGED");throw error}}export{desktopRuntimeChannel,desktopChannelInfo,configureDesktopChannel};
@@ -0,0 +1 @@
1
+ import{captureInstalledTools,embeddedRuntime,toolPreference}from"./chunk-QLHMJUBH.js";import{probeRecoveryBackup}from"./chunk-KAW7T5TR.js";import{allowedRuntimeFiles,launch,ownerClient,probe,probeLocalLibrary,probeTools,requiredRuntimeFiles,runningInventory,socketAbsent,verifySlot,waitStopped}from"./chunk-6YVGVNEH.js";import{withConfiguredLifecycle,withResourceLifecycleGates}from"./chunk-LVVSTKDW.js";import{asset,catalogue,select}from"./chunk-VKXFHOAR.js";import{LocalManagementInventorySchema,LocalRuntimeDescriptorSchema,LocalToolChoiceSchema,LocalToolSelectionSchema,LocalUpdatePlanSchema,RuntimeCaptionAssets,canonicalLocalJson,newerVersion,whisperCppRecognitionProfile}from"./chunk-UOYNCE7I.js";import{directory,entries,fail,optional,privateAccess,read,sha256,sha512,verifyBackup,write}from"./chunk-AZQLZA47.js";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)}import{constants}from"node:fs";import{open,chmod}from"node:fs/promises";import{join,isAbsolute}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(!isAbsolute(path))fail("CAPTION_ASSET_LOCATION_INVALID");const files=new Map;for(const name of names){const f=await open(join(path,name),constants.O_RDONLY|constants.O_NOFOLLOW|constants.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=join(await directory(join(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(join(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(join(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(join(root,"dist/captions"));const hashes={...candidate.files};for(const[path,bytes]of files){await write(join(root,path),bytes,true);await chmod(join(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 join2}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(join2(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(join2(manager.ledger.root,"plans",plan.planId+".json"),canonicalLocalJson(plan),true);return plan}import{join as join3}from"node:path";import{z}from"zod";var configurationSchema=z.strictObject({stateDirectory:z.string().min(1).max(4096),catalogueUrl:z.string().url().nullable().default(null),publicKeyFile:z.string().min(1).max(4096).nullable().default(null),cloudConfigFile:z.string().nullable().default(null),notifications:z.boolean().default(true),rejectedVersions:z.array(LocalRuntimeDescriptorSchema.shape.version).max(64).default([])}).refine(c=>!!c.catalogueUrl===!!c.publicKeyFile,"Release channel requires URL and key together");async function configureInstallation(ledger,raw,options={}){const configuration=configurationSchema.parse(raw);configuration.stateDirectory=await directory(configuration.stateDirectory);const configurationPath=join3(ledger.root,"configuration.json"),previousRaw=await optional(configurationPath),previous=previousRaw?configurationSchema.parse(previousRaw):null,gates=previous?[previous.stateDirectory,configuration.stateDirectory]:[configuration.stateDirectory];return withResourceLifecycleGates(gates,async()=>{const currentRaw=await optional(configurationPath),current=currentRaw?configurationSchema.parse(currentRaw):null;if(current&&!gates.includes(current.stateDirectory))fail("REVISION_CONFLICT","NO_WRITE");if(current&&current.stateDirectory!==configuration.stateDirectory&&!await socketAbsent(current.stateDirectory))fail("RUNTIME_ALREADY_RUNNING","NO_WRITE");await write(configurationPath,canonicalLocalJson(configuration),options.ifAbsent);return{configured:true}},options.lifecycleScope)}import{randomUUID as randomUUID2}from"node:crypto";import{join as join4,dirname}from"node:path";import{z as z2}from"zod";async function grant(manager,raw,output){const i=z2.strictObject({tenantId:z2.uuid(),deviceId:z2.uuid(),expiresAt:z2.iso.datetime({offset:true})}).parse(raw);const c=await manager.configuration(),client=await ownerClient(c.stateDirectory);await directory(dirname(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-G2HINGMA.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=z2.strictObject({tenantId:z2.uuid(),deviceId:z2.uuid(),expiresAt:z2.iso.datetime({offset:true}),output:z2.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 z4}from"zod";import{z as z3}from"zod";import{join as join5}from"node:path";var slotSchema=z3.strictObject({id:z3.uuid(),descriptor:LocalRuntimeDescriptorSchema,toolsConfigPath:z3.string().nullable().default(null),files:z3.record(z3.string().min(1).max(100),z3.string().regex(/^[0-9a-f]{64}$/))});var transitionSchema=z3.strictObject({id:z3.uuid(),planId:z3.uuid(),fingerprint:z3.string().regex(/^[0-9a-f]{64}$/),phase:z3.enum(["STAGING","STAGED","DRAINING","ACTIVATING","VERIFYING","ROLLBACK_REQUIRED"]),previous:slotSchema.nullable(),candidate:slotSchema.nullable(),backupPath:z3.string().nullable(),failedPhase:z3.enum(["STAGING","STAGED","DRAINING","ACTIVATING","VERIFYING","ROLLBACK_REQUIRED"]).nullable().default(null)});var installationSchema=z3.strictObject({revision:z3.int().nonnegative(),active:slotSchema.nullable(),transition:transitionSchema.nullable()});var recordSchema=z3.strictObject({previous:z3.string().nullable(),value:installationSchema,digest:z3.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 atRevision(revision){let found=null;await this.load(value=>{if(value.revision===revision)found=value});return found}async toolSelectionHistory(){const historical=new Set;const revisionDigests=new Map;const slots=new Map;let previous;const current=await this.load((value,digest)=>{revisionDigests.set(value.revision,digest);for(const slot of[value.active,value.transition?.previous,value.transition?.candidate]){if(!slot)continue;const identity2=sha256(canonicalLocalJson(slot));const versions=slots.get(slot.id)??new Map;versions.set(identity2,{slot,lastReferencedRevision:value.revision,lastReferencedDigest:digest});slots.set(slot.id,versions)}if(previous){for(const slot of[previous.active,previous.transition?.previous,previous.transition?.candidate])if(slot?.toolsConfigPath)historical.add(slot.toolsConfigPath)}previous=value});const slotHistory=[...slots.entries()].map(([id,versions])=>{const values=[...versions.values()].sort((a,b)=>sha256(canonicalLocalJson(a.slot)).localeCompare(sha256(canonicalLocalJson(b.slot))));return{id,versions:values,lastReferencedRevision:Math.max(...values.map(v=>v.lastReferencedRevision))}}).sort((a,b)=>a.id.localeCompare(b.id));return{value:current.value,historical:[...historical].sort(),revisionDigests,slots:slotHistory}}async recoveryBackupReferences(){const paths=new Set;const current=await this.load(value=>{if(value.transition?.backupPath)paths.add(value.transition.backupPath)});return{...current,paths}}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,r.digest)}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 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}configure(raw,options={}){return configureInstallation(this.ledger,raw,options)}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}}async prepare(version,choice){return withConfiguredLifecycle(this,()=>prepareInstallation(this,version,choice))}async prepareBundled(version,choice){return withConfiguredLifecycle(this,()=>prepareInstallation(this,version,choice,true))}async plan(id){if(!z4.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(p.planId!==id||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){return withConfiguredLifecycle(this,()=>this.applyWithinGate(id,approval))}async applyWithinGate(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);await waitStopped(c.stateDirectory);if(!s.active)fail("BACKUP_INSPECTION_NOT_PROVEN");await probeRecoveryBackup(this.ledger.slotPath(s.active),s.active,c.stateDirectory,result.backupPath);s=await this.transition(s,"ACTIVATING",{backupPath:result.backupPath});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(scope){return withConfiguredLifecycle(this,()=>this.startWithinGate(),scope)}async startWithinGate(){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(scope){return withConfiguredLifecycle(this,()=>this.stopWithinGate(),scope)}async stopWithinGate(){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);if(!result||typeof result!=="object"||!("backupPath"in result)||typeof result.backupPath!=="string")fail("JOURNAL_BACKUP_REQUIRED");await verifyBackup(result.backupPath,c.stateDirectory);const installation=(await this.ledger.current()).value;if(!installation.active)fail("BACKUP_INSPECTION_NOT_PROVEN");await probeRecoveryBackup(this.ledger.slotPath(installation.active),installation.active,c.stateDirectory,result.backupPath);return result}async reconcile(id,approval){return withConfiguredLifecycle(this,()=>this.reconcileWithinGate(id,approval))}async reconcileWithinGate(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{installationSource,verifyCaptionDirectory,LocalInstallationManager};
@@ -1 +1 @@
1
- import{lstat as lstat2,mkdir,open,rename,link,unlink}from"node:fs/promises";import{dirname,isAbsolute as isAbsolute2,join as join2}from"node:path";import{createHash as createHash2}from"node:crypto";import{spawn}from"node:child_process";import{once}from"node:events";import{readFile,realpath,lstat}from"node:fs/promises";import{createHash,randomUUID}from"node:crypto";import{fileURLToPath}from"node:url";import{join,isAbsolute}from"node:path";var executable;var assetDirectory;async function windowsHelper(){if(process.platform!=="win32"||process.arch!=="x64")throw Error("WINDOWS_PLATFORM_REQUIRED");return executable??=bootstrap().catch(error=>{executable=void 0;throw error})}async function bootstrap(){const directory2=assetDirectory??fileURLToPath(new URL("./dist/native/",import.meta.resolve("@nativestudio/cli/package.json")));const read2=async(name,maximum)=>{const path=join(directory2,name),stat=await lstat(path);if(!stat.isFile()||stat.isSymbolicLink()||stat.nlink!==1||stat.size<1||stat.size>maximum)throw Error("WINDOWS_HELPER_INVALID");const bytes2=await readFile(path);if(bytes2.length!==stat.size)throw Error("WINDOWS_HELPER_INVALID");return bytes2};const m=JSON.parse((await read2("helper.json",4096)).toString());const bytes=await read2("helper.exe",2*1024*1024);if(m.protocol!=="NVS_WINDOWS_HELPER_V1"||m.format!=="PE_AMD64_NETFRAMEWORK48"||m.byteSize!==bytes.length||!/^[a-f0-9]{64}$/.test(m.sha256)||createHash("sha256").update(bytes).digest("hex")!==m.sha256)throw Error("WINDOWS_HELPER_INVALID");return realpath(join(directory2,"helper.exe"))}var service;async function connection(){return service??=(async()=>{const child=spawn(await windowsHelper(),["service",String(process.pid)],{shell:false,windowsHide:true,stdio:["pipe","pipe","pipe"]});const pending=new Map;let bytes=Buffer.alloc(0),stderr=0;const close=()=>{for(const item of pending.values()){clearTimeout(item.timer);item.reject(Error("WINDOWS_HELPER_UNAVAILABLE"))}pending.clear();service=void 0};child.stdout.on("data",part=>{bytes=Buffer.concat([bytes,part]);if(bytes.length>2*1024*1024)return child.kill();for(;;){const end=bytes.indexOf(10);if(end<0)break;const line=bytes.subarray(0,end);bytes=bytes.subarray(end+1);try{const value=JSON.parse(line.toString());const item=pending.get(value.id);if(!item)continue;pending.delete(value.id);clearTimeout(item.timer);if(value.ok)item.resolve(value.data);else item.reject(Error(["EXISTS","RESOURCE_BUDGET_EXCEEDED"].includes(value.error??"")?value.error:"WINDOWS_ACCESS_DENIED"))}catch{child.kill()}}});child.stderr.on("data",b=>{if((stderr+=b.length)>65536)child.kill()});child.on("error",close);child.on("close",close);child.stdin.on("error",close);await once(child,"spawn");child.unref();child.stdout.unref();child.stderr.unref();child.stdin.unref();return{child,pending}})().catch(error=>{service=void 0;throw error})}async function windowsRequest(request,timeoutMs=1e4,signal){signal?.throwIfAborted();const{child,pending}=await connection();signal?.throwIfAborted();if(child.exitCode!==null||child.signalCode!==null||child.stdin.destroyed)throw Error("WINDOWS_HELPER_UNAVAILABLE");if(pending.size>=32)throw Error("WINDOWS_HELPER_BUSY");const id=randomUUID(),data=JSON.stringify({...request,id});if(Buffer.byteLength(data)>1024*1024)throw Error("WINDOWS_HELPER_INPUT_LIMIT");return new Promise((resolve,reject)=>{const abort=()=>{child.stdin.write(JSON.stringify({operation:"cancel",target:id})+"\n")};const timer=setTimeout(()=>{abort();pending.delete(id);signal?.removeEventListener("abort",abort);reject(Error("WINDOWS_HELPER_TIMEOUT"))},timeoutMs);pending.set(id,{timer,resolve:v=>{signal?.removeEventListener("abort",abort);resolve(v)},reject:e=>{signal?.removeEventListener("abort",abort);reject(e)}});signal?.addEventListener("abort",abort,{once:true});child.stdin.write(data+"\n");if(signal?.aborted)abort()})}function localSocketPath(root,platform=process.platform){if(platform!=="win32")return join2(root,"runtime.sock");return"\\\\.\\pipe\\nvs-"+createHash2("sha256").update(root.toLowerCase()).digest("hex")}async function privateAccess(path,kind){if(process.platform==="win32"){if(kind!=="pipe")await lstat2(path);await windowsRequest({operation:"check",path,kind});return}const s=await lstat2(path);if(s.isSymbolicLink()||s.uid!==process.getuid?.()||s.mode&63||(kind==="directory"?!s.isDirectory():kind==="pipe"?!s.isSocket():!s.isFile()))throw Error("LOCAL_PERMISSIONS_INVALID")}async function privateDirectory(path,create=false){if(!isAbsolute2(path)||!["win32","darwin","linux"].includes(process.platform))throw Error("LOCAL_LOCATION_INVALID");if(process.platform==="win32")await windowsRequest({operation:create?"directory":"check",path,kind:"directory"});else{if(create)await mkdir(path,{recursive:true,mode:448});await privateAccess(path,"directory")}}async function syncDirectory(path){if(process.platform==="win32")return;const d=await open(path,"r");try{await d.sync()}finally{await d.close()}}async function atomicMove(source,target,exclusive=false){if(dirname(source)!==dirname(target))throw Error("LOCAL_ATOMIC_MOVE_INVALID");if(process.platform==="win32"){try{await windowsRequest({operation:"move",source,target,exclusive})}catch(error){if(error.message==="EXISTS")throw Object.assign(Error("EXISTS"),{code:"EEXIST"});throw error}}else{if(exclusive){await link(source,target);await unlink(source)}else await rename(source,target);await syncDirectory(dirname(target))}}async function assertExecutable(path){const s=await lstat2(path);if(!isAbsolute2(path)||!s.isFile()||s.isSymbolicLink()||s.nlink!==1)throw Error("LOCAL_EXECUTABLE_INVALID");if(process.platform==="win32"){if(!path.toLowerCase().endsWith(".exe"))throw Error("LOCAL_EXECUTABLE_INVALID");await windowsRequest({operation:"executable",path})}else if(!(s.mode&73)||s.mode&18)throw Error("LOCAL_EXECUTABLE_INVALID")}import{spawn as spawn2}from"node:child_process";import{Duplex}from"node:stream";import{createHash as createHash3}from"node:crypto";async function sha256OfOpenFile(file,before){const chunk=Buffer.allocUnsafe(Math.min(before.size+1,1024*1024));const hash=createHash3("sha256");let used=0;while(used<=before.size){const{bytesRead}=await file.read(chunk,0,Math.min(chunk.length,before.size+1-used),used);if(!bytesRead)break;used+=bytesRead;if(used>before.size)return null;hash.update(chunk.subarray(0,bytesRead))}const after=await file.stat();if(used!==before.size||after.size!==before.size||after.mtimeMs!==before.mtimeMs||after.ctimeMs!==before.ctimeMs)return null;return hash.digest("hex")}import{createHash as createHash4}from"node:crypto";import{constants}from"node:fs";import{open as open2,opendir}from"node:fs/promises";import{isAbsolute as isAbsolute3,join as join3}from"node:path";var runtimeLoginProtocol="NVS_RUNTIME_LOGIN_V1";var runtimeLoginApprovalFile="runtime-login.json";var digest=bytes=>createHash4("sha256").update(bytes).digest("hex");var isDigest=value=>typeof value==="string"&&/^[0-9a-f]{64}$/.test(value);function loginPath(path){if(typeof path!=="string"||path.length>4096||!isAbsolute3(path))return false;return[...path].every(character=>{const code=character.charCodeAt(0);return code>=32&&code!==127})}function parseRuntimeLoginApproval(bytes){const value=JSON.parse(bytes.toString());const file=input=>!!input&&loginPath(input.path)&&isDigest(input.sha256);if(!value||value.protocol!==runtimeLoginProtocol||typeof value.version!=="string"||!/^[0-9A-Za-z.+-]{1,80}$/.test(value.version)||!Number.isSafeInteger(value.revision)||value.revision<1||value.revision>=1e12||!loginPath(value.stateDirectory)||!isDigest(value.configurationSha256)||!isDigest(value.revisionSha256)||!file(value.node)||!file(value.entry)||!file(value.device)||value.supervision!==void 0&&value.supervision!=="EXPLICIT_RECOVERY"||value.tools!==null&&!file(value.tools))throw Error("LOGIN_APPROVAL_INVALID");return value}var loginRevisionName=revision=>String(revision).padStart(12,"0")+".json";async function loginInputsCurrent(home,approval,read2){const directory2=join3(home,"revisions"),expected=loginRevisionName(approval.revision);const pins=[{path:join3(home,"configuration.json"),sha256:approval.configurationSha256,limit:65536},{path:join3(directory2,expected),sha256:approval.revisionSha256,limit:262144},{...approval.device,limit:32768},...approval.tools?[{...approval.tools,limit:32768}]:[]];try{for(const pin of pins)if(digest(await read2(pin.path,pin.limit))!==pin.sha256)return false;let count=0;for await(const entry of await opendir(directory2)){if(++count>1e4||/^\d{12}\.json$/.test(entry.name)&&entry.name>expected)return false}return true}catch{return false}}async function loginExecutableDigest(path){const file=await open2(path,constants.O_RDONLY|constants.O_NOFOLLOW|constants.O_NONBLOCK);try{const info=await file.stat(),limit=160*1024*1024;if(!info.isFile()||info.nlink!==1||info.size<1||info.size>limit||process.platform!=="win32"&&(info.mode&18||!(info.mode&73)))throw Error("LOGIN_EXECUTABLE_INVALID");const sha2562=await sha256OfOpenFile(file,info);if(sha2562===null)throw Error("LOGIN_EXECUTABLE_CHANGED");return sha2562}finally{await file.close()}}function assertWindowsSystemTool(path){if(process.platform!=="win32"||!/^[A-Z]:\\(?:[^%"\r\n]+\\)?System32\\(?:schtasks|whoami)\.exe$/i.test(path))throw Error("WINDOWS_SYSTEM_TOOL_REQUIRED");return windowsRequest({operation:"executable",path})}import{constants as constants2}from"node:fs";import{open as open3,realpath as realpath2,rename as rename2,unlink as unlink2,link as link2,readdir}from"node:fs/promises";import{isAbsolute as isAbsolute4,join as join4,dirname as dirname2}from"node:path";import{randomUUID as randomUUID2,createHash as createHash5}from"node:crypto";var sha256=v=>createHash5("sha256").update(v).digest("hex");var sha512=v=>createHash5("sha512").update(v).digest("hex");var LocalClientError=class extends Error{constructor(code,outcome){super("NativeStudio local "+code);this.code=code;this.outcome=outcome}code;outcome};function fail(code,outcome){throw new LocalClientError(code,outcome)}async function directory(path){if(!isAbsolute4(path))fail("LOCATION_UNSUPPORTED");try{await privateDirectory(path,true)}catch{fail("PRIVATE_LOCATION_REQUIRED")}const root=await realpath2(path);if(/(?:^|[\\/])(?:node_modules|_npx)(?:[\\/]|$)/.test(root))fail("PRIVATE_LOCATION_REQUIRED");return root}async function withPrivateFile(path,maximum,ledger,use){try{await privateAccess(path,"file")}catch(e){if(e.code==="ENOENT")throw e;fail("PRIVATE_FILE_REQUIRED")}const f=await open3(path,constants2.O_RDONLY|constants2.O_NOFOLLOW|constants2.O_NONBLOCK);try{const s=await f.stat();if(!s.isFile()||process.platform!=="win32"&&(s.uid!==process.getuid?.()||s.mode&63)||s.size>maximum||(ledger?s.nlink>2:s.nlink!==1))fail("PRIVATE_FILE_REQUIRED");return await use(f,s)}finally{await f.close()}}function read(path,maximum=65536,ledger=false){return withPrivateFile(path,maximum,ledger,async(f,s)=>{const bytes=Buffer.alloc(Math.min(maximum+1,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)fail("FILE_CHANGED");if(used>maximum)fail("FILE_LIMIT");return bytes.subarray(0,used)})}function digestPrivateFile(path,maximum){return withPrivateFile(path,maximum,false,async(file,before)=>{const digest2=await sha256OfOpenFile(file,before);if(digest2===null)fail("FILE_CHANGED");return digest2})}async function write(path,value,exclusive=false){const temporary=join4(dirname2(path),".tmp-"+randomUUID2());const f=await open3(temporary,"wx",384);try{try{await f.writeFile(value);await f.sync()}finally{await f.close()}if(process.platform==="win32")await atomicMove(temporary,path,exclusive);else if(exclusive)await link2(temporary,path);else{try{await withPrivateFile(path,64*1024*1024,false,()=>void 0)}catch(e){if(e.code!=="ENOENT")throw e}await rename2(temporary,path)}}finally{await unlink2(temporary).catch(e=>{if(e.code!=="ENOENT")throw e})}await syncDirectory(dirname2(path))}async function entries(path){const values=await readdir(path);if(values.length>1e4)fail("HISTORY_LIMIT");return values}async function optional(path){try{return JSON.parse((await read(path)).toString())}catch(e){if(e.code==="ENOENT")return null;throw e}}async function verifyBackup(path,stateDirectory){const base=await realpath2(join4(stateDirectory,"backups")),actual=await realpath2(path);if(dirname2(actual)!==base||!/[0-9a-f-]{36}\.sqlite$/.test(actual))fail("JOURNAL_BACKUP_REQUIRED");try{await privateAccess(actual,"file")}catch{fail("JOURNAL_BACKUP_REQUIRED")}const f=await open3(actual,constants2.O_RDONLY|constants2.O_NOFOLLOW);try{const stat=await f.stat(),header=Buffer.alloc(16);if(!stat.isFile()||stat.nlink!==1||process.platform!=="win32"&&(stat.uid!==process.getuid?.()||stat.mode&63)||stat.size<100)fail("JOURNAL_BACKUP_REQUIRED");const n=await f.read(header,0,16,0);if(n.bytesRead!==16||header.toString()!=="SQLite format 3\0")fail("JOURNAL_BACKUP_REQUIRED")}finally{await f.close()}}export{localSocketPath,privateAccess,privateDirectory,syncDirectory,atomicMove,assertExecutable,runtimeLoginProtocol,runtimeLoginApprovalFile,loginPath,parseRuntimeLoginApproval,loginRevisionName,loginInputsCurrent,loginExecutableDigest,assertWindowsSystemTool,sha256,sha512,LocalClientError,fail,directory,read,digestPrivateFile,write,entries,optional,verifyBackup};
1
+ import{lstat as lstat2,mkdir,open,rename,link,unlink}from"node:fs/promises";import{dirname,isAbsolute as isAbsolute2,join as join2}from"node:path";import{createHash as createHash2}from"node:crypto";import{spawn}from"node:child_process";import{once}from"node:events";import{readFile,realpath,lstat}from"node:fs/promises";import{createHash,randomUUID}from"node:crypto";import{fileURLToPath}from"node:url";import{join,isAbsolute}from"node:path";var executable;var assetDirectory;async function windowsHelper(){if(process.platform!=="win32"||process.arch!=="x64")throw Error("WINDOWS_PLATFORM_REQUIRED");return executable??=bootstrap().catch(error=>{executable=void 0;throw error})}async function bootstrap(){const directory2=assetDirectory??fileURLToPath(new URL("./dist/native/",import.meta.resolve("@nativestudio/cli/package.json")));const read2=async(name,maximum)=>{const path=join(directory2,name),stat=await lstat(path);if(!stat.isFile()||stat.isSymbolicLink()||stat.nlink!==1||stat.size<1||stat.size>maximum)throw Error("WINDOWS_HELPER_INVALID");const bytes2=await readFile(path);if(bytes2.length!==stat.size)throw Error("WINDOWS_HELPER_INVALID");return bytes2};const m=JSON.parse((await read2("helper.json",4096)).toString());const bytes=await read2("helper.exe",2*1024*1024);if(m.protocol!=="NVS_WINDOWS_HELPER_V1"||m.format!=="PE_AMD64_NETFRAMEWORK48"||m.byteSize!==bytes.length||!/^[a-f0-9]{64}$/.test(m.sha256)||createHash("sha256").update(bytes).digest("hex")!==m.sha256)throw Error("WINDOWS_HELPER_INVALID");return realpath(join(directory2,"helper.exe"))}var service;async function connection(){return service??=(async()=>{const child=spawn(await windowsHelper(),["service",String(process.pid)],{shell:false,windowsHide:true,stdio:["pipe","pipe","pipe"]});const pending=new Map;let bytes=Buffer.alloc(0),stderr=0;const close=()=>{for(const item of pending.values()){clearTimeout(item.timer);item.reject(Error("WINDOWS_HELPER_UNAVAILABLE"))}pending.clear();service=void 0};child.stdout.on("data",part=>{bytes=Buffer.concat([bytes,part]);if(bytes.length>2*1024*1024)return child.kill();for(;;){const end=bytes.indexOf(10);if(end<0)break;const line=bytes.subarray(0,end);bytes=bytes.subarray(end+1);try{const value=JSON.parse(line.toString());const item=pending.get(value.id);if(!item)continue;pending.delete(value.id);clearTimeout(item.timer);if(value.ok)item.resolve(value.data);else item.reject(Error(["EXISTS","RESOURCE_BUDGET_EXCEEDED"].includes(value.error??"")?value.error:"WINDOWS_ACCESS_DENIED"))}catch{child.kill()}}});child.stderr.on("data",b=>{if((stderr+=b.length)>65536)child.kill()});child.on("error",close);child.on("close",close);child.stdin.on("error",close);await once(child,"spawn");child.unref();child.stdout.unref();child.stderr.unref();child.stdin.unref();return{child,pending}})().catch(error=>{service=void 0;throw error})}async function windowsRequest(request,timeoutMs=1e4,signal){signal?.throwIfAborted();const{child,pending}=await connection();signal?.throwIfAborted();if(child.exitCode!==null||child.signalCode!==null||child.stdin.destroyed)throw Error("WINDOWS_HELPER_UNAVAILABLE");if(pending.size>=32)throw Error("WINDOWS_HELPER_BUSY");const id=randomUUID(),data=JSON.stringify({...request,id});if(Buffer.byteLength(data)>1024*1024)throw Error("WINDOWS_HELPER_INPUT_LIMIT");return new Promise((resolve,reject)=>{const abort=()=>{child.stdin.write(JSON.stringify({operation:"cancel",target:id})+"\n")};const timer=setTimeout(()=>{abort();pending.delete(id);signal?.removeEventListener("abort",abort);reject(Error("WINDOWS_HELPER_TIMEOUT"))},timeoutMs);pending.set(id,{timer,resolve:v=>{signal?.removeEventListener("abort",abort);resolve(v)},reject:e=>{signal?.removeEventListener("abort",abort);reject(e)}});signal?.addEventListener("abort",abort,{once:true});child.stdin.write(data+"\n");if(signal?.aborted)abort()})}function localSocketPath(root,platform=process.platform){if(platform!=="win32")return join2(root,"runtime.sock");return"\\\\.\\pipe\\nvs-"+createHash2("sha256").update(root.toLowerCase()).digest("hex")}async function privateAccess(path,kind){if(process.platform==="win32"){if(kind!=="pipe")await lstat2(path);await windowsRequest({operation:"check",path,kind});return}const s=await lstat2(path);if(s.isSymbolicLink()||s.uid!==process.getuid?.()||s.mode&63||(kind==="directory"?!s.isDirectory():kind==="pipe"?!s.isSocket():!s.isFile()))throw Error("LOCAL_PERMISSIONS_INVALID")}async function privateDirectory(path,create=false){if(!isAbsolute2(path)||!["win32","darwin","linux"].includes(process.platform))throw Error("LOCAL_LOCATION_INVALID");if(process.platform==="win32")await windowsRequest({operation:create?"directory":"check",path,kind:"directory"});else{if(create)await mkdir(path,{recursive:true,mode:448});await privateAccess(path,"directory")}}async function syncDirectory(path){if(process.platform==="win32")return;const d=await open(path,"r");try{await d.sync()}finally{await d.close()}}async function atomicMove(source,target,exclusive=false){if(dirname(source)!==dirname(target))throw Error("LOCAL_ATOMIC_MOVE_INVALID");if(process.platform==="win32"){try{await windowsRequest({operation:"move",source,target,exclusive})}catch(error){if(error.message==="EXISTS")throw Object.assign(Error("EXISTS"),{code:"EEXIST"});throw error}}else{if(exclusive){await link(source,target);await unlink(source)}else await rename(source,target);await syncDirectory(dirname(target))}}async function assertExecutable(path){const s=await lstat2(path);if(!isAbsolute2(path)||!s.isFile()||s.isSymbolicLink()||s.nlink!==1)throw Error("LOCAL_EXECUTABLE_INVALID");if(process.platform==="win32"){if(!path.toLowerCase().endsWith(".exe"))throw Error("LOCAL_EXECUTABLE_INVALID");await windowsRequest({operation:"executable",path})}else if(!(s.mode&73)||s.mode&18)throw Error("LOCAL_EXECUTABLE_INVALID")}import{spawn as spawn2}from"node:child_process";import{Duplex}from"node:stream";import{createHash as createHash3}from"node:crypto";async function sha256OfOpenFile(file,before){const chunk=Buffer.allocUnsafe(Math.min(before.size+1,1024*1024));const hash=createHash3("sha256");let used=0;while(used<=before.size){const{bytesRead}=await file.read(chunk,0,Math.min(chunk.length,before.size+1-used),used);if(!bytesRead)break;used+=bytesRead;if(used>before.size)return null;hash.update(chunk.subarray(0,bytesRead))}const after=await file.stat();if(used!==before.size||after.size!==before.size||after.mtimeMs!==before.mtimeMs||after.ctimeMs!==before.ctimeMs)return null;return hash.digest("hex")}import{createHash as createHash4}from"node:crypto";import{constants}from"node:fs";import{open as open2,opendir}from"node:fs/promises";import{isAbsolute as isAbsolute3,join as join3}from"node:path";var runtimeLoginProtocol="NVS_RUNTIME_LOGIN_V1";var runtimeLoginApprovalFile="runtime-login.json";var digest=bytes=>createHash4("sha256").update(bytes).digest("hex");var isDigest=value=>typeof value==="string"&&/^[0-9a-f]{64}$/.test(value);function loginPath(path){if(typeof path!=="string"||path.length>4096||!isAbsolute3(path))return false;return[...path].every(character=>{const code=character.charCodeAt(0);return code>=32&&code!==127})}function parseRuntimeLoginApproval(bytes){const value=JSON.parse(bytes.toString());const file=input=>!!input&&loginPath(input.path)&&isDigest(input.sha256);if(!value||value.protocol!==runtimeLoginProtocol||typeof value.version!=="string"||!/^[0-9A-Za-z.+-]{1,80}$/.test(value.version)||!Number.isSafeInteger(value.revision)||value.revision<1||value.revision>=1e12||!loginPath(value.stateDirectory)||!isDigest(value.configurationSha256)||!isDigest(value.revisionSha256)||!file(value.node)||!file(value.entry)||!file(value.device)||value.supervision!==void 0&&value.supervision!=="EXPLICIT_RECOVERY"||value.tools!==null&&!file(value.tools))throw Error("LOGIN_APPROVAL_INVALID");return value}var loginRevisionName=revision=>String(revision).padStart(12,"0")+".json";async function loginInputsCurrent(home,approval,read2){const directory2=join3(home,"revisions"),expected=loginRevisionName(approval.revision);const pins=[{path:join3(home,"configuration.json"),sha256:approval.configurationSha256,limit:65536},{path:join3(directory2,expected),sha256:approval.revisionSha256,limit:262144},{...approval.device,limit:32768},...approval.tools?[{...approval.tools,limit:32768}]:[]];try{for(const pin of pins)if(digest(await read2(pin.path,pin.limit))!==pin.sha256)return false;let count=0;for await(const entry of await opendir(directory2)){if(++count>1e4||/^\d{12}\.json$/.test(entry.name)&&entry.name>expected)return false}return true}catch{return false}}async function loginExecutableDigest(path){const file=await open2(path,constants.O_RDONLY|constants.O_NOFOLLOW|constants.O_NONBLOCK);try{const info=await file.stat(),limit=160*1024*1024;if(!info.isFile()||info.nlink!==1||info.size<1||info.size>limit||process.platform!=="win32"&&(info.mode&18||!(info.mode&73)))throw Error("LOGIN_EXECUTABLE_INVALID");const sha2562=await sha256OfOpenFile(file,info);if(sha2562===null)throw Error("LOGIN_EXECUTABLE_CHANGED");return sha2562}finally{await file.close()}}import{constants as constants2}from"node:fs";import{open as open3,realpath as realpath2,readdir,unlink as unlink2}from"node:fs/promises";import{join as join4}from"node:path";import{randomUUID as randomUUID2}from"node:crypto";var unavailable=kind=>Error(kind==="model"?"CPU_RESOURCE_PREPARATION_NOT_PROVEN":"RESOURCE_LIFECYCLE_NOT_PROVEN");var busy=kind=>Error(kind==="model"?"CPU_RESOURCE_PREPARATION_BUSY":"RESOURCE_LIFECYCLE_BUSY");var missing=e=>e.code==="ENOENT";var generationName=n=>String(n).padStart(12,"0")+".json";async function gateRoot(stateDirectory,create,kind){await privateAccess(stateDirectory,"directory");const root=await realpath2(stateDirectory);const paths=kind==="model"?[join4(root,"cpu-speech"),join4(root,"cpu-speech","preparation-locks")]:[join4(root,"maintenance-locks")];for(const path of paths){try{await privateDirectory(path,create)}catch(error){if(!create&&missing(error))return null;throw error}if(await realpath2(path)!==path)throw unavailable(kind)}return paths.at(-1)}async function smallFile(path,kind){await privateAccess(path,"file");const file=await open3(path,constants2.O_RDONLY|constants2.O_NOFOLLOW|constants2.O_NONBLOCK);try{const info=await file.stat();if(!info.isFile()||info.nlink!==1||info.size>256||process.platform!=="win32"&&(info.uid!==process.getuid?.()||info.mode&63))throw unavailable(kind);const buffer=Buffer.alloc(257);const{bytesRead}=await file.read(buffer,0,buffer.length,0);if(bytesRead!==info.size)throw unavailable(kind);return buffer.subarray(0,bytesRead).toString("utf8")}finally{await file.close()}}async function observe(root,kind){const names=await readdir(root);if(names.length>1e4)throw unavailable(kind);const generations=names.filter(n=>/^\d{12}\.json$/.test(n)).sort();if(generations.some((name,index)=>name!==generationName(index+1)))throw unavailable(kind);if(names.some(n=>!/^\d{12}\.json(?:\.released)?$/.test(n)&&!/^\.tmp-[0-9a-f-]{36}$/.test(n)))throw unavailable(kind);if(names.some(n=>n.endsWith(".released")&&!generations.includes(n.slice(0,-9))))throw unavailable(kind);const generation=generations.length;if(!generation)return{state:"NONE",generation:0};const path=join4(root,generationName(generation));const owner=JSON.parse(await smallFile(path,kind));if(!owner||typeof owner!=="object"||Object.keys(owner).length!==1||!("pid"in owner)||typeof owner.pid!=="number"||!Number.isSafeInteger(owner.pid)||owner.pid<1||owner.pid>2147483647)throw unavailable(kind);try{if(await smallFile(path+".released",kind)!=="true")throw unavailable(kind);return{state:"RELEASED",generation}}catch(error){if(!missing(error))throw error}try{process.kill(owner.pid,0);return{state:"ACTIVE",generation}}catch(error){if(error.code==="ESRCH")return{state:"STALE",generation};return{state:"UNCONFIRMED",generation}}}async function publish(root,path,value){const temporary=join4(root,".tmp-"+randomUUID2());const file=await open3(temporary,"wx",384);try{try{await file.writeFile(value);await file.sync()}finally{await file.close()}await atomicMove(temporary,path,true)}finally{await unlink2(temporary).catch(error=>{if(!missing(error))throw error})}}async function inspectGate(stateDirectory,kind){try{const root=await gateRoot(stateDirectory,false,kind);return root?await observe(root,kind):{state:"NONE",generation:0}}catch{return{state:"UNCONFIRMED",generation:null}}}function inspectModelPreparationGate(stateDirectory){return inspectGate(stateDirectory,"model")}function inspectResourceLifecycleGate(stateDirectory){return inspectGate(stateDirectory,"lifecycle")}async function withGate(stateDirectory,work,kind){let root,observation;try{root=await gateRoot(stateDirectory,true,kind);observation=await observe(root,kind)}catch{throw unavailable(kind)}if(observation.state==="ACTIVE")throw busy(kind);if(observation.state==="UNCONFIRMED"||observation.generation===null)throw unavailable(kind);const path=join4(root,generationName(observation.generation+1));try{await publish(root,path,JSON.stringify({pid:process.pid}))}catch(error){if(error.code==="EEXIST")throw busy(kind);throw unavailable(kind)}try{return await work()}finally{await publish(root,path+".released","true")}}function withModelPreparationGate(stateDirectory,work){return withGate(stateDirectory,work,"model")}function withResourceLifecycleGate(stateDirectory,work){return withGate(stateDirectory,work,"lifecycle")}function assertWindowsSystemTool(path){if(process.platform!=="win32"||!/^[A-Z]:\\(?:[^%"\r\n]+\\)?System32\\(?:schtasks|whoami)\.exe$/i.test(path))throw Error("WINDOWS_SYSTEM_TOOL_REQUIRED");return windowsRequest({operation:"executable",path})}import{constants as constants3}from"node:fs";import{open as open4,realpath as realpath3,rename as rename2,unlink as unlink3,link as link2,readdir as readdir2}from"node:fs/promises";import{isAbsolute as isAbsolute4,join as join5,dirname as dirname2}from"node:path";import{randomUUID as randomUUID3,createHash as createHash5}from"node:crypto";var sha256=v=>createHash5("sha256").update(v).digest("hex");var sha512=v=>createHash5("sha512").update(v).digest("hex");var LocalClientError=class extends Error{constructor(code,outcome){super("NativeStudio local "+code);this.code=code;this.outcome=outcome}code;outcome};function fail(code,outcome){throw new LocalClientError(code,outcome)}async function directory(path){if(!isAbsolute4(path))fail("LOCATION_UNSUPPORTED");try{await privateDirectory(path,true)}catch{fail("PRIVATE_LOCATION_REQUIRED")}const root=await realpath3(path);if(/(?:^|[\\/])(?:node_modules|_npx)(?:[\\/]|$)/.test(root))fail("PRIVATE_LOCATION_REQUIRED");return root}async function withPrivateFile(path,maximum,ledger,use){try{await privateAccess(path,"file")}catch(e){if(e.code==="ENOENT")throw e;fail("PRIVATE_FILE_REQUIRED")}const f=await open4(path,constants3.O_RDONLY|constants3.O_NOFOLLOW|constants3.O_NONBLOCK);try{const s=await f.stat();if(!s.isFile()||process.platform!=="win32"&&(s.uid!==process.getuid?.()||s.mode&63)||s.size>maximum||(ledger?s.nlink>2:s.nlink!==1))fail("PRIVATE_FILE_REQUIRED");return await use(f,s)}finally{await f.close()}}function read(path,maximum=65536,ledger=false){return withPrivateFile(path,maximum,ledger,async(f,s)=>{const bytes=Buffer.alloc(Math.min(maximum+1,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)fail("FILE_CHANGED");if(used>maximum)fail("FILE_LIMIT");return bytes.subarray(0,used)})}function digestPrivateFile(path,maximum){return withPrivateFile(path,maximum,false,async(file,before)=>{const digest2=await sha256OfOpenFile(file,before);if(digest2===null)fail("FILE_CHANGED");return digest2})}async function write(path,value,exclusive=false){const temporary=join5(dirname2(path),".tmp-"+randomUUID3());const f=await open4(temporary,"wx",384);try{try{await f.writeFile(value);await f.sync()}finally{await f.close()}if(process.platform==="win32")await atomicMove(temporary,path,exclusive);else if(exclusive)await link2(temporary,path);else{try{await withPrivateFile(path,64*1024*1024,false,()=>void 0)}catch(e){if(e.code!=="ENOENT")throw e}await rename2(temporary,path)}}finally{await unlink3(temporary).catch(e=>{if(e.code!=="ENOENT")throw e})}await syncDirectory(dirname2(path))}async function entries(path){const values=await readdir2(path);if(values.length>1e4)fail("HISTORY_LIMIT");return values}async function optional(path){try{return JSON.parse((await read(path)).toString())}catch(e){if(e.code==="ENOENT")return null;throw e}}async function verifyBackup(path,stateDirectory){const base=await realpath3(join5(stateDirectory,"backups")),actual=await realpath3(path);if(dirname2(actual)!==base||!/[0-9a-f-]{36}\.sqlite$/.test(actual))fail("JOURNAL_BACKUP_REQUIRED");try{await privateAccess(actual,"file")}catch{fail("JOURNAL_BACKUP_REQUIRED")}const f=await open4(actual,constants3.O_RDONLY|constants3.O_NOFOLLOW);try{const stat=await f.stat(),header=Buffer.alloc(16);if(!stat.isFile()||stat.nlink!==1||process.platform!=="win32"&&(stat.uid!==process.getuid?.()||stat.mode&63)||stat.size<100)fail("JOURNAL_BACKUP_REQUIRED");const n=await f.read(header,0,16,0);if(n.bytesRead!==16||header.toString()!=="SQLite format 3\0")fail("JOURNAL_BACKUP_REQUIRED")}finally{await f.close()}}export{localSocketPath,privateAccess,privateDirectory,syncDirectory,atomicMove,assertExecutable,runtimeLoginProtocol,runtimeLoginApprovalFile,loginPath,parseRuntimeLoginApproval,loginRevisionName,loginInputsCurrent,loginExecutableDigest,inspectModelPreparationGate,inspectResourceLifecycleGate,withModelPreparationGate,withResourceLifecycleGate,assertWindowsSystemTool,sha256,sha512,LocalClientError,fail,directory,read,digestPrivateFile,write,entries,optional,verifyBackup};
@@ -1 +1 @@
1
- import{DesktopRuntimeChannelSchema}from"./chunk-WLQMICJN.js";import{InstalledToolPathsSchema}from"./chunk-FFXSXE3G.js";import{AgentComponentScopeSchema,LocalRuntimeDescriptorSchema,LocalToolChoiceSchema}from"./chunk-LDBXGRCQ.js";import{z}from"zod";var digest=z.string().regex(/^[0-9a-f]{64}$/);var version=LocalRuntimeDescriptorSchema.shape.version;var revision=z.int().nonnegative();var request={requestId:z.uuid(),expectedRevision:revision};var planRequest={...request,planId:z.uuid(),fingerprint:digest};var planSelection={version,source:z.enum(["BUNDLED","SIGNED_CHANNEL"]).default("BUNDLED"),tools:z.union([LocalToolChoiceSchema,InstalledToolPathsSchema]).optional()};var componentChannel=DesktopRuntimeChannelSchema.extend({protocol:z.enum(["NVS_RUNTIME_RELEASE_CHANNEL_V1","NVS_DESKTOP_RUNTIME_CHANNEL_V1"])});var selectionVersion=z.union([version,z.literal("latest")]);var ComponentCommandSchema=z.discriminatedUnion("action",[z.strictObject({action:z.literal("apply"),...planRequest}),z.strictObject({action:z.literal("rollback"),...planRequest}),z.strictObject({action:z.literal("reconcile-install"),...planRequest}),z.strictObject({action:z.literal("start"),...request}),z.strictObject({action:z.literal("stop"),...request}),z.strictObject({action:z.literal("recover"),...request}),z.strictObject({action:z.literal("service-enable"),...request,fingerprint:digest})]);var HostComponentRequestSchema=z.strictObject({scope:AgentComponentScopeSchema,call:z.discriminatedUnion("action",[z.strictObject({action:z.literal("initialize"),channel:componentChannel.optional()}),z.strictObject({action:z.literal("status")}),z.strictObject({action:z.literal("preflight"),kind:z.enum(["library","preview","final"]),source:planSelection.source,version:selectionVersion.default("latest"),channel:componentChannel.optional(),tools:InstalledToolPathsSchema.pick({ffmpeg:true,ffprobe:true,captionAssetsDirectory:true}).partial().optional()}),z.strictObject({action:z.literal("receipt"),requestId:z.uuid()}),z.strictObject({action:z.literal("observe-original"),requestId:z.uuid()}),z.strictObject({action:z.literal("install-plan"),...planSelection,version:selectionVersion.describe("Use latest for the code bundled in this CLI. SIGNED_CHANNEL requires an exact version.")}),z.strictObject({action:z.literal("rollback-plan"),...planSelection}),z.strictObject({action:z.literal("service-plan")}),...ComponentCommandSchema.options])});export{ComponentCommandSchema,HostComponentRequestSchema};
1
+ import{DesktopRuntimeChannelSchema}from"./chunk-VXANXYQL.js";import{InstalledToolPathsSchema}from"./chunk-QLHMJUBH.js";import{AgentComponentScopeSchema,LocalRuntimeDescriptorSchema,LocalToolChoiceSchema}from"./chunk-UOYNCE7I.js";import{z}from"zod";var digest=z.string().regex(/^[0-9a-f]{64}$/);var version=LocalRuntimeDescriptorSchema.shape.version;var revision=z.int().nonnegative();var request={requestId:z.uuid(),expectedRevision:revision};var planRequest={...request,planId:z.uuid(),fingerprint:digest};var planSelection={version,source:z.enum(["BUNDLED","SIGNED_CHANNEL"]).default("BUNDLED"),tools:z.union([LocalToolChoiceSchema,InstalledToolPathsSchema]).optional()};var componentChannel=DesktopRuntimeChannelSchema.extend({protocol:z.enum(["NVS_RUNTIME_RELEASE_CHANNEL_V1","NVS_DESKTOP_RUNTIME_CHANNEL_V1"])});var selectionVersion=z.union([version,z.literal("latest")]);var ComponentCommandSchema=z.discriminatedUnion("action",[z.strictObject({action:z.literal("apply"),...planRequest}),z.strictObject({action:z.literal("rollback"),...planRequest}),z.strictObject({action:z.literal("reconcile-install"),...planRequest}),z.strictObject({action:z.literal("start"),...request}),z.strictObject({action:z.literal("stop"),...request}),z.strictObject({action:z.literal("recover"),...request}),z.strictObject({action:z.literal("service-enable"),...request,fingerprint:digest})]);var HostComponentRequestSchema=z.strictObject({scope:AgentComponentScopeSchema,call:z.discriminatedUnion("action",[z.strictObject({action:z.literal("initialize"),channel:componentChannel.optional()}),z.strictObject({action:z.literal("status")}),z.strictObject({action:z.literal("preflight"),kind:z.enum(["library","preview","final"]),source:planSelection.source,version:selectionVersion.default("latest"),channel:componentChannel.optional(),tools:InstalledToolPathsSchema.pick({ffmpeg:true,ffprobe:true,captionAssetsDirectory:true}).partial().optional()}),z.strictObject({action:z.literal("receipt"),requestId:z.uuid()}),z.strictObject({action:z.literal("observe-original"),requestId:z.uuid()}),z.strictObject({action:z.literal("install-plan"),...planSelection,version:selectionVersion.describe("Use latest for the code bundled in this CLI. SIGNED_CHANNEL requires an exact version.")}),z.strictObject({action:z.literal("rollback-plan"),...planSelection}),z.strictObject({action:z.literal("service-plan")}),...ComponentCommandSchema.options])});export{ComponentCommandSchema,HostComponentRequestSchema};
@@ -0,0 +1 @@
1
+ import{directory,privateAccess,privateDirectory,write}from"./chunk-AZQLZA47.js";import{secureEndpoint}from"./chunk-NEZ7IY5E.js";import{NativeStudioSdkError}from"./chunk-TT7IA5HB.js";import{homedir}from"node:os";import{isAbsolute,join}from"node:path";import{realpath}from"node:fs/promises";function connectionError(code){throw new NativeStudioSdkError(code,"INVALID_INPUT","NO_WRITE")}async function clientHome(environment,create=false){const path=environment.NATIVESTUDIO_CLIENT_HOME??join(homedir(),".nativestudio","client");if(!isAbsolute(path))connectionError("CLIENT_HOME_ABSOLUTE_REQUIRED");if(create)return directory(path);await privateDirectory(path);const root=await realpath(path);if(/(?:^|[\\/])(?:node_modules|_npx)(?:[\\/]|$)/.test(root))connectionError("CLIENT_HOME_PRIVATE_REQUIRED");return root}import{randomBytes}from"node:crypto";import{open,unlink,constants}from"node:fs/promises";import{dirname,resolve}from"node:path";import{z}from"zod";var publicOAuthClientId=z.string().regex(/^[A-Za-z0-9._:-]{1,128}$/u);var OAuthBindingSchema=z.discriminatedUnion("mode",[z.strictObject({mode:z.literal("legacy"),issuer:z.url().max(2048)}),z.strictObject({mode:z.literal("shared"),issuer:z.url().max(2048),clientId:publicOAuthClientId})]);function profileVersion(shared,pending=false){return shared?pending?4:3:pending?2:1}function validatePinnedDiscovery(binding,resource,discovery){if(!binding)return;const expected=secureEndpoint(binding.issuer);const metadata=discovery.authorizationServerMetadata;if(secureEndpoint(discovery.authorizationServerUrl).href!==expected.href||metadata&&metadata.issuer!==binding.issuer||discovery.resourceMetadata&&discovery.resourceMetadata.resource!==resource)connectionError("OAUTH_DISCOVERY_BINDING_MISMATCH");if(binding.mode==="shared"){if(expected.protocol!=="https:"||secureEndpoint(resource).protocol!=="https:"||discovery.resourceMetadata?.resource!==resource||discovery.resourceMetadata.authorization_servers?.length!==1||discovery.resourceMetadata.authorization_servers[0]!==binding.issuer||metadata&&(secureEndpoint(metadata.authorization_endpoint).origin!==expected.origin||secureEndpoint(metadata.token_endpoint).origin!==expected.origin||!metadata.code_challenge_methods_supported?.includes("S256")))connectionError("OAUTH_DISCOVERY_BINDING_MISMATCH")}}function validateSharedTokens(binding,requested,token){const allowed=requested.split(" ");const business=(token.scope??requested).split(/\s+/u).filter(scope=>scope.startsWith("nvs:"));if(token.issuer!==binding.issuer||!business.includes("nvs:read")||business.some(scope=>!allowed.includes(scope)))throw Error()}var FileOAuthProvider=class _FileOAuthProvider{constructor(path,data){this.path=path;this.data=data}path;data;static async create(path,resource,redirect,scope,discovered){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:profileVersion(discovered?.binding?.mode==="shared"),resource,redirect,scope,state:randomBytes(24).toString("base64url"),...discovered?.binding?{binding:discovered.binding}:{},...discovered?.discovery?{discovery:discovered.discovery}:{},...discovered?.binding?.mode==="shared"?{client:{client_id:discovered.binding.clientId,issuer:discovered.binding.issuer}}:{}};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,3,4].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.binding)OAuthBindingSchema.parse(data.binding);const shared=data.binding?.mode==="shared";if(data.version!==profileVersion(shared,data.pendingExchange!==void 0)||data.invalidGrant!==void 0&&(data.invalidGrant!==true||data.token!==void 0||data.pendingExchange!==void 0))throw Error();if(data.binding&&data.discovery)validatePinnedDiscovery(data.binding,data.resource,data.discovery);if(data.binding?.mode==="shared"&&(!data.discovery||!data.client||data.client.client_id!==data.binding.clientId||data.client.issuer!==data.binding.issuer||data.client.client_secret!==void 0))throw Error();if(data.binding?.mode==="shared"&&data.token)validateSharedTokens(data.binding,data.scope,data.token);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.requestedOAuthScope(),application_type:"native"}}state(){return this.data.state}clientInformation(){return this.data.client}async saveClientInformation(value){if(this.data.binding?.mode==="shared"&&(value.client_id!==this.data.binding.clientId||value.issuer!==this.data.binding.issuer||value.client_secret!==void 0))connectionError("OAUTH_SHARED_CLIENT_NOT_APPROVED");this.data.client=value;await this.save()}tokens(){return this.data.token}async saveTokens(value){if(this.data.binding?.mode==="shared")validateSharedTokens(this.data.binding,this.data.pendingExchange==="REFRESH"?this.grantedBusinessScope():this.data.scope,value);this.data.token=value;this.data.expiresAt=Date.now()+(value.expires_in??600)*1e3;this.data.version=profileVersion(this.data.binding?.mode==="shared");delete this.data.pendingExchange;await this.save()}requestedOAuthScope(){return this.data.binding?.mode==="shared"?"openid offline_access "+this.data.scope:this.data.scope}grantedBusinessScope(){const scope=this.data.token?.scope??this.data.scope;return this.data.binding?.mode==="shared"?this.data.scope.split(" ").filter(name=>scope.split(/\s+/u).includes(name)).join(" "):scope}async beginExchange(kind){this.data.version=profileVersion(this.data.binding?.mode==="shared",true);this.data.pendingExchange=kind;await this.save()}async refuseGrant(){this.data.version=profileVersion(this.data.binding?.mode==="shared");this.data.invalidGrant=true;delete this.data.token;delete this.data.expiresAt;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){if(this.data.binding?.mode!=="shared"&&value.resourceMetadata&&"nativestudio_cli_client_id"in value.resourceMetadata)connectionError("OAUTH_SHARED_DISCOVERY_MISMATCH");validatePinnedDiscovery(this.data.binding,this.data.resource,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{connectionError,clientHome,publicOAuthClientId,OAuthBindingSchema,FileOAuthProvider,withProfileLock};
@@ -0,0 +1 @@
1
+ import{catalogue}from"./chunk-VKXFHOAR.js";import{NativeStudioLocalRuntimeClient}from"./chunk-EOWXXTEF.js";import{LocalExecutionInspectInputSchema,LocalExecutionListInputSchema,LocalLibraryGetSchema,LocalLibraryProjectionPageSchema,LocalLibraryProjectionQuerySchema,LocalMcpOutputSchemas}from"./chunk-UOYNCE7I.js";import{fail,optional}from"./chunk-AZQLZA47.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 +1 @@
1
- import{localCliVersion}from"./chunk-2UYKJ6YN.js";import{NativeStudioMcpClient}from"./chunk-2S7FI3HF.js";import{boundedRemoteFetch,secureEndpoint}from"./chunk-KOCUZ3AE.js";import{NativeStudioSdkError}from"./chunk-TT7IA5HB.js";import{Client,StreamableHTTPClientTransport}from"@modelcontextprotocol/client";async function connectRemoteMcp(endpoint,authorization,tenantId,options={}){const url=secureEndpoint(endpoint);const client=new Client({name:"native-studio-remote-cli",version:(await localCliVersion()).version},{versionNegotiation:{mode:"auto"}});const stop=()=>{void client.close().catch(()=>{})};options.signal?.throwIfAborted();options.signal?.addEventListener("abort",stop,{once:true});try{const transport=new StreamableHTTPClientTransport(url,{requestInit:{headers:{authorization}},fetch:boundedRemoteFetch(options.maxJsonBytes??32*1024*1024,options.signal)});await client.connect(transport);return{studio:new NativeStudioMcpClient({tenantId,client,...options.maxJsonBytes?{maxJsonBytes:options.maxJsonBytes}:{}}),close:()=>{options.signal?.removeEventListener("abort",stop);return client.close()}}}catch{options.signal?.removeEventListener("abort",stop);await client.close();throw new NativeStudioSdkError("TRANSPORT_UNAVAILABLE","INTERNAL_OPERATIONAL_FAILURE","NO_WRITE")}}export{connectRemoteMcp};
1
+ import{localCliVersion}from"./chunk-2UYKJ6YN.js";import{NativeStudioMcpClient}from"./chunk-XMZKBILZ.js";import{boundedRemoteFetch,secureEndpoint}from"./chunk-NEZ7IY5E.js";import{NativeStudioSdkError}from"./chunk-TT7IA5HB.js";import{Client,StreamableHTTPClientTransport}from"@modelcontextprotocol/client";async function connectRemoteMcp(endpoint,authorization,tenantId,options={}){const url=secureEndpoint(endpoint);const client=new Client({name:"native-studio-remote-cli",version:(await localCliVersion()).version},{versionNegotiation:{mode:"auto"}});const stop=()=>{void client.close().catch(()=>{})};options.signal?.throwIfAborted();options.signal?.addEventListener("abort",stop,{once:true});try{const transport=new StreamableHTTPClientTransport(url,{requestInit:{headers:{authorization}},fetch:boundedRemoteFetch(options.maxJsonBytes??32*1024*1024,options.signal)});await client.connect(transport);return{studio:new NativeStudioMcpClient({tenantId,client,...options.maxJsonBytes?{maxJsonBytes:options.maxJsonBytes}:{}}),close:()=>{options.signal?.removeEventListener("abort",stop);return client.close()}}}catch{options.signal?.removeEventListener("abort",stop);await client.close();throw new NativeStudioSdkError("TRANSPORT_UNAVAILABLE","INTERNAL_OPERATIONAL_FAILURE","NO_WRITE")}}export{connectRemoteMcp};
@@ -0,0 +1 @@
1
+ import{inspectRecoveryBackups}from"./chunk-KGS6SI5Y.js";import{ownerClient,socketAbsent}from"./chunk-6YVGVNEH.js";import{verifyModelPlanRetirement}from"./chunk-N4ORSVTY.js";import{verifyModelSlotRetirement}from"./chunk-RRYZZBXN.js";import{LocalManagementInventorySchema,LocalModelRetentionInventorySchema,LocalToolSelectionSchema,canonicalLocalJson,cpuSpeechResources}from"./chunk-UOYNCE7I.js";import{entries,fail,inspectModelPreparationGate,inspectResourceLifecycleGate,privateAccess,read,sha256}from"./chunk-AZQLZA47.js";import{lstat,realpath}from"node:fs/promises";import{basename,dirname,isAbsolute,join,relative,resolve,sep}from"node:path";var hex=/^[a-f0-9]{64}$/;var uuidJson=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\.json$/;async function names(path){try{await privateAccess(path,"directory");if(await realpath(path)!==resolve(path))fail("MODEL_RETENTION_NOT_PROVEN");return(await entries(path)).sort()}catch(error){if(error.code==="ENOENT")return[];fail("MODEL_RETENTION_NOT_PROVEN","NO_WRITE")}}function within(parent,child){const path=relative(parent,child);return path===""||!isAbsolute(path)&&path!==".."&&!path.startsWith(".."+sep)}async function pathIdentity(path){if(!isAbsolute(path))fail("MODEL_RETENTION_NOT_PROVEN","NO_WRITE");const lexical=resolve(path),tail=[];let current=lexical;for(let i=0;i<256;i++){try{return[...new Set([lexical,join(await realpath(current),...tail)])]}catch(error){if(error.code!=="ENOENT")fail("MODEL_RETENTION_NOT_PROVEN","NO_WRITE");try{await lstat(current);fail("MODEL_RETENTION_NOT_PROVEN","NO_WRITE")}catch(e){if(e.code!=="ENOENT")fail("MODEL_RETENTION_NOT_PROVEN","NO_WRITE")}const parent=dirname(current);if(parent===current)break;tail.unshift(basename(current));current=parent}}fail("MODEL_RETENTION_NOT_PROVEN","NO_WRITE")}async function inspectModelRetention(manager){const report={protocol:"NVS_LOCAL_MODEL_RETENTION_V1",installationRevision:0,resources:[],externalPathReferences:{CPU_SPEECH:0,WHISPER:0},preparationEntries:0,backupEntries:0,backups:[],cleanupBlockers:["EXCLUSIVE_RETIREMENT_NOT_PROVEN"],deletionAllowed:false};if(!manager)return LocalModelRetentionInventorySchema.parse(report);const history=await manager.ledger.toolSelectionHistory();const configuration=await manager.configuration();const root=join(configuration.stateDirectory,"cpu-speech");try{await privateAccess(configuration.stateDirectory,"directory");if(await realpath(configuration.stateDirectory)!==resolve(configuration.stateDirectory))fail("MODEL_RETENTION_NOT_PROVEN")}catch{fail("MODEL_RETENTION_NOT_PROVEN","NO_WRITE")}const directorySnapshots=new Map;async function snapshotNames(path){const observed=await names(path);directorySnapshots.set(path,observed);return observed}await snapshotNames(root);const refs=new Map;const selectionSnapshots=new Map;const planSnapshots=new Map;const pathSnapshots=new Map;const retirementSnapshots=new Map;const externalCpu=new Set,externalWhisper=new Set;async function identities(path){const values=await pathIdentity(path),snapshot=canonicalLocalJson(values);if(pathSnapshots.has(path)&&pathSnapshots.get(path)!==snapshot)fail("REVISION_CONFLICT","NO_WRITE");pathSnapshots.set(path,snapshot);return values}async function addPath(path,reason,cpu=false){for(const identity of await identities(path)){const reasons=refs.get(identity)??new Set;reasons.add(reason);refs.set(identity,reasons);if(cpu&&!within(root,identity))externalCpu.add(identity)}}async function add(selection,reason){if(!selection)return;if(selection.cpuSpeech){await addPath(selection.cpuSpeech.engineDirectory,reason,true);await addPath(selection.cpuSpeech.modelDirectory,reason,true)}if("ffmpeg"in selection){await addPath(selection.ffmpeg.path,reason);await addPath(selection.ffprobe.path,reason)}if(selection.mode==="MANAGED"&&"reuseMedia"in selection&&selection.reuseMedia){await addPath(selection.reuseMedia.ffmpeg.path,reason);await addPath(selection.reuseMedia.ffprobe.path,reason)}if(selection.mode==="INSTALLED"&&selection.compositionBrowser)await addPath(selection.compositionBrowser.path,reason);if("captionAssetsDirectory"in selection&&selection.captionAssetsDirectory)await addPath(selection.captionAssetsDirectory,reason);if(selection.mode==="INSTALLED"&&selection.whisper){for(const path of[selection.whisper.binaryPath,selection.whisper.modelPath])for(const identity of await identities(path)){externalWhisper.add(identity);const reasons=refs.get(identity)??new Set;reasons.add(reason);refs.set(identity,reasons)}}}async function selectionFile(path,reason,cloud=false){if(!path)return;const bytes=await read(path,32768),hash=sha256(bytes);if(selectionSnapshots.has(path)&&selectionSnapshots.get(path)!==hash)fail("REVISION_CONFLICT","NO_WRITE");selectionSnapshots.set(path,hash);const raw=JSON.parse(bytes.toString());await add(LocalToolSelectionSchema.parse(cloud?raw.tools:raw),reason)}const current=history.value;const slotsDirectory=join(manager.ledger.root,"slots");const slotEntries=await snapshotNames(slotsDirectory);const retiredSlotNames=slotEntries.filter(n=>n.endsWith(".retired.json"));if(retiredSlotNames.some(n=>!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\.retired\.json$/i.test(n)))fail("MODEL_RETIREMENT_NOT_PROVEN","NO_WRITE");const slotsById=new Map(history.slots.map(slot=>[slot.id,slot]));if(retiredSlotNames.some(name=>!slotsById.has(name.slice(0,-13))))fail("MODEL_RETIREMENT_NOT_PROVEN","NO_WRITE");const liveSlotIds=new Set([current.active?.id,current.transition?.previous?.id,current.transition?.candidate?.id].filter(value=>!!value));const plansDirectory=join(manager.ledger.root,"plans");const planEntries=await snapshotNames(plansDirectory);const plans=planEntries.filter(n=>uuidJson.test(n));const retiredNames=planEntries.filter(n=>n.endsWith(".retired.json"));if(retiredNames.some(n=>!plans.includes(n.slice(0,-13)+".json")))fail("MODEL_RETIREMENT_NOT_PROVEN","NO_WRITE");try{for(const name of retiredSlotNames){const slot=slotsById.get(name.slice(0,-13));const path=join(slotsDirectory,name),bytes=await read(path,8192);verifyModelSlotRetirement(JSON.parse(bytes.toString()),history,slot);retirementSnapshots.set(path,sha256(bytes))}for(const slot of history.slots){if(liveSlotIds.has(slot.id)||retiredSlotNames.includes(slot.id+".retired.json"))continue;for(const version of slot.versions)await selectionFile(version.slot.toolsConfigPath,"HISTORY")}await selectionFile(current.active?.toolsConfigPath,"ACTIVE");for(const slot of[current.transition?.previous,current.transition?.candidate])await selectionFile(slot?.toolsConfigPath,"ROLLBACK");await selectionFile(configuration.cloudConfigFile,"CLOUD_CONFIGURATION",true);for(const plan of plans){const value=await manager.plan(plan.slice(0,-5));planSnapshots.set(plan,value.fingerprint);const retiredName=plan.slice(0,-5)+".retired.json";if(retiredNames.includes(retiredName)){const path=join(plansDirectory,retiredName),bytes=await read(path,8192);verifyModelPlanRetirement(JSON.parse(bytes.toString()),value,history);retirementSnapshots.set(path,sha256(bytes))}else await add(value.toolSelection,"SAVED_PLAN")}}catch{fail("MODEL_RETENTION_NOT_PROVEN","NO_WRITE")}const inherit=(tree,archives)=>{const reasons=new Set;for(const[path,source]of refs)if(within(tree,path)||within(path,tree))for(const reason of source)reasons.add(reason);if(!reasons.size)return;for(const digest of archives){const path=join(root,"downloads",digest+".archive");const existing=refs.get(path)??new Set;for(const reason of reasons)existing.add(reason);refs.set(path,existing)}};for(const engine of cpuSpeechResources.engines)inherit(join(root,"engines",engine.engineDigest),[engine.sha256,cpuSpeechResources.wrapper.sha256]);inherit(join(root,"models",cpuSpeechResources.model.treeDigest),[cpuSpeechResources.model.sha256]);const preparationDirectory=join(manager.ledger.root,"preparations");const ownerPreparationDirectory=join(root,"owner-preparations");const preparedNames=await names(preparationDirectory);const ownerPreparationNames=await names(ownerPreparationDirectory);const preparationGate=await inspectModelPreparationGate(configuration.stateDirectory);const lifecycleGate=await inspectResourceLifecycleGate(configuration.stateDirectory);let preparationEntries=preparedNames.length+ownerPreparationNames.length+(["ACTIVE","STALE","UNCONFIRMED"].includes(preparationGate.state)?1:0);for(const[directory,kind]of[["engines","CPU_ENGINE"],["models","CPU_MODEL"],["downloads","CPU_DOWNLOAD"]]){const parent=join(root,directory);for(const name of await snapshotNames(parent)){if(name.startsWith(".prepare-")||name.startsWith(".download-")){preparationEntries++;continue}const digest=kind==="CPU_DOWNLOAD"&&name.endsWith(".archive")?name.slice(0,-8):name;if(!hex.test(digest)||kind==="CPU_DOWNLOAD"&&!name.endsWith(".archive"))continue;const path=join(parent,name),info=await lstat(path);if(info.isSymbolicLink()||(kind==="CPU_DOWNLOAD"?!info.isFile():!info.isDirectory()))fail("MODEL_RETENTION_NOT_PROVEN","NO_WRITE");await privateAccess(path,kind==="CPU_DOWNLOAD"?"file":"directory");const protectedBy=new Set;for(const[reference,reasons]of refs)if(within(path,reference)||within(reference,path))for(const reason of reasons)protectedBy.add(reason);report.resources.push({kind,digest,protectedBy:[...protectedBy].sort(),decision:protectedBy.size?"RETAIN_REFERENCED":"REVIEW_REQUIRED"});if(report.resources.length>128)fail("MODEL_RETENTION_NOT_PROVEN","NO_WRITE")}}const blockers=new Set(report.cleanupBlockers);if(lifecycleGate.state==="ACTIVE")blockers.add("LIFECYCLE_GATE_ACTIVE");if(lifecycleGate.state==="STALE")blockers.add("LIFECYCLE_GATE_STALE");if(lifecycleGate.state==="UNCONFIRMED")blockers.add("LIFECYCLE_GATE_UNCONFIRMED");if(current.transition)blockers.add("INSTALLATION_TRANSITION");if(report.resources.some(r=>r.protectedBy.length)||externalCpu.size||externalWhisper.size)blockers.add("REFERENCED_RESOURCES");if(preparationEntries)blockers.add("PREPARATION_RECORDS");const backupNames=await snapshotNames(join(configuration.stateDirectory,"backups"));const backupSlot=current.transition?.previous??current.active??current.transition?.candidate;if(backupNames.length&&!backupSlot)fail("MODEL_RETENTION_NOT_PROVEN","NO_WRITE");const backups=backupSlot?await inspectRecoveryBackups(manager.ledger.slotPath(backupSlot),backupSlot,configuration.stateDirectory,backupNames,current.transition?.backupPath??null,true).catch(()=>inspectRecoveryBackups(manager.ledger.slotPath(backupSlot),backupSlot,configuration.stateDirectory,backupNames,current.transition?.backupPath??null)):[];const backupEntries=backups.length;if(backupEntries)blockers.add("RECOVERY_BACKUPS");if(await socketAbsent(configuration.stateDirectory)){for(const suffix of["","-wal","-shm","-journal"]){try{await lstat(join(configuration.stateDirectory,"journal.sqlite"+suffix));blockers.add("RUNTIME_JOURNAL_NOT_INSPECTED")}catch(error){if(error.code!=="ENOENT")blockers.add("RUNTIME_STATE_UNCONFIRMED")}}}else{try{const client=await ownerClient(configuration.stateDirectory);blockers.add("RUNTIME_RUNNING");let inventory;try{inventory=LocalManagementInventorySchema.parse(await client.call({operation:"runtime.inventory",includeProviderWork:true},AbortSignal.timeout(3e3)))}catch{inventory=await client.inventory(AbortSignal.timeout(3e3))}if(inventory.pendingProviderWork===void 0)blockers.add("RUNTIME_STATE_UNCONFIRMED");if(inventory.activeProcesses+inventory.pendingExecutions+inventory.pendingRequests+(inventory.pendingProviderWork??0)>0)blockers.add("PENDING_WORK")}catch{blockers.add("RUNTIME_STATE_UNCONFIRMED")}}for(const[path,hash]of selectionSnapshots)if(sha256(await read(path,32768))!==hash)fail("REVISION_CONFLICT","NO_WRITE");for(const[name,hash]of planSnapshots)if((await manager.plan(name.slice(0,-5))).fingerprint!==hash)fail("REVISION_CONFLICT","NO_WRITE");for(const[path,observed]of directorySnapshots)if(canonicalLocalJson(await names(path))!==canonicalLocalJson(observed))fail("REVISION_CONFLICT","NO_WRITE");for(const[path,hash]of retirementSnapshots)if(sha256(await read(path,8192))!==hash)fail("REVISION_CONFLICT","NO_WRITE");for(const[path,snapshot]of pathSnapshots)if(canonicalLocalJson(await pathIdentity(path))!==snapshot)fail("REVISION_CONFLICT","NO_WRITE");if(canonicalLocalJson(await names(preparationDirectory))!==canonicalLocalJson(preparedNames)||canonicalLocalJson(await names(ownerPreparationDirectory))!==canonicalLocalJson(ownerPreparationNames)||canonicalLocalJson(await names(slotsDirectory))!==canonicalLocalJson(slotEntries)||canonicalLocalJson(await inspectModelPreparationGate(configuration.stateDirectory))!==canonicalLocalJson(preparationGate)||canonicalLocalJson(await inspectResourceLifecycleGate(configuration.stateDirectory))!==canonicalLocalJson(lifecycleGate)||(await manager.ledger.current()).value.revision!==current.revision||canonicalLocalJson(await manager.configuration())!==canonicalLocalJson(configuration)||canonicalLocalJson((await names(join(manager.ledger.root,"plans"))).filter(n=>uuidJson.test(n)))!==canonicalLocalJson(plans))fail("REVISION_CONFLICT","NO_WRITE");return LocalModelRetentionInventorySchema.parse({...report,installationRevision:current.revision,preparationEntries,backupEntries,backups,cleanupBlockers:[...blockers].sort(),externalPathReferences:{CPU_SPEECH:externalCpu.size,WHISPER:externalWhisper.size}})}export{inspectModelRetention};
@@ -0,0 +1 @@
1
+ import{EnrollLocalDeviceSchema,LocalAgentDiscoverySchema,LocalAgentGrantSchema,LocalAgentProbeSchema,LocalAgentReviewViewSchema,LocalAgentSnapshotSchema,LocalDeviceManagementCommandSchema,LocalDeviceViewSchema,LocalDiagnosticsSchema,LocalDoctorReportSchema,LocalExecutionInspectInputSchema,LocalExecutionInspectionSchema,LocalExecutionListInputSchema,LocalExecutionPageSchema,LocalFinalRenderAdmissionSchema,LocalIpcRequestSchema,LocalIpcResponseSchema,LocalLibraryCallSchema,LocalLibraryCapabilitySchema,LocalLibraryGetSchema,LocalLibraryImportSchema,LocalLibraryItemSchema,LocalLibraryPageSchema,LocalLibraryProjectionPageSchema,LocalLibraryProjectionSchema,LocalLibraryReadReplySchema,LocalLibraryUsageSchema,LocalManagementInventorySchema,LocalManagementReceiptSchema,LocalOfflineCallSchema,LocalOfflinePageSchema,LocalPreviewAdmissionSchema,LocalResourcePolicySchema,LocalRuntimeStatusSchema,LocalSessionConnectorSchema,LocalWorkspaceInspectionSchema,RevokeLocalDeviceSchema,StartLocalFinalRenderSchema,StartLocalPreviewSchema,assertManagementReceipt,canonicalLocalJson,checkedManagementReceipt,mediaCategoryOf}from"./chunk-UOYNCE7I.js";import{localSocketPath,privateAccess,privateDirectory}from"./chunk-AZQLZA47.js";import{NativeStudioSdkError}from"./chunk-TT7IA5HB.js";import{z}from"zod";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,z.strictObject({semanticStatus:z.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 z2}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=z2.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}};export{NativeStudioLocalDeviceClient,NativeStudioLocalRuntimeClient};
@@ -0,0 +1 @@
1
+ import{DeviceEnrollmentScopeSchema,LocalDeviceTransportConfigurationSchema,LocalDeviceViewSchema,LocalFinalRenderAdmissionSchema,LocalManagementCommandSchema,LocalManagementResultSchema,LocalPreviewAdmissionSchema,StartLocalFinalRenderSchema,StartLocalPreviewSchema,canonicalLocalJson}from"./chunk-UOYNCE7I.js";import{directory,entries,fail,privateAccess,read,sha256,write}from"./chunk-AZQLZA47.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 DesktopConnectionSchema=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(),configurationFingerprint:digest.optional(),providerPreviousFingerprint:digest.optional()});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:DesktopConnectionSchema.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({connection:DesktopConnectionSchema.omit({configurationFingerprint:true,providerPreviousFingerprint:true}).nullable(),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()});import{join}from"node:path";import{realpath}from"node:fs/promises";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 desktopDeviceKeyPath(home,scope){return join(await realpath(recordRoot(home,scope)),"device-key.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{DesktopDeviceScopeSchema,DesktopDeviceRequestSchema,DesktopDeviceReplySchema,DesktopDeviceRecords,desktopDeviceKeyPath,desktopDeviceConnector};