aegisone 1.0.64 → 1.0.65

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 (363) 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/package.json +1 -1
  17. package/vendor/cli/scripts/check.mjs +1 -1
  18. package/vendor/cli/scripts/demo.mjs +1 -1
  19. package/vendor/cli/scripts/postinstall.mjs +1 -1
  20. package/vendor/cli/scripts/predist.mjs +1 -1
  21. package/vendor/cli/scripts/runtests.mjs +1 -1
  22. package/vendor/cli/src/app.js +1 -1
  23. package/vendor/cli/src/art.js +1 -1
  24. package/vendor/cli/src/chatflow.js +1 -1
  25. package/vendor/cli/src/checkpoint.js +1 -1
  26. package/vendor/cli/src/clipboard.js +1 -1
  27. package/vendor/cli/src/cloudsync.js +1 -1
  28. package/vendor/cli/src/commands.js +2 -2
  29. package/vendor/cli/src/config.js +1 -1
  30. package/vendor/cli/src/connect.js +1 -1
  31. package/vendor/cli/src/devrun.js +1 -1
  32. package/vendor/cli/src/diff.js +1 -1
  33. package/vendor/cli/src/diffview.js +1 -1
  34. package/vendor/cli/src/dream.js +1 -1
  35. package/vendor/cli/src/engine.js +1 -1
  36. package/vendor/cli/src/events.js +1 -1
  37. package/vendor/cli/src/export.js +1 -1
  38. package/vendor/cli/src/fingerprint.js +1 -1
  39. package/vendor/cli/src/format.js +1 -1
  40. package/vendor/cli/src/fuzzy.js +1 -1
  41. package/vendor/cli/src/history.js +1 -1
  42. package/vendor/cli/src/init.js +1 -1
  43. package/vendor/cli/src/markdown.js +1 -1
  44. package/vendor/cli/src/models.js +1 -1
  45. package/vendor/cli/src/overlays.js +1 -1
  46. package/vendor/cli/src/panels.js +1 -1
  47. package/vendor/cli/src/ping.js +1 -1
  48. package/vendor/cli/src/presence.js +1 -1
  49. package/vendor/cli/src/render.js +1 -1
  50. package/vendor/cli/src/screen.js +1 -1
  51. package/vendor/cli/src/screens.js +1 -1
  52. package/vendor/cli/src/secret.js +1 -1
  53. package/vendor/cli/src/securefs.js +1 -1
  54. package/vendor/cli/src/settings.js +1 -1
  55. package/vendor/cli/src/signup.js +1 -1
  56. package/vendor/cli/src/summarize.js +1 -1
  57. package/vendor/cli/src/sysdiag.js +1 -1
  58. package/vendor/cli/src/theme.js +1 -1
  59. package/vendor/cli/src/title.js +1 -1
  60. package/vendor/cli/src/todos.js +1 -1
  61. package/vendor/cli/src/tokens.js +1 -1
  62. package/vendor/cli/src/topup.js +1 -1
  63. package/vendor/cli/src/update.js +1 -1
  64. package/vendor/cli/vendor/client/aegis.js +1 -1
  65. package/vendor/cli/vendor/client/attest.js +1 -1
  66. package/vendor/cli/vendor/client/authorship-key.js +1 -1
  67. package/vendor/cli/vendor/client/auto-provision.js +1 -1
  68. package/vendor/cli/vendor/client/brain-catalog.js +1 -1
  69. package/vendor/cli/vendor/client/byok-catalog.js +1 -1
  70. package/vendor/cli/vendor/client/catalog-client.js +1 -1
  71. package/vendor/cli/vendor/client/conversation-export.js +1 -1
  72. package/vendor/cli/vendor/client/credentials.js +1 -1
  73. package/vendor/cli/vendor/client/credits.js +1 -1
  74. package/vendor/cli/vendor/client/drive-connect.js +1 -1
  75. package/vendor/cli/vendor/client/env-file.js +1 -1
  76. package/vendor/cli/vendor/client/fingerprint.js +1 -1
  77. package/vendor/cli/vendor/client/foreign-memory.js +1 -1
  78. package/vendor/cli/vendor/client/foreign-sessions.js +1 -1
  79. package/vendor/cli/vendor/client/google-signin.js +1 -1
  80. package/vendor/cli/vendor/client/hooks.js +1 -1
  81. package/vendor/cli/vendor/client/model-discovery.js +1 -1
  82. package/vendor/cli/vendor/client/model-sync.js +1 -1
  83. package/vendor/cli/vendor/client/naming.js +1 -1
  84. package/vendor/cli/vendor/client/platform.js +1 -1
  85. package/vendor/cli/vendor/client/prefs.js +1 -1
  86. package/vendor/cli/vendor/client/presence.js +1 -1
  87. package/vendor/cli/vendor/client/record-vault.js +2 -2
  88. package/vendor/cli/vendor/client/session-search.js +1 -1
  89. package/vendor/cli/vendor/client/session-store.js +1 -1
  90. package/vendor/cli/vendor/client/skills.js +1 -1
  91. package/vendor/cli/vendor/client/topup.js +1 -1
  92. package/vendor/cli/vendor/client/touch.js +1 -1
  93. package/vendor/cli/vendor/client/update.js +1 -1
  94. package/vendor/cli/vendor/client/user-models.js +1 -1
  95. package/vendor/cli/vendor/desktop/lib/local/attachments.js +1 -1
  96. package/vendor/cli/vendor/desktop/lib/local/autonomous.js +1 -1
  97. package/vendor/cli/vendor/desktop/lib/local/claude-pro.js +1 -1
  98. package/vendor/cli/vendor/desktop/lib/local/context.js +1 -1
  99. package/vendor/cli/vendor/desktop/lib/local/engine.js +1 -1
  100. package/vendor/cli/vendor/desktop/lib/local/entitlement.js +1 -1
  101. package/vendor/cli/vendor/desktop/lib/local/integrity.js +1 -1
  102. package/vendor/cli/vendor/desktop/lib/local/local.js +1 -1
  103. package/vendor/cli/vendor/desktop/lib/local/perm-rules.js +5 -0
  104. package/vendor/cli/vendor/desktop/lib/local/perm-store.js +5 -0
  105. package/vendor/cli/vendor/desktop/lib/local/perm-write.js +5 -0
  106. package/vendor/cli/vendor/desktop/lib/local/pro-sessions.js +3 -1
  107. package/vendor/cli/vendor/desktop/lib/local/prompt.js +1 -1
  108. package/vendor/cli/vendor/desktop/lib/local/queue.js +1 -1
  109. package/vendor/cli/vendor/desktop/lib/local/repeat-guard.js +1 -1
  110. package/vendor/cli/vendor/desktop/lib/local/session-rounds.js +1 -1
  111. package/vendor/cli/vendor/desktop/lib/local/spill.js +1 -1
  112. package/vendor/cli/vendor/desktop/lib/local/turn-guard.js +1 -1
  113. package/vendor/cli/vendor/desktop/lib/local/verify-stop.js +1 -1
  114. package/vendor/cli/vendor/desktop/lib/local/worktree-lock.js +1 -1
  115. package/vendor/cli/vendor/desktop/lib/settings.js +1 -1
  116. package/vendor/cli/vendor/desktop/renderer/usage.js +1 -1
  117. package/vendor/cli/vendor/hosts/install.js +1 -1
  118. package/vendor/cli/vendor/hosts/openai-shim.js +1 -1
  119. package/vendor/cli/vendor/hosts/spec.js +1 -1
  120. package/vendor/cli/vendor/hosts/targets.js +1 -1
  121. package/vendor/cli/vendor/mcp/admission.js +1 -1
  122. package/vendor/cli/vendor/mcp/server.js +1 -1
  123. package/vendor/cli/vendor/mcp/tools.js +1 -1
  124. package/vendor/cli/vendor/one/src/child.js +1 -1
  125. package/vendor/cli/vendor/one/src/protocol.js +1 -1
  126. package/vendor/cli/vendor/one/src/selfhost.js +1 -1
  127. package/vendor/desktop/bin/aegis.js +1 -1
  128. package/vendor/desktop/lib/auto.js +1 -1
  129. package/vendor/desktop/lib/avatar/companion.js +1 -1
  130. package/vendor/desktop/lib/avatar/cosmetics.js +1 -1
  131. package/vendor/desktop/lib/avatar/holder-turn.js +1 -1
  132. package/vendor/desktop/lib/avatar/holders.js +1 -1
  133. package/vendor/desktop/lib/avatar/identity.js +1 -1
  134. package/vendor/desktop/lib/avatar/level.js +1 -1
  135. package/vendor/desktop/lib/avatar/mirror.js +1 -1
  136. package/vendor/desktop/lib/avatar/persona.js +1 -1
  137. package/vendor/desktop/lib/avatar/profile.js +1 -1
  138. package/vendor/desktop/lib/avatar/register.js +1 -1
  139. package/vendor/desktop/lib/avatar/store.js +1 -1
  140. package/vendor/desktop/lib/avatar/transfer.js +1 -1
  141. package/vendor/desktop/lib/avatar/turn.js +1 -1
  142. package/vendor/desktop/lib/avatar/voice.js +1 -1
  143. package/vendor/desktop/lib/avatar/xp.js +1 -1
  144. package/vendor/desktop/lib/deep-link.js +1 -1
  145. package/vendor/desktop/lib/local/attachments.js +1 -1
  146. package/vendor/desktop/lib/local/autonomous.js +1 -1
  147. package/vendor/desktop/lib/local/claude-pro.js +1 -1
  148. package/vendor/desktop/lib/local/cli-face.js +1 -1
  149. package/vendor/desktop/lib/local/context.js +1 -1
  150. package/vendor/desktop/lib/local/engine.js +1 -1
  151. package/vendor/desktop/lib/local/entitlement.js +1 -1
  152. package/vendor/desktop/lib/local/integrity.js +1 -1
  153. package/vendor/desktop/lib/local/local.js +1 -1
  154. package/vendor/desktop/lib/local/perm-rules.js +5 -0
  155. package/vendor/desktop/lib/local/perm-store.js +5 -0
  156. package/vendor/desktop/lib/local/perm-write.js +5 -0
  157. package/vendor/desktop/lib/local/pro-sessions.js +3 -1
  158. package/vendor/desktop/lib/local/prompt.js +1 -1
  159. package/vendor/desktop/lib/local/pty-host.js +1 -1
  160. package/vendor/desktop/lib/local/queue.js +1 -1
  161. package/vendor/desktop/lib/local/repeat-guard.js +1 -1
  162. package/vendor/desktop/lib/local/session-rounds.js +1 -1
  163. package/vendor/desktop/lib/local/spill.js +1 -1
  164. package/vendor/desktop/lib/local/telemetry.js +1 -1
  165. package/vendor/desktop/lib/local/turn-guard.js +1 -1
  166. package/vendor/desktop/lib/local/verify-stop.js +1 -1
  167. package/vendor/desktop/lib/local/worktree-lock.js +1 -1
  168. package/vendor/desktop/lib/provider-key-mirror.js +1 -1
  169. package/vendor/desktop/lib/quick-launcher.js +1 -1
  170. package/vendor/desktop/lib/settings.js +1 -1
  171. package/vendor/desktop/lib/skills-host.js +1 -1
  172. package/vendor/desktop/lib/speech-host.js +1 -1
  173. package/vendor/desktop/lib/sync/memory-store.js +1 -1
  174. package/vendor/desktop/lib/sync/persist-gate.js +1 -1
  175. package/vendor/desktop/lib/window-state.js +1 -1
  176. package/vendor/desktop/package.json +1 -1
  177. package/vendor/desktop/preload.js +3 -1
  178. package/vendor/desktop/renderer/app.js +3 -3
  179. package/vendor/desktop/renderer/avatar/assemble.js +1 -1
  180. package/vendor/desktop/renderer/avatar/avatar.js +1 -1
  181. package/vendor/desktop/renderer/avatar/cards.js +1 -1
  182. package/vendor/desktop/renderer/avatar/hud.js +1 -1
  183. package/vendor/desktop/renderer/avatar/pane.js +1 -1
  184. package/vendor/desktop/renderer/avatar/parts.js +1 -1
  185. package/vendor/desktop/renderer/commands.js +1 -1
  186. package/vendor/desktop/renderer/companion.js +1 -1
  187. package/vendor/desktop/renderer/composer-triggers.js +1 -1
  188. package/vendor/desktop/renderer/dictation.js +1 -1
  189. package/vendor/desktop/renderer/diff.js +1 -1
  190. package/vendor/desktop/renderer/diffview.js +1 -1
  191. package/vendor/desktop/renderer/fingerprint.js +2 -2
  192. package/vendor/desktop/renderer/index.html +10 -4
  193. package/vendor/desktop/renderer/library.js +1 -1
  194. package/vendor/desktop/renderer/markdown.js +1 -1
  195. package/vendor/desktop/renderer/palette-filter.js +1 -1
  196. package/vendor/desktop/renderer/provider-toolbar.js +1 -1
  197. package/vendor/desktop/renderer/providers.js +1 -1
  198. package/vendor/desktop/renderer/pty-frame.css +35 -0
  199. package/vendor/desktop/renderer/pty-frame.html +47 -0
  200. package/vendor/desktop/renderer/pty-panel.js +1 -1
  201. package/vendor/desktop/renderer/quick.js +1 -1
  202. package/vendor/desktop/renderer/settings-skills.js +1 -1
  203. package/vendor/desktop/renderer/shortcuts.js +1 -1
  204. package/vendor/desktop/renderer/stream-policy.js +1 -1
  205. package/vendor/desktop/renderer/style.css +22 -0
  206. package/vendor/desktop/renderer/transcript-view.js +1 -1
  207. package/vendor/desktop/renderer/usage.js +1 -1
  208. package/vendor/desktop/renderer/welcome-rows.js +1 -1
  209. package/vendor/desktop/vendor/aegis.js +1 -1
  210. package/vendor/desktop/vendor/attest.js +1 -1
  211. package/vendor/desktop/vendor/authorship-key.js +1 -1
  212. package/vendor/desktop/vendor/auto-provision.js +1 -1
  213. package/vendor/desktop/vendor/brain-catalog.js +1 -1
  214. package/vendor/desktop/vendor/byok-catalog.js +1 -1
  215. package/vendor/desktop/vendor/catalog-client.js +1 -1
  216. package/vendor/desktop/vendor/conversation-export.js +1 -1
  217. package/vendor/desktop/vendor/credentials.js +1 -1
  218. package/vendor/desktop/vendor/credits.js +1 -1
  219. package/vendor/desktop/vendor/drive-connect.js +1 -1
  220. package/vendor/desktop/vendor/env-file.js +1 -1
  221. package/vendor/desktop/vendor/faces/cli/bin/aegiscode.js +2 -2
  222. package/vendor/desktop/vendor/faces/cli/package.json +1 -1
  223. package/vendor/desktop/vendor/faces/cli/scripts/check.mjs +1 -1
  224. package/vendor/desktop/vendor/faces/cli/scripts/demo.mjs +1 -1
  225. package/vendor/desktop/vendor/faces/cli/scripts/postinstall.mjs +1 -1
  226. package/vendor/desktop/vendor/faces/cli/scripts/predist.mjs +1 -1
  227. package/vendor/desktop/vendor/faces/cli/scripts/runtests.mjs +1 -1
  228. package/vendor/desktop/vendor/faces/cli/src/app.js +1 -1
  229. package/vendor/desktop/vendor/faces/cli/src/art.js +1 -1
  230. package/vendor/desktop/vendor/faces/cli/src/autonomous.js +1 -1
  231. package/vendor/desktop/vendor/faces/cli/src/caps.js +1 -1
  232. package/vendor/desktop/vendor/faces/cli/src/chatflow.js +1 -1
  233. package/vendor/desktop/vendor/faces/cli/src/checkpoint.js +1 -1
  234. package/vendor/desktop/vendor/faces/cli/src/clipboard.js +1 -1
  235. package/vendor/desktop/vendor/faces/cli/src/cloudsync.js +1 -1
  236. package/vendor/desktop/vendor/faces/cli/src/commands.js +2 -2
  237. package/vendor/desktop/vendor/faces/cli/src/config.js +1 -1
  238. package/vendor/desktop/vendor/faces/cli/src/connect.js +1 -1
  239. package/vendor/desktop/vendor/faces/cli/src/devrun.js +1 -1
  240. package/vendor/desktop/vendor/faces/cli/src/diff.js +1 -1
  241. package/vendor/desktop/vendor/faces/cli/src/diffview.js +1 -1
  242. package/vendor/desktop/vendor/faces/cli/src/dream.js +1 -1
  243. package/vendor/desktop/vendor/faces/cli/src/engine.js +1 -1
  244. package/vendor/desktop/vendor/faces/cli/src/events.js +1 -1
  245. package/vendor/desktop/vendor/faces/cli/src/export.js +1 -1
  246. package/vendor/desktop/vendor/faces/cli/src/fingerprint.js +1 -1
  247. package/vendor/desktop/vendor/faces/cli/src/format.js +1 -1
  248. package/vendor/desktop/vendor/faces/cli/src/fuzzy.js +1 -1
  249. package/vendor/desktop/vendor/faces/cli/src/history.js +1 -1
  250. package/vendor/desktop/vendor/faces/cli/src/init.js +1 -1
  251. package/vendor/desktop/vendor/faces/cli/src/limits.js +1 -1
  252. package/vendor/desktop/vendor/faces/cli/src/markdown.js +1 -1
  253. package/vendor/desktop/vendor/faces/cli/src/mcp.js +1 -1
  254. package/vendor/desktop/vendor/faces/cli/src/models.js +1 -1
  255. package/vendor/desktop/vendor/faces/cli/src/overlays.js +1 -1
  256. package/vendor/desktop/vendor/faces/cli/src/panels.js +1 -1
  257. package/vendor/desktop/vendor/faces/cli/src/permissions.js +1 -1
  258. package/vendor/desktop/vendor/faces/cli/src/ping.js +1 -1
  259. package/vendor/desktop/vendor/faces/cli/src/presence.js +1 -1
  260. package/vendor/desktop/vendor/faces/cli/src/provenance.js +1 -1
  261. package/vendor/desktop/vendor/faces/cli/src/render.js +1 -1
  262. package/vendor/desktop/vendor/faces/cli/src/screen.js +1 -1
  263. package/vendor/desktop/vendor/faces/cli/src/screens.js +1 -1
  264. package/vendor/desktop/vendor/faces/cli/src/secret.js +1 -1
  265. package/vendor/desktop/vendor/faces/cli/src/securefs.js +1 -1
  266. package/vendor/desktop/vendor/faces/cli/src/settings.js +1 -1
  267. package/vendor/desktop/vendor/faces/cli/src/signup.js +1 -1
  268. package/vendor/desktop/vendor/faces/cli/src/summarize.js +1 -1
  269. package/vendor/desktop/vendor/faces/cli/src/sysdiag.js +1 -1
  270. package/vendor/desktop/vendor/faces/cli/src/theme.js +1 -1
  271. package/vendor/desktop/vendor/faces/cli/src/title.js +1 -1
  272. package/vendor/desktop/vendor/faces/cli/src/todos.js +1 -1
  273. package/vendor/desktop/vendor/faces/cli/src/tokens.js +1 -1
  274. package/vendor/desktop/vendor/faces/cli/src/topup.js +1 -1
  275. package/vendor/desktop/vendor/faces/cli/src/update.js +1 -1
  276. package/vendor/desktop/vendor/faces/cli/vendor/client/aegis.js +1 -1
  277. package/vendor/desktop/vendor/faces/cli/vendor/client/attest.js +1 -1
  278. package/vendor/desktop/vendor/faces/cli/vendor/client/authorship-key.js +1 -1
  279. package/vendor/desktop/vendor/faces/cli/vendor/client/auto-provision.js +1 -1
  280. package/vendor/desktop/vendor/faces/cli/vendor/client/brain-catalog.js +1 -1
  281. package/vendor/desktop/vendor/faces/cli/vendor/client/byok-catalog.js +1 -1
  282. package/vendor/desktop/vendor/faces/cli/vendor/client/catalog-client.js +1 -1
  283. package/vendor/desktop/vendor/faces/cli/vendor/client/conversation-export.js +1 -1
  284. package/vendor/desktop/vendor/faces/cli/vendor/client/credentials.js +1 -1
  285. package/vendor/desktop/vendor/faces/cli/vendor/client/credits.js +1 -1
  286. package/vendor/desktop/vendor/faces/cli/vendor/client/drive-connect.js +1 -1
  287. package/vendor/desktop/vendor/faces/cli/vendor/client/env-file.js +1 -1
  288. package/vendor/desktop/vendor/faces/cli/vendor/client/fingerprint.js +1 -1
  289. package/vendor/desktop/vendor/faces/cli/vendor/client/foreign-memory.js +1 -1
  290. package/vendor/desktop/vendor/faces/cli/vendor/client/foreign-sessions.js +1 -1
  291. package/vendor/desktop/vendor/faces/cli/vendor/client/google-signin.js +1 -1
  292. package/vendor/desktop/vendor/faces/cli/vendor/client/hooks.js +1 -1
  293. package/vendor/desktop/vendor/faces/cli/vendor/client/model-discovery.js +1 -1
  294. package/vendor/desktop/vendor/faces/cli/vendor/client/model-sync.js +1 -1
  295. package/vendor/desktop/vendor/faces/cli/vendor/client/naming.js +1 -1
  296. package/vendor/desktop/vendor/faces/cli/vendor/client/platform.js +1 -1
  297. package/vendor/desktop/vendor/faces/cli/vendor/client/prefs.js +1 -1
  298. package/vendor/desktop/vendor/faces/cli/vendor/client/presence.js +1 -1
  299. package/vendor/desktop/vendor/faces/cli/vendor/client/record-vault.js +2 -2
  300. package/vendor/desktop/vendor/faces/cli/vendor/client/session-search.js +1 -1
  301. package/vendor/desktop/vendor/faces/cli/vendor/client/session-store.js +1 -1
  302. package/vendor/desktop/vendor/faces/cli/vendor/client/skills.js +1 -1
  303. package/vendor/desktop/vendor/faces/cli/vendor/client/topup.js +1 -1
  304. package/vendor/desktop/vendor/faces/cli/vendor/client/touch.js +1 -1
  305. package/vendor/desktop/vendor/faces/cli/vendor/client/update.js +1 -1
  306. package/vendor/desktop/vendor/faces/cli/vendor/client/user-models.js +1 -1
  307. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/attachments.js +1 -1
  308. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/autonomous.js +1 -1
  309. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/claude-pro.js +1 -1
  310. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/context.js +1 -1
  311. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/engine.js +1 -1
  312. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/entitlement.js +1 -1
  313. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/exec-plan.js +1 -1
  314. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/integrity.js +1 -1
  315. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/local.js +1 -1
  316. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/perm-rules.js +2 -0
  317. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/perm-store.js +3 -1
  318. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/perm-write.js +2 -0
  319. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/pro-sessions.js +3 -1
  320. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/prompt.js +1 -1
  321. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/queue.js +1 -1
  322. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/repeat-guard.js +1 -1
  323. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/session-rounds.js +1 -1
  324. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/shell.js +1 -1
  325. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/spill.js +1 -1
  326. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/tools.js +1 -1
  327. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/turn-guard.js +1 -1
  328. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/verify-stop.js +1 -1
  329. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/worktree-lock.js +1 -1
  330. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/settings.js +1 -1
  331. package/vendor/desktop/vendor/faces/cli/vendor/desktop/main.js +3 -3
  332. package/vendor/desktop/vendor/faces/cli/vendor/desktop/renderer/usage.js +1 -1
  333. package/vendor/desktop/vendor/faces/cli/vendor/hosts/install.js +1 -1
  334. package/vendor/desktop/vendor/faces/cli/vendor/hosts/openai-shim.js +1 -1
  335. package/vendor/desktop/vendor/faces/cli/vendor/hosts/spec.js +1 -1
  336. package/vendor/desktop/vendor/faces/cli/vendor/hosts/targets.js +1 -1
  337. package/vendor/desktop/vendor/faces/cli/vendor/mcp/admission.js +1 -1
  338. package/vendor/desktop/vendor/faces/cli/vendor/mcp/server.js +1 -1
  339. package/vendor/desktop/vendor/faces/cli/vendor/mcp/tools.js +1 -1
  340. package/vendor/desktop/vendor/faces/cli/vendor/one/src/child.js +1 -1
  341. package/vendor/desktop/vendor/faces/cli/vendor/one/src/protocol.js +1 -1
  342. package/vendor/desktop/vendor/faces/cli/vendor/one/src/selfhost.js +1 -1
  343. package/vendor/desktop/vendor/fingerprint.js +1 -1
  344. package/vendor/desktop/vendor/foreign-memory.js +1 -1
  345. package/vendor/desktop/vendor/foreign-sessions.js +1 -1
  346. package/vendor/desktop/vendor/google-signin.js +1 -1
  347. package/vendor/desktop/vendor/hooks.js +1 -1
  348. package/vendor/desktop/vendor/model-discovery.js +1 -1
  349. package/vendor/desktop/vendor/model-sync.js +1 -1
  350. package/vendor/desktop/vendor/naming.js +1 -1
  351. package/vendor/desktop/vendor/platform.js +1 -1
  352. package/vendor/desktop/vendor/prefs.js +1 -1
  353. package/vendor/desktop/vendor/presence.js +1 -1
  354. package/vendor/desktop/vendor/protocol.js +1 -1
  355. package/vendor/desktop/vendor/record-vault.js +2 -2
  356. package/vendor/desktop/vendor/selfhost.js +1 -1
  357. package/vendor/desktop/vendor/session-search.js +1 -1
  358. package/vendor/desktop/vendor/session-store.js +1 -1
  359. package/vendor/desktop/vendor/skills.js +1 -1
  360. package/vendor/desktop/vendor/topup.js +1 -1
  361. package/vendor/desktop/vendor/touch.js +1 -1
  362. package/vendor/desktop/vendor/update.js +1 -1
  363. 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";const TTL_MS=18e5,MAX_ENTRIES=64,entries=new Map,historyKeys=new WeakMap;let historyKeySeq=0;function prune(e=Date.now()){for(const[t,n]of entries)e-n.at>TTL_MS&&entries.delete(t);for(;entries.size>MAX_ENTRIES;){const e=entries.keys().next();if(e.done)break;entries.delete(e.value)}return entries.size}function keyFor(e,t){const n=e&&"object"==typeof e?e:{},r=n.sessionKey||n.sessionId||n.chatId||n.threadId||n.conversationId;if("string"==typeof r&&r.trim())return`s:${r.trim()}`;if("string"==typeof n.cwd&&n.cwd.trim())return`cwd:${n.cwd.trim()}`;if(t&&"object"==typeof t){let e=historyKeys.get(t);return e||(historyKeySeq+=1,e=`hist-${historyKeySeq}`,historyKeys.set(t,e)),e}return"default"}function isStatedKey(e){const t=e&&"object"==typeof e?e:{},n=t.sessionKey||t.sessionId||t.chatId||t.threadId||t.conversationId;return!("string"!=typeof n||!n.trim())||"string"==typeof t.cwd&&t.cwd.trim().length>0}function bonus(e){const t=Number.isFinite(e)&&e>0?e:0;return Math.max(4,Math.ceil(t/4))}function peek(e,t=Date.now()){return prune(t),entries.get(e)||null}function take(e,t=Date.now()){prune(t);const n=entries.get(e);return n?(entries.delete(e),n):null}function adopt({now:e=Date.now(),maxAgeMs:t=6e5}={}){prune(e);let n=null,r=null;for(const[s,i]of entries)e-i.at>t||(!r||i.at>r.at)&&(r=i,n=s);return r?(entries.delete(n),{key:n,entry:r}):null}function record(e,{rounds:t,tokens:n,note:r,chain:s,messages:i,added:o}={},a=Date.now()){prune(a);const u=entries.get(e),d={rounds:Number.isFinite(t)?t:0,tokens:Number.isFinite(n)?n:0,note:"string"==typeof r?r:"",at:a,interruptions:(Number.isFinite(s)?s:u&&u.interruptions)||0,messages:Array.isArray(i)?i.slice():[],added:Array.isArray(o)?o.slice():[]};return d.interruptions+=1,entries.delete(e),entries.set(e,d),prune(a),d}function resumePreamble(e){return`[session resume] The previous turn in this conversation was cut off at ${e&&e.rounds?e.rounds:"the previous turn's"} tool rounds${e&&e.tokens?` (${e.tokens.toLocaleString()} tokens)`:""} because it reached the round horizon, so the work it started is unfinished. Continue that work now: do not restart, do not re-do steps that already completed, and do not treat the interruption as a failure to report. Pick up the next unfinished step and finish with a written answer.`}function state(e=Date.now()){return prune(e),{size:entries.size,ttlMs:TTL_MS,maxEntries:MAX_ENTRIES,entries:[...entries].map((([e,t])=>({key:e,...t})))}}function reset(){return entries.clear(),entries.size}module.exports={TTL_MS:TTL_MS,MAX_ENTRIES:MAX_ENTRIES,keyFor:keyFor,isStatedKey:isStatedKey,bonus:bonus,peek:peek,take:take,adopt:adopt,record:record,resumePreamble:resumePreamble,state:state,reset:reset};
