aegisone 1.0.34 → 1.0.37

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 (372) hide show
  1. package/LICENSE +661 -0
  2. package/README.md +1 -1
  3. package/SOURCE-OFFER.txt +9 -0
  4. package/bin/aegis.js +1 -322
  5. package/package.json +4 -5
  6. package/scripts/bump.mjs +1 -211
  7. package/scripts/bundle.js +1 -129
  8. package/scripts/predist.mjs +1 -976
  9. package/src/child.js +1 -285
  10. package/src/dispatch.js +1 -269
  11. package/src/doctor.js +1 -639
  12. package/src/host.js +1 -111
  13. package/src/iface/paths.js +3 -0
  14. package/src/iface/pty.js +3 -0
  15. package/src/iface/update.js +3 -0
  16. package/src/iface/window.js +3 -0
  17. package/src/permissions.js +1 -383
  18. package/src/probes.js +1 -159
  19. package/src/protocol.js +3 -0
  20. package/src/release.js +1 -409
  21. package/src/selfhost.js +3 -0
  22. package/vendor/cli/package.json +3 -7
  23. package/vendor/cli/scripts/check.mjs +1 -52
  24. package/vendor/cli/scripts/demo.mjs +1 -94
  25. package/vendor/cli/scripts/predist.mjs +1 -75
  26. package/vendor/cli/scripts/runtests.mjs +1 -56
  27. package/vendor/cli/scripts/seal-gate.mjs +1 -74
  28. package/vendor/cli/src/agents.js +1 -139
  29. package/vendor/cli/src/app.js +1 -2957
  30. package/vendor/cli/src/art.js +1 -289
  31. package/vendor/cli/src/chatflow.js +1 -3023
  32. package/vendor/cli/src/checkpoint.js +1 -90
  33. package/vendor/cli/src/clipboard.js +1 -424
  34. package/vendor/cli/src/cloudsync.js +1 -528
  35. package/vendor/cli/src/commands.js +1 -4089
  36. package/vendor/cli/src/config.js +1 -581
  37. package/vendor/cli/src/connect.js +1 -349
  38. package/vendor/cli/src/credentials.js +1 -33
  39. package/vendor/cli/src/deps.js +1 -232
  40. package/vendor/cli/src/devrun.js +1 -187
  41. package/vendor/cli/src/diff.js +1 -333
  42. package/vendor/cli/src/diffview.js +1 -296
  43. package/vendor/cli/src/engine.js +1 -297
  44. package/vendor/cli/src/entitlement.js +1 -355
  45. package/vendor/cli/src/events.js +1 -707
  46. package/vendor/cli/src/export.js +1 -67
  47. package/vendor/cli/src/filepreview.js +1 -153
  48. package/vendor/cli/src/fingerprint.js +1 -592
  49. package/vendor/cli/src/format.js +1 -259
  50. package/vendor/cli/src/fuzzy.js +1 -119
  51. package/vendor/cli/src/history.js +1 -423
  52. package/vendor/cli/src/init.js +1 -175
  53. package/vendor/cli/src/input.js +1 -139
  54. package/vendor/cli/src/keys.js +1 -183
  55. package/vendor/cli/src/markdown.js +1 -306
  56. package/vendor/cli/src/models.js +1 -507
  57. package/vendor/cli/src/naming.js +1 -57
  58. package/vendor/cli/src/overlays.js +1 -462
  59. package/vendor/cli/src/panels.js +1 -1418
  60. package/vendor/cli/src/ping.js +1 -226
  61. package/vendor/cli/src/presence.js +1 -238
  62. package/vendor/cli/src/render.js +1 -516
  63. package/vendor/cli/src/screen.js +1 -518
  64. package/vendor/cli/src/screens.js +1 -896
  65. package/vendor/cli/src/secret.js +1 -59
  66. package/vendor/cli/src/securefs.js +1 -359
  67. package/vendor/cli/src/settings.js +1 -155
  68. package/vendor/cli/src/shared.js +1 -52
  69. package/vendor/cli/src/sharedpaths.js +1 -53
  70. package/vendor/cli/src/signup.js +1 -156
  71. package/vendor/cli/src/summarize.js +1 -95
  72. package/vendor/cli/src/sysdiag.js +1 -585
  73. package/vendor/cli/src/system.js +1 -40
  74. package/vendor/cli/src/theme.js +1 -570
  75. package/vendor/cli/src/title.js +1 -220
  76. package/vendor/cli/src/todos.js +1 -115
  77. package/vendor/cli/src/tokens.js +1 -263
  78. package/vendor/cli/src/topup.js +1 -210
  79. package/vendor/cli/src/update.js +1 -191
  80. package/vendor/cli/vendor/client/aegis.js +1 -2441
  81. package/vendor/cli/vendor/client/attest.js +1 -518
  82. package/vendor/cli/vendor/client/authorship-key.js +1 -410
  83. package/vendor/cli/vendor/client/auto-provision.js +1 -134
  84. package/vendor/cli/vendor/client/brain-catalog.js +1 -268
  85. package/vendor/cli/vendor/client/byok-catalog.js +1 -199
  86. package/vendor/cli/vendor/client/catalog-client.js +1 -487
  87. package/vendor/cli/vendor/client/conversation-export.js +1 -177
  88. package/vendor/cli/vendor/client/credentials.js +1 -494
  89. package/vendor/cli/vendor/client/device-fingerprint.js +1 -141
  90. package/vendor/cli/vendor/client/drive-connect.js +1 -110
  91. package/vendor/cli/vendor/client/drive-upload.js +1 -234
  92. package/vendor/cli/vendor/client/env-file.js +1 -1273
  93. package/vendor/cli/vendor/client/fingerprint.js +1 -1064
  94. package/vendor/cli/vendor/client/foreign-memory.js +1 -669
  95. package/vendor/cli/vendor/client/google-signin.js +1 -133
  96. package/vendor/cli/vendor/client/hooks.js +1 -430
  97. package/vendor/cli/vendor/client/model-discovery.js +1 -373
  98. package/vendor/cli/vendor/client/naming.js +1 -283
  99. package/vendor/cli/vendor/client/platform.js +1 -937
  100. package/vendor/cli/vendor/client/prefs.js +1 -351
  101. package/vendor/cli/vendor/client/presence-constants.js +1 -107
  102. package/vendor/cli/vendor/client/presence.js +1 -438
  103. package/vendor/cli/vendor/client/record-vault.js +3 -1055
  104. package/vendor/cli/vendor/client/session-store.js +1 -575
  105. package/vendor/cli/vendor/client/topup.js +1 -297
  106. package/vendor/cli/vendor/client/touch.js +1 -458
  107. package/vendor/cli/vendor/client/update.js +1 -763
  108. package/vendor/cli/vendor/client/user-models.js +1 -381
  109. package/vendor/cli/vendor/desktop/lib/local/agents.js +1 -105
  110. package/vendor/cli/vendor/desktop/lib/local/attachments.js +1 -276
  111. package/vendor/cli/vendor/desktop/lib/local/autonomous.js +1 -1045
  112. package/vendor/cli/vendor/desktop/lib/local/claude-pro.js +1 -1028
  113. package/vendor/cli/vendor/desktop/lib/local/context.js +1 -125
  114. package/vendor/cli/vendor/desktop/lib/local/engine.js +1 -3666
  115. package/vendor/cli/vendor/desktop/lib/local/entitlement.js +1 -660
  116. package/vendor/cli/vendor/desktop/lib/local/git-scope.js +1 -228
  117. package/vendor/cli/vendor/desktop/lib/local/integrity.js +1 -1
  118. package/vendor/cli/vendor/desktop/lib/local/local.js +1 -2145
  119. package/vendor/cli/vendor/desktop/lib/local/prompt.js +1 -280
  120. package/vendor/cli/vendor/desktop/lib/local/queue.js +1 -560
  121. package/vendor/cli/vendor/desktop/lib/local/session-rounds.js +1 -238
  122. package/vendor/cli/vendor/desktop/lib/local/spill.js +1 -75
  123. package/vendor/cli/vendor/desktop/lib/local/turn-guard.js +1 -300
  124. package/vendor/cli/vendor/desktop/lib/local/worktree-lock.js +1 -235
  125. package/vendor/cli/vendor/desktop/lib/settings.js +1 -890
  126. package/vendor/cli/vendor/desktop/main.js +67 -1
  127. package/vendor/cli/vendor/desktop/renderer/usage.js +1 -1239
  128. package/vendor/cli/vendor/hosts/install.js +1 -638
  129. package/vendor/cli/vendor/hosts/openai-shim.js +1 -515
  130. package/vendor/cli/vendor/hosts/spec.js +1 -164
  131. package/vendor/cli/vendor/hosts/targets.js +1 -346
  132. package/vendor/cli/vendor/mcp/server.js +1 -221
  133. package/vendor/cli/vendor/mcp/tools.js +1 -408
  134. package/vendor/cli/vendor/one/src/child.js +1 -285
  135. package/vendor/cli/vendor/one/src/permissions.js +1 -383
  136. package/vendor/cli/vendor/one/src/selfhost.js +3 -0
  137. package/vendor/desktop/bin/aegis.js +1 -32
  138. package/vendor/desktop/lib/account-key.js +1 -56
  139. package/vendor/desktop/lib/auto.js +1 -461
  140. package/vendor/desktop/lib/avatar/companion.js +1 -698
  141. package/vendor/desktop/lib/avatar/cosmetics.js +1 -532
  142. package/vendor/desktop/lib/avatar/events.js +1 -344
  143. package/vendor/desktop/lib/avatar/holder-turn.js +1 -350
  144. package/vendor/desktop/lib/avatar/holders.js +1 -612
  145. package/vendor/desktop/lib/avatar/identity.js +1 -641
  146. package/vendor/desktop/lib/avatar/level.js +1 -368
  147. package/vendor/desktop/lib/avatar/mirror.js +1 -524
  148. package/vendor/desktop/lib/avatar/persona.js +1 -388
  149. package/vendor/desktop/lib/avatar/profile.js +1 -977
  150. package/vendor/desktop/lib/avatar/register.js +1 -307
  151. package/vendor/desktop/lib/avatar/store.js +1 -472
  152. package/vendor/desktop/lib/avatar/tiers.js +1 -38
  153. package/vendor/desktop/lib/avatar/transfer.js +1 -415
  154. package/vendor/desktop/lib/avatar/turn.js +1 -216
  155. package/vendor/desktop/lib/avatar/voice.js +1 -328
  156. package/vendor/desktop/lib/avatar/xp.js +1 -404
  157. package/vendor/desktop/lib/deep-link.js +1 -120
  158. package/vendor/desktop/lib/fingerprint.js +2 -347
  159. package/vendor/desktop/lib/google-connect.js +1 -323
  160. package/vendor/desktop/lib/local/agents.js +1 -105
  161. package/vendor/desktop/lib/local/attachments.js +1 -276
  162. package/vendor/desktop/lib/local/autonomous.js +1 -1045
  163. package/vendor/desktop/lib/local/claude-pro.js +1 -1028
  164. package/vendor/desktop/lib/local/context.js +1 -125
  165. package/vendor/desktop/lib/local/engine.js +1 -3666
  166. package/vendor/desktop/lib/local/entitlement.js +1 -660
  167. package/vendor/desktop/lib/local/git-scope.js +1 -228
  168. package/vendor/desktop/lib/local/integrity.js +1 -1
  169. package/vendor/desktop/lib/local/local.js +1 -2145
  170. package/vendor/desktop/lib/local/prompt.js +1 -280
  171. package/vendor/desktop/lib/local/queue.js +1 -560
  172. package/vendor/desktop/lib/local/session-rounds.js +1 -238
  173. package/vendor/desktop/lib/local/spill.js +1 -75
  174. package/vendor/desktop/lib/local/telemetry.js +1 -470
  175. package/vendor/desktop/lib/local/turn-guard.js +1 -300
  176. package/vendor/desktop/lib/local/worktree-lock.js +1 -235
  177. package/vendor/desktop/lib/provider-key-mirror.js +1 -252
  178. package/vendor/desktop/lib/quick-launcher.js +1 -84
  179. package/vendor/desktop/lib/settings.js +1 -890
  180. package/vendor/desktop/lib/sync/memory-queue.js +1 -60
  181. package/vendor/desktop/lib/sync/persist-gate.js +1 -148
  182. package/vendor/desktop/lib/sync/sessions.js +1 -106
  183. package/vendor/desktop/lib/window-state.js +1 -66
  184. package/vendor/desktop/main.js +67 -1
  185. package/vendor/desktop/package.json +3 -5
  186. package/vendor/desktop/preload.js +1 -679
  187. package/vendor/desktop/renderer/app.js +1 -7250
  188. package/vendor/desktop/renderer/avatar/assemble.js +1 -335
  189. package/vendor/desktop/renderer/avatar/avatar.js +1 -380
  190. package/vendor/desktop/renderer/avatar/cards.js +1 -141
  191. package/vendor/desktop/renderer/avatar/hud.js +1 -206
  192. package/vendor/desktop/renderer/avatar/machine.js +1 -213
  193. package/vendor/desktop/renderer/avatar/pane.js +1 -439
  194. package/vendor/desktop/renderer/avatar/parts.js +1 -437
  195. package/vendor/desktop/renderer/budget.js +1 -172
  196. package/vendor/desktop/renderer/companion.js +1 -223
  197. package/vendor/desktop/renderer/diff.js +1 -359
  198. package/vendor/desktop/renderer/diffview.js +1 -336
  199. package/vendor/desktop/renderer/filepreview.js +1 -211
  200. package/vendor/desktop/renderer/fingerprint.js +3 -789
  201. package/vendor/desktop/renderer/markdown.js +1 -168
  202. package/vendor/desktop/renderer/provider-mark.js +1 -311
  203. package/vendor/desktop/renderer/provider-toolbar.js +1 -134
  204. package/vendor/desktop/renderer/providers.js +1 -259
  205. package/vendor/desktop/renderer/quick.js +1 -285
  206. package/vendor/desktop/renderer/stream-policy.js +1 -387
  207. package/vendor/desktop/renderer/transcript-view.js +1 -323
  208. package/vendor/desktop/renderer/usage.js +1 -1239
  209. package/vendor/desktop/vendor/aegis.js +1 -2441
  210. package/vendor/desktop/vendor/attest.js +1 -518
  211. package/vendor/desktop/vendor/authorship-key.js +1 -410
  212. package/vendor/desktop/vendor/auto-provision.js +1 -134
  213. package/vendor/desktop/vendor/brain-catalog.js +1 -268
  214. package/vendor/desktop/vendor/byok-catalog.js +1 -199
  215. package/vendor/desktop/vendor/catalog-client.js +1 -487
  216. package/vendor/desktop/vendor/conversation-export.js +1 -177
  217. package/vendor/desktop/vendor/credentials.js +1 -494
  218. package/vendor/desktop/vendor/device-fingerprint.js +1 -141
  219. package/vendor/desktop/vendor/drive-connect.js +1 -110
  220. package/vendor/desktop/vendor/drive-upload.js +1 -234
  221. package/vendor/desktop/vendor/env-file.js +1 -1273
  222. package/vendor/desktop/vendor/faces/cli/LICENSE +661 -0
  223. package/vendor/desktop/vendor/faces/cli/README.md +784 -0
  224. package/vendor/desktop/vendor/faces/cli/bin/aegiscode.js +20 -0
  225. package/vendor/desktop/vendor/faces/cli/package.json +44 -0
  226. package/vendor/desktop/vendor/faces/cli/scripts/check.mjs +4 -0
  227. package/vendor/desktop/vendor/faces/cli/scripts/demo.mjs +4 -0
  228. package/vendor/desktop/vendor/faces/cli/scripts/predist.mjs +4 -0
  229. package/vendor/desktop/vendor/faces/cli/scripts/runtests.mjs +4 -0
  230. package/vendor/desktop/vendor/faces/cli/scripts/seal-gate.mjs +3 -0
  231. package/vendor/desktop/vendor/faces/cli/src/agents.js +3 -0
  232. package/vendor/desktop/vendor/faces/cli/src/app.js +3 -0
  233. package/vendor/desktop/vendor/faces/cli/src/art.js +3 -0
  234. package/vendor/desktop/vendor/faces/cli/src/autonomous.js +3 -0
  235. package/vendor/desktop/vendor/faces/cli/src/caps.js +3 -0
  236. package/vendor/desktop/vendor/faces/cli/src/chatflow.js +3 -0
  237. package/vendor/desktop/vendor/faces/cli/src/checkpoint.js +3 -0
  238. package/vendor/desktop/vendor/faces/cli/src/clipboard.js +3 -0
  239. package/vendor/desktop/vendor/faces/cli/src/cloudsync.js +3 -0
  240. package/vendor/desktop/vendor/faces/cli/src/commands.js +3 -0
  241. package/vendor/desktop/vendor/faces/cli/src/config.js +3 -0
  242. package/vendor/desktop/vendor/faces/cli/src/connect.js +3 -0
  243. package/vendor/desktop/vendor/faces/cli/src/credentials.js +3 -0
  244. package/vendor/desktop/vendor/faces/cli/src/deps.js +3 -0
  245. package/vendor/desktop/vendor/faces/cli/src/devrun.js +3 -0
  246. package/vendor/desktop/vendor/faces/cli/src/diff.js +3 -0
  247. package/vendor/desktop/vendor/faces/cli/src/diffview.js +3 -0
  248. package/vendor/desktop/vendor/faces/cli/src/engine.js +3 -0
  249. package/vendor/desktop/vendor/faces/cli/src/entitlement.js +3 -0
  250. package/vendor/desktop/vendor/faces/cli/src/events.js +3 -0
  251. package/vendor/desktop/vendor/faces/cli/src/export.js +3 -0
  252. package/vendor/desktop/vendor/faces/cli/src/filepreview.js +3 -0
  253. package/vendor/desktop/vendor/faces/cli/src/fingerprint.js +3 -0
  254. package/vendor/desktop/vendor/faces/cli/src/format.js +3 -0
  255. package/vendor/desktop/vendor/faces/cli/src/fuzzy.js +3 -0
  256. package/vendor/desktop/vendor/faces/cli/src/gate.js +3 -0
  257. package/vendor/desktop/vendor/faces/cli/src/history.js +3 -0
  258. package/vendor/desktop/vendor/faces/cli/src/init.js +3 -0
  259. package/vendor/desktop/vendor/faces/cli/src/input.js +3 -0
  260. package/vendor/desktop/vendor/faces/cli/src/keys.js +3 -0
  261. package/vendor/desktop/vendor/faces/cli/src/limits.js +3 -0
  262. package/vendor/desktop/vendor/faces/cli/src/markdown.js +3 -0
  263. package/vendor/desktop/vendor/faces/cli/src/mcp.js +3 -0
  264. package/vendor/desktop/vendor/faces/cli/src/models.js +3 -0
  265. package/vendor/desktop/vendor/faces/cli/src/naming.js +3 -0
  266. package/vendor/desktop/vendor/faces/cli/src/overlays.js +3 -0
  267. package/vendor/desktop/vendor/faces/cli/src/panels.js +3 -0
  268. package/vendor/desktop/vendor/faces/cli/src/permissions.js +3 -0
  269. package/vendor/desktop/vendor/faces/cli/src/ping.js +3 -0
  270. package/vendor/desktop/vendor/faces/cli/src/presence.js +3 -0
  271. package/vendor/desktop/vendor/faces/cli/src/provenance.js +58 -0
  272. package/vendor/desktop/vendor/faces/cli/src/provenance.lock.json +36 -0
  273. package/vendor/desktop/vendor/faces/cli/src/render.js +3 -0
  274. package/vendor/desktop/vendor/faces/cli/src/screen.js +3 -0
  275. package/vendor/desktop/vendor/faces/cli/src/screens.js +3 -0
  276. package/vendor/desktop/vendor/faces/cli/src/secret.js +3 -0
  277. package/vendor/desktop/vendor/faces/cli/src/securefs.js +3 -0
  278. package/vendor/desktop/vendor/faces/cli/src/settings.js +3 -0
  279. package/vendor/desktop/vendor/faces/cli/src/shared.js +3 -0
  280. package/vendor/desktop/vendor/faces/cli/src/sharedpaths.js +3 -0
  281. package/vendor/desktop/vendor/faces/cli/src/signup.js +3 -0
  282. package/vendor/desktop/vendor/faces/cli/src/summarize.js +3 -0
  283. package/vendor/desktop/vendor/faces/cli/src/sysdiag.js +3 -0
  284. package/vendor/desktop/vendor/faces/cli/src/system.js +3 -0
  285. package/vendor/desktop/vendor/faces/cli/src/theme.js +3 -0
  286. package/vendor/desktop/vendor/faces/cli/src/title.js +3 -0
  287. package/vendor/desktop/vendor/faces/cli/src/todos.js +3 -0
  288. package/vendor/desktop/vendor/faces/cli/src/tokens.js +3 -0
  289. package/vendor/desktop/vendor/faces/cli/src/topup.js +3 -0
  290. package/vendor/desktop/vendor/faces/cli/src/update.js +3 -0
  291. package/vendor/desktop/vendor/faces/cli/vendor/client/aegis.js +4 -0
  292. package/vendor/desktop/vendor/faces/cli/vendor/client/attest.js +3 -0
  293. package/vendor/desktop/vendor/faces/cli/vendor/client/authorship-key.js +3 -0
  294. package/vendor/desktop/vendor/faces/cli/vendor/client/auto-provision.js +3 -0
  295. package/vendor/desktop/vendor/faces/cli/vendor/client/brain-catalog.js +3 -0
  296. package/vendor/desktop/vendor/faces/cli/vendor/client/byok-catalog.js +3 -0
  297. package/vendor/desktop/vendor/faces/cli/vendor/client/catalog-client.js +3 -0
  298. package/vendor/desktop/vendor/faces/cli/vendor/client/conversation-export.js +3 -0
  299. package/vendor/desktop/vendor/faces/cli/vendor/client/credentials.js +3 -0
  300. package/vendor/desktop/vendor/faces/cli/vendor/client/device-fingerprint.js +3 -0
  301. package/vendor/desktop/vendor/faces/cli/vendor/client/drive-connect.js +3 -0
  302. package/vendor/desktop/vendor/faces/cli/vendor/client/drive-upload.js +3 -0
  303. package/vendor/desktop/vendor/faces/cli/vendor/client/env-file.js +3 -0
  304. package/vendor/desktop/vendor/faces/cli/vendor/client/fingerprint.js +3 -0
  305. package/vendor/desktop/vendor/faces/cli/vendor/client/foreign-memory.js +3 -0
  306. package/vendor/desktop/vendor/faces/cli/vendor/client/google-signin.js +3 -0
  307. package/vendor/desktop/vendor/faces/cli/vendor/client/hooks.js +3 -0
  308. package/vendor/desktop/vendor/faces/cli/vendor/client/model-discovery.js +3 -0
  309. package/vendor/desktop/vendor/faces/cli/vendor/client/naming.js +3 -0
  310. package/vendor/desktop/vendor/faces/cli/vendor/client/platform.js +3 -0
  311. package/vendor/desktop/vendor/faces/cli/vendor/client/prefs.js +3 -0
  312. package/vendor/desktop/vendor/faces/cli/vendor/client/presence-constants.js +3 -0
  313. package/vendor/desktop/vendor/faces/cli/vendor/client/presence.js +3 -0
  314. package/vendor/desktop/vendor/faces/cli/vendor/client/record-vault.js +105 -0
  315. package/vendor/desktop/vendor/faces/cli/vendor/client/session-store.js +3 -0
  316. package/vendor/desktop/vendor/faces/cli/vendor/client/topup.js +3 -0
  317. package/vendor/desktop/vendor/faces/cli/vendor/client/touch.js +3 -0
  318. package/vendor/desktop/vendor/faces/cli/vendor/client/update.js +3 -0
  319. package/vendor/desktop/vendor/faces/cli/vendor/client/user-models.js +3 -0
  320. package/vendor/desktop/vendor/faces/cli/vendor/covenant/README.md +21 -0
  321. package/vendor/desktop/vendor/faces/cli/vendor/covenant/aegis.seal +177 -0
  322. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/aegis-seal.mjs +241 -0
  323. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/agents.js +3 -0
  324. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/attachments.js +3 -0
  325. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/autonomous.js +3 -0
  326. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/claude-pro.js +3 -0
  327. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/context.js +3 -0
  328. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/covenant.js +567 -0
  329. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/engine.js +3 -0
  330. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/entitlement.js +3 -0
  331. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/exec-plan.js +3 -0
  332. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/git-scope.js +3 -0
  333. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/integrity.js +3 -0
  334. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/local.js +3 -0
  335. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/prompt.js +3 -0
  336. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/queue.js +3 -0
  337. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/session-rounds.js +3 -0
  338. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/shell.js +3 -0
  339. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/spill.js +3 -0
  340. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/tools.js +3 -0
  341. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/turn-guard.js +3 -0
  342. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/worktree-lock.js +3 -0
  343. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/settings.js +3 -0
  344. package/vendor/desktop/vendor/faces/cli/vendor/desktop/main.js +4 -0
  345. package/vendor/desktop/vendor/faces/cli/vendor/desktop/renderer/usage.js +3 -0
  346. package/vendor/desktop/vendor/faces/cli/vendor/hosts/install.js +1 -0
  347. package/vendor/desktop/vendor/faces/cli/vendor/hosts/openai-shim.js +2 -0
  348. package/vendor/desktop/vendor/faces/cli/vendor/hosts/spec.js +1 -0
  349. package/vendor/desktop/vendor/faces/cli/vendor/hosts/targets.js +1 -0
  350. package/vendor/desktop/vendor/faces/cli/vendor/mcp/server.js +4 -0
  351. package/vendor/desktop/vendor/faces/cli/vendor/mcp/tools.js +3 -0
  352. package/vendor/desktop/vendor/faces/cli/vendor/one/src/child.js +3 -0
  353. package/vendor/desktop/vendor/faces/cli/vendor/one/src/permissions.js +3 -0
  354. package/vendor/desktop/vendor/faces/cli/vendor/one/src/selfhost.js +3 -0
  355. package/vendor/desktop/vendor/faces/cli/vendor/tools/agent-gate.mjs +1203 -0
  356. package/vendor/desktop/vendor/fingerprint.js +1 -1064
  357. package/vendor/desktop/vendor/foreign-memory.js +1 -669
  358. package/vendor/desktop/vendor/google-signin.js +1 -133
  359. package/vendor/desktop/vendor/hooks.js +1 -430
  360. package/vendor/desktop/vendor/model-discovery.js +1 -373
  361. package/vendor/desktop/vendor/naming.js +1 -283
  362. package/vendor/desktop/vendor/platform.js +1 -937
  363. package/vendor/desktop/vendor/prefs.js +1 -351
  364. package/vendor/desktop/vendor/presence-constants.js +1 -107
  365. package/vendor/desktop/vendor/presence.js +1 -438
  366. package/vendor/desktop/vendor/record-vault.js +3 -1055
  367. package/vendor/desktop/vendor/selfhost.js +3 -0
  368. package/vendor/desktop/vendor/session-store.js +1 -575
  369. package/vendor/desktop/vendor/topup.js +1 -297
  370. package/vendor/desktop/vendor/touch.js +1 -458
  371. package/vendor/desktop/vendor/update.js +1 -763
  372. package/vendor/desktop/vendor/user-models.js +1 -381
