aegisone 1.0.63 → 1.0.65

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (363) hide show
  1. package/README.md +1 -1
  2. package/bin/aegis.js +1 -1
  3. package/package.json +1 -1
  4. package/scripts/bump.mjs +1 -1
  5. package/scripts/bundle.js +1 -1
  6. package/scripts/postinstall.mjs +1 -1
  7. package/scripts/predist.mjs +1 -1
  8. package/src/child.js +1 -1
  9. package/src/dispatch.js +1 -1
  10. package/src/doctor.js +1 -1
  11. package/src/probes.js +1 -1
  12. package/src/productupdate.js +1 -1
  13. package/src/protocol.js +1 -1
  14. package/src/release.js +1 -1
  15. package/src/selfhost.js +1 -1
  16. package/vendor/cli/package.json +1 -1
  17. package/vendor/cli/scripts/check.mjs +1 -1
  18. package/vendor/cli/scripts/demo.mjs +1 -1
  19. package/vendor/cli/scripts/postinstall.mjs +1 -1
  20. package/vendor/cli/scripts/predist.mjs +1 -1
  21. package/vendor/cli/scripts/runtests.mjs +1 -1
  22. package/vendor/cli/src/app.js +1 -1
  23. package/vendor/cli/src/art.js +1 -1
  24. package/vendor/cli/src/chatflow.js +1 -1
  25. package/vendor/cli/src/checkpoint.js +1 -1
  26. package/vendor/cli/src/clipboard.js +1 -1
  27. package/vendor/cli/src/cloudsync.js +1 -1
  28. package/vendor/cli/src/commands.js +2 -2
  29. package/vendor/cli/src/config.js +1 -1
  30. package/vendor/cli/src/connect.js +1 -1
  31. package/vendor/cli/src/devrun.js +1 -1
  32. package/vendor/cli/src/diff.js +1 -1
  33. package/vendor/cli/src/diffview.js +1 -1
  34. package/vendor/cli/src/dream.js +1 -1
  35. package/vendor/cli/src/engine.js +1 -1
  36. package/vendor/cli/src/events.js +1 -1
  37. package/vendor/cli/src/export.js +1 -1
  38. package/vendor/cli/src/fingerprint.js +1 -1
  39. package/vendor/cli/src/format.js +1 -1
  40. package/vendor/cli/src/fuzzy.js +1 -1
  41. package/vendor/cli/src/history.js +1 -1
  42. package/vendor/cli/src/init.js +1 -1
  43. package/vendor/cli/src/markdown.js +1 -1
  44. package/vendor/cli/src/models.js +1 -1
  45. package/vendor/cli/src/overlays.js +1 -1
  46. package/vendor/cli/src/panels.js +1 -1
  47. package/vendor/cli/src/ping.js +1 -1
  48. package/vendor/cli/src/presence.js +1 -1
  49. package/vendor/cli/src/render.js +1 -1
  50. package/vendor/cli/src/screen.js +1 -1
  51. package/vendor/cli/src/screens.js +1 -1
  52. package/vendor/cli/src/secret.js +1 -1
  53. package/vendor/cli/src/securefs.js +1 -1
  54. package/vendor/cli/src/settings.js +1 -1
  55. package/vendor/cli/src/signup.js +1 -1
  56. package/vendor/cli/src/summarize.js +1 -1
  57. package/vendor/cli/src/sysdiag.js +1 -1
  58. package/vendor/cli/src/theme.js +1 -1
  59. package/vendor/cli/src/title.js +1 -1
  60. package/vendor/cli/src/todos.js +1 -1
  61. package/vendor/cli/src/tokens.js +1 -1
  62. package/vendor/cli/src/topup.js +1 -1
  63. package/vendor/cli/src/update.js +1 -1
  64. package/vendor/cli/vendor/client/aegis.js +1 -1
  65. package/vendor/cli/vendor/client/attest.js +1 -1
  66. package/vendor/cli/vendor/client/authorship-key.js +1 -1
  67. package/vendor/cli/vendor/client/auto-provision.js +1 -1
  68. package/vendor/cli/vendor/client/brain-catalog.js +1 -1
  69. package/vendor/cli/vendor/client/byok-catalog.js +1 -1
  70. package/vendor/cli/vendor/client/catalog-client.js +1 -1
  71. package/vendor/cli/vendor/client/conversation-export.js +1 -1
  72. package/vendor/cli/vendor/client/credentials.js +1 -1
  73. package/vendor/cli/vendor/client/credits.js +1 -1
  74. package/vendor/cli/vendor/client/drive-connect.js +1 -1
  75. package/vendor/cli/vendor/client/env-file.js +1 -1
  76. package/vendor/cli/vendor/client/fingerprint.js +1 -1
  77. package/vendor/cli/vendor/client/foreign-memory.js +1 -1
  78. package/vendor/cli/vendor/client/foreign-sessions.js +1 -1
  79. package/vendor/cli/vendor/client/google-signin.js +1 -1
  80. package/vendor/cli/vendor/client/hooks.js +1 -1
  81. package/vendor/cli/vendor/client/model-discovery.js +1 -1
  82. package/vendor/cli/vendor/client/model-sync.js +1 -1
  83. package/vendor/cli/vendor/client/naming.js +1 -1
  84. package/vendor/cli/vendor/client/platform.js +1 -1
  85. package/vendor/cli/vendor/client/prefs.js +1 -1
  86. package/vendor/cli/vendor/client/presence.js +1 -1
  87. package/vendor/cli/vendor/client/record-vault.js +2 -2
  88. package/vendor/cli/vendor/client/session-search.js +1 -1
  89. package/vendor/cli/vendor/client/session-store.js +1 -1
  90. package/vendor/cli/vendor/client/skills.js +1 -1
  91. package/vendor/cli/vendor/client/topup.js +1 -1
  92. package/vendor/cli/vendor/client/touch.js +1 -1
  93. package/vendor/cli/vendor/client/update.js +1 -1
  94. package/vendor/cli/vendor/client/user-models.js +1 -1
  95. package/vendor/cli/vendor/desktop/lib/local/attachments.js +1 -1
  96. package/vendor/cli/vendor/desktop/lib/local/autonomous.js +1 -1
  97. package/vendor/cli/vendor/desktop/lib/local/claude-pro.js +1 -1
  98. package/vendor/cli/vendor/desktop/lib/local/context.js +1 -1
  99. package/vendor/cli/vendor/desktop/lib/local/engine.js +1 -1
  100. package/vendor/cli/vendor/desktop/lib/local/entitlement.js +1 -1
  101. package/vendor/cli/vendor/desktop/lib/local/integrity.js +1 -1
  102. package/vendor/cli/vendor/desktop/lib/local/local.js +1 -1
  103. package/vendor/cli/vendor/desktop/lib/local/perm-rules.js +5 -0
  104. package/vendor/cli/vendor/desktop/lib/local/perm-store.js +5 -0
  105. package/vendor/cli/vendor/desktop/lib/local/perm-write.js +5 -0
  106. package/vendor/cli/vendor/desktop/lib/local/pro-sessions.js +3 -1
  107. package/vendor/cli/vendor/desktop/lib/local/prompt.js +1 -1
  108. package/vendor/cli/vendor/desktop/lib/local/queue.js +1 -1
  109. package/vendor/cli/vendor/desktop/lib/local/repeat-guard.js +1 -1
  110. package/vendor/cli/vendor/desktop/lib/local/session-rounds.js +1 -1
  111. package/vendor/cli/vendor/desktop/lib/local/spill.js +1 -1
  112. package/vendor/cli/vendor/desktop/lib/local/turn-guard.js +1 -1
  113. package/vendor/cli/vendor/desktop/lib/local/verify-stop.js +1 -1
  114. package/vendor/cli/vendor/desktop/lib/local/worktree-lock.js +1 -1
  115. package/vendor/cli/vendor/desktop/lib/settings.js +1 -1
  116. package/vendor/cli/vendor/desktop/renderer/usage.js +1 -1
  117. package/vendor/cli/vendor/hosts/install.js +1 -1
  118. package/vendor/cli/vendor/hosts/openai-shim.js +1 -1
  119. package/vendor/cli/vendor/hosts/spec.js +1 -1
  120. package/vendor/cli/vendor/hosts/targets.js +1 -1
  121. package/vendor/cli/vendor/mcp/admission.js +1 -1
  122. package/vendor/cli/vendor/mcp/server.js +1 -1
  123. package/vendor/cli/vendor/mcp/tools.js +1 -1
  124. package/vendor/cli/vendor/one/src/child.js +1 -1
  125. package/vendor/cli/vendor/one/src/protocol.js +1 -1
  126. package/vendor/cli/vendor/one/src/selfhost.js +1 -1
  127. package/vendor/desktop/bin/aegis.js +1 -1
  128. package/vendor/desktop/lib/auto.js +1 -1
  129. package/vendor/desktop/lib/avatar/companion.js +1 -1
  130. package/vendor/desktop/lib/avatar/cosmetics.js +1 -1
  131. package/vendor/desktop/lib/avatar/holder-turn.js +1 -1
  132. package/vendor/desktop/lib/avatar/holders.js +1 -1
  133. package/vendor/desktop/lib/avatar/identity.js +1 -1
  134. package/vendor/desktop/lib/avatar/level.js +1 -1
  135. package/vendor/desktop/lib/avatar/mirror.js +1 -1
  136. package/vendor/desktop/lib/avatar/persona.js +1 -1
  137. package/vendor/desktop/lib/avatar/profile.js +1 -1
  138. package/vendor/desktop/lib/avatar/register.js +1 -1
  139. package/vendor/desktop/lib/avatar/store.js +1 -1
  140. package/vendor/desktop/lib/avatar/transfer.js +1 -1
  141. package/vendor/desktop/lib/avatar/turn.js +1 -1
  142. package/vendor/desktop/lib/avatar/voice.js +1 -1
  143. package/vendor/desktop/lib/avatar/xp.js +1 -1
  144. package/vendor/desktop/lib/deep-link.js +1 -1
  145. package/vendor/desktop/lib/local/attachments.js +1 -1
  146. package/vendor/desktop/lib/local/autonomous.js +1 -1
  147. package/vendor/desktop/lib/local/claude-pro.js +1 -1
  148. package/vendor/desktop/lib/local/cli-face.js +1 -1
  149. package/vendor/desktop/lib/local/context.js +1 -1
  150. package/vendor/desktop/lib/local/engine.js +1 -1
  151. package/vendor/desktop/lib/local/entitlement.js +1 -1
  152. package/vendor/desktop/lib/local/integrity.js +1 -1
  153. package/vendor/desktop/lib/local/local.js +1 -1
  154. package/vendor/desktop/lib/local/perm-rules.js +5 -0
  155. package/vendor/desktop/lib/local/perm-store.js +5 -0
  156. package/vendor/desktop/lib/local/perm-write.js +5 -0
  157. package/vendor/desktop/lib/local/pro-sessions.js +3 -1
  158. package/vendor/desktop/lib/local/prompt.js +1 -1
  159. package/vendor/desktop/lib/local/pty-host.js +1 -1
  160. package/vendor/desktop/lib/local/queue.js +1 -1
  161. package/vendor/desktop/lib/local/repeat-guard.js +1 -1
  162. package/vendor/desktop/lib/local/session-rounds.js +1 -1
  163. package/vendor/desktop/lib/local/spill.js +1 -1
  164. package/vendor/desktop/lib/local/telemetry.js +1 -1
  165. package/vendor/desktop/lib/local/turn-guard.js +1 -1
  166. package/vendor/desktop/lib/local/verify-stop.js +1 -1
  167. package/vendor/desktop/lib/local/worktree-lock.js +1 -1
  168. package/vendor/desktop/lib/provider-key-mirror.js +1 -1
  169. package/vendor/desktop/lib/quick-launcher.js +1 -1
  170. package/vendor/desktop/lib/settings.js +1 -1
  171. package/vendor/desktop/lib/skills-host.js +1 -1
  172. package/vendor/desktop/lib/speech-host.js +1 -1
  173. package/vendor/desktop/lib/sync/memory-store.js +1 -1
  174. package/vendor/desktop/lib/sync/persist-gate.js +1 -1
  175. package/vendor/desktop/lib/window-state.js +1 -1
  176. package/vendor/desktop/package.json +1 -1
  177. package/vendor/desktop/preload.js +3 -1
  178. package/vendor/desktop/renderer/app.js +3 -3
  179. package/vendor/desktop/renderer/avatar/assemble.js +1 -1
  180. package/vendor/desktop/renderer/avatar/avatar.js +1 -1
  181. package/vendor/desktop/renderer/avatar/cards.js +1 -1
  182. package/vendor/desktop/renderer/avatar/hud.js +1 -1
  183. package/vendor/desktop/renderer/avatar/pane.js +1 -1
  184. package/vendor/desktop/renderer/avatar/parts.js +1 -1
  185. package/vendor/desktop/renderer/commands.js +1 -1
  186. package/vendor/desktop/renderer/companion.js +1 -1
  187. package/vendor/desktop/renderer/composer-triggers.js +1 -1
  188. package/vendor/desktop/renderer/dictation.js +1 -1
  189. package/vendor/desktop/renderer/diff.js +1 -1
  190. package/vendor/desktop/renderer/diffview.js +1 -1
  191. package/vendor/desktop/renderer/fingerprint.js +2 -2
  192. package/vendor/desktop/renderer/index.html +10 -4
  193. package/vendor/desktop/renderer/library.js +1 -1
  194. package/vendor/desktop/renderer/markdown.js +1 -1
  195. package/vendor/desktop/renderer/palette-filter.js +1 -1
  196. package/vendor/desktop/renderer/provider-toolbar.js +1 -1
  197. package/vendor/desktop/renderer/providers.js +1 -1
  198. package/vendor/desktop/renderer/pty-frame.css +35 -0
  199. package/vendor/desktop/renderer/pty-frame.html +47 -0
  200. package/vendor/desktop/renderer/pty-panel.js +1 -1
  201. package/vendor/desktop/renderer/quick.js +1 -1
  202. package/vendor/desktop/renderer/settings-skills.js +1 -1
  203. package/vendor/desktop/renderer/shortcuts.js +1 -1
  204. package/vendor/desktop/renderer/stream-policy.js +1 -1
  205. package/vendor/desktop/renderer/style.css +22 -0
  206. package/vendor/desktop/renderer/transcript-view.js +1 -1
  207. package/vendor/desktop/renderer/usage.js +1 -1
  208. package/vendor/desktop/renderer/welcome-rows.js +1 -1
  209. package/vendor/desktop/vendor/aegis.js +1 -1
  210. package/vendor/desktop/vendor/attest.js +1 -1
  211. package/vendor/desktop/vendor/authorship-key.js +1 -1
  212. package/vendor/desktop/vendor/auto-provision.js +1 -1
  213. package/vendor/desktop/vendor/brain-catalog.js +1 -1
  214. package/vendor/desktop/vendor/byok-catalog.js +1 -1
  215. package/vendor/desktop/vendor/catalog-client.js +1 -1
  216. package/vendor/desktop/vendor/conversation-export.js +1 -1
  217. package/vendor/desktop/vendor/credentials.js +1 -1
  218. package/vendor/desktop/vendor/credits.js +1 -1
  219. package/vendor/desktop/vendor/drive-connect.js +1 -1
  220. package/vendor/desktop/vendor/env-file.js +1 -1
  221. package/vendor/desktop/vendor/faces/cli/bin/aegiscode.js +2 -2
  222. package/vendor/desktop/vendor/faces/cli/package.json +1 -1
  223. package/vendor/desktop/vendor/faces/cli/scripts/check.mjs +1 -1
  224. package/vendor/desktop/vendor/faces/cli/scripts/demo.mjs +1 -1
  225. package/vendor/desktop/vendor/faces/cli/scripts/postinstall.mjs +1 -1
  226. package/vendor/desktop/vendor/faces/cli/scripts/predist.mjs +1 -1
  227. package/vendor/desktop/vendor/faces/cli/scripts/runtests.mjs +1 -1
  228. package/vendor/desktop/vendor/faces/cli/src/app.js +1 -1
  229. package/vendor/desktop/vendor/faces/cli/src/art.js +1 -1
  230. package/vendor/desktop/vendor/faces/cli/src/autonomous.js +1 -1
  231. package/vendor/desktop/vendor/faces/cli/src/caps.js +1 -1
  232. package/vendor/desktop/vendor/faces/cli/src/chatflow.js +1 -1
  233. package/vendor/desktop/vendor/faces/cli/src/checkpoint.js +1 -1
  234. package/vendor/desktop/vendor/faces/cli/src/clipboard.js +1 -1
  235. package/vendor/desktop/vendor/faces/cli/src/cloudsync.js +1 -1
  236. package/vendor/desktop/vendor/faces/cli/src/commands.js +2 -2
  237. package/vendor/desktop/vendor/faces/cli/src/config.js +1 -1
  238. package/vendor/desktop/vendor/faces/cli/src/connect.js +1 -1
  239. package/vendor/desktop/vendor/faces/cli/src/devrun.js +1 -1
  240. package/vendor/desktop/vendor/faces/cli/src/diff.js +1 -1
  241. package/vendor/desktop/vendor/faces/cli/src/diffview.js +1 -1
  242. package/vendor/desktop/vendor/faces/cli/src/dream.js +1 -1
  243. package/vendor/desktop/vendor/faces/cli/src/engine.js +1 -1
  244. package/vendor/desktop/vendor/faces/cli/src/events.js +1 -1
  245. package/vendor/desktop/vendor/faces/cli/src/export.js +1 -1
  246. package/vendor/desktop/vendor/faces/cli/src/fingerprint.js +1 -1
  247. package/vendor/desktop/vendor/faces/cli/src/format.js +1 -1
  248. package/vendor/desktop/vendor/faces/cli/src/fuzzy.js +1 -1
  249. package/vendor/desktop/vendor/faces/cli/src/history.js +1 -1
  250. package/vendor/desktop/vendor/faces/cli/src/init.js +1 -1
  251. package/vendor/desktop/vendor/faces/cli/src/limits.js +1 -1
  252. package/vendor/desktop/vendor/faces/cli/src/markdown.js +1 -1
  253. package/vendor/desktop/vendor/faces/cli/src/mcp.js +1 -1
  254. package/vendor/desktop/vendor/faces/cli/src/models.js +1 -1
  255. package/vendor/desktop/vendor/faces/cli/src/overlays.js +1 -1
  256. package/vendor/desktop/vendor/faces/cli/src/panels.js +1 -1
  257. package/vendor/desktop/vendor/faces/cli/src/permissions.js +1 -1
  258. package/vendor/desktop/vendor/faces/cli/src/ping.js +1 -1
  259. package/vendor/desktop/vendor/faces/cli/src/presence.js +1 -1
  260. package/vendor/desktop/vendor/faces/cli/src/provenance.js +1 -1
  261. package/vendor/desktop/vendor/faces/cli/src/render.js +1 -1
  262. package/vendor/desktop/vendor/faces/cli/src/screen.js +1 -1
  263. package/vendor/desktop/vendor/faces/cli/src/screens.js +1 -1
  264. package/vendor/desktop/vendor/faces/cli/src/secret.js +1 -1
  265. package/vendor/desktop/vendor/faces/cli/src/securefs.js +1 -1
  266. package/vendor/desktop/vendor/faces/cli/src/settings.js +1 -1
  267. package/vendor/desktop/vendor/faces/cli/src/signup.js +1 -1
  268. package/vendor/desktop/vendor/faces/cli/src/summarize.js +1 -1
  269. package/vendor/desktop/vendor/faces/cli/src/sysdiag.js +1 -1
  270. package/vendor/desktop/vendor/faces/cli/src/theme.js +1 -1
  271. package/vendor/desktop/vendor/faces/cli/src/title.js +1 -1
  272. package/vendor/desktop/vendor/faces/cli/src/todos.js +1 -1
  273. package/vendor/desktop/vendor/faces/cli/src/tokens.js +1 -1
  274. package/vendor/desktop/vendor/faces/cli/src/topup.js +1 -1
  275. package/vendor/desktop/vendor/faces/cli/src/update.js +1 -1
  276. package/vendor/desktop/vendor/faces/cli/vendor/client/aegis.js +1 -1
  277. package/vendor/desktop/vendor/faces/cli/vendor/client/attest.js +1 -1
  278. package/vendor/desktop/vendor/faces/cli/vendor/client/authorship-key.js +1 -1
  279. package/vendor/desktop/vendor/faces/cli/vendor/client/auto-provision.js +1 -1
  280. package/vendor/desktop/vendor/faces/cli/vendor/client/brain-catalog.js +1 -1
  281. package/vendor/desktop/vendor/faces/cli/vendor/client/byok-catalog.js +1 -1
  282. package/vendor/desktop/vendor/faces/cli/vendor/client/catalog-client.js +1 -1
  283. package/vendor/desktop/vendor/faces/cli/vendor/client/conversation-export.js +1 -1
  284. package/vendor/desktop/vendor/faces/cli/vendor/client/credentials.js +1 -1
  285. package/vendor/desktop/vendor/faces/cli/vendor/client/credits.js +1 -1
  286. package/vendor/desktop/vendor/faces/cli/vendor/client/drive-connect.js +1 -1
  287. package/vendor/desktop/vendor/faces/cli/vendor/client/env-file.js +1 -1
  288. package/vendor/desktop/vendor/faces/cli/vendor/client/fingerprint.js +1 -1
  289. package/vendor/desktop/vendor/faces/cli/vendor/client/foreign-memory.js +1 -1
  290. package/vendor/desktop/vendor/faces/cli/vendor/client/foreign-sessions.js +1 -1
  291. package/vendor/desktop/vendor/faces/cli/vendor/client/google-signin.js +1 -1
  292. package/vendor/desktop/vendor/faces/cli/vendor/client/hooks.js +1 -1
  293. package/vendor/desktop/vendor/faces/cli/vendor/client/model-discovery.js +1 -1
  294. package/vendor/desktop/vendor/faces/cli/vendor/client/model-sync.js +1 -1
  295. package/vendor/desktop/vendor/faces/cli/vendor/client/naming.js +1 -1
  296. package/vendor/desktop/vendor/faces/cli/vendor/client/platform.js +1 -1
  297. package/vendor/desktop/vendor/faces/cli/vendor/client/prefs.js +1 -1
  298. package/vendor/desktop/vendor/faces/cli/vendor/client/presence.js +1 -1
  299. package/vendor/desktop/vendor/faces/cli/vendor/client/record-vault.js +2 -2
  300. package/vendor/desktop/vendor/faces/cli/vendor/client/session-search.js +1 -1
  301. package/vendor/desktop/vendor/faces/cli/vendor/client/session-store.js +1 -1
  302. package/vendor/desktop/vendor/faces/cli/vendor/client/skills.js +1 -1
  303. package/vendor/desktop/vendor/faces/cli/vendor/client/topup.js +1 -1
  304. package/vendor/desktop/vendor/faces/cli/vendor/client/touch.js +1 -1
  305. package/vendor/desktop/vendor/faces/cli/vendor/client/update.js +1 -1
  306. package/vendor/desktop/vendor/faces/cli/vendor/client/user-models.js +1 -1
  307. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/attachments.js +1 -1
  308. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/autonomous.js +1 -1
  309. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/claude-pro.js +1 -1
  310. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/context.js +1 -1
  311. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/engine.js +1 -1
  312. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/entitlement.js +1 -1
  313. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/exec-plan.js +1 -1
  314. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/integrity.js +1 -1
  315. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/local.js +1 -1
  316. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/perm-rules.js +2 -0
  317. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/perm-store.js +3 -1
  318. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/perm-write.js +2 -0
  319. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/pro-sessions.js +3 -1
  320. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/prompt.js +1 -1
  321. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/queue.js +1 -1
  322. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/repeat-guard.js +1 -1
  323. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/session-rounds.js +1 -1
  324. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/shell.js +1 -1
  325. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/spill.js +1 -1
  326. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/tools.js +1 -1
  327. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/turn-guard.js +1 -1
  328. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/verify-stop.js +1 -1
  329. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/worktree-lock.js +1 -1
  330. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/settings.js +1 -1
  331. package/vendor/desktop/vendor/faces/cli/vendor/desktop/main.js +3 -3
  332. package/vendor/desktop/vendor/faces/cli/vendor/desktop/renderer/usage.js +1 -1
  333. package/vendor/desktop/vendor/faces/cli/vendor/hosts/install.js +1 -1
  334. package/vendor/desktop/vendor/faces/cli/vendor/hosts/openai-shim.js +1 -1
  335. package/vendor/desktop/vendor/faces/cli/vendor/hosts/spec.js +1 -1
  336. package/vendor/desktop/vendor/faces/cli/vendor/hosts/targets.js +1 -1
  337. package/vendor/desktop/vendor/faces/cli/vendor/mcp/admission.js +1 -1
  338. package/vendor/desktop/vendor/faces/cli/vendor/mcp/server.js +1 -1
  339. package/vendor/desktop/vendor/faces/cli/vendor/mcp/tools.js +1 -1
  340. package/vendor/desktop/vendor/faces/cli/vendor/one/src/child.js +1 -1
  341. package/vendor/desktop/vendor/faces/cli/vendor/one/src/protocol.js +1 -1
  342. package/vendor/desktop/vendor/faces/cli/vendor/one/src/selfhost.js +1 -1
  343. package/vendor/desktop/vendor/fingerprint.js +1 -1
  344. package/vendor/desktop/vendor/foreign-memory.js +1 -1
  345. package/vendor/desktop/vendor/foreign-sessions.js +1 -1
  346. package/vendor/desktop/vendor/google-signin.js +1 -1
  347. package/vendor/desktop/vendor/hooks.js +1 -1
  348. package/vendor/desktop/vendor/model-discovery.js +1 -1
  349. package/vendor/desktop/vendor/model-sync.js +1 -1
  350. package/vendor/desktop/vendor/naming.js +1 -1
  351. package/vendor/desktop/vendor/platform.js +1 -1
  352. package/vendor/desktop/vendor/prefs.js +1 -1
  353. package/vendor/desktop/vendor/presence.js +1 -1
  354. package/vendor/desktop/vendor/protocol.js +1 -1
  355. package/vendor/desktop/vendor/record-vault.js +2 -2
  356. package/vendor/desktop/vendor/selfhost.js +1 -1
  357. package/vendor/desktop/vendor/session-search.js +1 -1
  358. package/vendor/desktop/vendor/session-store.js +1 -1
  359. package/vendor/desktop/vendor/skills.js +1 -1
  360. package/vendor/desktop/vendor/topup.js +1 -1
  361. package/vendor/desktop/vendor/touch.js +1 -1
  362. package/vendor/desktop/vendor/update.js +1 -1
  363. package/vendor/desktop/vendor/user-models.js +1 -1
@@ -1,3 +1,3 @@
1
1
  // SPDX-License-Identifier: AGPL-3.0-or-later
2
2
  // Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
