aegisone 1.0.64 → 1.0.66

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (374) hide show
  1. package/README.md +1 -1
  2. package/bin/aegis.js +1 -1
  3. package/package.json +1 -1
  4. package/scripts/bump.mjs +1 -1
  5. package/scripts/bundle.js +1 -1
  6. package/scripts/postinstall.mjs +1 -1
  7. package/scripts/predist.mjs +1 -1
  8. package/src/child.js +1 -1
  9. package/src/dispatch.js +1 -1
  10. package/src/doctor.js +1 -1
  11. package/src/probes.js +1 -1
  12. package/src/productupdate.js +1 -1
  13. package/src/protocol.js +1 -1
  14. package/src/release.js +1 -1
  15. package/src/selfhost.js +1 -1
  16. package/vendor/cli/bin/aegiscode.js +47 -5
  17. package/vendor/cli/package.json +1 -1
  18. package/vendor/cli/scripts/check.mjs +1 -1
  19. package/vendor/cli/scripts/demo.mjs +1 -1
  20. package/vendor/cli/scripts/postinstall.mjs +1 -1
  21. package/vendor/cli/scripts/predist.mjs +1 -1
  22. package/vendor/cli/scripts/runtests.mjs +1 -1
  23. package/vendor/cli/src/app.js +1 -1
  24. package/vendor/cli/src/art.js +1 -1
  25. package/vendor/cli/src/autonomous.js +574 -10
  26. package/vendor/cli/src/chatflow.js +1 -1
  27. package/vendor/cli/src/checkpoint.js +1 -1
  28. package/vendor/cli/src/clipboard.js +1 -1
  29. package/vendor/cli/src/cloudsync.js +1 -1
  30. package/vendor/cli/src/commands.js +2 -2
  31. package/vendor/cli/src/config.js +1 -1
  32. package/vendor/cli/src/connect.js +1 -1
  33. package/vendor/cli/src/devrun.js +1 -1
  34. package/vendor/cli/src/diff.js +1 -1
  35. package/vendor/cli/src/diffview.js +1 -1
  36. package/vendor/cli/src/dream-cmd.js +3 -0
  37. package/vendor/cli/src/dream.js +1 -1
  38. package/vendor/cli/src/engine.js +1 -1
  39. package/vendor/cli/src/events.js +1 -1
  40. package/vendor/cli/src/export.js +1 -1
  41. package/vendor/cli/src/fingerprint.js +1 -1
  42. package/vendor/cli/src/format.js +1 -1
  43. package/vendor/cli/src/fuzzy.js +1 -1
  44. package/vendor/cli/src/history.js +1 -1
  45. package/vendor/cli/src/init.js +1 -1
  46. package/vendor/cli/src/limits.js +1 -1
  47. package/vendor/cli/src/markdown.js +1 -1
  48. package/vendor/cli/src/models.js +1 -1
  49. package/vendor/cli/src/overlays.js +1 -1
  50. package/vendor/cli/src/panels.js +1 -1
  51. package/vendor/cli/src/ping.js +1 -1
  52. package/vendor/cli/src/presence.js +1 -1
  53. package/vendor/cli/src/provenance.lock.json +3 -3
  54. package/vendor/cli/src/render.js +1 -1
  55. package/vendor/cli/src/screen.js +1 -1
  56. package/vendor/cli/src/screens.js +1 -1
  57. package/vendor/cli/src/secret.js +1 -1
  58. package/vendor/cli/src/securefs.js +1 -1
  59. package/vendor/cli/src/settings.js +1 -1
  60. package/vendor/cli/src/signup.js +1 -1
  61. package/vendor/cli/src/summarize.js +1 -1
  62. package/vendor/cli/src/sysdiag.js +1 -1
  63. package/vendor/cli/src/theme.js +1 -1
  64. package/vendor/cli/src/title.js +1 -1
  65. package/vendor/cli/src/todos.js +1 -1
  66. package/vendor/cli/src/tokens.js +1 -1
  67. package/vendor/cli/src/topup.js +1 -1
  68. package/vendor/cli/src/update.js +1 -1
  69. package/vendor/cli/vendor/client/aegis.js +1 -1
  70. package/vendor/cli/vendor/client/attest.js +1 -1
  71. package/vendor/cli/vendor/client/authorship-key.js +1 -1
  72. package/vendor/cli/vendor/client/auto-provision.js +1 -1
  73. package/vendor/cli/vendor/client/brain-catalog.js +1 -1
  74. package/vendor/cli/vendor/client/byok-catalog.js +1 -1
  75. package/vendor/cli/vendor/client/catalog-client.js +1 -1
  76. package/vendor/cli/vendor/client/conversation-export.js +1 -1
  77. package/vendor/cli/vendor/client/credentials.js +1 -1
  78. package/vendor/cli/vendor/client/credits.js +1 -1
  79. package/vendor/cli/vendor/client/drive-connect.js +1 -1
  80. package/vendor/cli/vendor/client/env-file.js +1 -1
  81. package/vendor/cli/vendor/client/fingerprint.js +1 -1
  82. package/vendor/cli/vendor/client/foreign-memory.js +1 -1
  83. package/vendor/cli/vendor/client/foreign-sessions.js +1 -1
  84. package/vendor/cli/vendor/client/google-signin.js +1 -1
  85. package/vendor/cli/vendor/client/hooks.js +1 -1
  86. package/vendor/cli/vendor/client/model-discovery.js +1 -1
  87. package/vendor/cli/vendor/client/model-sync.js +1 -1
  88. package/vendor/cli/vendor/client/naming.js +1 -1
  89. package/vendor/cli/vendor/client/platform.js +1 -1
  90. package/vendor/cli/vendor/client/prefs.js +1 -1
  91. package/vendor/cli/vendor/client/presence.js +1 -1
  92. package/vendor/cli/vendor/client/record-vault.js +2 -2
  93. package/vendor/cli/vendor/client/session-search.js +1 -1
  94. package/vendor/cli/vendor/client/session-store.js +1 -1
  95. package/vendor/cli/vendor/client/skills.js +1 -1
  96. package/vendor/cli/vendor/client/topup.js +1 -1
  97. package/vendor/cli/vendor/client/touch.js +1 -1
  98. package/vendor/cli/vendor/client/update.js +1 -1
  99. package/vendor/cli/vendor/client/user-models.js +1 -1
  100. package/vendor/cli/vendor/desktop/lib/local/attachments.js +1 -1
  101. package/vendor/cli/vendor/desktop/lib/local/autonomous.js +1 -1
  102. package/vendor/cli/vendor/desktop/lib/local/claude-pro.js +1 -1
  103. package/vendor/cli/vendor/desktop/lib/local/context.js +1 -1
  104. package/vendor/cli/vendor/desktop/lib/local/engine.js +1 -1
  105. package/vendor/cli/vendor/desktop/lib/local/entitlement.js +1 -1
  106. package/vendor/cli/vendor/desktop/lib/local/integrity.js +1 -1
  107. package/vendor/cli/vendor/desktop/lib/local/local.js +1 -1
  108. package/vendor/cli/vendor/desktop/lib/local/perm-rules.js +5 -0
  109. package/vendor/cli/vendor/desktop/lib/local/perm-store.js +5 -0
  110. package/vendor/cli/vendor/desktop/lib/local/perm-write.js +5 -0
  111. package/vendor/cli/vendor/desktop/lib/local/pro-sessions.js +3 -1
  112. package/vendor/cli/vendor/desktop/lib/local/prompt.js +1 -1
  113. package/vendor/cli/vendor/desktop/lib/local/queue.js +1 -1
  114. package/vendor/cli/vendor/desktop/lib/local/repeat-guard.js +1 -1
  115. package/vendor/cli/vendor/desktop/lib/local/session-rounds.js +1 -1
  116. package/vendor/cli/vendor/desktop/lib/local/spill.js +1 -1
  117. package/vendor/cli/vendor/desktop/lib/local/turn-guard.js +1 -1
  118. package/vendor/cli/vendor/desktop/lib/local/verify-stop.js +1 -1
  119. package/vendor/cli/vendor/desktop/lib/local/worktree-lock.js +1 -1
  120. package/vendor/cli/vendor/desktop/lib/settings.js +1 -1
  121. package/vendor/cli/vendor/desktop/main.js +82 -1
  122. package/vendor/cli/vendor/desktop/renderer/usage.js +1 -1
  123. package/vendor/cli/vendor/hosts/install.js +1 -1
  124. package/vendor/cli/vendor/hosts/openai-shim.js +1 -1
  125. package/vendor/cli/vendor/hosts/spec.js +1 -1
  126. package/vendor/cli/vendor/hosts/targets.js +1 -1
  127. package/vendor/cli/vendor/mcp/admission.js +1 -1
  128. package/vendor/cli/vendor/mcp/server.js +1 -1
  129. package/vendor/cli/vendor/mcp/tools.js +1 -1
  130. package/vendor/cli/vendor/one/src/child.js +1 -1
  131. package/vendor/cli/vendor/one/src/protocol.js +1 -1
  132. package/vendor/cli/vendor/one/src/selfhost.js +1 -1
  133. package/vendor/desktop/bin/aegis.js +1 -1
  134. package/vendor/desktop/lib/auto.js +1 -1
  135. package/vendor/desktop/lib/avatar/companion.js +1 -1
  136. package/vendor/desktop/lib/avatar/cosmetics.js +1 -1
  137. package/vendor/desktop/lib/avatar/holder-turn.js +1 -1
  138. package/vendor/desktop/lib/avatar/holders.js +1 -1
  139. package/vendor/desktop/lib/avatar/identity.js +1 -1
  140. package/vendor/desktop/lib/avatar/level.js +1 -1
  141. package/vendor/desktop/lib/avatar/mirror.js +1 -1
  142. package/vendor/desktop/lib/avatar/persona.js +1 -1
  143. package/vendor/desktop/lib/avatar/profile.js +1 -1
  144. package/vendor/desktop/lib/avatar/register.js +1 -1
  145. package/vendor/desktop/lib/avatar/store.js +1 -1
  146. package/vendor/desktop/lib/avatar/transfer.js +1 -1
  147. package/vendor/desktop/lib/avatar/turn.js +1 -1
  148. package/vendor/desktop/lib/avatar/voice.js +1 -1
  149. package/vendor/desktop/lib/avatar/xp.js +1 -1
  150. package/vendor/desktop/lib/deep-link.js +1 -1
  151. package/vendor/desktop/lib/local/attachments.js +1 -1
  152. package/vendor/desktop/lib/local/autonomous.js +1 -1
  153. package/vendor/desktop/lib/local/claude-pro.js +1 -1
  154. package/vendor/desktop/lib/local/cli-face.js +1 -1
  155. package/vendor/desktop/lib/local/context.js +1 -1
  156. package/vendor/desktop/lib/local/engine.js +1 -1
  157. package/vendor/desktop/lib/local/entitlement.js +1 -1
  158. package/vendor/desktop/lib/local/integrity.js +1 -1
  159. package/vendor/desktop/lib/local/local.js +1 -1
  160. package/vendor/desktop/lib/local/perm-rules.js +5 -0
  161. package/vendor/desktop/lib/local/perm-store.js +5 -0
  162. package/vendor/desktop/lib/local/perm-write.js +5 -0
  163. package/vendor/desktop/lib/local/pro-sessions.js +3 -1
  164. package/vendor/desktop/lib/local/prompt.js +1 -1
  165. package/vendor/desktop/lib/local/pty-host.js +1 -1
  166. package/vendor/desktop/lib/local/queue.js +1 -1
  167. package/vendor/desktop/lib/local/repeat-guard.js +1 -1
  168. package/vendor/desktop/lib/local/session-rounds.js +1 -1
  169. package/vendor/desktop/lib/local/spill.js +1 -1
  170. package/vendor/desktop/lib/local/telemetry.js +1 -1
  171. package/vendor/desktop/lib/local/turn-guard.js +1 -1
  172. package/vendor/desktop/lib/local/verify-stop.js +1 -1
  173. package/vendor/desktop/lib/local/worktree-lock.js +1 -1
  174. package/vendor/desktop/lib/provider-key-mirror.js +1 -1
  175. package/vendor/desktop/lib/quick-launcher.js +1 -1
  176. package/vendor/desktop/lib/settings.js +1 -1
  177. package/vendor/desktop/lib/skills-host.js +1 -1
  178. package/vendor/desktop/lib/speech-host.js +1 -1
  179. package/vendor/desktop/lib/sync/memory-store.js +1 -1
  180. package/vendor/desktop/lib/sync/persist-gate.js +1 -1
  181. package/vendor/desktop/lib/window-state.js +1 -1
  182. package/vendor/desktop/main.js +82 -1
  183. package/vendor/desktop/package.json +1 -1
  184. package/vendor/desktop/preload.js +3 -1
  185. package/vendor/desktop/renderer/app.js +3 -3
  186. package/vendor/desktop/renderer/avatar/assemble.js +1 -1
  187. package/vendor/desktop/renderer/avatar/avatar.js +1 -1
  188. package/vendor/desktop/renderer/avatar/cards.js +1 -1
  189. package/vendor/desktop/renderer/avatar/hud.js +1 -1
  190. package/vendor/desktop/renderer/avatar/pane.js +1 -1
  191. package/vendor/desktop/renderer/avatar/parts.js +1 -1
  192. package/vendor/desktop/renderer/commands.js +1 -1
  193. package/vendor/desktop/renderer/companion.js +1 -1
  194. package/vendor/desktop/renderer/composer-triggers.js +1 -1
  195. package/vendor/desktop/renderer/dictation.js +1 -1
  196. package/vendor/desktop/renderer/diff.js +1 -1
  197. package/vendor/desktop/renderer/diffview.js +1 -1
  198. package/vendor/desktop/renderer/fingerprint.js +2 -2
  199. package/vendor/desktop/renderer/index.html +10 -4
  200. package/vendor/desktop/renderer/library.js +1 -1
  201. package/vendor/desktop/renderer/markdown.js +1 -1
  202. package/vendor/desktop/renderer/palette-filter.js +1 -1
  203. package/vendor/desktop/renderer/provider-toolbar.js +1 -1
  204. package/vendor/desktop/renderer/providers.js +1 -1
  205. package/vendor/desktop/renderer/pty-frame.css +35 -0
  206. package/vendor/desktop/renderer/pty-frame.html +47 -0
  207. package/vendor/desktop/renderer/pty-panel.js +1 -1
  208. package/vendor/desktop/renderer/pty-window.html +72 -0
  209. package/vendor/desktop/renderer/pty-window.js +3 -0
  210. package/vendor/desktop/renderer/quick.js +1 -1
  211. package/vendor/desktop/renderer/settings-skills.js +1 -1
  212. package/vendor/desktop/renderer/shortcuts.js +1 -1
  213. package/vendor/desktop/renderer/stream-policy.js +1 -1
  214. package/vendor/desktop/renderer/style.css +77 -3
  215. package/vendor/desktop/renderer/transcript-view.js +1 -1
  216. package/vendor/desktop/renderer/usage.js +1 -1
  217. package/vendor/desktop/renderer/welcome-rows.js +1 -1
  218. package/vendor/desktop/vendor/aegis.js +1 -1
  219. package/vendor/desktop/vendor/attest.js +1 -1
  220. package/vendor/desktop/vendor/authorship-key.js +1 -1
  221. package/vendor/desktop/vendor/auto-provision.js +1 -1
  222. package/vendor/desktop/vendor/brain-catalog.js +1 -1
  223. package/vendor/desktop/vendor/byok-catalog.js +1 -1
  224. package/vendor/desktop/vendor/catalog-client.js +1 -1
  225. package/vendor/desktop/vendor/conversation-export.js +1 -1
  226. package/vendor/desktop/vendor/credentials.js +1 -1
  227. package/vendor/desktop/vendor/credits.js +1 -1
  228. package/vendor/desktop/vendor/drive-connect.js +1 -1
  229. package/vendor/desktop/vendor/env-file.js +1 -1
  230. package/vendor/desktop/vendor/faces/cli/bin/aegiscode.js +2 -2
  231. package/vendor/desktop/vendor/faces/cli/package.json +1 -1
  232. package/vendor/desktop/vendor/faces/cli/scripts/check.mjs +1 -1
  233. package/vendor/desktop/vendor/faces/cli/scripts/demo.mjs +1 -1
  234. package/vendor/desktop/vendor/faces/cli/scripts/postinstall.mjs +1 -1
  235. package/vendor/desktop/vendor/faces/cli/scripts/predist.mjs +1 -1
  236. package/vendor/desktop/vendor/faces/cli/scripts/runtests.mjs +1 -1
  237. package/vendor/desktop/vendor/faces/cli/src/app.js +1 -1
  238. package/vendor/desktop/vendor/faces/cli/src/art.js +1 -1
  239. package/vendor/desktop/vendor/faces/cli/src/autonomous.js +1 -1
  240. package/vendor/desktop/vendor/faces/cli/src/caps.js +1 -1
  241. package/vendor/desktop/vendor/faces/cli/src/chatflow.js +1 -1
  242. package/vendor/desktop/vendor/faces/cli/src/checkpoint.js +1 -1
  243. package/vendor/desktop/vendor/faces/cli/src/clipboard.js +1 -1
  244. package/vendor/desktop/vendor/faces/cli/src/cloudsync.js +1 -1
  245. package/vendor/desktop/vendor/faces/cli/src/commands.js +2 -2
  246. package/vendor/desktop/vendor/faces/cli/src/config.js +1 -1
  247. package/vendor/desktop/vendor/faces/cli/src/connect.js +1 -1
  248. package/vendor/desktop/vendor/faces/cli/src/devrun.js +1 -1
  249. package/vendor/desktop/vendor/faces/cli/src/diff.js +1 -1
  250. package/vendor/desktop/vendor/faces/cli/src/diffview.js +1 -1
  251. package/vendor/desktop/vendor/faces/cli/src/dream-cmd.js +3 -0
  252. package/vendor/desktop/vendor/faces/cli/src/dream.js +1 -1
  253. package/vendor/desktop/vendor/faces/cli/src/engine.js +1 -1
  254. package/vendor/desktop/vendor/faces/cli/src/events.js +1 -1
  255. package/vendor/desktop/vendor/faces/cli/src/export.js +1 -1
  256. package/vendor/desktop/vendor/faces/cli/src/fingerprint.js +1 -1
  257. package/vendor/desktop/vendor/faces/cli/src/format.js +1 -1
  258. package/vendor/desktop/vendor/faces/cli/src/fuzzy.js +1 -1
  259. package/vendor/desktop/vendor/faces/cli/src/history.js +1 -1
  260. package/vendor/desktop/vendor/faces/cli/src/init.js +1 -1
  261. package/vendor/desktop/vendor/faces/cli/src/limits.js +1 -1
  262. package/vendor/desktop/vendor/faces/cli/src/markdown.js +1 -1
  263. package/vendor/desktop/vendor/faces/cli/src/mcp.js +1 -1
  264. package/vendor/desktop/vendor/faces/cli/src/models.js +1 -1
  265. package/vendor/desktop/vendor/faces/cli/src/overlays.js +1 -1
  266. package/vendor/desktop/vendor/faces/cli/src/panels.js +1 -1
  267. package/vendor/desktop/vendor/faces/cli/src/permissions.js +1 -1
  268. package/vendor/desktop/vendor/faces/cli/src/ping.js +1 -1
  269. package/vendor/desktop/vendor/faces/cli/src/presence.js +1 -1
  270. package/vendor/desktop/vendor/faces/cli/src/provenance.js +1 -1
  271. package/vendor/desktop/vendor/faces/cli/src/provenance.lock.json +3 -3
  272. package/vendor/desktop/vendor/faces/cli/src/render.js +1 -1
  273. package/vendor/desktop/vendor/faces/cli/src/screen.js +1 -1
  274. package/vendor/desktop/vendor/faces/cli/src/screens.js +1 -1
  275. package/vendor/desktop/vendor/faces/cli/src/secret.js +1 -1
  276. package/vendor/desktop/vendor/faces/cli/src/securefs.js +1 -1
  277. package/vendor/desktop/vendor/faces/cli/src/settings.js +1 -1
  278. package/vendor/desktop/vendor/faces/cli/src/signup.js +1 -1
  279. package/vendor/desktop/vendor/faces/cli/src/summarize.js +1 -1
  280. package/vendor/desktop/vendor/faces/cli/src/sysdiag.js +1 -1
  281. package/vendor/desktop/vendor/faces/cli/src/theme.js +1 -1
  282. package/vendor/desktop/vendor/faces/cli/src/title.js +1 -1
  283. package/vendor/desktop/vendor/faces/cli/src/todos.js +1 -1
  284. package/vendor/desktop/vendor/faces/cli/src/tokens.js +1 -1
  285. package/vendor/desktop/vendor/faces/cli/src/topup.js +1 -1
  286. package/vendor/desktop/vendor/faces/cli/src/update.js +1 -1
  287. package/vendor/desktop/vendor/faces/cli/vendor/client/aegis.js +1 -1
  288. package/vendor/desktop/vendor/faces/cli/vendor/client/attest.js +1 -1
  289. package/vendor/desktop/vendor/faces/cli/vendor/client/authorship-key.js +1 -1
  290. package/vendor/desktop/vendor/faces/cli/vendor/client/auto-provision.js +1 -1
  291. package/vendor/desktop/vendor/faces/cli/vendor/client/brain-catalog.js +1 -1
  292. package/vendor/desktop/vendor/faces/cli/vendor/client/byok-catalog.js +1 -1
  293. package/vendor/desktop/vendor/faces/cli/vendor/client/catalog-client.js +1 -1
  294. package/vendor/desktop/vendor/faces/cli/vendor/client/conversation-export.js +1 -1
  295. package/vendor/desktop/vendor/faces/cli/vendor/client/credentials.js +1 -1
  296. package/vendor/desktop/vendor/faces/cli/vendor/client/credits.js +1 -1
  297. package/vendor/desktop/vendor/faces/cli/vendor/client/drive-connect.js +1 -1
  298. package/vendor/desktop/vendor/faces/cli/vendor/client/env-file.js +1 -1
  299. package/vendor/desktop/vendor/faces/cli/vendor/client/fingerprint.js +1 -1
  300. package/vendor/desktop/vendor/faces/cli/vendor/client/foreign-memory.js +1 -1
  301. package/vendor/desktop/vendor/faces/cli/vendor/client/foreign-sessions.js +1 -1
  302. package/vendor/desktop/vendor/faces/cli/vendor/client/google-signin.js +1 -1
  303. package/vendor/desktop/vendor/faces/cli/vendor/client/hooks.js +1 -1
  304. package/vendor/desktop/vendor/faces/cli/vendor/client/model-discovery.js +1 -1
  305. package/vendor/desktop/vendor/faces/cli/vendor/client/model-sync.js +1 -1
  306. package/vendor/desktop/vendor/faces/cli/vendor/client/naming.js +1 -1
  307. package/vendor/desktop/vendor/faces/cli/vendor/client/platform.js +1 -1
  308. package/vendor/desktop/vendor/faces/cli/vendor/client/prefs.js +1 -1
  309. package/vendor/desktop/vendor/faces/cli/vendor/client/presence.js +1 -1
  310. package/vendor/desktop/vendor/faces/cli/vendor/client/record-vault.js +2 -2
  311. package/vendor/desktop/vendor/faces/cli/vendor/client/session-search.js +1 -1
  312. package/vendor/desktop/vendor/faces/cli/vendor/client/session-store.js +1 -1
  313. package/vendor/desktop/vendor/faces/cli/vendor/client/skills.js +1 -1
  314. package/vendor/desktop/vendor/faces/cli/vendor/client/topup.js +1 -1
  315. package/vendor/desktop/vendor/faces/cli/vendor/client/touch.js +1 -1
  316. package/vendor/desktop/vendor/faces/cli/vendor/client/update.js +1 -1
  317. package/vendor/desktop/vendor/faces/cli/vendor/client/user-models.js +1 -1
  318. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/attachments.js +1 -1
  319. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/autonomous.js +1 -1
  320. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/claude-pro.js +1 -1
  321. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/context.js +1 -1
  322. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/engine.js +1 -1
  323. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/entitlement.js +1 -1
  324. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/exec-plan.js +1 -1
  325. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/integrity.js +1 -1
  326. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/local.js +1 -1
  327. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/perm-rules.js +2 -0
  328. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/perm-store.js +3 -1
  329. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/perm-write.js +2 -0
  330. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/pro-sessions.js +3 -1
  331. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/prompt.js +1 -1
  332. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/queue.js +1 -1
  333. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/repeat-guard.js +1 -1
  334. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/session-rounds.js +1 -1
  335. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/shell.js +1 -1
  336. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/spill.js +1 -1
  337. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/tools.js +1 -1
  338. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/turn-guard.js +1 -1
  339. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/verify-stop.js +1 -1
  340. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/worktree-lock.js +1 -1
  341. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/settings.js +1 -1
  342. package/vendor/desktop/vendor/faces/cli/vendor/desktop/main.js +3 -3
  343. package/vendor/desktop/vendor/faces/cli/vendor/desktop/renderer/usage.js +1 -1
  344. package/vendor/desktop/vendor/faces/cli/vendor/hosts/install.js +1 -1
  345. package/vendor/desktop/vendor/faces/cli/vendor/hosts/openai-shim.js +1 -1
  346. package/vendor/desktop/vendor/faces/cli/vendor/hosts/spec.js +1 -1
  347. package/vendor/desktop/vendor/faces/cli/vendor/hosts/targets.js +1 -1
  348. package/vendor/desktop/vendor/faces/cli/vendor/mcp/admission.js +1 -1
  349. package/vendor/desktop/vendor/faces/cli/vendor/mcp/server.js +1 -1
  350. package/vendor/desktop/vendor/faces/cli/vendor/mcp/tools.js +1 -1
  351. package/vendor/desktop/vendor/faces/cli/vendor/one/src/child.js +1 -1
  352. package/vendor/desktop/vendor/faces/cli/vendor/one/src/protocol.js +1 -1
  353. package/vendor/desktop/vendor/faces/cli/vendor/one/src/selfhost.js +1 -1
  354. package/vendor/desktop/vendor/fingerprint.js +1 -1
  355. package/vendor/desktop/vendor/foreign-memory.js +1 -1
  356. package/vendor/desktop/vendor/foreign-sessions.js +1 -1
  357. package/vendor/desktop/vendor/google-signin.js +1 -1
  358. package/vendor/desktop/vendor/hooks.js +1 -1
  359. package/vendor/desktop/vendor/model-discovery.js +1 -1
  360. package/vendor/desktop/vendor/model-sync.js +1 -1
  361. package/vendor/desktop/vendor/naming.js +1 -1
  362. package/vendor/desktop/vendor/platform.js +1 -1
  363. package/vendor/desktop/vendor/prefs.js +1 -1
  364. package/vendor/desktop/vendor/presence.js +1 -1
  365. package/vendor/desktop/vendor/protocol.js +1 -1
  366. package/vendor/desktop/vendor/record-vault.js +2 -2
  367. package/vendor/desktop/vendor/selfhost.js +1 -1
  368. package/vendor/desktop/vendor/session-search.js +1 -1
  369. package/vendor/desktop/vendor/session-store.js +1 -1
  370. package/vendor/desktop/vendor/skills.js +1 -1
  371. package/vendor/desktop/vendor/topup.js +1 -1
  372. package/vendor/desktop/vendor/touch.js +1 -1
  373. package/vendor/desktop/vendor/update.js +1 -1
  374. package/vendor/desktop/vendor/user-models.js +1 -1
