@xylabs/aries 0.1.1

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 (421) hide show
  1. package/README.md +693 -0
  2. package/dist/actions/audit/auditPaths.mjs +22 -0
  3. package/dist/actions/audit/auditPaths.mjs.map +1 -0
  4. package/dist/actions/audit/index.mjs +739 -0
  5. package/dist/actions/audit/index.mjs.map +1 -0
  6. package/dist/actions/audit/installPlugin.mjs +298 -0
  7. package/dist/actions/audit/installPlugin.mjs.map +1 -0
  8. package/dist/actions/audit/listSessions.mjs +93 -0
  9. package/dist/actions/audit/listSessions.mjs.map +1 -0
  10. package/dist/actions/audit/openAuditDir.mjs +44 -0
  11. package/dist/actions/audit/openAuditDir.mjs.map +1 -0
  12. package/dist/actions/audit/searchAudit.mjs +77 -0
  13. package/dist/actions/audit/searchAudit.mjs.map +1 -0
  14. package/dist/actions/audit/showAiMeta.mjs +105 -0
  15. package/dist/actions/audit/showAiMeta.mjs.map +1 -0
  16. package/dist/actions/audit/showSession.mjs +105 -0
  17. package/dist/actions/audit/showSession.mjs.map +1 -0
  18. package/dist/actions/audit/statusAudit.mjs +98 -0
  19. package/dist/actions/audit/statusAudit.mjs.map +1 -0
  20. package/dist/actions/clamp/clampAudit.mjs +53 -0
  21. package/dist/actions/clamp/clampAudit.mjs.map +1 -0
  22. package/dist/actions/clamp/index.mjs +2258 -0
  23. package/dist/actions/clamp/index.mjs.map +1 -0
  24. package/dist/actions/clamp/ipcServer.mjs +55 -0
  25. package/dist/actions/clamp/ipcServer.mjs.map +1 -0
  26. package/dist/actions/clamp/policyManagement.mjs +144 -0
  27. package/dist/actions/clamp/policyManagement.mjs.map +1 -0
  28. package/dist/actions/clamp/promptUser.mjs +91 -0
  29. package/dist/actions/clamp/promptUser.mjs.map +1 -0
  30. package/dist/actions/clamp/runClamped.mjs +2107 -0
  31. package/dist/actions/clamp/runClamped.mjs.map +1 -0
  32. package/dist/actions/clamp/sandboxExec.mjs +1612 -0
  33. package/dist/actions/clamp/sandboxExec.mjs.map +1 -0
  34. package/dist/actions/clamp/shellEnvSetup.mjs +59 -0
  35. package/dist/actions/clamp/shellEnvSetup.mjs.map +1 -0
  36. package/dist/actions/clamp/shimGenerator.mjs +68 -0
  37. package/dist/actions/clamp/shimGenerator.mjs.map +1 -0
  38. package/dist/actions/clamp/terminalRenderer.mjs +145 -0
  39. package/dist/actions/clamp/terminalRenderer.mjs.map +1 -0
  40. package/dist/actions/datalake/audit/auditLog.mjs +191 -0
  41. package/dist/actions/datalake/audit/auditLog.mjs.map +1 -0
  42. package/dist/actions/datalake/createDatalake.mjs +127 -0
  43. package/dist/actions/datalake/createDatalake.mjs.map +1 -0
  44. package/dist/actions/datalake/describeDatalake.mjs +159 -0
  45. package/dist/actions/datalake/describeDatalake.mjs.map +1 -0
  46. package/dist/actions/datalake/destroyDatalake.mjs +34 -0
  47. package/dist/actions/datalake/destroyDatalake.mjs.map +1 -0
  48. package/dist/actions/datalake/dev/downDevServer.mjs +102 -0
  49. package/dist/actions/datalake/dev/downDevServer.mjs.map +1 -0
  50. package/dist/actions/datalake/dev/index.mjs +369 -0
  51. package/dist/actions/datalake/dev/index.mjs.map +1 -0
  52. package/dist/actions/datalake/dev/logsDevServer.mjs +44 -0
  53. package/dist/actions/datalake/dev/logsDevServer.mjs.map +1 -0
  54. package/dist/actions/datalake/dev/paths.mjs +25 -0
  55. package/dist/actions/datalake/dev/paths.mjs.map +1 -0
  56. package/dist/actions/datalake/dev/resetDevServer.mjs +118 -0
  57. package/dist/actions/datalake/dev/resetDevServer.mjs.map +1 -0
  58. package/dist/actions/datalake/dev/resolveServerBin.mjs +26 -0
  59. package/dist/actions/datalake/dev/resolveServerBin.mjs.map +1 -0
  60. package/dist/actions/datalake/dev/state.mjs +62 -0
  61. package/dist/actions/datalake/dev/state.mjs.map +1 -0
  62. package/dist/actions/datalake/dev/statusDevServer.mjs +101 -0
  63. package/dist/actions/datalake/dev/statusDevServer.mjs.map +1 -0
  64. package/dist/actions/datalake/dev/upDevServer.mjs +221 -0
  65. package/dist/actions/datalake/dev/upDevServer.mjs.map +1 -0
  66. package/dist/actions/datalake/dev/waitForHealth.mjs +22 -0
  67. package/dist/actions/datalake/dev/waitForHealth.mjs.map +1 -0
  68. package/dist/actions/datalake/formatters.mjs +90 -0
  69. package/dist/actions/datalake/formatters.mjs.map +1 -0
  70. package/dist/actions/datalake/grantAccess.mjs +116 -0
  71. package/dist/actions/datalake/grantAccess.mjs.map +1 -0
  72. package/dist/actions/datalake/index.mjs +361 -0
  73. package/dist/actions/datalake/index.mjs.map +1 -0
  74. package/dist/actions/datalake/listDatalakes.mjs +54 -0
  75. package/dist/actions/datalake/listDatalakes.mjs.map +1 -0
  76. package/dist/actions/datalake/login.mjs +20 -0
  77. package/dist/actions/datalake/login.mjs.map +1 -0
  78. package/dist/actions/datalake/logout.mjs +11 -0
  79. package/dist/actions/datalake/logout.mjs.map +1 -0
  80. package/dist/actions/datalake/mintToken.mjs +37 -0
  81. package/dist/actions/datalake/mintToken.mjs.map +1 -0
  82. package/dist/actions/datalake/parseSize.mjs +21 -0
  83. package/dist/actions/datalake/parseSize.mjs.map +1 -0
  84. package/dist/actions/datalake/payloads/fetchPayload.mjs +76 -0
  85. package/dist/actions/datalake/payloads/fetchPayload.mjs.map +1 -0
  86. package/dist/actions/datalake/payloads/index.mjs +271 -0
  87. package/dist/actions/datalake/payloads/index.mjs.map +1 -0
  88. package/dist/actions/datalake/payloads/mintAndConnect.mjs +46 -0
  89. package/dist/actions/datalake/payloads/mintAndConnect.mjs.map +1 -0
  90. package/dist/actions/datalake/payloads/parsePayloadsFile.mjs +71 -0
  91. package/dist/actions/datalake/payloads/parsePayloadsFile.mjs.map +1 -0
  92. package/dist/actions/datalake/payloads/pushPayloads.mjs +181 -0
  93. package/dist/actions/datalake/payloads/pushPayloads.mjs.map +1 -0
  94. package/dist/actions/datalake/payloads/tailPayloads.mjs +106 -0
  95. package/dist/actions/datalake/payloads/tailPayloads.mjs.map +1 -0
  96. package/dist/actions/datalake/resolveTarget.mjs +15 -0
  97. package/dist/actions/datalake/resolveTarget.mjs.map +1 -0
  98. package/dist/actions/datalake/revokeAccess.mjs +108 -0
  99. package/dist/actions/datalake/revokeAccess.mjs.map +1 -0
  100. package/dist/actions/datalake/useDatalake.mjs +22 -0
  101. package/dist/actions/datalake/useDatalake.mjs.map +1 -0
  102. package/dist/actions/detect/detectAiClients.mjs +405 -0
  103. package/dist/actions/detect/detectAiClients.mjs.map +1 -0
  104. package/dist/actions/detect/index.mjs +405 -0
  105. package/dist/actions/detect/index.mjs.map +1 -0
  106. package/dist/actions/hash/algorithms/blockhash.mjs +61 -0
  107. package/dist/actions/hash/algorithms/blockhash.mjs.map +1 -0
  108. package/dist/actions/hash/algorithms/chromaprint.mjs +205 -0
  109. package/dist/actions/hash/algorithms/chromaprint.mjs.map +1 -0
  110. package/dist/actions/hash/algorithms/dhash.mjs +75 -0
  111. package/dist/actions/hash/algorithms/dhash.mjs.map +1 -0
  112. package/dist/actions/hash/algorithms/index.mjs +818 -0
  113. package/dist/actions/hash/algorithms/index.mjs.map +1 -0
  114. package/dist/actions/hash/algorithms/nilsimsa.mjs +27 -0
  115. package/dist/actions/hash/algorithms/nilsimsa.mjs.map +1 -0
  116. package/dist/actions/hash/algorithms/pdq.mjs +83 -0
  117. package/dist/actions/hash/algorithms/pdq.mjs.map +1 -0
  118. package/dist/actions/hash/algorithms/phash.mjs +71 -0
  119. package/dist/actions/hash/algorithms/phash.mjs.map +1 -0
  120. package/dist/actions/hash/algorithms/sha256.mjs +24 -0
  121. package/dist/actions/hash/algorithms/sha256.mjs.map +1 -0
  122. package/dist/actions/hash/algorithms/ssdeep.mjs +203 -0
  123. package/dist/actions/hash/algorithms/ssdeep.mjs.map +1 -0
  124. package/dist/actions/hash/algorithms/tlsh.mjs +66 -0
  125. package/dist/actions/hash/algorithms/tlsh.mjs.map +1 -0
  126. package/dist/actions/hash/algorithms/types.mjs +1 -0
  127. package/dist/actions/hash/algorithms/types.mjs.map +1 -0
  128. package/dist/actions/hash/algorithms/videoFrames.mjs +404 -0
  129. package/dist/actions/hash/algorithms/videoFrames.mjs.map +1 -0
  130. package/dist/actions/hash/algorithms/xyo.mjs +30 -0
  131. package/dist/actions/hash/algorithms/xyo.mjs.map +1 -0
  132. package/dist/actions/hash/compareHashes.mjs +823 -0
  133. package/dist/actions/hash/compareHashes.mjs.map +1 -0
  134. package/dist/actions/hash/hashInput.mjs +868 -0
  135. package/dist/actions/hash/hashInput.mjs.map +1 -0
  136. package/dist/actions/hash/index.mjs +881 -0
  137. package/dist/actions/hash/index.mjs.map +1 -0
  138. package/dist/actions/hash/lib/hamming.mjs +44 -0
  139. package/dist/actions/hash/lib/hamming.mjs.map +1 -0
  140. package/dist/actions/hash/lib/levenshtein.mjs +36 -0
  141. package/dist/actions/hash/lib/levenshtein.mjs.map +1 -0
  142. package/dist/actions/hash/lib/runBinary.mjs +54 -0
  143. package/dist/actions/hash/lib/runBinary.mjs.map +1 -0
  144. package/dist/actions/hash/lib/which.mjs +36 -0
  145. package/dist/actions/hash/lib/which.mjs.map +1 -0
  146. package/dist/actions/hash/lib/withTempfile.mjs +19 -0
  147. package/dist/actions/hash/lib/withTempfile.mjs.map +1 -0
  148. package/dist/actions/index.mjs +4615 -0
  149. package/dist/actions/index.mjs.map +1 -0
  150. package/dist/actions/printVersion.mjs +12 -0
  151. package/dist/actions/printVersion.mjs.map +1 -0
  152. package/dist/actions/sync/index.mjs +51 -0
  153. package/dist/actions/sync/index.mjs.map +1 -0
  154. package/dist/actions/sync/syncAiConfig.mjs +51 -0
  155. package/dist/actions/sync/syncAiConfig.mjs.map +1 -0
  156. package/dist/actions/wallet/account/deriveAndAdd.mjs +394 -0
  157. package/dist/actions/wallet/account/deriveAndAdd.mjs.map +1 -0
  158. package/dist/actions/wallet/account/getActiveWallet.mjs +338 -0
  159. package/dist/actions/wallet/account/getActiveWallet.mjs.map +1 -0
  160. package/dist/actions/wallet/account/labelAccount.mjs +389 -0
  161. package/dist/actions/wallet/account/labelAccount.mjs.map +1 -0
  162. package/dist/actions/wallet/account/listAccounts.mjs +374 -0
  163. package/dist/actions/wallet/account/listAccounts.mjs.map +1 -0
  164. package/dist/actions/wallet/account/removeAccount.mjs +384 -0
  165. package/dist/actions/wallet/account/removeAccount.mjs.map +1 -0
  166. package/dist/actions/wallet/account/showAccount.mjs +368 -0
  167. package/dist/actions/wallet/account/showAccount.mjs.map +1 -0
  168. package/dist/actions/wallet/addressBook/storage.mjs +110 -0
  169. package/dist/actions/wallet/addressBook/storage.mjs.map +1 -0
  170. package/dist/actions/wallet/backup/exportBackup.mjs +93 -0
  171. package/dist/actions/wallet/backup/exportBackup.mjs.map +1 -0
  172. package/dist/actions/wallet/backup/importBackup.mjs +142 -0
  173. package/dist/actions/wallet/backup/importBackup.mjs.map +1 -0
  174. package/dist/actions/wallet/balance/getBalance.mjs +434 -0
  175. package/dist/actions/wallet/balance/getBalance.mjs.map +1 -0
  176. package/dist/actions/wallet/client/walletClient.mjs +64 -0
  177. package/dist/actions/wallet/client/walletClient.mjs.map +1 -0
  178. package/dist/actions/wallet/contact/contactActions.mjs +120 -0
  179. package/dist/actions/wallet/contact/contactActions.mjs.map +1 -0
  180. package/dist/actions/wallet/contact/storage.mjs +69 -0
  181. package/dist/actions/wallet/contact/storage.mjs.map +1 -0
  182. package/dist/actions/wallet/index.mjs +1439 -0
  183. package/dist/actions/wallet/index.mjs.map +1 -0
  184. package/dist/actions/wallet/network/networkActions.mjs +137 -0
  185. package/dist/actions/wallet/network/networkActions.mjs.map +1 -0
  186. package/dist/actions/wallet/network/storage.mjs +93 -0
  187. package/dist/actions/wallet/network/storage.mjs.map +1 -0
  188. package/dist/actions/wallet/password/changePassword.mjs +282 -0
  189. package/dist/actions/wallet/password/changePassword.mjs.map +1 -0
  190. package/dist/actions/wallet/password/getActiveKey.mjs +297 -0
  191. package/dist/actions/wallet/password/getActiveKey.mjs.map +1 -0
  192. package/dist/actions/wallet/password/initOrUnlock.mjs +337 -0
  193. package/dist/actions/wallet/password/initOrUnlock.mjs.map +1 -0
  194. package/dist/actions/wallet/password/passwordStorage.mjs +69 -0
  195. package/dist/actions/wallet/password/passwordStorage.mjs.map +1 -0
  196. package/dist/actions/wallet/password/setPassword.mjs +138 -0
  197. package/dist/actions/wallet/password/setPassword.mjs.map +1 -0
  198. package/dist/actions/wallet/password/validatePassword.mjs +123 -0
  199. package/dist/actions/wallet/password/validatePassword.mjs.map +1 -0
  200. package/dist/actions/wallet/passwordKey.mjs +87 -0
  201. package/dist/actions/wallet/passwordKey.mjs.map +1 -0
  202. package/dist/actions/wallet/paths.mjs +26 -0
  203. package/dist/actions/wallet/paths.mjs.map +1 -0
  204. package/dist/actions/wallet/prompt.mjs +93 -0
  205. package/dist/actions/wallet/prompt.mjs.map +1 -0
  206. package/dist/actions/wallet/seedPhrase/createPhrase.mjs +392 -0
  207. package/dist/actions/wallet/seedPhrase/createPhrase.mjs.map +1 -0
  208. package/dist/actions/wallet/seedPhrase/exportPhrase.mjs +334 -0
  209. package/dist/actions/wallet/seedPhrase/exportPhrase.mjs.map +1 -0
  210. package/dist/actions/wallet/seedPhrase/idGen.mjs +11 -0
  211. package/dist/actions/wallet/seedPhrase/idGen.mjs.map +1 -0
  212. package/dist/actions/wallet/seedPhrase/importPhrase.mjs +393 -0
  213. package/dist/actions/wallet/seedPhrase/importPhrase.mjs.map +1 -0
  214. package/dist/actions/wallet/seedPhrase/listPhrases.mjs +62 -0
  215. package/dist/actions/wallet/seedPhrase/listPhrases.mjs.map +1 -0
  216. package/dist/actions/wallet/seedPhrase/phraseStorage.mjs +89 -0
  217. package/dist/actions/wallet/seedPhrase/phraseStorage.mjs.map +1 -0
  218. package/dist/actions/wallet/seedPhrase/removePhrase.mjs +366 -0
  219. package/dist/actions/wallet/seedPhrase/removePhrase.mjs.map +1 -0
  220. package/dist/actions/wallet/seedPhrase/renamePhrase.mjs +78 -0
  221. package/dist/actions/wallet/seedPhrase/renamePhrase.mjs.map +1 -0
  222. package/dist/actions/wallet/seedPhrase/types.mjs +1 -0
  223. package/dist/actions/wallet/seedPhrase/types.mjs.map +1 -0
  224. package/dist/actions/wallet/seedPhrase/usePhrase.mjs +83 -0
  225. package/dist/actions/wallet/seedPhrase/usePhrase.mjs.map +1 -0
  226. package/dist/actions/wallet/session/machineId.mjs +145 -0
  227. package/dist/actions/wallet/session/machineId.mjs.map +1 -0
  228. package/dist/actions/wallet/session/sessionCache.mjs +221 -0
  229. package/dist/actions/wallet/session/sessionCache.mjs.map +1 -0
  230. package/dist/actions/wallet/session/unlock.mjs +307 -0
  231. package/dist/actions/wallet/session/unlock.mjs.map +1 -0
  232. package/dist/actions/wallet/sign/signPayload.mjs +637 -0
  233. package/dist/actions/wallet/sign/signPayload.mjs.map +1 -0
  234. package/dist/actions/wallet/storage.mjs +51 -0
  235. package/dist/actions/wallet/storage.mjs.map +1 -0
  236. package/dist/actions/wallet/transaction/broadcastTransaction.mjs +453 -0
  237. package/dist/actions/wallet/transaction/broadcastTransaction.mjs.map +1 -0
  238. package/dist/actions/wallet/transaction/sendTransaction.mjs +457 -0
  239. package/dist/actions/wallet/transaction/sendTransaction.mjs.map +1 -0
  240. package/dist/actions/wallet/transaction/signTransactionFile.mjs +378 -0
  241. package/dist/actions/wallet/transaction/signTransactionFile.mjs.map +1 -0
  242. package/dist/actions/xyo/index.mjs +138 -0
  243. package/dist/actions/xyo/index.mjs.map +1 -0
  244. package/dist/actions/xyo/transaction/index.mjs +138 -0
  245. package/dist/actions/xyo/transaction/index.mjs.map +1 -0
  246. package/dist/actions/xyo/transaction/validateTransactions.mjs +138 -0
  247. package/dist/actions/xyo/transaction/validateTransactions.mjs.map +1 -0
  248. package/dist/aries.mjs +8466 -0
  249. package/dist/aries.mjs.map +1 -0
  250. package/dist/bin/aries.mjs +8472 -0
  251. package/dist/bin/aries.mjs.map +1 -0
  252. package/dist/commands/aiCommand.mjs +492 -0
  253. package/dist/commands/aiCommand.mjs.map +1 -0
  254. package/dist/commands/auditAiCommand.mjs +119 -0
  255. package/dist/commands/auditAiCommand.mjs.map +1 -0
  256. package/dist/commands/auditCommand.mjs +857 -0
  257. package/dist/commands/auditCommand.mjs.map +1 -0
  258. package/dist/commands/auditInstallCommand.mjs +324 -0
  259. package/dist/commands/auditInstallCommand.mjs.map +1 -0
  260. package/dist/commands/auditListCommand.mjs +107 -0
  261. package/dist/commands/auditListCommand.mjs.map +1 -0
  262. package/dist/commands/auditOpenCommand.mjs +51 -0
  263. package/dist/commands/auditOpenCommand.mjs.map +1 -0
  264. package/dist/commands/auditSearchCommand.mjs +98 -0
  265. package/dist/commands/auditSearchCommand.mjs.map +1 -0
  266. package/dist/commands/auditShowCommand.mjs +123 -0
  267. package/dist/commands/auditShowCommand.mjs.map +1 -0
  268. package/dist/commands/auditStatusCommand.mjs +105 -0
  269. package/dist/commands/auditStatusCommand.mjs.map +1 -0
  270. package/dist/commands/clampCommand.mjs +2328 -0
  271. package/dist/commands/clampCommand.mjs.map +1 -0
  272. package/dist/commands/clampPolicyCommand.mjs +184 -0
  273. package/dist/commands/clampPolicyCommand.mjs.map +1 -0
  274. package/dist/commands/clampPolicyInitCommand.mjs +63 -0
  275. package/dist/commands/clampPolicyInitCommand.mjs.map +1 -0
  276. package/dist/commands/clampPolicyListCommand.mjs +56 -0
  277. package/dist/commands/clampPolicyListCommand.mjs.map +1 -0
  278. package/dist/commands/clampPolicyShowCommand.mjs +83 -0
  279. package/dist/commands/clampPolicyShowCommand.mjs.map +1 -0
  280. package/dist/commands/clampRunCommand.mjs +2137 -0
  281. package/dist/commands/clampRunCommand.mjs.map +1 -0
  282. package/dist/commands/datalakeAuditCommand.mjs +273 -0
  283. package/dist/commands/datalakeAuditCommand.mjs.map +1 -0
  284. package/dist/commands/datalakeCommand.mjs +1637 -0
  285. package/dist/commands/datalakeCommand.mjs.map +1 -0
  286. package/dist/commands/datalakeCreateCommand.mjs +189 -0
  287. package/dist/commands/datalakeCreateCommand.mjs.map +1 -0
  288. package/dist/commands/datalakeDescribeCommand.mjs +172 -0
  289. package/dist/commands/datalakeDescribeCommand.mjs.map +1 -0
  290. package/dist/commands/datalakeDestroyCommand.mjs +53 -0
  291. package/dist/commands/datalakeDestroyCommand.mjs.map +1 -0
  292. package/dist/commands/datalakeDevCommand.mjs +470 -0
  293. package/dist/commands/datalakeDevCommand.mjs.map +1 -0
  294. package/dist/commands/datalakeDevDownCommand.mjs +111 -0
  295. package/dist/commands/datalakeDevDownCommand.mjs.map +1 -0
  296. package/dist/commands/datalakeDevLogsCommand.mjs +65 -0
  297. package/dist/commands/datalakeDevLogsCommand.mjs.map +1 -0
  298. package/dist/commands/datalakeDevResetCommand.mjs +125 -0
  299. package/dist/commands/datalakeDevResetCommand.mjs.map +1 -0
  300. package/dist/commands/datalakeDevStatusCommand.mjs +110 -0
  301. package/dist/commands/datalakeDevStatusCommand.mjs.map +1 -0
  302. package/dist/commands/datalakeDevUpCommand.mjs +268 -0
  303. package/dist/commands/datalakeDevUpCommand.mjs.map +1 -0
  304. package/dist/commands/datalakeFetchCommand.mjs +106 -0
  305. package/dist/commands/datalakeFetchCommand.mjs.map +1 -0
  306. package/dist/commands/datalakeGrantCommand.mjs +147 -0
  307. package/dist/commands/datalakeGrantCommand.mjs.map +1 -0
  308. package/dist/commands/datalakeListCommand.mjs +61 -0
  309. package/dist/commands/datalakeListCommand.mjs.map +1 -0
  310. package/dist/commands/datalakeLoginCommand.mjs +39 -0
  311. package/dist/commands/datalakeLoginCommand.mjs.map +1 -0
  312. package/dist/commands/datalakeLogoutCommand.mjs +20 -0
  313. package/dist/commands/datalakeLogoutCommand.mjs.map +1 -0
  314. package/dist/commands/datalakePushCommand.mjs +214 -0
  315. package/dist/commands/datalakePushCommand.mjs.map +1 -0
  316. package/dist/commands/datalakeRevokeCommand.mjs +127 -0
  317. package/dist/commands/datalakeRevokeCommand.mjs.map +1 -0
  318. package/dist/commands/datalakeTailCommand.mjs +144 -0
  319. package/dist/commands/datalakeTailCommand.mjs.map +1 -0
  320. package/dist/commands/datalakeTokenCommand.mjs +61 -0
  321. package/dist/commands/datalakeTokenCommand.mjs.map +1 -0
  322. package/dist/commands/datalakeUseCommand.mjs +35 -0
  323. package/dist/commands/datalakeUseCommand.mjs.map +1 -0
  324. package/dist/commands/detectCommand.mjs +419 -0
  325. package/dist/commands/detectCommand.mjs.map +1 -0
  326. package/dist/commands/hashCommand.mjs +976 -0
  327. package/dist/commands/hashCommand.mjs.map +1 -0
  328. package/dist/commands/hashCompareCommand.mjs +865 -0
  329. package/dist/commands/hashCompareCommand.mjs.map +1 -0
  330. package/dist/commands/index.mjs +8461 -0
  331. package/dist/commands/index.mjs.map +1 -0
  332. package/dist/commands/syncCommand.mjs +66 -0
  333. package/dist/commands/syncCommand.mjs.map +1 -0
  334. package/dist/commands/versionCommand.mjs +24 -0
  335. package/dist/commands/versionCommand.mjs.map +1 -0
  336. package/dist/commands/walletAccountCommand.mjs +536 -0
  337. package/dist/commands/walletAccountCommand.mjs.map +1 -0
  338. package/dist/commands/walletAccountDeriveCommand.mjs +415 -0
  339. package/dist/commands/walletAccountDeriveCommand.mjs.map +1 -0
  340. package/dist/commands/walletAccountLabelCommand.mjs +405 -0
  341. package/dist/commands/walletAccountLabelCommand.mjs.map +1 -0
  342. package/dist/commands/walletAccountListCommand.mjs +381 -0
  343. package/dist/commands/walletAccountListCommand.mjs.map +1 -0
  344. package/dist/commands/walletAccountRemoveCommand.mjs +396 -0
  345. package/dist/commands/walletAccountRemoveCommand.mjs.map +1 -0
  346. package/dist/commands/walletAccountShowCommand.mjs +380 -0
  347. package/dist/commands/walletAccountShowCommand.mjs.map +1 -0
  348. package/dist/commands/walletBackupCommand.mjs +222 -0
  349. package/dist/commands/walletBackupCommand.mjs.map +1 -0
  350. package/dist/commands/walletBackupExportCommand.mjs +107 -0
  351. package/dist/commands/walletBackupExportCommand.mjs.map +1 -0
  352. package/dist/commands/walletBackupImportCommand.mjs +154 -0
  353. package/dist/commands/walletBackupImportCommand.mjs.map +1 -0
  354. package/dist/commands/walletBalanceCommand.mjs +448 -0
  355. package/dist/commands/walletBalanceCommand.mjs.map +1 -0
  356. package/dist/commands/walletCommand.mjs +1968 -0
  357. package/dist/commands/walletCommand.mjs.map +1 -0
  358. package/dist/commands/walletContactAddCommand.mjs +111 -0
  359. package/dist/commands/walletContactAddCommand.mjs.map +1 -0
  360. package/dist/commands/walletContactCommand.mjs +184 -0
  361. package/dist/commands/walletContactCommand.mjs.map +1 -0
  362. package/dist/commands/walletContactListCommand.mjs +66 -0
  363. package/dist/commands/walletContactListCommand.mjs.map +1 -0
  364. package/dist/commands/walletContactRemoveCommand.mjs +97 -0
  365. package/dist/commands/walletContactRemoveCommand.mjs.map +1 -0
  366. package/dist/commands/walletContactRenameCommand.mjs +114 -0
  367. package/dist/commands/walletContactRenameCommand.mjs.map +1 -0
  368. package/dist/commands/walletCreateCommand.mjs +407 -0
  369. package/dist/commands/walletCreateCommand.mjs.map +1 -0
  370. package/dist/commands/walletExportCommand.mjs +345 -0
  371. package/dist/commands/walletExportCommand.mjs.map +1 -0
  372. package/dist/commands/walletImportCommand.mjs +413 -0
  373. package/dist/commands/walletImportCommand.mjs.map +1 -0
  374. package/dist/commands/walletListCommand.mjs +69 -0
  375. package/dist/commands/walletListCommand.mjs.map +1 -0
  376. package/dist/commands/walletLockCommand.mjs +56 -0
  377. package/dist/commands/walletLockCommand.mjs.map +1 -0
  378. package/dist/commands/walletNetworkAddCommand.mjs +131 -0
  379. package/dist/commands/walletNetworkAddCommand.mjs.map +1 -0
  380. package/dist/commands/walletNetworkCommand.mjs +206 -0
  381. package/dist/commands/walletNetworkCommand.mjs.map +1 -0
  382. package/dist/commands/walletNetworkListCommand.mjs +104 -0
  383. package/dist/commands/walletNetworkListCommand.mjs.map +1 -0
  384. package/dist/commands/walletNetworkRemoveCommand.mjs +112 -0
  385. package/dist/commands/walletNetworkRemoveCommand.mjs.map +1 -0
  386. package/dist/commands/walletNetworkUseCommand.mjs +110 -0
  387. package/dist/commands/walletNetworkUseCommand.mjs.map +1 -0
  388. package/dist/commands/walletPasswordChangeCommand.mjs +291 -0
  389. package/dist/commands/walletPasswordChangeCommand.mjs.map +1 -0
  390. package/dist/commands/walletPasswordCommand.mjs +301 -0
  391. package/dist/commands/walletPasswordCommand.mjs.map +1 -0
  392. package/dist/commands/walletRemoveCommand.mjs +378 -0
  393. package/dist/commands/walletRemoveCommand.mjs.map +1 -0
  394. package/dist/commands/walletRenameCommand.mjs +94 -0
  395. package/dist/commands/walletRenameCommand.mjs.map +1 -0
  396. package/dist/commands/walletSignCommand.mjs +662 -0
  397. package/dist/commands/walletSignCommand.mjs.map +1 -0
  398. package/dist/commands/walletTxBroadcastCommand.mjs +473 -0
  399. package/dist/commands/walletTxBroadcastCommand.mjs.map +1 -0
  400. package/dist/commands/walletTxCommand.mjs +612 -0
  401. package/dist/commands/walletTxCommand.mjs.map +1 -0
  402. package/dist/commands/walletTxSendCommand.mjs +492 -0
  403. package/dist/commands/walletTxSendCommand.mjs.map +1 -0
  404. package/dist/commands/walletTxSignCommand.mjs +403 -0
  405. package/dist/commands/walletTxSignCommand.mjs.map +1 -0
  406. package/dist/commands/walletUnlockCommand.mjs +308 -0
  407. package/dist/commands/walletUnlockCommand.mjs.map +1 -0
  408. package/dist/commands/walletUseCommand.mjs +95 -0
  409. package/dist/commands/walletUseCommand.mjs.map +1 -0
  410. package/dist/commands/xyoCommand.mjs +188 -0
  411. package/dist/commands/xyoCommand.mjs.map +1 -0
  412. package/dist/commands/xyoTxCommand.mjs +178 -0
  413. package/dist/commands/xyoTxCommand.mjs.map +1 -0
  414. package/dist/commands/xyoTxValidateCommand.mjs +168 -0
  415. package/dist/commands/xyoTxValidateCommand.mjs.map +1 -0
  416. package/dist/index.d.ts +3 -0
  417. package/dist/index.mjs +8466 -0
  418. package/dist/index.mjs.map +1 -0
  419. package/dist/types/modules.d.mjs +1 -0
  420. package/dist/types/modules.d.mjs.map +1 -0
  421. package/package.json +197 -0
