aegisone 1.0.64 → 1.0.66

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 (374) hide show
  1. package/README.md +1 -1
  2. package/bin/aegis.js +1 -1
  3. package/package.json +1 -1
  4. package/scripts/bump.mjs +1 -1
  5. package/scripts/bundle.js +1 -1
  6. package/scripts/postinstall.mjs +1 -1
  7. package/scripts/predist.mjs +1 -1
  8. package/src/child.js +1 -1
  9. package/src/dispatch.js +1 -1
  10. package/src/doctor.js +1 -1
  11. package/src/probes.js +1 -1
  12. package/src/productupdate.js +1 -1
  13. package/src/protocol.js +1 -1
  14. package/src/release.js +1 -1
  15. package/src/selfhost.js +1 -1
  16. package/vendor/cli/bin/aegiscode.js +47 -5
  17. package/vendor/cli/package.json +1 -1
  18. package/vendor/cli/scripts/check.mjs +1 -1
  19. package/vendor/cli/scripts/demo.mjs +1 -1
  20. package/vendor/cli/scripts/postinstall.mjs +1 -1
  21. package/vendor/cli/scripts/predist.mjs +1 -1
  22. package/vendor/cli/scripts/runtests.mjs +1 -1
  23. package/vendor/cli/src/app.js +1 -1
  24. package/vendor/cli/src/art.js +1 -1
  25. package/vendor/cli/src/autonomous.js +574 -10
  26. package/vendor/cli/src/chatflow.js +1 -1
  27. package/vendor/cli/src/checkpoint.js +1 -1
  28. package/vendor/cli/src/clipboard.js +1 -1
  29. package/vendor/cli/src/cloudsync.js +1 -1
  30. package/vendor/cli/src/commands.js +2 -2
  31. package/vendor/cli/src/config.js +1 -1
  32. package/vendor/cli/src/connect.js +1 -1
  33. package/vendor/cli/src/devrun.js +1 -1
  34. package/vendor/cli/src/diff.js +1 -1
  35. package/vendor/cli/src/diffview.js +1 -1
  36. package/vendor/cli/src/dream-cmd.js +3 -0
  37. package/vendor/cli/src/dream.js +1 -1
  38. package/vendor/cli/src/engine.js +1 -1
  39. package/vendor/cli/src/events.js +1 -1
  40. package/vendor/cli/src/export.js +1 -1
  41. package/vendor/cli/src/fingerprint.js +1 -1
  42. package/vendor/cli/src/format.js +1 -1
  43. package/vendor/cli/src/fuzzy.js +1 -1
  44. package/vendor/cli/src/history.js +1 -1
  45. package/vendor/cli/src/init.js +1 -1
  46. package/vendor/cli/src/limits.js +1 -1
  47. package/vendor/cli/src/markdown.js +1 -1
  48. package/vendor/cli/src/models.js +1 -1
  49. package/vendor/cli/src/overlays.js +1 -1
  50. package/vendor/cli/src/panels.js +1 -1
  51. package/vendor/cli/src/ping.js +1 -1
  52. package/vendor/cli/src/presence.js +1 -1
  53. package/vendor/cli/src/provenance.lock.json +3 -3
  54. package/vendor/cli/src/render.js +1 -1
  55. package/vendor/cli/src/screen.js +1 -1
  56. package/vendor/cli/src/screens.js +1 -1
  57. package/vendor/cli/src/secret.js +1 -1
  58. package/vendor/cli/src/securefs.js +1 -1
  59. package/vendor/cli/src/settings.js +1 -1
  60. package/vendor/cli/src/signup.js +1 -1
  61. package/vendor/cli/src/summarize.js +1 -1
  62. package/vendor/cli/src/sysdiag.js +1 -1
  63. package/vendor/cli/src/theme.js +1 -1
  64. package/vendor/cli/src/title.js +1 -1
  65. package/vendor/cli/src/todos.js +1 -1
  66. package/vendor/cli/src/tokens.js +1 -1
  67. package/vendor/cli/src/topup.js +1 -1
  68. package/vendor/cli/src/update.js +1 -1
  69. package/vendor/cli/vendor/client/aegis.js +1 -1
  70. package/vendor/cli/vendor/client/attest.js +1 -1
  71. package/vendor/cli/vendor/client/authorship-key.js +1 -1
  72. package/vendor/cli/vendor/client/auto-provision.js +1 -1
  73. package/vendor/cli/vendor/client/brain-catalog.js +1 -1
  74. package/vendor/cli/vendor/client/byok-catalog.js +1 -1
  75. package/vendor/cli/vendor/client/catalog-client.js +1 -1
  76. package/vendor/cli/vendor/client/conversation-export.js +1 -1
  77. package/vendor/cli/vendor/client/credentials.js +1 -1
  78. package/vendor/cli/vendor/client/credits.js +1 -1
  79. package/vendor/cli/vendor/client/drive-connect.js +1 -1
  80. package/vendor/cli/vendor/client/env-file.js +1 -1
  81. package/vendor/cli/vendor/client/fingerprint.js +1 -1
  82. package/vendor/cli/vendor/client/foreign-memory.js +1 -1
  83. package/vendor/cli/vendor/client/foreign-sessions.js +1 -1
  84. package/vendor/cli/vendor/client/google-signin.js +1 -1
  85. package/vendor/cli/vendor/client/hooks.js +1 -1
  86. package/vendor/cli/vendor/client/model-discovery.js +1 -1
  87. package/vendor/cli/vendor/client/model-sync.js +1 -1
  88. package/vendor/cli/vendor/client/naming.js +1 -1
  89. package/vendor/cli/vendor/client/platform.js +1 -1
  90. package/vendor/cli/vendor/client/prefs.js +1 -1
  91. package/vendor/cli/vendor/client/presence.js +1 -1
  92. package/vendor/cli/vendor/client/record-vault.js +2 -2
  93. package/vendor/cli/vendor/client/session-search.js +1 -1
  94. package/vendor/cli/vendor/client/session-store.js +1 -1
  95. package/vendor/cli/vendor/client/skills.js +1 -1
  96. package/vendor/cli/vendor/client/topup.js +1 -1
  97. package/vendor/cli/vendor/client/touch.js +1 -1
  98. package/vendor/cli/vendor/client/update.js +1 -1
  99. package/vendor/cli/vendor/client/user-models.js +1 -1
  100. package/vendor/cli/vendor/desktop/lib/local/attachments.js +1 -1
  101. package/vendor/cli/vendor/desktop/lib/local/autonomous.js +1 -1
  102. package/vendor/cli/vendor/desktop/lib/local/claude-pro.js +1 -1
  103. package/vendor/cli/vendor/desktop/lib/local/context.js +1 -1
  104. package/vendor/cli/vendor/desktop/lib/local/engine.js +1 -1
  105. package/vendor/cli/vendor/desktop/lib/local/entitlement.js +1 -1
  106. package/vendor/cli/vendor/desktop/lib/local/integrity.js +1 -1
  107. package/vendor/cli/vendor/desktop/lib/local/local.js +1 -1
  108. package/vendor/cli/vendor/desktop/lib/local/perm-rules.js +5 -0
  109. package/vendor/cli/vendor/desktop/lib/local/perm-store.js +5 -0
  110. package/vendor/cli/vendor/desktop/lib/local/perm-write.js +5 -0
  111. package/vendor/cli/vendor/desktop/lib/local/pro-sessions.js +3 -1
  112. package/vendor/cli/vendor/desktop/lib/local/prompt.js +1 -1
  113. package/vendor/cli/vendor/desktop/lib/local/queue.js +1 -1
  114. package/vendor/cli/vendor/desktop/lib/local/repeat-guard.js +1 -1
  115. package/vendor/cli/vendor/desktop/lib/local/session-rounds.js +1 -1
  116. package/vendor/cli/vendor/desktop/lib/local/spill.js +1 -1
  117. package/vendor/cli/vendor/desktop/lib/local/turn-guard.js +1 -1
  118. package/vendor/cli/vendor/desktop/lib/local/verify-stop.js +1 -1
  119. package/vendor/cli/vendor/desktop/lib/local/worktree-lock.js +1 -1
  120. package/vendor/cli/vendor/desktop/lib/settings.js +1 -1
  121. package/vendor/cli/vendor/desktop/main.js +82 -1
  122. package/vendor/cli/vendor/desktop/renderer/usage.js +1 -1
  123. package/vendor/cli/vendor/hosts/install.js +1 -1
  124. package/vendor/cli/vendor/hosts/openai-shim.js +1 -1
  125. package/vendor/cli/vendor/hosts/spec.js +1 -1
  126. package/vendor/cli/vendor/hosts/targets.js +1 -1
  127. package/vendor/cli/vendor/mcp/admission.js +1 -1
  128. package/vendor/cli/vendor/mcp/server.js +1 -1
  129. package/vendor/cli/vendor/mcp/tools.js +1 -1
  130. package/vendor/cli/vendor/one/src/child.js +1 -1
  131. package/vendor/cli/vendor/one/src/protocol.js +1 -1
  132. package/vendor/cli/vendor/one/src/selfhost.js +1 -1
  133. package/vendor/desktop/bin/aegis.js +1 -1
  134. package/vendor/desktop/lib/auto.js +1 -1
  135. package/vendor/desktop/lib/avatar/companion.js +1 -1
  136. package/vendor/desktop/lib/avatar/cosmetics.js +1 -1
  137. package/vendor/desktop/lib/avatar/holder-turn.js +1 -1
  138. package/vendor/desktop/lib/avatar/holders.js +1 -1
  139. package/vendor/desktop/lib/avatar/identity.js +1 -1
  140. package/vendor/desktop/lib/avatar/level.js +1 -1
  141. package/vendor/desktop/lib/avatar/mirror.js +1 -1
  142. package/vendor/desktop/lib/avatar/persona.js +1 -1
  143. package/vendor/desktop/lib/avatar/profile.js +1 -1
  144. package/vendor/desktop/lib/avatar/register.js +1 -1
  145. package/vendor/desktop/lib/avatar/store.js +1 -1
  146. package/vendor/desktop/lib/avatar/transfer.js +1 -1
  147. package/vendor/desktop/lib/avatar/turn.js +1 -1
  148. package/vendor/desktop/lib/avatar/voice.js +1 -1
  149. package/vendor/desktop/lib/avatar/xp.js +1 -1
  150. package/vendor/desktop/lib/deep-link.js +1 -1
  151. package/vendor/desktop/lib/local/attachments.js +1 -1
  152. package/vendor/desktop/lib/local/autonomous.js +1 -1
  153. package/vendor/desktop/lib/local/claude-pro.js +1 -1
  154. package/vendor/desktop/lib/local/cli-face.js +1 -1
  155. package/vendor/desktop/lib/local/context.js +1 -1
  156. package/vendor/desktop/lib/local/engine.js +1 -1
  157. package/vendor/desktop/lib/local/entitlement.js +1 -1
  158. package/vendor/desktop/lib/local/integrity.js +1 -1
  159. package/vendor/desktop/lib/local/local.js +1 -1
  160. package/vendor/desktop/lib/local/perm-rules.js +5 -0
  161. package/vendor/desktop/lib/local/perm-store.js +5 -0
  162. package/vendor/desktop/lib/local/perm-write.js +5 -0
  163. package/vendor/desktop/lib/local/pro-sessions.js +3 -1
  164. package/vendor/desktop/lib/local/prompt.js +1 -1
  165. package/vendor/desktop/lib/local/pty-host.js +1 -1
  166. package/vendor/desktop/lib/local/queue.js +1 -1
  167. package/vendor/desktop/lib/local/repeat-guard.js +1 -1
  168. package/vendor/desktop/lib/local/session-rounds.js +1 -1
  169. package/vendor/desktop/lib/local/spill.js +1 -1
  170. package/vendor/desktop/lib/local/telemetry.js +1 -1
  171. package/vendor/desktop/lib/local/turn-guard.js +1 -1
  172. package/vendor/desktop/lib/local/verify-stop.js +1 -1
  173. package/vendor/desktop/lib/local/worktree-lock.js +1 -1
  174. package/vendor/desktop/lib/provider-key-mirror.js +1 -1
  175. package/vendor/desktop/lib/quick-launcher.js +1 -1
  176. package/vendor/desktop/lib/settings.js +1 -1
  177. package/vendor/desktop/lib/skills-host.js +1 -1
  178. package/vendor/desktop/lib/speech-host.js +1 -1
  179. package/vendor/desktop/lib/sync/memory-store.js +1 -1
  180. package/vendor/desktop/lib/sync/persist-gate.js +1 -1
  181. package/vendor/desktop/lib/window-state.js +1 -1
  182. package/vendor/desktop/main.js +82 -1
  183. package/vendor/desktop/package.json +1 -1
  184. package/vendor/desktop/preload.js +3 -1
  185. package/vendor/desktop/renderer/app.js +3 -3
  186. package/vendor/desktop/renderer/avatar/assemble.js +1 -1
  187. package/vendor/desktop/renderer/avatar/avatar.js +1 -1
  188. package/vendor/desktop/renderer/avatar/cards.js +1 -1
  189. package/vendor/desktop/renderer/avatar/hud.js +1 -1
  190. package/vendor/desktop/renderer/avatar/pane.js +1 -1
  191. package/vendor/desktop/renderer/avatar/parts.js +1 -1
  192. package/vendor/desktop/renderer/commands.js +1 -1
  193. package/vendor/desktop/renderer/companion.js +1 -1
  194. package/vendor/desktop/renderer/composer-triggers.js +1 -1
  195. package/vendor/desktop/renderer/dictation.js +1 -1
  196. package/vendor/desktop/renderer/diff.js +1 -1
  197. package/vendor/desktop/renderer/diffview.js +1 -1
  198. package/vendor/desktop/renderer/fingerprint.js +2 -2
  199. package/vendor/desktop/renderer/index.html +10 -4
  200. package/vendor/desktop/renderer/library.js +1 -1
  201. package/vendor/desktop/renderer/markdown.js +1 -1
  202. package/vendor/desktop/renderer/palette-filter.js +1 -1
  203. package/vendor/desktop/renderer/provider-toolbar.js +1 -1
  204. package/vendor/desktop/renderer/providers.js +1 -1
  205. package/vendor/desktop/renderer/pty-frame.css +35 -0
  206. package/vendor/desktop/renderer/pty-frame.html +47 -0
  207. package/vendor/desktop/renderer/pty-panel.js +1 -1
  208. package/vendor/desktop/renderer/pty-window.html +72 -0
  209. package/vendor/desktop/renderer/pty-window.js +3 -0
  210. package/vendor/desktop/renderer/quick.js +1 -1
  211. package/vendor/desktop/renderer/settings-skills.js +1 -1
  212. package/vendor/desktop/renderer/shortcuts.js +1 -1
  213. package/vendor/desktop/renderer/stream-policy.js +1 -1
  214. package/vendor/desktop/renderer/style.css +77 -3
  215. package/vendor/desktop/renderer/transcript-view.js +1 -1
  216. package/vendor/desktop/renderer/usage.js +1 -1
  217. package/vendor/desktop/renderer/welcome-rows.js +1 -1
  218. package/vendor/desktop/vendor/aegis.js +1 -1
  219. package/vendor/desktop/vendor/attest.js +1 -1
  220. package/vendor/desktop/vendor/authorship-key.js +1 -1
  221. package/vendor/desktop/vendor/auto-provision.js +1 -1
  222. package/vendor/desktop/vendor/brain-catalog.js +1 -1
  223. package/vendor/desktop/vendor/byok-catalog.js +1 -1
  224. package/vendor/desktop/vendor/catalog-client.js +1 -1
  225. package/vendor/desktop/vendor/conversation-export.js +1 -1
  226. package/vendor/desktop/vendor/credentials.js +1 -1
  227. package/vendor/desktop/vendor/credits.js +1 -1
  228. package/vendor/desktop/vendor/drive-connect.js +1 -1
  229. package/vendor/desktop/vendor/env-file.js +1 -1
  230. package/vendor/desktop/vendor/faces/cli/bin/aegiscode.js +2 -2
  231. package/vendor/desktop/vendor/faces/cli/package.json +1 -1
  232. package/vendor/desktop/vendor/faces/cli/scripts/check.mjs +1 -1
  233. package/vendor/desktop/vendor/faces/cli/scripts/demo.mjs +1 -1
  234. package/vendor/desktop/vendor/faces/cli/scripts/postinstall.mjs +1 -1
  235. package/vendor/desktop/vendor/faces/cli/scripts/predist.mjs +1 -1
  236. package/vendor/desktop/vendor/faces/cli/scripts/runtests.mjs +1 -1
  237. package/vendor/desktop/vendor/faces/cli/src/app.js +1 -1
  238. package/vendor/desktop/vendor/faces/cli/src/art.js +1 -1
  239. package/vendor/desktop/vendor/faces/cli/src/autonomous.js +1 -1
  240. package/vendor/desktop/vendor/faces/cli/src/caps.js +1 -1
  241. package/vendor/desktop/vendor/faces/cli/src/chatflow.js +1 -1
  242. package/vendor/desktop/vendor/faces/cli/src/checkpoint.js +1 -1
  243. package/vendor/desktop/vendor/faces/cli/src/clipboard.js +1 -1
  244. package/vendor/desktop/vendor/faces/cli/src/cloudsync.js +1 -1
  245. package/vendor/desktop/vendor/faces/cli/src/commands.js +2 -2
  246. package/vendor/desktop/vendor/faces/cli/src/config.js +1 -1
  247. package/vendor/desktop/vendor/faces/cli/src/connect.js +1 -1
  248. package/vendor/desktop/vendor/faces/cli/src/devrun.js +1 -1
  249. package/vendor/desktop/vendor/faces/cli/src/diff.js +1 -1
  250. package/vendor/desktop/vendor/faces/cli/src/diffview.js +1 -1
  251. package/vendor/desktop/vendor/faces/cli/src/dream-cmd.js +3 -0
  252. package/vendor/desktop/vendor/faces/cli/src/dream.js +1 -1
  253. package/vendor/desktop/vendor/faces/cli/src/engine.js +1 -1
  254. package/vendor/desktop/vendor/faces/cli/src/events.js +1 -1
  255. package/vendor/desktop/vendor/faces/cli/src/export.js +1 -1
  256. package/vendor/desktop/vendor/faces/cli/src/fingerprint.js +1 -1
  257. package/vendor/desktop/vendor/faces/cli/src/format.js +1 -1
  258. package/vendor/desktop/vendor/faces/cli/src/fuzzy.js +1 -1
  259. package/vendor/desktop/vendor/faces/cli/src/history.js +1 -1
  260. package/vendor/desktop/vendor/faces/cli/src/init.js +1 -1
  261. package/vendor/desktop/vendor/faces/cli/src/limits.js +1 -1
  262. package/vendor/desktop/vendor/faces/cli/src/markdown.js +1 -1
  263. package/vendor/desktop/vendor/faces/cli/src/mcp.js +1 -1
  264. package/vendor/desktop/vendor/faces/cli/src/models.js +1 -1
  265. package/vendor/desktop/vendor/faces/cli/src/overlays.js +1 -1
  266. package/vendor/desktop/vendor/faces/cli/src/panels.js +1 -1
  267. package/vendor/desktop/vendor/faces/cli/src/permissions.js +1 -1
  268. package/vendor/desktop/vendor/faces/cli/src/ping.js +1 -1
  269. package/vendor/desktop/vendor/faces/cli/src/presence.js +1 -1
  270. package/vendor/desktop/vendor/faces/cli/src/provenance.js +1 -1
  271. package/vendor/desktop/vendor/faces/cli/src/provenance.lock.json +3 -3
  272. package/vendor/desktop/vendor/faces/cli/src/render.js +1 -1
  273. package/vendor/desktop/vendor/faces/cli/src/screen.js +1 -1
  274. package/vendor/desktop/vendor/faces/cli/src/screens.js +1 -1
  275. package/vendor/desktop/vendor/faces/cli/src/secret.js +1 -1
  276. package/vendor/desktop/vendor/faces/cli/src/securefs.js +1 -1
  277. package/vendor/desktop/vendor/faces/cli/src/settings.js +1 -1
  278. package/vendor/desktop/vendor/faces/cli/src/signup.js +1 -1
  279. package/vendor/desktop/vendor/faces/cli/src/summarize.js +1 -1
  280. package/vendor/desktop/vendor/faces/cli/src/sysdiag.js +1 -1
  281. package/vendor/desktop/vendor/faces/cli/src/theme.js +1 -1
  282. package/vendor/desktop/vendor/faces/cli/src/title.js +1 -1
  283. package/vendor/desktop/vendor/faces/cli/src/todos.js +1 -1
  284. package/vendor/desktop/vendor/faces/cli/src/tokens.js +1 -1
  285. package/vendor/desktop/vendor/faces/cli/src/topup.js +1 -1
  286. package/vendor/desktop/vendor/faces/cli/src/update.js +1 -1
  287. package/vendor/desktop/vendor/faces/cli/vendor/client/aegis.js +1 -1
  288. package/vendor/desktop/vendor/faces/cli/vendor/client/attest.js +1 -1
  289. package/vendor/desktop/vendor/faces/cli/vendor/client/authorship-key.js +1 -1
  290. package/vendor/desktop/vendor/faces/cli/vendor/client/auto-provision.js +1 -1
  291. package/vendor/desktop/vendor/faces/cli/vendor/client/brain-catalog.js +1 -1
  292. package/vendor/desktop/vendor/faces/cli/vendor/client/byok-catalog.js +1 -1
  293. package/vendor/desktop/vendor/faces/cli/vendor/client/catalog-client.js +1 -1
  294. package/vendor/desktop/vendor/faces/cli/vendor/client/conversation-export.js +1 -1
  295. package/vendor/desktop/vendor/faces/cli/vendor/client/credentials.js +1 -1
  296. package/vendor/desktop/vendor/faces/cli/vendor/client/credits.js +1 -1
  297. package/vendor/desktop/vendor/faces/cli/vendor/client/drive-connect.js +1 -1
  298. package/vendor/desktop/vendor/faces/cli/vendor/client/env-file.js +1 -1
  299. package/vendor/desktop/vendor/faces/cli/vendor/client/fingerprint.js +1 -1
  300. package/vendor/desktop/vendor/faces/cli/vendor/client/foreign-memory.js +1 -1
  301. package/vendor/desktop/vendor/faces/cli/vendor/client/foreign-sessions.js +1 -1
  302. package/vendor/desktop/vendor/faces/cli/vendor/client/google-signin.js +1 -1
  303. package/vendor/desktop/vendor/faces/cli/vendor/client/hooks.js +1 -1
  304. package/vendor/desktop/vendor/faces/cli/vendor/client/model-discovery.js +1 -1
  305. package/vendor/desktop/vendor/faces/cli/vendor/client/model-sync.js +1 -1
  306. package/vendor/desktop/vendor/faces/cli/vendor/client/naming.js +1 -1
  307. package/vendor/desktop/vendor/faces/cli/vendor/client/platform.js +1 -1
  308. package/vendor/desktop/vendor/faces/cli/vendor/client/prefs.js +1 -1
  309. package/vendor/desktop/vendor/faces/cli/vendor/client/presence.js +1 -1
  310. package/vendor/desktop/vendor/faces/cli/vendor/client/record-vault.js +2 -2
  311. package/vendor/desktop/vendor/faces/cli/vendor/client/session-search.js +1 -1
  312. package/vendor/desktop/vendor/faces/cli/vendor/client/session-store.js +1 -1
  313. package/vendor/desktop/vendor/faces/cli/vendor/client/skills.js +1 -1
  314. package/vendor/desktop/vendor/faces/cli/vendor/client/topup.js +1 -1
  315. package/vendor/desktop/vendor/faces/cli/vendor/client/touch.js +1 -1
  316. package/vendor/desktop/vendor/faces/cli/vendor/client/update.js +1 -1
  317. package/vendor/desktop/vendor/faces/cli/vendor/client/user-models.js +1 -1
  318. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/attachments.js +1 -1
  319. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/autonomous.js +1 -1
  320. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/claude-pro.js +1 -1
  321. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/context.js +1 -1
  322. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/engine.js +1 -1
  323. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/entitlement.js +1 -1
  324. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/exec-plan.js +1 -1
  325. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/integrity.js +1 -1
  326. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/local.js +1 -1
  327. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/perm-rules.js +2 -0
  328. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/perm-store.js +3 -1
  329. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/perm-write.js +2 -0
  330. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/pro-sessions.js +3 -1
  331. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/prompt.js +1 -1
  332. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/queue.js +1 -1
  333. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/repeat-guard.js +1 -1
  334. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/session-rounds.js +1 -1
  335. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/shell.js +1 -1
  336. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/spill.js +1 -1
  337. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/tools.js +1 -1
  338. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/turn-guard.js +1 -1
  339. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/verify-stop.js +1 -1
  340. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/worktree-lock.js +1 -1
  341. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/settings.js +1 -1
  342. package/vendor/desktop/vendor/faces/cli/vendor/desktop/main.js +3 -3
  343. package/vendor/desktop/vendor/faces/cli/vendor/desktop/renderer/usage.js +1 -1
  344. package/vendor/desktop/vendor/faces/cli/vendor/hosts/install.js +1 -1
  345. package/vendor/desktop/vendor/faces/cli/vendor/hosts/openai-shim.js +1 -1
  346. package/vendor/desktop/vendor/faces/cli/vendor/hosts/spec.js +1 -1
  347. package/vendor/desktop/vendor/faces/cli/vendor/hosts/targets.js +1 -1
  348. package/vendor/desktop/vendor/faces/cli/vendor/mcp/admission.js +1 -1
  349. package/vendor/desktop/vendor/faces/cli/vendor/mcp/server.js +1 -1
  350. package/vendor/desktop/vendor/faces/cli/vendor/mcp/tools.js +1 -1
  351. package/vendor/desktop/vendor/faces/cli/vendor/one/src/child.js +1 -1
  352. package/vendor/desktop/vendor/faces/cli/vendor/one/src/protocol.js +1 -1
  353. package/vendor/desktop/vendor/faces/cli/vendor/one/src/selfhost.js +1 -1
  354. package/vendor/desktop/vendor/fingerprint.js +1 -1
  355. package/vendor/desktop/vendor/foreign-memory.js +1 -1
  356. package/vendor/desktop/vendor/foreign-sessions.js +1 -1
  357. package/vendor/desktop/vendor/google-signin.js +1 -1
  358. package/vendor/desktop/vendor/hooks.js +1 -1
  359. package/vendor/desktop/vendor/model-discovery.js +1 -1
  360. package/vendor/desktop/vendor/model-sync.js +1 -1
  361. package/vendor/desktop/vendor/naming.js +1 -1
  362. package/vendor/desktop/vendor/platform.js +1 -1
  363. package/vendor/desktop/vendor/prefs.js +1 -1
  364. package/vendor/desktop/vendor/presence.js +1 -1
  365. package/vendor/desktop/vendor/protocol.js +1 -1
  366. package/vendor/desktop/vendor/record-vault.js +2 -2
  367. package/vendor/desktop/vendor/selfhost.js +1 -1
  368. package/vendor/desktop/vendor/session-search.js +1 -1
  369. package/vendor/desktop/vendor/session-store.js +1 -1
  370. package/vendor/desktop/vendor/skills.js +1 -1
  371. package/vendor/desktop/vendor/topup.js +1 -1
  372. package/vendor/desktop/vendor/touch.js +1 -1
  373. package/vendor/desktop/vendor/update.js +1 -1
  374. package/vendor/desktop/vendor/user-models.js +1 -1