3
+ "use strict";const TTL_MS=18e5,MAX_ENTRIES=64,entries=new Map,historyKeys=new WeakMap;let historyKeySeq=0;function prune(e=Date.now()){for(const[t,n]of entries)e-n.at>TTL_MS&&entries.delete(t);for(;entries.size>64;){const e=entries.keys().next();if(e.done)break;entries.delete(e.value)}return entries.size}function keyFor(e,t){const n=e&&"object"==typeof e?e:{},r=n.sessionKey||n.sessionId||n.chatId||n.threadId||n.conversationId;if("string"==typeof r&&r.trim())return`s:${r.trim()}`;if("string"==typeof n.cwd&&n.cwd.trim())return`cwd:${n.cwd.trim()}`;if(t&&"object"==typeof t){let e=historyKeys.get(t);return e||(historyKeySeq+=1,e=`hist-${historyKeySeq}`,historyKeys.set(t,e)),e}return"default"}function isStatedKey(e){const t=e&&"object"==typeof e?e:{},n=t.sessionKey||t.sessionId||t.chatId||t.threadId||t.conversationId;return!("string"!=typeof n||!n.trim())||"string"==typeof t.cwd&&t.cwd.trim().length>0}function bonus(e){const t=Number.isFinite(e)&&e>0?e:0;return Math.max(4,Math.ceil(t/4))}function peek(e,t=Date.now()){return prune(t),entries.get(e)||null}function take(e,t=Date.now()){prune(t);const n=entries.get(e);return n?(entries.delete(e),n):null}function adopt({now:e=Date.now(),maxAgeMs:t=6e5}={}){prune(e);let n=null,r=null;for(const[s,i]of entries)e-i.at>t||(!r||i.at>r.at)&&(r=i,n=s);return r?(entries.delete(n),{key:n,entry:r}):null}function record(e,{rounds:t,tokens:n,note:r,chain:s,messages:i,added:o}={},a=Date.now()){prune(a);const u=entries.get(e),d={rounds:Number.isFinite(t)?t:0,tokens:Number.isFinite(n)?n:0,note:"string"==typeof r?r:"",at:a,interruptions:(Number.isFinite(s)?s:u&&u.interruptions)||0,messages:Array.isArray(i)?i.slice():[],added:Array.isArray(o)?o.slice():[]};return d.interruptions+=1,entries.delete(e),entries.set(e,d),prune(a),d}function resumePreamble(e){return`[session resume] The previous turn in this conversation was cut off at ${e&&e.rounds?e.rounds:"the previous turn's"} tool rounds${e&&e.tokens?` (${e.tokens.toLocaleString()} tokens)`:""} because it reached the round horizon, so the work it started is unfinished. Continue that work now: do not restart, do not re-do steps that already completed, and do not treat the interruption as a failure to report. Pick up the next unfinished step and finish with a written answer.`}function state(e=Date.now()){return prune(e),{size:entries.size,ttlMs:TTL_MS,maxEntries:64,entries:[...entries].map(([e,t])=>({key:e,...t}))}}function reset(){return entries.clear(),entries.size}module.exports={TTL_MS:TTL_MS,MAX_ENTRIES:64,keyFor:keyFor,isStatedKey:isStatedKey,bonus:bonus,peek:peek,take:take,adopt:adopt,record:record,resumePreamble:resumePreamble,state:state,reset:reset};
@@ -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"),SPILL_MAX_FILES=40;let spillDir=null,spillCount=0;function spill(t){try{if(spillCount>=SPILL_MAX_FILES)return null;spillDir||(spillDir=fs.mkdtempSync(path.join(os.tmpdir(),"aegiscode-tool-"))),spillCount+=1;const l=path.join(spillDir,`output-${spillCount}.txt`);return fs.writeFileSync(l,String(t),"utf8"),l}catch{return null}}function cap(t,l){const n=String(null==t?"":t);if(n.length<=l)return n;const i=n.slice(0,l),r=spill(n);return r?`${i}\n… (truncated after ${l} of ${n.length} chars — full output: ${r} — grep or readFile that path)`:`${i}\n… (truncated)`}module.exports={spill:spill,cap:cap,SPILL_MAX_FILES:SPILL_MAX_FILES};
3
+ "use strict";const fs=require("node:fs"),os=require("node:os"),path=require("node:path"),SPILL_MAX_FILES=40;let spillDir=null,spillCount=0;function spill(t){try{if(spillCount>=40)return null;spillDir||(spillDir=fs.mkdtempSync(path.join(os.tmpdir(),"aegiscode-tool-"))),spillCount+=1;const l=path.join(spillDir,`output-${spillCount}.txt`);return fs.writeFileSync(l,String(t),"utf8"),l}catch{return null}}function cap(t,l){const n=String(null==t?"":t);if(n.length<=l)return n;const i=n.slice(0,l),r=spill(n);return r?`${i}\n… (truncated after ${l} of ${n.length} chars — full output: ${r} — grep or readFile that path)`:`${i}\n… (truncated)`}module.exports={spill:spill,cap:cap,SPILL_MAX_FILES:40};
@@ -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{gitRoot:gitRoot,gitStatusSnapshot:gitStatusSnapshot}=require("./git-scope.js"),GIT_FLAGS_WITH_ARG=new Set(["-C","-c","--git-dir","--work-tree","--namespace","--exec-path"]);function tokenize(t){const e=[];for(const n of String(t||"").split(/[|;&\n]+/)){const t=[],r=/"([^"]*)"|'([^']*)'|(\S+)/g;let s;for(;s=r.exec(n);)t.push(s[1]??s[2]??s[3]);t.length&&e.push(t)}return e}function gitInvocation(t){const e=t.findIndex((t=>"git"===t||t.endsWith("/git")));if(-1===e)return null;let n=e+1;for(;n<t.length&&t[n].startsWith("-");)n+=GIT_FLAGS_WITH_ARG.has(t[n])?2:1;return n>=t.length?null:{sub:t[n],args:t.slice(n+1)}}function namedPaths(t){const e=t.indexOf("--");return-1!==e?t.slice(e+1).filter((t=>!t.startsWith("-"))):t.filter((t=>!t.startsWith("-")))}const isTreeMark=t=>"."===t||"./"===t||"*"===t||"./*"===t,hasForce=t=>t.some((t=>"-f"===t||"--force"===t||/^-[a-zA-Z]*f/.test(t)));function judge(t,e){const n=namedPaths(e),r=0===n.length||n.some(isTreeMark);switch(t){case"checkout":return e.includes("--")||hasForce(e)?{what:"checkout of uncommitted changes",scope:r?"tree":"paths",paths:n}:r&&n.length?{what:"checkout . (tree-wide restore)",scope:"tree",paths:n}:null;case"restore":return{what:"restore (discards uncommitted changes)",scope:r?"tree":"paths",paths:n};case"reset":return e.includes("--hard")?{what:"reset --hard",scope:"tree",paths:[]}:null;case"clean":return hasForce(e)?{what:"clean -f (deletes untracked files)",scope:"tree",paths:[]}:null;case"stash":{const t=e.find((t=>!t.startsWith("-")));return"list"===t||"show"===t?null:{what:`stash ${t||"push"} (uncommitted changes across the tree)`,scope:"tree",paths:[]}}case"worktree":{const t=e.find((t=>!t.startsWith("-")));return"remove"===t||"prune"===t?{what:`worktree ${t}`,scope:"tree",paths:[]}:null}default:return null}}function classifyDestructive(t){for(const e of tokenize(t)){const t=gitInvocation(e);if(!t)continue;const n=judge(t.sub,t.args);if(n)return{destructive:!0,...n}}return{destructive:!1}}function beginTurnGuard(t){const e=gitRoot(t),n=e?gitStatusSnapshot(t):null;return{root:e,cwd:t,before:n,startedAt:Date.now(),written:new Set,active:Boolean(e&&n)}}function toRel(t,e){let n=String(e||"");return n?(t.root&&n.startsWith(t.root)&&(n=n.slice(t.root.length).replace(/^[/\\]/,"")),n.split("\\").join("/")):null}function recordWrite(t,e){if(!t||!t.active)return;const n=toRel(t,e);n&&t.written.add(n)}function foreignSince(t){if(!t||!t.active)return[];const e=gitStatusSnapshot(t.cwd);if(!e)return[];const n=[];for(const[r,s]of e)t.written.has(r)||t.before.has(r)&&t.before.get(r)===s&&n.push(r);return n.sort()}function concurrentSince(t){if(!t||!t.active)return[];const e=gitStatusSnapshot(t.cwd);if(!e)return[];const n=[];for(const[r]of e)t.written.has(r)||t.before.has(r)||n.push(r);return n.sort()}function blocksDestructive(t,e){const n=classifyDestructive(e);if(!n.destructive)return{ok:!0};if(!t||!t.active)return{ok:!0};let r=foreignSince(t),s=concurrentSince(t).filter((t=>!r.includes(t))),o=[];if("tree"===n.scope)o=[...r,...s];else{const t=new Set(n.paths.map((t=>t.replace(/^\.\//,"")))),e=e=>e.filter((e=>t.has(e)||t.has("./"+e)));r=e(r),s=e(s),o=[...r,...s]}if(!o.length)return{ok:!0,what:n.what};const i=[];return r.length&&i.push(`${r.length} hold another agent's uncommitted work: `+r.slice(0,8).join(", ")+(r.length>8?` (+${r.length-8} more)`:"")),s.length&&i.push(`${s.length} changed since this turn began and were not written by this session: ${s.slice(0,8).join(", ")}`+(s.length>8?` (+${s.length-8} more)`:"")),{ok:!1,what:n.what,scope:n.scope,foreign:r,unattributed:s,reason:`refusing \`${n.what}\` in ${t.root}: `+("tree"===n.scope?"it is tree-scoped and would discard work it did not create — ":"it targets a path that is not yours to discard — ")+i.join("; ")+". Name only the paths you mean, or take the worktree lock first."}}module.exports={classifyDestructive:classifyDestructive,beginTurnGuard:beginTurnGuard,recordWrite:recordWrite,foreignSince:foreignSince,concurrentSince:concurrentSince,blocksDestructive:blocksDestructive};
3
+ "use strict";const{gitRoot:gitRoot,gitStatusSnapshot:gitStatusSnapshot}=require("./git-scope.js"),GIT_FLAGS_WITH_ARG=new Set(["-C","-c","--git-dir","--work-tree","--namespace","--exec-path"]);function tokenize(t){const e=[];for(const n of String(t||"").split(/[|;&\n]+/)){const t=[],r=/"([^"]*)"|'([^']*)'|(\S+)/g;let s;for(;s=r.exec(n);)t.push(s[1]??s[2]??s[3]);t.length&&e.push(t)}return e}function gitInvocation(t){const e=t.findIndex(t=>"git"===t||t.endsWith("/git"));if(-1===e)return null;let n=e+1;for(;n<t.length&&t[n].startsWith("-");)n+=GIT_FLAGS_WITH_ARG.has(t[n])?2:1;return n>=t.length?null:{sub:t[n],args:t.slice(n+1)}}function namedPaths(t){const e=t.indexOf("--");return-1!==e?t.slice(e+1).filter(t=>!t.startsWith("-")):t.filter(t=>!t.startsWith("-"))}const isTreeMark=t=>"."===t||"./"===t||"*"===t||"./*"===t,hasForce=t=>t.some(t=>"-f"===t||"--force"===t||/^-[a-zA-Z]*f/.test(t));function judge(t,e){const n=namedPaths(e),r=0===n.length||n.some(isTreeMark);switch(t){case"checkout":return e.includes("--")||hasForce(e)?{what:"checkout of uncommitted changes",scope:r?"tree":"paths",paths:n}:r&&n.length?{what:"checkout . (tree-wide restore)",scope:"tree",paths:n}:null;case"restore":return{what:"restore (discards uncommitted changes)",scope:r?"tree":"paths",paths:n};case"reset":return e.includes("--hard")?{what:"reset --hard",scope:"tree",paths:[]}:null;case"clean":return hasForce(e)?{what:"clean -f (deletes untracked files)",scope:"tree",paths:[]}:null;case"stash":{const t=e.find(t=>!t.startsWith("-"));return"list"===t||"show"===t?null:{what:`stash ${t||"push"} (uncommitted changes across the tree)`,scope:"tree",paths:[]}}case"worktree":{const t=e.find(t=>!t.startsWith("-"));return"remove"===t||"prune"===t?{what:`worktree ${t}`,scope:"tree",paths:[]}:null}default:return null}}function classifyDestructive(t){for(const e of tokenize(t)){const t=gitInvocation(e);if(!t)continue;const n=judge(t.sub,t.args);if(n)return{destructive:!0,...n}}return{destructive:!1}}function beginTurnGuard(t){const e=gitRoot(t),n=e?gitStatusSnapshot(t):null;return{root:e,cwd:t,before:n,startedAt:Date.now(),written:new Set,active:Boolean(e&&n)}}function toRel(t,e){let n=String(e||"");return n?(t.root&&n.startsWith(t.root)&&(n=n.slice(t.root.length).replace(/^[/\\]/,"")),n.split("\\").join("/")):null}function recordWrite(t,e){if(!t||!t.active)return;const n=toRel(t,e);n&&t.written.add(n)}function foreignSince(t){if(!t||!t.active)return[];const e=gitStatusSnapshot(t.cwd);if(!e)return[];const n=[];for(const[r,s]of e)t.written.has(r)||t.before.has(r)&&t.before.get(r)===s&&n.push(r);return n.sort()}function concurrentSince(t){if(!t||!t.active)return[];const e=gitStatusSnapshot(t.cwd);if(!e)return[];const n=[];for(const[r]of e)t.written.has(r)||t.before.has(r)||n.push(r);return n.sort()}function blocksDestructive(t,e){const n=classifyDestructive(e);if(!n.destructive)return{ok:!0};if(!t||!t.active)return{ok:!0};let r=foreignSince(t),s=concurrentSince(t).filter(t=>!r.includes(t)),o=[];if("tree"===n.scope)o=[...r,...s];else{const t=new Set(n.paths.map(t=>t.replace(/^\.\//,""))),e=e=>e.filter(e=>t.has(e)||t.has("./"+e));r=e(r),s=e(s),o=[...r,...s]}if(!o.length)return{ok:!0,what:n.what};const i=[];return r.length&&i.push(`${r.length} hold another agent's uncommitted work: `+r.slice(0,8).join(", ")+(r.length>8?` (+${r.length-8} more)`:"")),s.length&&i.push(`${s.length} changed since this turn began and were not written by this session: ${s.slice(0,8).join(", ")}`+(s.length>8?` (+${s.length-8} more)`:"")),{ok:!1,what:n.what,scope:n.scope,foreign:r,unattributed:s,reason:`refusing \`${n.what}\` in ${t.root}: `+("tree"===n.scope?"it is tree-scoped and would discard work it did not create — ":"it targets a path that is not yours to discard — ")+i.join("; ")+". Name only the paths you mean, or take the worktree lock first."}}module.exports={classifyDestructive:classifyDestructive,beginTurnGuard:beginTurnGuard,recordWrite:recordWrite,foreignSince:foreignSince,concurrentSince:concurrentSince,blocksDestructive:blocksDestructive};
@@ -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 CODE_EXT=new Set([".js",".mjs",".cjs",".jsx",".ts",".tsx",".mts",".cts",".py",".rb",".go",".rs",".java",".kt",".kts",".scala",".swift",".c",".h",".cc",".cpp",".hpp",".cxx",".hh",".m",".mm",".cs",".fs",".php",".pl",".pm",".lua",".r",".jl",".dart",".ex",".exs",".erl",".hrl",".hs",".clj",".cljs",".ml",".mli",".sh",".bash",".zsh",".fish",".ps1",".sql",".vue",".svelte",".zig",".nim",".cr",".v",".sv",".sol",".tf"]),EXEC_TOOLS=new Set(["exec"]),NUDGE="You edited %s and the turn is ending, but no command has been run since that edit. Editing a file proves it compiles no more than describing it did. Run the project's check now — its tests, a type check, or at minimum the file's own linter — and report what it printed. If you already know the change cannot be checked by a command (a comment, a docs string, a config value), say so explicitly and finish; do not claim the change \"works\" without evidence.",NUDGE_WITH_CMD='You edited %s and the turn is ending, but no command has been run since that edit. Editing a file proves it compiles no more than describing it did. The check for this repo is likely `%s` (%s) — run it and report what it printed. If you disagree with that command, run what actually checks this change. If the change cannot be checked by a command (a comment, a docs string, a config value), say so explicitly and finish; do not claim the change "works" without evidence.',MODES=new Set(["off","dark","enforce"]);function resolveMode(e){const t=String(e&&e.mode||"").trim().toLowerCase();if(MODES.has(t))return t;const n=String(process.env.AEGIS_VERIFY_STOP||"").trim().toLowerCase();return MODES.has(n)?n:"dark"}function beginVerifyGuard(e){const t=resolveMode(e);return{mode:t,cwd:e&&e.cwd||null,active:"off"!==t,dirty:[],ranSince:!1,nudged:!1,fired:0}}function extOf(e){const t=String(e||"").split(/[/\\]/).pop()||"",n=t.lastIndexOf(".");return n<=0?"":t.slice(n).toLowerCase()}function isCodePath(e){return CODE_EXT.has(extOf(e))}function recordMutation(e,t){e&&e.active&&isCodePath(t)&&(e.dirty.push(String(t)),e.ranSince=!1)}function recordExec(e){e&&e.active&&(e.ranSince=!0,e.dirty=[])}function shouldNudge(e){if(!e||!e.active)return{nudge:!1};if(!e.dirty.length)return{nudge:!1};if(e.ranSince)return{nudge:!1};if(e.nudged)return{nudge:!1};const t=e.dirty.slice(-3),n=t.join(", ")+(e.dirty.length>3?` (+${e.dirty.length-3} more)`:"");if(e.fired=1,"enforce"!==e.mode)return{nudge:!1,fired:!0,paths:t};e.nudged=!0;let i=null;if(e.cwd)try{const{detectCheckCommand:t}=require("./check-command.js");i=t(e.cwd,e.dirty[e.dirty.length-1])}catch{i=null}if(i){const e=[n,i.cmd,i.why];let r=0;return{nudge:!0,text:NUDGE_WITH_CMD.replace(/%s/g,(()=>String(e[r++]))),paths:t,cmd:i.cmd}}return{nudge:!0,text:NUDGE.replace("%s",n),paths:t}}module.exports={beginVerifyGuard:beginVerifyGuard,recordMutation:recordMutation,recordExec:recordExec,shouldNudge:shouldNudge,resolveMode:resolveMode,isCodePath:isCodePath,extOf:extOf,EXEC_TOOLS:EXEC_TOOLS,CODE_EXT:CODE_EXT,NUDGE:NUDGE};
3
+ "use strict";const CODE_EXT=new Set([".js",".mjs",".cjs",".jsx",".ts",".tsx",".mts",".cts",".py",".rb",".go",".rs",".java",".kt",".kts",".scala",".swift",".c",".h",".cc",".cpp",".hpp",".cxx",".hh",".m",".mm",".cs",".fs",".php",".pl",".pm",".lua",".r",".jl",".dart",".ex",".exs",".erl",".hrl",".hs",".clj",".cljs",".ml",".mli",".sh",".bash",".zsh",".fish",".ps1",".sql",".vue",".svelte",".zig",".nim",".cr",".v",".sv",".sol",".tf"]),EXEC_TOOLS=new Set(["exec"]),NUDGE="You edited %s and the turn is ending, but no command has been run since that edit. Editing a file proves it compiles no more than describing it did. Run the project's check now — its tests, a type check, or at minimum the file's own linter — and report what it printed. If you already know the change cannot be checked by a command (a comment, a docs string, a config value), say so explicitly and finish; do not claim the change \"works\" without evidence.",NUDGE_WITH_CMD='You edited %s and the turn is ending, but no command has been run since that edit. Editing a file proves it compiles no more than describing it did. The check for this repo is likely `%s` (%s) — run it and report what it printed. If you disagree with that command, run what actually checks this change. If the change cannot be checked by a command (a comment, a docs string, a config value), say so explicitly and finish; do not claim the change "works" without evidence.',MODES=new Set(["off","dark","enforce"]);function resolveMode(e){const t=String(e&&e.mode||"").trim().toLowerCase();if(MODES.has(t))return t;const n=String(process.env.AEGIS_VERIFY_STOP||"").trim().toLowerCase();return MODES.has(n)?n:"dark"}function beginVerifyGuard(e){const t=resolveMode(e);return{mode:t,cwd:e&&e.cwd||null,active:"off"!==t,dirty:[],ranSince:!1,nudged:!1,fired:0}}function extOf(e){const t=String(e||"").split(/[/\\]/).pop()||"",n=t.lastIndexOf(".");return n<=0?"":t.slice(n).toLowerCase()}function isCodePath(e){return CODE_EXT.has(extOf(e))}function recordMutation(e,t){e&&e.active&&isCodePath(t)&&(e.dirty.push(String(t)),e.ranSince=!1)}function recordExec(e){e&&e.active&&(e.ranSince=!0,e.dirty=[])}function shouldNudge(e){if(!e||!e.active)return{nudge:!1};if(!e.dirty.length)return{nudge:!1};if(e.ranSince)return{nudge:!1};if(e.nudged)return{nudge:!1};const t=e.dirty.slice(-3),n=t.join(", ")+(e.dirty.length>3?` (+${e.dirty.length-3} more)`:"");if(e.fired=1,"enforce"!==e.mode)return{nudge:!1,fired:!0,paths:t};e.nudged=!0;let i=null;if(e.cwd)try{const{detectCheckCommand:t}=require("./check-command.js");i=t(e.cwd,e.dirty[e.dirty.length-1])}catch{i=null}if(i){const e=[n,i.cmd,i.why];let r=0;return{nudge:!0,text:NUDGE_WITH_CMD.replace(/%s/g,()=>String(e[r++])),paths:t,cmd:i.cmd}}return{nudge:!0,text:NUDGE.replace("%s",n),paths:t}}module.exports={beginVerifyGuard:beginVerifyGuard,recordMutation:recordMutation,recordExec:recordExec,shouldNudge:shouldNudge,resolveMode:resolveMode,isCodePath:isCodePath,extOf:extOf,EXEC_TOOLS:EXEC_TOOLS,CODE_EXT:CODE_EXT,NUDGE:NUDGE};
@@ -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");function worktreeLockDir(){if(process.env.AEGISCODE_WORKTREE_LOCK_DIR)return process.env.AEGISCODE_WORKTREE_LOCK_DIR;if(process.env.AEGISCODEX_WORKTREE_LOCK_DIR)return process.env.AEGISCODEX_WORKTREE_LOCK_DIR;const r=process.env.AEGISCODE_HOME||process.env.AEGISCODEX_HOME||path.join(os.homedir(),".aegiscode");return path.join(r,"worktree-locks")}const DEFAULT_WORKTREE_WAIT_MS=66e4,NOOP_TOKEN="(no-worktree)";function canonical(r){if(!r)return null;const e=path.resolve(String(r));try{return fs.realpathSync(e)}catch{return e}}function worktreeLockPath(r){if(!r)return null;const e=crypto.createHash("sha1").update(canonical(r)).digest("hex").slice(0,16);return path.join(worktreeLockDir(),e+".lock")}function pidAlive(r){try{return process.kill(r,0),!0}catch{return!1}}function readHolder(r){try{return JSON.parse(fs.readFileSync(worktreeLockPath(r),"utf8"))}catch{return null}}function worktreeLockHolder(r){if(!r)return null;const e=readHolder(r);return e?{pid:e.pid,token:e.token,since:e.since,root:e.root||canonical(r),session:e.session||null}:null}function isWorktreeLocked(r){if(!r)return!1;const e=readHolder(r),o=Number(e&&e.pid);if(!Number.isInteger(o)||o<=0||!pidAlive(o)){try{fs.unlinkSync(worktreeLockPath(r))}catch{}return!1}return!0}function tryAcquire(r,e,o){try{fs.mkdirSync(worktreeLockDir(),{recursive:!0});const t=fs.openSync(worktreeLockPath(r),"wx");return fs.writeFileSync(t,JSON.stringify({pid:process.pid,token:e,since:Date.now(),root:canonical(r),session:o&&o.session||null})),fs.closeSync(t),!0}catch(r){return!r||"EEXIST"!==r.code}}function releaseWorktreeLock(r,e){if(!r||!e||e===NOOP_TOKEN)return;const o=readHolder(r);if(o&&o.token===e)try{fs.unlinkSync(worktreeLockPath(r))}catch{}}async function acquireWorktreeLock(r,{waitMs:e=DEFAULT_WORKTREE_WAIT_MS,pollMs:o=200,signal:t,session:n=null}={}){if(!r)return NOOP_TOKEN;const c=crypto.randomUUID(),i=Date.now()+e;for(;;){if(t&&t.aborted)return null;if(tryAcquire(r,c,{session:n}))return c;if(isWorktreeLocked(r)){if(Date.now()>=i)return null;await new Promise((r=>setTimeout(r,o)))}}}class WorktreeBusyError extends Error{constructor(r,e){super(`working tree ${r} is locked by pid ${e?e.pid:"?"}`),this.name="WorktreeBusyError",this.root=r,this.holder=e||null}}async function withWorktreeLock(r,e,o){const t=await acquireWorktreeLock(r,e);if(!t)throw new WorktreeBusyError(r,worktreeLockHolder(r));try{return await o()}finally{releaseWorktreeLock(r,t)}}module.exports={DEFAULT_WORKTREE_WAIT_MS:DEFAULT_WORKTREE_WAIT_MS,worktreeLockDir:worktreeLockDir,worktreeLockPath:worktreeLockPath,worktreeLockHolder:worktreeLockHolder,isWorktreeLocked:isWorktreeLocked,releaseWorktreeLock:releaseWorktreeLock,acquireWorktreeLock:acquireWorktreeLock,WorktreeBusyError:WorktreeBusyError,withWorktreeLock:withWorktreeLock};
3
+ "use strict";const fs=require("node:fs"),path=require("node:path"),os=require("node:os"),crypto=require("node:crypto");function worktreeLockDir(){if(process.env.AEGISCODE_WORKTREE_LOCK_DIR)return process.env.AEGISCODE_WORKTREE_LOCK_DIR;if(process.env.AEGISCODEX_WORKTREE_LOCK_DIR)return process.env.AEGISCODEX_WORKTREE_LOCK_DIR;const r=process.env.AEGISCODE_HOME||process.env.AEGISCODEX_HOME||path.join(os.homedir(),".aegiscode");return path.join(r,"worktree-locks")}const DEFAULT_WORKTREE_WAIT_MS=66e4,NOOP_TOKEN="(no-worktree)";function canonical(r){if(!r)return null;const e=path.resolve(String(r));try{return fs.realpathSync(e)}catch{return e}}function worktreeLockPath(r){if(!r)return null;const e=crypto.createHash("sha1").update(canonical(r)).digest("hex").slice(0,16);return path.join(worktreeLockDir(),e+".lock")}function pidAlive(r){try{return process.kill(r,0),!0}catch{return!1}}function readHolder(r){try{return JSON.parse(fs.readFileSync(worktreeLockPath(r),"utf8"))}catch{return null}}function worktreeLockHolder(r){if(!r)return null;const e=readHolder(r);return e?{pid:e.pid,token:e.token,since:e.since,root:e.root||canonical(r),session:e.session||null}:null}function isWorktreeLocked(r){if(!r)return!1;const e=readHolder(r),o=Number(e&&e.pid);if(!Number.isInteger(o)||o<=0||!pidAlive(o)){try{fs.unlinkSync(worktreeLockPath(r))}catch{}return!1}return!0}function tryAcquire(r,e,o){try{fs.mkdirSync(worktreeLockDir(),{recursive:!0});const t=fs.openSync(worktreeLockPath(r),"wx");return fs.writeFileSync(t,JSON.stringify({pid:process.pid,token:e,since:Date.now(),root:canonical(r),session:o&&o.session||null})),fs.closeSync(t),!0}catch(r){return!r||"EEXIST"!==r.code}}function releaseWorktreeLock(r,e){if(!r||!e||e===NOOP_TOKEN)return;const o=readHolder(r);if(o&&o.token===e)try{fs.unlinkSync(worktreeLockPath(r))}catch{}}async function acquireWorktreeLock(r,{waitMs:e=66e4,pollMs:o=200,signal:t,session:n=null}={}){if(!r)return NOOP_TOKEN;const c=crypto.randomUUID(),i=Date.now()+e;for(;;){if(t&&t.aborted)return null;if(tryAcquire(r,c,{session:n}))return c;if(isWorktreeLocked(r)){if(Date.now()>=i)return null;await new Promise(r=>setTimeout(r,o))}}}class WorktreeBusyError extends Error{constructor(r,e){super(`working tree ${r} is locked by pid ${e?e.pid:"?"}`),this.name="WorktreeBusyError",this.root=r,this.holder=e||null}}async function withWorktreeLock(r,e,o){const t=await acquireWorktreeLock(r,e);if(!t)throw new WorktreeBusyError(r,worktreeLockHolder(r));try{return await o()}finally{releaseWorktreeLock(r,t)}}module.exports={DEFAULT_WORKTREE_WAIT_MS:66e4,worktreeLockDir:worktreeLockDir,worktreeLockPath:worktreeLockPath,worktreeLockHolder:worktreeLockHolder,isWorktreeLocked:isWorktreeLocked,releaseWorktreeLock:releaseWorktreeLock,acquireWorktreeLock:acquireWorktreeLock,WorktreeBusyError:WorktreeBusyError,withWorktreeLock:withWorktreeLock};
@@ -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"),{execFileSync:execFileSync}=require("node:child_process"),prefs=(()=>{try{return require("../../client/prefs.js")}catch{return require("../vendor/prefs.js")}})(),credentials=(()=>{try{return require("../../client/credentials.js")}catch{return require("../vendor/credentials.js")}})(),localTransport=require("./local/local.js"),LOCAL_NAMESPACE="local",SETTINGS_FILE="settings.json",AEGIS_KEY_NAMESPACE="__aegis",LEGACY_AEGIS_NAMESPACE="aegis",QUICK_LAUNCHER_NAMESPACE="__quickLauncher",DEFAULT_QUICK_LAUNCHER_SHORTCUT="CmdOrCtrl+Shift+Space",VAULT_BACKEND_NAMESPACE="__vaultBackend",DEFAULT_VAULT_BACKEND="aegiscloud",VAULT_BACKEND_VALUES=Object.freeze(["aegiscloud","drive","off"]),CONFIRM_MODE_NAMESPACE="__confirmMode",FONT_SCALE_NAMESPACE="__fontScale",ACCENT_NAMESPACE="__accent",MEMORY_PERSIST_NAMESPACE="__memoryPersist",AVATAR_NAMESPACE="__avatar",TELEMETRY_NAMESPACE="__telemetry",AUTO_DRAIN_NAMESPACE="__autoDrain",AUTO_MINT_NAMESPACE="__autoMint",AUTO_DRAIN_INTERVAL_DEFAULT_MS=6e4,AUTO_DRAIN_INTERVAL_MIN_MS=15e3,AUTO_DRAIN_INTERVAL_MAX_MS=18e5,RESERVED_NAMESPACES=Object.freeze(["__aegis","aegis","__quickLauncher","__vaultBackend","__confirmMode","__memoryPersist","__avatar","__telemetry","__autoDrain","__autoMint"]),AVATAR_MOTION_MODES=Object.freeze(["system","full","minimal"]);function isReservedNamespace(e){return RESERVED_NAMESPACES.includes(e)}function maskKey(e){return e?e.length<=10?"configured":`${e.slice(0,9)}…${e.slice(-4)}`:null}const IS_WIN32="win32"===process.platform;function restrictFile(e){if(IS_WIN32){const n=process.env.USERNAME||process.env.USER||process.env.USERDOMAIN;if(!n)return void console.error(`[settings] cannot restrict ${e}: no current user to grant (USERNAME unset)`);try{execFileSync("icacls",[e,"/inheritance:r","/grant:r",`${n}:(F)`],{stdio:"ignore"})}catch(n){console.error(`[settings] failed to restrict ACL on ${e}: ${n.message}`)}}else try{fs.chmodSync(e,384)}catch(n){console.error(`[settings] failed to chmod ${e} to 0600: ${n.message}`)}}function createSettingsStore({dir:e,safeStorage:n,prefsDir:t,env:r}={}){if(!e)throw new Error("createSettingsStore requires a storage dir");const o=path.join(e,SETTINGS_FILE),i=(()=>{const e=null==t?"":String(t).trim();return e?path.resolve(e):credentials.aegisHome(r)})(),s=(()=>{try{return prefs.adopt({dir:i,legacyDir:e})}catch(e){return(process.env.AEGISCODE_DEBUG||process.env.AEGIS_HIST_DEBUG)&&process.stderr.write(`aegis-desktop: shared-preference adoption failed: ${e.message}\n`),{adopted:!1,keys:[],reason:`adoption failed: ${e.message}`}}})();function a(){try{return prefs.load({dir:i})}catch{return{}}}function c(e){if(!prefs.SHARED_PREF_KEYS.includes(e))throw new Error(`"${e}" is not a shared preference (see client/prefs.js SHARED_PREF_KEYS)`);const n=a()[e];return void 0===n?null:n}const u=()=>Boolean(n&&"function"==typeof n.isEncryptionAvailable&&n.isEncryptionAvailable());function l(e){return null==e?null:u()?n.encryptString(String(e)).toString("base64"):Buffer.from(String(e),"utf8").toString("base64")}function _(e){if(!e)return null;try{const t=Buffer.from(String(e),"base64");return u()?n.decryptString(t):t.toString("utf8")}catch{return null}}function d(){try{return JSON.parse(fs.readFileSync(o,"utf8"))||{}}catch{return{}}}function f(e){fs.mkdirSync(path.dirname(o),{recursive:!0});const n=`${o}.tmp-${process.pid}`;fs.writeFileSync(n,JSON.stringify(e,null,2),{mode:384}),fs.renameSync(n,o),restrictFile(o)}function A(e){if(isReservedNamespace(e))throw new Error(`reserved namespace "${e}" is not a provider config — use setAegisKey()/aegisRawKey() for the AEGIS key`)}function E(e){const n=d()[e]||{},t=_(n.key);return{provider:e,baseURL:n.baseURL||"",configured:Boolean(t),keyMask:maskKey(t)}}function S(){const e=_((d().__aegis||{}).key);return{configured:Boolean(e),keyMask:maskKey(e)}}function m(e){return Number.isFinite(e)?Math.min(1.3,Math.max(.85,Math.round(100*e)/100)):1}function M(){return m((d().__fontScale||{}).scale)}const p=["default","cobalt","amber"];function g(e){const n="string"==typeof e?e.trim().toLowerCase():"";return p.includes(n)?n:"default"}function y(){return g((d().__accent||{}).name)}function N(){const e=d().__quickLauncher||{},n="string"==typeof e.shortcut&&e.shortcut.trim()?e.shortcut.trim():"CmdOrCtrl+Shift+Space";return{enabled:Boolean(e.enabled),shortcut:n}}function b(){const e=d().__vaultBackend||{};return{backend:VAULT_BACKEND_VALUES.includes(e.backend)?e.backend:"aegiscloud"}}function v(){const e=a();if("boolean"==typeof e.confirmMode)return{enabled:e.confirmMode,source:"config"};const n=d().__confirmMode||{};return void 0===n.enabled?{enabled:!0,source:"default"}:{enabled:Boolean(n.enabled),source:"config"}}function C(){const e=a().sandboxPolicy;return e&&"object"==typeof e?e:null}function T(){return!0===a().devMode}function h(){const e=a().accountUsername;return"string"==typeof e?e:null}function R(){const e=a();return"string"==typeof e.permissionMode?e.permissionMode:null}function I(){return!0===(d().__telemetry||{}).enabled}function L(){const e=a();if("boolean"==typeof e.memoryPersist)return{enabled:e.memoryPersist,source:"config"};const n=d().__memoryPersist||{};return void 0===n.enabled?{enabled:!0,source:"default"}:{enabled:Boolean(n.enabled),source:"config"}}function D(){const e=d().__avatar||{};return{enabled:void 0===e.enabled||Boolean(e.enabled),showLevel:void 0===e.showLevel||Boolean(e.showLevel),motion:AVATAR_MOTION_MODES.includes(e.motion)?e.motion:"system"}}function P(){const e=d().__avatar||{};return{...D(),source:void 0===e.enabled?"default":"config"}}function O(e){const n=Number(e);if(!Number.isFinite(n))return 6e4;const t=Math.round(n);return t<15e3||t>18e5?6e4:t}function U(){const e=d().__autoDrain||{};return{enabled:!1!==e.enabled,intervalMs:O(e.intervalMs)}}function k(){const e=d().__autoDrain||{};return{...U(),source:void 0===e.enabled?"default":"config"}}function B(){const e=d().__autoMint||{};return{enabled:!1!==e.enabled,publish:!0===e.publish}}function K(){const e=d().__autoMint||{};return{...B(),source:void 0===e.enabled?"default":"config"}}return{file:o,sharedDir:i,adoption:s,sharedFile:function(){return prefs.prefsFile({dir:i})},getSharedPref:c,setSharedPref:function(e,n){if(!prefs.SHARED_PREF_KEYS.includes(e))throw new Error(`"${e}" is not a shared preference (see client/prefs.js SHARED_PREF_KEYS)`);return prefs.set({[e]:n},{dir:i}),c(e)},getDevMode:T,setDevMode:function(e){return prefs.set({devMode:Boolean(e)},{dir:i}),T()},getAccountUsername:h,setAccountUsername:function(e){return prefs.set({accountUsername:"string"==typeof e?e:null},{dir:i}),h()},get:E,set:function(e,{baseURL:n,key:t}={}){A(e);let r=n;if("local"===e&&n){const e=localTransport.remoteRefusal(n);if(e)throw e;r=localTransport.normalizeBase(n)}const o=d(),i=o[e]||{};return void 0!==r&&(i.baseURL=r),void 0!==t&&(i.key=t?l(t):null),o[e]=i,f(o),E(e)},rawKey:function(e){return _((d()[e]||{}).key)},remove:function(e){A(e);const n=d();return delete n[e],f(n),{ok:!0}},list:function(){const e=d();return Object.keys(e).filter((e=>!isReservedNamespace(e))).map((e=>E(e)))},maskKey:maskKey,aegisKey:S,aegisRawKey:function(){return _((d().__aegis||{}).key)},aegisKeySavedAt:function(){return(d().__aegis||{}).savedAt||null},setAegisKey:function(e){const n=d();return n.__aegis={...n.__aegis||{},key:e?l(e):null,savedAt:e?(new Date).toISOString():null},f(n),S()},migrateLegacyAegisKey:function(){try{const e=d();if(!e.aegis)return{migrated:!1};const n=e.aegis||{},t=e.__aegis||{},r={...e};return n.key&&!t.key&&(r.__aegis={...t,key:n.key}),delete r.aegis,f(r),{migrated:!0}}catch{return{migrated:!1}}},quickLauncherConfig:N,setQuickLauncherConfig:function({enabled:e,shortcut:n}={}){const t=d();return t.__quickLauncher={enabled:Boolean(e),shortcut:"string"==typeof n&&n.trim()?n.trim():"CmdOrCtrl+Shift+Space"},f(t),N()},vaultBackendConfig:b,setVaultBackendConfig:function(e){if(!VAULT_BACKEND_VALUES.includes(e))return b();const n=d();return n.__vaultBackend={backend:e},f(n),b()},getConfirmMode:function(){return v().enabled},setConfirmMode:function(e){prefs.set({confirmMode:Boolean(e)},{dir:i});const n=d();return void 0!==n.__confirmMode&&(delete n.__confirmMode,f(n)),v().enabled},confirmModeState:v,getFontScale:M,setFontScale:function(e){const n=d();return n.__fontScale={scale:m(e)},f(n),M()},clampFontScale:m,getAccent:y,setAccent:function(e){const n=d();return n.__accent={name:g(e)},f(n),y()},clampAccent:g,ACCENT_SKINS:p,getPermissionMode:R,setPermissionMode:function(e){if(null==e||""===e||"off"===e||"none"===e)return prefs.remove("permissionMode",{dir:i}),null;const n=String(e),t=function(){const e=[path.join(__dirname,"..","..","one","src","permissions.js"),path.join(__dirname,"..","vendor","one","src","permissions.js")];for(const n of e)try{const e=require(n);if(e&&Array.isArray(e.PERMISSION_MODES)&&e.PERMISSION_MODES.length)return[...e.PERMISSION_MODES]}catch{}return["acceptEdits","auto","bypassPermissions","manual","dontAsk","plan"]}();if(!t.includes(n))throw new Error(`"${n}" is not one of ${t.join("|")} (or 'off' to clear it)`);return prefs.set({permissionMode:n},{dir:i}),R()},getSandboxPolicy:C,setSandboxPolicy:function(e){return e&&"object"==typeof e?(prefs.set({sandboxPolicy:e},{dir:i}),C()):(prefs.set({sandboxPolicy:null},{dir:i}),null)},getTelemetryOptIn:I,setTelemetryOptIn:function(e){const n=d();return n.__telemetry={enabled:Boolean(e)},f(n),I()},getMemoryPersist:function(){return L().enabled},memoryPersistState:L,setMemoryPersist:function(e){prefs.set({memoryPersist:Boolean(e)},{dir:i});const n=d();return void 0!==n.__memoryPersist&&(delete n.__memoryPersist,f(n)),L()},getAvatar:D,avatarState:P,setAvatar:function(e={}){const n=D(),t=e&&"object"==typeof e?e:{},r={enabled:void 0===t.enabled?n.enabled:Boolean(t.enabled),showLevel:void 0===t.showLevel?n.showLevel:Boolean(t.showLevel),motion:AVATAR_MOTION_MODES.includes(t.motion)?t.motion:n.motion},o=d();return o.__avatar=r,f(o),P()},getAutoDrain:U,autoDrainState:k,setAutoDrain:function(e={}){const n=U(),t=e&&"object"==typeof e?e:{},r=d();return r.__autoDrain={enabled:void 0===t.enabled?n.enabled:Boolean(t.enabled),intervalMs:void 0===t.intervalMs?n.intervalMs:O(t.intervalMs)},f(r),k()},getAutoMint:B,autoMintState:K,setAutoMint:function(e={}){const n=B(),t=e&&"object"==typeof e?e:{},r=d();return r.__autoMint={enabled:void 0===t.enabled?n.enabled:Boolean(t.enabled),publish:void 0===t.publish?n.publish:Boolean(t.publish)},f(r),K()},clampAutoDrainInterval:O}}module.exports={SETTINGS_FILE:SETTINGS_FILE,AEGIS_KEY_NAMESPACE:"__aegis",LEGACY_AEGIS_NAMESPACE:"aegis",QUICK_LAUNCHER_NAMESPACE:"__quickLauncher",VAULT_BACKEND_NAMESPACE:"__vaultBackend",CONFIRM_MODE_NAMESPACE:"__confirmMode",MEMORY_PERSIST_NAMESPACE:"__memoryPersist",AVATAR_NAMESPACE:"__avatar",TELEMETRY_NAMESPACE:"__telemetry",AUTO_DRAIN_NAMESPACE:"__autoDrain",AUTO_MINT_NAMESPACE:"__autoMint",AUTO_DRAIN_INTERVAL_DEFAULT_MS:6e4,AUTO_DRAIN_INTERVAL_MIN_MS:15e3,AUTO_DRAIN_INTERVAL_MAX_MS:18e5,AVATAR_MOTION_MODES:AVATAR_MOTION_MODES,DEFAULT_QUICK_LAUNCHER_SHORTCUT:"CmdOrCtrl+Shift+Space",DEFAULT_VAULT_BACKEND:"aegiscloud",VAULT_BACKEND_VALUES:VAULT_BACKEND_VALUES,RESERVED_NAMESPACES:RESERVED_NAMESPACES,isReservedNamespace:isReservedNamespace,maskKey:maskKey,createSettingsStore:createSettingsStore};
3
+ "use strict";const fs=require("node:fs"),path=require("node:path"),{execFileSync:execFileSync}=require("node:child_process"),prefs=(()=>{try{return require("../../client/prefs.js")}catch{return require("../vendor/prefs.js")}})(),credentials=(()=>{try{return require("../../client/credentials.js")}catch{return require("../vendor/credentials.js")}})(),localTransport=require("./local/local.js"),LOCAL_NAMESPACE="local",SETTINGS_FILE="settings.json",AEGIS_KEY_NAMESPACE="__aegis",LEGACY_AEGIS_NAMESPACE="aegis",QUICK_LAUNCHER_NAMESPACE="__quickLauncher",DEFAULT_QUICK_LAUNCHER_SHORTCUT="CmdOrCtrl+Shift+Space",VAULT_BACKEND_NAMESPACE="__vaultBackend",DEFAULT_VAULT_BACKEND="aegiscloud",VAULT_BACKEND_VALUES=Object.freeze(["aegiscloud","drive","off"]),CONFIRM_MODE_NAMESPACE="__confirmMode",FONT_SCALE_NAMESPACE="__fontScale",ACCENT_NAMESPACE="__accent",MEMORY_PERSIST_NAMESPACE="__memoryPersist",AVATAR_NAMESPACE="__avatar",TELEMETRY_NAMESPACE="__telemetry",AUTO_DRAIN_NAMESPACE="__autoDrain",AUTO_MINT_NAMESPACE="__autoMint",AUTO_DRAIN_INTERVAL_DEFAULT_MS=6e4,AUTO_DRAIN_INTERVAL_MIN_MS=15e3,AUTO_DRAIN_INTERVAL_MAX_MS=18e5,RESERVED_NAMESPACES=Object.freeze(["__aegis","aegis","__quickLauncher","__vaultBackend","__confirmMode","__memoryPersist","__avatar","__telemetry","__autoDrain","__autoMint"]),AVATAR_MOTION_MODES=Object.freeze(["system","full","minimal"]);function isReservedNamespace(e){return RESERVED_NAMESPACES.includes(e)}function maskKey(e){return e?e.length<=10?"configured":`${e.slice(0,9)}…${e.slice(-4)}`:null}const IS_WIN32="win32"===process.platform;function restrictFile(e){if(IS_WIN32){const n=process.env.USERNAME||process.env.USER||process.env.USERDOMAIN;if(!n)return void console.error(`[settings] cannot restrict ${e}: no current user to grant (USERNAME unset)`);try{execFileSync("icacls",[e,"/inheritance:r","/grant:r",`${n}:(F)`],{stdio:"ignore"})}catch(n){console.error(`[settings] failed to restrict ACL on ${e}: ${n.message}`)}return}try{fs.chmodSync(e,384)}catch(n){console.error(`[settings] failed to chmod ${e} to 0600: ${n.message}`)}}function createSettingsStore({dir:e,safeStorage:n,prefsDir:t,env:r}={}){if(!e)throw new Error("createSettingsStore requires a storage dir");const o=path.join(e,SETTINGS_FILE),i=(()=>{const e=null==t?"":String(t).trim();return e?path.resolve(e):credentials.aegisHome(r)})(),s=(()=>{try{return prefs.adopt({dir:i,legacyDir:e})}catch(e){return(process.env.AEGISCODE_DEBUG||process.env.AEGIS_HIST_DEBUG)&&process.stderr.write(`aegis-desktop: shared-preference adoption failed: ${e.message}\n`),{adopted:!1,keys:[],reason:`adoption failed: ${e.message}`}}})();function a(){try{return prefs.load({dir:i})}catch{return{}}}function c(e){if(!prefs.SHARED_PREF_KEYS.includes(e))throw new Error(`"${e}" is not a shared preference (see client/prefs.js SHARED_PREF_KEYS)`);const n=a()[e];return void 0===n?null:n}const u=()=>Boolean(n&&"function"==typeof n.isEncryptionAvailable&&n.isEncryptionAvailable());function _(e){return null==e?null:u()?n.encryptString(String(e)).toString("base64"):Buffer.from(String(e),"utf8").toString("base64")}function l(e){if(!e)return null;try{const t=Buffer.from(String(e),"base64");return u()?n.decryptString(t):t.toString("utf8")}catch{return null}}function d(){try{return JSON.parse(fs.readFileSync(o,"utf8"))||{}}catch{return{}}}function f(e){fs.mkdirSync(path.dirname(o),{recursive:!0});const n=`${o}.tmp-${process.pid}`;fs.writeFileSync(n,JSON.stringify(e,null,2),{mode:384}),fs.renameSync(n,o),restrictFile(o)}function A(e){if(isReservedNamespace(e))throw new Error(`reserved namespace "${e}" is not a provider config — use setAegisKey()/aegisRawKey() for the AEGIS key`)}function E(e){const n=d()[e]||{},t=l(n.key);return{provider:e,baseURL:n.baseURL||"",configured:Boolean(t),keyMask:maskKey(t)}}function S(){const e=l((d().__aegis||{}).key);return{configured:Boolean(e),keyMask:maskKey(e)}}function m(e){return Number.isFinite(e)?Math.min(1.3,Math.max(.85,Math.round(100*e)/100)):1}function M(){return m((d().__fontScale||{}).scale)}const p=["default","cobalt","amber"];function g(e){const n="string"==typeof e?e.trim().toLowerCase():"";return p.includes(n)?n:"default"}function y(){return g((d().__accent||{}).name)}function N(){const e=d().__quickLauncher||{},n="string"==typeof e.shortcut&&e.shortcut.trim()?e.shortcut.trim():"CmdOrCtrl+Shift+Space";return{enabled:Boolean(e.enabled),shortcut:n}}function b(){const e=d().__vaultBackend||{};return{backend:VAULT_BACKEND_VALUES.includes(e.backend)?e.backend:"aegiscloud"}}function v(){const e=a();if("boolean"==typeof e.confirmMode)return{enabled:e.confirmMode,source:"config"};const n=d().__confirmMode||{};return void 0===n.enabled?{enabled:!0,source:"default"}:{enabled:Boolean(n.enabled),source:"config"}}function C(){const e=a().sandboxPolicy;return e&&"object"==typeof e?e:null}function T(){return!0===a().devMode}function h(){const e=a().accountUsername;return"string"==typeof e?e:null}function R(){const e=a();return"string"==typeof e.permissionMode?e.permissionMode:null}function I(){return!0===(d().__telemetry||{}).enabled}function L(){const e=a();if("boolean"==typeof e.memoryPersist)return{enabled:e.memoryPersist,source:"config"};const n=d().__memoryPersist||{};return void 0===n.enabled?{enabled:!0,source:"default"}:{enabled:Boolean(n.enabled),source:"config"}}function D(){const e=d().__avatar||{};return{enabled:void 0===e.enabled||Boolean(e.enabled),showLevel:void 0===e.showLevel||Boolean(e.showLevel),motion:AVATAR_MOTION_MODES.includes(e.motion)?e.motion:"system"}}function P(){const e=d().__avatar||{};return{...D(),source:void 0===e.enabled?"default":"config"}}function O(e){const n=Number(e);if(!Number.isFinite(n))return 6e4;const t=Math.round(n);return t<15e3||t>18e5?6e4:t}function U(){const e=d().__autoDrain||{};return{enabled:!1!==e.enabled,intervalMs:O(e.intervalMs)}}function k(){const e=d().__autoDrain||{};return{...U(),source:void 0===e.enabled?"default":"config"}}function B(){const e=d().__autoMint||{};return{enabled:!1!==e.enabled,publish:!0===e.publish}}function K(){const e=d().__autoMint||{};return{...B(),source:void 0===e.enabled?"default":"config"}}return{file:o,sharedDir:i,adoption:s,sharedFile:function(){return prefs.prefsFile({dir:i})},getSharedPref:c,setSharedPref:function(e,n){if(!prefs.SHARED_PREF_KEYS.includes(e))throw new Error(`"${e}" is not a shared preference (see client/prefs.js SHARED_PREF_KEYS)`);return prefs.set({[e]:n},{dir:i}),c(e)},getDevMode:T,setDevMode:function(e){return prefs.set({devMode:Boolean(e)},{dir:i}),T()},getAccountUsername:h,setAccountUsername:function(e){return prefs.set({accountUsername:"string"==typeof e?e:null},{dir:i}),h()},get:E,set:function(e,{baseURL:n,key:t}={}){A(e);let r=n;if("local"===e&&n){const e=localTransport.remoteRefusal(n);if(e)throw e;r=localTransport.normalizeBase(n)}const o=d(),i=o[e]||{};return void 0!==r&&(i.baseURL=r),void 0!==t&&(i.key=t?_(t):null),o[e]=i,f(o),E(e)},rawKey:function(e){return l((d()[e]||{}).key)},remove:function(e){A(e);const n=d();return delete n[e],f(n),{ok:!0}},list:function(){const e=d();return Object.keys(e).filter(e=>!isReservedNamespace(e)).map(e=>E(e))},maskKey:maskKey,aegisKey:S,aegisRawKey:function(){return l((d().__aegis||{}).key)},aegisKeySavedAt:function(){return(d().__aegis||{}).savedAt||null},setAegisKey:function(e){const n=d();return n.__aegis={...n.__aegis||{},key:e?_(e):null,savedAt:e?(new Date).toISOString():null},f(n),S()},migrateLegacyAegisKey:function(){try{const e=d();if(!e.aegis)return{migrated:!1};const n=e.aegis||{},t=e.__aegis||{},r={...e};return n.key&&!t.key&&(r.__aegis={...t,key:n.key}),delete r.aegis,f(r),{migrated:!0}}catch{return{migrated:!1}}},quickLauncherConfig:N,setQuickLauncherConfig:function({enabled:e,shortcut:n}={}){const t=d();return t.__quickLauncher={enabled:Boolean(e),shortcut:"string"==typeof n&&n.trim()?n.trim():"CmdOrCtrl+Shift+Space"},f(t),N()},vaultBackendConfig:b,setVaultBackendConfig:function(e){if(!VAULT_BACKEND_VALUES.includes(e))return b();const n=d();return n.__vaultBackend={backend:e},f(n),b()},getConfirmMode:function(){return v().enabled},setConfirmMode:function(e){prefs.set({confirmMode:Boolean(e)},{dir:i});const n=d();return void 0!==n.__confirmMode&&(delete n.__confirmMode,f(n)),v().enabled},confirmModeState:v,getFontScale:M,setFontScale:function(e){const n=d();return n.__fontScale={scale:m(e)},f(n),M()},clampFontScale:m,getAccent:y,setAccent:function(e){const n=d();return n.__accent={name:g(e)},f(n),y()},clampAccent:g,ACCENT_SKINS:p,getPermissionMode:R,setPermissionMode:function(e){if(null==e||""===e||"off"===e||"none"===e)return prefs.remove("permissionMode",{dir:i}),null;const n=String(e),t=function(){const e=[path.join(__dirname,"..","..","one","src","permissions.js"),path.join(__dirname,"..","vendor","one","src","permissions.js")];for(const n of e)try{const e=require(n);if(e&&Array.isArray(e.PERMISSION_MODES)&&e.PERMISSION_MODES.length)return[...e.PERMISSION_MODES]}catch{}return["acceptEdits","auto","bypassPermissions","manual","dontAsk","plan"]}();if(!t.includes(n))throw new Error(`"${n}" is not one of ${t.join("|")} (or 'off' to clear it)`);return prefs.set({permissionMode:n},{dir:i}),R()},getSandboxPolicy:C,setSandboxPolicy:function(e){return e&&"object"==typeof e?(prefs.set({sandboxPolicy:e},{dir:i}),C()):(prefs.set({sandboxPolicy:null},{dir:i}),null)},getTelemetryOptIn:I,setTelemetryOptIn:function(e){const n=d();return n.__telemetry={enabled:Boolean(e)},f(n),I()},getMemoryPersist:function(){return L().enabled},memoryPersistState:L,setMemoryPersist:function(e){prefs.set({memoryPersist:Boolean(e)},{dir:i});const n=d();return void 0!==n.__memoryPersist&&(delete n.__memoryPersist,f(n)),L()},getAvatar:D,avatarState:P,setAvatar:function(e={}){const n=D(),t=e&&"object"==typeof e?e:{},r={enabled:void 0===t.enabled?n.enabled:Boolean(t.enabled),showLevel:void 0===t.showLevel?n.showLevel:Boolean(t.showLevel),motion:AVATAR_MOTION_MODES.includes(t.motion)?t.motion:n.motion},o=d();return o.__avatar=r,f(o),P()},getAutoDrain:U,autoDrainState:k,setAutoDrain:function(e={}){const n=U(),t=e&&"object"==typeof e?e:{},r=d();return r.__autoDrain={enabled:void 0===t.enabled?n.enabled:Boolean(t.enabled),intervalMs:void 0===t.intervalMs?n.intervalMs:O(t.intervalMs)},f(r),k()},getAutoMint:B,autoMintState:K,setAutoMint:function(e={}){const n=B(),t=e&&"object"==typeof e?e:{},r=d();return r.__autoMint={enabled:void 0===t.enabled?n.enabled:Boolean(t.enabled),publish:void 0===t.publish?n.publish:Boolean(t.publish)},f(r),K()},clampAutoDrainInterval:O}}module.exports={SETTINGS_FILE:SETTINGS_FILE,AEGIS_KEY_NAMESPACE:"__aegis",LEGACY_AEGIS_NAMESPACE:"aegis",QUICK_LAUNCHER_NAMESPACE:"__quickLauncher",VAULT_BACKEND_NAMESPACE:"__vaultBackend",CONFIRM_MODE_NAMESPACE:"__confirmMode",MEMORY_PERSIST_NAMESPACE:"__memoryPersist",AVATAR_NAMESPACE:"__avatar",TELEMETRY_NAMESPACE:"__telemetry",AUTO_DRAIN_NAMESPACE:"__autoDrain",AUTO_MINT_NAMESPACE:"__autoMint",AUTO_DRAIN_INTERVAL_DEFAULT_MS:6e4,AUTO_DRAIN_INTERVAL_MIN_MS:15e3,AUTO_DRAIN_INTERVAL_MAX_MS:18e5,AVATAR_MOTION_MODES:AVATAR_MOTION_MODES,DEFAULT_QUICK_LAUNCHER_SHORTCUT:"CmdOrCtrl+Shift+Space",DEFAULT_VAULT_BACKEND:"aegiscloud",VAULT_BACKEND_VALUES:VAULT_BACKEND_VALUES,RESERVED_NAMESPACES:RESERVED_NAMESPACES,isReservedNamespace:isReservedNamespace,maskKey:maskKey,createSettingsStore:createSettingsStore};
@@ -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){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};
@@ -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,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 path=require("node:path"),{spawn:spawn}=require("node:child_process"),appDir=path.join(__dirname,"..");let electronPath;(process.argv.includes("--version")||process.argv.includes("-v"))&&(console.log(require(path.join(appDir,"package.json")).version),process.exit(0));try{electronPath=require("electron")}catch(e){console.error("Failed to launch aegis one: the electron runtime is not installed.\nIt ships as an optional dependency, so an install run with --omit=optional\n(or --no-optional, or a registry/proxy that skipped it) leaves it out.\nFix it with: npm i -g electron@^44 — or reinstall without that flag."),process.env.AEGIS_DEBUG&&console.error(e),process.exit(1)}const child=spawn(electronPath,[appDir,...process.argv.slice(2)],{stdio:"inherit"});child.on("error",(e=>{console.error("Failed to launch aegis one:",e.message),process.exit(1)})),child.on("close",(e=>process.exit(null==e?0:e)));
4
+ "use strict";const path=require("node:path"),{spawn:spawn}=require("node:child_process"),appDir=path.join(__dirname,"..");let electronPath;(process.argv.includes("--version")||process.argv.includes("-v"))&&(console.log(require(path.join(appDir,"package.json")).version),process.exit(0));try{electronPath=require("electron")}catch(e){console.error("Failed to launch aegis one: the electron runtime is not installed.\nIt ships as an optional dependency, so an install run with --omit=optional\n(or --no-optional, or a registry/proxy that skipped it) leaves it out.\nFix it with: npm i -g electron@^44 — or reinstall without that flag."),process.env.AEGIS_DEBUG&&console.error(e),process.exit(1)}const child=spawn(electronPath,[appDir,...process.argv.slice(2)],{stdio:"inherit"});child.on("error",e=>{console.error("Failed to launch aegis one:",e.message),process.exit(1)}),child.on("close",e=>process.exit(null==e?0:e));
@@ -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 AUTO_MINT_QUIET_DEFAULT_MS=9e4,AUTO_MINT_QUIET_MIN_MS=1e4,AUTO_MINT_QUIET_MAX_MS=36e5;function errorText(e){return e&&e.message||String(e)}function createAutoDrain({proceed:e,settings:t,queue:r,env:n=process.env,log:o=(()=>{}),setIntervalFn:i=setInterval,clearIntervalFn:u=clearInterval}={}){if("function"!=typeof e)throw new Error("createAutoDrain: a proceed() entry point is required");if(!t||"function"!=typeof t.getAutoDrain)throw new Error("createAutoDrain: the settings store is required");let s=null,a=!1,l=0,c=0,p=null,d=null;const f=e=>(p=e,o(e),e);function y(){return{...t.autoDrainState(),armed:Boolean(s),busy:a,ticks:l,drains:c,last:p,lastSkip:d}}function M(){const e=t.getAutoDrain();return e.enabled?(s&&e.intervalMs===s.__intervalMs||(A(),s=i((()=>{_()}),e.intervalMs),s.__intervalMs=e.intervalMs,s&&"function"==typeof s.unref&&s.unref(),o({type:"auto-drain-armed",intervalMs:e.intervalMs})),y()):(A(),y())}function A(){return s?(u(s),s=null,o({type:"auto-drain-disarmed"}),y()):y()}async function _(){if(l+=1,!t.getAutoDrain().enabled)return f({type:"skip",reason:"disabled"});if(a)return f({type:"skip",reason:"busy"});if(!r||"function"!=typeof r.loadQueue)return f({type:"skip",reason:"no queue access"});let o;try{o=r.loadQueue(n)}catch(e){return f({type:"error",phase:"read",error:errorText(e)})}if(!r.pendingCount(o))return f({type:"skip",reason:"empty"});try{const e=r.lockHolder(n);if(e&&e.pid&&e.pid!==process.pid&&("function"!=typeof r.isAlive||r.isAlive(e.pid)))return f({type:"skip",reason:"locked",holder:e})}catch{}a=!0;try{const t=await e();return t&&t.locked?f({type:"skip",reason:"locked",holder:t.holder||null}):(c+=1,f({type:"drain",ok:!(t&&!1===t.ok),ran:t&&t.ran||[],reason:t&&t.reason||null}))}catch(e){return f({type:"error",phase:"drain",error:errorText(e)})}finally{a=!1}}return{state:y,start:M,arm:M,stop:A,tick:_,set:e=>(t.setAutoDrain(e||{}),M(),y()),_timer:()=>s}}function createAutoMint({mint:e,settings:t,log:r=(()=>{}),quietMs:n=9e4,setTimeoutFn:o=setTimeout,clearTimeoutFn:i=clearTimeout}={}){if("function"!=typeof e)throw new Error("createAutoMint: mint() is required");if(!t||"function"!=typeof t.getAutoMint)throw new Error("createAutoMint: the settings store is required");const u=(()=>{const e=Number(n);if(!Number.isFinite(e))return 9e4;const t=Math.round(e);return t<1e4||t>36e5?9e4:t})();let s=null,a=0,l=null,c=!1,p=0,d=0,f=null,y=null,M=null;function A(){return{...t.autoMintState(),armed:Boolean(s),quietMs:u,pendingTurns:a,model:l,busy:c,seals:p,failures:d,last:f,lastError:y,lastSeal:M}}function _(){s&&(i(s),s=null)}async function T(){const r=t.getAutoMint();if(!r.enabled)return{type:"skip",reason:"disabled"};if(c)return{type:"skip",reason:"busy"};if(!a)return{type:"skip",reason:"nothing new"};c=!0;const n=a;a=0;try{const t=await e({publish:!0===r.publish,aiModel:l||void 0});return t&&!1!==t.ok?(p+=1,y=null,l=null,M={at:Date.now(),id:t.record&&t.record.id||null,out:t.out||null,turns:n,vaultError:t.vaultError||null},f={type:"seal",...M}):(d+=1,y=t&&t.error||"the seal did not complete",f={type:"error",phase:"seal",error:y})}catch(e){return d+=1,y=errorText(e),f={type:"error",phase:"seal",error:y}}finally{c=!1}}return{state:A,note:function(e){const r=t.getAutoMint(),n=e&&"string"==typeof e.model?e.model.trim():"";return n&&(l=n),r.enabled?(a+=1,f={type:"turn",at:Date.now(),sessionId:e&&e.sessionId||null},_(),s=o((()=>{s=null,T()}),u),s&&"function"==typeof s.unref&&s.unref(),A()):(a+=1,A())},flush:T,reset:()=>(_(),a=0,l=null,A()),start:()=>(t.getAutoMint().enabled||_(),A()),stop:()=>(_(),A()),set:e=>(t.setAutoMint(e||{}),t.getAutoMint().enabled||_(),A()),_timer:()=>s}}module.exports={createAutoDrain:createAutoDrain,createAutoMint:createAutoMint,AUTO_MINT_QUIET_DEFAULT_MS:9e4,AUTO_MINT_QUIET_MIN_MS:1e4,AUTO_MINT_QUIET_MAX_MS:36e5};
3
+ "use strict";const AUTO_MINT_QUIET_DEFAULT_MS=9e4,AUTO_MINT_QUIET_MIN_MS=1e4,AUTO_MINT_QUIET_MAX_MS=36e5;function errorText(e){return e&&e.message||String(e)}function createAutoDrain({proceed:e,settings:t,queue:r,env:n=process.env,log:o=()=>{},setIntervalFn:i=setInterval,clearIntervalFn:u=clearInterval}={}){if("function"!=typeof e)throw new Error("createAutoDrain: a proceed() entry point is required");if(!t||"function"!=typeof t.getAutoDrain)throw new Error("createAutoDrain: the settings store is required");let s=null,a=!1,l=0,c=0,p=null;const d=e=>(p=e,o(e),e);function f(){return{...t.autoDrainState(),armed:Boolean(s),busy:a,ticks:l,drains:c,last:p,lastSkip:null}}function y(){const e=t.getAutoDrain();return e.enabled?(s&&e.intervalMs===s.__intervalMs||(M(),s=i(()=>{A()},e.intervalMs),s.__intervalMs=e.intervalMs,s&&"function"==typeof s.unref&&s.unref(),o({type:"auto-drain-armed",intervalMs:e.intervalMs})),f()):(M(),f())}function M(){return s?(u(s),s=null,o({type:"auto-drain-disarmed"}),f()):f()}async function A(){if(l+=1,!t.getAutoDrain().enabled)return d({type:"skip",reason:"disabled"});if(a)return d({type:"skip",reason:"busy"});if(!r||"function"!=typeof r.loadQueue)return d({type:"skip",reason:"no queue access"});let o;try{o=r.loadQueue(n)}catch(e){return d({type:"error",phase:"read",error:errorText(e)})}if(!r.pendingCount(o))return d({type:"skip",reason:"empty"});try{const e=r.lockHolder(n);if(e&&e.pid&&e.pid!==process.pid&&("function"!=typeof r.isAlive||r.isAlive(e.pid)))return d({type:"skip",reason:"locked",holder:e})}catch{}a=!0;try{const t=await e();return t&&t.locked?d({type:"skip",reason:"locked",holder:t.holder||null}):(c+=1,d({type:"drain",ok:!(t&&!1===t.ok),ran:t&&t.ran||[],reason:t&&t.reason||null}))}catch(e){return d({type:"error",phase:"drain",error:errorText(e)})}finally{a=!1}}return{state:f,start:y,arm:y,stop:M,tick:A,set:e=>(t.setAutoDrain(e||{}),y(),f()),_timer:()=>s}}function createAutoMint({mint:e,settings:t,log:r=()=>{},quietMs:n=9e4,setTimeoutFn:o=setTimeout,clearTimeoutFn:i=clearTimeout}={}){if("function"!=typeof e)throw new Error("createAutoMint: mint() is required");if(!t||"function"!=typeof t.getAutoMint)throw new Error("createAutoMint: the settings store is required");const u=(()=>{const e=Number(n);if(!Number.isFinite(e))return 9e4;const t=Math.round(e);return t<1e4||t>36e5?9e4:t})();let s=null,a=0,l=null,c=!1,p=0,d=0,f=null,y=null,M=null;function A(){return{...t.autoMintState(),armed:Boolean(s),quietMs:u,pendingTurns:a,model:l,busy:c,seals:p,failures:d,last:f,lastError:y,lastSeal:M}}function _(){s&&(i(s),s=null)}async function T(){const r=t.getAutoMint();if(!r.enabled)return{type:"skip",reason:"disabled"};if(c)return{type:"skip",reason:"busy"};if(!a)return{type:"skip",reason:"nothing new"};c=!0;const n=a;a=0;try{const t=await e({publish:!0===r.publish,aiModel:l||void 0});return t&&!1!==t.ok?(p+=1,y=null,l=null,M={at:Date.now(),id:t.record&&t.record.id||null,out:t.out||null,turns:n,vaultError:t.vaultError||null},f={type:"seal",...M}):(d+=1,y=t&&t.error||"the seal did not complete",f={type:"error",phase:"seal",error:y})}catch(e){return d+=1,y=errorText(e),f={type:"error",phase:"seal",error:y}}finally{c=!1}}return{state:A,note:function(e){const r=t.getAutoMint(),n=e&&"string"==typeof e.model?e.model.trim():"";return n&&(l=n),r.enabled?(a+=1,f={type:"turn",at:Date.now(),sessionId:e&&e.sessionId||null},_(),s=o(()=>{s=null,T()},u),s&&"function"==typeof s.unref&&s.unref(),A()):(a+=1,A())},flush:T,reset:()=>(_(),a=0,l=null,A()),start:()=>(t.getAutoMint().enabled||_(),A()),stop:()=>(_(),A()),set:e=>(t.setAutoMint(e||{}),t.getAutoMint().enabled||_(),A()),_timer:()=>s}}module.exports={createAutoDrain:createAutoDrain,createAutoMint:createAutoMint,AUTO_MINT_QUIET_DEFAULT_MS:9e4,AUTO_MINT_QUIET_MIN_MS:1e4,AUTO_MINT_QUIET_MAX_MS:36e5};