@@ -0,0 +1,4615 @@
1
+ var __getOwnPropNames = Object.getOwnPropertyNames;
2
+ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
3
+ get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
4
+ }) : x)(function(x) {
5
+ if (typeof require !== "undefined") return require.apply(this, arguments);
6
+ throw Error('Dynamic require of "' + x + '" is not supported');
7
+ });
8
+ var __commonJS = (cb, mod) => function __require2() {
9
+ return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
10
+ };
11
+
12
+ // ../../node_modules/.pnpm/node-pty@1.1.0/node_modules/node-pty/lib/utils.js
13
+ var require_utils = __commonJS({
14
+ "../../node_modules/.pnpm/node-pty@1.1.0/node_modules/node-pty/lib/utils.js"(exports) {
15
+ "use strict";
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ exports.loadNativeModule = exports.assign = void 0;
18
+ function assign(target) {
19
+ var sources = [];
20
+ for (var _i = 1; _i < arguments.length; _i++) {
21
+ sources[_i - 1] = arguments[_i];
22
+ }
23
+ sources.forEach(function(source) {
24
+ return Object.keys(source).forEach(function(key) {
25
+ return target[key] = source[key];
26
+ });
27
+ });
28
+ return target;
29
+ }
30
+ exports.assign = assign;
31
+ function loadNativeModule(name) {
32
+ var dirs = ["build/Release", "build/Debug", "prebuilds/" + process.platform + "-" + process.arch];
33
+ var relative = ["..", "."];
34
+ var lastError;
35
+ for (var _i = 0, dirs_1 = dirs; _i < dirs_1.length; _i++) {
36
+ var d = dirs_1[_i];
37
+ for (var _a = 0, relative_1 = relative; _a < relative_1.length; _a++) {
38
+ var r = relative_1[_a];
39
+ var dir = r + "/" + d + "/";
40
+ try {
41
+ return { dir, module: __require(dir + "/" + name + ".node") };
42
+ } catch (e) {
43
+ lastError = e;
44
+ }
45
+ }
46
+ }
47
+ throw new Error("Failed to load native module: " + name + ".node, checked: " + dirs.join(", ") + ": " + lastError);
48
+ }
49
+ exports.loadNativeModule = loadNativeModule;
50
+ }
51
+ });
52
+
53
+ // ../../node_modules/.pnpm/node-pty@1.1.0/node_modules/node-pty/lib/eventEmitter2.js
54
+ var require_eventEmitter2 = __commonJS({
55
+ "../../node_modules/.pnpm/node-pty@1.1.0/node_modules/node-pty/lib/eventEmitter2.js"(exports) {
56
+ "use strict";
57
+ Object.defineProperty(exports, "__esModule", { value: true });
58
+ exports.EventEmitter2 = void 0;
59
+ var EventEmitter2 = (
60
+ /** @class */
61
+ (function() {
62
+ function EventEmitter22() {
63
+ this._listeners = [];
64
+ }
65
+ Object.defineProperty(EventEmitter22.prototype, "event", {
66
+ get: function() {
67
+ var _this = this;
68
+ if (!this._event) {
69
+ this._event = function(listener) {
70
+ _this._listeners.push(listener);
71
+ var disposable = {
72
+ dispose: function() {
73
+ for (var i = 0; i < _this._listeners.length; i++) {
74
+ if (_this._listeners[i] === listener) {
75
+ _this._listeners.splice(i, 1);
76
+ return;
77
+ }
78
+ }
79
+ }
80
+ };
81
+ return disposable;
82
+ };
83
+ }
84
+ return this._event;
85
+ },
86
+ enumerable: false,
87
+ configurable: true
88
+ });
89
+ EventEmitter22.prototype.fire = function(data) {
90
+ var queue = [];
91
+ for (var i = 0; i < this._listeners.length; i++) {
92
+ queue.push(this._listeners[i]);
93
+ }
94
+ for (var i = 0; i < queue.length; i++) {
95
+ queue[i].call(void 0, data);
96
+ }
97
+ };
98
+ return EventEmitter22;
99
+ })()
100
+ );
101
+ exports.EventEmitter2 = EventEmitter2;
102
+ }
103
+ });
104
+
105
+ // ../../node_modules/.pnpm/node-pty@1.1.0/node_modules/node-pty/lib/terminal.js
106
+ var require_terminal = __commonJS({
107
+ "../../node_modules/.pnpm/node-pty@1.1.0/node_modules/node-pty/lib/terminal.js"(exports) {
108
+ "use strict";
109
+ Object.defineProperty(exports, "__esModule", { value: true });
110
+ exports.Terminal = exports.DEFAULT_ROWS = exports.DEFAULT_COLS = void 0;
111
+ var events_1 = __require("events");
112
+ var eventEmitter2_1 = require_eventEmitter2();
113
+ exports.DEFAULT_COLS = 80;
114
+ exports.DEFAULT_ROWS = 24;
115
+ var FLOW_CONTROL_PAUSE = "";
116
+ var FLOW_CONTROL_RESUME = "";
117
+ var Terminal2 = (
118
+ /** @class */
119
+ (function() {
120
+ function Terminal3(opt) {
121
+ this._pid = 0;
122
+ this._fd = 0;
123
+ this._cols = 0;
124
+ this._rows = 0;
125
+ this._readable = false;
126
+ this._writable = false;
127
+ this._onData = new eventEmitter2_1.EventEmitter2();
128
+ this._onExit = new eventEmitter2_1.EventEmitter2();
129
+ this._internalee = new events_1.EventEmitter();
130
+ this.handleFlowControl = !!(opt === null || opt === void 0 ? void 0 : opt.handleFlowControl);
131
+ this._flowControlPause = (opt === null || opt === void 0 ? void 0 : opt.flowControlPause) || FLOW_CONTROL_PAUSE;
132
+ this._flowControlResume = (opt === null || opt === void 0 ? void 0 : opt.flowControlResume) || FLOW_CONTROL_RESUME;
133
+ if (!opt) {
134
+ return;
135
+ }
136
+ this._checkType("name", opt.name ? opt.name : void 0, "string");
137
+ this._checkType("cols", opt.cols ? opt.cols : void 0, "number");
138
+ this._checkType("rows", opt.rows ? opt.rows : void 0, "number");
139
+ this._checkType("cwd", opt.cwd ? opt.cwd : void 0, "string");
140
+ this._checkType("env", opt.env ? opt.env : void 0, "object");
141
+ this._checkType("uid", opt.uid ? opt.uid : void 0, "number");
142
+ this._checkType("gid", opt.gid ? opt.gid : void 0, "number");
143
+ this._checkType("encoding", opt.encoding ? opt.encoding : void 0, "string");
144
+ }
145
+ Object.defineProperty(Terminal3.prototype, "onData", {
146
+ get: function() {
147
+ return this._onData.event;
148
+ },
149
+ enumerable: false,
150
+ configurable: true
151
+ });
152
+ Object.defineProperty(Terminal3.prototype, "onExit", {
153
+ get: function() {
154
+ return this._onExit.event;
155
+ },
156
+ enumerable: false,
157
+ configurable: true
158
+ });
159
+ Object.defineProperty(Terminal3.prototype, "pid", {
160
+ get: function() {
161
+ return this._pid;
162
+ },
163
+ enumerable: false,
164
+ configurable: true
165
+ });
166
+ Object.defineProperty(Terminal3.prototype, "cols", {
167
+ get: function() {
168
+ return this._cols;
169
+ },
170
+ enumerable: false,
171
+ configurable: true
172
+ });
173
+ Object.defineProperty(Terminal3.prototype, "rows", {
174
+ get: function() {
175
+ return this._rows;
176
+ },
177
+ enumerable: false,
178
+ configurable: true
179
+ });
180
+ Terminal3.prototype.write = function(data) {
181
+ if (this.handleFlowControl) {
182
+ if (data === this._flowControlPause) {
183
+ this.pause();
184
+ return;
185
+ }
186
+ if (data === this._flowControlResume) {
187
+ this.resume();
188
+ return;
189
+ }
190
+ }
191
+ this._write(data);
192
+ };
193
+ Terminal3.prototype._forwardEvents = function() {
194
+ var _this = this;
195
+ this.on("data", function(e) {
196
+ return _this._onData.fire(e);
197
+ });
198
+ this.on("exit", function(exitCode, signal) {
199
+ return _this._onExit.fire({ exitCode, signal });
200
+ });
201
+ };
202
+ Terminal3.prototype._checkType = function(name, value, type, allowArray) {
203
+ if (allowArray === void 0) {
204
+ allowArray = false;
205
+ }
206
+ if (value === void 0) {
207
+ return;
208
+ }
209
+ if (allowArray) {
210
+ if (Array.isArray(value)) {
211
+ value.forEach(function(v, i) {
212
+ if (typeof v !== type) {
213
+ throw new Error(name + "[" + i + "] must be a " + type + " (not a " + typeof v[i] + ")");
214
+ }
215
+ });
216
+ return;
217
+ }
218
+ }
219
+ if (typeof value !== type) {
220
+ throw new Error(name + " must be a " + type + " (not a " + typeof value + ")");
221
+ }
222
+ };
223
+ Terminal3.prototype.end = function(data) {
224
+ this._socket.end(data);
225
+ };
226
+ Terminal3.prototype.pipe = function(dest, options) {
227
+ return this._socket.pipe(dest, options);
228
+ };
229
+ Terminal3.prototype.pause = function() {
230
+ return this._socket.pause();
231
+ };
232
+ Terminal3.prototype.resume = function() {
233
+ return this._socket.resume();
234
+ };
235
+ Terminal3.prototype.setEncoding = function(encoding) {
236
+ if (this._socket._decoder) {
237
+ delete this._socket._decoder;
238
+ }
239
+ if (encoding) {
240
+ this._socket.setEncoding(encoding);
241
+ }
242
+ };
243
+ Terminal3.prototype.addListener = function(eventName, listener) {
244
+ this.on(eventName, listener);
245
+ };
246
+ Terminal3.prototype.on = function(eventName, listener) {
247
+ if (eventName === "close") {
248
+ this._internalee.on("close", listener);
249
+ return;
250
+ }
251
+ this._socket.on(eventName, listener);
252
+ };
253
+ Terminal3.prototype.emit = function(eventName) {
254
+ var args = [];
255
+ for (var _i = 1; _i < arguments.length; _i++) {
256
+ args[_i - 1] = arguments[_i];
257
+ }
258
+ if (eventName === "close") {
259
+ return this._internalee.emit.apply(this._internalee, arguments);
260
+ }
261
+ return this._socket.emit.apply(this._socket, arguments);
262
+ };
263
+ Terminal3.prototype.listeners = function(eventName) {
264
+ return this._socket.listeners(eventName);
265
+ };
266
+ Terminal3.prototype.removeListener = function(eventName, listener) {
267
+ this._socket.removeListener(eventName, listener);
268
+ };
269
+ Terminal3.prototype.removeAllListeners = function(eventName) {
270
+ this._socket.removeAllListeners(eventName);
271
+ };
272
+ Terminal3.prototype.once = function(eventName, listener) {
273
+ this._socket.once(eventName, listener);
274
+ };
275
+ Terminal3.prototype._close = function() {
276
+ this._socket.readable = false;
277
+ this.write = function() {
278
+ };
279
+ this.end = function() {
280
+ };
281
+ this._writable = false;
282
+ this._readable = false;
283
+ };
284
+ Terminal3.prototype._parseEnv = function(env) {
285
+ var keys = Object.keys(env || {});
286
+ var pairs = [];
287
+ for (var i = 0; i < keys.length; i++) {
288
+ if (keys[i] === void 0) {
289
+ continue;
290
+ }
291
+ pairs.push(keys[i] + "=" + env[keys[i]]);
292
+ }
293
+ return pairs;
294
+ };
295
+ return Terminal3;
296
+ })()
297
+ );
298
+ exports.Terminal = Terminal2;
299
+ }
300
+ });
301
+
302
+ // ../../node_modules/.pnpm/node-pty@1.1.0/node_modules/node-pty/lib/shared/conout.js
303
+ var require_conout = __commonJS({
304
+ "../../node_modules/.pnpm/node-pty@1.1.0/node_modules/node-pty/lib/shared/conout.js"(exports) {
305
+ "use strict";
306
+ Object.defineProperty(exports, "__esModule", { value: true });
307
+ exports.getWorkerPipeName = void 0;
308
+ function getWorkerPipeName(conoutPipeName) {
309
+ return conoutPipeName + "-worker";
310
+ }
311
+ exports.getWorkerPipeName = getWorkerPipeName;
312
+ }
313
+ });
314
+
315
+ // ../../node_modules/.pnpm/node-pty@1.1.0/node_modules/node-pty/lib/windowsConoutConnection.js
316
+ var require_windowsConoutConnection = __commonJS({
317
+ "../../node_modules/.pnpm/node-pty@1.1.0/node_modules/node-pty/lib/windowsConoutConnection.js"(exports) {
318
+ "use strict";
319
+ var __awaiter = exports && exports.__awaiter || function(thisArg, _arguments, P, generator) {
320
+ function adopt(value) {
321
+ return value instanceof P ? value : new P(function(resolve) {
322
+ resolve(value);
323
+ });
324
+ }
325
+ return new (P || (P = Promise))(function(resolve, reject) {
326
+ function fulfilled(value) {
327
+ try {
328
+ step(generator.next(value));
329
+ } catch (e) {
330
+ reject(e);
331
+ }
332
+ }
333
+ function rejected(value) {
334
+ try {
335
+ step(generator["throw"](value));
336
+ } catch (e) {
337
+ reject(e);
338
+ }
339
+ }
340
+ function step(result) {
341
+ result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected);
342
+ }
343
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
344
+ });
345
+ };
346
+ var __generator = exports && exports.__generator || function(thisArg, body) {
347
+ var _ = { label: 0, sent: function() {
348
+ if (t[0] & 1) throw t[1];
349
+ return t[1];
350
+ }, trys: [], ops: [] }, f, y, t, g;
351
+ return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() {
352
+ return this;
353
+ }), g;
354
+ function verb(n) {
355
+ return function(v) {
356
+ return step([n, v]);
357
+ };
358
+ }
359
+ function step(op) {
360
+ if (f) throw new TypeError("Generator is already executing.");
361
+ while (_) try {
362
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
363
+ if (y = 0, t) op = [op[0] & 2, t.value];
364
+ switch (op[0]) {
365
+ case 0:
366
+ case 1:
367
+ t = op;
368
+ break;
369
+ case 4:
370
+ _.label++;
371
+ return { value: op[1], done: false };
372
+ case 5:
373
+ _.label++;
374
+ y = op[1];
375
+ op = [0];
376
+ continue;
377
+ case 7:
378
+ op = _.ops.pop();
379
+ _.trys.pop();
380
+ continue;
381
+ default:
382
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
383
+ _ = 0;
384
+ continue;
385
+ }
386
+ if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
387
+ _.label = op[1];
388
+ break;
389
+ }
390
+ if (op[0] === 6 && _.label < t[1]) {
391
+ _.label = t[1];
392
+ t = op;
393
+ break;
394
+ }
395
+ if (t && _.label < t[2]) {
396
+ _.label = t[2];
397
+ _.ops.push(op);
398
+ break;
399
+ }
400
+ if (t[2]) _.ops.pop();
401
+ _.trys.pop();
402
+ continue;
403
+ }
404
+ op = body.call(thisArg, _);
405
+ } catch (e) {
406
+ op = [6, e];
407
+ y = 0;
408
+ } finally {
409
+ f = t = 0;
410
+ }
411
+ if (op[0] & 5) throw op[1];
412
+ return { value: op[0] ? op[1] : void 0, done: true };
413
+ }
414
+ };
415
+ Object.defineProperty(exports, "__esModule", { value: true });
416
+ exports.ConoutConnection = void 0;
417
+ var worker_threads_1 = __require("worker_threads");
418
+ var conout_1 = require_conout();
419
+ var path_1 = __require("path");
420
+ var eventEmitter2_1 = require_eventEmitter2();
421
+ var FLUSH_DATA_INTERVAL = 1e3;
422
+ var ConoutConnection = (
423
+ /** @class */
424
+ (function() {
425
+ function ConoutConnection2(_conoutPipeName, _useConptyDll) {
426
+ var _this = this;
427
+ this._conoutPipeName = _conoutPipeName;
428
+ this._useConptyDll = _useConptyDll;
429
+ this._isDisposed = false;
430
+ this._onReady = new eventEmitter2_1.EventEmitter2();
431
+ var workerData = {
432
+ conoutPipeName: _conoutPipeName
433
+ };
434
+ var scriptPath = __dirname.replace("node_modules.asar", "node_modules.asar.unpacked");
435
+ this._worker = new worker_threads_1.Worker(path_1.join(scriptPath, "worker/conoutSocketWorker.js"), { workerData });
436
+ this._worker.on("message", function(message) {
437
+ switch (message) {
438
+ case 1:
439
+ _this._onReady.fire();
440
+ return;
441
+ default:
442
+ console.warn("Unexpected ConoutWorkerMessage", message);
443
+ }
444
+ });
445
+ }
446
+ Object.defineProperty(ConoutConnection2.prototype, "onReady", {
447
+ get: function() {
448
+ return this._onReady.event;
449
+ },
450
+ enumerable: false,
451
+ configurable: true
452
+ });
453
+ ConoutConnection2.prototype.dispose = function() {
454
+ if (!this._useConptyDll && this._isDisposed) {
455
+ return;
456
+ }
457
+ this._isDisposed = true;
458
+ this._drainDataAndClose();
459
+ };
460
+ ConoutConnection2.prototype.connectSocket = function(socket) {
461
+ socket.connect(conout_1.getWorkerPipeName(this._conoutPipeName));
462
+ };
463
+ ConoutConnection2.prototype._drainDataAndClose = function() {
464
+ var _this = this;
465
+ if (this._drainTimeout) {
466
+ clearTimeout(this._drainTimeout);
467
+ }
468
+ this._drainTimeout = setTimeout(function() {
469
+ return _this._destroySocket();
470
+ }, FLUSH_DATA_INTERVAL);
471
+ };
472
+ ConoutConnection2.prototype._destroySocket = function() {
473
+ return __awaiter(this, void 0, void 0, function() {
474
+ return __generator(this, function(_a) {
475
+ switch (_a.label) {
476
+ case 0:
477
+ return [4, this._worker.terminate()];
478
+ case 1:
479
+ _a.sent();
480
+ return [
481
+ 2
482
+ /*return*/
483
+ ];
484
+ }
485
+ });
486
+ });
487
+ };
488
+ return ConoutConnection2;
489
+ })()
490
+ );
491
+ exports.ConoutConnection = ConoutConnection;
492
+ }
493
+ });
494
+
495
+ // ../../node_modules/.pnpm/node-pty@1.1.0/node_modules/node-pty/lib/windowsPtyAgent.js
496
+ var require_windowsPtyAgent = __commonJS({
497
+ "../../node_modules/.pnpm/node-pty@1.1.0/node_modules/node-pty/lib/windowsPtyAgent.js"(exports) {
498
+ "use strict";
499
+ Object.defineProperty(exports, "__esModule", { value: true });
500
+ exports.argsToCommandLine = exports.WindowsPtyAgent = void 0;
501
+ var fs = __require("fs");
502
+ var os = __require("os");
503
+ var path13 = __require("path");
504
+ var child_process_1 = __require("child_process");
505
+ var net_1 = __require("net");
506
+ var windowsConoutConnection_1 = require_windowsConoutConnection();
507
+ var utils_1 = require_utils();
508
+ var conptyNative;
509
+ var winptyNative;
510
+ var FLUSH_DATA_INTERVAL = 1e3;
511
+ var WindowsPtyAgent = (
512
+ /** @class */
513
+ (function() {
514
+ function WindowsPtyAgent2(file, args, env, cwd, cols, rows, debug, _useConpty, _useConptyDll, conptyInheritCursor) {
515
+ var _this = this;
516
+ if (_useConptyDll === void 0) {
517
+ _useConptyDll = false;
518
+ }
519
+ if (conptyInheritCursor === void 0) {
520
+ conptyInheritCursor = false;
521
+ }
522
+ this._useConpty = _useConpty;
523
+ this._useConptyDll = _useConptyDll;
524
+ this._pid = 0;
525
+ this._innerPid = 0;
526
+ if (this._useConpty === void 0 || this._useConpty === true) {
527
+ this._useConpty = this._getWindowsBuildNumber() >= 18309;
528
+ }
529
+ if (this._useConpty) {
530
+ if (!conptyNative) {
531
+ conptyNative = utils_1.loadNativeModule("conpty").module;
532
+ }
533
+ } else {
534
+ if (!winptyNative) {
535
+ winptyNative = utils_1.loadNativeModule("pty").module;
536
+ }
537
+ }
538
+ this._ptyNative = this._useConpty ? conptyNative : winptyNative;
539
+ cwd = path13.resolve(cwd);
540
+ var commandLine = argsToCommandLine(file, args);
541
+ var term;
542
+ if (this._useConpty) {
543
+ term = this._ptyNative.startProcess(file, cols, rows, debug, this._generatePipeName(), conptyInheritCursor, this._useConptyDll);
544
+ } else {
545
+ term = this._ptyNative.startProcess(file, commandLine, env, cwd, cols, rows, debug);
546
+ this._pid = term.pid;
547
+ this._innerPid = term.innerPid;
548
+ }
549
+ this._fd = term.fd;
550
+ this._pty = term.pty;
551
+ this._outSocket = new net_1.Socket();
552
+ this._outSocket.setEncoding("utf8");
553
+ this._conoutSocketWorker = new windowsConoutConnection_1.ConoutConnection(term.conout, this._useConptyDll);
554
+ this._conoutSocketWorker.onReady(function() {
555
+ _this._conoutSocketWorker.connectSocket(_this._outSocket);
556
+ });
557
+ this._outSocket.on("connect", function() {
558
+ _this._outSocket.emit("ready_datapipe");
559
+ });
560
+ var inSocketFD = fs.openSync(term.conin, "w");
561
+ this._inSocket = new net_1.Socket({
562
+ fd: inSocketFD,
563
+ readable: false,
564
+ writable: true
565
+ });
566
+ this._inSocket.setEncoding("utf8");
567
+ if (this._useConpty) {
568
+ var connect = this._ptyNative.connect(this._pty, commandLine, cwd, env, this._useConptyDll, function(c) {
569
+ return _this._$onProcessExit(c);
570
+ });
571
+ this._innerPid = connect.pid;
572
+ }
573
+ }
574
+ Object.defineProperty(WindowsPtyAgent2.prototype, "inSocket", {
575
+ get: function() {
576
+ return this._inSocket;
577
+ },
578
+ enumerable: false,
579
+ configurable: true
580
+ });
581
+ Object.defineProperty(WindowsPtyAgent2.prototype, "outSocket", {
582
+ get: function() {
583
+ return this._outSocket;
584
+ },
585
+ enumerable: false,
586
+ configurable: true
587
+ });
588
+ Object.defineProperty(WindowsPtyAgent2.prototype, "fd", {
589
+ get: function() {
590
+ return this._fd;
591
+ },
592
+ enumerable: false,
593
+ configurable: true
594
+ });
595
+ Object.defineProperty(WindowsPtyAgent2.prototype, "innerPid", {
596
+ get: function() {
597
+ return this._innerPid;
598
+ },
599
+ enumerable: false,
600
+ configurable: true
601
+ });
602
+ Object.defineProperty(WindowsPtyAgent2.prototype, "pty", {
603
+ get: function() {
604
+ return this._pty;
605
+ },
606
+ enumerable: false,
607
+ configurable: true
608
+ });
609
+ WindowsPtyAgent2.prototype.resize = function(cols, rows) {
610
+ if (this._useConpty) {
611
+ if (this._exitCode !== void 0) {
612
+ throw new Error("Cannot resize a pty that has already exited");
613
+ }
614
+ this._ptyNative.resize(this._pty, cols, rows, this._useConptyDll);
615
+ return;
616
+ }
617
+ this._ptyNative.resize(this._pid, cols, rows);
618
+ };
619
+ WindowsPtyAgent2.prototype.clear = function() {
620
+ if (this._useConpty) {
621
+ this._ptyNative.clear(this._pty, this._useConptyDll);
622
+ }
623
+ };
624
+ WindowsPtyAgent2.prototype.kill = function() {
625
+ var _this = this;
626
+ if (this._useConpty) {
627
+ if (!this._useConptyDll) {
628
+ this._inSocket.readable = false;
629
+ this._outSocket.readable = false;
630
+ this._getConsoleProcessList().then(function(consoleProcessList) {
631
+ consoleProcessList.forEach(function(pid) {
632
+ try {
633
+ process.kill(pid);
634
+ } catch (e) {
635
+ }
636
+ });
637
+ });
638
+ this._ptyNative.kill(this._pty, this._useConptyDll);
639
+ this._conoutSocketWorker.dispose();
640
+ } else {
641
+ this._inSocket.destroy();
642
+ this._ptyNative.kill(this._pty, this._useConptyDll);
643
+ this._outSocket.on("data", function() {
644
+ _this._conoutSocketWorker.dispose();
645
+ });
646
+ }
647
+ } else {
648
+ var processList = this._ptyNative.getProcessList(this._pid);
649
+ this._ptyNative.kill(this._pid, this._innerPid);
650
+ processList.forEach(function(pid) {
651
+ try {
652
+ process.kill(pid);
653
+ } catch (e) {
654
+ }
655
+ });
656
+ }
657
+ };
658
+ WindowsPtyAgent2.prototype._getConsoleProcessList = function() {
659
+ var _this = this;
660
+ return new Promise(function(resolve) {
661
+ var agent = child_process_1.fork(path13.join(__dirname, "conpty_console_list_agent"), [_this._innerPid.toString()]);
662
+ agent.on("message", function(message) {
663
+ clearTimeout(timeout);
664
+ resolve(message.consoleProcessList);
665
+ });
666
+ var timeout = setTimeout(function() {
667
+ agent.kill();
668
+ resolve([_this._innerPid]);
669
+ }, 5e3);
670
+ });
671
+ };
672
+ Object.defineProperty(WindowsPtyAgent2.prototype, "exitCode", {
673
+ get: function() {
674
+ if (this._useConpty) {
675
+ return this._exitCode;
676
+ }
677
+ var winptyExitCode = this._ptyNative.getExitCode(this._innerPid);
678
+ return winptyExitCode === -1 ? void 0 : winptyExitCode;
679
+ },
680
+ enumerable: false,
681
+ configurable: true
682
+ });
683
+ WindowsPtyAgent2.prototype._getWindowsBuildNumber = function() {
684
+ var osVersion = /(\d+)\.(\d+)\.(\d+)/g.exec(os.release());
685
+ var buildNumber = 0;
686
+ if (osVersion && osVersion.length === 4) {
687
+ buildNumber = parseInt(osVersion[3]);
688
+ }
689
+ return buildNumber;
690
+ };
691
+ WindowsPtyAgent2.prototype._generatePipeName = function() {
692
+ return "conpty-" + Math.random() * 1e7;
693
+ };
694
+ WindowsPtyAgent2.prototype._$onProcessExit = function(exitCode) {
695
+ var _this = this;
696
+ this._exitCode = exitCode;
697
+ if (!this._useConptyDll) {
698
+ this._flushDataAndCleanUp();
699
+ this._outSocket.on("data", function() {
700
+ return _this._flushDataAndCleanUp();
701
+ });
702
+ }
703
+ };
704
+ WindowsPtyAgent2.prototype._flushDataAndCleanUp = function() {
705
+ var _this = this;
706
+ if (this._useConptyDll) {
707
+ return;
708
+ }
709
+ if (this._closeTimeout) {
710
+ clearTimeout(this._closeTimeout);
711
+ }
712
+ this._closeTimeout = setTimeout(function() {
713
+ return _this._cleanUpProcess();
714
+ }, FLUSH_DATA_INTERVAL);
715
+ };
716
+ WindowsPtyAgent2.prototype._cleanUpProcess = function() {
717
+ if (this._useConptyDll) {
718
+ return;
719
+ }
720
+ this._inSocket.readable = false;
721
+ this._outSocket.readable = false;
722
+ this._outSocket.destroy();
723
+ };
724
+ return WindowsPtyAgent2;
725
+ })()
726
+ );
727
+ exports.WindowsPtyAgent = WindowsPtyAgent;
728
+ function argsToCommandLine(file, args) {
729
+ if (isCommandLine(args)) {
730
+ if (args.length === 0) {
731
+ return file;
732
+ }
733
+ return argsToCommandLine(file, []) + " " + args;
734
+ }
735
+ var argv = [file];
736
+ Array.prototype.push.apply(argv, args);
737
+ var result = "";
738
+ for (var argIndex = 0; argIndex < argv.length; argIndex++) {
739
+ if (argIndex > 0) {
740
+ result += " ";
741
+ }
742
+ var arg = argv[argIndex];
743
+ var hasLopsidedEnclosingQuote = xOr(arg[0] !== '"', arg[arg.length - 1] !== '"');
744
+ var hasNoEnclosingQuotes = arg[0] !== '"' && arg[arg.length - 1] !== '"';
745
+ var quote = arg === "" || (arg.indexOf(" ") !== -1 || arg.indexOf(" ") !== -1) && (arg.length > 1 && (hasLopsidedEnclosingQuote || hasNoEnclosingQuotes));
746
+ if (quote) {
747
+ result += '"';
748
+ }
749
+ var bsCount = 0;
750
+ for (var i = 0; i < arg.length; i++) {
751
+ var p = arg[i];
752
+ if (p === "\\") {
753
+ bsCount++;
754
+ } else if (p === '"') {
755
+ result += repeatText("\\", bsCount * 2 + 1);
756
+ result += '"';
757
+ bsCount = 0;
758
+ } else {
759
+ result += repeatText("\\", bsCount);
760
+ bsCount = 0;
761
+ result += p;
762
+ }
763
+ }
764
+ if (quote) {
765
+ result += repeatText("\\", bsCount * 2);
766
+ result += '"';
767
+ } else {
768
+ result += repeatText("\\", bsCount);
769
+ }
770
+ }
771
+ return result;
772
+ }
773
+ exports.argsToCommandLine = argsToCommandLine;
774
+ function isCommandLine(args) {
775
+ return typeof args === "string";
776
+ }
777
+ function repeatText(text, count) {
778
+ var result = "";
779
+ for (var i = 0; i < count; i++) {
780
+ result += text;
781
+ }
782
+ return result;
783
+ }
784
+ function xOr(arg1, arg2) {
785
+ return arg1 && !arg2 || !arg1 && arg2;
786
+ }
787
+ }
788
+ });
789
+
790
+ // ../../node_modules/.pnpm/node-pty@1.1.0/node_modules/node-pty/lib/windowsTerminal.js
791
+ var require_windowsTerminal = __commonJS({
792
+ "../../node_modules/.pnpm/node-pty@1.1.0/node_modules/node-pty/lib/windowsTerminal.js"(exports) {
793
+ "use strict";
794
+ var __extends = exports && exports.__extends || /* @__PURE__ */ (function() {
795
+ var extendStatics = function(d, b) {
796
+ extendStatics = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(d2, b2) {
797
+ d2.__proto__ = b2;
798
+ } || function(d2, b2) {
799
+ for (var p in b2) if (b2.hasOwnProperty(p)) d2[p] = b2[p];
800
+ };
801
+ return extendStatics(d, b);
802
+ };
803
+ return function(d, b) {
804
+ extendStatics(d, b);
805
+ function __() {
806
+ this.constructor = d;
807
+ }
808
+ d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
809
+ };
810
+ })();
811
+ Object.defineProperty(exports, "__esModule", { value: true });
812
+ exports.WindowsTerminal = void 0;
813
+ var terminal_1 = require_terminal();
814
+ var windowsPtyAgent_1 = require_windowsPtyAgent();
815
+ var utils_1 = require_utils();
816
+ var DEFAULT_FILE = "cmd.exe";
817
+ var DEFAULT_NAME = "Windows Shell";
818
+ var WindowsTerminal = (
819
+ /** @class */
820
+ (function(_super) {
821
+ __extends(WindowsTerminal2, _super);
822
+ function WindowsTerminal2(file, args, opt) {
823
+ var _this = _super.call(this, opt) || this;
824
+ _this._checkType("args", args, "string", true);
825
+ args = args || [];
826
+ file = file || DEFAULT_FILE;
827
+ opt = opt || {};
828
+ opt.env = opt.env || process.env;
829
+ if (opt.encoding) {
830
+ console.warn("Setting encoding on Windows is not supported");
831
+ }
832
+ var env = utils_1.assign({}, opt.env);
833
+ _this._cols = opt.cols || terminal_1.DEFAULT_COLS;
834
+ _this._rows = opt.rows || terminal_1.DEFAULT_ROWS;
835
+ var cwd = opt.cwd || process.cwd();
836
+ var name = opt.name || env.TERM || DEFAULT_NAME;
837
+ var parsedEnv = _this._parseEnv(env);
838
+ _this._isReady = false;
839
+ _this._deferreds = [];
840
+ _this._agent = new windowsPtyAgent_1.WindowsPtyAgent(file, args, parsedEnv, cwd, _this._cols, _this._rows, false, opt.useConpty, opt.useConptyDll, opt.conptyInheritCursor);
841
+ _this._socket = _this._agent.outSocket;
842
+ _this._pid = _this._agent.innerPid;
843
+ _this._fd = _this._agent.fd;
844
+ _this._pty = _this._agent.pty;
845
+ _this._socket.on("ready_datapipe", function() {
846
+ _this._socket.once("data", function() {
847
+ if (!_this._isReady) {
848
+ _this._isReady = true;
849
+ _this._deferreds.forEach(function(fn) {
850
+ fn.run();
851
+ });
852
+ _this._deferreds = [];
853
+ }
854
+ });
855
+ _this._socket.on("error", function(err) {
856
+ _this._close();
857
+ if (err.code) {
858
+ if (~err.code.indexOf("errno 5") || ~err.code.indexOf("EIO"))
859
+ return;
860
+ }
861
+ if (_this.listeners("error").length < 2) {
862
+ throw err;
863
+ }
864
+ });
865
+ _this._socket.on("close", function() {
866
+ _this.emit("exit", _this._agent.exitCode);
867
+ _this._close();
868
+ });
869
+ });
870
+ _this._file = file;
871
+ _this._name = name;
872
+ _this._readable = true;
873
+ _this._writable = true;
874
+ _this._forwardEvents();
875
+ return _this;
876
+ }
877
+ WindowsTerminal2.prototype._write = function(data) {
878
+ this._defer(this._doWrite, data);
879
+ };
880
+ WindowsTerminal2.prototype._doWrite = function(data) {
881
+ this._agent.inSocket.write(data);
882
+ };
883
+ WindowsTerminal2.open = function(options) {
884
+ throw new Error("open() not supported on windows, use Fork() instead.");
885
+ };
886
+ WindowsTerminal2.prototype.resize = function(cols, rows) {
887
+ var _this = this;
888
+ if (cols <= 0 || rows <= 0 || isNaN(cols) || isNaN(rows) || cols === Infinity || rows === Infinity) {
889
+ throw new Error("resizing must be done using positive cols and rows");
890
+ }
891
+ this._deferNoArgs(function() {
892
+ _this._agent.resize(cols, rows);
893
+ _this._cols = cols;
894
+ _this._rows = rows;
895
+ });
896
+ };
897
+ WindowsTerminal2.prototype.clear = function() {
898
+ var _this = this;
899
+ this._deferNoArgs(function() {
900
+ _this._agent.clear();
901
+ });
902
+ };
903
+ WindowsTerminal2.prototype.destroy = function() {
904
+ var _this = this;
905
+ this._deferNoArgs(function() {
906
+ _this.kill();
907
+ });
908
+ };
909
+ WindowsTerminal2.prototype.kill = function(signal) {
910
+ var _this = this;
911
+ this._deferNoArgs(function() {
912
+ if (signal) {
913
+ throw new Error("Signals not supported on windows.");
914
+ }
915
+ _this._close();
916
+ _this._agent.kill();
917
+ });
918
+ };
919
+ WindowsTerminal2.prototype._deferNoArgs = function(deferredFn) {
920
+ var _this = this;
921
+ if (this._isReady) {
922
+ deferredFn.call(this);
923
+ return;
924
+ }
925
+ this._deferreds.push({
926
+ run: function() {
927
+ return deferredFn.call(_this);
928
+ }
929
+ });
930
+ };
931
+ WindowsTerminal2.prototype._defer = function(deferredFn, arg) {
932
+ var _this = this;
933
+ if (this._isReady) {
934
+ deferredFn.call(this, arg);
935
+ return;
936
+ }
937
+ this._deferreds.push({
938
+ run: function() {
939
+ return deferredFn.call(_this, arg);
940
+ }
941
+ });
942
+ };
943
+ Object.defineProperty(WindowsTerminal2.prototype, "process", {
944
+ get: function() {
945
+ return this._name;
946
+ },
947
+ enumerable: false,
948
+ configurable: true
949
+ });
950
+ Object.defineProperty(WindowsTerminal2.prototype, "master", {
951
+ get: function() {
952
+ throw new Error("master is not supported on Windows");
953
+ },
954
+ enumerable: false,
955
+ configurable: true
956
+ });
957
+ Object.defineProperty(WindowsTerminal2.prototype, "slave", {
958
+ get: function() {
959
+ throw new Error("slave is not supported on Windows");
960
+ },
961
+ enumerable: false,
962
+ configurable: true
963
+ });
964
+ return WindowsTerminal2;
965
+ })(terminal_1.Terminal)
966
+ );
967
+ exports.WindowsTerminal = WindowsTerminal;
968
+ }
969
+ });
970
+
971
+ // ../../node_modules/.pnpm/node-pty@1.1.0/node_modules/node-pty/lib/unixTerminal.js
972
+ var require_unixTerminal = __commonJS({
973
+ "../../node_modules/.pnpm/node-pty@1.1.0/node_modules/node-pty/lib/unixTerminal.js"(exports) {
974
+ "use strict";
975
+ var __extends = exports && exports.__extends || /* @__PURE__ */ (function() {
976
+ var extendStatics = function(d, b) {
977
+ extendStatics = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(d2, b2) {
978
+ d2.__proto__ = b2;
979
+ } || function(d2, b2) {
980
+ for (var p in b2) if (b2.hasOwnProperty(p)) d2[p] = b2[p];
981
+ };
982
+ return extendStatics(d, b);
983
+ };
984
+ return function(d, b) {
985
+ extendStatics(d, b);
986
+ function __() {
987
+ this.constructor = d;
988
+ }
989
+ d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
990
+ };
991
+ })();
992
+ Object.defineProperty(exports, "__esModule", { value: true });
993
+ exports.UnixTerminal = void 0;
994
+ var fs = __require("fs");
995
+ var path13 = __require("path");
996
+ var tty = __require("tty");
997
+ var terminal_1 = require_terminal();
998
+ var utils_1 = require_utils();
999
+ var native = utils_1.loadNativeModule("pty");
1000
+ var pty = native.module;
1001
+ var helperPath = native.dir + "/spawn-helper";
1002
+ helperPath = path13.resolve(__dirname, helperPath);
1003
+ helperPath = helperPath.replace("app.asar", "app.asar.unpacked");
1004
+ helperPath = helperPath.replace("node_modules.asar", "node_modules.asar.unpacked");
1005
+ var DEFAULT_FILE = "sh";
1006
+ var DEFAULT_NAME = "xterm";
1007
+ var DESTROY_SOCKET_TIMEOUT_MS = 200;
1008
+ var UnixTerminal = (
1009
+ /** @class */
1010
+ (function(_super) {
1011
+ __extends(UnixTerminal2, _super);
1012
+ function UnixTerminal2(file, args, opt) {
1013
+ var _a, _b;
1014
+ var _this = _super.call(this, opt) || this;
1015
+ _this._boundClose = false;
1016
+ _this._emittedClose = false;
1017
+ if (typeof args === "string") {
1018
+ throw new Error("args as a string is not supported on unix.");
1019
+ }
1020
+ args = args || [];
1021
+ file = file || DEFAULT_FILE;
1022
+ opt = opt || {};
1023
+ opt.env = opt.env || process.env;
1024
+ _this._cols = opt.cols || terminal_1.DEFAULT_COLS;
1025
+ _this._rows = opt.rows || terminal_1.DEFAULT_ROWS;
1026
+ var uid = (_a = opt.uid) !== null && _a !== void 0 ? _a : -1;
1027
+ var gid = (_b = opt.gid) !== null && _b !== void 0 ? _b : -1;
1028
+ var env = utils_1.assign({}, opt.env);
1029
+ if (opt.env === process.env) {
1030
+ _this._sanitizeEnv(env);
1031
+ }
1032
+ var cwd = opt.cwd || process.cwd();
1033
+ env.PWD = cwd;
1034
+ var name = opt.name || env.TERM || DEFAULT_NAME;
1035
+ env.TERM = name;
1036
+ var parsedEnv = _this._parseEnv(env);
1037
+ var encoding = opt.encoding === void 0 ? "utf8" : opt.encoding;
1038
+ var onexit = function(code, signal) {
1039
+ if (!_this._emittedClose) {
1040
+ if (_this._boundClose) {
1041
+ return;
1042
+ }
1043
+ _this._boundClose = true;
1044
+ var timeout_1 = setTimeout(function() {
1045
+ timeout_1 = null;
1046
+ _this._socket.destroy();
1047
+ }, DESTROY_SOCKET_TIMEOUT_MS);
1048
+ _this.once("close", function() {
1049
+ if (timeout_1 !== null) {
1050
+ clearTimeout(timeout_1);
1051
+ }
1052
+ _this.emit("exit", code, signal);
1053
+ });
1054
+ return;
1055
+ }
1056
+ _this.emit("exit", code, signal);
1057
+ };
1058
+ var term = pty.fork(file, args, parsedEnv, cwd, _this._cols, _this._rows, uid, gid, encoding === "utf8", helperPath, onexit);
1059
+ _this._socket = new tty.ReadStream(term.fd);
1060
+ if (encoding !== null) {
1061
+ _this._socket.setEncoding(encoding);
1062
+ }
1063
+ _this._writeStream = new CustomWriteStream(term.fd, encoding || void 0);
1064
+ _this._socket.on("error", function(err) {
1065
+ if (err.code) {
1066
+ if (~err.code.indexOf("EAGAIN")) {
1067
+ return;
1068
+ }
1069
+ }
1070
+ _this._close();
1071
+ if (!_this._emittedClose) {
1072
+ _this._emittedClose = true;
1073
+ _this.emit("close");
1074
+ }
1075
+ if (err.code) {
1076
+ if (~err.code.indexOf("errno 5") || ~err.code.indexOf("EIO")) {
1077
+ return;
1078
+ }
1079
+ }
1080
+ if (_this.listeners("error").length < 2) {
1081
+ throw err;
1082
+ }
1083
+ });
1084
+ _this._pid = term.pid;
1085
+ _this._fd = term.fd;
1086
+ _this._pty = term.pty;
1087
+ _this._file = file;
1088
+ _this._name = name;
1089
+ _this._readable = true;
1090
+ _this._writable = true;
1091
+ _this._socket.on("close", function() {
1092
+ if (_this._emittedClose) {
1093
+ return;
1094
+ }
1095
+ _this._emittedClose = true;
1096
+ _this._close();
1097
+ _this.emit("close");
1098
+ });
1099
+ _this._forwardEvents();
1100
+ return _this;
1101
+ }
1102
+ Object.defineProperty(UnixTerminal2.prototype, "master", {
1103
+ get: function() {
1104
+ return this._master;
1105
+ },
1106
+ enumerable: false,
1107
+ configurable: true
1108
+ });
1109
+ Object.defineProperty(UnixTerminal2.prototype, "slave", {
1110
+ get: function() {
1111
+ return this._slave;
1112
+ },
1113
+ enumerable: false,
1114
+ configurable: true
1115
+ });
1116
+ UnixTerminal2.prototype._write = function(data) {
1117
+ this._writeStream.write(data);
1118
+ };
1119
+ Object.defineProperty(UnixTerminal2.prototype, "fd", {
1120
+ /* Accessors */
1121
+ get: function() {
1122
+ return this._fd;
1123
+ },
1124
+ enumerable: false,
1125
+ configurable: true
1126
+ });
1127
+ Object.defineProperty(UnixTerminal2.prototype, "ptsName", {
1128
+ get: function() {
1129
+ return this._pty;
1130
+ },
1131
+ enumerable: false,
1132
+ configurable: true
1133
+ });
1134
+ UnixTerminal2.open = function(opt) {
1135
+ var self = Object.create(UnixTerminal2.prototype);
1136
+ opt = opt || {};
1137
+ if (arguments.length > 1) {
1138
+ opt = {
1139
+ cols: arguments[1],
1140
+ rows: arguments[2]
1141
+ };
1142
+ }
1143
+ var cols = opt.cols || terminal_1.DEFAULT_COLS;
1144
+ var rows = opt.rows || terminal_1.DEFAULT_ROWS;
1145
+ var encoding = opt.encoding === void 0 ? "utf8" : opt.encoding;
1146
+ var term = pty.open(cols, rows);
1147
+ self._master = new tty.ReadStream(term.master);
1148
+ if (encoding !== null) {
1149
+ self._master.setEncoding(encoding);
1150
+ }
1151
+ self._master.resume();
1152
+ self._slave = new tty.ReadStream(term.slave);
1153
+ if (encoding !== null) {
1154
+ self._slave.setEncoding(encoding);
1155
+ }
1156
+ self._slave.resume();
1157
+ self._socket = self._master;
1158
+ self._pid = -1;
1159
+ self._fd = term.master;
1160
+ self._pty = term.pty;
1161
+ self._file = process.argv[0] || "node";
1162
+ self._name = process.env.TERM || "";
1163
+ self._readable = true;
1164
+ self._writable = true;
1165
+ self._socket.on("error", function(err) {
1166
+ self._close();
1167
+ if (self.listeners("error").length < 2) {
1168
+ throw err;
1169
+ }
1170
+ });
1171
+ self._socket.on("close", function() {
1172
+ self._close();
1173
+ });
1174
+ return self;
1175
+ };
1176
+ UnixTerminal2.prototype.destroy = function() {
1177
+ var _this = this;
1178
+ this._close();
1179
+ this._socket.once("close", function() {
1180
+ _this.kill("SIGHUP");
1181
+ });
1182
+ this._socket.destroy();
1183
+ this._writeStream.dispose();
1184
+ };
1185
+ UnixTerminal2.prototype.kill = function(signal) {
1186
+ try {
1187
+ process.kill(this.pid, signal || "SIGHUP");
1188
+ } catch (e) {
1189
+ }
1190
+ };
1191
+ Object.defineProperty(UnixTerminal2.prototype, "process", {
1192
+ /**
1193
+ * Gets the name of the process.
1194
+ */
1195
+ get: function() {
1196
+ if (process.platform === "darwin") {
1197
+ var title = pty.process(this._fd);
1198
+ return title !== "kernel_task" ? title : this._file;
1199
+ }
1200
+ return pty.process(this._fd, this._pty) || this._file;
1201
+ },
1202
+ enumerable: false,
1203
+ configurable: true
1204
+ });
1205
+ UnixTerminal2.prototype.resize = function(cols, rows) {
1206
+ if (cols <= 0 || rows <= 0 || isNaN(cols) || isNaN(rows) || cols === Infinity || rows === Infinity) {
1207
+ throw new Error("resizing must be done using positive cols and rows");
1208
+ }
1209
+ pty.resize(this._fd, cols, rows);
1210
+ this._cols = cols;
1211
+ this._rows = rows;
1212
+ };
1213
+ UnixTerminal2.prototype.clear = function() {
1214
+ };
1215
+ UnixTerminal2.prototype._sanitizeEnv = function(env) {
1216
+ delete env["TMUX"];
1217
+ delete env["TMUX_PANE"];
1218
+ delete env["STY"];
1219
+ delete env["WINDOW"];
1220
+ delete env["WINDOWID"];
1221
+ delete env["TERMCAP"];
1222
+ delete env["COLUMNS"];
1223
+ delete env["LINES"];
1224
+ };
1225
+ return UnixTerminal2;
1226
+ })(terminal_1.Terminal)
1227
+ );
1228
+ exports.UnixTerminal = UnixTerminal;
1229
+ var CustomWriteStream = (
1230
+ /** @class */
1231
+ (function() {
1232
+ function CustomWriteStream2(_fd, _encoding) {
1233
+ this._fd = _fd;
1234
+ this._encoding = _encoding;
1235
+ this._writeQueue = [];
1236
+ }
1237
+ CustomWriteStream2.prototype.dispose = function() {
1238
+ clearImmediate(this._writeImmediate);
1239
+ this._writeImmediate = void 0;
1240
+ };
1241
+ CustomWriteStream2.prototype.write = function(data) {
1242
+ var buffer = typeof data === "string" ? Buffer.from(data, this._encoding) : Buffer.from(data);
1243
+ if (buffer.byteLength !== 0) {
1244
+ this._writeQueue.push({ buffer, offset: 0 });
1245
+ if (this._writeQueue.length === 1) {
1246
+ this._processWriteQueue();
1247
+ }
1248
+ }
1249
+ };
1250
+ CustomWriteStream2.prototype._processWriteQueue = function() {
1251
+ var _this = this;
1252
+ this._writeImmediate = void 0;
1253
+ if (this._writeQueue.length === 0) {
1254
+ return;
1255
+ }
1256
+ var task = this._writeQueue[0];
1257
+ fs.write(this._fd, task.buffer, task.offset, function(err, written) {
1258
+ if (err) {
1259
+ if ("code" in err && err.code === "EAGAIN") {
1260
+ _this._writeImmediate = setImmediate(function() {
1261
+ return _this._processWriteQueue();
1262
+ });
1263
+ } else {
1264
+ _this._writeQueue.length = 0;
1265
+ console.error("Unhandled pty write error", err);
1266
+ }
1267
+ return;
1268
+ }
1269
+ task.offset += written;
1270
+ if (task.offset >= task.buffer.byteLength) {
1271
+ _this._writeQueue.shift();
1272
+ }
1273
+ _this._processWriteQueue();
1274
+ });
1275
+ };
1276
+ return CustomWriteStream2;
1277
+ })()
1278
+ );
1279
+ }
1280
+ });
1281
+
1282
+ // ../../node_modules/.pnpm/node-pty@1.1.0/node_modules/node-pty/lib/index.js
1283
+ var require_lib = __commonJS({
1284
+ "../../node_modules/.pnpm/node-pty@1.1.0/node_modules/node-pty/lib/index.js"(exports) {
1285
+ "use strict";
1286
+ Object.defineProperty(exports, "__esModule", { value: true });
1287
+ exports.native = exports.open = exports.createTerminal = exports.fork = exports.spawn = void 0;
1288
+ var utils_1 = require_utils();
1289
+ var terminalCtor;
1290
+ if (process.platform === "win32") {
1291
+ terminalCtor = require_windowsTerminal().WindowsTerminal;
1292
+ } else {
1293
+ terminalCtor = require_unixTerminal().UnixTerminal;
1294
+ }
1295
+ function spawn2(file, args, opt) {
1296
+ return new terminalCtor(file, args, opt);
1297
+ }
1298
+ exports.spawn = spawn2;
1299
+ function fork(file, args, opt) {
1300
+ return new terminalCtor(file, args, opt);
1301
+ }
1302
+ exports.fork = fork;
1303
+ function createTerminal(file, args, opt) {
1304
+ return new terminalCtor(file, args, opt);
1305
+ }
1306
+ exports.createTerminal = createTerminal;
1307
+ function open(options) {
1308
+ return terminalCtor.open(options);
1309
+ }
1310
+ exports.open = open;
1311
+ exports.native = process.platform !== "win32" ? utils_1.loadNativeModule("pty").module : null;
1312
+ }
1313
+ });
1314
+
1315
+ // src/actions/audit/installPlugin.ts
1316
+ import {
1317
+ existsSync,
1318
+ mkdirSync,
1319
+ readFileSync,
1320
+ writeFileSync
1321
+ } from "fs";
1322
+ import { homedir } from "os";
1323
+ import path from "path";
1324
+ import chalk from "chalk";
1325
+ function findMonorepoRoot(startDir) {
1326
+ let dir = startDir;
1327
+ while (dir !== path.dirname(dir)) {
1328
+ if (existsSync(path.join(dir, "pnpm-workspace.yaml"))) return dir;
1329
+ dir = path.dirname(dir);
1330
+ }
1331
+ return void 0;
1332
+ }
1333
+ function getRepoRoot() {
1334
+ const root = findMonorepoRoot(process.cwd());
1335
+ if (!root) throw new Error("Could not find monorepo root (pnpm-workspace.yaml)");
1336
+ return root;
1337
+ }
1338
+ function resolveClaudeHooksDist() {
1339
+ return path.join(getRepoRoot(), "packages", "audit-plugin", "dist", "hooks");
1340
+ }
1341
+ function getClaudeSettingsPath() {
1342
+ return path.join(homedir(), ".claude", "settings.json");
1343
+ }
1344
+ function readClaudeSettings() {
1345
+ const settingsPath = getClaudeSettingsPath();
1346
+ if (!existsSync(settingsPath)) return {};
1347
+ const raw = readFileSync(settingsPath, "utf8");
1348
+ return JSON.parse(raw);
1349
+ }
1350
+ function writeClaudeSettings(settings) {
1351
+ const settingsPath = getClaudeSettingsPath();
1352
+ mkdirSync(path.dirname(settingsPath), { recursive: true });
1353
+ writeFileSync(settingsPath, JSON.stringify(settings, null, 2) + "\n", "utf8");
1354
+ }
1355
+ function buildClaudeHooks(hooksDir) {
1356
+ return {
1357
+ SessionStart: [
1358
+ {
1359
+ matcher: "",
1360
+ hooks: [{
1361
+ type: "command",
1362
+ command: `node ${hooksDir}/session-start.mjs`,
1363
+ timeout: 5
1364
+ }]
1365
+ }
1366
+ ],
1367
+ UserPromptSubmit: [
1368
+ {
1369
+ matcher: "",
1370
+ hooks: [{
1371
+ type: "command",
1372
+ command: `node ${hooksDir}/user-prompt-submit.mjs`,
1373
+ timeout: 5
1374
+ }]
1375
+ }
1376
+ ],
1377
+ PostToolUse: [
1378
+ {
1379
+ matcher: "",
1380
+ hooks: [{
1381
+ type: "command",
1382
+ command: `node ${hooksDir}/post-tool-use.mjs`,
1383
+ timeout: 5
1384
+ }]
1385
+ }
1386
+ ],
1387
+ Stop: [
1388
+ {
1389
+ matcher: "",
1390
+ hooks: [{
1391
+ type: "command",
1392
+ command: `node ${hooksDir}/stop.mjs`,
1393
+ timeout: 5
1394
+ }]
1395
+ }
1396
+ ]
1397
+ };
1398
+ }
1399
+ function getCodexConfigPath() {
1400
+ return path.join(homedir(), ".codex", "config.toml");
1401
+ }
1402
+ function getCodexHooksPath() {
1403
+ return path.join(getRepoRoot(), ".codex", "hooks.json");
1404
+ }
1405
+ function readCodexConfig() {
1406
+ const configPath = getCodexConfigPath();
1407
+ if (!existsSync(configPath)) return "";
1408
+ return readFileSync(configPath, "utf8");
1409
+ }
1410
+ function writeCodexConfig(config) {
1411
+ const configPath = getCodexConfigPath();
1412
+ mkdirSync(path.dirname(configPath), { recursive: true });
1413
+ writeFileSync(configPath, config, "utf8");
1414
+ }
1415
+ function enableCodexHooksFeature() {
1416
+ const config = readCodexConfig();
1417
+ const lines = config === "" ? [] : config.split("\n");
1418
+ const featuresIndex = lines.findIndex((line) => line.trim() === "[features]");
1419
+ if (featuresIndex === -1) {
1420
+ const separator = config === "" || config.endsWith("\n\n") || config.endsWith("\n") ? "" : "\n";
1421
+ writeCodexConfig(config + separator + "[features]\ncodex_hooks = true\n");
1422
+ return;
1423
+ }
1424
+ const sectionEnd = lines.findIndex(
1425
+ (line, index) => index > featuresIndex && /^\s*\[.*\]\s*$/.test(line)
1426
+ );
1427
+ const endIndex = sectionEnd === -1 ? lines.length : sectionEnd;
1428
+ const codexHooksIndex = lines.findIndex(
1429
+ (line, index) => index > featuresIndex && index < endIndex && /^\s*codex_hooks\s*=/.test(line)
1430
+ );
1431
+ if (codexHooksIndex === -1) {
1432
+ lines.splice(endIndex, 0, "codex_hooks = true");
1433
+ } else {
1434
+ lines[codexHooksIndex] = "codex_hooks = true";
1435
+ }
1436
+ writeCodexConfig(lines.join("\n"));
1437
+ }
1438
+ function readCodexHooks() {
1439
+ const hooksPath = getCodexHooksPath();
1440
+ if (!existsSync(hooksPath)) return {};
1441
+ return JSON.parse(readFileSync(hooksPath, "utf8"));
1442
+ }
1443
+ function writeCodexHooks(config) {
1444
+ const hooksPath = getCodexHooksPath();
1445
+ mkdirSync(path.dirname(hooksPath), { recursive: true });
1446
+ writeFileSync(hooksPath, JSON.stringify(config, null, 2) + "\n", "utf8");
1447
+ }
1448
+ function buildCodexHookCommand(eventName) {
1449
+ const recorderPath = path.join(getRepoRoot(), "packages", "audit-plugin", "dist", "codex", "record-event.mjs");
1450
+ return `node "${recorderPath}" ${eventName}`;
1451
+ }
1452
+ function buildCodexHooks() {
1453
+ return {
1454
+ PostToolUse: [
1455
+ {
1456
+ hooks: [
1457
+ {
1458
+ command: buildCodexHookCommand("PostToolUse"),
1459
+ statusMessage: "Recording Codex audit entry",
1460
+ type: "command"
1461
+ }
1462
+ ],
1463
+ matcher: "Bash"
1464
+ }
1465
+ ],
1466
+ SessionStart: [
1467
+ {
1468
+ hooks: [
1469
+ {
1470
+ command: buildCodexHookCommand("SessionStart"),
1471
+ statusMessage: "Recording Codex audit entry",
1472
+ type: "command"
1473
+ }
1474
+ ],
1475
+ matcher: "startup|resume"
1476
+ }
1477
+ ],
1478
+ Stop: [
1479
+ {
1480
+ hooks: [
1481
+ {
1482
+ command: buildCodexHookCommand("Stop"),
1483
+ statusMessage: "Recording Codex audit entry",
1484
+ type: "command"
1485
+ }
1486
+ ]
1487
+ }
1488
+ ],
1489
+ UserPromptSubmit: [
1490
+ {
1491
+ hooks: [
1492
+ {
1493
+ command: buildCodexHookCommand("UserPromptSubmit"),
1494
+ statusMessage: "Recording Codex audit entry",
1495
+ type: "command"
1496
+ }
1497
+ ]
1498
+ }
1499
+ ]
1500
+ };
1501
+ }
1502
+ function isManagedCodexHook(hook) {
1503
+ return hook.command.includes(path.join("packages", "audit-plugin", "dist", "codex", "record-event.mjs"));
1504
+ }
1505
+ function mergeCodexHooks(existing) {
1506
+ const mergedHooks = existing.hooks ? { ...existing.hooks } : {};
1507
+ const managedHooks = buildCodexHooks();
1508
+ for (const [eventName, groups] of Object.entries(managedHooks)) {
1509
+ const remaining = (mergedHooks[eventName] ?? []).map((group) => ({
1510
+ ...group,
1511
+ hooks: group.hooks.filter((hook) => !isManagedCodexHook(hook))
1512
+ })).filter((group) => group.hooks.length > 0);
1513
+ mergedHooks[eventName] = [...remaining, ...groups];
1514
+ }
1515
+ return { hooks: mergedHooks };
1516
+ }
1517
+ function removeManagedCodexHooks(existing) {
1518
+ const nextHooks = {};
1519
+ for (const [eventName, groups] of Object.entries(existing.hooks ?? {})) {
1520
+ const remaining = groups.map((group) => ({
1521
+ ...group,
1522
+ hooks: group.hooks.filter((hook) => !isManagedCodexHook(hook))
1523
+ })).filter((group) => group.hooks.length > 0);
1524
+ if (remaining.length > 0) {
1525
+ nextHooks[eventName] = remaining;
1526
+ }
1527
+ }
1528
+ return Object.keys(nextHooks).length > 0 ? { hooks: nextHooks } : {};
1529
+ }
1530
+ function installClaudePlugin() {
1531
+ const hooksDir = resolveClaudeHooksDist();
1532
+ if (!existsSync(hooksDir)) {
1533
+ console.log(chalk.red(`Hook scripts not found: ${hooksDir}`));
1534
+ console.log(chalk.gray("Make sure @xylabs/aries-audit-plugin is built (pnpm xy build)."));
1535
+ return;
1536
+ }
1537
+ const settings = readClaudeSettings();
1538
+ settings.hooks = buildClaudeHooks(hooksDir);
1539
+ writeClaudeSettings(settings);
1540
+ console.log(chalk.green("Claude audit hooks installed into ~/.claude/settings.json"));
1541
+ console.log(` ${chalk.gray("Hook scripts:")} ${hooksDir}`);
1542
+ console.log(chalk.yellow("\nRestart Claude Code for the hooks to take effect."));
1543
+ }
1544
+ function uninstallClaudePlugin() {
1545
+ const settings = readClaudeSettings();
1546
+ if (!settings.hooks) {
1547
+ console.log(chalk.yellow("No Claude hooks configured in ~/.claude/settings.json"));
1548
+ return;
1549
+ }
1550
+ delete settings.hooks;
1551
+ writeClaudeSettings(settings);
1552
+ console.log(chalk.green("Claude audit hooks removed from ~/.claude/settings.json"));
1553
+ console.log(chalk.yellow("Restart Claude Code for the change to take effect."));
1554
+ }
1555
+ function installCodexPlugin() {
1556
+ const recorderPath = path.join(getRepoRoot(), "packages", "audit-plugin", "dist", "codex", "record-event.mjs");
1557
+ if (!existsSync(recorderPath)) {
1558
+ console.log(chalk.red(`Codex recorder not found: ${recorderPath}`));
1559
+ console.log(chalk.gray("Make sure @xylabs/aries-audit-plugin is built (pnpm xy build)."));
1560
+ return;
1561
+ }
1562
+ enableCodexHooksFeature();
1563
+ const hooks = mergeCodexHooks(readCodexHooks());
1564
+ writeCodexHooks(hooks);
1565
+ console.log(chalk.green("Codex audit hooks installed"));
1566
+ console.log(` ${chalk.gray("Hooks file:")} ${getCodexHooksPath()}`);
1567
+ console.log(` ${chalk.gray("Config file:")} ${getCodexConfigPath()}`);
1568
+ console.log(chalk.yellow("\nRestart Codex CLI in this repo for the hooks to take effect."));
1569
+ }
1570
+ function uninstallCodexPlugin() {
1571
+ const hooksPath = getCodexHooksPath();
1572
+ if (!existsSync(hooksPath)) {
1573
+ console.log(chalk.yellow("No repo-local Codex hooks file found to update."));
1574
+ return;
1575
+ }
1576
+ const hooks = removeManagedCodexHooks(readCodexHooks());
1577
+ writeCodexHooks(hooks);
1578
+ console.log(chalk.green("Codex audit hooks removed from repo-local hooks.json"));
1579
+ console.log(` ${chalk.gray("Hooks file:")} ${hooksPath}`);
1580
+ console.log(chalk.gray("Leaving features.codex_hooks enabled in ~/.codex/config.toml to avoid disabling unrelated hooks."));
1581
+ }
1582
+ function installPlugin(provider) {
1583
+ if (!provider) {
1584
+ installClaudePlugin();
1585
+ console.log();
1586
+ installCodexPlugin();
1587
+ return;
1588
+ }
1589
+ if (provider === "claude") {
1590
+ installClaudePlugin();
1591
+ return;
1592
+ }
1593
+ installCodexPlugin();
1594
+ }
1595
+ function uninstallPlugin(provider) {
1596
+ if (!provider) {
1597
+ uninstallClaudePlugin();
1598
+ console.log();
1599
+ uninstallCodexPlugin();
1600
+ return;
1601
+ }
1602
+ if (provider === "claude") {
1603
+ uninstallClaudePlugin();
1604
+ return;
1605
+ }
1606
+ uninstallCodexPlugin();
1607
+ }
1608
+
1609
+ // src/actions/audit/listSessions.ts
1610
+ import {
1611
+ existsSync as existsSync2,
1612
+ readdirSync,
1613
+ readFileSync as readFileSync2
1614
+ } from "fs";
1615
+ import path3 from "path";
1616
+ import chalk2 from "chalk";
1617
+
1618
+ // src/actions/audit/auditPaths.ts
1619
+ import { homedir as homedir2 } from "os";
1620
+ import path2 from "path";
1621
+ function getAuditRootDir() {
1622
+ return path2.join(homedir2(), ".aries", "audit-logs");
1623
+ }
1624
+ function getAuditDir(provider) {
1625
+ return provider ? path2.join(getAuditRootDir(), provider) : getAuditRootDir();
1626
+ }
1627
+ function getAuditSearchDirs() {
1628
+ return [
1629
+ getAuditDir("claude"),
1630
+ getAuditDir("codex"),
1631
+ getAuditRootDir()
1632
+ ];
1633
+ }
1634
+
1635
+ // src/actions/audit/listSessions.ts
1636
+ function summarizeSession(filePath, date) {
1637
+ const content = readFileSync2(filePath, "utf8").trim();
1638
+ if (!content) return void 0;
1639
+ const lines = content.split("\n");
1640
+ const events = {};
1641
+ let firstTimestamp = "";
1642
+ let lastTimestamp = "";
1643
+ let sessionId = "unknown";
1644
+ for (const line of lines) {
1645
+ try {
1646
+ const entry = JSON.parse(line);
1647
+ if (!firstTimestamp) firstTimestamp = entry.timestamp ?? "";
1648
+ lastTimestamp = entry.timestamp ?? "";
1649
+ sessionId = entry.sessionId ?? sessionId;
1650
+ const eventName = entry.event ?? "unknown";
1651
+ events[eventName] = (events[eventName] ?? 0) + 1;
1652
+ } catch {
1653
+ }
1654
+ }
1655
+ return {
1656
+ date,
1657
+ entryCount: lines.length,
1658
+ events,
1659
+ firstTimestamp,
1660
+ lastTimestamp,
1661
+ sessionId
1662
+ };
1663
+ }
1664
+ function listSessions(date) {
1665
+ const auditDirs = getAuditSearchDirs().filter((dir) => existsSync2(dir));
1666
+ if (auditDirs.length === 0) {
1667
+ console.log(chalk2.yellow("No audit logs found."));
1668
+ return;
1669
+ }
1670
+ const dates = date ? [date] : [...new Set(
1671
+ auditDirs.flatMap((auditDir) => readdirSync(auditDir).filter((d) => /^\d{4}-\d{2}-\d{2}$/.test(d)))
1672
+ )].toSorted((a, b) => a.localeCompare(b)).toReversed();
1673
+ let found = false;
1674
+ for (const d of dates) {
1675
+ const files = auditDirs.flatMap((auditDir) => {
1676
+ const dayDir = path3.join(auditDir, d);
1677
+ if (!existsSync2(dayDir)) return [];
1678
+ return readdirSync(dayDir).filter((f) => f.endsWith(".jsonl")).map((file) => path3.join(dayDir, file));
1679
+ });
1680
+ if (files.length === 0) continue;
1681
+ found = true;
1682
+ console.log(chalk2.cyan(`
1683
+ ${d}`));
1684
+ for (const file of files) {
1685
+ const summary = summarizeSession(file, d);
1686
+ if (!summary) continue;
1687
+ const timeRange = `${summary.firstTimestamp.slice(11, 19)} - ${summary.lastTimestamp.slice(11, 19)}`;
1688
+ const eventSummary = Object.entries(summary.events).map(([k, v]) => `${k}:${v}`).join(" ");
1689
+ console.log(
1690
+ ` ${chalk2.white(summary.sessionId.slice(0, 12).padEnd(12))} ${chalk2.gray(timeRange)} ${chalk2.green(String(summary.entryCount).padStart(4))} entries ${chalk2.gray(eventSummary)}`
1691
+ );
1692
+ }
1693
+ }
1694
+ if (!found) {
1695
+ console.log(chalk2.yellow("No audit logs found."));
1696
+ }
1697
+ }
1698
+
1699
+ // src/actions/audit/searchAudit.ts
1700
+ import {
1701
+ existsSync as existsSync3,
1702
+ readdirSync as readdirSync2,
1703
+ readFileSync as readFileSync3
1704
+ } from "fs";
1705
+ import path4 from "path";
1706
+ import chalk3 from "chalk";
1707
+ function searchAudit(query, date, limit = 50) {
1708
+ const auditDirs = getAuditSearchDirs().filter((dir) => existsSync3(dir));
1709
+ if (auditDirs.length === 0) {
1710
+ console.log(chalk3.yellow("No audit logs found."));
1711
+ return;
1712
+ }
1713
+ const dates = date ? [date] : [...new Set(
1714
+ auditDirs.flatMap((auditDir) => readdirSync2(auditDir).filter((d) => /^\d{4}-\d{2}-\d{2}$/.test(d)))
1715
+ )].toSorted((a, b) => a.localeCompare(b)).toReversed();
1716
+ const lowerQuery = query.toLowerCase();
1717
+ let matchCount = 0;
1718
+ for (const d of dates) {
1719
+ const files = auditDirs.flatMap((auditDir) => {
1720
+ const dayDir = path4.join(auditDir, d);
1721
+ if (!existsSync3(dayDir)) return [];
1722
+ return readdirSync2(dayDir).filter((f) => f.endsWith(".jsonl")).map((file) => path4.join(dayDir, file));
1723
+ });
1724
+ for (const file of files) {
1725
+ const content = readFileSync3(file, "utf8").trim();
1726
+ if (!content) continue;
1727
+ for (const line of content.split("\n")) {
1728
+ if (!line.toLowerCase().includes(lowerQuery)) continue;
1729
+ try {
1730
+ const entry = JSON.parse(line);
1731
+ const time = (entry.timestamp ?? "").slice(0, 19);
1732
+ const event = entry.event ?? "unknown";
1733
+ const snippet = JSON.stringify(entry.data).slice(0, 150);
1734
+ console.log(`${chalk3.gray(time)} ${chalk3.cyan((entry.sessionId ?? "").slice(0, 8))} ${chalk3.yellow(event)} ${snippet}`);
1735
+ matchCount++;
1736
+ if (matchCount >= limit) {
1737
+ console.log(chalk3.gray(`
1738
+ ... showing first ${limit} matches`));
1739
+ return;
1740
+ }
1741
+ } catch {
1742
+ }
1743
+ }
1744
+ }
1745
+ }
1746
+ if (matchCount === 0) {
1747
+ console.log(chalk3.yellow(`No matches found for: ${query}`));
1748
+ } else {
1749
+ console.log(chalk3.gray(`
1750
+ ${matchCount} match${matchCount === 1 ? "" : "es"} found`));
1751
+ }
1752
+ }
1753
+
1754
+ // src/actions/audit/showSession.ts
1755
+ import {
1756
+ existsSync as existsSync4,
1757
+ readdirSync as readdirSync3,
1758
+ readFileSync as readFileSync4
1759
+ } from "fs";
1760
+ import path5 from "path";
1761
+ import chalk4 from "chalk";
1762
+ function findSessionFile(sessionId) {
1763
+ const auditDirs = getAuditSearchDirs().filter((dir) => existsSync4(dir));
1764
+ if (auditDirs.length === 0) return void 0;
1765
+ const dates = [...new Set(
1766
+ auditDirs.flatMap((auditDir) => readdirSync3(auditDir).filter((d) => /^\d{4}-\d{2}-\d{2}$/.test(d)))
1767
+ )].toSorted((a, b) => a.localeCompare(b)).toReversed();
1768
+ for (const date of dates) {
1769
+ for (const auditDir of auditDirs) {
1770
+ const dayDir = path5.join(auditDir, date);
1771
+ if (!existsSync4(dayDir)) continue;
1772
+ const files = readdirSync3(dayDir).filter((f) => f.includes(sessionId) && f.endsWith(".jsonl"));
1773
+ if (files.length > 0) return path5.join(dayDir, files[0]);
1774
+ }
1775
+ }
1776
+ return void 0;
1777
+ }
1778
+ function formatSessionStart(time, entry) {
1779
+ const version = entry.ai?.version ? ` v${entry.ai.version}` : "";
1780
+ const mode = entry.data?.permissionMode ? ` mode=${entry.data.permissionMode}` : "";
1781
+ return `${chalk4.gray(time)} ${chalk4.blue("SESSION START")}${version}${mode}`;
1782
+ }
1783
+ function formatEntry(entry) {
1784
+ const time = (entry.timestamp ?? "").slice(11, 23);
1785
+ const event = entry.event ?? "unknown";
1786
+ const data = entry.data;
1787
+ switch (event) {
1788
+ case "SessionStart": {
1789
+ return formatSessionStart(time, entry);
1790
+ }
1791
+ case "UserPromptSubmit": {
1792
+ return `${chalk4.gray(time)} ${chalk4.green("PROMPT")} ${String(data?.prompt ?? "").slice(0, 200)}`;
1793
+ }
1794
+ case "PostToolUse": {
1795
+ return `${chalk4.gray(time)} ${chalk4.yellow("TOOL")} ${chalk4.white(String(data?.toolName ?? ""))} ${chalk4.gray(String(data?.toolInput ?? "").slice(0, 120))}`;
1796
+ }
1797
+ case "Stop": {
1798
+ return `${chalk4.gray(time)} ${chalk4.magenta("RESPONSE")} ${String(data?.response ?? "").slice(0, 200)}`;
1799
+ }
1800
+ default: {
1801
+ return `${chalk4.gray(time)} ${event} ${JSON.stringify(data)}`;
1802
+ }
1803
+ }
1804
+ }
1805
+ function showSession(sessionId, format) {
1806
+ const filePath = findSessionFile(sessionId);
1807
+ if (!filePath) {
1808
+ console.log(chalk4.red(`No audit log found for session: ${sessionId}`));
1809
+ return;
1810
+ }
1811
+ const content = readFileSync4(filePath, "utf8").trim();
1812
+ if (!content) {
1813
+ console.log(chalk4.yellow("Session log is empty."));
1814
+ return;
1815
+ }
1816
+ const lines = content.split("\n");
1817
+ if (format === "json") {
1818
+ for (const line of lines) {
1819
+ console.log(line);
1820
+ }
1821
+ return;
1822
+ }
1823
+ console.log(chalk4.cyan(`Session: ${sessionId}`));
1824
+ console.log(chalk4.cyan(`File: ${filePath}`));
1825
+ console.log(chalk4.cyan(`Entries: ${lines.length}`));
1826
+ console.log();
1827
+ for (const line of lines) {
1828
+ try {
1829
+ const entry = JSON.parse(line);
1830
+ console.log(formatEntry(entry));
1831
+ } catch {
1832
+ console.log(chalk4.red(` [malformed] ${line.slice(0, 80)}`));
1833
+ }
1834
+ }
1835
+ }
1836
+
1837
+ // src/actions/audit/statusAudit.ts
1838
+ import {
1839
+ existsSync as existsSync5,
1840
+ readdirSync as readdirSync4,
1841
+ readFileSync as readFileSync5,
1842
+ statSync
1843
+ } from "fs";
1844
+ import { homedir as homedir3 } from "os";
1845
+ import path6 from "path";
1846
+ import chalk5 from "chalk";
1847
+ function getDirectorySize(dir) {
1848
+ let size = 0;
1849
+ if (!existsSync5(dir)) return size;
1850
+ for (const entry of readdirSync4(dir)) {
1851
+ const fullPath = path6.join(dir, entry);
1852
+ const stat = statSync(fullPath);
1853
+ size += stat.isDirectory() ? getDirectorySize(fullPath) : stat.size;
1854
+ }
1855
+ return size;
1856
+ }
1857
+ function formatBytes(bytes) {
1858
+ if (bytes < 1024) return `${bytes} B`;
1859
+ if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
1860
+ return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
1861
+ }
1862
+ function countSessions(dir) {
1863
+ if (!existsSync5(dir)) return 0;
1864
+ let count = 0;
1865
+ for (const date of readdirSync4(dir)) {
1866
+ const dayDir = path6.join(dir, date);
1867
+ const stat = statSync(dayDir);
1868
+ if (stat.isDirectory()) {
1869
+ count += readdirSync4(dayDir).filter((f) => f.endsWith(".jsonl")).length;
1870
+ }
1871
+ }
1872
+ return count;
1873
+ }
1874
+ function checkHooksInstalled() {
1875
+ const settingsPath = path6.join(homedir3(), ".claude", "settings.json");
1876
+ if (!existsSync5(settingsPath)) return false;
1877
+ try {
1878
+ const settings = JSON.parse(readFileSync5(settingsPath, "utf8"));
1879
+ return settings.hooks != null;
1880
+ } catch {
1881
+ return false;
1882
+ }
1883
+ }
1884
+ function statusAudit() {
1885
+ const auditRootDir = getAuditRootDir();
1886
+ const auditDirs = getAuditSearchDirs().filter((dir) => existsSync5(dir));
1887
+ console.log(chalk5.cyan("Audit Plugin Status"));
1888
+ console.log();
1889
+ if (checkHooksInstalled()) {
1890
+ console.log(` ${chalk5.green("Hooks:")} configured in ~/.claude/settings.json`);
1891
+ } else {
1892
+ console.log(` ${chalk5.red("Hooks:")} not installed (run: aries audit install)`);
1893
+ }
1894
+ console.log();
1895
+ console.log(` ${chalk5.gray("Log root:")} ${auditRootDir}`);
1896
+ console.log(` ${chalk5.gray("Claude logs:")} ${getAuditDir("claude")}`);
1897
+ console.log(` ${chalk5.gray("Codex logs:")} ${getAuditDir("codex")}`);
1898
+ if (auditDirs.length > 0) {
1899
+ const sessions = auditDirs.reduce((sum, dir) => sum + countSessions(dir), 0);
1900
+ const size = auditDirs.reduce((sum, dir) => sum + getDirectorySize(dir), 0);
1901
+ const dates = [...new Set(
1902
+ auditDirs.flatMap((dir) => readdirSync4(dir).filter((d) => /^\d{4}-\d{2}-\d{2}$/.test(d)))
1903
+ )];
1904
+ const sorted = dates.toSorted((a, b) => a.localeCompare(b));
1905
+ console.log(` ${chalk5.gray("Sessions:")} ${sessions}`);
1906
+ console.log(` ${chalk5.gray("Date range:")} ${sorted[0] ?? "none"} - ${sorted.at(-1) ?? "none"}`);
1907
+ console.log(` ${chalk5.gray("Disk usage:")} ${formatBytes(size)}`);
1908
+ } else {
1909
+ console.log(` ${chalk5.gray("No logs yet")}`);
1910
+ }
1911
+ }
1912
+
1913
+ // src/actions/clamp/clampAudit.ts
1914
+ import { writeAuditEntry } from "@xylabs/aries-audit-core";
1915
+ import { CLAMP_AUDIT_SCHEMA } from "@xylabs/aries-clamp-core";
1916
+ function logClampPermission(options) {
1917
+ writeAuditEntry({
1918
+ ai: { product: "clamp", provider: "aries" },
1919
+ client: { name: "@xylabs/aries", version: "0.1.0" },
1920
+ cwd: process.cwd(),
1921
+ data: {
1922
+ args: options.args,
1923
+ command: options.command,
1924
+ decision: options.decision,
1925
+ policy: options.policy.name
1926
+ },
1927
+ event: "ClampPermission",
1928
+ schema: CLAMP_AUDIT_SCHEMA,
1929
+ sessionId: options.sessionId,
1930
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
1931
+ });
1932
+ }
1933
+ function logClampStart(options) {
1934
+ writeAuditEntry({
1935
+ ai: { product: "clamp", provider: "aries" },
1936
+ client: { name: "@xylabs/aries", version: "0.1.0" },
1937
+ cwd: process.cwd(),
1938
+ data: {
1939
+ command: options.command,
1940
+ policy: options.policy.name
1941
+ },
1942
+ event: "ClampStart",
1943
+ schema: CLAMP_AUDIT_SCHEMA,
1944
+ sessionId: options.sessionId,
1945
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
1946
+ });
1947
+ }
1948
+ function logClampStop(options) {
1949
+ writeAuditEntry({
1950
+ ai: { product: "clamp", provider: "aries" },
1951
+ client: { name: "@xylabs/aries", version: "0.1.0" },
1952
+ cwd: process.cwd(),
1953
+ data: { exitCode: options.exitCode },
1954
+ event: "ClampStop",
1955
+ schema: CLAMP_AUDIT_SCHEMA,
1956
+ sessionId: options.sessionId,
1957
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
1958
+ });
1959
+ }
1960
+
1961
+ // src/actions/clamp/ipcServer.ts
1962
+ import {
1963
+ createServer
1964
+ } from "net";
1965
+ function createIpcServer(options) {
1966
+ const { socketPath, onPermissionRequest } = options;
1967
+ const server = createServer((socket) => {
1968
+ let data = "";
1969
+ socket.on("data", (chunk) => {
1970
+ data += chunk.toString();
1971
+ const newlineIdx = data.indexOf("\n");
1972
+ if (newlineIdx === -1) return;
1973
+ const line = data.slice(0, newlineIdx);
1974
+ data = data.slice(newlineIdx + 1);
1975
+ let request;
1976
+ try {
1977
+ request = JSON.parse(line);
1978
+ } catch {
1979
+ socket.end(JSON.stringify({
1980
+ allowed: false,
1981
+ reason: "Invalid request",
1982
+ requestId: "unknown",
1983
+ type: "permission-response"
1984
+ }) + "\n");
1985
+ return;
1986
+ }
1987
+ onPermissionRequest(request).then((response) => {
1988
+ socket.end(JSON.stringify(response) + "\n");
1989
+ }).catch(() => {
1990
+ const errorResponse = {
1991
+ allowed: false,
1992
+ reason: "Internal error",
1993
+ requestId: request.requestId,
1994
+ type: "permission-response"
1995
+ };
1996
+ socket.end(JSON.stringify(errorResponse) + "\n");
1997
+ });
1998
+ });
1999
+ socket.on("error", () => {
2000
+ });
2001
+ });
2002
+ const listening = new Promise((resolve, reject) => {
2003
+ server.listen(socketPath, () => resolve());
2004
+ server.on("error", reject);
2005
+ });
2006
+ return {
2007
+ close: () => server.close(),
2008
+ listening,
2009
+ server
2010
+ };
2011
+ }
2012
+
2013
+ // src/actions/clamp/promptUser.ts
2014
+ import {
2015
+ closeSync,
2016
+ openSync,
2017
+ writeSync
2018
+ } from "fs";
2019
+ import { createInterface } from "readline";
2020
+ import { ReadStream } from "tty";
2021
+ function parseAnswer(answer) {
2022
+ const trimmed = answer.trim().toLowerCase();
2023
+ if (trimmed === "y" || trimmed === "yes") return "allow-once";
2024
+ if (trimmed === "a" || trimmed === "always") return "allow-always";
2025
+ return "deny";
2026
+ }
2027
+ function promptViaTty(fullCommand) {
2028
+ let readFd;
2029
+ let writeFd;
2030
+ try {
2031
+ readFd = openSync("/dev/tty", "r");
2032
+ writeFd = openSync("/dev/tty", "w");
2033
+ } catch {
2034
+ return Promise.resolve("deny");
2035
+ }
2036
+ const ttyIn = new ReadStream(readFd);
2037
+ writeSync(writeFd, `
2038
+ [clamp] "${fullCommand}" \u2014 Allow? [y/N/a(lways)] `);
2039
+ const rl = createInterface({ input: ttyIn, terminal: false });
2040
+ return new Promise((resolve) => {
2041
+ const cleanup = () => {
2042
+ rl.close();
2043
+ ttyIn.destroy();
2044
+ try {
2045
+ closeSync(writeFd);
2046
+ } catch {
2047
+ }
2048
+ };
2049
+ rl.once("line", (answer) => {
2050
+ cleanup();
2051
+ resolve(parseAnswer(answer));
2052
+ });
2053
+ rl.once("close", () => resolve("deny"));
2054
+ ttyIn.on("error", () => {
2055
+ cleanup();
2056
+ resolve("deny");
2057
+ });
2058
+ });
2059
+ }
2060
+ function promptViaRenderer(fullCommand, renderer) {
2061
+ const promptText2 = `[clamp] "${fullCommand}" \u2014 Allow? [y/N/a(lways)] `;
2062
+ renderer.setStatusLine(promptText2);
2063
+ let readFd;
2064
+ try {
2065
+ readFd = openSync("/dev/tty", "r");
2066
+ } catch {
2067
+ renderer.setStatusLine("[clamp] No TTY \u2014 denied");
2068
+ return Promise.resolve("deny");
2069
+ }
2070
+ const ttyIn = new ReadStream(readFd);
2071
+ const rl = createInterface({ input: ttyIn, terminal: false });
2072
+ return new Promise((resolve) => {
2073
+ const cleanup = () => {
2074
+ rl.close();
2075
+ ttyIn.destroy();
2076
+ renderer.setStatusLine("[clamp] Ready");
2077
+ };
2078
+ rl.once("line", (answer) => {
2079
+ const decision = parseAnswer(answer);
2080
+ cleanup();
2081
+ resolve(decision);
2082
+ });
2083
+ rl.once("close", () => {
2084
+ cleanup();
2085
+ resolve("deny");
2086
+ });
2087
+ ttyIn.on("error", () => {
2088
+ cleanup();
2089
+ resolve("deny");
2090
+ });
2091
+ });
2092
+ }
2093
+ async function promptUser(command, args, renderer) {
2094
+ const fullCommand = [command, ...args].join(" ");
2095
+ if (renderer) {
2096
+ return promptViaRenderer(fullCommand, renderer);
2097
+ }
2098
+ return promptViaTty(fullCommand);
2099
+ }
2100
+
2101
+ // src/actions/clamp/runClamped.ts
2102
+ import { randomUUID } from "crypto";
2103
+ import { rmSync as rmSync3, unlinkSync } from "fs";
2104
+ import { tmpdir as tmpdir4 } from "os";
2105
+ import path10 from "path";
2106
+ import {
2107
+ CLAMP_IPC_ENV,
2108
+ CLAMP_ORIGINAL_PATH_ENV,
2109
+ CLAMP_SESSION_ENV,
2110
+ loadPolicy,
2111
+ matchProcess
2112
+ } from "@xylabs/aries-clamp-core";
2113
+ import chalk7 from "chalk";
2114
+
2115
+ // src/actions/clamp/sandboxExec.ts
2116
+ import { spawn } from "child_process";
2117
+ import {
2118
+ mkdtempSync,
2119
+ rmSync,
2120
+ writeFileSync as writeFileSync2
2121
+ } from "fs";
2122
+ import { tmpdir } from "os";
2123
+ import path7 from "path";
2124
+ import { detectPlatform, generateMacOSProfile } from "@xylabs/aries-clamp-core";
2125
+ import chalk6 from "chalk";
2126
+
2127
+ // src/actions/clamp/terminalRenderer.ts
2128
+ import pkg from "@xterm/headless";
2129
+ var { Terminal } = pkg;
2130
+ var STATUS_BAR_HEIGHT = 2;
2131
+ var ESC = "\x1B[";
2132
+ var moveTo = (row, col) => `${ESC}${row};${col}H`;
2133
+ var resetStyle = `${ESC}0m`;
2134
+ var hideCursor = `${ESC}?25l`;
2135
+ var showCursor = `${ESC}?25h`;
2136
+ var clearScreen = `${ESC}2J`;
2137
+ var setBg = (r, g, b) => `${ESC}48;2;${r};${g};${b}m`;
2138
+ var setFg = (r, g, b) => `${ESC}38;2;${r};${g};${b}m`;
2139
+ var fgPalette = (n) => `${ESC}38;5;${n}m`;
2140
+ var bgPalette = (n) => `${ESC}48;5;${n}m`;
2141
+ var bold = `${ESC}1m`;
2142
+ var dim = `${ESC}2m`;
2143
+ var italic = `${ESC}3m`;
2144
+ var underline = `${ESC}4m`;
2145
+ var inverse = `${ESC}7m`;
2146
+ var strikethrough = `${ESC}9m`;
2147
+ function getCellStyle(cell) {
2148
+ if (!cell) return {
2149
+ attrs: "",
2150
+ bg: "",
2151
+ fg: ""
2152
+ };
2153
+ let fg = "";
2154
+ let bg = "";
2155
+ let attrs = "";
2156
+ if (cell.isFgRGB()) {
2157
+ const color = cell.getFgColor();
2158
+ fg = setFg(color >> 16 & 255, color >> 8 & 255, color & 255);
2159
+ } else if (cell.getFgColorMode() !== 0) {
2160
+ fg = fgPalette(cell.getFgColor());
2161
+ }
2162
+ if (cell.isBgRGB()) {
2163
+ const color = cell.getBgColor();
2164
+ bg = setBg(color >> 16 & 255, color >> 8 & 255, color & 255);
2165
+ } else if (cell.getBgColorMode() !== 0) {
2166
+ bg = bgPalette(cell.getBgColor());
2167
+ }
2168
+ if (cell.isBold()) attrs += bold;
2169
+ if (cell.isDim()) attrs += dim;
2170
+ if (cell.isItalic()) attrs += italic;
2171
+ if (cell.isUnderline()) attrs += underline;
2172
+ if (cell.isInverse()) attrs += inverse;
2173
+ if (cell.isStrikethrough()) attrs += strikethrough;
2174
+ return {
2175
+ attrs,
2176
+ bg,
2177
+ fg
2178
+ };
2179
+ }
2180
+ function createTerminalRenderer() {
2181
+ const realCols = process.stdout.columns ?? 80;
2182
+ const realRows = process.stdout.rows ?? 24;
2183
+ const innerRows = realRows - STATUS_BAR_HEIGHT;
2184
+ const terminal = new Terminal({
2185
+ cols: realCols,
2186
+ rows: innerRows
2187
+ });
2188
+ let statusLine = "";
2189
+ let renderScheduled = false;
2190
+ function renderBuffer() {
2191
+ const buf = terminal.buffer.active;
2192
+ const cols = terminal.cols;
2193
+ const rows = terminal.rows;
2194
+ const output = [hideCursor];
2195
+ for (let y = 0; y < rows; y++) {
2196
+ const line = buf.getLine(y);
2197
+ output.push(moveTo(y + 1, 1));
2198
+ if (!line) {
2199
+ output.push(resetStyle + " ".repeat(cols));
2200
+ continue;
2201
+ }
2202
+ let lineStr = "";
2203
+ let lastStyle = "";
2204
+ for (let x = 0; x < cols; x++) {
2205
+ const cell = line.getCell(x);
2206
+ if (!cell || cell.getWidth() === 0) continue;
2207
+ const style = getCellStyle(cell);
2208
+ const styleStr = resetStyle + style.fg + style.bg + style.attrs;
2209
+ if (styleStr !== lastStyle) {
2210
+ lineStr += styleStr;
2211
+ lastStyle = styleStr;
2212
+ }
2213
+ const ch = cell.getChars();
2214
+ lineStr += ch || " ";
2215
+ }
2216
+ output.push(lineStr + resetStyle);
2217
+ }
2218
+ const statusRow = realRows - 1;
2219
+ output.push(
2220
+ moveTo(statusRow, 1),
2221
+ resetStyle + dim + "\u2500".repeat(realCols) + resetStyle,
2222
+ moveTo(statusRow + 1, 1),
2223
+ resetStyle,
2224
+ statusLine.padEnd(realCols).slice(0, realCols),
2225
+ resetStyle
2226
+ );
2227
+ const cursorY = buf.cursorY + 1;
2228
+ const cursorX = buf.cursorX + 1;
2229
+ output.push(moveTo(cursorY, cursorX), showCursor);
2230
+ process.stdout.write(output.join(""));
2231
+ }
2232
+ function scheduleRender() {
2233
+ if (renderScheduled) return;
2234
+ renderScheduled = true;
2235
+ setImmediate(() => {
2236
+ renderScheduled = false;
2237
+ renderBuffer();
2238
+ });
2239
+ }
2240
+ function handleResize() {
2241
+ const newCols = process.stdout.columns ?? 80;
2242
+ const newRows = process.stdout.rows ?? 24;
2243
+ const newInnerRows = newRows - STATUS_BAR_HEIGHT;
2244
+ terminal.resize(newCols, newInnerRows);
2245
+ process.stdout.write(clearScreen);
2246
+ scheduleRender();
2247
+ }
2248
+ process.stdout.on("resize", handleResize);
2249
+ process.stdout.write(clearScreen + moveTo(1, 1));
2250
+ return {
2251
+ destroy: () => {
2252
+ process.stdout.removeListener("resize", handleResize);
2253
+ process.stdout.write(clearScreen + moveTo(1, 1) + showCursor + resetStyle);
2254
+ terminal.dispose();
2255
+ },
2256
+ render: scheduleRender,
2257
+ setStatusLine: (line) => {
2258
+ statusLine = line;
2259
+ scheduleRender();
2260
+ },
2261
+ terminal,
2262
+ write: (data) => {
2263
+ terminal.write(data);
2264
+ scheduleRender();
2265
+ }
2266
+ };
2267
+ }
2268
+
2269
+ // src/actions/clamp/sandboxExec.ts
2270
+ function createMacOSSandbox(policy) {
2271
+ const profileContent = generateMacOSProfile(policy, process.cwd());
2272
+ const profileDir = mkdtempSync(path7.join(tmpdir(), "aries-clamp-sb-"));
2273
+ const profilePath = path7.join(profileDir, "sandbox.sb");
2274
+ writeFileSync2(profilePath, profileContent, "utf8");
2275
+ console.error(chalk6.gray("[clamp] macOS sandbox enabled"));
2276
+ return {
2277
+ args: ["-f", profilePath],
2278
+ cleanup: () => {
2279
+ try {
2280
+ rmSync(profileDir, { force: true, recursive: true });
2281
+ } catch {
2282
+ }
2283
+ }
2284
+ };
2285
+ }
2286
+ function resolveSpawnCommand(command, args, policy) {
2287
+ const platform2 = detectPlatform();
2288
+ const cleanupFns = [];
2289
+ if (platform2 === "darwin" && policy.filesystem) {
2290
+ const sandbox = createMacOSSandbox(policy);
2291
+ cleanupFns.push(sandbox.cleanup);
2292
+ return {
2293
+ cleanupFns,
2294
+ spawnArgs: [...sandbox.args, command, ...args],
2295
+ spawnCommand: "sandbox-exec"
2296
+ };
2297
+ }
2298
+ if (platform2 === "linux" && policy.filesystem) {
2299
+ console.error(chalk6.yellow("[clamp] Linux filesystem sandbox: Landlock integration pending"));
2300
+ } else if (policy.filesystem) {
2301
+ console.error(chalk6.yellow(`[clamp] OS filesystem sandbox not available on ${platform2}`));
2302
+ }
2303
+ return {
2304
+ cleanupFns,
2305
+ spawnArgs: args,
2306
+ spawnCommand: command
2307
+ };
2308
+ }
2309
+ function cleanEnvRecord(env) {
2310
+ const clean = {};
2311
+ for (const [k, v] of Object.entries(env)) {
2312
+ if (v !== void 0) clean[k] = v;
2313
+ }
2314
+ return clean;
2315
+ }
2316
+ function spawnWithRenderedPty(spawnCommand, spawnArgs, env) {
2317
+ try {
2318
+ const pty = require_lib();
2319
+ const renderer = createTerminalRenderer();
2320
+ const innerRows = (process.stdout.rows ?? 24) - 2;
2321
+ const ptyProcess = pty.spawn(spawnCommand, spawnArgs, {
2322
+ cols: process.stdout.columns ?? 80,
2323
+ cwd: process.cwd(),
2324
+ env,
2325
+ name: process.env.TERM ?? "xterm-256color",
2326
+ rows: innerRows
2327
+ });
2328
+ let paused = false;
2329
+ ptyProcess.onData((data) => {
2330
+ if (!paused) {
2331
+ renderer.write(data);
2332
+ }
2333
+ });
2334
+ if (process.stdin.isTTY) process.stdin.setRawMode(true);
2335
+ process.stdin.resume();
2336
+ const onStdin = (data) => {
2337
+ ptyProcess.write(data.toString());
2338
+ };
2339
+ process.stdin.on("data", onStdin);
2340
+ const onResize = () => {
2341
+ const newInnerRows = (process.stdout.rows ?? 24) - 2;
2342
+ ptyProcess.resize(process.stdout.columns ?? 80, newInnerRows);
2343
+ };
2344
+ process.stdout.on("resize", onResize);
2345
+ const exitCode = new Promise((resolve) => {
2346
+ ptyProcess.onExit(({ exitCode: code }) => {
2347
+ process.stdin.removeListener("data", onStdin);
2348
+ process.stdout.removeListener("resize", onResize);
2349
+ if (process.stdin.isTTY) process.stdin.setRawMode(false);
2350
+ process.stdin.pause();
2351
+ renderer.destroy();
2352
+ resolve(code);
2353
+ });
2354
+ });
2355
+ return {
2356
+ cleanup: () => {
2357
+ },
2358
+ exitCode,
2359
+ ok: true,
2360
+ pause: () => {
2361
+ paused = true;
2362
+ },
2363
+ renderer,
2364
+ resume: () => {
2365
+ paused = false;
2366
+ renderer.render();
2367
+ }
2368
+ };
2369
+ } catch {
2370
+ return { ok: false };
2371
+ }
2372
+ }
2373
+ function spawnFallback(spawnCommand, spawnArgs, env) {
2374
+ console.error(chalk6.yellow("[clamp] PTY unavailable, falling back to basic stdio passthrough"));
2375
+ const child = spawn(spawnCommand, spawnArgs, { env, stdio: "inherit" });
2376
+ const exitCode = new Promise((resolve) => {
2377
+ child.on("close", (code) => resolve(code));
2378
+ child.on("error", () => resolve(1));
2379
+ });
2380
+ const noop = () => {
2381
+ };
2382
+ return {
2383
+ cleanup: noop,
2384
+ exitCode,
2385
+ pause: noop,
2386
+ renderer: void 0,
2387
+ resume: noop
2388
+ };
2389
+ }
2390
+ function spawnSandboxed(options) {
2391
+ const { env, policy } = options;
2392
+ const {
2393
+ spawnCommand,
2394
+ spawnArgs,
2395
+ cleanupFns
2396
+ } = resolveSpawnCommand(options.command, options.args, policy);
2397
+ const cleanEnv = cleanEnvRecord(env);
2398
+ const ptyResult = spawnWithRenderedPty(spawnCommand, spawnArgs, cleanEnv);
2399
+ const result = ptyResult.ok ? ptyResult : spawnFallback(spawnCommand, spawnArgs, env);
2400
+ const originalCleanup = result.cleanup;
2401
+ return {
2402
+ ...result,
2403
+ cleanup: () => {
2404
+ originalCleanup();
2405
+ for (const fn of cleanupFns) fn();
2406
+ }
2407
+ };
2408
+ }
2409
+
2410
+ // src/actions/clamp/shellEnvSetup.ts
2411
+ import {
2412
+ mkdtempSync as mkdtempSync2,
2413
+ rmSync as rmSync2,
2414
+ writeFileSync as writeFileSync3
2415
+ } from "fs";
2416
+ import { homedir as homedir4, tmpdir as tmpdir2 } from "os";
2417
+ import path8 from "path";
2418
+ function createShellEnvOverrides(shimDir) {
2419
+ const tmpDir = mkdtempSync2(path8.join(tmpdir2(), "aries-clamp-env-"));
2420
+ const home = homedir4();
2421
+ const zshenv = [
2422
+ "# Aries Clamp: source real .zshenv then re-prepend shim dir",
2423
+ `[ -f "${home}/.zshenv" ] && ZDOTDIR="${home}" source "${home}/.zshenv"`,
2424
+ `export PATH="${shimDir}:\${PATH}"`
2425
+ ].join("\n") + "\n";
2426
+ writeFileSync3(path8.join(tmpDir, ".zshenv"), zshenv, "utf8");
2427
+ const zshrc = [
2428
+ "# Aries Clamp: source real .zshrc then re-prepend shim dir",
2429
+ `[ -f "${home}/.zshrc" ] && ZDOTDIR="${home}" source "${home}/.zshrc"`,
2430
+ `export PATH="${shimDir}:\${PATH}"`
2431
+ ].join("\n") + "\n";
2432
+ writeFileSync3(path8.join(tmpDir, ".zshrc"), zshrc, "utf8");
2433
+ const zprofile = [
2434
+ "# Aries Clamp: source real .zprofile then re-prepend shim dir",
2435
+ `[ -f "${home}/.zprofile" ] && ZDOTDIR="${home}" source "${home}/.zprofile"`,
2436
+ `export PATH="${shimDir}:\${PATH}"`
2437
+ ].join("\n") + "\n";
2438
+ writeFileSync3(path8.join(tmpDir, ".zprofile"), zprofile, "utf8");
2439
+ const bashEnv = [
2440
+ "# Aries Clamp: prepend shim dir to PATH",
2441
+ `export PATH="${shimDir}:\${PATH}"`
2442
+ ].join("\n") + "\n";
2443
+ const bashEnvPath = path8.join(tmpDir, "bash_env.sh");
2444
+ writeFileSync3(bashEnvPath, bashEnv, "utf8");
2445
+ const bashrc = [
2446
+ "# Aries Clamp: source real .bashrc then re-prepend shim dir",
2447
+ `[ -f "${home}/.bashrc" ] && source "${home}/.bashrc"`,
2448
+ `export PATH="${shimDir}:\${PATH}"`
2449
+ ].join("\n") + "\n";
2450
+ writeFileSync3(path8.join(tmpDir, ".bashrc"), bashrc, "utf8");
2451
+ return {
2452
+ cleanup: () => {
2453
+ try {
2454
+ rmSync2(tmpDir, { force: true, recursive: true });
2455
+ } catch {
2456
+ }
2457
+ },
2458
+ env: {
2459
+ BASH_ENV: bashEnvPath,
2460
+ ENV: bashEnvPath,
2461
+ ZDOTDIR: tmpDir
2462
+ }
2463
+ };
2464
+ }
2465
+
2466
+ // src/actions/clamp/shimGenerator.ts
2467
+ import {
2468
+ chmodSync,
2469
+ existsSync as existsSync6,
2470
+ mkdtempSync as mkdtempSync3,
2471
+ writeFileSync as writeFileSync4
2472
+ } from "fs";
2473
+ import { createRequire } from "module";
2474
+ import { tmpdir as tmpdir3 } from "os";
2475
+ import path9 from "path";
2476
+ var DANGEROUS_COMMANDS = [
2477
+ "chmod",
2478
+ "chown",
2479
+ "curl",
2480
+ "docker",
2481
+ "kill",
2482
+ "killall",
2483
+ "mv",
2484
+ "pkill",
2485
+ "rm",
2486
+ "rmdir",
2487
+ "sudo",
2488
+ "wget"
2489
+ ];
2490
+ function getGatekeeperPath() {
2491
+ const require2 = createRequire(import.meta.url);
2492
+ try {
2493
+ const pluginPkg = require2.resolve("@xylabs/aries-clamp-plugin/package.json");
2494
+ return path9.join(path9.dirname(pluginPkg), "dist", "shim", "gatekeeper.mjs");
2495
+ } catch {
2496
+ const candidates = [
2497
+ path9.resolve("packages", "clamp-plugin", "dist", "shim", "gatekeeper.mjs"),
2498
+ path9.resolve("node_modules", "@xylabs", "aries-clamp-plugin", "dist", "shim", "gatekeeper.mjs")
2499
+ ];
2500
+ for (const candidate of candidates) {
2501
+ if (existsSync6(candidate)) return candidate;
2502
+ }
2503
+ throw new Error("Could not find gatekeeper.mjs \u2014 is @xylabs/aries-clamp-plugin built?");
2504
+ }
2505
+ }
2506
+ async function generateShimDirectory(policy) {
2507
+ const shimDir = mkdtempSync3(path9.join(tmpdir3(), "aries-clamp-"));
2508
+ const gatekeeperPath = getGatekeeperPath();
2509
+ const nodePath = process.execPath;
2510
+ const commands = /* @__PURE__ */ new Set();
2511
+ const processRules = policy.process;
2512
+ if (processRules) {
2513
+ for (const cmd of processRules.allow ?? []) commands.add(cmd);
2514
+ for (const cmd of processRules.prompt ?? []) commands.add(cmd);
2515
+ for (const cmd of processRules.deny ?? []) commands.add(cmd);
2516
+ }
2517
+ for (const cmd of DANGEROUS_COMMANDS) {
2518
+ commands.add(cmd);
2519
+ }
2520
+ for (const cmd of commands) {
2521
+ const shimPath = path9.join(shimDir, cmd);
2522
+ const script = `#!/bin/sh
2523
+ exec "${nodePath}" "${gatekeeperPath}" "${cmd}" "$@"
2524
+ `;
2525
+ writeFileSync4(shimPath, script, "utf8");
2526
+ chmodSync(shimPath, 493);
2527
+ }
2528
+ return shimDir;
2529
+ }
2530
+
2531
+ // src/actions/clamp/runClamped.ts
2532
+ function printDryRun(command, args, policy, auditEnabled) {
2533
+ console.log(chalk7.cyan("\n[clamp] Dry run \u2014 would sandbox with:\n"));
2534
+ console.log(chalk7.white(` Command: ${command} ${args.join(" ")}`));
2535
+ console.log(chalk7.white(` Policy: ${policy.name}`));
2536
+ console.log(chalk7.white(` Default action: ${policy.defaultAction ?? "prompt"}`));
2537
+ console.log(chalk7.white(` Audit: ${auditEnabled ? "enabled" : "disabled"}`));
2538
+ if (policy.process) {
2539
+ console.log(chalk7.green(` Allowed: ${policy.process.allow?.join(", ") ?? "(none)"}`));
2540
+ console.log(chalk7.yellow(` Prompted: ${policy.process.prompt?.join(", ") ?? "(none)"}`));
2541
+ console.log(chalk7.red(` Denied: ${policy.process.deny?.join(", ") ?? "(none)"}`));
2542
+ }
2543
+ if (policy.filesystem) {
2544
+ console.log(chalk7.white(" Filesystem sandbox: enabled"));
2545
+ }
2546
+ console.log("");
2547
+ }
2548
+ async function resolveDecision(command, args, alwaysAllow, renderer) {
2549
+ const answer = await promptUser(command, args, renderer);
2550
+ if (answer === "allow-always") {
2551
+ alwaysAllow.add(command);
2552
+ return "prompted-allow";
2553
+ }
2554
+ return answer === "allow-once" ? "prompted-allow" : "prompted-deny";
2555
+ }
2556
+ function createPermissionHandler(policy, sessionId, auditEnabled, alwaysAllow, sandboxRef) {
2557
+ const defaultAction = policy.defaultAction ?? "prompt";
2558
+ return async (request) => {
2559
+ const {
2560
+ command: reqCommand,
2561
+ args: reqArgs,
2562
+ requestId
2563
+ } = request;
2564
+ if (alwaysAllow.has(reqCommand)) {
2565
+ if (auditEnabled) {
2566
+ logClampPermission({
2567
+ args: reqArgs,
2568
+ command: reqCommand,
2569
+ decision: "allowed",
2570
+ policy,
2571
+ sessionId
2572
+ });
2573
+ }
2574
+ return {
2575
+ allowed: true,
2576
+ requestId,
2577
+ type: "permission-response"
2578
+ };
2579
+ }
2580
+ const level = matchProcess(reqCommand, policy.process, defaultAction);
2581
+ if (level === "allow" || level === "deny") {
2582
+ const decision2 = level === "allow" ? "allowed" : "denied";
2583
+ if (auditEnabled) {
2584
+ logClampPermission({
2585
+ args: reqArgs,
2586
+ command: reqCommand,
2587
+ decision: decision2,
2588
+ policy,
2589
+ sessionId
2590
+ });
2591
+ }
2592
+ return {
2593
+ allowed: level === "allow",
2594
+ reason: level === "deny" ? `Policy "${policy.name}": deny` : void 0,
2595
+ requestId,
2596
+ type: "permission-response"
2597
+ };
2598
+ }
2599
+ sandboxRef.sandbox?.pause();
2600
+ const decision = await resolveDecision(reqCommand, reqArgs, alwaysAllow, sandboxRef.sandbox?.renderer);
2601
+ sandboxRef.sandbox?.resume();
2602
+ if (auditEnabled) {
2603
+ logClampPermission({
2604
+ args: reqArgs,
2605
+ command: reqCommand,
2606
+ decision,
2607
+ policy,
2608
+ sessionId
2609
+ });
2610
+ }
2611
+ const allowed = decision === "prompted-allow";
2612
+ return {
2613
+ allowed,
2614
+ reason: allowed ? void 0 : `Policy "${policy.name}": denied by user`,
2615
+ requestId,
2616
+ type: "permission-response"
2617
+ };
2618
+ };
2619
+ }
2620
+ function buildChildEnv(shimDir, socketPath, sessionId, shellEnv) {
2621
+ const originalPath = process.env.PATH ?? "";
2622
+ return {
2623
+ ...process.env,
2624
+ ...shellEnv,
2625
+ PATH: `${shimDir}${path10.delimiter}${originalPath}`,
2626
+ [CLAMP_IPC_ENV]: socketPath,
2627
+ [CLAMP_ORIGINAL_PATH_ENV]: originalPath,
2628
+ [CLAMP_SESSION_ENV]: sessionId
2629
+ };
2630
+ }
2631
+ function cleanupResources(socketPath, shimDir) {
2632
+ try {
2633
+ unlinkSync(socketPath);
2634
+ } catch {
2635
+ }
2636
+ try {
2637
+ rmSync3(shimDir, { force: true, recursive: true });
2638
+ } catch {
2639
+ }
2640
+ }
2641
+ function parseArgs(argv) {
2642
+ return {
2643
+ args: argv.args ?? [],
2644
+ auditEnabled: argv.audit !== false,
2645
+ command: argv.command,
2646
+ dryRun: argv["dry-run"] ?? false,
2647
+ policyOption: argv.policy
2648
+ };
2649
+ }
2650
+ async function runClamped(argv) {
2651
+ const {
2652
+ command,
2653
+ args,
2654
+ policyOption,
2655
+ auditEnabled,
2656
+ dryRun
2657
+ } = parseArgs(argv);
2658
+ let policy;
2659
+ try {
2660
+ policy = loadPolicy({ path: policyOption });
2661
+ } catch (err) {
2662
+ console.error(chalk7.red(`Failed to load policy: ${String(err)}`));
2663
+ process.exit(1);
2664
+ }
2665
+ if (dryRun) {
2666
+ printDryRun(command, args, policy, auditEnabled);
2667
+ return;
2668
+ }
2669
+ const sessionId = randomUUID();
2670
+ const shimDir = await generateShimDirectory(policy);
2671
+ const shellOverrides = createShellEnvOverrides(shimDir);
2672
+ const socketPath = path10.join(tmpdir4(), `aries-clamp-${process.pid}-${randomUUID().slice(0, 8)}.sock`);
2673
+ const sandboxRef = {};
2674
+ const handler = createPermissionHandler(policy, sessionId, auditEnabled, /* @__PURE__ */ new Set(), sandboxRef);
2675
+ const ipcHandle = createIpcServer({ onPermissionRequest: handler, socketPath });
2676
+ await ipcHandle.listening;
2677
+ if (auditEnabled) logClampStart({
2678
+ command,
2679
+ policy,
2680
+ sessionId
2681
+ });
2682
+ console.error(chalk7.cyan(`[clamp] Session ${sessionId.slice(0, 8)} \u2014 policy: ${policy.name}`));
2683
+ const childEnv = buildChildEnv(shimDir, socketPath, sessionId, shellOverrides.env);
2684
+ const sandbox = spawnSandboxed({
2685
+ args,
2686
+ command,
2687
+ env: childEnv,
2688
+ policy
2689
+ });
2690
+ sandboxRef.sandbox = sandbox;
2691
+ sandbox.renderer?.setStatusLine(`[clamp] policy: ${policy.name} | allowed: 0 | denied: 0`);
2692
+ const exitCode = await sandbox.exitCode;
2693
+ sandbox.cleanup();
2694
+ shellOverrides.cleanup();
2695
+ ipcHandle.close();
2696
+ cleanupResources(socketPath, shimDir);
2697
+ if (auditEnabled) logClampStop({ exitCode, sessionId });
2698
+ console.error(chalk7.gray(`
2699
+ [clamp] Session ended (exit code: ${exitCode})`));
2700
+ process.exit(exitCode ?? 1);
2701
+ }
2702
+
2703
+ // src/actions/detect/detectAiClients.ts
2704
+ import { execFileSync, execSync } from "child_process";
2705
+ import { existsSync as existsSync7, realpathSync } from "fs";
2706
+ import { homedir as homedir5, platform } from "os";
2707
+ import path11 from "path";
2708
+ import chalk8 from "chalk";
2709
+ function getAppPaths() {
2710
+ const os = platform();
2711
+ const home = homedir5();
2712
+ if (os === "darwin") {
2713
+ return ["/Applications", path11.join(home, "Applications")];
2714
+ }
2715
+ if (os === "win32") {
2716
+ return [
2717
+ String.raw`C:\Program Files`,
2718
+ String.raw`C:\Program Files (x86)`,
2719
+ path11.join(home, "AppData", "Local", "Programs")
2720
+ ];
2721
+ }
2722
+ return ["/usr/share/applications"];
2723
+ }
2724
+ function detectApp(candidate) {
2725
+ const appDirs = getAppPaths();
2726
+ for (const dir of appDirs) {
2727
+ for (const appPath of candidate.paths) {
2728
+ const full = path11.join(dir, appPath);
2729
+ if (existsSync7(full)) {
2730
+ return {
2731
+ detected: true,
2732
+ name: candidate.name,
2733
+ path: full,
2734
+ provider: candidate.provider,
2735
+ type: "app"
2736
+ };
2737
+ }
2738
+ }
2739
+ }
2740
+ return {
2741
+ detected: false,
2742
+ name: candidate.name,
2743
+ provider: candidate.provider,
2744
+ type: "app"
2745
+ };
2746
+ }
2747
+ function resolveCliPath(location) {
2748
+ try {
2749
+ return realpathSync(location);
2750
+ } catch {
2751
+ return location;
2752
+ }
2753
+ }
2754
+ function findCliLocation(candidate) {
2755
+ try {
2756
+ return execSync(`which ${candidate.command}`, {
2757
+ encoding: "utf8",
2758
+ stdio: ["pipe", "pipe", "pipe"],
2759
+ timeout: 5e3
2760
+ }).trim();
2761
+ } catch {
2762
+ for (const cliPath of candidate.paths ?? []) {
2763
+ if (existsSync7(cliPath)) {
2764
+ return cliPath;
2765
+ }
2766
+ }
2767
+ }
2768
+ }
2769
+ function detectCli(candidate) {
2770
+ const location = findCliLocation(candidate);
2771
+ if (!location) {
2772
+ return {
2773
+ detected: false,
2774
+ name: candidate.name,
2775
+ provider: candidate.provider,
2776
+ type: "cli"
2777
+ };
2778
+ }
2779
+ const resolvedLocation = resolveCliPath(location);
2780
+ let version;
2781
+ if (candidate.versionFlag) {
2782
+ try {
2783
+ const output = execFileSync(resolvedLocation, [candidate.versionFlag], {
2784
+ encoding: "utf8",
2785
+ stdio: ["pipe", "pipe", "pipe"],
2786
+ timeout: 5e3
2787
+ }).trim();
2788
+ const match = /[\d.]+/.exec(output);
2789
+ version = match?.[0];
2790
+ } catch {
2791
+ }
2792
+ }
2793
+ return {
2794
+ detected: true,
2795
+ name: candidate.name,
2796
+ path: resolvedLocation,
2797
+ provider: candidate.provider,
2798
+ type: "cli",
2799
+ version
2800
+ };
2801
+ }
2802
+ function getVscodeExtensions() {
2803
+ try {
2804
+ const output = execSync("code --list-extensions", {
2805
+ encoding: "utf8",
2806
+ stdio: ["pipe", "pipe", "pipe"],
2807
+ timeout: 1e4
2808
+ }).trim();
2809
+ return new Set(output.toLowerCase().split("\n").map((e) => e.trim()));
2810
+ } catch {
2811
+ return /* @__PURE__ */ new Set();
2812
+ }
2813
+ }
2814
+ function detectVscode(candidate, extensions) {
2815
+ const extensionId = candidate.extensionIds.find((id) => extensions.has(id.toLowerCase()));
2816
+ const detected = Boolean(extensionId);
2817
+ return {
2818
+ detected,
2819
+ name: candidate.name,
2820
+ ...extensionId ? { path: extensionId } : {},
2821
+ provider: candidate.provider,
2822
+ type: "vscode"
2823
+ };
2824
+ }
2825
+ var APP_CANDIDATES = [
2826
+ {
2827
+ name: "Claude Desktop",
2828
+ paths: ["Claude.app"],
2829
+ provider: "Anthropic"
2830
+ },
2831
+ {
2832
+ name: "ChatGPT Desktop",
2833
+ paths: ["ChatGPT.app"],
2834
+ provider: "OpenAI"
2835
+ },
2836
+ {
2837
+ name: "Codex Desktop",
2838
+ paths: ["Codex.app", "OpenAI Codex.app"],
2839
+ provider: "OpenAI"
2840
+ },
2841
+ {
2842
+ name: "Cursor",
2843
+ paths: ["Cursor.app", "Cursor/Cursor.exe", "cursor.desktop"],
2844
+ provider: "Cursor"
2845
+ },
2846
+ {
2847
+ name: "Grok Desktop",
2848
+ paths: ["Grok.app"],
2849
+ provider: "xAI"
2850
+ },
2851
+ {
2852
+ name: "Windsurf",
2853
+ paths: ["Windsurf.app", "Windsurf/Windsurf.exe", "windsurf.desktop"],
2854
+ provider: "Windsurf"
2855
+ },
2856
+ {
2857
+ name: "Gemini Desktop",
2858
+ paths: ["Gemini.app", "Google Gemini.app"],
2859
+ provider: "Google"
2860
+ },
2861
+ {
2862
+ name: "Gemini in Android Studio",
2863
+ paths: ["Android Studio.app"],
2864
+ provider: "Google"
2865
+ },
2866
+ {
2867
+ name: "Kiro",
2868
+ paths: ["Kiro.app", "Kiro/Kiro.exe", "kiro.desktop"],
2869
+ provider: "Kiro"
2870
+ },
2871
+ {
2872
+ name: "Copilot Desktop",
2873
+ paths: ["Microsoft Copilot.app", "Copilot.app"],
2874
+ provider: "Microsoft"
2875
+ },
2876
+ {
2877
+ name: "Ollama",
2878
+ paths: ["Ollama.app", "Ollama/Ollama.exe", "ollama.desktop"],
2879
+ provider: "Ollama"
2880
+ },
2881
+ {
2882
+ name: "LM Studio",
2883
+ paths: ["LM Studio.app"],
2884
+ provider: "LM Studio"
2885
+ },
2886
+ {
2887
+ name: "OpenCode",
2888
+ paths: ["OpenCode.app"],
2889
+ provider: "OpenCode"
2890
+ }
2891
+ ];
2892
+ var CLI_CANDIDATES = [
2893
+ {
2894
+ command: "claude",
2895
+ name: "Claude Code",
2896
+ provider: "Anthropic",
2897
+ versionFlag: "--version"
2898
+ },
2899
+ {
2900
+ command: "chatgpt",
2901
+ name: "ChatGPT CLI",
2902
+ provider: "OpenAI",
2903
+ versionFlag: "--version"
2904
+ },
2905
+ {
2906
+ command: "codex",
2907
+ name: "Codex CLI",
2908
+ provider: "OpenAI",
2909
+ versionFlag: "--version"
2910
+ },
2911
+ {
2912
+ command: "cursor-agent",
2913
+ name: "Cursor Agent CLI",
2914
+ provider: "Cursor",
2915
+ versionFlag: "--version"
2916
+ },
2917
+ {
2918
+ command: "cursor",
2919
+ name: "Cursor Editor CLI",
2920
+ paths: ["/Applications/Cursor.app/Contents/Resources/app/bin/cursor"],
2921
+ provider: "Cursor",
2922
+ versionFlag: "--version"
2923
+ },
2924
+ {
2925
+ command: "grok",
2926
+ name: "Grok CLI",
2927
+ provider: "xAI",
2928
+ versionFlag: "--version"
2929
+ },
2930
+ {
2931
+ command: "windsurf",
2932
+ name: "Windsurf CLI",
2933
+ paths: ["/Applications/Windsurf.app/Contents/Resources/app/bin/windsurf"],
2934
+ provider: "Windsurf",
2935
+ versionFlag: "--version"
2936
+ },
2937
+ {
2938
+ command: "gemini",
2939
+ name: "Gemini CLI",
2940
+ provider: "Google",
2941
+ versionFlag: "--version"
2942
+ },
2943
+ {
2944
+ command: "kiro-cli",
2945
+ name: "Kiro CLI",
2946
+ provider: "Kiro",
2947
+ versionFlag: "version"
2948
+ },
2949
+ {
2950
+ command: "kiro",
2951
+ name: "Kiro Editor CLI",
2952
+ provider: "Kiro",
2953
+ versionFlag: "--version"
2954
+ },
2955
+ {
2956
+ command: "copilot",
2957
+ name: "GitHub Copilot CLI",
2958
+ provider: "Microsoft",
2959
+ versionFlag: "--version"
2960
+ },
2961
+ {
2962
+ command: "ollama",
2963
+ name: "Ollama CLI",
2964
+ paths: ["/Applications/Ollama.app/Contents/Resources/ollama"],
2965
+ provider: "Ollama",
2966
+ versionFlag: "--version"
2967
+ },
2968
+ {
2969
+ command: "aider",
2970
+ name: "Aider CLI",
2971
+ provider: "Aider",
2972
+ versionFlag: "--version"
2973
+ },
2974
+ {
2975
+ command: "cn",
2976
+ name: "Continue CLI",
2977
+ provider: "Continue",
2978
+ versionFlag: "--version"
2979
+ },
2980
+ {
2981
+ command: "cline",
2982
+ name: "Cline CLI",
2983
+ provider: "Cline",
2984
+ versionFlag: "--version"
2985
+ },
2986
+ {
2987
+ command: "droid",
2988
+ name: "Factory Droid CLI",
2989
+ provider: "Factory",
2990
+ versionFlag: "--version"
2991
+ },
2992
+ {
2993
+ command: "lms",
2994
+ name: "LM Studio CLI",
2995
+ provider: "LM Studio",
2996
+ versionFlag: "version"
2997
+ },
2998
+ {
2999
+ command: "opencode",
3000
+ name: "OpenCode CLI",
3001
+ provider: "OpenCode",
3002
+ versionFlag: "--version"
3003
+ }
3004
+ ];
3005
+ var VSCODE_CANDIDATES = [
3006
+ {
3007
+ extensionIds: ["anthropic.claude-code"],
3008
+ name: "Claude Code Extension",
3009
+ provider: "Anthropic"
3010
+ },
3011
+ {
3012
+ extensionIds: ["openai.chatgpt"],
3013
+ name: "Codex IDE Extension",
3014
+ provider: "OpenAI"
3015
+ },
3016
+ {
3017
+ extensionIds: ["codeium.codeium"],
3018
+ name: "Windsurf / Codeium Extension",
3019
+ provider: "Windsurf"
3020
+ },
3021
+ {
3022
+ extensionIds: ["github.copilot"],
3023
+ name: "GitHub Copilot",
3024
+ provider: "Microsoft"
3025
+ },
3026
+ {
3027
+ extensionIds: ["github.copilot-chat"],
3028
+ name: "GitHub Copilot Chat",
3029
+ provider: "Microsoft"
3030
+ },
3031
+ {
3032
+ extensionIds: ["google.geminicodeassist", "google.gemini-code-assist"],
3033
+ name: "Gemini Code Assist",
3034
+ provider: "Google"
3035
+ },
3036
+ {
3037
+ extensionIds: ["continue.continue"],
3038
+ name: "Continue",
3039
+ provider: "Continue"
3040
+ },
3041
+ {
3042
+ extensionIds: ["saoudrizwan.claude-dev"],
3043
+ name: "Cline",
3044
+ provider: "Cline"
3045
+ }
3046
+ ];
3047
+ function detectAll() {
3048
+ const results = [];
3049
+ for (const candidate of APP_CANDIDATES) {
3050
+ results.push(detectApp(candidate));
3051
+ }
3052
+ for (const candidate of CLI_CANDIDATES) {
3053
+ results.push(detectCli(candidate));
3054
+ }
3055
+ const extensions = getVscodeExtensions();
3056
+ for (const candidate of VSCODE_CANDIDATES) {
3057
+ results.push(detectVscode(candidate, extensions));
3058
+ }
3059
+ return results;
3060
+ }
3061
+ function printResults(results) {
3062
+ const providers = [
3063
+ "Anthropic",
3064
+ "OpenAI",
3065
+ "Cursor",
3066
+ "xAI",
3067
+ "Windsurf",
3068
+ "Google",
3069
+ "Kiro",
3070
+ "Microsoft",
3071
+ "Ollama",
3072
+ "Aider",
3073
+ "Continue",
3074
+ "Cline",
3075
+ "Factory",
3076
+ "LM Studio",
3077
+ "OpenCode"
3078
+ ];
3079
+ for (const provider of providers) {
3080
+ const clients = results.filter((c) => c.provider === provider);
3081
+ const found = clients.filter((c) => c.detected);
3082
+ console.log(chalk8.cyan(provider));
3083
+ if (found.length === 0) {
3084
+ console.log(chalk8.gray(" (none detected)"));
3085
+ } else {
3086
+ for (const client of found) {
3087
+ const info = [client.path, client.version].filter(Boolean).join(" ");
3088
+ console.log(` ${chalk8.green("+")} ${chalk8.white(client.name.padEnd(28))} ${chalk8.gray(info)}`);
3089
+ }
3090
+ }
3091
+ console.log();
3092
+ }
3093
+ const total = results.filter((c) => c.detected).length;
3094
+ console.log(chalk8.white(`${total} AI client${total === 1 ? "" : "s"} detected`));
3095
+ }
3096
+ function detectAiClients(json) {
3097
+ const results = detectAll();
3098
+ if (json) {
3099
+ console.log(JSON.stringify(results, null, 2));
3100
+ return;
3101
+ }
3102
+ printResults(results);
3103
+ }
3104
+
3105
+ // src/actions/printVersion.ts
3106
+ import chalk9 from "chalk";
3107
+ function printVersion() {
3108
+ console.log(chalk9.cyan("ariestools"));
3109
+ console.log(` Node: ${process.version}`);
3110
+ console.log(` Platform: ${process.platform}`);
3111
+ console.log(` Arch: ${process.arch}`);
3112
+ }
3113
+
3114
+ // src/actions/sync/syncAiConfig.ts
3115
+ import {
3116
+ copyFileSync,
3117
+ cpSync,
3118
+ existsSync as existsSync8,
3119
+ rmSync as rmSync4
3120
+ } from "fs";
3121
+ import path12 from "path";
3122
+ import chalk10 from "chalk";
3123
+ function resolveMapping(from, cwd) {
3124
+ if (from === "claude") {
3125
+ return {
3126
+ destDir: path12.join(cwd, ".agents"),
3127
+ destFile: path12.join(cwd, "AGENTS.md"),
3128
+ sourceDir: path12.join(cwd, ".claude"),
3129
+ sourceFile: path12.join(cwd, "CLAUDE.md")
3130
+ };
3131
+ }
3132
+ return {
3133
+ destDir: path12.join(cwd, ".claude"),
3134
+ destFile: path12.join(cwd, "CLAUDE.md"),
3135
+ sourceDir: path12.join(cwd, ".agents"),
3136
+ sourceFile: path12.join(cwd, "AGENTS.md")
3137
+ };
3138
+ }
3139
+ function syncAiConfig(from) {
3140
+ const cwd = process.cwd();
3141
+ const mapping = resolveMapping(from, cwd);
3142
+ if (!existsSync8(mapping.sourceDir)) {
3143
+ throw new Error(chalk10.red(`Source directory not found: ${mapping.sourceDir}`));
3144
+ }
3145
+ if (!existsSync8(mapping.sourceFile)) {
3146
+ throw new Error(chalk10.red(`Source file not found: ${mapping.sourceFile}`));
3147
+ }
3148
+ if (existsSync8(mapping.destDir)) {
3149
+ rmSync4(mapping.destDir, { recursive: true });
3150
+ }
3151
+ if (existsSync8(mapping.destFile)) {
3152
+ rmSync4(mapping.destFile);
3153
+ }
3154
+ cpSync(mapping.sourceDir, mapping.destDir, { recursive: true });
3155
+ copyFileSync(mapping.sourceFile, mapping.destFile);
3156
+ const label = from === "claude" ? "Claude \u2192 Codex" : "Codex \u2192 Claude";
3157
+ console.log(chalk10.green(`Synced ${label}:`));
3158
+ console.log(` ${path12.basename(mapping.sourceDir)}/ \u2192 ${path12.basename(mapping.destDir)}/`);
3159
+ console.log(` ${path12.basename(mapping.sourceFile)} \u2192 ${path12.basename(mapping.destFile)}`);
3160
+ }
3161
+
3162
+ // src/actions/wallet/account/deriveAndAdd.ts
3163
+ import chalk11 from "chalk";
3164
+
3165
+ // src/actions/wallet/paths.ts
3166
+ import OS from "os";
3167
+ import PATH from "path";
3168
+ function walletRoot() {
3169
+ const override = process.env.ARIES_WALLET_HOME;
3170
+ if (override) return override;
3171
+ return PATH.join(OS.homedir(), ".aries", "wallet");
3172
+ }
3173
+ function walletPaths(root = walletRoot()) {
3174
+ return {
3175
+ root,
3176
+ password: PATH.join(root, "password.json"),
3177
+ phrases: PATH.join(root, "phrases.json"),
3178
+ active: PATH.join(root, "active.json"),
3179
+ addressBooks: PATH.join(root, "address-books.json"),
3180
+ contacts: PATH.join(root, "contacts.json"),
3181
+ networks: PATH.join(root, "networks.json"),
3182
+ session: PATH.join(root, "session.json"),
3183
+ machineId: PATH.join(root, ".machine-id")
3184
+ };
3185
+ }
3186
+
3187
+ // src/actions/wallet/storage.ts
3188
+ import FS from "fs";
3189
+ import PATH2 from "path";
3190
+ function ensureWalletDir(root = walletRoot()) {
3191
+ if (!FS.existsSync(root)) {
3192
+ FS.mkdirSync(root, { recursive: true, mode: 448 });
3193
+ return;
3194
+ }
3195
+ try {
3196
+ FS.chmodSync(root, 448);
3197
+ } catch {
3198
+ }
3199
+ }
3200
+ function readJsonFile(file) {
3201
+ if (!FS.existsSync(file)) return void 0;
3202
+ const raw = FS.readFileSync(file, "utf8");
3203
+ if (raw.trim().length === 0) return void 0;
3204
+ return JSON.parse(raw);
3205
+ }
3206
+ function writeJsonFile(file, value) {
3207
+ ensureWalletDir(PATH2.dirname(file));
3208
+ const tmp = `${file}.tmp`;
3209
+ FS.writeFileSync(tmp, `${JSON.stringify(value, null, 2)}
3210
+ `, { mode: 384 });
3211
+ FS.renameSync(tmp, file);
3212
+ try {
3213
+ FS.chmodSync(file, 384);
3214
+ } catch {
3215
+ }
3216
+ }
3217
+ function deleteFile(file) {
3218
+ if (FS.existsSync(file)) FS.unlinkSync(file);
3219
+ }
3220
+
3221
+ // src/actions/wallet/addressBook/storage.ts
3222
+ var ADDRESS_BOOK_VERSION = 1;
3223
+ function readAllAddressBooks() {
3224
+ return readJsonFile(walletPaths().addressBooks) ?? {};
3225
+ }
3226
+ function writeAllAddressBooks(data) {
3227
+ writeJsonFile(walletPaths().addressBooks, data);
3228
+ }
3229
+ function readAddressBook(rootAddress) {
3230
+ const all = readAllAddressBooks();
3231
+ const key = rootAddress.toLowerCase();
3232
+ return all[key] ?? {
3233
+ rootAddress: key,
3234
+ entries: [{ offset: "0" }, { offset: "1" }, { offset: "2" }],
3235
+ version: ADDRESS_BOOK_VERSION
3236
+ };
3237
+ }
3238
+ function writeAddressBook(book) {
3239
+ const all = readAllAddressBooks();
3240
+ all[book.rootAddress.toLowerCase()] = book;
3241
+ writeAllAddressBooks(all);
3242
+ }
3243
+ function removeAddressBook(rootAddress) {
3244
+ const all = readAllAddressBooks();
3245
+ const key = rootAddress.toLowerCase();
3246
+ if (key in all) {
3247
+ delete all[key];
3248
+ writeAllAddressBooks(all);
3249
+ }
3250
+ }
3251
+ function upsertAddressBookEntry(rootAddress, entry) {
3252
+ const book = readAddressBook(rootAddress);
3253
+ const existing = book.entries.find((e) => e.offset === entry.offset);
3254
+ if (existing) {
3255
+ if (entry.label !== void 0) existing.label = entry.label;
3256
+ } else {
3257
+ book.entries.push(entry);
3258
+ }
3259
+ writeAddressBook(book);
3260
+ return book;
3261
+ }
3262
+ function removeAddressBookEntry(rootAddress, offset) {
3263
+ const book = readAddressBook(rootAddress);
3264
+ book.entries = book.entries.filter((e) => e.offset !== offset);
3265
+ writeAddressBook(book);
3266
+ return book;
3267
+ }
3268
+
3269
+ // src/actions/wallet/account/getActiveWallet.ts
3270
+ import { HDWallet } from "@xyo-network/sdk-js";
3271
+ import { DEFAULT_WALLET_PATH } from "@xyo-network/xl1-protocol-sdk";
3272
+
3273
+ // src/actions/wallet/prompt.ts
3274
+ import { execFileSync as execFileSync2 } from "child_process";
3275
+ import {
3276
+ closeSync as closeSync2,
3277
+ openSync as openSync2,
3278
+ readSync,
3279
+ writeSync as writeSync2
3280
+ } from "fs";
3281
+ var CTRL_C = 3;
3282
+ var ENTER = 13;
3283
+ var NEWLINE = 10;
3284
+ var BACKSPACE_DELETE = 127;
3285
+ var BACKSPACE = 8;
3286
+ function readChars(readFd, writeFd, mask) {
3287
+ const chars = [];
3288
+ const buf = Buffer.alloc(1);
3289
+ for (; ; ) {
3290
+ const bytes = readSync(readFd, buf, 0, 1, null);
3291
+ if (bytes === 0) break;
3292
+ const ch = buf[0];
3293
+ if (ch === ENTER || ch === NEWLINE) break;
3294
+ if (ch === CTRL_C) {
3295
+ writeSync2(writeFd, "\n");
3296
+ throw new Error("Aborted");
3297
+ }
3298
+ if (ch === BACKSPACE_DELETE || ch === BACKSPACE) {
3299
+ if (chars.length > 0) {
3300
+ chars.pop();
3301
+ writeSync2(writeFd, "\b \b");
3302
+ }
3303
+ continue;
3304
+ }
3305
+ chars.push(ch);
3306
+ writeSync2(writeFd, mask ? "*" : String.fromCodePoint(ch));
3307
+ }
3308
+ writeSync2(writeFd, "\n");
3309
+ return Buffer.from(chars).toString("utf8");
3310
+ }
3311
+ function saveStty(readFd) {
3312
+ try {
3313
+ return execFileSync2("stty", ["-g"], {
3314
+ stdio: [readFd, "pipe", "ignore"],
3315
+ encoding: "utf8"
3316
+ }).trim();
3317
+ } catch {
3318
+ return void 0;
3319
+ }
3320
+ }
3321
+ function applyStty(readFd, args) {
3322
+ try {
3323
+ execFileSync2("stty", args, { stdio: [readFd, "ignore", "ignore"] });
3324
+ } catch {
3325
+ }
3326
+ }
3327
+ function promptTty(options) {
3328
+ const readFd = openSync2("/dev/tty", "r");
3329
+ const writeFd = openSync2("/dev/tty", "w");
3330
+ const saved = saveStty(readFd);
3331
+ try {
3332
+ if (saved) applyStty(readFd, ["-echo", "-icanon", "min", "1", "time", "0"]);
3333
+ writeSync2(writeFd, options.prompt);
3334
+ return readChars(readFd, writeFd, options.mask === true);
3335
+ } finally {
3336
+ if (saved) applyStty(readFd, [saved]);
3337
+ try {
3338
+ closeSync2(readFd);
3339
+ } catch {
3340
+ }
3341
+ try {
3342
+ closeSync2(writeFd);
3343
+ } catch {
3344
+ }
3345
+ }
3346
+ }
3347
+ function promptPassword(prompt = "Password: ") {
3348
+ const env = process.env.ARIES_WALLET_PASSWORD;
3349
+ if (env !== void 0 && env.length > 0) return env;
3350
+ return promptTty({ prompt, mask: true });
3351
+ }
3352
+ function promptText(prompt) {
3353
+ return promptTty({ prompt, mask: false });
3354
+ }
3355
+
3356
+ // src/actions/wallet/session/sessionCache.ts
3357
+ import { webcrypto as webcrypto3 } from "crypto";
3358
+
3359
+ // src/actions/wallet/passwordKey.ts
3360
+ import { webcrypto } from "crypto";
3361
+ var subtle = webcrypto.subtle;
3362
+ var INITIALIZATION_VECTOR_LENGTH = 12;
3363
+ var PBKDF2_ITERATIONS = 1e5;
3364
+ var SALT_BYTES = 16;
3365
+ var PasswordKey = class _PasswordKey {
3366
+ password;
3367
+ salt;
3368
+ constructor(password, salt = _PasswordKey.generateSalt()) {
3369
+ this.password = password;
3370
+ this.salt = salt;
3371
+ }
3372
+ static async decryptString(key, data) {
3373
+ const encryptedData = new Uint8Array(Buffer.from(data, "base64"));
3374
+ const iv = encryptedData.slice(0, INITIALIZATION_VECTOR_LENGTH);
3375
+ const ciphertext = encryptedData.slice(INITIALIZATION_VECTOR_LENGTH);
3376
+ const decrypted = await subtle.decrypt({ name: "AES-GCM", iv }, key, ciphertext);
3377
+ return new TextDecoder("utf-8").decode(decrypted);
3378
+ }
3379
+ static async encryptString(key, data) {
3380
+ const iv = webcrypto.getRandomValues(new Uint8Array(INITIALIZATION_VECTOR_LENGTH));
3381
+ const ciphertext = await subtle.encrypt({ name: "AES-GCM", iv }, key, new TextEncoder().encode(data));
3382
+ const combined = new Uint8Array(iv.length + ciphertext.byteLength);
3383
+ combined.set(iv, 0);
3384
+ combined.set(new Uint8Array(ciphertext), iv.length);
3385
+ return Buffer.from(combined).toString("base64");
3386
+ }
3387
+ static generateSalt() {
3388
+ const array = new Uint8Array(SALT_BYTES);
3389
+ webcrypto.getRandomValues(array);
3390
+ return [...array].map((byte) => byte.toString(16).padStart(2, "0")).join("");
3391
+ }
3392
+ static async getHashFromKey(key) {
3393
+ const exported = await subtle.exportKey("raw", key);
3394
+ const digest = await subtle.digest("SHA-256", exported);
3395
+ return [...new Uint8Array(digest)].map((byte) => byte.toString(16).padStart(2, "0")).join("");
3396
+ }
3397
+ static async importEncryptionKey(rawKey) {
3398
+ return await subtle.importKey("raw", rawKey, { name: "AES-GCM" }, false, ["encrypt", "decrypt"]);
3399
+ }
3400
+ static async importExtractableKey(rawKey) {
3401
+ return await subtle.importKey("raw", rawKey, { name: "AES-GCM" }, true, ["encrypt", "decrypt"]);
3402
+ }
3403
+ static async serializeKey(key, salt = _PasswordKey.generateSalt()) {
3404
+ const hash = await _PasswordKey.getHashFromKey(key);
3405
+ return { hash, salt };
3406
+ }
3407
+ async deriveKey() {
3408
+ const encoder = new TextEncoder();
3409
+ const passphraseKey = await subtle.importKey(
3410
+ "raw",
3411
+ encoder.encode(this.password),
3412
+ { name: "PBKDF2" },
3413
+ false,
3414
+ ["deriveKey"]
3415
+ );
3416
+ return await subtle.deriveKey(
3417
+ {
3418
+ name: "PBKDF2",
3419
+ salt: encoder.encode(this.salt),
3420
+ iterations: PBKDF2_ITERATIONS,
3421
+ hash: "SHA-256"
3422
+ },
3423
+ passphraseKey,
3424
+ { name: "AES-GCM", length: 256 },
3425
+ true,
3426
+ ["encrypt", "decrypt"]
3427
+ );
3428
+ }
3429
+ };
3430
+ async function encryptWithKey(key, data) {
3431
+ const exported = await subtle.exportKey("raw", key);
3432
+ const encKey = await PasswordKey.importEncryptionKey(exported);
3433
+ return await PasswordKey.encryptString(encKey, data);
3434
+ }
3435
+ async function decryptWithKey(key, data) {
3436
+ const exported = await subtle.exportKey("raw", key);
3437
+ const encKey = await PasswordKey.importEncryptionKey(exported);
3438
+ return await PasswordKey.decryptString(encKey, data);
3439
+ }
3440
+
3441
+ // src/actions/wallet/session/machineId.ts
3442
+ import { webcrypto as webcrypto2 } from "crypto";
3443
+ import FS2 from "fs";
3444
+ import OS2 from "os";
3445
+ function generateMachineSecret() {
3446
+ const bytes = new Uint8Array(32);
3447
+ webcrypto2.getRandomValues(bytes);
3448
+ return [...bytes].map((b) => b.toString(16).padStart(2, "0")).join("");
3449
+ }
3450
+ function loadMachineSecret() {
3451
+ ensureWalletDir();
3452
+ const path13 = walletPaths().machineId;
3453
+ if (FS2.existsSync(path13)) {
3454
+ return FS2.readFileSync(path13, "utf8").trim();
3455
+ }
3456
+ const secret = generateMachineSecret();
3457
+ FS2.writeFileSync(path13, `${secret}
3458
+ `, { mode: 384 });
3459
+ try {
3460
+ FS2.chmodSync(path13, 384);
3461
+ } catch {
3462
+ }
3463
+ return secret;
3464
+ }
3465
+ async function deriveMachineKey() {
3466
+ const secret = loadMachineSecret();
3467
+ const stable = `${OS2.hostname()}:${OS2.userInfo().username}:${secret}`;
3468
+ const passwordKey = new PasswordKey(stable, "aries-wallet-machine-kek-v1");
3469
+ return await passwordKey.deriveKey();
3470
+ }
3471
+
3472
+ // src/actions/wallet/session/sessionCache.ts
3473
+ var subtle2 = webcrypto3.subtle;
3474
+ var DEFAULT_SESSION_TTL_SECONDS = 15 * 60;
3475
+ async function unlockSession(passwordKey, ttlSeconds = DEFAULT_SESSION_TTL_SECONDS) {
3476
+ const machineKey = await deriveMachineKey();
3477
+ const exported = await subtle2.exportKey("raw", passwordKey);
3478
+ const exportedBase64 = Buffer.from(new Uint8Array(exported)).toString("base64");
3479
+ const encryptedKey = await encryptWithKey(machineKey, exportedBase64);
3480
+ const expiresAt = Date.now() + ttlSeconds * 1e3;
3481
+ const data = { encryptedKey, expiresAt };
3482
+ writeJsonFile(walletPaths().session, data);
3483
+ return expiresAt;
3484
+ }
3485
+ function lockSession() {
3486
+ deleteFile(walletPaths().session);
3487
+ }
3488
+ async function readSession() {
3489
+ const data = readJsonFile(walletPaths().session);
3490
+ if (!data) return void 0;
3491
+ if (data.expiresAt <= Date.now()) {
3492
+ lockSession();
3493
+ return void 0;
3494
+ }
3495
+ try {
3496
+ const machineKey = await deriveMachineKey();
3497
+ const exportedBase64 = await decryptWithKey(machineKey, data.encryptedKey);
3498
+ const raw = Buffer.from(exportedBase64, "base64");
3499
+ return await PasswordKey.importExtractableKey(
3500
+ raw.buffer.slice(raw.byteOffset, raw.byteOffset + raw.byteLength)
3501
+ );
3502
+ } catch {
3503
+ lockSession();
3504
+ return void 0;
3505
+ }
3506
+ }
3507
+
3508
+ // src/actions/wallet/password/passwordStorage.ts
3509
+ function readPassword() {
3510
+ return readJsonFile(walletPaths().password);
3511
+ }
3512
+ function writePassword(values) {
3513
+ writeJsonFile(walletPaths().password, values);
3514
+ }
3515
+ function hasPassword() {
3516
+ return readPassword() !== void 0;
3517
+ }
3518
+
3519
+ // src/actions/wallet/password/validatePassword.ts
3520
+ async function validatePassword(password) {
3521
+ const stored = readPassword();
3522
+ if (!stored) return void 0;
3523
+ const passwordKey = new PasswordKey(password, stored.salt);
3524
+ const key = await passwordKey.deriveKey();
3525
+ const hash = await PasswordKey.getHashFromKey(key);
3526
+ if (hash !== stored.hash) return void 0;
3527
+ return key;
3528
+ }
3529
+
3530
+ // src/actions/wallet/password/getActiveKey.ts
3531
+ async function getActiveKey() {
3532
+ if (!hasPassword()) {
3533
+ throw new Error("Wallet not initialized. Run `aries wallet create` or `aries wallet import` first.");
3534
+ }
3535
+ const cached = await readSession();
3536
+ if (cached) return cached;
3537
+ const password = promptPassword("Wallet password: ");
3538
+ const key = await validatePassword(password);
3539
+ if (!key) throw new Error("Incorrect password.");
3540
+ return key;
3541
+ }
3542
+
3543
+ // src/actions/wallet/seedPhrase/phraseStorage.ts
3544
+ function readPhrases() {
3545
+ const data = readJsonFile(walletPaths().phrases);
3546
+ return data?.phrases ?? [];
3547
+ }
3548
+ function writePhrases(phrases) {
3549
+ writeJsonFile(walletPaths().phrases, { phrases });
3550
+ }
3551
+ function readActive() {
3552
+ return readJsonFile(walletPaths().active) ?? {};
3553
+ }
3554
+ function writeActive(active) {
3555
+ writeJsonFile(walletPaths().active, active);
3556
+ }
3557
+ function findPhrase(id) {
3558
+ return readPhrases().find((p) => p.id === id || p.label === id);
3559
+ }
3560
+ function getActivePhrase() {
3561
+ const phrases = readPhrases();
3562
+ if (phrases.length === 0) return void 0;
3563
+ const active = readActive();
3564
+ if (active.phraseId) {
3565
+ const found = phrases.find((p) => p.id === active.phraseId);
3566
+ if (found) return found;
3567
+ }
3568
+ return phrases[0];
3569
+ }
3570
+
3571
+ // src/actions/wallet/account/getActiveWallet.ts
3572
+ async function getActiveWallet() {
3573
+ const record = getActivePhrase();
3574
+ if (!record) throw new Error("No active wallet. Run `aries wallet create` or `aries wallet import` first.");
3575
+ const key = await getActiveKey();
3576
+ const mnemonic = await decryptWithKey(key, record.encryptedPhrase);
3577
+ const rootWallet = await HDWallet.fromPhrase(mnemonic, DEFAULT_WALLET_PATH);
3578
+ return {
3579
+ record,
3580
+ mnemonic,
3581
+ rootWallet
3582
+ };
3583
+ }
3584
+ async function deriveAccount(rootWallet, offset) {
3585
+ return await rootWallet.derivePath(offset);
3586
+ }
3587
+
3588
+ // src/actions/wallet/account/deriveAndAdd.ts
3589
+ async function deriveAndAdd(options) {
3590
+ const { rootWallet } = await getActiveWallet();
3591
+ const account = await deriveAccount(rootWallet, options.offset);
3592
+ upsertAddressBookEntry(rootWallet.address, { offset: options.offset, label: options.label });
3593
+ console.log(chalk11.green(`Derived account at offset ${chalk11.cyan(options.offset)}: 0x${account.address}`));
3594
+ if (options.label) console.log(chalk11.gray(` label: ${options.label}`));
3595
+ }
3596
+
3597
+ // src/actions/wallet/account/labelAccount.ts
3598
+ import chalk12 from "chalk";
3599
+ async function labelAccount(offset, label) {
3600
+ const { rootWallet } = await getActiveWallet();
3601
+ upsertAddressBookEntry(rootWallet.address, { offset, label });
3602
+ console.log(chalk12.green(`Labeled account ${chalk12.cyan(offset)} as ${chalk12.white(label)}`));
3603
+ }
3604
+
3605
+ // src/actions/wallet/account/listAccounts.ts
3606
+ import chalk13 from "chalk";
3607
+ async function listAccounts() {
3608
+ const { record, rootWallet } = await getActiveWallet();
3609
+ const book = readAddressBook(rootWallet.address);
3610
+ console.log(chalk13.cyan(`Wallet ${record.label} (${record.id})`));
3611
+ console.log(chalk13.gray(` root: ${rootWallet.address}`));
3612
+ console.log();
3613
+ if (book.entries.length === 0) {
3614
+ console.log(chalk13.gray(" No derived accounts. Run `aries wallet account derive <offset>`."));
3615
+ return;
3616
+ }
3617
+ for (const entry of book.entries) {
3618
+ const account = await deriveAccount(rootWallet, entry.offset);
3619
+ const offset = chalk13.cyan(entry.offset.padEnd(6));
3620
+ const label = chalk13.white((entry.label ?? "").padEnd(20));
3621
+ console.log(` ${offset} ${label} 0x${account.address}`);
3622
+ }
3623
+ }
3624
+
3625
+ // src/actions/wallet/account/removeAccount.ts
3626
+ import chalk14 from "chalk";
3627
+ async function removeAccount(offset) {
3628
+ const { rootWallet } = await getActiveWallet();
3629
+ removeAddressBookEntry(rootWallet.address, offset);
3630
+ console.log(chalk14.green(`Removed account at offset ${chalk14.cyan(offset)} from address book`));
3631
+ }
3632
+
3633
+ // src/actions/wallet/account/showAccount.ts
3634
+ import chalk15 from "chalk";
3635
+ async function showAccount(offset) {
3636
+ const { rootWallet } = await getActiveWallet();
3637
+ const book = readAddressBook(rootWallet.address);
3638
+ const entry = book.entries.find((e) => e.offset === offset);
3639
+ const account = await deriveAccount(rootWallet, offset);
3640
+ console.log(chalk15.cyan(`Account ${offset}`));
3641
+ console.log(` ${chalk15.gray("label:")} ${entry?.label ?? "\u2014"}`);
3642
+ console.log(` ${chalk15.gray("address:")} 0x${account.address}`);
3643
+ if (account.public) console.log(` ${chalk15.gray("public:")} ${account.public.hex}`);
3644
+ console.log(` ${chalk15.gray("path:")} ${offset}`);
3645
+ }
3646
+
3647
+ // src/actions/wallet/backup/exportBackup.ts
3648
+ import FS3 from "fs";
3649
+ import chalk16 from "chalk";
3650
+
3651
+ // src/actions/wallet/contact/storage.ts
3652
+ var CONTACTS_VERSION = 1;
3653
+ function readContacts() {
3654
+ return readJsonFile(walletPaths().contacts) ?? {
3655
+ entries: [],
3656
+ version: CONTACTS_VERSION
3657
+ };
3658
+ }
3659
+ function writeContacts(file) {
3660
+ writeJsonFile(walletPaths().contacts, file);
3661
+ }
3662
+
3663
+ // src/actions/wallet/backup/exportBackup.ts
3664
+ var SCHEMA = "network.xyo.wallet.backup";
3665
+ var VERSION = 1;
3666
+ var ADDRESS_BOOK_SCHEMA = "network.xyo.wallet.addressBook";
3667
+ var CONTACTS_SCHEMA = "network.xyo.wallet.contacts";
3668
+ function exportBackup(options) {
3669
+ const exportedAt = (/* @__PURE__ */ new Date()).toISOString();
3670
+ const entries = [];
3671
+ const sources = [];
3672
+ const addressBooks = readAllAddressBooks();
3673
+ for (const book of Object.values(addressBooks)) {
3674
+ entries.push({
3675
+ ...book,
3676
+ schema: ADDRESS_BOOK_SCHEMA,
3677
+ exportedAt
3678
+ });
3679
+ if (!sources.includes(ADDRESS_BOOK_SCHEMA)) sources.push(ADDRESS_BOOK_SCHEMA);
3680
+ }
3681
+ const contacts = readContacts();
3682
+ if (contacts.entries.length > 0) {
3683
+ entries.push({
3684
+ ...contacts,
3685
+ schema: CONTACTS_SCHEMA,
3686
+ exportedAt
3687
+ });
3688
+ sources.push(CONTACTS_SCHEMA);
3689
+ }
3690
+ const backup = {
3691
+ schema: SCHEMA,
3692
+ version: VERSION,
3693
+ entries,
3694
+ exportedAt,
3695
+ sources
3696
+ };
3697
+ FS3.writeFileSync(options.file, `${JSON.stringify(backup, null, 2)}
3698
+ `, { mode: 384 });
3699
+ console.log(chalk16.green(`Backup written to ${options.file}`));
3700
+ console.log(chalk16.gray(` ${entries.length} entries, sources: ${sources.join(", ")}`));
3701
+ }
3702
+
3703
+ // src/actions/wallet/backup/importBackup.ts
3704
+ import FS4 from "fs";
3705
+ import chalk17 from "chalk";
3706
+ function importBackup(options) {
3707
+ const raw = FS4.readFileSync(options.file, "utf8");
3708
+ const parsed = JSON.parse(raw);
3709
+ if (parsed.schema !== "network.xyo.wallet.backup") {
3710
+ throw new Error(`Not a wallet backup (schema=${parsed.schema}).`);
3711
+ }
3712
+ const allBooks = readAllAddressBooks();
3713
+ let booksImported = 0;
3714
+ let contactsImported = 0;
3715
+ const existingContacts = readContacts();
3716
+ for (const entry of parsed.entries) {
3717
+ if (entry.schema === "network.xyo.wallet.addressBook") {
3718
+ const book = entry;
3719
+ const key = book.rootAddress.toLowerCase();
3720
+ const merged = allBooks[key] ? mergeAddressBooks(allBooks[key], book) : {
3721
+ rootAddress: key,
3722
+ entries: book.entries,
3723
+ version: book.version
3724
+ };
3725
+ allBooks[key] = merged;
3726
+ booksImported++;
3727
+ } else if (entry.schema === "network.xyo.wallet.contacts") {
3728
+ const contacts = entry;
3729
+ for (const contact of contacts.entries) {
3730
+ upsertContact(existingContacts, contact);
3731
+ contactsImported++;
3732
+ }
3733
+ }
3734
+ }
3735
+ if (booksImported > 0) writeAllAddressBooks(allBooks);
3736
+ if (contactsImported > 0) writeContacts(existingContacts);
3737
+ console.log(chalk17.green(`Imported backup from ${options.file}`));
3738
+ console.log(chalk17.gray(` address books: ${booksImported}, contacts: ${contactsImported}`));
3739
+ }
3740
+ function mergeAddressBooks(existing, incoming) {
3741
+ const merged = {
3742
+ rootAddress: existing.rootAddress,
3743
+ version: Math.max(existing.version, incoming.version),
3744
+ entries: [...existing.entries]
3745
+ };
3746
+ for (const entry of incoming.entries) {
3747
+ const found = merged.entries.find((e) => e.offset === entry.offset);
3748
+ if (found) {
3749
+ if (entry.label !== void 0) found.label = entry.label;
3750
+ } else {
3751
+ merged.entries.push(entry);
3752
+ }
3753
+ }
3754
+ return merged;
3755
+ }
3756
+ function upsertContact(file, contact) {
3757
+ const normalized = contact.address.toLowerCase();
3758
+ const found = file.entries.find((e) => e.address.toLowerCase() === normalized);
3759
+ if (found) {
3760
+ found.label = contact.label;
3761
+ found.updatedAt = contact.updatedAt;
3762
+ } else {
3763
+ file.entries.push({ ...contact, address: normalized });
3764
+ }
3765
+ }
3766
+
3767
+ // src/actions/wallet/balance/getBalance.ts
3768
+ import { XL1Amount } from "@xyo-network/xl1-protocol-sdk";
3769
+ import chalk18 from "chalk";
3770
+
3771
+ // src/actions/wallet/client/walletClient.ts
3772
+ import {
3773
+ basicRemoteViewerLocator,
3774
+ ProviderFactoryLocator,
3775
+ SimpleXyoConnectionRunner,
3776
+ SimpleXyoGatewayRunner,
3777
+ SimpleXyoRunner,
3778
+ SimpleXyoSigner,
3779
+ XyoGatewayRunnerMoniker,
3780
+ XyoRunnerMoniker,
3781
+ XyoViewerMoniker
3782
+ } from "@xyo-network/xl1-sdk";
3783
+ async function loadValidators() {
3784
+ try {
3785
+ const mod = await import("@xyo-network/chain-validation");
3786
+ return {
3787
+ validateHydratedBlock: mod.validateHydratedBlock,
3788
+ validateHydratedBlockState: mod.validateHydratedBlockState
3789
+ };
3790
+ } catch {
3791
+ return void 0;
3792
+ }
3793
+ }
3794
+ async function createReadOnlyClient(rpcUrl) {
3795
+ const validators = await loadValidators();
3796
+ const viewerLocator = await basicRemoteViewerLocator(
3797
+ "aries-wallet-readonly",
3798
+ { rpc: { protocol: "http", url: rpcUrl } },
3799
+ void 0,
3800
+ validators ? { validators } : void 0
3801
+ );
3802
+ const viewer = await viewerLocator.getInstance(XyoViewerMoniker);
3803
+ return { viewer, locator: viewerLocator };
3804
+ }
3805
+ async function createWalletClient(rpcUrl, account) {
3806
+ const validators = await loadValidators();
3807
+ const viewerLocator = await basicRemoteViewerLocator(
3808
+ "aries-wallet",
3809
+ { rpc: { protocol: "http", url: rpcUrl } },
3810
+ void 0,
3811
+ validators ? { validators } : void 0
3812
+ );
3813
+ const locator = new ProviderFactoryLocator(viewerLocator.context, {});
3814
+ locator.register(SimpleXyoSigner.factory(SimpleXyoSigner.dependencies, { account }));
3815
+ locator.register(SimpleXyoGatewayRunner.factory(SimpleXyoGatewayRunner.dependencies, {}));
3816
+ locator.register(SimpleXyoRunner.factory(SimpleXyoRunner.dependencies, {}));
3817
+ locator.register(SimpleXyoConnectionRunner.factory(SimpleXyoConnectionRunner.dependencies, {}));
3818
+ locator.validateDependencies();
3819
+ const gateway = await locator.getInstance(XyoGatewayRunnerMoniker);
3820
+ const runner = await locator.getInstance(XyoRunnerMoniker);
3821
+ const viewer = await locator.getInstance(XyoViewerMoniker);
3822
+ return {
3823
+ gateway,
3824
+ runner,
3825
+ viewer,
3826
+ connection: gateway.connection,
3827
+ locator
3828
+ };
3829
+ }
3830
+
3831
+ // src/actions/wallet/network/storage.ts
3832
+ var DEFAULT_NETWORKS = [
3833
+ {
3834
+ id: "xl1-mainnet",
3835
+ label: "XL1 Mainnet",
3836
+ rpcUrl: "https://node.xyo.network",
3837
+ isCustom: false
3838
+ },
3839
+ {
3840
+ id: "xl1-testnet",
3841
+ label: "XL1 Testnet",
3842
+ rpcUrl: "https://testnet.node.xyo.network",
3843
+ isCustom: false
3844
+ }
3845
+ ];
3846
+ function readNetworks() {
3847
+ const data = readJsonFile(walletPaths().networks);
3848
+ if (data) return data;
3849
+ const seeded = {
3850
+ networks: DEFAULT_NETWORKS,
3851
+ activeId: DEFAULT_NETWORKS[0].id
3852
+ };
3853
+ writeJsonFile(walletPaths().networks, seeded);
3854
+ return seeded;
3855
+ }
3856
+ function writeNetworks(file) {
3857
+ writeJsonFile(walletPaths().networks, file);
3858
+ }
3859
+ function getActiveNetwork() {
3860
+ const file = readNetworks();
3861
+ const found = file.networks.find((n) => n.id === file.activeId);
3862
+ if (!found) throw new Error(`Active network ${file.activeId} not found.`);
3863
+ return found;
3864
+ }
3865
+
3866
+ // src/actions/wallet/balance/getBalance.ts
3867
+ async function getBalance(options = {}) {
3868
+ const offset = options.offset ?? "0";
3869
+ const { rootWallet } = await getActiveWallet();
3870
+ const account = await deriveAccount(rootWallet, offset);
3871
+ const network = getActiveNetwork();
3872
+ const { viewer } = await createReadOnlyClient(network.rpcUrl);
3873
+ const atto = await viewer.account.balance.accountBalance(account.address);
3874
+ const display = new XL1Amount(atto).toString();
3875
+ console.log(`${chalk18.cyan("balance:")} ${display} XL1`);
3876
+ console.log(`${chalk18.gray("atto:")} ${atto}`);
3877
+ console.log(`${chalk18.gray("address:")} 0x${account.address}`);
3878
+ console.log(`${chalk18.gray("network:")} ${network.id} (${network.rpcUrl})`);
3879
+ }
3880
+
3881
+ // src/actions/wallet/contact/contactActions.ts
3882
+ import chalk19 from "chalk";
3883
+ function normalize(address) {
3884
+ return address.toLowerCase();
3885
+ }
3886
+ function listContacts() {
3887
+ const file = readContacts();
3888
+ if (file.entries.length === 0) {
3889
+ console.log(chalk19.gray("No contacts. Run `aries wallet contact add <address> <label>` to add one."));
3890
+ return;
3891
+ }
3892
+ for (const entry of file.entries) {
3893
+ console.log(` ${chalk19.white(entry.label.padEnd(20))} ${entry.address}`);
3894
+ }
3895
+ }
3896
+ function addContact(address, label) {
3897
+ const file = readContacts();
3898
+ const now = (/* @__PURE__ */ new Date()).toISOString();
3899
+ const normalized = normalize(address);
3900
+ const existing = file.entries.find((e) => normalize(e.address) === normalized);
3901
+ if (existing) {
3902
+ existing.label = label;
3903
+ existing.updatedAt = now;
3904
+ } else {
3905
+ file.entries.push({
3906
+ address: normalized,
3907
+ label,
3908
+ createdAt: now,
3909
+ updatedAt: now
3910
+ });
3911
+ }
3912
+ writeContacts(file);
3913
+ console.log(chalk19.green(`Saved contact ${chalk19.cyan(label)} (${normalized})`));
3914
+ }
3915
+ function renameContact(address, label) {
3916
+ addContact(address, label);
3917
+ }
3918
+ function removeContact(address) {
3919
+ const file = readContacts();
3920
+ const normalized = normalize(address);
3921
+ const before = file.entries.length;
3922
+ file.entries = file.entries.filter((e) => normalize(e.address) !== normalized);
3923
+ if (file.entries.length === before) throw new Error(`Contact not found: ${address}`);
3924
+ writeContacts(file);
3925
+ console.log(chalk19.green(`Removed contact ${normalized}`));
3926
+ }
3927
+
3928
+ // src/actions/wallet/network/networkActions.ts
3929
+ import chalk20 from "chalk";
3930
+ function listNetworks() {
3931
+ const file = readNetworks();
3932
+ for (const network of file.networks) {
3933
+ const marker = network.id === file.activeId ? chalk20.green("* ") : " ";
3934
+ const id = chalk20.cyan(network.id.padEnd(20));
3935
+ const label = chalk20.white(network.label.padEnd(20));
3936
+ const custom = network.isCustom ? chalk20.gray("(custom)") : "";
3937
+ console.log(`${marker}${id} ${label} ${network.rpcUrl} ${custom}`);
3938
+ }
3939
+ }
3940
+ function useNetwork(id) {
3941
+ const file = readNetworks();
3942
+ const found = file.networks.find((n) => n.id === id);
3943
+ if (!found) throw new Error(`Network not found: ${id}`);
3944
+ file.activeId = id;
3945
+ writeNetworks(file);
3946
+ console.log(chalk20.green(`Active network set to ${chalk20.cyan(id)}`));
3947
+ }
3948
+ function addNetwork(options) {
3949
+ const file = readNetworks();
3950
+ if (file.networks.some((n) => n.id === options.id)) {
3951
+ throw new Error(`Network already exists: ${options.id}`);
3952
+ }
3953
+ const record = {
3954
+ id: options.id,
3955
+ label: options.label ?? options.id,
3956
+ rpcUrl: options.rpcUrl,
3957
+ chainId: options.chainId,
3958
+ isCustom: true
3959
+ };
3960
+ file.networks.push(record);
3961
+ writeNetworks(file);
3962
+ console.log(chalk20.green(`Added network ${chalk20.cyan(options.id)} (${options.rpcUrl})`));
3963
+ }
3964
+ function removeNetwork(id) {
3965
+ const file = readNetworks();
3966
+ const target = file.networks.find((n) => n.id === id);
3967
+ if (!target) throw new Error(`Network not found: ${id}`);
3968
+ if (!target.isCustom) throw new Error(`Cannot remove built-in network: ${id}`);
3969
+ file.networks = file.networks.filter((n) => n.id !== id);
3970
+ if (file.activeId === id) file.activeId = file.networks[0]?.id ?? "";
3971
+ writeNetworks(file);
3972
+ console.log(chalk20.green(`Removed network ${chalk20.cyan(id)}`));
3973
+ }
3974
+
3975
+ // src/actions/wallet/password/changePassword.ts
3976
+ import chalk21 from "chalk";
3977
+ async function changePassword() {
3978
+ const current = promptPassword("Current password: ");
3979
+ const oldKey = await validatePassword(current);
3980
+ if (!oldKey) throw new Error("Incorrect password.");
3981
+ const next = promptPassword("New password: ");
3982
+ const confirmed = promptPassword("Confirm new password: ");
3983
+ if (next !== confirmed) throw new Error("Passwords do not match.");
3984
+ if (next.length === 0) throw new Error("Password cannot be empty.");
3985
+ const salt = PasswordKey.generateSalt();
3986
+ const newKey = await new PasswordKey(next, salt).deriveKey();
3987
+ const phrases = readPhrases();
3988
+ for (const phrase of phrases) {
3989
+ const mnemonic = await decryptWithKey(oldKey, phrase.encryptedPhrase);
3990
+ phrase.encryptedPhrase = await encryptWithKey(newKey, mnemonic);
3991
+ }
3992
+ writePhrases(phrases);
3993
+ writePassword(await PasswordKey.serializeKey(newKey, salt));
3994
+ lockSession();
3995
+ console.log(chalk21.green("Password changed. Re-unlock to start a new session."));
3996
+ }
3997
+
3998
+ // src/actions/wallet/seedPhrase/createPhrase.ts
3999
+ import { HDWallet as HDWallet2 } from "@xyo-network/sdk-js";
4000
+ import chalk22 from "chalk";
4001
+
4002
+ // src/actions/wallet/password/setPassword.ts
4003
+ async function setPassword(password) {
4004
+ if (password.length === 0) throw new Error("Password cannot be empty");
4005
+ const salt = PasswordKey.generateSalt();
4006
+ const passwordKey = new PasswordKey(password, salt);
4007
+ const key = await passwordKey.deriveKey();
4008
+ const values = await PasswordKey.serializeKey(key, salt);
4009
+ writePassword(values);
4010
+ return { key, salt };
4011
+ }
4012
+
4013
+ // src/actions/wallet/password/initOrUnlock.ts
4014
+ async function initOrUnlock() {
4015
+ if (hasPassword()) return await getActiveKey();
4016
+ const fromEnv = process.env.ARIES_WALLET_PASSWORD;
4017
+ if (fromEnv !== void 0 && fromEnv.length > 0) {
4018
+ const { key: key2 } = await setPassword(fromEnv);
4019
+ return key2;
4020
+ }
4021
+ const password = promptPassword("Set wallet password: ");
4022
+ const confirmed = promptPassword("Confirm password: ");
4023
+ if (password !== confirmed) throw new Error("Passwords do not match.");
4024
+ const { key } = await setPassword(password);
4025
+ return key;
4026
+ }
4027
+
4028
+ // src/actions/wallet/seedPhrase/idGen.ts
4029
+ import { webcrypto as webcrypto4 } from "crypto";
4030
+ function generatePhraseId() {
4031
+ const bytes = new Uint8Array(8);
4032
+ webcrypto4.getRandomValues(bytes);
4033
+ return [...bytes].map((b) => b.toString(16).padStart(2, "0")).join("");
4034
+ }
4035
+
4036
+ // src/actions/wallet/seedPhrase/createPhrase.ts
4037
+ async function createPhrase(options) {
4038
+ const key = await initOrUnlock();
4039
+ const mnemonic = HDWallet2.generateMnemonic();
4040
+ const encryptedPhrase = await encryptWithKey(key, mnemonic);
4041
+ const record = {
4042
+ id: generatePhraseId(),
4043
+ label: options.label,
4044
+ walletKind: "user",
4045
+ encryptedPhrase,
4046
+ createdAt: Date.now()
4047
+ };
4048
+ const phrases = readPhrases();
4049
+ phrases.push(record);
4050
+ writePhrases(phrases);
4051
+ if (phrases.length === 1) writeActive({ phraseId: record.id });
4052
+ console.log(chalk22.green(`Created wallet ${chalk22.cyan(record.label)} (id ${record.id})`));
4053
+ console.log();
4054
+ console.log(chalk22.yellow("Recovery phrase \u2014 write this down and store it safely:"));
4055
+ console.log();
4056
+ console.log(` ${chalk22.white(mnemonic)}`);
4057
+ console.log();
4058
+ console.log(chalk22.gray("You will not be shown this phrase again unless you run `aries wallet export`."));
4059
+ return record;
4060
+ }
4061
+
4062
+ // src/actions/wallet/seedPhrase/exportPhrase.ts
4063
+ import chalk23 from "chalk";
4064
+ async function exportPhrase(options = {}) {
4065
+ const record = options.id ? findPhrase(options.id) : getActivePhrase();
4066
+ if (!record) throw new Error("Wallet not found.");
4067
+ const key = await getActiveKey();
4068
+ const mnemonic = await decryptWithKey(key, record.encryptedPhrase);
4069
+ console.log(chalk23.yellow(`Recovery phrase for ${chalk23.cyan(record.label)} (id ${record.id}):`));
4070
+ console.log();
4071
+ console.log(` ${chalk23.white(mnemonic)}`);
4072
+ return mnemonic;
4073
+ }
4074
+
4075
+ // src/actions/wallet/seedPhrase/importPhrase.ts
4076
+ import { HDWallet as HDWallet3 } from "@xyo-network/sdk-js";
4077
+ import chalk24 from "chalk";
4078
+ async function importPhrase(options) {
4079
+ const key = await initOrUnlock();
4080
+ const mnemonic = (options.phrase ?? promptText("Recovery phrase: ")).trim();
4081
+ if (mnemonic.split(/\s+/).length < 12) {
4082
+ throw new Error("Recovery phrase must be at least 12 words.");
4083
+ }
4084
+ await HDWallet3.fromPhrase(mnemonic);
4085
+ const encryptedPhrase = await encryptWithKey(key, mnemonic);
4086
+ const record = {
4087
+ id: generatePhraseId(),
4088
+ label: options.label,
4089
+ walletKind: "user",
4090
+ encryptedPhrase,
4091
+ createdAt: Date.now()
4092
+ };
4093
+ const phrases = readPhrases();
4094
+ phrases.push(record);
4095
+ writePhrases(phrases);
4096
+ if (phrases.length === 1) writeActive({ phraseId: record.id });
4097
+ console.log(chalk24.green(`Imported wallet ${chalk24.cyan(record.label)} (id ${record.id})`));
4098
+ return record;
4099
+ }
4100
+
4101
+ // src/actions/wallet/seedPhrase/listPhrases.ts
4102
+ import chalk25 from "chalk";
4103
+ function listPhrases() {
4104
+ const phrases = readPhrases();
4105
+ if (phrases.length === 0) {
4106
+ console.log(chalk25.gray("No wallets. Run `aries wallet create` or `aries wallet import` to add one."));
4107
+ return;
4108
+ }
4109
+ const active = readActive();
4110
+ for (const phrase of phrases) {
4111
+ const marker = phrase.id === active.phraseId ? chalk25.green("* ") : " ";
4112
+ const created = new Date(phrase.createdAt).toISOString();
4113
+ console.log(`${marker}${chalk25.cyan(phrase.label.padEnd(20))} ${chalk25.gray(phrase.id)} ${chalk25.gray(created)}`);
4114
+ }
4115
+ }
4116
+
4117
+ // src/actions/wallet/seedPhrase/removePhrase.ts
4118
+ import { HDWallet as HDWallet4 } from "@xyo-network/sdk-js";
4119
+ import { DEFAULT_WALLET_PATH as DEFAULT_WALLET_PATH2 } from "@xyo-network/xl1-protocol-sdk";
4120
+ import chalk26 from "chalk";
4121
+ async function removePhrase(options) {
4122
+ const phrases = readPhrases();
4123
+ const target = phrases.find((p) => p.id === options.id || p.label === options.id);
4124
+ if (!target) throw new Error(`Wallet not found: ${options.id}`);
4125
+ try {
4126
+ const key = await getActiveKey();
4127
+ const mnemonic = await decryptWithKey(key, target.encryptedPhrase);
4128
+ const root = await HDWallet4.fromPhrase(mnemonic, DEFAULT_WALLET_PATH2);
4129
+ removeAddressBook(root.address);
4130
+ } catch (e) {
4131
+ console.warn(chalk26.yellow(`Warning: failed to clean up address book: ${e.message}`));
4132
+ }
4133
+ const remaining = phrases.filter((p) => p.id !== target.id);
4134
+ writePhrases(remaining);
4135
+ const active = readActive();
4136
+ if (active.phraseId === target.id) {
4137
+ writeActive({ ...active, phraseId: remaining[0]?.id });
4138
+ }
4139
+ console.log(chalk26.green(`Removed wallet ${chalk26.cyan(target.label)} (id ${target.id})`));
4140
+ }
4141
+
4142
+ // src/actions/wallet/seedPhrase/renamePhrase.ts
4143
+ import chalk27 from "chalk";
4144
+ function renamePhrase(id, label) {
4145
+ const phrases = readPhrases();
4146
+ const target = phrases.find((p) => p.id === id || p.label === id);
4147
+ if (!target) throw new Error(`Wallet not found: ${id}`);
4148
+ target.label = label;
4149
+ writePhrases(phrases);
4150
+ console.log(chalk27.green(`Renamed wallet ${target.id} to ${chalk27.cyan(label)}`));
4151
+ }
4152
+
4153
+ // src/actions/wallet/seedPhrase/usePhrase.ts
4154
+ import chalk28 from "chalk";
4155
+ function usePhrase(id) {
4156
+ const record = findPhrase(id);
4157
+ if (!record) throw new Error(`Wallet not found: ${id}`);
4158
+ const active = readActive();
4159
+ writeActive({ ...active, phraseId: record.id });
4160
+ console.log(chalk28.green(`Active wallet set to ${chalk28.cyan(record.label)} (id ${record.id})`));
4161
+ }
4162
+
4163
+ // src/actions/wallet/session/unlock.ts
4164
+ import chalk29 from "chalk";
4165
+ async function unlock(options = {}) {
4166
+ if (!hasPassword()) {
4167
+ throw new Error("Wallet not initialized. Run `aries wallet create` or `aries wallet import` first.");
4168
+ }
4169
+ const password = promptPassword("Wallet password: ");
4170
+ const key = await validatePassword(password);
4171
+ if (!key) throw new Error("Incorrect password.");
4172
+ const ttl = options.ttl ?? DEFAULT_SESSION_TTL_SECONDS;
4173
+ const expiresAt = await unlockSession(key, ttl);
4174
+ console.log(chalk29.green(`Wallet unlocked. Session expires ${new Date(expiresAt).toISOString()}.`));
4175
+ }
4176
+ function lock() {
4177
+ lockSession();
4178
+ console.log(chalk29.green("Wallet locked."));
4179
+ }
4180
+
4181
+ // src/actions/wallet/sign/signPayload.ts
4182
+ import FS5 from "fs";
4183
+
4184
+ // ../../node_modules/.pnpm/@xyo-network+boundwitness-builder@5.5.2_@bitauth+libauth@3.0.0_@scure+base@2.2.0_@xylab_4c4b2704d625c906bfa16bd14f65b27b/node_modules/@xyo-network/boundwitness-builder/dist/neutral/index.mjs
4185
+ import {
4186
+ asAddress,
4187
+ asHash,
4188
+ assertEx,
4189
+ hexFromArrayBuffer,
4190
+ toArrayBuffer
4191
+ } from "@xylabs/sdk-js";
4192
+
4193
+ // ../../node_modules/.pnpm/@xyo-network+boundwitness-model@5.5.2_@xylabs+sdk-js@5.0.101_@opentelemetry+api@1.9.1_@_815cc9f8526e164e787cddfcee3cd298/node_modules/@xyo-network/boundwitness-model/dist/neutral/index.mjs
4194
+ import {
4195
+ AddressZod,
4196
+ HashZod,
4197
+ zodAsFactory,
4198
+ zodIsFactory,
4199
+ zodToFactory
4200
+ } from "@xylabs/sdk-js";
4201
+ import { PayloadZod, SchemaZod } from "@xyo-network/payload-model";
4202
+ import z2 from "zod";
4203
+ import { asSchema } from "@xyo-network/payload-model";
4204
+ import { HexZod } from "@xylabs/sdk-js";
4205
+ import z from "zod";
4206
+ import { PayloadZod as PayloadZod2 } from "@xyo-network/payload-model";
4207
+ import z3 from "zod";
4208
+ import { isStorageMeta } from "@xyo-network/payload-model";
4209
+ var BoundWitnessSchema = asSchema("network.xyo.boundwitness", true);
4210
+ var SignaturesMetaZod = z.object({ $signatures: z.array(z.union([HexZod, z.null()])) });
4211
+ var UnsignedSignaturesMetaZod = z.object({ $signatures: z.array(z.null()) });
4212
+ var SignedSignaturesMetaZod = z.object({ $signatures: z.array(HexZod).min(1) });
4213
+ var BoundWitnessRequiredFieldsZod = z2.object({
4214
+ addresses: z2.array(AddressZod),
4215
+ payload_hashes: z2.array(HashZod),
4216
+ payload_schemas: z2.array(SchemaZod),
4217
+ previous_hashes: z2.array(HashZod.nullable())
4218
+ });
4219
+ var BoundWitnessMetaZod = z2.object({
4220
+ $destination: AddressZod.optional(),
4221
+ $sourceQuery: HashZod.optional()
4222
+ }).extend(SignaturesMetaZod.shape);
4223
+ var BoundWitnessZod = PayloadZod.safeExtend({ schema: z2.literal(BoundWitnessSchema) }).safeExtend(BoundWitnessRequiredFieldsZod.shape).safeExtend(BoundWitnessMetaZod.shape);
4224
+ var isBoundWitness = zodIsFactory(BoundWitnessZod);
4225
+ var asBoundWitness = zodAsFactory(BoundWitnessZod, "asBoundWitness");
4226
+ var toBoundWitness = zodToFactory(BoundWitnessZod, "toBoundWitness");
4227
+ var AnyBoundWitnessZod = BoundWitnessZod.loose();
4228
+ var SignedBoundWitnessZod = BoundWitnessZod.extend(SignedSignaturesMetaZod.shape);
4229
+ var AnySignedBoundWitnessZod = SignedBoundWitnessZod.loose();
4230
+ var UnsignedBoundWitnessZod = BoundWitnessZod.extend(UnsignedSignaturesMetaZod.shape);
4231
+ var AnyUnsignedBoundWitnessZod = UnsignedBoundWitnessZod.loose();
4232
+ function HydratedBoundWitnessZodBuilder(bwZod) {
4233
+ return z3.tuple([bwZod, z3.array(PayloadZod2.loose())]);
4234
+ }
4235
+ var HydratedBoundWitnessZod = HydratedBoundWitnessZodBuilder(BoundWitnessZod);
4236
+ var SignedHydratedBoundWitnessZod = HydratedBoundWitnessZodBuilder(SignedBoundWitnessZod);
4237
+ var UnsignedHydratedBoundWitnessZod = HydratedBoundWitnessZodBuilder(UnsignedBoundWitnessZod);
4238
+
4239
+ // ../../node_modules/.pnpm/@xyo-network+boundwitness-builder@5.5.2_@bitauth+libauth@3.0.0_@scure+base@2.2.0_@xylab_4c4b2704d625c906bfa16bd14f65b27b/node_modules/@xyo-network/boundwitness-builder/dist/neutral/index.mjs
4240
+ import {
4241
+ ObjectHasher,
4242
+ removeEmptyFields,
4243
+ sortFields
4244
+ } from "@xyo-network/hash";
4245
+ import { omitSchema, PayloadBuilder } from "@xyo-network/payload-builder";
4246
+ import { Mutex } from "async-mutex";
4247
+ import {
4248
+ asHash as asHash2,
4249
+ difference,
4250
+ exists
4251
+ } from "@xylabs/sdk-js";
4252
+ import { PayloadBuilder as PayloadBuilder2 } from "@xyo-network/payload-builder";
4253
+ import { asHash as asHash3 } from "@xylabs/sdk-js";
4254
+ import { assertEx as assertEx2 } from "@xylabs/sdk-js";
4255
+ var GeneratedBoundWitnessFields = ["addresses", "payload_hashes", "payload_schemas", "previous_hashes"];
4256
+ var uniqueAddresses = (addresses, throwOnFalse = false) => {
4257
+ const addressesSet = /* @__PURE__ */ new Set();
4258
+ for (const address of addresses) {
4259
+ if (addressesSet.has(address)) {
4260
+ if (throwOnFalse) {
4261
+ throw new Error("Duplicate address");
4262
+ }
4263
+ return false;
4264
+ }
4265
+ addressesSet.add(address);
4266
+ }
4267
+ return true;
4268
+ };
4269
+ var uniqueAccounts = (accounts, throwOnFalse = false) => {
4270
+ return uniqueAddresses(accounts.map((account) => account.address), throwOnFalse);
4271
+ };
4272
+ var BoundWitnessBuilder = class _BoundWitnessBuilder extends PayloadBuilder {
4273
+ static _buildMutex = new Mutex();
4274
+ _accounts = [];
4275
+ _errorHashes;
4276
+ _errors = [];
4277
+ _payloadHashes;
4278
+ _payloadSchemas;
4279
+ _payloads = [];
4280
+ constructor(options) {
4281
+ super({ ...options, schema: BoundWitnessSchema });
4282
+ }
4283
+ get addresses() {
4284
+ uniqueAccounts(this._accounts, true);
4285
+ return this._accounts.map((account) => account.address.toLowerCase());
4286
+ }
4287
+ get payloadSchemas() {
4288
+ return this._payloadSchemas ?? this._payloads.map((payload) => {
4289
+ return assertEx(payload.schema, () => this.missingSchemaMessage(payload));
4290
+ });
4291
+ }
4292
+ get previousHashBytes() {
4293
+ return this._accounts.map((account) => account.previousHashBytes ?? null);
4294
+ }
4295
+ get previousHashes() {
4296
+ return this._accounts.map((account) => account.previousHash ?? null);
4297
+ }
4298
+ static addressIndex(payload, address) {
4299
+ const index = payload.addresses.indexOf(address);
4300
+ if (index === -1) {
4301
+ throw new Error("Invalid address");
4302
+ }
4303
+ return index;
4304
+ }
4305
+ static previousHash(boundWitness, address) {
4306
+ return asHash(boundWitness.previous_hashes[this.addressIndex(boundWitness, address)])?.toLowerCase();
4307
+ }
4308
+ static async linkingFields(accounts, payloads) {
4309
+ const addresses = accounts.map((account) => asAddress(hexFromArrayBuffer(account.addressBytes, { prefix: false }), true));
4310
+ const previous_hashes = accounts.map((account) => account.previousHash ?? null);
4311
+ const payload_hashes = payloads ? await _BoundWitnessBuilder.hashes(payloads) : [];
4312
+ const payload_schemas = payloads?.map(({ schema }) => schema) ?? [];
4313
+ return {
4314
+ addresses,
4315
+ payload_hashes,
4316
+ payload_schemas,
4317
+ previous_hashes
4318
+ };
4319
+ }
4320
+ static signature(payload, address) {
4321
+ return payload.$signatures[this.addressIndex(payload, address)];
4322
+ }
4323
+ static async signatures(accounts, dataHash) {
4324
+ const hashBytes = toArrayBuffer(dataHash);
4325
+ const previousHashesBytes = accounts?.map((account) => account.previousHashBytes);
4326
+ return await Promise.all(accounts.map(async (account, index) => hexFromArrayBuffer((await account.sign(hashBytes, previousHashesBytes[index]))[0])));
4327
+ }
4328
+ static validateGeneratedFields(fields) {
4329
+ assertEx(fields.payload_hashes?.length === fields.payload_schemas?.length, () => "Payload hash/schema mismatch");
4330
+ assertEx(!fields.payload_hashes.includes(null), () => "nulls found in hashes");
4331
+ assertEx(!fields.payload_schemas.includes(null), () => "nulls found in schemas");
4332
+ }
4333
+ async build(sign = true) {
4334
+ return await _BoundWitnessBuilder._buildMutex.runExclusive(async () => {
4335
+ const dataHashableFields = await this.dataHashableFields();
4336
+ const $signatures = sign ? await this.sign() : this.addresses.map(() => null);
4337
+ const ret = {
4338
+ ...this._meta,
4339
+ ...dataHashableFields,
4340
+ ...this._fields,
4341
+ $signatures
4342
+ };
4343
+ return [
4344
+ ret,
4345
+ this._payloads,
4346
+ this._errors
4347
+ ];
4348
+ });
4349
+ }
4350
+ async dataHash() {
4351
+ const dataHashableFields = await this.dataHashableFields();
4352
+ const hash = await ObjectHasher.hash(dataHashableFields);
4353
+ return hash;
4354
+ }
4355
+ async dataHashableFields() {
4356
+ const generatedFields = await this.generatedFields();
4357
+ _BoundWitnessBuilder.validateGeneratedFields(generatedFields);
4358
+ const fields = {
4359
+ ...PayloadBuilder.omitMeta(this._fields ?? {}),
4360
+ ...generatedFields
4361
+ };
4362
+ return await _BoundWitnessBuilder.dataHashableFields(this._schema, fields);
4363
+ }
4364
+ error(payload) {
4365
+ assertEx(this._errorHashes === void 0, () => "Can not set errors when hashes already set");
4366
+ if (payload) {
4367
+ this._errors.push(assertEx(sortFields(payload)));
4368
+ }
4369
+ return this;
4370
+ }
4371
+ errors(errors) {
4372
+ if (errors) {
4373
+ for (const error of errors) {
4374
+ if (error !== null) {
4375
+ this.error(error);
4376
+ }
4377
+ }
4378
+ }
4379
+ return this;
4380
+ }
4381
+ fields(fields) {
4382
+ const clone = structuredClone(fields);
4383
+ for (const field of GeneratedBoundWitnessFields) {
4384
+ delete clone[field];
4385
+ }
4386
+ this._fields = _BoundWitnessBuilder.omitStorageMeta(
4387
+ _BoundWitnessBuilder.omitClientMeta(
4388
+ omitSchema(removeEmptyFields(clone))
4389
+ )
4390
+ );
4391
+ return this;
4392
+ }
4393
+ hashes(hashes, schema) {
4394
+ assertEx(this.payloads.length === 0, () => "Can not set hashes when payloads already set");
4395
+ this._payloadHashes = hashes;
4396
+ this._payloadSchemas = schema;
4397
+ return this;
4398
+ }
4399
+ payload(payload) {
4400
+ assertEx(this._payloadHashes === void 0, () => "Can not set payloads when hashes already set");
4401
+ if (payload) {
4402
+ this._payloads.push(assertEx(sortFields(payload)));
4403
+ }
4404
+ return this;
4405
+ }
4406
+ payloads(payloads) {
4407
+ if (payloads)
4408
+ for (const payload of payloads) {
4409
+ if (payload !== null) {
4410
+ this.payload(payload);
4411
+ }
4412
+ }
4413
+ return this;
4414
+ }
4415
+ signer(account) {
4416
+ uniqueAccounts([...this._accounts, account], true);
4417
+ this._accounts?.push(account);
4418
+ return this;
4419
+ }
4420
+ signers(accounts) {
4421
+ uniqueAccounts([...this._accounts, ...accounts], true);
4422
+ this._accounts?.push(...accounts);
4423
+ return this;
4424
+ }
4425
+ sourceQuery(sourceQuery) {
4426
+ this._meta = {
4427
+ ...this._meta,
4428
+ $sourceQuery: sourceQuery
4429
+ };
4430
+ return this;
4431
+ }
4432
+ /** @deprecated use signer instead */
4433
+ witness(account) {
4434
+ this._accounts?.push(account);
4435
+ return this;
4436
+ }
4437
+ /** @deprecated use signers instead */
4438
+ witnesses(accounts) {
4439
+ this._accounts?.push(...accounts);
4440
+ return this;
4441
+ }
4442
+ async sign() {
4443
+ uniqueAccounts(this._accounts, true);
4444
+ const hashBytes = toArrayBuffer(await this.dataHash());
4445
+ return await Promise.all(this._accounts.map(async (account) => hexFromArrayBuffer((await account.sign(hashBytes))[0])));
4446
+ }
4447
+ async generatedFields() {
4448
+ return await _BoundWitnessBuilder.linkingFields(this._accounts, this._payloads);
4449
+ }
4450
+ missingSchemaMessage(payload) {
4451
+ return `Builder: Missing Schema
4452
+ ${JSON.stringify(payload, null, 2)}`;
4453
+ }
4454
+ };
4455
+
4456
+ // src/actions/wallet/sign/signPayload.ts
4457
+ import chalk30 from "chalk";
4458
+ async function signPayload(options) {
4459
+ const offset = options.offset ?? "0";
4460
+ const raw = FS5.readFileSync(options.file, "utf8");
4461
+ const payload = JSON.parse(raw);
4462
+ if (typeof payload.schema !== "string" || payload.schema.length === 0) {
4463
+ throw new Error("Payload must have a non-empty `schema` string field.");
4464
+ }
4465
+ const { rootWallet } = await getActiveWallet();
4466
+ const account = await deriveAccount(rootWallet, offset);
4467
+ const [boundwitness, payloads] = await new BoundWitnessBuilder().payload(payload).signer(account).build();
4468
+ const result = { boundwitness, payloads };
4469
+ const json = JSON.stringify(result, null, 2);
4470
+ if (options.output) {
4471
+ FS5.writeFileSync(options.output, `${json}
4472
+ `);
4473
+ console.log(chalk30.green(`Signed payload written to ${options.output}`));
4474
+ } else {
4475
+ console.log(json);
4476
+ }
4477
+ }
4478
+
4479
+ // src/actions/wallet/transaction/broadcastTransaction.ts
4480
+ import FS6 from "fs";
4481
+ import chalk31 from "chalk";
4482
+ function reviveBigints(_key, value) {
4483
+ if (typeof value === "string" && /^-?\d+n$/.test(value)) {
4484
+ return BigInt(value.slice(0, -1));
4485
+ }
4486
+ return value;
4487
+ }
4488
+ async function broadcastTransaction(options) {
4489
+ const offset = options.offset ?? "0";
4490
+ const raw = FS6.readFileSync(options.file, "utf8");
4491
+ const signedTx = JSON.parse(raw, reviveBigints);
4492
+ const network = getActiveNetwork();
4493
+ const { rootWallet } = await getActiveWallet();
4494
+ const account = await deriveAccount(rootWallet, offset);
4495
+ console.log(chalk31.gray(`Connecting to ${network.rpcUrl}...`));
4496
+ const { runner } = await createWalletClient(network.rpcUrl, account);
4497
+ const hash = await runner.broadcastTransaction(signedTx);
4498
+ console.log(chalk31.green(`Broadcast accepted: ${hash}`));
4499
+ }
4500
+
4501
+ // src/actions/wallet/transaction/sendTransaction.ts
4502
+ import { asAddress as asAddress2, assertEx as assertEx3 } from "@xylabs/sdk-js";
4503
+ import { XL1Amount as XL1Amount2 } from "@xyo-network/xl1-protocol-sdk";
4504
+ import chalk32 from "chalk";
4505
+ async function sendTransaction(options) {
4506
+ const offset = options.offset ?? "0";
4507
+ const { rootWallet } = await getActiveWallet();
4508
+ const account = await deriveAccount(rootWallet, offset);
4509
+ const network = getActiveNetwork();
4510
+ const recipient = assertEx3(asAddress2(options.recipient.toLowerCase().replace(/^0x/, "")), () => `Invalid recipient address: ${options.recipient}`);
4511
+ const amountXL1 = XL1Amount2.fromXL1(BigInt(options.amount));
4512
+ console.log(chalk32.gray(`Connecting to ${network.rpcUrl}...`));
4513
+ const { gateway } = await createWalletClient(network.rpcUrl, account);
4514
+ console.log(chalk32.gray(`Submitting transfer of ${options.amount} XL1 to 0x${recipient}...`));
4515
+ const hash = await gateway.send(recipient, amountXL1.atto);
4516
+ console.log(chalk32.gray(`Tx submitted: ${hash}`));
4517
+ const attempts = options.attempts ?? 30;
4518
+ const delay = options.delay ?? 2e3;
4519
+ console.log(chalk32.gray(`Confirming (up to ${attempts} attempts, ${delay}ms apart)...`));
4520
+ await gateway.confirmSubmittedTransaction(hash, { attempts, delay });
4521
+ console.log(chalk32.green(`Sent ${options.amount} XL1 \u2192 0x${recipient}`));
4522
+ console.log(`${chalk32.gray("hash:")} ${hash}`);
4523
+ console.log(`${chalk32.gray("from:")} 0x${account.address}`);
4524
+ console.log(`${chalk32.gray("network:")} ${network.id}`);
4525
+ }
4526
+
4527
+ // src/actions/wallet/transaction/signTransactionFile.ts
4528
+ import FS7 from "fs";
4529
+ import { buildTransaction } from "@xyo-network/xl1-protocol-sdk";
4530
+ import chalk33 from "chalk";
4531
+ function asBigint(value) {
4532
+ return typeof value === "bigint" ? value : BigInt(value);
4533
+ }
4534
+ async function signTransactionFile(options) {
4535
+ const offset = options.offset ?? "0";
4536
+ const raw = FS7.readFileSync(options.file, "utf8");
4537
+ const tx = JSON.parse(raw);
4538
+ const { rootWallet } = await getActiveWallet();
4539
+ const account = await deriveAccount(rootWallet, offset);
4540
+ const fees = tx.fees ? {
4541
+ base: asBigint(tx.fees.base),
4542
+ gasLimit: asBigint(tx.fees.gasLimit),
4543
+ gasPrice: asBigint(tx.fees.gasPrice),
4544
+ priority: asBigint(tx.fees.priority)
4545
+ } : void 0;
4546
+ const signed = await buildTransaction(
4547
+ tx.chain,
4548
+ tx.onChainPayloads ?? [],
4549
+ tx.offChainPayloads ?? [],
4550
+ account,
4551
+ asBigint(tx.nbf),
4552
+ asBigint(tx.exp),
4553
+ void 0,
4554
+ fees
4555
+ );
4556
+ const serialized = JSON.stringify(signed, (_key, value) => typeof value === "bigint" ? value.toString() : value, 2);
4557
+ if (options.output) {
4558
+ FS7.writeFileSync(options.output, `${serialized}
4559
+ `);
4560
+ console.log(chalk33.green(`Signed transaction written to ${options.output}`));
4561
+ } else {
4562
+ console.log(serialized);
4563
+ }
4564
+ }
4565
+
4566
+ // src/actions/index.ts
4567
+ import { executeWitness, registerWitnessCommand } from "@xylabs/aries-witness-cli";
4568
+ export {
4569
+ addContact,
4570
+ addNetwork,
4571
+ broadcastTransaction,
4572
+ changePassword,
4573
+ createPhrase,
4574
+ deriveAccount,
4575
+ deriveAndAdd,
4576
+ detectAiClients,
4577
+ executeWitness,
4578
+ exportBackup,
4579
+ exportPhrase,
4580
+ getActiveWallet,
4581
+ getBalance,
4582
+ hasPassword,
4583
+ importBackup,
4584
+ importPhrase,
4585
+ installPlugin,
4586
+ labelAccount,
4587
+ listAccounts,
4588
+ listContacts,
4589
+ listNetworks,
4590
+ listPhrases,
4591
+ listSessions,
4592
+ lock,
4593
+ printVersion,
4594
+ registerWitnessCommand,
4595
+ removeAccount,
4596
+ removeContact,
4597
+ removeNetwork,
4598
+ removePhrase,
4599
+ renameContact,
4600
+ renamePhrase,
4601
+ runClamped,
4602
+ searchAudit,
4603
+ sendTransaction,
4604
+ showAccount,
4605
+ showSession,
4606
+ signPayload,
4607
+ signTransactionFile,
4608
+ statusAudit,
4609
+ syncAiConfig,
4610
+ uninstallPlugin,
4611
+ unlock,
4612
+ useNetwork,
4613
+ usePhrase
4614
+ };
4615
+ //# sourceMappingURL=index.mjs.map