@@ -1,3 +1,3 @@
1
1
  // SPDX-License-Identifier: AGPL-3.0-or-later
2
2
  // Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
3
- "use strict";function usageTokens(e){if(!e||"object"!=typeof e)return null;if("number"==typeof e.total_tokens)return e.total_tokens;const t=e.input_tokens??e.prompt_tokens??e.input,o=e.output_tokens??e.completion_tokens??e.output;return"number"!=typeof t&&"number"!=typeof o?null:(t||0)+(o||0)}function estimateTokens(e){return e?Math.max(1,Math.ceil([...String(e)].length/4)):0}function estimatedBuckets(e,t,o){const n=("string"==typeof t?t:"")+("string"==typeof o?o:"");return"string"==typeof e&&e.length>0||n.length>0?{input:estimateTokens(e),output:estimateTokens(n),cacheRead:0,cacheWrite:0,real:!1}:null}const RATES={sonnet:{input:3,output:15,cacheRead:.3,cacheWrite:3.75},default:{input:3,output:15,cacheRead:.3,cacheWrite:3.75},fable:{input:10,output:50,cacheRead:1,cacheWrite:12.5},opus:{input:5,output:25,cacheRead:.5,cacheWrite:6.25},haiku:{input:1,output:5,cacheRead:.1,cacheWrite:1.25},"claude-haiku":{input:1,output:5,cacheRead:.1,cacheWrite:1.25},"claude-opus-5":{input:5,output:25,cacheRead:.5,cacheWrite:6.25},"claude-opus-5-5":{input:4,output:20,cacheRead:.2,cacheWrite:5},"claude-sonnet-5":{input:2,output:10,cacheRead:.2,cacheWrite:2.5},"claude-sonnet-5-5":{input:2,output:10,cacheRead:.1,cacheWrite:2.5},"claude-haiku-5-5":{input:.1,output:.5,cacheRead:.01,cacheWrite:.125},"claude-fable-5":{input:10,output:50,cacheRead:1,cacheWrite:12.5},"claude-fable-5-1":{input:10,output:50,cacheRead:.25,cacheWrite:12.5},"claude-sonnet-4-6":{input:3,output:15,cacheRead:.3,cacheWrite:3.75},"claude-sonnet-4-5":{input:3,output:15,cacheRead:.3,cacheWrite:3.75},deepseek:{input:.3,output:1.2,cacheRead:.006,cacheWrite:.3,offPeak:{input:.15,output:.6,cacheRead:.003,cacheWrite:.15}},"deepseek-v4-pro":{input:1.32,output:3.96,cacheRead:.044,cacheWrite:1.32,offPeak:{input:.66,output:1.98,cacheRead:.022,cacheWrite:.66}},"deepseek-v4.1-pro":{input:1.32,output:3.96,cacheRead:.044,cacheWrite:1.32,offPeak:{input:.66,output:1.98,cacheRead:.022,cacheWrite:.66}},"grok-4.7":{input:2,output:6,cacheRead:.5,cacheWrite:2},"gemini-3.8-flash":{input:.75,output:3.75,cacheRead:.075,cacheWrite:.75},"gpt-5.5":{input:5,output:30,cacheRead:.5,cacheWrite:5}};function isPeak(e,t=new Date){if(0!==String(e||"").toLowerCase().indexOf("deepseek"))return!0;const o=t.getUTCDay();if(0===o||6===o)return!1;const n=t.getUTCHours();return n>=1&&n<4||n>=6&&n<10}const RATE_BASIS=Object.freeze({EXACT:"exact",PREFIX:"prefix",FAMILY:"family",DEFAULT:"default"}),RATE_FAMILIES=Object.keys(RATES).filter((e=>"default"!==e)),UNPRICED_BY_DESIGN=Object.freeze({nexus:"auto-routing id: aegis1 picks the tier and settles the charge","nexus-brain":"pooled: multi-call fan-out, aegis1 settles the charge","aegis-brain":"pooled alias of nexus-brain","nexus-brain-smart":"pooled alias of nexus-brain","nexus-brain-neo":"pooled alias of nexus-brain","aegis-brain-smart":"pooled alias of nexus-brain","aegis-brain-neo":"pooled alias of nexus-brain","openai-gpt4o-mini":"pooled seat, aegis1 settles the charge",anthropic:"provider name, not a model id",openai:"provider name, not a model id",groq:"provider name, not a model id",google:"provider name, not a model id",xai:"provider name, not a model id"});function ratesFor(e,{at:t}={}){const o=String(e||"").toLowerCase(),n=(e,n)=>{const s=isPeak(0===o.indexOf("deepseek")||o.indexOf(":deepseek")>-1?"deepseek":o,t||new Date);return{...!s&&e.offPeak?{...e,...e.offPeak}:e,basis:n,peak:s,model:o}};if(!o)return n(RATES.default,RATE_BASIS.DEFAULT);const s=[o],a=Math.max(o.lastIndexOf(":"),o.lastIndexOf("/")),u=o.slice(a+1);u&&u!==o&&s.push(u);for(const e of s)if(RATES[e])return n(RATES[e],RATE_BASIS.EXACT);let c=null,i=0;for(const e of s)for(const[t,o]of Object.entries(RATES))"default"!==t&&e.startsWith(t)&&t.length>i&&(c=o,i=t.length);if(c)return n(c,RATE_BASIS.PREFIX);let r=null,p=0;for(const e of RATE_FAMILIES)o.includes(e)&&e.length>p&&(r=RATES[e],p=e.length);return n(r||RATES.default,r?RATE_BASIS.FAMILY:RATE_BASIS.DEFAULT)}function usageBuckets(e){const t=e&&"object"==typeof e?e:{},o=(...e)=>{for(const t of e)if("number"==typeof t)return t;return 0},n=e=>"number"==typeof e?e:void 0,s=n(t.input_tokens),a=n(t.prompt_tokens),u=t.prompt_tokens_details,c=u&&"object"==typeof u?n(u.cached_tokens):void 0,i=o(t.prompt_cache_hit_tokens,c,t.cached_tokens),r=void 0===s&&void 0!==a,p=r?a:o(s,a,t.input),l=o(t.cache_read_input_tokens,t.cacheRead,i),d=r?Math.min(Math.max(0,p),l):l,f=o(t.cache_creation_input_tokens,t.cacheWrite),m=o(t.output_tokens,t.completion_tokens,t.output),h=r?Math.max(0,p-d):p,k=o(t.total_tokens),R=h+m+d+f;return{input:k>R?h+(k-R):h,output:m,cacheRead:d,cacheWrite:f,cacheReported:"number"==typeof t.cache_read_input_tokens||"number"==typeof t.cacheRead||"number"==typeof t.cache_creation_input_tokens||"number"==typeof t.cacheWrite||"number"==typeof t.prompt_cache_hit_tokens||"number"==typeof t.cached_tokens||"number"==typeof c}}function cacheHitRate(e){const t=usageBuckets(e),o=Math.max(0,t.cacheRead||0),n=Math.max(0,t.input||0),s=o+n;return{read:o,miss:n,prompt:s,pct:t.cacheReported&&s>0?o/s*100:null,reported:t.cacheReported}}function costBreakdown(e,t,o={}){const n=ratesFor(t,o),s=usageBuckets(e),a=(e,t)=>Math.max(0,Number(e)||0)/1e6*t;return{cost:a(s.input,n.input)+a(s.output,n.output)+a(s.cacheRead,n.cacheRead)+a(s.cacheWrite,n.cacheWrite),basis:n.basis,peak:n.peak,model:n.model,priced:n.basis!==RATE_BASIS.DEFAULT}}function usageCost(e,t,o={}){return costBreakdown(e,t,o).cost}function turnAccounting(e,t,o={}){const n=usageTokens(e),s=e&&"object"==typeof e?e:{},a=e&&"object"==typeof e?usageBuckets(e).output:null,u="number"==typeof o.costUsd?o.costUsd:"number"==typeof s.costUsd?s.costUsd:void 0;if("number"==typeof u)return{tokens:n,output:a,cost:u,real:!0,estimated:!1,basis:"settled",priced:!0};if(null==n)return{tokens:n,output:a,cost:null,real:!1,estimated:!1,basis:null,priced:!1};const c=costBreakdown(s,t,o);return{tokens:n,output:a,cost:c.cost,real:!1,estimated:!0,basis:c.basis,priced:c.priced}}function emptyRoll(){return{turns:0,calls:0,tokens:0,input:0,output:0,cacheRead:0,cacheWrite:0,unknown:0,estimated:0,cost:0,estimate:0}}function rollTurn(e,t,o={}){const n=Object.assign(emptyRoll(),e||{});n.turns+=void 0===o.turns?1:Number(o.turns)||0,n.calls+=void 0===o.calls?1:Number(o.calls)||0;const s=turnAccounting(t,o.model,{costUsd:o.costUsd}),a=!0===o.estimated||t&&!1===t.real;if(null==s.tokens){const e=estimatedBuckets(o.prompt,o.reply,o.reasoning),t="number"==typeof o.measuredReasoningTokens&&o.measuredReasoningTokens>0?o.measuredReasoningTokens:0;return e?(n.tokens+=e.input+e.output+t,n.input+=e.input,n.output+=e.output+t,n.estimated+=1,n):t?(n.tokens+=t,n.output+=t,n.estimated+=1,n):(n.unknown+=1,n)}const u=usageBuckets(t);return n.tokens+=s.tokens,n.input+=u.input,n.output+=u.output,n.cacheRead+=u.cacheRead,n.cacheWrite+=u.cacheWrite,a?(n.estimated+=1,n):(s.real?n.cost+=s.cost:null!=s.cost&&(n.estimate+=s.cost),n)}function rollMessages(e){let t=emptyRoll();for(const o of Array.isArray(e)?e:[])o&&"assistant"===o.role&&(t=rollTurn(t,o.tokens,{model:o.model,costUsd:"number"==typeof o.costUsd?o.costUsd:void 0,calls:o.calls}));return t}function ledgerRow(e,t,o={}){const n=t||turnAccounting(e,o.model,{costUsd:o.costUsd}),s=Number.isFinite(o.calls)&&o.calls>0?o.calls:void 0;if(null!=n.tokens){const t={tokens:usageBuckets(e)};return n.real&&null!=n.cost&&(t.costUsd=n.cost),void 0!==s&&(t.calls=s),t}const a=estimatedBuckets(o.prompt,o.reply,o.reasoning);if(!a)return null;const u={tokens:a};return void 0!==s&&(u.calls=s),u}function fmtTokens(e){const t=Number(e);return!Number.isFinite(t)||t<=0?"0":Math.round(t).toString().replace(/\B(?=(\d{3})+(?!\d))/g,",")}function displayTokens(e){if(!e||"object"!=typeof e)return null;const t=e.tokens,o=[e.output];t&&"object"==typeof t?o.push(t.output,t.output_tokens,t.completion_tokens):o.push(e.output_tokens,e.completion_tokens);for(const e of o)if("number"==typeof e&&isFinite(e)&&e>0)return e;return null}function fmtRoll(e,t={}){const o=e||emptyRoll();if(!o.turns&&!o.calls)return"";const n=[],s=displayTokens(o);if(null!=s&&n.push(`${fmtTokens(s)} tokens`),n.push(`${o.calls} call${1===o.calls?"":"s"}`),!t.omitMoney&&(o.cost>0||o.estimate>0)){const e=[];o.cost>0&&e.push(fmtCost(o.cost,!0)),o.estimate>0&&e.push(fmtCost(o.estimate,!1)),n.push(e.join(" + "))}return o.unknown&&n.push(`${o.unknown} unrpt`),o.estimated&&n.push(`${o.estimated} est`),n.join(" · ")}function fmtCost(e,t){return"number"==typeof e&&isFinite(e)?`${t?"":"~"}$${e.toFixed(4)}`:""}function feeWaived(e){if(!e||"object"!=typeof e)return!1;const t=[e.tier,e.plan,e.planRaw,e.subscription,e.subscriptionTier,e.product,e.item,e.sku].filter((e=>"string"==typeof e)).map((e=>e.trim().toLowerCase()));return!0===e.unlimited||!!t.some((e=>"unlimited"===e||"trial"===e))||t.some((e=>/(^|[^a-z])unlimited([^a-z]|$)/.test(e)))}function feeBillable(e){return!e||"object"!=typeof e||!feeWaived(e)&&!0!==e.degraded}"undefined"!=typeof module&&module.exports&&(module.exports={feeWaived:feeWaived,feeBillable:feeBillable,RATES:RATES,RATE_BASIS:RATE_BASIS,UNPRICED_BY_DESIGN:UNPRICED_BY_DESIGN,isPeak:isPeak,usageTokens:usageTokens,ratesFor:ratesFor,usageBuckets:usageBuckets,cacheHitRate:cacheHitRate,usageCost:usageCost,costBreakdown:costBreakdown,turnAccounting:turnAccounting,displayTokens:displayTokens,estimateTokens:estimateTokens,estimatedBuckets:estimatedBuckets,emptyRoll:emptyRoll,rollTurn:rollTurn,rollMessages:rollMessages,ledgerRow:ledgerRow,fmtTokens:fmtTokens,fmtRoll:fmtRoll,fmtCost:fmtCost});
3
+ "use strict";function usageTokens(e){if(!e||"object"!=typeof e)return null;if("number"==typeof e.total_tokens)return e.total_tokens;const t=e.input_tokens??e.prompt_tokens??e.input,o=e.output_tokens??e.completion_tokens??e.output;return"number"!=typeof t&&"number"!=typeof o?null:(t||0)+(o||0)}function estimateTokens(e){return e?Math.max(1,Math.ceil([...String(e)].length/4)):0}function estimatedBuckets(e,t,o){const n=("string"==typeof t?t:"")+("string"==typeof o?o:"");return"string"==typeof e&&e.length>0||n.length>0?{input:estimateTokens(e),output:estimateTokens(n),cacheRead:0,cacheWrite:0,real:!1}:null}const RATES={sonnet:{input:3,output:15,cacheRead:.3,cacheWrite:3.75},default:{input:3,output:15,cacheRead:.3,cacheWrite:3.75},fable:{input:10,output:50,cacheRead:1,cacheWrite:12.5},opus:{input:5,output:25,cacheRead:.5,cacheWrite:6.25},haiku:{input:1,output:5,cacheRead:.1,cacheWrite:1.25},"claude-haiku":{input:1,output:5,cacheRead:.1,cacheWrite:1.25},"claude-opus-5":{input:5,output:25,cacheRead:.5,cacheWrite:6.25},"claude-opus-5-5":{input:4,output:20,cacheRead:.2,cacheWrite:5},"claude-sonnet-5":{input:2,output:10,cacheRead:.2,cacheWrite:2.5},"claude-sonnet-5-5":{input:2,output:10,cacheRead:.1,cacheWrite:2.5},"claude-haiku-5-5":{input:.1,output:.5,cacheRead:.01,cacheWrite:.125},"claude-fable-5":{input:10,output:50,cacheRead:1,cacheWrite:12.5},"claude-fable-5-1":{input:10,output:50,cacheRead:.25,cacheWrite:12.5},"claude-sonnet-4-6":{input:3,output:15,cacheRead:.3,cacheWrite:3.75},"claude-sonnet-4-5":{input:3,output:15,cacheRead:.3,cacheWrite:3.75},deepseek:{input:.3,output:1.2,cacheRead:.006,cacheWrite:.3,offPeak:{input:.15,output:.6,cacheRead:.003,cacheWrite:.15}},"deepseek-v4-pro":{input:1.32,output:3.96,cacheRead:.044,cacheWrite:1.32,offPeak:{input:.66,output:1.98,cacheRead:.022,cacheWrite:.66}},"deepseek-v4.1-pro":{input:1.32,output:3.96,cacheRead:.044,cacheWrite:1.32,offPeak:{input:.66,output:1.98,cacheRead:.022,cacheWrite:.66}},"grok-4.7":{input:2,output:6,cacheRead:.5,cacheWrite:2},"gemini-3.8-flash":{input:.75,output:3.75,cacheRead:.075,cacheWrite:.75},"gpt-5.5":{input:5,output:30,cacheRead:.5,cacheWrite:5}};function isPeak(e,t=new Date){if(0!==String(e||"").toLowerCase().indexOf("deepseek"))return!0;const o=t.getUTCDay();if(0===o||6===o)return!1;const n=t.getUTCHours();return n>=1&&n<4||n>=6&&n<10}const RATE_BASIS=Object.freeze({EXACT:"exact",PREFIX:"prefix",FAMILY:"family",DEFAULT:"default"}),RATE_FAMILIES=Object.keys(RATES).filter(e=>"default"!==e),UNPRICED_BY_DESIGN=Object.freeze({nexus:"auto-routing id: aegis1 picks the tier and settles the charge","nexus-brain":"pooled: multi-call fan-out, aegis1 settles the charge","aegis-brain":"pooled alias of nexus-brain","nexus-brain-smart":"pooled alias of nexus-brain","nexus-brain-neo":"pooled alias of nexus-brain","aegis-brain-smart":"pooled alias of nexus-brain","aegis-brain-neo":"pooled alias of nexus-brain","openai-gpt4o-mini":"pooled seat, aegis1 settles the charge",anthropic:"provider name, not a model id",openai:"provider name, not a model id",groq:"provider name, not a model id",google:"provider name, not a model id",xai:"provider name, not a model id"});function ratesFor(e,{at:t}={}){const o=String(e||"").toLowerCase(),n=(e,n)=>{const s=isPeak(0===o.indexOf("deepseek")||o.indexOf(":deepseek")>-1?"deepseek":o,t||new Date);return{...!s&&e.offPeak?{...e,...e.offPeak}:e,basis:n,peak:s,model:o}};if(!o)return n(RATES.default,RATE_BASIS.DEFAULT);const s=[o],a=Math.max(o.lastIndexOf(":"),o.lastIndexOf("/")),u=o.slice(a+1);u&&u!==o&&s.push(u);for(const e of s)if(RATES[e])return n(RATES[e],RATE_BASIS.EXACT);let c=null,i=0;for(const e of s)for(const[t,o]of Object.entries(RATES))"default"!==t&&e.startsWith(t)&&t.length>i&&(c=o,i=t.length);if(c)return n(c,RATE_BASIS.PREFIX);let r=null,p=0;for(const e of RATE_FAMILIES)o.includes(e)&&e.length>p&&(r=RATES[e],p=e.length);return n(r||RATES.default,r?RATE_BASIS.FAMILY:RATE_BASIS.DEFAULT)}function usageBuckets(e){const t=e&&"object"==typeof e?e:{},o=(...e)=>{for(const t of e)if("number"==typeof t)return t;return 0},n=e=>"number"==typeof e?e:void 0,s=n(t.input_tokens),a=n(t.prompt_tokens),u=t.prompt_tokens_details,c=u&&"object"==typeof u?n(u.cached_tokens):void 0,i=o(t.prompt_cache_hit_tokens,c,t.cached_tokens),r=void 0===s&&void 0!==a,p=r?a:o(s,a,t.input),l=o(t.cache_read_input_tokens,t.cacheRead,i),d=r?Math.min(Math.max(0,p),l):l,f=o(t.cache_creation_input_tokens,t.cacheWrite),m=o(t.output_tokens,t.completion_tokens,t.output),h=r?Math.max(0,p-d):p,k=o(t.total_tokens),R=h+m+d+f;return{input:k>R?h+(k-R):h,output:m,cacheRead:d,cacheWrite:f,cacheReported:"number"==typeof t.cache_read_input_tokens||"number"==typeof t.cacheRead||"number"==typeof t.cache_creation_input_tokens||"number"==typeof t.cacheWrite||"number"==typeof t.prompt_cache_hit_tokens||"number"==typeof t.cached_tokens||"number"==typeof c}}function cacheHitRate(e){const t=usageBuckets(e),o=Math.max(0,t.cacheRead||0),n=Math.max(0,t.input||0),s=o+n;return{read:o,miss:n,prompt:s,pct:t.cacheReported&&s>0?o/s*100:null,reported:t.cacheReported}}function costBreakdown(e,t,o={}){const n=ratesFor(t,o),s=usageBuckets(e),a=(e,t)=>Math.max(0,Number(e)||0)/1e6*t;return{cost:a(s.input,n.input)+a(s.output,n.output)+a(s.cacheRead,n.cacheRead)+a(s.cacheWrite,n.cacheWrite),basis:n.basis,peak:n.peak,model:n.model,priced:n.basis!==RATE_BASIS.DEFAULT}}function usageCost(e,t,o={}){return costBreakdown(e,t,o).cost}function turnAccounting(e,t,o={}){const n=usageTokens(e),s=e&&"object"==typeof e?e:{},a=e&&"object"==typeof e?usageBuckets(e).output:null,u="number"==typeof o.costUsd?o.costUsd:"number"==typeof s.costUsd?s.costUsd:void 0;if("number"==typeof u)return{tokens:n,output:a,cost:u,real:!0,estimated:!1,basis:"settled",priced:!0};if(null==n)return{tokens:n,output:a,cost:null,real:!1,estimated:!1,basis:null,priced:!1};const c=costBreakdown(s,t,o);return{tokens:n,output:a,cost:c.cost,real:!1,estimated:!0,basis:c.basis,priced:c.priced}}function emptyRoll(){return{turns:0,calls:0,tokens:0,input:0,output:0,cacheRead:0,cacheWrite:0,unknown:0,estimated:0,cost:0,estimate:0}}function rollTurn(e,t,o={}){const n=Object.assign(emptyRoll(),e||{});n.turns+=void 0===o.turns?1:Number(o.turns)||0,n.calls+=void 0===o.calls?1:Number(o.calls)||0;const s=turnAccounting(t,o.model,{costUsd:o.costUsd}),a=!0===o.estimated||t&&!1===t.real;if(null==s.tokens){const e=estimatedBuckets(o.prompt,o.reply,o.reasoning),t="number"==typeof o.measuredReasoningTokens&&o.measuredReasoningTokens>0?o.measuredReasoningTokens:0;return e?(n.tokens+=e.input+e.output+t,n.input+=e.input,n.output+=e.output+t,n.estimated+=1,n):t?(n.tokens+=t,n.output+=t,n.estimated+=1,n):(n.unknown+=1,n)}const u=usageBuckets(t);return n.tokens+=s.tokens,n.input+=u.input,n.output+=u.output,n.cacheRead+=u.cacheRead,n.cacheWrite+=u.cacheWrite,a?(n.estimated+=1,n):(s.real?n.cost+=s.cost:null!=s.cost&&(n.estimate+=s.cost),n)}function rollMessages(e){let t=emptyRoll();for(const o of Array.isArray(e)?e:[])o&&"assistant"===o.role&&(t=rollTurn(t,o.tokens,{model:o.model,costUsd:"number"==typeof o.costUsd?o.costUsd:void 0,calls:o.calls}));return t}function ledgerRow(e,t,o={}){const n=t||turnAccounting(e,o.model,{costUsd:o.costUsd}),s=Number.isFinite(o.calls)&&o.calls>0?o.calls:void 0;if(null!=n.tokens){const t={tokens:usageBuckets(e)};return n.real&&null!=n.cost&&(t.costUsd=n.cost),void 0!==s&&(t.calls=s),t}const a=estimatedBuckets(o.prompt,o.reply,o.reasoning);if(!a)return null;const u={tokens:a};return void 0!==s&&(u.calls=s),u}function fmtTokens(e){const t=Number(e);return!Number.isFinite(t)||t<=0?"0":Math.round(t).toString().replace(/\B(?=(\d{3})+(?!\d))/g,",")}function displayTokens(e){if(!e||"object"!=typeof e)return null;const t=e.tokens,o=[e.output];t&&"object"==typeof t?o.push(t.output,t.output_tokens,t.completion_tokens):o.push(e.output_tokens,e.completion_tokens);for(const e of o)if("number"==typeof e&&isFinite(e)&&e>0)return e;return null}function fmtRoll(e,t={}){const o=e||emptyRoll();if(!o.turns&&!o.calls)return"";const n=[],s=displayTokens(o);if(null!=s&&n.push(`${fmtTokens(s)} tokens`),n.push(`${o.calls} call${1===o.calls?"":"s"}`),!t.omitMoney&&(o.cost>0||o.estimate>0)){const e=[];o.cost>0&&e.push(fmtCost(o.cost,!0)),o.estimate>0&&e.push(fmtCost(o.estimate,!1)),n.push(e.join(" + "))}return o.unknown&&n.push(`${o.unknown} unrpt`),o.estimated&&n.push(`${o.estimated} est`),n.join(" · ")}function fmtCost(e,t){return"number"==typeof e&&isFinite(e)?`${t?"":"~"}$${e.toFixed(4)}`:""}function feeWaived(e){if(!e||"object"!=typeof e)return!1;const t=[e.tier,e.plan,e.planRaw,e.subscription,e.subscriptionTier,e.product,e.item,e.sku].filter(e=>"string"==typeof e).map(e=>e.trim().toLowerCase());return!0===e.unlimited||!!t.some(e=>"unlimited"===e||"trial"===e)||t.some(e=>/(^|[^a-z])unlimited([^a-z]|$)/.test(e))}function feeBillable(e){return!e||"object"!=typeof e||!feeWaived(e)&&!0!==e.degraded}"undefined"!=typeof module&&module.exports&&(module.exports={feeWaived:feeWaived,feeBillable:feeBillable,RATES:RATES,RATE_BASIS:RATE_BASIS,UNPRICED_BY_DESIGN:UNPRICED_BY_DESIGN,isPeak:isPeak,usageTokens:usageTokens,ratesFor:ratesFor,usageBuckets:usageBuckets,cacheHitRate:cacheHitRate,usageCost:usageCost,costBreakdown:costBreakdown,turnAccounting:turnAccounting,displayTokens:displayTokens,estimateTokens:estimateTokens,estimatedBuckets:estimatedBuckets,emptyRoll:emptyRoll,rollTurn:rollTurn,rollMessages:rollMessages,ledgerRow:ledgerRow,fmtTokens:fmtTokens,fmtRoll:fmtRoll,fmtCost:fmtCost});
@@ -1 +1 @@
1
- "use strict";const fs=require("node:fs"),path=require("node:path"),{TARGETS:TARGETS,getTarget:getTarget,appConfig:appConfig}=require("./targets.js"),{buildSpec:buildSpec,resolveServer:resolveServer}=require("./spec.js");function hostCtx(e={}){return{env:process.env,platform:process.platform,home:null,cwd:process.cwd(),...e}}function readText(e){try{return{text:fs.readFileSync(e,"utf8"),exists:!0}}catch(e){if("ENOENT"===e.code)return{text:null,exists:!1};throw e}}function isFile(e){try{return fs.statSync(e).isFile()}catch{return!1}}function parseJson(e,t){if(null===e||""===e.trim())return{};try{return JSON.parse(e)}catch(e){throw new Error(`${t} is not valid JSON (${e.message}) — refusing to overwrite it`)}}function setPath(e,t,r){const n=t.split(".");let s=e;for(const e of n.slice(0,-1))(null===s[e]||"object"!=typeof s[e]||Array.isArray(s[e]))&&(s[e]={}),s=s[e];return s[n[n.length-1]]=r,e}function getPath(e,t){let r=e;for(const e of t.split(".")){if(null===r||"object"!=typeof r)return;r=r[e]}return r}function delPath(e,t,r=!1){const n=t.split("."),s=[];let o=e;for(const t of n.slice(0,-1)){if(null===o||"object"!=typeof o)return e;s.push([o,t]),o=o[t]}if(o&&"object"==typeof o&&delete o[n[n.length-1]],!r)return e;for(let e=s.length-1;e>=0;e--){const[t,r]=s[e],n=t[r];if(!n||"object"!=typeof n||0!==Object.keys(n).length)break;delete t[r]}return e}const TOML_BARE=/^[A-Za-z0-9_-]+$/;function tomlKey(e){return TOML_BARE.test(e)?e:JSON.stringify(e)}function tomlString(e){return JSON.stringify(String(e))}function tomlArray(e){return`[${e.map(tomlString).join(", ")}]`}function tomlHeaderName(e){const t=e.trim();return/^\[/.test(t)?t.replace(/^\[+\s*/,"").replace(/\s*\]+$/,""):null}function ownedTomlHeader(e,t){const r=tomlHeaderName(e);return null!==r&&(r===t||r.startsWith(`${t}.`))}function upsertTomlSection(e,t,r){const n=`[${t}]`,s=(e||"").split("\n"),o=[];let i=!1,a=0;for(;a<s.length;)if(s[a].trim()!==n)o.push(s[a]),a++;else{for(o.push(n,...r,""),i=!0,a++;a<s.length&&!/^\s*\[/.test(s[a]);)a++;for(;a<s.length&&ownedTomlHeader(s[a],t);)for(a++;a<s.length&&!/^\s*\[/.test(s[a]);)a++}if(!i){for(;o.length&&""===o[o.length-1].trim();)o.pop();o.length&&o.push(""),o.push(n,...r,"")}return o.join("\n")}function removeTomlSection(e,t){const r=`[${t}]`,n=(e||"").split("\n"),s=[];let o=0;for(;o<n.length;)if(n[o].trim()!==r)s.push(n[o]),o++;else{for(o++;o<n.length&&!/^\s*\[/.test(n[o]);)o++;for(;o<n.length&&ownedTomlHeader(n[o],t);)for(o++;o<n.length&&!/^\s*\[/.test(n[o]);)o++}return s.join("\n")}function renderEntry(e,t){if("mcp-toml"===e.kind){const r=[`# Added by \`aegiscode mcp install ${e.id}\`. Key resolution lives in`,"# ~/.aegiscode/.env and the 0600 store `aegiscode login` writes.","command = "+tomlString(t.command),"args = "+tomlArray(t.args)];if(t.env&&Object.keys(t.env).length){r.push("",`[${e.container}.${t.name}.env]`);for(const[e,n]of Object.entries(t.env))r.push(`${tomlKey(e)} = ${tomlString(n)}`)}return r}return e.entry(t)}function planTarget(e,t,r={}){const n=r.ctx||hostCtx(),s=r.spec||buildSpec(r.specOpts||{}),o=e.path(t,n),i={target:e,scope:t,file:o,exists:!1,changed:!1,before:null,after:null,error:null,backupOf:null};let a,c=null;try{const e=readText(o);c=e.text,i.exists=e.exists}catch(e){return i.error=e,i}if(i.exists)try{i.mode=511&fs.statSync(o).mode}catch{}if("mcp-toml"===e.kind){const t=`${e.container}.${s.name}`,r=renderEntry(e,s);return i.before=c,i.after=upsertTomlSection(c,t,r),i.changed=i.after!==(c||""),i}try{a=parseJson(c,o)}catch(e){return i.error=e,i}if(null===a||"object"!=typeof a||Array.isArray(a))return i.error=new Error(`${o} does not contain a JSON object — refusing to overwrite it`),i;if(setPath(a,`${e.container}.${s.name}`,renderEntry(e,s)),"function"==typeof e.extras){const t=e.extras(s);if(t&&t.inputs){const e=Array.isArray(a.inputs)?a.inputs:[];for(const r of t.inputs){const t=e.findIndex((e=>e&&e.id===r.id));-1===t?e.push(r):e[t]=r}a.inputs=e}}return i.before=c,i.after=JSON.stringify(a,null,2)+"\n",i.changed=i.after!==(c||""),i}function planRemove(e,t,r={}){const n=r.ctx||hostCtx(),s=r.spec||buildSpec(r.specOpts||{}),o=e.path(t,n),i={target:e,scope:t,file:o,exists:!1,changed:!1,before:null,after:null,error:null,backupOf:null};let a,c=null;try{const e=readText(o);c=e.text,i.exists=e.exists}catch(e){return i.error=e,i}if(!i.exists)return i;try{i.mode=511&fs.statSync(o).mode}catch{}if("mcp-toml"===e.kind)return i.before=c,i.after=removeTomlSection(c,`${e.container}.${s.name}`),i.changed=i.after!==c,i;try{a=parseJson(c,o)}catch(e){return i.error=e,i}const l=`${e.container}.${s.name}`,u=void 0!==getPath(a,l),f=Array.isArray(a.inputs)&&a.inputs.some((e=>e&&"aegis-api-key"===e.id));if(!u&&!f)return i.before=c,i.after=c,i.changed=!1,i;delPath(a,l,!0);const p=Array.isArray(a.inputs)?a.inputs.filter((e=>!(e&&"aegis-api-key"===e.id))):null;return p&&(p.length?a.inputs=p:delete a.inputs),i.before=c,i.after=JSON.stringify(a,null,2)+"\n",i.changed=i.after!==c,i}function modeFor(e){return e.withKey?384:e.mode||420}function apply(e,t={}){if(e.error)return{...e,applied:!1};if(!e.changed)return{...e,applied:!1};if(t.dryRun)return{...e,applied:!1,dryRun:!0};if(e.withKey=Boolean(t.withKey),fs.mkdirSync(path.dirname(e.file),{recursive:!0}),e.exists&&null!==e.before){const t=`${e.file}.aegis-backup-${Date.now()}`;fs.writeFileSync(t,e.before,{mode:384}),e.backupOf=t}const r=`${e.file}.aegis-tmp-${process.pid}`;try{fs.writeFileSync(r,e.after,{mode:384}),fs.renameSync(r,e.file),fs.chmodSync(e.file,modeFor(e))}finally{try{fs.unlinkSync(r)}catch{}}return{...e,applied:!0}}function parseTomlEntry(e,t){if(!e)return null;const r=t.replace(/[.[\]*+?^$(){}|]/g,"\\$&"),n=new RegExp("^\\s*\\["+r+"\\]\\s*$","m").exec(e);if(!n)return null;const s=e.slice(n.index+n[0].length).split("\n"),o=[];let i=0;for(;i<s.length&&(!/^\s*\[/.test(s[i])||ownedTomlHeader(s[i],t));)o.push(s[i]),i++;const a={command:null,args:[],env:{}},c=/^\s*command\s*=\s*"((?:[^"\\]|\\.)*)"/m.exec(o.join("\n"));c&&(a.command=JSON.parse('"'+c[1]+'"'));const l=/^\s*args\s*=\s*\[([\s\S]*?)\]/m.exec(o.join("\n"));l&&(a.args=[...l[1].matchAll(/"((?:[^"\\]|\\.)*)"/g)].map((e=>JSON.parse('"'+e[1]+'"'))));for(const e of o.join("\n").matchAll(/^\s*([A-Za-z_][A-Za-z0-9_]*)\s*=\s*"((?:[^"\\]|\\.)*)"\s*$/gm))"command"!==e[1]&&"args"!==e[1]&&(a.env[e[1]]=JSON.parse('"'+e[2]+'"'));return a}function entryServerPath(e){return e&&(Array.isArray(e.args)?e.args:[]).find((e=>"string"==typeof e&&/\.(js|mjs|cjs)$/.test(e)))||null}const HOST_VAR_RE=/\$\{?[A-Za-z_][A-Za-z0-9_]*\}?|%[A-Za-z_][A-Za-z0-9_]*%/;function hasHostVar(e){return"string"==typeof e&&HOST_VAR_RE.test(e)}function status(e,t={}){const r=t.ctx||hostCtx(),n=t.spec||buildSpec(t.specOpts||{}),s=e&&e.length?e.map((e=>getTarget(e))).filter(Boolean):TARGETS,o=[];for(const t of s)for(const s of t.scopes||["user"]){const i=t.path(s,r),a={id:t.id,label:t.label,scope:s,file:i,exists:!1,installed:!1,entry:null,error:null,docs:t.docs,verified:t.verified};let c;try{c=readText(i)}catch(e){a.error=e.message,o.push(a);continue}if(a.exists=c.exists,c.exists&&null!==c.text)if("mcp-toml"===t.kind)a.entry=parseTomlEntry(c.text,`${t.container}.${n.name}`),a.installed=Boolean(a.entry);else try{const e=parseJson(c.text,i);a.entry=getPath(e,`${t.container}.${n.name}`)||null,a.installed=Boolean(a.entry)}catch(e){a.error=e.message}a.installed&&(a.serverPath=entryServerPath(a.entry),a.serverUnverifiable=hasHostVar(a.serverPath),a.serverExists=a.serverPath&&!a.serverUnverifiable?isFile(a.serverPath):null),o.push(a)}return o}function detected(e={}){const t=e.ctx||hostCtx(),r=new Set;for(const e of TARGETS)for(const n of e.scopes||["user"])try{fs.accessSync(e.path(n,t)),r.add(e.id)}catch{}for(const[e,n]of[["Code","vscode"],["Code - Insiders","vscode-insiders"],["VSCodium","vscodium"],["Cursor","cursor"]])try{fs.accessSync(path.join(appConfig(t),e)),r.add(n)}catch{}for(const[e,n]of[[[".codeium"],"windsurf"],[[".gemini"],"gemini"],[[".codex"],"codex"],[[".continue"],"continue"],[[".junie"],"junie"],[[".cursor"],"cursor"]])try{fs.accessSync(path.join(t.home||t.env.HOME||t.env.USERPROFILE,...e)),r.add(n)}catch{}return r}module.exports={hostCtx:hostCtx,planTarget:planTarget,planRemove:planRemove,apply:apply,status:status,detected:detected,renderEntry:renderEntry,entryServerPath:entryServerPath,hasHostVar:hasHostVar,parseTomlEntry:parseTomlEntry,upsertTomlSection:upsertTomlSection,removeTomlSection:removeTomlSection,setPath:setPath,getPath:getPath,delPath:delPath,readText:readText,resolveServer:resolveServer};
1
+ "use strict";const fs=require("node:fs"),path=require("node:path"),{TARGETS:TARGETS,getTarget:getTarget,appConfig:appConfig}=require("./targets.js"),{buildSpec:buildSpec,resolveServer:resolveServer}=require("./spec.js");function hostCtx(e={}){return{env:process.env,platform:process.platform,home:null,cwd:process.cwd(),...e}}function readText(e){try{return{text:fs.readFileSync(e,"utf8"),exists:!0}}catch(e){if("ENOENT"===e.code)return{text:null,exists:!1};throw e}}function isFile(e){try{return fs.statSync(e).isFile()}catch{return!1}}function parseJson(e,t){if(null===e||""===e.trim())return{};try{return JSON.parse(e)}catch(e){throw new Error(`${t} is not valid JSON (${e.message}) — refusing to overwrite it`)}}function setPath(e,t,r){const n=t.split(".");let s=e;for(const e of n.slice(0,-1))(null===s[e]||"object"!=typeof s[e]||Array.isArray(s[e]))&&(s[e]={}),s=s[e];return s[n[n.length-1]]=r,e}function getPath(e,t){let r=e;for(const e of t.split(".")){if(null===r||"object"!=typeof r)return;r=r[e]}return r}function delPath(e,t,r=!1){const n=t.split("."),s=[];let o=e;for(const t of n.slice(0,-1)){if(null===o||"object"!=typeof o)return e;s.push([o,t]),o=o[t]}if(o&&"object"==typeof o&&delete o[n[n.length-1]],!r)return e;for(let e=s.length-1;e>=0;e--){const[t,r]=s[e],n=t[r];if(!n||"object"!=typeof n||0!==Object.keys(n).length)break;delete t[r]}return e}const TOML_BARE=/^[A-Za-z0-9_-]+$/;function tomlKey(e){return TOML_BARE.test(e)?e:JSON.stringify(e)}function tomlString(e){return JSON.stringify(String(e))}function tomlArray(e){return`[${e.map(tomlString).join(", ")}]`}function tomlHeaderName(e){const t=e.trim();return/^\[/.test(t)?t.replace(/^\[+\s*/,"").replace(/\s*\]+$/,""):null}function ownedTomlHeader(e,t){const r=tomlHeaderName(e);return null!==r&&(r===t||r.startsWith(`${t}.`))}function upsertTomlSection(e,t,r){const n=`[${t}]`,s=(e||"").split("\n"),o=[];let i=!1,a=0;for(;a<s.length;)if(s[a].trim()!==n)o.push(s[a]),a++;else{for(o.push(n,...r,""),i=!0,a++;a<s.length&&!/^\s*\[/.test(s[a]);)a++;for(;a<s.length&&ownedTomlHeader(s[a],t);)for(a++;a<s.length&&!/^\s*\[/.test(s[a]);)a++}if(!i){for(;o.length&&""===o[o.length-1].trim();)o.pop();o.length&&o.push(""),o.push(n,...r,"")}return o.join("\n")}function removeTomlSection(e,t){const r=`[${t}]`,n=(e||"").split("\n"),s=[];let o=0;for(;o<n.length;)if(n[o].trim()!==r)s.push(n[o]),o++;else{for(o++;o<n.length&&!/^\s*\[/.test(n[o]);)o++;for(;o<n.length&&ownedTomlHeader(n[o],t);)for(o++;o<n.length&&!/^\s*\[/.test(n[o]);)o++}return s.join("\n")}function renderEntry(e,t){if("mcp-toml"===e.kind){const r=[`# Added by \`aegiscode mcp install ${e.id}\`. Key resolution lives in`,"# ~/.aegiscode/.env and the 0600 store `aegiscode login` writes.","command = "+tomlString(t.command),"args = "+tomlArray(t.args)];if(t.env&&Object.keys(t.env).length){r.push("",`[${e.container}.${t.name}.env]`);for(const[e,n]of Object.entries(t.env))r.push(`${tomlKey(e)} = ${tomlString(n)}`)}return r}return e.entry(t)}function planTarget(e,t,r={}){const n=r.ctx||hostCtx(),s=r.spec||buildSpec(r.specOpts||{}),o=e.path(t,n),i={target:e,scope:t,file:o,exists:!1,changed:!1,before:null,after:null,error:null,backupOf:null};let a,c=null;try{const e=readText(o);c=e.text,i.exists=e.exists}catch(e){return i.error=e,i}if(i.exists)try{i.mode=511&fs.statSync(o).mode}catch{}if("mcp-toml"===e.kind){const t=`${e.container}.${s.name}`,r=renderEntry(e,s);return i.before=c,i.after=upsertTomlSection(c,t,r),i.changed=i.after!==(c||""),i}try{a=parseJson(c,o)}catch(e){return i.error=e,i}if(null===a||"object"!=typeof a||Array.isArray(a))return i.error=new Error(`${o} does not contain a JSON object — refusing to overwrite it`),i;if(setPath(a,`${e.container}.${s.name}`,renderEntry(e,s)),"function"==typeof e.extras){const t=e.extras(s);if(t&&t.inputs){const e=Array.isArray(a.inputs)?a.inputs:[];for(const r of t.inputs){const t=e.findIndex(e=>e&&e.id===r.id);-1===t?e.push(r):e[t]=r}a.inputs=e}}return i.before=c,i.after=JSON.stringify(a,null,2)+"\n",i.changed=i.after!==(c||""),i}function planRemove(e,t,r={}){const n=r.ctx||hostCtx(),s=r.spec||buildSpec(r.specOpts||{}),o=e.path(t,n),i={target:e,scope:t,file:o,exists:!1,changed:!1,before:null,after:null,error:null,backupOf:null};let a,c=null;try{const e=readText(o);c=e.text,i.exists=e.exists}catch(e){return i.error=e,i}if(!i.exists)return i;try{i.mode=511&fs.statSync(o).mode}catch{}if("mcp-toml"===e.kind)return i.before=c,i.after=removeTomlSection(c,`${e.container}.${s.name}`),i.changed=i.after!==c,i;try{a=parseJson(c,o)}catch(e){return i.error=e,i}const l=`${e.container}.${s.name}`,u=void 0!==getPath(a,l),f=Array.isArray(a.inputs)&&a.inputs.some(e=>e&&"aegis-api-key"===e.id);if(!u&&!f)return i.before=c,i.after=c,i.changed=!1,i;delPath(a,l,!0);const p=Array.isArray(a.inputs)?a.inputs.filter(e=>!(e&&"aegis-api-key"===e.id)):null;return p&&(p.length?a.inputs=p:delete a.inputs),i.before=c,i.after=JSON.stringify(a,null,2)+"\n",i.changed=i.after!==c,i}function modeFor(e){return e.withKey?384:e.mode||420}function apply(e,t={}){if(e.error)return{...e,applied:!1};if(!e.changed)return{...e,applied:!1};if(t.dryRun)return{...e,applied:!1,dryRun:!0};if(e.withKey=Boolean(t.withKey),fs.mkdirSync(path.dirname(e.file),{recursive:!0}),e.exists&&null!==e.before){const t=`${e.file}.aegis-backup-${Date.now()}`;fs.writeFileSync(t,e.before,{mode:384}),e.backupOf=t}const r=`${e.file}.aegis-tmp-${process.pid}`;try{fs.writeFileSync(r,e.after,{mode:384}),fs.renameSync(r,e.file),fs.chmodSync(e.file,modeFor(e))}finally{try{fs.unlinkSync(r)}catch{}}return{...e,applied:!0}}function parseTomlEntry(e,t){if(!e)return null;const r=t.replace(/[.[\]*+?^$(){}|]/g,"\\$&"),n=new RegExp("^\\s*\\["+r+"\\]\\s*$","m").exec(e);if(!n)return null;const s=e.slice(n.index+n[0].length).split("\n"),o=[];let i=0;for(;i<s.length&&(!/^\s*\[/.test(s[i])||ownedTomlHeader(s[i],t));)o.push(s[i]),i++;const a={command:null,args:[],env:{}},c=/^\s*command\s*=\s*"((?:[^"\\]|\\.)*)"/m.exec(o.join("\n"));c&&(a.command=JSON.parse('"'+c[1]+'"'));const l=/^\s*args\s*=\s*\[([\s\S]*?)\]/m.exec(o.join("\n"));l&&(a.args=[...l[1].matchAll(/"((?:[^"\\]|\\.)*)"/g)].map(e=>JSON.parse('"'+e[1]+'"')));for(const e of o.join("\n").matchAll(/^\s*([A-Za-z_][A-Za-z0-9_]*)\s*=\s*"((?:[^"\\]|\\.)*)"\s*$/gm))"command"!==e[1]&&"args"!==e[1]&&(a.env[e[1]]=JSON.parse('"'+e[2]+'"'));return a}function entryServerPath(e){return e&&(Array.isArray(e.args)?e.args:[]).find(e=>"string"==typeof e&&/\.(js|mjs|cjs)$/.test(e))||null}const HOST_VAR_RE=/\$\{?[A-Za-z_][A-Za-z0-9_]*\}?|%[A-Za-z_][A-Za-z0-9_]*%/;function hasHostVar(e){return"string"==typeof e&&HOST_VAR_RE.test(e)}function status(e,t={}){const r=t.ctx||hostCtx(),n=t.spec||buildSpec(t.specOpts||{}),s=e&&e.length?e.map(e=>getTarget(e)).filter(Boolean):TARGETS,o=[];for(const t of s)for(const s of t.scopes||["user"]){const i=t.path(s,r),a={id:t.id,label:t.label,scope:s,file:i,exists:!1,installed:!1,entry:null,error:null,docs:t.docs,verified:t.verified};let c;try{c=readText(i)}catch(e){a.error=e.message,o.push(a);continue}if(a.exists=c.exists,c.exists&&null!==c.text)if("mcp-toml"===t.kind)a.entry=parseTomlEntry(c.text,`${t.container}.${n.name}`),a.installed=Boolean(a.entry);else try{const e=parseJson(c.text,i);a.entry=getPath(e,`${t.container}.${n.name}`)||null,a.installed=Boolean(a.entry)}catch(e){a.error=e.message}a.installed&&(a.serverPath=entryServerPath(a.entry),a.serverUnverifiable=hasHostVar(a.serverPath),a.serverExists=a.serverPath&&!a.serverUnverifiable?isFile(a.serverPath):null),o.push(a)}return o}function detected(e={}){const t=e.ctx||hostCtx(),r=new Set;for(const e of TARGETS)for(const n of e.scopes||["user"])try{fs.accessSync(e.path(n,t)),r.add(e.id)}catch{}for(const[e,n]of[["Code","vscode"],["Code - Insiders","vscode-insiders"],["VSCodium","vscodium"],["Cursor","cursor"]])try{fs.accessSync(path.join(appConfig(t),e)),r.add(n)}catch{}for(const[e,n]of[[[".codeium"],"windsurf"],[[".gemini"],"gemini"],[[".codex"],"codex"],[[".continue"],"continue"],[[".junie"],"junie"],[[".cursor"],"cursor"]])try{fs.accessSync(path.join(t.home||t.env.HOME||t.env.USERPROFILE,...e)),r.add(n)}catch{}return r}module.exports={hostCtx:hostCtx,planTarget:planTarget,planRemove:planRemove,apply:apply,status:status,detected:detected,renderEntry:renderEntry,entryServerPath:entryServerPath,hasHostVar:hasHostVar,parseTomlEntry:parseTomlEntry,upsertTomlSection:upsertTomlSection,removeTomlSection:removeTomlSection,setPath:setPath,getPath:getPath,delPath:delPath,readText:readText,resolveServer:resolveServer};
@@ -1,2 +1,2 @@
1
1
  #!/usr/bin/env node
2
- "use strict";const fs=require("node:fs"),path=require("node:path"),http=require("node:http"),{createClient:createClient}=require("../client/aegis.js"),credentials=require("../client/credentials.js");function resolveModelsModule(){const e=[path.join(__dirname,"..","cli","src","models.js"),path.join(__dirname,"..","..","src","models.js")];for(const t of e)if(fs.existsSync(t))return t;throw new Error(`aegis-shim: cannot find models.js. Expected cli/src/models.js beside hosts/ (source checkout) or src/models.js in the package root (installed). Looked in: ${e.join(", ")}`)}const{normalizeModelCatalog:normalizeModelCatalog,pickerEntries:pickerEntries}=require(resolveModelsModule()),DEFAULT_PORT=8787,DEFAULT_HOST="127.0.0.1",LOOPBACK=new Set(["127.0.0.1","::1","localhost"]);function assertBindAllowed(e,t){if(!LOOPBACK.has(e)&&!t)throw new Error(`refusing to bind ${e}: the shim spends your account's tokens, so it is loopback-only unless you pass --allow-remote`)}const EPOCH=1735689600;function logLine(e,t){e.write(`aegis-shim: ${t}\n`)}function extraFromBody(e){const t={};for(const o of["tools","tool_choice","temperature","top_p","stop","presence_penalty","frequency_penalty"])void 0!==e[o]&&(t[o]=e[o]);const o=e.reasoning_effort||e.effort;return"string"==typeof o&&["low","medium","high"].includes(o.toLowerCase())&&(t.effort=o.toLowerCase()),void 0!==e.workers&&(t.workers=e.workers),t}function sseHead(e){e.writeHead(200,{"Content-Type":"text/event-stream; charset=utf-8","Cache-Control":"no-cache, no-transform",Connection:"keep-alive","X-Accel-Buffering":"no"})}function sseSend(e,t){e.write(`data: ${JSON.stringify(t)}\n\n`)}function chunkFrame(e,t,o,n){return{id:e,object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:t||"aegis",choices:[{index:0,delta:o,finish_reason:n||null}]}}function createShimServer(e={}){const t=e.client||createClient(credentials.clientOptions()),o=e.host||DEFAULT_HOST,n=void 0===e.port?DEFAULT_PORT:e.port,s=e.log||process.stderr,r=!1!==e.requireKey,a=e.fetchModels||(()=>t.listModels());assertBindAllowed(o,e.allowRemote);let i={at:0,models:[]};function c(e,t,o){const n=JSON.stringify(o);e.writeHead(t,{"Content-Type":"application/json; charset=utf-8","Content-Length":Buffer.byteLength(n)}),e.end(n)}function l(e,t,o,n){c(e,t,{error:{message:o,type:n||"aegis_error",code:t}})}function d(e){if(!r)return!0;const t=e.headers.authorization||"",o=/^Bearer\s+(.+)$/i.exec(t);return Boolean(o&&o[1].trim())}const m=http.createServer(((e,s)=>{const r=new URL(e.url||"/",`http://${e.headers.host||"127.0.0.1"}`).pathname.replace(/\/+$/,"")||"/";return"GET"!==e.method||"/health"!==r&&"/"!==r?"GET"!==e.method||"/v1/models"!==r&&"/models"!==r?"POST"!==e.method||"/v1/chat/completions"!==r&&"/chat/completions"!==r?"POST"===e.method&&"/v1/messages"===r?l(s,404,"this endpoint speaks the OpenAI schema; point the client at /v1 with the OpenAI provider","invalid_request_error"):l(s,404,`no such route: ${e.method} ${r}`,"invalid_request_error"):d(e)?async function(e,o){let n;try{n=await async function(e){const t=[];let o=0;for await(const n of e){if(o+=n.length,o>8388608)throw new Error("request body too large");t.push(n)}const n=Buffer.concat(t).toString("utf8");return n.trim()?JSON.parse(n):{}}(e)}catch(e){return l(o,400,`invalid JSON body: ${e.message}`,"invalid_request_error")}const s=Array.isArray(n.messages)?n.messages:null;if(!s||!s.length)return l(o,400,"`messages` is required","invalid_request_error");const r=!0===n.stream,a=`chatcmpl-aegis-${Date.now().toString(36)}`,i=n.model&&"aegis-default"!==n.model?String(n.model):void 0,d={messages:s,model:i,maxTokens:n.max_tokens||n.max_completion_tokens,extra:extraFromBody(n),includeUsage:r};if(!r)try{const e=await t.chatCompletion({...d,stream:!1}),n=e.choices&&e.choices[0]&&e.choices[0].message||{content:""};return c(o,200,{id:a,object:"chat.completion",created:Math.floor(Date.now()/1e3),model:e.model||i||"aegis",choices:[{index:0,message:{role:"assistant",...n},finish_reason:n.tool_calls?"tool_calls":"stop"}],usage:e.usage||void 0})}catch(e){return l(o,e.status&&e.status>=400&&e.status<600?e.status:502,e.message)}sseHead(o);let m=!1;e.on("close",(()=>{m=!0}));const u=e=>{m||sseSend(o,e)};u(chunkFrame(a,i,{role:"assistant",content:""}));try{const e=await t.chatCompletion({...d,stream:!0,onStream:e=>{e.delta?u(chunkFrame(a,i,{content:e.delta})):e.reasoning&&u(chunkFrame(a,i,{reasoning_content:e.reasoning}))},onReasoning:e=>u(chunkFrame(a,i,{reasoning_content:e}))}),n=e.choices&&e.choices[0]&&e.choices[0].message||{};Array.isArray(n.tool_calls)&&n.tool_calls.length&&u(chunkFrame(a,i,{tool_calls:n.tool_calls.map(((e,t)=>({index:t,id:e.id,type:"function",function:{name:e.function&&e.function.name,arguments:e.function&&e.function.arguments||""}})))})),u(chunkFrame(a,i,{},n.tool_calls&&n.tool_calls.length?"tool_calls":"stop")),e.usage&&u({id:a,object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:e.model||i||"aegis",choices:[],usage:e.usage}),m||(o.write("data: [DONE]\n\n"),o.end())}catch(e){u({error:{message:e.message,type:"aegis_error"}}),m||(o.write("data: [DONE]\n\n"),o.end())}}(e,s):l(s,401,"missing API key — any non-empty value works locally","invalid_request_error"):d(e)?async function(e){c(e,200,{object:"list",data:(await async function(){if(Date.now()-i.at<6e4&&i.models.length)return i.models;const e=await a();return i={at:Date.now(),models:pickerEntries(normalizeModelCatalog(e&&e.models?e.models:e))},i.models}()).map((e=>({id:e.id,object:"model",created:EPOCH,owned_by:"aegis",...e.label&&e.label!==e.id?{name:e.label}:{}})))})}(s).catch((e=>l(s,502,e.message))):l(s,401,"missing API key — any non-empty value works locally","invalid_request_error"):c(s,200,{ok:!0,service:"aegis-openai-shim",endpoint:`http://${o}:${n}/v1`})}));var u;return m.listen=(u=m.listen,function(...e){return u.apply(m,e)}),{server:m,host:o,port:n,url:`http://${o}:${n}/v1`,listen:()=>new Promise(((e,t)=>{m.once("error",t),m.listen(n,o,(()=>{const t=m.address();logLine(s,`OpenAI-compatible endpoint on http://${o}:${t.port}/v1`),logLine(s,"point any OpenAI-compatible client at that base URL (any API key value)"),e(t)}))})),close:()=>new Promise((e=>m.close(e)))}}function parseArgv(e){const t={log:process.stderr};for(let o=0;o<e.length;o++){const n=e[o];"--port"===n?t.port=Number(e[++o]):"--host"===n?t.host=e[++o]:"--allow-remote"===n?t.allowRemote=!0:"--no-auth"===n?t.requireKey=!1:"--help"!==n&&"-h"!==n||(t.help=!0)}return t}async function main(e){const t=parseArgv(e);if(t.help)return process.stdout.write(["aegis openai shim — serve AEGIS as an OpenAI-compatible endpoint",""," node hosts/openai-shim.js [--port 8787] [--host 127.0.0.1] [--allow-remote] [--no-auth]","","Then point a coding tool at it:"," base URL http://127.0.0.1:8787/v1"," API key anything non-empty (the AEGIS key is read from ~/.aegiscode/.env)",""].join("\n")),0;const o=t.log||process.stderr;try{assertBindAllowed(t.host||DEFAULT_HOST,t.allowRemote)}catch(e){return logLine(o,e.message),1}try{const e=require("../client/env-file.js").loadEnvFile();e.loose&&logLine(o,`${e.file} is readable by other accounts (mode ${e.mode.toString(8)}) — consider \`chmod 600\` on it`)}catch(e){logLine(o,`could not read the shared env file: ${e&&e.message}`)}const n=credentials.resolveApiKey();if(!n.key)return logLine(o,`no AEGIS account key — ${credentials.HOW_TO_SET}, or set ${credentials.KEY_ENV} in ~/.aegiscode/.env`),1;let s;logLine(o,`AEGIS key: ${credentials.sourceLabel(n.source)}`);try{s=createShimServer(t),await s.listen()}catch(e){return logLine(process.stderr,e.message),1}const r=async()=>{await s.close(),process.exit(0)};return process.on("SIGINT",r),process.on("SIGTERM",r),null}require.main===module&&main(process.argv.slice(2)).then((e=>{"number"==typeof e&&process.exit(e)})).catch((e=>{logLine(process.stderr,e&&e.message?e.message:e),process.exit(1)})),module.exports={createShimServer:createShimServer,extraFromBody:extraFromBody,DEFAULT_PORT:DEFAULT_PORT};
2
+ "use strict";const fs=require("node:fs"),path=require("node:path"),http=require("node:http"),{createClient:createClient}=require("../client/aegis.js"),credentials=require("../client/credentials.js");function resolveModelsModule(){const e=[path.join(__dirname,"..","cli","src","models.js"),path.join(__dirname,"..","..","src","models.js")];for(const t of e)if(fs.existsSync(t))return t;throw new Error(`aegis-shim: cannot find models.js. Expected cli/src/models.js beside hosts/ (source checkout) or src/models.js in the package root (installed). Looked in: ${e.join(", ")}`)}const{normalizeModelCatalog:normalizeModelCatalog,pickerEntries:pickerEntries}=require(resolveModelsModule()),DEFAULT_PORT=8787,DEFAULT_HOST="127.0.0.1",LOOPBACK=new Set(["127.0.0.1","::1","localhost"]);function assertBindAllowed(e,t){if(!LOOPBACK.has(e)&&!t)throw new Error(`refusing to bind ${e}: the shim spends your account's tokens, so it is loopback-only unless you pass --allow-remote`)}const EPOCH=1735689600;function logLine(e,t){e.write(`aegis-shim: ${t}\n`)}function extraFromBody(e){const t={};for(const o of["tools","tool_choice","temperature","top_p","stop","presence_penalty","frequency_penalty"])void 0!==e[o]&&(t[o]=e[o]);const o=e.reasoning_effort||e.effort;return"string"==typeof o&&["low","medium","high"].includes(o.toLowerCase())&&(t.effort=o.toLowerCase()),void 0!==e.workers&&(t.workers=e.workers),t}function sseHead(e){e.writeHead(200,{"Content-Type":"text/event-stream; charset=utf-8","Cache-Control":"no-cache, no-transform",Connection:"keep-alive","X-Accel-Buffering":"no"})}function sseSend(e,t){e.write(`data: ${JSON.stringify(t)}\n\n`)}function chunkFrame(e,t,o,n){return{id:e,object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:t||"aegis",choices:[{index:0,delta:o,finish_reason:n||null}]}}function createShimServer(e={}){const t=e.client||createClient(credentials.clientOptions()),o=e.host||"127.0.0.1",n=void 0===e.port?8787:e.port,s=e.log||process.stderr,r=!1!==e.requireKey,a=e.fetchModels||(()=>t.listModels());assertBindAllowed(o,e.allowRemote);let i={at:0,models:[]};function c(e,t,o){const n=JSON.stringify(o);e.writeHead(t,{"Content-Type":"application/json; charset=utf-8","Content-Length":Buffer.byteLength(n)}),e.end(n)}function l(e,t,o,n){c(e,t,{error:{message:o,type:n||"aegis_error",code:t}})}function d(e){if(!r)return!0;const t=e.headers.authorization||"",o=/^Bearer\s+(.+)$/i.exec(t);return Boolean(o&&o[1].trim())}const m=http.createServer((e,s)=>{const r=new URL(e.url||"/",`http://${e.headers.host||"127.0.0.1"}`).pathname.replace(/\/+$/,"")||"/";return"GET"!==e.method||"/health"!==r&&"/"!==r?"GET"!==e.method||"/v1/models"!==r&&"/models"!==r?"POST"!==e.method||"/v1/chat/completions"!==r&&"/chat/completions"!==r?"POST"===e.method&&"/v1/messages"===r?l(s,404,"this endpoint speaks the OpenAI schema; point the client at /v1 with the OpenAI provider","invalid_request_error"):l(s,404,`no such route: ${e.method} ${r}`,"invalid_request_error"):d(e)?async function(e,o){let n;try{n=await async function(e){const t=[];let o=0;for await(const n of e){if(o+=n.length,o>8388608)throw new Error("request body too large");t.push(n)}const n=Buffer.concat(t).toString("utf8");return n.trim()?JSON.parse(n):{}}(e)}catch(e){return l(o,400,`invalid JSON body: ${e.message}`,"invalid_request_error")}const s=Array.isArray(n.messages)?n.messages:null;if(!s||!s.length)return l(o,400,"`messages` is required","invalid_request_error");const r=!0===n.stream,a=`chatcmpl-aegis-${Date.now().toString(36)}`,i=n.model&&"aegis-default"!==n.model?String(n.model):void 0,d={messages:s,model:i,maxTokens:n.max_tokens||n.max_completion_tokens,extra:extraFromBody(n),includeUsage:r};if(!r)try{const e=await t.chatCompletion({...d,stream:!1}),n=e.choices&&e.choices[0]&&e.choices[0].message||{content:""};return c(o,200,{id:a,object:"chat.completion",created:Math.floor(Date.now()/1e3),model:e.model||i||"aegis",choices:[{index:0,message:{role:"assistant",...n},finish_reason:n.tool_calls?"tool_calls":"stop"}],usage:e.usage||void 0})}catch(e){return l(o,e.status&&e.status>=400&&e.status<600?e.status:502,e.message)}sseHead(o);let m=!1;e.on("close",()=>{m=!0});const u=e=>{m||sseSend(o,e)};u(chunkFrame(a,i,{role:"assistant",content:""}));try{const e=await t.chatCompletion({...d,stream:!0,onStream:e=>{e.delta?u(chunkFrame(a,i,{content:e.delta})):e.reasoning&&u(chunkFrame(a,i,{reasoning_content:e.reasoning}))},onReasoning:e=>u(chunkFrame(a,i,{reasoning_content:e}))}),n=e.choices&&e.choices[0]&&e.choices[0].message||{};Array.isArray(n.tool_calls)&&n.tool_calls.length&&u(chunkFrame(a,i,{tool_calls:n.tool_calls.map((e,t)=>({index:t,id:e.id,type:"function",function:{name:e.function&&e.function.name,arguments:e.function&&e.function.arguments||""}}))})),u(chunkFrame(a,i,{},n.tool_calls&&n.tool_calls.length?"tool_calls":"stop")),e.usage&&u({id:a,object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:e.model||i||"aegis",choices:[],usage:e.usage}),m||(o.write("data: [DONE]\n\n"),o.end())}catch(e){u({error:{message:e.message,type:"aegis_error"}}),m||(o.write("data: [DONE]\n\n"),o.end())}}(e,s):l(s,401,"missing API key — any non-empty value works locally","invalid_request_error"):d(e)?async function(e){c(e,200,{object:"list",data:(await async function(){if(Date.now()-i.at<6e4&&i.models.length)return i.models;const e=await a();return i={at:Date.now(),models:pickerEntries(normalizeModelCatalog(e&&e.models?e.models:e))},i.models}()).map(e=>({id:e.id,object:"model",created:EPOCH,owned_by:"aegis",...e.label&&e.label!==e.id?{name:e.label}:{}}))})}(s).catch(e=>l(s,502,e.message)):l(s,401,"missing API key — any non-empty value works locally","invalid_request_error"):c(s,200,{ok:!0,service:"aegis-openai-shim",endpoint:`http://${o}:${n}/v1`})});var u;return m.listen=(u=m.listen,function(...e){return u.apply(m,e)}),{server:m,host:o,port:n,url:`http://${o}:${n}/v1`,listen:()=>new Promise((e,t)=>{m.once("error",t),m.listen(n,o,()=>{const t=m.address();logLine(s,`OpenAI-compatible endpoint on http://${o}:${t.port}/v1`),logLine(s,"point any OpenAI-compatible client at that base URL (any API key value)"),e(t)})}),close:()=>new Promise(e=>m.close(e))}}function parseArgv(e){const t={log:process.stderr};for(let o=0;o<e.length;o++){const n=e[o];"--port"===n?t.port=Number(e[++o]):"--host"===n?t.host=e[++o]:"--allow-remote"===n?t.allowRemote=!0:"--no-auth"===n?t.requireKey=!1:"--help"!==n&&"-h"!==n||(t.help=!0)}return t}async function main(e){const t=parseArgv(e);if(t.help)return process.stdout.write(["aegis openai shim — serve AEGIS as an OpenAI-compatible endpoint",""," node hosts/openai-shim.js [--port 8787] [--host 127.0.0.1] [--allow-remote] [--no-auth]","","Then point a coding tool at it:"," base URL http://127.0.0.1:8787/v1"," API key anything non-empty (the AEGIS key is read from ~/.aegiscode/.env)",""].join("\n")),0;const o=t.log||process.stderr;try{assertBindAllowed(t.host||"127.0.0.1",t.allowRemote)}catch(e){return logLine(o,e.message),1}try{const e=require("../client/env-file.js").loadEnvFile();e.loose&&logLine(o,`${e.file} is readable by other accounts (mode ${e.mode.toString(8)}) — consider \`chmod 600\` on it`)}catch(e){logLine(o,`could not read the shared env file: ${e&&e.message}`)}const n=credentials.resolveApiKey();if(!n.key)return logLine(o,`no AEGIS account key — ${credentials.HOW_TO_SET}, or set ${credentials.KEY_ENV} in ~/.aegiscode/.env`),1;let s;logLine(o,`AEGIS key: ${credentials.sourceLabel(n.source)}`);try{s=createShimServer(t),await s.listen()}catch(e){return logLine(process.stderr,e.message),1}const r=async()=>{await s.close(),process.exit(0)};return process.on("SIGINT",r),process.on("SIGTERM",r),null}require.main===module&&main(process.argv.slice(2)).then(e=>{"number"==typeof e&&process.exit(e)}).catch(e=>{logLine(process.stderr,e&&e.message?e.message:e),process.exit(1)}),module.exports={createShimServer:createShimServer,extraFromBody:extraFromBody,DEFAULT_PORT:8787};
@@ -1 +1 @@
1
- "use strict";const fs=require("node:fs"),path=require("node:path"),SERVER_NAME="aegis",DEFAULT_API_BASE="https://aegiscloud.org";function serverCandidates(e=process.env){const s=[],r=e=>{if(!e)return;const r=path.resolve(e);s.includes(r)||s.push(r)};r(e.AEGIS_MCP_SERVER),r(path.resolve(__dirname,"..","mcp","server.js")),r(path.resolve(__dirname,"..","cli","vendor","mcp","server.js")),r(path.resolve(__dirname,"..","vendor","mcp","server.js")),r(path.resolve(__dirname,"..","..","mcp","server.js"));for(const s of globalRoots(e))r(path.join(s,"aegiscode","vendor","mcp","server.js"));return s}function globalRoots(e=process.env){const s=[];e.npm_config_prefix&&s.push(path.join(e.npm_config_prefix,"lib","node_modules")),s.push("/usr/local/lib/node_modules","/usr/lib/node_modules");const r=process.execPath||"";return r.includes(`${path.sep}bin${path.sep}`)&&s.push(path.resolve(r,"..","..","lib","node_modules")),s}function resolveServer(e=process.env){const s=serverCandidates(e),r=s.find((e=>{try{return fs.statSync(e).isFile()}catch{return!1}}));return{path:r||s[0],exists:Boolean(r),candidates:s}}function resolveApiBase(e=process.env,s){return s||e.AEGIS_API_BASE||DEFAULT_API_BASE}function buildSpec(e={}){const s=e.env||process.env,r=resolveServer(s),o=e.serverPath||r.path,n=resolveApiBase(s,e.apiBase),t={};return e.promptKey?t.AEGIS_API_KEY="${input:aegis-api-key}":e.apiKey&&(t.AEGIS_API_KEY=e.apiKey),t.AEGIS_API_BASE=n,{name:"aegis",command:"node",args:[o],env:t,keyRef:e.promptKey?"${input:aegis-api-key}":e.apiKey||null,server:r}}function vscodeKeyInput(){return{type:"promptString",id:"aegis-api-key",description:"AEGIS API key (aegiscloud.org → Account → API keys)",password:!0}}module.exports={SERVER_NAME:"aegis",DEFAULT_API_BASE:DEFAULT_API_BASE,buildSpec:buildSpec,resolveServer:resolveServer,serverCandidates:serverCandidates,resolveApiBase:resolveApiBase,vscodeKeyInput:vscodeKeyInput};
1
+ "use strict";const fs=require("node:fs"),path=require("node:path"),SERVER_NAME="aegis",DEFAULT_API_BASE="https://aegiscloud.org";function serverCandidates(e=process.env){const s=[],r=e=>{if(!e)return;const r=path.resolve(e);s.includes(r)||s.push(r)};r(e.AEGIS_MCP_SERVER),r(path.resolve(__dirname,"..","mcp","server.js")),r(path.resolve(__dirname,"..","cli","vendor","mcp","server.js")),r(path.resolve(__dirname,"..","vendor","mcp","server.js")),r(path.resolve(__dirname,"..","..","mcp","server.js"));for(const s of globalRoots(e))r(path.join(s,"aegiscode","vendor","mcp","server.js"));return s}function globalRoots(e=process.env){const s=[];e.npm_config_prefix&&s.push(path.join(e.npm_config_prefix,"lib","node_modules")),s.push("/usr/local/lib/node_modules","/usr/lib/node_modules");const r=process.execPath||"";return r.includes(`${path.sep}bin${path.sep}`)&&s.push(path.resolve(r,"..","..","lib","node_modules")),s}function resolveServer(e=process.env){const s=serverCandidates(e),r=s.find(e=>{try{return fs.statSync(e).isFile()}catch{return!1}});return{path:r||s[0],exists:Boolean(r),candidates:s}}function resolveApiBase(e=process.env,s){return s||e.AEGIS_API_BASE||DEFAULT_API_BASE}function buildSpec(e={}){const s=e.env||process.env,r=resolveServer(s),o=e.serverPath||r.path,n=resolveApiBase(s,e.apiBase),t={};return e.promptKey?t.AEGIS_API_KEY="${input:aegis-api-key}":e.apiKey&&(t.AEGIS_API_KEY=e.apiKey),t.AEGIS_API_BASE=n,{name:"aegis",command:"node",args:[o],env:t,keyRef:e.promptKey?"${input:aegis-api-key}":e.apiKey||null,server:r}}function vscodeKeyInput(){return{type:"promptString",id:"aegis-api-key",description:"AEGIS API key (aegiscloud.org → Account → API keys)",password:!0}}module.exports={SERVER_NAME:"aegis",DEFAULT_API_BASE:DEFAULT_API_BASE,buildSpec:buildSpec,resolveServer:resolveServer,serverCandidates:serverCandidates,resolveApiBase:resolveApiBase,vscodeKeyInput:vscodeKeyInput};
@@ -1 +1 @@
1
- "use strict";const os=require("node:os"),path=require("node:path"),{SERVER_NAME:SERVER_NAME,vscodeKeyInput:vscodeKeyInput}=require("./spec.js");function home(e){return e.home||e.env.HOME||e.env.USERPROFILE||os.homedir()}function appConfig(e){const{env:o,platform:n}=e;return o.XDG_CONFIG_HOME?o.XDG_CONFIG_HOME:"win32"===n?o.APPDATA||path.join(home(e),"AppData","Roaming"):"darwin"===n?path.join(home(e),"Library","Application Support"):path.join(home(e),".config")}function zedConfig(e){const{env:o,platform:n}=e;return"win32"===n?path.join(o.APPDATA||path.join(home(e),"AppData","Roaming"),"Zed"):path.join(o.XDG_CONFIG_HOME||path.join(home(e),".config"),"zed")}function dot(e,...o){return path.join(home(e),...o)}function vscodeUserFile(e,o){return path.join(appConfig(e),o,"User","mcp.json")}function orEnv(e){return e.env&&Object.keys(e.env).length?e.env:null}function plainEntry(e){const o=orEnv(e),n={command:e.command,args:e.args};return o&&(n.env=o),n}const TARGETS=[{id:"vscode",label:"VS Code",kind:"mcp-json",container:"servers",scopes:["user","workspace"],docs:"https://code.visualstudio.com/docs/copilot/customization/mcp-servers",verified:!0,supportsKeyPrompt:!0,note:"Copilot agent mode reads `.vscode/mcp.json` for the workspace, or the user file for every project.",path:(e,o)=>"workspace"===e?path.join(o.cwd,".vscode","mcp.json"):vscodeUserFile(o,"Code"),entry(e){const o={type:"stdio",command:e.command,args:e.args},n=orEnv(e);return n&&(o.env=n),o},extras:e=>e.keyRef&&e.keyRef.startsWith("${input:")?{inputs:[vscodeKeyInput()]}:null},{id:"vscode-insiders",label:"VS Code Insiders",kind:"mcp-json",container:"servers",scopes:["user"],docs:"https://code.visualstudio.com/docs/copilot/customization/mcp-servers",verified:!0,supportsKeyPrompt:!0,path:(e,o)=>vscodeUserFile(o,"Code - Insiders"),entry:e=>TARGETS[0].entry(e),extras:e=>TARGETS[0].extras(e)},{id:"vscodium",label:"VSCodium",kind:"mcp-json",container:"servers",scopes:["user","workspace"],docs:"https://code.visualstudio.com/docs/copilot/customization/mcp-servers",verified:!0,supportsKeyPrompt:!0,path:(e,o)=>"workspace"===e?path.join(o.cwd,".vscode","mcp.json"):vscodeUserFile(o,"VSCodium"),entry:e=>TARGETS[0].entry(e),extras:e=>TARGETS[0].extras(e)},{id:"cursor",label:"Cursor",kind:"mcp-json",container:"mcpServers",scopes:["user","workspace"],docs:"https://cursor.com/docs/context/mcp",verified:!0,path:(e,o)=>"workspace"===e?path.join(o.cwd,".cursor","mcp.json"):path.join(appConfig(o),"Cursor","mcp.json"),entry:plainEntry},{id:"windsurf",label:"Windsurf",kind:"mcp-json",container:"mcpServers",scopes:["user"],docs:"https://docs.windsurf.com/windsurf/cascade/mcp",verified:!0,path:(e,o)=>dot(o,".codeium","windsurf","mcp_config.json"),entry:plainEntry},{id:"cline",label:"Cline (VS Code extension)",kind:"mcp-json",container:"mcpServers",scopes:["user"],docs:"https://docs.cline.bot/mcp/configuring-mcp-servers",verified:!0,path:(e,o)=>path.join(appConfig(o),"Code","User","globalStorage","saoudrizwan.claude-dev","settings","cline_mcp_settings.json"),entry:e=>({...plainEntry(e),disabled:!1,autoApprove:[],type:"stdio"})},{id:"roo",label:"Roo Code (VS Code extension)",kind:"mcp-json",container:"mcpServers",scopes:["user"],docs:"https://docs.roocode.com/features/mcp/using-mcp-in-roo",verified:!0,path:(e,o)=>path.join(appConfig(o),"Code","User","globalStorage","rooveterinaryinc.roo-cline","settings","mcp_settings.json"),entry:e=>({...plainEntry(e),disabled:!1,alwaysAllow:[],type:"stdio"})},{id:"zed",label:"Zed",kind:"mcp-json",container:"context_servers",scopes:["user"],docs:"https://zed.dev/docs/ai/mcp",verified:!0,path:(e,o)=>path.join(zedConfig(o),"settings.json"),entry(e){const o={path:e.command,args:e.args},n=orEnv(e);return n&&(o.env=n),{source:"custom",command:o}}},{id:"continue",label:"Continue (VS Code / JetBrains)",kind:"mcp-json",container:"mcpServers",scopes:["user"],docs:"https://docs.continue.dev/customize/deep-dives/mcp",verified:!0,path:(e,o)=>dot(o,".continue","config.json"),entry:plainEntry,yamlWins:!0},{id:"claude",label:"Claude Code (project scope)",kind:"mcp-json",container:"mcpServers",scopes:["workspace"],docs:"https://docs.claude.com/en/docs/claude-code/mcp",verified:!0,path:(e,o)=>path.join(o.cwd,".mcp.json"),entry:plainEntry},{id:"gemini",label:"Gemini CLI",kind:"mcp-json",container:"mcpServers",scopes:["user"],docs:"https://github.com/google-gemini/gemini-cli/blob/main/docs/tools/mcp-server.md",verified:!0,path:(e,o)=>dot(o,".gemini","settings.json"),entry:plainEntry},{id:"codex",label:"Codex CLI",kind:"mcp-toml",container:"mcp_servers",scopes:["user"],docs:"https://github.com/openai/codex/blob/main/docs/config.md",verified:!0,path:(e,o)=>dot(o,".codex","config.toml")},{id:"junie",label:"JetBrains Junie / AI Assistant",kind:"mcp-json",container:"mcpServers",scopes:["user","workspace"],docs:"https://www.jetbrains.com/help/junie/mcp.html",verified:!1,note:"JetBrains reads this file but the IDE also caches MCP config in Settings — restart the IDE and confirm the server is listed there.",path:(e,o)=>"workspace"===e?path.join(o.cwd,".junie","mcp","mcp.json"):dot(o,".junie","mcp","mcp.json"),entry:plainEntry},{id:"opencode",label:"OpenCode",kind:"mcp-json",container:"mcp",scopes:["user"],docs:"https://opencode.ai/docs/mcp-servers/",verified:!1,note:"OpenCode takes a single command array instead of command + args.",path:(e,o)=>path.join(appConfig(o),"opencode","opencode.json"),entry(e){const o=orEnv(e),n={type:"local",command:[e.command,...e.args],enabled:!0};return o&&(n.environment=o),n}}],BY_ID=new Map(TARGETS.map((e=>[e.id,e]))),ALIASES={code:"vscode","vs-code":"vscode","vscode-code":"vscode",windsurfcodeium:"windsurf","roo-code":"roo",roocode:"roo",jetbrains:"junie","claude-code":"claude",gemini_cli:"gemini","codex-cli":"codex",vsc:"vscodium"};function getTarget(e){if(!e)return null;const o=String(e).toLowerCase().trim();return BY_ID.get(o)||BY_ID.get(ALIASES[o])||null}function targetIds(){return TARGETS.map((e=>e.id))}const VSCODE_VARIANTS=["Code","Code - Insiders","VSCodium"];module.exports={TARGETS:TARGETS,ALIASES:ALIASES,VSCODE_VARIANTS:VSCODE_VARIANTS,getTarget:getTarget,targetIds:targetIds,SERVER_NAME:SERVER_NAME,appConfig:appConfig,zedConfig:zedConfig,home:home};
1
+ "use strict";const os=require("node:os"),path=require("node:path"),{SERVER_NAME:SERVER_NAME,vscodeKeyInput:vscodeKeyInput}=require("./spec.js");function home(e){return e.home||e.env.HOME||e.env.USERPROFILE||os.homedir()}function appConfig(e){const{env:o,platform:n}=e;return o.XDG_CONFIG_HOME?o.XDG_CONFIG_HOME:"win32"===n?o.APPDATA||path.join(home(e),"AppData","Roaming"):"darwin"===n?path.join(home(e),"Library","Application Support"):path.join(home(e),".config")}function zedConfig(e){const{env:o,platform:n}=e;return"win32"===n?path.join(o.APPDATA||path.join(home(e),"AppData","Roaming"),"Zed"):path.join(o.XDG_CONFIG_HOME||path.join(home(e),".config"),"zed")}function dot(e,...o){return path.join(home(e),...o)}function vscodeUserFile(e,o){return path.join(appConfig(e),o,"User","mcp.json")}function orEnv(e){return e.env&&Object.keys(e.env).length?e.env:null}function plainEntry(e){const o=orEnv(e),n={command:e.command,args:e.args};return o&&(n.env=o),n}const TARGETS=[{id:"vscode",label:"VS Code",kind:"mcp-json",container:"servers",scopes:["user","workspace"],docs:"https://code.visualstudio.com/docs/copilot/customization/mcp-servers",verified:!0,supportsKeyPrompt:!0,note:"Copilot agent mode reads `.vscode/mcp.json` for the workspace, or the user file for every project.",path:(e,o)=>"workspace"===e?path.join(o.cwd,".vscode","mcp.json"):vscodeUserFile(o,"Code"),entry(e){const o={type:"stdio",command:e.command,args:e.args},n=orEnv(e);return n&&(o.env=n),o},extras:e=>e.keyRef&&e.keyRef.startsWith("${input:")?{inputs:[vscodeKeyInput()]}:null},{id:"vscode-insiders",label:"VS Code Insiders",kind:"mcp-json",container:"servers",scopes:["user"],docs:"https://code.visualstudio.com/docs/copilot/customization/mcp-servers",verified:!0,supportsKeyPrompt:!0,path:(e,o)=>vscodeUserFile(o,"Code - Insiders"),entry:e=>TARGETS[0].entry(e),extras:e=>TARGETS[0].extras(e)},{id:"vscodium",label:"VSCodium",kind:"mcp-json",container:"servers",scopes:["user","workspace"],docs:"https://code.visualstudio.com/docs/copilot/customization/mcp-servers",verified:!0,supportsKeyPrompt:!0,path:(e,o)=>"workspace"===e?path.join(o.cwd,".vscode","mcp.json"):vscodeUserFile(o,"VSCodium"),entry:e=>TARGETS[0].entry(e),extras:e=>TARGETS[0].extras(e)},{id:"cursor",label:"Cursor",kind:"mcp-json",container:"mcpServers",scopes:["user","workspace"],docs:"https://cursor.com/docs/context/mcp",verified:!0,path:(e,o)=>"workspace"===e?path.join(o.cwd,".cursor","mcp.json"):path.join(appConfig(o),"Cursor","mcp.json"),entry:plainEntry},{id:"windsurf",label:"Windsurf",kind:"mcp-json",container:"mcpServers",scopes:["user"],docs:"https://docs.windsurf.com/windsurf/cascade/mcp",verified:!0,path:(e,o)=>dot(o,".codeium","windsurf","mcp_config.json"),entry:plainEntry},{id:"cline",label:"Cline (VS Code extension)",kind:"mcp-json",container:"mcpServers",scopes:["user"],docs:"https://docs.cline.bot/mcp/configuring-mcp-servers",verified:!0,path:(e,o)=>path.join(appConfig(o),"Code","User","globalStorage","saoudrizwan.claude-dev","settings","cline_mcp_settings.json"),entry:e=>({...plainEntry(e),disabled:!1,autoApprove:[],type:"stdio"})},{id:"roo",label:"Roo Code (VS Code extension)",kind:"mcp-json",container:"mcpServers",scopes:["user"],docs:"https://docs.roocode.com/features/mcp/using-mcp-in-roo",verified:!0,path:(e,o)=>path.join(appConfig(o),"Code","User","globalStorage","rooveterinaryinc.roo-cline","settings","mcp_settings.json"),entry:e=>({...plainEntry(e),disabled:!1,alwaysAllow:[],type:"stdio"})},{id:"zed",label:"Zed",kind:"mcp-json",container:"context_servers",scopes:["user"],docs:"https://zed.dev/docs/ai/mcp",verified:!0,path:(e,o)=>path.join(zedConfig(o),"settings.json"),entry(e){const o={path:e.command,args:e.args},n=orEnv(e);return n&&(o.env=n),{source:"custom",command:o}}},{id:"continue",label:"Continue (VS Code / JetBrains)",kind:"mcp-json",container:"mcpServers",scopes:["user"],docs:"https://docs.continue.dev/customize/deep-dives/mcp",verified:!0,path:(e,o)=>dot(o,".continue","config.json"),entry:plainEntry,yamlWins:!0},{id:"claude",label:"Claude Code (project scope)",kind:"mcp-json",container:"mcpServers",scopes:["workspace"],docs:"https://docs.claude.com/en/docs/claude-code/mcp",verified:!0,path:(e,o)=>path.join(o.cwd,".mcp.json"),entry:plainEntry},{id:"gemini",label:"Gemini CLI",kind:"mcp-json",container:"mcpServers",scopes:["user"],docs:"https://github.com/google-gemini/gemini-cli/blob/main/docs/tools/mcp-server.md",verified:!0,path:(e,o)=>dot(o,".gemini","settings.json"),entry:plainEntry},{id:"codex",label:"Codex CLI",kind:"mcp-toml",container:"mcp_servers",scopes:["user"],docs:"https://github.com/openai/codex/blob/main/docs/config.md",verified:!0,path:(e,o)=>dot(o,".codex","config.toml")},{id:"junie",label:"JetBrains Junie / AI Assistant",kind:"mcp-json",container:"mcpServers",scopes:["user","workspace"],docs:"https://www.jetbrains.com/help/junie/mcp.html",verified:!1,note:"JetBrains reads this file but the IDE also caches MCP config in Settings — restart the IDE and confirm the server is listed there.",path:(e,o)=>"workspace"===e?path.join(o.cwd,".junie","mcp","mcp.json"):dot(o,".junie","mcp","mcp.json"),entry:plainEntry},{id:"opencode",label:"OpenCode",kind:"mcp-json",container:"mcp",scopes:["user"],docs:"https://opencode.ai/docs/mcp-servers/",verified:!1,note:"OpenCode takes a single command array instead of command + args.",path:(e,o)=>path.join(appConfig(o),"opencode","opencode.json"),entry(e){const o=orEnv(e),n={type:"local",command:[e.command,...e.args],enabled:!0};return o&&(n.environment=o),n}}],BY_ID=new Map(TARGETS.map(e=>[e.id,e])),ALIASES={code:"vscode","vs-code":"vscode","vscode-code":"vscode",windsurfcodeium:"windsurf","roo-code":"roo",roocode:"roo",jetbrains:"junie","claude-code":"claude",gemini_cli:"gemini","codex-cli":"codex",vsc:"vscodium"};function getTarget(e){if(!e)return null;const o=String(e).toLowerCase().trim();return BY_ID.get(o)||BY_ID.get(ALIASES[o])||null}function targetIds(){return TARGETS.map(e=>e.id)}const VSCODE_VARIANTS=["Code","Code - Insiders","VSCodium"];module.exports={TARGETS:TARGETS,ALIASES:ALIASES,VSCODE_VARIANTS:VSCODE_VARIANTS,getTarget:getTarget,targetIds:targetIds,SERVER_NAME:SERVER_NAME,appConfig:appConfig,zedConfig:zedConfig,home:home};
@@ -1,3 +1,3 @@
1
1
  // SPDX-License-Identifier: AGPL-3.0-or-later
2
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");function dataDir(e={}){if(e.dir)return e.dir;const r=e.env||process.env;if(r.AEGISCODE_HOME)return r.AEGISCODE_HOME;const n=e.home||(()=>{try{return os.homedir()}catch{return r.HOME||r.USERPROFILE||""}})();return path.join(n,".aegiscode")}function registryPath(e={}){return path.join(dataDir(e),"harnesses.json")}function harnessName(e){const r=e&&(e.name||e.title);return String(null==r?"":r).trim().toLowerCase().replace(/\s+/g,"-").replace(/_/g,"-").replace(/[^a-z0-9.-]/g,"").replace(/-+/g,"-").replace(/^-+|-+$/g,"")||"unknown"}function deniedHarnesses(e={}){const r=e.env||process.env;return String(r.AEGISCODE_HARNESS_DENY||"").split(/[\s,]+/).map((e=>e.trim().toLowerCase())).filter(Boolean)}function admit(e,r={}){const n=harnessName(e),s=deniedHarnesses(r);return s.includes(n)||s.includes("*")?{ok:!1,name:n,reason:`AEGIS: harness "${n}" is denied by AEGISCODE_HARNESS_DENY. Unset that variable (or remove this name from it) to admit it.`}:{ok:!0,name:n,reason:""}}function read(e={}){const r=registryPath(e);try{const e=JSON.parse(fs.readFileSync(r,"utf8"));return e&&"object"==typeof e&&e&&"object"==typeof e.harnesses&&e.harnesses?e.harnesses:{}}catch{return{}}}function record(e,r={}){const n=harnessName(e),s=(new Date).toISOString();try{const t=read(r),a=t[n]||{},i=e&&e.version?String(e.version):a.version||null;t[n]={firstSeen:a.firstSeen||s,lastSeen:s,calls:(Number(a.calls)||0)+1,version:i};const o=registryPath(r);fs.mkdirSync(path.dirname(o),{recursive:!0,mode:448});const c=`${o}.${process.pid}.tmp`;return fs.writeFileSync(c,JSON.stringify({harnesses:t},null,2),{mode:384}),fs.renameSync(c,o),{ok:!0,name:n}}catch{return{ok:!1,name:n}}}module.exports={dataDir:dataDir,registryPath:registryPath,harnessName:harnessName,deniedHarnesses:deniedHarnesses,admit:admit,read:read,record:record};
3
+ "use strict";const fs=require("node:fs"),os=require("node:os"),path=require("node:path");function dataDir(e={}){if(e.dir)return e.dir;const r=e.env||process.env;if(r.AEGISCODE_HOME)return r.AEGISCODE_HOME;const n=e.home||(()=>{try{return os.homedir()}catch{return r.HOME||r.USERPROFILE||""}})();return path.join(n,".aegiscode")}function registryPath(e={}){return path.join(dataDir(e),"harnesses.json")}function harnessName(e){const r=e&&(e.name||e.title);return String(null==r?"":r).trim().toLowerCase().replace(/\s+/g,"-").replace(/_/g,"-").replace(/[^a-z0-9.-]/g,"").replace(/-+/g,"-").replace(/^-+|-+$/g,"")||"unknown"}function deniedHarnesses(e={}){const r=e.env||process.env;return String(r.AEGISCODE_HARNESS_DENY||"").split(/[\s,]+/).map(e=>e.trim().toLowerCase()).filter(Boolean)}function admit(e,r={}){const n=harnessName(e),s=deniedHarnesses(r);return s.includes(n)||s.includes("*")?{ok:!1,name:n,reason:`AEGIS: harness "${n}" is denied by AEGISCODE_HARNESS_DENY. Unset that variable (or remove this name from it) to admit it.`}:{ok:!0,name:n,reason:""}}function read(e={}){const r=registryPath(e);try{const e=JSON.parse(fs.readFileSync(r,"utf8"));return e&&"object"==typeof e&&e&&"object"==typeof e.harnesses&&e.harnesses?e.harnesses:{}}catch{return{}}}function record(e,r={}){const n=harnessName(e),s=(new Date).toISOString();try{const t=read(r),a=t[n]||{},i=e&&e.version?String(e.version):a.version||null;t[n]={firstSeen:a.firstSeen||s,lastSeen:s,calls:(Number(a.calls)||0)+1,version:i};const o=registryPath(r);fs.mkdirSync(path.dirname(o),{recursive:!0,mode:448});const c=`${o}.${process.pid}.tmp`;return fs.writeFileSync(c,JSON.stringify({harnesses:t},null,2),{mode:384}),fs.renameSync(c,o),{ok:!0,name:n}}catch{return{ok:!1,name:n}}}module.exports={dataDir:dataDir,registryPath:registryPath,harnessName:harnessName,deniedHarnesses:deniedHarnesses,admit:admit,read:read,record:record};
@@ -1,4 +1,4 @@
1
1
  #!/usr/bin/env node
2
2
  // SPDX-License-Identifier: AGPL-3.0-or-later
3
3
  // Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
4
- "use strict";const{createClient:createClient}=require("../client/aegis.js"),credentials=require("../client/credentials.js"),{autoProvisionApiKey:autoProvisionApiKey}=require("../client/auto-provision.js"),{createTools:createTools}=require("./tools.js"),admission=require("./admission.js");try{const e=require("../client/env-file.js").loadEnvFile();e.loose&&process.stderr.write(`aegis: ${e.file} is readable by other accounts (mode ${e.mode.toString(8)}) — consider \`chmod 600\` on it.\n`)}catch{}const aegis=createClient(credentials.clientOptions()),{TOOLS:TOOLS,toolList:toolList}=createTools(aegis),API_BASE=aegis.apiBase,SERVER_NAME="aegis",SERVER_VERSION="0.4.0";function missingKeyText(){const{path:e}=credentials.keyStatus();return["No AEGIS API key is configured for this session.","","Set one with any of:"," • `aegiscode login` in a terminal (saves it to "+e+", mode 0600)"," • export AEGIS_API_KEY=… in the environment Claude Code was launched from"," • put `AEGIS_API_KEY=…` in ~/.aegiscode/.env (read at startup, every host)","","Then restart Claude Code. Get a key at https://aegiscloud.org."].join("\n")}let provisionAttempted=!1;async function ensureApiKey(){if(aegis.apiKey||provisionAttempted)return;provisionAttempted=!0;const e=await autoProvisionApiKey(aegis,credentials,{app:"mcp"});e.error?process.stderr.write(`aegis: device auto-registration failed (${e.error.message}) — falling back to manual setup.\n`):e.key?process.stderr.write("aegis: no API key was configured — auto-provisioned a free AEGIS account"+(e.ok?` (key saved to ${credentials.keyStatus().path}).\n`:" (could not save it — see above).\n")+`Fund it at ${aegis.promptUrl("topup","device_autoprovision")} or set your own BYOK key with aegis_byok_set.\n`):process.stderr.write("aegis: device auto-registration returned no usable key — falling back to manual setup.\n")}function send(e){process.stdout.write(JSON.stringify(e)+"\n")}function reply(e,t){send({jsonrpc:"2.0",id:e,result:t})}function replyError(e,t,i){send({jsonrpc:"2.0",id:e,error:{code:t,message:i}})}let caller={ok:!0,name:"unknown",reason:""},pending=0,stdinClosed=!1;function maybeExit(){stdinClosed&&0===pending&&process.exit(0)}async function handleMessage(e){const{id:t,method:i,params:r}=e,o=null==t;try{switch(i){case"initialize":{const e=r&&r.clientInfo||null;return caller=admission.admit(e),caller.ok?admission.record(e):process.stderr.write(`${caller.reason}\n`),void reply(t,{protocolVersion:r&&r.protocolVersion||"2024-11-05",capabilities:{tools:{}},serverInfo:{name:"aegis",version:"0.4.0"}})}case"notifications/initialized":case"notifications/cancelled":return;case"ping":return void(o||reply(t,{}));case"tools/list":return void reply(t,{tools:toolList()});case"tools/call":{if(!caller.ok)return void reply(t,{content:[{type:"text",text:caller.reason}],isError:!0});const i=r&&r.name,o=TOOLS[i];if(!o)return void reply(t,{content:[{type:"text",text:`Unknown tool: ${i}`}],isError:!0});if(aegis.apiKey||await ensureApiKey(),!aegis.apiKey)return void reply(t,{content:[{type:"text",text:missingKeyText()}],isError:!0});try{reply(t,{content:[{type:"text",text:await o.run(r&&r.arguments||{})}],isError:!1})}catch(e){reply(t,{content:[{type:"text",text:`AEGIS error: ${e.message}`}],isError:!0})}return}default:return void(o||replyError(t,-32601,`Method not found: ${i}`))}}catch(e){o||replyError(t,-32603,e.message)}}const MAX_LINE_BYTES=33554432;function overflowNote(){process.stderr.write("aegis: discarded a JSON-RPC message over 33554432 bytes.\n")}let buffer="",discarding=!1;process.stdin.setEncoding("utf8"),process.stdin.on("data",(e=>{if(discarding){const t=e.indexOf("\n");if(-1===t)return;discarding=!1,e=e.slice(t+1)}let t;for(buffer+=e;-1!==(t=buffer.indexOf("\n"));){const e=buffer.slice(0,t).trim();if(buffer=buffer.slice(t+1),!e)continue;if(e.length>33554432){overflowNote();continue}let i;try{i=JSON.parse(e)}catch{continue}pending++,Promise.resolve(handleMessage(i)).finally((()=>{pending--,maybeExit()}))}buffer.length>33554432&&(buffer="",discarding=!0,overflowNote())})),process.stdin.on("end",(()=>{stdinClosed=!0,maybeExit()}));
4
+ "use strict";const{createClient:createClient}=require("../client/aegis.js"),credentials=require("../client/credentials.js"),{autoProvisionApiKey:autoProvisionApiKey}=require("../client/auto-provision.js"),{createTools:createTools}=require("./tools.js"),admission=require("./admission.js");try{const e=require("../client/env-file.js").loadEnvFile();e.loose&&process.stderr.write(`aegis: ${e.file} is readable by other accounts (mode ${e.mode.toString(8)}) — consider \`chmod 600\` on it.\n`)}catch{}const aegis=createClient(credentials.clientOptions()),{TOOLS:TOOLS,toolList:toolList}=createTools(aegis),API_BASE=aegis.apiBase,SERVER_NAME="aegis",SERVER_VERSION="0.4.0";function missingKeyText(){const{path:e}=credentials.keyStatus();return["No AEGIS API key is configured for this session.","","Set one with any of:"," • `aegiscode login` in a terminal (saves it to "+e+", mode 0600)"," • export AEGIS_API_KEY=… in the environment Claude Code was launched from"," • put `AEGIS_API_KEY=…` in ~/.aegiscode/.env (read at startup, every host)","","Then restart Claude Code. Get a key at https://aegiscloud.org."].join("\n")}let provisionAttempted=!1;async function ensureApiKey(){if(aegis.apiKey||provisionAttempted)return;provisionAttempted=!0;const e=await autoProvisionApiKey(aegis,credentials,{app:"mcp"});e.error?process.stderr.write(`aegis: device auto-registration failed (${e.error.message}) — falling back to manual setup.\n`):e.key?process.stderr.write("aegis: no API key was configured — auto-provisioned a free AEGIS account"+(e.ok?` (key saved to ${credentials.keyStatus().path}).\n`:" (could not save it — see above).\n")+`Fund it at ${aegis.promptUrl("topup","device_autoprovision")} or set your own BYOK key with aegis_byok_set.\n`):process.stderr.write("aegis: device auto-registration returned no usable key — falling back to manual setup.\n")}function send(e){process.stdout.write(JSON.stringify(e)+"\n")}function reply(e,t){send({jsonrpc:"2.0",id:e,result:t})}function replyError(e,t,i){send({jsonrpc:"2.0",id:e,error:{code:t,message:i}})}let caller={ok:!0,name:"unknown",reason:""},pending=0,stdinClosed=!1;function maybeExit(){stdinClosed&&0===pending&&process.exit(0)}async function handleMessage(e){const{id:t,method:i,params:r}=e,o=null==t;try{switch(i){case"initialize":{const e=r&&r.clientInfo||null;return caller=admission.admit(e),caller.ok?admission.record(e):process.stderr.write(`${caller.reason}\n`),void reply(t,{protocolVersion:r&&r.protocolVersion||"2024-11-05",capabilities:{tools:{}},serverInfo:{name:"aegis",version:"0.4.0"}})}case"notifications/initialized":case"notifications/cancelled":return;case"ping":return void(o||reply(t,{}));case"tools/list":return void reply(t,{tools:toolList()});case"tools/call":{if(!caller.ok)return void reply(t,{content:[{type:"text",text:caller.reason}],isError:!0});const i=r&&r.name,o=TOOLS[i];if(!o)return void reply(t,{content:[{type:"text",text:`Unknown tool: ${i}`}],isError:!0});if(aegis.apiKey||await ensureApiKey(),!aegis.apiKey)return void reply(t,{content:[{type:"text",text:missingKeyText()}],isError:!0});try{reply(t,{content:[{type:"text",text:await o.run(r&&r.arguments||{})}],isError:!1})}catch(e){reply(t,{content:[{type:"text",text:`AEGIS error: ${e.message}`}],isError:!0})}return}default:return void(o||replyError(t,-32601,`Method not found: ${i}`))}}catch(e){o||replyError(t,-32603,e.message)}}const MAX_LINE_BYTES=33554432;function overflowNote(){process.stderr.write("aegis: discarded a JSON-RPC message over 33554432 bytes.\n")}let buffer="",discarding=!1;process.stdin.setEncoding("utf8"),process.stdin.on("data",e=>{if(discarding){const t=e.indexOf("\n");if(-1===t)return;discarding=!1,e=e.slice(t+1)}let t;for(buffer+=e;-1!==(t=buffer.indexOf("\n"));){const e=buffer.slice(0,t).trim();if(buffer=buffer.slice(t+1),!e)continue;if(e.length>33554432){overflowNote();continue}let i;try{i=JSON.parse(e)}catch{continue}pending++,Promise.resolve(handleMessage(i)).finally(()=>{pending--,maybeExit()})}buffer.length>33554432&&(buffer="",discarding=!0,overflowNote())}),process.stdin.on("end",()=>{stdinClosed=!0,maybeExit()});
@@ -1,3 +1,3 @@
1
1
  // SPDX-License-Identifier: AGPL-3.0-or-later
2
2
  // Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
3
- "use strict";const foreignMemory=require("../client/foreign-memory.js");function createTools(e){if(!e||"object"!=typeof e)throw new TypeError("createTools(client): a client instance is required");const t=e,o={aegis_status:{description:"Check the current AEGIS account: validates the API key and reports the plan, email, and whether cloud memory is enabled. Call this first to confirm setup.",inputSchema:{type:"object",properties:{},additionalProperties:!1},async run(){const e=await t.verifyApiKey();return["Key valid: "+(e.valid?"yes":"no"),`Plan: ${e.plan||"unknown"}`,e.email?`Account: ${e.email}`:null,"Memory: "+(e.memory_token?"enabled (cloud sync available)":"not enabled"),`API base: ${t.apiBase}`].filter(Boolean).join("\n")}},aegis_ask:{description:"Send a prompt to AEGIS pooled inference, billed against the account's token bank. List models with aegis_list_models and pass any id as `model`; omit `model` to let the server pick its default. `mode` is a legacy server-side shorthand and is never required.",inputSchema:{type:"object",properties:{prompt:{type:"string",description:"The user prompt / question."},model:{type:"string",description:"Pin any model id from aegis_list_models — or omit for the server default."},mode:{type:"string",description:"Legacy server-side shorthand (e.g. 'fast', 'smart', 'neo'). Optional — never defaulted client-side."},system:{type:"string",description:"Optional system instruction."},max_tokens:{type:"integer",description:"Max output tokens. The server enforces the true ceiling; omit for the server default.",minimum:1,maximum:64e3}},required:["prompt"],additionalProperties:!1},async run(e){const o=await t.chatCompletion({prompt:e.prompt,system:e.system,model:e.model,mode:e.mode,maxTokens:e.max_tokens}),s=o.choices&&o.choices[0]||{};return`${s.message&&s.message.content||"(empty response)"}\n\n— ${[o.model?`model: ${o.model}`:null,o.usage?`tokens: ${o.usage.total_tokens}`:null].filter(Boolean).join(" · ")}`}},aegis_list_models:{description:"List the exact models available to pin with aegis_ask's `model` argument — the server's model list is the truth, and omitting `model` uses the server default.",inputSchema:{type:"object",properties:{},additionalProperties:!1},async run(){const e=(await t.listModels()).models||[];return e.length?["Pass one of these as aegis_ask's `model` argument:","",...e.map((e=>` ${e.id} (${(e.capabilities||[]).join(", ")})`))].join("\n"):"No pinnable models are currently configured on AEGIS."}},aegis_balance:{description:"Check the AEGIS token bank balance and recent spend. Call this before aegis_ask if you're unsure whether the account has funds, or to see what recent calls cost.",inputSchema:{type:"object",properties:{},additionalProperties:!1},async run(){const e=await t.tokenBankBalance(),o=[`Balance: €${Number(e.balance_eur||0).toFixed(2)}`],s=(e.ledger||[]).slice(0,5);if(s.length){o.push("","Recent activity:");for(const e of s){const t=null!=e.amount_eur?Number(e.amount_eur):-Number(e.charged_micros||0)/1e6,s=Math.abs(t),r=`${t<0?"-":"+"}€${s<.01?s.toFixed(4):s.toFixed(2)}`,i="topup"===e.kind?"top-up":e.kind||"",n=e.model_key||i||"",a=e.tokens_in||e.tokens_out?` ${e.tokens_in||0}/${e.tokens_out||0} tokens`:"";o.push(` ${e.created_at||""} ${n}${a} ${r}`)}}else o.push("No spend yet.");var r;return(e.balance_eur||0)<=0&&o.push("",`Balance is empty — top up at ${r="topup","function"==typeof t.promptUrl?t.promptUrl(r,"topup_bank"):`https://aegiscloud.org/go/${r}`}, or set your own provider key with aegis_byok_set to use aegis_ask for free at cost.`),o.join("\n")}},aegis_byok_providers:{description:"List every provider that accepts a Bring-Your-Own-Key on AEGIS: the exact provider id to pass to aegis_byok_set, the models each one unlocks, where to create the key, and the prefix a valid key starts with. Call this before aegis_byok_set so the user knows which key to go get rather than guessing a provider id.",inputSchema:{type:"object",properties:{},additionalProperties:!1},async run(){const e=(await t.byokProviders()).providers||[];if(!e.length)return"AEGIS is not advertising any BYOK providers right now.";const o=["Set one with aegis_byok_set — pass the id exactly as shown:"];for(const t of e){const e=(t.models||[]).map((e=>"string"==typeof e?e:e&&e.id)).filter(Boolean),s=t.configured?" ✓ set"+(t.masked?` (${t.masked})`:""):"";o.push(""),o.push(` ${t.id}${s}`),t.label&&o.push(` ${t.label}`),e.length&&o.push(` models: ${e.join(", ")}`),t.key_prefix&&o.push(` key starts with: ${t.key_prefix}`),t.key_url&&o.push(` get a key: ${t.key_url}`)}return o.join("\n")}},aegis_byok_status:{description:"List which providers have a Bring-Your-Own-Key configured on this AEGIS account (known ids: openai, anthropic, groq, openrouter, together, deepseek, gemini, …). A configured BYOK key is used automatically by aegis_ask instead of the pooled balance for that provider, so calls no longer cost AEGIS token-bank funds.",inputSchema:{type:"object",properties:{},additionalProperties:!1},async run(){const e=await t.byokStatus(),o=Object.entries(e||{});if(!o.length)return"No BYOK providers are configured. Run aegis_byok_providers to see what you can set.";let s={};try{const e=await t.byokProviders();for(const t of e.providers||[])s[t.id]=t.label||""}catch{}return`BYOK keys:\n${o.map((([e,t])=>{const o=t&&t.set;return` ${e}${s[e]?` ${s[e]}`:""}: ${o?`set (${t.masked})`:"not set"}`})).join("\n")}`}},aegis_byok_set:{description:"Set or remove a Bring-Your-Own-Key API key for a provider on this AEGIS account (known ids: openai, anthropic, groq, openrouter, together, deepseek, gemini, …; the server validates what it supports). Once set, aegis_ask uses that key directly for that provider instead of the pooled AEGIS balance — unlimited use at the user's own cost. Omit api_key to remove a previously set key.",inputSchema:{type:"object",properties:{provider:{type:"string",description:"Which provider this key is for (known ids: openai, anthropic, groq, openrouter, together, deepseek, gemini, …)."},api_key:{type:"string",description:"The provider's own API key. Omit to delete the stored key instead."}},required:["provider"],additionalProperties:!1},run:async e=>(await t.byokSet(e.provider,e.api_key)).message||(e.api_key?`${e.provider} key saved.`:`${e.provider} key removed.`)},aegis_memory_search:{description:"Search the user's AEGIS cloud memory (persists across machines and sessions). Returns the most relevant stored entries for a query.",inputSchema:{type:"object",properties:{query:{type:"string",description:"Search text. Empty returns most recent."},limit:{type:"integer",description:"Max entries (1-50). Default 5.",minimum:1,maximum:50}},required:["query"],additionalProperties:!1},async run(e){const o=(await t.memorySearch(e.query,e.limit||5)).entries||[];return o.length?o.map(((e,t)=>{const o=e.timestamp||e.createdAt||"",s=e.tags&&e.tags.length?` [${e.tags.join(", ")}]`:"";return`${t+1}. ${e.content}${s}${o?`\n (${o})`:""}`})).join("\n"):`No memory entries matched "${e.query}".`}},aegis_memory_save:{description:"Save a note to the user's AEGIS cloud memory so it persists across machines and future sessions. Use for durable facts, decisions, or preferences the user asks you to remember.",inputSchema:{type:"object",properties:{content:{type:"string",description:"The fact/note to store."},tags:{type:"array",items:{type:"string"},description:"Optional tags."},importance:{type:"integer",description:"Optional 1-10 salience. Default 5.",minimum:1,maximum:10},session:{type:"string",description:"Optional session/label to group under."}},required:["content"],additionalProperties:!1},async run(e){const o={id:t.randomUUID(),content:e.content,role:"assistant",source:"claude-code",session:e.session||"claude-code",tags:e.tags||[],importance:"number"==typeof e.importance?e.importance:5,timestamp:(new Date).toISOString()};return`Saved ${(await t.memorySave(o)).saved||1} memory entry (id ${o.id}).`}},aegis_memory_import:{description:"Import memory and past conversation context from OTHER AI coding tools installed on this machine (Claude Code, Codex, Cursor, Gemini CLI, Continue, Goose, opencode, Windsurf, Zed, and a local AEGIS engine) into the user's AEGIS cloud memory. Scans read-only; nothing in the other tools' directories is modified. Defaults to a DRY RUN that only reports what it found — pass confirm:true to actually save. Entries are content-addressed, so re-running never duplicates.",inputSchema:{type:"object",properties:{confirm:{type:"boolean",description:"false (default) = report only. true = actually write the entries to AEGIS memory."},sources:{type:"array",items:{type:"string"},description:'Optional subset of source ids to import (e.g. ["claude-code"]). Omit for every source found on this machine.'},limit:{type:"integer",description:"Max entries to import (1-5000). Default 1000.",minimum:1,maximum:5e3}},additionalProperties:!1},async run(e){const o=e.limit||1e3,s=foreignMemory.scan({sources:e.sources,limit:o}),r=foreignMemory.describe(s);if(!s.entries.length)return`${r}\n\nNothing to import.`;if(!e.confirm)return[r,"",`Dry run — ${s.totals.entries} entries would be saved to AEGIS memory under ${s.totals.sourcesWithEntries} session(s) (${s.totals.skipped} skipped as too short/noise).`,"Call this tool again with confirm:true to save them."].join("\n");let i=0;const n=[];for(const o of foreignMemory.chunk(s.entries,200))try{const e=await t.memorySaveBatch(o);i+=e&&e.saved||o.length}catch(e){n.push(e.message);break}return n.length?`${r}\n\nSaved ${i} of ${s.totals.entries} entries, then stopped: ${n[0]}`:`${r}\n\nSaved ${i} entries to AEGIS memory. They are searchable now with aegis_memory_search.`}},aegis_memory_list:{description:"List the most recent entries in the user's AEGIS cloud memory. Useful to review what AEGIS already remembers.",inputSchema:{type:"object",properties:{limit:{type:"integer",description:"Max entries (1-50). Default 10.",minimum:1,maximum:50}},additionalProperties:!1},async run(e){const o=(await t.memoryList(e.limit||10)).entries||[];if(!o.length)return"AEGIS cloud memory is empty.";const s=o.map(((e,t)=>`${t+1}. ${e.content}`)).join("\n");return`Recent ${o.length} entries:\n${s}`}}};return{TOOLS:o,toolList:function(){return Object.entries(o).map((([e,t])=>({name:e,description:t.description,inputSchema:t.inputSchema})))}}}module.exports={createTools:createTools};
3
+ "use strict";const foreignMemory=require("../client/foreign-memory.js");function createTools(e,t={}){if(!e||"object"!=typeof e)throw new TypeError("createTools(client): a client instance is required");const o=t&&"object"==typeof t.localWiki?t.localWiki:null,i=e,s={aegis_status:{description:"Check the current AEGIS account: validates the API key and reports the plan, email, and whether cloud memory is enabled. Call this first to confirm setup.",inputSchema:{type:"object",properties:{},additionalProperties:!1},async run(){const e=await i.verifyApiKey();return["Key valid: "+(e.valid?"yes":"no"),`Plan: ${e.plan||"unknown"}`,e.email?`Account: ${e.email}`:null,"Memory: "+(e.memory_token?"enabled (cloud sync available)":"not enabled"),`API base: ${i.apiBase}`].filter(Boolean).join("\n")}},aegis_ask:{description:"Send a prompt to AEGIS pooled inference, billed against the account's token bank. List models with aegis_list_models and pass any id as `model`; omit `model` to let the server pick its default. `mode` is a legacy server-side shorthand and is never required.",inputSchema:{type:"object",properties:{prompt:{type:"string",description:"The user prompt / question."},model:{type:"string",description:"Pin any model id from aegis_list_models — or omit for the server default."},mode:{type:"string",description:"Legacy server-side shorthand (e.g. 'fast', 'smart', 'neo'). Optional — never defaulted client-side."},system:{type:"string",description:"Optional system instruction."},max_tokens:{type:"integer",description:"Max output tokens. The server enforces the true ceiling; omit for the server default.",minimum:1,maximum:64e3}},required:["prompt"],additionalProperties:!1},async run(e){const t=await i.chatCompletion({prompt:e.prompt,system:e.system,model:e.model,mode:e.mode,maxTokens:e.max_tokens}),o=t.choices&&t.choices[0]||{};return`${o.message&&o.message.content||"(empty response)"}\n\n— ${[t.model?`model: ${t.model}`:null,t.usage?`tokens: ${t.usage.total_tokens}`:null].filter(Boolean).join(" · ")}`}},aegis_list_models:{description:"List the exact models available to pin with aegis_ask's `model` argument — the server's model list is the truth, and omitting `model` uses the server default.",inputSchema:{type:"object",properties:{},additionalProperties:!1},async run(){const e=(await i.listModels()).models||[];return e.length?["Pass one of these as aegis_ask's `model` argument:","",...e.map(e=>` ${e.id} (${(e.capabilities||[]).join(", ")})`)].join("\n"):"No pinnable models are currently configured on AEGIS."}},aegis_balance:{description:"Check the AEGIS token bank balance and recent spend. Call this before aegis_ask if you're unsure whether the account has funds, or to see what recent calls cost.",inputSchema:{type:"object",properties:{},additionalProperties:!1},async run(){const e=await i.tokenBankBalance(),t=[`Balance: €${Number(e.balance_eur||0).toFixed(2)}`],o=(e.ledger||[]).slice(0,5);if(o.length){t.push("","Recent activity:");for(const e of o){const o=null!=e.amount_eur?Number(e.amount_eur):-Number(e.charged_micros||0)/1e6,i=Math.abs(o),s=`${o<0?"-":"+"}€${i<.01?i.toFixed(4):i.toFixed(2)}`,r="topup"===e.kind?"top-up":e.kind||"",n=e.model_key||r||"",a=e.tokens_in||e.tokens_out?` ${e.tokens_in||0}/${e.tokens_out||0} tokens`:"";t.push(` ${e.created_at||""} ${n}${a} ${s}`)}}else t.push("No spend yet.");var s;return(e.balance_eur||0)<=0&&t.push("",`Balance is empty — top up at ${s="topup","function"==typeof i.promptUrl?i.promptUrl(s,"topup_bank"):`https://aegiscloud.org/go/${s}`}, or set your own provider key with aegis_byok_set to use aegis_ask for free at cost.`),t.join("\n")}},aegis_byok_providers:{description:"List every provider that accepts a Bring-Your-Own-Key on AEGIS: the exact provider id to pass to aegis_byok_set, the models each one unlocks, where to create the key, and the prefix a valid key starts with. Call this before aegis_byok_set so the user knows which key to go get rather than guessing a provider id.",inputSchema:{type:"object",properties:{},additionalProperties:!1},async run(){const e=(await i.byokProviders()).providers||[];if(!e.length)return"AEGIS is not advertising any BYOK providers right now.";const t=["Set one with aegis_byok_set — pass the id exactly as shown:"];for(const o of e){const e=(o.models||[]).map(e=>"string"==typeof e?e:e&&e.id).filter(Boolean),i=o.configured?" ✓ set"+(o.masked?` (${o.masked})`:""):"";t.push(""),t.push(` ${o.id}${i}`),o.label&&t.push(` ${o.label}`),e.length&&t.push(` models: ${e.join(", ")}`),o.key_prefix&&t.push(` key starts with: ${o.key_prefix}`),o.key_url&&t.push(` get a key: ${o.key_url}`)}return t.join("\n")}},aegis_byok_status:{description:"List which providers have a Bring-Your-Own-Key configured on this AEGIS account (known ids: openai, anthropic, groq, openrouter, together, deepseek, gemini, …). A configured BYOK key is used automatically by aegis_ask instead of the pooled balance for that provider, so calls no longer cost AEGIS token-bank funds.",inputSchema:{type:"object",properties:{},additionalProperties:!1},async run(){const e=await i.byokStatus(),t=Object.entries(e||{});if(!t.length)return"No BYOK providers are configured. Run aegis_byok_providers to see what you can set.";let o={};try{const e=await i.byokProviders();for(const t of e.providers||[])o[t.id]=t.label||""}catch{}return`BYOK keys:\n${t.map(([e,t])=>{const i=t&&t.set;return` ${e}${o[e]?` ${o[e]}`:""}: ${i?`set (${t.masked})`:"not set"}`}).join("\n")}`}},aegis_byok_set:{description:"Set or remove a Bring-Your-Own-Key API key for a provider on this AEGIS account (known ids: openai, anthropic, groq, openrouter, together, deepseek, gemini, …; the server validates what it supports). Once set, aegis_ask uses that key directly for that provider instead of the pooled AEGIS balance — unlimited use at the user's own cost. Omit api_key to remove a previously set key.",inputSchema:{type:"object",properties:{provider:{type:"string",description:"Which provider this key is for (known ids: openai, anthropic, groq, openrouter, together, deepseek, gemini, …)."},api_key:{type:"string",description:"The provider's own API key. Omit to delete the stored key instead."}},required:["provider"],additionalProperties:!1},run:async e=>(await i.byokSet(e.provider,e.api_key)).message||(e.api_key?`${e.provider} key saved.`:`${e.provider} key removed.`)},aegis_memory_search:{description:"Search the user's AEGIS cloud memory (persists across machines and sessions). Returns the most relevant stored entries for a query.",inputSchema:{type:"object",properties:{query:{type:"string",description:"Search text. Empty returns most recent."},limit:{type:"integer",description:"Max entries (1-50). Default 5.",minimum:1,maximum:50}},required:["query"],additionalProperties:!1},async run(e){const t=(await i.memorySearch(e.query,e.limit||5)).entries||[],s=o?o.search(e.query,e.limit||5):[];if(!s.length&&!t.length)return`No memory entries matched "${e.query}".`;const r=[];let n=0;for(const e of s)r.push(`${++n}. [wiki] ${e.title}: ${e.value??""}\n ${e.body}`);for(const e of t){const t=e.timestamp||e.createdAt||"",o=e.tags&&e.tags.length?` [${e.tags.join(", ")}]`:"";r.push(`${++n}. ${e.content}${o}${t?`\n (${t})`:""}`)}return r.join("\n")}},aegis_memory_save:{description:"Save a note to the user's AEGIS cloud memory so it persists across machines and future sessions. Use for durable facts, decisions, or preferences the user asks you to remember.",inputSchema:{type:"object",properties:{content:{type:"string",description:"The fact/note to store."},tags:{type:"array",items:{type:"string"},description:"Optional tags."},importance:{type:"integer",description:"Optional 1-10 salience. Default 5.",minimum:1,maximum:10},session:{type:"string",description:"Optional session/label to group under."}},required:["content"],additionalProperties:!1},async run(e){const t={id:i.randomUUID(),content:e.content,role:"assistant",source:"claude-code",session:e.session||"claude-code",tags:e.tags||[],importance:"number"==typeof e.importance?e.importance:5,timestamp:(new Date).toISOString()};return`Saved ${(await i.memorySave(t)).saved||1} memory entry (id ${t.id}).`}},aegis_memory_import:{description:"Import memory and past conversation context from OTHER AI coding tools installed on this machine (Claude Code, Codex, Cursor, Gemini CLI, Continue, Goose, opencode, Windsurf, Zed, and a local AEGIS engine) into the user's AEGIS cloud memory. Scans read-only; nothing in the other tools' directories is modified. Defaults to a DRY RUN that only reports what it found — pass confirm:true to actually save. Entries are content-addressed, so re-running never duplicates.",inputSchema:{type:"object",properties:{confirm:{type:"boolean",description:"false (default) = report only. true = actually write the entries to AEGIS memory."},sources:{type:"array",items:{type:"string"},description:'Optional subset of source ids to import (e.g. ["claude-code"]). Omit for every source found on this machine.'},limit:{type:"integer",description:"Max entries to import (1-5000). Default 1000.",minimum:1,maximum:5e3}},additionalProperties:!1},async run(e){const t=e.limit||1e3,o=foreignMemory.scan({sources:e.sources,limit:t}),s=foreignMemory.describe(o);if(!o.entries.length)return`${s}\n\nNothing to import.`;if(!e.confirm)return[s,"",`Dry run — ${o.totals.entries} entries would be saved to AEGIS memory under ${o.totals.sourcesWithEntries} session(s) (${o.totals.skipped} skipped as too short/noise).`,"Call this tool again with confirm:true to save them."].join("\n");let r=0;const n=[];for(const t of foreignMemory.chunk(o.entries,200))try{const e=await i.memorySaveBatch(t);r+=e&&e.saved||t.length}catch(e){n.push(e.message);break}return n.length?`${s}\n\nSaved ${r} of ${o.totals.entries} entries, then stopped: ${n[0]}`:`${s}\n\nSaved ${r} entries to AEGIS memory. They are searchable now with aegis_memory_search.`}},aegis_memory_list:{description:"List the most recent entries in the user's AEGIS cloud memory. Useful to review what AEGIS already remembers.",inputSchema:{type:"object",properties:{limit:{type:"integer",description:"Max entries (1-50). Default 10.",minimum:1,maximum:50}},additionalProperties:!1},async run(e){const t=(await i.memoryList(e.limit||10)).entries||[];if(!t.length)return"AEGIS cloud memory is empty.";const o=t.map((e,t)=>`${t+1}. ${e.content}`).join("\n");return`Recent ${t.length} entries:\n${o}`}}};return{TOOLS:s,toolList:function(){return Object.entries(s).map(([e,t])=>({name:e,description:t.description,inputSchema:t.inputSchema}))}}}module.exports={createTools:createTools};
@@ -1,3 +1,3 @@
1
1
  // SPDX-License-Identifier: AGPL-3.0-or-later
2
2
  // Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
3
- "use strict";const FLAGS=Object.freeze({headlessSkip:"--dangerously-skip-permissions",interactiveSkip:"--allow-dangerously-skip-permissions",permissionMode:"--permission-mode",allowedTools:"--allowedTools",disallowedTools:"--disallowedTools",print:"-p",outputFormat:"--output-format",model:"--model",sessionId:"--session-id",resume:"--resume",inputFormat:"--input-format",permissionPromptTool:"--permission-prompt-tool",addDir:"--add-dir"});function addDirArgs(e){const s=[];for(const o of unique(e))s.push(`${FLAGS.addDir}=${o}`);return s}const UUID_RE=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,DEFAULT_OUTPUT_FORMAT="stream-json";function unique(e){const s=new Set,o=[];for(const i of Array.isArray(e)?e:[]){const e=String(i).trim();e&&!s.has(e)&&(s.add(e),o.push(e))}return o}function claudeArgv(e={}){const s=e.posture;if(!s||"object"!=typeof s)throw new Error("claudeArgv requires a resolved posture record (one/src/permissions.js resolvePosture)");const o=s.childKind,i="interactive"!==o,{PERMISSION_MODES:r}=require("./permissions.js"),n=s.child&&"string"==typeof s.child.permissionMode?s.child.permissionMode:null,d=void 0!==e.permissionMode&&null!==e.permissionMode?String(e.permissionMode):null,t=null!==d||null!==n,l=null!==d?d:n;if(t&&!r.includes(l))throw new Error(`--permission-mode ${JSON.stringify(l)} is not one of ${r.join("|")} — refusing to pass (or to silently drop) a mode the child does not accept.`);const a=s.rules||{},p=unique(a.allow),u=unique(a.deny),c=unique(a.ask),m=e.resumeSessionId?String(e.resumeSessionId).trim():"",h=e.sessionId?String(e.sessionId).trim():"",g=m||null,f=!g&&h?h:null;for(const[e,s]of[["resumeSessionId",g],["sessionId",f]])if(s&&!UUID_RE.test(s))throw new Error(`${e} ${JSON.stringify(s)} is not a UUID — refusing to pass it to --resume/--session-id, which the child rejects after the spawn (turning a continuity bug into an opaque failed turn).`);const S=!0===e.askBridge&&!(s.child&&s.child.skip),A=[];i&&A.push(FLAGS.print,FLAGS.outputFormat,String(e.outputFormat||"stream-json")),e.model&&A.push(FLAGS.model,String(e.model));const F=addDirArgs(e.addDir);A.push(...F),p.length&&A.push(FLAGS.allowedTools,p.join(",")),u.length&&A.push(FLAGS.disallowedTools,u.join(",")),t&&A.push(FLAGS.permissionMode,l),s.child&&s.child.flag&&A.push(s.child.flag),S&&A.push(FLAGS.inputFormat,"stream-json",FLAGS.permissionPromptTool,"stdio"),g?A.push(FLAGS.resume,g):f&&A.push(FLAGS.sessionId,f),Array.isArray(e.extra)&&A.push(...e.extra.map(String)),S||void 0===e.prompt||null===e.prompt||A.push(String(e.prompt));const w=Object.freeze({kind:o,permissionMode:l,permissionModePassed:t,permissionModeSource:t?null!==d?"descriptor":"posture":null,permissionModeDropped:s&&s.permissionModeDropped||null,skip:Boolean(s.child&&s.child.skip),skipFlag:s.child&&s.child.flag||null,allowedTools:Object.freeze(p),disallowedTools:Object.freeze(u),unmappedAsk:Object.freeze(c),addDir:Object.freeze(F.map((e=>e.slice(FLAGS.addDir.length+1)))),resumeSessionId:g,sessionId:f,askBridge:S,argv:Object.freeze(A.slice())});return{argv:w.argv,record:w}}function childRecordLine(e){if(!e||"object"!=typeof e)return null;const s=e.permissionModePassed?`${FLAGS.permissionMode}=${e.permissionMode}`:e.permissionModeDropped?`no --permission-mode (asked for one, dropped: ${e.permissionModeDropped})`:"no --permission-mode (none was set)";return`aegis: claude child [${e.kind}] ${e.skipFlag||"no permission flag"} · ${s} · allowedTools=[${e.allowedTools.join(", ")}] disallowedTools=[${e.disallowedTools.join(", ")}]`+(e.unmappedAsk.length?` (ask rules recorded, unmapped: ${e.unmappedAsk.join(", ")})`:"")+(e.addDir&&e.addDir.length?` · addDir=[${e.addDir.join(", ")}]`:"")+(e.resumeSessionId?` · resumed session ${e.resumeSessionId}`:e.sessionId?` · new session ${e.sessionId}`:" · no session id (each turn is a new conversation)")+(e.askBridge?" · ask bridge (the child can raise approval cards)":" · no ask bridge (headless: unapproved tools auto-deny)")}module.exports={FLAGS:FLAGS,DEFAULT_OUTPUT_FORMAT:"stream-json",claudeArgv:claudeArgv,addDirArgs:addDirArgs,childRecordLine:childRecordLine};
3
+ "use strict";const FLAGS=Object.freeze({headlessSkip:"--dangerously-skip-permissions",interactiveSkip:"--allow-dangerously-skip-permissions",permissionMode:"--permission-mode",allowedTools:"--allowedTools",disallowedTools:"--disallowedTools",print:"-p",outputFormat:"--output-format",model:"--model",sessionId:"--session-id",resume:"--resume",inputFormat:"--input-format",permissionPromptTool:"--permission-prompt-tool",addDir:"--add-dir"});function addDirArgs(e){const s=[];for(const o of unique(e))s.push(`${FLAGS.addDir}=${o}`);return s}const UUID_RE=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,DEFAULT_OUTPUT_FORMAT="stream-json";function unique(e){const s=new Set,o=[];for(const i of Array.isArray(e)?e:[]){const e=String(i).trim();e&&!s.has(e)&&(s.add(e),o.push(e))}return o}function claudeArgv(e={}){const s=e.posture;if(!s||"object"!=typeof s)throw new Error("claudeArgv requires a resolved posture record (one/src/permissions.js resolvePosture)");const o=s.childKind,i="interactive"!==o,{PERMISSION_MODES:r}=require("./permissions.js"),n=s.child&&"string"==typeof s.child.permissionMode?s.child.permissionMode:null,d=void 0!==e.permissionMode&&null!==e.permissionMode?String(e.permissionMode):null,t=null!==d||null!==n,l=null!==d?d:n;if(t&&!r.includes(l))throw new Error(`--permission-mode ${JSON.stringify(l)} is not one of ${r.join("|")} — refusing to pass (or to silently drop) a mode the child does not accept.`);const a=s.rules||{},p=unique(a.allow),u=unique(a.deny),c=unique(a.ask),m=e.resumeSessionId?String(e.resumeSessionId).trim():"",h=e.sessionId?String(e.sessionId).trim():"",g=m||null,f=!g&&h?h:null;for(const[e,s]of[["resumeSessionId",g],["sessionId",f]])if(s&&!UUID_RE.test(s))throw new Error(`${e} ${JSON.stringify(s)} is not a UUID — refusing to pass it to --resume/--session-id, which the child rejects after the spawn (turning a continuity bug into an opaque failed turn).`);const S=!0===e.askBridge&&!(s.child&&s.child.skip),A=[];i&&A.push(FLAGS.print,FLAGS.outputFormat,String(e.outputFormat||"stream-json")),e.model&&A.push(FLAGS.model,String(e.model));const F=addDirArgs(e.addDir);A.push(...F),p.length&&A.push(FLAGS.allowedTools,p.join(",")),u.length&&A.push(FLAGS.disallowedTools,u.join(",")),t&&A.push(FLAGS.permissionMode,l),s.child&&s.child.flag&&A.push(s.child.flag),S&&A.push(FLAGS.inputFormat,"stream-json",FLAGS.permissionPromptTool,"stdio"),g?A.push(FLAGS.resume,g):f&&A.push(FLAGS.sessionId,f),Array.isArray(e.extra)&&A.push(...e.extra.map(String)),S||void 0===e.prompt||null===e.prompt||A.push(String(e.prompt));const w=Object.freeze({kind:o,permissionMode:l,permissionModePassed:t,permissionModeSource:t?null!==d?"descriptor":"posture":null,permissionModeDropped:s&&s.permissionModeDropped||null,skip:Boolean(s.child&&s.child.skip),skipFlag:s.child&&s.child.flag||null,allowedTools:Object.freeze(p),disallowedTools:Object.freeze(u),unmappedAsk:Object.freeze(c),addDir:Object.freeze(F.map(e=>e.slice(FLAGS.addDir.length+1))),resumeSessionId:g,sessionId:f,askBridge:S,argv:Object.freeze(A.slice())});return{argv:w.argv,record:w}}function childRecordLine(e){if(!e||"object"!=typeof e)return null;const s=e.permissionModePassed?`${FLAGS.permissionMode}=${e.permissionMode}`:e.permissionModeDropped?`no --permission-mode (asked for one, dropped: ${e.permissionModeDropped})`:"no --permission-mode (none was set)";return`aegis: claude child [${e.kind}] ${e.skipFlag||"no permission flag"} · ${s} · allowedTools=[${e.allowedTools.join(", ")}] disallowedTools=[${e.disallowedTools.join(", ")}]`+(e.unmappedAsk.length?` (ask rules recorded, unmapped: ${e.unmappedAsk.join(", ")})`:"")+(e.addDir&&e.addDir.length?` · addDir=[${e.addDir.join(", ")}]`:"")+(e.resumeSessionId?` · resumed session ${e.resumeSessionId}`:e.sessionId?` · new session ${e.sessionId}`:" · no session id (each turn is a new conversation)")+(e.askBridge?" · ask bridge (the child can raise approval cards)":" · no ask bridge (headless: unapproved tools auto-deny)")}module.exports={FLAGS:FLAGS,DEFAULT_OUTPUT_FORMAT:"stream-json",claudeArgv:claudeArgv,addDirArgs:addDirArgs,childRecordLine:childRecordLine};
@@ -1,3 +1,3 @@
1
1
  // SPDX-License-Identifier: AGPL-3.0-or-later
2
2
  // Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
3
- "use strict";const PROTO=1,METHODS=Object.freeze(["hello","exec","event","cancel"]),CAPS=Object.freeze({EXEC:"exec",EVENT:"event",CANCEL:"cancel",PTY:"pty"}),CODE=Object.freeze({BAD_JSON:"bad_json",BAD_FRAME:"bad_frame",UNKNOWN_METHOD:"unknown_method",PROTO_MISMATCH:"proto_mismatch",HELLO_REQUIRED:"hello_required",CAPABILITY_MISSING:"capability_missing",UNSUPPORTED:"unsupported"});function request(e,o,t){return{id:e,m:String(o),p:t&&"object"==typeof t?t:{}}}function ok(e,o){return{id:e,ok:!0,r:o&&"object"==typeof o?o:{}}}function err(e,o,t){return{id:e,ok:!1,e:{code:String(o||CODE.UNSUPPORTED),msg:String(t||"")}}}function isObject(e){return Boolean(e)&&"object"==typeof e&&!Array.isArray(e)}function validate(e){return isObject(e)?void 0===e.id||null===e.id?{ok:!1,code:CODE.BAD_FRAME,msg:"frame has no id"}:void 0!==e.ok?!0===e.ok?void 0!==e.e?{ok:!1,code:CODE.BAD_FRAME,msg:"reply carries both r and e"}:{ok:!0}:!1===e.ok?isObject(e.e)&&e.e.code?{ok:!0}:{ok:!1,code:CODE.BAD_FRAME,msg:"a failed reply must name a code"}:{ok:!1,code:CODE.BAD_FRAME,msg:"ok must be true or false"}:"string"==typeof e.m&&METHODS.includes(e.m)?void 0===e.p||isObject(e.p)?{ok:!0}:{ok:!1,code:CODE.BAD_FRAME,msg:"params must be an object"}:{ok:!1,code:CODE.UNKNOWN_METHOD,msg:`unknown method: ${String(e.m)}`}:{ok:!1,code:CODE.BAD_FRAME,msg:"frame must be an object"}}function negotiate(e,o){const t=o||{},r=validate(e);if(!r.ok)return{ok:!1,code:r.code,msg:r.msg};if("hello"!==e.m)return{ok:!1,code:CODE.HELLO_REQUIRED,msg:`the first frame must be hello, got ${String(e.m)}`};const n=e.p||{};if(1!==n.proto)return{ok:!1,code:CODE.PROTO_MISMATCH,msg:`peer speaks protocol ${String(n.proto)}, this build speaks 1`};const i=Array.isArray(n.caps)?n.caps.map(String):[],s=(Array.isArray(t.requireCaps)?t.requireCaps.map(String):[]).filter((e=>!i.includes(e)));return s.length?{ok:!1,code:CODE.CAPABILITY_MISSING,msg:`peer does not offer: ${s.join(", ")}`}:{ok:!0,proto:1,caps:i}}function hello(e){return request(void 0===e?0:e,"hello",{proto:1,caps:[CAPS.EXEC,CAPS.EVENT,CAPS.CANCEL]})}function encode(e){return`${JSON.stringify(e)}\n`}function decodeLine(e){const o=String(null==e?"":e).trim();if(!o)return{ok:!1,id:null,code:CODE.BAD_JSON,msg:"empty line"};let t;try{t=JSON.parse(o)}catch(e){return{ok:!1,id:null,code:CODE.BAD_JSON,msg:`not JSON: ${e.message}`}}const r=validate(t);return r.ok?{ok:!0,frame:t}:{ok:!1,id:isObject(t)&&void 0!==t.id?t.id:null,code:r.code,msg:r.msg}}function splitLines(e){const o=String(null==e?"":e).split("\n"),t=o.pop();return{lines:o.filter((e=>""!==e.trim())),rest:void 0===t?"":t}}module.exports={PROTO:1,METHODS:METHODS,CAPS:CAPS,CODE:CODE,request:request,ok:ok,err:err,hello:hello,validate:validate,negotiate:negotiate,encode:encode,decodeLine:decodeLine,splitLines:splitLines};
3
+ "use strict";const PROTO=1,METHODS=Object.freeze(["hello","exec","event","cancel"]),CAPS=Object.freeze({EXEC:"exec",EVENT:"event",CANCEL:"cancel",PTY:"pty"}),CODE=Object.freeze({BAD_JSON:"bad_json",BAD_FRAME:"bad_frame",UNKNOWN_METHOD:"unknown_method",PROTO_MISMATCH:"proto_mismatch",HELLO_REQUIRED:"hello_required",CAPABILITY_MISSING:"capability_missing",UNSUPPORTED:"unsupported"});function request(e,o,t){return{id:e,m:String(o),p:t&&"object"==typeof t?t:{}}}function ok(e,o){return{id:e,ok:!0,r:o&&"object"==typeof o?o:{}}}function err(e,o,t){return{id:e,ok:!1,e:{code:String(o||CODE.UNSUPPORTED),msg:String(t||"")}}}function isObject(e){return Boolean(e)&&"object"==typeof e&&!Array.isArray(e)}function validate(e){return isObject(e)?void 0===e.id||null===e.id?{ok:!1,code:CODE.BAD_FRAME,msg:"frame has no id"}:void 0!==e.ok?!0===e.ok?void 0!==e.e?{ok:!1,code:CODE.BAD_FRAME,msg:"reply carries both r and e"}:{ok:!0}:!1===e.ok?isObject(e.e)&&e.e.code?{ok:!0}:{ok:!1,code:CODE.BAD_FRAME,msg:"a failed reply must name a code"}:{ok:!1,code:CODE.BAD_FRAME,msg:"ok must be true or false"}:"string"==typeof e.m&&METHODS.includes(e.m)?void 0===e.p||isObject(e.p)?{ok:!0}:{ok:!1,code:CODE.BAD_FRAME,msg:"params must be an object"}:{ok:!1,code:CODE.UNKNOWN_METHOD,msg:`unknown method: ${String(e.m)}`}:{ok:!1,code:CODE.BAD_FRAME,msg:"frame must be an object"}}function negotiate(e,o){const t=o||{},r=validate(e);if(!r.ok)return{ok:!1,code:r.code,msg:r.msg};if("hello"!==e.m)return{ok:!1,code:CODE.HELLO_REQUIRED,msg:`the first frame must be hello, got ${String(e.m)}`};const n=e.p||{};if(1!==n.proto)return{ok:!1,code:CODE.PROTO_MISMATCH,msg:`peer speaks protocol ${String(n.proto)}, this build speaks 1`};const i=Array.isArray(n.caps)?n.caps.map(String):[],s=(Array.isArray(t.requireCaps)?t.requireCaps.map(String):[]).filter(e=>!i.includes(e));return s.length?{ok:!1,code:CODE.CAPABILITY_MISSING,msg:`peer does not offer: ${s.join(", ")}`}:{ok:!0,proto:1,caps:i}}function hello(e){return request(void 0===e?0:e,"hello",{proto:1,caps:[CAPS.EXEC,CAPS.EVENT,CAPS.CANCEL]})}function encode(e){return`${JSON.stringify(e)}\n`}function decodeLine(e){const o=String(null==e?"":e).trim();if(!o)return{ok:!1,id:null,code:CODE.BAD_JSON,msg:"empty line"};let t;try{t=JSON.parse(o)}catch(e){return{ok:!1,id:null,code:CODE.BAD_JSON,msg:`not JSON: ${e.message}`}}const r=validate(t);return r.ok?{ok:!0,frame:t}:{ok:!1,id:isObject(t)&&void 0!==t.id?t.id:null,code:r.code,msg:r.msg}}function splitLines(e){const o=String(null==e?"":e).split("\n"),t=o.pop();return{lines:o.filter(e=>""!==e.trim()),rest:void 0===t?"":t}}module.exports={PROTO:1,METHODS:METHODS,CAPS:CAPS,CODE:CODE,request:request,ok:ok,err:err,hello:hello,validate:validate,negotiate:negotiate,encode:encode,decodeLine:decodeLine,splitLines:splitLines};
@@ -1,3 +1,3 @@
1
1
  // SPDX-License-Identifier: AGPL-3.0-or-later
2
2
  // Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
3
- "use strict";const path=require("node:path"),FACE=Object.freeze({TUI:"tui",GUI:"gui"}),RUN_AS_NODE="ELECTRON_RUN_AS_NODE",FORCE_TUI=["--tui","code"],COMPAT_BIN="aegiscode";function faceRoot(e,n){return path.join(e,"faces",n)}function cliEntry(e){return path.join(faceRoot(e,"cli"),"bin","aegiscode.js")}function binName(e){return path.basename(String(e||"aegis")).replace(/\.(exe|cmd|bat|AppImage)$/i,"").replace(/\.js$/,"")}function plan(e){const n=e||{};if(!n.packaged)return null;const t=n.execPath,a=n.resourcesPath,i=Array.isArray(n.argv)?n.argv.map(String):[];if(!t||!a)return null;const r=(e,n)=>({face:FACE.TUI,exec:t,args:[cliEntry(a),...e],env:{[RUN_AS_NODE]:"1"},reason:n});if(binName(n.invokedAs)===COMPAT_BIN)return r(i,"aegiscode is the compatibility bin");const c=i.find((e=>FORCE_TUI.includes(e)));return c?r(i.filter((e=>e!==c)),`${c} asks for the terminal face`):null}function spawnOptions(e,n){return e?{exec:e.exec,args:e.args,env:Object.assign({},n||{},e.env)}:null}module.exports={plan:plan,spawnOptions:spawnOptions,FACE:FACE,RUN_AS_NODE:RUN_AS_NODE,COMPAT_BIN:COMPAT_BIN,FORCE_TUI:FORCE_TUI,cliEntry:cliEntry,faceRoot:faceRoot,binName:binName};
3
+ "use strict";const path=require("node:path"),FACE=Object.freeze({TUI:"tui",GUI:"gui"}),RUN_AS_NODE="ELECTRON_RUN_AS_NODE",FORCE_TUI=["--tui","code"],COMPAT_BIN="aegiscode";function faceRoot(e,n){return path.join(e,"faces",n)}function cliEntry(e){return path.join(faceRoot(e,"cli"),"bin","aegiscode.js")}function binName(e){return path.basename(String(e||"aegis")).replace(/\.(exe|cmd|bat|AppImage)$/i,"").replace(/\.js$/,"")}function plan(e){const n=e||{};if(!n.packaged)return null;const t=n.execPath,a=n.resourcesPath,i=Array.isArray(n.argv)?n.argv.map(String):[];if(!t||!a)return null;const r=(e,n)=>({face:FACE.TUI,exec:t,args:[cliEntry(a),...e],env:{[RUN_AS_NODE]:"1"},reason:n});if(binName(n.invokedAs)===COMPAT_BIN)return r(i,"aegiscode is the compatibility bin");const c=i.find(e=>FORCE_TUI.includes(e));return c?r(i.filter(e=>e!==c),`${c} asks for the terminal face`):null}function spawnOptions(e,n){return e?{exec:e.exec,args:e.args,env:Object.assign({},n||{},e.env)}:null}module.exports={plan:plan,spawnOptions:spawnOptions,FACE:FACE,RUN_AS_NODE:RUN_AS_NODE,COMPAT_BIN:COMPAT_BIN,FORCE_TUI:FORCE_TUI,cliEntry:cliEntry,faceRoot:faceRoot,binName:binName};
@@ -1,3 +1,3 @@
1
1
  // SPDX-License-Identifier: AGPL-3.0-or-later
2
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;
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=16,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>8)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=40){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=24){return new RegExp(`[0-9a-fA-F]{${t},}`).test(String(e))}const HEX_ATTESTATION=new RegExp("^[0-9a-f]{32}$");function isFingerprintShape(e){return new RegExp("^[0-9a-f]{12}$").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,12):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,4096).filter(e=>""!==observationKey(e)).length:0}function signatureFromObservations(e,t){if(!Array.isArray(e))return null;const r=e.slice(0,4096).map(observationKey).filter(Boolean);return r.length?digest(t,Array.from(new Set(r)).sort().join("\n")).slice(0,16):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,64)){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>200?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>4096)throw new Error(`fingerprint: ${r.length} code files exceeds MAX_CODE_FILES (4096); 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,16),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,64)||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,32)}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:g}=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 E=touchSignatureFrom(s),p=codeAxisFrom(l,u),m=aiAxisFrom({secret:c,model:f,observations:d}),F={v:4,algo:FP_ALGO,keyFingerprint:S,label:safeLabel(r,40),account:safeLabel(n,64)||null,model:safeLabel(i,64)||null,tools:normaliseTools(o),behaviour:behaviouralSignature(a),behaviourSamples:countObservations(a),touch:E.signature,touchSamples:E.samples,code:p.code,codeFiles:p.codeFiles,codeDirty:p.codeDirty,aiKey:m.aiKey,aiModel:m.aiModel,ai:m.ai,aiSamples:m.aiSamples,createdAt:isoTs(g)},h={...F,attestation:attest(F,t)};return assertNoLeak(h,t,c),Object.freeze(h)}function id(e){if(!e||!isFingerprintShape(e.keyFingerprint))throw new Error("fingerprint: not a fingerprinted record");return`φ_${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:4,FP_ALGO:FP_ALGO,FP_PREFIX:"φ_",KEY_FP_LENGTH:12,SIG_LENGTH:16,ATTEST_LENGTH:32,LEAK_HEX_RUN:24,CODE_LEN:16,MAX_CODE_FILES:4096,MAX_PATH:200,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;
@@ -1,3 +1,3 @@
1
1
  // SPDX-License-Identifier: AGPL-3.0-or-later
2
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}};
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}};