@@ -1 +1 @@
1
- "use strict";const os=require("node:os"),path=require("node:path"),{SERVER_NAME:SERVER_NAME,vscodeKeyInput:vscodeKeyInput}=require("./spec.js");function home(e){return e.home||e.env.HOME||e.env.USERPROFILE||os.homedir()}function appConfig(e){const{env:o,platform:n}=e;return o.XDG_CONFIG_HOME?o.XDG_CONFIG_HOME:"win32"===n?o.APPDATA||path.join(home(e),"AppData","Roaming"):"darwin"===n?path.join(home(e),"Library","Application Support"):path.join(home(e),".config")}function zedConfig(e){const{env:o,platform:n}=e;return"win32"===n?path.join(o.APPDATA||path.join(home(e),"AppData","Roaming"),"Zed"):path.join(o.XDG_CONFIG_HOME||path.join(home(e),".config"),"zed")}function dot(e,...o){return path.join(home(e),...o)}function vscodeUserFile(e,o){return path.join(appConfig(e),o,"User","mcp.json")}function orEnv(e){return e.env&&Object.keys(e.env).length?e.env:null}function plainEntry(e){const o=orEnv(e),n={command:e.command,args:e.args};return o&&(n.env=o),n}const TARGETS=[{id:"vscode",label:"VS Code",kind:"mcp-json",container:"servers",scopes:["user","workspace"],docs:"https://code.visualstudio.com/docs/copilot/customization/mcp-servers",verified:!0,supportsKeyPrompt:!0,note:"Copilot agent mode reads `.vscode/mcp.json` for the workspace, or the user file for every project.",path:(e,o)=>"workspace"===e?path.join(o.cwd,".vscode","mcp.json"):vscodeUserFile(o,"Code"),entry(e){const o={type:"stdio",command:e.command,args:e.args},n=orEnv(e);return n&&(o.env=n),o},extras:e=>e.keyRef&&e.keyRef.startsWith("${input:")?{inputs:[vscodeKeyInput()]}:null},{id:"vscode-insiders",label:"VS Code Insiders",kind:"mcp-json",container:"servers",scopes:["user"],docs:"https://code.visualstudio.com/docs/copilot/customization/mcp-servers",verified:!0,supportsKeyPrompt:!0,path:(e,o)=>vscodeUserFile(o,"Code - Insiders"),entry:e=>TARGETS[0].entry(e),extras:e=>TARGETS[0].extras(e)},{id:"vscodium",label:"VSCodium",kind:"mcp-json",container:"servers",scopes:["user","workspace"],docs:"https://code.visualstudio.com/docs/copilot/customization/mcp-servers",verified:!0,supportsKeyPrompt:!0,path:(e,o)=>"workspace"===e?path.join(o.cwd,".vscode","mcp.json"):vscodeUserFile(o,"VSCodium"),entry:e=>TARGETS[0].entry(e),extras:e=>TARGETS[0].extras(e)},{id:"cursor",label:"Cursor",kind:"mcp-json",container:"mcpServers",scopes:["user","workspace"],docs:"https://cursor.com/docs/context/mcp",verified:!0,path:(e,o)=>"workspace"===e?path.join(o.cwd,".cursor","mcp.json"):path.join(appConfig(o),"Cursor","mcp.json"),entry:plainEntry},{id:"windsurf",label:"Windsurf",kind:"mcp-json",container:"mcpServers",scopes:["user"],docs:"https://docs.windsurf.com/windsurf/cascade/mcp",verified:!0,path:(e,o)=>dot(o,".codeium","windsurf","mcp_config.json"),entry:plainEntry},{id:"cline",label:"Cline (VS Code extension)",kind:"mcp-json",container:"mcpServers",scopes:["user"],docs:"https://docs.cline.bot/mcp/configuring-mcp-servers",verified:!0,path:(e,o)=>path.join(appConfig(o),"Code","User","globalStorage","saoudrizwan.claude-dev","settings","cline_mcp_settings.json"),entry:e=>({...plainEntry(e),disabled:!1,autoApprove:[],type:"stdio"})},{id:"roo",label:"Roo Code (VS Code extension)",kind:"mcp-json",container:"mcpServers",scopes:["user"],docs:"https://docs.roocode.com/features/mcp/using-mcp-in-roo",verified:!0,path:(e,o)=>path.join(appConfig(o),"Code","User","globalStorage","rooveterinaryinc.roo-cline","settings","mcp_settings.json"),entry:e=>({...plainEntry(e),disabled:!1,alwaysAllow:[],type:"stdio"})},{id:"zed",label:"Zed",kind:"mcp-json",container:"context_servers",scopes:["user"],docs:"https://zed.dev/docs/ai/mcp",verified:!0,path:(e,o)=>path.join(zedConfig(o),"settings.json"),entry(e){const o={path:e.command,args:e.args},n=orEnv(e);return n&&(o.env=n),{source:"custom",command:o}}},{id:"continue",label:"Continue (VS Code / JetBrains)",kind:"mcp-json",container:"mcpServers",scopes:["user"],docs:"https://docs.continue.dev/customize/deep-dives/mcp",verified:!0,path:(e,o)=>dot(o,".continue","config.json"),entry:plainEntry,yamlWins:!0},{id:"claude",label:"Claude Code (project scope)",kind:"mcp-json",container:"mcpServers",scopes:["workspace"],docs:"https://docs.claude.com/en/docs/claude-code/mcp",verified:!0,path:(e,o)=>path.join(o.cwd,".mcp.json"),entry:plainEntry},{id:"gemini",label:"Gemini CLI",kind:"mcp-json",container:"mcpServers",scopes:["user"],docs:"https://github.com/google-gemini/gemini-cli/blob/main/docs/tools/mcp-server.md",verified:!0,path:(e,o)=>dot(o,".gemini","settings.json"),entry:plainEntry},{id:"codex",label:"Codex CLI",kind:"mcp-toml",container:"mcp_servers",scopes:["user"],docs:"https://github.com/openai/codex/blob/main/docs/config.md",verified:!0,path:(e,o)=>dot(o,".codex","config.toml")},{id:"junie",label:"JetBrains Junie / AI Assistant",kind:"mcp-json",container:"mcpServers",scopes:["user","workspace"],docs:"https://www.jetbrains.com/help/junie/mcp.html",verified:!1,note:"JetBrains reads this file but the IDE also caches MCP config in Settings — restart the IDE and confirm the server is listed there.",path:(e,o)=>"workspace"===e?path.join(o.cwd,".junie","mcp","mcp.json"):dot(o,".junie","mcp","mcp.json"),entry:plainEntry},{id:"opencode",label:"OpenCode",kind:"mcp-json",container:"mcp",scopes:["user"],docs:"https://opencode.ai/docs/mcp-servers/",verified:!1,note:"OpenCode takes a single command array instead of command + args.",path:(e,o)=>path.join(appConfig(o),"opencode","opencode.json"),entry(e){const o=orEnv(e),n={type:"local",command:[e.command,...e.args],enabled:!0};return o&&(n.environment=o),n}}],BY_ID=new Map(TARGETS.map((e=>[e.id,e]))),ALIASES={code:"vscode","vs-code":"vscode","vscode-code":"vscode",windsurfcodeium:"windsurf","roo-code":"roo",roocode:"roo",jetbrains:"junie","claude-code":"claude",gemini_cli:"gemini","codex-cli":"codex",vsc:"vscodium"};function getTarget(e){if(!e)return null;const o=String(e).toLowerCase().trim();return BY_ID.get(o)||BY_ID.get(ALIASES[o])||null}function targetIds(){return TARGETS.map((e=>e.id))}const VSCODE_VARIANTS=["Code","Code - Insiders","VSCodium"];module.exports={TARGETS:TARGETS,ALIASES:ALIASES,VSCODE_VARIANTS:VSCODE_VARIANTS,getTarget:getTarget,targetIds:targetIds,SERVER_NAME:SERVER_NAME,appConfig:appConfig,zedConfig:zedConfig,home:home};
1
+ "use strict";const os=require("node:os"),path=require("node:path"),{SERVER_NAME:SERVER_NAME,vscodeKeyInput:vscodeKeyInput}=require("./spec.js");function home(e){return e.home||e.env.HOME||e.env.USERPROFILE||os.homedir()}function appConfig(e){const{env:o,platform:n}=e;return o.XDG_CONFIG_HOME?o.XDG_CONFIG_HOME:"win32"===n?o.APPDATA||path.join(home(e),"AppData","Roaming"):"darwin"===n?path.join(home(e),"Library","Application Support"):path.join(home(e),".config")}function zedConfig(e){const{env:o,platform:n}=e;return"win32"===n?path.join(o.APPDATA||path.join(home(e),"AppData","Roaming"),"Zed"):path.join(o.XDG_CONFIG_HOME||path.join(home(e),".config"),"zed")}function dot(e,...o){return path.join(home(e),...o)}function vscodeUserFile(e,o){return path.join(appConfig(e),o,"User","mcp.json")}function orEnv(e){return e.env&&Object.keys(e.env).length?e.env:null}function plainEntry(e){const o=orEnv(e),n={command:e.command,args:e.args};return o&&(n.env=o),n}const TARGETS=[{id:"vscode",label:"VS Code",kind:"mcp-json",container:"servers",scopes:["user","workspace"],docs:"https://code.visualstudio.com/docs/copilot/customization/mcp-servers",verified:!0,supportsKeyPrompt:!0,note:"Copilot agent mode reads `.vscode/mcp.json` for the workspace, or the user file for every project.",path:(e,o)=>"workspace"===e?path.join(o.cwd,".vscode","mcp.json"):vscodeUserFile(o,"Code"),entry(e){const o={type:"stdio",command:e.command,args:e.args},n=orEnv(e);return n&&(o.env=n),o},extras:e=>e.keyRef&&e.keyRef.startsWith("${input:")?{inputs:[vscodeKeyInput()]}:null},{id:"vscode-insiders",label:"VS Code Insiders",kind:"mcp-json",container:"servers",scopes:["user"],docs:"https://code.visualstudio.com/docs/copilot/customization/mcp-servers",verified:!0,supportsKeyPrompt:!0,path:(e,o)=>vscodeUserFile(o,"Code - Insiders"),entry:e=>TARGETS[0].entry(e),extras:e=>TARGETS[0].extras(e)},{id:"vscodium",label:"VSCodium",kind:"mcp-json",container:"servers",scopes:["user","workspace"],docs:"https://code.visualstudio.com/docs/copilot/customization/mcp-servers",verified:!0,supportsKeyPrompt:!0,path:(e,o)=>"workspace"===e?path.join(o.cwd,".vscode","mcp.json"):vscodeUserFile(o,"VSCodium"),entry:e=>TARGETS[0].entry(e),extras:e=>TARGETS[0].extras(e)},{id:"cursor",label:"Cursor",kind:"mcp-json",container:"mcpServers",scopes:["user","workspace"],docs:"https://cursor.com/docs/context/mcp",verified:!0,path:(e,o)=>"workspace"===e?path.join(o.cwd,".cursor","mcp.json"):path.join(appConfig(o),"Cursor","mcp.json"),entry:plainEntry},{id:"windsurf",label:"Windsurf",kind:"mcp-json",container:"mcpServers",scopes:["user"],docs:"https://docs.windsurf.com/windsurf/cascade/mcp",verified:!0,path:(e,o)=>dot(o,".codeium","windsurf","mcp_config.json"),entry:plainEntry},{id:"cline",label:"Cline (VS Code extension)",kind:"mcp-json",container:"mcpServers",scopes:["user"],docs:"https://docs.cline.bot/mcp/configuring-mcp-servers",verified:!0,path:(e,o)=>path.join(appConfig(o),"Code","User","globalStorage","saoudrizwan.claude-dev","settings","cline_mcp_settings.json"),entry:e=>({...plainEntry(e),disabled:!1,autoApprove:[],type:"stdio"})},{id:"roo",label:"Roo Code (VS Code extension)",kind:"mcp-json",container:"mcpServers",scopes:["user"],docs:"https://docs.roocode.com/features/mcp/using-mcp-in-roo",verified:!0,path:(e,o)=>path.join(appConfig(o),"Code","User","globalStorage","rooveterinaryinc.roo-cline","settings","mcp_settings.json"),entry:e=>({...plainEntry(e),disabled:!1,alwaysAllow:[],type:"stdio"})},{id:"zed",label:"Zed",kind:"mcp-json",container:"context_servers",scopes:["user"],docs:"https://zed.dev/docs/ai/mcp",verified:!0,path:(e,o)=>path.join(zedConfig(o),"settings.json"),entry(e){const o={path:e.command,args:e.args},n=orEnv(e);return n&&(o.env=n),{source:"custom",command:o}}},{id:"continue",label:"Continue (VS Code / JetBrains)",kind:"mcp-json",container:"mcpServers",scopes:["user"],docs:"https://docs.continue.dev/customize/deep-dives/mcp",verified:!0,path:(e,o)=>dot(o,".continue","config.json"),entry:plainEntry,yamlWins:!0},{id:"claude",label:"Claude Code (project scope)",kind:"mcp-json",container:"mcpServers",scopes:["workspace"],docs:"https://docs.claude.com/en/docs/claude-code/mcp",verified:!0,path:(e,o)=>path.join(o.cwd,".mcp.json"),entry:plainEntry},{id:"gemini",label:"Gemini CLI",kind:"mcp-json",container:"mcpServers",scopes:["user"],docs:"https://github.com/google-gemini/gemini-cli/blob/main/docs/tools/mcp-server.md",verified:!0,path:(e,o)=>dot(o,".gemini","settings.json"),entry:plainEntry},{id:"codex",label:"Codex CLI",kind:"mcp-toml",container:"mcp_servers",scopes:["user"],docs:"https://github.com/openai/codex/blob/main/docs/config.md",verified:!0,path:(e,o)=>dot(o,".codex","config.toml")},{id:"junie",label:"JetBrains Junie / AI Assistant",kind:"mcp-json",container:"mcpServers",scopes:["user","workspace"],docs:"https://www.jetbrains.com/help/junie/mcp.html",verified:!1,note:"JetBrains reads this file but the IDE also caches MCP config in Settings — restart the IDE and confirm the server is listed there.",path:(e,o)=>"workspace"===e?path.join(o.cwd,".junie","mcp","mcp.json"):dot(o,".junie","mcp","mcp.json"),entry:plainEntry},{id:"opencode",label:"OpenCode",kind:"mcp-json",container:"mcp",scopes:["user"],docs:"https://opencode.ai/docs/mcp-servers/",verified:!1,note:"OpenCode takes a single command array instead of command + args.",path:(e,o)=>path.join(appConfig(o),"opencode","opencode.json"),entry(e){const o=orEnv(e),n={type:"local",command:[e.command,...e.args],enabled:!0};return o&&(n.environment=o),n}}],BY_ID=new Map(TARGETS.map(e=>[e.id,e])),ALIASES={code:"vscode","vs-code":"vscode","vscode-code":"vscode",windsurfcodeium:"windsurf","roo-code":"roo",roocode:"roo",jetbrains:"junie","claude-code":"claude",gemini_cli:"gemini","codex-cli":"codex",vsc:"vscodium"};function getTarget(e){if(!e)return null;const o=String(e).toLowerCase().trim();return BY_ID.get(o)||BY_ID.get(ALIASES[o])||null}function targetIds(){return TARGETS.map(e=>e.id)}const VSCODE_VARIANTS=["Code","Code - Insiders","VSCodium"];module.exports={TARGETS:TARGETS,ALIASES:ALIASES,VSCODE_VARIANTS:VSCODE_VARIANTS,getTarget:getTarget,targetIds:targetIds,SERVER_NAME:SERVER_NAME,appConfig:appConfig,zedConfig:zedConfig,home:home};
@@ -1,3 +1,3 @@
1
1
  // SPDX-License-Identifier: AGPL-3.0-or-later
2
2
  // Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
3
- "use strict";const fs=require("node:fs"),os=require("node:os"),path=require("node:path");function dataDir(e={}){if(e.dir)return e.dir;const r=e.env||process.env;if(r.AEGISCODE_HOME)return r.AEGISCODE_HOME;const n=e.home||(()=>{try{return os.homedir()}catch{return r.HOME||r.USERPROFILE||""}})();return path.join(n,".aegiscode")}function registryPath(e={}){return path.join(dataDir(e),"harnesses.json")}function harnessName(e){const r=e&&(e.name||e.title);return String(null==r?"":r).trim().toLowerCase().replace(/\s+/g,"-").replace(/_/g,"-").replace(/[^a-z0-9.-]/g,"").replace(/-+/g,"-").replace(/^-+|-+$/g,"")||"unknown"}function deniedHarnesses(e={}){const r=e.env||process.env;return String(r.AEGISCODE_HARNESS_DENY||"").split(/[\s,]+/).map((e=>e.trim().toLowerCase())).filter(Boolean)}function admit(e,r={}){const n=harnessName(e),s=deniedHarnesses(r);return s.includes(n)||s.includes("*")?{ok:!1,name:n,reason:`AEGIS: harness "${n}" is denied by AEGISCODE_HARNESS_DENY. Unset that variable (or remove this name from it) to admit it.`}:{ok:!0,name:n,reason:""}}function read(e={}){const r=registryPath(e);try{const e=JSON.parse(fs.readFileSync(r,"utf8"));return e&&"object"==typeof e&&e&&"object"==typeof e.harnesses&&e.harnesses?e.harnesses:{}}catch{return{}}}function record(e,r={}){const n=harnessName(e),s=(new Date).toISOString();try{const t=read(r),a=t[n]||{},i=e&&e.version?String(e.version):a.version||null;t[n]={firstSeen:a.firstSeen||s,lastSeen:s,calls:(Number(a.calls)||0)+1,version:i};const o=registryPath(r);fs.mkdirSync(path.dirname(o),{recursive:!0,mode:448});const c=`${o}.${process.pid}.tmp`;return fs.writeFileSync(c,JSON.stringify({harnesses:t},null,2),{mode:384}),fs.renameSync(c,o),{ok:!0,name:n}}catch{return{ok:!1,name:n}}}module.exports={dataDir:dataDir,registryPath:registryPath,harnessName:harnessName,deniedHarnesses:deniedHarnesses,admit:admit,read:read,record:record};
3
+ "use strict";const fs=require("node:fs"),os=require("node:os"),path=require("node:path");function dataDir(e={}){if(e.dir)return e.dir;const r=e.env||process.env;if(r.AEGISCODE_HOME)return r.AEGISCODE_HOME;const n=e.home||(()=>{try{return os.homedir()}catch{return r.HOME||r.USERPROFILE||""}})();return path.join(n,".aegiscode")}function registryPath(e={}){return path.join(dataDir(e),"harnesses.json")}function harnessName(e){const r=e&&(e.name||e.title);return String(null==r?"":r).trim().toLowerCase().replace(/\s+/g,"-").replace(/_/g,"-").replace(/[^a-z0-9.-]/g,"").replace(/-+/g,"-").replace(/^-+|-+$/g,"")||"unknown"}function deniedHarnesses(e={}){const r=e.env||process.env;return String(r.AEGISCODE_HARNESS_DENY||"").split(/[\s,]+/).map(e=>e.trim().toLowerCase()).filter(Boolean)}function admit(e,r={}){const n=harnessName(e),s=deniedHarnesses(r);return s.includes(n)||s.includes("*")?{ok:!1,name:n,reason:`AEGIS: harness "${n}" is denied by AEGISCODE_HARNESS_DENY. Unset that variable (or remove this name from it) to admit it.`}:{ok:!0,name:n,reason:""}}function read(e={}){const r=registryPath(e);try{const e=JSON.parse(fs.readFileSync(r,"utf8"));return e&&"object"==typeof e&&e&&"object"==typeof e.harnesses&&e.harnesses?e.harnesses:{}}catch{return{}}}function record(e,r={}){const n=harnessName(e),s=(new Date).toISOString();try{const t=read(r),a=t[n]||{},i=e&&e.version?String(e.version):a.version||null;t[n]={firstSeen:a.firstSeen||s,lastSeen:s,calls:(Number(a.calls)||0)+1,version:i};const o=registryPath(r);fs.mkdirSync(path.dirname(o),{recursive:!0,mode:448});const c=`${o}.${process.pid}.tmp`;return fs.writeFileSync(c,JSON.stringify({harnesses:t},null,2),{mode:384}),fs.renameSync(c,o),{ok:!0,name:n}}catch{return{ok:!1,name:n}}}module.exports={dataDir:dataDir,registryPath:registryPath,harnessName:harnessName,deniedHarnesses:deniedHarnesses,admit:admit,read:read,record:record};
@@ -1,4 +1,4 @@
1
1
  #!/usr/bin/env node
2
2
  // SPDX-License-Identifier: AGPL-3.0-or-later
3
3
  // Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
4
- "use strict";const{createClient:createClient}=require("../client/aegis.js"),credentials=require("../client/credentials.js"),{autoProvisionApiKey:autoProvisionApiKey}=require("../client/auto-provision.js"),{createTools:createTools}=require("./tools.js"),admission=require("./admission.js");try{const e=require("../client/env-file.js").loadEnvFile();e.loose&&process.stderr.write(`aegis: ${e.file} is readable by other accounts (mode ${e.mode.toString(8)}) — consider \`chmod 600\` on it.\n`)}catch{}const aegis=createClient(credentials.clientOptions()),{TOOLS:TOOLS,toolList:toolList}=createTools(aegis),API_BASE=aegis.apiBase,SERVER_NAME="aegis",SERVER_VERSION="0.4.0";function missingKeyText(){const{path:e}=credentials.keyStatus();return["No AEGIS API key is configured for this session.","","Set one with any of:"," • `aegiscode login` in a terminal (saves it to "+e+", mode 0600)"," • export AEGIS_API_KEY=… in the environment Claude Code was launched from"," • put `AEGIS_API_KEY=…` in ~/.aegiscode/.env (read at startup, every host)","","Then restart Claude Code. Get a key at https://aegiscloud.org."].join("\n")}let provisionAttempted=!1;async function ensureApiKey(){if(aegis.apiKey||provisionAttempted)return;provisionAttempted=!0;const e=await autoProvisionApiKey(aegis,credentials,{app:"mcp"});e.error?process.stderr.write(`aegis: device auto-registration failed (${e.error.message}) — falling back to manual setup.\n`):e.key?process.stderr.write("aegis: no API key was configured — auto-provisioned a free AEGIS account"+(e.ok?` (key saved to ${credentials.keyStatus().path}).\n`:" (could not save it — see above).\n")+`Fund it at ${aegis.promptUrl("topup","device_autoprovision")} or set your own BYOK key with aegis_byok_set.\n`):process.stderr.write("aegis: device auto-registration returned no usable key — falling back to manual setup.\n")}function send(e){process.stdout.write(JSON.stringify(e)+"\n")}function reply(e,t){send({jsonrpc:"2.0",id:e,result:t})}function replyError(e,t,i){send({jsonrpc:"2.0",id:e,error:{code:t,message:i}})}let caller={ok:!0,name:"unknown",reason:""},pending=0,stdinClosed=!1;function maybeExit(){stdinClosed&&0===pending&&process.exit(0)}async function handleMessage(e){const{id:t,method:i,params:r}=e,o=null==t;try{switch(i){case"initialize":{const e=r&&r.clientInfo||null;return caller=admission.admit(e),caller.ok?admission.record(e):process.stderr.write(`${caller.reason}\n`),void reply(t,{protocolVersion:r&&r.protocolVersion||"2024-11-05",capabilities:{tools:{}},serverInfo:{name:"aegis",version:"0.4.0"}})}case"notifications/initialized":case"notifications/cancelled":return;case"ping":return void(o||reply(t,{}));case"tools/list":return void reply(t,{tools:toolList()});case"tools/call":{if(!caller.ok)return void reply(t,{content:[{type:"text",text:caller.reason}],isError:!0});const i=r&&r.name,o=TOOLS[i];if(!o)return void reply(t,{content:[{type:"text",text:`Unknown tool: ${i}`}],isError:!0});if(aegis.apiKey||await ensureApiKey(),!aegis.apiKey)return void reply(t,{content:[{type:"text",text:missingKeyText()}],isError:!0});try{reply(t,{content:[{type:"text",text:await o.run(r&&r.arguments||{})}],isError:!1})}catch(e){reply(t,{content:[{type:"text",text:`AEGIS error: ${e.message}`}],isError:!0})}return}default:return void(o||replyError(t,-32601,`Method not found: ${i}`))}}catch(e){o||replyError(t,-32603,e.message)}}const MAX_LINE_BYTES=33554432;function overflowNote(){process.stderr.write("aegis: discarded a JSON-RPC message over 33554432 bytes.\n")}let buffer="",discarding=!1;process.stdin.setEncoding("utf8"),process.stdin.on("data",(e=>{if(discarding){const t=e.indexOf("\n");if(-1===t)return;discarding=!1,e=e.slice(t+1)}let t;for(buffer+=e;-1!==(t=buffer.indexOf("\n"));){const e=buffer.slice(0,t).trim();if(buffer=buffer.slice(t+1),!e)continue;if(e.length>33554432){overflowNote();continue}let i;try{i=JSON.parse(e)}catch{continue}pending++,Promise.resolve(handleMessage(i)).finally((()=>{pending--,maybeExit()}))}buffer.length>33554432&&(buffer="",discarding=!0,overflowNote())})),process.stdin.on("end",(()=>{stdinClosed=!0,maybeExit()}));
4
+ "use strict";const{createClient:createClient}=require("../client/aegis.js"),credentials=require("../client/credentials.js"),{autoProvisionApiKey:autoProvisionApiKey}=require("../client/auto-provision.js"),{createTools:createTools}=require("./tools.js"),admission=require("./admission.js");try{const e=require("../client/env-file.js").loadEnvFile();e.loose&&process.stderr.write(`aegis: ${e.file} is readable by other accounts (mode ${e.mode.toString(8)}) — consider \`chmod 600\` on it.\n`)}catch{}const aegis=createClient(credentials.clientOptions()),{TOOLS:TOOLS,toolList:toolList}=createTools(aegis),API_BASE=aegis.apiBase,SERVER_NAME="aegis",SERVER_VERSION="0.4.0";function missingKeyText(){const{path:e}=credentials.keyStatus();return["No AEGIS API key is configured for this session.","","Set one with any of:"," • `aegiscode login` in a terminal (saves it to "+e+", mode 0600)"," • export AEGIS_API_KEY=… in the environment Claude Code was launched from"," • put `AEGIS_API_KEY=…` in ~/.aegiscode/.env (read at startup, every host)","","Then restart Claude Code. Get a key at https://aegiscloud.org."].join("\n")}let provisionAttempted=!1;async function ensureApiKey(){if(aegis.apiKey||provisionAttempted)return;provisionAttempted=!0;const e=await autoProvisionApiKey(aegis,credentials,{app:"mcp"});e.error?process.stderr.write(`aegis: device auto-registration failed (${e.error.message}) — falling back to manual setup.\n`):e.key?process.stderr.write("aegis: no API key was configured — auto-provisioned a free AEGIS account"+(e.ok?` (key saved to ${credentials.keyStatus().path}).\n`:" (could not save it — see above).\n")+`Fund it at ${aegis.promptUrl("topup","device_autoprovision")} or set your own BYOK key with aegis_byok_set.\n`):process.stderr.write("aegis: device auto-registration returned no usable key — falling back to manual setup.\n")}function send(e){process.stdout.write(JSON.stringify(e)+"\n")}function reply(e,t){send({jsonrpc:"2.0",id:e,result:t})}function replyError(e,t,i){send({jsonrpc:"2.0",id:e,error:{code:t,message:i}})}let caller={ok:!0,name:"unknown",reason:""},pending=0,stdinClosed=!1;function maybeExit(){stdinClosed&&0===pending&&process.exit(0)}async function handleMessage(e){const{id:t,method:i,params:r}=e,o=null==t;try{switch(i){case"initialize":{const e=r&&r.clientInfo||null;return caller=admission.admit(e),caller.ok?admission.record(e):process.stderr.write(`${caller.reason}\n`),void reply(t,{protocolVersion:r&&r.protocolVersion||"2024-11-05",capabilities:{tools:{}},serverInfo:{name:"aegis",version:"0.4.0"}})}case"notifications/initialized":case"notifications/cancelled":return;case"ping":return void(o||reply(t,{}));case"tools/list":return void reply(t,{tools:toolList()});case"tools/call":{if(!caller.ok)return void reply(t,{content:[{type:"text",text:caller.reason}],isError:!0});const i=r&&r.name,o=TOOLS[i];if(!o)return void reply(t,{content:[{type:"text",text:`Unknown tool: ${i}`}],isError:!0});if(aegis.apiKey||await ensureApiKey(),!aegis.apiKey)return void reply(t,{content:[{type:"text",text:missingKeyText()}],isError:!0});try{reply(t,{content:[{type:"text",text:await o.run(r&&r.arguments||{})}],isError:!1})}catch(e){reply(t,{content:[{type:"text",text:`AEGIS error: ${e.message}`}],isError:!0})}return}default:return void(o||replyError(t,-32601,`Method not found: ${i}`))}}catch(e){o||replyError(t,-32603,e.message)}}const MAX_LINE_BYTES=33554432;function overflowNote(){process.stderr.write("aegis: discarded a JSON-RPC message over 33554432 bytes.\n")}let buffer="",discarding=!1;process.stdin.setEncoding("utf8"),process.stdin.on("data",e=>{if(discarding){const t=e.indexOf("\n");if(-1===t)return;discarding=!1,e=e.slice(t+1)}let t;for(buffer+=e;-1!==(t=buffer.indexOf("\n"));){const e=buffer.slice(0,t).trim();if(buffer=buffer.slice(t+1),!e)continue;if(e.length>33554432){overflowNote();continue}let i;try{i=JSON.parse(e)}catch{continue}pending++,Promise.resolve(handleMessage(i)).finally(()=>{pending--,maybeExit()})}buffer.length>33554432&&(buffer="",discarding=!0,overflowNote())}),process.stdin.on("end",()=>{stdinClosed=!0,maybeExit()});
@@ -1,3 +1,3 @@
1
1
  // SPDX-License-Identifier: AGPL-3.0-or-later
2
2
  // Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