3
- "use strict";const fs=require("node:fs"),path=require("node:path"),{writePrivateFile:writePrivateFile}=require("./securefs.js"),{credentials:credentials,prefs:prefs}=require("./shared.js");function aegisDir(e){return credentials.aegisHome(e)}function configPath(){return path.join(aegisDir(),"config.json")}function prefsPath(){return prefs.prefsFile({dir:aegisDir()})}function configExists(){try{return fs.existsSync(configPath())}catch{return!1}}function permissionsPath(){return path.join(aegisDir(),"permissions.json")}const DEFAULT_CONFIG={themeIndex:1,updateCheck:null,updateCheckServer:null,model:null,modelClass:"aegis",proEnabled:!1,models:null,currentModelId:null,effort:"high",vim:!1,lastCwd:""},MEMORY_PERSIST_KEY="memoryPersist",LEGACY_MEMORY_PERSIST_KEY="cloudSync",MEMORY_PERSIST_DEFAULT=!0;function memoryPersistState(e){let o=e;if(!o)try{o=loadConfig()}catch{return{enabled:MEMORY_PERSIST_DEFAULT,source:"default",explicit:!1}}return o&&"boolean"==typeof o[MEMORY_PERSIST_KEY]?{enabled:o[MEMORY_PERSIST_KEY],source:"config",explicit:!0}:o&&"boolean"==typeof o[LEGACY_MEMORY_PERSIST_KEY]?{enabled:o[LEGACY_MEMORY_PERSIST_KEY],source:"legacy",explicit:!0}:{enabled:MEMORY_PERSIST_DEFAULT,source:"default",explicit:!1}}function memoryPersistEnabled(e){return memoryPersistState(e).enabled}function setMemoryPersist(e){return updateConfig({[MEMORY_PERSIST_KEY]:!0===e,[LEGACY_MEMORY_PERSIST_KEY]:void 0})}const SHARED_KEYS=new Set(prefs.SHARED_PREF_KEYS);function pickShared(e){const o={};for(const r of Object.keys(e||{}))SHARED_KEYS.has(r)&&(o[r]=e[r]);return o}function readHostConfig(){try{const e=JSON.parse(fs.readFileSync(configPath(),"utf8"));if(e&&"object"==typeof e)return e}catch{}return{}}function readSharedPrefs(){try{return prefs.load({dir:aegisDir()})}catch{return{}}}function loadConfig(){const e=readHostConfig(),o=readSharedPrefs(),r={...DEFAULT_CONFIG,...e},s={};for(const r of SHARED_KEYS){const i=void 0!==e[r],t=void 0!==o[r];i&&t?s[r]=null===o[r]&&null!==e[r]?e[r]:o[r]:i?s[r]=e[r]:t&&(s[r]=o[r])}return{...r,...s}}const WRITE_WHEN_KNOWN=new Set(["memoryPersist","confirmMode","permissionMode","sandboxPolicy"]);function sharedView(e,o,r){const s={};for(const i of SHARED_KEYS)WRITE_WHEN_KNOWN.has(i)||(void 0!==e[i]?s[i]=e[i]:void 0!==r[i]?s[i]=r[i]:void 0!==o[i]?s[i]=o[i]:s[i]=DEFAULT_CONFIG[i]);return void 0!==e.memoryPersist?s.memoryPersist=e.memoryPersist:void 0!==r.memoryPersist?s.memoryPersist=r.memoryPersist:void 0!==o.memoryPersist?s.memoryPersist=o.memoryPersist:"boolean"==typeof o[LEGACY_MEMORY_PERSIST_KEY]&&(s.memoryPersist=o[LEGACY_MEMORY_PERSIST_KEY]),void 0!==e.confirmMode?s.confirmMode=e.confirmMode:void 0!==r.confirmMode&&(s.confirmMode=r.confirmMode),void 0!==e.permissionMode?s.permissionMode=e.permissionMode:void 0!==r.permissionMode&&(s.permissionMode=r.permissionMode),void 0!==e.sandboxPolicy?s.sandboxPolicy=e.sandboxPolicy:void 0!==r.sandboxPolicy&&(s.sandboxPolicy=r.sandboxPolicy),s}function updateConfig(e){const o=e||{},r=readHostConfig(),s=readSharedPrefs(),i=(pickShared(o),{...o});for(const e of SHARED_KEYS)delete i[e];try{prefs.set(sharedView(o,r,s),{dir:aegisDir()})}catch(e){process.env.AEGIS_HIST_DEBUG&&console.error("[prefs] write failed:",e)}const t={...DEFAULT_CONFIG,...r,...i};for(const e of SHARED_KEYS)delete t[e];try{writePrivateFile(configPath(),JSON.stringify(t,null,2)+"\n")}catch(e){process.env.AEGIS_HIST_DEBUG&&console.error("[config] write failed:",e)}return loadConfig()}const DEFAULT_PERMISSIONS={defaultMode:"ask",allow:[],deny:[],ask:[]};function loadPermissions(){try{const e=fs.readFileSync(permissionsPath(),"utf8"),o=JSON.parse(e);if(o&&"object"==typeof o)return{...DEFAULT_PERMISSIONS,allow:Array.isArray(o.allow)?o.allow:[],deny:Array.isArray(o.deny)?o.deny:[],ask:Array.isArray(o.ask)?o.ask:[],defaultMode:o.defaultMode||DEFAULT_PERMISSIONS.defaultMode,explicitAsk:"ask"===o.defaultMode}}catch{}return{...DEFAULT_PERMISSIONS,allow:[],deny:[],ask:[],explicitAsk:!1}}function savePermissions(e){try{writePrivateFile(permissionsPath(),JSON.stringify(e,null,2)+"\n")}catch(e){process.env.AEGIS_HIST_DEBUG&&console.error("[permissions] write failed:",e)}return e}function saveRuleMode(e){const{explicitAsk:o,...r}=loadPermissions();return savePermissions({...r,defaultMode:e})}function addPermissionRule(e,o,r){const s="allow"===e||"deny"===e||"ask"===e?e:"allow",i=r[s];return i.includes(o)?{added:!1,rules:r}:{added:!0,rules:{...r,[s]:[...i,o]}}}function removePermissionRule(e,o,r){const s="allow"===e||"deny"===e||"ask"===e?e:"allow",i=r[s].filter((e=>e!==o));return{removed:i.length!==r[s].length,rules:{...r,[s]:i}}}function confirmPosture(){try{const e=readSharedPrefs().confirmMode;if("boolean"==typeof e)return{enabled:e,source:"shared"}}catch{}try{const e=JSON.parse(fs.readFileSync(permissionsPath(),"utf8"));if(e&&"object"==typeof e&&"string"==typeof e.defaultMode)return{enabled:"allow"!==e.defaultMode,source:"rules"}}catch{}return{enabled:!0,source:"default"}}function setConfirmPosture(e){const o=Boolean(e);try{prefs.set({confirmMode:o},{dir:aegisDir()})}catch(e){process.env.AEGIS_HIST_DEBUG&&console.error("[prefs] write failed:",e)}return saveRuleMode(o?"ask":"allow"),o}function getModelAutoSync(){try{const e=prefs.load({dir:aegisDir()}).modelAutoSync;return"boolean"==typeof e?e:e&&"object"==typeof e&&"boolean"==typeof e.enabled?e.enabled:null}catch{return null}}function setModelAutoSync(e){const o=Boolean(e);try{prefs.set({modelAutoSync:o},{dir:aegisDir()})}catch(e){process.env.AEGIS_HIST_DEBUG&&console.error("[prefs] write failed:",e)}return o}function setPermissionDefaultMode(e){const o="allow"===e?"allow":"deny"===e?"deny":"ask";try{prefs.set({confirmMode:"allow"!==o},{dir:aegisDir()})}catch(e){process.env.AEGIS_HIST_DEBUG&&console.error("[prefs] write failed:",e)}return saveRuleMode(o),o}const PERMISSION_MODE_ALIASES=Object.freeze({accept:"acceptEdits",default:"manual","accept-edits":"acceptEdits","bypass-permissions":"bypassPermissions","dont-ask":"dontAsk"}),PERMISSION_MODES_LOCAL=Object.freeze(["acceptEdits","auto","bypassPermissions","manual","dontAsk","plan"]);function permissionModePosture(){let e;try{e=readSharedPrefs().permissionMode}catch{return{mode:null,source:"unset"}}if("string"!=typeof e||!e)return{mode:null,source:"unset"};const o=PERMISSION_MODE_ALIASES[e]||e;return PERMISSION_MODES_LOCAL.includes(o)?{mode:o,source:"shared"}:{mode:null,source:"invalid"}}function permissionMode(){return permissionModePosture().mode}function setPermissionMode(e){if(null==e||""===e||"off"===e||"none"===e){try{prefs.remove("permissionMode",{dir:aegisDir()})}catch(e){process.env.AEGIS_HIST_DEBUG&&console.error("[prefs] write failed:",e)}return null}const o=PERMISSION_MODE_ALIASES[String(e)]||String(e);if(!PERMISSION_MODES_LOCAL.includes(o))throw new Error(`--permission-mode ${JSON.stringify(String(e))} is not one of ${PERMISSION_MODES_LOCAL.join("|")} (or 'off' to clear it)`);try{prefs.set({permissionMode:o},{dir:aegisDir()})}catch(e){process.env.AEGIS_HIST_DEBUG&&console.error("[prefs] write failed:",e)}return o}module.exports={aegisDir:aegisDir,configPath:configPath,prefsPath:prefsPath,configExists:configExists,permissionsPath:permissionsPath,DEFAULT_CONFIG:DEFAULT_CONFIG,loadConfig:loadConfig,updateConfig:updateConfig,MEMORY_PERSIST_KEY:MEMORY_PERSIST_KEY,LEGACY_MEMORY_PERSIST_KEY:LEGACY_MEMORY_PERSIST_KEY,MEMORY_PERSIST_DEFAULT:MEMORY_PERSIST_DEFAULT,memoryPersistState:memoryPersistState,memoryPersistEnabled:memoryPersistEnabled,setMemoryPersist:setMemoryPersist,DEFAULT_PERMISSIONS:DEFAULT_PERMISSIONS,loadPermissions:loadPermissions,savePermissions:savePermissions,saveRuleMode:saveRuleMode,addPermissionRule:addPermissionRule,removePermissionRule:removePermissionRule,confirmPosture:confirmPosture,setConfirmPosture:setConfirmPosture,setPermissionDefaultMode:setPermissionDefaultMode,PERMISSION_MODES_LOCAL:PERMISSION_MODES_LOCAL,permissionModePosture:permissionModePosture,permissionMode:permissionMode,setPermissionMode:setPermissionMode,getModelAutoSync:getModelAutoSync,setModelAutoSync:setModelAutoSync};
3
+ "use strict";const fs=require("node:fs"),path=require("node:path"),{writePrivateFile:writePrivateFile}=require("./securefs.js"),{credentials:credentials,prefs:prefs}=require("./shared.js");function aegisDir(e){return credentials.aegisHome(e)}function configPath(){return path.join(aegisDir(),"config.json")}function prefsPath(){return prefs.prefsFile({dir:aegisDir()})}function configExists(){try{return fs.existsSync(configPath())}catch{return!1}}function permissionsPath(){return path.join(aegisDir(),"permissions.json")}const DEFAULT_CONFIG={themeIndex:1,updateCheck:null,updateCheckServer:null,model:null,modelClass:"aegis",proEnabled:!1,models:null,currentModelId:null,effort:"high",vim:!1,lastCwd:""},MEMORY_PERSIST_KEY="memoryPersist",LEGACY_MEMORY_PERSIST_KEY="cloudSync",MEMORY_PERSIST_DEFAULT=!0;function memoryPersistState(e){let o=e;if(!o)try{o=loadConfig()}catch{return{enabled:!0,source:"default",explicit:!1}}return o&&"boolean"==typeof o.memoryPersist?{enabled:o.memoryPersist,source:"config",explicit:!0}:o&&"boolean"==typeof o.cloudSync?{enabled:o.cloudSync,source:"legacy",explicit:!0}:{enabled:!0,source:"default",explicit:!1}}function memoryPersistEnabled(e){return memoryPersistState(e).enabled}function setMemoryPersist(e){return updateConfig({[MEMORY_PERSIST_KEY]:!0===e,[LEGACY_MEMORY_PERSIST_KEY]:void 0})}const SHARED_KEYS=new Set(prefs.SHARED_PREF_KEYS);function pickShared(e){const o={};for(const r of Object.keys(e||{}))SHARED_KEYS.has(r)&&(o[r]=e[r]);return o}function readHostConfig(){try{const e=JSON.parse(fs.readFileSync(configPath(),"utf8"));if(e&&"object"==typeof e)return e}catch{}return{}}function readSharedPrefs(){try{return prefs.load({dir:aegisDir()})}catch{return{}}}function loadConfig(){const e=readHostConfig(),o=readSharedPrefs(),r={...DEFAULT_CONFIG,...e},s={};for(const r of SHARED_KEYS){const i=void 0!==e[r],n=void 0!==o[r];i&&n?s[r]=null===o[r]&&null!==e[r]?e[r]:o[r]:i?s[r]=e[r]:n&&(s[r]=o[r])}return{...r,...s}}const WRITE_WHEN_KNOWN=new Set(["memoryPersist","confirmMode","permissionMode","sandboxPolicy"]);function sharedView(e,o,r){const s={};for(const i of SHARED_KEYS)WRITE_WHEN_KNOWN.has(i)||(void 0!==e[i]?s[i]=e[i]:void 0!==r[i]?s[i]=r[i]:void 0!==o[i]?s[i]=o[i]:s[i]=DEFAULT_CONFIG[i]);return void 0!==e.memoryPersist?s.memoryPersist=e.memoryPersist:void 0!==r.memoryPersist?s.memoryPersist=r.memoryPersist:void 0!==o.memoryPersist?s.memoryPersist=o.memoryPersist:"boolean"==typeof o.cloudSync&&(s.memoryPersist=o.cloudSync),void 0!==e.confirmMode?s.confirmMode=e.confirmMode:void 0!==r.confirmMode&&(s.confirmMode=r.confirmMode),void 0!==e.permissionMode?s.permissionMode=e.permissionMode:void 0!==r.permissionMode&&(s.permissionMode=r.permissionMode),void 0!==e.sandboxPolicy?s.sandboxPolicy=e.sandboxPolicy:void 0!==r.sandboxPolicy&&(s.sandboxPolicy=r.sandboxPolicy),s}function updateConfig(e){const o=e||{},r=readHostConfig(),s=readSharedPrefs(),i=(pickShared(o),{...o});for(const e of SHARED_KEYS)delete i[e];try{prefs.set(sharedView(o,r,s),{dir:aegisDir()})}catch(e){process.env.AEGIS_HIST_DEBUG&&console.error("[prefs] write failed:",e)}const n={...DEFAULT_CONFIG,...r,...i};for(const e of SHARED_KEYS)delete n[e];try{writePrivateFile(configPath(),JSON.stringify(n,null,2)+"\n")}catch(e){process.env.AEGIS_HIST_DEBUG&&console.error("[config] write failed:",e)}return loadConfig()}const DEFAULT_PERMISSIONS={defaultMode:"ask",allow:[],deny:[],ask:[]};function loadPermissions(){try{const e=fs.readFileSync(permissionsPath(),"utf8"),o=JSON.parse(e);if(o&&"object"==typeof o)return{...DEFAULT_PERMISSIONS,allow:Array.isArray(o.allow)?o.allow:[],deny:Array.isArray(o.deny)?o.deny:[],ask:Array.isArray(o.ask)?o.ask:[],defaultMode:o.defaultMode||DEFAULT_PERMISSIONS.defaultMode,explicitAsk:"ask"===o.defaultMode}}catch{}return{...DEFAULT_PERMISSIONS,allow:[],deny:[],ask:[],explicitAsk:!1}}function savePermissions(e){try{writePrivateFile(permissionsPath(),JSON.stringify(e,null,2)+"\n")}catch(e){process.env.AEGIS_HIST_DEBUG&&console.error("[permissions] write failed:",e)}return e}function saveRuleMode(e){const{explicitAsk:o,...r}=loadPermissions();return savePermissions({...r,defaultMode:e})}function addPermissionRule(e,o,r){const s="allow"===e||"deny"===e||"ask"===e?e:"allow",i=r[s];return i.includes(o)?{added:!1,rules:r}:{added:!0,rules:{...r,[s]:[...i,o]}}}function removePermissionRule(e,o,r){const s="allow"===e||"deny"===e||"ask"===e?e:"allow",i=r[s].filter(e=>e!==o);return{removed:i.length!==r[s].length,rules:{...r,[s]:i}}}function confirmPosture(){try{const e=readSharedPrefs().confirmMode;if("boolean"==typeof e)return{enabled:e,source:"shared"}}catch{}try{const e=JSON.parse(fs.readFileSync(permissionsPath(),"utf8"));if(e&&"object"==typeof e&&"string"==typeof e.defaultMode)return{enabled:"allow"!==e.defaultMode,source:"rules"}}catch{}return{enabled:!0,source:"default"}}function setConfirmPosture(e){const o=Boolean(e);try{prefs.set({confirmMode:o},{dir:aegisDir()})}catch(e){process.env.AEGIS_HIST_DEBUG&&console.error("[prefs] write failed:",e)}return saveRuleMode(o?"ask":"allow"),o}function getModelAutoSync(){try{const e=prefs.load({dir:aegisDir()}).modelAutoSync;return"boolean"==typeof e?e:e&&"object"==typeof e&&"boolean"==typeof e.enabled?e.enabled:null}catch{return null}}function setModelAutoSync(e){const o=Boolean(e);try{prefs.set({modelAutoSync:o},{dir:aegisDir()})}catch(e){process.env.AEGIS_HIST_DEBUG&&console.error("[prefs] write failed:",e)}return o}function setPermissionDefaultMode(e){const o="allow"===e?"allow":"deny"===e?"deny":"ask";try{prefs.set({confirmMode:"allow"!==o},{dir:aegisDir()})}catch(e){process.env.AEGIS_HIST_DEBUG&&console.error("[prefs] write failed:",e)}return saveRuleMode(o),o}const PERMISSION_MODE_ALIASES=Object.freeze({accept:"acceptEdits",default:"manual","accept-edits":"acceptEdits","bypass-permissions":"bypassPermissions","dont-ask":"dontAsk"}),PERMISSION_MODES_LOCAL=Object.freeze(["acceptEdits","auto","bypassPermissions","manual","dontAsk","plan"]);function permissionModePosture(){let e;try{e=readSharedPrefs().permissionMode}catch{return{mode:null,source:"unset"}}if("string"!=typeof e||!e)return{mode:null,source:"unset"};const o=PERMISSION_MODE_ALIASES[e]||e;return PERMISSION_MODES_LOCAL.includes(o)?{mode:o,source:"shared"}:{mode:null,source:"invalid"}}function permissionMode(){return permissionModePosture().mode}function setPermissionMode(e){if(null==e||""===e||"off"===e||"none"===e){try{prefs.remove("permissionMode",{dir:aegisDir()})}catch(e){process.env.AEGIS_HIST_DEBUG&&console.error("[prefs] write failed:",e)}return null}const o=PERMISSION_MODE_ALIASES[String(e)]||String(e);if(!PERMISSION_MODES_LOCAL.includes(o))throw new Error(`--permission-mode ${JSON.stringify(String(e))} is not one of ${PERMISSION_MODES_LOCAL.join("|")} (or 'off' to clear it)`);try{prefs.set({permissionMode:o},{dir:aegisDir()})}catch(e){process.env.AEGIS_HIST_DEBUG&&console.error("[prefs] write failed:",e)}return o}module.exports={aegisDir:aegisDir,configPath:configPath,prefsPath:prefsPath,configExists:configExists,permissionsPath:permissionsPath,DEFAULT_CONFIG:DEFAULT_CONFIG,loadConfig:loadConfig,updateConfig:updateConfig,MEMORY_PERSIST_KEY:"memoryPersist",LEGACY_MEMORY_PERSIST_KEY:"cloudSync",MEMORY_PERSIST_DEFAULT:!0,memoryPersistState:memoryPersistState,memoryPersistEnabled:memoryPersistEnabled,setMemoryPersist:setMemoryPersist,DEFAULT_PERMISSIONS:DEFAULT_PERMISSIONS,loadPermissions:loadPermissions,savePermissions:savePermissions,saveRuleMode:saveRuleMode,addPermissionRule:addPermissionRule,removePermissionRule:removePermissionRule,confirmPosture:confirmPosture,setConfirmPosture:setConfirmPosture,setPermissionDefaultMode:setPermissionDefaultMode,PERMISSION_MODES_LOCAL:PERMISSION_MODES_LOCAL,permissionModePosture:permissionModePosture,permissionMode:permissionMode,setPermissionMode:setPermissionMode,getModelAutoSync:getModelAutoSync,setModelAutoSync:setModelAutoSync};
@@ -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{resolveClientModule:resolveClientModule}=require("./shared.js"),{maskKey:maskKey}=require("./format.js"),{openUrl:defaultOpenUrl}=require("./system.js");function load(){return{credentials:require(resolveClientModule("credentials.js")),autoProvision:require(resolveClientModule("auto-provision.js")),client:require(resolveClientModule("aegis.js")),vault:require(resolveClientModule("record-vault.js")),googleSignIn:require(resolveClientModule("google-signin.js")),fingerprint:require(resolveClientModule("device-fingerprint.js"))}}const HELP="aegiscode connect — sign this machine in (and register it, if it is new).\n\nUsage:\n aegiscode connect sign in with Google (default) — opens a\n browser; the key this machine saves is\n tied to that account, so the same account\n comes back on any machine signed in with it\n aegiscode connect --anonymous sign in with an anonymous per-machine key\n instead (no Google identity involved);\n registers this device if it has no account\n yet (one request, idempotent per machine —\n a machine that registered before gets the\n same account back)\n aegiscode connect --status is this machine connected? (--json; exit 1\n when it is not)\n aegiscode connect --logout forget the saved key on this machine\n aegiscode connect --help\n\nWhat it gives you, with no further setup:\n cloud memory sync, conversation sync, and the DEFAULT RECORD VAULT\n (aegiscode fingerprint publish goes to your account vault).\n\nIt writes the same key `aegiscode login` writes, so a key you already saved is\nused as-is: this never replaces a working credential.\n\nOptions:\n --status report only; changes nothing\n --anonymous, --device sign in with the anonymous per-machine key, not Google\n --google sign in with Google (the default — accepted explicitly too)\n --logout remove the saved key from this machine\n --json machine-readable output\n --app NAME the host name sent to the server (default: cli)\n --base URL API base (same as $AEGIS_API_BASE)";function flag(e,n){for(let t=0;t<e.length;t+=1){const o=String(e[t]);if(o===n&&void 0!==e[t+1]&&!String(e[t+1]).startsWith("--"))return e[t+1];if(o.startsWith(`${n}=`))return o.slice(n.length+1)}return null}function has(e,n){return(Array.isArray(e)?e:[]).some((e=>e===n||String(e).startsWith(`${n}=`)))}function storeFor(e,n){const t=e.aegisHome(n);return{dir:t,keyStatus:()=>e.keyStatus({env:n,dir:t}),clearApiKey:()=>e.clearApiKey(t),saveApiKey:n=>e.saveApiKey(n,t)}}function report(e,n,t){const o=e.keyStatus({env:t,dir:e.aegisHome(t)});let i=null;try{i=n.vaultTarget(t,[]).backend}catch{i=null}return{connected:Boolean(o.configured),source:o.source||"none",path:o.path||null,file_mode:o.fileMode||null,memory_token:Boolean(o.configured&&o.memoryToken),vault_backend:i,masked:o.configured?maskKey(o.key):null}}async function runConnect(e=[],n={}){const t={stdout:process.stdout,stderr:process.stderr,env:process.env,json:!1,...n,json:Boolean(n.json)||has(e,"--json")},o=(e,n)=>(t.json?t.stdout.write(JSON.stringify({connected:!1,error:n},null,2)+"\n"):t.stderr.write(`aegiscode: ${n}\n`),e);try{if(has(e,"--help")||has(e,"-h"))return t.stdout.write(HELP+"\n"),0;const{credentials:i,autoProvision:s,client:r,vault:a,googleSignIn:c,fingerprint:l}=load(),u=flag(e,"--base");u&&(t.env.AEGIS_API_BASE=u);const d=storeFor(i,t.env);if(has(e,"--logout")){const e=d.clearApiKey();return t.json?t.stdout.write(JSON.stringify({connected:!1,cleared:e.cleared},null,2)+"\n"):t.stdout.write(e.cleared?`aegiscode: key removed from ${e.path} — this machine is signed out\n`:"aegiscode: this machine had no saved key\n"),0}if(has(e,"--status")){const e=report(i,a,t.env);return t.json?t.stdout.write(JSON.stringify(e,null,2)+"\n"):t.stdout.write(["connected: "+(e.connected?"yes":"no"),`key: ${e.masked||"not set"}${e.file_mode?` (${e.file_mode})`:""}`,`source: ${e.source}`,`file: ${e.path||"-"}`,"memory: "+(e.memory_token?"token held (cloud sync ready)":"no token yet"),`vault: ${e.vault_backend||"unknown"} (record publishing)`,e.connected?"":"Sign in with: aegiscode connect"].filter((e=>""!==e)).join("\n")+"\n"),e.connected?0:1}const g=report(i,a,t.env);if(g.connected)return t.json?t.stdout.write(JSON.stringify({...g,already:!0},null,2)+"\n"):t.stdout.write([`already connected — ${g.masked} (${g.source})`,`vault: ${g.vault_backend}`,"","Nothing changed. Sign out first (`aegiscode connect --logout`) to switch accounts."].join("\n")+"\n"),0;if(!has(e,"--anonymous")&&!has(e,"--device")){const s=r.createClient(i.clientOptions({channel:"cli",env:t.env,dir:d.dir})),u=flag(e,"--app")||"cli";let g,h;try{g=await c.startGoogleSignIn({apiBase:s.apiBase,fingerprint:l.machineFingerprint(),app:u})}catch(e){return o(2,`could not start the local sign-in server — ${e&&e.message||e}`)}t.json||t.stdout.write("aegiscode: opening a browser to sign in with Google…\n"),(n.openUrl||defaultOpenUrl)(g.url)||t.json||t.stdout.write(`aegiscode: could not open a browser automatically — open this URL:\n ${g.url}\n`);try{h=await g.wait()}catch(e){return o(2,`google sign-in did not complete — ${e&&e.message||e}`)}const m=d.saveApiKey(h.apiKey);if(!m.ok)return o(2,m.message||`could not save the key to ${m.path}`);h.memoryToken&&i.saveMemoryToken(h.memoryToken,{},d.dir);const y=report(i,a,t.env);return t.json?(t.stdout.write(JSON.stringify({...y,registered:!0,provider:"google",username:h.username},null,2)+"\n"),0):(t.stdout.write([`connected — ${y.masked}${h.username?` (signed in as ${h.username})`:""}`,`key saved to ${y.path}`,`vault ${y.vault_backend} — \`aegiscode fingerprint publish\` lands here`,y.memory_token?"Cloud memory sync is ready on this account.":"Cloud sync takes a moment to provision; the key is already valid."].join("\n")+"\n"),0)}const h=r.createClient(i.clientOptions({channel:"cli",env:t.env,dir:d.dir})),m=await s.autoProvisionApiKey(h,d,{app:flag(e,"--app")||"cli"});if(!m.key)return o(2,`could not register this device — ${s.provisionFailureText(m)}`);const y=report(i,a,t.env),p=s.trialOutcomeNote(m);return t.json?(t.stdout.write(JSON.stringify({...y,registered:!0,trial_granted:m.trialGranted,reused_account:Boolean(m.reusedAccount),saved:Boolean(m.ok)},null,2)+"\n"),m.ok?0:2):(t.stdout.write([`${m.reusedAccount?"welcome back":"connected"} — ${y.masked}`,`registered this machine${p}`,"key "+(m.ok?`saved to ${y.path}`:"COULD NOT SAVE — re-run `aegiscode connect`"),`vault ${y.vault_backend} — \`aegiscode fingerprint publish\` lands here`,"",y.memory_token?"Cloud memory sync is ready on this account.":"Cloud sync takes a moment to provision; the key is already valid.",m.reusedAccount?"":`Fund or inspect the account: ${h.promptUrl("topup","welcome_cloud")}`].filter(Boolean).join("\n")+"\n"),m.ok?0:2)}catch(e){return o(2,e&&e.message||String(e))}}module.exports={runConnect:runConnect,HELP:HELP,report:report};
3
+ "use strict";const{resolveClientModule:resolveClientModule}=require("./shared.js"),{maskKey:maskKey}=require("./format.js"),{openUrl:defaultOpenUrl}=require("./system.js");function load(){return{credentials:require(resolveClientModule("credentials.js")),autoProvision:require(resolveClientModule("auto-provision.js")),client:require(resolveClientModule("aegis.js")),vault:require(resolveClientModule("record-vault.js")),googleSignIn:require(resolveClientModule("google-signin.js")),fingerprint:require(resolveClientModule("device-fingerprint.js"))}}const HELP="aegiscode connect — sign this machine in (and register it, if it is new).\n\nUsage:\n aegiscode connect sign in with Google (default) — opens a\n browser; the key this machine saves is\n tied to that account, so the same account\n comes back on any machine signed in with it\n aegiscode connect --anonymous sign in with an anonymous per-machine key\n instead (no Google identity involved);\n registers this device if it has no account\n yet (one request, idempotent per machine —\n a machine that registered before gets the\n same account back)\n aegiscode connect --status is this machine connected? (--json; exit 1\n when it is not)\n aegiscode connect --logout forget the saved key on this machine\n aegiscode connect --help\n\nWhat it gives you, with no further setup:\n cloud memory sync, conversation sync, and the DEFAULT RECORD VAULT\n (aegiscode fingerprint publish goes to your account vault).\n\nIt writes the same key `aegiscode login` writes, so a key you already saved is\nused as-is: this never replaces a working credential.\n\nOptions:\n --status report only; changes nothing\n --anonymous, --device sign in with the anonymous per-machine key, not Google\n --google sign in with Google (the default — accepted explicitly too)\n --logout remove the saved key from this machine\n --json machine-readable output\n --app NAME the host name sent to the server (default: cli)\n --base URL API base (same as $AEGIS_API_BASE)";function flag(e,n){for(let t=0;t<e.length;t+=1){const o=String(e[t]);if(o===n&&void 0!==e[t+1]&&!String(e[t+1]).startsWith("--"))return e[t+1];if(o.startsWith(`${n}=`))return o.slice(n.length+1)}return null}function has(e,n){return(Array.isArray(e)?e:[]).some(e=>e===n||String(e).startsWith(`${n}=`))}function storeFor(e,n){const t=e.aegisHome(n);return{dir:t,keyStatus:()=>e.keyStatus({env:n,dir:t}),clearApiKey:()=>e.clearApiKey(t),saveApiKey:n=>e.saveApiKey(n,t)}}function report(e,n,t){const o=e.keyStatus({env:t,dir:e.aegisHome(t)});let i=null;try{i=n.vaultTarget(t,[]).backend}catch{i=null}return{connected:Boolean(o.configured),source:o.source||"none",path:o.path||null,file_mode:o.fileMode||null,memory_token:Boolean(o.configured&&o.memoryToken),vault_backend:i,masked:o.configured?maskKey(o.key):null}}async function runConnect(e=[],n={}){const t={stdout:process.stdout,stderr:process.stderr,env:process.env,json:!1,...n,json:Boolean(n.json)||has(e,"--json")},o=(e,n)=>(t.json?t.stdout.write(JSON.stringify({connected:!1,error:n},null,2)+"\n"):t.stderr.write(`aegiscode: ${n}\n`),e);try{if(has(e,"--help")||has(e,"-h"))return t.stdout.write(HELP+"\n"),0;const{credentials:i,autoProvision:s,client:r,vault:a,googleSignIn:c,fingerprint:l}=load(),u=flag(e,"--base");u&&(t.env.AEGIS_API_BASE=u);const d=storeFor(i,t.env);if(has(e,"--logout")){const e=d.clearApiKey();return t.json?t.stdout.write(JSON.stringify({connected:!1,cleared:e.cleared},null,2)+"\n"):t.stdout.write(e.cleared?`aegiscode: key removed from ${e.path} — this machine is signed out\n`:"aegiscode: this machine had no saved key\n"),0}if(has(e,"--status")){const e=report(i,a,t.env);return t.json?t.stdout.write(JSON.stringify(e,null,2)+"\n"):t.stdout.write(["connected: "+(e.connected?"yes":"no"),`key: ${e.masked||"not set"}${e.file_mode?` (${e.file_mode})`:""}`,`source: ${e.source}`,`file: ${e.path||"-"}`,"memory: "+(e.memory_token?"token held (cloud sync ready)":"no token yet"),`vault: ${e.vault_backend||"unknown"} (record publishing)`,e.connected?"":"Sign in with: aegiscode connect"].filter(e=>""!==e).join("\n")+"\n"),e.connected?0:1}const g=report(i,a,t.env);if(g.connected)return t.json?t.stdout.write(JSON.stringify({...g,already:!0},null,2)+"\n"):t.stdout.write([`already connected — ${g.masked} (${g.source})`,`vault: ${g.vault_backend}`,"","Nothing changed. Sign out first (`aegiscode connect --logout`) to switch accounts."].join("\n")+"\n"),0;if(!has(e,"--anonymous")&&!has(e,"--device")){const s=r.createClient(i.clientOptions({channel:"cli",env:t.env,dir:d.dir})),u=flag(e,"--app")||"cli";let g,h;try{g=await c.startGoogleSignIn({apiBase:s.apiBase,fingerprint:l.machineFingerprint(),app:u})}catch(e){return o(2,`could not start the local sign-in server — ${e&&e.message||e}`)}t.json||t.stdout.write("aegiscode: opening a browser to sign in with Google…\n"),(n.openUrl||defaultOpenUrl)(g.url)||t.json||t.stdout.write(`aegiscode: could not open a browser automatically — open this URL:\n ${g.url}\n`);try{h=await g.wait()}catch(e){return o(2,`google sign-in did not complete — ${e&&e.message||e}`)}const m=d.saveApiKey(h.apiKey);if(!m.ok)return o(2,m.message||`could not save the key to ${m.path}`);h.memoryToken&&i.saveMemoryToken(h.memoryToken,{},d.dir);const y=report(i,a,t.env);return t.json?(t.stdout.write(JSON.stringify({...y,registered:!0,provider:"google",username:h.username},null,2)+"\n"),0):(t.stdout.write([`connected — ${y.masked}${h.username?` (signed in as ${h.username})`:""}`,`key saved to ${y.path}`,`vault ${y.vault_backend} — \`aegiscode fingerprint publish\` lands here`,y.memory_token?"Cloud memory sync is ready on this account.":"Cloud sync takes a moment to provision; the key is already valid."].join("\n")+"\n"),0)}const h=r.createClient(i.clientOptions({channel:"cli",env:t.env,dir:d.dir})),m=await s.autoProvisionApiKey(h,d,{app:flag(e,"--app")||"cli"});if(!m.key)return o(2,`could not register this device — ${s.provisionFailureText(m)}`);const y=report(i,a,t.env),p=s.trialOutcomeNote(m);return t.json?(t.stdout.write(JSON.stringify({...y,registered:!0,trial_granted:m.trialGranted,reused_account:Boolean(m.reusedAccount),saved:Boolean(m.ok)},null,2)+"\n"),m.ok?0:2):(t.stdout.write([`${m.reusedAccount?"welcome back":"connected"} — ${y.masked}`,`registered this machine${p}`,"key "+(m.ok?`saved to ${y.path}`:"COULD NOT SAVE — re-run `aegiscode connect`"),`vault ${y.vault_backend} — \`aegiscode fingerprint publish\` lands here`,"",y.memory_token?"Cloud memory sync is ready on this account.":"Cloud sync takes a moment to provision; the key is already valid.",m.reusedAccount?"":`Fund or inspect the account: ${h.promptUrl("topup","welcome_cloud")}`].filter(Boolean).join("\n")+"\n"),m.ok?0:2)}catch(e){return o(2,e&&e.message||String(e))}}module.exports={runConnect:runConnect,HELP:HELP,report:report};
@@ -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{spawn:spawn}=require("node:child_process"),fs=require("node:fs"),path=require("node:path"),{resolveClientModule:resolveClientModule}=require("./shared.js"),sharedPlatform=require(resolveClientModule("platform.js")),MAX_STREAM_LINES=40;function detectDevCommand(e=process.cwd()){const t=path.join(e,"package.json");if(fs.existsSync(t)){try{const e=JSON.parse(fs.readFileSync(t,"utf8")).scripts||{};for(const t of["dev","start","watch","serve"])if("string"==typeof e[t]&&e[t].trim())return`npm run ${t}`}catch{}return"npm start"}return fs.existsSync(path.join(e,"go.mod"))?"go run .":fs.existsSync(path.join(e,"Cargo.toml"))?"cargo run":fs.existsSync(path.join(e,"Makefile"))?"make":fs.existsSync(path.join(e,"pyproject.toml"))?"python -m <module>":null}function runDevServer(e,{onLine:t,signal:r,cwd:o,onError:n,platform:s,killOptions:i}={}){const l=spawn(e,{shell:!0,cwd:o||process.cwd(),env:process.env,detached:!0});let c="",d=!1,p=null,a=0,u=!1,f=null;const m=e=>{let r;for(c+=e;(r=c.indexOf("\n"))>=0;){const e=c.slice(0,r).replace(/\r$/,"").trimEnd();c=c.slice(r+1),e&&a++<40&&t&&t(e)}};l.stdout&&l.stdout.on("data",m),l.stderr&&l.stderr.on("data",m),c.trim()&&t&&t(c.trim());const v=s&&"object"==typeof s&&"function"==typeof s.killTree?s:sharedPlatform,h={...i||{}};"string"!=typeof s||h.platform||(h.platform=s);let y=null;const S=()=>{const e=v.killTree(l,h);return e&&e.ok||(y=e&&e.error||new Error("killTree failed without an error result"),(e=>{if("function"==typeof n)return void n(e);const r=`[run] could not stop the dev server (pid ${l.pid}): ${e&&e.message} — it may still be running`;"function"==typeof t?t(r):console.error(r)})(y)),e},g=()=>{d=!0,S()};r&&r.addEventListener("abort",g,{once:!0});const w=e=>{u||(u=!0,r&&r.removeEventListener("abort",g),f(e))},j=new Promise((e=>{f=e}));return l.on("error",(()=>w({code:p??1,stopped:d}))),l.on("close",(e=>{p=e,w({code:p,stopped:d})})),l.on("exit",(()=>setTimeout((()=>w({code:p??0,stopped:d})),1e3))),{pid:l.pid,stop:()=>{d=!0;const e=S();return setTimeout((()=>w({code:p??null,stopped:!0})),5e3),e},get killError(){return y},done:j}}module.exports={MAX_STREAM_LINES:40,detectDevCommand:detectDevCommand,runDevServer:runDevServer};
3
+ "use strict";const{spawn:spawn}=require("node:child_process"),fs=require("node:fs"),path=require("node:path"),{resolveClientModule:resolveClientModule}=require("./shared.js"),sharedPlatform=require(resolveClientModule("platform.js")),MAX_STREAM_LINES=40;function detectDevCommand(e=process.cwd()){const t=path.join(e,"package.json");if(fs.existsSync(t)){try{const e=JSON.parse(fs.readFileSync(t,"utf8")).scripts||{};for(const t of["dev","start","watch","serve"])if("string"==typeof e[t]&&e[t].trim())return`npm run ${t}`}catch{}return"npm start"}return fs.existsSync(path.join(e,"go.mod"))?"go run .":fs.existsSync(path.join(e,"Cargo.toml"))?"cargo run":fs.existsSync(path.join(e,"Makefile"))?"make":fs.existsSync(path.join(e,"pyproject.toml"))?"python -m <module>":null}function runDevServer(e,{onLine:t,signal:r,cwd:o,onError:n,platform:s,killOptions:i}={}){const l=spawn(e,{shell:!0,cwd:o||process.cwd(),env:process.env,detached:!0});let c="",d=!1,p=null,a=0,u=!1,f=null;const m=e=>{let r;for(c+=e;(r=c.indexOf("\n"))>=0;){const e=c.slice(0,r).replace(/\r$/,"").trimEnd();c=c.slice(r+1),e&&a++<40&&t&&t(e)}};l.stdout&&l.stdout.on("data",m),l.stderr&&l.stderr.on("data",m),c.trim()&&t&&t(c.trim());const v=s&&"object"==typeof s&&"function"==typeof s.killTree?s:sharedPlatform,h={...i||{}};"string"!=typeof s||h.platform||(h.platform=s);let y=null;const S=()=>{const e=v.killTree(l,h);return e&&e.ok||(y=e&&e.error||new Error("killTree failed without an error result"),(e=>{if("function"==typeof n)return void n(e);const r=`[run] could not stop the dev server (pid ${l.pid}): ${e&&e.message} — it may still be running`;"function"==typeof t?t(r):console.error(r)})(y)),e},g=()=>{d=!0,S()};r&&r.addEventListener("abort",g,{once:!0});const w=e=>{u||(u=!0,r&&r.removeEventListener("abort",g),f(e))},j=new Promise(e=>{f=e});return l.on("error",()=>w({code:p??1,stopped:d})),l.on("close",e=>{p=e,w({code:p,stopped:d})}),l.on("exit",()=>setTimeout(()=>w({code:p??0,stopped:d}),1e3)),{pid:l.pid,stop:()=>{d=!0;const e=S();return setTimeout(()=>w({code:p??null,stopped:!0}),5e3),e},get killError(){return y},done:j}}module.exports={MAX_STREAM_LINES:40,detectDevCommand:detectDevCommand,runDevServer:runDevServer};
@@ -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"),DIFF_LIMITS={fileBytes:262144,lcsCells:25e4,rows:400,context:3};function splitLines(t){const e=String(null==t?"":t).replace(/\r\n?/g,"\n");if(""===e)return[];const n=e.split("\n");return n.length&&""===n[n.length-1]&&n.pop(),n}function lineDiff(t,e){const n=splitLines(t),s=splitLines(e);let i=0;for(;i<n.length&&i<s.length&&n[i]===s[i];)i++;let r=0;for(;r<n.length-i&&r<s.length-i&&n[n.length-1-r]===s[s.length-1-r];)r++;const l=n.slice(i,n.length-r),o=s.slice(i,s.length-r),a=lcsOps(l,o),c=null===a,g=a||[...l.map((t=>({sign:"-",text:t}))),...o.map((t=>({sign:"+",text:t})))];if(!g.some((t=>" "!==t.sign)))return{rows:[],adds:0,dels:0,truncated:c};const d=DIFF_LIMITS.context,f=[];let u=1,p=1;const h=i>d?i-d:0,x=h;x>0&&f.push({sign:" ",text:"",marker:!0,note:`… ${x} unchanged line${1===x?"":"s"}`});for(let t=h;t<i;t++)f.push({sign:" ",text:n[t],no:p}),p++,u++;for(const t of g)" "===t.sign?(f.push({sign:" ",text:t.text,no:p}),p++,u++):"-"===t.sign?(f.push({sign:"-",text:t.text,no:u}),u++):(f.push({sign:"+",text:t.text,no:p}),p++);const m=s.length-r,I=Math.min(r,d);p=m+1;for(let t=0;t<I;t++)f.push({sign:" ",text:s[m+t],no:p}),p++,u++;if(r>d){const t=r-d;f.push({sign:" ",text:"",marker:!0,note:`… ${t} unchanged line${1===t?"":"s"}`})}const _=f.filter((t=>"+"===t.sign)).length,w=f.filter((t=>"-"===t.sign)).length;let y=f,F=!1;return y.length>DIFF_LIMITS.rows&&(y=y.slice(0,DIFF_LIMITS.rows),y.push({sign:" ",text:"",marker:!0,note:`… ${f.length-DIFF_LIMITS.rows} more diff lines`}),F=!0),{rows:y,adds:_,dels:w,truncated:c||F}}function lcsOps(t,e){const n=t.length,s=e.length;if(!n||!s)return[...t.map((t=>({sign:"-",text:t}))),...e.map((t=>({sign:"+",text:t})))];if(n*s>DIFF_LIMITS.lcsCells)return null;const i=s+1,r=new Int32Array((n+1)*i);for(let l=n-1;l>=0;l--)for(let n=s-1;n>=0;n--)r[l*i+n]=t[l]===e[n]?r[(l+1)*i+(n+1)]+1:Math.max(r[(l+1)*i+n],r[l*i+(n+1)]);const l=[];let o=0,a=0;for(;o<n&&a<s;)t[o]===e[a]?(l.push({sign:" ",text:t[o]}),o++,a++):r[(o+1)*i+a]>=r[o*i+(a+1)]?(l.push({sign:"-",text:t[o]}),o++):(l.push({sign:"+",text:e[a]}),a++);for(;o<n;)l.push({sign:"-",text:t[o++]});for(;a<s;)l.push({sign:"+",text:e[a++]});return l}function fileRows(t){const e=splitLines(t),n=e.slice(0,DIFF_LIMITS.rows),s=n.map(((t,e)=>({sign:" ",text:t,no:e+1}))),i=e.length-n.length;return i>0&&s.push({sign:" ",text:"",marker:!0,note:`… ${i} more lines`}),{rows:s,adds:0,dels:0,truncated:i>0}}function readCapped(t,e={}){const n=null==e.bytes?DIFF_LIMITS.fileBytes:e.bytes;try{const e=fs.statSync(t);if(!e.isFile())return{text:null,missing:!0};const s=fs.readFileSync(t,"utf8");return e.size>n?{text:s.slice(0,n),missing:!1,truncated:!0}:{text:s,missing:!1}}catch{return{text:null,missing:!0}}}function shortPath(t,e){const n=String(t||"");if(!e)return n;const s=path.relative(e,n);if(s&&!s.startsWith("..")&&!path.isAbsolute(s))return s;const i=n.split(path.sep).filter(Boolean),r=n.startsWith(path.sep)?path.sep:"";return i.length>2?r+"…"+path.sep+i.slice(-2).join(path.sep):n}function editsDiff(t,e,n){const s=n(t)||{text:null,missing:!0};if("string"==typeof s.text){let t=s.text,n=0;for(const s of e)-1!==t.indexOf(s.old_string)?t=s.replace_all?t.split(s.old_string).join(s.new_string):t.replace(s.old_string,s.new_string):n++;const i=lineDiff(s.text,t);return Object.assign({kind:"Update"},i,{misses:n,replaceAll:e.some((t=>t.replace_all))})}let i=[],r=0,l=0,o=!1;return e.forEach(((t,n)=>{const s=lineDiff(t.old_string,t.new_string);n&&i.push({sign:" ",text:"",marker:!0,note:`… edit ${n+1} of ${e.length}`}),i=i.concat(s.rows),r+=s.adds,l+=s.dels,o=o||s.truncated})),{kind:"Update",rows:i,adds:r,dels:l,truncated:o,stacked:e.length}}function editPreview(t,e,n={}){try{const s=null==n.cwd?process.cwd():n.cwd,i=n.readFile||readCapped;if(!e||"object"!=typeof e)return null;const r="string"==typeof e.file_path?e.file_path:"string"==typeof e.path?e.path:null;if(!r)return null;const l={file:r,short:shortPath(r,s)};if("Edit"===t||"editFile"===t){if("string"==typeof e.old_string&&"string"==typeof e.new_string)return Object.assign({kind:"Update"},l,lineDiff(e.old_string,e.new_string),{replaceAll:!!e.replace_all});const t=(Array.isArray(e.edits)?e.edits:[]).filter((t=>t&&"string"==typeof t.old_string&&"string"==typeof t.new_string));return t.length?Object.assign({kind:"Update"},l,editsDiff(r,t,i)):null}if("Write"===t||"writeFile"===t){if("string"!=typeof e.content)return null;const t=i(r)||{text:null,missing:!0};let n=lineDiff(null==t.text?"":t.text,e.content);return n.rows.length||t.missing||!e.content||(n=fileRows(e.content)),Object.assign({kind:t.missing?"Create":"Write"},l,n,{truncated:n.truncated||!!t.truncated})}if("MultiEdit"===t){const t=(Array.isArray(e.edits)?e.edits:[]).filter((t=>t&&"string"==typeof t.old_string&&"string"==typeof t.new_string));return t.length?Object.assign({kind:"Update"},l,editsDiff(r,t,i)):null}return null}catch{return null}}function changeSummary(t){const e=[];return t.adds&&e.push(`Added ${t.adds} line${1===t.adds?"":"s"}`),t.dels&&e.push(`removed ${t.dels} line${1===t.dels?"":"s"}`),e.length?e.join(", "):"no line changes"}module.exports={DIFF_LIMITS:DIFF_LIMITS,splitLines:splitLines,lineDiff:lineDiff,readCapped:readCapped,shortPath:shortPath,changeSummary:changeSummary,editPreview:editPreview};
3
+ "use strict";const fs=require("node:fs"),path=require("node:path"),DIFF_LIMITS={fileBytes:262144,lcsCells:25e4,rows:400,context:3};function splitLines(t){const e=String(null==t?"":t).replace(/\r\n?/g,"\n");if(""===e)return[];const n=e.split("\n");return n.length&&""===n[n.length-1]&&n.pop(),n}function lineDiff(t,e){const n=splitLines(t),s=splitLines(e);let i=0;for(;i<n.length&&i<s.length&&n[i]===s[i];)i++;let r=0;for(;r<n.length-i&&r<s.length-i&&n[n.length-1-r]===s[s.length-1-r];)r++;const l=n.slice(i,n.length-r),o=s.slice(i,s.length-r),a=lcsOps(l,o),c=null===a,g=a||[...l.map(t=>({sign:"-",text:t})),...o.map(t=>({sign:"+",text:t}))];if(!g.some(t=>" "!==t.sign))return{rows:[],adds:0,dels:0,truncated:c};const d=DIFF_LIMITS.context,f=[];let u=1,p=1;const h=i>d?i-d:0,x=h;x>0&&f.push({sign:" ",text:"",marker:!0,note:`… ${x} unchanged line${1===x?"":"s"}`});for(let t=h;t<i;t++)f.push({sign:" ",text:n[t],no:p}),p++,u++;for(const t of g)" "===t.sign?(f.push({sign:" ",text:t.text,no:p}),p++,u++):"-"===t.sign?(f.push({sign:"-",text:t.text,no:u}),u++):(f.push({sign:"+",text:t.text,no:p}),p++);const m=s.length-r,I=Math.min(r,d);p=m+1;for(let t=0;t<I;t++)f.push({sign:" ",text:s[m+t],no:p}),p++,u++;if(r>d){const t=r-d;f.push({sign:" ",text:"",marker:!0,note:`… ${t} unchanged line${1===t?"":"s"}`})}const _=f.filter(t=>"+"===t.sign).length,w=f.filter(t=>"-"===t.sign).length;let y=f,F=!1;return y.length>DIFF_LIMITS.rows&&(y=y.slice(0,DIFF_LIMITS.rows),y.push({sign:" ",text:"",marker:!0,note:`… ${f.length-DIFF_LIMITS.rows} more diff lines`}),F=!0),{rows:y,adds:_,dels:w,truncated:c||F}}function lcsOps(t,e){const n=t.length,s=e.length;if(!n||!s)return[...t.map(t=>({sign:"-",text:t})),...e.map(t=>({sign:"+",text:t}))];if(n*s>DIFF_LIMITS.lcsCells)return null;const i=s+1,r=new Int32Array((n+1)*i);for(let l=n-1;l>=0;l--)for(let n=s-1;n>=0;n--)r[l*i+n]=t[l]===e[n]?r[(l+1)*i+(n+1)]+1:Math.max(r[(l+1)*i+n],r[l*i+(n+1)]);const l=[];let o=0,a=0;for(;o<n&&a<s;)t[o]===e[a]?(l.push({sign:" ",text:t[o]}),o++,a++):r[(o+1)*i+a]>=r[o*i+(a+1)]?(l.push({sign:"-",text:t[o]}),o++):(l.push({sign:"+",text:e[a]}),a++);for(;o<n;)l.push({sign:"-",text:t[o++]});for(;a<s;)l.push({sign:"+",text:e[a++]});return l}function fileRows(t){const e=splitLines(t),n=e.slice(0,DIFF_LIMITS.rows),s=n.map((t,e)=>({sign:" ",text:t,no:e+1})),i=e.length-n.length;return i>0&&s.push({sign:" ",text:"",marker:!0,note:`… ${i} more lines`}),{rows:s,adds:0,dels:0,truncated:i>0}}function readCapped(t,e={}){const n=null==e.bytes?DIFF_LIMITS.fileBytes:e.bytes;try{const e=fs.statSync(t);if(!e.isFile())return{text:null,missing:!0};const s=fs.readFileSync(t,"utf8");return e.size>n?{text:s.slice(0,n),missing:!1,truncated:!0}:{text:s,missing:!1}}catch{return{text:null,missing:!0}}}function shortPath(t,e){const n=String(t||"");if(!e)return n;const s=path.relative(e,n);if(s&&!s.startsWith("..")&&!path.isAbsolute(s))return s;const i=n.split(path.sep).filter(Boolean),r=n.startsWith(path.sep)?path.sep:"";return i.length>2?r+"…"+path.sep+i.slice(-2).join(path.sep):n}function editsDiff(t,e,n){const s=n(t)||{text:null,missing:!0};if("string"==typeof s.text){let t=s.text,n=0;for(const s of e)-1!==t.indexOf(s.old_string)?t=s.replace_all?t.split(s.old_string).join(s.new_string):t.replace(s.old_string,s.new_string):n++;const i=lineDiff(s.text,t);return Object.assign({kind:"Update"},i,{misses:n,replaceAll:e.some(t=>t.replace_all)})}let i=[],r=0,l=0,o=!1;return e.forEach((t,n)=>{const s=lineDiff(t.old_string,t.new_string);n&&i.push({sign:" ",text:"",marker:!0,note:`… edit ${n+1} of ${e.length}`}),i=i.concat(s.rows),r+=s.adds,l+=s.dels,o=o||s.truncated}),{kind:"Update",rows:i,adds:r,dels:l,truncated:o,stacked:e.length}}function editPreview(t,e,n={}){try{const s=null==n.cwd?process.cwd():n.cwd,i=n.readFile||readCapped;if(!e||"object"!=typeof e)return null;const r="string"==typeof e.file_path?e.file_path:"string"==typeof e.path?e.path:null;if(!r)return null;const l={file:r,short:shortPath(r,s)};if("Edit"===t||"editFile"===t){if("string"==typeof e.old_string&&"string"==typeof e.new_string)return Object.assign({kind:"Update"},l,lineDiff(e.old_string,e.new_string),{replaceAll:!!e.replace_all});const t=(Array.isArray(e.edits)?e.edits:[]).filter(t=>t&&"string"==typeof t.old_string&&"string"==typeof t.new_string);return t.length?Object.assign({kind:"Update"},l,editsDiff(r,t,i)):null}if("Write"===t||"writeFile"===t){if("string"!=typeof e.content)return null;const t=i(r)||{text:null,missing:!0};let n=lineDiff(null==t.text?"":t.text,e.content);return n.rows.length||t.missing||!e.content||(n=fileRows(e.content)),Object.assign({kind:t.missing?"Create":"Write"},l,n,{truncated:n.truncated||!!t.truncated})}if("MultiEdit"===t){const t=(Array.isArray(e.edits)?e.edits:[]).filter(t=>t&&"string"==typeof t.old_string&&"string"==typeof t.new_string);return t.length?Object.assign({kind:"Update"},l,editsDiff(r,t,i)):null}return null}catch{return null}}function changeSummary(t){const e=[];return t.adds&&e.push(`Added ${t.adds} line${1===t.adds?"":"s"}`),t.dels&&e.push(`removed ${t.dels} line${1===t.dels?"":"s"}`),e.length?e.join(", "):"no line changes"}module.exports={DIFF_LIMITS:DIFF_LIMITS,splitLines:splitLines,lineDiff:lineDiff,readCapped:readCapped,shortPath:shortPath,changeSummary:changeSummary,editPreview:editPreview};
@@ -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{DIM:DIM,RESET:RESET,GLYPH:GLYPH,themeOf:themeOf,diffOf:diffOf}=require("./theme.js"),{w:w,clip:clip}=require("./screen.js"),AUTO_OPEN_ROWS=30,MAX_BLOCK_ROWS=200,INDENT=" ",KEYWORDS=new Set(["const","let","var","function","return","if","else","for","while","do","switch","case","break","continue","import","export","from","default","class","extends","new","try","catch","finally","throw","async","await","yield","static","typeof","instanceof","in","of","delete","this","super","null","undefined","true","false","def","elif","lambda","pass","raise","with","as","not","and","or","is","None","True","False","self","fn","mut","pub","impl","struct","enum","trait","match","package","func","defer","chan","nil","echo","local","then","fi","esac"]);function highlightLine(e,n){const t=n||diffOf(null),i=[],l=String(null==e?"":e),o=/(\/\/[^\n]*|#[^\n]*|\/\*[\s\S]*?\*\/)|('(?:\\.|[^'\\])*'|"(?:\\.|[^"\\])*"|`(?:\\.|[^`\\])*`)|(0[xX][0-9a-fA-F]+|\d+(?:\.\d+)?)|([A-Za-z_$][A-Za-z0-9_$]*)/g,s=(e,n)=>{e&&i.push({t:e,c:n})};let r,d=0;for(;r=o.exec(l);){if(r.index>d&&s(l.slice(d,r.index),t.codeFg),r[1])s(r[1],t.comment);else if(r[2])s(r[2],t.str);else if(r[3])s(r[3],t.num);else{const e=r[4],n=/^\s*\(/.test(l.slice(r.index+e.length));s(e,KEYWORDS.has(e)?t.kw:n?t.fn:t.codeFg)}d=r.index+r[0].length}return d<l.length&&s(l.slice(d),t.codeFg),i}function markIntraLine(e){for(let n=0;n<e.length;n++){if("-"!==e[n].sign)continue;let t=n;for(;t<e.length&&"-"===e[t].sign;)t++;let i=t;for(;i<e.length&&"+"===e[i].sign;)i++;const l=t-n;if(l&&l===i-t)for(let i=0;i<l;i++){const l=intraLine(e[n+i].text,e[t+i].text);l&&(e[n+i].hi={start:l.delStart,end:l.delEnd,side:"del"},e[t+i].hi={start:l.addStart,end:l.addEnd,side:"add"})}n=i-1}return e}function intraLine(e,n){const t=[...String(null==e?"":e)],i=[...String(null==n?"":n)];let l=0;for(;l<t.length&&l<i.length&&t[l]===i[l];)l++;let o=0;for(;o<t.length-l&&o<i.length-l&&t[t.length-1-o]===i[i.length-1-o];)o++;return l+o<.4*(Math.max(t.length,i.length)||1)?null:{delStart:l,delEnd:t.length-o,addStart:l,addEnd:i.length-o}}function defaultOpen(e){return!(!e||!e.rows)&&e.rows.length<=30}function diffSummaryRow(e,n,t={}){const i=themeOf(n),l=diffOf(n),o=[` ${i.gray}${GLYPH.hook} ${RESET}`];if(o.push(`${i.lavender}${e.kind}(${e.short})${RESET}`),e.adds&&o.push(`${l.addFg} +${e.adds}${RESET}`),e.dels&&o.push(`${l.delFg} -${e.dels}${RESET}`),e.adds||e.dels||o.push(`${i.gray} no line changes${RESET}`),e.misses&&o.push(`${i.gold} ${e.misses} edit(s) not applied${RESET}`),e.rows&&e.rows.length){const n=t.open?"click to collapse":e.adds||e.dels?"click to view diff":"click to view file";o.push(`${DIM} · ${n}${RESET}`)}return o.join("")}function renderDiffBlock(e,n,t,i={}){const l=Math.max(8,Number(t)||80),o=diffOf(n),s=(themeOf(n),[clipRow(diffSummaryRow(e,n,{open:i.open}),l)]);if(!(i.open&&e&&e.rows&&e.rows.length))return s;const r=markIntraLine(e.rows.slice(0,200).map((e=>Object.assign({},e))));let d=1;for(const e of r)e.no&&e.no>d&&(d=e.no);const a=Math.max(2,String(d).length),c=Math.max(4,l-(5+a+3));for(const e of r){if(e.marker){s.push(clipRow(`${DIM}${INDENT}… ${null==e.note?"":e.note}${RESET}`,l));continue}const n="-"===e.sign?"del":"+"===e.sign?"add":"ctx",t="del"===n?o.delBg:"add"===n?o.addBg:"",i="del"===n?o.delHiBg:o.addHiBg,r="del"===n?o.delHiFg:o.addHiFg,d="del"===n?o.delFg:"add"===n?o.addFg:DIM,f=`${t}${o.gutter}${INDENT}${String(null==e.no?"":e.no).padStart(a)} ${RESET}`,h=`${t}${d}${" "===e.sign?" ":e.sign} ${RESET}`,u=codeRow(clip(String(null==e.text?"":e.text),c),t,i,r,o,e.hi),g=w(`${INDENT}${String(null==e.no?"":e.no).padStart(a)} `)+2+w(clip(String(null==e.text?"":e.text),c)),$=t&&g<l?`${t}${" ".repeat(l-g)}${RESET}`:"";s.push(f+h+u+$+RESET)}const f=e.rows.length-200;return f>0&&s.push(clipRow(`${DIM}${INDENT}… ${f} more diff lines${RESET}`,l)),e.truncated&&s.push(clipRow(`${DIM}${INDENT}… diff truncated (file too large to compare in full)${RESET}`,l)),s}function codeRow(e,n,t,i,l,o){const s=[];let r=0;for(const d of highlightLine(e,l)){const e=[...d.t],l=r,a=r+e.length;if(r=a,!o||a<=o.start||l>=o.end){s.push(`${n}${d.c}${d.t}`);continue}const c=Math.max(o.start,l)-l,f=Math.min(o.end,a)-l;c>0&&s.push(`${n}${d.c}${e.slice(0,c).join("")}`),f>c&&s.push(`${t}${i}${e.slice(c,f).join("")}`),f<e.length&&s.push(`${n}${d.c}${e.slice(f).join("")}`)}return s.join("")}function clipRow(e,n){return w(e)<=n?e:clipVisible(e,n)+RESET}function clipVisible(e,n){let t=0,i="",l=0;const o=String(e);for(;l<o.length;){if(""===o[l]&&"["===o[l+1]){const e=o.indexOf("m",l);if(-1===e)break;i+=o.slice(l,e+1),l=e+1;continue}const e=o.codePointAt(l),s=String.fromCodePoint(e);l+=s.length;const r=w(s);if(t+r>n)break;i+=s,t+=r}return i}module.exports={AUTO_OPEN_ROWS:30,MAX_BLOCK_ROWS:200,INDENT:INDENT,defaultOpen:defaultOpen,highlightLine:highlightLine,markIntraLine:markIntraLine,diffSummaryRow:diffSummaryRow,renderDiffBlock:renderDiffBlock};
3
+ "use strict";const{DIM:DIM,RESET:RESET,GLYPH:GLYPH,themeOf:themeOf,diffOf:diffOf}=require("./theme.js"),{w:w,clip:clip}=require("./screen.js"),AUTO_OPEN_ROWS=30,MAX_BLOCK_ROWS=200,INDENT=" ",KEYWORDS=new Set(["const","let","var","function","return","if","else","for","while","do","switch","case","break","continue","import","export","from","default","class","extends","new","try","catch","finally","throw","async","await","yield","static","typeof","instanceof","in","of","delete","this","super","null","undefined","true","false","def","elif","lambda","pass","raise","with","as","not","and","or","is","None","True","False","self","fn","mut","pub","impl","struct","enum","trait","match","package","func","defer","chan","nil","echo","local","then","fi","esac"]);function highlightLine(e,n){const t=n||diffOf(null),i=[],l=String(null==e?"":e),o=/(\/\/[^\n]*|#[^\n]*|\/\*[\s\S]*?\*\/)|('(?:\\.|[^'\\])*'|"(?:\\.|[^"\\])*"|`(?:\\.|[^`\\])*`)|(0[xX][0-9a-fA-F]+|\d+(?:\.\d+)?)|([A-Za-z_$][A-Za-z0-9_$]*)/g,s=(e,n)=>{e&&i.push({t:e,c:n})};let r,d=0;for(;r=o.exec(l);){if(r.index>d&&s(l.slice(d,r.index),t.codeFg),r[1])s(r[1],t.comment);else if(r[2])s(r[2],t.str);else if(r[3])s(r[3],t.num);else{const e=r[4],n=/^\s*\(/.test(l.slice(r.index+e.length));s(e,KEYWORDS.has(e)?t.kw:n?t.fn:t.codeFg)}d=r.index+r[0].length}return d<l.length&&s(l.slice(d),t.codeFg),i}function markIntraLine(e){for(let n=0;n<e.length;n++){if("-"!==e[n].sign)continue;let t=n;for(;t<e.length&&"-"===e[t].sign;)t++;let i=t;for(;i<e.length&&"+"===e[i].sign;)i++;const l=t-n;if(l&&l===i-t)for(let i=0;i<l;i++){const l=intraLine(e[n+i].text,e[t+i].text);l&&(e[n+i].hi={start:l.delStart,end:l.delEnd,side:"del"},e[t+i].hi={start:l.addStart,end:l.addEnd,side:"add"})}n=i-1}return e}function intraLine(e,n){const t=[...String(null==e?"":e)],i=[...String(null==n?"":n)];let l=0;for(;l<t.length&&l<i.length&&t[l]===i[l];)l++;let o=0;for(;o<t.length-l&&o<i.length-l&&t[t.length-1-o]===i[i.length-1-o];)o++;return l+o<.4*(Math.max(t.length,i.length)||1)?null:{delStart:l,delEnd:t.length-o,addStart:l,addEnd:i.length-o}}function defaultOpen(e){return!(!e||!e.rows)&&e.rows.length<=30}function diffSummaryRow(e,n,t={}){const i=themeOf(n),l=diffOf(n),o=[` ${i.gray}${GLYPH.hook} ${RESET}`];if(o.push(`${i.lavender}${e.kind}(${e.short})${RESET}`),e.adds&&o.push(`${l.addFg} +${e.adds}${RESET}`),e.dels&&o.push(`${l.delFg} -${e.dels}${RESET}`),e.adds||e.dels||o.push(`${i.gray} no line changes${RESET}`),e.misses&&o.push(`${i.gold} ${e.misses} edit(s) not applied${RESET}`),e.rows&&e.rows.length){const n=t.open?"click to collapse":e.adds||e.dels?"click to view diff":"click to view file";o.push(`${DIM} · ${n}${RESET}`)}return o.join("")}function renderDiffBlock(e,n,t,i={}){const l=Math.max(8,Number(t)||80),o=diffOf(n),s=(themeOf(n),[clipRow(diffSummaryRow(e,n,{open:i.open}),l)]);if(!(i.open&&e&&e.rows&&e.rows.length))return s;const r=markIntraLine(e.rows.slice(0,200).map(e=>Object.assign({},e)));let d=1;for(const e of r)e.no&&e.no>d&&(d=e.no);const a=Math.max(2,String(d).length),c=Math.max(4,l-(5+a+3));for(const e of r){if(e.marker){s.push(clipRow(`${DIM}${INDENT}… ${null==e.note?"":e.note}${RESET}`,l));continue}const n="-"===e.sign?"del":"+"===e.sign?"add":"ctx",t="del"===n?o.delBg:"add"===n?o.addBg:"",i="del"===n?o.delHiBg:o.addHiBg,r="del"===n?o.delHiFg:o.addHiFg,d="del"===n?o.delFg:"add"===n?o.addFg:DIM,f=`${t}${o.gutter}${INDENT}${String(null==e.no?"":e.no).padStart(a)} ${RESET}`,h=`${t}${d}${" "===e.sign?" ":e.sign} ${RESET}`,u=codeRow(clip(String(null==e.text?"":e.text),c),t,i,r,o,e.hi),g=w(`${INDENT}${String(null==e.no?"":e.no).padStart(a)} `)+2+w(clip(String(null==e.text?"":e.text),c)),$=t&&g<l?`${t}${" ".repeat(l-g)}${RESET}`:"";s.push(f+h+u+$+RESET)}const f=e.rows.length-200;return f>0&&s.push(clipRow(`${DIM}${INDENT}… ${f} more diff lines${RESET}`,l)),e.truncated&&s.push(clipRow(`${DIM}${INDENT}… diff truncated (file too large to compare in full)${RESET}`,l)),s}function codeRow(e,n,t,i,l,o){const s=[];let r=0;for(const d of highlightLine(e,l)){const e=[...d.t],l=r,a=r+e.length;if(r=a,!o||a<=o.start||l>=o.end){s.push(`${n}${d.c}${d.t}`);continue}const c=Math.max(o.start,l)-l,f=Math.min(o.end,a)-l;c>0&&s.push(`${n}${d.c}${e.slice(0,c).join("")}`),f>c&&s.push(`${t}${i}${e.slice(c,f).join("")}`),f<e.length&&s.push(`${n}${d.c}${e.slice(f).join("")}`)}return s.join("")}function clipRow(e,n){return w(e)<=n?e:clipVisible(e,n)+RESET}function clipVisible(e,n){let t=0,i="",l=0;const o=String(e);for(;l<o.length;){if(""===o[l]&&"["===o[l+1]){const e=o.indexOf("m",l);if(-1===e)break;i+=o.slice(l,e+1),l=e+1;continue}const e=o.codePointAt(l),s=String.fromCodePoint(e);l+=s.length;const r=w(s);if(t+r>n)break;i+=s,t+=r}return i}module.exports={AUTO_OPEN_ROWS:30,MAX_BLOCK_ROWS:200,INDENT:INDENT,defaultOpen:defaultOpen,highlightLine:highlightLine,markIntraLine:markIntraLine,diffSummaryRow:diffSummaryRow,renderDiffBlock:renderDiffBlock};
@@ -1,3 +1,3 @@
1
1
  // SPDX-License-Identifier: AGPL-3.0-or-later
2
2
  // Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
3
- "use strict";function normalizeSubject(e){return String(e||"").trim().toLowerCase().replace(/^(the|a|an)\s+/,"")}const FACT_PATTERNS=[/^(?:the\s+)?(.+?)\s+(?:is|was|are|were)\s+(.+)$/i,/^(.+?):\s*(.+)$/];function extractFact(e){const t=String(e||"").trim();if(!t)return null;for(const e of FACT_PATTERNS){const n=e.exec(t);if(!n)continue;const s=n[1].trim(),o=n[2].trim();if(!s||!o)continue;const i=normalizeSubject(s);if(i)return{key:i,value:o,displaySubject:s}}return null}function bodyOf(e){return String(e&&(e.body||e.content||e.text)||"").trim()}function collectFacts({notes:e,transcripts:t}){const n=[];for(const t of e||[]){const e=extractFact(bodyOf(t));e&&n.push({...e,citation:{type:"note",id:String(t&&t.id||"")},recency:Number(t&&t.updated)||0,order:n.length})}for(const e of t||[]){const t=extractFact(String(e&&e.text||""));t&&n.push({...t,citation:{type:"session",id:String(e&&e.sessionId||"")},recency:Number(e&&e.ts)||0,order:n.length})}return n}function citationLabel(e){return"session"===e.type?`session ${e.id}`:`note ${e.id}`}function slug(e){return String(e).toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,80)||"untitled"}function groupFactsIntoPages(e){const t=new Map;for(const n of e){const e=t.get(n.key);e?(e.citations.push(n.citation),n.value!==e.value&&(n.recency>e.recency?(e.supersededValues.push(e.value),e.value=n.value,e.recency=n.recency):e.supersededValues.push(n.value))):t.set(n.key,{key:n.key,title:n.displaySubject,value:n.value,recency:n.recency,citations:[n.citation],supersededValues:[]})}return[...t.values()]}function computeLinks(e){const t=e.map((e=>new Set(e.citations.map(citationLabel))));return e.map(((n,s)=>{const o=[];for(let n=0;n<e.length;n++){if(s===n)continue;let i=!1;for(const e of t[s])if(t[n].has(e)){i=!0;break}i&&o.push(e[n].title)}return{...n,links:o}}))}function renderBody(e){const t=[`${e.title} ${e.value}.`];return e.supersededValues.length&&t.push(`Superseded: ${e.supersededValues.join("; ")}`),e.links.length&&t.push(`See also: ${e.links.map((e=>`[[${e}]]`)).join(", ")}`),t.push(`Sources: ${[...new Set(e.citations.map(citationLabel))].join(", ")}`),t.join("\n")}function buildWikiPages({notes:e=[],transcripts:t=[],existingPages:n=[]}={}){const s=computeLinks(groupFactsIntoPages(collectFacts({notes:e,transcripts:t}))).map((e=>({...e,body:renderBody(e)}))),o=new Map((n||[]).map((e=>[e.key,e])));let i=0,c=0,r=0;for(const e of s){const t=o.get(e.key);t?t.body!==e.body&&(c+=1):i+=1;const n=new Set(t&&t.links||[]);r+=e.links.filter((e=>!n.has(e))).length}return{pages:s,report:{pagesCreated:i,pagesExtended:c,linksAdded:r}}}function pagesToStagedEntries(e,{now:t=Date.now()}={}){return e.map((e=>({id:`dream/wiki/${slug(e.key)}`,body:e.body,scope:"default",tags:["dream","wiki"],updated:t,source:"dream"})))}module.exports={normalizeSubject:normalizeSubject,extractFact:extractFact,collectFacts:collectFacts,groupFactsIntoPages:groupFactsIntoPages,computeLinks:computeLinks,buildWikiPages:buildWikiPages,pagesToStagedEntries:pagesToStagedEntries,slug:slug};
3
+ "use strict";function normalizeSubject(e){return String(e||"").trim().toLowerCase().replace(/^(the|a|an)\s+/,"")}const FACT_PATTERNS=[/^(?:the\s+)?(.+?)\s+(?:is|was|are|were)\s+(.+)$/i,/^(.+?):\s*(.+)$/];function extractFact(e){const t=String(e||"").trim();if(!t)return null;for(const e of FACT_PATTERNS){const n=e.exec(t);if(!n)continue;const s=n[1].trim(),o=n[2].trim();if(!s||!o)continue;const i=normalizeSubject(s);if(i)return{key:i,value:o,displaySubject:s}}return null}function bodyOf(e){return String(e&&(e.body||e.content||e.text)||"").trim()}function collectFacts({notes:e,transcripts:t}){const n=[];for(const t of e||[]){const e=extractFact(bodyOf(t));e&&n.push({...e,citation:{type:"note",id:String(t&&t.id||"")},recency:Number(t&&t.updated)||0,order:n.length})}for(const e of t||[]){const t=extractFact(String(e&&e.text||""));t&&n.push({...t,citation:{type:"session",id:String(e&&e.sessionId||"")},recency:Number(e&&e.ts)||0,order:n.length})}return n}function citationLabel(e){return"session"===e.type?`session ${e.id}`:`note ${e.id}`}function slug(e){return String(e).toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,80)||"untitled"}function groupFactsIntoPages(e){const t=new Map;for(const n of e){const e=t.get(n.key);e?(e.citations.push(n.citation),n.value!==e.value&&(n.recency>e.recency?(e.supersededValues.push(e.value),e.value=n.value,e.recency=n.recency):e.supersededValues.push(n.value))):t.set(n.key,{key:n.key,title:n.displaySubject,value:n.value,recency:n.recency,citations:[n.citation],supersededValues:[]})}return[...t.values()]}function computeLinks(e){const t=e.map(e=>new Set(e.citations.map(citationLabel)));return e.map((n,s)=>{const o=[];for(let n=0;n<e.length;n++){if(s===n)continue;let i=!1;for(const e of t[s])if(t[n].has(e)){i=!0;break}i&&o.push(e[n].title)}return{...n,links:o}})}function renderBody(e){const t=[`${e.title} ${e.value}.`];return e.supersededValues.length&&t.push(`Superseded: ${e.supersededValues.join("; ")}`),e.links.length&&t.push(`See also: ${e.links.map(e=>`[[${e}]]`).join(", ")}`),t.push(`Sources: ${[...new Set(e.citations.map(citationLabel))].join(", ")}`),t.join("\n")}function buildWikiPages({notes:e=[],transcripts:t=[],existingPages:n=[]}={}){const s=computeLinks(groupFactsIntoPages(collectFacts({notes:e,transcripts:t}))).map(e=>({...e,body:renderBody(e)})),o=new Map((n||[]).map(e=>[e.key,e]));let i=0,c=0,r=0;for(const e of s){const t=o.get(e.key);t?t.body!==e.body&&(c+=1):i+=1;const n=new Set(t&&t.links||[]);r+=e.links.filter(e=>!n.has(e)).length}return{pages:s,report:{pagesCreated:i,pagesExtended:c,linksAdded:r}}}function pagesToStagedEntries(e,{now:t=Date.now()}={}){return e.map(e=>({id:`dream/wiki/${slug(e.key)}`,body:e.body,scope:"default",tags:["dream","wiki"],updated:t,source:"dream"}))}module.exports={normalizeSubject:normalizeSubject,extractFact:extractFact,collectFacts:collectFacts,groupFactsIntoPages:groupFactsIntoPages,computeLinks:computeLinks,buildWikiPages:buildWikiPages,pagesToStagedEntries:pagesToStagedEntries,slug:slug};
@@ -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 os=require("node:os"),path=require("node:path"),{createLocalEngine:createLocalEngine,createSettingsStore:createSettingsStore,paths:sharedPaths}=require("./deps.js"),{credentials:credentials}=require("./shared.js"),VERSION=require("../package.json").version,HOST_CLASSES=Object.freeze(["aegis","byok","local","pro"]);function offeredClasses(e){return!0===e||e&&!0===e.proEnabled?HOST_CLASSES:HOST_CLASSES.filter((e=>"pro"!==e))}function proEnabled(e){return!0===e||!!e&&!0===e.proEnabled}const DEFAULT_CLASS="aegis",CLASS_LABELS=Object.freeze({aegis:"AEGIS Cloud (pooled)",byok:"Bring your own key (relayed, billed)",local:"Local model (your own machine, free)",pro:"Claude Code Pro (your own subscription)"});function createEngine({client:e,getConfirmMode:o,getPermissionMode:s,getClass:n,getProEnabled:r,settings:a}={}){const t=a||createSettingsStore({dir:credentials.aegisHome()}),i=path.join(path.dirname(sharedPaths.engine),"..",".."),l=createLocalEngine({aegis:e,settings:t,env:{platform:process.platform,arch:process.arch,homedir:os.homedir(),cwd:process.cwd(),appVersion:`aegiscode v${VERSION}`},getConfirmMode:o,getPermissionMode:s,sandbox:{policy:()=>"function"==typeof t.getSandboxPolicy?t.getSandboxPolicy():null,strict:!1,appDir:i}});function c(){return offeredClasses("function"==typeof r&&!!r())}function d(){const e="function"==typeof n?n():null;return c().includes(e)?e:"aegis"}return{chat:function(e,o){const s="function"==typeof n?n():null,r=e&&e.class,a=c(),t=a.includes(s)?s:a.includes(r)?r:"aegis";return l.chat({...e,class:t},o)},cancel:l.cancel,respondApproval:l.respondApproval,respondRoundsAsk:l.respondRoundsAsk,clearSessionApprovals:l.clearSessionApprovals,unloadLocalModels:()=>"function"==typeof l.unloadLocalModels?l.unloadLocalModels():Promise.resolve(),listClasses:async()=>{const e=c();return(await l.listClasses()).filter((o=>e.includes(o.class)))},listModels:e=>l.listModels(e||d()),userModels:()=>"function"==typeof l.userModels?l.userModels():{dir:"",file:"",map:{},invalid:[]},classLabel:e=>CLASS_LABELS[e]||CLASS_LABELS.aegis,getClass:d,offeredClasses:()=>c(),settings:t}}function byokNamespace(e){return`byok:${e}`}function effortRung(e){return"low"===e||"medium"===e||"max"===e?e:"high"}module.exports={createEngine:createEngine,HOST_CLASSES:HOST_CLASSES,DEFAULT_CLASS:"aegis",CLASS_LABELS:CLASS_LABELS,offeredClasses:offeredClasses,proEnabled:proEnabled,byokNamespace:byokNamespace,effortRung:effortRung};
3
+ "use strict";const os=require("node:os"),path=require("node:path"),{createLocalEngine:createLocalEngine,createSettingsStore:createSettingsStore,paths:sharedPaths}=require("./deps.js"),{credentials:credentials}=require("./shared.js"),VERSION=require("../package.json").version,HOST_CLASSES=Object.freeze(["aegis","byok","local","pro"]);function offeredClasses(e){return!0===e||e&&!0===e.proEnabled?HOST_CLASSES:HOST_CLASSES.filter(e=>"pro"!==e)}function proEnabled(e){return!0===e||!!e&&!0===e.proEnabled}const DEFAULT_CLASS="aegis",CLASS_LABELS=Object.freeze({aegis:"AEGIS Cloud (pooled)",byok:"Bring your own key (relayed, billed)",local:"Local model (your own machine, free)",pro:"Claude Code Pro (your own subscription)"});function createEngine({client:e,getConfirmMode:o,getPermissionMode:s,getClass:n,getProEnabled:r,settings:a}={}){const t=a||createSettingsStore({dir:credentials.aegisHome()}),i=path.join(path.dirname(sharedPaths.engine),"..",".."),l=createLocalEngine({aegis:e,settings:t,env:{platform:process.platform,arch:process.arch,homedir:os.homedir(),cwd:process.cwd(),appVersion:`aegiscode v${VERSION}`},getConfirmMode:o,getPermissionMode:s,sandbox:{policy:()=>"function"==typeof t.getSandboxPolicy?t.getSandboxPolicy():null,strict:!1,appDir:i}});function c(){return offeredClasses("function"==typeof r&&!!r())}function d(){const e="function"==typeof n?n():null;return c().includes(e)?e:"aegis"}return{chat:function(e,o){const s="function"==typeof n?n():null,r=e&&e.class,a=c(),t=a.includes(s)?s:a.includes(r)?r:"aegis";return l.chat({...e,class:t},o)},cancel:l.cancel,respondApproval:l.respondApproval,respondRoundsAsk:l.respondRoundsAsk,clearSessionApprovals:l.clearSessionApprovals,unloadLocalModels:()=>"function"==typeof l.unloadLocalModels?l.unloadLocalModels():Promise.resolve(),listClasses:async()=>{const e=c();return(await l.listClasses()).filter(o=>e.includes(o.class))},listModels:e=>l.listModels(e||d()),userModels:()=>"function"==typeof l.userModels?l.userModels():{dir:"",file:"",map:{},invalid:[]},classLabel:e=>CLASS_LABELS[e]||CLASS_LABELS.aegis,getClass:d,offeredClasses:()=>c(),settings:t}}function byokNamespace(e){return`byok:${e}`}function effortRung(e){return"low"===e||"medium"===e||"max"===e?e:"high"}module.exports={createEngine:createEngine,HOST_CLASSES:HOST_CLASSES,DEFAULT_CLASS:"aegis",CLASS_LABELS:CLASS_LABELS,offeredClasses:offeredClasses,proEnabled:proEnabled,byokNamespace:byokNamespace,effortRung:effortRung};
@@ -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{decodeEscSequence:decodeEscSequence,decodePlain:decodePlain,KEY:KEY}=require("./keys.js"),queue=[];let waiting=[],preSessionKeys=[],everAttached=!1;const STREAM_END=Symbol("aegis.streamEnd");let buffer="",seq="",escTimer=null;const PASTE_LARGE=100,PASTE_DEBOUNCE_MS=30;let pasteChunks=[],pasteTimer=null;const ESC_SEQUENCE_RE=/\x1b\[[0-9;?<]*[A-Za-z~]|\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)|\x1b[\s\S]/g,SGR_MOUSE_RE=/\x1b\[<\d+;\d+;\d+[Mm]/g,isControlOnly=e=>{const t=String(e);return!!t.includes("")&&""===t.replace(ESC_SEQUENCE_RE,"").replace(/[\u0000-\u001f\u007f]/g,"").trim()},looksLikePaste=e=>!isControlOnly(e)&&(e.length>PASTE_LARGE||/[\n\r]/.test(e.replace(/\r\n$|[\r\n]$/,"")));let attachedStdin=null,onData=null,onEnd=null,suspended=!1,streamEnded=!1,sessionStarted=!1;function isKeyStreamSuspended(){return suspended}function attachKeyStream(e){attachedStdin=e,everAttached=!0;const t=!(!e||!0!==e.readableEnded&&!0!==e.destroyed);streamEnded=t,onData=e=>pushChars(String(e));try{if("function"==typeof e.read)for(let t=0;t<64;t+=1){const t=e.read();if(null===t)break;feedKeys(String(t),{keystrokes:!0})}}catch{}"function"==typeof e.setRawMode&&e.setRawMode(!0),e.resume(),e.setEncoding("utf8"),e.on("data",onData),attachEndHandler(e)}function attachEndHandler(e){onEnd=()=>{streamEnded=!0;try{resetKeyStream()}catch{}};try{e.on("end",onEnd),e.on("close",onEnd)}catch{}}function detachEndHandler(e){if(e&&onEnd)try{e.removeListener("end",onEnd),e.removeListener("close",onEnd)}catch{}}function suspendKeyStream(){if(attachedStdin&&!suspended){suspended=!0,attachedStdin.removeListener("data",onData),detachEndHandler(attachedStdin),clearTimeout(escTimer),seq="",buffer="",clearTimeout(pasteTimer),pasteTimer=null,pasteChunks=[],drainQueue();try{attachedStdin.setRawMode(!1)}catch{}attachedStdin.pause()}}function resumeKeyStream(){if(attachedStdin&&suspended){suspended=!1;try{attachedStdin.setRawMode(!0)}catch{}attachedStdin.resume(),attachedStdin.setEncoding("utf8"),attachedStdin.on("data",onData),attachEndHandler(attachedStdin)}}function flushPaste(){const e=pasteChunks.join("");pasteChunks=[],pasteTimer=null;const t=e.replace(/\x1b\[200~/g,"").replace(/\x1b\[201~/g,"").replace(SGR_MOUSE_RE,"").replace(/\r\n/g,"\n").replace(/\r/g,"\n").trimEnd();t&&dispatch({name:"paste",text:t})}function feedKeys(e,{keystrokes:t=!1}={}){if(!e)return;const n=String(e);t&&n.length<=PASTE_LARGE&&!n.includes("[200~")?feedChars(n):pushChars(n)}function feedChars(e){for(buffer+=e;buffer.length;){const e=buffer.codePointAt(0),t=String.fromCodePoint(e),n=t.length;if(n>buffer.length)break;buffer=buffer.slice(n),feed(t)}}function pushChars(e){const t=e.match(/^\x1b\[200~(.*)\x1b\[201~$/s);return t?(pasteChunks.push(t[1]),clearTimeout(pasteTimer),void(pasteTimer=setTimeout(flushPaste,PASTE_DEBOUNCE_MS))):e.startsWith("[200~")?(pasteChunks.push(e.slice(6)),clearTimeout(pasteTimer),void(pasteTimer=setTimeout(flushPaste,PASTE_DEBOUNCE_MS))):isControlOnly(e)?void feedChars(e):pasteChunks.length||looksLikePaste(e)?(pasteChunks.push(e),clearTimeout(pasteTimer),void(pasteTimer=setTimeout(flushPaste,PASTE_DEBOUNCE_MS))):void feedChars(e)}function feed(e){if(""===e)return clearTimeout(escTimer),escTimer=setTimeout((()=>{""===seq&&dispatch({name:KEY.ESC}),seq=""}),60),void(seq="");if(""===seq)return"["===e||"O"===e?void(seq+=e):(clearTimeout(escTimer),seq="","\r"===e||"\n"===e?void dispatch({name:"shift-enter"}):void dispatch({name:"alt",ch:e}));if(seq.startsWith("[")||seq.startsWith("O")){if(seq+=e,/[A-Za-z~]/.test(e)){clearTimeout(escTimer);const e=parseSgrMouse(seq);if(e)return seq="",void dispatch("string"==typeof e?{name:"wheel",dir:e}:e);const t=decodeEscSequence(seq);seq="",t&&dispatch(t)}return}const t=decodePlain(e);t&&dispatch(t)}function parseSgrMouse(e){const t=/^\x1b\[<(\d+);(\d+);(\d+)([Mm])$/.exec(e);if(!t)return null;const n=parseInt(t[1],10),s=parseInt(t[2],10),a=parseInt(t[3],10);if(!Number.isFinite(n)||!Number.isFinite(s)||!Number.isFinite(a))return null;const r=-61&n;return 64===r?"up":65===r?"down":3==(3&n)&&"M"===t[4]?{name:"release",col:s,row:a}:0!=(3&n)?null:"m"===t[4]?{name:"release",col:s,row:a}:0!=(32&n)?{name:"drag",col:s,row:a}:{name:"click",col:s,row:a}}function dispatch(e){waiting.length?waiting.shift()(e):everAttached?queue.push(e):preSessionKeys.push(e)}function streamFinished(){return!!attachedStdin&&(!0===attachedStdin.readableEnded||!0===attachedStdin.destroyed)}function nextKey(){return queue.length?Promise.resolve(queue.shift()):preSessionKeys.length?Promise.resolve(preSessionKeys.shift()):streamEnded||streamFinished()?Promise.resolve(STREAM_END):new Promise((e=>waiting.push(e)))}function nextKeyTimeout(e){return queue.length?Promise.resolve(queue.shift()):preSessionKeys.length?Promise.resolve(preSessionKeys.shift()):new Promise((t=>{const n=setTimeout((()=>{const e=waiting.indexOf(s);-1!==e&&waiting.splice(e,1),t(null)}),e),s=e=>{clearTimeout(n),t(e===STREAM_END?null:e)};waiting.push(s)}))}function requeueKeys(e){e&&e.length&&queue.unshift(...e)}function drainQueue(){if(sessionStarted)queue.length=0;else for(;queue.length;)preSessionKeys.push(queue.shift())}function markSessionStart(){sessionStarted=!0}function isKeyStreamAttached(){return!!attachedStdin}function detachKeyStream(){if(attachedStdin&&onData){try{attachedStdin.removeListener("data",onData)}catch{}detachEndHandler(attachedStdin);try{"function"==typeof attachedStdin.setRawMode&&attachedStdin.setRawMode(!1)}catch{}}resetKeyStream()}function resetKeyStream(){clearTimeout(escTimer),clearTimeout(pasteTimer),escTimer=null,pasteTimer=null,seq="",buffer="",pasteChunks=[],drainQueue();const e=waiting;waiting=[];for(const t of e)try{t(STREAM_END)}catch{}attachedStdin=null,onData=null,onEnd=null,suspended=!1}module.exports={KEY:KEY,STREAM_END:STREAM_END,parseSgrMouse:parseSgrMouse,attachKeyStream:attachKeyStream,feedKeys:feedKeys,suspendKeyStream:suspendKeyStream,resumeKeyStream:resumeKeyStream,isKeyStreamSuspended:isKeyStreamSuspended,isKeyStreamAttached:isKeyStreamAttached,detachKeyStream:detachKeyStream,nextKey:nextKey,nextKeyTimeout:nextKeyTimeout,requeueKeys:requeueKeys,drainQueue:drainQueue,markSessionStart:markSessionStart,resetKeyStream:resetKeyStream};
3
+ "use strict";const{decodeEscSequence:decodeEscSequence,decodePlain:decodePlain,KEY:KEY}=require("./keys.js"),queue=[];let waiting=[],preSessionKeys=[],everAttached=!1;const STREAM_END=Symbol("aegis.streamEnd");let buffer="",seq="",escTimer=null;const PASTE_LARGE=100,PASTE_DEBOUNCE_MS=30;let pasteChunks=[],pasteTimer=null;const ESC_SEQUENCE_RE=/\x1b\[[0-9;?<]*[A-Za-z~]|\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)|\x1b[\s\S]/g,SGR_MOUSE_RE=/\x1b\[<\d+;\d+;\d+[Mm]/g,isControlOnly=e=>{const t=String(e);return!!t.includes("")&&""===t.replace(ESC_SEQUENCE_RE,"").replace(/[\u0000-\u001f\u007f]/g,"").trim()},looksLikePaste=e=>!isControlOnly(e)&&(e.length>100||/[\n\r]/.test(e.replace(/\r\n$|[\r\n]$/,"")));let attachedStdin=null,onData=null,onEnd=null,suspended=!1,streamEnded=!1,sessionStarted=!1;function isKeyStreamSuspended(){return suspended}function attachKeyStream(e){attachedStdin=e,everAttached=!0;const t=!(!e||!0!==e.readableEnded&&!0!==e.destroyed);streamEnded=t,onData=e=>pushChars(String(e));try{if("function"==typeof e.read)for(let t=0;t<64;t+=1){const t=e.read();if(null===t)break;feedKeys(String(t),{keystrokes:!0})}}catch{}"function"==typeof e.setRawMode&&e.setRawMode(!0),e.resume(),e.setEncoding("utf8"),e.on("data",onData),attachEndHandler(e)}function attachEndHandler(e){onEnd=()=>{streamEnded=!0;try{resetKeyStream()}catch{}};try{e.on("end",onEnd),e.on("close",onEnd)}catch{}}function detachEndHandler(e){if(e&&onEnd)try{e.removeListener("end",onEnd),e.removeListener("close",onEnd)}catch{}}function suspendKeyStream(){if(attachedStdin&&!suspended){suspended=!0,attachedStdin.removeListener("data",onData),detachEndHandler(attachedStdin),clearTimeout(escTimer),seq="",buffer="",clearTimeout(pasteTimer),pasteTimer=null,pasteChunks=[],drainQueue();try{attachedStdin.setRawMode(!1)}catch{}attachedStdin.pause()}}function resumeKeyStream(){if(attachedStdin&&suspended){suspended=!1;try{attachedStdin.setRawMode(!0)}catch{}attachedStdin.resume(),attachedStdin.setEncoding("utf8"),attachedStdin.on("data",onData),attachEndHandler(attachedStdin)}}function flushPaste(){const e=pasteChunks.join("");pasteChunks=[],pasteTimer=null;const t=e.replace(/\x1b\[200~/g,"").replace(/\x1b\[201~/g,"").replace(SGR_MOUSE_RE,"").replace(/\r\n/g,"\n").replace(/\r/g,"\n").trimEnd();t&&dispatch({name:"paste",text:t})}function feedKeys(e,{keystrokes:t=!1}={}){if(!e)return;const n=String(e);t&&n.length<=100&&!n.includes("[200~")?feedChars(n):pushChars(n)}function feedChars(e){for(buffer+=e;buffer.length;){const e=buffer.codePointAt(0),t=String.fromCodePoint(e),n=t.length;if(n>buffer.length)break;buffer=buffer.slice(n),feed(t)}}function pushChars(e){const t=e.match(/^\x1b\[200~(.*)\x1b\[201~$/s);return t?(pasteChunks.push(t[1]),clearTimeout(pasteTimer),void(pasteTimer=setTimeout(flushPaste,30))):e.startsWith("[200~")?(pasteChunks.push(e.slice(6)),clearTimeout(pasteTimer),void(pasteTimer=setTimeout(flushPaste,30))):isControlOnly(e)?void feedChars(e):pasteChunks.length||looksLikePaste(e)?(pasteChunks.push(e),clearTimeout(pasteTimer),void(pasteTimer=setTimeout(flushPaste,30))):void feedChars(e)}function feed(e){if(""===e)return clearTimeout(escTimer),escTimer=setTimeout(()=>{""===seq&&dispatch({name:KEY.ESC}),seq=""},60),void(seq="");if(""===seq)return"["===e||"O"===e?void(seq+=e):(clearTimeout(escTimer),seq="","\r"===e||"\n"===e?void dispatch({name:"shift-enter"}):void dispatch({name:"alt",ch:e}));if(seq.startsWith("[")||seq.startsWith("O")){if(seq+=e,/[A-Za-z~]/.test(e)){clearTimeout(escTimer);const e=parseSgrMouse(seq);if(e)return seq="",void dispatch("string"==typeof e?{name:"wheel",dir:e}:e);const t=decodeEscSequence(seq);seq="",t&&dispatch(t)}return}const t=decodePlain(e);t&&dispatch(t)}function parseSgrMouse(e){const t=/^\x1b\[<(\d+);(\d+);(\d+)([Mm])$/.exec(e);if(!t)return null;const n=parseInt(t[1],10),s=parseInt(t[2],10),a=parseInt(t[3],10);if(!Number.isFinite(n)||!Number.isFinite(s)||!Number.isFinite(a))return null;const r=-61&n;return 64===r?"up":65===r?"down":3&~n||"M"!==t[4]?3&n?null:"m"===t[4]?{name:"release",col:s,row:a}:32&n?{name:"drag",col:s,row:a}:{name:"click",col:s,row:a}:{name:"release",col:s,row:a}}function dispatch(e){waiting.length?waiting.shift()(e):everAttached?queue.push(e):preSessionKeys.push(e)}function streamFinished(){return!!attachedStdin&&(!0===attachedStdin.readableEnded||!0===attachedStdin.destroyed)}function nextKey(){return queue.length?Promise.resolve(queue.shift()):preSessionKeys.length?Promise.resolve(preSessionKeys.shift()):streamEnded||streamFinished()?Promise.resolve(STREAM_END):new Promise(e=>waiting.push(e))}function nextKeyTimeout(e){return queue.length?Promise.resolve(queue.shift()):preSessionKeys.length?Promise.resolve(preSessionKeys.shift()):new Promise(t=>{const n=setTimeout(()=>{const e=waiting.indexOf(s);-1!==e&&waiting.splice(e,1),t(null)},e),s=e=>{clearTimeout(n),t(e===STREAM_END?null:e)};waiting.push(s)})}function requeueKeys(e){e&&e.length&&queue.unshift(...e)}function drainQueue(){if(sessionStarted)queue.length=0;else for(;queue.length;)preSessionKeys.push(queue.shift())}function markSessionStart(){sessionStarted=!0}function isKeyStreamAttached(){return!!attachedStdin}function detachKeyStream(){if(attachedStdin&&onData){try{attachedStdin.removeListener("data",onData)}catch{}detachEndHandler(attachedStdin);try{"function"==typeof attachedStdin.setRawMode&&attachedStdin.setRawMode(!1)}catch{}}resetKeyStream()}function resetKeyStream(){clearTimeout(escTimer),clearTimeout(pasteTimer),escTimer=null,pasteTimer=null,seq="",buffer="",pasteChunks=[],drainQueue();const e=waiting;waiting=[];for(const t of e)try{t(STREAM_END)}catch{}attachedStdin=null,onData=null,onEnd=null,suspended=!1}module.exports={KEY:KEY,STREAM_END:STREAM_END,parseSgrMouse:parseSgrMouse,attachKeyStream:attachKeyStream,feedKeys:feedKeys,suspendKeyStream:suspendKeyStream,resumeKeyStream:resumeKeyStream,isKeyStreamSuspended:isKeyStreamSuspended,isKeyStreamAttached:isKeyStreamAttached,detachKeyStream:detachKeyStream,nextKey:nextKey,nextKeyTimeout:nextKeyTimeout,requeueKeys:requeueKeys,drainQueue:drainQueue,markSessionStart:markSessionStart,resetKeyStream:resetKeyStream};
@@ -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");function transcriptToMarkdown(t){const e=["# Aegiscodex session","",`> exported ${(new Date).toISOString()}`,""];for(const n of t){const t=(n.text||"").replace(/\n{3,}/g,"\n\n").trim();"user"===n.role?e.push(`## User\n\n${t||"_(empty)_"}`,""):"assistant"===n.role?e.push(`## Claude\n\n${t||"_(empty)_"}`,""):"note"===n.role&&e.push(`> ${t}`,"")}return e.join("\n")}function transcriptToJSON(t){const e=t.map((t=>({role:t.role,text:t.text||"",...t.tool?{tool:t.tool}:{}})));return JSON.stringify(e,null,2)}function writeExportFile(t,e,n=process.cwd()){const o="json"===e?"json":"md",r=`aegiscodex-export-${(new Date).toISOString().replace(/[:.]/g,"-").slice(0,19)}.${o}`,s=path.join(n,r);return fs.writeFileSync(s,t,"utf8"),s}function lastAssistantText(t,e=1){const n=t.filter((t=>"assistant"===t.role)),o=Math.max(1,Math.min(e,n.length));return n.slice(n.length-o).map((t=>t.text||"")).join("\n\n")}module.exports={transcriptToMarkdown:transcriptToMarkdown,transcriptToJSON:transcriptToJSON,writeExportFile:writeExportFile,lastAssistantText:lastAssistantText};
3
+ "use strict";const fs=require("node:fs"),path=require("node:path");function transcriptToMarkdown(t){const e=["# Aegiscodex session","",`> exported ${(new Date).toISOString()}`,""];for(const n of t){const t=(n.text||"").replace(/\n{3,}/g,"\n\n").trim();"user"===n.role?e.push(`## User\n\n${t||"_(empty)_"}`,""):"assistant"===n.role?e.push(`## Claude\n\n${t||"_(empty)_"}`,""):"note"===n.role&&e.push(`> ${t}`,"")}return e.join("\n")}function transcriptToJSON(t){const e=t.map(t=>({role:t.role,text:t.text||"",...t.tool?{tool:t.tool}:{}}));return JSON.stringify(e,null,2)}function writeExportFile(t,e,n=process.cwd()){const o="json"===e?"json":"md",r=`aegiscodex-export-${(new Date).toISOString().replace(/[:.]/g,"-").slice(0,19)}.${o}`,s=path.join(n,r);return fs.writeFileSync(s,t,"utf8"),s}function lastAssistantText(t,e=1){const n=t.filter(t=>"assistant"===t.role),o=Math.max(1,Math.min(e,n.length));return n.slice(n.length-o).map(t=>t.text||"").join("\n\n")}module.exports={transcriptToMarkdown:transcriptToMarkdown,transcriptToJSON:transcriptToJSON,writeExportFile:writeExportFile,lastAssistantText:lastAssistantText};
@@ -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"),{resolveClientModule:resolveClientModule}=require("./shared.js");function load(){return{fp:require(resolveClientModule("fingerprint.js")),authorship:require(resolveClientModule("authorship-key.js")),attest:require(resolveClientModule("attest.js")),vault:require(resolveClientModule("record-vault.js"))}}function flag(e,n,t=null){const r=e.indexOf(n);return-1===r||void 0===e[r+1]||e[r+1].startsWith("--")?t:e[r+1]}function everyFlag(e,n){const t=[];for(let r=0;r<e.length-1;r+=1)e[r]!==n||e[r+1].startsWith("--")||t.push(e[r+1]);return t}function has(e,n){return e.includes(n)}function slug(e,n=80){return String(e||"session").replace(/[^A-Za-z0-9._-]+/g,"_").replace(/^[._-]+/,"").slice(0,n)||"session"}function defaultRecordPath(e,n,t){const r=String(e.createdAt).replace(/[:.]/g,"-");return path.join(t,"fingerprints",`${slug(n)}.${r}.json`)}const HELP="aegiscode fingerprint — φ(α): a sealed record of what a session was.\n\nUsage:\n aegiscode fingerprint status [--json]\n aegiscode fingerprint keygen [--out F] [--force]\n aegiscode fingerprint mint [--history F] [--session ID] [--turns N]\n [--label L] [--account A] [--model M] [--tools a,b]\n [--code-root DIR]... [--code-file F]...\n [--code-clean | --code-dirty] [--out F] [--json]\n [--ai-secret FILE] [--ai-model M]\n aegiscode fingerprint verify <record.json> [--secret FILE] [--json]\n aegiscode fingerprint backup [--secret FILE] --to DIR [--name N]\n aegiscode fingerprint publish [<record.json>] [--remote R] [--root D]\n [--dry-run] [--no-index] [--out F] [--json]\n aegiscode fingerprint anchor <record.json> [--json]\n aegiscode fingerprint vault [--audit] [--max N] [--json]\n\nKey:\n --secret FILE also --secret-file (the engine's spelling). A private\n key, which MUST NOT be group/other readable.\n --ai-secret FILE the credential the session RAN ON — a model-provider key,\n not the authorship key. Only its 12-hex fingerprint is\n recorded as 'aiKey'; the key itself never is. Also read\n from $AEGIS_AI_SECRET. With neither, the record says\n aiKey: null rather than borrowing the sealing key.\n --ai-model M the model that answered. Defaults to whatever the session\n log recorded, else null.\n --out F where keygen writes, or where mint writes the record\n --force keygen: replace an existing key. Orphans every record\n minted under the old one, so it is never implicit.\n --public --covenant F\n key to the published covenant hash instead of a private\n key. Such a record verifies for ANY covenant holder —\n integrity, not authorship — and is labelled as such.\n\nVault:\n publish copies the SEALED BYTES to the vault, byte-identical, and\n writes the link (<record>.anchor.json) beside the local\n copy.\n\n DEFAULT BACKEND: aegiscloud — the account this machine\n already registered for (the same device key every other\n cloud feature uses, so publishing needs no second\n sign-in). Nothing to configure; if there is no key yet,\n 'aegiscode login' gives you one.\n\n --backend rclone puts the copy somewhere YOU own instead:\n --remote <name> --root <folder> (AEGIS_VAULT_REMOTE /\n AEGIS_VAULT_ROOT), e.g. --remote gdrive --root\n AEGIS-AGPL. That needs an rclone remote already\n configured; the account vault does not.\n anchor re-downloads the published copy and checks three separate\n things: present, unchanged (sha256), still attested.\n vault --audit inspects every object already in the vault for key\n material and names it. The key is never published: a\n secret in cloud storage can mint records that\n impersonate yours.\n\nThe key is read from --secret, then $AEGIS_FINGERPRINT_SECRET, then\n$AEGIS_HOME/keys/authorship.key (default ~/.aegiscode/keys/authorship.key).\nWith none of those, mint and verify refuse: a key nobody chose is a key whose\nrecords prove nothing.";function status(e,n){const{authorship:t}=load(),r=n.env||process.env,o=t.resolveKey({argv:e,env:r}),i=path.join(t.dataDir(r),"history.jsonl"),s={configured:Boolean(o.secret),key_source:o.source,key_path:o.path,key_file_mode:o.path&&!/^win/.test(process.platform)?t.modeString(511&fs.statSync(o.path).mode):null,key_fingerprint:o.secret?load().fp.keyFingerprint(o.secret):null,public_key:o.public,default_key_path:t.defaultKeyPath(r),history_path:i,history_present:fs.existsSync(i)};if(n.json)return n.stdout.write(JSON.stringify(s,null,2)+"\n"),s.configured?0:1;const a=[`key: ${s.configured?s.key_fingerprint:"not set"}`,`source: ${s.key_source||"none"}`,`file: ${s.key_path||s.default_key_path}`,`mode: ${s.key_file_mode||"n/a"}`,"public key: "+(s.public_key?"YES — anyone holding the covenant can forge these records":"no"),`history: ${s.history_path}${s.history_present?"":" (not created yet)"}`];return s.configured||a.push("","No key yet. Mint one: aegiscode fingerprint keygen"),n.stdout.write(a.join("\n")+"\n"),s.configured?0:1}function keygen(e,n){const{authorship:t}=load(),r=t.keygen({argv:e,env:n.env||process.env});return n.json?(n.stdout.write(JSON.stringify(r,null,2)+"\n"),0):(n.stdout.write([`${r.replaced?"replaced":"created"} ${r.out} (mode ${r.mode})`,`key: ${r.keyFingerprint} (derived — the key itself was not printed)`,`bytes: ${r.bytes} random (256-bit)`,"","Next: aegiscode fingerprint mint seal the last session"," aegiscode fingerprint backup --to ~/safe keep a copy of the key"].join("\n")+"\n"),0)}function mint(e,n){const{attest:t,authorship:r}=load(),o=n.env||process.env,i=everyFlag(e,"--code-root"),s=everyFlag(e,"--code-file"),a=has(e,"--code-clean"),c=has(e,"--code-dirty");if(a&&c)throw new Error("fingerprint: --code-clean and --code-dirty are exclusive");const d=i.length||s.length?t.collectCode({roots:i,files:s,skip:everyFlag(e,"--code-skip")}):[],l=t.mintSession({argv:e,env:o,aiModel:flag(e,"--ai-model")||void 0,history:flag(e,"--history")||void 0,session:flag(e,"--session")||void 0,turns:flag(e,"--turns")||void 0,label:flag(e,"--label")||void 0,account:flag(e,"--account")||void 0,model:flag(e,"--model")||void 0,tools:flag(e,"--tools")?flag(e,"--tools").split(",").map((e=>e.trim())).filter(Boolean):void 0,code:d,codeDirty:!a&&(!!c||null)}),u=flag(e,"--out")||defaultRecordPath(l.record,flag(e,"--session")||"last",r.dataDir(o));return fs.mkdirSync(path.dirname(path.resolve(u)),{recursive:!0}),fs.writeFileSync(path.resolve(u),JSON.stringify(l.record,null,2)+"\n"),n.json?(n.stdout.write(JSON.stringify({...l.record,keySource:l.keySource,out:path.resolve(u)},null,2)+"\n"),0):(n.stdout.write([`record ${path.resolve(u)}`,`identity φ_${l.record.keyFingerprint} (key: ${l.keySource}${l.public?" — PUBLIC, forgeable by any covenant holder":""})`,`behaviour ${l.record.behaviour||"none"} from ${l.record.behaviourSamples} turn(s)`,`code ${l.record.code||"none"} ${l.record.codeFiles} file(s)${null===l.record.codeDirty?" (clean/dirty unknown)":l.record.codeDirty?" (dirty tree)":" (clean tree)"}`,`ai ${l.record.aiKey||"none"}${l.record.aiKey?` (${l.aiKeySource})`:" — no AI credential nominated (--ai-secret | $AEGIS_AI_SECRET)"}`,`ai habit ${l.record.ai||"unobserved"} from ${l.record.aiSamples} reply/replies${l.record.aiModel?` on ${l.record.aiModel}`:""}`,`sealed ${l.record.attestation} (v${l.record.v}, ${l.record.algo})`,0===l.samples?"note: no turns matched — the record says so rather than signing nothing":""].filter(Boolean).join("\n")+"\n"),0)}function verify(e,n){const{fp:t,authorship:r}=load(),o=e.find((e=>!e.startsWith("-")));if(!o)throw new Error("fingerprint: verify needs a record file");let i;try{i=JSON.parse(fs.readFileSync(o,"utf8"))}catch(e){throw new Error(`fingerprint: cannot read ${o} as JSON — ${e.message}`)}const s=r.resolveKey({argv:e,env:n.env||process.env});if(!s.secret)throw new Error("fingerprint: no key to verify with — pass --secret <file>, set AEGIS_FINGERPRINT_SECRET, or run `aegiscode fingerprint keygen`");const a=t.verify(i,s.secret),c={ok:a.ok,reason:a.reason,id:a.id,credential_match:a.credentialMatch,key_source:s.source,key_fingerprint_recorded:i.keyFingerprint||null,file:path.resolve(o)};return n.json?(n.stdout.write(JSON.stringify(c,null,2)+"\n"),a.ok?0:1):(n.stdout.write(a.ok?`verified ${i.keyFingerprint} — intact, and minted by ${s.source}\nrecord ${a.id}\n`:`FAILED ${a.reason}\nkey used ${s.source}\nfingerprint recorded ${i.keyFingerprint||"(none)"}\n`),a.ok?0:1)}function backup(e,n){const{authorship:t}=load(),r=t.backup({argv:e,env:n.env||process.env});return n.json?(n.stdout.write(JSON.stringify(r,null,2)+"\n"),0):(n.stdout.write([`key copied ${r.from} -> ${r.to}`,`fingerprint ${r.keyFingerprint} (same key, confirmed by re-reading the copy)`,"restore: point --secret at the copy (or copy it back to the key path). Nothing else changes."].join("\n")+"\n"),0)}function secretOrNull(e,n,t){try{return e.resolveKey({argv:n,env:t}).secret||null}catch{return null}}function newestRecord(e){const n=path.join(e,"fingerprints");if(!fs.existsSync(n))return null;const t=fs.readdirSync(n).filter((e=>e.endsWith(".json")&&!e.endsWith(".anchor.json"))).map((e=>path.join(n,e))).map((e=>({f:e,mtime:fs.statSync(e).mtimeMs}))).sort(((e,n)=>n.mtime-e.mtime));return t.length?t[0].f:null}async function publish(e,n){const{authorship:t,vault:r}=load(),o=n.env||process.env,i=e.find((e=>!e.startsWith("-"))),s=i?path.resolve(i):newestRecord(t.dataDir(o));if(!s)throw new Error("fingerprint: no record to publish — seal one first (`aegiscode fingerprint mint`), or name the file: `aegiscode fingerprint publish <record.json>`");if(!fs.existsSync(s))throw new Error(`fingerprint: no record at ${s}`);const a=await r.publish({file:s,argv:e,env:o,dryRun:has(e,"--dry-run"),secret:secretOrNull(t,e,o)});return n.json?(n.stdout.write(JSON.stringify(a,null,2)+"\n"),0):a.dryRun?(n.stdout.write(["dry run nothing uploaded",`backend ${a.backend}`,`record ${s}`,`would go ${a.remotePath}`,...a.commands.map((e=>` ${e}`))].join("\n")+"\n"),0):(n.stdout.write([`published ${a.remotePath} (${a.backend})`,`identity φ_${a.anchor.keyFingerprint}-${a.anchor.behaviour||"unobserved"}`,`digest sha256 ${a.sha256.slice(0,16)}… (${a.bytes} bytes, byte-identical to ${s})`,`link ${a.url||"(no share link — the copy is at the path above)"}`,`anchored ${a.localAnchor}${null===a.indexLines?"":` · ledger lines ${a.indexLines}`}`,"","The key was NOT published. Only the sealed record travels; verify the copy",`any time with: aegiscode fingerprint anchor ${path.basename(s)}`].join("\n")+"\n"),0)}async function anchorCmd(e,n){const{vault:t}=load(),r=e.find((e=>!e.startsWith("-")));if(!r)throw new Error("fingerprint: anchor needs a record file (the one you published)");const o=await t.checkAnchor({file:path.resolve(r),argv:e,env:n.env||process.env});return n.json?(n.stdout.write(JSON.stringify(o,null,2)+"\n"),o.ok?0:1):o.anchor?(n.stdout.write([`record ${path.resolve(r)}`,`published ${o.anchor.path}${o.anchor.url?`\n ${o.anchor.url}`:""}`,`emitted ${o.anchor.emittedAt}`,"present "+(o.present?"yes":"NO"),"unchanged "+(o.unchanged?"yes — the copy is the bytes that were sealed":"NO — sha256 differs"),"attested "+(null===o.attested?`unknown (${o.attestationReason})`:o.attested?"yes — this key still recomputes it":`NO — ${o.attestationReason}`),"",o.ok?"ok — the vault copy is the sealed record, unchanged.":`FAILED — ${o.reason}`].join("\n")+"\n"),o.ok?0:1):(n.stdout.write(`not linked ${path.resolve(r)}\n ${o.reason}\n`),1)}async function vaultCmd(e,n){const{authorship:t,vault:r}=load(),o=n.env||process.env;if(has(e,"--audit")){const i=await r.audit({argv:e,env:o,secret:secretOrNull(t,e,o)});return n.json?(n.stdout.write(JSON.stringify(i,null,2)+"\n"),i.ok?0:1):i.error?(n.stdout.write(`vault unreachable — ${i.error}\n`),2):(n.stdout.write([`vault ${i.where} (backend ${i.backend})`,`inspected ${i.checked} of ${i.files} object(s)`,i.uninspected.length?`skipped ${i.uninspected.length} (see --json)`:"","",0===i.findings.length?"clean — no key material in the vault.":[`KEY MATERIAL IN THE VAULT — ${i.findings.length} finding(s):`,...i.findings.map((e=>` ${e.path}\n ${e.reason}`)),"","Anyone who can read that folder can mint records that look like yours.","Move it out, then rotate: aegiscode fingerprint keygen --force","(rotation orphans every record minted under the old key — publish new ones.)"].join("\n")].filter(Boolean).join("\n")+"\n"),i.ok?0:1)}const i=await r.list({argv:e,env:o});if(n.json)return n.stdout.write(JSON.stringify(i,null,2)+"\n"),0;const s=[`vault ${i.where} (${i.records.length} record(s), backend ${i.backend})`];for(const e of i.records)s.push(` ${e.name}`,` id ${e.id||"(no anchor)"} · sha256 ${e.sha256?e.sha256.slice(0,16)+"…":"(none)"}`,e.url?` ${e.url}`:"");return i.records.length||s.push(" (no records published yet — `aegiscode fingerprint publish`)"),n.stdout.write(s.filter(Boolean).join("\n")+"\n"),0}function runFingerprint(e,n=[],t={}){const r={json:!1,stdout:process.stdout,stderr:process.stderr,env:process.env,...t,json:Boolean(t.json)||n.includes("--json")},o=String(e||"status").toLowerCase();try{if("help"===o||"--help"===o||"-h"===o)return r.stdout.write(HELP+"\n"),0;switch(o){case"status":return status(n,r);case"keygen":return keygen(n,r);case"mint":return mint(n,r);case"verify":return verify(n,r);case"backup":return backup(n,r);case"publish":return asExitCode(publish(n,r),r);case"anchor":return asExitCode(anchorCmd(n,r),r);case"vault":return asExitCode(vaultCmd(n,r),r);default:return r.stderr.write(`aegiscode: unknown fingerprint subcommand "${e}"\n\n${HELP}\n`),2}}catch(e){return r.stderr.write(`aegiscode: ${e&&e.message||e}\n`),2}}function asExitCode(e,n){return e.catch((e=>(n.stderr.write(`aegiscode: ${e&&e.message||e}\n`),2)))}module.exports={runFingerprint:runFingerprint,HELP:HELP,slug:slug,defaultRecordPath:defaultRecordPath,flag:flag,everyFlag:everyFlag};
3
+ "use strict";const fs=require("node:fs"),path=require("node:path"),{resolveClientModule:resolveClientModule}=require("./shared.js");function load(){return{fp:require(resolveClientModule("fingerprint.js")),authorship:require(resolveClientModule("authorship-key.js")),attest:require(resolveClientModule("attest.js")),vault:require(resolveClientModule("record-vault.js"))}}function flag(e,n,t=null){const r=e.indexOf(n);return-1===r||void 0===e[r+1]||e[r+1].startsWith("--")?t:e[r+1]}function everyFlag(e,n){const t=[];for(let r=0;r<e.length-1;r+=1)e[r]!==n||e[r+1].startsWith("--")||t.push(e[r+1]);return t}function has(e,n){return e.includes(n)}function slug(e,n=80){return String(e||"session").replace(/[^A-Za-z0-9._-]+/g,"_").replace(/^[._-]+/,"").slice(0,n)||"session"}function defaultRecordPath(e,n,t){const r=String(e.createdAt).replace(/[:.]/g,"-");return path.join(t,"fingerprints",`${slug(n)}.${r}.json`)}const HELP="aegiscode fingerprint — φ(α): a sealed record of what a session was.\n\nUsage:\n aegiscode fingerprint status [--json]\n aegiscode fingerprint keygen [--out F] [--force]\n aegiscode fingerprint mint [--history F] [--session ID] [--turns N]\n [--label L] [--account A] [--model M] [--tools a,b]\n [--code-root DIR]... [--code-file F]...\n [--code-clean | --code-dirty] [--out F] [--json]\n [--ai-secret FILE] [--ai-model M]\n aegiscode fingerprint verify <record.json> [--secret FILE] [--json]\n aegiscode fingerprint backup [--secret FILE] --to DIR [--name N]\n aegiscode fingerprint publish [<record.json>] [--remote R] [--root D]\n [--dry-run] [--no-index] [--out F] [--json]\n aegiscode fingerprint anchor <record.json> [--json]\n aegiscode fingerprint vault [--audit] [--max N] [--json]\n\nKey:\n --secret FILE also --secret-file (the engine's spelling). A private\n key, which MUST NOT be group/other readable.\n --ai-secret FILE the credential the session RAN ON — a model-provider key,\n not the authorship key. Only its 12-hex fingerprint is\n recorded as 'aiKey'; the key itself never is. Also read\n from $AEGIS_AI_SECRET. With neither, the record says\n aiKey: null rather than borrowing the sealing key.\n --ai-model M the model that answered. Defaults to whatever the session\n log recorded, else null.\n --out F where keygen writes, or where mint writes the record\n --force keygen: replace an existing key. Orphans every record\n minted under the old one, so it is never implicit.\n --public --covenant F\n key to the published covenant hash instead of a private\n key. Such a record verifies for ANY covenant holder —\n integrity, not authorship — and is labelled as such.\n\nVault:\n publish copies the SEALED BYTES to the vault, byte-identical, and\n writes the link (<record>.anchor.json) beside the local\n copy.\n\n DEFAULT BACKEND: aegiscloud — the account this machine\n already registered for (the same device key every other\n cloud feature uses, so publishing needs no second\n sign-in). Nothing to configure; if there is no key yet,\n 'aegiscode login' gives you one.\n\n --backend rclone puts the copy somewhere YOU own instead:\n --remote <name> --root <folder> (AEGIS_VAULT_REMOTE /\n AEGIS_VAULT_ROOT), e.g. --remote gdrive --root\n AEGIS-AGPL. That needs an rclone remote already\n configured; the account vault does not.\n anchor re-downloads the published copy and checks three separate\n things: present, unchanged (sha256), still attested.\n vault --audit inspects every object already in the vault for key\n material and names it. The key is never published: a\n secret in cloud storage can mint records that\n impersonate yours.\n\nThe key is read from --secret, then $AEGIS_FINGERPRINT_SECRET, then\n$AEGIS_HOME/keys/authorship.key (default ~/.aegiscode/keys/authorship.key).\nWith none of those, mint and verify refuse: a key nobody chose is a key whose\nrecords prove nothing.";function status(e,n){const{authorship:t}=load(),r=n.env||process.env,o=t.resolveKey({argv:e,env:r}),i=path.join(t.dataDir(r),"history.jsonl"),s={configured:Boolean(o.secret),key_source:o.source,key_path:o.path,key_file_mode:o.path&&!/^win/.test(process.platform)?t.modeString(511&fs.statSync(o.path).mode):null,key_fingerprint:o.secret?load().fp.keyFingerprint(o.secret):null,public_key:o.public,default_key_path:t.defaultKeyPath(r),history_path:i,history_present:fs.existsSync(i)};if(n.json)return n.stdout.write(JSON.stringify(s,null,2)+"\n"),s.configured?0:1;const a=[`key: ${s.configured?s.key_fingerprint:"not set"}`,`source: ${s.key_source||"none"}`,`file: ${s.key_path||s.default_key_path}`,`mode: ${s.key_file_mode||"n/a"}`,"public key: "+(s.public_key?"YES — anyone holding the covenant can forge these records":"no"),`history: ${s.history_path}${s.history_present?"":" (not created yet)"}`];return s.configured||a.push("","No key yet. Mint one: aegiscode fingerprint keygen"),n.stdout.write(a.join("\n")+"\n"),s.configured?0:1}function keygen(e,n){const{authorship:t}=load(),r=t.keygen({argv:e,env:n.env||process.env});return n.json?(n.stdout.write(JSON.stringify(r,null,2)+"\n"),0):(n.stdout.write([`${r.replaced?"replaced":"created"} ${r.out} (mode ${r.mode})`,`key: ${r.keyFingerprint} (derived — the key itself was not printed)`,`bytes: ${r.bytes} random (256-bit)`,"","Next: aegiscode fingerprint mint seal the last session"," aegiscode fingerprint backup --to ~/safe keep a copy of the key"].join("\n")+"\n"),0)}function mint(e,n){const{attest:t,authorship:r}=load(),o=n.env||process.env,i=everyFlag(e,"--code-root"),s=everyFlag(e,"--code-file"),a=has(e,"--code-clean"),c=has(e,"--code-dirty");if(a&&c)throw new Error("fingerprint: --code-clean and --code-dirty are exclusive");const d=i.length||s.length?t.collectCode({roots:i,files:s,skip:everyFlag(e,"--code-skip")}):[],l=t.mintSession({argv:e,env:o,aiModel:flag(e,"--ai-model")||void 0,history:flag(e,"--history")||void 0,session:flag(e,"--session")||void 0,turns:flag(e,"--turns")||void 0,label:flag(e,"--label")||void 0,account:flag(e,"--account")||void 0,model:flag(e,"--model")||void 0,tools:flag(e,"--tools")?flag(e,"--tools").split(",").map(e=>e.trim()).filter(Boolean):void 0,code:d,codeDirty:!a&&(!!c||null)}),u=flag(e,"--out")||defaultRecordPath(l.record,flag(e,"--session")||"last",r.dataDir(o));return fs.mkdirSync(path.dirname(path.resolve(u)),{recursive:!0}),fs.writeFileSync(path.resolve(u),JSON.stringify(l.record,null,2)+"\n"),n.json?(n.stdout.write(JSON.stringify({...l.record,keySource:l.keySource,out:path.resolve(u)},null,2)+"\n"),0):(n.stdout.write([`record ${path.resolve(u)}`,`identity φ_${l.record.keyFingerprint} (key: ${l.keySource}${l.public?" — PUBLIC, forgeable by any covenant holder":""})`,`behaviour ${l.record.behaviour||"none"} from ${l.record.behaviourSamples} turn(s)`,`code ${l.record.code||"none"} ${l.record.codeFiles} file(s)${null===l.record.codeDirty?" (clean/dirty unknown)":l.record.codeDirty?" (dirty tree)":" (clean tree)"}`,`ai ${l.record.aiKey||"none"}${l.record.aiKey?` (${l.aiKeySource})`:" — no AI credential nominated (--ai-secret | $AEGIS_AI_SECRET)"}`,`ai habit ${l.record.ai||"unobserved"} from ${l.record.aiSamples} reply/replies${l.record.aiModel?` on ${l.record.aiModel}`:""}`,`sealed ${l.record.attestation} (v${l.record.v}, ${l.record.algo})`,0===l.samples?"note: no turns matched — the record says so rather than signing nothing":""].filter(Boolean).join("\n")+"\n"),0)}function verify(e,n){const{fp:t,authorship:r}=load(),o=e.find(e=>!e.startsWith("-"));if(!o)throw new Error("fingerprint: verify needs a record file");let i;try{i=JSON.parse(fs.readFileSync(o,"utf8"))}catch(e){throw new Error(`fingerprint: cannot read ${o} as JSON — ${e.message}`)}const s=r.resolveKey({argv:e,env:n.env||process.env});if(!s.secret)throw new Error("fingerprint: no key to verify with — pass --secret <file>, set AEGIS_FINGERPRINT_SECRET, or run `aegiscode fingerprint keygen`");const a=t.verify(i,s.secret),c={ok:a.ok,reason:a.reason,id:a.id,credential_match:a.credentialMatch,key_source:s.source,key_fingerprint_recorded:i.keyFingerprint||null,file:path.resolve(o)};return n.json?(n.stdout.write(JSON.stringify(c,null,2)+"\n"),a.ok?0:1):(n.stdout.write(a.ok?`verified ${i.keyFingerprint} — intact, and minted by ${s.source}\nrecord ${a.id}\n`:`FAILED ${a.reason}\nkey used ${s.source}\nfingerprint recorded ${i.keyFingerprint||"(none)"}\n`),a.ok?0:1)}function backup(e,n){const{authorship:t}=load(),r=t.backup({argv:e,env:n.env||process.env});return n.json?(n.stdout.write(JSON.stringify(r,null,2)+"\n"),0):(n.stdout.write([`key copied ${r.from} -> ${r.to}`,`fingerprint ${r.keyFingerprint} (same key, confirmed by re-reading the copy)`,"restore: point --secret at the copy (or copy it back to the key path). Nothing else changes."].join("\n")+"\n"),0)}function secretOrNull(e,n,t){try{return e.resolveKey({argv:n,env:t}).secret||null}catch{return null}}function newestRecord(e){const n=path.join(e,"fingerprints");if(!fs.existsSync(n))return null;const t=fs.readdirSync(n).filter(e=>e.endsWith(".json")&&!e.endsWith(".anchor.json")).map(e=>path.join(n,e)).map(e=>({f:e,mtime:fs.statSync(e).mtimeMs})).sort((e,n)=>n.mtime-e.mtime);return t.length?t[0].f:null}async function publish(e,n){const{authorship:t,vault:r}=load(),o=n.env||process.env,i=e.find(e=>!e.startsWith("-")),s=i?path.resolve(i):newestRecord(t.dataDir(o));if(!s)throw new Error("fingerprint: no record to publish — seal one first (`aegiscode fingerprint mint`), or name the file: `aegiscode fingerprint publish <record.json>`");if(!fs.existsSync(s))throw new Error(`fingerprint: no record at ${s}`);const a=await r.publish({file:s,argv:e,env:o,dryRun:has(e,"--dry-run"),secret:secretOrNull(t,e,o)});return n.json?(n.stdout.write(JSON.stringify(a,null,2)+"\n"),0):a.dryRun?(n.stdout.write(["dry run nothing uploaded",`backend ${a.backend}`,`record ${s}`,`would go ${a.remotePath}`,...a.commands.map(e=>` ${e}`)].join("\n")+"\n"),0):(n.stdout.write([`published ${a.remotePath} (${a.backend})`,`identity φ_${a.anchor.keyFingerprint}-${a.anchor.behaviour||"unobserved"}`,`digest sha256 ${a.sha256.slice(0,16)}… (${a.bytes} bytes, byte-identical to ${s})`,`link ${a.url||"(no share link — the copy is at the path above)"}`,`anchored ${a.localAnchor}${null===a.indexLines?"":` · ledger lines ${a.indexLines}`}`,"","The key was NOT published. Only the sealed record travels; verify the copy",`any time with: aegiscode fingerprint anchor ${path.basename(s)}`].join("\n")+"\n"),0)}async function anchorCmd(e,n){const{vault:t}=load(),r=e.find(e=>!e.startsWith("-"));if(!r)throw new Error("fingerprint: anchor needs a record file (the one you published)");const o=await t.checkAnchor({file:path.resolve(r),argv:e,env:n.env||process.env});return n.json?(n.stdout.write(JSON.stringify(o,null,2)+"\n"),o.ok?0:1):o.anchor?(n.stdout.write([`record ${path.resolve(r)}`,`published ${o.anchor.path}${o.anchor.url?`\n ${o.anchor.url}`:""}`,`emitted ${o.anchor.emittedAt}`,"present "+(o.present?"yes":"NO"),"unchanged "+(o.unchanged?"yes — the copy is the bytes that were sealed":"NO — sha256 differs"),"attested "+(null===o.attested?`unknown (${o.attestationReason})`:o.attested?"yes — this key still recomputes it":`NO — ${o.attestationReason}`),"",o.ok?"ok — the vault copy is the sealed record, unchanged.":`FAILED — ${o.reason}`].join("\n")+"\n"),o.ok?0:1):(n.stdout.write(`not linked ${path.resolve(r)}\n ${o.reason}\n`),1)}async function vaultCmd(e,n){const{authorship:t,vault:r}=load(),o=n.env||process.env;if(has(e,"--audit")){const i=await r.audit({argv:e,env:o,secret:secretOrNull(t,e,o)});return n.json?(n.stdout.write(JSON.stringify(i,null,2)+"\n"),i.ok?0:1):i.error?(n.stdout.write(`vault unreachable — ${i.error}\n`),2):(n.stdout.write([`vault ${i.where} (backend ${i.backend})`,`inspected ${i.checked} of ${i.files} object(s)`,i.uninspected.length?`skipped ${i.uninspected.length} (see --json)`:"","",0===i.findings.length?"clean — no key material in the vault.":[`KEY MATERIAL IN THE VAULT — ${i.findings.length} finding(s):`,...i.findings.map(e=>` ${e.path}\n ${e.reason}`),"","Anyone who can read that folder can mint records that look like yours.","Move it out, then rotate: aegiscode fingerprint keygen --force","(rotation orphans every record minted under the old key — publish new ones.)"].join("\n")].filter(Boolean).join("\n")+"\n"),i.ok?0:1)}const i=await r.list({argv:e,env:o});if(n.json)return n.stdout.write(JSON.stringify(i,null,2)+"\n"),0;const s=[`vault ${i.where} (${i.records.length} record(s), backend ${i.backend})`];for(const e of i.records)s.push(` ${e.name}`,` id ${e.id||"(no anchor)"} · sha256 ${e.sha256?e.sha256.slice(0,16)+"…":"(none)"}`,e.url?` ${e.url}`:"");return i.records.length||s.push(" (no records published yet — `aegiscode fingerprint publish`)"),n.stdout.write(s.filter(Boolean).join("\n")+"\n"),0}function runFingerprint(e,n=[],t={}){const r={json:!1,stdout:process.stdout,stderr:process.stderr,env:process.env,...t,json:Boolean(t.json)||n.includes("--json")},o=String(e||"status").toLowerCase();try{if("help"===o||"--help"===o||"-h"===o)return r.stdout.write(HELP+"\n"),0;switch(o){case"status":return status(n,r);case"keygen":return keygen(n,r);case"mint":return mint(n,r);case"verify":return verify(n,r);case"backup":return backup(n,r);case"publish":return asExitCode(publish(n,r),r);case"anchor":return asExitCode(anchorCmd(n,r),r);case"vault":return asExitCode(vaultCmd(n,r),r);default:return r.stderr.write(`aegiscode: unknown fingerprint subcommand "${e}"\n\n${HELP}\n`),2}}catch(e){return r.stderr.write(`aegiscode: ${e&&e.message||e}\n`),2}}function asExitCode(e,n){return e.catch(e=>(n.stderr.write(`aegiscode: ${e&&e.message||e}\n`),2))}module.exports={runFingerprint:runFingerprint,HELP:HELP,slug:slug,defaultRecordPath:defaultRecordPath,flag:flag,everyFlag:everyFlag};
@@ -1,3 +1,3 @@
1
1
  // SPDX-License-Identifier: AGPL-3.0-or-later
2
2
  // Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
3
- "use strict";function fmtTokens(t){const e=Number(t);return!Number.isFinite(e)||e<=0?"0":Math.round(e).toString().replace(/\B(?=(\d{3})+(?!\d))/g,",")}function fmtEur(t){const e=Number(t);if(!Number.isFinite(e))return"€?";const n=Math.abs(e);return`€${n<.01?n.toFixed(4):n.toFixed(2)}`}function fmtEurSigned(t){const e=Number(t);return Number.isFinite(e)?`${e<0?"-":"+"}${fmtEur(Math.abs(e))}`:"€?"}function fmtUsageSplit(t){const e=t&&"object"==typeof t?t:{};return Number.isFinite(e.output)?{output:`${fmtTokens(e.output||0)} tokens`}:null}function displayTokens(t){const e=t&&"object"==typeof t?t:{},n=e.tokens&&"object"==typeof e.tokens?e.tokens:null,o=[e.output];n?o.push(n.output,n.output_tokens,n.completion_tokens):o.push(e.output_tokens,e.completion_tokens);for(const t of o)if("number"==typeof t&&isFinite(t)&&t>0)return t;return null}let tierSnapshot=null;function noteTier(t){return tierSnapshot=t&&"object"==typeof t?t:null,tierSnapshot}function feeWaived(t){const e=void 0===t?tierSnapshot:t;if(!e||"object"!=typeof e)return!1;if(!0===e.unlimited)return!0;const n=[e.tier,e.plan,e.planRaw,e.subscription,e.subscriptionTier,e.product,e.item,e.sku].filter((t=>"string"==typeof t)).map((t=>t.trim().toLowerCase()));return!!n.some((t=>"unlimited"===t||"trial"===t))||n.some((t=>/(^|[^a-z])unlimited([^a-z]|$)/.test(t)))}function feeBillable(t){const e=void 0===t?tierSnapshot:t;return!e||"object"!=typeof e||!feeWaived(e)&&!0!==e.degraded}function fmtElapsed(t){const e=Math.max(0,Number(t)||0)/1e3;if(e<10)return`${e.toFixed(1)}s`;if(e<60)return`${Math.round(e)}s`;const n=Math.floor(e/60),o=Math.round(e-60*n);return`${n}m${String(o).padStart(2,"0")}s`}function maskKey(t){const e=String(t||"");return e?e.length<=8?"•".repeat(e.length):`${e.slice(0,6)}${"•".repeat(4)}${e.slice(-4)}`:"not set"}const sharedPlatform=require(require("./shared.js").resolveClientModule("platform.js"));function pathName(t){return sharedPlatform.baseName(t)}function cwdName(t){return pathName(t)||"~"}function shortCwd(){return cwdName(process.cwd())}module.exports={fmtTokens:fmtTokens,fmtEur:fmtEur,fmtEurSigned:fmtEurSigned,fmtElapsed:fmtElapsed,fmtUsageSplit:fmtUsageSplit,displayTokens:displayTokens,feeWaived:feeWaived,feeBillable:feeBillable,noteTier:noteTier,maskKey:maskKey,pathName:pathName,cwdName:cwdName,shortCwd:shortCwd};
3
+ "use strict";function fmtTokens(t){const e=Number(t);return!Number.isFinite(e)||e<=0?"0":Math.round(e).toString().replace(/\B(?=(\d{3})+(?!\d))/g,",")}function fmtEur(t){const e=Number(t);if(!Number.isFinite(e))return"€?";const n=Math.abs(e);return`€${n<.01?n.toFixed(4):n.toFixed(2)}`}function fmtEurSigned(t){const e=Number(t);return Number.isFinite(e)?`${e<0?"-":"+"}${fmtEur(Math.abs(e))}`:"€?"}function fmtUsageSplit(t){const e=t&&"object"==typeof t?t:{};return Number.isFinite(e.output)?{output:`${fmtTokens(e.output||0)} tokens`}:null}function displayTokens(t){const e=t&&"object"==typeof t?t:{},n=e.tokens&&"object"==typeof e.tokens?e.tokens:null,o=[e.output];n?o.push(n.output,n.output_tokens,n.completion_tokens):o.push(e.output_tokens,e.completion_tokens);for(const t of o)if("number"==typeof t&&isFinite(t)&&t>0)return t;return null}let tierSnapshot=null;function noteTier(t){return tierSnapshot=t&&"object"==typeof t?t:null,tierSnapshot}function feeWaived(t){const e=void 0===t?tierSnapshot:t;if(!e||"object"!=typeof e)return!1;if(!0===e.unlimited)return!0;const n=[e.tier,e.plan,e.planRaw,e.subscription,e.subscriptionTier,e.product,e.item,e.sku].filter(t=>"string"==typeof t).map(t=>t.trim().toLowerCase());return!!n.some(t=>"unlimited"===t||"trial"===t)||n.some(t=>/(^|[^a-z])unlimited([^a-z]|$)/.test(t))}function feeBillable(t){const e=void 0===t?tierSnapshot:t;return!e||"object"!=typeof e||!feeWaived(e)&&!0!==e.degraded}function fmtElapsed(t){const e=Math.max(0,Number(t)||0)/1e3;if(e<10)return`${e.toFixed(1)}s`;if(e<60)return`${Math.round(e)}s`;const n=Math.floor(e/60),o=Math.round(e-60*n);return`${n}m${String(o).padStart(2,"0")}s`}function maskKey(t){const e=String(t||"");return e?e.length<=8?"•".repeat(e.length):`${e.slice(0,6)}${"•".repeat(4)}${e.slice(-4)}`:"not set"}const sharedPlatform=require(require("./shared.js").resolveClientModule("platform.js"));function pathName(t){return sharedPlatform.baseName(t)}function cwdName(t){return pathName(t)||"~"}function shortCwd(){return cwdName(process.cwd())}module.exports={fmtTokens:fmtTokens,fmtEur:fmtEur,fmtEurSigned:fmtEurSigned,fmtElapsed:fmtElapsed,fmtUsageSplit:fmtUsageSplit,displayTokens:displayTokens,feeWaived:feeWaived,feeBillable:feeBillable,noteTier:noteTier,maskKey:maskKey,pathName:pathName,cwdName:cwdName,shortCwd:shortCwd};
@@ -1,3 +1,3 @@
1
1
  // SPDX-License-Identifier: AGPL-3.0-or-later
2
2
  // Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
3
- "use strict";function fuzzyScore(t,r){const e=String(t).toLowerCase(),n=String(r).toLowerCase();if(!e)return{matched:!0,score:0};if(n===e)return{matched:!0,score:1e3};if(n.startsWith(e))return{matched:!0,score:900};const o=n.indexOf(e);if(-1!==o)return{matched:!0,score:700-o};let s=50,i=-2,c=-1;for(const t of e){const r=n.indexOf(t,c+1);if(-1===r)return{matched:!1,score:0};s+=r===i+1?15:5,0===r&&(s+=10),i=r,c=r}return{matched:!0,score:s}}function fuzzyMatchPositions(t,r){const e=String(t).toLowerCase(),n=String(r).toLowerCase();if(!e)return[];if(n===e)return Array.from({length:e.length},((t,r)=>r));if(n.startsWith(e))return Array.from({length:e.length},((t,r)=>r));const o=n.indexOf(e);if(-1!==o)return Array.from({length:e.length},((t,r)=>o+r));const s=[];let i=-1;for(const t of e){const r=n.indexOf(t,i+1);if(-1===r)return null;s.push(r),i=r}return s}function fuzzyRank(t,r,e){const n=String(t||"");return n?r.map(((t,r)=>({item:t,idx:r,m:fuzzyScore(n,e(t))}))).filter((t=>t.m.matched)).sort(((t,r)=>r.m.score-t.m.score||t.idx-r.idx)).map((t=>t.item)):r}function fuzzyRankWithAliases(t,r,e,n){const o=String(t||"");return o?r.map(((t,r)=>{const s=[e(t),...n&&n(t)||[]];let i=null;for(const t of s){const r=fuzzyScore(o,t);r.matched&&(!i||r.score>i.score)&&(i=r)}return{item:t,idx:r,m:i}})).filter((t=>t.m)).sort(((t,r)=>r.m.score-t.m.score||t.idx-r.idx)).map((t=>t.item)):r}module.exports={fuzzyScore:fuzzyScore,fuzzyMatchPositions:fuzzyMatchPositions,fuzzyRank:fuzzyRank,fuzzyRankWithAliases:fuzzyRankWithAliases};
3
+ "use strict";function fuzzyScore(t,r){const e=String(t).toLowerCase(),n=String(r).toLowerCase();if(!e)return{matched:!0,score:0};if(n===e)return{matched:!0,score:1e3};if(n.startsWith(e))return{matched:!0,score:900};const o=n.indexOf(e);if(-1!==o)return{matched:!0,score:700-o};let s=50,i=-2,c=-1;for(const t of e){const r=n.indexOf(t,c+1);if(-1===r)return{matched:!1,score:0};s+=r===i+1?15:5,0===r&&(s+=10),i=r,c=r}return{matched:!0,score:s}}function fuzzyMatchPositions(t,r){const e=String(t).toLowerCase(),n=String(r).toLowerCase();if(!e)return[];if(n===e)return Array.from({length:e.length},(t,r)=>r);if(n.startsWith(e))return Array.from({length:e.length},(t,r)=>r);const o=n.indexOf(e);if(-1!==o)return Array.from({length:e.length},(t,r)=>o+r);const s=[];let i=-1;for(const t of e){const r=n.indexOf(t,i+1);if(-1===r)return null;s.push(r),i=r}return s}function fuzzyRank(t,r,e){const n=String(t||"");return n?r.map((t,r)=>({item:t,idx:r,m:fuzzyScore(n,e(t))})).filter(t=>t.m.matched).sort((t,r)=>r.m.score-t.m.score||t.idx-r.idx).map(t=>t.item):r}function fuzzyRankWithAliases(t,r,e,n){const o=String(t||"");return o?r.map((t,r)=>{const s=[e(t),...n&&n(t)||[]];let i=null;for(const t of s){const r=fuzzyScore(o,t);r.matched&&(!i||r.score>i.score)&&(i=r)}return{item:t,idx:r,m:i}}).filter(t=>t.m).sort((t,r)=>r.m.score-t.m.score||t.idx-r.idx).map(t=>t.item):r}module.exports={fuzzyScore:fuzzyScore,fuzzyMatchPositions:fuzzyMatchPositions,fuzzyRank:fuzzyRank,fuzzyRankWithAliases:fuzzyRankWithAliases};
@@ -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"),{aegisDir:aegisDir}=require("./config.js"),{ensurePrivateDir:ensurePrivateDir,writePrivateFile:writePrivateFile}=require("./securefs.js"),{sessionStore:sessionStore}=require("./shared.js"),{cwdName:cwdName}=require("./format.js"),{estimateTokens:estimateTokens}=require("./tokens.js"),HISTORY_LIMIT=500,SOURCE="aegiscode-cli";function historyPath(){return path.join(aegisDir(),"history.jsonl")}function ensureHistoryDir(){ensurePrivateDir(path.dirname(historyPath()))}function appendHistory({sessionId:e,prompt:t,reply:s,status:r,usage:i,title:n,model:o,provider:a}){try{const c={ts:(new Date).toISOString(),sessionId:e,cwd:process.cwd(),prompt:t,reply:s,status:r,tokens:i?{input:i.input||0,output:i.output||0,cacheRead:i.cacheRead||0,cacheWrite:i.cacheWrite||0,real:!0}:{input:estimateTokens(t),output:estimateTokens(s||""),real:!1}};i&&"number"==typeof i.costUsd&&(c.costUsd=i.costUsd);const d=String(n||"").trim();d&&(c.title=d);const u="string"==typeof o?o.trim():"";u&&(c.model=u);const l="string"==typeof a?a.trim():"";return l&&(c.provider=l),appendHistoryEntries([c])}catch(e){return process.env.AEGIS_HIST_DEBUG&&console.error("[history] write failed:",e),0}}function appendHistoryEntries(e){const t=(Array.isArray(e)?e:[]).filter(Boolean);if(!t.length)return 0;try{ensureHistoryDir();const e=historyPath(),s=[...fs.existsSync(e)?fs.readFileSync(e,"utf8").split("\n").filter(Boolean):[],...t.map((e=>JSON.stringify(e)))],r=s.slice(Math.max(0,s.length-HISTORY_LIMIT));return writePrivateFile(e,r.join("\n")+"\n"),mirrorToSharedStore(t),t.length}catch(e){return process.env.AEGIS_HIST_DEBUG&&console.error("[history] write failed:",e),0}}function mirrorToSharedStore(e){for(const t of e)try{sessionStore.recordExchange(aegisDir(),{sessionId:t.sessionId,prompt:t.prompt,reply:t.reply,status:t.status,cwd:t.cwd,ts:t.ts,tokens:t.tokens,costUsd:t.costUsd,model:t.model,provider:t.provider,origin:SOURCE})}catch(e){process.env.AEGIS_HIST_DEBUG&&console.error("[history] mirror failed:",e)}}function readEntries(){try{return fs.readFileSync(historyPath(),"utf8").split("\n").map((e=>e.trim())).filter(Boolean).map((e=>{try{return JSON.parse(e)}catch{return null}})).filter(Boolean)}catch{return[]}}function readHistoryEntries(){return readEntries()}function readOwnSessions(e=8){const t=readEntries(),s=new Map;for(const e of t){const t=s.get(e.sessionId);t?(!t.title&&e.title||!t.title==!e.title&&String(e.ts)>String(t.ts))&&s.set(e.sessionId,e):s.set(e.sessionId,e)}return[...s.values()].sort(((e,t)=>e.ts<t.ts?1:-1)).slice(0,e).map((e=>({id:e.sessionId,cwd:cwdName(e.cwd),summary:(e.title||e.prompt||"").slice(0,60),time:e.ts,own:!0})))}function readSessionTranscript(e){const t=readEntries().filter((t=>t.sessionId===e)).flatMap((e=>[{role:"user",text:e.prompt},{role:"assistant",text:e.reply||"(no response)"}]));if(t.length)return t;try{return sessionStore.readTranscript(aegisDir(),e)}catch{return[]}}function readSharedStoreSessions(e=8){try{return sessionStore.listSummaries(aegisDir(),e)}catch{return[]}}function sessionHistoryEntries(e){return readEntries().filter((t=>t.sessionId===e))}function setSessionTitle(e,t){const s=String(t||"").trim();if(!s)return 0;try{sessionStore.setTitle(aegisDir(),e,s,{named:!0})}catch{}try{const t=historyPath();if(!fs.existsSync(t))return 0;let r=0;const i=fs.readFileSync(t,"utf8").split("\n").map((e=>e.trim())).filter(Boolean).map((t=>{try{const i=JSON.parse(t);return i.sessionId!==e||i.title===s?t:(i.title=s,r++,JSON.stringify(i))}catch{return t}}));return r?(writePrivateFile(t,i.join("\n")+"\n"),r):0}catch(e){return process.env.AEGIS_HIST_DEBUG&&console.error("[history] title write failed:",e),0}}function readSessionTitle(e){const t=readEntries().find((t=>t.sessionId===e&&t.title));return t?String(t.title):""}function pruneSessionHistory(e){try{const t=historyPath();if(!fs.existsSync(t))return;const s=fs.readFileSync(t,"utf8").split("\n").map((e=>e.trim())).filter(Boolean).filter((t=>{try{return JSON.parse(t).sessionId!==e}catch{return!0}}));writePrivateFile(t,s.length?s.join("\n")+"\n":"")}catch(e){process.env.AEGIS_HIST_DEBUG&&console.error("[history] prune failed:",e)}}function aggregateSessionUsage(e){const t=sessionHistoryEntries(e),s={input:0,output:0,cacheRead:0,cacheWrite:0};let r=t.length>0,i=0;for(const e of t){const t=e.tokens||{};t.real||(r=!1),s.input+=t.input||0,s.output+=t.output||0,s.cacheRead+=t.cacheRead||0,s.cacheWrite+=t.cacheWrite||0,"number"==typeof e.costUsd&&(i+=e.costUsd)}return{entries:t.length,usage:s,real:r,costUsd:i}}function readResumeList(e=8,t=5,s=8){const r=readOwnSessions(t),i=new Set(r.map((e=>e.id))),n=readSharedStoreSessions(t).filter((e=>!i.has(e.id)&&(i.add(e.id),!0))),o=[],a=`${os.homedir()}/.claude/history.jsonl`;try{const e=fs.readFileSync(a,"utf8").trim().split("\n").reverse().slice(0,s);for(const t of e)try{const e=JSON.parse(t),s=e.extra&&JSON.parse(e.extra);if(s&&s.sessionId&&!i.has(s.sessionId)){i.add(s.sessionId);const t=cwdName(e.cwd),r=(e.summary||"").slice(0,60);o.push({id:s.sessionId,cwd:t,summary:r,time:e.timestamp,own:!1})}}catch{}}catch{}return[...r,...n,...o].sort(((e,t)=>String(e.time||"")<String(t.time||"")?1:-1)).slice(0,e)}module.exports={HISTORY_LIMIT:HISTORY_LIMIT,SOURCE:SOURCE,historyPath:historyPath,ensureHistoryDir:ensureHistoryDir,appendHistory:appendHistory,appendHistoryEntries:appendHistoryEntries,readHistoryEntries:readHistoryEntries,readOwnSessions:readOwnSessions,readSessionTranscript:readSessionTranscript,readSharedStoreSessions:readSharedStoreSessions,sessionHistoryEntries:sessionHistoryEntries,pruneSessionHistory:pruneSessionHistory,aggregateSessionUsage:aggregateSessionUsage,readResumeList:readResumeList,setSessionTitle:setSessionTitle,readSessionTitle:readSessionTitle};
3
+ "use strict";const fs=require("node:fs"),os=require("node:os"),path=require("node:path"),{aegisDir:aegisDir}=require("./config.js"),{ensurePrivateDir:ensurePrivateDir,writePrivateFile:writePrivateFile}=require("./securefs.js"),{sessionStore:sessionStore}=require("./shared.js"),{cwdName:cwdName}=require("./format.js"),{estimateTokens:estimateTokens}=require("./tokens.js"),HISTORY_LIMIT=500,SOURCE="aegiscode-cli";function historyPath(){return path.join(aegisDir(),"history.jsonl")}function ensureHistoryDir(){ensurePrivateDir(path.dirname(historyPath()))}function appendHistory({sessionId:e,prompt:t,reply:s,status:r,usage:i,title:n,model:o,provider:a}){try{const c={ts:(new Date).toISOString(),sessionId:e,cwd:process.cwd(),prompt:t,reply:s,status:r,tokens:i?{input:i.input||0,output:i.output||0,cacheRead:i.cacheRead||0,cacheWrite:i.cacheWrite||0,real:!0}:{input:estimateTokens(t),output:estimateTokens(s||""),real:!1}};i&&"number"==typeof i.costUsd&&(c.costUsd=i.costUsd);const d=String(n||"").trim();d&&(c.title=d);const u="string"==typeof o?o.trim():"";u&&(c.model=u);const l="string"==typeof a?a.trim():"";return l&&(c.provider=l),appendHistoryEntries([c])}catch(e){return process.env.AEGIS_HIST_DEBUG&&console.error("[history] write failed:",e),0}}function appendHistoryEntries(e){const t=(Array.isArray(e)?e:[]).filter(Boolean);if(!t.length)return 0;try{ensureHistoryDir();const e=historyPath(),s=[...fs.existsSync(e)?fs.readFileSync(e,"utf8").split("\n").filter(Boolean):[],...t.map(e=>JSON.stringify(e))],r=s.slice(Math.max(0,s.length-500));return writePrivateFile(e,r.join("\n")+"\n"),mirrorToSharedStore(t),t.length}catch(e){return process.env.AEGIS_HIST_DEBUG&&console.error("[history] write failed:",e),0}}function mirrorToSharedStore(e){for(const t of e)try{sessionStore.recordExchange(aegisDir(),{sessionId:t.sessionId,prompt:t.prompt,reply:t.reply,status:t.status,cwd:t.cwd,ts:t.ts,tokens:t.tokens,costUsd:t.costUsd,model:t.model,provider:t.provider,origin:SOURCE})}catch(e){process.env.AEGIS_HIST_DEBUG&&console.error("[history] mirror failed:",e)}}function readEntries(){try{return fs.readFileSync(historyPath(),"utf8").split("\n").map(e=>e.trim()).filter(Boolean).map(e=>{try{return JSON.parse(e)}catch{return null}}).filter(Boolean)}catch{return[]}}function readHistoryEntries(){return readEntries()}function readOwnSessions(e=8){const t=readEntries(),s=new Map;for(const e of t){const t=s.get(e.sessionId);t?(!t.title&&e.title||!t.title==!e.title&&String(e.ts)>String(t.ts))&&s.set(e.sessionId,e):s.set(e.sessionId,e)}return[...s.values()].sort((e,t)=>e.ts<t.ts?1:-1).slice(0,e).map(e=>({id:e.sessionId,cwd:cwdName(e.cwd),summary:(e.title||e.prompt||"").slice(0,60),time:e.ts,own:!0}))}function readSessionTranscript(e){const t=readEntries().filter(t=>t.sessionId===e).flatMap(e=>[{role:"user",text:e.prompt},{role:"assistant",text:e.reply||"(no response)"}]);if(t.length)return t;try{return sessionStore.readTranscript(aegisDir(),e)}catch{return[]}}function readSharedStoreSessions(e=8){try{return sessionStore.listSummaries(aegisDir(),e)}catch{return[]}}function sessionHistoryEntries(e){return readEntries().filter(t=>t.sessionId===e)}function setSessionTitle(e,t){const s=String(t||"").trim();if(!s)return 0;try{sessionStore.setTitle(aegisDir(),e,s,{named:!0})}catch{}try{const t=historyPath();if(!fs.existsSync(t))return 0;let r=0;const i=fs.readFileSync(t,"utf8").split("\n").map(e=>e.trim()).filter(Boolean).map(t=>{try{const i=JSON.parse(t);return i.sessionId!==e||i.title===s?t:(i.title=s,r++,JSON.stringify(i))}catch{return t}});return r?(writePrivateFile(t,i.join("\n")+"\n"),r):0}catch(e){return process.env.AEGIS_HIST_DEBUG&&console.error("[history] title write failed:",e),0}}function readSessionTitle(e){const t=readEntries().find(t=>t.sessionId===e&&t.title);return t?String(t.title):""}function pruneSessionHistory(e){try{const t=historyPath();if(!fs.existsSync(t))return;const s=fs.readFileSync(t,"utf8").split("\n").map(e=>e.trim()).filter(Boolean).filter(t=>{try{return JSON.parse(t).sessionId!==e}catch{return!0}});writePrivateFile(t,s.length?s.join("\n")+"\n":"")}catch(e){process.env.AEGIS_HIST_DEBUG&&console.error("[history] prune failed:",e)}}function aggregateSessionUsage(e){const t=sessionHistoryEntries(e),s={input:0,output:0,cacheRead:0,cacheWrite:0};let r=t.length>0,i=0;for(const e of t){const t=e.tokens||{};t.real||(r=!1),s.input+=t.input||0,s.output+=t.output||0,s.cacheRead+=t.cacheRead||0,s.cacheWrite+=t.cacheWrite||0,"number"==typeof e.costUsd&&(i+=e.costUsd)}return{entries:t.length,usage:s,real:r,costUsd:i}}function readResumeList(e=8,t=5,s=8){const r=readOwnSessions(t),i=new Set(r.map(e=>e.id)),n=readSharedStoreSessions(t).filter(e=>!i.has(e.id)&&(i.add(e.id),!0)),o=[],a=`${os.homedir()}/.claude/history.jsonl`;try{const e=fs.readFileSync(a,"utf8").trim().split("\n").reverse().slice(0,s);for(const t of e)try{const e=JSON.parse(t),s=e.extra&&JSON.parse(e.extra);if(s&&s.sessionId&&!i.has(s.sessionId)){i.add(s.sessionId);const t=cwdName(e.cwd),r=(e.summary||"").slice(0,60);o.push({id:s.sessionId,cwd:t,summary:r,time:e.timestamp,own:!1})}}catch{}}catch{}return[...r,...n,...o].sort((e,t)=>String(e.time||"")<String(t.time||"")?1:-1).slice(0,e)}module.exports={HISTORY_LIMIT:500,SOURCE:SOURCE,historyPath:historyPath,ensureHistoryDir:ensureHistoryDir,appendHistory:appendHistory,appendHistoryEntries:appendHistoryEntries,readHistoryEntries:readHistoryEntries,readOwnSessions:readOwnSessions,readSessionTranscript:readSessionTranscript,readSharedStoreSessions:readSharedStoreSessions,sessionHistoryEntries:sessionHistoryEntries,pruneSessionHistory:pruneSessionHistory,aggregateSessionUsage:aggregateSessionUsage,readResumeList:readResumeList,setSessionTitle:setSessionTitle,readSessionTitle:readSessionTitle};
@@ -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"),{execSync:execSync}=require("node:child_process"),{pathName:pathName}=require("./format.js");function readJson(e,t){try{return JSON.parse(fs.readFileSync(path.join(t,e),"utf8"))}catch{return null}}function hasFile(e,...t){return t.some((t=>fs.existsSync(path.join(e,t))))}function gitName(e){try{const t=execSync("git config --get remote.origin.url",{encoding:"utf8",cwd:e,stdio:["ignore","pipe","ignore"]}).trim(),s=pathName(t).replace(/\.git$/,"");if(s)return s}catch{}try{return pathName(e)||"this project"}catch{return"this project"}}function sniffProject(e=process.cwd()){const t=readJson("package.json",e),s={name:t&&t.name?t.name:gitName(e),lang:"unknown",build:null,test:null,lint:null,dev:null,structure:[],toolchain:[]};if(t){s.lang="JavaScript/TypeScript (Node.js)",s.toolchain.push("Node.js");const e=t.scripts||{};e.build&&(s.build="npm run build"),e.test&&(s.test="npm test"),e.lint&&(s.lint="npm run lint"),(e.dev||e.start||e.watch)&&(s.dev=e.dev?"npm run dev":"npm start"),t.packageManager&&s.toolchain.push(t.packageManager)}else hasFile(e,"go.mod")?(s.lang="Go",s.toolchain.push("Go"),s.build="go build ./...",s.test="go test ./...",s.lint="golangci-lint run",s.dev="go run ."):hasFile(e,"Cargo.toml")?(s.lang="Rust",s.toolchain.push("Cargo"),s.build="cargo build",s.test="cargo test",s.lint="cargo clippy -- -D warnings",s.dev="cargo run"):hasFile(e,"pyproject.toml","setup.py","requirements.txt")?(s.lang="Python",s.toolchain.push("Python"),s.test=hasFile(e,"pytest.ini","tox.ini")?"pytest":"python -m pytest",s.lint="ruff check ."):hasFile(e,"Makefile")?(s.lang="C/C++ or make-driven",s.toolchain.push("make"),s.build="make",s.test="make test",s.dev="make run"):hasFile(e,"pom.xml","build.gradle")?(s.lang="Java",s.toolchain.push("Maven/Gradle"),s.build=hasFile(e,"pom.xml")?"mvn package":"gradle build",s.test=hasFile(e,"pom.xml")?"mvn test":"gradle test"):hasFile(e,"Gemfile")?(s.lang="Ruby",s.toolchain.push("Ruby"),s.test="bundle exec rspec",s.build="bundle exec rake build"):hasFile(e,"composer.json")?(s.lang="PHP",s.toolchain.push("Composer"),s.test="composer test"):hasFile(e,".csproj")&&(s.lang="C#/.NET",s.toolchain.push(".NET"),s.build="dotnet build",s.test="dotnet test");for(const t of["src","lib","app","tests","test","spec","docs","scripts"])fs.existsSync(path.join(e,t))&&s.structure.push(t);for(const t of["eslint.config.js",".eslintrc",".prettierrc","biome.json","tsconfig.json",".github/workflows"])fs.existsSync(path.join(e,t))&&s.toolchain.push(t.split("/")[0]);return s}function buildAegisMd(e){const t=e,s=[];if(s.push("# AEGIS.md"),s.push(""),s.push("Generated by AEGIS Code /init — edit freely. This file teaches AI agents how to work in this repo."),s.push(""),s.push("## Project"),s.push(""),s.push(`- Project: ${t.name}`),s.push(`- Language: ${t.lang}`),t.toolchain.length&&s.push(`- Toolchain: ${[...new Set(t.toolchain)].join(", ")}`),s.push(""),s.push("## Commands"),s.push(""),s.push("Run these to build, test, and lint:"),s.push("```bash"),t.build&&s.push(t.build+" # build"),t.test&&s.push(t.test+" # test"),t.lint&&s.push(t.lint+" # lint"),t.dev&&s.push(t.dev+" # dev server"),s.push("```"),s.push(""),t.structure.length){s.push("## Project structure"),s.push("");for(const e of t.structure)s.push(`- \`${e}/\` — ${"src"===e||"lib"===e?"source code":"tests"===e||"test"===e||"spec"===e?"tests":e}`);s.push("")}return s.push("## Coding conventions"),s.push(""),s.push("- Keep changes minimal and focused; match the surrounding style."),s.push("- Before editing a file, read it; verify with the test command above."),s.push("- Prefer the project's own scripts over ad-hoc shell commands."),s.push(""),s.join("\n")}module.exports={sniffProject:sniffProject,buildAegisMd:buildAegisMd,buildClaudeMd:buildAegisMd};
3
+ "use strict";const fs=require("node:fs"),path=require("node:path"),{execSync:execSync}=require("node:child_process"),{pathName:pathName}=require("./format.js");function readJson(e,t){try{return JSON.parse(fs.readFileSync(path.join(t,e),"utf8"))}catch{return null}}function hasFile(e,...t){return t.some(t=>fs.existsSync(path.join(e,t)))}function gitName(e){try{const t=execSync("git config --get remote.origin.url",{encoding:"utf8",cwd:e,stdio:["ignore","pipe","ignore"]}).trim(),s=pathName(t).replace(/\.git$/,"");if(s)return s}catch{}try{return pathName(e)||"this project"}catch{return"this project"}}function sniffProject(e=process.cwd()){const t=readJson("package.json",e),s={name:t&&t.name?t.name:gitName(e),lang:"unknown",build:null,test:null,lint:null,dev:null,structure:[],toolchain:[]};if(t){s.lang="JavaScript/TypeScript (Node.js)",s.toolchain.push("Node.js");const e=t.scripts||{};e.build&&(s.build="npm run build"),e.test&&(s.test="npm test"),e.lint&&(s.lint="npm run lint"),(e.dev||e.start||e.watch)&&(s.dev=e.dev?"npm run dev":"npm start"),t.packageManager&&s.toolchain.push(t.packageManager)}else hasFile(e,"go.mod")?(s.lang="Go",s.toolchain.push("Go"),s.build="go build ./...",s.test="go test ./...",s.lint="golangci-lint run",s.dev="go run ."):hasFile(e,"Cargo.toml")?(s.lang="Rust",s.toolchain.push("Cargo"),s.build="cargo build",s.test="cargo test",s.lint="cargo clippy -- -D warnings",s.dev="cargo run"):hasFile(e,"pyproject.toml","setup.py","requirements.txt")?(s.lang="Python",s.toolchain.push("Python"),s.test=hasFile(e,"pytest.ini","tox.ini")?"pytest":"python -m pytest",s.lint="ruff check ."):hasFile(e,"Makefile")?(s.lang="C/C++ or make-driven",s.toolchain.push("make"),s.build="make",s.test="make test",s.dev="make run"):hasFile(e,"pom.xml","build.gradle")?(s.lang="Java",s.toolchain.push("Maven/Gradle"),s.build=hasFile(e,"pom.xml")?"mvn package":"gradle build",s.test=hasFile(e,"pom.xml")?"mvn test":"gradle test"):hasFile(e,"Gemfile")?(s.lang="Ruby",s.toolchain.push("Ruby"),s.test="bundle exec rspec",s.build="bundle exec rake build"):hasFile(e,"composer.json")?(s.lang="PHP",s.toolchain.push("Composer"),s.test="composer test"):hasFile(e,".csproj")&&(s.lang="C#/.NET",s.toolchain.push(".NET"),s.build="dotnet build",s.test="dotnet test");for(const t of["src","lib","app","tests","test","spec","docs","scripts"])fs.existsSync(path.join(e,t))&&s.structure.push(t);for(const t of["eslint.config.js",".eslintrc",".prettierrc","biome.json","tsconfig.json",".github/workflows"])fs.existsSync(path.join(e,t))&&s.toolchain.push(t.split("/")[0]);return s}function buildAegisMd(e){const t=e,s=[];if(s.push("# AEGIS.md"),s.push(""),s.push("Generated by AEGIS Code /init — edit freely. This file teaches AI agents how to work in this repo."),s.push(""),s.push("## Project"),s.push(""),s.push(`- Project: ${t.name}`),s.push(`- Language: ${t.lang}`),t.toolchain.length&&s.push(`- Toolchain: ${[...new Set(t.toolchain)].join(", ")}`),s.push(""),s.push("## Commands"),s.push(""),s.push("Run these to build, test, and lint:"),s.push("```bash"),t.build&&s.push(t.build+" # build"),t.test&&s.push(t.test+" # test"),t.lint&&s.push(t.lint+" # lint"),t.dev&&s.push(t.dev+" # dev server"),s.push("```"),s.push(""),t.structure.length){s.push("## Project structure"),s.push("");for(const e of t.structure)s.push(`- \`${e}/\` — ${"src"===e||"lib"===e?"source code":"tests"===e||"test"===e||"spec"===e?"tests":e}`);s.push("")}return s.push("## Coding conventions"),s.push(""),s.push("- Keep changes minimal and focused; match the surrounding style."),s.push("- Before editing a file, read it; verify with the test command above."),s.push("- Prefer the project's own scripts over ad-hoc shell commands."),s.push(""),s.join("\n")}module.exports={sniffProject:sniffProject,buildAegisMd:buildAegisMd,buildClaudeMd:buildAegisMd};
@@ -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{createHash:createHash}=require("node:crypto"),{existsSync:existsSync,readFileSync:readFileSync}=require("node:fs"),path=require("node:path"),PACKAGE_ROOT=path.join(__dirname,".."),SALT="aegiscode-interlock-v1",PAD="aegis-interlock-pad-v1",sha256=e=>createHash("sha256").update(e).digest("hex"),PAD_HEX=sha256(PAD);function unmask(e){let t="";for(let r=0;r<e.length;r++){const n=parseInt(e[r],16),i=parseInt(PAD_HEX[r%PAD_HEX.length],16);if(Number.isNaN(n)||Number.isNaN(i))return null;t+=(n^i).toString(16)}return t}const UNITS=Object.freeze([{id:"p1",rel:Buffer.from("YmluL2FlZ2lzY29kZS5qcw==","base64").toString("utf8")},{id:"p2",rel:Buffer.from("c3JjL3Byb3ZlbmFuY2UuanM=","base64").toString("utf8")},{id:"p3",rel:Buffer.from("c3JjL2dhdGUuanM=","base64").toString("utf8")},{id:"p4",rel:Buffer.from("c3JjL3Blcm1pc3Npb25zLmpz","base64").toString("utf8")},{id:"p5",rel:Buffer.from("c3JjL2NhcHMuanM=","base64").toString("utf8")},{id:"p6",rel:Buffer.from("c3JjL2F1dG9ub21vdXMuanM=","base64").toString("utf8")},{id:"p8",rel:Buffer.from("c3JjL21jcC5qcw==","base64").toString("utf8")}]),SEALED="5b21370a8635798d3063838effdce067a5eb3e50525689b72a5b6aa51f9c7ebb",PRIVILEGED=Object.freeze(["gate","provenance","mcp"]);function check(){const e=[];for(const t of UNITS){const r=path.join(PACKAGE_ROOT,t.rel);if(!existsSync(r))return{tripped:!0,code:"p1",units:UNITS.length};try{e.push(sha256(readFileSync(r)))}catch{return{tripped:!0,code:"p1",units:UNITS.length}}}const t=sha256(`${SALT}\n${e.join("\n")}`),r="string"==typeof SEALED?SEALED.trim():"";return 64!==r.length?{tripped:!0,code:"p2",units:UNITS.length}:unmask(r)!==t?{tripped:!0,code:"p3",units:UNITS.length}:{tripped:!1,code:null,units:UNITS.length}}function line(e){return e&&e.tripped?`aegiscode: reduced mode (${e.code}) — this build is not the one that was published.\n`:null}let ARMED=null;function armed(){if(null!==ARMED)return ARMED;let e;try{e=check()}catch{e={tripped:!0,code:"p2",units:UNITS.length}}if(ARMED=Boolean(e.tripped),ARMED){process.env.AEGIS_REDUCED_MODE="1";const t=line(e);t&&process.stderr.write(t)}return ARMED}function isPrivileged(e){return PRIVILEGED.includes(e)}function refuse(){return 1}function sealOf(e){const t=e.map((e=>sha256(readFileSync(e))));return sha256(`${SALT}\n${t.join("\n")}`)}module.exports={UNITS:UNITS,PRIVILEGED:PRIVILEGED,SALT:SALT,PAD:PAD,check:check,armed:armed,line:line,isPrivileged:isPrivileged,refuse:refuse,sealOf:sealOf,mask:e=>unmask(e)};
3
+ "use strict";const{createHash:createHash}=require("node:crypto"),{existsSync:existsSync,readFileSync:readFileSync}=require("node:fs"),path=require("node:path"),PACKAGE_ROOT=path.join(__dirname,".."),SALT="aegiscode-interlock-v1",PAD="aegis-interlock-pad-v1",sha256=e=>createHash("sha256").update(e).digest("hex"),PAD_HEX=sha256(PAD);function unmask(e){let t="";for(let r=0;r<e.length;r++){const n=parseInt(e[r],16),i=parseInt(PAD_HEX[r%PAD_HEX.length],16);if(Number.isNaN(n)||Number.isNaN(i))return null;t+=(n^i).toString(16)}return t}const UNITS=Object.freeze([{id:"p1",rel:Buffer.from("YmluL2FlZ2lzY29kZS5qcw==","base64").toString("utf8")},{id:"p2",rel:Buffer.from("c3JjL3Byb3ZlbmFuY2UuanM=","base64").toString("utf8")},{id:"p3",rel:Buffer.from("c3JjL2dhdGUuanM=","base64").toString("utf8")},{id:"p4",rel:Buffer.from("c3JjL3Blcm1pc3Npb25zLmpz","base64").toString("utf8")},{id:"p5",rel:Buffer.from("c3JjL2NhcHMuanM=","base64").toString("utf8")},{id:"p6",rel:Buffer.from("c3JjL2F1dG9ub21vdXMuanM=","base64").toString("utf8")},{id:"p8",rel:Buffer.from("c3JjL21jcC5qcw==","base64").toString("utf8")}]),SEALED="5b21370a8635798d3063838effdce067a5eb3e50525689b72a5b6aa51f9c7ebb",PRIVILEGED=Object.freeze(["gate","provenance","mcp"]);function check(){const e=[];for(const t of UNITS){const r=path.join(PACKAGE_ROOT,t.rel);if(!existsSync(r))return{tripped:!0,code:"p1",units:UNITS.length};try{e.push(sha256(readFileSync(r)))}catch{return{tripped:!0,code:"p1",units:UNITS.length}}}const t=sha256(`${SALT}\n${e.join("\n")}`),r=SEALED.trim();return 64!==r.length?{tripped:!0,code:"p2",units:UNITS.length}:unmask(r)!==t?{tripped:!0,code:"p3",units:UNITS.length}:{tripped:!1,code:null,units:UNITS.length}}function line(e){return e&&e.tripped?`aegiscode: reduced mode (${e.code}) — this build is not the one that was published.\n`:null}let ARMED=null;function armed(){if(null!==ARMED)return ARMED;let e;try{e=check()}catch{e={tripped:!0,code:"p2",units:UNITS.length}}if(ARMED=Boolean(e.tripped),ARMED){process.env.AEGIS_REDUCED_MODE="1";const t=line(e);t&&process.stderr.write(t)}return ARMED}function isPrivileged(e){return PRIVILEGED.includes(e)}function refuse(){return 1}function sealOf(e){const t=e.map(e=>sha256(readFileSync(e)));return sha256(`${SALT}\n${t.join("\n")}`)}module.exports={UNITS:UNITS,PRIVILEGED:PRIVILEGED,SALT:SALT,PAD:PAD,check:check,armed:armed,line:line,isPrivileged:isPrivileged,refuse:refuse,sealOf:sealOf,mask:e=>unmask(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{BOLD:BOLD,BOLD_OFF:BOLD_OFF,DIM:DIM,ITALIC:ITALIC,ITALIC_OFF:ITALIC_OFF,RESET_BG:RESET_BG,RESET_FG:RESET_FG,themeOf:themeOf}=require("./theme.js"),RE_ZERO=/[\u0300-\u036F\u1AB0-\u1AFF\u1DC0-\u1DFF\u20D0-\u20FF\uFE00-\uFE0F\uFE20-\uFE2F]/u,RE_WIDE=/[\u1100-\u115F\u2E80-\u303E\u3041-\u33FF\u3400-\u4DBF\u4E00-\u9FFF\uA000-\uA4CF\uA960-\uA97F\uAC00-\uD7A3\uF900-\uFAFF\uFE10-\uFE19\uFE30-\uFE4F\uFF00-\uFF60\uFFE0-\uFFE6\u{1F1E6}-\u{1F1FF}\u{1F300}-\u{1F64F}\u{1F680}-\u{1F6FF}\u{1F900}-\u{1F9FF}\u{1FA70}-\u{1FAFF}\u{20000}-\u{3FFFD}]/u;function w(n){let s=0;for(const t of String(null==n?"":n))RE_ZERO.test(t)||(s+=RE_WIDE.test(t)?2:1);return s}function span(n,s){return{t:s,s:n,w:w(s)}}function asBg(n){return n.replace("[38;2;","[48;2;")}function renderMarkdown(n,s,t){const e=themeOf(t),u=asBg(e.black)+e.white,F=String(null==n?"":n).split("\n"),r=[];let o=!1;for(const n of F){const t=n.replace(/\r$/,"");t.startsWith("```")?o=!o:o?r.push([span(u," "+(t||""))]):r.push(...inlineLine(t,s,e))}return r}function inlineLine(n,s,t){const e=n.trimStart();let u=n,F=null,r=!1;e.startsWith("- ")?(F=span(t.white," - "),u=e.slice(2)):e.startsWith(" - ")?(F=span(t.white," - "),u=e.slice(4)):e.startsWith("> ")&&(F=span(DIM," ▎ "),u=e.slice(2),r=!0);const o=[],p=/(\*\*[^*]+\*\*|`[^`]+`)/g;let i,a=0;for(;i=p.exec(u);){i.index>a&&pushText(o,u.slice(a,i.index),t);const n=i[0];n.startsWith("**")?pushText(o,n.slice(2,-2),t,BOLD):pushText(o,n.slice(1,-1),t,t.green),a=i.index+n.length}if(a<u.length&&pushText(o,u.slice(a),t),r)for(const n of o)n.s=ITALIC+n.s+ITALIC_OFF;return wrapInline(o,s,F)}function pushText(n,s,t,e){const u=null==e?t.white:e,F=s.split(/[ \t]+/).filter(Boolean);for(const s of F)n.push(span(u,s))}function wrapInline(n,s,t){const e=[];let u=t?[t]:[],F=t?t.w:0,r=!!t&&/\s$/.test(t.t);const o=()=>{u.length&&(e.push(u),u=[],F=0,r=!1)};for(const t of n){const n=t.t.split(" ");for(let p=0;p<n.length;p++){const i=n[p],a=w(i),l=F>0&&0===p&&/^\S/.test(i)&&!r;if(F+a+(l?1:0)>s&&F>0&&o(),a>s){const n=[...i],p=n.map((n=>w(n)));let a=0;for(const n of p)a+=n;const l=400;let c=0,h=0;for(;a>s;){let i=0,f=0;for(;c+i<n.length&&f+p[c+i]<=s;)f+=p[c+i],i++;i||(i=1);const E=n.slice(c,c+i).join("");if(F&&(u.push(span(""," ")),F++,r=!0),u.push(span(t.s,E)),F+=f,o(),c+=i,a-=f,++h>=l)return F&&(u.push(span(""," ")),F++),u.push(span(t.s,"…")),o(),e.length?e:[[span("","")]]}const f=n.slice(c).join("");f&&(u.push(span(t.s,f)),F+=w(f),r=/\s$/.test(f))}else F>0&&l&&(u.push(span(""," ")),F++,r=!0),u.push(span(t.s,i)),F+=a,r=/\s$/.test(i)}}return o(),e.length?e:[[span("","")]]}function renderDiffPreview(n,s){const t=themeOf(s),e="╌".repeat(Math.max(10,n-4)),u=n=>span(t.gray+"",n),F=n=>span(t.white,n),r=n=>span(RGB_LEGACY(230,219,116),n),o=n=>span("",n),p=n=>span("",n),i=Math.max(28,n-8),a=(n,s)=>{let t=0;const e=[...n];for(const n of e)t+=n.w;return t<i&&e.push(span(s+" "," ".repeat(i-t))),e.push(span(RESET_BG,"")),e},l=[];return l.push([span(t.dim,e)]),l.push([u(" 1 "),span(RGB_LEGACY(102,217,239),"function"),F(" "),span(RGB_LEGACY(166,226,46),"greet"),F("()"),span(t.white,"{")]),l.push(a([u(" 2 "),o("-"),F(" "),o("console"),span("",".log"),o("("),r('"Hello, '),span("","World"),o('!");')],"")),l.push(a([u(" 2 "),p("+"),F(" "),p("console"),span("",".log"),p("("),r('"Hello, '),span("","Claude"),p('!");')],"")),l.push([u(" 3 "),F("}")]),l.push([span(t.dim,e)]),l}function RGB_LEGACY(n,s,t){return`[38;2;${n};${s};${t}m`}module.exports={renderMarkdown:renderMarkdown,renderDiffPreview:renderDiffPreview,RESET_FG:RESET_FG,BOLD:BOLD,BOLD_OFF:BOLD_OFF,span:span,w:w};
3
+ "use strict";const{BOLD:BOLD,BOLD_OFF:BOLD_OFF,DIM:DIM,ITALIC:ITALIC,ITALIC_OFF:ITALIC_OFF,RESET_BG:RESET_BG,RESET_FG:RESET_FG,themeOf:themeOf}=require("./theme.js"),RE_ZERO=/[\u0300-\u036F\u1AB0-\u1AFF\u1DC0-\u1DFF\u20D0-\u20FF\uFE00-\uFE0F\uFE20-\uFE2F]/u,RE_WIDE=/[\u1100-\u115F\u2E80-\u303E\u3041-\u33FF\u3400-\u4DBF\u4E00-\u9FFF\uA000-\uA4CF\uA960-\uA97F\uAC00-\uD7A3\uF900-\uFAFF\uFE10-\uFE19\uFE30-\uFE4F\uFF00-\uFF60\uFFE0-\uFFE6\u{1F1E6}-\u{1F1FF}\u{1F300}-\u{1F64F}\u{1F680}-\u{1F6FF}\u{1F900}-\u{1F9FF}\u{1FA70}-\u{1FAFF}\u{20000}-\u{3FFFD}]/u;function w(n){let s=0;for(const t of String(null==n?"":n))RE_ZERO.test(t)||(s+=RE_WIDE.test(t)?2:1);return s}function span(n,s){return{t:s,s:n,w:w(s)}}function asBg(n){return n.replace("[38;2;","[48;2;")}function renderMarkdown(n,s,t){const e=themeOf(t),u=asBg(e.black)+e.white,F=String(null==n?"":n).split("\n"),r=[];let o=!1;for(const n of F){const t=n.replace(/\r$/,"");t.startsWith("```")?o=!o:o?r.push([span(u," "+(t||""))]):r.push(...inlineLine(t,s,e))}return r}function inlineLine(n,s,t){const e=n.trimStart();let u=n,F=null,r=!1;e.startsWith("- ")?(F=span(t.white," - "),u=e.slice(2)):e.startsWith(" - ")?(F=span(t.white," - "),u=e.slice(4)):e.startsWith("> ")&&(F=span(DIM," ▎ "),u=e.slice(2),r=!0);const o=[],p=/(\*\*[^*]+\*\*|`[^`]+`)/g;let i,a=0;for(;i=p.exec(u);){i.index>a&&pushText(o,u.slice(a,i.index),t);const n=i[0];n.startsWith("**")?pushText(o,n.slice(2,-2),t,BOLD):pushText(o,n.slice(1,-1),t,t.green),a=i.index+n.length}if(a<u.length&&pushText(o,u.slice(a),t),r)for(const n of o)n.s=ITALIC+n.s+ITALIC_OFF;return wrapInline(o,s,F)}function pushText(n,s,t,e){const u=null==e?t.white:e,F=s.split(/[ \t]+/).filter(Boolean);for(const s of F)n.push(span(u,s))}function wrapInline(n,s,t){const e=[];let u=t?[t]:[],F=t?t.w:0,r=!!t&&/\s$/.test(t.t);const o=()=>{u.length&&(e.push(u),u=[],F=0,r=!1)};for(const t of n){const n=t.t.split(" ");for(let p=0;p<n.length;p++){const i=n[p],a=w(i),l=F>0&&0===p&&/^\S/.test(i)&&!r;if(F+a+(l?1:0)>s&&F>0&&o(),a>s){const n=[...i],p=n.map(n=>w(n));let a=0;for(const n of p)a+=n;const l=400;let c=0,h=0;for(;a>s;){let i=0,f=0;for(;c+i<n.length&&f+p[c+i]<=s;)f+=p[c+i],i++;i||(i=1);const E=n.slice(c,c+i).join("");if(F&&(u.push(span(""," ")),F++,r=!0),u.push(span(t.s,E)),F+=f,o(),c+=i,a-=f,++h>=l)return F&&(u.push(span(""," ")),F++),u.push(span(t.s,"…")),o(),e.length?e:[[span("","")]]}const f=n.slice(c).join("");f&&(u.push(span(t.s,f)),F+=w(f),r=/\s$/.test(f))}else F>0&&l&&(u.push(span(""," ")),F++,r=!0),u.push(span(t.s,i)),F+=a,r=/\s$/.test(i)}}return o(),e.length?e:[[span("","")]]}function renderDiffPreview(n,s){const t=themeOf(s),e="╌".repeat(Math.max(10,n-4)),u=n=>span(t.gray+"",n),F=n=>span(t.white,n),r=n=>span(RGB_LEGACY(230,219,116),n),o=n=>span("",n),p=n=>span("",n),i=Math.max(28,n-8),a=(n,s)=>{let t=0;const e=[...n];for(const n of e)t+=n.w;return t<i&&e.push(span(s+" "," ".repeat(i-t))),e.push(span(RESET_BG,"")),e},l=[];return l.push([span(t.dim,e)]),l.push([u(" 1 "),span(RGB_LEGACY(102,217,239),"function"),F(" "),span(RGB_LEGACY(166,226,46),"greet"),F("()"),span(t.white,"{")]),l.push(a([u(" 2 "),o("-"),F(" "),o("console"),span("",".log"),o("("),r('"Hello, '),span("","World"),o('!");')],"")),l.push(a([u(" 2 "),p("+"),F(" "),p("console"),span("",".log"),p("("),r('"Hello, '),span("","Claude"),p('!");')],"")),l.push([u(" 3 "),F("}")]),l.push([span(t.dim,e)]),l}function RGB_LEGACY(n,s,t){return`[38;2;${n};${s};${t}m`}module.exports={renderMarkdown:renderMarkdown,renderDiffPreview:renderDiffPreview,RESET_FG:RESET_FG,BOLD:BOLD,BOLD_OFF:BOLD_OFF,span:span,w:w};
@@ -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"),{spawn:spawn}=require("node:child_process"),{resolveShared:resolveShared}=require("./sharedpaths.js"),limits=require("./limits.js"),install=require(resolveShared(path.join("hosts","install.js"))),targets=require(resolveShared(path.join("hosts","targets.js"))),spec=require(resolveShared(path.join("hosts","spec.js"))),SUBCOMMANDS=new Set(["install","remove","status","list","print","serve","shim","help"]),USAGE="aegiscode mcp — put AEGIS inside your editor.\n\nUsage:\n aegiscode mcp install [options] write the editor config (merges, never replaces)\n aegiscode mcp status [options] which hosts are configured, and do they still work\n aegiscode mcp list every supported host, its config file and its docs\n aegiscode mcp print <host> show the entry that would be written, touch nothing\n aegiscode mcp remove [options] take our entry out again\n aegiscode mcp serve run the stdio MCP server (editors spawn this themselves)\n aegiscode mcp shim [options] run the OpenAI-compatible endpoint on loopback\n\nTargets:\n --target <id> one host, repeatable and comma-separated (see `aegiscode mcp list`)\n --all every supported host, not just the ones detected\n --scope <s> user (default) or workspace — workspace writes into the\n current directory, which is committed in many projects\n\nInstall options:\n --dry-run print what would change, write nothing\n --with-key embed the resolved API key in the config file. Off by\n default: these files are plain and often world-readable, and\n the server already finds a key from the environment, the\n 0600 store, or ~/.aegiscode/.env\n --prompt-key VS Code only: reference its own secret prompt instead of\n storing a value anywhere\n --base <url> API base to record (default $AEGIS_API_BASE or aegiscloud.org)\n\nShim options:\n --port <n> default 8787\n --host <addr> default 127.0.0.1; any non-loopback address also requires\n --allow-remote ... this flag, because the endpoint spends your tokens\n\nOptions:\n --json machine-readable output\n -h, --help this text\n",BOOL_FLAGS=new Set(["json","all","dry-run","with-key","prompt-key","yes","allow-remote","help"]),VALUE_FLAGS=new Set(["target","scope","base","port","host"]);function parseFlags(e){const t={terms:[],json:!1,flags:{},targetList:[]};for(let s=0;s<e.length;s++){const n=e[s];if("--json"===n){t.json=!0;continue}if("-h"===n){t.flags.help=!0;continue}if(!n.startsWith("--")){t.terms.push(n);continue}const[r,o]=n.slice(2).split("="),i=r.trim();if(BOOL_FLAGS.has(i)){t.flags[i]=!0;continue}if(!VALUE_FLAGS.has(i))throw new Error(`unknown option: --${i}`);const a=void 0!==o?o:e[++s];if(void 0===a)throw new Error(`--${i} needs a value`);if("target"!==i)t.flags[i]=a;else for(const e of String(a).split(",")){const s=e.trim();s&&t.targetList.push(s)}}return t}function selectTargets(e,t,s){const n=[];let r,o=[];if(e.targetList.length){r="named";for(const t of e.targetList){const e=targets.getTarget(t);e?o.push(e.id):n.push(t)}o=[...new Set(o)]}else e.flags.all?(r="all",o=targets.targetIds()):(r="detected",o=[...install.detected({ctx:t})]);return{targets:o.map((e=>targets.getTarget(e))).filter(Boolean),ids:o,source:r,unknown:n}}function specOptsFor(e,t){const s={};if(e.flags.base&&(s.apiBase=String(e.flags.base)),e.flags["prompt-key"]&&(s.promptKey=!0),e.flags["with-key"]){const e=require("./credentials.js").keyStatus();if(!e.configured)return t.stderr.write("aegiscode mcp: --with-key was given but no key is configured. Run `aegiscode login` first, or export AEGIS_API_KEY.\n"),null;s.apiKey=e.key}return s}function scopeFor(e,t,s,{quiet:n=!1}={}){const r=String(t.flags.scope||"user").toLowerCase();if("user"!==r&&"workspace"!==r&&"project"!==r)return null;const o="project"===r?"workspace":r;return(e.scopes||["user"]).includes(o)?o:(n||s.stderr.write(`aegiscode mcp: ${e.label} has no ${o} config — it supports: ${(e.scopes||["user"]).join(", ")}\n`),null)}function homeShort(e,t){const s=t.home||t.env.HOME||t.env.USERPROFILE;return s&&e.startsWith(s)?`~${e.slice(s.length)}`:e}function statusWord(e){return e.error?"unreadable":e.installed?!1===e.serverExists?"BROKEN":e.serverUnverifiable?"host-resolved":"installed":e.exists?"not installed":"no config"}function statusText(e,t,s){const n=Math.max(9,...e.map((e=>statusWord(e).length))),r=[];for(const s of e)r.push(` ${statusWord(s).padEnd(n)} ${s.id.padEnd(14)} ${homeShort(s.file,t)}${"workspace"===s.scope?" (workspace)":""}`),s.error&&r.push(` ${" ".repeat(n)} ${s.error}`),!1===s.serverExists&&r.push(` ${" ".repeat(n)} the server this names is gone: ${s.serverPath}\n ${" ".repeat(n)} re-run \`aegiscode mcp install --target ${s.id}\``),s.serverUnverifiable&&r.push(` ${" ".repeat(n)} path is host-resolved (${s.serverPath}) — the editor\n ${" ".repeat(n)} expands it at load time, so it cannot be checked from here.`);return r.join("\n")+"\n"}function runList(e,t,s){const n=install.detected({ctx:t}),r=targets.TARGETS.map((e=>({id:e.id,label:e.label,kind:e.kind,scopes:e.scopes||["user"],docs:e.docs,verified:Boolean(e.verified),detected:n.has(e.id),files:(e.scopes||["user"]).map((s=>e.path(s,t))),note:e.note||null})));if(e.json)return s.stdout.write(`${JSON.stringify(r,null,2)}\n`),0;s.stdout.write(`${r.length} hosts AEGIS can appear in:\n\n`);for(const e of r)s.stdout.write(` ${e.id.padEnd(16)} ${e.label}${e.detected?" [present on this machine]":""}\n`),s.stdout.write(` ${" ".repeat(16)} ${homeShort(e.files[0],t)} (${e.scopes.join(", ")})\n`),e.note&&s.stdout.write(` ${" ".repeat(16)} ${e.note}\n`),e.verified||s.stdout.write(` ${" ".repeat(16)} ✗ NOT VERIFIED against this host's own docs — check ${e.docs} before relying on it\n`);return s.stdout.write("\n `aegiscode mcp install` with no --target configures every host detected above.\n API keys are NOT written unless you pass --with-key.\n"),0}function runStatus(e,t,s){const n=selectTargets(e,t,s);if(n.unknown.length)return s.stderr.write(`aegiscode mcp: unknown host${n.unknown.length>1?"s":""}: ${n.unknown.join(", ")} — run \`aegiscode mcp list\`\n`),2;const r=e.flags.scope?scopeFor(n.targets[0],e,s):null;if(e.flags.scope&&!r)return 2;const o=e.targetList.length?n.ids:[];let i=install.status(o,{ctx:t});if(e.flags.all||e.targetList.length||(i=i.filter((e=>e.exists||e.installed||e.error))),e.json)return s.stdout.write(`${JSON.stringify(i.map((e=>({id:e.id,label:e.label,scope:e.scope,file:e.file,exists:e.exists,installed:e.installed,state:statusWord(e),server_path:e.serverPath||null,server_exists:void 0===e.serverExists?null:e.serverExists,server_unverifiable:Boolean(e.serverUnverifiable),entry:e.entry,error:e.error,docs:e.docs,verified:e.verified}))),null,2)}\n`),0;if(!i.length)return s.stdout.write("aegiscode mcp: no editor configs found on this machine.\n `aegiscode mcp list` shows every host AEGIS supports,\n `aegiscode mcp install --target <id>` configures one.\n"),0;s.stdout.write(statusText(i,t,s));const a=i.filter((e=>!1===e.serverExists)).length,l=i.filter((e=>e.installed)).length,c=i.filter((e=>e.serverUnverifiable)).length;return s.stdout.write(`\n ${l} configured`+(c?`, ${c} host-resolved`:"")+(a?`, ${a} pointing at a missing server — re-run install`:"")+".\n"),0}function runInstall(e,t,s){const n=selectTargets(e,t,s);if(n.unknown.length)return s.stderr.write(`aegiscode mcp: unknown host${n.unknown.length>1?"s":""}: ${n.unknown.join(", ")} — run \`aegiscode mcp list\`\n`),2;if(!n.targets.length)return s.stderr.write("aegiscode mcp: no editor detected, so there is nothing to configure automatically.\n `aegiscode mcp list` shows the hosts AEGIS supports;\n `aegiscode mcp install --target <id>` names one explicitly.\n"),2;const r=specOptsFor(e,s);if(!r)return 2;if(e.flags["prompt-key"]&&n.targets.some((e=>!e.supportsKeyPrompt)))return s.stderr.write("aegiscode mcp: --prompt-key only works for VS Code, which is the only host with a secret-prompt mechanism. Drop it for the rest.\n"),2;const o=spec.resolveServer(),i=[];let a=0;for(const o of n.targets){const l="named"===n.source,c=scopeFor(o,e,s,{quiet:!l});if(!c){l?a++:(i.push({id:o.id,file:null,applied:!1,skipped:!0}),s.stdout.write(`aegiscode mcp: ${o.label} — skipped (no ${String(e.flags.scope||"user")} config)\n`));continue}const d=install.planTarget(o,c,{ctx:t,specOpts:r});if(d.error){s.stderr.write(`aegiscode mcp: ${o.label} — ${d.error.message}\n`),i.push({id:o.id,file:d.file,error:d.error.message,applied:!1}),a++;continue}if(!d.changed){s.stdout.write(`aegiscode mcp: ${o.label} — already configured (${homeShort(d.file,t)})\n`),i.push({id:o.id,file:d.file,applied:!1,changed:!1});continue}if(e.flags["dry-run"]){i.push({id:o.id,file:d.file,applied:!1,changed:!0,dryRun:!0}),s.stdout.write(`aegiscode mcp: ${o.label} — would write ${homeShort(d.file,t)}\n${indent(d.after)}\n`);continue}const p=install.apply(d,{withKey:Boolean(e.flags["with-key"])});i.push({id:o.id,file:d.file,applied:p.applied,changed:d.changed,backup:p.backupOf||null}),s.stdout.write(`aegiscode mcp: ${o.label} — wrote ${homeShort(d.file,t)}`+(p.backupOf?` (backup: ${homeShort(p.backupOf,t)})`:"")+"\n")}return e.flags["dry-run"]||a||!i.some((e=>e.applied))||(o.exists?s.stdout.write("\n Restart the editor (or its MCP host) to pick this up. Configured hosts\n spawn the AEGIS server themselves — nothing needs to keep running in a terminal.\n"):(s.stderr.write(`aegiscode mcp: WARNING — the server file does not exist at ${o.path}, so the editors just configured will not start it.\n`),a++)),e.flags["dry-run"]&&s.stdout.write("\naegiscode mcp: dry run — nothing was written.\n"),e.json&&s.stdout.write(`${JSON.stringify({changed:i,server:o.path,exists:o.exists},null,2)}\n`),a?1:0}function indent(e){return String(e||"").split("\n").filter(((e,t,s)=>!(t===s.length-1&&""===e))).map((e=>` ${e}`)).join("\n")}function runRemove(e,t,s){const n=selectTargets(e,t,s);if(n.unknown.length)return s.stderr.write(`aegiscode mcp: unknown host${n.unknown.length>1?"s":""}: ${n.unknown.join(", ")}\n`),2;const r=e.targetList.length||e.flags.all?n.ids:[],o={};e.flags.base&&(o.apiBase=String(e.flags.base));const i=install.status(r,{ctx:t,specOpts:o}).filter((e=>e.installed));let a=0;if(!i.length)return s.stdout.write("aegiscode mcp: nothing to remove — no config names an AEGIS server.\n"),e.json&&s.stdout.write(`${JSON.stringify({removed:[],changed:[]},null,2)}\n`),0;const l=[];for(const n of i){const r=targets.getTarget(n.id),i=install.planRemove(r,n.scope,{ctx:t,specOpts:o});if(i.error){s.stderr.write(`aegiscode mcp: ${n.label} — ${i.error.message}\n`),a++;continue}if(!i.changed){s.stdout.write(`aegiscode mcp: ${n.label} — nothing of ours in ${homeShort(i.file,t)}\n`);continue}if(e.flags["dry-run"]){l.push({id:n.id,file:i.file,dryRun:!0}),s.stdout.write(`aegiscode mcp: ${n.label} — would update ${homeShort(i.file,t)}\n`);continue}const c=install.apply(i);l.push({id:n.id,file:i.file,backup:c.backupOf||null}),s.stdout.write(`aegiscode mcp: ${n.label} — removed from ${homeShort(i.file,t)}`+(c.backupOf?` (backup: ${homeShort(c.backupOf,t)})`:"")+"\n")}return e.flags["dry-run"]&&s.stdout.write("\naegiscode mcp: dry run — nothing was written.\n"),e.json&&s.stdout.write(`${JSON.stringify({changed:l},null,2)}\n`),a?1:0}function runPrint(e,t,s){const n=e.terms[0]||e.targetList[0];if(!n)return s.stderr.write("aegiscode mcp print: name a host — `aegiscode mcp print vscode`\n"),2;const r=targets.getTarget(n);if(!r)return s.stderr.write(`aegiscode mcp print: unknown host "${n}" — run \`aegiscode mcp list\`\n`),2;const o={};e.flags.base&&(o.apiBase=String(e.flags.base)),e.flags["prompt-key"]&&(o.promptKey=!0);const i=spec.buildSpec(o),a=install.renderEntry(r,i),l=r.path(r.scopes?r.scopes[0]:"user",t);return"mcp-toml"===r.kind?(s.stdout.write(`# ${l}\n[${r.container}.${a.name||"aegis"}]\n${a.join("\n")}\n`),0):e.json?(s.stdout.write(`${JSON.stringify({file:l,container:r.container,entry:a},null,2)}\n`),0):(s.stdout.write(`# ${l}\n${JSON.stringify({[r.container]:{aegis:a}},null,2)}\n`),e.flags["prompt-key"]&&s.stdout.write(`\n# VS Code also needs this in the same file so the prompt can resolve:\n${JSON.stringify({inputs:[spec.vscodeKeyInput()]},null,2)}\n`),0)}function runChild(e,t,s){return new Promise((n=>{const r=spawn(process.execPath,[e,...t],{stdio:"inherit"});r.on("error",(t=>{s.stderr.write(`aegiscode mcp: could not start ${e}: ${t.message}\n`),n(1)})),r.on("exit",((e,t)=>{n(t?0:null===e?1:e)}))}))}function runServe(e,t,s){const n=spec.resolveServer();return n.exists?(s.stderr.write(`aegiscode mcp: serving ${n.path} on stdio.\n Editors start this themselves — you only need it to test one by hand.\n`),runChild(n.path,[],s)):(s.stderr.write(`aegiscode mcp serve: no server found at ${n.path}.\n Looked in:\n ${n.candidates.join("\n ")}\n`),2)}function runShim(e,t,s){const n=resolveShared(path.join("hosts","openai-shim.js")),r=[];return e.flags.port&&r.push("--port",String(e.flags.port)),e.flags.host&&r.push("--host",String(e.flags.host)),e.flags["allow-remote"]&&r.push("--allow-remote"),runChild(n,r,s)}async function runMcpCommand(e,t,s={}){const n=s.stdout||process.stdout,r=s.stderr||process.stderr,o={stdout:n,stderr:r};if(limits.armed())return limits.refuse();let i;try{i=parseFlags(t||[])}catch(e){return r.write(`aegiscode mcp: ${e.message}\n`),2}if(i.json=Boolean(s.json||i.json),o.json=i.json,"help"===e||!SUBCOMMANDS.has(e)||i.flags.help)return n.write(USAGE),"help"===e||i.flags.help?0:2;if("serve"===e||"shim"===e){const t=install.hostCtx({cwd:s.cwd||process.cwd(),home:s.home||null});return"serve"===e?runServe(i,t,o):runShim(i,t,o)}if("list"===e)return runList(i,install.hostCtx({cwd:s.cwd||process.cwd(),home:s.home||null}),o);if("print"===e)return runPrint(i,install.hostCtx({cwd:s.cwd||process.cwd(),home:s.home||null}),o);const a=install.hostCtx({cwd:s.cwd||process.cwd(),home:s.home||null});return"install"===e?runInstall(i,a,o):"remove"===e?runRemove(i,a,o):"status"===e?runStatus(i,a,o):2}module.exports={runMcpCommand:runMcpCommand,parseFlags:parseFlags,selectTargets:selectTargets,USAGE:USAGE,SUBCOMMANDS:SUBCOMMANDS};
3
+ "use strict";const path=require("node:path"),{spawn:spawn}=require("node:child_process"),{resolveShared:resolveShared}=require("./sharedpaths.js"),limits=require("./limits.js"),install=require(resolveShared(path.join("hosts","install.js"))),targets=require(resolveShared(path.join("hosts","targets.js"))),spec=require(resolveShared(path.join("hosts","spec.js"))),SUBCOMMANDS=new Set(["install","remove","status","list","print","serve","shim","help"]),USAGE="aegiscode mcp — put AEGIS inside your editor.\n\nUsage:\n aegiscode mcp install [options] write the editor config (merges, never replaces)\n aegiscode mcp status [options] which hosts are configured, and do they still work\n aegiscode mcp list every supported host, its config file and its docs\n aegiscode mcp print <host> show the entry that would be written, touch nothing\n aegiscode mcp remove [options] take our entry out again\n aegiscode mcp serve run the stdio MCP server (editors spawn this themselves)\n aegiscode mcp shim [options] run the OpenAI-compatible endpoint on loopback\n\nTargets:\n --target <id> one host, repeatable and comma-separated (see `aegiscode mcp list`)\n --all every supported host, not just the ones detected\n --scope <s> user (default) or workspace — workspace writes into the\n current directory, which is committed in many projects\n\nInstall options:\n --dry-run print what would change, write nothing\n --with-key embed the resolved API key in the config file. Off by\n default: these files are plain and often world-readable, and\n the server already finds a key from the environment, the\n 0600 store, or ~/.aegiscode/.env\n --prompt-key VS Code only: reference its own secret prompt instead of\n storing a value anywhere\n --base <url> API base to record (default $AEGIS_API_BASE or aegiscloud.org)\n\nShim options:\n --port <n> default 8787\n --host <addr> default 127.0.0.1; any non-loopback address also requires\n --allow-remote ... this flag, because the endpoint spends your tokens\n\nOptions:\n --json machine-readable output\n -h, --help this text\n",BOOL_FLAGS=new Set(["json","all","dry-run","with-key","prompt-key","yes","allow-remote","help"]),VALUE_FLAGS=new Set(["target","scope","base","port","host"]);function parseFlags(e){const t={terms:[],json:!1,flags:{},targetList:[]};for(let s=0;s<e.length;s++){const n=e[s];if("--json"===n){t.json=!0;continue}if("-h"===n){t.flags.help=!0;continue}if(!n.startsWith("--")){t.terms.push(n);continue}const[r,o]=n.slice(2).split("="),i=r.trim();if(BOOL_FLAGS.has(i)){t.flags[i]=!0;continue}if(!VALUE_FLAGS.has(i))throw new Error(`unknown option: --${i}`);const a=void 0!==o?o:e[++s];if(void 0===a)throw new Error(`--${i} needs a value`);if("target"!==i)t.flags[i]=a;else for(const e of String(a).split(",")){const s=e.trim();s&&t.targetList.push(s)}}return t}function selectTargets(e,t,s){const n=[];let r,o=[];if(e.targetList.length){r="named";for(const t of e.targetList){const e=targets.getTarget(t);e?o.push(e.id):n.push(t)}o=[...new Set(o)]}else e.flags.all?(r="all",o=targets.targetIds()):(r="detected",o=[...install.detected({ctx:t})]);return{targets:o.map(e=>targets.getTarget(e)).filter(Boolean),ids:o,source:r,unknown:n}}function specOptsFor(e,t){const s={};if(e.flags.base&&(s.apiBase=String(e.flags.base)),e.flags["prompt-key"]&&(s.promptKey=!0),e.flags["with-key"]){const e=require("./credentials.js").keyStatus();if(!e.configured)return t.stderr.write("aegiscode mcp: --with-key was given but no key is configured. Run `aegiscode login` first, or export AEGIS_API_KEY.\n"),null;s.apiKey=e.key}return s}function scopeFor(e,t,s,{quiet:n=!1}={}){const r=String(t.flags.scope||"user").toLowerCase();if("user"!==r&&"workspace"!==r&&"project"!==r)return null;const o="project"===r?"workspace":r;return(e.scopes||["user"]).includes(o)?o:(n||s.stderr.write(`aegiscode mcp: ${e.label} has no ${o} config — it supports: ${(e.scopes||["user"]).join(", ")}\n`),null)}function homeShort(e,t){const s=t.home||t.env.HOME||t.env.USERPROFILE;return s&&e.startsWith(s)?`~${e.slice(s.length)}`:e}function statusWord(e){return e.error?"unreadable":e.installed?!1===e.serverExists?"BROKEN":e.serverUnverifiable?"host-resolved":"installed":e.exists?"not installed":"no config"}function statusText(e,t,s){const n=Math.max(9,...e.map(e=>statusWord(e).length)),r=[];for(const s of e)r.push(` ${statusWord(s).padEnd(n)} ${s.id.padEnd(14)} ${homeShort(s.file,t)}${"workspace"===s.scope?" (workspace)":""}`),s.error&&r.push(` ${" ".repeat(n)} ${s.error}`),!1===s.serverExists&&r.push(` ${" ".repeat(n)} the server this names is gone: ${s.serverPath}\n ${" ".repeat(n)} re-run \`aegiscode mcp install --target ${s.id}\``),s.serverUnverifiable&&r.push(` ${" ".repeat(n)} path is host-resolved (${s.serverPath}) — the editor\n ${" ".repeat(n)} expands it at load time, so it cannot be checked from here.`);return r.join("\n")+"\n"}function runList(e,t,s){const n=install.detected({ctx:t}),r=targets.TARGETS.map(e=>({id:e.id,label:e.label,kind:e.kind,scopes:e.scopes||["user"],docs:e.docs,verified:Boolean(e.verified),detected:n.has(e.id),files:(e.scopes||["user"]).map(s=>e.path(s,t)),note:e.note||null}));if(e.json)return s.stdout.write(`${JSON.stringify(r,null,2)}\n`),0;s.stdout.write(`${r.length} hosts AEGIS can appear in:\n\n`);for(const e of r)s.stdout.write(` ${e.id.padEnd(16)} ${e.label}${e.detected?" [present on this machine]":""}\n`),s.stdout.write(` ${" ".repeat(16)} ${homeShort(e.files[0],t)} (${e.scopes.join(", ")})\n`),e.note&&s.stdout.write(` ${" ".repeat(16)} ${e.note}\n`),e.verified||s.stdout.write(` ${" ".repeat(16)} ✗ NOT VERIFIED against this host's own docs — check ${e.docs} before relying on it\n`);return s.stdout.write("\n `aegiscode mcp install` with no --target configures every host detected above.\n API keys are NOT written unless you pass --with-key.\n"),0}function runStatus(e,t,s){const n=selectTargets(e,t,s);if(n.unknown.length)return s.stderr.write(`aegiscode mcp: unknown host${n.unknown.length>1?"s":""}: ${n.unknown.join(", ")} — run \`aegiscode mcp list\`\n`),2;const r=e.flags.scope?scopeFor(n.targets[0],e,s):null;if(e.flags.scope&&!r)return 2;const o=e.targetList.length?n.ids:[];let i=install.status(o,{ctx:t});if(e.flags.all||e.targetList.length||(i=i.filter(e=>e.exists||e.installed||e.error)),e.json)return s.stdout.write(`${JSON.stringify(i.map(e=>({id:e.id,label:e.label,scope:e.scope,file:e.file,exists:e.exists,installed:e.installed,state:statusWord(e),server_path:e.serverPath||null,server_exists:void 0===e.serverExists?null:e.serverExists,server_unverifiable:Boolean(e.serverUnverifiable),entry:e.entry,error:e.error,docs:e.docs,verified:e.verified})),null,2)}\n`),0;if(!i.length)return s.stdout.write("aegiscode mcp: no editor configs found on this machine.\n `aegiscode mcp list` shows every host AEGIS supports,\n `aegiscode mcp install --target <id>` configures one.\n"),0;s.stdout.write(statusText(i,t,s));const a=i.filter(e=>!1===e.serverExists).length,l=i.filter(e=>e.installed).length,c=i.filter(e=>e.serverUnverifiable).length;return s.stdout.write(`\n ${l} configured`+(c?`, ${c} host-resolved`:"")+(a?`, ${a} pointing at a missing server — re-run install`:"")+".\n"),0}function runInstall(e,t,s){const n=selectTargets(e,t,s);if(n.unknown.length)return s.stderr.write(`aegiscode mcp: unknown host${n.unknown.length>1?"s":""}: ${n.unknown.join(", ")} — run \`aegiscode mcp list\`\n`),2;if(!n.targets.length)return s.stderr.write("aegiscode mcp: no editor detected, so there is nothing to configure automatically.\n `aegiscode mcp list` shows the hosts AEGIS supports;\n `aegiscode mcp install --target <id>` names one explicitly.\n"),2;const r=specOptsFor(e,s);if(!r)return 2;if(e.flags["prompt-key"]&&n.targets.some(e=>!e.supportsKeyPrompt))return s.stderr.write("aegiscode mcp: --prompt-key only works for VS Code, which is the only host with a secret-prompt mechanism. Drop it for the rest.\n"),2;const o=spec.resolveServer(),i=[];let a=0;for(const o of n.targets){const l="named"===n.source,c=scopeFor(o,e,s,{quiet:!l});if(!c){l?a++:(i.push({id:o.id,file:null,applied:!1,skipped:!0}),s.stdout.write(`aegiscode mcp: ${o.label} — skipped (no ${String(e.flags.scope||"user")} config)\n`));continue}const d=install.planTarget(o,c,{ctx:t,specOpts:r});if(d.error){s.stderr.write(`aegiscode mcp: ${o.label} — ${d.error.message}\n`),i.push({id:o.id,file:d.file,error:d.error.message,applied:!1}),a++;continue}if(!d.changed){s.stdout.write(`aegiscode mcp: ${o.label} — already configured (${homeShort(d.file,t)})\n`),i.push({id:o.id,file:d.file,applied:!1,changed:!1});continue}if(e.flags["dry-run"]){i.push({id:o.id,file:d.file,applied:!1,changed:!0,dryRun:!0}),s.stdout.write(`aegiscode mcp: ${o.label} — would write ${homeShort(d.file,t)}\n${indent(d.after)}\n`);continue}const p=install.apply(d,{withKey:Boolean(e.flags["with-key"])});i.push({id:o.id,file:d.file,applied:p.applied,changed:d.changed,backup:p.backupOf||null}),s.stdout.write(`aegiscode mcp: ${o.label} — wrote ${homeShort(d.file,t)}`+(p.backupOf?` (backup: ${homeShort(p.backupOf,t)})`:"")+"\n")}return e.flags["dry-run"]||a||!i.some(e=>e.applied)||(o.exists?s.stdout.write("\n Restart the editor (or its MCP host) to pick this up. Configured hosts\n spawn the AEGIS server themselves — nothing needs to keep running in a terminal.\n"):(s.stderr.write(`aegiscode mcp: WARNING — the server file does not exist at ${o.path}, so the editors just configured will not start it.\n`),a++)),e.flags["dry-run"]&&s.stdout.write("\naegiscode mcp: dry run — nothing was written.\n"),e.json&&s.stdout.write(`${JSON.stringify({changed:i,server:o.path,exists:o.exists},null,2)}\n`),a?1:0}function indent(e){return String(e||"").split("\n").filter((e,t,s)=>!(t===s.length-1&&""===e)).map(e=>` ${e}`).join("\n")}function runRemove(e,t,s){const n=selectTargets(e,t,s);if(n.unknown.length)return s.stderr.write(`aegiscode mcp: unknown host${n.unknown.length>1?"s":""}: ${n.unknown.join(", ")}\n`),2;const r=e.targetList.length||e.flags.all?n.ids:[],o={};e.flags.base&&(o.apiBase=String(e.flags.base));const i=install.status(r,{ctx:t,specOpts:o}).filter(e=>e.installed);let a=0;if(!i.length)return s.stdout.write("aegiscode mcp: nothing to remove — no config names an AEGIS server.\n"),e.json&&s.stdout.write(`${JSON.stringify({removed:[],changed:[]},null,2)}\n`),0;const l=[];for(const n of i){const r=targets.getTarget(n.id),i=install.planRemove(r,n.scope,{ctx:t,specOpts:o});if(i.error){s.stderr.write(`aegiscode mcp: ${n.label} — ${i.error.message}\n`),a++;continue}if(!i.changed){s.stdout.write(`aegiscode mcp: ${n.label} — nothing of ours in ${homeShort(i.file,t)}\n`);continue}if(e.flags["dry-run"]){l.push({id:n.id,file:i.file,dryRun:!0}),s.stdout.write(`aegiscode mcp: ${n.label} — would update ${homeShort(i.file,t)}\n`);continue}const c=install.apply(i);l.push({id:n.id,file:i.file,backup:c.backupOf||null}),s.stdout.write(`aegiscode mcp: ${n.label} — removed from ${homeShort(i.file,t)}`+(c.backupOf?` (backup: ${homeShort(c.backupOf,t)})`:"")+"\n")}return e.flags["dry-run"]&&s.stdout.write("\naegiscode mcp: dry run — nothing was written.\n"),e.json&&s.stdout.write(`${JSON.stringify({changed:l},null,2)}\n`),a?1:0}function runPrint(e,t,s){const n=e.terms[0]||e.targetList[0];if(!n)return s.stderr.write("aegiscode mcp print: name a host — `aegiscode mcp print vscode`\n"),2;const r=targets.getTarget(n);if(!r)return s.stderr.write(`aegiscode mcp print: unknown host "${n}" — run \`aegiscode mcp list\`\n`),2;const o={};e.flags.base&&(o.apiBase=String(e.flags.base)),e.flags["prompt-key"]&&(o.promptKey=!0);const i=spec.buildSpec(o),a=install.renderEntry(r,i),l=r.path(r.scopes?r.scopes[0]:"user",t);return"mcp-toml"===r.kind?(s.stdout.write(`# ${l}\n[${r.container}.${a.name||"aegis"}]\n${a.join("\n")}\n`),0):e.json?(s.stdout.write(`${JSON.stringify({file:l,container:r.container,entry:a},null,2)}\n`),0):(s.stdout.write(`# ${l}\n${JSON.stringify({[r.container]:{aegis:a}},null,2)}\n`),e.flags["prompt-key"]&&s.stdout.write(`\n# VS Code also needs this in the same file so the prompt can resolve:\n${JSON.stringify({inputs:[spec.vscodeKeyInput()]},null,2)}\n`),0)}function runChild(e,t,s){return new Promise(n=>{const r=spawn(process.execPath,[e,...t],{stdio:"inherit"});r.on("error",t=>{s.stderr.write(`aegiscode mcp: could not start ${e}: ${t.message}\n`),n(1)}),r.on("exit",(e,t)=>{n(t?0:null===e?1:e)})})}function runServe(e,t,s){const n=spec.resolveServer();return n.exists?(s.stderr.write(`aegiscode mcp: serving ${n.path} on stdio.\n Editors start this themselves — you only need it to test one by hand.\n`),runChild(n.path,[],s)):(s.stderr.write(`aegiscode mcp serve: no server found at ${n.path}.\n Looked in:\n ${n.candidates.join("\n ")}\n`),2)}function runShim(e,t,s){const n=resolveShared(path.join("hosts","openai-shim.js")),r=[];return e.flags.port&&r.push("--port",String(e.flags.port)),e.flags.host&&r.push("--host",String(e.flags.host)),e.flags["allow-remote"]&&r.push("--allow-remote"),runChild(n,r,s)}async function runMcpCommand(e,t,s={}){const n=s.stdout||process.stdout,r=s.stderr||process.stderr,o={stdout:n,stderr:r};if(limits.armed())return limits.refuse();let i;try{i=parseFlags(t||[])}catch(e){return r.write(`aegiscode mcp: ${e.message}\n`),2}if(i.json=Boolean(s.json||i.json),o.json=i.json,"help"===e||!SUBCOMMANDS.has(e)||i.flags.help)return n.write(USAGE),"help"===e||i.flags.help?0:2;if("serve"===e||"shim"===e){const t=install.hostCtx({cwd:s.cwd||process.cwd(),home:s.home||null});return"serve"===e?runServe(i,t,o):runShim(i,t,o)}if("list"===e)return runList(i,install.hostCtx({cwd:s.cwd||process.cwd(),home:s.home||null}),o);if("print"===e)return runPrint(i,install.hostCtx({cwd:s.cwd||process.cwd(),home:s.home||null}),o);const a=install.hostCtx({cwd:s.cwd||process.cwd(),home:s.home||null});return"install"===e?runInstall(i,a,o):"remove"===e?runRemove(i,a,o):"status"===e?runStatus(i,a,o):2}module.exports={runMcpCommand:runMcpCommand,parseFlags:parseFlags,selectTargets:selectTargets,USAGE:USAGE,SUBCOMMANDS:SUBCOMMANDS};