@@ -0,0 +1,3 @@
1
+ // SPDX-License-Identifier: AGPL-3.0-or-later
2
+ // Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
3
+ "use strict";const fs=require("node:fs"),path=require("node:path"),{aegisDir:aegisDir}=require("./config.js"),{writePrivateFile:writePrivateFile}=require("./securefs.js");function todosFile(){return path.join(aegisDir(),"todos.json")}function readTodos(){try{const t=JSON.parse(fs.readFileSync(todosFile(),"utf8"));return Array.isArray(t)?t.filter((t=>t&&"string"==typeof t.text)).map((t=>({text:t.text,done:!0===t.done,at:t.at||null}))):[]}catch{return[]}}function writeTodos(t){const e=(Array.isArray(t)?t:[]).filter((t=>t&&"string"==typeof t.text&&t.text.trim())).map((t=>({text:t.text.trim(),done:!0===t.done,at:t.at||(new Date).toISOString()})));try{writePrivateFile(todosFile(),`${JSON.stringify(e,null,2)}\n`)}catch{}return e}function addTodo(t){const e=String(t||"").trim();if(!e)return{error:"usage: /todos add <text>"};const o=readTodos();return o.push({text:e,done:!1,at:(new Date).toISOString()}),{list:writeTodos(o),added:e}}function completeTodo(t){const e=readTodos(),o=String(t||"").trim();if(!o)return{error:"usage: /todos done <n|text>"};let r=-1;const i=Number.parseInt(o,10);if(Number.isFinite(i)&&String(i)===o)r=i-1;else{const t=e.map(((t,e)=>t.text.startsWith(o)?e:-1)).filter((t=>t>=0));if(1===t.length)r=t[0];else if(t.length>1)return{error:`"${o}" matches ${t.length} todos — use the number from /todos`}}return r<0||r>=e.length?{error:`no todo #${o} — run /todos to list them`}:(e[r].done=!e[r].done,{list:writeTodos(e),item:e[r]})}function clearTodos(){return writeTodos([]),{list:[]}}function formatTodos(t=readTodos()){return t.length?t.map(((t,e)=>` ${String(e+1).padStart(2)}. ${t.done?"✔":"○"} ${t.text}`)):[" No todos yet — /todos add <text>"]}module.exports={todosFile:todosFile,readTodos:readTodos,writeTodos:writeTodos,addTodo:addTodo,completeTodo:completeTodo,clearTodos:clearTodos,formatTodos:formatTodos};
@@ -0,0 +1,3 @@
1
+ // SPDX-License-Identifier: AGPL-3.0-or-later
2
+ // Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
3
+ "use strict";const path=require("node:path"),{resolveShared:resolveShared}=require("./sharedpaths.js"),shared=require(resolveShared(path.join("desktop","renderer","usage.js"))),{RATES:RATES,RATE_BASIS:RATE_BASIS,UNPRICED_BY_DESIGN:UNPRICED_BY_DESIGN,isPeak:isPeak,ratesFor:ratesFor,costBreakdown:costBreakdown,cacheHitRate:cacheHitRate,usageBuckets:usageBuckets}=shared,SYSTEM_TOKENS=18e3,TOOL_TOKENS=12e3,CONTEXT_WINDOW=2e5,CONTEXT_WINDOWS={deepseek:1048576,openrouter:256e3,together:256e3,xai:256e3,groq:128e3,ollama:128e3,openai:2e5,anthropic:2e5,google:1e6,gemini:1e6};function contextWindowFor(e){const t=String(e||"").toLowerCase();if(!t)return CONTEXT_WINDOW;const s=[t],o=t.slice(t.lastIndexOf(":")+1);o&&o!==t&&s.push(o);for(const e of s){if(CONTEXT_WINDOWS[e])return CONTEXT_WINDOWS[e];for(const[t,s]of Object.entries(CONTEXT_WINDOWS))if(e.startsWith(t))return s}return CONTEXT_WINDOW}function estimateTokens(e){return e?Math.max(1,Math.ceil([...String(e)].length/4)):0}function estimateTokensFromCells(e){const t=Number(e);return t>0?Math.ceil(t/4):0}function transcriptUsage(e,t="sonnet"){const s=e.filter((e=>"user"===e.role)),o=e.filter((e=>"assistant"===e.role)),n=s.reduce(((e,t)=>e+estimateTokens(t.text||"")),0);return{input:n,output:o.reduce(((e,t)=>e+estimateTokens(t.text||"")),0),cacheRead:Math.max(0,n-(s.length?estimateTokens(s[s.length-1].text||""):0)),cacheWrite:s.length?estimateTokens(s[s.length-1].text||""):0}}function usageCost(e,t,s={}){return shared.usageCost(e,t,s)}function sessionAccounting(e,t="sonnet"){const s=transcriptUsage(e,t),o=s.input+s.output,n=3e4+o,r=contextWindowFor(t),a=costBreakdown(s,t);return{usage:s,system:18e3,tools:12e3,history:o,used:n,contextWindow:r,pct:Math.min(100,Math.round(n/r*100)),cost:a.cost,costBasis:a.basis,costPriced:a.priced}}function accountingFromUsage(e,t="sonnet",{exchanges:s=0,real:o=!1,costUsd:n,at:r}={}){const a=costBreakdown(e,t,{at:r}),c="number"==typeof n?n:a.cost,i=o?e.input+e.output+e.cacheRead+e.cacheWrite:3e4+e.input+e.output,u=contextWindowFor(t);return{usage:e,system:18e3,tools:12e3,history:e.input+e.output,used:i,contextWindow:u,pct:Math.min(100,Math.round(i/u*100)),cost:c,costBasis:"number"==typeof n?"settled":a.basis,costPriced:"number"==typeof n||a.priced,exchanges:s,real:o}}function fmtTokens(e){return e>=1e3?`${(e/1e3).toFixed(1)}k`:String(e)}function fmtCost(e){return`$${e.toFixed(4)}`}module.exports={RATES:RATES,RATE_BASIS:RATE_BASIS,UNPRICED_BY_DESIGN:UNPRICED_BY_DESIGN,isPeak:isPeak,SYSTEM_TOKENS:18e3,TOOL_TOKENS:12e3,CONTEXT_WINDOW:CONTEXT_WINDOW,CONTEXT_WINDOWS:CONTEXT_WINDOWS,contextWindowFor:contextWindowFor,ratesFor:ratesFor,costBreakdown:costBreakdown,cacheHitRate:cacheHitRate,usageBuckets:usageBuckets,estimateTokens:estimateTokens,estimateTokensFromCells:estimateTokensFromCells,transcriptUsage:transcriptUsage,usageCost:usageCost,sessionAccounting:sessionAccounting,accountingFromUsage:accountingFromUsage,fmtTokens:fmtTokens,fmtCost:fmtCost};
@@ -0,0 +1,3 @@
1
+ // SPDX-License-Identifier: AGPL-3.0-or-later
2
+ // Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
3
+ "use strict";const{resolveShared:resolveShared}=require("./sharedpaths.js"),{openUrl:defaultOpenUrl}=require("./system.js"),credentials=require("./credentials.js");function loadShared(e){return require(resolveShared(e))}function createCliClient(){const{createClient:e}=loadShared("client/aegis.js");return e(credentials.clientOptions({channel:"cli"}))}async function ensureKey(e,t){if(e.apiKey)return!0;try{const n=loadShared("client/auto-provision.js"),o=n.autoProvisionApiKey||n.default;if("function"==typeof o){const n=await o(e,t,{app:"cli"});n&&n.key&&"function"==typeof e.setApiKey&&e.setApiKey(n.key)}}catch{}return Boolean(e.apiKey)}async function runTopupCommand(e,t){const n=t||{},o=n.stdout||process.stdout,r=n.stderr||process.stderr,i=n.json?()=>{}:e=>o.write(e);let a=null;const s=(e,t)=>(n.json&&o.write(JSON.stringify(t)+"\n"),e);let c;try{c=loadShared("client/topup.js")}catch(e){return r.write(`aegiscode: the shared top-up module is missing — ${e&&e.message||e}\n`),2}const{parseTopupAmount:u,startTopup:l,createCreditWatch:d,TOPUP_POLL_MS:p,TOPUP_POLL_TRIES:h,TOPUP_MIN_EUR:m,TOPUP_MAX_EUR:g}=c,f=u(e);if(!f.ok)return r.write(`aegiscode: ${f.message}\n usage: aegiscode topup [${m}..${g}] (default 10)\n`),s(2,{ok:!1,credited:!1,amount_eur:null,url:null,balance_eur:null,error:f.message});a={ok:!1,credited:!1,amount_eur:f.amount,url:null,balance_eur:null},r.write(`aegiscode: requesting a ${f.amount} EUR top-up from the account service…\n`);const y=n.client||createCliClient();if(!y.apiKey&&!await ensureKey(y,credentials))return r.write("aegiscode: no AEGIS key on this machine and none could be provisioned —\n `aegiscode login <api_key>` (from https://aegiscloud.org/dashboard) first\n"),a.error="no usable AEGIS key",s(2,a);const w=await l(y,f.amount);if(!w.ok)return r.write(`aegiscode: the top-up could not be started — ${w.message}\n`),w.hint&&r.write(`aegiscode: ${w.hint}\n`),a.error=w.message,a.status=w.status,s(2,a);a.url=w.url;const b=n.openUrl||defaultOpenUrl,k=n.sleep||(e=>new Promise((t=>setTimeout(t,e)))),U=null==n.intervalMs?p:n.intervalMs,S=null==n.maxTries?h:n.maxTries,T=Math.max(1,Math.round(U*S/1e3));b(w.url)?i(`aegiscode: opening the payment page in your browser — ${w.amount} EUR\n`):i(`aegiscode: open this to pay ${w.amount} EUR:\n ${w.url}\n`),i(`aegiscode: watching this account's bank for up to ${T}s to confirm the credit\n`);const $=d(y,{maxTries:S});let _=!1;for(;;){const e=await $.tick();if("function"==typeof n.onStep&&n.onStep(e),"credited"===e.state)return a.ok=!0,a.credited=!0,a.balance_eur=e.amount,i(`aegiscode: credit confirmed — the bank is now ${e.amount.toFixed(2)} EUR\naegiscode: (this account was created by this machine, so the browser there has no\n session for it — the confirmation comes from the API, not the page)\n`),s(0,a);if("expired"===e.state)return i(`aegiscode: no credit observed within ${T}s — if you completed the payment it\naegiscode: may still land; re-run \`aegiscode topup\` or check \`/billing\` in a session\n`),a.error="no credit observed within the watch window",s(1,a);null==e.baseline||_||n.json||(_=!0,i(`aegiscode: bank before the payment: ${e.baseline.toFixed(2)} EUR\n`)),await k(U)}}module.exports={runTopupCommand:runTopupCommand,ensureKey:ensureKey,createCliClient:createCliClient};
@@ -0,0 +1,3 @@
1
+ // SPDX-License-Identifier: AGPL-3.0-or-later
2
+ // Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
3
+ "use strict";const path=require("node:path"),fs=require("node:fs"),{execFileSync:execFileSync}=require("node:child_process"),{resolveShared:resolveShared}=require("./deps.js"),shared=require(resolveShared("client/update.js")),VERSION=require("../package.json").version,PKG=shared.PKG||"aegiscode";let methodCache=null;function installMethod(){if(methodCache)return methodCache;const e=shared.detectInstallMethod;if("function"!=typeof e)return methodCache="npm",methodCache;try{methodCache=e({env:process.env,argv:process.argv,pkg:PKG,entry:path.resolve(__dirname,".."),fileExists:e=>fs.existsSync(path.resolve(__dirname,"..","..",e))})}catch{methodCache="npm"}return methodCache}function compareVersions(e,n){const t=String(e||"0").split("-")[0].split(".").map((e=>Number.parseInt(e,10)||0)),r=String(n||"0").split("-")[0].split(".").map((e=>Number.parseInt(e,10)||0));for(let e=0;e<Math.max(t.length,r.length);e++){const n=(t[e]||0)-(r[e]||0);if(n)return n>0?1:-1}return 0}function upgradeAdvice({current:e=VERSION,latest:n=null,packageName:t=PKG,method:r="npm"}={}){if(!n)return{upToDate:null,lines:[` Could not read the npm registry — local version is ${e}.`]};if(compareVersions(n,e)>0){const a="function"==typeof shared.updatePlan?shared.updatePlan({current:e,latest:n,behind:!0,channel:"npm",pkg:t,method:r}):null,s=[` Installed: ${e}`,` Published: ${n}`,` Channel: ${r}`,` Upgrade: ${a&&a.instruction||`npm i -g ${t}@latest`}`];return a&&a.apply&&s.push(" (or run `/upgrade apply` to do it here)"),{upToDate:!1,lines:s,plan:a}}return{upToDate:!0,lines:[` Installed ${e} is the published ${n} — nothing to upgrade.`]}}function applyUpgrade({current:e=VERSION,packageName:n=PKG,method:t="npm",latest:r=null}={}){const a="function"==typeof shared.updatePlan&&r?shared.updatePlan({current:e,latest:r,behind:!0,channel:"npm",pkg:n,method:t}):null,s=a&&a.apply?a.apply:null;if(!s)return{ok:!0,skipped:!0,channel:t,command:null,instruction:a&&a.instruction||("npm"===t?`npm i -g ${n}@latest`:"restart to pick up the new version")};try{const e=("function"==typeof shared.installSpawn?shared.installSpawn(s,{env:process.env}):{command:s.command,args:s.args,shell:!1})||{command:s.command,args:s.args,shell:!1},n=execFileSync(e.command,e.args,{encoding:"utf8",timeout:18e4,stdio:["ignore","pipe","pipe"],shell:!0===e.shell,windowsHide:!0});return{ok:!0,channel:t,command:`${s.command} ${s.args.join(" ")}`,output:String(n||"").trim()}}catch(e){return{ok:!1,channel:t,command:`${s.command} ${s.args.join(" ")}`,error:String(e&&(e.stderr||e.message)||e).trim()}}}function latestPublishedVersion({packageName:e=PKG,timeoutMs:n=5e3}={}){try{const t=execFileSync("npm",["view",e,"version"],{encoding:"utf8",timeout:n,stdio:["ignore","pipe","ignore"]}),r=String(t).trim();return/^\d+\.\d+\.\d+/.test(r)?r:null}catch{return null}}module.exports={...shared,VERSION:VERSION,compareVersions:compareVersions,upgradeAdvice:upgradeAdvice,applyUpgrade:applyUpgrade,installMethod:installMethod,latestPublishedVersion:latestPublishedVersion};
@@ -0,0 +1,4 @@
1
+ #!/usr/bin/env node
2
+ // SPDX-License-Identifier: AGPL-3.0-or-later
3
+ // Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
4
+ "use strict";function envVar(e){if("undefined"==typeof process||!process.env)return"";const t=process.env[e];return t&&!/^\$\{[A-Z_]+\}$/.test(t)?t:""}function envIdleMs(e){const t=envVar(e);if(!t)return 0;const n=Number(t);return Number.isFinite(n)&&n>0?n:0}const DSML_RE_INVOKE=/<\s*|\s*(?:DSML\s*)?|\s*(?:invoke|call|tool_call)\b\s*([^>]*?)\s*>([\s\S]*?)<\s*\/\s*|\s*(?:DSML\s*)?|\s*(?:invoke|call|tool_call)\b\s*>/g,DSML_RE_PARAM=/<\s*|\s*(?:DSML\s*)?|\s*(?:parameter|param|arg)\b\s*([^>]*?)\s*>([\s\S]*?)<\s*\/\s*|\s*(?:DSML\s*)?|\s*(?:parameter|param|arg)\b\s*>/g,DSML_RE_LEADER=/<\s*\/?\s*|\s*(?:DSML\s*)?|\s*(?:(?:tool|function)[_▁ ]*calls?|reasoning)[_▁ ]*(?:begin|end)?\s*>/gi,DSML_RE_ANY_TAG=/<\s*\/?\s*|\s*(?:DSML\s*)?|\s*[A-Za-z_][A-Za-z0-9_]*[^>]{0,120}>/g,DSML_RE_SKELETON=/<\s*\/?\s*(?:tool_calls|function_calls|invoke|parameter|param|reasoning)\b[^>]{0,120}>/gi,DSML_RE_JSON_CALLS=/|[ \t]*(?:tool|function)[_▁ ]*calls?[_▁ ]*begin[ \t]*|([\s\S]*?)|[ \t]*(?:tool|function)[_▁ ]*calls?[_▁ ]*end[ \t]*|/gi,DSML_RE_JSON_CALLS_OPEN=/|[ \t]*(?:tool|function)[_▁ ]*calls?[_▁ ]*begin[ \t]*|/gi,DSML_RE_JSON_CALLS_CLOSE=/|[ \t]*(?:tool|function)[_▁ ]*calls?[_▁ ]*end[ \t]*|/gi,DSML_RE_ENVELOPE_TOKEN=/|[ \t]?[A-Za-z0-9_▁]*[ \t]?|/g,DSML_RE_DRIFT_INVOKE=/<\s*|\s*(?:DSML\s*)?|\s*(?:invoke|call|tool_call)\b\s*([^>]*?)\s*>/gi,DSML_RE_DRIFT_PARAM=/<\s*|\s*(?:DSML\s*)?|\s*(?:parameter|param|arg)\b\s*([^>]*?)\s*>/gi,DSML_RE_PARAM_CLOSE=/<\s*\/\s*|\s*(?:DSML\s*)?|\s*(?:parameter|param|arg)\b\s*>/gi,DSML_RE_ATTR=/([A-Za-z_][A-Za-z0-9_.-]*)\s*=\s*(?:"([^"]*)"|'([^']*)')/g,DSML_RE_STRUCT_TAG=/<\s*\/?\s*|\s*(?:DSML\s*)?|\s*(?:invoke|call|tool_call|parameter|param|arg|reasoning|(?:tool|function)[_▁ ]*calls?)\b/gi,DSML_RE_STRUCT_CLOSER=/<\s*\/\s*|\s*(?:DSML\s*)?|\s*(?:invoke|call|tool_call|parameter|param|arg|reasoning|(?:tool|function)[_▁ ]*calls?)\b/gi,DSML_RE_WRAPPER_TAG=/<\s*\/?\s*|\s*(?:DSML\s*)?|\s*(?!(?:invoke|call|tool_call|parameter|param|arg)\b)[A-Za-z_][A-Za-z0-9_]*[^>]{0,120}>/g,DSML_RE_TRAILING_LT=/<\s*\/?\s*$/,DSML_RE_OPEN_TOKEN=/^|[ \t]?[A-Za-z0-9_▁]*[ \t]?$/,DSML_HOLD_MAX=4194304;function dsmlAttrs(e){const t={};if(!e)return t;let n;for(DSML_RE_ATTR.lastIndex=0;n=DSML_RE_ATTR.exec(e);)t[n[1].toLowerCase()]=null!=n[2]?n[2]:n[3];return t}function dsmlJson(e){const t=String(null==e?"":e).trim();try{const e=JSON.parse(t);return void 0===e?t:e}catch{return t}}function dsmlArgs(e){const t={};let n;for(DSML_RE_PARAM.lastIndex=0;n=DSML_RE_PARAM.exec(e);){const e=dsmlAttrs(n[1]),r=e.name||e.key||`arg${Object.keys(t).length}`,o="false"===String(e.string||"").toLowerCase()||"true"===String(e.json||"").toLowerCase();t[r]=o?dsmlJson(n[2]):n[2]}return t}function decodeDeepSeekDSML(e){if("string"!=typeof e||!e||-1===e.indexOf("|"))return{text:e||"",calls:[]};const t=[];let n=e;DSML_RE_INVOKE.lastIndex=0;const r=[];let o;for(;o=DSML_RE_INVOKE.exec(n);){const e=dsmlAttrs(o[1]),n=e.name||e.function||e.tool||"";n&&t.push({name:n,args:dsmlArgs(o[2])}),r.push([o.index,o.index+o[0].length])}for(let e=r.length-1;e>=0;e--)n=n.slice(0,r[e][0])+n.slice(r[e][1]);return n=n.replace(DSML_RE_JSON_CALLS,((e,n)=>{const r=dsmlJson(n),o=Array.isArray(r)?r:r&&Array.isArray(r.tool_calls)?r.tool_calls:[];for(const e of o){const n=e&&e.function||e||{},r=n.name||e&&e.name||"";if(!r)continue;let o=null!=n.arguments?n.arguments:e&&e.arguments;"string"==typeof o&&(o=dsmlJson(o)),t.push({name:r,args:o&&"object"==typeof o?o:{}})}return""})),n=n.replace(DSML_RE_LEADER,""),{text:n,calls:t}}function decodeDeepSeekDSMLDrift(e){if("string"!=typeof e||!e||-1===e.indexOf("|"))return{text:e||"",calls:[]};const t=[];let n;for(DSML_RE_DRIFT_INVOKE.lastIndex=0;n=DSML_RE_DRIFT_INVOKE.exec(e);)t.push({at:n.index,attrs:n[1],body:DSML_RE_DRIFT_INVOKE.lastIndex});if(!t.length)return{text:e,calls:[]};const r=[];let o="",s=0;for(let n=0;n<t.length;n++){const a=n+1<t.length?t[n+1].at:e.length,i=e.slice(t[n].body,a),c=dsmlAttrs(t[n].attrs),l=c.name||c.function||c.tool||"",u={},d=[];let m;for(DSML_RE_DRIFT_PARAM.lastIndex=0;m=DSML_RE_DRIFT_PARAM.exec(i);)d.push({at:m.index,attrs:m[1],from:DSML_RE_DRIFT_PARAM.lastIndex});for(let e=0;e<d.length;e++){const t=e+1<d.length?d[e+1].at:i.length,n=i.slice(d[e].from,t).replace(DSML_RE_PARAM_CLOSE,""),r=dsmlAttrs(d[e].attrs),o=r.name||r.key||`arg${Object.keys(u).length}`,s="false"===String(r.string||"").toLowerCase();u[o]=s?dsmlJson(n):n}o+=e.slice(s,t[n].at),s=a,l&&r.push({name:l,args:u})}return o+=e.slice(s),{text:o,calls:r}}function dsmlResidue(e){return e?-1===e.indexOf("|")?e.replace(DSML_RE_SKELETON,""):e.replace(DSML_RE_ANY_TAG,"").replace(DSML_RE_SKELETON,"").replace(DSML_RE_ENVELOPE_TOKEN,""):e}function dsmlUnterminated(e){return!!DSML_RE_OPEN_TOKEN.test(e)||(e.match(DSML_RE_STRUCT_TAG)||[]).length>(e.match(DSML_RE_STRUCT_CLOSER)||[]).length}function dsmlHoldFrom(e){const t=e.search(/<\s*\/?\s*|/);if(-1!==t)return t;const n=e.search(DSML_RE_JSON_CALLS_OPEN);if(-1!==n&&-1===e.slice(n).search(DSML_RE_JSON_CALLS_CLOSE))return n;const r=DSML_RE_TRAILING_LT.exec(e);if(r)return r.index;const o=e.indexOf("|");return-1!==o&&dsmlUnterminated(e.slice(o))?o:-1}function makeDeepSeekEnvelopeStripper(){let e="";const t=[],n=n=>{e+="string"==typeof n?n:"";const r=decodeDeepSeekDSML(e);e=r.text;for(const e of r.calls)t.push(e);e=e.replace(DSML_RE_WRAPPER_TAG,"");const o=dsmlHoldFrom(e);let s;return-1!==o&&e.length-o<=DSML_HOLD_MAX?(s=e.slice(0,o),e=e.slice(o)):(s=e,e=""),dsmlResidue(s)};return n.flush=()=>{const n=decodeDeepSeekDSML(e);e="";for(const e of n.calls)t.push(e);const r=decodeDeepSeekDSMLDrift(n.text);for(const e of r.calls)t.push(e);return dsmlResidue(r.text)},n.calls=()=>t.slice(),n}function randomUUID(){const e="undefined"!=typeof globalThis&&globalThis||"undefined"!=typeof self&&self||null,t=e&&e.crypto;if(t&&"function"==typeof t.randomUUID)try{return t.randomUUID()}catch(e){}if(t&&"function"==typeof t.getRandomValues)try{const e=new Uint8Array(16);t.getRandomValues(e),e[6]=15&e[6]|64,e[8]=63&e[8]|128;const n=Array.from(e,(e=>e.toString(16).padStart(2,"0"))).join("");return`${n.slice(0,8)}-${n.slice(8,12)}-${n.slice(12,16)}-${n.slice(16,20)}-${n.slice(20)}`}catch(e){}if("function"==typeof require)try{const e=require("crypto");if(e&&"function"==typeof e.randomUUID)return e.randomUUID()}catch(e){}return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(e=>{const t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)}))}const DEFAULT_API_BASE="https://aegiscloud.org",CLIENT_VERSION="3.2.0",DEFAULT_TIMEOUT_MS=6e4,MAX_BODY_BYTES=8388608,RATE_LIMIT_RETRIES=4,RATE_LIMIT_MAX_WAIT_MS=3e4,RATE_LIMIT_BASE_WAIT_MS=1e3,TRANSIENT_STREAM_ERROR_PATTERN=/connection reset by peer|broken pipe|connection aborted|errno 104|errno 32|errno 54|econnreset|epipe/i,TRANSIENT_STREAM_RETRIES=2,TRANSIENT_STREAM_BASE_WAIT_MS=500,TRANSIENT_SOCKET_CODE_PATTERN=/^(ECONNRESET|EPIPE|ECONNABORTED|UND_ERR_SOCKET|UND_ERR_CLOSED)$/,TRANSIENT_SOCKET_RETRIES=2,SSE_UPSTREAM_TIMEOUT_PATTERN=/request timed out|timed out waiting|upstream timeout/i;function upstreamTimeoutMessage(e,t){const n=Number(t);return`${e} — the upstream provider gave up before answering${null!=t&&Number.isFinite(n)?n>=1e3?` after ${(n/1e3).toFixed(1)}s`:` after ${Math.max(0,Math.round(n))}ms`:""}. That is the provider's own deadline, not this client's stream budget, so raising AEGIS_SSE_IDLE_TIMEOUT_MS cannot help`}function createClient(e={}){const t=(e.apiBase||envVar("AEGIS_API_BASE")||DEFAULT_API_BASE).replace(/\/+$/,"");let n=void 0!==e.apiKey?e.apiKey:envVar("AEGIS_API_KEY");const r=void 0!==e.memoryToken?e.memoryToken:envVar("AEGIS_MEMORY_TOKEN"),o=e.clientVersion||"3.2.0",s="cli"===e.channel?"cli":"desktop";function a(e){return n&&"string"==typeof e?e.split(n).join("[redacted]"):e}const i={ECONNRESET:"connection reset by the backend",ECONNREFUSED:"connection refused — is the backend running?",EPIPE:"connection closed while sending the request",ETIMEDOUT:"connection timed out",ENOTFOUND:"host not found — check the endpoint URL",EAI_AGAIN:"DNS lookup failed temporarily",EHOSTUNREACH:"host unreachable",ENETUNREACH:"network unreachable",CERT_HAS_EXPIRED:"TLS certificate has expired",DEPTH_ZERO_SELF_SIGNED_CERT:"TLS certificate is self-signed",UND_ERR_SOCKET:"the socket closed before the response finished",UND_ERR_CLOSED:"the connection was closed",UND_ERR_CONNECT_TIMEOUT:"timed out connecting to the backend",UND_ERR_HEADERS_TIMEOUT:"the backend accepted the connection but never sent a response",UND_ERR_BODY_TIMEOUT:"the backend stalled mid-response",UND_ERR_ABORTED:"the request was aborted"};function c(e,t){const n=e instanceof Error?e:new Error(String(e)),r=n&&n.name;if("AbortError"===r||"TimeoutError"===r)return e;const o=l(n),s=t||"the backend",a=new Error(o?`Could not reach ${s} (${o}).`:`Could not reach ${s}: ${n.message||"network failure"}.`);return a.status=0,a.code="network",a.networkCode=o||null,a.data=null,a.cause=n,a}function l(e,t=0){if(!e||t>4)return null;const n=e.code||e.cause&&e.cause.code,r=e.cause,o=r?l(r,t+1):null;return i[n]?i[n]:o||(r&&r.message&&r.message!==e.message?r.message:n||null)}async function u(e,n){const r=n&&n.signal,o="function"==typeof AbortController?new AbortController:null;let s=null;o&&(s=setTimeout((()=>o.abort()),S),s&&"function"==typeof s.unref&&s.unref(),r&&(r.aborted?o.abort():"function"==typeof r.addEventListener&&r.addEventListener("abort",(()=>{o&&o.abort()}),{once:!0})));try{return await fetch(e,{...n||{},signal:o?o.signal:r})}catch(e){if(o&&o.signal.aborted&&(!r||!r.aborted)){const e=new Error(`Timed out after ${S/1e3}s waiting for ${t}.`);throw e.status=0,e.code="timeout",e.data=null,e}throw c(e,t)}finally{s&&clearTimeout(s)}}function d(e,t){const n=e&&e.headers&&"function"==typeof e.headers.get?e.headers.get("retry-after"):null;let r=0;if(n){const e=Number(n);if(Number.isFinite(e)&&e>=0)r=1e3*e;else{const e=Date.parse(n);Number.isFinite(e)&&(r=e-Date.now())}}return r||(r=R*Math.pow(2,t)),Math.min(r,A)}function m(e,t){return new Promise((n=>{const r=setTimeout(n,e);if(r&&"function"==typeof r.unref&&r.unref(),t&&"function"==typeof t.addEventListener)return t.aborted?(clearTimeout(r),void n()):void t.addEventListener("abort",(()=>{clearTimeout(r),n()}),{once:!0})}))}function _(e,t=0){if(!e||t>4)return null;const n=e.code;return"string"==typeof n&&"network"!==n?n:_(e.cause,t+1)}async function f(e,t){let n=0;for(;;)try{return await u(e,t)}catch(e){const r=e&&"network"===e.code?String(_(e)||""):"";if(n>=2||!TRANSIENT_SOCKET_CODE_PATTERN.test(r))throw e;if(t&&t.signal&&t.signal.aborted)throw e;if(await m(500*Math.pow(2,n),t&&t.signal),t&&t.signal&&t.signal.aborted)throw e;n++}}async function E(e,t){let n=await f(e,t);for(let r=0;n&&429===n.status&&r<T;r++){const o=d(n,r);try{n.body&&await n.body.cancel()}catch{}await m(o,t&&t.signal),n=await f(e,t)}for(let r=0;n&&n.status>=500&&n.status<600&&r<2;r++){let o="";try{o=await g(n.clone())}catch{break}if(!TRANSIENT_STREAM_ERROR_PATTERN.test(o))break;await m(500*Math.pow(2,r),t&&t.signal),n=await f(e,t)}return n}function p(e){if(!e)return e;if("AbortError"===e.name||"TimeoutError"===e.name)return e;if("network"===e.code||"timeout"===e.code||"ABORT_ERR"===e.code)return e;if(/^stream stalled - /.test(String(e.message||"")))return e;if(!_(e))return e;const n=c(e,t);return n.bodyPhase=!0,n}async function g(e){if(!e||!e.body||"function"!=typeof e.body.getReader){let t;try{t=await e.text()}catch(e){const t=p(e);throw t&&"network"===t.code&&(t.bytesRead=0),t||e}return t.length>h?t.slice(0,h):t}const n=e.body.getReader(),r=new TextDecoder;let o="",s=0;try{for(;;){let a;try{a=await n.read()}catch(e){const t=p(e);throw t&&"network"===t.code&&(t.bytesRead=s),t||e}const{done:i,value:c}=a;if(i)break;if(s+=c?c.byteLength:0,s>h){const n=new Error(`Response from ${t} exceeded the ${h/1048576}MB cap.`);throw n.status=e.status,n.code="body_too_large",n.data=null,n}o+=r.decode(c,{stream:!0})}return o+=r.decode(),o}finally{try{await n.cancel()}catch{}}}let y=null;const S=Number(e.timeoutMs)>0?Number(e.timeoutMs):Number(envVar("AEGIS_HTTP_TIMEOUT_MS"))>0?Number(envVar("AEGIS_HTTP_TIMEOUT_MS")):6e4,h=Number(e.maxBodyBytes)>0?Number(e.maxBodyBytes):8388608,T=Number(e.rateLimitRetries)>=0?Number(e.rateLimitRetries):4,R=Number(e.rateLimitBaseWaitMs)>=0?Number(e.rateLimitBaseWaitMs):1e3,A=Number(e.rateLimitMaxWaitMs)>0?Number(e.rateLimitMaxWaitMs):3e4;function M(e,n){try{const r=new URL(`/go/${String(e||"upgrade").replace(/^\/+|\/+$/g,"")}`,t);r.searchParams.set("s",s);const o=String(n||"").trim().toLowerCase();return/^[a-z0-9][a-z0-9_-]{0,63}$/.test(o)&&r.searchParams.set("c",o),r.toString()}catch(e){return""}}function D(e){const t={"Content-Type":"application/json","X-AEGIS-Version":o,...e};return n&&(t["X-API-Key"]=n,t.Authorization=`Bearer ${n}`),t}async function L(e,n){return O(await E(`${t}${e}`,n))}async function I(e,t){let n=0;for(;;)try{return await L(e,t)}catch(e){if(!e||"network"!==e.code||!0!==e.bodyPhase||0!==e.bytesRead||n>=2)throw e;if(t&&t.signal&&t.signal.aborted)throw e;if(await m(500*Math.pow(2,n),t&&t.signal),t&&t.signal&&t.signal.aborted)throw e;n++}}async function w(e,t,n,r){return I(e,{method:"POST",headers:n||D(),body:JSON.stringify(t||{}),signal:r&&r.signal})}async function b(e,t,n){return I(e,{method:"GET",headers:t||D(),signal:n&&n.signal})}function N(e,t){const n=e||{},r=n.latest_cli||"",s=n.latest_desktop||"",a=r||s||n.required||"",i=new Error(a?`This client (v${o}) is out of date — upgrade to v${a}.`:`This client (v${o}) is out of date.`);return i.status=t,i.code="version_mismatch",i.data=n,i.upgrade={required:n.required||"",latestCli:r,latestDesktop:s,url:M("upgrade","version_gate")||n.update_url||""},i}async function O(e){const t=await g(e);let n;try{n=t?JSON.parse(t):{}}catch{n={raw:a(t)}}if(!e.ok){if(function(e,t){return 426===e||t&&"version_mismatch"===t.code}(e.status,n))throw N(n,e.status);const t=n&&(n.error?.message||n.error||n.message)||`HTTP ${e.status}`,r=new Error(a("string"==typeof t?t:JSON.stringify(t)));throw e.status>=500&&e.status<600&&SSE_UPSTREAM_TIMEOUT_PATTERN.test(r.message)?(r.serverStatus=e.status,r.status=0,r.code="timeout",r.message=upstreamTimeoutMessage(r.message)):r.status=e.status,r.data=n,r}if(n&&"version_mismatch"===n.code)throw N(n,e.status);return n}function v(e){if(!e)return"";const t=e.error;return"string"==typeof t?t:t&&"string"==typeof t.message?t.message:t&&"string"==typeof t.error?t.error:"string"==typeof e.message?e.message:"string"==typeof e.error_message?e.error_message:""}async function k(){if(r)return r;if(y)return y;const e=await w("/api/verify-api-key",{api_key:n});if(!e||!e.memory_token){const e=M("upgrade","memory_quota");throw new Error("This AEGIS account has no memory token. "+(e?`Enable cloud memory at ${e}`:"Enable cloud memory in your AEGIS account settings."))}return y=e.memory_token,y}function x(e){return{"Content-Type":"application/json","X-AEGIS-Version":o,Authorization:`Bearer ${e}`}}function U(e){if(null==e)return"";if("string"==typeof e)return e;if(!Array.isArray(e))return String(e);let t="";for(let n=0;n<e.length;n+=1){const r=e[n];r&&"object"==typeof r&&("string"==typeof r.text?t+=(t?"\n":"")+r.text:"image_url"===r.type&&(t+=(t?"\n":"")+"[image]"))}return t}function C(e,t,n){const r=Array.isArray(e)?e.filter(Boolean):[],o=[];if(t&&!r.some((e=>e&&"system"===e.role))&&o.push({role:"system",content:t}),o.push(...r),null!=n&&("string"==typeof n?""!==n:Array.isArray(n)&&n.length>0)){const e=o[o.length-1];(Array.isArray(n)&&e&&"user"===e.role?U(e.content)===U(n):e&&"user"===e.role&&e.content===n)||o.push({role:"user",content:n})}return o}function P(e){const t=e&&e.choices&&e.choices[0],n=t&&t.message&&t.message.content;return"string"==typeof n?n:""}function $(e){const t=e&&e.choices&&e.choices[0],n=t&&t.message&&t.message.content;if("string"!=typeof n||-1===n.indexOf("|"))return e;const r=decodeDeepSeekDSML(n),o=decodeDeepSeekDSMLDrift(r.text);t.message.content=dsmlResidue(o.text);const s=[...r.calls,...o.calls];return s.length&&(e.toolCalls=[...Array.isArray(e.toolCalls)?e.toolCalls:[],...s.map((e=>({id:"",name:e.name,args:e.args||{}})))]),e}async function B(e,n,r,o,s,i){const{onReasoning:c,idleTimeoutMs:l,retryWithoutStreamOptions:u,_transientStreamAttempt:d=0}=i||{},_=n=>E(`${t}${e}`,{method:"POST",headers:r,body:JSON.stringify({...n,stream:!0}),signal:s});let f;try{f=await _(n)}catch(e){throw e}if(!f.ok&&426===f.status){let e={};try{const t=await g(f);e=t?JSON.parse(t):{}}catch{e={}}throw N(e,f.status)}if(!f.ok&&u&&n.stream_options){try{f.body&&await f.body.cancel()}catch{}const t={...n};delete t.stream_options,n=t;try{f=await _(n)}catch(e){throw e}}if(!f.ok){const t={...n};delete t.stream_options;const a=$(await w(e,{...t,stream:!1},r,{signal:s})),i=P(a);return i&&o({delta:i}),a}if(!(f.headers.get("content-type")||"").includes("text/event-stream")){const e=$(await O(f)),t=P(e);return t?o({delta:t}):function(e,t){if(e&&"version_mismatch"===e.code)throw N(e,t||426);const n=a(v(e));if(!n)return;const r=new Error(n);throw r.status=t||500,r.data=e,r}(e,f.status),e}const y=f.body.getReader(),S=new TextDecoder;let h="",T="",R="",A=n.model,M=null,D="";const L=new Map;let I=null,b="";const k=makeDeepSeekEnvelopeStripper(),x=idleBudgetFor(f,l);let U=Date.now();const C=U;let K=0;async function G(){let e,t=null;const n=Math.max(0,x-(Date.now()-U)),r=new Promise(((t,r)=>{e=setTimeout((()=>{r(new Error(K>0?`stream stalled - only keep-alives for ${x/1e3}s`:`stream stalled - no data for ${x/1e3}s`))}),n)})),o=s&&"function"==typeof s.addEventListener?new Promise(((e,n)=>{t=()=>{const e=new Error("The turn was stopped.");e.name="AbortError",e.code="ABORT_ERR",n(e)},s.aborted?t():s.addEventListener("abort",t,{once:!0})})):null;try{return await(o?Promise.race([y.read(),r,o]):Promise.race([y.read(),r]))}finally{clearTimeout(e),s&&t&&"function"==typeof s.removeEventListener&&s.removeEventListener("abort",t)}}for(;;){let t,l;try{({done:t,value:l}=await G())}catch(t){y.cancel().catch((()=>{}));const a=p(t);if(a&&"network"===a.code&&(a.bytesRead=b?1:0,0===a.bytesRead&&d<2&&(!s||!s.aborted))){if(await m(500*Math.pow(2,d),s),s&&s.aborted)throw a;return B(e,n,r,o,s,{...i,_transientStreamAttempt:d+1})}throw a||t}if(t)break;h+=S.decode(l,{stream:!0});const u=h.split("\n");h=u.pop();for(const e of u){const t=e.trim();if(!t.startsWith("data:")){t.startsWith(":")&&K++;continue}U=Date.now();const n=t.slice(5).trim();if(!n||"[DONE]"===n)continue;let r;try{r=JSON.parse(n)}catch{continue}if(r.error){if(!D){const e=r.error;D="string"==typeof e?e:v({error:e})||"stream error",D=a(D)}continue}r.model&&(A=r.model),r.usage&&(M=r.usage);const s=r.choices&&r.choices[0];s&&s.finish_reason&&(I=s.finish_reason);const i=(e,t,n,r)=>{if("string"==typeof e&&e)return r(e),n+e;if("string"==typeof t&&t){if(!n)return r(t),t;if(t.startsWith(n)){const e=t.slice(n.length);return e&&r(e),t}return n}return n};R=i(s&&s.delta&&s.delta.reasoning_content,s&&s.message&&s.message.reasoning_content,R,(e=>{"function"==typeof c?c(e):o({reasoning:e})})),T=i(s&&s.delta&&s.delta.content,s&&s.message&&s.message.content,T,(e=>{const t=k(e);t&&(b+=t,o({delta:t}))}));const l=s&&s.delta&&s.delta.tool_calls||s&&s.message&&s.message.tool_calls;if(Array.isArray(l))for(const e of l){const t=null==e.index?0:e.index,n=L.get(t)||{id:"",type:"function",function:{name:"",arguments:""}};e.id&&(n.id=e.id),e.type&&(n.type=e.type);const r=e.function||{};r.name&&(n.function.name=r.name),"string"==typeof r.arguments&&(n.function.arguments+=r.arguments),L.set(t,n)}}}if(!T&&D){if(d<2&&TRANSIENT_STREAM_ERROR_PATTERN.test(D))return await m(500*Math.pow(2,d),s),B(e,n,r,o,s,{...i,_transientStreamAttempt:d+1});const t=SSE_UPSTREAM_TIMEOUT_PATTERN.test(D),a=new Error(t?upstreamTimeoutMessage(D,Date.now()-C):D);throw a.status=t?0:f.status,t&&(a.code="timeout"),a}const V=k.flush();V&&(b+=V,o({delta:V}));const F=[...L.entries()].sort(((e,t)=>e[0]-t[0])).map((([e,t])=>({...t,id:t.id||`call_${e}`}))),J={content:b};R&&(J.reasoning_content=R),F.length&&(J.tool_calls=F);const W={model:A,choices:[{message:J,...I?{finish_reason:I}:{}}]};M&&(W.usage=M);const X=k.calls();return(F.length||X.length)&&(W.toolCalls=[...F.map((e=>({id:e.id,name:e.function.name,args:e.function.arguments}))),...X.map((e=>({id:"",name:e.name,args:e.args||{}})))]),W}return{apiBase:t,get apiKey(){return n},setApiKey:function(e){return n="string"==typeof e?e.trim():"",y=null,n},get clientVersion(){return o},get channel(){return s},promptUrl:M,verifyApiKey:async function(){return w("/api/verify-api-key",{api_key:n})},registerDevice:async function(e,t){return w("/api/v1/auth/register-device",{fingerprint:e,app:t&&t.app},void 0,t)},chatCompletion:async function({prompt:e,system:t,messages:n,model:r,mode:o,maxTokens:s,stream:a=!1,onStream:i,onReasoning:c,idleTimeoutMs:l,includeUsage:u,signal:d,extra:m,agentKey:_}={}){const f={messages:C(n,t,e),...s?{max_tokens:s}:{},...m||{}};r?f.model=r:o&&(f.mode=o);const E=D(_?{"X-AEGIS-Agent-Key":_}:void 0);return a&&"function"==typeof i?(u&&(f.stream_options={include_usage:!0}),B("/api/v1/chat/completions",f,E,i,d,{onReasoning:c,idleTimeoutMs:l,retryWithoutStreamOptions:Boolean(u)})):$(await w("/api/v1/chat/completions",{...f,stream:!1},E,{signal:d}))},byokChatCompletion:async function({provider:t="openai",model:r,messages:s,prompt:a,system:i,maxTokens:c,effort:l,reasoningEffort:u,tools:d,toolChoice:m,stream:_=!1,onStream:f,signal:E,providerKey:p,baseURL:g}={}){const y=void 0!==p?p:e.providerKey;if("custom"===t&&!g){const e=new Error('the "custom" provider dials the endpoint you name, and this call names none — save the address first: /model-add custom <https-base-url> <api-key> <model-id>, or the endpoint field in Settings › Provider (custom).');throw e.status=400,e.code="custom_endpoint_missing",e}const S={provider:t,messages:C(s,i,a),...c?{max_tokens:c}:{},...l?{effort:l}:{},...u?{reasoning_effort:u}:{},...Array.isArray(d)&&d.length?{tools:d}:{},...m?{tool_choice:m}:{},...g?{base_url:g}:{}};r&&(S.model=r);const h={"Content-Type":"application/json","X-AEGIS-Version":o,"X-Provider-Key":y};return n&&(h["X-AEGIS-Key"]=n),_&&"function"==typeof f?B("/api/v1/byok/chat/completions",S,h,f,E):$(await w("/api/v1/byok/chat/completions",{...S,stream:!1},h))},listModels:async function(e){return b("/api/v1/models",null,e)},tokenBankBalance:async function(e){return b("/api/token-bank/balance",null,e)},tokenBankTopup:async function(e){return w("/api/token-bank/topup",{amount_eur:e})},billingCheckout:async function(){return w("/api/billing/checkout",{})},byokStatus:async function(e){return b("/api/user/api-keys",null,e)},byokProviders:async function(e){return b("/api/v1/byok/providers",null,e)},catalog:async function(e,t,n){const r=(e||"models").replace(/^\/+/,""),o=new URLSearchParams;for(const[e,n]of Object.entries(t||{}))null!=n&&""!==n&&o.set(e,String(n));const s=o.toString();return b(`/api/v1/catalog/${r}${s?`?${s}`:""}`,n&&n.etag?{...D(),"If-None-Match":n.etag}:D(),n)},byokSet:async function(e,t){return w("/api/user/api-keys",{provider:e,api_key:t||""})},getMemoryToken:k,memorySearch:async function(e,t){return w("/api/memory/search",{query:e||"",limit:t||5},x(await k()))},memorySave:async function(e){return w("/api/memory/save",{entry:e},x(await k()))},memoryList:async function(e){return w("/api/memory/search",{query:"",limit:e||10},x(await k()))},verifyToken:async function(e){return w("/api/verify-token",{token:e||""},{"Content-Type":"application/json","X-AEGIS-Version":o,Authorization:`Bearer ${e}`})},memoryActivate:async function(e){return w("/api/memory/activate",{},x(e||await k()))},memoryPull:async function(e){return w("/api/memory/pull",{since:e||0},x(await k()))},memorySaveBatch:async function(e){return w("/api/memory/save",{entries:e||[]},x(await k()))},conversationSyncPush:async function(e){const t=await k();return w("/api/conversations/sync",{session_id:e&&e.session_id,title:e&&e.title||"",messages:e&&e.messages||[],source:e&&e.source||"aegis-desktop"},x(t))},conversationSyncPull:async function(){return w("/api/conversations/sync",{},x(await k()))},importConversation:async function({messages:e,url:t,title:n,source:r}={}){return w("/api/import",{messages:e||[],url:t||"",title:n||"",source:r||"aegiscode-plugin"})},driveToken:async function(){try{return await b("/api/drive/token")}catch(e){if(e&&404===e.status)return{connected:!1,access_token:null,email:null};throw e}},randomUUID:randomUUID}}const SSE_IDLE_TIMEOUT_MS=6e4,BRAIN_IDLE_TIMEOUT_MS=9e5;function idleBudgetFor(e,t){const n=Number(t),r=envIdleMs("AEGIS_SSE_IDLE_TIMEOUT_MS"),o=n>0?n:r>0?r:SSE_IDLE_TIMEOUT_MS;let s="";try{const t=e&&e.headers&&"function"==typeof e.headers.get?e.headers.get.bind(e.headers):null;s=t&&t("X-AEGIS-Brain")||""}catch{s=""}const a=envIdleMs("AEGIS_BRAIN_IDLE_TIMEOUT_MS")||BRAIN_IDLE_TIMEOUT_MS;return s&&String(s).trim()?Math.max(o,a):o}function isVersionGateError(e){return!(!e||"version_mismatch"!==e.code)}const api={createClient:createClient,envVar:envVar,randomUUID:randomUUID,DEFAULT_API_BASE:DEFAULT_API_BASE,CLIENT_VERSION:"3.2.0",isVersionGateError:isVersionGateError,idleBudgetFor:idleBudgetFor,SSE_IDLE_TIMEOUT_MS:SSE_IDLE_TIMEOUT_MS,BRAIN_IDLE_TIMEOUT_MS:BRAIN_IDLE_TIMEOUT_MS};"undefined"!=typeof module&&module.exports&&(module.exports=api),"undefined"!=typeof window&&(window.AegisClient=api);
@@ -0,0 +1,3 @@
1
+ // SPDX-License-Identifier: AGPL-3.0-or-later
2
+ // Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
3
+ "use strict";const crypto=require("node:crypto"),fs=require("node:fs"),path=require("node:path"),fp=require("./fingerprint.js"),authorship=require("./authorship-key.js"),envFile=require("./env-file.js"),DEFAULT_HISTORY=()=>path.join(authorship.dataDir(),"history.jsonl"),DIR_KEYS=["cwd","dir","workspace","root"],DEMAND_KEYS=["demand","prompt","task","text","content"],OUTCOME_KEYS=["outcome","status","result"],SESSION_KEYS=["session","sessionId","session_id"],TIME_KEYS=["at","ts","time","createdAt"],REPLY_KEYS=["reply","answer","response"],MODEL_KEYS=["model","aiModel","modelId"],sha256hex=e=>crypto.createHash("sha256").update(String(e||""),"utf8").digest("hex"),AI_SECRET_ENV="AEGIS_AI_SECRET";function firstKey(e,t){for(const r of t){const t=e[r];if(null==t)continue;const o="string"==typeof t?t:String(t);if(""!==o.trim())return o}return null}function readHistory(e){if(!fs.existsSync(e))throw new Error(`attest: no session log at ${e}`);const t=[];let r=0;for(const o of fs.readFileSync(e,"utf8").split("\n")){const e=o.trim();if(e)try{const o=JSON.parse(e);o&&"object"==typeof o?t.push(o):r+=1}catch{r+=1}}return{entries:t,skipped:r}}function lastSessionId(e){for(let t=e.length-1;t>=0;t-=1){const r=firstKey(e[t],SESSION_KEYS);if(r)return r}return null}function selectTurns(e,{session:t=null,turns:r=null}={}){let o=e;if(t){const r=String(t);o=e.filter((e=>firstKey(e,SESSION_KEYS)===r))}return r&&Number.isFinite(Number(r))&&Number(r)>0&&(o=o.slice(-Math.floor(Number(r)))),o}function observationsFromTurns(e){const t=[];for(const r of Array.isArray(e)?e:[]){if(!r||"object"!=typeof r)continue;const e=firstKey(r,DIR_KEYS),o=firstKey(r,DEMAND_KEYS);t.push({tool:o||e?"turn":null,target:`${e?path.basename(e):"?"}#${sha256hex(o||"").slice(0,8)}`,outcome:firstKey(r,OUTCOME_KEYS)})}return t}function aiObservationsFromTurns(e){const t=[];for(const r of Array.isArray(e)?e:[]){if(!r||"object"!=typeof r)continue;const e=firstKey(r,REPLY_KEYS),o=firstKey(r,OUTCOME_KEYS),s=firstKey(r,MODEL_KEYS),n=Boolean(e||o||s);t.push({tool:n?"reply":null,target:n?`reply#${sha256hex(e||"").slice(0,8)}`:null,outcome:o||null,model:s})}return t}function resolveAiSecret(e={}){const t=e.argv||[],r=e.env||{},o=firstFlag(t,["--ai-secret","--ai-secret-file"]);if(o){const e=fs.readFileSync(o,"utf8").trim();if(!e)throw new Error(`attest: ${o} is empty — an empty AI credential is not one`);return{secret:e,source:o}}const s=r[AI_SECRET_ENV]&&String(r[AI_SECRET_ENV]).trim();if(s)return{secret:s,source:AI_SECRET_ENV};const n=String(e.aiModel||e.model||"").trim();if(n&&"function"==typeof envFile.providerForModelId){const t=envFile.providerForModelId(n,e.cls);if(t){const e=envFile.providerKeyFromEnv(t,r);if(e&&e.key)return{secret:e.key,source:e.env};const o=providerKeyFromFile(t,r);if(o)return o}}return{secret:null,source:"none"}}function providerKeyFromFile(e,t){const r="function"==typeof envFile.envVarFor?envFile.envVarFor(e):"";if(!r)return null;const o=t&&(t.AEGIS_HOME||t.AEGISCODE_HOME)?String(t.AEGIS_HOME||t.AEGISCODE_HOME):void 0;let s;try{s=envFile.parseEnvText(fs.readFileSync(envFile.envFileFor(o),"utf8"))}catch{return null}const n=s&&"string"==typeof s[r]?s[r].trim():"";return n&&("function"!=typeof envFile.credentialLooksUsable||envFile.credentialLooksUsable(n))?{secret:n,source:r}:null}function firstFlag(e,t){for(const r of t){const t=e.indexOf(r);if(-1!==t&&void 0!==e[t+1]&&!String(e[t+1]).startsWith("--"))return e[t+1]}return null}const SKIP_DIRS=new Set([".git","node_modules","dist","build","out","vendor",".venv","venv","__pycache__",".next",".cache","release","coverage"]),MAX_FILE_BYTES=2097152,MAX_FILES=4096;function collectCode({roots:e=[],files:t=[],skip:r=[]}={}){const o=new Set(r),s=[],n=(e,t)=>{const r=fs.statSync(t);if(!r.isFile())return;if(r.size>2097152)throw new Error(`attest: ${t} is ${r.size} bytes — too large to attest (max 2097152)`);if(s.length>=4096)throw new Error("attest: more than 4096 files — refusing to attest a partial walk");const o=fp.normaliseCodePath(e);o&&s.push({path:o,content:fs.readFileSync(t,"utf8")})};for(const t of e){const e=path.resolve(t),r=(e,t)=>{for(const s of fs.readdirSync(e).sort()){const i=path.join(e,s),c=t?`${t}/${s}`:s,l=fs.lstatSync(i);if(!l.isSymbolicLink())if(l.isDirectory()){if(SKIP_DIRS.has(s)||o.has(s))continue;r(i,c)}else n(c,i)}};r(e,"")}for(const e of t){const t=path.resolve(e);n(path.basename(t),t)}return s}function mintSession(e={}){const t=e.key||authorship.resolveKey(e);if(!t.secret)throw new Error(`attest: no authorship key — run \`aegiscode fingerprint keygen\`, set ${authorship.SECRET_ENV}, or pass --secret <file>`);const r=e.history||DEFAULT_HISTORY(),{entries:o,skipped:s}=readHistory(r),n=selectTurns(o,{session:e.session||lastSessionId(o),turns:e.turns}),i=observationsFromTurns(n),c=e.code||[],l=e.aiObservations||aiObservationsFromTurns(n),a=void 0!==e.aiModel&&null!==e.aiModel?e.aiModel:l.map((e=>e.model)).filter(Boolean).pop()||"",u=void 0===e.aiSecret?resolveAiSecret({...e,aiModel:a}):{secret:e.aiSecret,source:e.aiSecret?"caller":"none"},S=fp.mint({secret:t.secret,label:e.label,account:e.account,model:e.model,tools:e.tools,observations:i,code:c,codeDirty:void 0===e.codeDirty?null:e.codeDirty,aiSecret:u.secret,aiModel:a,aiObservations:l,createdAt:e.createdAt||void 0});return{record:S,keySource:t.source,public:t.public,samples:S.behaviourSamples,observations:i.length,aiKeySource:u.source,aiSamples:S.aiSamples,skippedLines:s}}module.exports={DEFAULT_HISTORY:DEFAULT_HISTORY,DIR_KEYS:DIR_KEYS,DEMAND_KEYS:DEMAND_KEYS,OUTCOME_KEYS:OUTCOME_KEYS,SESSION_KEYS:SESSION_KEYS,REPLY_KEYS:REPLY_KEYS,MODEL_KEYS:MODEL_KEYS,AI_SECRET_ENV:AI_SECRET_ENV,TIME_KEYS:TIME_KEYS,SKIP_DIRS:SKIP_DIRS,MAX_FILE_BYTES:2097152,MAX_FILES:4096,firstKey:firstKey,readHistory:readHistory,lastSessionId:lastSessionId,selectTurns:selectTurns,observationsFromTurns:observationsFromTurns,aiObservationsFromTurns:aiObservationsFromTurns,resolveAiSecret:resolveAiSecret,collectCode:collectCode,mintSession:mintSession};
@@ -0,0 +1,3 @@
1
+ // SPDX-License-Identifier: AGPL-3.0-or-later
2
+ // Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
3
+ "use strict";const crypto=require("node:crypto"),fs=require("node:fs"),os=require("node:os"),path=require("node:path"),{execFileSync:execFileSync}=require("node:child_process"),fp=require("./fingerprint.js"),KEY_FILE_MODE=384,DIR_MODE=448,GROUP_OTHER_BITS=63,KEY_BYTES=32,SECRET_ENV="AEGIS_FINGERPRINT_SECRET",HOME_ENV="AEGIS_HOME",KEY_FILENAME="authorship.key",isWin="win32"===process.platform;function dataDir(e=process.env){const r=e[HOME_ENV];return r&&String(r).trim()?path.resolve(String(r).trim()):path.join(os.homedir(),".aegiscode")}function defaultKeyPath(e=process.env){return path.join(dataDir(e),"keys",KEY_FILENAME)}function modeOf(e){return 511&fs.statSync(e).mode}function modeString(e){return e.toString(8).padStart(3,"0")}function assertPrivate(e){if(isWin)return;const r=modeOf(e);if(r&GROUP_OTHER_BITS)throw new Error(`authorship-key: ${e} is mode ${modeString(r)} — a secret file must not be group/other readable. chmod 600 ${e}`)}function readSecretFile(e){const r=fs.readFileSync(e,"utf8").replace(/\r?\n$/,"");if(!r.trim())throw new Error(`authorship-key: ${e} is empty`);if(/\s/.test(r.trim()))throw new Error(`authorship-key: ${e} holds more than one line — not a key file`);return r.trim()}function flag(e,r,t=null){const i="--secret"===r?["--secret","--secret-file"]:[r];for(const r of i){const t=e.indexOf(r);if(-1!==t&&void 0!==e[t+1]&&!e[t+1].startsWith("--"))return e[t+1]}return t}function hasFlag(e,r){return("--secret"===r?["--secret","--secret-file"]:[r]).some((r=>e.includes(r)))}function resolveKey(e={}){const r=e.argv||[],t=e.env||process.env,i=flag(r,"--secret");if(i){if(!fs.existsSync(i))throw new Error(`authorship-key: no such secret file: ${i}`);return assertPrivate(i),{secret:readSecretFile(i),source:i,public:!1,path:i}}if(hasFlag(r,"--public")){const e=flag(r,"--covenant");if(!e)throw new Error("authorship-key: --public requires --covenant <file> — the public key IS the covenant document's hash, so it cannot be assumed");if(!fs.existsSync(e))throw new Error(`authorship-key: no such covenant file: ${e}`);return{secret:crypto.createHash("sha256").update(fs.readFileSync(e)).digest("hex"),source:`covenant (public): ${e}`,public:!0,path:null}}const o=t[SECRET_ENV];if(o&&String(o).trim())return{secret:String(o).trim(),source:SECRET_ENV,public:!1,path:null};const n=defaultKeyPath(t);return fs.existsSync(n)?(assertPrivate(n),{secret:readSecretFile(n),source:n,public:!1,path:n}):{secret:null,source:null,public:!1,path:null}}function writeSecret(e,r){try{fs.mkdirSync(path.dirname(e),{recursive:!0,mode:DIR_MODE}),fs.writeFileSync(e,r+"\n",{mode:KEY_FILE_MODE})}catch(r){const t=r&&r.code,i=path.dirname(e);if("EACCES"===t||"EPERM"===t)throw new Error(`authorship-key: cannot write ${e} — ${i} is not writable by this user (${t}). Fix it with: chmod u+rwx ${i}`);if("EROFS"===t)throw new Error(`authorship-key: cannot write ${e} — ${i} is on a read-only filesystem (EROFS). Point --out (or $AEGIS_HOME) at a writable location.`);if("ENOSPC"===t)throw new Error(`authorship-key: cannot write ${e} — the disk is full (ENOSPC).`);throw r}}function keygen(e={}){const r=e.argv||[],t=e.env||process.env,i=path.resolve(flag(r,"--out")||defaultKeyPath(t)),o=hasFlag(r,"--force")||!0===e.force,n=fs.existsSync(i);if(n&&!o)throw new Error(`authorship-key: ${i} already exists — pass --force to replace it`);n&&!isWin&&assertPrivate(i);const s=crypto.randomBytes(32).toString("base64url");if(writeSecret(i,s),fs.chmodSync(i,KEY_FILE_MODE),!isWin){const e=modeOf(i);if(e!==KEY_FILE_MODE)throw new Error(`authorship-key: ${i} landed mode ${modeString(e)}, expected 600 — refusing to report success for a key another user may be able to read`)}if(readSecretFile(i)!==s)throw new Error(`authorship-key: ${i} does not read back as written`);return{out:i,created:!n,replaced:n,keyFingerprint:fp.keyFingerprint(s),bytes:32,secretPrinted:!1,mode:isWin?"n/a":modeString(modeOf(i))}}function git(e,r){try{return execFileSync("git",e,{cwd:r,encoding:"utf8",stdio:["ignore","pipe","ignore"]})}catch{return null}}function insideGitTree(e){return"true\n"===git(["rev-parse","--is-inside-work-tree"],e)}function backup(e={}){const r=e.argv||[],t=e.env||process.env,i=flag(r,"--to");if(!i)throw new Error("authorship-key: backup requires --to DIR");const o=flag(r,"--secret")||defaultKeyPath(t);if(!fs.existsSync(o))throw new Error(`authorship-key: no key at ${o} — run keygen first`);assertPrivate(o);const n=path.resolve(i),s=flag(r,"--name")||path.basename(o),a=path.join(n,s);if(insideGitTree(n)&&!hasFlag(r,"--allow-git")&&!e.allowGit&&null===git(["check-ignore","-q",a],n))throw new Error(`authorship-key: ${a} is inside a git working tree and is not gitignored — a committed key cannot be un-published. Add it to .gitignore, choose another --to, or pass --allow-git if you know the destination is protected`);const c=readSecretFile(o);if(writeSecret(a,c),fs.chmodSync(a,KEY_FILE_MODE),!isWin&&modeOf(a)!==KEY_FILE_MODE)throw new Error(`authorship-key: ${a} landed mode ${modeString(modeOf(a))}, expected 600`);if(readSecretFile(a)!==c)throw new Error(`authorship-key: ${a} does not read back as the same key`);return{from:o,to:a,keyFingerprint:fp.keyFingerprint(c),matchesSource:!0,secretPrinted:!1}}module.exports={KEY_FILE_MODE:KEY_FILE_MODE,DIR_MODE:DIR_MODE,GROUP_OTHER_BITS:GROUP_OTHER_BITS,KEY_BYTES:32,SECRET_ENV:SECRET_ENV,HOME_ENV:HOME_ENV,KEY_FILENAME:KEY_FILENAME,dataDir:dataDir,defaultKeyPath:defaultKeyPath,assertPrivate:assertPrivate,readSecretFile:readSecretFile,flag:flag,hasFlag:hasFlag,resolveKey:resolveKey,keygen:keygen,backup:backup,modeString:modeString};
@@ -0,0 +1,3 @@
1
+ // SPDX-License-Identifier: AGPL-3.0-or-later
2
+ // Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
3
+ "use strict";const{machineFingerprint:machineFingerprint}=require("./device-fingerprint.js"),DEVICE_REGISTER_TIMEOUT_MS=8e3,DEVICE_REGISTER_RETRY_DELAYS_MS=[1e3,3e3];function isTransientRegisterError(e){const r=e&&e.status;return!r||408===r||r>=500}function provisionFailureText(e){const r=e&&e.error;return r?429===r.status?"too many sign-ups from this network — try again later":r.status>=500?`aegiscloud.org failed to register this device: ${r.message}`:isTransientRegisterError(r)?"could not reach aegiscloud.org":`the server refused the request (HTTP ${r.status})`:"the server returned no account key"}function trialOutcomeNote(e){return e&&e.reusedAccount?". This machine was already registered, so it got its existing account back — the welcome trial is granted once per machine, ever, and was not granted again. A fresh trial needs a new sign-up, not a new key.":e&&!1===e.trialGranted?". The welcome trial was withheld this hour (too many new devices from this network)":""}async function autoProvisionApiKey(e,r,t={}){if(Array.isArray(t))throw new TypeError("autoProvisionApiKey takes { app, retryDelaysMs }; a bare retry array is no longer accepted");if(e.apiKey)return{ok:!0,key:e.apiKey};const{app:i,retryDelaysMs:n=DEVICE_REGISTER_RETRY_DELAYS_MS}=t;let o=null;for(let t=0;t<=n.length;t++){t>0&&await new Promise((e=>setTimeout(e,n[t-1])));const a=new AbortController,s=setTimeout((()=>a.abort()),8e3);try{const t=await e.registerDevice(machineFingerprint(),{app:i,signal:a.signal}),n=t&&"string"==typeof t.api_key?t.api_key.trim():"";if(!n)return{ok:!1,key:""};const o=r.saveApiKey(n);return e.setApiKey(n),{ok:!!o.ok,key:n,trialGranted:t.trial_granted,reusedAccount:!0===t.reused_account}}catch(e){if(o=e,!isTransientRegisterError(e))break}finally{clearTimeout(s)}}return{ok:!1,key:"",error:o}}module.exports={autoProvisionApiKey:autoProvisionApiKey,provisionFailureText:provisionFailureText,trialOutcomeNote:trialOutcomeNote,DEVICE_REGISTER_TIMEOUT_MS:8e3,DEVICE_REGISTER_RETRY_DELAYS_MS:DEVICE_REGISTER_RETRY_DELAYS_MS};
@@ -0,0 +1,3 @@
1
+ // SPDX-License-Identifier: AGPL-3.0-or-later
2
+ // Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
3
+ "use strict";const NEXUS_BRAIN_IDS=Object.freeze(["nexus-brain","aegis-brain"]),AEGIS_CLOUD_MODEL_IDS=Object.freeze(["nexus-brain","aegis-brain","nexus-brain-smart","aegis-brain-smart","nexus-brain-neo","aegis-brain-neo"]),AEGIS_CLOUD_MODEL_RE=/^(?:nexus|aegis)-brain(?:-(?:smart|neo))?$/,NEXUS_LABEL="Nexus";function aliasOfEntry(e){if(!e||"object"!=typeof e)return null;for(const i of[e.alias_of,e.aliasOf])if("string"==typeof i&&i.trim())return i.trim();return null}function isHiddenEntry(e){return Boolean(e)&&!0===e.hidden}function selectBrainEntry(e){const i=Array.isArray(e)?e.filter(Boolean):[];return i.find((e=>NEXUS_BRAIN_IDS.includes(e.id)&&!isHiddenEntry(e)&&null===aliasOfEntry(e)))||i.find((e=>NEXUS_BRAIN_IDS.includes(e.id)))||i.find((e=>NEXUS_BRAIN_IDS.includes(aliasOfEntry(e))))||null}function filterAegisCatalog(e){const i=selectBrainEntry(e);if(!i)return[];const{hidden:n,alias_of:t,aliasOf:r,...s}=i;return[{...s,label:"Nexus"}]}function isAegisCloudModel(e){const i="string"==typeof e?e.trim():e&&"object"==typeof e&&"string"==typeof e.id?e.id.trim():"";return!!AEGIS_CLOUD_MODEL_IDS.includes(i)||!!AEGIS_CLOUD_MODEL_RE.test(i)||NEXUS_BRAIN_IDS.includes(aliasOfEntry(e))}function omitAegisCloudModels(e){return(Array.isArray(e)?e:[]).filter((e=>{if(!e)return!1;if("string"==typeof e)return!isAegisCloudModel(e);const i="string"==typeof e.id?e.id.trim():"";return Boolean(i)&&!isAegisCloudModel(e)}))}function offerableCatalog(e){const i=Array.isArray(e)?e.filter(Boolean):[];if(!i.length)return[];const n=selectBrainEntry(i),t=[],r=new Set;if(n){const{hidden:e,alias_of:i,aliasOf:s,...o}=n;t.push({...o,label:"Nexus"});for(const e of NEXUS_BRAIN_IDS)r.add(e);"string"==typeof n.id&&r.add(n.id)}const s=new Set(i.map((e=>"string"==typeof e.id?e.id.trim():"")).filter(Boolean)),o=new Set(i.map((e=>aliasOfEntry(e))).filter((e=>e&&s.has(e))));for(const e of i){const i="string"==typeof e.id?e.id.trim():"";i&&!r.has(i)&&(aliasOfEntry(e)&&o.has(aliasOfEntry(e))||(r.add(i),t.push(e)))}return t}module.exports={NEXUS_BRAIN_IDS:NEXUS_BRAIN_IDS,NEXUS_LABEL:"Nexus",AEGIS_CLOUD_MODEL_IDS:AEGIS_CLOUD_MODEL_IDS,isAegisCloudModel:isAegisCloudModel,omitAegisCloudModels:omitAegisCloudModels,selectBrainEntry:selectBrainEntry,filterAegisCatalog:filterAegisCatalog,offerableCatalog:offerableCatalog};
@@ -0,0 +1,3 @@
1
+ // SPDX-License-Identifier: AGPL-3.0-or-later
2
+ // Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
3
+ "use strict";const BYOK_MODEL_ADDITIONS=Object.freeze({}),WIRE_MODEL_ALIASES=Object.freeze({deepseek:Object.freeze({"deepseek-v4.1-flash":"deepseek-flash","deepseek-flash-41":"deepseek-flash","deepseek-flash-0731":"deepseek-flash","deepseek-v4-flash-0731":"deepseek-flash","deepseek-pro":"deepseek-v4-pro","deepseek-v4-pro-latest":"deepseek-v4-pro"})});function canonicalModelId(e,r){const s="string"==typeof r?r.trim():"";if(!s)return s;const o="string"==typeof e?e.trim():"",t=o?WIRE_MODEL_ALIASES[o]:null;return t&&Object.prototype.hasOwnProperty.call(t,s)?t[s]:s}function addedModelsFor(e){const r="string"==typeof e?e.trim():"",s=r?BYOK_MODEL_ADDITIONS[r]:null;return Array.isArray(s)?s.slice():[]}function modelIdsOf(e){return(Array.isArray(e&&e.models)?e.models:[]).map((e=>"string"==typeof e?e:e&&e.id)).map((e=>"string"==typeof e?e.trim():"")).filter(Boolean)}function withByokAdditions(e){const r=Array.isArray(e)?e:Array.isArray(e&&e.providers)?e.providers:null;if(!r)return[];const s=[];for(const e of r){if(!e||"object"!=typeof e)continue;const r="string"==typeof e.id?e.id.trim():"",o=r?BYOK_MODEL_ADDITIONS[r]:null;if(!Array.isArray(o)||!o.length){s.push(e);continue}const t=new Set(modelIdsOf(e)),n=o.filter((e=>!t.has(e)));if(!n.length){s.push(e);continue}const d=Array.isArray(e.models)?e.models:[];s.push({...e,models:[...d,...n]})}return s}module.exports={BYOK_MODEL_ADDITIONS:BYOK_MODEL_ADDITIONS,WIRE_MODEL_ALIASES:WIRE_MODEL_ALIASES,addedModelsFor:addedModelsFor,canonicalModelId:canonicalModelId,withByokAdditions:withByokAdditions};
@@ -0,0 +1,3 @@
1
+ // SPDX-License-Identifier: AGPL-3.0-or-later
2
+ // Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
3
+ "use strict";const fs=require("fs"),path=require("path"),credentials=require("./credentials.js"),CATALOG_FILE="catalog.json",STALE_AFTER_MS=864e5;function catalogDir(e){return e&&e.dir||credentials.aegisHome(e&&e.env)}function catalogPath(e){return path.join(catalogDir(e),CATALOG_FILE)}function modelIdsOf(e){return(Array.isArray(e&&e.models)?e.models:[]).map((e=>"string"==typeof e?e:e&&e.id)).map((e=>"string"==typeof e?e.trim():"")).filter(Boolean)}function providerArray(e){return Array.isArray(e)?e:Array.isArray(e&&e.providers)?e.providers:null}function indexCatalog(e){const t=Object.create(null),r=Array.isArray(e&&e.models)?e.models:[];for(const e of r){if(!e||"object"!=typeof e)continue;const r="string"==typeof e.provider_id?e.provider_id.trim():"",o="string"==typeof e.model_id?e.model_id.trim():"";r&&o&&"active"===("string"==typeof e.status?e.status.toLowerCase():"active")&&(t[r]||(t[r]=[])).push(o)}return t}function read(e){const t=catalogPath(e);let r,o;try{r=fs.readFileSync(t,"utf8")}catch(e){return null}try{o=JSON.parse(r)}catch(e){return null}if(!o||"object"!=typeof o||!Array.isArray(o.providers))return null;let n=null;const a=o.snapshot&&(o.snapshot.fetched_at||o.snapshot.fetchedAt);if("string"==typeof a&&a){const e=Date.parse(a);Number.isNaN(e)||(n=e)}if(null===n)try{n=fs.statSync(t).mtimeMs}catch(e){n=null}const s=null===n?null:Math.max(0,Date.now()-n);let i=null;const l=o.snapshot&&o.snapshot.revalidated_at;if("string"==typeof l&&l){const e=Date.parse(l);Number.isNaN(e)||(i=e)}const d=null!==i&&(null===n||i>n)?i:n;return{data:o,fetchedAt:n,revalidatedAt:i,ageMs:s,stale:null===d||Date.now()-d>STALE_AFTER_MS,path:t}}function write(e,t){const r=catalogPath(t);fs.mkdirSync(path.dirname(r),{recursive:!0});const o=`${r}.${process.pid}.tmp`;return fs.writeFileSync(o,JSON.stringify(e),"utf8"),fs.renameSync(o,r),r}function withCatalog(e,t,r){const o=providerArray(e);if(!o)return[];let n=t;if(void 0===n){const e=read(r);n=e?e.data:null}const a=indexCatalog(n);if(!Object.keys(a).length)return o.slice();const s=[];for(const e of o){if(!e||"object"!=typeof e)continue;const t="string"==typeof e.id?e.id.trim():"",r=t?a[t]:null;if(!r||!r.length){s.push(e);continue}const o=new Set(modelIdsOf(e)),n=r.filter((e=>!o.has(e)));if(!n.length){s.push(e);continue}const i=Array.isArray(e.models)?e.models:[];s.push({...e,models:[...i,...n]})}return s}function addedModelsFor(e,t,r,o){const n="string"==typeof e?e.trim():"";if(!n)return[];let a=r;if(void 0===a){const e=read(o);a=e?e.data:null}const s=indexCatalog(a)[n]||[],i=(providerArray(t)||[]).find((e=>e&&"string"==typeof e.id&&e.id.trim()===n)),l=new Set(modelIdsOf(i));return s.filter((e=>!l.has(e)))}const MAX_PAGES=200;async function refresh(e,t){const r=t||{},o=r.limit||500,n=r.maxPages||200,a=read(r),s=a&&a.data||null,i=[];let l=null,d=0,c=r.etag||null,u=null,f=!1;try{for(;;){const t=await e({cursor:l,limit:o,etag:c});if(!t||t.notModified){f=!0;break}0===d&&t.etag&&(u=t.etag);const r=Array.isArray(t.models)?t.models:[];for(const e of r)e&&"object"==typeof e&&i.push(e);if(d+=1,!t.has_more||!t.next_cursor)break;if(d>=n)return _refreshResult({ok:!1,changed:!1,pages:d,models:i.length,providers:0,staleKept:Boolean(s),reason:`stopped after ${d} pages; cache left untouched`});l=t.next_cursor,c=null}}catch(e){return _refreshResult({ok:!1,changed:!1,pages:d,models:0,providers:0,staleKept:Boolean(s),reason:e&&e.message||String(e)})}if(f){let e=null;if(s)try{const t="function"==typeof r.now?r.now():Date.now();e=write({...s,snapshot:{...s.snapshot||{},revalidated_at:new Date(t).toISOString(),...u?{etag:u}:{}}},r)}catch{e=null}return _refreshResult({ok:!0,changed:!1,pages:0,models:0,providers:0,staleKept:!e,written:e,reason:"not-modified"})}if(!i.length)return _refreshResult({ok:!1,changed:!1,pages:d,models:0,providers:0,staleKept:Boolean(s),reason:"empty catalog; cache left untouched"});const p=s&&Array.isArray(s.providers)?s.providers:[],h="function"==typeof r.now?r.now():Date.now(),g={schema_version:s&&s.schema_version||1,providers:p,models:i,snapshot:{fetched_at:new Date(h).toISOString(),models_seen:i.length,providers_seen:p.length,source:"catalog-api",...u?{etag:u}:{}}};let m=null;try{m=write(g,r)}catch(e){return _refreshResult({ok:!1,changed:!1,pages:d,models:i.length,providers:p.length,staleKept:Boolean(s),reason:e&&e.message||String(e)})}return _refreshResult({ok:!0,changed:!0,pages:d,models:i.length,providers:p.length,staleKept:!1,written:m})}function _refreshResult(e){return{ok:Boolean(e.ok),changed:Boolean(e.changed),written:e.written||null,pages:e.pages||0,models:e.models||0,providers:e.providers||0,staleKept:Boolean(e.staleKept),...e.reason?{reason:e.reason}:{}}}module.exports={CATALOG_FILE:CATALOG_FILE,STALE_AFTER_MS:STALE_AFTER_MS,MAX_PAGES:200,catalogDir:catalogDir,catalogPath:catalogPath,indexCatalog:indexCatalog,read:read,write:write,refresh:refresh,withCatalog:withCatalog,addedModelsFor:addedModelsFor};
@@ -0,0 +1,3 @@
1
+ // SPDX-License-Identifier: AGPL-3.0-or-later
2
+ // Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
3
+ "use strict";const SCOPE_CONVERSATION="conversation",SCOPE_MEMORY="memory",SCOPE_TEXT={conversation:"one conversation",memory:"the whole memory base"};function keyTag(e){const n="string"==typeof e?e.trim():"";return n?`φ_${n}`:null}function authorLine(e){return keyTag(e)||"no key — this copy is unsigned"}function safeFileName(e,n){return String(e||n||"aegis-export").normalize("NFKD").replace(/[^\w.-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,80)||"aegis-export"}function stamp({scope:e,keyFingerprint:n=null,email:t=null,exportedAt:o=null,subject:r=null,count:i=null}={}){const a=keyTag(n),s=[];return r&&s.push(`**What this is:** ${r}`),s.push(`**Scope:** ${SCOPE_TEXT[e]||String(e||"unknown")} (${e||"unknown"})`),s.push(`**Author:** ${authorLine(n)}`),s.push(`**Account:** ${t||"not reported by the server"}`),null!=i&&s.push(`**Entries:** ${i}`),s.push(`**Exported:** ${o||"timestamp not recorded"}`),s.push(a?`**Sealed by:** ${a} — this is a key tag, not the key. It proves the same machine wrote it.`:"**Sealed by:** nothing — no authorship key is set on this machine, so this copy cannot prove it came from you."),`${s.join("\n")}\n\n`}function conversationMarkdown(e,n={}){return`# ${e&&(e.title||e.id)||"Untitled conversation"}\n\n${stamp({scope:"conversation",subject:null,keyFingerprint:n.keyFingerprint,email:n.email,exportedAt:n.exportedAt,count:void 0===n.count?null:n.count})}---\n\n${n.transcript||""}`}function memoryMarkdown(e,n={}){return`${stamp({scope:"memory",subject:null,keyFingerprint:n.keyFingerprint,email:n.email,exportedAt:n.exportedAt,count:void 0===n.count?null:n.count})}---\n\n${e||""}`}function conversationFileName(e,n){const t=String(n||"").replace(/[:.]/g,"-").replace(/[^\w-]+/g,""),o=safeFileName(e&&(e.title||e.id),"conversation");return t?`${o}-${t}.md`:`${o}.md`}module.exports={SCOPE_CONVERSATION:"conversation",SCOPE_MEMORY:"memory",SCOPE_TEXT:SCOPE_TEXT,keyTag:keyTag,authorLine:authorLine,safeFileName:safeFileName,stamp:stamp,conversationMarkdown:conversationMarkdown,memoryMarkdown:memoryMarkdown,conversationFileName:conversationFileName};
@@ -0,0 +1,3 @@
1
+ // SPDX-License-Identifier: AGPL-3.0-or-later
2
+ // Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
3
+ "use strict";const fs=require("node:fs"),os=require("node:os"),path=require("node:path"),KEY_ENV="AEGIS_API_KEY",MEMORY_ENV="AEGIS_MEMORY_TOKEN",HOME_ENV="AEGISCODE_HOME",CREDENTIALS_FILE="credentials.json",CONFIG_FILE="config.json",FILE_MODE=384,DIR_MODE=448;function aegisHome(e){const r=e||process.env,n=r&&r[HOME_ENV];return n&&String(n).trim()?path.resolve(String(n).trim()):path.join(os.homedir(),".aegiscode")}function credentialsPath(e){return path.join(e||aegisHome(),CREDENTIALS_FILE)}function configPath(e){return path.join(e||aegisHome(),CONFIG_FILE)}function normalizeApiKey(e){let r=String(null==e?"":e).trim();if(!r)return"";r=r.replace(/^export\s+/i,"").trim();const n=/^[A-Za-z_][A-Za-z0-9_]*\s*=\s*(.+)$/s.exec(r);return n&&(r=n[1].trim()),r=r.replace(/^["']|["']$/g,"").trim(),r=r.replace(/^Bearer\s+/i,"").trim(),r}function validateApiKey(e,r={}){const n=String(r.label||"AEGIS"),t=normalizeApiKey(e);return t?/\s/.test(t)?{ok:!1,key:t,reason:"whitespace",message:"that looks like more than one word — paste just the key"}:t.length<16?{ok:!1,key:t,reason:"too short",message:`that key is ${t.length} characters — ${n} keys are longer than that`}:{ok:!0,key:t,reason:null,message:null}:{ok:!1,key:t,reason:"empty",message:"no key given"}}function readCredentials(e){try{const r=JSON.parse(fs.readFileSync(credentialsPath(e),"utf8"));if(r&&"object"==typeof r)return r}catch{}return{}}function writeCredentials(e,r){const n=credentialsPath(r),t={...readCredentials(r),...e,version:1};try{fs.mkdirSync(path.dirname(n),{recursive:!0,mode:DIR_MODE});const e=n+".tmp";fs.writeFileSync(e,JSON.stringify(t,null,2)+"\n",{mode:FILE_MODE}),fs.renameSync(e,n);try{fs.chmodSync(n,FILE_MODE)}catch{}}catch(e){return process.env.AEGIS_HIST_DEBUG&&console.error("[credentials] write failed:",e),{ok:!1,error:e,credentials:t}}return{ok:!0,credentials:t}}function readLegacyConfig(e){try{const r=JSON.parse(fs.readFileSync(configPath(e),"utf8"));if(!r||"object"!=typeof r)return{};const n=r.aegiscloud&&"object"==typeof r.aegiscloud?r.aegiscloud:{},t=r.memory&&"object"==typeof r.memory?r.memory:{};return{apiKey:normalizeApiKey(n.api_key),memoryToken:String(t.token||"").trim(),syncConversations:!0===n.syncConversations||void 0,lastVerified:n.lastVerified||null,memorySubscribed:!0===t.subscribed||void 0}}catch{return{}}}function legacyKeyOnDisk(e){return!!readLegacyConfig(e).apiKey}function adoptLegacy(e){const r=readLegacyConfig(e),n=readCredentials(e),t={};return r.apiKey&&!n.aegisApiKey&&(t.aegisApiKey=r.apiKey),r.memoryToken&&!n.memoryToken&&(t.memoryToken=r.memoryToken),Object.keys(t).length&&writeCredentials({...t,adoptedFrom:configPath(e)},e).ok?{adopted:Object.keys(t)}:{adopted:[]}}function fromEnvFile(e,r,n){try{const t=require("./env-file.js");return"function"==typeof t.isFromEnvFile&&t.isFromEnvFile(e,r,n?{env:n}:void 0)}catch{return!1}}function resolveApiKey(e={}){const r=e.env||process.env,n=e.dir,t=normalizeApiKey(r&&r[KEY_ENV]);if(t&&!fromEnvFile(KEY_ENV,r&&r[KEY_ENV],r))return{key:t,source:"env",from:KEY_ENV};const o=normalizeApiKey(readCredentials(n).aegisApiKey);if(o)return{key:o,source:"credentials",from:credentialsPath(n)};if(t)return{key:t,source:"envfile",from:envFileLabel(r,n)};const i=readLegacyConfig(n).apiKey;return i?{key:i,source:"config",from:configPath(n)}:{key:"",source:"none",from:""}}function hasApiKey(e={}){return!!resolveApiKey(e).key}function saveApiKey(e,r){const n=validateApiKey(e);if(!n.ok)return{ok:!1,key:n.key,path:credentialsPath(r),message:n.message};const t=writeCredentials({aegisApiKey:n.key,savedAt:(new Date).toISOString()},r);return t.ok?{ok:!0,key:n.key,path:credentialsPath(r)}:{ok:!1,key:n.key,path:credentialsPath(r),error:t.error,message:`could not write ${credentialsPath(r)}`}}function clearApiKey(e){return{cleared:!!normalizeApiKey(readCredentials(e).aegisApiKey),ok:writeCredentials({aegisApiKey:"",adoptedFrom:""},e).ok,path:credentialsPath(e)}}function resolveMemoryToken(e={}){const r=e.env||process.env,n=e.dir,t=String(r&&r[MEMORY_ENV]||"").trim();if(t)return{token:t,source:"env"};const o=readCredentials(n),i=String(o.memoryToken||"").trim();if(i)return{token:i,source:"credentials"};const a=readLegacyConfig(n).memoryToken;return a?{token:a,source:"config"}:{token:"",source:"none"}}function saveMemoryToken(e,r={},n){return writeCredentials({memoryToken:String(e||"").trim(),...r},n)}function clearMemoryToken(e){return writeCredentials({memoryToken:"",memorySubscribed:!1},e)}function keyStatus(e={}){const r=e.dir,{key:n,source:t,from:o}=resolveApiKey(e),i=readCredentials(r);let a=null;try{a=511&fs.statSync(credentialsPath(r)).mode}catch{}return{configured:!!n,key:n,source:t,from:o,path:credentialsPath(r),fileMode:null==a?null:"0"+a.toString(8),stored:!!normalizeApiKey(i.aegisApiKey),legacyPlaintext:legacyKeyOnDisk(r),verifiedAt:i.verifiedAt||null,account:i.account||null,memoryToken:!!resolveMemoryToken(e).token,memorySource:resolveMemoryToken(e).source}}function clientOptions(e={}){const{key:r}=resolveApiKey(e),{token:n}=resolveMemoryToken(e),t={};return t.apiKey=r,t.memoryToken=n,e.channel&&(t.channel=e.channel),t}const SOURCE_LABEL={env:`${KEY_ENV}`,credentials:"saved key file",envfile:`~/.aegiscode/.env (${KEY_ENV})`,config:"config.json (aegis CLI)",none:"not set"};function envFileLabel(e,r){try{const e=require("./env-file.js");if("function"==typeof e.envFileFor)return e.envFileFor(r)}catch{}return envFileForFallback(r)}function envFileForFallback(e){return path.join(e||aegisHome(),".env")}function sourceLabel(e){return SOURCE_LABEL[e]||SOURCE_LABEL.none}function preferNewest(e,r,n={}){const t=normalizeApiKey(e),o=Date.parse(r||"")||0,i=readCredentials(n.dir),a=normalizeApiKey(i.aegisApiKey),s=Date.parse(i.savedAt||"")||0;return a?t?t===a?{key:t,source:"host",sharedAt:s,hostAt:o}:s>o?{key:a,source:"shared",sharedAt:s,hostAt:o}:{key:t,source:"host",sharedAt:s,hostAt:o}:{key:a,source:"shared",sharedAt:s,hostAt:o}:{key:t,source:t?"host":"none",sharedAt:s,hostAt:o}}const HOW_TO_SET="run `aegiscode login` (or /key inside a session) to save one";module.exports={KEY_ENV:KEY_ENV,MEMORY_ENV:MEMORY_ENV,HOME_ENV:HOME_ENV,CREDENTIALS_FILE:CREDENTIALS_FILE,CONFIG_FILE:CONFIG_FILE,aegisHome:aegisHome,credentialsPath:credentialsPath,configPath:configPath,normalizeApiKey:normalizeApiKey,validateApiKey:validateApiKey,readCredentials:readCredentials,writeCredentials:writeCredentials,readLegacyConfig:readLegacyConfig,legacyKeyOnDisk:legacyKeyOnDisk,adoptLegacy:adoptLegacy,resolveApiKey:resolveApiKey,hasApiKey:hasApiKey,fromEnvFile:fromEnvFile,envFileForFallback:envFileForFallback,saveApiKey:saveApiKey,clearApiKey:clearApiKey,resolveMemoryToken:resolveMemoryToken,saveMemoryToken:saveMemoryToken,clearMemoryToken:clearMemoryToken,keyStatus:keyStatus,clientOptions:clientOptions,preferNewest:preferNewest,sourceLabel:sourceLabel,HOW_TO_SET:HOW_TO_SET};
@@ -0,0 +1,3 @@
1
+ // SPDX-License-Identifier: AGPL-3.0-or-later
2
+ // Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
3
+ "use strict";const crypto=require("node:crypto"),os=require("node:os"),fs=require("node:fs"),path=require("node:path");function installIdPath(){const e=process.env.AEGISCODEX_HOME||path.join(os.homedir(),".aegiscode");return path.join(e,"install-id")}function readMachineId(){try{if("linux"===process.platform){const e=require("node:fs");try{return e.readFileSync("/etc/machine-id","utf8").trim()}catch{return e.readFileSync("/var/lib/dbus/machine-id","utf8").trim()}}if("darwin"===process.platform){const{execSync:e}=require("node:child_process"),t=e("ioreg -rd1 -c IOPlatformExpertDevice",{encoding:"utf8",timeout:3e3}).match(/"IOPlatformUUID"\s*=\s*"([^"]+)"/);if(t)return t[1]}if("win32"===process.platform){const{execSync:e}=require("node:child_process"),t=e("reg query HKLM\\SOFTWARE\\Microsoft\\Cryptography /v MachineGuid",{encoding:"utf8",timeout:3e3}).match(/MachineGuid\s+REG_SZ\s+(\S+)/);if(t)return t[1]}}catch{}return""}function persistedInstallId(){const e=installIdPath(),t=()=>{try{const t=fs.readFileSync(e,"utf8").trim();return/^[0-9a-f]{32}$/.test(t)?t:""}catch{return""}},r=t();if(r)return r;try{const t=crypto.randomBytes(16).toString("hex");return fs.mkdirSync(path.dirname(e),{recursive:!0,mode:448}),fs.writeFileSync(e,t,{mode:384,flag:"wx"}),t}catch{return t()}}function machineFingerprint(e){return crypto.createHash("sha256").update(`aegiscode-plugin-device-v1:${machineIdentity(e).id}`).digest("hex")}function machineIdentity(e){if(e)return{kind:"override",id:String(e)};const t=readMachineId();if(t)return{kind:"machine-id",id:t};const r=persistedInstallId();return r?{kind:"install-id",id:r}:{kind:"hostname",id:`${os.hostname()}:${os.platform()}:${os.arch()}`}}module.exports={machineFingerprint:machineFingerprint,machineIdentity:machineIdentity,readMachineId:readMachineId,persistedInstallId:persistedInstallId};
@@ -0,0 +1,3 @@
1
+ // SPDX-License-Identifier: AGPL-3.0-or-later
2
+ // Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
3
+ "use strict";function driveConnectUrl(e){return`${String(e||"").replace(/\/+$/,"")}/connect/drive`}async function driveStatus(e){const n=await e.driveToken(),o=Boolean(n&&n.connected),t=n&&n.google_linked;return{connected:o,googleLinked:o||!0===t,googleLinkedKnown:"boolean"==typeof t||o,email:n&&n.email||null}}async function waitForDriveConnected(e,n={}){const o=Number(n.timeoutMs)>0?Number(n.timeoutMs):18e4,t=Number(n.pollMs)>0?Number(n.pollMs):2e3,r=n.signal||null,i=Date.now()+o;for(;;){const n=await driveStatus(e);if(n.connected)return n;if(r&&r.aborted){const e=new Error("cancelled");throw e.name="AbortError",e}if(Date.now()>=i)throw new Error(`timed out after ${Math.round(o/1e3)}s waiting for Google Drive to connect`);await new Promise((e=>setTimeout(e,t)))}}module.exports={driveConnectUrl:driveConnectUrl,driveStatus:driveStatus,waitForDriveConnected:waitForDriveConnected};
@@ -0,0 +1,3 @@
1
+ // SPDX-License-Identifier: AGPL-3.0-or-later
2
+ // Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
3
+ "use strict";const DRIVE_FILES_URL="https://www.googleapis.com/drive/v3/files",DRIVE_UPLOAD_URL="https://www.googleapis.com/upload/drive/v3/files",FOLDER_MIME="application/vnd.google-apps.folder",BOUNDARY="aegiscode-drive-upload-boundary",DEFAULT_FOLDER="AEGIS Memory",DEFAULT_FILE="aegis-memory-backup.json",DEFAULT_CONVERSATIONS_FOLDER="conversations";function resolveFetch(e){const n=e||("function"==typeof fetch?fetch:null);if(!n)throw new Error("drive: this Node has no global fetch — upgrade to Node 22+");return n}function escapeQ(e){return String(e).replace(/\\/g,"\\\\").replace(/'/g,"\\'")}async function driveRequest(e,n,{method:t="GET",accessToken:o,body:r,headers:a}={}){const i=resolveFetch(e),d=await i(n,{method:t,headers:{Authorization:`Bearer ${o}`,...a||{}},body:r}),l=await d.text();let s=null;try{s=l?JSON.parse(l):null}catch{s=null}if(!d.ok){const e=s&&s.error&&(s.error.message||s.error)||l.slice(0,200)||`HTTP ${d.status}`,o=new Error(`drive: ${t} ${n.split("?")[0]} failed — ${"string"==typeof e?e:JSON.stringify(e)}`);throw o.status=d.status,o.data=s,o}return s||{}}async function findOne(e,n,t){const o=`${DRIVE_FILES_URL}?q=${encodeURIComponent(t)}&fields=${encodeURIComponent("files(id,name)")}&pageSize=1`,r=await driveRequest(e,o,{accessToken:n});return(Array.isArray(r.files)?r.files:[])[0]||null}async function findOrCreateFolder(e,n,{fetchImpl:t,parentId:o=null}={}){const r=`${o?`'${escapeQ(o)}' in parents and `:""}mimeType='${FOLDER_MIME}' and name='${escapeQ(n)}' and trashed=false`,a=await findOne(t,e,r);if(a)return a.id;const i={name:n,mimeType:FOLDER_MIME};return o&&(i.parents=[o]),(await driveRequest(t,DRIVE_FILES_URL,{method:"POST",accessToken:e,headers:{"Content-Type":"application/json"},body:JSON.stringify(i)})).id}async function findFileInFolder(e,n,t,{fetchImpl:o}={}){return findOne(o,e,`'${escapeQ(t)}' in parents and name='${escapeQ(n)}' and trashed=false`)}async function createFile(e,{name:n,folderId:t,content:o,mimeType:r},{fetchImpl:a}={}){const i=JSON.stringify({name:n,parents:[t]}),d=`--${BOUNDARY}\r\nContent-Type: application/json; charset=UTF-8\r\n\r\n${i}\r\n--${BOUNDARY}\r\nContent-Type: ${r}\r\n\r\n${o}\r\n--${BOUNDARY}--`;return driveRequest(a,`${DRIVE_UPLOAD_URL}?uploadType=multipart&fields=${encodeURIComponent("id,webViewLink")}`,{method:"POST",accessToken:e,headers:{"Content-Type":`multipart/related; boundary=${BOUNDARY}`},body:d})}async function updateFileContent(e,n,t,o,{fetchImpl:r}={}){return driveRequest(r,`${DRIVE_UPLOAD_URL}/${encodeURIComponent(n)}?uploadType=media&fields=${encodeURIComponent("id,webViewLink")}`,{method:"PATCH",accessToken:e,headers:{"Content-Type":o},body:t})}async function uploadMemoryBackup(e,n,t={}){const o=t.folderName||"AEGIS Memory",r=t.fileName||DEFAULT_FILE,a=t.mimeType||"application/json",i=t.fetchImpl,d=await findOrCreateFolder(e,o,{fetchImpl:i}),l=await findFileInFolder(e,r,d,{fetchImpl:i}),s=l?await updateFileContent(e,l.id,n,a,{fetchImpl:i}):await createFile(e,{name:r,folderId:d,content:n,mimeType:a},{fetchImpl:i});return{fileId:s.id||l&&l.id||null,webViewLink:s.webViewLink||null,updated:Boolean(l)}}async function uploadConversation(e,n={}){const t=n.name,o=n.content;if(!t)throw new Error("drive: uploadConversation needs a file name");if("string"!=typeof o)throw new Error("drive: uploadConversation needs the file content as a string");const r=n.folderName||"AEGIS Memory",a=void 0===n.subfolder?"conversations":n.subfolder,i=n.mimeType||"text/markdown",d=n.fetchImpl,l=await findOrCreateFolder(e,r,{fetchImpl:d}),s=a?await findOrCreateFolder(e,a,{fetchImpl:d,parentId:l}):l,c=await createFile(e,{name:t,folderId:s,content:o,mimeType:i},{fetchImpl:d});return{fileId:c.id||null,webViewLink:c.webViewLink||null,created:!0,folder:a?`${r}/${a}`:r,path:a?`${r}/${a}/${t}`:`${r}/${t}`}}module.exports={DEFAULT_FOLDER:"AEGIS Memory",DEFAULT_FILE:DEFAULT_FILE,DEFAULT_CONVERSATIONS_FOLDER:"conversations",findOrCreateFolder:findOrCreateFolder,findFileInFolder:findFileInFolder,createFile:createFile,updateFileContent:updateFileContent,uploadMemoryBackup:uploadMemoryBackup,uploadConversation:uploadConversation};
@@ -0,0 +1,3 @@
1
+ // SPDX-License-Identifier: AGPL-3.0-or-later
2
+ // Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
3
+ "use strict";const fs=require("node:fs"),path=require("node:path"),credentials=require("./credentials.js"),platform=require("./platform.js"),ENV_FILE=".env",SECRETS_FILE="secrets.env",FOREIGN_SECRET_PREFIXES=Object.freeze(["STRIPE_"]),FOREIGN_SECRET_NAMES=Object.freeze(["STRIPE_SECRET_KEY","STRIPE_WEBHOOK_SECRET","STRIPE_PRODUCT","STRIPE_PRO_PRICE_ID","STRIPE_S_PRICE_ID","STRIPE_MEMORY_PRICE_ID","PYPI_API_TOKEN","TWINE_PASSWORD","CLAUDE_CODE_OAUTH_TOKEN"]);function isForeignSecret(e){const r=String(null==e?"":e).trim();return!!r&&(!!FOREIGN_SECRET_NAMES.includes(r)||FOREIGN_SECRET_PREFIXES.some((e=>r.startsWith(e))))}const SECRET_FILE_MODE=384,SECRET_DIR_MODE=448,ALIASES=Object.freeze({google:"GEMINI_API_KEY",gemini:"GEMINI_API_KEY","google-ai":"GEMINI_API_KEY",xai:"XAI_API_KEY","x-ai":"XAI_API_KEY",grok:"XAI_API_KEY",huggingface:"HF_TOKEN",together:"TOGETHER_API_KEY","together-ai":"TOGETHER_API_KEY",fireworks:"FIREWORKS_API_KEY","azure-openai":"AZURE_OPENAI_API_KEY","voyage-ai":"VOYAGE_API_KEY"}),ACCOUNT_ENV_VAR="AEGIS_API_KEY";function envFileFor(e){return path.join(e||credentials.aegisHome(),ENV_FILE)}function secretEnvFileFor(e){return path.join(e||credentials.aegisHome(),SECRETS_FILE)}function envVarFor(e){const r=String(e||"").trim().toLowerCase();if(!r)return"";const t=r.startsWith("byok:")?r.slice(5).trim():r;if(!t)return"";if(ALIASES[t])return ALIASES[t];const n=t.toUpperCase().replace(/[^A-Z0-9]+/g,"_").replace(/^_+|_+$/g,"");return n?`${n}_API_KEY`:""}const ENV_TOKENISH=/^[A-Za-z0-9_+/.-]+$/,ENV_WRAP_MIN_VALUE=32;function foldWrappedEnvValue(e,r,t){let n=t;if(n.startsWith('"')||n.startsWith("'"))return{value:n,i:r};for(;r+1<e.length;){const t=e[r+1],o=t.trim();if(!o||o.startsWith("#")||o.includes("="))break;if(!ENV_TOKENISH.test(o))break;if(!/^[ \t]/.test(t)&&(n.length<ENV_WRAP_MIN_VALUE||!ENV_TOKENISH.test(n)))break;n+=o,r+=1}return{value:n,i:r}}function parseEnvText(e){const r={},t=String(null==e?"":e).split(/\r?\n/);for(let e=0;e<t.length;e++){const n=t[e].trim();if(!n||n.startsWith("#"))continue;const o=n.indexOf("=");if(o<=0)continue;let i=n.slice(0,o).trim();if(i.startsWith("export ")&&(i=i.slice(7).trim()),!/^[A-Za-z_][A-Za-z0-9_]*$/.test(i))continue;const s=foldWrappedEnvValue(t,e,n.slice(o+1).trim());let c=s.value;e=s.i;const E=c.startsWith('"')&&c.endsWith('"')&&c.length>=2,a=c.startsWith("'")&&c.endsWith("'")&&c.length>=2;if(E)c=c.slice(1,-1).replace(/\\(["\\])/g,"$1");else if(a)c=c.slice(1,-1);else{const e=c.indexOf(" #");-1!==e&&(c=c.slice(0,e).trim())}r[i]=c}return r}const ENV_SOURCED=new WeakMap;function sourcedFrom(e){let r=ENV_SOURCED.get(e);return r||(r=new Map,ENV_SOURCED.set(e,r)),r}function isFromEnvFile(e,r,t={}){const n=t.env||process.env,o=ENV_SOURCED.get(n);return!(!o||!o.has(e)||void 0!==r&&o.get(e)!==String(r))}function loadEnvFile(e={}){const r=e.env||process.env,t=e.file||envFileFor(e.dir),n=sourcedFrom(r),o={ok:!1,file:t,loaded:[],kept:[],refused:[],reason:"",loose:!1,mode:0};let i;try{i=fs.readFileSync(t,"utf8")}catch(e){return o.reason=e&&"ENOENT"===e.code?"absent":"unreadable",o}try{const e=fs.statSync(t);o.mode=511&e.mode,o.loose=platform.hasPosixModes()&&0!=(63&e.mode)}catch{}const s=parseEnvText(i);for(const[e,t]of Object.entries(s))isForeignSecret(e)?o.refused.push(e):void 0===r[e]||""===r[e]?(r[e]=t,n.set(e,t),o.loaded.push(e)):o.kept.push(e);return o.ok=!0,o}function loadForeignSecrets(e={}){const r=e.env||process.env,t=e.file||secretEnvFileFor(e.dir),n={ok:!1,file:t,loaded:[],reason:"",mode:0,loose:!1},o=Array.isArray(e.only)&&e.only.length?e.only.filter(isForeignSecret):null;let i;try{i=fs.readFileSync(t,"utf8")}catch(e){return n.reason=e&&"ENOENT"===e.code?"absent":"unreadable",n}try{const e=fs.statSync(t);n.mode=511&e.mode,n.loose=platform.hasPosixModes()&&0!=(63&e.mode)}catch{}const s=parseEnvText(i);for(const[e,t]of Object.entries(s))o&&!o.includes(e)||(r[e]=t,n.loaded.push(e));return n.ok=!0,n}function foreignSecretValue(e,r={}){if(!isForeignSecret(e))return"";const t=r.file||secretEnvFileFor(r.dir);try{const r=parseEnvText(fs.readFileSync(t,"utf8"))[String(e)];return"string"==typeof r?r:""}catch{return""}}function resolveForeignSecret(e,r={}){if(!isForeignSecret(e))return"";const t=r.env||process.env,n=t&&t[e];if("string"==typeof n&&n.trim())return n.trim();const o=foreignSecretValue(e,r);if(o&&o.trim())return o.trim();try{const t=parseEnvText(fs.readFileSync(envFileFor(r.dir),"utf8"))[String(e)];return"string"==typeof t?t.trim():""}catch{return""}}function writeSecretFile(e,r){fs.mkdirSync(path.dirname(e),{recursive:!0,mode:SECRET_DIR_MODE});const t=`${e}.tmp-${process.pid}-${Date.now()}`;fs.writeFileSync(t,r,{mode:SECRET_FILE_MODE}),fs.renameSync(t,e),fs.chmodSync(e,SECRET_FILE_MODE)}function setForeignSecret(e,r,t={}){const n=t.file||secretEnvFileFor(t.dir),o={ok:!1,file:n,name:String(e||""),changed:!1,created:!1,replaced:!1,mode:0,tightened:!1,error:""};if(!isWritableName(e))return o.error=`refusing to write "${e}" — an env var name is [A-Za-z_][A-Za-z0-9_]*`,o;if(!isForeignSecret(e))return o.error=`refusing to write ${e} to ${SECRETS_FILE} — it is a host credential, not a foreign secret; use setEnvValue (${ENV_FILE}) instead`,o;const i=String(null==r?"":r).trim();if(!i)return o.error=`refusing to write an empty ${e}`,o;if(/[\r\n]/.test(String(r)))return o.error=`refusing to write ${e} — the value contains a line break`,o;let s="",c=0;o.created=!0;try{s=fs.readFileSync(n,"utf8"),o.created=!1;try{c=511&fs.statSync(n).mode}catch{}}catch(e){if(e&&"ENOENT"!==e.code)return o.error=`could not read ${n}: ${e.code||e.message}`,o}const E=String(s).replace(/\r\n/g,"\n");if(!o.created&&parseEnvText(E)[e]===i)return o.ok=!0,o.changed=!1,o.replaced=!0,o.mode=c||SECRET_FILE_MODE,o;const{text:a,replaced:l}=upsertEnvText(E,e,i);try{writeSecretFile(n,a)}catch(e){return o.error=`could not write ${n}: ${e.code||e.message}`,o}return o.ok=!0,o.changed=!0,o.replaced=l,o.mode=SECRET_FILE_MODE,o.tightened=platform.hasPosixModes()&&!o.created&&0!==c&&0!=(63&c),o}function splitForeignSecrets(e={}){const r=e.env||process.env,t=e.file||envFileFor(e.dir),n=e.secretsFile||secretEnvFileFor(e.dir),o=!0===e.apply,i={ok:!1,moved:[],kept:[],envFile:t,secretsFile:n,apply:o};let s;try{s=fs.readFileSync(t,"utf8")}catch(e){return i.reason=e&&"ENOENT"===e.code?"absent":"unreadable",i}const c=parseEnvText(s),E=Object.keys(c).filter(isForeignSecret).sort();if(!E.length)return i.ok=!0,i;let a="";try{a=fs.readFileSync(n,"utf8")}catch{}const l=parseEnvText(a);for(const e of E)Object.prototype.hasOwnProperty.call(l,e)?i.kept.push(e):(a=upsertEnvText(a,e,c[e]).text,i.moved.push(e));if(o){for(const e of E)s=removeEnvText(s,e).text;i.moved.length&&writeSecretFile(n,a),writeSecretFile(t,s);for(const e of E)r[e]===c[e]&&delete r[e]}else i.moved.length&&(i.secretsFile=n);return i.ok=!0,i}const MIN_CREDENTIAL_LEN=8;function credentialLooksUsable(e){return"string"==typeof e&&e.trim().length>=MIN_CREDENTIAL_LEN}function providerKeyFromEnv(e,r){const t=envVarFor(e);if(!t)return{key:"",env:"",rejected:null};const n=(r||process.env)[t],o="string"==typeof n?n.trim():"";return""===o?{key:"",env:t,rejected:null}:credentialLooksUsable(o)?{key:o,env:t,rejected:null}:{key:"",env:t,rejected:`${t} holds ${o.length} character${1===o.length?"":"s"}, which cannot be a credential`}}function isWritableName(e){return"string"==typeof e&&/^[A-Za-z_][A-Za-z0-9_]*$/.test(e)}function quoteEnvValue(e){const r=String(e);return""===r?"":/[\s"'#\\]/.test(r)?`"${r.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`:r}function upsertEnvText(e,r,t){const n=String(null==e?"":e),o=""===n||n.endsWith("\n"),i=""!==n&&""===n.split("\n").slice(-1)[0],s=""===n?[]:n.split("\n");i&&s.pop();const c=new RegExp(`^(\\s*(?:export\\s+)?)${r}\\s*=`),E=[];let a=!1;for(const e of s){const n=c.exec(e);n?a||(E.push(`${n[1]}${r}=${quoteEnvValue(t)}`),a=!0):E.push(e)}a||E.push(`${r}=${quoteEnvValue(t)}`);let l=E.join("\n");return""!==l&&(o||i)&&(l+="\n"),{text:l,replaced:a}}function setEnvValue(e,r,t={}){const n=t.env||process.env,o=t.file||envFileFor(t.dir),i={ok:!1,file:o,name:String(e||""),changed:!1,created:!1,replaced:!1,mode:0,tightened:!1,error:""};if(!isWritableName(e))return i.error=`refusing to write "${e}" — an env var name is [A-Za-z_][A-Za-z0-9_]*`,i;if(isForeignSecret(e))return i.error=`refusing to write ${e} to ${ENV_FILE} — it is a production secret, not a host key; put it in ${SECRETS_FILE} (or use loadForeignSecrets)`,i;const s=String(null==r?"":r).trim();if(!s)return i.error=`refusing to write an empty ${e}`,i;if(/[\r\n]/.test(String(r)))return i.error=`refusing to write ${e} — the value contains a line break`,i;let c="",E=0;i.created=!0;try{c=fs.readFileSync(o,"utf8"),i.created=!1;try{E=511&fs.statSync(o).mode}catch{}}catch(e){if(e&&"ENOENT"!==e.code)return i.error=`could not read ${o}: ${e.code||e.message}`,i}const a=String(c).replace(/\r\n/g,"\n");if(!i.created&&parseEnvText(a)[e]===s)return i.ok=!0,i.changed=!1,i.replaced=!0,i.mode=E||SECRET_FILE_MODE,!1!==t.apply&&(n[e]=s,sourcedFrom(n).set(e,s)),i;const{text:l,replaced:d}=upsertEnvText(a,e,s),u=`${o}.tmp-${process.pid}`;try{fs.mkdirSync(path.dirname(o),{recursive:!0,mode:SECRET_DIR_MODE}),fs.writeFileSync(u,l,{encoding:"utf8",mode:SECRET_FILE_MODE}),fs.chmodSync(u,SECRET_FILE_MODE),fs.renameSync(u,o)}catch(e){try{fs.unlinkSync(u)}catch{}return i.error=`could not write ${o}: ${e.code||e.message}`,i}return i.ok=!0,i.changed=!0,i.replaced=d,i.mode=SECRET_FILE_MODE,i.tightened=platform.hasPosixModes()&&!i.created&&0!==E&&0!=(63&E),!1!==t.apply&&(n[e]=s,sourcedFrom(n).set(e,s)),i}function removeEnvText(e,r){const t=String(null==e?"":e),n=""===t||t.endsWith("\n"),o=""!==t&&""===t.split("\n").slice(-1)[0],i=""===t?[]:t.split("\n");o&&i.pop();const s=new RegExp(`^(\\s*(?:export\\s+)?)${r}\\s*=`),c=[];let E=0;for(const e of i)s.test(e)?E+=1:c.push(e);let a=c.join("\n");return""!==a&&(n||o)&&(a+="\n"),{text:a,removed:E,changed:E>0}}function clearEnvValue(e,r={}){const t=r.env||process.env,n=r.file||envFileFor(r.dir),o={ok:!1,file:n,name:String(e||""),changed:!1,removed:0,mode:0,error:""};if(!isWritableName(e))return o.error=`refusing to clear "${e}" — an env var name is [A-Za-z_][A-Za-z0-9_]*`,o;let i="",s=!1,c=0;try{i=fs.readFileSync(n,"utf8");try{c=511&fs.statSync(n).mode}catch{}}catch(e){if(!e||"ENOENT"!==e.code)return o.error=`could not read ${n}: ${e.code||e.message}`,o;s=!0}const{text:E,removed:a,changed:l}=s?{text:"",removed:0,changed:!1}:removeEnvText(i,e);if(!l)return o.ok=!0,o.mode=c||SECRET_FILE_MODE,!1!==r.apply&&delete t[String(e)],o;const d=`${n}.tmp-${process.pid}`;try{fs.mkdirSync(path.dirname(n),{recursive:!0,mode:SECRET_DIR_MODE}),fs.writeFileSync(d,E,{encoding:"utf8",mode:SECRET_FILE_MODE}),fs.chmodSync(d,SECRET_FILE_MODE),fs.renameSync(d,n)}catch(e){try{fs.unlinkSync(d)}catch{}return o.error=`could not write ${n}: ${e.code||e.message}`,o}return o.ok=!0,o.changed=!0,o.removed=a,o.mode=SECRET_FILE_MODE,!1!==r.apply&&delete t[String(e)],o}function keyStatus(e,r={}){const t=r.env||process.env,n=r.file||envFileFor(r.dir),o=String(e||""),i={name:o,present:!1,inFile:!1,source:"none"};if(!isWritableName(o))return i;const s=t[o],c="string"==typeof s&&""!==s.trim();let E=!1;try{const e=parseEnvText(fs.readFileSync(n,"utf8"));E="string"==typeof e[o]&&""!==e[o].trim()}catch{}return i.present=c||E,i.inFile=E,i.source=c&&E?"both":c?"shell":E?"file":"none",i}function keyForModelId(e,r){const t=String(null==e?"":e).trim();if("pro"===String(r||"").toLowerCase())return{env:"CLAUDE_CODE_OAUTH_TOKEN",provider:"",vendor:"",pooled:!1,foreign:!0};if(("byok"===String(r||"").toLowerCase()||t.includes(":"))&&t.includes(":")){const e=t.slice(0,t.indexOf(":")).trim();return{env:envVarFor(e),provider:e,vendor:e,pooled:!1}}return{env:"AEGIS_API_KEY",provider:"",vendor:providerForModelId(t,r),pooled:!0}}const VENDOR_SLUGS=Object.freeze(["openai","anthropic","deepseek","google","gemini","groq","mistral","openrouter","together","together-ai","xai","x-ai","grok","huggingface","fireworks","voyage-ai","azure-openai"]),VENDOR_COMPOUNDS=Object.freeze(VENDOR_SLUGS.filter((e=>e.includes("-"))).sort(((e,r)=>r.length-e.length)));function providerForModelId(e,r){const t=String(null==e?"":e).trim().toLowerCase();if(!t)return"";if(t.includes(":"))return t.slice(0,t.indexOf(":")).trim();for(const e of VENDOR_COMPOUNDS)if(t===e||t.startsWith(e+"-"))return e;const n=t.split("-")[0];return VENDOR_SLUGS.includes(n)?n:""}module.exports={ENV_FILE:ENV_FILE,ALIASES:ALIASES,ACCOUNT_ENV_VAR:"AEGIS_API_KEY",SECRET_FILE_MODE:SECRET_FILE_MODE,envFileFor:envFileFor,envVarFor:envVarFor,parseEnvText:parseEnvText,loadEnvFile:loadEnvFile,isFromEnvFile:isFromEnvFile,providerKeyFromEnv:providerKeyFromEnv,MIN_CREDENTIAL_LEN:MIN_CREDENTIAL_LEN,credentialLooksUsable:credentialLooksUsable,providerForModelId:providerForModelId,VENDOR_SLUGS:VENDOR_SLUGS,isWritableName:isWritableName,quoteEnvValue:quoteEnvValue,upsertEnvText:upsertEnvText,removeEnvText:removeEnvText,setEnvValue:setEnvValue,clearEnvValue:clearEnvValue,keyStatus:keyStatus,keyForModelId:keyForModelId,SECRETS_FILE:SECRETS_FILE,FOREIGN_SECRET_NAMES:FOREIGN_SECRET_NAMES,FOREIGN_SECRET_PREFIXES:FOREIGN_SECRET_PREFIXES,isForeignSecret:isForeignSecret,secretEnvFileFor:secretEnvFileFor,loadForeignSecrets:loadForeignSecrets,foreignSecretValue:foreignSecretValue,resolveForeignSecret:resolveForeignSecret,setForeignSecret:setForeignSecret,splitForeignSecrets:splitForeignSecrets};
@@ -0,0 +1,3 @@
1
+ // SPDX-License-Identifier: AGPL-3.0-or-later
2
+ // Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
3
+ "use strict";const crypto=require("node:crypto"),fs=require("node:fs"),{signatureFromMedians:signatureFromMedians,MIN_STROKES:TOUCH_MIN_STROKES}=require("./touch.js"),FP_VERSION=4,FP_ALGO="sha256",FP_PREFIX="φ_",KEY_FP_LENGTH=12,SIG_LENGTH=16,ATTEST_LENGTH=32,LEAK_HEX_RUN=24,MAX_LABEL=40,MAX_FIELD=64,MAX_TOOLS=64,MAX_OBSERVATIONS=4096,MAX_DEPTH=8,CODE_LEN=SIG_LENGTH,MAX_CODE_FILES=4096,MAX_PATH=200,ATTESTED_FIELDS_V1=Object.freeze(["v","algo","keyFingerprint","label","account","model","tools","behaviour","behaviourSamples","createdAt"]),BEHAVIOUR_PURPOSE="aegiscode-behaviour-v2",AI_PURPOSE="aegiscode-ai-v1",ATTESTED_FIELDS_V2=Object.freeze(["v","algo","keyFingerprint","label","account","model","tools","behaviour","behaviourSamples","touch","touchSamples","createdAt"]),ATTESTED_FIELDS_V3=Object.freeze(["v","algo","keyFingerprint","label","account","model","tools","behaviour","behaviourSamples","touch","touchSamples","code","codeFiles","codeDirty","createdAt"]),ATTESTED_FIELDS_V4=Object.freeze(["v","algo","keyFingerprint","label","account","model","tools","behaviour","behaviourSamples","touch","touchSamples","code","codeFiles","codeDirty","aiKey","aiModel","ai","aiSamples","createdAt"]),ATTESTED_FIELDS=ATTESTED_FIELDS_V4,ATTESTED_FIELDS_BY_VERSION=Object.freeze({1:ATTESTED_FIELDS_V1,2:ATTESTED_FIELDS_V2,3:ATTESTED_FIELDS_V3,4:ATTESTED_FIELDS_V4});function attestedFieldsFor(e){return"number"==typeof e&&Number.isInteger(e)&&Object.prototype.hasOwnProperty.call(ATTESTED_FIELDS_BY_VERSION,e)?ATTESTED_FIELDS_BY_VERSION[e]:null}function normalise(e){return null==e?"":String(e).trim().replace(/\s+/g," ").toLowerCase()}function canonical(e,t=0){if(t>MAX_DEPTH)return'"[depth]"';if(null==e)return"null";const r=typeof e;return"number"===r?Number.isFinite(e)?String(e):"null":"boolean"===r?e?"true":"false":"string"===r?JSON.stringify(normalise(e)):"function"===r||"symbol"===r||"bigint"===r?"null":Array.isArray(e)?"["+e.map((e=>canonical(e,t+1))).join(",")+"]":"object"===r?"{"+Object.keys(e).filter((t=>void 0!==e[t]&&"function"!=typeof e[t])).sort().map((r=>JSON.stringify(r)+":"+canonical(e[r],t+1))).join(",")+"}":"null"}function digest(e,t){return crypto.createHash(FP_ALGO).update(e+"\n"+t,"utf8").digest("hex")}function safeLabel(e,t=MAX_LABEL){if(null==e)return"";const r=String(e).replace(/[\u0000-\u001f\u007f]+/g," ").replace(/\s+/g," ").trim();return r?r.length>t?r.slice(0,t):r:""}function longHexRun(e,t=LEAK_HEX_RUN){return new RegExp(`[0-9a-fA-F]{${t},}`).test(String(e))}const HEX_ATTESTATION=new RegExp(`^[0-9a-f]{${ATTEST_LENGTH}}$`);function isFingerprintShape(e){return new RegExp(`^[0-9a-f]{${KEY_FP_LENGTH}}$`).test(String(e||""))}function assertNoLeak(e,t,r){const n=[t,r].map((e=>null==e?"":String(e))).filter(Boolean);for(const[t,r]of Object.entries(e)){if(null==r)continue;const e=Array.isArray(r)?r.join("\0"):String(r);for(const r of n)if(e.includes(r))throw new Error(`fingerprint: field "${t}" would carry the secret verbatim`);if("attestation"!==t){if(longHexRun(e))throw new Error(`fingerprint: field "${t}" carries a long hex run (possible key leak)`)}else if(!HEX_ATTESTATION.test(e))throw new Error("fingerprint: attestation must be 32 lowercase hex characters")}return!0}function assertInputsClean(e,t,r){const n=[t,r].map((e=>null==e?"":String(e))).filter(Boolean);if(!n.length)return!0;for(const t of["label","account","model","tools","aiModel"]){const r=e[t];if(null==r)continue;const i=Array.isArray(r)?r.join("\0"):String(r);if(n.some((e=>i.includes(e))))throw new Error(`fingerprint: input "${t}" would carry the secret verbatim`);if(longHexRun(i))throw new Error(`fingerprint: input "${t}" carries a long hex run (possible key leak)`)}return!0}function keyFingerprint(e){if(null==e)return null;const t=String(e).trim();return t?digest("aegiscode-agent-v1",t).slice(0,KEY_FP_LENGTH):null}function observationKey(e){if("string"==typeof e||"number"==typeof e)return normalise(e);if(!e||"object"!=typeof e)return"";const t=[e.tool,e.target,e.outcome,e.model].map((e=>normalise(e))).join("|");return t.replace(/^\|+|\|+$/g,"")?t:""}function countObservations(e){return Array.isArray(e)?e.slice(0,MAX_OBSERVATIONS).filter((e=>""!==observationKey(e))).length:0}function signatureFromObservations(e,t){if(!Array.isArray(e))return null;const r=e.slice(0,MAX_OBSERVATIONS).map(observationKey).filter(Boolean);return r.length?digest(t,Array.from(new Set(r)).sort().join("\n")).slice(0,SIG_LENGTH):null}function behaviouralSignature(e){return signatureFromObservations(e,BEHAVIOUR_PURPOSE)}function aiSignature(e){return signatureFromObservations(e,AI_PURPOSE)}function normaliseTools(e){if(!Array.isArray(e))return Object.freeze([]);const t=new Set;for(const r of e.slice(0,MAX_TOOLS)){const e=normalise("string"==typeof r?r:r&&(r.name||r.id)||"");e&&t.add(e)}return Object.freeze(Array.from(t).sort())}function normaliseCodePath(e){if(null==e)return null;const t=String(e).replace(/\\/g,"/").trim();if(!t)return null;if(t.startsWith("/")||/^[a-zA-Z]:\//.test(t))return null;const r=[];for(const e of t.split("/"))if(""!==e&&"."!==e){if(".."===e)return null;r.push(e)}const n=r.join("/");return n?n.length>MAX_PATH?null:n:null}function codeFileDigest(e,t){const r=normaliseCodePath(e);if(!r)throw new Error(`fingerprint: unusable code path ${JSON.stringify(String(e))}`);const n=Buffer.isBuffer(t)?t:Buffer.from(null==t?"":String(t),"utf8");return crypto.createHash(FP_ALGO).update(`aegiscode-code-v3\0${r}\0`,"utf8").update(n).digest("hex")}function codeDigest(e){if(!Array.isArray(e))return{code:null,codeFiles:0};const t=new Map;for(const r of e){if(!r||"object"!=typeof r)continue;const e=normaliseCodePath(r.path);e&&t.set(e,{path:e,content:r.content})}const r=Array.from(t.keys()).sort();if(!r.length)return{code:null,codeFiles:0};if(r.length>MAX_CODE_FILES)throw new Error(`fingerprint: ${r.length} code files exceeds MAX_CODE_FILES (${MAX_CODE_FILES}); hash a subtree rather than silently attesting a prefix of one`);let n=digest("aegiscode-code-v3-root",String(r.length));for(const e of r)n=digest("aegiscode-code-v3-fold",`${n}\n${e}\n${codeFileDigest(e,t.get(e).content)}`);return{code:n.slice(0,CODE_LEN),codeFiles:r.length}}function codeAxisFrom(e,t){const{code:r,codeFiles:n}=codeDigest(e);return{code:r,codeFiles:n,codeDirty:r&&"boolean"==typeof t?t:null}}function aiAxisFrom(e={}){const{secret:t,model:r,observations:n}=e||{},i=keyFingerprint(t),o=aiSignature(n);return{aiKey:i,aiModel:safeLabel(r,MAX_FIELD)||null,ai:o,aiSamples:o?countObservations(n):0}}function attestationBody(e){const t=attestedFieldsFor(e&&e.v);if(!t)throw new Error(`fingerprint: cannot attest version ${e&&e.v}`);const r={};for(const n of t){const t=e[n];r[n]=void 0===t?null:t}return canonical(r)}function attest(e,t){if(!t)throw new Error("fingerprint: a secret is required to attest a record");return crypto.createHmac(FP_ALGO,String(t)).update(attestationBody(e),"utf8").digest("hex").slice(0,ATTEST_LENGTH)}function isoTs(e){if(null==e)return(new Date).toISOString();const t=e instanceof Date?e:new Date(e);if(Number.isNaN(t.getTime()))throw new Error("fingerprint: createdAt is not a valid date");return t.toISOString()}function touchSignatureFrom(e){if(!e||"object"!=typeof e)return{signature:null,samples:0};const t=Number(e.samples)||0,r=signatureFromMedians(e.medians,t);return{signature:r,samples:r?t:0}}function mint(e={}){const{secret:t,label:r,account:n,model:i,tools:o,observations:a,touch:s,code:l,codeDirty:u,aiSecret:c,aiModel:f,aiObservations:d,createdAt:E}=e,S=keyFingerprint(t);if(!S)throw new Error("fingerprint: a secret (API key or device seed) is required to mint φ(α)");assertInputsClean({label:r,account:n,model:i,tools:o,aiModel:f},t,c);const g=touchSignatureFrom(s),_=codeAxisFrom(l,u),p=aiAxisFrom({secret:c,model:f,observations:d}),F={v:FP_VERSION,algo:FP_ALGO,keyFingerprint:S,label:safeLabel(r,MAX_LABEL),account:safeLabel(n,MAX_FIELD)||null,model:safeLabel(i,MAX_FIELD)||null,tools:normaliseTools(o),behaviour:behaviouralSignature(a),behaviourSamples:countObservations(a),touch:g.signature,touchSamples:g.samples,code:_.code,codeFiles:_.codeFiles,codeDirty:_.codeDirty,aiKey:p.aiKey,aiModel:p.aiModel,ai:p.ai,aiSamples:p.aiSamples,createdAt:isoTs(E)},T={...F,attestation:attest(F,t)};return assertNoLeak(T,t,c),Object.freeze(T)}function id(e){if(!e||!isFingerprintShape(e.keyFingerprint))throw new Error("fingerprint: not a fingerprinted record");return`${FP_PREFIX}${e.keyFingerprint}-${e.behaviour||"unobserved"}`}function sameReason(e){return e&&"object"==typeof e?attestedFieldsFor(e.v)?e.algo!==FP_ALGO?`unsupported algo ${e.algo}`:isFingerprintShape(e.keyFingerprint)?null:"keyFingerprint is malformed":`unsupported version ${e.v}`:"not a record"}function verify(e,t){const r=sameReason(e);if(r)return{ok:!1,reason:r,id:null,credentialMatch:null};const n=t?keyFingerprint(t)===e.keyFingerprint:null;if(!t)return{ok:!1,reason:"no secret supplied — attestation cannot be recomputed",id:id(e),credentialMatch:null};const i=attest(e,t),o=String(e.attestation||""),a=Buffer.from(i,"utf8"),s=Buffer.from(o.padEnd(i.length," ").slice(0,i.length),"utf8");return a.length===s.length&&crypto.timingSafeEqual(a,s)?n?{ok:!0,reason:null,id:id(e),credentialMatch:!0}:{ok:!1,reason:"attestation valid but secret does not match keyFingerprint",id:id(e),credentialMatch:!1}:{ok:!1,reason:"attestation mismatch",id:id(e),credentialMatch:n}}function same(e,t,r="full"){if(!e||!t)return!1;if("credential"===r)return e.keyFingerprint===t.keyFingerprint;if("behaviour"===r)return Boolean(e.behaviour)&&e.behaviour===t.behaviour;if("full"===r)return e.keyFingerprint===t.keyFingerprint&&e.behaviour===t.behaviour;if("ai-credential"===r)return Boolean(e.aiKey)&&e.aiKey===t.aiKey;if("ai"===r)return Boolean(e.ai)&&e.ai===t.ai;if("mind"===r)return Boolean(e.aiKey)&&e.aiKey===t.aiKey&&Boolean(e.ai)&&e.ai===t.ai;throw new Error(`fingerprint: unknown comparison axis "${r}"`)}function describe(e){const t=sameReason(e);if(t)return`φ(?) ${t}`;const r=[`key ${e.keyFingerprint}`,e.behaviour?`behaviour ${e.behaviour}`:"behaviour unobserved",e.behaviourSamples?`${e.behaviourSamples} samples`:null,e.touch?`touch ${e.touch}`:"touch unobserved",e.touchSamples?`${e.touchSamples} strokes`:null,e.code?`code ${e.code}${null===e.codeDirty?"":e.codeDirty?" (dirty)":" (clean)"}`:"code unobserved",e.codeFiles?`${e.codeFiles} files`:null,e.ai&&e.aiKey?`ai ${e.ai} on ${e.aiKey}`:e.ai?`ai ${e.ai} (no key nominated)`:e.aiKey?`ai key ${e.aiKey}, behaviour unobserved`:"ai unobserved",e.aiSamples?`${e.aiSamples} ai turn(s)`:null,e.aiModel?`ran on ${e.aiModel}`:null,e.model?`model ${e.model}`:null,e.tools&&e.tools.length?`tools ${e.tools.length}`:null].filter(Boolean);return`${e.label||"agent"} · ${r.join(" · ")}`}function readAiSecret(e,t){if(t.AEGIS_AI_SECRET)return String(t.AEGIS_AI_SECRET).trim();const r=e.indexOf("--ai-secret-file");return-1!==r&&e[r+1]?fs.readFileSync(e[r+1],"utf8").trim():""}function readSecret(e,t){if(t.AEGIS_FINGERPRINT_SECRET)return String(t.AEGIS_FINGERPRINT_SECRET).trim();const r=e.indexOf("--secret-file");return-1!==r&&e[r+1]?fs.readFileSync(e[r+1],"utf8").trim():""}function flag(e,t,r=null){const n=e.indexOf(t);return-1!==n&&void 0!==e[n+1]?e[n+1]:r}function main(e,t=process.env){const r=readSecret(e,t);if(e.includes("--verify")){const t=flag(e,"--verify");if(!t)throw new Error("fingerprint: --verify needs a record file");const n=verify(JSON.parse(fs.readFileSync(t,"utf8")),r);return process.stdout.write(JSON.stringify(n,null,2)+"\n"),n.ok?0:1}const n=flag(e,"--observations"),i=n?JSON.parse(fs.readFileSync(n,"utf8")):[],o=flag(e,"--touch"),a=o?JSON.parse(fs.readFileSync(o,"utf8")):null,s=flag(e,"--ai-observations"),l=s?JSON.parse(fs.readFileSync(s,"utf8")):null,u=mint({secret:r,label:flag(e,"--label",""),account:flag(e,"--account",""),model:flag(e,"--model",""),tools:(flag(e,"--tools","")||"").split(",").filter(Boolean),observations:i,touch:a,aiSecret:readAiSecret(e,t),aiModel:flag(e,"--ai-model",""),aiObservations:l});return process.stdout.write(JSON.stringify(u,null,2)+"\n"),0}const API={mint:mint,verify:verify,attest:attest,attestationBody:attestationBody,id:id,same:same,describe:describe,keyFingerprint:keyFingerprint,behaviouralSignature:behaviouralSignature,aiSignature:aiSignature,aiAxisFrom:aiAxisFrom,observationKey:observationKey,countObservations:countObservations,normaliseTools:normaliseTools,safeLabel:safeLabel,touchSignatureFrom:touchSignatureFrom,normaliseCodePath:normaliseCodePath,codeFileDigest:codeFileDigest,codeDigest:codeDigest,codeAxisFrom:codeAxisFrom,canonical:canonical,assertNoLeak:assertNoLeak,assertInputsClean:assertInputsClean,longHexRun:longHexRun,isFingerprintShape:isFingerprintShape,attestedFieldsFor:attestedFieldsFor,FP_VERSION:FP_VERSION,FP_ALGO:FP_ALGO,FP_PREFIX:FP_PREFIX,KEY_FP_LENGTH:KEY_FP_LENGTH,SIG_LENGTH:SIG_LENGTH,ATTEST_LENGTH:ATTEST_LENGTH,LEAK_HEX_RUN:LEAK_HEX_RUN,CODE_LEN:CODE_LEN,MAX_CODE_FILES:MAX_CODE_FILES,MAX_PATH:MAX_PATH,BEHAVIOUR_PURPOSE:BEHAVIOUR_PURPOSE,AI_PURPOSE:AI_PURPOSE,ATTESTED_FIELDS:ATTESTED_FIELDS,ATTESTED_FIELDS_V1:ATTESTED_FIELDS_V1,ATTESTED_FIELDS_V2:ATTESTED_FIELDS_V2,ATTESTED_FIELDS_V3:ATTESTED_FIELDS_V3,ATTESTED_FIELDS_V4:ATTESTED_FIELDS_V4,ATTESTED_FIELDS_BY_VERSION:ATTESTED_FIELDS_BY_VERSION,main:main};module.exports=API;
@@ -0,0 +1,3 @@
1
+ // SPDX-License-Identifier: AGPL-3.0-or-later
2
+ // Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
3
+ "use strict";const fs=require("node:fs"),path=require("node:path"),os=require("node:os"),crypto=require("node:crypto"),DEFAULTS={minChars:24,maxChars:2e3,maxEntriesPerSource:500,maxFilesPerSource:400,maxFileBytes:8388608},NOISE=[/^<command-name>/i,/^<local-command-stdout>/i,/^\[Request interrupted by user/i,/^Caveat: The messages below were generated by the user while running local commands/i,/^(ok|okay|yes|no|yep|nope|sure|thanks|thank you|continue|proceed|go on|done)[.!]?$/i];function isNoise(e){return NOISE.some((t=>t.test(e)))}function homeDir(e){return e||os.homedir()}function platformOf(e){return e||process.platform}function roamingDir(e,t){return"win32"!==t?null:e===os.homedir()&&process.env.APPDATA?process.env.APPDATA:path.join(e,"AppData","Roaming")}function localDir(e,t){return"win32"!==t?null:e===os.homedir()&&process.env.LOCALAPPDATA?process.env.LOCALAPPDATA:path.join(e,"AppData","Local")}function macSupportDir(e,t){return"darwin"===t?path.join(e,"Library","Application Support"):null}function appRoots(e,t,r,{config:o=!0,data:n=!1,macSupport:s=!1}={}){const i=[];o&&i.push(path.join(e,".config",r)),n&&i.push(path.join(e,".local","share",r));const a=roamingDir(e,t);a&&o&&i.push(path.join(a,r));const c=localDir(e,t);if(c&&i.push(path.join(c,r)),s){const o=macSupportDir(e,t);o&&i.push(path.join(o,r))}return i}function cleanText(e){return"string"!=typeof e?"":e.replace(/[\u0000-\u0008\u000b\u000c\u000e-\u001f]/g," ").replace(/\s+/g," ").trim()}function stableId(...e){return`import-${crypto.createHash("sha1").update(e.join("|")).digest("hex").slice(0,32)}`}function readJsonl(e){const t=[];let r;try{r=fs.readFileSync(e,"utf8")}catch{return t}for(const e of r.split("\n")){const r=e.trim();if(r)try{t.push(JSON.parse(r))}catch{}}return t}function walkFiles(e,{ext:t,limit:r}){const o=[],n=[e];for(;n.length&&o.length<r;){const e=n.pop();let s;try{s=fs.readdirSync(e,{withFileTypes:!0})}catch{continue}for(const i of s){if(o.length>=r)break;if(i.isSymbolicLink())continue;const s=path.join(e,i.name);if(i.isDirectory()){if("node_modules"===i.name||".git"===i.name)continue;n.push(s)}else if(i.isFile()){if(t&&!t.some((e=>i.name.endsWith(e))))continue;o.push(s)}}}return o}function fileSize(e){try{return fs.statSync(e).size}catch{return 0}}function isFile(e){try{return fs.statSync(e).isFile()}catch{return!1}}function isDir(e){try{return fs.statSync(e).isDirectory()}catch{return!1}}function textFromClaudeMessage(e){if(!e)return"";const t=e.content;return"string"==typeof t?cleanText(t):Array.isArray(t)?t.filter((e=>e&&"text"===e.type&&"string"==typeof e.text)).map((e=>e.text)).join("\n"):""}function extractClaudeJsonl(e,t){const r=[],o=t.rel(e);for(const[t,n]of readJsonl(e).entries()){const e=n&&n.type,s="user"===e?"user":"assistant"===e?"assistant":null;if(!s)continue;if(n.isSidechain)continue;const i=cleanText(textFromClaudeMessage(n.message));i&&r.push({role:s,text:i,timestamp:n.timestamp||"",where:`${o}#${t}`})}return r}function extractGenericJsonl(e,t){const r=[],o=t.rel(e);for(const[t,n]of readJsonl(e).entries()){if(!n||"object"!=typeof n)continue;const e=n.role||n.message&&n.message.role;if("user"!==e&&"assistant"!==e)continue;const s=null!=n.content?n.content:n.message&&n.message.content,i=cleanText("string"==typeof s?s:textFromClaudeMessage({content:s}));i&&r.push({role:e,text:i,timestamp:n.timestamp||n.created_at||"",where:`${o}#${t}`})}return r}function extractMarkdown(e,t){if(fileSize(e)>DEFAULTS.maxFileBytes)return[];let r;try{r=fs.readFileSync(e,"utf8")}catch{return[]}const o=cleanText(r);return o?[{role:"user",text:o,timestamp:"",where:t.rel(e)}]:[]}function extractJsonMemory(e,t){if(fileSize(e)>DEFAULTS.maxFileBytes)return[];let r;try{r=JSON.parse(fs.readFileSync(e,"utf8"))}catch{return[]}const o=Array.isArray(r)?r:r&&Array.isArray(r.entries)?r.entries:r&&Array.isArray(r.memories)?r.memories:r&&Array.isArray(r.memory)?r.memory:[],n=t.rel(e);return o.map(((e,t)=>"string"==typeof e?{role:"user",text:cleanText(e),timestamp:"",where:`${n}#${t}`}:{role:"user",text:cleanText(e&&(e.content||e.text||e.value||e.fact)),timestamp:e&&(e.timestamp||e.createdAt)||"",where:`${n}#${t}`})).filter((e=>e.text))}const SOURCES=[{id:"claude-code",label:"Claude Code",verified:!0,roots:e=>[path.join(e,".claude","projects")],files:e=>[path.join(e,".claude","history.jsonl")],extract:{"**/*.jsonl":extractClaudeJsonl,"*.jsonl":extractClaudeJsonl}},{id:"claude-memory",label:"Claude memory files",verified:!0,roots:e=>[path.join(e,".claude","memory")],files:e=>[path.join(e,".claude","memory.json")],extract:{".json":extractJsonMemory,".md":extractMarkdown,".txt":extractMarkdown}},{id:"aegiscodex",label:"AEGIS Codex engine",verified:!0,roots:e=>[path.join(e,".aegiscodex","memory")],files:()=>[],extract:{".json":extractJsonMemory,".jsonl":extractGenericJsonl,".md":extractMarkdown}},{id:"codex",label:"OpenAI Codex CLI",verified:!1,roots:e=>[path.join(e,".codex")],files:()=>[],extract:{".jsonl":extractGenericJsonl,".json":extractJsonMemory,".md":extractMarkdown}},{id:"gemini-cli",label:"Gemini CLI",verified:!1,roots:e=>[path.join(e,".gemini")],files:()=>[],extract:{".json":extractJsonMemory,".jsonl":extractGenericJsonl,".md":extractMarkdown}},{id:"cursor",label:"Cursor",verified:!1,roots:e=>[path.join(e,".cursor")],files:()=>[],extract:{".json":extractJsonMemory,".jsonl":extractGenericJsonl,".md":extractMarkdown}},{id:"continue",label:"Continue",verified:!1,roots:e=>[path.join(e,".continue")],files:()=>[],extract:{".json":extractJsonMemory,".jsonl":extractGenericJsonl,".md":extractMarkdown}},{id:"goose",label:"Goose",verified:!1,roots:(e,t)=>appRoots(e,t,"goose",{data:!0}),files:()=>[],extract:{".jsonl":extractGenericJsonl,".json":extractJsonMemory,".md":extractMarkdown}},{id:"opencode",label:"opencode",verified:!1,roots:(e,t)=>appRoots(e,t,"opencode",{data:!0}),files:()=>[],extract:{".json":extractJsonMemory,".jsonl":extractGenericJsonl,".md":extractMarkdown}},{id:"windsurf",label:"Windsurf / Codeium",verified:!1,roots:(e,t)=>[path.join(e,".windsurf"),path.join(e,".codeium"),...appRoots(e,t,"Windsurf",{config:!1,macSupport:!0}),...appRoots(e,t,"Codeium",{config:!1,macSupport:!0})],files:()=>[],extract:{".json":extractJsonMemory,".jsonl":extractGenericJsonl,".md":extractMarkdown}},{id:"zed",label:"Zed",verified:!1,roots:(e,t)=>appRoots(e,t,"zed"),files:()=>[],extract:{".json":extractJsonMemory,".jsonl":extractGenericJsonl}},{id:"claude-desktop",label:"Claude Desktop app",verified:!1,roots:(e,t)=>appRoots(e,t,"Claude",{macSupport:!0}),files:()=>[],extract:{".json":extractJsonMemory,".jsonl":extractClaudeJsonl,".md":extractMarkdown}}];function suffixOf(e){const t=e.lastIndexOf("*");return-1===t?e:e.slice(t+1)}function extractorFor(e,t){for(const[r,o]of Object.entries(e))if(t.endsWith(suffixOf(r)))return o;return null}function sourceById(e){return SOURCES.find((t=>t.id===e))||null}function listSources(e,t){const r=homeDir(e),o=platformOf(t);return SOURCES.map((e=>{const t=e.roots(r,o).filter(isDir),n=(e.files?e.files(r):[]).filter(isFile);return{id:e.id,label:e.label,verified:e.verified,roots:t.concat(n),present:t.length>0||n.length>0}}))}function scan(e={}){const t=homeDir(e.home),r=platformOf(e.platform),o=null!=e.minChars?e.minChars:DEFAULTS.minChars,n=null!=e.maxChars?e.maxChars:DEFAULTS.maxChars,s=null!=e.maxEntriesPerSource?e.maxEntriesPerSource:DEFAULTS.maxEntriesPerSource,i=null!=e.limit?e.limit:1/0,a=e.sources&&e.sources.length?new Set(e.sources):null,c=[],l=[],u=new Set;for(const e of SOURCES){if(a&&!a.has(e.id))continue;const f=e.roots(t,r).filter(isDir),d=(e.files?e.files(t):[]).filter(isFile),p=f.length>0||d.length>0,m={id:e.id,label:e.label,verified:e.verified,present:p,files:0,scanned:0,count:0,skipped:0,roots:f,session:`import:${e.id}`};if(!p){c.push(m);continue}const x=d.slice();for(const t of f){const r=Object.keys(e.extract).map(suffixOf);x.push(...walkFiles(t,{ext:r,limit:DEFAULTS.maxFilesPerSource}))}const h={rel:e=>path.relative(t,e)};for(const t of x){if(m.count>=s||l.length>=i)break;if(fileSize(t)>DEFAULTS.maxFileBytes){m.skipped+=1;continue}const r=extractorFor(e.extract,t);if(!r)continue;let a;m.files+=1;try{a=r(t,h)}catch{continue}for(const t of a){if(m.count>=s||l.length>=i)break;m.scanned+=1;let r=t.text;if(r.length>n&&(r=`${r.slice(0,n)}…`),r.length<o||isNoise(r)){m.skipped+=1;continue}const a=stableId(e.id,t.where,t.role,r);u.has(a)||(u.add(a),l.push({id:a,content:r,role:t.role,source:e.id,session:m.session,tags:["imported",e.id],importance:5,timestamp:t.timestamp||(new Date).toISOString()}),m.count+=1)}}c.push(m)}return{entries:l,sources:c,totals:{entries:l.length,sourcesPresent:c.filter((e=>e.present)).length,sourcesWithEntries:c.filter((e=>e.count>0)).length,scanned:c.reduce(((e,t)=>e+t.scanned),0),skipped:c.reduce(((e,t)=>e+t.skipped),0)},scannedAt:(new Date).toISOString()}}function chunk(e,t=200){const r=[];for(let o=0;o<e.length;o+=t)r.push(e.slice(o,o+t));return r}function describe(e){const t=e.sources.filter((e=>e.present));if(!t.length)return"No other AI tool memory found on this machine.";const r=t.map((e=>{const t=e.verified?"":" (best-effort layout)";return` ${e.label}${t}: ${e.count} entries from ${e.files} file(s), ${e.skipped} skipped`}));return[`Found ${e.totals.entries} importable entries across ${e.totals.sourcesWithEntries} source(s):`,...r].join("\n")}module.exports={DEFAULTS:DEFAULTS,SOURCES:SOURCES,scan:scan,listSources:listSources,describe:describe,chunk:chunk,stableId:stableId,sourceById:sourceById,_internal:{walkFiles:walkFiles,extractClaudeJsonl:extractClaudeJsonl,extractGenericJsonl:extractGenericJsonl,extractJsonMemory:extractJsonMemory,extractMarkdown:extractMarkdown,cleanText:cleanText,isNoise:isNoise,suffixOf:suffixOf,platformOf:platformOf,roamingDir:roamingDir,localDir:localDir,macSupportDir:macSupportDir,appRoots:appRoots}};
@@ -0,0 +1,3 @@
1
+ // SPDX-License-Identifier: AGPL-3.0-or-later
2
+ // Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
3
+ "use strict";const http=require("node:http"),{URL:URL}=require("node:url");function escapeHtml(e){return String(null==e?"":e).replace(/[&<>"']/g,(e=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"}[e])))}function page({ok:e,error:t,username:r,surface:n}){const a=e?"Signed in":"Sign-in failed",o="app"===n?"the app":"the terminal";return`<!doctype html><html><head><meta charset="utf-8"><title>${a} — AEGIS</title></head><body style="font:16px sans-serif;max-width:32rem;margin:4rem auto;text-align:center;"><h2>${a}</h2><p>${e?`Signed in${r?` as <b>${escapeHtml(r)}</b>`:""}. You can close this tab and return to ${o}.`:`Sign-in failed: ${escapeHtml(t||"no token was returned")}. You can close this tab and try again.`}</p></body></html>`}function buildAuthUrl(e,t){const r=new URL("/auth/google",e);return r.searchParams.set("callback",t),r.toString()}async function startGoogleSignIn({apiBase:e,host:t="127.0.0.1",timeoutMs:r=3e5,surface:n="terminal"}={}){if(!e)throw new Error("startGoogleSignIn requires apiBase");let a,o,s=!1;const i=new Promise(((e,t)=>{a=e,o=t})),u=http.createServer(((e,r)=>{let i;try{i=new URL(e.url,`http://${t}`)}catch{return void r.writeHead(400).end()}const l=i.searchParams.get("token"),c=i.searchParams.get("username"),m=i.searchParams.get("memory_token"),d=i.searchParams.get("error");l||d?(r.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),r.end(page({ok:Boolean(l),error:d,username:c,surface:n})),s||(s=!0,clearTimeout(h),u.close(),l?a({apiKey:l,username:c||null,memoryToken:m||null}):o(new Error(d||"no token was returned")))):r.writeHead(404).end()}));await new Promise(((e,r)=>{u.once("error",r),u.listen(0,t,e)}));const{port:l}=u.address(),c=buildAuthUrl(e,`http://${t}:${l}`),h=setTimeout((()=>{s||(s=!0,u.close(),o(new Error(`timed out after ${Math.round(r/1e3)}s waiting for the browser sign-in`)))}),r);return"function"==typeof h.unref&&h.unref(),{url:c,wait:()=>i}}module.exports={startGoogleSignIn:startGoogleSignIn,buildAuthUrl:buildAuthUrl};
@@ -0,0 +1,3 @@
1
+ // SPDX-License-Identifier: AGPL-3.0-or-later
2
+ // Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
3
+ "use strict";const fs=require("node:fs"),os=require("node:os"),path=require("node:path"),{execFileSync:execFileSync}=require("node:child_process"),SETTINGS_DIRS=[".aegis",".aegiscode"];function hookSettingPaths(o={}){const e=platformPath(o.platform),t=homeDir(o),n=o.cwd||process.cwd(),s=[];for(const o of SETTINGS_DIRS)s.push(e.join(t,o,"settings.json")),s.push(e.join(n,o,"settings.json"));return s.push(e.join(t,".claude","settings.json")),dedupe(s)}function platformPath(o){return"win32"===(o||process.platform)?path.win32:path.posix}function homeDir(o={}){if(o.home)return String(o.home);const e=o.env||process.env,t="win32"===(o.platform||process.platform)?["USERPROFILE","HOME"]:["HOME","USERPROFILE"];for(const o of t)if(e&&e[o])return String(e[o]);return os.homedir()}function hookSourceKind(o){const e=path.posix.basename(String(o).replace(/\\/g,"/")),t=path.posix.basename(path.posix.dirname(String(o).replace(/\\/g,"/")));return"settings.json"!==e?"other":".claude"===t?"foreign":SETTINGS_DIRS.includes(t)?"aegis":"other"}function dedupe(o){const e=new Set,t=[];for(const n of o){const o=String(n).replace(/\\/g,"/");e.has(o)||(e.add(o),t.push(n))}return t}function shorten(o,e={}){const t=homeDir(e),n=String(o);if(!t)return n;const s=n.replace(/\\/g,"/"),r=String(t).replace(/\\/g,"/").replace(/\/+$/,"");return s===r?"~":s.startsWith(`${r}/`)?`~${s.slice(r.length)}`:n}function readHookConfig(o={}){const e=o.readFile||defaultReadFile,t=o.paths||hookSettingPaths(o),n={},s=[],r=[],i=[];for(const a of t){let t,c=null;try{c=e(a)}catch{c=null}if(null==c){i.push({path:a,exists:!1,kind:hookSourceKind(a)});continue}try{t=JSON.parse(String(c))}catch{i.push({path:a,exists:!0,parsed:!1,kind:hookSourceKind(a)});continue}const h=hookSourceKind(a),u=eventsOf(t),d=Object.keys(u);if(i.push({path:a,exists:!0,parsed:!0,kind:h,events:d}),"foreign"!==h){if(d.length){s.push(shorten(a,o));for(const[o,e]of Object.entries(u))Array.isArray(e)&&e.length&&(n[o]=[...n[o]||[],...e])}}else r.push(shorten(a,o))}return{hooks:n,from:s,foreign:r,files:i}}function eventsOf(o){if(!o||"object"!=typeof o)return{};if(o.hooks&&"object"==typeof o.hooks&&!Array.isArray(o.hooks)){const e={};for(const[t,n]of Object.entries(o.hooks))Array.isArray(n)&&(e[t]=n);return e}const e={};for(const t of HOOK_EVENTS)Array.isArray(o[t])&&(e[t]=o[t]);return e}const HOOK_EVENTS=["PreToolUse","PostToolUse","PostToolUseFailure","PermissionRequest","UserPromptSubmit","SessionStart","SessionEnd","Stop","SubagentStop","Notification","Compaction"];function hookStats(o){const e=o&&"object"==typeof o?o:{},t=Object.keys(e);let n=0;const s={};for(const o of t){const t=Array.isArray(e[o])?e[o]:[];s[o]=t.length,n+=t.length}return{enabled:n>0,hooks:n,events:t,byEvent:s}}const REQUIRED_HOOKS=["pre-commit","pre-push"],OPTIONAL_HOOKS=["post-merge","lib-gate.sh","push-policy"];function defaultRunGit(o,{cwd:e,env:t}={}){try{const n=execFileSync("git",o,{cwd:e,env:t||process.env,encoding:"utf8",stdio:["ignore","pipe","pipe"],windowsHide:!0});return{ok:!0,out:String(n).trim(),err:""}}catch(o){return{ok:!1,out:String(o&&o.stdout?o.stdout:"").trim(),err:String(o&&o.stderr?o.stderr:o&&o.message||o).trim()}}}function defaultReadFile(o){return fs.readFileSync(o,"utf8")}function defaultExists(o){try{return fs.statSync(o).isFile()}catch{return!1}}function defaultChmod(o){fs.chmodSync(o,493)}function repoHookStatus(o={}){const e=o.platform||process.platform,t=platformPath(e),n=o.cwd||process.cwd(),s=o.exists||defaultExists,r=o.runGit||defaultRunGit,i=t.join(n,".githooks"),a=[],c=[];for(const o of[...REQUIRED_HOOKS,...OPTIONAL_HOOKS])s(t.join(i,o))?a.push(o):c.push(o);const h=r(["rev-parse","--is-inside-work-tree"],{cwd:n,env:o.env}),u=h.ok&&"true"===h.out;let d=null;if(u){const e=r(["config","--get","core.hooksPath"],{cwd:n,env:o.env});d=e.ok&&e.out?e.out:null}const f=".githooks";var l;return{repo:n,hooksDir:i,platform:e,inGitRepo:u,configured:d,wanted:f,installed:u&&(null==(l=d)?null:String(l).replace(/\\/g,"/").replace(/\/+$/,""))===f,present:a,missing:c,execBit:"win32"!==e,execNote:"win32"===e?"Windows: the exec bit is not enforced and not needed — git for Windows runs hooks with its bundled sh.":"POSIX: the hooks are chmod 0755 so git can execute them."}}function installRepoHooks(o={}){const e=o.platform||process.platform,t=platformPath(e),n=o.cwd||process.cwd(),s=o.runGit||defaultRunGit,r=o.exists||defaultExists,i=o.chmod||defaultChmod,a=Boolean(o.dryRun),c=repoHookStatus({...o,platform:e,cwd:n,runGit:s,exists:r}),h=[];if(!r(t.join(c.hooksDir,"pre-commit")))return{ok:!1,changed:!1,code:"no-hooks",actions:h,status:c,error:`no ${c.wanted}/pre-commit under ${n} — nothing to install. A tree that never had the hooks needs them restored (\`git checkout -- .githooks/\`) or created (\`agent-gate.mjs init --hooks\`).`};if(!c.inGitRepo)return{ok:!1,changed:!1,code:"no-git",actions:h,status:c,error:`${n} is not inside a git work tree (core.hooksPath is a per-repo setting), or git is not on PATH.`};if(!c.installed&&(h.push(`git -C ${n} config core.hooksPath ${c.wanted}`),!a)){const e=s(["config","core.hooksPath",c.wanted],{cwd:n,env:o.env});if(!e.ok)return{ok:!1,changed:!1,code:"git-failed",actions:h,status:c,error:`git config refused: ${e.err||"unknown error"}`};const t=s(["config","--get","core.hooksPath"],{cwd:n,env:o.env}),r=t.ok?String(t.out).replace(/\\/g,"/").replace(/\/+$/,""):null;if(r!==c.wanted)return{ok:!1,changed:!0,code:"verify-failed",actions:h,status:c,error:`core.hooksPath reads back as "${r||"(unset)"}", not "${c.wanted}"`}}const u=[];if("win32"!==e){const n=o.modeOf||(o=>{try{return 511&fs.statSync(o).mode}catch{return null}});for(const o of c.present.filter((o=>"push-policy"!==o))){const s=t.join(c.hooksDir,o);if(493!==n(s))if(a)u.push(`chmod 0755 ${s}`);else try{i(s,493),u.push(`chmod 0755 ${o}`)}catch(e){u.push(`chmod 0755 ${o} FAILED: ${e&&e.message||e}`)}}h.push(...u)}return d={modes:u,note:c.execNote},{ok:!0,changed:h.length>0,code:"installed",actions:h,status:c,...d};var d}function hooksSummary(o={}){const e=o.platform||process.platform,t=o.config||readHookConfig({...o,platform:e}),n=o.stats||hookStats(t.hooks),s=o.repo||repoHookStatus({...o,platform:e}),r=[];if(r.push(`hooks: ${n.enabled?"enabled":"disabled"} · ${n.hooks} matcher(s) in ${n.events.length} event(s)`),n.events.length)for(const o of n.events)r.push(` ${o}: ${n.byEvent[o]}`);else r.push(" (no settings.json declares hooks — checked "+hookSettingPaths({...o,platform:e}).map((e=>shorten(e,o))).join(", ")+")");return t.from.length&&r.push(` from: ${t.from.join(", ")}`),t.foreign&&t.foreign.length&&r.push(` foreign host files (read, listed—${n.hooks&&t.foreign.length?"may outrank ours":"no hooks"}): ${t.foreign.join(", ")}`),r.push(""),r.push(`repo guard hooks (${s.wanted}/): ${s.present.length?s.present.join(", "):"none found"}`),s.missing.length&&r.push(` missing: ${s.missing.join(", ")}`),r.push(" core.hooksPath: "+(s.installed?`${s.wanted} (installed)`:`${s.configured||"(unset)"} — NOT installed, so a commit runs NO guard hooks`)),r.push(` ${s.execNote}`),r.join("\n")}module.exports={HOOK_EVENTS:HOOK_EVENTS,SETTINGS_DIRS:SETTINGS_DIRS,hooksSummary:hooksSummary,REQUIRED_HOOKS:REQUIRED_HOOKS,OPTIONAL_HOOKS:OPTIONAL_HOOKS,hookSettingPaths:hookSettingPaths,hookSourceKind:hookSourceKind,homeDir:homeDir,platformPath:platformPath,shorten:shorten,readHookConfig:readHookConfig,hookStats:hookStats,repoHookStatus:repoHookStatus,installRepoHooks:installRepoHooks};
@@ -0,0 +1,3 @@
1
+ // SPDX-License-Identifier: AGPL-3.0-or-later
2
+ // Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
3
+ "use strict";const{sanitizeModel:sanitizeModel}=require("./user-models.js"),DISCOVERY_TIMEOUT_MS=8e3;function bearer(e){return{authorization:`Bearer ${e}`}}const ENDPOINTS=Object.freeze({anthropic:Object.freeze({url:"https://api.anthropic.com/v1/models",headers:e=>({"x-api-key":e,"anthropic-version":"2023-06-01"}),note:"the vendor requires anthropic-version; the console key is sent as x-api-key"}),openai:Object.freeze({url:"https://api.openai.com/v1/models",headers:bearer,note:"OpenAI-compatible: { data: [ { id } ] }"}),deepseek:Object.freeze({url:"https://api.deepseek.com/models",headers:bearer,note:"OpenAI-compatible; /v1/models answers the same list"}),grok:Object.freeze({url:"https://api.x.ai/v1/models",headers:bearer,note:"xAI answers on /v1/models under the vendor id grok"}),gemini:Object.freeze({url:"https://generativelanguage.googleapis.com/v1beta/models",headers:()=>({}),query:e=>({key:e}),note:'the key travels in the query string; ids come back as "models/<id>"'}),groq:Object.freeze({url:"https://api.groq.com/openai/v1/models",headers:bearer,note:"OpenAI-compatible under /openai/v1"}),mistral:Object.freeze({url:"https://api.mistral.ai/v1/models",headers:bearer,note:"OpenAI-compatible"}),openrouter:Object.freeze({url:"https://openrouter.ai/api/v1/models",headers:bearer,note:'OpenAI-compatible; ids are prefixed "vendor/model"'}),together:Object.freeze({url:"https://api.together.xyz/v1/models",headers:bearer,note:"OpenAI-compatible"}),cerebras:Object.freeze({url:"https://api.cerebras.ai/v1/models",headers:bearer,note:"OpenAI-compatible under /v1"}),fireworks:Object.freeze({url:"https://api.fireworks.ai/inference/v1/models",headers:bearer,note:'OpenAI-compatible under /inference/v1; ids are "accounts/fireworks/models/<id>"'}),nvidia_nim:Object.freeze({url:"https://integrate.api.nvidia.com/v1/models",headers:bearer,note:'OpenAI-compatible; ids are "<vendor>/<model>"'}),sakana:Object.freeze({url:"https://api.sakana.ai/v1/models",headers:bearer,note:"OpenAI-compatible under /v1"})}),ALIASES=Object.freeze({"x.ai":"grok",xai:"grok",google:"gemini","google-ai":"gemini",googleai:"gemini","open-ai":"openai","deep-seek":"deepseek","openai-gpt4o-mini":"openai","anthropic-haiku":"anthropic"}),NON_CHAT_RE=/embed|whisper|\btts\b|dall-e|moderation|rerank|imagen|\bveo\b|\baqa\b|transcribe|audio|speech|synthia|guard-content/i;function endpointFor(e){const r=String(null==e?"":e).trim().toLowerCase();if(!r)return null;const o=ALIASES[r]||r,t=ENDPOINTS[o];return t?Object.freeze({id:o,...t}):null}function canDiscover(e){return Boolean(endpointFor(e))}function discoverableProviders(){return Object.keys(ENDPOINTS).sort()}function looksNonChat(e){return NON_CHAT_RE.test(String(e))}function idsFromPayload(e){const r=Array.isArray(e)?e:Array.isArray(e&&e.data)?e.data:Array.isArray(e&&e.models)?e.models:null;if(!r)return null;const o=[],t=[];for(const e of r){if(null==e)continue;const r="string"==typeof e?e:e.id||e.name||e.model;if("string"!=typeof r||!r.trim())continue;const n=r.trim().replace(/^models\//,""),i=e&&Array.isArray(e.supportedGenerationMethods)?e.supportedGenerationMethods:e&&Array.isArray(e.supported_actions)?e.supported_actions:null,s=i?i.includes("generateContent")||i.includes("generate"):null;let a;try{a=sanitizeModel(n)}catch{continue}!1===s||null===s&&looksNonChat(a)?t.push(a):o.push(a)}const n=e=>[...new Set(e)];return{ids:n(o),others:n(t).filter((e=>!o.includes(e)))}}async function discoverModels(e,r={}){const o=endpointFor(e),t=String(null==e?"":e).trim().toLowerCase(),n=String(null==r.key?"":r.key).trim();if(!o)return{ok:!1,provider:t,supported:!1,error:`${t||"that provider"} has no model-list endpoint this client knows`};if(!n)return{ok:!1,provider:o.id,supported:!0,error:`no ${o.id} key on this machine`};const i=r.fetchImpl||("function"==typeof fetch?fetch:null);if(!i)return{ok:!1,provider:o.id,supported:!0,error:"no fetch implementation available"};const s=Number.isFinite(r.timeoutMs)?r.timeoutMs:8e3,a="function"==typeof AbortController?new AbortController:null,d=a?setTimeout((()=>a.abort()),s):null,l=()=>a&&a.abort();a&&r.signal&&(r.signal.aborted?l():"function"==typeof r.signal.addEventListener&&r.signal.addEventListener("abort",l,{once:!0}));try{const r=new URL(o.url);if("function"==typeof o.query)for(const[e,t]of Object.entries(o.query(n)||{}))r.searchParams.set(e,t);const t={accept:"application/json"};for(const[e,r]of Object.entries(o.headers(n)||{}))t["authorization"===e?"Authorization":e]=r;const s=await i(r.toString(),{method:"GET",headers:t,signal:a?a.signal:void 0}),d=s&&"number"==typeof s.status?s.status:0;if(!s||"boolean"==typeof s.ok&&!s.ok){const e=401===d||403===d?`the vendor refused the key (HTTP ${d})`:404===d?`the vendor has no model list at ${r.pathname} (HTTP 404)`:`the vendor answered HTTP ${d||"nothing"}`;return{ok:!1,provider:o.id,supported:!0,status:d,error:e}}let l;try{l=await s.json()}catch(e){return{ok:!1,provider:o.id,supported:!0,status:d,error:`the vendor's reply was not JSON (${e&&e.message||e})`}}const c=idsFromPayload(l);return c?{ok:!0,provider:o.id,endpoint:o.url,ids:c.ids,others:c.others,count:c.ids.length}:{ok:!1,provider:o.id,supported:!0,status:d,error:'the vendor answered in a shape this client does not know (no "data" or "models" list)'}}catch(e){const r=e&&("AbortError"===e.name||"ABORT_ERR"===e.code)||a&&a.signal.aborted;return{ok:!1,provider:o.id,supported:!0,error:r?`the vendor did not answer within ${s} ms`:`could not reach the vendor (${e&&e.message||e})`}}finally{d&&clearTimeout(d),a&&r.signal&&"function"==typeof r.signal.removeEventListener&&r.signal.removeEventListener("abort",l)}}module.exports={DISCOVERY_TIMEOUT_MS:8e3,ENDPOINTS:ENDPOINTS,ALIASES:ALIASES,NON_CHAT_RE:NON_CHAT_RE,endpointFor:endpointFor,canDiscover:canDiscover,discoverableProviders:discoverableProviders,looksNonChat:looksNonChat,idsFromPayload:idsFromPayload,discoverModels:discoverModels};
@@ -0,0 +1,3 @@
1
+ // SPDX-License-Identifier: AGPL-3.0-or-later
2
+ // Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
3
+ "use strict";const GENERIC_TITLE="New conversation",TITLE_SYSTEM='You name conversations. Write a short descriptive title (2 to 6 words) that captures the topic of the conversation. Never repeat the user\'s words verbatim — if the message is just a greeting or has no clear topic, name it something like "New conversation". Sentence case, no quotes, no markdown, no trailing punctuation, no explanation.',isGenericTitle=e=>!e||String(e).trim().toLowerCase()===GENERIC_TITLE.toLowerCase(),GREETINGS=new Set(["hey","heey","heyy","heyyy","hi","hii","hello","hej","hejj","yo","sup","hola","howdy","hai","heyo","hiya","wassup","greetings","namaste","ahoy","hallo"]);function isTopicless(e){const t=String(e).trim().toLowerCase().replace(/[^a-z0-9\s]/g," ").replace(/\s+/g," ").trim();if(!t)return!0;const i=t.split(" ");return!!/^(good (morning|afternoon|evening)|whats up|wassup|hey there|hello there|hi there|how are you)\b/.test(t)||i.length<=2&&t.length<=12&&GREETINGS.has(i[0])}function looksLikeEcho(e,t){const i=e=>String(e).toLowerCase().replace(/[^a-z0-9\s]/g,"").replace(/\s+/g," ").trim(),n=i(e),o=i(t);if(!n||!o)return!1;if(n===o)return!0;if(o.length<=14&&(n.startsWith(o)||o.startsWith(n)))return!0;if(o.length<=24){const i=e=>new Set((String(e).toLowerCase().match(/[a-z0-9]+/g)||[]).filter((e=>!ECHO_STOP.has(e)))),n=i(e),o=i(t);if(n.size&&n.size===o.size&&[...n].every((e=>o.has(e))))return!0}return!1}const ECHO_STOP=new Set(["the","a","an","to","of","in","on","at","for","and","or","is","are","be","it","its","my","our","please","can","you","just","do","that","this"]);function cleanTitle(e){return String(null==e?"":e).replace(/\s+/g," ").trim().replace(/["'`“”‘’]/g,"").replace(/[*_#]/g,"").replace(/^\s*(?:title|name)\s*[:\-–]\s*/i,"").replace(/[.\s]+$/g,"").slice(0,60).trim()}const titlePromptOf=e=>`Write a short title for a conversation that begins with: "${String(e).slice(0,500)}"`,FILLER=/^(?:please|pls|plz|hey|hi|hello|ok(?:ay)?|so|now|just|also|and|then|maybe|well|um|uh|can you|could you|would you|will you|i want you to|i want to|i need you to|i need to|i'?d like you to|i would like you to|i'?d like to|help me|help|let'?s|lets|go ahead and)\b[\s,:;-]*/i,TRAILING_STOP=new Set(["the","a","an","in","on","at","to","for","of","and","or","with","is","are","my","our","this","that","please","can","you","could","would","i","we","just","do","it"]);function deriveTitle(e){let t=String(null==e?"":e).trim().replace(/\s+/g," ");if(!t)return GENERIC_TITLE;for(let e=0;e<6;e++){const e=t.replace(FILLER,"").trim();if(e===t)break;t=e}const i=t.split(" ").filter(Boolean);if(!i.length)return GENERIC_TITLE;const n=i.slice(0,6);for(;n.length>2&&TRAILING_STOP.has(n[n.length-1].toLowerCase().replace(/[^a-z0-9]/g,""));)n.pop();let o=n.join(" ").replace(/[.,!?;:]+$/,"").trim();return o?(o=o[0].toUpperCase()+o.slice(1),o.slice(0,60).trim()||GENERIC_TITLE):GENERIC_TITLE}async function nameConversation(e,{callModel:t,signal:i}={}){const n=null==e?"":String(e);if(!n.trim())return"";if(isTopicless(n))return GENERIC_TITLE;if(!("function"!=typeof t||i&&i.aborted)){let e=null;try{e=await t(titlePromptOf(n),{system:TITLE_SYSTEM,signal:i,naming:!0})}catch{e=null}const o=cleanTitle(e);if(o)return looksLikeEcho(o,n)?GENERIC_TITLE:o}return deriveTitle(n)}async function refineTitle(e,t,i={}){const n=i&&!0===i.named,o=i&&!0===i.seeded;if(n)return null;if(!o&&!isGenericTitle(e))return null;if(!String(t||"").trim()||isTopicless(t))return null;const r=cleanTitle(await nameConversation(t,i));return!r||isGenericTitle(r)?null:r}async function nameSession(e,t,i,n,o={}){if(!e||"function"!=typeof e.setTitle)return null;if(!i)return null;const r="function"==typeof e.getSession?e.getSession(t,i):null,s=r&&r.title,l={...o,seeded:!(!r||r.named)},a=await refineTitle(s,n,l);if(a){try{e.setTitle(t,i,a,{named:!0})}catch{return null}return a}if(isTopicless(n)&&r&&!r.named&&!isGenericTitle(s)){try{e.setTitle(t,i,GENERIC_TITLE)}catch{return null}return GENERIC_TITLE}return null}module.exports={GENERIC_TITLE:GENERIC_TITLE,TITLE_SYSTEM:TITLE_SYSTEM,isGenericTitle:isGenericTitle,isTopicless:isTopicless,looksLikeEcho:looksLikeEcho,cleanTitle:cleanTitle,titlePromptOf:titlePromptOf,deriveTitle:deriveTitle,nameConversation:nameConversation,refineTitle:refineTitle,nameSession:nameSession};
@@ -0,0 +1,3 @@
1
+ // SPDX-License-Identifier: AGPL-3.0-or-later
2
+ // Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
3
+ "use strict";const fs=require("node:fs"),os=require("node:os"),path=require("node:path"),{spawnSync:spawnSync}=require("node:child_process"),IS_WIN32="win32"===process.platform,DEFAULT_PATHEXT=".COM;.EXE;.BAT;.CMD";function defaultExists(e){try{return fs.statSync(e).isFile()}catch{return!1}}function defaultProbe(e,t=[],r={}){try{const n=spawnSync(e,t,{encoding:"utf8",timeout:r.timeout||5e3,windowsHide:!0,env:r.env});return n.error||0!==n.status?null:"string"==typeof n.stdout?n.stdout:""}catch{return null}}function defaultDirExists(e){try{return fs.statSync(e).isDirectory()}catch{return!1}}function defaultDirNonEmpty(e){try{return fs.readdirSync(e).length>0}catch{return!1}}function defaultReadText(e){try{return fs.readFileSync(e,"utf8")}catch{return null}}function defaultRun(e,t=[],r={}){try{const n=spawnSync(e,t,{encoding:"utf8",windowsHide:!0,timeout:r.timeout||1e4,env:r.env});if(n.error)return{ok:!1,error:n.error,output:""};if(0!==n.status){const t=String(n.stderr||"").trim();return{ok:!1,error:new Error(`${e} exited ${n.status}${t?`: ${t}`:""}`),status:n.status,output:String(n.stdout||"")}}return{ok:!0,error:null,output:String(n.stdout||"")}}catch(e){return{ok:!1,error:e,output:""}}}function seams(e){const t=e&&"object"==typeof e?e:{},r="string"==typeof t.platform&&t.platform?t.platform:process.platform;return{o:t,platform:r,env:t.env&&"object"==typeof t.env?t.env:process.env,win32:"win32"===r,exists:"function"==typeof t.exists?t.exists:defaultExists,probe:"function"==typeof t.probe?t.probe:defaultProbe,injectedProbe:"function"==typeof t.probe,kill:"function"==typeof t.kill?t.kill:(...e)=>process.kill(...e),run:"function"==typeof t.run?t.run:defaultRun}}function envValue(e,t,r){if(!e||"object"!=typeof e)return;const n=void 0!==e[t]?e[t]:e[t.toUpperCase()];if(void 0!==n)return n;if("win32"!==r)return;const o=t.toLowerCase();for(const t of Object.keys(e))if(t.toLowerCase()===o)return e[t]}function pathEntries(e,t,r,n){const o=String(envValue(e,"PATH",t)||"").split("win32"===t?";":":"),s=[];for(const e of o){const t=e.trim().replace(/^"|"$/g,"");t&&s.push(n.isAbsolute(t)?t:n.join(r,t))}return s}function extList(e,t){const r=String(envValue(e,"PATHEXT",t)||DEFAULT_PATHEXT).split(";").map((e=>e.trim())).filter(Boolean).map((e=>e.startsWith(".")?e:`.${e}`));return r.length?r:DEFAULT_PATHEXT.split(";")}function resolveExecutable(e,t={}){const{platform:r,env:n,exists:o,win32:s,o:i}=seams(t);if("string"!=typeof e||!e.trim())return null;const a=e.trim(),l="string"==typeof i.cwd&&i.cwd?i.cwd:process.cwd(),u=s?path.win32:path;if(s?a.includes("/")||a.includes("\\")||/^[a-zA-Z]:/.test(a):a.includes("/")){const e=u.isAbsolute(a)?a:u.join(l,a);return o(e)?e:null}const c=s?["",...extList(n,r)]:[""];for(const e of pathEntries(n,r,l,u))for(const t of c){const r=u.join(e,a+t);if(o(r))return r}return null}function shellSpec(e={}){const{platform:t,env:r,win32:n}=seams(e);return n?{cmd:envValue(r,"ComSpec",t)||envValue(r,"COMSPEC",t)||"cmd.exe",arg:"/d /s /c",kind:"cmd"}:{cmd:envValue(r,"SHELL",t)||"/bin/sh",arg:"-c",kind:"posix"}}function killTree(e,t={}){const{platform:r,env:n,win32:o,kill:s,run:i,o:a}=seams(t),l="number"==typeof e?e:e&&e.pid,u=a.signal||"SIGTERM",c=!1!==a.detached,f=a.timeout||1e4;if(!Number.isInteger(l)||l<=0)return{ok:!1,method:"none",pid:Number.isInteger(l)?l:null,error:new Error(`killTree: no usable pid (got ${JSON.stringify(e&&e.pid)})`),gone:!1};if(o){const e=i("taskkill",["/PID",String(l),"/T","/F"],{env:n,platform:r,timeout:f})||{};return!1===e.ok?{ok:!1,method:"taskkill",pid:l,error:e.error||new Error("taskkill failed"),gone:!1}:{ok:!0,method:"taskkill",pid:l,error:null,gone:!1}}let p=null;if(c)try{return s(-l,u),{ok:!0,method:"group",pid:l,error:null,gone:!1}}catch(e){p=e;const t=e&&e.code;if("ESRCH"!==t&&"EPERM"!==t)return{ok:!1,method:"group",pid:l,error:e,gone:!1}}try{return s(l,u),{ok:!0,method:"signal",pid:l,error:null,groupError:p,gone:!1}}catch(e){return{ok:!1,method:"signal",pid:l,error:e,groupError:p,gone:"ESRCH"===(e&&e.code)}}}function isAlive(e,t={}){const{platform:r,env:n,win32:o,probe:s,kill:i}=seams(t),a="number"==typeof e?e:Number(e);if(!Number.isInteger(a)||a<=0)return!1;if(o){const e=s("tasklist",["/FI",`PID eq ${a}`,"/NH","/FO","CSV"],{env:n,platform:r});if(null==e)return!1;const t=String(e).trim();return!!t&&new RegExp(`(^|[^0-9])${a}([^0-9]|$)`).test(t)}try{return i(a,0),!0}catch(e){return Boolean(e&&"EPERM"===e.code)}}function hasDisplay(e={}){const{platform:t,env:r,win32:n,probe:o,injectedProbe:s}=seams(e);return!!(n||"darwin"===t||envValue(r,"DISPLAY",t)||envValue(r,"WAYLAND_DISPLAY",t)||s&&null!==o("xdpyinfo",[],{env:r,platform:t}))}function normalizeLocale(e){if(null==e)return"";const t=String(e).trim();if(!t)return"";const r=t.split("@")[0].split(".")[0];if(/^(c|posix)$/i.test(r))return"";const n=/^([A-Za-z]{2,3})(?:[_-]([A-Za-z0-9]{2,8}))?$/.exec(r);if(!n)return"";const o=n[1].toLowerCase();return"c"===o||"posix"===o?"":n[2]?`${o}-${n[2].toUpperCase()}`:o}function appLocale(e={}){const{platform:t,env:r,o:n}=seams(e);if("string"==typeof n.locale)return normalizeLocale(n.locale);const o=n.env&&"object"==typeof n.env;for(const e of["LC_ALL","LC_CTYPE","LC_MESSAGES","LANG"]){const n=normalizeLocale(envValue(r,e,t));if(n)return n}const s=String(envValue(r,"LANGUAGE",t)||"");if(s)for(const e of s.split(":")){const t=normalizeLocale(e);if(t)return t}if(o)return"";try{return normalizeLocale((new Intl.DateTimeFormat).resolvedOptions().locale)}catch{return""}}function languageName(e,t={}){const{o:r}=seams(t);if("string"==typeof r.languageName)return r.languageName;const n=normalizeLocale(e);if(!n)return"";const o=n.split("-")[0];try{return new Intl.DisplayNames(["en"],{type:"language"}).of(o)||""}catch{return""}}function homeDir(e={}){const{platform:t,env:r,o:n}=seams(e);if("string"==typeof n.home)return n.home.trim();const o="win32"===t?["USERPROFILE","HOME"]:["HOME","USERPROFILE"];for(const e of o){const n=envValue(r,e,t);if(n&&String(n).trim())return String(n).trim()}try{return os.homedir()||""}catch{return""}}function hasPosixModes(e={}){const{win32:t}=seams(e);return!t}function winShellFolderDesktop(e,t){const r=e("reg",["query","HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Shell Folders","/v","Desktop"]);if(!r)return"";const n=/^\s*Desktop\s+REG_(?:EXPAND_)?SZ\s+(.+)$/im.exec(r),o=n&&n[1].trim();return o&&t(o)?o:""}function desktopDir(e={}){const{platform:t,env:r,win32:n,probe:o,o:s}=seams(e),i=n?path.win32:path.posix,a=homeDir(e),l="function"==typeof s.dirExists?s.dirExists:defaultDirExists,u="function"==typeof s.dirNonEmpty?s.dirNonEmpty:defaultDirNonEmpty;if(n){const e=winShellFolderDesktop(o,l);if(e)return e}const c="function"==typeof s.readText?s.readText:defaultReadText,f=[],p=e=>{e&&String(e).trim()&&f.push(String(e).trim())};if(n){const e=envValue(r,"OneDrive",t)||envValue(r,"OneDriveConsumer",t);e&&p(i.join(e,"Desktop")),a&&p(i.join(a,"OneDrive","Desktop")),a&&p(i.join(a,"Desktop"));const n=a?i.join(a,"Desktop"):"",o=f.indexOf(n);o>0&&l(n)&&u(n)&&f.slice(0,o).every((e=>!l(e)||!u(e)))&&(f.splice(o,1),f.unshift(n))}else if("darwin"===t)a&&p(i.join(a,"Desktop"));else{if(p(envValue(r,"XDG_DESKTOP_DIR",t)),a){const e=c(i.join(a,".config","user-dirs.dirs")),t=e&&/^\s*XDG_DESKTOP_DIR\s*=\s*"?([^"\n]+)"?\s*$/m.exec(e);t&&p(t[1].replace(/\$HOME\b|\${HOME}/g,a))}a&&p(i.join(a,"Desktop"))}for(const e of f)if(l(e))return e;return a&&(n||"darwin"===t)?i.join(a,"Desktop"):""}function applyDesktopAlias(e,{home:t,desktopdir:r,win32:n,P:o}){if(!t||!r)return e;const s=o.join(t,"Desktop"),i=e=>n?e.toLowerCase():e;if(i(s)===i(r))return e;if(i(e)===i(s))return r;const a=s+o.sep;return i(e).startsWith(i(a))?r+o.sep+e.slice(a.length):e}const WIN_DRIVE_RE=/^[A-Za-z]:[\\/]/,WIN_BARE_DRIVE_RE=/^[A-Za-z]:$/,WIN_UNC_RE=/^\\\\[^\\?.]/;function resolvePath(e,t={}){const{platform:r,win32:n,o:o}=seams(t),s=n?path.win32:path.posix,i=e=>({ok:!1,path:null,error:e,expandedHome:!1});if("string"!=typeof e||!e.trim())return i(`a path is required (got ${JSON.stringify(e)})`);const a=e.trim();let l=a,u=!1;if("~"===a||a.startsWith("~/")||n&&a.startsWith("~\\")){const e=homeDir(t);if(!e)return i(`cannot expand "~" in ${JSON.stringify(a)}: this machine reports no home directory. Pass a full absolute path instead.`);l="~"===a?e:s.join(e,a.slice(2)),u=!0}else if(a.startsWith("~"))return i(`${JSON.stringify(a)} names another user's home directory, which cannot be resolved from here. Use "~" for this user, or pass a full absolute path.`);if(l=applyDesktopAlias(l,{home:homeDir(t),desktopdir:o.desktopdir,win32:n,P:s}),!u){const e=homeDir(t),o=e?` This machine's home directory is ${e}.`:"";if(n){if((l.startsWith("/")||l.startsWith("\\"))&&!WIN_UNC_RE.test(l))return i(`${JSON.stringify(a)} is not an absolute path on this machine, which runs ${r}. A leading slash here means "the root of the current drive", so writing to it would silently land somewhere other than where you meant. Use a drive-qualified path (C:\\Users\\you\\Desktop\\file.txt) or "~/…".${o}`)}else if(WIN_DRIVE_RE.test(l)||WIN_BARE_DRIVE_RE.test(l)||WIN_UNC_RE.test(l))return i(`${JSON.stringify(a)} is a Windows path, but this machine runs ${r}. Use a posix path (/home/you/file.txt) or "~/…".${o}`)}const c="string"==typeof o.cwd&&o.cwd.trim()?o.cwd.trim():process.cwd(),f=s.isAbsolute(l)?s.resolve(l):s.resolve(c,l);return s.isAbsolute(f)?{ok:!0,path:f,error:null,expandedHome:u}:i(`${JSON.stringify(a)} is relative and the working directory (${JSON.stringify(c)}) is not absolute, so it cannot be resolved. Pass an absolute path.`)}function baseName(e){if("string"!=typeof e)return"";const t=e.trim().replace(/[/\\]+$/,"");if(!t)return"";if(/^[A-Za-z]:$/.test(t))return"";const r=Math.max(t.lastIndexOf("/"),t.lastIndexOf("\\"));return-1===r?t:t.slice(r+1)}const api={IS_WIN32:IS_WIN32,seams:seams,resolveExecutable:resolveExecutable,shellSpec:shellSpec,killTree:killTree,isAlive:isAlive,hasDisplay:hasDisplay,homeDir:homeDir,desktopDir:desktopDir,resolvePath:resolvePath,baseName:baseName,hasPosixModes:hasPosixModes,appLocale:appLocale,languageName:languageName,normalizeLocale:normalizeLocale};module.exports=api;
@@ -0,0 +1,3 @@
1
+ // SPDX-License-Identifier: AGPL-3.0-or-later
2
+ // Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
3
+ "use strict";const fs=require("node:fs"),path=require("node:path"),{aegisHome:aegisHome}=require("./credentials.js"),PREFS_FILE="preferences.json",PREFS_VERSION=1,SHARED_PREF_KEYS=Object.freeze(["themeIndex","model","modelClass","currentModelId","models","effort","vim","memoryPersist","confirmMode"]),LEGACY_MEMORY_PERSIST_NAMESPACE="__memoryPersist",LEGACY_CONFIRM_MODE_NAMESPACE="__confirmMode",SECRET_KEY_RE=/(^|[^a-z0-9])(api[_-]?key|apikey|key|keys|token|secret|password|passwd|credential|credentials|authorization|bearer|private[_-]?key|access[_-]?key|session[_-]?key)([^a-z0-9]|$)/i,SECRET_VALUE_RES=[/\baegis_[A-Za-z0-9_\-]{12,}/,/\bsk-[A-Za-z0-9_\-]{12,}/,/\bghp_[A-Za-z0-9_\-]{20,}/,/\bxox[baprs]-[A-Za-z0-9\-]{10,}/,/\beyJ[A-Za-z0-9_\-]{16,}\.[A-Za-z0-9_\-]{8,}/,/^[A-Za-z0-9+/]{48,}={0,2}$/];function prefsDir(e){const r=e||{};return r.dir&&String(r.dir).trim()?path.resolve(String(r.dir).trim()):aegisHome(r.env)}function prefsFile(e){const r=e||{};return r.file&&String(r.file).trim()?path.resolve(String(r.file).trim()):path.join(prefsDir(r),PREFS_FILE)}function scanForSecrets(e,r="",t=[]){if(null==e)return t;if("string"==typeof e)return SECRET_VALUE_RES.some((r=>r.test(e)))&&t.push(r||"(root)"),t;if("object"!=typeof e)return t;if(Array.isArray(e))return e.forEach(((e,o)=>scanForSecrets(e,`${r}[${o}]`,t))),t;for(const[o,s]of Object.entries(e)){const e=r?`${r}.${o}`:o;SECRET_KEY_RE.test(o)&&null!=s&&""!==s&&!1!==s?t.push(e):scanForSecrets(s,e,t)}return t}function assertNoSecrets(e,r="shared preference store"){const t=scanForSecrets(e);if(t.length)throw new Error(`${r} must not carry key material — refusing to write (found: ${t.join(", ")}). Secrets belong in the host-local credential store, where the OS can protect them.`);return e}function readJson(e,r){try{const t=JSON.parse(fs.readFileSync(e,"utf8"));return t&&"object"==typeof t&&!Array.isArray(t)?t:r}catch{return r}}function load(e){return readJson(prefsFile(e),{})}function write(e,r){assertNoSecrets(e);const t=prefsFile(r);fs.mkdirSync(path.dirname(t),{recursive:!0});const o=`${t}.tmp-${process.pid}`;fs.writeFileSync(o,JSON.stringify(e,null,2)+"\n",{mode:384}),fs.renameSync(o,t);try{fs.chmodSync(t,384)}catch{}return e}function set(e,r){const t={...load(r),...e||{}};for(const e of Object.keys(t))void 0===t[e]&&delete t[e];return void 0===t.version&&(t.version=1),write(t,r)}function get(e,r,t){const o=load(r)[e];return void 0===o?t:o}function has(e,r){return void 0!==load(r)[e]}function remove(e,r){const t=load(r);return delete t[e],write(t,r)}function extractNonSecretHalf(e){const r={},t=(e||{})[LEGACY_MEMORY_PERSIST_NAMESPACE];t&&"object"==typeof t&&"boolean"==typeof t.enabled&&(r.memoryPersist=t.enabled);const o=(e||{})[LEGACY_CONFIRM_MODE_NAMESPACE];return o&&"object"==typeof o&&"boolean"==typeof o.enabled&&(r.confirmMode=o.enabled),r}function adopt(e){const r=e||{},t=prefsFile(r),o=r.legacyDir,s=o?path.join(String(o),"settings.json"):null;if(s&&path.resolve(s)===t)return{adopted:!1,keys:[],from:s,reason:"shared store is the legacy file"};if(!s||!fs.existsSync(s))return{adopted:!1,keys:[],from:s,reason:"no legacy settings file"};const n=load(r),a=extractNonSecretHalf(readJson(s,{})),i=Object.keys(a).filter((e=>void 0===n[e]));if(!i.length)return{adopted:!1,keys:[],from:s,reason:Object.keys(a).length?"shared store already carries these preferences":"legacy store has no shared preferences"};const c={};for(const e of i)c[e]=a[e];return c.adopted={from:s,at:(new Date).toISOString(),names:i.slice().sort()},write({...n,...c},r),{adopted:!0,keys:i.slice().sort(),from:s}}module.exports={PREFS_FILE:PREFS_FILE,PREFS_VERSION:1,SHARED_PREF_KEYS:SHARED_PREF_KEYS,LEGACY_MEMORY_PERSIST_NAMESPACE:LEGACY_MEMORY_PERSIST_NAMESPACE,prefsDir:prefsDir,prefsFile:prefsFile,load:load,set:set,get:get,has:has,remove:remove,scanForSecrets:scanForSecrets,assertNoSecrets:assertNoSecrets,extractNonSecretHalf:extractNonSecretHalf,adopt:adopt};
@@ -0,0 +1,3 @@
1
+ // SPDX-License-Identifier: AGPL-3.0-or-later
2
+ // Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
3
+ "use strict";const PRESENCE_PATH="/api/v1/heartbeat",DEFAULT_INTERVAL_MS=3e5,MIN_INTERVAL_MS=6e4,MAX_INTERVAL_MS=36e5,BACKOFF_FACTOR=2,MAX_BACKOFF_MS=18e5,REQUEST_TIMEOUT_MS=2e4,APP_NAMES=Object.freeze(["desktop","cli","mcp","extension","web"]);function saneToken(e,n){try{if(null==e)return"";if("number"==typeof e&&!Number.isFinite(e))return"";const t=String(e).replace(/[\u0000-\u001f\u007f\s]+/g,""),_=Number.isFinite(Number(n))&&Number(n)>0?Math.floor(Number(n)):64;return t.slice(0,_)}catch{return""}}function saneCount(e){const n=Number(e);return!Number.isFinite(n)||n<=0?0:Math.min(1e5,Math.floor(n))}module.exports={PRESENCE_PATH:PRESENCE_PATH,DEFAULT_INTERVAL_MS:3e5,MIN_INTERVAL_MS:6e4,MAX_INTERVAL_MS:36e5,BACKOFF_FACTOR:2,MAX_BACKOFF_MS:18e5,REQUEST_TIMEOUT_MS:2e4,APP_NAMES:APP_NAMES,saneToken:saneToken,saneCount:saneCount};
@@ -0,0 +1,3 @@
1
+ // SPDX-License-Identifier: AGPL-3.0-or-later
2
+ // Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
3
+ "use strict";const{PRESENCE_PATH:PRESENCE_PATH,DEFAULT_INTERVAL_MS:DEFAULT_INTERVAL_MS,MIN_INTERVAL_MS:MIN_INTERVAL_MS,MAX_INTERVAL_MS:MAX_INTERVAL_MS,BACKOFF_FACTOR:BACKOFF_FACTOR,MAX_BACKOFF_MS:MAX_BACKOFF_MS,REQUEST_TIMEOUT_MS:REQUEST_TIMEOUT_MS,APP_NAMES:APP_NAMES,saneToken:saneToken,saneCount:saneCount}=require("./presence-constants.js"),DEFAULT_API_BASE="https://aegiscloud.org";function disabledPresence(e){const n={enabled:!1,reason:String(e||"disabled"),beats:0,failures:0,lastError:null,lastSeenAt:null,intervalMs:null,install:null,app:null,running:!1};return{enabled:!1,reason:n.reason,install:null,beat:()=>Promise.resolve(!1),start:()=>!1,stop:()=>!1,state:()=>({...n})}}function isoOf(e){try{const n=Number(e);return Number.isFinite(n)?new Date(n).toISOString():null}catch{return null}}function createPresence(e={}){const n="string"==typeof e.apiKey?e.apiKey.trim():"";if(!n)return disabledPresence("no-api-key");if(!1===e.enabled)return disabledPresence("disabled");const t="function"==typeof e.log?e.log:()=>{};function r(e){if(!o.has(e)){o.add(e);try{t("debug",`presence: ${e}`)}catch{}}}const o=new Set,s="function"==typeof e.now?e.now:()=>Date.now(),i="function"==typeof e.setTimer?e.setTimer:setTimeout,a="function"==typeof e.clearTimer?e.clearTimer:clearTimeout;let l=saneToken(e.install,64);if(l||"function"!=typeof e.fingerprint){if(!l)try{l=saneToken(require("./device-fingerprint.js").machineFingerprint(),64)}catch{r("fingerprint")}}else try{l=saneToken(e.fingerprint(),64)}catch{r("fingerprint")}if(!l)return disabledPresence("no-install-identity");const u=saneToken(e.app,24).toLowerCase()||"other",c=saneToken(e.version,32),f=saneToken(e.platform,16).toLowerCase()||("undefined"!=typeof process&&process.platform?process.platform:""),_=String(e.baseUrl||"undefined"!=typeof process&&process.env&&process.env.AEGIS_API_BASE||DEFAULT_API_BASE).replace(/\/+$/,""),A=PRESENCE_PATH,E="function"==typeof e.fetchImpl?e.fetchImpl:"function"==typeof fetch?fetch:null;function M(e,n){try{return"function"==typeof e?e():e}catch{return n}}let p=b(e.intervalMs);const T={enabled:!0,reason:null,beats:0,failures:0,lastError:null,lastSeenAt:null,intervalMs:p,install:l,app:u,version:c||null,platform:f||null,running:!1};let S=null,m=null,d=0,N=!1;function b(e){const n=Number(e);return!Number.isFinite(n)||n<=0?DEFAULT_INTERVAL_MS:Math.min(MAX_INTERVAL_MS,Math.max(MIN_INTERVAL_MS,Math.floor(n)))}function y(){if(N)return Promise.resolve(!1);if(m)return m;if(!E)return r("no-fetch"),T.lastError="no fetch implementation",T.failures+=1,Promise.resolve(!1);const t=s();return m=(async()=>{let o=!1,P=null;try{const t="function"==typeof AbortController?new AbortController:null;if(t){const e=i((()=>{o=!0;try{t.abort()}catch{}}),REQUEST_TIMEOUT_MS);e&&"function"==typeof e.unref&&e.unref(),P=()=>a(e)}const r=await E(`${_}${A}`,{method:"POST",headers:{"Content-Type":"application/json","X-API-Key":n,"X-AEGIS-Version":saneToken(e.clientVersion,32)||c||""},body:JSON.stringify({app:u,version:c||void 0,platform:f||void 0,install:l,queue:saneCount(M(e.queueDepth,0)),autonomous:Boolean(M(e.autonomous,!1))}),...t?{signal:t.signal}:{}});if(P&&P(),!r||"number"!=typeof r.status||r.status<200||r.status>=300)return T.failures+=1,T.lastError=`http ${r&&r.status?r.status:"error"}`,d=I(d),!1;let S=null;try{S=await r.json()}catch{S=null}if(T.beats+=1,T.failures=0,T.lastError=null,T.lastSeenAt=isoOf(s()),d=0,S&&"object"==typeof S&&null!=S.beat_interval_s){const e=Number(S.beat_interval_s);Number.isFinite(e)&&e>0&&(p=b(1e3*e))}return T.intervalMs=p,!0}catch(e){return P&&P(),T.failures+=1,T.lastError=o?"timeout":String(e&&e.message||e||"error").slice(0,200),d=I(d),1===T.failures&&r("beat-failed"),!1}finally{m=null,T.running&&function(e){if(N||"function"!=typeof i)return;S&&a(S);const n=Math.max(1e3,Math.floor(Number(e)||p));S=i((()=>{S=null,y()}),n),S&&"function"==typeof S.unref&&S.unref()}(Math.max(0,p+d-(s()-t)))}})(),m}function I(e){const n=e>0?e*BACKOFF_FACTOR:Math.max(MIN_INTERVAL_MS,p);return Math.min(MAX_BACKOFF_MS,Math.floor(n))}return{enabled:!0,app:u,install:l,beat:y,start:function(){return!N&&(T.running=!0,y(),!0)},stop:function(){if(N=!0,T.running=!1,S){try{a(S)}catch{}S=null}return!0},pending:()=>m,state:()=>({...T,intervalMs:p})}}module.exports={createPresence:createPresence,disabledPresence:disabledPresence,PRESENCE_PATH:PRESENCE_PATH,DEFAULT_INTERVAL_MS:DEFAULT_INTERVAL_MS,MIN_INTERVAL_MS:MIN_INTERVAL_MS,MAX_INTERVAL_MS:MAX_INTERVAL_MS,MAX_BACKOFF_MS:MAX_BACKOFF_MS,REQUEST_TIMEOUT_MS:REQUEST_TIMEOUT_MS,APP_NAMES:APP_NAMES};