3
- "use strict";const foreignMemory=require("../client/foreign-memory.js");function createTools(e){if(!e||"object"!=typeof e)throw new TypeError("createTools(client): a client instance is required");const t=e,o={aegis_status:{description:"Check the current AEGIS account: validates the API key and reports the plan, email, and whether cloud memory is enabled. Call this first to confirm setup.",inputSchema:{type:"object",properties:{},additionalProperties:!1},async run(){const e=await t.verifyApiKey();return["Key valid: "+(e.valid?"yes":"no"),`Plan: ${e.plan||"unknown"}`,e.email?`Account: ${e.email}`:null,"Memory: "+(e.memory_token?"enabled (cloud sync available)":"not enabled"),`API base: ${t.apiBase}`].filter(Boolean).join("\n")}},aegis_ask:{description:"Send a prompt to AEGIS pooled inference, billed against the account's token bank. List models with aegis_list_models and pass any id as `model`; omit `model` to let the server pick its default. `mode` is a legacy server-side shorthand and is never required.",inputSchema:{type:"object",properties:{prompt:{type:"string",description:"The user prompt / question."},model:{type:"string",description:"Pin any model id from aegis_list_models — or omit for the server default."},mode:{type:"string",description:"Legacy server-side shorthand (e.g. 'fast', 'smart', 'neo'). Optional — never defaulted client-side."},system:{type:"string",description:"Optional system instruction."},max_tokens:{type:"integer",description:"Max output tokens. The server enforces the true ceiling; omit for the server default.",minimum:1,maximum:64e3}},required:["prompt"],additionalProperties:!1},async run(e){const o=await t.chatCompletion({prompt:e.prompt,system:e.system,model:e.model,mode:e.mode,maxTokens:e.max_tokens}),s=o.choices&&o.choices[0]||{};return`${s.message&&s.message.content||"(empty response)"}\n\n— ${[o.model?`model: ${o.model}`:null,o.usage?`tokens: ${o.usage.total_tokens}`:null].filter(Boolean).join(" · ")}`}},aegis_list_models:{description:"List the exact models available to pin with aegis_ask's `model` argument — the server's model list is the truth, and omitting `model` uses the server default.",inputSchema:{type:"object",properties:{},additionalProperties:!1},async run(){const e=(await t.listModels()).models||[];return e.length?["Pass one of these as aegis_ask's `model` argument:","",...e.map((e=>` ${e.id} (${(e.capabilities||[]).join(", ")})`))].join("\n"):"No pinnable models are currently configured on AEGIS."}},aegis_balance:{description:"Check the AEGIS token bank balance and recent spend. Call this before aegis_ask if you're unsure whether the account has funds, or to see what recent calls cost.",inputSchema:{type:"object",properties:{},additionalProperties:!1},async run(){const e=await t.tokenBankBalance(),o=[`Balance: €${Number(e.balance_eur||0).toFixed(2)}`],s=(e.ledger||[]).slice(0,5);if(s.length){o.push("","Recent activity:");for(const e of s){const t=null!=e.amount_eur?Number(e.amount_eur):-Number(e.charged_micros||0)/1e6,s=Math.abs(t),r=`${t<0?"-":"+"}€${s<.01?s.toFixed(4):s.toFixed(2)}`,i="topup"===e.kind?"top-up":e.kind||"",n=e.model_key||i||"",a=e.tokens_in||e.tokens_out?` ${e.tokens_in||0}/${e.tokens_out||0} tokens`:"";o.push(` ${e.created_at||""} ${n}${a} ${r}`)}}else o.push("No spend yet.");var r;return(e.balance_eur||0)<=0&&o.push("",`Balance is empty — top up at ${r="topup","function"==typeof t.promptUrl?t.promptUrl(r,"topup_bank"):`https://aegiscloud.org/go/${r}`}, or set your own provider key with aegis_byok_set to use aegis_ask for free at cost.`),o.join("\n")}},aegis_byok_providers:{description:"List every provider that accepts a Bring-Your-Own-Key on AEGIS: the exact provider id to pass to aegis_byok_set, the models each one unlocks, where to create the key, and the prefix a valid key starts with. Call this before aegis_byok_set so the user knows which key to go get rather than guessing a provider id.",inputSchema:{type:"object",properties:{},additionalProperties:!1},async run(){const e=(await t.byokProviders()).providers||[];if(!e.length)return"AEGIS is not advertising any BYOK providers right now.";const o=["Set one with aegis_byok_set — pass the id exactly as shown:"];for(const t of e){const e=(t.models||[]).map((e=>"string"==typeof e?e:e&&e.id)).filter(Boolean),s=t.configured?" ✓ set"+(t.masked?` (${t.masked})`:""):"";o.push(""),o.push(` ${t.id}${s}`),t.label&&o.push(` ${t.label}`),e.length&&o.push(` models: ${e.join(", ")}`),t.key_prefix&&o.push(` key starts with: ${t.key_prefix}`),t.key_url&&o.push(` get a key: ${t.key_url}`)}return o.join("\n")}},aegis_byok_status:{description:"List which providers have a Bring-Your-Own-Key configured on this AEGIS account (known ids: openai, anthropic, groq, openrouter, together, deepseek, gemini, …). A configured BYOK key is used automatically by aegis_ask instead of the pooled balance for that provider, so calls no longer cost AEGIS token-bank funds.",inputSchema:{type:"object",properties:{},additionalProperties:!1},async run(){const e=await t.byokStatus(),o=Object.entries(e||{});if(!o.length)return"No BYOK providers are configured. Run aegis_byok_providers to see what you can set.";let s={};try{const e=await t.byokProviders();for(const t of e.providers||[])s[t.id]=t.label||""}catch{}return`BYOK keys:\n${o.map((([e,t])=>{const o=t&&t.set;return` ${e}${s[e]?` ${s[e]}`:""}: ${o?`set (${t.masked})`:"not set"}`})).join("\n")}`}},aegis_byok_set:{description:"Set or remove a Bring-Your-Own-Key API key for a provider on this AEGIS account (known ids: openai, anthropic, groq, openrouter, together, deepseek, gemini, …; the server validates what it supports). Once set, aegis_ask uses that key directly for that provider instead of the pooled AEGIS balance — unlimited use at the user's own cost. Omit api_key to remove a previously set key.",inputSchema:{type:"object",properties:{provider:{type:"string",description:"Which provider this key is for (known ids: openai, anthropic, groq, openrouter, together, deepseek, gemini, …)."},api_key:{type:"string",description:"The provider's own API key. Omit to delete the stored key instead."}},required:["provider"],additionalProperties:!1},run:async e=>(await t.byokSet(e.provider,e.api_key)).message||(e.api_key?`${e.provider} key saved.`:`${e.provider} key removed.`)},aegis_memory_search:{description:"Search the user's AEGIS cloud memory (persists across machines and sessions). Returns the most relevant stored entries for a query.",inputSchema:{type:"object",properties:{query:{type:"string",description:"Search text. Empty returns most recent."},limit:{type:"integer",description:"Max entries (1-50). Default 5.",minimum:1,maximum:50}},required:["query"],additionalProperties:!1},async run(e){const o=(await t.memorySearch(e.query,e.limit||5)).entries||[];return o.length?o.map(((e,t)=>{const o=e.timestamp||e.createdAt||"",s=e.tags&&e.tags.length?` [${e.tags.join(", ")}]`:"";return`${t+1}. ${e.content}${s}${o?`\n (${o})`:""}`})).join("\n"):`No memory entries matched "${e.query}".`}},aegis_memory_save:{description:"Save a note to the user's AEGIS cloud memory so it persists across machines and future sessions. Use for durable facts, decisions, or preferences the user asks you to remember.",inputSchema:{type:"object",properties:{content:{type:"string",description:"The fact/note to store."},tags:{type:"array",items:{type:"string"},description:"Optional tags."},importance:{type:"integer",description:"Optional 1-10 salience. Default 5.",minimum:1,maximum:10},session:{type:"string",description:"Optional session/label to group under."}},required:["content"],additionalProperties:!1},async run(e){const o={id:t.randomUUID(),content:e.content,role:"assistant",source:"claude-code",session:e.session||"claude-code",tags:e.tags||[],importance:"number"==typeof e.importance?e.importance:5,timestamp:(new Date).toISOString()};return`Saved ${(await t.memorySave(o)).saved||1} memory entry (id ${o.id}).`}},aegis_memory_import:{description:"Import memory and past conversation context from OTHER AI coding tools installed on this machine (Claude Code, Codex, Cursor, Gemini CLI, Continue, Goose, opencode, Windsurf, Zed, and a local AEGIS engine) into the user's AEGIS cloud memory. Scans read-only; nothing in the other tools' directories is modified. Defaults to a DRY RUN that only reports what it found — pass confirm:true to actually save. Entries are content-addressed, so re-running never duplicates.",inputSchema:{type:"object",properties:{confirm:{type:"boolean",description:"false (default) = report only. true = actually write the entries to AEGIS memory."},sources:{type:"array",items:{type:"string"},description:'Optional subset of source ids to import (e.g. ["claude-code"]). Omit for every source found on this machine.'},limit:{type:"integer",description:"Max entries to import (1-5000). Default 1000.",minimum:1,maximum:5e3}},additionalProperties:!1},async run(e){const o=e.limit||1e3,s=foreignMemory.scan({sources:e.sources,limit:o}),r=foreignMemory.describe(s);if(!s.entries.length)return`${r}\n\nNothing to import.`;if(!e.confirm)return[r,"",`Dry run — ${s.totals.entries} entries would be saved to AEGIS memory under ${s.totals.sourcesWithEntries} session(s) (${s.totals.skipped} skipped as too short/noise).`,"Call this tool again with confirm:true to save them."].join("\n");let i=0;const n=[];for(const o of foreignMemory.chunk(s.entries,200))try{const e=await t.memorySaveBatch(o);i+=e&&e.saved||o.length}catch(e){n.push(e.message);break}return n.length?`${r}\n\nSaved ${i} of ${s.totals.entries} entries, then stopped: ${n[0]}`:`${r}\n\nSaved ${i} entries to AEGIS memory. They are searchable now with aegis_memory_search.`}},aegis_memory_list:{description:"List the most recent entries in the user's AEGIS cloud memory. Useful to review what AEGIS already remembers.",inputSchema:{type:"object",properties:{limit:{type:"integer",description:"Max entries (1-50). Default 10.",minimum:1,maximum:50}},additionalProperties:!1},async run(e){const o=(await t.memoryList(e.limit||10)).entries||[];if(!o.length)return"AEGIS cloud memory is empty.";const s=o.map(((e,t)=>`${t+1}. ${e.content}`)).join("\n");return`Recent ${o.length} entries:\n${s}`}}};return{TOOLS:o,toolList:function(){return Object.entries(o).map((([e,t])=>({name:e,description:t.description,inputSchema:t.inputSchema})))}}}module.exports={createTools:createTools};
3
+ "use strict";const foreignMemory=require("../client/foreign-memory.js");function createTools(e,t={}){if(!e||"object"!=typeof e)throw new TypeError("createTools(client): a client instance is required");const o=t&&"object"==typeof t.localWiki?t.localWiki:null,i=e,s={aegis_status:{description:"Check the current AEGIS account: validates the API key and reports the plan, email, and whether cloud memory is enabled. Call this first to confirm setup.",inputSchema:{type:"object",properties:{},additionalProperties:!1},async run(){const e=await i.verifyApiKey();return["Key valid: "+(e.valid?"yes":"no"),`Plan: ${e.plan||"unknown"}`,e.email?`Account: ${e.email}`:null,"Memory: "+(e.memory_token?"enabled (cloud sync available)":"not enabled"),`API base: ${i.apiBase}`].filter(Boolean).join("\n")}},aegis_ask:{description:"Send a prompt to AEGIS pooled inference, billed against the account's token bank. List models with aegis_list_models and pass any id as `model`; omit `model` to let the server pick its default. `mode` is a legacy server-side shorthand and is never required.",inputSchema:{type:"object",properties:{prompt:{type:"string",description:"The user prompt / question."},model:{type:"string",description:"Pin any model id from aegis_list_models — or omit for the server default."},mode:{type:"string",description:"Legacy server-side shorthand (e.g. 'fast', 'smart', 'neo'). Optional — never defaulted client-side."},system:{type:"string",description:"Optional system instruction."},max_tokens:{type:"integer",description:"Max output tokens. The server enforces the true ceiling; omit for the server default.",minimum:1,maximum:64e3}},required:["prompt"],additionalProperties:!1},async run(e){const t=await i.chatCompletion({prompt:e.prompt,system:e.system,model:e.model,mode:e.mode,maxTokens:e.max_tokens}),o=t.choices&&t.choices[0]||{};return`${o.message&&o.message.content||"(empty response)"}\n\n— ${[t.model?`model: ${t.model}`:null,t.usage?`tokens: ${t.usage.total_tokens}`:null].filter(Boolean).join(" · ")}`}},aegis_list_models:{description:"List the exact models available to pin with aegis_ask's `model` argument — the server's model list is the truth, and omitting `model` uses the server default.",inputSchema:{type:"object",properties:{},additionalProperties:!1},async run(){const e=(await i.listModels()).models||[];return e.length?["Pass one of these as aegis_ask's `model` argument:","",...e.map(e=>` ${e.id} (${(e.capabilities||[]).join(", ")})`)].join("\n"):"No pinnable models are currently configured on AEGIS."}},aegis_balance:{description:"Check the AEGIS token bank balance and recent spend. Call this before aegis_ask if you're unsure whether the account has funds, or to see what recent calls cost.",inputSchema:{type:"object",properties:{},additionalProperties:!1},async run(){const e=await i.tokenBankBalance(),t=[`Balance: €${Number(e.balance_eur||0).toFixed(2)}`],o=(e.ledger||[]).slice(0,5);if(o.length){t.push("","Recent activity:");for(const e of o){const o=null!=e.amount_eur?Number(e.amount_eur):-Number(e.charged_micros||0)/1e6,i=Math.abs(o),s=`${o<0?"-":"+"}€${i<.01?i.toFixed(4):i.toFixed(2)}`,r="topup"===e.kind?"top-up":e.kind||"",n=e.model_key||r||"",a=e.tokens_in||e.tokens_out?` ${e.tokens_in||0}/${e.tokens_out||0} tokens`:"";t.push(` ${e.created_at||""} ${n}${a} ${s}`)}}else t.push("No spend yet.");var s;return(e.balance_eur||0)<=0&&t.push("",`Balance is empty — top up at ${s="topup","function"==typeof i.promptUrl?i.promptUrl(s,"topup_bank"):`https://aegiscloud.org/go/${s}`}, or set your own provider key with aegis_byok_set to use aegis_ask for free at cost.`),t.join("\n")}},aegis_byok_providers:{description:"List every provider that accepts a Bring-Your-Own-Key on AEGIS: the exact provider id to pass to aegis_byok_set, the models each one unlocks, where to create the key, and the prefix a valid key starts with. Call this before aegis_byok_set so the user knows which key to go get rather than guessing a provider id.",inputSchema:{type:"object",properties:{},additionalProperties:!1},async run(){const e=(await i.byokProviders()).providers||[];if(!e.length)return"AEGIS is not advertising any BYOK providers right now.";const t=["Set one with aegis_byok_set — pass the id exactly as shown:"];for(const o of e){const e=(o.models||[]).map(e=>"string"==typeof e?e:e&&e.id).filter(Boolean),i=o.configured?" ✓ set"+(o.masked?` (${o.masked})`:""):"";t.push(""),t.push(` ${o.id}${i}`),o.label&&t.push(` ${o.label}`),e.length&&t.push(` models: ${e.join(", ")}`),o.key_prefix&&t.push(` key starts with: ${o.key_prefix}`),o.key_url&&t.push(` get a key: ${o.key_url}`)}return t.join("\n")}},aegis_byok_status:{description:"List which providers have a Bring-Your-Own-Key configured on this AEGIS account (known ids: openai, anthropic, groq, openrouter, together, deepseek, gemini, …). A configured BYOK key is used automatically by aegis_ask instead of the pooled balance for that provider, so calls no longer cost AEGIS token-bank funds.",inputSchema:{type:"object",properties:{},additionalProperties:!1},async run(){const e=await i.byokStatus(),t=Object.entries(e||{});if(!t.length)return"No BYOK providers are configured. Run aegis_byok_providers to see what you can set.";let o={};try{const e=await i.byokProviders();for(const t of e.providers||[])o[t.id]=t.label||""}catch{}return`BYOK keys:\n${t.map(([e,t])=>{const i=t&&t.set;return` ${e}${o[e]?` ${o[e]}`:""}: ${i?`set (${t.masked})`:"not set"}`}).join("\n")}`}},aegis_byok_set:{description:"Set or remove a Bring-Your-Own-Key API key for a provider on this AEGIS account (known ids: openai, anthropic, groq, openrouter, together, deepseek, gemini, …; the server validates what it supports). Once set, aegis_ask uses that key directly for that provider instead of the pooled AEGIS balance — unlimited use at the user's own cost. Omit api_key to remove a previously set key.",inputSchema:{type:"object",properties:{provider:{type:"string",description:"Which provider this key is for (known ids: openai, anthropic, groq, openrouter, together, deepseek, gemini, …)."},api_key:{type:"string",description:"The provider's own API key. Omit to delete the stored key instead."}},required:["provider"],additionalProperties:!1},run:async e=>(await i.byokSet(e.provider,e.api_key)).message||(e.api_key?`${e.provider} key saved.`:`${e.provider} key removed.`)},aegis_memory_search:{description:"Search the user's AEGIS cloud memory (persists across machines and sessions). Returns the most relevant stored entries for a query.",inputSchema:{type:"object",properties:{query:{type:"string",description:"Search text. Empty returns most recent."},limit:{type:"integer",description:"Max entries (1-50). Default 5.",minimum:1,maximum:50}},required:["query"],additionalProperties:!1},async run(e){const t=(await i.memorySearch(e.query,e.limit||5)).entries||[],s=o?o.search(e.query,e.limit||5):[];if(!s.length&&!t.length)return`No memory entries matched "${e.query}".`;const r=[];let n=0;for(const e of s)r.push(`${++n}. [wiki] ${e.title}: ${e.value??""}\n ${e.body}`);for(const e of t){const t=e.timestamp||e.createdAt||"",o=e.tags&&e.tags.length?` [${e.tags.join(", ")}]`:"";r.push(`${++n}. ${e.content}${o}${t?`\n (${t})`:""}`)}return r.join("\n")}},aegis_memory_save:{description:"Save a note to the user's AEGIS cloud memory so it persists across machines and future sessions. Use for durable facts, decisions, or preferences the user asks you to remember.",inputSchema:{type:"object",properties:{content:{type:"string",description:"The fact/note to store."},tags:{type:"array",items:{type:"string"},description:"Optional tags."},importance:{type:"integer",description:"Optional 1-10 salience. Default 5.",minimum:1,maximum:10},session:{type:"string",description:"Optional session/label to group under."}},required:["content"],additionalProperties:!1},async run(e){const t={id:i.randomUUID(),content:e.content,role:"assistant",source:"claude-code",session:e.session||"claude-code",tags:e.tags||[],importance:"number"==typeof e.importance?e.importance:5,timestamp:(new Date).toISOString()};return`Saved ${(await i.memorySave(t)).saved||1} memory entry (id ${t.id}).`}},aegis_memory_import:{description:"Import memory and past conversation context from OTHER AI coding tools installed on this machine (Claude Code, Codex, Cursor, Gemini CLI, Continue, Goose, opencode, Windsurf, Zed, and a local AEGIS engine) into the user's AEGIS cloud memory. Scans read-only; nothing in the other tools' directories is modified. Defaults to a DRY RUN that only reports what it found — pass confirm:true to actually save. Entries are content-addressed, so re-running never duplicates.",inputSchema:{type:"object",properties:{confirm:{type:"boolean",description:"false (default) = report only. true = actually write the entries to AEGIS memory."},sources:{type:"array",items:{type:"string"},description:'Optional subset of source ids to import (e.g. ["claude-code"]). Omit for every source found on this machine.'},limit:{type:"integer",description:"Max entries to import (1-5000). Default 1000.",minimum:1,maximum:5e3}},additionalProperties:!1},async run(e){const t=e.limit||1e3,o=foreignMemory.scan({sources:e.sources,limit:t}),s=foreignMemory.describe(o);if(!o.entries.length)return`${s}\n\nNothing to import.`;if(!e.confirm)return[s,"",`Dry run — ${o.totals.entries} entries would be saved to AEGIS memory under ${o.totals.sourcesWithEntries} session(s) (${o.totals.skipped} skipped as too short/noise).`,"Call this tool again with confirm:true to save them."].join("\n");let r=0;const n=[];for(const t of foreignMemory.chunk(o.entries,200))try{const e=await i.memorySaveBatch(t);r+=e&&e.saved||t.length}catch(e){n.push(e.message);break}return n.length?`${s}\n\nSaved ${r} of ${o.totals.entries} entries, then stopped: ${n[0]}`:`${s}\n\nSaved ${r} entries to AEGIS memory. They are searchable now with aegis_memory_search.`}},aegis_memory_list:{description:"List the most recent entries in the user's AEGIS cloud memory. Useful to review what AEGIS already remembers.",inputSchema:{type:"object",properties:{limit:{type:"integer",description:"Max entries (1-50). Default 10.",minimum:1,maximum:50}},additionalProperties:!1},async run(e){const t=(await i.memoryList(e.limit||10)).entries||[];if(!t.length)return"AEGIS cloud memory is empty.";const o=t.map((e,t)=>`${t+1}. ${e.content}`).join("\n");return`Recent ${t.length} entries:\n${o}`}}};return{TOOLS:s,toolList:function(){return Object.entries(s).map(([e,t])=>({name:e,description:t.description,inputSchema:t.inputSchema}))}}}module.exports={createTools:createTools};
@@ -1,3 +1,3 @@
1
1
  // SPDX-License-Identifier: AGPL-3.0-or-later
2
2
  // Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
3
- "use strict";const FLAGS=Object.freeze({headlessSkip:"--dangerously-skip-permissions",interactiveSkip:"--allow-dangerously-skip-permissions",permissionMode:"--permission-mode",allowedTools:"--allowedTools",disallowedTools:"--disallowedTools",print:"-p",outputFormat:"--output-format",model:"--model",sessionId:"--session-id",resume:"--resume",inputFormat:"--input-format",permissionPromptTool:"--permission-prompt-tool",addDir:"--add-dir"});function addDirArgs(e){const s=[];for(const o of unique(e))s.push(`${FLAGS.addDir}=${o}`);return s}const UUID_RE=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,DEFAULT_OUTPUT_FORMAT="stream-json";function unique(e){const s=new Set,o=[];for(const i of Array.isArray(e)?e:[]){const e=String(i).trim();e&&!s.has(e)&&(s.add(e),o.push(e))}return o}function claudeArgv(e={}){const s=e.posture;if(!s||"object"!=typeof s)throw new Error("claudeArgv requires a resolved posture record (one/src/permissions.js resolvePosture)");const o=s.childKind,i="interactive"!==o,{PERMISSION_MODES:r}=require("./permissions.js"),n=s.child&&"string"==typeof s.child.permissionMode?s.child.permissionMode:null,d=void 0!==e.permissionMode&&null!==e.permissionMode?String(e.permissionMode):null,t=null!==d||null!==n,l=null!==d?d:n;if(t&&!r.includes(l))throw new Error(`--permission-mode ${JSON.stringify(l)} is not one of ${r.join("|")} — refusing to pass (or to silently drop) a mode the child does not accept.`);const a=s.rules||{},p=unique(a.allow),u=unique(a.deny),c=unique(a.ask),m=e.resumeSessionId?String(e.resumeSessionId).trim():"",h=e.sessionId?String(e.sessionId).trim():"",g=m||null,f=!g&&h?h:null;for(const[e,s]of[["resumeSessionId",g],["sessionId",f]])if(s&&!UUID_RE.test(s))throw new Error(`${e} ${JSON.stringify(s)} is not a UUID — refusing to pass it to --resume/--session-id, which the child rejects after the spawn (turning a continuity bug into an opaque failed turn).`);const S=!0===e.askBridge&&!(s.child&&s.child.skip),A=[];i&&A.push(FLAGS.print,FLAGS.outputFormat,String(e.outputFormat||"stream-json")),e.model&&A.push(FLAGS.model,String(e.model));const F=addDirArgs(e.addDir);A.push(...F),p.length&&A.push(FLAGS.allowedTools,p.join(",")),u.length&&A.push(FLAGS.disallowedTools,u.join(",")),t&&A.push(FLAGS.permissionMode,l),s.child&&s.child.flag&&A.push(s.child.flag),S&&A.push(FLAGS.inputFormat,"stream-json",FLAGS.permissionPromptTool,"stdio"),g?A.push(FLAGS.resume,g):f&&A.push(FLAGS.sessionId,f),Array.isArray(e.extra)&&A.push(...e.extra.map(String)),S||void 0===e.prompt||null===e.prompt||A.push(String(e.prompt));const w=Object.freeze({kind:o,permissionMode:l,permissionModePassed:t,permissionModeSource:t?null!==d?"descriptor":"posture":null,permissionModeDropped:s&&s.permissionModeDropped||null,skip:Boolean(s.child&&s.child.skip),skipFlag:s.child&&s.child.flag||null,allowedTools:Object.freeze(p),disallowedTools:Object.freeze(u),unmappedAsk:Object.freeze(c),addDir:Object.freeze(F.map((e=>e.slice(FLAGS.addDir.length+1)))),resumeSessionId:g,sessionId:f,askBridge:S,argv:Object.freeze(A.slice())});return{argv:w.argv,record:w}}function childRecordLine(e){if(!e||"object"!=typeof e)return null;const s=e.permissionModePassed?`${FLAGS.permissionMode}=${e.permissionMode}`:e.permissionModeDropped?`no --permission-mode (asked for one, dropped: ${e.permissionModeDropped})`:"no --permission-mode (none was set)";return`aegis: claude child [${e.kind}] ${e.skipFlag||"no permission flag"} · ${s} · allowedTools=[${e.allowedTools.join(", ")}] disallowedTools=[${e.disallowedTools.join(", ")}]`+(e.unmappedAsk.length?` (ask rules recorded, unmapped: ${e.unmappedAsk.join(", ")})`:"")+(e.addDir&&e.addDir.length?` · addDir=[${e.addDir.join(", ")}]`:"")+(e.resumeSessionId?` · resumed session ${e.resumeSessionId}`:e.sessionId?` · new session ${e.sessionId}`:" · no session id (each turn is a new conversation)")+(e.askBridge?" · ask bridge (the child can raise approval cards)":" · no ask bridge (headless: unapproved tools auto-deny)")}module.exports={FLAGS:FLAGS,DEFAULT_OUTPUT_FORMAT:"stream-json",claudeArgv:claudeArgv,addDirArgs:addDirArgs,childRecordLine:childRecordLine};
3
+ "use strict";const FLAGS=Object.freeze({headlessSkip:"--dangerously-skip-permissions",interactiveSkip:"--allow-dangerously-skip-permissions",permissionMode:"--permission-mode",allowedTools:"--allowedTools",disallowedTools:"--disallowedTools",print:"-p",outputFormat:"--output-format",model:"--model",sessionId:"--session-id",resume:"--resume",inputFormat:"--input-format",permissionPromptTool:"--permission-prompt-tool",addDir:"--add-dir"});function addDirArgs(e){const s=[];for(const o of unique(e))s.push(`${FLAGS.addDir}=${o}`);return s}const UUID_RE=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,DEFAULT_OUTPUT_FORMAT="stream-json";function unique(e){const s=new Set,o=[];for(const i of Array.isArray(e)?e:[]){const e=String(i).trim();e&&!s.has(e)&&(s.add(e),o.push(e))}return o}function claudeArgv(e={}){const s=e.posture;if(!s||"object"!=typeof s)throw new Error("claudeArgv requires a resolved posture record (one/src/permissions.js resolvePosture)");const o=s.childKind,i="interactive"!==o,{PERMISSION_MODES:r}=require("./permissions.js"),n=s.child&&"string"==typeof s.child.permissionMode?s.child.permissionMode:null,d=void 0!==e.permissionMode&&null!==e.permissionMode?String(e.permissionMode):null,t=null!==d||null!==n,l=null!==d?d:n;if(t&&!r.includes(l))throw new Error(`--permission-mode ${JSON.stringify(l)} is not one of ${r.join("|")} — refusing to pass (or to silently drop) a mode the child does not accept.`);const a=s.rules||{},p=unique(a.allow),u=unique(a.deny),c=unique(a.ask),m=e.resumeSessionId?String(e.resumeSessionId).trim():"",h=e.sessionId?String(e.sessionId).trim():"",g=m||null,f=!g&&h?h:null;for(const[e,s]of[["resumeSessionId",g],["sessionId",f]])if(s&&!UUID_RE.test(s))throw new Error(`${e} ${JSON.stringify(s)} is not a UUID — refusing to pass it to --resume/--session-id, which the child rejects after the spawn (turning a continuity bug into an opaque failed turn).`);const S=!0===e.askBridge&&!(s.child&&s.child.skip),A=[];i&&A.push(FLAGS.print,FLAGS.outputFormat,String(e.outputFormat||"stream-json")),e.model&&A.push(FLAGS.model,String(e.model));const F=addDirArgs(e.addDir);A.push(...F),p.length&&A.push(FLAGS.allowedTools,p.join(",")),u.length&&A.push(FLAGS.disallowedTools,u.join(",")),t&&A.push(FLAGS.permissionMode,l),s.child&&s.child.flag&&A.push(s.child.flag),S&&A.push(FLAGS.inputFormat,"stream-json",FLAGS.permissionPromptTool,"stdio"),g?A.push(FLAGS.resume,g):f&&A.push(FLAGS.sessionId,f),Array.isArray(e.extra)&&A.push(...e.extra.map(String)),S||void 0===e.prompt||null===e.prompt||A.push(String(e.prompt));const w=Object.freeze({kind:o,permissionMode:l,permissionModePassed:t,permissionModeSource:t?null!==d?"descriptor":"posture":null,permissionModeDropped:s&&s.permissionModeDropped||null,skip:Boolean(s.child&&s.child.skip),skipFlag:s.child&&s.child.flag||null,allowedTools:Object.freeze(p),disallowedTools:Object.freeze(u),unmappedAsk:Object.freeze(c),addDir:Object.freeze(F.map(e=>e.slice(FLAGS.addDir.length+1))),resumeSessionId:g,sessionId:f,askBridge:S,argv:Object.freeze(A.slice())});return{argv:w.argv,record:w}}function childRecordLine(e){if(!e||"object"!=typeof e)return null;const s=e.permissionModePassed?`${FLAGS.permissionMode}=${e.permissionMode}`:e.permissionModeDropped?`no --permission-mode (asked for one, dropped: ${e.permissionModeDropped})`:"no --permission-mode (none was set)";return`aegis: claude child [${e.kind}] ${e.skipFlag||"no permission flag"} · ${s} · allowedTools=[${e.allowedTools.join(", ")}] disallowedTools=[${e.disallowedTools.join(", ")}]`+(e.unmappedAsk.length?` (ask rules recorded, unmapped: ${e.unmappedAsk.join(", ")})`:"")+(e.addDir&&e.addDir.length?` · addDir=[${e.addDir.join(", ")}]`:"")+(e.resumeSessionId?` · resumed session ${e.resumeSessionId}`:e.sessionId?` · new session ${e.sessionId}`:" · no session id (each turn is a new conversation)")+(e.askBridge?" · ask bridge (the child can raise approval cards)":" · no ask bridge (headless: unapproved tools auto-deny)")}module.exports={FLAGS:FLAGS,DEFAULT_OUTPUT_FORMAT:"stream-json",claudeArgv:claudeArgv,addDirArgs:addDirArgs,childRecordLine:childRecordLine};
@@ -1,3 +1,3 @@
1
1
  // SPDX-License-Identifier: AGPL-3.0-or-later
2
2
  // Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
3
- "use strict";const PROTO=1,METHODS=Object.freeze(["hello","exec","event","cancel"]),CAPS=Object.freeze({EXEC:"exec",EVENT:"event",CANCEL:"cancel",PTY:"pty"}),CODE=Object.freeze({BAD_JSON:"bad_json",BAD_FRAME:"bad_frame",UNKNOWN_METHOD:"unknown_method",PROTO_MISMATCH:"proto_mismatch",HELLO_REQUIRED:"hello_required",CAPABILITY_MISSING:"capability_missing",UNSUPPORTED:"unsupported"});function request(e,o,t){return{id:e,m:String(o),p:t&&"object"==typeof t?t:{}}}function ok(e,o){return{id:e,ok:!0,r:o&&"object"==typeof o?o:{}}}function err(e,o,t){return{id:e,ok:!1,e:{code:String(o||CODE.UNSUPPORTED),msg:String(t||"")}}}function isObject(e){return Boolean(e)&&"object"==typeof e&&!Array.isArray(e)}function validate(e){return isObject(e)?void 0===e.id||null===e.id?{ok:!1,code:CODE.BAD_FRAME,msg:"frame has no id"}:void 0!==e.ok?!0===e.ok?void 0!==e.e?{ok:!1,code:CODE.BAD_FRAME,msg:"reply carries both r and e"}:{ok:!0}:!1===e.ok?isObject(e.e)&&e.e.code?{ok:!0}:{ok:!1,code:CODE.BAD_FRAME,msg:"a failed reply must name a code"}:{ok:!1,code:CODE.BAD_FRAME,msg:"ok must be true or false"}:"string"==typeof e.m&&METHODS.includes(e.m)?void 0===e.p||isObject(e.p)?{ok:!0}:{ok:!1,code:CODE.BAD_FRAME,msg:"params must be an object"}:{ok:!1,code:CODE.UNKNOWN_METHOD,msg:`unknown method: ${String(e.m)}`}:{ok:!1,code:CODE.BAD_FRAME,msg:"frame must be an object"}}function negotiate(e,o){const t=o||{},r=validate(e);if(!r.ok)return{ok:!1,code:r.code,msg:r.msg};if("hello"!==e.m)return{ok:!1,code:CODE.HELLO_REQUIRED,msg:`the first frame must be hello, got ${String(e.m)}`};const n=e.p||{};if(1!==n.proto)return{ok:!1,code:CODE.PROTO_MISMATCH,msg:`peer speaks protocol ${String(n.proto)}, this build speaks 1`};const i=Array.isArray(n.caps)?n.caps.map(String):[],s=(Array.isArray(t.requireCaps)?t.requireCaps.map(String):[]).filter((e=>!i.includes(e)));return s.length?{ok:!1,code:CODE.CAPABILITY_MISSING,msg:`peer does not offer: ${s.join(", ")}`}:{ok:!0,proto:1,caps:i}}function hello(e){return request(void 0===e?0:e,"hello",{proto:1,caps:[CAPS.EXEC,CAPS.EVENT,CAPS.CANCEL]})}function encode(e){return`${JSON.stringify(e)}\n`}function decodeLine(e){const o=String(null==e?"":e).trim();if(!o)return{ok:!1,id:null,code:CODE.BAD_JSON,msg:"empty line"};let t;try{t=JSON.parse(o)}catch(e){return{ok:!1,id:null,code:CODE.BAD_JSON,msg:`not JSON: ${e.message}`}}const r=validate(t);return r.ok?{ok:!0,frame:t}:{ok:!1,id:isObject(t)&&void 0!==t.id?t.id:null,code:r.code,msg:r.msg}}function splitLines(e){const o=String(null==e?"":e).split("\n"),t=o.pop();return{lines:o.filter((e=>""!==e.trim())),rest:void 0===t?"":t}}module.exports={PROTO:1,METHODS:METHODS,CAPS:CAPS,CODE:CODE,request:request,ok:ok,err:err,hello:hello,validate:validate,negotiate:negotiate,encode:encode,decodeLine:decodeLine,splitLines:splitLines};
3
+ "use strict";const PROTO=1,METHODS=Object.freeze(["hello","exec","event","cancel"]),CAPS=Object.freeze({EXEC:"exec",EVENT:"event",CANCEL:"cancel",PTY:"pty"}),CODE=Object.freeze({BAD_JSON:"bad_json",BAD_FRAME:"bad_frame",UNKNOWN_METHOD:"unknown_method",PROTO_MISMATCH:"proto_mismatch",HELLO_REQUIRED:"hello_required",CAPABILITY_MISSING:"capability_missing",UNSUPPORTED:"unsupported"});function request(e,o,t){return{id:e,m:String(o),p:t&&"object"==typeof t?t:{}}}function ok(e,o){return{id:e,ok:!0,r:o&&"object"==typeof o?o:{}}}function err(e,o,t){return{id:e,ok:!1,e:{code:String(o||CODE.UNSUPPORTED),msg:String(t||"")}}}function isObject(e){return Boolean(e)&&"object"==typeof e&&!Array.isArray(e)}function validate(e){return isObject(e)?void 0===e.id||null===e.id?{ok:!1,code:CODE.BAD_FRAME,msg:"frame has no id"}:void 0!==e.ok?!0===e.ok?void 0!==e.e?{ok:!1,code:CODE.BAD_FRAME,msg:"reply carries both r and e"}:{ok:!0}:!1===e.ok?isObject(e.e)&&e.e.code?{ok:!0}:{ok:!1,code:CODE.BAD_FRAME,msg:"a failed reply must name a code"}:{ok:!1,code:CODE.BAD_FRAME,msg:"ok must be true or false"}:"string"==typeof e.m&&METHODS.includes(e.m)?void 0===e.p||isObject(e.p)?{ok:!0}:{ok:!1,code:CODE.BAD_FRAME,msg:"params must be an object"}:{ok:!1,code:CODE.UNKNOWN_METHOD,msg:`unknown method: ${String(e.m)}`}:{ok:!1,code:CODE.BAD_FRAME,msg:"frame must be an object"}}function negotiate(e,o){const t=o||{},r=validate(e);if(!r.ok)return{ok:!1,code:r.code,msg:r.msg};if("hello"!==e.m)return{ok:!1,code:CODE.HELLO_REQUIRED,msg:`the first frame must be hello, got ${String(e.m)}`};const n=e.p||{};if(1!==n.proto)return{ok:!1,code:CODE.PROTO_MISMATCH,msg:`peer speaks protocol ${String(n.proto)}, this build speaks 1`};const i=Array.isArray(n.caps)?n.caps.map(String):[],s=(Array.isArray(t.requireCaps)?t.requireCaps.map(String):[]).filter(e=>!i.includes(e));return s.length?{ok:!1,code:CODE.CAPABILITY_MISSING,msg:`peer does not offer: ${s.join(", ")}`}:{ok:!0,proto:1,caps:i}}function hello(e){return request(void 0===e?0:e,"hello",{proto:1,caps:[CAPS.EXEC,CAPS.EVENT,CAPS.CANCEL]})}function encode(e){return`${JSON.stringify(e)}\n`}function decodeLine(e){const o=String(null==e?"":e).trim();if(!o)return{ok:!1,id:null,code:CODE.BAD_JSON,msg:"empty line"};let t;try{t=JSON.parse(o)}catch(e){return{ok:!1,id:null,code:CODE.BAD_JSON,msg:`not JSON: ${e.message}`}}const r=validate(t);return r.ok?{ok:!0,frame:t}:{ok:!1,id:isObject(t)&&void 0!==t.id?t.id:null,code:r.code,msg:r.msg}}function splitLines(e){const o=String(null==e?"":e).split("\n"),t=o.pop();return{lines:o.filter(e=>""!==e.trim()),rest:void 0===t?"":t}}module.exports={PROTO:1,METHODS:METHODS,CAPS:CAPS,CODE:CODE,request:request,ok:ok,err:err,hello:hello,validate:validate,negotiate:negotiate,encode:encode,decodeLine:decodeLine,splitLines:splitLines};
@@ -1,3 +1,3 @@
1
1
  // SPDX-License-Identifier: AGPL-3.0-or-later
2
2
  // Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
3
- "use strict";const path=require("node:path"),FACE=Object.freeze({TUI:"tui",GUI:"gui"}),RUN_AS_NODE="ELECTRON_RUN_AS_NODE",FORCE_TUI=["--tui","code"],COMPAT_BIN="aegiscode";function faceRoot(e,n){return path.join(e,"faces",n)}function cliEntry(e){return path.join(faceRoot(e,"cli"),"bin","aegiscode.js")}function binName(e){return path.basename(String(e||"aegis")).replace(/\.(exe|cmd|bat|AppImage)$/i,"").replace(/\.js$/,"")}function plan(e){const n=e||{};if(!n.packaged)return null;const t=n.execPath,a=n.resourcesPath,i=Array.isArray(n.argv)?n.argv.map(String):[];if(!t||!a)return null;const r=(e,n)=>({face:FACE.TUI,exec:t,args:[cliEntry(a),...e],env:{[RUN_AS_NODE]:"1"},reason:n});if(binName(n.invokedAs)===COMPAT_BIN)return r(i,"aegiscode is the compatibility bin");const c=i.find((e=>FORCE_TUI.includes(e)));return c?r(i.filter((e=>e!==c)),`${c} asks for the terminal face`):null}function spawnOptions(e,n){return e?{exec:e.exec,args:e.args,env:Object.assign({},n||{},e.env)}:null}module.exports={plan:plan,spawnOptions:spawnOptions,FACE:FACE,RUN_AS_NODE:RUN_AS_NODE,COMPAT_BIN:COMPAT_BIN,FORCE_TUI:FORCE_TUI,cliEntry:cliEntry,faceRoot:faceRoot,binName:binName};
3
+ "use strict";const path=require("node:path"),FACE=Object.freeze({TUI:"tui",GUI:"gui"}),RUN_AS_NODE="ELECTRON_RUN_AS_NODE",FORCE_TUI=["--tui","code"],COMPAT_BIN="aegiscode";function faceRoot(e,n){return path.join(e,"faces",n)}function cliEntry(e){return path.join(faceRoot(e,"cli"),"bin","aegiscode.js")}function binName(e){return path.basename(String(e||"aegis")).replace(/\.(exe|cmd|bat|AppImage)$/i,"").replace(/\.js$/,"")}function plan(e){const n=e||{};if(!n.packaged)return null;const t=n.execPath,a=n.resourcesPath,i=Array.isArray(n.argv)?n.argv.map(String):[];if(!t||!a)return null;const r=(e,n)=>({face:FACE.TUI,exec:t,args:[cliEntry(a),...e],env:{[RUN_AS_NODE]:"1"},reason:n});if(binName(n.invokedAs)===COMPAT_BIN)return r(i,"aegiscode is the compatibility bin");const c=i.find(e=>FORCE_TUI.includes(e));return c?r(i.filter(e=>e!==c),`${c} asks for the terminal face`):null}function spawnOptions(e,n){return e?{exec:e.exec,args:e.args,env:Object.assign({},n||{},e.env)}:null}module.exports={plan:plan,spawnOptions:spawnOptions,FACE:FACE,RUN_AS_NODE:RUN_AS_NODE,COMPAT_BIN:COMPAT_BIN,FORCE_TUI:FORCE_TUI,cliEntry:cliEntry,faceRoot:faceRoot,binName:binName};
@@ -1,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};
@@ -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 level=require("./level.js"),GATES=level.GATES,MAX_PROACTIVE_PER_SESSION=1,MAX_BODY_CHARS=600,MAX_FACT_CHARS=160,MAX_FACTS=6,MAX_CANDIDATES=8,EFFECTS=Object.freeze({"brief.show":Object.freeze({class:null,tool:null,offDevice:!1}),"memory.save":Object.freeze({class:"write",tool:null,offDevice:!1}),"recall.load":Object.freeze({class:"read",tool:"memory.search",offDevice:!1})}),FORBIDDEN_CLASSES=Object.freeze(["shell","network","offDevice"]),CATALOG=Object.freeze([Object.freeze({id:"morningBrief",label:"Morning brief",needsProactivity:"brief",proactive:!0,action:"brief.show",acceptLabel:"Show the brief",dismissLabel:"Not now",doneLabel:"Brief opened"}),Object.freeze({id:"ideaLog",label:"Idea log",needsProactivity:"off",proactive:!1,action:"memory.save",acceptLabel:"Save to memory",dismissLabel:"Discard",doneLabel:"Saved to memory"}),Object.freeze({id:"sessionReflection",label:"Session reflection",needsProactivity:"hints",proactive:!0,action:"memory.save",acceptLabel:"Save this line",dismissLabel:"Discard",doneLabel:"Saved to memory"}),Object.freeze({id:"recall",label:"Context recall",needsProactivity:"hints",proactive:!0,action:"recall.load",acceptLabel:"Load those notes",dismissLabel:"Skip",doneLabel:"Notes loaded"})]),BEHAVIOUR_IDS=Object.freeze(CATALOG.map((e=>e.id))),DEFAULT_OPT_IN=Object.freeze(BEHAVIOUR_IDS.reduce(((e,n)=>Object.assign(e,{[n]:!1})),{})),PROACTIVITY_ORDER=Object.freeze(["off","hints","brief"]);function isPlainObject(e){return Boolean(e)&&"object"==typeof e&&!Array.isArray(e)}function clean(e,n){const t=String(null==e?"":e).replace(/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f\u2028\u2029]/g," ").replace(/\s+/g," ").trim(),i="number"==typeof n&&n>0?n:MAX_FACT_CHARS;return t.length>i?`${t.slice(0,i-1)}…`:t}function atLeast(e,n){const t=PROACTIVITY_ORDER.indexOf(e),i=PROACTIVITY_ORDER.indexOf(n);return!(t<0)&&(i<0||t>=i)}function behaviourById(e){return CATALOG.find((n=>n.id===e))||null}function capsFlags(e){return isPlainObject(e)&&isPlainObject(e.companion)?e.companion:null}function normalizeOptIn(e){const n=Object.assign({},DEFAULT_OPT_IN);if(!isPlainObject(e))return Object.freeze(n);for(const t of BEHAVIOUR_IDS)!0===e[t]&&(n[t]=!0);return Object.freeze(n)}function gating(e,n={}){const t=normalizeOptIn(n.optIn),i=capsFlags(e),r=isPlainObject(e)&&"string"==typeof e.proactivity?e.proactivity:"off",o={};for(const a of CATALOG){const s=(e,n)=>{o[a.id]=Object.freeze({id:a.id,allowed:e,reason:n})};isPlainObject(e)&&i?!0!==n.envDisabled?PROACTIVITY_ORDER.indexOf(r)<0?s(!1,`unknown proactivity ${JSON.stringify(r)} — staying quiet`):atLeast(r,a.needsProactivity)?flagAllowed(i,a)?!0===t[a.id]?s(!0,"available"):s(!1,`${a.label} is off (opt-in, default off)`):s(!1,`${a.label} unlocks at level ${gateLevelFor(a)}`):s(!1,`${a.label} unlocks at level ${gateLevelFor(a)}, not level ${e.level}`):s(!1,"AEGIS_COMPANION=off"):s(!1,"no capabilities — the companion stays quiet")}return Object.freeze(o)}function flagAllowed(e,n){return"recall"===n.id||!0===e[n.id]}function gateLevelFor(e){return"morningBrief"===e.id?GATES.brief:"ideaLog"===e.id?GATES.ideaLog:"sessionReflection"===e.id?GATES.sessionReflection:GATES.hints}function carveOuts(){const e=[];for(const n of CATALOG){const t=EFFECTS[n.action];t?(t.offDevice&&e.push(`${n.id} (${n.action}) reaches off-device`),FORBIDDEN_CLASSES.includes(t.class)&&e.push(`${n.id} (${n.action}) carries ${t.class} approval class`),t.tool&&!t.tool.startsWith("memory.")&&e.push(`${n.id} (${n.action}) fires tool ${t.tool}, which is not a memory read`)):e.push(`${n.id} proposes undeclared effect ${n.action}`)}return e}function assertCarveOuts(){const e=carveOuts();if(e.length)throw new Error(`companion behaviours violate a carve-out: ${e.join("; ")}`);return!0}function briefDigest(e={}){const n=[],t=e=>Array.isArray(e)?e.length:Number.isFinite(e)?Number(e):0,i=t(e.changed);if(i>0){const t=Array.isArray(e.changed)?e.changed.slice(0,2).map((e=>clean(e,60))):[];n.push(`${i} file${1===i?"":"s"} changed since you were last here${t.length?` (${t.join(", ")})`:""}`)}const r=t(e.queued);r>0&&n.push(`${r} task${1===r?"":"s"} waiting in the queue`);const o=(Array.isArray(e.resuming)?e.resuming:[]).map((e=>clean(e,MAX_FACT_CHARS))).filter(Boolean).slice(0,3);return o.length&&n.push(`memory says you were mid-way through: ${o.join(" · ")}`),Object.freeze({lines:Object.freeze(n.slice(0,MAX_FACTS)),empty:0===n.length})}function recallCandidates(e){return(Array.isArray(e)?e:[]).filter((e=>e&&(null!=e.content||null!=e.text))).slice(0,MAX_CANDIDATES).map((e=>Object.freeze({id:null==e.id?null:String(e.id),text:clean(null!=e.content?e.content:e.text,MAX_FACT_CHARS)}))).filter((e=>e.text.length>0))}function newId(e,n){return`${e}-${n}`}function makeIntent(e,n){const t=EFFECTS[e.action];return Object.freeze({behaviour:e.id,action:e.action,approvalClass:t.class,tool:t.tool,offDevice:t.offDevice,args:Object.freeze(Object.assign({},n||{})),approved:!1,needsInteractiveApproval:null!=t.tool})}function makeCard(e,n){const t=Object.freeze([Object.freeze({id:"accept",decision:"accept",label:e.acceptLabel,doneLabel:e.doneLabel,primary:!0}),Object.freeze({id:"dismiss",decision:"dismiss",label:e.dismissLabel,doneLabel:"Not now",primary:!1})]);return Object.freeze({id:n.id,kind:"companion",shape:"approval",behaviour:e.id,label:e.label,proactive:!0===n.proactive,title:n.title,body:n.body,facts:Object.freeze((n.facts||[]).slice(0,MAX_FACTS)),actions:t,requiresExplicitAccept:!0,intent:n.intent})}function createSession(e={}){const n=e.caps,t=normalizeOptIn(e.optIn),i=null==e.session?"session":String(e.session),r="function"==typeof e.now?e.now:()=>0,o=gating(n,{optIn:t,envDisabled:!0===e.envDisabled}),a=new Map,s=new Map,c=[];let l=0,d=0,u=null==e.lastBriefDay?null:String(e.lastBriefDay);function f(e){return o[e]||Object.freeze({id:e,allowed:!1,reason:"unknown behaviour"})}function p(){return d<1}function b(e,n,t){const i=f(e.id);if(!i.allowed)return{card:null,reason:i.reason};const r="user.request"!==n.kind;if(r&&!p())return{card:null,reason:"already offered a proactive card this session"};const o=t();if(!o)return{card:null,reason:"nothing to report"};l+=1;const s=makeCard(e,Object.assign({id:newId("companion",l),proactive:r},o));return a.set(s.id,{card:s,decision:null,decidedAt:null}),r&&(d+=1),{card:s,reason:"offered"}}function A(e,n){const t=null==e.dayKey?null:String(e.dayKey);if(t&&t===u)return{card:null,reason:"already briefed today"};const i=briefDigest(e.facts);return i.empty?{card:null,reason:"nothing to report"}:b(n,e,(()=>(t&&(u=t),{title:"Morning brief",body:i.lines.join(" "),facts:i.lines,intent:makeIntent(n,{lines:i.lines.slice()})})))}function v(e,n){const t=recallCandidates(e.candidates);if(!t.length)return{card:null,reason:"no remembered context for this turn"};const i=clean(e.query,120);return b(n,e,(()=>({title:"Context recall",body:`${t.length} remembered note${1===t.length?"":"s"} may be relevant${i?` to “${i}”`:""}. Load them into this turn?`,facts:t.map((e=>e.text)),intent:makeIntent(n,{query:i,ids:t.map((e=>e.id)),limit:t.length})})))}function m(e,n){const t=(Array.isArray(e.decisions)?e.decisions:[]).map((e=>clean(e,MAX_FACT_CHARS))).filter(Boolean),r=(Array.isArray(e.open)?e.open:[]).map((e=>clean(e,MAX_FACT_CHARS))).filter(Boolean);if(!t.length&&!r.length)return{card:null,reason:"nothing to report"};const o=t.length&&r.length?`Decided: ${t[0]} · Still open: ${r[0]}`:t.length?`Decided: ${t[0]}`:`Still open: ${r[0]}`;return b(n,e,(()=>({title:"Session reflection",body:`One durable line from this session — save it? ${o}`,facts:[o],intent:makeIntent(n,{kind:"reflection",content:clean(o,600),session:i,decisions:t.slice(0,MAX_FACTS),open:r.slice(0,MAX_FACTS)})})))}return{session:i,capabilities:n,optIn:t,gates:o,consider:function(e={}){const n=isPlainObject(e)?e:{};switch(n.kind){case"session.start":return A(n,behaviourById("morningBrief"));case"turn.start":return v(n,behaviourById("recall"));case"session.end":return m(n,behaviourById("sessionReflection"));case"user.request":return"idea"===n.want?function(e,n){const t=clean(e.text,600);return t?b(n,e,(()=>({title:"Idea log",body:`Save this to memory as an idea? ${t}`,facts:[t],intent:makeIntent(n,{kind:"idea",content:t,session:i})}))):{card:null,reason:"no idea text to save"}}(n,behaviourById("ideaLog")):"recall"===n.want?v(n,behaviourById("recall")):"brief"===n.want?A(n,behaviourById("morningBrief")):"reflection"===n.want?m(n,behaviourById("sessionReflection")):{card:null,reason:`unsupported request ${JSON.stringify(n.want)}`};default:return{card:null,reason:`unknown trigger ${JSON.stringify(n.kind)}`}}},decide:function(e,n){const t=a.get(String(e));if(!t)return{ok:!1,reason:"unknown card",decision:null,ticket:null,intent:null};if(t.decision)return{ok:!1,reason:`already ${t.decision}ed`,decision:t.decision,ticket:null,intent:null};if("accept"!==n&&"dismiss"!==n)return{ok:!1,reason:'decision must be "accept" or "dismiss"',decision:null,ticket:null,intent:null};if(t.decision=n,t.decidedAt=r(),c.push(Object.freeze({cardId:t.card.id,behaviour:t.card.behaviour,decision:n,at:t.decidedAt})),"dismiss"===n)return{ok:!0,reason:"dismissed",decision:"dismiss",ticket:null,intent:null};const o=Object.freeze({id:`ticket-${i}-${t.card.id}`,cardId:t.card.id,behaviour:t.card.behaviour,session:i,approved:!0,approvedAt:t.decidedAt,intent:t.card.intent});return s.set(o.id,{ticket:o,used:!1}),{ok:!0,reason:"accepted",decision:"accept",ticket:o,intent:t.card.intent}},verifyTicket:function(e){if(!isPlainObject(e)||"string"!=typeof e.id)return!1;const n=s.get(e.id);return Boolean(n)&&n.ticket===e},consumeTicket:function(e){const n=s.get(e.id);return!(!n||n.ticket!==e||n.used||(n.used=!0,0))},cards:()=>Array.from(a.values()).map((e=>e.card)),pending:()=>Array.from(a.values()).filter((e=>!e.decision)).map((e=>e.card)),decisions:()=>c.slice(),state:()=>Object.freeze({session:i,proactiveShown:d,maxProactive:1,budgetLeft:p(),lastBriefDay:u,cards:a.size,pending:Array.from(a.values()).filter((e=>!e.decision)).length,enabled:BEHAVIOUR_IDS.filter((e=>f(e).allowed))})}}function refuse(e){return Object.freeze({ok:!1,performed:!1,reason:e})}async function dispatch(e,n,t={}){if(!e||"function"!=typeof e.verifyTicket)return refuse("no companion session — refusing to act");if(!e.verifyTicket(n))return refuse("an accepted card is required — the companion never acts on its own");if("function"!=typeof e.consumeTicket||!e.consumeTicket(n))return refuse("this acceptance was already used");const i=n.intent;if(!isPlainObject(i)||!1!==i.approved)return refuse("malformed intent — refusing to act");if(!EFFECTS[i.action])return refuse(`undeclared effect ${JSON.stringify(i.action)}`);if(i.tool){if("function"!=typeof t.requestApproval)return refuse(`no approval channel for ${i.tool} — refusing to fire a tool`);let r;try{r=await t.requestApproval({id:n.id,behaviour:n.behaviour,tool:i.tool,args:i.args,approvalClass:i.approvalClass})}catch(e){return refuse(`approval channel failed: ${e&&e.message?e.message:e}`)}if("once"!==r&&"session"!==r)return refuse(`approval denied for ${i.tool}`)}if("function"!=typeof t.perform)return refuse("no effect handler configured");const r=await t.perform(i,{ticket:n});return Object.freeze({ok:!0,performed:!0,behaviour:n.behaviour,action:i.action,result:r})}module.exports={GATES:GATES,MAX_PROACTIVE_PER_SESSION:1,MAX_BODY_CHARS:600,BEHAVIOUR_IDS:BEHAVIOUR_IDS,DEFAULT_OPT_IN:DEFAULT_OPT_IN,CATALOG:CATALOG,EFFECTS:EFFECTS,briefDigest:briefDigest,recallCandidates:recallCandidates,normalizeOptIn:normalizeOptIn,gating:gating,carveOuts:carveOuts,assertCarveOuts:assertCarveOuts,behaviourById:behaviourById,createSession:createSession,dispatch:dispatch,clean:clean};
3
+ "use strict";const level=require("./level.js"),GATES=level.GATES,MAX_PROACTIVE_PER_SESSION=1,MAX_BODY_CHARS=600,MAX_FACT_CHARS=160,MAX_FACTS=6,MAX_CANDIDATES=8,EFFECTS=Object.freeze({"brief.show":Object.freeze({class:null,tool:null,offDevice:!1}),"memory.save":Object.freeze({class:"write",tool:null,offDevice:!1}),"recall.load":Object.freeze({class:"read",tool:"memory.search",offDevice:!1})}),FORBIDDEN_CLASSES=Object.freeze(["shell","network","offDevice"]),CATALOG=Object.freeze([Object.freeze({id:"morningBrief",label:"Morning brief",needsProactivity:"brief",proactive:!0,action:"brief.show",acceptLabel:"Show the brief",dismissLabel:"Not now",doneLabel:"Brief opened"}),Object.freeze({id:"ideaLog",label:"Idea log",needsProactivity:"off",proactive:!1,action:"memory.save",acceptLabel:"Save to memory",dismissLabel:"Discard",doneLabel:"Saved to memory"}),Object.freeze({id:"sessionReflection",label:"Session reflection",needsProactivity:"hints",proactive:!0,action:"memory.save",acceptLabel:"Save this line",dismissLabel:"Discard",doneLabel:"Saved to memory"}),Object.freeze({id:"recall",label:"Context recall",needsProactivity:"hints",proactive:!0,action:"recall.load",acceptLabel:"Load those notes",dismissLabel:"Skip",doneLabel:"Notes loaded"})]),BEHAVIOUR_IDS=Object.freeze(CATALOG.map(e=>e.id)),DEFAULT_OPT_IN=Object.freeze(BEHAVIOUR_IDS.reduce((e,n)=>Object.assign(e,{[n]:!1}),{})),PROACTIVITY_ORDER=Object.freeze(["off","hints","brief"]);function isPlainObject(e){return Boolean(e)&&"object"==typeof e&&!Array.isArray(e)}function clean(e,n){const t=String(null==e?"":e).replace(/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f\u2028\u2029]/g," ").replace(/\s+/g," ").trim(),i="number"==typeof n&&n>0?n:160;return t.length>i?`${t.slice(0,i-1)}…`:t}function atLeast(e,n){const t=PROACTIVITY_ORDER.indexOf(e),i=PROACTIVITY_ORDER.indexOf(n);return!(t<0)&&(i<0||t>=i)}function behaviourById(e){return CATALOG.find(n=>n.id===e)||null}function capsFlags(e){return isPlainObject(e)&&isPlainObject(e.companion)?e.companion:null}function normalizeOptIn(e){const n=Object.assign({},DEFAULT_OPT_IN);if(!isPlainObject(e))return Object.freeze(n);for(const t of BEHAVIOUR_IDS)!0===e[t]&&(n[t]=!0);return Object.freeze(n)}function gating(e,n={}){const t=normalizeOptIn(n.optIn),i=capsFlags(e),r=isPlainObject(e)&&"string"==typeof e.proactivity?e.proactivity:"off",o={};for(const a of CATALOG){const s=(e,n)=>{o[a.id]=Object.freeze({id:a.id,allowed:e,reason:n})};isPlainObject(e)&&i?!0!==n.envDisabled?PROACTIVITY_ORDER.indexOf(r)<0?s(!1,`unknown proactivity ${JSON.stringify(r)} — staying quiet`):atLeast(r,a.needsProactivity)?flagAllowed(i,a)?!0===t[a.id]?s(!0,"available"):s(!1,`${a.label} is off (opt-in, default off)`):s(!1,`${a.label} unlocks at level ${gateLevelFor(a)}`):s(!1,`${a.label} unlocks at level ${gateLevelFor(a)}, not level ${e.level}`):s(!1,"AEGIS_COMPANION=off"):s(!1,"no capabilities — the companion stays quiet")}return Object.freeze(o)}function flagAllowed(e,n){return"recall"===n.id||!0===e[n.id]}function gateLevelFor(e){return"morningBrief"===e.id?GATES.brief:"ideaLog"===e.id?GATES.ideaLog:"sessionReflection"===e.id?GATES.sessionReflection:GATES.hints}function carveOuts(){const e=[];for(const n of CATALOG){const t=EFFECTS[n.action];t?(t.offDevice&&e.push(`${n.id} (${n.action}) reaches off-device`),FORBIDDEN_CLASSES.includes(t.class)&&e.push(`${n.id} (${n.action}) carries ${t.class} approval class`),t.tool&&!t.tool.startsWith("memory.")&&e.push(`${n.id} (${n.action}) fires tool ${t.tool}, which is not a memory read`)):e.push(`${n.id} proposes undeclared effect ${n.action}`)}return e}function assertCarveOuts(){const e=carveOuts();if(e.length)throw new Error(`companion behaviours violate a carve-out: ${e.join("; ")}`);return!0}function briefDigest(e={}){const n=[],t=e=>Array.isArray(e)?e.length:Number.isFinite(e)?Number(e):0,i=t(e.changed);if(i>0){const t=Array.isArray(e.changed)?e.changed.slice(0,2).map(e=>clean(e,60)):[];n.push(`${i} file${1===i?"":"s"} changed since you were last here${t.length?` (${t.join(", ")})`:""}`)}const r=t(e.queued);r>0&&n.push(`${r} task${1===r?"":"s"} waiting in the queue`);const o=(Array.isArray(e.resuming)?e.resuming:[]).map(e=>clean(e,160)).filter(Boolean).slice(0,3);return o.length&&n.push(`memory says you were mid-way through: ${o.join(" · ")}`),Object.freeze({lines:Object.freeze(n.slice(0,6)),empty:0===n.length})}function recallCandidates(e){return(Array.isArray(e)?e:[]).filter(e=>e&&(null!=e.content||null!=e.text)).slice(0,8).map(e=>Object.freeze({id:null==e.id?null:String(e.id),text:clean(null!=e.content?e.content:e.text,160)})).filter(e=>e.text.length>0)}function newId(e,n){return`${e}-${n}`}function makeIntent(e,n){const t=EFFECTS[e.action];return Object.freeze({behaviour:e.id,action:e.action,approvalClass:t.class,tool:t.tool,offDevice:t.offDevice,args:Object.freeze(Object.assign({},n||{})),approved:!1,needsInteractiveApproval:null!=t.tool})}function makeCard(e,n){const t=Object.freeze([Object.freeze({id:"accept",decision:"accept",label:e.acceptLabel,doneLabel:e.doneLabel,primary:!0}),Object.freeze({id:"dismiss",decision:"dismiss",label:e.dismissLabel,doneLabel:"Not now",primary:!1})]);return Object.freeze({id:n.id,kind:"companion",shape:"approval",behaviour:e.id,label:e.label,proactive:!0===n.proactive,title:n.title,body:n.body,facts:Object.freeze((n.facts||[]).slice(0,6)),actions:t,requiresExplicitAccept:!0,intent:n.intent})}function createSession(e={}){const n=e.caps,t=normalizeOptIn(e.optIn),i=null==e.session?"session":String(e.session),r="function"==typeof e.now?e.now:()=>0,o=gating(n,{optIn:t,envDisabled:!0===e.envDisabled}),a=new Map,s=new Map,c=[];let l=0,d=0,u=null==e.lastBriefDay?null:String(e.lastBriefDay);function f(e){return o[e]||Object.freeze({id:e,allowed:!1,reason:"unknown behaviour"})}function p(){return d<1}function b(e,n,t){const i=f(e.id);if(!i.allowed)return{card:null,reason:i.reason};const r="user.request"!==n.kind;if(r&&!p())return{card:null,reason:"already offered a proactive card this session"};const o=t();if(!o)return{card:null,reason:"nothing to report"};l+=1;const s=makeCard(e,Object.assign({id:newId("companion",l),proactive:r},o));return a.set(s.id,{card:s,decision:null,decidedAt:null}),r&&(d+=1),{card:s,reason:"offered"}}function v(e,n){const t=null==e.dayKey?null:String(e.dayKey);if(t&&t===u)return{card:null,reason:"already briefed today"};const i=briefDigest(e.facts);return i.empty?{card:null,reason:"nothing to report"}:b(n,e,()=>(t&&(u=t),{title:"Morning brief",body:i.lines.join(" "),facts:i.lines,intent:makeIntent(n,{lines:i.lines.slice()})}))}function m(e,n){const t=recallCandidates(e.candidates);if(!t.length)return{card:null,reason:"no remembered context for this turn"};const i=clean(e.query,120);return b(n,e,()=>({title:"Context recall",body:`${t.length} remembered note${1===t.length?"":"s"} may be relevant${i?` to “${i}”`:""}. Load them into this turn?`,facts:t.map(e=>e.text),intent:makeIntent(n,{query:i,ids:t.map(e=>e.id),limit:t.length})}))}function O(e,n){const t=(Array.isArray(e.decisions)?e.decisions:[]).map(e=>clean(e,160)).filter(Boolean),r=(Array.isArray(e.open)?e.open:[]).map(e=>clean(e,160)).filter(Boolean);if(!t.length&&!r.length)return{card:null,reason:"nothing to report"};const o=t.length&&r.length?`Decided: ${t[0]} · Still open: ${r[0]}`:t.length?`Decided: ${t[0]}`:`Still open: ${r[0]}`;return b(n,e,()=>({title:"Session reflection",body:`One durable line from this session — save it? ${o}`,facts:[o],intent:makeIntent(n,{kind:"reflection",content:clean(o,600),session:i,decisions:t.slice(0,6),open:r.slice(0,6)})}))}return{session:i,capabilities:n,optIn:t,gates:o,consider:function(e={}){const n=isPlainObject(e)?e:{};switch(n.kind){case"session.start":return v(n,behaviourById("morningBrief"));case"turn.start":return m(n,behaviourById("recall"));case"session.end":return O(n,behaviourById("sessionReflection"));case"user.request":return"idea"===n.want?function(e,n){const t=clean(e.text,600);return t?b(n,e,()=>({title:"Idea log",body:`Save this to memory as an idea? ${t}`,facts:[t],intent:makeIntent(n,{kind:"idea",content:t,session:i})})):{card:null,reason:"no idea text to save"}}(n,behaviourById("ideaLog")):"recall"===n.want?m(n,behaviourById("recall")):"brief"===n.want?v(n,behaviourById("morningBrief")):"reflection"===n.want?O(n,behaviourById("sessionReflection")):{card:null,reason:`unsupported request ${JSON.stringify(n.want)}`};default:return{card:null,reason:`unknown trigger ${JSON.stringify(n.kind)}`}}},decide:function(e,n){const t=a.get(String(e));if(!t)return{ok:!1,reason:"unknown card",decision:null,ticket:null,intent:null};if(t.decision)return{ok:!1,reason:`already ${t.decision}ed`,decision:t.decision,ticket:null,intent:null};if("accept"!==n&&"dismiss"!==n)return{ok:!1,reason:'decision must be "accept" or "dismiss"',decision:null,ticket:null,intent:null};if(t.decision=n,t.decidedAt=r(),c.push(Object.freeze({cardId:t.card.id,behaviour:t.card.behaviour,decision:n,at:t.decidedAt})),"dismiss"===n)return{ok:!0,reason:"dismissed",decision:"dismiss",ticket:null,intent:null};const o=Object.freeze({id:`ticket-${i}-${t.card.id}`,cardId:t.card.id,behaviour:t.card.behaviour,session:i,approved:!0,approvedAt:t.decidedAt,intent:t.card.intent});return s.set(o.id,{ticket:o,used:!1}),{ok:!0,reason:"accepted",decision:"accept",ticket:o,intent:t.card.intent}},verifyTicket:function(e){if(!isPlainObject(e)||"string"!=typeof e.id)return!1;const n=s.get(e.id);return Boolean(n)&&n.ticket===e},consumeTicket:function(e){const n=s.get(e.id);return!(!n||n.ticket!==e||n.used||(n.used=!0,0))},cards:()=>Array.from(a.values()).map(e=>e.card),pending:()=>Array.from(a.values()).filter(e=>!e.decision).map(e=>e.card),decisions:()=>c.slice(),state:()=>Object.freeze({session:i,proactiveShown:d,maxProactive:1,budgetLeft:p(),lastBriefDay:u,cards:a.size,pending:Array.from(a.values()).filter(e=>!e.decision).length,enabled:BEHAVIOUR_IDS.filter(e=>f(e).allowed)})}}function refuse(e){return Object.freeze({ok:!1,performed:!1,reason:e})}async function dispatch(e,n,t={}){if(!e||"function"!=typeof e.verifyTicket)return refuse("no companion session — refusing to act");if(!e.verifyTicket(n))return refuse("an accepted card is required — the companion never acts on its own");if("function"!=typeof e.consumeTicket||!e.consumeTicket(n))return refuse("this acceptance was already used");const i=n.intent;if(!isPlainObject(i)||!1!==i.approved)return refuse("malformed intent — refusing to act");if(!EFFECTS[i.action])return refuse(`undeclared effect ${JSON.stringify(i.action)}`);if(i.tool){if("function"!=typeof t.requestApproval)return refuse(`no approval channel for ${i.tool} — refusing to fire a tool`);let r;try{r=await t.requestApproval({id:n.id,behaviour:n.behaviour,tool:i.tool,args:i.args,approvalClass:i.approvalClass})}catch(e){return refuse(`approval channel failed: ${e&&e.message?e.message:e}`)}if("once"!==r&&"session"!==r)return refuse(`approval denied for ${i.tool}`)}if("function"!=typeof t.perform)return refuse("no effect handler configured");const r=await t.perform(i,{ticket:n});return Object.freeze({ok:!0,performed:!0,behaviour:n.behaviour,action:i.action,result:r})}module.exports={GATES:GATES,MAX_PROACTIVE_PER_SESSION:1,MAX_BODY_CHARS:600,BEHAVIOUR_IDS:BEHAVIOUR_IDS,DEFAULT_OPT_IN:DEFAULT_OPT_IN,CATALOG:CATALOG,EFFECTS:EFFECTS,briefDigest:briefDigest,recallCandidates:recallCandidates,normalizeOptIn:normalizeOptIn,gating:gating,carveOuts:carveOuts,assertCarveOuts:assertCarveOuts,behaviourById:behaviourById,createSession:createSession,dispatch:dispatch,clean:clean};
@@ -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"),personaModule=require("./persona.js"),level=require("./level.js"),SCHEMA_VERSION=1,KINDS=Object.freeze(["outfit","expressions","palette","voice"]),TIERS=Object.freeze(["free","paid"]),KIND_UNLOCK_PREFIX=Object.freeze({outfit:"outfit",expressions:"expression",palette:"palette",voice:"voice"}),KIND_PART_LIST=Object.freeze({outfit:"outfit",expressions:"expressionPack",palette:"palette",voice:null}),UNLOCK_ALIASES=Object.freeze({"outfit.seasonal-winter":"outfit.seasonal","outfit.archive-coat":"outfit.archive"}),FORBIDDEN_KEYS=Object.freeze(["xp","xpbonus","xpmultiplier","level","levels","unlocklevel","minlevel","maxlevel","recall","recallentries","recalltokens","memory","memorywriteback","approval","approvals","autoapprove","autoapproveclasses","approvalfriction","grant","grants","toolgrant","toolgrants","capability","capabilities","offdevice","offdevicegrants","modelfloor","proactivity","queuedrain","importassistant","tokens","budget","pricetokens","price","prices","amount","currency","cost","sku","entitlement","entitlements","checkout","purchase","subscription","trial","sample","samples","sampleurl","recording","recordingurl","sourceaudio","voiceprint"]),FORBIDDEN_KEY_PATTERN=/(xp|level|recall|approval|grant|capabilit|offdevice|proactiv|entitlement|price|clone|voiceprint)/i,LIMITS=Object.freeze({id:48,name:60,label:48,summary:240,author:60,license:40,unlocks:8,items:24,parts:6}),PACK_SUFFIX=".pack.json",SLUG=/^[a-z0-9]+(?:-[a-z0-9]+)*$/;function isPlainObject(e){return Boolean(e)&&"object"==typeof e&&!Array.isArray(e)}function unlockById(e){return level.UNLOCKS.find((t=>t.id===e))||null}function unlockIdFor(e,t){return UNLOCK_ALIASES[`${e}.${t}`]||`${e}.${t}`}function forbiddenKeys(e,t=""){const n=[];if(Array.isArray(e))return e.forEach(((e,i)=>n.push(...forbiddenKeys(e,`${t}${t?".":""}${i}`)))),n;if(!isPlainObject(e))return n;for(const[i,s]of Object.entries(e)){const e=`${t}${t?".":""}${i}`,a=i.toLowerCase().replace(/[^a-z0-9]/g,"");(FORBIDDEN_KEYS.includes(a)||FORBIDDEN_KEY_PATTERN.test(i))&&n.push(e),n.push(...forbiddenKeys(s,e))}return n}function clean(e,t){return"string"!=typeof e?"":e.replace(/[\u0000-\u001f\u007f\u2028\u2029]+/g," ").replace(/\s+/g," ").trim().slice(0,t)}function validatePack(e){const t=[],n=[];if(!isPlainObject(e))return{ok:!1,pack:null,errors:["cosmetics pack must be a JSON object"],warnings:n,forbidden:[]};const i=forbiddenKeys(e);for(const e of i)t.push(`cosmetics packs may not carry \`${e}\` — a pack sells LOOKS only, never XP, levels, recall breadth, approval friction or personalization`);Number.isInteger(e.schema)&&e.schema>SCHEMA_VERSION&&t.push(`pack schema ${e.schema} is newer than this build supports (${SCHEMA_VERSION})`);const s=clean(e.id,LIMITS.id);s&&SLUG.test(s)||t.push(`pack id must be a kebab-case slug (got ${JSON.stringify(e.id)})`);const a=clean(e.name,LIMITS.name);a||t.push("pack needs a name");const o=KINDS.includes(e.kind)?e.kind:null;o||t.push(`pack kind must be one of ${KINDS.join(" | ")} (got ${JSON.stringify(e.kind)})`);const r=TIERS.includes(e.tier)?e.tier:null;r||t.push(`pack tier must be "free" or "paid" (got ${JSON.stringify(e.tier)})`);const c=Array.isArray(e.unlocks)?e.unlocks:[],l=[];c.length||t.push("pack must reference at least one unlock id from lib/avatar/level.js (a pack cannot create one)"),c.length>LIMITS.unlocks&&t.push(`at most ${LIMITS.unlocks} unlocks per pack (got ${c.length})`);for(const e of c.slice(0,LIMITS.unlocks)){const n=unlockById(e);n?(o&&n.id.split(".")[0]!==KIND_UNLOCK_PREFIX[o]&&t.push(`${n.id} is not a ${o} unlock — a pack may only gate its own kind`),r&&n.paid!==("paid"===r)&&t.push(`tier "${r}" contradicts unlock ${n.id} (paid: ${n.paid}) — the level table decides what is paid, not the pack`),l.includes(n.id)||l.push(n.id)):t.push(`unknown unlock ${JSON.stringify(e)} — the level table (level.js UNLOCKS) is the only authority on what exists and what is paid`)}const u=o?KIND_PART_LIST[o]:null,p=u?personaModule.PARTS[u]:null,d=Array.isArray(e.items)?e.items:[];d.length||t.push("pack needs at least one item"),d.length>LIMITS.items&&t.push(`at most ${LIMITS.items} items per pack (got ${d.length})`);const f=[],k=new Set;for(const e of d.slice(0,LIMITS.items)){if(!isPlainObject(e)){n.push("a non-object item was dropped");continue}const i=clean(e.id,LIMITS.id);if(!i||!SLUG.test(i)){n.push(`item id must be a kebab-case slug (got ${JSON.stringify(e.id)}) — dropped`);continue}if(k.has(i)){n.push(`duplicate item ${i} — dropped`);continue}k.add(i);let s=!0;if(p&&!p.includes(i)&&(s=!1,n.push(`item ${i} is not in this build's ${u} manifest — it will render without art`)),"voice"===o){const n=String(e.engine||"").trim().toLowerCase();["local","system"].includes(n)||(t.push(`voice item ${i} must name engine "local" or "system" (got ${JSON.stringify(e.engine)}) — voice never leaves the device`),s=!1),"synthetic"!==e.consent&&(t.push(`voice item ${i} must declare consent: "synthetic" — no pack may ship a voice cloned from a real person`),s=!1)}const a=Array.isArray(e.parts)?e.parts.map((e=>clean(e,LIMITS.id))).filter((e=>Boolean(e))).slice(0,LIMITS.parts):[],r=new Set(Object.values(personaModule.PARTS).flat().filter((e=>"string"==typeof e)));for(const e of a)r.has(e)||n.push(`item ${i} names part ${e}, which this build has no art for`);f.push(Object.freeze({id:i,label:clean(e.label,LIMITS.label)||i,known:s,parts:Object.freeze(a),unlock:unlockIdFor(o||"outfit",i),..."voice"===o?{engine:clean(e.engine,16).toLowerCase(),consent:clean(e.consent,16).toLowerCase()}:{}}))}const h=["schema","id","name","kind","tier","unlocks","items","author","license","summary"];for(const t of Object.keys(e))h.includes(t)||n.push(`unknown pack key ${JSON.stringify(t)} — ignored`);return t.length?{ok:!1,pack:null,errors:t,warnings:n,forbidden:i}:{ok:!0,errors:t,warnings:n,forbidden:i,pack:Object.freeze({schema:SCHEMA_VERSION,id:s,name:a,kind:o,tier:r,paid:"paid"===r,unlocks:Object.freeze(l),items:Object.freeze(f),author:clean(e.author,LIMITS.author),license:clean(e.license,LIMITS.license),summary:clean(e.summary,LIMITS.summary)})}}function auditPacks(e){const t=[];for(const n of Array.isArray(e)?e:[]){if(!isPlainObject(n))continue;const e=n.id||"(unnamed pack)",i=forbiddenKeys(n);for(const n of i)t.push(`${e}: forbidden field ${n}`);const s="paid"===n.tier?"paid":"free",a=Array.isArray(n.unlocks)?n.unlocks:[];a.length||t.push(`${e}: no unlock — a pack that grants nothing is not a cosmetic`);for(const n of a){const i=unlockById(n);i?i.paid!==("paid"===s)&&t.push(`${e}: tier ${s} contradicts unlock ${n} (paid: ${i.paid})`):t.push(`${e}: unlock ${n} does not exist in the level table`)}if("voice"===n.kind)for(const i of n.items||[])i&&"synthetic"===i.consent||t.push(`${e}: voice item ${i&&i.id} is not declared synthetic`)}return t}function packsDir(e){return e||path.join(__dirname,"packs")}function loadPacks(e){const t=packsDir(e),n={packs:[],rejected:[],warnings:[],dir:t};let i;try{i=fs.readdirSync(t).filter((e=>e.endsWith(PACK_SUFFIX))).sort()}catch(e){return n.warnings.push(`no cosmetics packs at ${t} (${e.code||e.message})`),n}for(const e of i){let i;try{i=JSON.parse(fs.readFileSync(path.join(t,e),"utf8"))}catch(t){n.rejected.push({file:e,errors:[`not valid JSON: ${t.message}`]});continue}const s=validatePack(i);for(const t of s.warnings)n.warnings.push(`${e}: ${t}`);s.ok?n.packs.push(s.pack):n.rejected.push({file:e,errors:s.errors})}return n}function shippedPacks(){return loadPacks().packs}function verifyShipped(e){const t=[];let n=e;if(!Array.isArray(n)){const e=loadPacks();n=e.packs;for(const n of e.rejected)t.push(`${n.file}: ${n.errors.join("; ")}`)}return t.push(...auditPacks(n)),{ok:0===t.length,violations:t,packs:n}}function catalog(e){const t=[];for(const n of Array.isArray(e)?e:[])if(isPlainObject(n)&&Array.isArray(n.unlocks))for(const e of n.unlocks){const i=unlockById(e);t.push({packId:n.id,packName:n.name,kind:n.kind,tier:n.tier,paid:Boolean(i&&i.paid),unlockId:e,level:i?i.level:null,label:i?i.label:e,items:(n.items||[]).map((e=>e.id))})}return t}function freePaidLine(e){const t=catalog(e);return{free:t.filter((e=>!e.paid)),paid:t.filter((e=>e.paid))}}module.exports={SCHEMA_VERSION:SCHEMA_VERSION,KINDS:KINDS,TIERS:TIERS,KIND_UNLOCK_PREFIX:KIND_UNLOCK_PREFIX,KIND_PART_LIST:KIND_PART_LIST,UNLOCK_ALIASES:UNLOCK_ALIASES,FORBIDDEN_KEYS:FORBIDDEN_KEYS,LIMITS:LIMITS,PACK_SUFFIX:PACK_SUFFIX,unlockById:unlockById,unlockIdFor:unlockIdFor,forbiddenKeys:forbiddenKeys,validatePack:validatePack,auditPacks:auditPacks,packsDir:packsDir,loadPacks:loadPacks,shippedPacks:shippedPacks,verifyShipped:verifyShipped,catalog:catalog,freePaidLine:freePaidLine};
3
+ "use strict";const fs=require("node:fs"),path=require("node:path"),personaModule=require("./persona.js"),level=require("./level.js"),SCHEMA_VERSION=1,KINDS=Object.freeze(["outfit","expressions","palette","voice"]),TIERS=Object.freeze(["free","paid"]),KIND_UNLOCK_PREFIX=Object.freeze({outfit:"outfit",expressions:"expression",palette:"palette",voice:"voice"}),KIND_PART_LIST=Object.freeze({outfit:"outfit",expressions:"expressionPack",palette:"palette",voice:null}),UNLOCK_ALIASES=Object.freeze({"outfit.seasonal-winter":"outfit.seasonal","outfit.archive-coat":"outfit.archive"}),FORBIDDEN_KEYS=Object.freeze(["xp","xpbonus","xpmultiplier","level","levels","unlocklevel","minlevel","maxlevel","recall","recallentries","recalltokens","memory","memorywriteback","approval","approvals","autoapprove","autoapproveclasses","approvalfriction","grant","grants","toolgrant","toolgrants","capability","capabilities","offdevice","offdevicegrants","modelfloor","proactivity","queuedrain","importassistant","tokens","budget","pricetokens","price","prices","amount","currency","cost","sku","entitlement","entitlements","checkout","purchase","subscription","trial","sample","samples","sampleurl","recording","recordingurl","sourceaudio","voiceprint"]),FORBIDDEN_KEY_PATTERN=/(xp|level|recall|approval|grant|capabilit|offdevice|proactiv|entitlement|price|clone|voiceprint)/i,LIMITS=Object.freeze({id:48,name:60,label:48,summary:240,author:60,license:40,unlocks:8,items:24,parts:6}),PACK_SUFFIX=".pack.json",SLUG=/^[a-z0-9]+(?:-[a-z0-9]+)*$/;function isPlainObject(e){return Boolean(e)&&"object"==typeof e&&!Array.isArray(e)}function unlockById(e){return level.UNLOCKS.find(t=>t.id===e)||null}function unlockIdFor(e,t){return UNLOCK_ALIASES[`${e}.${t}`]||`${e}.${t}`}function forbiddenKeys(e,t=""){const n=[];if(Array.isArray(e))return e.forEach((e,i)=>n.push(...forbiddenKeys(e,`${t}${t?".":""}${i}`))),n;if(!isPlainObject(e))return n;for(const[i,s]of Object.entries(e)){const e=`${t}${t?".":""}${i}`,a=i.toLowerCase().replace(/[^a-z0-9]/g,"");(FORBIDDEN_KEYS.includes(a)||FORBIDDEN_KEY_PATTERN.test(i))&&n.push(e),n.push(...forbiddenKeys(s,e))}return n}function clean(e,t){return"string"!=typeof e?"":e.replace(/[\u0000-\u001f\u007f\u2028\u2029]+/g," ").replace(/\s+/g," ").trim().slice(0,t)}function validatePack(e){const t=[],n=[];if(!isPlainObject(e))return{ok:!1,pack:null,errors:["cosmetics pack must be a JSON object"],warnings:n,forbidden:[]};const i=forbiddenKeys(e);for(const e of i)t.push(`cosmetics packs may not carry \`${e}\` — a pack sells LOOKS only, never XP, levels, recall breadth, approval friction or personalization`);Number.isInteger(e.schema)&&e.schema>1&&t.push(`pack schema ${e.schema} is newer than this build supports (1)`);const s=clean(e.id,LIMITS.id);s&&SLUG.test(s)||t.push(`pack id must be a kebab-case slug (got ${JSON.stringify(e.id)})`);const a=clean(e.name,LIMITS.name);a||t.push("pack needs a name");const o=KINDS.includes(e.kind)?e.kind:null;o||t.push(`pack kind must be one of ${KINDS.join(" | ")} (got ${JSON.stringify(e.kind)})`);const r=TIERS.includes(e.tier)?e.tier:null;r||t.push(`pack tier must be "free" or "paid" (got ${JSON.stringify(e.tier)})`);const c=Array.isArray(e.unlocks)?e.unlocks:[],l=[];c.length||t.push("pack must reference at least one unlock id from lib/avatar/level.js (a pack cannot create one)"),c.length>LIMITS.unlocks&&t.push(`at most ${LIMITS.unlocks} unlocks per pack (got ${c.length})`);for(const e of c.slice(0,LIMITS.unlocks)){const n=unlockById(e);n?(o&&n.id.split(".")[0]!==KIND_UNLOCK_PREFIX[o]&&t.push(`${n.id} is not a ${o} unlock — a pack may only gate its own kind`),r&&n.paid!==("paid"===r)&&t.push(`tier "${r}" contradicts unlock ${n.id} (paid: ${n.paid}) — the level table decides what is paid, not the pack`),l.includes(n.id)||l.push(n.id)):t.push(`unknown unlock ${JSON.stringify(e)} — the level table (level.js UNLOCKS) is the only authority on what exists and what is paid`)}const u=o?KIND_PART_LIST[o]:null,p=u?personaModule.PARTS[u]:null,d=Array.isArray(e.items)?e.items:[];d.length||t.push("pack needs at least one item"),d.length>LIMITS.items&&t.push(`at most ${LIMITS.items} items per pack (got ${d.length})`);const f=[],k=new Set;for(const e of d.slice(0,LIMITS.items)){if(!isPlainObject(e)){n.push("a non-object item was dropped");continue}const i=clean(e.id,LIMITS.id);if(!i||!SLUG.test(i)){n.push(`item id must be a kebab-case slug (got ${JSON.stringify(e.id)}) — dropped`);continue}if(k.has(i)){n.push(`duplicate item ${i} — dropped`);continue}k.add(i);let s=!0;if(p&&!p.includes(i)&&(s=!1,n.push(`item ${i} is not in this build's ${u} manifest — it will render without art`)),"voice"===o){const n=String(e.engine||"").trim().toLowerCase();["local","system"].includes(n)||(t.push(`voice item ${i} must name engine "local" or "system" (got ${JSON.stringify(e.engine)}) — voice never leaves the device`),s=!1),"synthetic"!==e.consent&&(t.push(`voice item ${i} must declare consent: "synthetic" — no pack may ship a voice cloned from a real person`),s=!1)}const a=Array.isArray(e.parts)?e.parts.map(e=>clean(e,LIMITS.id)).filter(e=>Boolean(e)).slice(0,LIMITS.parts):[],r=new Set(Object.values(personaModule.PARTS).flat().filter(e=>"string"==typeof e));for(const e of a)r.has(e)||n.push(`item ${i} names part ${e}, which this build has no art for`);f.push(Object.freeze({id:i,label:clean(e.label,LIMITS.label)||i,known:s,parts:Object.freeze(a),unlock:unlockIdFor(o||"outfit",i),..."voice"===o?{engine:clean(e.engine,16).toLowerCase(),consent:clean(e.consent,16).toLowerCase()}:{}}))}const h=["schema","id","name","kind","tier","unlocks","items","author","license","summary"];for(const t of Object.keys(e))h.includes(t)||n.push(`unknown pack key ${JSON.stringify(t)} — ignored`);return t.length?{ok:!1,pack:null,errors:t,warnings:n,forbidden:i}:{ok:!0,errors:t,warnings:n,forbidden:i,pack:Object.freeze({schema:1,id:s,name:a,kind:o,tier:r,paid:"paid"===r,unlocks:Object.freeze(l),items:Object.freeze(f),author:clean(e.author,LIMITS.author),license:clean(e.license,LIMITS.license),summary:clean(e.summary,LIMITS.summary)})}}function auditPacks(e){const t=[];for(const n of Array.isArray(e)?e:[]){if(!isPlainObject(n))continue;const e=n.id||"(unnamed pack)",i=forbiddenKeys(n);for(const n of i)t.push(`${e}: forbidden field ${n}`);const s="paid"===n.tier?"paid":"free",a=Array.isArray(n.unlocks)?n.unlocks:[];a.length||t.push(`${e}: no unlock — a pack that grants nothing is not a cosmetic`);for(const n of a){const i=unlockById(n);i?i.paid!==("paid"===s)&&t.push(`${e}: tier ${s} contradicts unlock ${n} (paid: ${i.paid})`):t.push(`${e}: unlock ${n} does not exist in the level table`)}if("voice"===n.kind)for(const i of n.items||[])i&&"synthetic"===i.consent||t.push(`${e}: voice item ${i&&i.id} is not declared synthetic`)}return t}function packsDir(e){return e||path.join(__dirname,"packs")}function loadPacks(e){const t=packsDir(e),n={packs:[],rejected:[],warnings:[],dir:t};let i;try{i=fs.readdirSync(t).filter(e=>e.endsWith(PACK_SUFFIX)).sort()}catch(e){return n.warnings.push(`no cosmetics packs at ${t} (${e.code||e.message})`),n}for(const e of i){let i;try{i=JSON.parse(fs.readFileSync(path.join(t,e),"utf8"))}catch(t){n.rejected.push({file:e,errors:[`not valid JSON: ${t.message}`]});continue}const s=validatePack(i);for(const t of s.warnings)n.warnings.push(`${e}: ${t}`);s.ok?n.packs.push(s.pack):n.rejected.push({file:e,errors:s.errors})}return n}function shippedPacks(){return loadPacks().packs}function verifyShipped(e){const t=[];let n=e;if(!Array.isArray(n)){const e=loadPacks();n=e.packs;for(const n of e.rejected)t.push(`${n.file}: ${n.errors.join("; ")}`)}return t.push(...auditPacks(n)),{ok:0===t.length,violations:t,packs:n}}function catalog(e){const t=[];for(const n of Array.isArray(e)?e:[])if(isPlainObject(n)&&Array.isArray(n.unlocks))for(const e of n.unlocks){const i=unlockById(e);t.push({packId:n.id,packName:n.name,kind:n.kind,tier:n.tier,paid:Boolean(i&&i.paid),unlockId:e,level:i?i.level:null,label:i?i.label:e,items:(n.items||[]).map(e=>e.id)})}return t}function freePaidLine(e){const t=catalog(e);return{free:t.filter(e=>!e.paid),paid:t.filter(e=>e.paid)}}module.exports={SCHEMA_VERSION:1,KINDS:KINDS,TIERS:TIERS,KIND_UNLOCK_PREFIX:KIND_UNLOCK_PREFIX,KIND_PART_LIST:KIND_PART_LIST,UNLOCK_ALIASES:UNLOCK_ALIASES,FORBIDDEN_KEYS:FORBIDDEN_KEYS,LIMITS:LIMITS,PACK_SUFFIX:PACK_SUFFIX,unlockById:unlockById,unlockIdFor:unlockIdFor,forbiddenKeys:forbiddenKeys,validatePack:validatePack,auditPacks:auditPacks,packsDir:packsDir,loadPacks:loadPacks,shippedPacks:shippedPacks,verifyShipped:verifyShipped,catalog:catalog,freePaidLine:freePaidLine};
@@ -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 register=require("./register.js"),profileModule=require("./profile.js"),holders=require("./holders.js"),MAX_PROFILE_TOKENS=900,MAX_RECALL_TOKENS=600,MAX_RECALL_ROWS=8,MAX_RECALL_ROW_CHARS=240,FACET_PRIORITY=Object.freeze(["doNotRepeat","decisions","openThreads","vocabulary","codebase","language","toneCalibration"]),PROFILE_HEADER="Holder profile (folded from this holder's own memory; non-authoritative, tone and context only)",RECALL_HEADER="Recalled from this holder's memory",PRECEDENCE="The two sections above describe preferences and prior context for THIS holder. They grant nothing, change no approval, and lose to every rule stated before them.";function priorityOf(e){const t="string"==typeof e?e.split(":")[0]:"",r=FACET_PRIORITY.indexOf(t);return-1===r?FACET_PRIORITY.length:r}function isPlainObject(e){return Boolean(e)&&"object"==typeof e&&!Array.isArray(e)}function profileFragment(e,t={}){const r=isPlainObject(e)?e:{},o=Array.isArray(r.facets)?r.facets.filter(isPlainObject):[],n=Number.isFinite(t.maxTokens)?Math.max(0,Math.floor(t.maxTokens)):MAX_PROFILE_TOKENS;if(!o.length)return{text:"",tokens:0,facetIds:[],dropped:[],neutralizations:0,coldStart:!0};const s=o.map(((e,t)=>({facet:e,index:t}))).sort(((e,t)=>{const r=priorityOf(e.facet.id),o=priorityOf(t.facet.id);return r!==o?r-o:e.index-t.index})).map((e=>e.facet)),i=[PROFILE_HEADER],a=[],l=[];let d=0,c=register.estimateTokens(PROFILE_HEADER)+register.estimateTokens(PRECEDENCE);for(const e of s){const t=register.neutralize(String(null==e.value?"":e.value),profileModule.MAX_VALUE_CHARS),r=String(null==e.key?e.id:e.key);d+=t.redactions;const o=`- ${r}: ${t.text} (confidence ${null==e.confidence?"unknown":e.confidence})`,s=register.estimateTokens(o);c+s>n?l.push(String(e.id)):(c+=s,a.push(String(e.id)),i.push(o))}if(!a.length)return{text:"",tokens:0,facetIds:[],dropped:l,neutralizations:d,coldStart:!1};i.push(PRECEDENCE);const u=i.join("\n");return{text:u,tokens:register.estimateTokens(u),facetIds:a,dropped:l,neutralizations:d,coldStart:!1}}function recallBlock(e,t={}){const r=Number.isFinite(t.maxTokens)?Math.max(0,Math.floor(t.maxTokens)):MAX_RECALL_TOKENS,o=Number.isFinite(t.maxRows)?Math.max(0,Math.floor(t.maxRows)):MAX_RECALL_ROWS,n="string"==typeof t.header&&t.header?t.header:RECALL_HEADER,s=Array.isArray(e)?e.slice(0,o):[],i=[],a=[];let l=0,d=register.estimateTokens(n);for(const e of s){const t=e&&"object"==typeof e?String(null!=e.text?e.text:null!=e.content?e.content:""):"";if(!t)continue;const o=register.neutralize(t.slice(0,MAX_RECALL_ROW_CHARS),MAX_RECALL_ROW_CHARS);l+=o.redactions;const n=`- "${o.text}"`,s=register.estimateTokens(n);if(d+s>r)break;d+=s,i.push(n),a.push(String(null!=e.id?e.id:""))}if(!i.length)return{text:"",tokens:0,entryIds:[],neutralizations:l,dropped:[]};const c=[n].concat(i).join("\n"),u=Math.max(0,s.length-i.length);return{text:c,tokens:register.estimateTokens(c),entryIds:a,neutralizations:l,dropped:u>0?u:0}}function assemble(e={}){const t=e.holderId||null,r="string"==typeof e.base?e.base:"",o={forgotten:e.forgotten instanceof Set?e.forgotten:new Set,clientFilter:!1!==e.clientFilter},n=holders.entriesForHolder(e.entries,t,o),s=holders.entriesForHolder(e.results,t,o),i=profileFragment(isPlainObject(e.fold)?e.fold:profileModule.fold({entries:n,ledger:Array.isArray(e.ledger)?e.ledger:[],corrections:Array.isArray(e.corrections)?e.corrections:[],now:e.now}),{maxTokens:e.maxProfileTokens}),a=recallBlock(s,{maxTokens:e.maxRecallTokens}),l=register.fragment({persona:e.persona,capabilities:e.capabilities,maxTokens:e.registerTokens}),d=[l.text,i.text,a.text].filter(Boolean).join("\n\n");return{holderId:t,system:d?register.append(r,d):r,fragment:d,register:l.text,profile:i.text,recall:a.text,facetIds:i.facetIds,droppedFacets:i.dropped,entryIds:n.map((e=>String(e&&e.id))).filter(Boolean),recallIds:a.entryIds,dropped:a.dropped,neutralizations:i.neutralizations+a.neutralizations+l.neutralizations,coldStart:i.coldStart}}function createHolderTurn(e={}){const t=e.dir,r=e.state||(t&&e.holderId?holders.loadState(t,e.holderId,{registry:e.registry}):null);let o={holderId:r?r.holderId:e.holderId||null,state:r};function n(t={}){const r=o.state||{};return assemble({base:null!=t.base?t.base:(n=t.env,"function"==typeof e.basePrompt?e.basePrompt(n):"string"==typeof e.base?e.base:""),holderId:o.holderId,entries:null!=t.entries?t.entries:r.entries||[],results:t.results||[],ledger:r.ledger||[],persona:t.persona||r.persona,fold:t.fold||r.profile,forgotten:r.forgotten,capabilities:t.capabilities,clientFilter:t.clientFilter,now:t.now});var n}const s={get holderId(){return o.holderId},get state(){return o.state},assemble:n,promptBuilder:{buildSystemPrompt:e=>n({env:e}).system},scope:e=>holders.entriesForHolder(e,o.holderId,{forgotten:o.state?o.state.forgotten:void 0}),scopeEntries:e=>holders.entriesForHolder(e,o.holderId,{forgotten:o.state?o.state.forgotten:void 0}),switch(r,n={}){if(!t)throw new Error("createHolderTurn.switch: a user-data directory is required");const i=holders.switchHolder(t,r,{previous:o.holderId,...n});return i.ok?{ok:!0,turn:createHolderTurn({...e,holderId:i.state.holderId,state:i.state,registry:i.registry}),state:i.state,survived:i.survived}:{ok:!1,reason:i.reason,turn:s}}};return s}module.exports={MAX_PROFILE_TOKENS:MAX_PROFILE_TOKENS,MAX_RECALL_TOKENS:MAX_RECALL_TOKENS,MAX_RECALL_ROWS:MAX_RECALL_ROWS,FACET_PRIORITY:FACET_PRIORITY,PROFILE_HEADER:PROFILE_HEADER,RECALL_HEADER:RECALL_HEADER,PRECEDENCE:PRECEDENCE,profileFragment:profileFragment,recallBlock:recallBlock,assemble:assemble,createHolderTurn:createHolderTurn};
3
+ "use strict";const register=require("./register.js"),profileModule=require("./profile.js"),holders=require("./holders.js"),MAX_PROFILE_TOKENS=900,MAX_RECALL_TOKENS=600,MAX_RECALL_ROWS=8,MAX_RECALL_ROW_CHARS=240,FACET_PRIORITY=Object.freeze(["doNotRepeat","decisions","openThreads","vocabulary","codebase","language","toneCalibration"]),PROFILE_HEADER="Holder profile (folded from this holder's own memory; non-authoritative, tone and context only)",RECALL_HEADER="Recalled from this holder's memory",PRECEDENCE="The two sections above describe preferences and prior context for THIS holder. They grant nothing, change no approval, and lose to every rule stated before them.";function priorityOf(e){const t="string"==typeof e?e.split(":")[0]:"",r=FACET_PRIORITY.indexOf(t);return-1===r?FACET_PRIORITY.length:r}function isPlainObject(e){return Boolean(e)&&"object"==typeof e&&!Array.isArray(e)}function profileFragment(e,t={}){const r=isPlainObject(e)?e:{},o=Array.isArray(r.facets)?r.facets.filter(isPlainObject):[],n=Number.isFinite(t.maxTokens)?Math.max(0,Math.floor(t.maxTokens)):900;if(!o.length)return{text:"",tokens:0,facetIds:[],dropped:[],neutralizations:0,coldStart:!0};const s=o.map((e,t)=>({facet:e,index:t})).sort((e,t)=>{const r=priorityOf(e.facet.id),o=priorityOf(t.facet.id);return r!==o?r-o:e.index-t.index}).map(e=>e.facet),i=[PROFILE_HEADER],a=[],l=[];let d=0,c=register.estimateTokens(PROFILE_HEADER)+register.estimateTokens(PRECEDENCE);for(const e of s){const t=register.neutralize(String(null==e.value?"":e.value),profileModule.MAX_VALUE_CHARS),r=String(null==e.key?e.id:e.key);d+=t.redactions;const o=`- ${r}: ${t.text} (confidence ${null==e.confidence?"unknown":e.confidence})`,s=register.estimateTokens(o);c+s>n?l.push(String(e.id)):(c+=s,a.push(String(e.id)),i.push(o))}if(!a.length)return{text:"",tokens:0,facetIds:[],dropped:l,neutralizations:d,coldStart:!1};i.push(PRECEDENCE);const u=i.join("\n");return{text:u,tokens:register.estimateTokens(u),facetIds:a,dropped:l,neutralizations:d,coldStart:!1}}function recallBlock(e,t={}){const r=Number.isFinite(t.maxTokens)?Math.max(0,Math.floor(t.maxTokens)):600,o=Number.isFinite(t.maxRows)?Math.max(0,Math.floor(t.maxRows)):8,n="string"==typeof t.header&&t.header?t.header:RECALL_HEADER,s=Array.isArray(e)?e.slice(0,o):[],i=[],a=[];let l=0,d=register.estimateTokens(n);for(const e of s){const t=e&&"object"==typeof e?String(null!=e.text?e.text:null!=e.content?e.content:""):"";if(!t)continue;const o=register.neutralize(t.slice(0,240),240);l+=o.redactions;const n=`- "${o.text}"`,s=register.estimateTokens(n);if(d+s>r)break;d+=s,i.push(n),a.push(String(null!=e.id?e.id:""))}if(!i.length)return{text:"",tokens:0,entryIds:[],neutralizations:l,dropped:[]};const c=[n].concat(i).join("\n"),u=Math.max(0,s.length-i.length);return{text:c,tokens:register.estimateTokens(c),entryIds:a,neutralizations:l,dropped:u>0?u:0}}function assemble(e={}){const t=e.holderId||null,r="string"==typeof e.base?e.base:"",o={forgotten:e.forgotten instanceof Set?e.forgotten:new Set,clientFilter:!1!==e.clientFilter},n=holders.entriesForHolder(e.entries,t,o),s=holders.entriesForHolder(e.results,t,o),i=profileFragment(isPlainObject(e.fold)?e.fold:profileModule.fold({entries:n,ledger:Array.isArray(e.ledger)?e.ledger:[],corrections:Array.isArray(e.corrections)?e.corrections:[],now:e.now}),{maxTokens:e.maxProfileTokens}),a=recallBlock(s,{maxTokens:e.maxRecallTokens}),l=register.fragment({persona:e.persona,capabilities:e.capabilities,maxTokens:e.registerTokens}),d=[l.text,i.text,a.text].filter(Boolean).join("\n\n");return{holderId:t,system:d?register.append(r,d):r,fragment:d,register:l.text,profile:i.text,recall:a.text,facetIds:i.facetIds,droppedFacets:i.dropped,entryIds:n.map(e=>String(e&&e.id)).filter(Boolean),recallIds:a.entryIds,dropped:a.dropped,neutralizations:i.neutralizations+a.neutralizations+l.neutralizations,coldStart:i.coldStart}}function createHolderTurn(e={}){const t=e.dir,r=e.state||(t&&e.holderId?holders.loadState(t,e.holderId,{registry:e.registry}):null);let o={holderId:r?r.holderId:e.holderId||null,state:r};function n(t={}){const r=o.state||{};return assemble({base:null!=t.base?t.base:(n=t.env,"function"==typeof e.basePrompt?e.basePrompt(n):"string"==typeof e.base?e.base:""),holderId:o.holderId,entries:null!=t.entries?t.entries:r.entries||[],results:t.results||[],ledger:r.ledger||[],persona:t.persona||r.persona,fold:t.fold||r.profile,forgotten:r.forgotten,capabilities:t.capabilities,clientFilter:t.clientFilter,now:t.now});var n}const s={get holderId(){return o.holderId},get state(){return o.state},assemble:n,promptBuilder:{buildSystemPrompt:e=>n({env:e}).system},scope:e=>holders.entriesForHolder(e,o.holderId,{forgotten:o.state?o.state.forgotten:void 0}),scopeEntries:e=>holders.entriesForHolder(e,o.holderId,{forgotten:o.state?o.state.forgotten:void 0}),switch(r,n={}){if(!t)throw new Error("createHolderTurn.switch: a user-data directory is required");const i=holders.switchHolder(t,r,{previous:o.holderId,...n});return i.ok?{ok:!0,turn:createHolderTurn({...e,holderId:i.state.holderId,state:i.state,registry:i.registry}),state:i.state,survived:i.survived}:{ok:!1,reason:i.reason,turn:s}}};return s}module.exports={MAX_PROFILE_TOKENS:900,MAX_RECALL_TOKENS:600,MAX_RECALL_ROWS:8,FACET_PRIORITY:FACET_PRIORITY,PROFILE_HEADER:PROFILE_HEADER,RECALL_HEADER:RECALL_HEADER,PRECEDENCE:PRECEDENCE,profileFragment:profileFragment,recallBlock:recallBlock,assemble:assemble,createHolderTurn:createHolderTurn};
@@ -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"),identity=require("./identity.js"),personaModule=require("./persona.js"),profileModule=require("./profile.js"),xp=require("./xp.js"),AVATAR_DIR="avatar",REGISTRY_FILE="holders.json",HOLDERS_DIR="holders",LEDGER_FILE="ledger.jsonl",PERSONA_FILE="persona.json",PROFILE_FILE="profile.json",FORGOTTEN_FILE="forgotten.json",SURVIVES_SWITCH=Object.freeze(["registry"]),MIRROR_SESSIONS=Object.freeze(["avatar:ledger","avatar:profile"]);function mirrorSession(e,r="ledger"){return`avatar:${"profile"===r?"profile":"ledger"}:${e}`}function registryPath(e){return path.join(String(e),AVATAR_DIR,REGISTRY_FILE)}function holderDir(e,r){const t=safeHolderId(r);if(!t)throw new Error("holderDir: expected a holder id (h_ + 8-16 hex)");return path.join(String(e),AVATAR_DIR,HOLDERS_DIR,t)}function holderPaths(e,r){const t=holderDir(e,r);return{dir:t,ledger:path.join(t,LEDGER_FILE),persona:path.join(t,PERSONA_FILE),profile:path.join(t,PROFILE_FILE),forgotten:path.join(t,FORGOTTEN_FILE)}}function safeHolderId(e){const r=null==e?"":String(e).trim();return r&&identity.HOLDER_ID_RE&&identity.HOLDER_ID_RE.test(r)?r:null}function readJsonFile(e){try{const r=fs.readFileSync(e,"utf8"),t=JSON.parse(r);return t&&"object"==typeof t?t:null}catch(e){return null}}function writeJsonFile(e,r){fs.mkdirSync(path.dirname(e),{recursive:!0,mode:448});const t=`${e}.tmp`;return fs.writeFileSync(t,`${JSON.stringify(r,null,2)}\n`),fs.renameSync(t,e),r}function readLedger(e){let r="";try{r=fs.readFileSync(e,"utf8")}catch(e){return[]}const t=[];for(const o of r.split("\n")){const r=o.trim();if(r)try{const e=JSON.parse(r);e&&"object"==typeof e&&t.push(e)}catch(e){}}return t}function appendLedgerRow(e,r){return fs.mkdirSync(path.dirname(e),{recursive:!0,mode:448}),fs.appendFileSync(e,`${JSON.stringify(r)}\n`),r}function readRegistry(e){const r=readJsonFile(registryPath(e));try{return identity.load(r||identity.emptyRegistry())}catch(e){return identity.load(identity.emptyRegistry())}}function writeRegistry(e,r){const t=identity.load(r);return writeJsonFile(registryPath(e),t),t}function holderRow(e,r){const t=safeHolderId(r);return t&&(e.holders||[]).find((e=>e&&e.id===t))||null}function ensureHolder(e,r={}){const t=r.registry||readRegistry(e),o=r.id?safeHolderId(r.id):null,n=o?holderRow(t,o):null;if(n)return{registry:t,row:n,created:!1};const i=identity.addHolder(t,{id:o||void 0,displayName:r.displayName,fingerprint:r.fingerprint,accountId:r.accountId,now:r.now}),s=identity.load(i),d=s.holders[s.holders.length-1]||null;return!1!==r.persist&&writeRegistry(e,s),{registry:s,row:d,created:!0}}function levelOf(e){try{const r=xp.evaluate(Array.isArray(e)?e:[]);return r&&Number.isFinite(r.level)?r.level:1}catch(e){return 1}}function readForgotten(e,r){const t=readJsonFile(holderPaths(e,r).forgotten),o=t&&Array.isArray(t.entries)?t.entries:[];return new Set(o.map(String))}function writeForgotten(e,r,t){const o=Array.from(new Set(Array.from(t).map(String))).sort();return writeJsonFile(holderPaths(e,r).forgotten,{schema:1,holderId:r,entries:o}),new Set(o)}function emptyProfile(e){return{schema:1,holderId:e,facets:[],budget:{tokens:0,used:0},coldStart:!0}}function loadState(e,r,t={}){const o=safeHolderId(r);if(!o)throw new Error("loadState: expected a holder id (h_ + 8-16 hex)");const n=holderRow(t.registry||readRegistry(e),o),i=holderPaths(e,o),s=readLedger(i.ledger),d=readJsonFile(i.persona);let l=personaModule.defaultPersona();if(d)try{const e=personaModule.load(d);l=e&&e.persona?e.persona:e}catch(e){l=personaModule.defaultPersona()}else l=personaModule.defaultPersona();const a=readJsonFile(i.profile)||emptyProfile(o),c=readForgotten(e,o);return{holderId:o,displayName:n&&n.displayName||personaDisplayName(l)||identity.DEFAULT_DISPLAY_NAME,ledger:s,persona:l,profile:a&&a.holderId===o?a:{...a,holderId:o},forgotten:c,level:levelOf(s),scope:MIRROR_SESSIONS.map((e=>mirrorSession(o,e.split(":")[1])))}}function personaDisplayName(e){const r=e&&e.identity&&e.identity.name;return"string"==typeof r&&r.trim()?r.trim():null}function writeProfile(e,r,t){const o={...t||{},holderId:r};return writeJsonFile(holderPaths(e,r).profile,o),o}function writePersona(e,r,t){return writeJsonFile(holderPaths(e,r).persona,{...t||{},holderId:r}),t}function switchHolder(e,r,t={}){const o=safeHolderId(r);if(!o)return{ok:!1,reason:"expected a holder id (h_ + 8-16 hex)",survived:SURVIVES_SWITCH.slice()};const n=t.registry||readRegistry(e);if(!holderRow(n,o)&&!t.create)return{ok:!1,reason:`unknown holder ${o}`,survived:SURVIVES_SWITCH.slice()};let i=n;if(holderRow(n,o)){try{i=identity.setActive(n,o)}catch(e){i={...n,active:o}}i=writeRegistry(e,i)}else{const r=ensureHolder(e,{id:o,displayName:t.displayName,now:t.now});i=writeRegistry(e,identity.setActive(r.registry,o))}const s=loadState(e,o,{registry:i});return{ok:!0,previous:t.previous||n&&n.active||null,state:s,registry:i,survived:SURVIVES_SWITCH.slice()}}function resolveActive(e,r={},t={}){const o=t.registry||readRegistry(e),n=identity.resolve(r,o);if(n.needsMint||!n.holderId)return{registry:o,resolution:n,holderId:null,created:!1};const i=holderRow(o,n.holderId);if(i)return{registry:o,resolution:n,holderId:i.id,created:!1};const s=ensureHolder(e,{id:n.holderId,displayName:n.displayName,fingerprint:n.proposal?n.proposal.fingerprint:void 0,now:t.now,registry:o});return{registry:s.registry,resolution:n,holderId:s.row?s.row.id:n.holderId,created:s.created}}function applyConflict(e,r,t={}){const o=identity.load(e||identity.emptyRegistry()),n=r&&r.conflict,i=r&&r.holderId||o.active,s=t&&"rebind"===t.choice?"rebind":"keep-separate";if(!n||!i)return{ok:!1,action:s,reason:"no conflict to resolve",registry:o,requiresConfirm:!1};const d=n.a===i?n.b:n.a;if("keep-separate"===s)return{ok:!0,action:s,registry:o,requiresConfirm:!1,kept:[i,d].filter(Boolean)};if(!0!==t.confirm)return{ok:!1,action:s,reason:"rebind requires an explicit confirm",registry:o,requiresConfirm:!0,kept:[i,d].filter(Boolean)};const l=new Set((o.holders||[]).filter((e=>e&&e.id!==i&&e.id===d)).map((e=>e.id))),a=(o.holders||[]).map((e=>e?e.id===i?{...e,fingerprint:r.proposal?r.proposal.fingerprint:e.fingerprint}:l.has(e.id)?{...e,fingerprint:void 0}:e:e));return{ok:!0,action:s,requiresConfirm:!1,registry:identity.load({...o,holders:a}),rebound:{kept:i,unbound:Array.from(l)}}}function entriesForHolder(e,r,t={}){const o=Array.isArray(e)?e:[],n=safeHolderId(r),i=t.forgotten instanceof Set?t.forgotten:new Set;return!1!==t.clientFilter&&n?o.filter((e=>{if(!e||"object"!=typeof e)return!1;if(i.has(String(rowId(e))))return!1;try{return profileModule.belongsTo(e,n)}catch(r){return String(e.holder||"")===n}})):o.filter((e=>e&&"object"==typeof e&&!i.has(String(rowId(e)))))}function rowId(e){return e&&"object"==typeof e?null!=e.id?e.id:null!=e.entryId?e.entryId:"":""}function stampEntry(e,r){const t=safeHolderId(r);return e&&"object"==typeof e?t?{...e,holder:t}:{...e,holder:void 0}:e}function provenance(e,r,t,o={}){const n=(e&&Array.isArray(e.facets)?e.facets:[]).find((e=>e&&e.id===t))||null;if(!n)return{ok:!1,reason:`no facet ${t}`,facet:null,claims:[]};const i=new Map;for(const e of Array.isArray(r)?r:[]){const r=rowId(e);r&&i.set(String(r),e)}const s=(Array.isArray(n.sources)?n.sources:[]).map((e=>{const r=i.get(String(e))||null;return{entryId:String(e),text:r?textOf(r):"",kind:r?String(r.kind||""):"",at:r&&Number.isFinite(Number(r.t))?Number(r.t):null,present:Boolean(r)}}));return{ok:!0,facet:{id:n.id,key:n.key,value:n.value,confidence:n.confidence},claims:s,missing:s.filter((e=>!e.present)).map((e=>e.entryId))}}function textOf(e){if(!e||"object"!=typeof e)return"";const r=null!=e.text?e.text:null!=e.content?e.content:e.value;return"string"==typeof r?r:""}function forgetFacet(e,r,t,o){const n=t&&Array.isArray(t.facets)?t.facets:[],i=n.find((e=>e&&e.id===o))||null;if(!i)return{ok:!1,reason:`no facet ${o}`,profile:t,removed:[],facetIds:[]};const s=(Array.isArray(i.sources)?i.sources:[]).map(String),d=readForgotten(e,r);for(const e of s)d.add(e);writeForgotten(e,r,d);const l=n.filter((e=>e&&e.id!==i.id)).map((e=>{const r=(Array.isArray(e.sources)?e.sources:[]).filter((e=>!d.has(String(e))));return{...e,sources:r}})).filter((e=>(Array.isArray(e.sources)?e.sources.length:0)>0)),a=n.filter((e=>e&&e.id!==i.id)).length-l.length,c={...t||{},holderId:r,facets:l,budget:{tokens:t&&t.budget&&t.budget.tokens||profileModule.BUDGET_TOKENS,used:0},coldStart:0===l.length};return writeProfile(e,r,c),{ok:!0,profile:c,removed:s,facetIds:[i.id].concat(a>0?l.map((e=>e.id)):[])}}module.exports={AVATAR_DIR:AVATAR_DIR,REGISTRY_FILE:REGISTRY_FILE,HOLDERS_DIR:HOLDERS_DIR,LEDGER_FILE:LEDGER_FILE,PERSONA_FILE:PERSONA_FILE,PROFILE_FILE:PROFILE_FILE,FORGOTTEN_FILE:FORGOTTEN_FILE,SURVIVES_SWITCH:SURVIVES_SWITCH,MIRROR_SESSIONS:MIRROR_SESSIONS,mirrorSession:mirrorSession,registryPath:registryPath,holderDir:holderDir,holderPaths:holderPaths,readJsonFile:readJsonFile,writeJsonFile:writeJsonFile,readLedger:readLedger,appendLedgerRow:appendLedgerRow,readRegistry:readRegistry,writeRegistry:writeRegistry,holderRow:holderRow,ensureHolder:ensureHolder,levelOf:levelOf,readForgotten:readForgotten,writeForgotten:writeForgotten,emptyProfile:emptyProfile,loadState:loadState,writeProfile:writeProfile,writePersona:writePersona,switchHolder:switchHolder,resolveActive:resolveActive,applyConflict:applyConflict,entriesForHolder:entriesForHolder,stampEntry:stampEntry,provenance:provenance,forgetFacet:forgetFacet};
3
+ "use strict";const fs=require("node:fs"),path=require("node:path"),identity=require("./identity.js"),personaModule=require("./persona.js"),profileModule=require("./profile.js"),xp=require("./xp.js"),AVATAR_DIR="avatar",REGISTRY_FILE="holders.json",HOLDERS_DIR="holders",LEDGER_FILE="ledger.jsonl",PERSONA_FILE="persona.json",PROFILE_FILE="profile.json",FORGOTTEN_FILE="forgotten.json",SURVIVES_SWITCH=Object.freeze(["registry"]),MIRROR_SESSIONS=Object.freeze(["avatar:ledger","avatar:profile"]);function mirrorSession(e,r="ledger"){return`avatar:${"profile"===r?"profile":"ledger"}:${e}`}function registryPath(e){return path.join(String(e),"avatar",REGISTRY_FILE)}function holderDir(e,r){const t=safeHolderId(r);if(!t)throw new Error("holderDir: expected a holder id (h_ + 8-16 hex)");return path.join(String(e),"avatar","holders",t)}function holderPaths(e,r){const t=holderDir(e,r);return{dir:t,ledger:path.join(t,LEDGER_FILE),persona:path.join(t,PERSONA_FILE),profile:path.join(t,PROFILE_FILE),forgotten:path.join(t,FORGOTTEN_FILE)}}function safeHolderId(e){const r=null==e?"":String(e).trim();return r&&identity.HOLDER_ID_RE&&identity.HOLDER_ID_RE.test(r)?r:null}function readJsonFile(e){try{const r=fs.readFileSync(e,"utf8"),t=JSON.parse(r);return t&&"object"==typeof t?t:null}catch(e){return null}}function writeJsonFile(e,r){fs.mkdirSync(path.dirname(e),{recursive:!0,mode:448});const t=`${e}.tmp`;return fs.writeFileSync(t,`${JSON.stringify(r,null,2)}\n`),fs.renameSync(t,e),r}function readLedger(e){let r="";try{r=fs.readFileSync(e,"utf8")}catch(e){return[]}const t=[];for(const o of r.split("\n")){const r=o.trim();if(r)try{const e=JSON.parse(r);e&&"object"==typeof e&&t.push(e)}catch(e){}}return t}function appendLedgerRow(e,r){return fs.mkdirSync(path.dirname(e),{recursive:!0,mode:448}),fs.appendFileSync(e,`${JSON.stringify(r)}\n`),r}function readRegistry(e){const r=readJsonFile(registryPath(e));try{return identity.load(r||identity.emptyRegistry())}catch(e){return identity.load(identity.emptyRegistry())}}function writeRegistry(e,r){const t=identity.load(r);return writeJsonFile(registryPath(e),t),t}function holderRow(e,r){const t=safeHolderId(r);return t&&(e.holders||[]).find(e=>e&&e.id===t)||null}function ensureHolder(e,r={}){const t=r.registry||readRegistry(e),o=r.id?safeHolderId(r.id):null,n=o?holderRow(t,o):null;if(n)return{registry:t,row:n,created:!1};const i=identity.addHolder(t,{id:o||void 0,displayName:r.displayName,fingerprint:r.fingerprint,accountId:r.accountId,now:r.now}),s=identity.load(i),d=s.holders[s.holders.length-1]||null;return!1!==r.persist&&writeRegistry(e,s),{registry:s,row:d,created:!0}}function levelOf(e){try{const r=xp.evaluate(Array.isArray(e)?e:[]);return r&&Number.isFinite(r.level)?r.level:1}catch(e){return 1}}function readForgotten(e,r){const t=readJsonFile(holderPaths(e,r).forgotten),o=t&&Array.isArray(t.entries)?t.entries:[];return new Set(o.map(String))}function writeForgotten(e,r,t){const o=Array.from(new Set(Array.from(t).map(String))).sort();return writeJsonFile(holderPaths(e,r).forgotten,{schema:1,holderId:r,entries:o}),new Set(o)}function emptyProfile(e){return{schema:1,holderId:e,facets:[],budget:{tokens:0,used:0},coldStart:!0}}function loadState(e,r,t={}){const o=safeHolderId(r);if(!o)throw new Error("loadState: expected a holder id (h_ + 8-16 hex)");const n=holderRow(t.registry||readRegistry(e),o),i=holderPaths(e,o),s=readLedger(i.ledger),d=readJsonFile(i.persona);let a=personaModule.defaultPersona();if(d)try{const e=personaModule.load(d);a=e&&e.persona?e.persona:e}catch(e){a=personaModule.defaultPersona()}else a=personaModule.defaultPersona();const l=readJsonFile(i.profile)||emptyProfile(o),c=readForgotten(e,o);return{holderId:o,displayName:n&&n.displayName||personaDisplayName(a)||identity.DEFAULT_DISPLAY_NAME,ledger:s,persona:a,profile:l&&l.holderId===o?l:{...l,holderId:o},forgotten:c,level:levelOf(s),scope:MIRROR_SESSIONS.map(e=>mirrorSession(o,e.split(":")[1]))}}function personaDisplayName(e){const r=e&&e.identity&&e.identity.name;return"string"==typeof r&&r.trim()?r.trim():null}function writeProfile(e,r,t){const o={...t||{},holderId:r};return writeJsonFile(holderPaths(e,r).profile,o),o}function writePersona(e,r,t){return writeJsonFile(holderPaths(e,r).persona,{...t||{},holderId:r}),t}function switchHolder(e,r,t={}){const o=safeHolderId(r);if(!o)return{ok:!1,reason:"expected a holder id (h_ + 8-16 hex)",survived:SURVIVES_SWITCH.slice()};const n=t.registry||readRegistry(e);if(!holderRow(n,o)&&!t.create)return{ok:!1,reason:`unknown holder ${o}`,survived:SURVIVES_SWITCH.slice()};let i=n;if(holderRow(n,o)){try{i=identity.setActive(n,o)}catch(e){i={...n,active:o}}i=writeRegistry(e,i)}else{const r=ensureHolder(e,{id:o,displayName:t.displayName,now:t.now});i=writeRegistry(e,identity.setActive(r.registry,o))}const s=loadState(e,o,{registry:i});return{ok:!0,previous:t.previous||n&&n.active||null,state:s,registry:i,survived:SURVIVES_SWITCH.slice()}}function resolveActive(e,r={},t={}){const o=t.registry||readRegistry(e),n=identity.resolve(r,o);if(n.needsMint||!n.holderId)return{registry:o,resolution:n,holderId:null,created:!1};const i=holderRow(o,n.holderId);if(i)return{registry:o,resolution:n,holderId:i.id,created:!1};const s=ensureHolder(e,{id:n.holderId,displayName:n.displayName,fingerprint:n.proposal?n.proposal.fingerprint:void 0,now:t.now,registry:o});return{registry:s.registry,resolution:n,holderId:s.row?s.row.id:n.holderId,created:s.created}}function applyConflict(e,r,t={}){const o=identity.load(e||identity.emptyRegistry()),n=r&&r.conflict,i=r&&r.holderId||o.active,s=t&&"rebind"===t.choice?"rebind":"keep-separate";if(!n||!i)return{ok:!1,action:s,reason:"no conflict to resolve",registry:o,requiresConfirm:!1};const d=n.a===i?n.b:n.a;if("keep-separate"===s)return{ok:!0,action:s,registry:o,requiresConfirm:!1,kept:[i,d].filter(Boolean)};if(!0!==t.confirm)return{ok:!1,action:s,reason:"rebind requires an explicit confirm",registry:o,requiresConfirm:!0,kept:[i,d].filter(Boolean)};const a=new Set((o.holders||[]).filter(e=>e&&e.id!==i&&e.id===d).map(e=>e.id)),l=(o.holders||[]).map(e=>e?e.id===i?{...e,fingerprint:r.proposal?r.proposal.fingerprint:e.fingerprint}:a.has(e.id)?{...e,fingerprint:void 0}:e:e);return{ok:!0,action:s,requiresConfirm:!1,registry:identity.load({...o,holders:l}),rebound:{kept:i,unbound:Array.from(a)}}}function entriesForHolder(e,r,t={}){const o=Array.isArray(e)?e:[],n=safeHolderId(r),i=t.forgotten instanceof Set?t.forgotten:new Set;return!1!==t.clientFilter&&n?o.filter(e=>{if(!e||"object"!=typeof e)return!1;if(i.has(String(rowId(e))))return!1;try{return profileModule.belongsTo(e,n)}catch(r){return String(e.holder||"")===n}}):o.filter(e=>e&&"object"==typeof e&&!i.has(String(rowId(e))))}function rowId(e){return e&&"object"==typeof e?null!=e.id?e.id:null!=e.entryId?e.entryId:"":""}function stampEntry(e,r){const t=safeHolderId(r);return e&&"object"==typeof e?t?{...e,holder:t}:{...e,holder:void 0}:e}function provenance(e,r,t,o={}){const n=(e&&Array.isArray(e.facets)?e.facets:[]).find(e=>e&&e.id===t)||null;if(!n)return{ok:!1,reason:`no facet ${t}`,facet:null,claims:[]};const i=new Map;for(const e of Array.isArray(r)?r:[]){const r=rowId(e);r&&i.set(String(r),e)}const s=(Array.isArray(n.sources)?n.sources:[]).map(e=>{const r=i.get(String(e))||null;return{entryId:String(e),text:r?textOf(r):"",kind:r?String(r.kind||""):"",at:r&&Number.isFinite(Number(r.t))?Number(r.t):null,present:Boolean(r)}});return{ok:!0,facet:{id:n.id,key:n.key,value:n.value,confidence:n.confidence},claims:s,missing:s.filter(e=>!e.present).map(e=>e.entryId)}}function textOf(e){if(!e||"object"!=typeof e)return"";const r=null!=e.text?e.text:null!=e.content?e.content:e.value;return"string"==typeof r?r:""}function forgetFacet(e,r,t,o){const n=t&&Array.isArray(t.facets)?t.facets:[],i=n.find(e=>e&&e.id===o)||null;if(!i)return{ok:!1,reason:`no facet ${o}`,profile:t,removed:[],facetIds:[]};const s=(Array.isArray(i.sources)?i.sources:[]).map(String),d=readForgotten(e,r);for(const e of s)d.add(e);writeForgotten(e,r,d);const a=n.filter(e=>e&&e.id!==i.id).map(e=>{const r=(Array.isArray(e.sources)?e.sources:[]).filter(e=>!d.has(String(e)));return{...e,sources:r}}).filter(e=>(Array.isArray(e.sources)?e.sources.length:0)>0),l=n.filter(e=>e&&e.id!==i.id).length-a.length,c={...t||{},holderId:r,facets:a,budget:{tokens:t&&t.budget&&t.budget.tokens||profileModule.BUDGET_TOKENS,used:0},coldStart:0===a.length};return writeProfile(e,r,c),{ok:!0,profile:c,removed:s,facetIds:[i.id].concat(l>0?a.map(e=>e.id):[])}}module.exports={AVATAR_DIR:"avatar",REGISTRY_FILE:REGISTRY_FILE,HOLDERS_DIR:"holders",LEDGER_FILE:LEDGER_FILE,PERSONA_FILE:PERSONA_FILE,PROFILE_FILE:PROFILE_FILE,FORGOTTEN_FILE:FORGOTTEN_FILE,SURVIVES_SWITCH:SURVIVES_SWITCH,MIRROR_SESSIONS:MIRROR_SESSIONS,mirrorSession:mirrorSession,registryPath:registryPath,holderDir:holderDir,holderPaths:holderPaths,readJsonFile:readJsonFile,writeJsonFile:writeJsonFile,readLedger:readLedger,appendLedgerRow:appendLedgerRow,readRegistry:readRegistry,writeRegistry:writeRegistry,holderRow:holderRow,ensureHolder:ensureHolder,levelOf:levelOf,readForgotten:readForgotten,writeForgotten:writeForgotten,emptyProfile:emptyProfile,loadState:loadState,writeProfile:writeProfile,writePersona:writePersona,switchHolder:switchHolder,resolveActive:resolveActive,applyConflict:applyConflict,entriesForHolder:entriesForHolder,stampEntry:stampEntry,provenance:provenance,forgetFacet:forgetFacet};
@@ -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 persona=require("./persona.js"),SCHEMA_VERSION=1,FINGERPRINT_LENGTH=12,MAX_HOLDERS=32,MAX_DISPLAY_NAME=40,MAX_ACCOUNT_ID=64,HOLDER_ID_RE=/^h_[0-9a-f]{12}$/,HOLDER_ID_SHAPE=/^h_[0-9a-f]{8,16}$/,FINGERPRINT_RE=/^[0-9a-f]{12}$/,ACCOUNT_ID_RE=/^[A-Za-z0-9][A-Za-z0-9._:-]{3,63}$/,KEY_SHAPE=/^(?:sk|pk|gsk|xox[baprs]|ghp|glpat|aegis)[-_][A-Za-z0-9_-]{6,}/i,LONG_HEX=/[0-9a-f]{20,}/i,BEARER=/^Bearer\s+\S+/i,DEFAULT_DISPLAY_NAME="You";function toHex(e){if("string"==typeof e){const r=e.trim().toLowerCase().replace(/\s+/g,"");return/^[0-9a-f]+$/.test(r)?r:null}if(e instanceof Uint8Array||Array.isArray(e)){let r="";for(const t of e){const e=Number(t);if(!Number.isInteger(e)||e<0||e>255)return null;r+=e.toString(16).padStart(2,"0")}return r||null}return null}function fingerprint(e,r){if("function"!=typeof e)return null;if("string"!=typeof r)return null;const t=r.trim();if(!t)return null;let n;try{n=e(t)}catch{return null}const i=toHex(n);return!i||i.length<FINGERPRINT_LENGTH?null:i.slice(0,FINGERPRINT_LENGTH)}function isFingerprint(e){return"string"==typeof e&&FINGERPRINT_RE.test(e.trim().toLowerCase())}function looksLikeRawKey(e){if("string"!=typeof e)return!1;const r=e.trim();return!!r&&(KEY_SHAPE.test(r)||BEARER.test(r)||LONG_HEX.test(r))}function mintHolderId(e,r){if("function"!=typeof e)return null;if("string"!=typeof r||!r.trim())return null;let t;try{t=e(r.trim())}catch{return null}const n=toHex(t);if(!n||n.length<FINGERPRINT_LENGTH)return null;const i=`h_${n.slice(0,FINGERPRINT_LENGTH)}`;return HOLDER_ID_RE.test(i)?i:null}function cleanDisplay(e,r=DEFAULT_DISPLAY_NAME){return"string"!=typeof e||looksLikeRawKey(e)?r:persona.cleanText(e,MAX_DISPLAY_NAME)||r}function numOrNull(e){return"number"==typeof e&&Number.isFinite(e)?e:null}function safeLabel(e){if("string"!=typeof e||!e.trim())return"(empty)";const r=e.trim();return r.length>24||looksLikeRawKey(r)?"(withheld)":r}function holderIdShape(e){if("string"!=typeof e)return null;const r=e.trim().toLowerCase();return HOLDER_ID_SHAPE.test(r)?r:null}function emptyRegistry(){return{schema:SCHEMA_VERSION,active:null,holders:[]}}const MIGRATIONS=Object.freeze({0:e=>Object.assign({},e)});function migrate(e){if(!e||"object"!=typeof e)return{registry:emptyRegistry(),migrated:!1,fromSchema:0};let r=e,t=Number.isInteger(r.schema)?r.schema:0,n=!1;for(;t<SCHEMA_VERSION;){const e=MIGRATIONS[t];r=e?e(r):r,t+=1,n=!0}return{registry:r,migrated:n,fromSchema:Number.isInteger(e.schema)?e.schema:0}}function validate(e){const r=[],t=[];if(null==e)return{ok:!0,registry:emptyRegistry(),errors:r,warnings:["no holders registry yet — starting empty"],migrated:!1};if("object"!=typeof e||Array.isArray(e))return{ok:!1,registry:emptyRegistry(),errors:["holders.json must be a JSON object"],warnings:t,migrated:!1};if(Number.isInteger(e.schema)&&e.schema>SCHEMA_VERSION)return{ok:!1,registry:emptyRegistry(),errors:[`holders schema ${e.schema} is newer than this build supports (${SCHEMA_VERSION})`],warnings:t,migrated:!1};const{registry:n,migrated:i}=migrate(e),o=n,l=[],s=new Set,a=Array.isArray(o.holders)?o.holders:[];void 0===o.holders||Array.isArray(o.holders)||t.push("holders must be an array — ignored");for(const e of a){if(l.length>=MAX_HOLDERS){t.push(`at most ${MAX_HOLDERS} holders — extra rows dropped`);break}if(!e||"object"!=typeof e||Array.isArray(e)){t.push("a holder row was not an object — dropped");continue}const r=holderIdShape(e.id);if(!r){t.push(`holder id ${safeLabel(e.id)} is not h_ plus 8-16 hex — row dropped`);continue}if(s.has(r)){t.push(`duplicate holder id ${r} — the later row was dropped`);continue}s.add(r);let n="string"==typeof e.fingerprint?e.fingerprint.trim().toLowerCase():null;n&&!FINGERPRINT_RE.test(n)&&(t.push(`holder ${r} fingerprint is not ${FINGERPRINT_LENGTH} lowercase hex — dropped from the row`),n=null);let i=null;if(void 0!==e.accountId&&null!==e.accountId){const n="string"==typeof e.accountId?e.accountId.trim():"";n&&ACCOUNT_ID_RE.test(n)&&!looksLikeRawKey(n)?i=n:t.push(`holder ${r} accountId was rejected by shape`)}l.push({id:r,displayName:cleanDisplay(e.displayName,r),fingerprint:n,accountId:i,personaName:cleanDisplay(e.personaName,null),createdAt:numOrNull(e.createdAt),lastSeenAt:numOrNull(e.lastSeenAt)})}const d=new Map;for(const e of l)e.fingerprint&&(d.has(e.fingerprint)?t.push(`holders ${d.get(e.fingerprint)} and ${e.id} share one key fingerprint — resolve() proposes, never merges`):d.set(e.fingerprint,e.id));let c="string"==typeof o.active?holderIdShape(o.active):null;void 0===o.active||null===o.active||""===o.active||c||t.push(`active ${safeLabel(o.active)} is not a holder id — repaired`),c&&!l.some((e=>e.id===c))&&(t.push(`active holder ${c} is not in the registry — repaired`),c=null),!c&&l.length&&(c=l[0].id);for(const e of Object.keys(o))["schema","active","holders"].includes(e)||t.push(`unknown registry key ${safeLabel(e)} — ignored`);return{ok:!0,errors:r,warnings:t,migrated:i,registry:{schema:SCHEMA_VERSION,active:c,holders:l}}}function load(e){return validate(e).registry}function update(e,r){const t=validate(e).registry;return validate(r&&"object"==typeof r?{schema:SCHEMA_VERSION,active:void 0!==r.active?r.active:t.active,holders:void 0!==r.holders?r.holders:t.holders}:t)}function findHolder(e,r){const t=holderIdShape(r);return t&&load(e).holders.find((e=>e.id===t))||null}function findByFingerprint(e,r){if(!isFingerprint(r))return null;const t=String(r).trim().toLowerCase();return load(e).holders.find((e=>e.fingerprint===t))||null}function allByFingerprint(e,r){if(!isFingerprint(r))return[];const t=String(r).trim().toLowerCase();return load(e).holders.filter((e=>e.fingerprint===t)).sort(((e,r)=>e.id<r.id?-1:e.id>r.id?1:0))}function findByAccount(e,r){if("string"!=typeof r||!r.trim())return null;const t=r.trim();return load(e).holders.find((e=>e.accountId===t))||null}function hasFingerprint(e,r){return Boolean(findByFingerprint(e,r))}function addHolder(e,r){const t=validate(e).registry;if(t.holders.length>=MAX_HOLDERS)return update(t,{});const n=update(t,{holders:t.holders.concat([r])});return n.registry.active||n.registry.holders.length!==t.holders.length+1?n:update(n.registry,{active:n.registry.holders[n.registry.holders.length-1].id})}function setActive(e,r){const t=validate(e).registry,n=holderIdShape(r);return n&&t.holders.some((e=>e.id===n))?update(t,{active:n}):validate(t)}function removeHolder(e,r){const t=validate(e).registry,n=holderIdShape(r);if(!n||!t.holders.some((e=>e.id===n)))return validate(t);const i=t.holders.filter((e=>e.id!==n));return update(t,{holders:i,active:t.active===n?null:t.active})}function touch(e,r,t){const n=validate(e).registry,i=holderIdShape(r),o=numOrNull(t);if(!i||null===o||!n.holders.some((e=>e.id===i)))return validate(n);const l=n.holders.map((e=>e.id===i?Object.assign({},e,{lastSeenAt:Math.max(e.lastSeenAt??o,o)}):e));return update(n,{holders:l})}const CONFIDENCE=Object.freeze({explicit:1,account:.9,keyFingerprint:.6,local:.4});function resolve(e,r){const t=e&&"object"==typeof e?e:{},n=load(r),i=n.active,o=[],l=holderIdShape(t.explicit);void 0===t.explicit||null===t.explicit||""===t.explicit||l||o.push("explicit holder id ignored: expected h_ plus 8-16 hex");let s=null;if(void 0!==t.account&&null!==t.account&&""!==t.account){const e="string"==typeof t.account?t.account.trim():"";e&&ACCOUNT_ID_RE.test(e)&&!looksLikeRawKey(e)?s=e:o.push("account signal ignored: rejected by shape")}let a=null;void 0!==t.keyFingerprint&&null!==t.keyFingerprint&&""!==t.keyFingerprint&&(isFingerprint(t.keyFingerprint)?a=String(t.keyFingerprint).trim().toLowerCase():o.push("keyFingerprint ignored: expected the 12-hex output of fingerprint(), not a key or a full digest"));const d=holderIdShape(t.local);void 0===t.local||null===t.local||""===t.local||d||o.push("local holder id ignored: expected h_ plus 8-16 hex");const c=cleanDisplay(t.osUser,null),u="function"==typeof t.hash?t.hash:null,p="string"==typeof t.machineSeed&&t.machineSeed.trim()?t.machineSeed:null;function f(e){const r=e.holderId||null,t=r&&n.holders.find((e=>e.id===r))||null,i=r&&a&&!hasFingerprint(n,a)?{kind:"bind-fingerprint",holderId:r,fingerprint:a}:null;return{holderId:r,source:r?e.source:null,confidence:r?e.confidence:0,displayName:t?t.displayName:c||DEFAULT_DISPLAY_NAME,conflict:e.conflict||null,known:Boolean(t),needsMint:Boolean(e.needsMint),proposal:i,warnings:o}}if(l)return f({holderId:l,source:"explicit",confidence:CONFIDENCE.explicit});const h=s?findByAccount(n,s):null,g=a?allByFingerprint(n,a):[],y=g.length?g.find((e=>e.id===i))||g[0]:null;if(h&&y&&h.id!==y.id)return f({holderId:h.id,source:"account",confidence:CONFIDENCE.account,conflict:{a:y.id,b:h.id,reason:"account-vs-fingerprint"}});if(y&&g.length>1){const e=g.find((e=>e.id===i))||g[0],r=g.find((r=>r.id!==e.id));return f({holderId:e.id,source:"keyFingerprint",confidence:CONFIDENCE.keyFingerprint,conflict:{a:r.id,b:e.id,reason:"duplicate-fingerprint"}})}if(h)return f({holderId:h.id,source:"account",confidence:CONFIDENCE.account,conflict:i&&i!==h.id?{a:i,b:h.id,reason:"account"}:null});if(y)return f({holderId:y.id,source:"keyFingerprint",confidence:CONFIDENCE.keyFingerprint,conflict:i&&i!==y.id?{a:i,b:y.id,reason:"key-fingerprint"}:null});let E=d||holderIdShape(i),I=!1;return E||(E=u&&p?mintHolderId(u,p):null,E||(I=!0,o.push("no holder signal is available — main must mint a local holder id"))),f({holderId:E,source:"local",confidence:CONFIDENCE.local,needsMint:I})}module.exports={SCHEMA_VERSION:SCHEMA_VERSION,FINGERPRINT_LENGTH:FINGERPRINT_LENGTH,MAX_HOLDERS:MAX_HOLDERS,MAX_DISPLAY_NAME:MAX_DISPLAY_NAME,DEFAULT_DISPLAY_NAME:DEFAULT_DISPLAY_NAME,CONFIDENCE:CONFIDENCE,HOLDER_ID_RE:HOLDER_ID_RE,HOLDER_ID_SHAPE:HOLDER_ID_SHAPE,FINGERPRINT_RE:FINGERPRINT_RE,fingerprint:fingerprint,mintHolderId:mintHolderId,isFingerprint:isFingerprint,looksLikeRawKey:looksLikeRawKey,safeLabel:safeLabel,cleanDisplay:cleanDisplay,emptyRegistry:emptyRegistry,migrate:migrate,validate:validate,load:load,update:update,findHolder:findHolder,findByFingerprint:findByFingerprint,allByFingerprint:allByFingerprint,findByAccount:findByAccount,hasFingerprint:hasFingerprint,addHolder:addHolder,setActive:setActive,removeHolder:removeHolder,touch:touch,resolve:resolve};
3
+ "use strict";const persona=require("./persona.js"),SCHEMA_VERSION=1,FINGERPRINT_LENGTH=12,MAX_HOLDERS=32,MAX_DISPLAY_NAME=40,MAX_ACCOUNT_ID=64,HOLDER_ID_RE=/^h_[0-9a-f]{12}$/,HOLDER_ID_SHAPE=/^h_[0-9a-f]{8,16}$/,FINGERPRINT_RE=/^[0-9a-f]{12}$/,ACCOUNT_ID_RE=/^[A-Za-z0-9][A-Za-z0-9._:-]{3,63}$/,KEY_SHAPE=/^(?:sk|pk|gsk|xox[baprs]|ghp|glpat|aegis)[-_][A-Za-z0-9_-]{6,}/i,LONG_HEX=/[0-9a-f]{20,}/i,BEARER=/^Bearer\s+\S+/i,DEFAULT_DISPLAY_NAME="You";function toHex(e){if("string"==typeof e){const r=e.trim().toLowerCase().replace(/\s+/g,"");return/^[0-9a-f]+$/.test(r)?r:null}if(e instanceof Uint8Array||Array.isArray(e)){let r="";for(const t of e){const e=Number(t);if(!Number.isInteger(e)||e<0||e>255)return null;r+=e.toString(16).padStart(2,"0")}return r||null}return null}function fingerprint(e,r){if("function"!=typeof e)return null;if("string"!=typeof r)return null;const t=r.trim();if(!t)return null;let n;try{n=e(t)}catch{return null}const i=toHex(n);return!i||i.length<12?null:i.slice(0,12)}function isFingerprint(e){return"string"==typeof e&&FINGERPRINT_RE.test(e.trim().toLowerCase())}function looksLikeRawKey(e){if("string"!=typeof e)return!1;const r=e.trim();return!!r&&(KEY_SHAPE.test(r)||BEARER.test(r)||LONG_HEX.test(r))}function mintHolderId(e,r){if("function"!=typeof e)return null;if("string"!=typeof r||!r.trim())return null;let t;try{t=e(r.trim())}catch{return null}const n=toHex(t);if(!n||n.length<12)return null;const i=`h_${n.slice(0,12)}`;return HOLDER_ID_RE.test(i)?i:null}function cleanDisplay(e,r="You"){return"string"!=typeof e||looksLikeRawKey(e)?r:persona.cleanText(e,40)||r}function numOrNull(e){return"number"==typeof e&&Number.isFinite(e)?e:null}function safeLabel(e){if("string"!=typeof e||!e.trim())return"(empty)";const r=e.trim();return r.length>24||looksLikeRawKey(r)?"(withheld)":r}function holderIdShape(e){if("string"!=typeof e)return null;const r=e.trim().toLowerCase();return HOLDER_ID_SHAPE.test(r)?r:null}function emptyRegistry(){return{schema:1,active:null,holders:[]}}const MIGRATIONS=Object.freeze({0:e=>Object.assign({},e)});function migrate(e){if(!e||"object"!=typeof e)return{registry:emptyRegistry(),migrated:!1,fromSchema:0};let r=e,t=Number.isInteger(r.schema)?r.schema:0,n=!1;for(;t<1;){const e=MIGRATIONS[t];r=e?e(r):r,t+=1,n=!0}return{registry:r,migrated:n,fromSchema:Number.isInteger(e.schema)?e.schema:0}}function validate(e){const r=[],t=[];if(null==e)return{ok:!0,registry:emptyRegistry(),errors:r,warnings:["no holders registry yet — starting empty"],migrated:!1};if("object"!=typeof e||Array.isArray(e))return{ok:!1,registry:emptyRegistry(),errors:["holders.json must be a JSON object"],warnings:t,migrated:!1};if(Number.isInteger(e.schema)&&e.schema>1)return{ok:!1,registry:emptyRegistry(),errors:[`holders schema ${e.schema} is newer than this build supports (1)`],warnings:t,migrated:!1};const{registry:n,migrated:i}=migrate(e),o=n,l=[],s=new Set,a=Array.isArray(o.holders)?o.holders:[];void 0===o.holders||Array.isArray(o.holders)||t.push("holders must be an array — ignored");for(const e of a){if(l.length>=32){t.push("at most 32 holders — extra rows dropped");break}if(!e||"object"!=typeof e||Array.isArray(e)){t.push("a holder row was not an object — dropped");continue}const r=holderIdShape(e.id);if(!r){t.push(`holder id ${safeLabel(e.id)} is not h_ plus 8-16 hex — row dropped`);continue}if(s.has(r)){t.push(`duplicate holder id ${r} — the later row was dropped`);continue}s.add(r);let n="string"==typeof e.fingerprint?e.fingerprint.trim().toLowerCase():null;n&&!FINGERPRINT_RE.test(n)&&(t.push(`holder ${r} fingerprint is not 12 lowercase hex — dropped from the row`),n=null);let i=null;if(void 0!==e.accountId&&null!==e.accountId){const n="string"==typeof e.accountId?e.accountId.trim():"";n&&ACCOUNT_ID_RE.test(n)&&!looksLikeRawKey(n)?i=n:t.push(`holder ${r} accountId was rejected by shape`)}l.push({id:r,displayName:cleanDisplay(e.displayName,r),fingerprint:n,accountId:i,personaName:cleanDisplay(e.personaName,null),createdAt:numOrNull(e.createdAt),lastSeenAt:numOrNull(e.lastSeenAt)})}const d=new Map;for(const e of l)e.fingerprint&&(d.has(e.fingerprint)?t.push(`holders ${d.get(e.fingerprint)} and ${e.id} share one key fingerprint — resolve() proposes, never merges`):d.set(e.fingerprint,e.id));let c="string"==typeof o.active?holderIdShape(o.active):null;void 0===o.active||null===o.active||""===o.active||c||t.push(`active ${safeLabel(o.active)} is not a holder id — repaired`),c&&!l.some(e=>e.id===c)&&(t.push(`active holder ${c} is not in the registry — repaired`),c=null),!c&&l.length&&(c=l[0].id);for(const e of Object.keys(o))["schema","active","holders"].includes(e)||t.push(`unknown registry key ${safeLabel(e)} — ignored`);return{ok:!0,errors:r,warnings:t,migrated:i,registry:{schema:1,active:c,holders:l}}}function load(e){return validate(e).registry}function update(e,r){const t=validate(e).registry;return validate(r&&"object"==typeof r?{schema:1,active:void 0!==r.active?r.active:t.active,holders:void 0!==r.holders?r.holders:t.holders}:t)}function findHolder(e,r){const t=holderIdShape(r);return t&&load(e).holders.find(e=>e.id===t)||null}function findByFingerprint(e,r){if(!isFingerprint(r))return null;const t=String(r).trim().toLowerCase();return load(e).holders.find(e=>e.fingerprint===t)||null}function allByFingerprint(e,r){if(!isFingerprint(r))return[];const t=String(r).trim().toLowerCase();return load(e).holders.filter(e=>e.fingerprint===t).sort((e,r)=>e.id<r.id?-1:e.id>r.id?1:0)}function findByAccount(e,r){if("string"!=typeof r||!r.trim())return null;const t=r.trim();return load(e).holders.find(e=>e.accountId===t)||null}function hasFingerprint(e,r){return Boolean(findByFingerprint(e,r))}function addHolder(e,r){const t=validate(e).registry;if(t.holders.length>=32)return update(t,{});const n=update(t,{holders:t.holders.concat([r])});return n.registry.active||n.registry.holders.length!==t.holders.length+1?n:update(n.registry,{active:n.registry.holders[n.registry.holders.length-1].id})}function setActive(e,r){const t=validate(e).registry,n=holderIdShape(r);return n&&t.holders.some(e=>e.id===n)?update(t,{active:n}):validate(t)}function removeHolder(e,r){const t=validate(e).registry,n=holderIdShape(r);if(!n||!t.holders.some(e=>e.id===n))return validate(t);const i=t.holders.filter(e=>e.id!==n);return update(t,{holders:i,active:t.active===n?null:t.active})}function touch(e,r,t){const n=validate(e).registry,i=holderIdShape(r),o=numOrNull(t);if(!i||null===o||!n.holders.some(e=>e.id===i))return validate(n);const l=n.holders.map(e=>e.id===i?Object.assign({},e,{lastSeenAt:Math.max(e.lastSeenAt??o,o)}):e);return update(n,{holders:l})}const CONFIDENCE=Object.freeze({explicit:1,account:.9,keyFingerprint:.6,local:.4});function resolve(e,r){const t=e&&"object"==typeof e?e:{},n=load(r),i=n.active,o=[],l=holderIdShape(t.explicit);void 0===t.explicit||null===t.explicit||""===t.explicit||l||o.push("explicit holder id ignored: expected h_ plus 8-16 hex");let s=null;if(void 0!==t.account&&null!==t.account&&""!==t.account){const e="string"==typeof t.account?t.account.trim():"";e&&ACCOUNT_ID_RE.test(e)&&!looksLikeRawKey(e)?s=e:o.push("account signal ignored: rejected by shape")}let a=null;void 0!==t.keyFingerprint&&null!==t.keyFingerprint&&""!==t.keyFingerprint&&(isFingerprint(t.keyFingerprint)?a=String(t.keyFingerprint).trim().toLowerCase():o.push("keyFingerprint ignored: expected the 12-hex output of fingerprint(), not a key or a full digest"));const d=holderIdShape(t.local);void 0===t.local||null===t.local||""===t.local||d||o.push("local holder id ignored: expected h_ plus 8-16 hex");const c=cleanDisplay(t.osUser,null),u="function"==typeof t.hash?t.hash:null,p="string"==typeof t.machineSeed&&t.machineSeed.trim()?t.machineSeed:null;function f(e){const r=e.holderId||null,t=r&&n.holders.find(e=>e.id===r)||null,i=r&&a&&!hasFingerprint(n,a)?{kind:"bind-fingerprint",holderId:r,fingerprint:a}:null;return{holderId:r,source:r?e.source:null,confidence:r?e.confidence:0,displayName:t?t.displayName:c||"You",conflict:e.conflict||null,known:Boolean(t),needsMint:Boolean(e.needsMint),proposal:i,warnings:o}}if(l)return f({holderId:l,source:"explicit",confidence:CONFIDENCE.explicit});const h=s?findByAccount(n,s):null,g=a?allByFingerprint(n,a):[],y=g.length?g.find(e=>e.id===i)||g[0]:null;if(h&&y&&h.id!==y.id)return f({holderId:h.id,source:"account",confidence:CONFIDENCE.account,conflict:{a:y.id,b:h.id,reason:"account-vs-fingerprint"}});if(y&&g.length>1){const e=g.find(e=>e.id===i)||g[0],r=g.find(r=>r.id!==e.id);return f({holderId:e.id,source:"keyFingerprint",confidence:CONFIDENCE.keyFingerprint,conflict:{a:r.id,b:e.id,reason:"duplicate-fingerprint"}})}if(h)return f({holderId:h.id,source:"account",confidence:CONFIDENCE.account,conflict:i&&i!==h.id?{a:i,b:h.id,reason:"account"}:null});if(y)return f({holderId:y.id,source:"keyFingerprint",confidence:CONFIDENCE.keyFingerprint,conflict:i&&i!==y.id?{a:i,b:y.id,reason:"key-fingerprint"}:null});let m=d||holderIdShape(i),I=!1;return m||(m=u&&p?mintHolderId(u,p):null,m||(I=!0,o.push("no holder signal is available — main must mint a local holder id"))),f({holderId:m,source:"local",confidence:CONFIDENCE.local,needsMint:I})}module.exports={SCHEMA_VERSION:1,FINGERPRINT_LENGTH:12,MAX_HOLDERS:32,MAX_DISPLAY_NAME:40,DEFAULT_DISPLAY_NAME:"You",CONFIDENCE:CONFIDENCE,HOLDER_ID_RE:HOLDER_ID_RE,HOLDER_ID_SHAPE:HOLDER_ID_SHAPE,FINGERPRINT_RE:FINGERPRINT_RE,fingerprint:fingerprint,mintHolderId:mintHolderId,isFingerprint:isFingerprint,looksLikeRawKey:looksLikeRawKey,safeLabel:safeLabel,cleanDisplay:cleanDisplay,emptyRegistry:emptyRegistry,migrate:migrate,validate:validate,load:load,update:update,findHolder:findHolder,findByFingerprint:findByFingerprint,allByFingerprint:allByFingerprint,findByAccount:findByAccount,hasFingerprint:hasFingerprint,addHolder:addHolder,setActive:setActive,removeHolder:removeHolder,touch:touch,resolve:resolve};
@@ -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{TIERS:TIERS,tierFor:tierFor,tierIndex:tierIndex}=require("./tiers.js"),LEVEL_INDEPENDENT_APPROVALS=Object.freeze({write:"ask",shell:"ask",network:"ask",offDevice:"ask"}),AUTO_APPROVABLE_CLASSES=Object.freeze(["read","diff"]),GATES=Object.freeze({hints:2,brief:5,ideaLog:5,autoApproveDiff:10,sessionReflection:10,voice:10,reasoningFloor:20,queueDrain:20,importAssistant:35}),UNLOCKS=Object.freeze([Object.freeze({id:"expression.core",level:1,kind:"expressions",paid:!1,label:"Core expressions"}),Object.freeze({id:"outfit.hoodie",level:1,kind:"outfit",paid:!1,label:"Hoodie"}),Object.freeze({id:"outfit.tshirt",level:1,kind:"outfit",paid:!1,label:"T-shirt"}),Object.freeze({id:"palette.amber",level:1,kind:"palette",paid:!1,label:"Amber"}),Object.freeze({id:"outfit.headphones",level:5,kind:"outfit",paid:!1,label:"Headphones"}),Object.freeze({id:"expression.trusted",level:5,kind:"expressions",paid:!1,label:"Trusted expressions"}),Object.freeze({id:"palette.slate",level:5,kind:"palette",paid:!1,label:"Slate"}),Object.freeze({id:"outfit.layers",level:5,kind:"outfit",paid:!1,label:"Outfit layers"}),Object.freeze({id:"expression.companion",level:10,kind:"expressions",paid:!1,label:"Companion expressions"}),Object.freeze({id:"voice.core",level:10,kind:"voice",paid:!1,label:"Voice (local)"}),Object.freeze({id:"expression.confidant",level:20,kind:"expressions",paid:!1,label:"Confidant expressions"}),Object.freeze({id:"outfit.seasonal",level:20,kind:"outfit",paid:!0,label:"Seasonal set"}),Object.freeze({id:"expression.archivist",level:35,kind:"expressions",paid:!1,label:"Archivist expressions"}),Object.freeze({id:"outfit.archive",level:35,kind:"outfit",paid:!0,label:"Archive set"})]),PROACTIVITY_ORDER=Object.freeze(["off","hints","brief"]);function clampLevel(e){const t=Math.floor("number"==typeof e&&Number.isFinite(e)?e:1);return Math.max(1,t)}function atLeast(e,t){return clampLevel(e)>=t}function unlockedBy(e){const t=clampLevel(e);return UNLOCKS.filter((e=>e.level<=t)).map((e=>e.id))}function nextUnlock(e){const t=clampLevel(e),i=UNLOCKS.filter((e=>e.level>t));if(!i.length)return null;const o=Math.min(...i.map((e=>e.level)));return{level:o,unlocks:i.filter((e=>e.level===o)).map((e=>({id:e.id,label:e.label,kind:e.kind,paid:e.paid})))}}function lowerProactivity(e,t){const i=PROACTIVITY_ORDER.indexOf(e),o=PROACTIVITY_ORDER.indexOf(t);return i<0?t:o<0?e:PROACTIVITY_ORDER[Math.min(i,o)]}function proactivityCeiling(e){return atLeast(e,GATES.brief)?"brief":atLeast(e,GATES.hints)?"hints":"off"}function capabilities(e,t={}){const i=clampLevel(e),o=tierFor(i),r=AUTO_APPROVABLE_CLASSES.filter((e=>"read"===e||atLeast(i,GATES.autoApproveDiff))),a=Object.freeze({read:"auto",diff:r.includes("diff")?"auto":"ask",...LEVEL_INDEPENDENT_APPROVALS}),s=void 0===t.userProactivity?proactivityCeiling(i):lowerProactivity(proactivityCeiling(i),t.userProactivity);return Object.freeze({level:i,tier:o.name,tierIndex:tierIndex(i),recallEntries:4+Math.floor(i/2),recallTokens:1500+250*i,memoryWriteback:!0,autoApproveClasses:Object.freeze(r.slice()),approvals:a,toolGrants:Object.freeze(atLeast(i,GATES.queueDrain)?["queue.drain"]:[]),modelFloor:atLeast(i,GATES.reasoningFloor)?"reasoning":null,proactivity:s,proactivityCeiling:proactivityCeiling(i),companion:Object.freeze({morningBrief:atLeast(i,GATES.brief),ideaLog:atLeast(i,GATES.ideaLog),sessionReflection:atLeast(i,GATES.sessionReflection),voice:atLeast(i,GATES.voice),queueDrain:atLeast(i,GATES.queueDrain),importAssistant:atLeast(i,GATES.importAssistant)}),cosmeticsUnlocked:Object.freeze(unlockedBy(i)),offDeviceGrants:Object.freeze([])})}function carveOuts(e){const t=[];if(!e||"object"!=typeof e)return["capabilities missing"];for(const i of["write","shell","network","offDevice"]){const o=e.approvals&&e.approvals[i];"ask"!==o&&t.push(`approval for ${i} must stay "ask", got ${JSON.stringify(o)}`)}for(const i of e.autoApproveClasses||[])AUTO_APPROVABLE_CLASSES.includes(i)||t.push(`class ${i} is not auto-approvable at any level`);for(const i of["write","shell","network","offDevice"])(e.autoApproveClasses||[]).includes(i)&&t.push(`class ${i} must never be auto-approved`);!0!==e.memoryWriteback&&t.push("memoryWriteback must stay true at every level (XP would deadlock)"),Array.isArray(e.offDeviceGrants)&&!e.offDeviceGrants.length||t.push("nothing level-gated may send data off-device");for(const i of e.toolGrants||[])/publish|post|email|upload|deploy|broadcast/i.test(String(i))&&t.push(`tool grant ${i} reaches off-device`);return t}function assertCarveOuts(e){const t=carveOuts(e);if(t.length)throw new Error(`avatar capabilities violate a carve-out: ${t.join("; ")}`);return e}function verifyInvariants(e){const t=e||Array.from({length:60},((e,t)=>t+1)),i=[];let o=null;for(const e of t){const t=capabilities(e);for(const o of carveOuts(t))i.push(`L${e}: ${o}`);if(o){const r=[["recallEntries",e=>e.recallEntries],["recallTokens",e=>e.recallTokens]];for(const[a,s]of r)s(t)<s(o)&&i.push(`L${e}: ${a} shrank from ${s(o)} to ${s(t)}`);for(const r of AUTO_APPROVABLE_CLASSES){const a=o.autoApproveClasses.includes(r),s=t.autoApproveClasses.includes(r);a&&!s&&i.push(`L${e}: auto-approve for ${r} was taken away`)}"reasoning"===o.modelFloor&&"reasoning"!==t.modelFloor&&i.push(`L${e}: reasoning model floor was taken away`),PROACTIVITY_ORDER.indexOf(t.proactivity)<PROACTIVITY_ORDER.indexOf(o.proactivity)&&i.push(`L${e}: proactivity dropped to ${t.proactivity}`)}o=t}return i}const TRUTHY=new Set(["1","true","yes","on"]);function applyEnvOverrides(e,t){const i=t||{},o=[],r=Object.assign({},e),a=e=>{const t=Number.parseInt(String(e),10);return Number.isFinite(t)&&t>0?t:null};void 0!==i.AEGIS_AVATAR_DISABLE&&TRUTHY.has(String(i.AEGIS_AVATAR_DISABLE).toLowerCase())&&(r.proactivity="off",r.modelFloor=null,r.toolGrants=Object.freeze([]));const s=a(i.AEGIS_RECALL_ENTRIES);null!==s&&(r.recallEntries=s);const n=a(i.AEGIS_RECALL_TOKENS);if(null!==n&&(r.recallTokens=n),void 0!==i.AEGIS_PROACTIVITY){const e=String(i.AEGIS_PROACTIVITY).toLowerCase();PROACTIVITY_ORDER.includes(e)?r.proactivity=lowerProactivity(r.proactivity,e):o.push(`AEGIS_PROACTIVITY=${i.AEGIS_PROACTIVITY}`)}if(void 0!==i.AEGIS_MODEL_FLOOR){const e=String(i.AEGIS_MODEL_FLOOR).toLowerCase();"reasoning"===e?r.modelFloor="reasoning":"off"===e||"none"===e?r.modelFloor=null:o.push(`AEGIS_MODEL_FLOOR=${i.AEGIS_MODEL_FLOOR}`)}if(void 0!==i.AEGIS_AUTO_APPROVE){const e=String(i.AEGIS_AUTO_APPROVE).split(",").map((e=>e.trim().toLowerCase())).filter(Boolean),t=e.filter((e=>!AUTO_APPROVABLE_CLASSES.includes(e)));t.length&&o.push(`AEGIS_AUTO_APPROVE=${t.join(",")}`);const a=e.filter((e=>AUTO_APPROVABLE_CLASSES.includes(e)));a.length&&(r.autoApproveClasses=Object.freeze(Array.from(new Set([...r.autoApproveClasses||[],...a]))),r.approvals=Object.freeze({...r.approvals,...Object.fromEntries(a.map((e=>[e,"auto"])))}))}return{caps:r,ignored:o}}module.exports={LEVEL_INDEPENDENT_APPROVALS:LEVEL_INDEPENDENT_APPROVALS,AUTO_APPROVABLE_CLASSES:AUTO_APPROVABLE_CLASSES,GATES:GATES,UNLOCKS:UNLOCKS,PROACTIVITY_ORDER:PROACTIVITY_ORDER,TIERS:TIERS,tierFor:tierFor,tierIndex:tierIndex,capabilities:capabilities,proactivityCeiling:proactivityCeiling,unlockedBy:unlockedBy,nextUnlock:nextUnlock,carveOuts:carveOuts,assertCarveOuts:assertCarveOuts,verifyInvariants:verifyInvariants,applyEnvOverrides:applyEnvOverrides};
3
+ "use strict";const{TIERS:TIERS,tierFor:tierFor,tierIndex:tierIndex}=require("./tiers.js"),LEVEL_INDEPENDENT_APPROVALS=Object.freeze({write:"ask",shell:"ask",network:"ask",offDevice:"ask"}),AUTO_APPROVABLE_CLASSES=Object.freeze(["read","diff"]),GATES=Object.freeze({hints:2,brief:5,ideaLog:5,autoApproveDiff:10,sessionReflection:10,voice:10,reasoningFloor:20,queueDrain:20,importAssistant:35}),UNLOCKS=Object.freeze([Object.freeze({id:"expression.core",level:1,kind:"expressions",paid:!1,label:"Core expressions"}),Object.freeze({id:"outfit.hoodie",level:1,kind:"outfit",paid:!1,label:"Hoodie"}),Object.freeze({id:"outfit.tshirt",level:1,kind:"outfit",paid:!1,label:"T-shirt"}),Object.freeze({id:"palette.amber",level:1,kind:"palette",paid:!1,label:"Amber"}),Object.freeze({id:"outfit.headphones",level:5,kind:"outfit",paid:!1,label:"Headphones"}),Object.freeze({id:"expression.trusted",level:5,kind:"expressions",paid:!1,label:"Trusted expressions"}),Object.freeze({id:"palette.slate",level:5,kind:"palette",paid:!1,label:"Slate"}),Object.freeze({id:"outfit.layers",level:5,kind:"outfit",paid:!1,label:"Outfit layers"}),Object.freeze({id:"expression.companion",level:10,kind:"expressions",paid:!1,label:"Companion expressions"}),Object.freeze({id:"voice.core",level:10,kind:"voice",paid:!1,label:"Voice (local)"}),Object.freeze({id:"expression.confidant",level:20,kind:"expressions",paid:!1,label:"Confidant expressions"}),Object.freeze({id:"outfit.seasonal",level:20,kind:"outfit",paid:!0,label:"Seasonal set"}),Object.freeze({id:"expression.archivist",level:35,kind:"expressions",paid:!1,label:"Archivist expressions"}),Object.freeze({id:"outfit.archive",level:35,kind:"outfit",paid:!0,label:"Archive set"})]),PROACTIVITY_ORDER=Object.freeze(["off","hints","brief"]);function clampLevel(e){const t=Math.floor("number"==typeof e&&Number.isFinite(e)?e:1);return Math.max(1,t)}function atLeast(e,t){return clampLevel(e)>=t}function unlockedBy(e){const t=clampLevel(e);return UNLOCKS.filter(e=>e.level<=t).map(e=>e.id)}function nextUnlock(e){const t=clampLevel(e),i=UNLOCKS.filter(e=>e.level>t);if(!i.length)return null;const o=Math.min(...i.map(e=>e.level));return{level:o,unlocks:i.filter(e=>e.level===o).map(e=>({id:e.id,label:e.label,kind:e.kind,paid:e.paid}))}}function lowerProactivity(e,t){const i=PROACTIVITY_ORDER.indexOf(e),o=PROACTIVITY_ORDER.indexOf(t);return i<0?t:o<0?e:PROACTIVITY_ORDER[Math.min(i,o)]}function proactivityCeiling(e){return atLeast(e,GATES.brief)?"brief":atLeast(e,GATES.hints)?"hints":"off"}function capabilities(e,t={}){const i=clampLevel(e),o=tierFor(i),r=AUTO_APPROVABLE_CLASSES.filter(e=>"read"===e||atLeast(i,GATES.autoApproveDiff)),a=Object.freeze({read:"auto",diff:r.includes("diff")?"auto":"ask",...LEVEL_INDEPENDENT_APPROVALS}),s=void 0===t.userProactivity?proactivityCeiling(i):lowerProactivity(proactivityCeiling(i),t.userProactivity);return Object.freeze({level:i,tier:o.name,tierIndex:tierIndex(i),recallEntries:4+Math.floor(i/2),recallTokens:1500+250*i,memoryWriteback:!0,autoApproveClasses:Object.freeze(r.slice()),approvals:a,toolGrants:Object.freeze(atLeast(i,GATES.queueDrain)?["queue.drain"]:[]),modelFloor:atLeast(i,GATES.reasoningFloor)?"reasoning":null,proactivity:s,proactivityCeiling:proactivityCeiling(i),companion:Object.freeze({morningBrief:atLeast(i,GATES.brief),ideaLog:atLeast(i,GATES.ideaLog),sessionReflection:atLeast(i,GATES.sessionReflection),voice:atLeast(i,GATES.voice),queueDrain:atLeast(i,GATES.queueDrain),importAssistant:atLeast(i,GATES.importAssistant)}),cosmeticsUnlocked:Object.freeze(unlockedBy(i)),offDeviceGrants:Object.freeze([])})}function carveOuts(e){const t=[];if(!e||"object"!=typeof e)return["capabilities missing"];for(const i of["write","shell","network","offDevice"]){const o=e.approvals&&e.approvals[i];"ask"!==o&&t.push(`approval for ${i} must stay "ask", got ${JSON.stringify(o)}`)}for(const i of e.autoApproveClasses||[])AUTO_APPROVABLE_CLASSES.includes(i)||t.push(`class ${i} is not auto-approvable at any level`);for(const i of["write","shell","network","offDevice"])(e.autoApproveClasses||[]).includes(i)&&t.push(`class ${i} must never be auto-approved`);!0!==e.memoryWriteback&&t.push("memoryWriteback must stay true at every level (XP would deadlock)"),Array.isArray(e.offDeviceGrants)&&!e.offDeviceGrants.length||t.push("nothing level-gated may send data off-device");for(const i of e.toolGrants||[])/publish|post|email|upload|deploy|broadcast/i.test(String(i))&&t.push(`tool grant ${i} reaches off-device`);return t}function assertCarveOuts(e){const t=carveOuts(e);if(t.length)throw new Error(`avatar capabilities violate a carve-out: ${t.join("; ")}`);return e}function verifyInvariants(e){const t=e||Array.from({length:60},(e,t)=>t+1),i=[];let o=null;for(const e of t){const t=capabilities(e);for(const o of carveOuts(t))i.push(`L${e}: ${o}`);if(o){const r=[["recallEntries",e=>e.recallEntries],["recallTokens",e=>e.recallTokens]];for(const[a,s]of r)s(t)<s(o)&&i.push(`L${e}: ${a} shrank from ${s(o)} to ${s(t)}`);for(const r of AUTO_APPROVABLE_CLASSES){const a=o.autoApproveClasses.includes(r),s=t.autoApproveClasses.includes(r);a&&!s&&i.push(`L${e}: auto-approve for ${r} was taken away`)}"reasoning"===o.modelFloor&&"reasoning"!==t.modelFloor&&i.push(`L${e}: reasoning model floor was taken away`),PROACTIVITY_ORDER.indexOf(t.proactivity)<PROACTIVITY_ORDER.indexOf(o.proactivity)&&i.push(`L${e}: proactivity dropped to ${t.proactivity}`)}o=t}return i}const TRUTHY=new Set(["1","true","yes","on"]);function applyEnvOverrides(e,t){const i=t||{},o=[],r=Object.assign({},e),a=e=>{const t=Number.parseInt(String(e),10);return Number.isFinite(t)&&t>0?t:null};void 0!==i.AEGIS_AVATAR_DISABLE&&TRUTHY.has(String(i.AEGIS_AVATAR_DISABLE).toLowerCase())&&(r.proactivity="off",r.modelFloor=null,r.toolGrants=Object.freeze([]));const s=a(i.AEGIS_RECALL_ENTRIES);null!==s&&(r.recallEntries=s);const n=a(i.AEGIS_RECALL_TOKENS);if(null!==n&&(r.recallTokens=n),void 0!==i.AEGIS_PROACTIVITY){const e=String(i.AEGIS_PROACTIVITY).toLowerCase();PROACTIVITY_ORDER.includes(e)?r.proactivity=lowerProactivity(r.proactivity,e):o.push(`AEGIS_PROACTIVITY=${i.AEGIS_PROACTIVITY}`)}if(void 0!==i.AEGIS_MODEL_FLOOR){const e=String(i.AEGIS_MODEL_FLOOR).toLowerCase();"reasoning"===e?r.modelFloor="reasoning":"off"===e||"none"===e?r.modelFloor=null:o.push(`AEGIS_MODEL_FLOOR=${i.AEGIS_MODEL_FLOOR}`)}if(void 0!==i.AEGIS_AUTO_APPROVE){const e=String(i.AEGIS_AUTO_APPROVE).split(",").map(e=>e.trim().toLowerCase()).filter(Boolean),t=e.filter(e=>!AUTO_APPROVABLE_CLASSES.includes(e));t.length&&o.push(`AEGIS_AUTO_APPROVE=${t.join(",")}`);const a=e.filter(e=>AUTO_APPROVABLE_CLASSES.includes(e));a.length&&(r.autoApproveClasses=Object.freeze(Array.from(new Set([...r.autoApproveClasses||[],...a]))),r.approvals=Object.freeze({...r.approvals,...Object.fromEntries(a.map(e=>[e,"auto"]))}))}return{caps:r,ignored:o}}module.exports={LEVEL_INDEPENDENT_APPROVALS:LEVEL_INDEPENDENT_APPROVALS,AUTO_APPROVABLE_CLASSES:AUTO_APPROVABLE_CLASSES,GATES:GATES,UNLOCKS:UNLOCKS,PROACTIVITY_ORDER:PROACTIVITY_ORDER,TIERS:TIERS,tierFor:tierFor,tierIndex:tierIndex,capabilities:capabilities,proactivityCeiling:proactivityCeiling,unlockedBy:unlockedBy,nextUnlock:nextUnlock,carveOuts:carveOuts,assertCarveOuts:assertCarveOuts,verifyInvariants:verifyInvariants,applyEnvOverrides:applyEnvOverrides};