aegisone 1.0.64 → 1.0.65

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (363) hide show
  1. package/README.md +1 -1
  2. package/bin/aegis.js +1 -1
  3. package/package.json +1 -1
  4. package/scripts/bump.mjs +1 -1
  5. package/scripts/bundle.js +1 -1
  6. package/scripts/postinstall.mjs +1 -1
  7. package/scripts/predist.mjs +1 -1
  8. package/src/child.js +1 -1
  9. package/src/dispatch.js +1 -1
  10. package/src/doctor.js +1 -1
  11. package/src/probes.js +1 -1
  12. package/src/productupdate.js +1 -1
  13. package/src/protocol.js +1 -1
  14. package/src/release.js +1 -1
  15. package/src/selfhost.js +1 -1
  16. package/vendor/cli/package.json +1 -1
  17. package/vendor/cli/scripts/check.mjs +1 -1
  18. package/vendor/cli/scripts/demo.mjs +1 -1
  19. package/vendor/cli/scripts/postinstall.mjs +1 -1
  20. package/vendor/cli/scripts/predist.mjs +1 -1
  21. package/vendor/cli/scripts/runtests.mjs +1 -1
  22. package/vendor/cli/src/app.js +1 -1
  23. package/vendor/cli/src/art.js +1 -1
  24. package/vendor/cli/src/chatflow.js +1 -1
  25. package/vendor/cli/src/checkpoint.js +1 -1
  26. package/vendor/cli/src/clipboard.js +1 -1
  27. package/vendor/cli/src/cloudsync.js +1 -1
  28. package/vendor/cli/src/commands.js +2 -2
  29. package/vendor/cli/src/config.js +1 -1
  30. package/vendor/cli/src/connect.js +1 -1
  31. package/vendor/cli/src/devrun.js +1 -1
  32. package/vendor/cli/src/diff.js +1 -1
  33. package/vendor/cli/src/diffview.js +1 -1
  34. package/vendor/cli/src/dream.js +1 -1
  35. package/vendor/cli/src/engine.js +1 -1
  36. package/vendor/cli/src/events.js +1 -1
  37. package/vendor/cli/src/export.js +1 -1
  38. package/vendor/cli/src/fingerprint.js +1 -1
  39. package/vendor/cli/src/format.js +1 -1
  40. package/vendor/cli/src/fuzzy.js +1 -1
  41. package/vendor/cli/src/history.js +1 -1
  42. package/vendor/cli/src/init.js +1 -1
  43. package/vendor/cli/src/markdown.js +1 -1
  44. package/vendor/cli/src/models.js +1 -1
  45. package/vendor/cli/src/overlays.js +1 -1
  46. package/vendor/cli/src/panels.js +1 -1
  47. package/vendor/cli/src/ping.js +1 -1
  48. package/vendor/cli/src/presence.js +1 -1
  49. package/vendor/cli/src/render.js +1 -1
  50. package/vendor/cli/src/screen.js +1 -1
  51. package/vendor/cli/src/screens.js +1 -1
  52. package/vendor/cli/src/secret.js +1 -1
  53. package/vendor/cli/src/securefs.js +1 -1
  54. package/vendor/cli/src/settings.js +1 -1
  55. package/vendor/cli/src/signup.js +1 -1
  56. package/vendor/cli/src/summarize.js +1 -1
  57. package/vendor/cli/src/sysdiag.js +1 -1
  58. package/vendor/cli/src/theme.js +1 -1
  59. package/vendor/cli/src/title.js +1 -1
  60. package/vendor/cli/src/todos.js +1 -1
  61. package/vendor/cli/src/tokens.js +1 -1
  62. package/vendor/cli/src/topup.js +1 -1
  63. package/vendor/cli/src/update.js +1 -1
  64. package/vendor/cli/vendor/client/aegis.js +1 -1
  65. package/vendor/cli/vendor/client/attest.js +1 -1
  66. package/vendor/cli/vendor/client/authorship-key.js +1 -1
  67. package/vendor/cli/vendor/client/auto-provision.js +1 -1
  68. package/vendor/cli/vendor/client/brain-catalog.js +1 -1
  69. package/vendor/cli/vendor/client/byok-catalog.js +1 -1
  70. package/vendor/cli/vendor/client/catalog-client.js +1 -1
  71. package/vendor/cli/vendor/client/conversation-export.js +1 -1
  72. package/vendor/cli/vendor/client/credentials.js +1 -1
  73. package/vendor/cli/vendor/client/credits.js +1 -1
  74. package/vendor/cli/vendor/client/drive-connect.js +1 -1
  75. package/vendor/cli/vendor/client/env-file.js +1 -1
  76. package/vendor/cli/vendor/client/fingerprint.js +1 -1
  77. package/vendor/cli/vendor/client/foreign-memory.js +1 -1
  78. package/vendor/cli/vendor/client/foreign-sessions.js +1 -1
  79. package/vendor/cli/vendor/client/google-signin.js +1 -1
  80. package/vendor/cli/vendor/client/hooks.js +1 -1
  81. package/vendor/cli/vendor/client/model-discovery.js +1 -1
  82. package/vendor/cli/vendor/client/model-sync.js +1 -1
  83. package/vendor/cli/vendor/client/naming.js +1 -1
  84. package/vendor/cli/vendor/client/platform.js +1 -1
  85. package/vendor/cli/vendor/client/prefs.js +1 -1
  86. package/vendor/cli/vendor/client/presence.js +1 -1
  87. package/vendor/cli/vendor/client/record-vault.js +2 -2
  88. package/vendor/cli/vendor/client/session-search.js +1 -1
  89. package/vendor/cli/vendor/client/session-store.js +1 -1
  90. package/vendor/cli/vendor/client/skills.js +1 -1
  91. package/vendor/cli/vendor/client/topup.js +1 -1
  92. package/vendor/cli/vendor/client/touch.js +1 -1
  93. package/vendor/cli/vendor/client/update.js +1 -1
  94. package/vendor/cli/vendor/client/user-models.js +1 -1
  95. package/vendor/cli/vendor/desktop/lib/local/attachments.js +1 -1
  96. package/vendor/cli/vendor/desktop/lib/local/autonomous.js +1 -1
  97. package/vendor/cli/vendor/desktop/lib/local/claude-pro.js +1 -1
  98. package/vendor/cli/vendor/desktop/lib/local/context.js +1 -1
  99. package/vendor/cli/vendor/desktop/lib/local/engine.js +1 -1
  100. package/vendor/cli/vendor/desktop/lib/local/entitlement.js +1 -1
  101. package/vendor/cli/vendor/desktop/lib/local/integrity.js +1 -1
  102. package/vendor/cli/vendor/desktop/lib/local/local.js +1 -1
  103. package/vendor/cli/vendor/desktop/lib/local/perm-rules.js +5 -0
  104. package/vendor/cli/vendor/desktop/lib/local/perm-store.js +5 -0
  105. package/vendor/cli/vendor/desktop/lib/local/perm-write.js +5 -0
  106. package/vendor/cli/vendor/desktop/lib/local/pro-sessions.js +3 -1
  107. package/vendor/cli/vendor/desktop/lib/local/prompt.js +1 -1
  108. package/vendor/cli/vendor/desktop/lib/local/queue.js +1 -1
  109. package/vendor/cli/vendor/desktop/lib/local/repeat-guard.js +1 -1
  110. package/vendor/cli/vendor/desktop/lib/local/session-rounds.js +1 -1
  111. package/vendor/cli/vendor/desktop/lib/local/spill.js +1 -1
  112. package/vendor/cli/vendor/desktop/lib/local/turn-guard.js +1 -1
  113. package/vendor/cli/vendor/desktop/lib/local/verify-stop.js +1 -1
  114. package/vendor/cli/vendor/desktop/lib/local/worktree-lock.js +1 -1
  115. package/vendor/cli/vendor/desktop/lib/settings.js +1 -1
  116. package/vendor/cli/vendor/desktop/renderer/usage.js +1 -1
  117. package/vendor/cli/vendor/hosts/install.js +1 -1
  118. package/vendor/cli/vendor/hosts/openai-shim.js +1 -1
  119. package/vendor/cli/vendor/hosts/spec.js +1 -1
  120. package/vendor/cli/vendor/hosts/targets.js +1 -1
  121. package/vendor/cli/vendor/mcp/admission.js +1 -1
  122. package/vendor/cli/vendor/mcp/server.js +1 -1
  123. package/vendor/cli/vendor/mcp/tools.js +1 -1
  124. package/vendor/cli/vendor/one/src/child.js +1 -1
  125. package/vendor/cli/vendor/one/src/protocol.js +1 -1
  126. package/vendor/cli/vendor/one/src/selfhost.js +1 -1
  127. package/vendor/desktop/bin/aegis.js +1 -1
  128. package/vendor/desktop/lib/auto.js +1 -1
  129. package/vendor/desktop/lib/avatar/companion.js +1 -1
  130. package/vendor/desktop/lib/avatar/cosmetics.js +1 -1
  131. package/vendor/desktop/lib/avatar/holder-turn.js +1 -1
  132. package/vendor/desktop/lib/avatar/holders.js +1 -1
  133. package/vendor/desktop/lib/avatar/identity.js +1 -1
  134. package/vendor/desktop/lib/avatar/level.js +1 -1
  135. package/vendor/desktop/lib/avatar/mirror.js +1 -1
  136. package/vendor/desktop/lib/avatar/persona.js +1 -1
  137. package/vendor/desktop/lib/avatar/profile.js +1 -1
  138. package/vendor/desktop/lib/avatar/register.js +1 -1
  139. package/vendor/desktop/lib/avatar/store.js +1 -1
  140. package/vendor/desktop/lib/avatar/transfer.js +1 -1
  141. package/vendor/desktop/lib/avatar/turn.js +1 -1
  142. package/vendor/desktop/lib/avatar/voice.js +1 -1
  143. package/vendor/desktop/lib/avatar/xp.js +1 -1
  144. package/vendor/desktop/lib/deep-link.js +1 -1
  145. package/vendor/desktop/lib/local/attachments.js +1 -1
  146. package/vendor/desktop/lib/local/autonomous.js +1 -1
  147. package/vendor/desktop/lib/local/claude-pro.js +1 -1
  148. package/vendor/desktop/lib/local/cli-face.js +1 -1
  149. package/vendor/desktop/lib/local/context.js +1 -1
  150. package/vendor/desktop/lib/local/engine.js +1 -1
  151. package/vendor/desktop/lib/local/entitlement.js +1 -1
  152. package/vendor/desktop/lib/local/integrity.js +1 -1
  153. package/vendor/desktop/lib/local/local.js +1 -1
  154. package/vendor/desktop/lib/local/perm-rules.js +5 -0
  155. package/vendor/desktop/lib/local/perm-store.js +5 -0
  156. package/vendor/desktop/lib/local/perm-write.js +5 -0
  157. package/vendor/desktop/lib/local/pro-sessions.js +3 -1
  158. package/vendor/desktop/lib/local/prompt.js +1 -1
  159. package/vendor/desktop/lib/local/pty-host.js +1 -1
  160. package/vendor/desktop/lib/local/queue.js +1 -1
  161. package/vendor/desktop/lib/local/repeat-guard.js +1 -1
  162. package/vendor/desktop/lib/local/session-rounds.js +1 -1
  163. package/vendor/desktop/lib/local/spill.js +1 -1
  164. package/vendor/desktop/lib/local/telemetry.js +1 -1
  165. package/vendor/desktop/lib/local/turn-guard.js +1 -1
  166. package/vendor/desktop/lib/local/verify-stop.js +1 -1
  167. package/vendor/desktop/lib/local/worktree-lock.js +1 -1
  168. package/vendor/desktop/lib/provider-key-mirror.js +1 -1
  169. package/vendor/desktop/lib/quick-launcher.js +1 -1
  170. package/vendor/desktop/lib/settings.js +1 -1
  171. package/vendor/desktop/lib/skills-host.js +1 -1
  172. package/vendor/desktop/lib/speech-host.js +1 -1
  173. package/vendor/desktop/lib/sync/memory-store.js +1 -1
  174. package/vendor/desktop/lib/sync/persist-gate.js +1 -1
  175. package/vendor/desktop/lib/window-state.js +1 -1
  176. package/vendor/desktop/package.json +1 -1
  177. package/vendor/desktop/preload.js +3 -1
  178. package/vendor/desktop/renderer/app.js +3 -3
  179. package/vendor/desktop/renderer/avatar/assemble.js +1 -1
  180. package/vendor/desktop/renderer/avatar/avatar.js +1 -1
  181. package/vendor/desktop/renderer/avatar/cards.js +1 -1
  182. package/vendor/desktop/renderer/avatar/hud.js +1 -1
  183. package/vendor/desktop/renderer/avatar/pane.js +1 -1
  184. package/vendor/desktop/renderer/avatar/parts.js +1 -1
  185. package/vendor/desktop/renderer/commands.js +1 -1
  186. package/vendor/desktop/renderer/companion.js +1 -1
  187. package/vendor/desktop/renderer/composer-triggers.js +1 -1
  188. package/vendor/desktop/renderer/dictation.js +1 -1
  189. package/vendor/desktop/renderer/diff.js +1 -1
  190. package/vendor/desktop/renderer/diffview.js +1 -1
  191. package/vendor/desktop/renderer/fingerprint.js +2 -2
  192. package/vendor/desktop/renderer/index.html +10 -4
  193. package/vendor/desktop/renderer/library.js +1 -1
  194. package/vendor/desktop/renderer/markdown.js +1 -1
  195. package/vendor/desktop/renderer/palette-filter.js +1 -1
  196. package/vendor/desktop/renderer/provider-toolbar.js +1 -1
  197. package/vendor/desktop/renderer/providers.js +1 -1
  198. package/vendor/desktop/renderer/pty-frame.css +35 -0
  199. package/vendor/desktop/renderer/pty-frame.html +47 -0
  200. package/vendor/desktop/renderer/pty-panel.js +1 -1
  201. package/vendor/desktop/renderer/quick.js +1 -1
  202. package/vendor/desktop/renderer/settings-skills.js +1 -1
  203. package/vendor/desktop/renderer/shortcuts.js +1 -1
  204. package/vendor/desktop/renderer/stream-policy.js +1 -1
  205. package/vendor/desktop/renderer/style.css +22 -0
  206. package/vendor/desktop/renderer/transcript-view.js +1 -1
  207. package/vendor/desktop/renderer/usage.js +1 -1
  208. package/vendor/desktop/renderer/welcome-rows.js +1 -1
  209. package/vendor/desktop/vendor/aegis.js +1 -1
  210. package/vendor/desktop/vendor/attest.js +1 -1
  211. package/vendor/desktop/vendor/authorship-key.js +1 -1
  212. package/vendor/desktop/vendor/auto-provision.js +1 -1
  213. package/vendor/desktop/vendor/brain-catalog.js +1 -1
  214. package/vendor/desktop/vendor/byok-catalog.js +1 -1
  215. package/vendor/desktop/vendor/catalog-client.js +1 -1
  216. package/vendor/desktop/vendor/conversation-export.js +1 -1
  217. package/vendor/desktop/vendor/credentials.js +1 -1
  218. package/vendor/desktop/vendor/credits.js +1 -1
  219. package/vendor/desktop/vendor/drive-connect.js +1 -1
  220. package/vendor/desktop/vendor/env-file.js +1 -1
  221. package/vendor/desktop/vendor/faces/cli/bin/aegiscode.js +2 -2
  222. package/vendor/desktop/vendor/faces/cli/package.json +1 -1
  223. package/vendor/desktop/vendor/faces/cli/scripts/check.mjs +1 -1
  224. package/vendor/desktop/vendor/faces/cli/scripts/demo.mjs +1 -1
  225. package/vendor/desktop/vendor/faces/cli/scripts/postinstall.mjs +1 -1
  226. package/vendor/desktop/vendor/faces/cli/scripts/predist.mjs +1 -1
  227. package/vendor/desktop/vendor/faces/cli/scripts/runtests.mjs +1 -1
  228. package/vendor/desktop/vendor/faces/cli/src/app.js +1 -1
  229. package/vendor/desktop/vendor/faces/cli/src/art.js +1 -1
  230. package/vendor/desktop/vendor/faces/cli/src/autonomous.js +1 -1
  231. package/vendor/desktop/vendor/faces/cli/src/caps.js +1 -1
  232. package/vendor/desktop/vendor/faces/cli/src/chatflow.js +1 -1
  233. package/vendor/desktop/vendor/faces/cli/src/checkpoint.js +1 -1
  234. package/vendor/desktop/vendor/faces/cli/src/clipboard.js +1 -1
  235. package/vendor/desktop/vendor/faces/cli/src/cloudsync.js +1 -1
  236. package/vendor/desktop/vendor/faces/cli/src/commands.js +2 -2
  237. package/vendor/desktop/vendor/faces/cli/src/config.js +1 -1
  238. package/vendor/desktop/vendor/faces/cli/src/connect.js +1 -1
  239. package/vendor/desktop/vendor/faces/cli/src/devrun.js +1 -1
  240. package/vendor/desktop/vendor/faces/cli/src/diff.js +1 -1
  241. package/vendor/desktop/vendor/faces/cli/src/diffview.js +1 -1
  242. package/vendor/desktop/vendor/faces/cli/src/dream.js +1 -1
  243. package/vendor/desktop/vendor/faces/cli/src/engine.js +1 -1
  244. package/vendor/desktop/vendor/faces/cli/src/events.js +1 -1
  245. package/vendor/desktop/vendor/faces/cli/src/export.js +1 -1
  246. package/vendor/desktop/vendor/faces/cli/src/fingerprint.js +1 -1
  247. package/vendor/desktop/vendor/faces/cli/src/format.js +1 -1
  248. package/vendor/desktop/vendor/faces/cli/src/fuzzy.js +1 -1
  249. package/vendor/desktop/vendor/faces/cli/src/history.js +1 -1
  250. package/vendor/desktop/vendor/faces/cli/src/init.js +1 -1
  251. package/vendor/desktop/vendor/faces/cli/src/limits.js +1 -1
  252. package/vendor/desktop/vendor/faces/cli/src/markdown.js +1 -1
  253. package/vendor/desktop/vendor/faces/cli/src/mcp.js +1 -1
  254. package/vendor/desktop/vendor/faces/cli/src/models.js +1 -1
  255. package/vendor/desktop/vendor/faces/cli/src/overlays.js +1 -1
  256. package/vendor/desktop/vendor/faces/cli/src/panels.js +1 -1
  257. package/vendor/desktop/vendor/faces/cli/src/permissions.js +1 -1
  258. package/vendor/desktop/vendor/faces/cli/src/ping.js +1 -1
  259. package/vendor/desktop/vendor/faces/cli/src/presence.js +1 -1
  260. package/vendor/desktop/vendor/faces/cli/src/provenance.js +1 -1
  261. package/vendor/desktop/vendor/faces/cli/src/render.js +1 -1
  262. package/vendor/desktop/vendor/faces/cli/src/screen.js +1 -1
  263. package/vendor/desktop/vendor/faces/cli/src/screens.js +1 -1
  264. package/vendor/desktop/vendor/faces/cli/src/secret.js +1 -1
  265. package/vendor/desktop/vendor/faces/cli/src/securefs.js +1 -1
  266. package/vendor/desktop/vendor/faces/cli/src/settings.js +1 -1
  267. package/vendor/desktop/vendor/faces/cli/src/signup.js +1 -1
  268. package/vendor/desktop/vendor/faces/cli/src/summarize.js +1 -1
  269. package/vendor/desktop/vendor/faces/cli/src/sysdiag.js +1 -1
  270. package/vendor/desktop/vendor/faces/cli/src/theme.js +1 -1
  271. package/vendor/desktop/vendor/faces/cli/src/title.js +1 -1
  272. package/vendor/desktop/vendor/faces/cli/src/todos.js +1 -1
  273. package/vendor/desktop/vendor/faces/cli/src/tokens.js +1 -1
  274. package/vendor/desktop/vendor/faces/cli/src/topup.js +1 -1
  275. package/vendor/desktop/vendor/faces/cli/src/update.js +1 -1
  276. package/vendor/desktop/vendor/faces/cli/vendor/client/aegis.js +1 -1
  277. package/vendor/desktop/vendor/faces/cli/vendor/client/attest.js +1 -1
  278. package/vendor/desktop/vendor/faces/cli/vendor/client/authorship-key.js +1 -1
  279. package/vendor/desktop/vendor/faces/cli/vendor/client/auto-provision.js +1 -1
  280. package/vendor/desktop/vendor/faces/cli/vendor/client/brain-catalog.js +1 -1
  281. package/vendor/desktop/vendor/faces/cli/vendor/client/byok-catalog.js +1 -1
  282. package/vendor/desktop/vendor/faces/cli/vendor/client/catalog-client.js +1 -1
  283. package/vendor/desktop/vendor/faces/cli/vendor/client/conversation-export.js +1 -1
  284. package/vendor/desktop/vendor/faces/cli/vendor/client/credentials.js +1 -1
  285. package/vendor/desktop/vendor/faces/cli/vendor/client/credits.js +1 -1
  286. package/vendor/desktop/vendor/faces/cli/vendor/client/drive-connect.js +1 -1
  287. package/vendor/desktop/vendor/faces/cli/vendor/client/env-file.js +1 -1
  288. package/vendor/desktop/vendor/faces/cli/vendor/client/fingerprint.js +1 -1
  289. package/vendor/desktop/vendor/faces/cli/vendor/client/foreign-memory.js +1 -1
  290. package/vendor/desktop/vendor/faces/cli/vendor/client/foreign-sessions.js +1 -1
  291. package/vendor/desktop/vendor/faces/cli/vendor/client/google-signin.js +1 -1
  292. package/vendor/desktop/vendor/faces/cli/vendor/client/hooks.js +1 -1
  293. package/vendor/desktop/vendor/faces/cli/vendor/client/model-discovery.js +1 -1
  294. package/vendor/desktop/vendor/faces/cli/vendor/client/model-sync.js +1 -1
  295. package/vendor/desktop/vendor/faces/cli/vendor/client/naming.js +1 -1
  296. package/vendor/desktop/vendor/faces/cli/vendor/client/platform.js +1 -1
  297. package/vendor/desktop/vendor/faces/cli/vendor/client/prefs.js +1 -1
  298. package/vendor/desktop/vendor/faces/cli/vendor/client/presence.js +1 -1
  299. package/vendor/desktop/vendor/faces/cli/vendor/client/record-vault.js +2 -2
  300. package/vendor/desktop/vendor/faces/cli/vendor/client/session-search.js +1 -1
  301. package/vendor/desktop/vendor/faces/cli/vendor/client/session-store.js +1 -1
  302. package/vendor/desktop/vendor/faces/cli/vendor/client/skills.js +1 -1
  303. package/vendor/desktop/vendor/faces/cli/vendor/client/topup.js +1 -1
  304. package/vendor/desktop/vendor/faces/cli/vendor/client/touch.js +1 -1
  305. package/vendor/desktop/vendor/faces/cli/vendor/client/update.js +1 -1
  306. package/vendor/desktop/vendor/faces/cli/vendor/client/user-models.js +1 -1
  307. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/attachments.js +1 -1
  308. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/autonomous.js +1 -1
  309. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/claude-pro.js +1 -1
  310. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/context.js +1 -1
  311. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/engine.js +1 -1
  312. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/entitlement.js +1 -1
  313. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/exec-plan.js +1 -1
  314. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/integrity.js +1 -1
  315. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/local.js +1 -1
  316. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/perm-rules.js +2 -0
  317. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/perm-store.js +3 -1
  318. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/perm-write.js +2 -0
  319. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/pro-sessions.js +3 -1
  320. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/prompt.js +1 -1
  321. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/queue.js +1 -1
  322. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/repeat-guard.js +1 -1
  323. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/session-rounds.js +1 -1
  324. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/shell.js +1 -1
  325. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/spill.js +1 -1
  326. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/tools.js +1 -1
  327. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/turn-guard.js +1 -1
  328. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/verify-stop.js +1 -1
  329. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/worktree-lock.js +1 -1
  330. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/settings.js +1 -1
  331. package/vendor/desktop/vendor/faces/cli/vendor/desktop/main.js +3 -3
  332. package/vendor/desktop/vendor/faces/cli/vendor/desktop/renderer/usage.js +1 -1
  333. package/vendor/desktop/vendor/faces/cli/vendor/hosts/install.js +1 -1
  334. package/vendor/desktop/vendor/faces/cli/vendor/hosts/openai-shim.js +1 -1
  335. package/vendor/desktop/vendor/faces/cli/vendor/hosts/spec.js +1 -1
  336. package/vendor/desktop/vendor/faces/cli/vendor/hosts/targets.js +1 -1
  337. package/vendor/desktop/vendor/faces/cli/vendor/mcp/admission.js +1 -1
  338. package/vendor/desktop/vendor/faces/cli/vendor/mcp/server.js +1 -1
  339. package/vendor/desktop/vendor/faces/cli/vendor/mcp/tools.js +1 -1
  340. package/vendor/desktop/vendor/faces/cli/vendor/one/src/child.js +1 -1
  341. package/vendor/desktop/vendor/faces/cli/vendor/one/src/protocol.js +1 -1
  342. package/vendor/desktop/vendor/faces/cli/vendor/one/src/selfhost.js +1 -1
  343. package/vendor/desktop/vendor/fingerprint.js +1 -1
  344. package/vendor/desktop/vendor/foreign-memory.js +1 -1
  345. package/vendor/desktop/vendor/foreign-sessions.js +1 -1
  346. package/vendor/desktop/vendor/google-signin.js +1 -1
  347. package/vendor/desktop/vendor/hooks.js +1 -1
  348. package/vendor/desktop/vendor/model-discovery.js +1 -1
  349. package/vendor/desktop/vendor/model-sync.js +1 -1
  350. package/vendor/desktop/vendor/naming.js +1 -1
  351. package/vendor/desktop/vendor/platform.js +1 -1
  352. package/vendor/desktop/vendor/prefs.js +1 -1
  353. package/vendor/desktop/vendor/presence.js +1 -1
  354. package/vendor/desktop/vendor/protocol.js +1 -1
  355. package/vendor/desktop/vendor/record-vault.js +2 -2
  356. package/vendor/desktop/vendor/selfhost.js +1 -1
  357. package/vendor/desktop/vendor/session-search.js +1 -1
  358. package/vendor/desktop/vendor/session-store.js +1 -1
  359. package/vendor/desktop/vendor/skills.js +1 -1
  360. package/vendor/desktop/vendor/topup.js +1 -1
  361. package/vendor/desktop/vendor/touch.js +1 -1
  362. package/vendor/desktop/vendor/update.js +1 -1
  363. package/vendor/desktop/vendor/user-models.js +1 -1
@@ -1,3 +1,3 @@
1
1
  // SPDX-License-Identifier: AGPL-3.0-or-later
2
2
  // Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
3
- "use strict";const{PRESENCE_PATH:PRESENCE_PATH,DEFAULT_INTERVAL_MS:DEFAULT_INTERVAL_MS,MIN_INTERVAL_MS:MIN_INTERVAL_MS,MAX_INTERVAL_MS:MAX_INTERVAL_MS,BACKOFF_FACTOR:BACKOFF_FACTOR,MAX_BACKOFF_MS:MAX_BACKOFF_MS,REQUEST_TIMEOUT_MS:REQUEST_TIMEOUT_MS,APP_NAMES:APP_NAMES,saneToken:saneToken,saneCount:saneCount}=require("./presence-constants.js"),DEFAULT_API_BASE="https://aegiscloud.org";function disabledPresence(e){const n={enabled:!1,reason:String(e||"disabled"),beats:0,failures:0,lastError:null,lastSeenAt:null,intervalMs:null,install:null,app:null,running:!1};return{enabled:!1,reason:n.reason,install:null,beat:()=>Promise.resolve(!1),start:()=>!1,stop:()=>!1,state:()=>({...n})}}function isoOf(e){try{const n=Number(e);return Number.isFinite(n)?new Date(n).toISOString():null}catch{return null}}function createPresence(e={}){const n="string"==typeof e.apiKey?e.apiKey.trim():"";if(!n)return disabledPresence("no-api-key");if(!1===e.enabled)return disabledPresence("disabled");const t="function"==typeof e.log?e.log:()=>{};function r(e){if(!o.has(e)){o.add(e);try{t("debug",`presence: ${e}`)}catch{}}}const o=new Set,s="function"==typeof e.now?e.now:()=>Date.now(),i="function"==typeof e.setTimer?e.setTimer:setTimeout,a="function"==typeof e.clearTimer?e.clearTimer:clearTimeout;let l=saneToken(e.install,64);if(l||"function"!=typeof e.fingerprint){if(!l)try{l=saneToken(require("./device-fingerprint.js").machineFingerprint(),64)}catch{r("fingerprint")}}else try{l=saneToken(e.fingerprint(),64)}catch{r("fingerprint")}if(!l)return disabledPresence("no-install-identity");const u=saneToken(e.app,24).toLowerCase()||"other",c=saneToken(e.version,32),f=saneToken(e.platform,16).toLowerCase()||("undefined"!=typeof process&&process.platform?process.platform:""),_=String(e.baseUrl||"undefined"!=typeof process&&process.env&&process.env.AEGIS_API_BASE||DEFAULT_API_BASE).replace(/\/+$/,""),A=PRESENCE_PATH,E="function"==typeof e.fetchImpl?e.fetchImpl:"function"==typeof fetch?fetch:null;function M(e,n){try{return"function"==typeof e?e():e}catch{return n}}let p=b(e.intervalMs);const T={enabled:!0,reason:null,beats:0,failures:0,lastError:null,lastSeenAt:null,intervalMs:p,install:l,app:u,version:c||null,platform:f||null,running:!1};let S=null,m=null,d=0,N=!1;function b(e){const n=Number(e);return!Number.isFinite(n)||n<=0?DEFAULT_INTERVAL_MS:Math.min(MAX_INTERVAL_MS,Math.max(MIN_INTERVAL_MS,Math.floor(n)))}function y(){if(N)return Promise.resolve(!1);if(m)return m;if(!E)return r("no-fetch"),T.lastError="no fetch implementation",T.failures+=1,Promise.resolve(!1);const t=s();return m=(async()=>{let o=!1,P=null;try{const t="function"==typeof AbortController?new AbortController:null;if(t){const e=i((()=>{o=!0;try{t.abort()}catch{}}),REQUEST_TIMEOUT_MS);e&&"function"==typeof e.unref&&e.unref(),P=()=>a(e)}const r=await E(`${_}${A}`,{method:"POST",headers:{"Content-Type":"application/json","X-API-Key":n,"X-AEGIS-Version":saneToken(e.clientVersion,32)||c||""},body:JSON.stringify({app:u,version:c||void 0,platform:f||void 0,install:l,queue:saneCount(M(e.queueDepth,0)),autonomous:Boolean(M(e.autonomous,!1))}),...t?{signal:t.signal}:{}});if(P&&P(),!r||"number"!=typeof r.status||r.status<200||r.status>=300)return T.failures+=1,T.lastError=`http ${r&&r.status?r.status:"error"}`,d=I(d),!1;let S=null;try{S=await r.json()}catch{S=null}if(T.beats+=1,T.failures=0,T.lastError=null,T.lastSeenAt=isoOf(s()),d=0,S&&"object"==typeof S&&null!=S.beat_interval_s){const e=Number(S.beat_interval_s);Number.isFinite(e)&&e>0&&(p=b(1e3*e))}return T.intervalMs=p,!0}catch(e){return P&&P(),T.failures+=1,T.lastError=o?"timeout":String(e&&e.message||e||"error").slice(0,200),d=I(d),1===T.failures&&r("beat-failed"),!1}finally{m=null,T.running&&function(e){if(N||"function"!=typeof i)return;S&&a(S);const n=Math.max(1e3,Math.floor(Number(e)||p));S=i((()=>{S=null,y()}),n),S&&"function"==typeof S.unref&&S.unref()}(Math.max(0,p+d-(s()-t)))}})(),m}function I(e){const n=e>0?e*BACKOFF_FACTOR:Math.max(MIN_INTERVAL_MS,p);return Math.min(MAX_BACKOFF_MS,Math.floor(n))}return{enabled:!0,app:u,install:l,beat:y,start:function(){return!N&&(T.running=!0,y(),!0)},stop:function(){if(N=!0,T.running=!1,S){try{a(S)}catch{}S=null}return!0},pending:()=>m,state:()=>({...T,intervalMs:p})}}module.exports={createPresence:createPresence,disabledPresence:disabledPresence,PRESENCE_PATH:PRESENCE_PATH,DEFAULT_INTERVAL_MS:DEFAULT_INTERVAL_MS,MIN_INTERVAL_MS:MIN_INTERVAL_MS,MAX_INTERVAL_MS:MAX_INTERVAL_MS,MAX_BACKOFF_MS:MAX_BACKOFF_MS,REQUEST_TIMEOUT_MS:REQUEST_TIMEOUT_MS,APP_NAMES:APP_NAMES};
3
+ "use strict";const{PRESENCE_PATH:PRESENCE_PATH,DEFAULT_INTERVAL_MS:DEFAULT_INTERVAL_MS,MIN_INTERVAL_MS:MIN_INTERVAL_MS,MAX_INTERVAL_MS:MAX_INTERVAL_MS,BACKOFF_FACTOR:BACKOFF_FACTOR,MAX_BACKOFF_MS:MAX_BACKOFF_MS,REQUEST_TIMEOUT_MS:REQUEST_TIMEOUT_MS,APP_NAMES:APP_NAMES,saneToken:saneToken,saneCount:saneCount}=require("./presence-constants.js"),DEFAULT_API_BASE="https://aegiscloud.org";function disabledPresence(e){const n={enabled:!1,reason:String(e||"disabled"),beats:0,failures:0,lastError:null,lastSeenAt:null,intervalMs:null,install:null,app:null,running:!1};return{enabled:!1,reason:n.reason,install:null,beat:()=>Promise.resolve(!1),start:()=>!1,stop:()=>!1,state:()=>({...n})}}function isoOf(e){try{const n=Number(e);return Number.isFinite(n)?new Date(n).toISOString():null}catch{return null}}function createPresence(e={}){const n="string"==typeof e.apiKey?e.apiKey.trim():"";if(!n)return disabledPresence("no-api-key");if(!1===e.enabled)return disabledPresence("disabled");const t="function"==typeof e.log?e.log:()=>{};function r(e){if(!o.has(e)){o.add(e);try{t("debug",`presence: ${e}`)}catch{}}}const o=new Set,s="function"==typeof e.now?e.now:()=>Date.now(),i="function"==typeof e.setTimer?e.setTimer:setTimeout,a="function"==typeof e.clearTimer?e.clearTimer:clearTimeout;let l=saneToken(e.install,64);if(l||"function"!=typeof e.fingerprint){if(!l)try{l=saneToken(require("./device-fingerprint.js").machineFingerprint(),64)}catch{r("fingerprint")}}else try{l=saneToken(e.fingerprint(),64)}catch{r("fingerprint")}if(!l)return disabledPresence("no-install-identity");const u=saneToken(e.app,24).toLowerCase()||"other",c=saneToken(e.version,32),f=saneToken(e.platform,16).toLowerCase()||("undefined"!=typeof process&&process.platform?process.platform:""),_=String(e.baseUrl||"undefined"!=typeof process&&process.env&&process.env.AEGIS_API_BASE||DEFAULT_API_BASE).replace(/\/+$/,""),A=PRESENCE_PATH,E="function"==typeof e.fetchImpl?e.fetchImpl:"function"==typeof fetch?fetch:null;function M(e,n){try{return"function"==typeof e?e():e}catch{return n}}let p=b(e.intervalMs);const T={enabled:!0,reason:null,beats:0,failures:0,lastError:null,lastSeenAt:null,intervalMs:p,install:l,app:u,version:c||null,platform:f||null,running:!1};let S=null,m=null,d=0,N=!1;function b(e){const n=Number(e);return!Number.isFinite(n)||n<=0?DEFAULT_INTERVAL_MS:Math.min(MAX_INTERVAL_MS,Math.max(MIN_INTERVAL_MS,Math.floor(n)))}function y(){if(N)return Promise.resolve(!1);if(m)return m;if(!E)return r("no-fetch"),T.lastError="no fetch implementation",T.failures+=1,Promise.resolve(!1);const t=s();return m=(async()=>{let o=!1,P=null;try{const t="function"==typeof AbortController?new AbortController:null;if(t){const e=i(()=>{o=!0;try{t.abort()}catch{}},REQUEST_TIMEOUT_MS);e&&"function"==typeof e.unref&&e.unref(),P=()=>a(e)}const r=await E(`${_}${A}`,{method:"POST",headers:{"Content-Type":"application/json","X-API-Key":n,"X-AEGIS-Version":saneToken(e.clientVersion,32)||c||""},body:JSON.stringify({app:u,version:c||void 0,platform:f||void 0,install:l,queue:saneCount(M(e.queueDepth,0)),autonomous:Boolean(M(e.autonomous,!1))}),...t?{signal:t.signal}:{}});if(P&&P(),!r||"number"!=typeof r.status||r.status<200||r.status>=300)return T.failures+=1,T.lastError=`http ${r&&r.status?r.status:"error"}`,d=I(d),!1;let S=null;try{S=await r.json()}catch{S=null}if(T.beats+=1,T.failures=0,T.lastError=null,T.lastSeenAt=isoOf(s()),d=0,S&&"object"==typeof S&&null!=S.beat_interval_s){const e=Number(S.beat_interval_s);Number.isFinite(e)&&e>0&&(p=b(1e3*e))}return T.intervalMs=p,!0}catch(e){return P&&P(),T.failures+=1,T.lastError=o?"timeout":String(e&&e.message||e||"error").slice(0,200),d=I(d),1===T.failures&&r("beat-failed"),!1}finally{m=null,T.running&&function(e){if(N||"function"!=typeof i)return;S&&a(S);const n=Math.max(1e3,Math.floor(Number(e)||p));S=i(()=>{S=null,y()},n),S&&"function"==typeof S.unref&&S.unref()}(Math.max(0,p+d-(s()-t)))}})(),m}function I(e){const n=e>0?e*BACKOFF_FACTOR:Math.max(MIN_INTERVAL_MS,p);return Math.min(MAX_BACKOFF_MS,Math.floor(n))}return{enabled:!0,app:u,install:l,beat:y,start:function(){return!N&&(T.running=!0,y(),!0)},stop:function(){if(N=!0,T.running=!1,S){try{a(S)}catch{}S=null}return!0},pending:()=>m,state:()=>({...T,intervalMs:p})}}module.exports={createPresence:createPresence,disabledPresence:disabledPresence,PRESENCE_PATH:PRESENCE_PATH,DEFAULT_INTERVAL_MS:DEFAULT_INTERVAL_MS,MIN_INTERVAL_MS:MIN_INTERVAL_MS,MAX_INTERVAL_MS:MAX_INTERVAL_MS,MAX_BACKOFF_MS:MAX_BACKOFF_MS,REQUEST_TIMEOUT_MS:REQUEST_TIMEOUT_MS,APP_NAMES:APP_NAMES};
@@ -95,11 +95,11 @@
95
95
  * user's Drive or their account. The remote/root are overridable the same way
96
96
  * (`AEGIS_VAULT_REMOTE`/`AEGIS_VAULT_ROOT`, `AEGIS_VAULT_BACKEND`), which is
97
97
  * also what keeps a misconfigured vault from writing into an unrelated folder.
98
- */const crypto=require("node:crypto"),fs=require("node:fs"),os=require("node:os"),path=require("node:path"),{execFileSync:execFileSync}=require("node:child_process"),fp=require("./fingerprint.js"),authorship=require("./authorship-key.js"),BACKEND_CLOUD="aegiscloud",BACKEND_RCLONE="rclone",DEFAULT_BACKEND=BACKEND_CLOUD,DEFAULT_REMOTE="gdrive",DEFAULT_ROOT="AEGIS-AGPL",RECORDS_DIR="records",INDEX_NAME="index.jsonl",ANCHOR_SUFFIX=".anchor.json",ANCHOR_VERSION=1,ANCHOR_KIND="aegiscode.record.anchor",INDEX_KIND="aegiscode.record.index",RCLONE_ENV="AEGIS_VAULT_RCLONE",REMOTE_ENV="AEGIS_VAULT_REMOTE",ROOT_ENV="AEGIS_VAULT_ROOT",BACKEND_ENV="AEGIS_VAULT_BACKEND",API_BASE_ENV="AEGIS_API_BASE",CLOUD_PREFIX="/api/v1/vault",RCLONE_TIMEOUT_MS=6e4,MAX_INSPECT_BYTES=2097152,MAX_AUDIT_FILES=500,KEY_PATH_PATTERNS=[/(^|\/)keys?\//i,/\.key$/i,/\.pem$/i,/(^|\/)id_(rsa|dsa|ecdsa|ed25519)(\.|$)/i,/(^|\/)agent\.key(\.|$)/i],BARE_TOKEN=/^[A-Za-z0-9_\-+/=]{40,}$/,BARE_HEX=/^[0-9a-fA-F]{32,}$/,PEM_PRIVATE=/-----BEGIN [A-Z0-9 ]*PRIVATE KEY-----/;function flag(e,t,r=null){const n=Array.isArray(e)?e:[],o=n.indexOf(t);return-1===o||void 0===n[o+1]||String(n[o+1]).startsWith("--")?r:n[o+1]}function has(e,t){return(Array.isArray(e)?e:[]).includes(t)}function rcloneBinary(e=process.env,t=[]){return flag(t,"--rclone")||e[RCLONE_ENV]||"rclone"}function vaultTarget(e=process.env,t=[],r=null){const n=flag(t,"--remote")||e[REMOTE_ENV]||r&&r.remote||DEFAULT_REMOTE;return{backend:backendFor(e,t,n,r),remote:n,root:flag(t,"--root")||e[ROOT_ENV]||r&&r.root||DEFAULT_ROOT,apiBase:String(flag(t,"--base")||e[API_BASE_ENV]||"https://aegiscloud.org").replace(/\/+$/,""),rclone:rcloneBinary(e,t),env:e}}function backendFor(e,t,r,n=null){const o=String(flag(t,"--backend")||e[BACKEND_ENV]||"").trim().toLowerCase();if(o){if(o!==BACKEND_CLOUD&&o!==BACKEND_RCLONE)throw new Error(`vault: unknown backend "${o}" — expected ${BACKEND_CLOUD} or ${BACKEND_RCLONE}`);return o}return flag(t,"--remote")||e[REMOTE_ENV]?BACKEND_RCLONE:!n||n.backend!==BACKEND_CLOUD&&n.backend!==BACKEND_RCLONE?n&&void 0===n.backend&&n.remote&&n.remote!==DEFAULT_REMOTE?BACKEND_RCLONE:DEFAULT_BACKEND:n.backend}function remoteSpec(e,...t){return`${e.remote}:${[e.root,...t].filter(Boolean).join("/")}`
98
+ */const crypto=require("node:crypto"),fs=require("node:fs"),os=require("node:os"),path=require("node:path"),{execFileSync:execFileSync}=require("node:child_process"),fp=require("./fingerprint.js"),authorship=require("./authorship-key.js"),BACKEND_CLOUD="aegiscloud",BACKEND_RCLONE="rclone",DEFAULT_BACKEND="aegiscloud",DEFAULT_REMOTE="gdrive",DEFAULT_ROOT="AEGIS-AGPL",RECORDS_DIR="records",INDEX_NAME="index.jsonl",ANCHOR_SUFFIX=".anchor.json",ANCHOR_VERSION=1,ANCHOR_KIND="aegiscode.record.anchor",INDEX_KIND="aegiscode.record.index",RCLONE_ENV="AEGIS_VAULT_RCLONE",REMOTE_ENV="AEGIS_VAULT_REMOTE",ROOT_ENV="AEGIS_VAULT_ROOT",BACKEND_ENV="AEGIS_VAULT_BACKEND",API_BASE_ENV="AEGIS_API_BASE",CLOUD_PREFIX="/api/v1/vault",RCLONE_TIMEOUT_MS=6e4,MAX_INSPECT_BYTES=2097152,MAX_AUDIT_FILES=500,KEY_PATH_PATTERNS=[/(^|\/)keys?\//i,/\.key$/i,/\.pem$/i,/(^|\/)id_(rsa|dsa|ecdsa|ed25519)(\.|$)/i,/(^|\/)agent\.key(\.|$)/i],BARE_TOKEN=/^[A-Za-z0-9_\-+/=]{40,}$/,BARE_HEX=/^[0-9a-fA-F]{32,}$/,PEM_PRIVATE=/-----BEGIN [A-Z0-9 ]*PRIVATE KEY-----/;function flag(e,t,r=null){const n=Array.isArray(e)?e:[],o=n.indexOf(t);return-1===o||void 0===n[o+1]||String(n[o+1]).startsWith("--")?r:n[o+1]}function has(e,t){return(Array.isArray(e)?e:[]).includes(t)}function rcloneBinary(e=process.env,t=[]){return flag(t,"--rclone")||e[RCLONE_ENV]||"rclone"}function vaultTarget(e=process.env,t=[],r=null){const n=flag(t,"--remote")||e[REMOTE_ENV]||r&&r.remote||"gdrive";return{backend:backendFor(e,t,n,r),remote:n,root:flag(t,"--root")||e[ROOT_ENV]||r&&r.root||"AEGIS-AGPL",apiBase:String(flag(t,"--base")||e[API_BASE_ENV]||"https://aegiscloud.org").replace(/\/+$/,""),rclone:rcloneBinary(e,t),env:e}}function backendFor(e,t,r,n=null){const o=String(flag(t,"--backend")||e[BACKEND_ENV]||"").trim().toLowerCase();if(o){if("aegiscloud"!==o&&"rclone"!==o)throw new Error(`vault: unknown backend "${o}" — expected aegiscloud or rclone`);return o}return flag(t,"--remote")||e[REMOTE_ENV]?"rclone":!n||"aegiscloud"!==n.backend&&"rclone"!==n.backend?n&&void 0===n.backend&&n.remote&&"gdrive"!==n.remote?"rclone":"aegiscloud":n.backend}function remoteSpec(e,...t){return`${e.remote}:${[e.root,...t].filter(Boolean).join("/")}`
99
99
  /**
100
100
  * A path *below* the root, however it was written: `records/x.json`,
101
101
  * `<root>/records/x.json`, or an absolute `remote:…` spec. Everything that
102
102
  * reads tolerates all three, because the anchor stores the browsable
103
103
  * root-prefixed form (a human reads `AEGIS-AGPL/records/x.json`) while rclone
104
104
  * wants it relative.
105
- */}function relativeToRoot(e,t){let r=String(t||"").replace(/^\/+/,"");const n=`${e.remote}:`;return r.startsWith(n)&&(r=r.slice(n.length)),r===e.root?"":(r.startsWith(`${e.root}/`)&&(r=r.slice(e.root.length+1)),r)}function remoteSpecOf(e,t){const r=relativeToRoot(e,t);return r?remoteSpec(e,r):remoteSpec(e)}function rcloneRun(e,t,{timeout:r=RCLONE_TIMEOUT_MS}={}){try{return execFileSync(e.rclone,t,{encoding:"utf8",timeout:r,stdio:["ignore","pipe","pipe"],maxBuffer:33554432,env:e.env?{...process.env,...e.env}:process.env})}catch(e){const r=String(e&&e.stderr||"").trim().split("\n").filter((e=>!/NOTICE:/.test(e))).pop()||e&&e.message||String(e),n=new Error(`vault: rclone ${t[0]} failed — ${r}`);throw n.code="ERCLONE",n.stderr=String(e&&e.stderr||""),n}}function tempDir(){return fs.mkdtempSync(path.join(os.tmpdir(),"aegis-vault-"))}function cloudApiKey(e={}){if(e.apiKey)return String(e.apiKey).trim();const t=e.env||process.env;try{const e=require("./credentials.js");return String(e.resolveApiKey({env:t,dir:e.aegisHome(t)}).key||"").trim()}catch{return""}}async function cloudRun(e,t,r,{body:n=null,raw:o=!1,timeout:a=RCLONE_TIMEOUT_MS,fetchImpl:s=null,apiKey:i=null}={}){const c=i||"";if(!c){const e=new Error("vault: no AEGIS account key on this machine — the aegiscloud vault is the account you already have. Run `aegiscode login`, or publish to a folder you own with `--backend rclone --remote <name>`.");throw e.code="ENOKEY",e}const l=s||("function"==typeof fetch?fetch:null);if(!l){const e=new Error("vault: this Node has no global fetch — upgrade to Node 22+ to use the aegiscloud vault");throw e.code="ENOFETCH",e}const u=new AbortController,d=setTimeout((()=>u.abort()),a);let h;try{h=await l(`${e.apiBase}${CLOUD_PREFIX}${r}`,{method:t,headers:{"Content-Type":"application/json","X-API-Key":c,Authorization:`Bearer ${c}`},body:null===n?void 0:JSON.stringify(n),signal:u.signal})}catch(t){const r=new Error(`vault: could not reach ${e.apiBase} — ${t&&t.message||t}`);throw r.code="ENETWORK",r}finally{clearTimeout(d)}const E=await h.text();let p=null;try{p=E?JSON.parse(E):null}catch{p=null}if(!h.ok){if(404===h.status&&(""===r||r.startsWith("?"))){const t=new Error(`vault: ${e.apiBase} does not serve the account vault yet (${CLOUD_PREFIX} is missing on this server). Publish to a folder you own instead: \`--backend rclone --remote <name> --root <folder>\`.`);throw t.code="ENOVAULT",t.status=404,t}const n=p&&(p.error||p.message)||E.slice(0,200)||`HTTP ${h.status}`,o=new Error(`vault: ${t} ${CLOUD_PREFIX}${r} failed — ${n}`);throw o.code="ECLOUD",o.status=h.status,o}return o?E:null===p?{}:p}function cloudObject(e,t){return`/${String(t||"").split("/").filter(Boolean).map((e=>encodeURIComponent(e))).join("/")}`}function transportFor(e,t={}){if(e.backend===BACKEND_CLOUD){const r=cloudApiKey(t),n=(n,o,a)=>cloudRun(e,n,o,{...a,fetchImpl:t.fetch,apiKey:r});return{backend:BACKEND_CLOUD,async put(t,r){await n("PUT",cloudObject(e,remoteObjectName(t)),{body:{content:r}})},async putFile(e,t){await this.put(e,fs.readFileSync(t,"utf8"))},async cat(t){try{const r=await n("GET",cloudObject(e,remoteObjectName(t)));return r&&"string"==typeof r.content?r.content:null}catch(e){if(404===e.status)return null;throw e}},async list(t){const r=await n("GET",`?dir=${encodeURIComponent(relativeToRoot(e,t))}`);return Array.isArray(r&&r.files)?r.files:[]},async listRecursive(t){const r=await n("GET",`?dir=${encodeURIComponent(relativeToRoot(e,t))}&recursive=1`);return Array.isArray(r&&r.files)?r.files:[]},describe:`${e.apiBase} (account vault)`}}return{backend:BACKEND_RCLONE,async put(t,r,{name:n="object"}={}){const o=tempDir();try{const a=path.join(o,n);fs.writeFileSync(a,r),rcloneRun(e,["copyto",a,remoteSpecOf(e,t)])}finally{fs.rmSync(o,{recursive:!0,force:!0})}},async putFile(t,r){rcloneRun(e,["copyto",r,remoteSpecOf(e,t)])},async cat(t){try{return rcloneRun(e,["cat",remoteSpecOf(e,t)])}catch(e){if("ERCLONE"===e.code&&/not found|does not exist|error 404/i.test(e.stderr||e.message))return null;throw e}},list:async t=>listRaw(e,t),listRecursive:async t=>rcloneLsjsonRecursive(e,t),describe:`${e.remote}:${e.root}`}}function remoteObjectName(e){return relativeToRoot({remote:"",root:""},e).replace(/^\/+/,"")}function inspect(e,t,{secret:r=null,keyPath:n=null}={}){const o=String(e||"");for(const e of KEY_PATH_PATTERNS)if(e.test(o))return{dangerous:!0,reason:`the path looks like key material (${e})`};if(n&&path.resolve(o)===path.resolve(n))return{dangerous:!0,reason:"this path IS the authorship key"};const a=String(null==t?"":t),s=a.trim();if(r&&s.includes(String(r)))return{dangerous:!0,reason:"the content carries the authorship key verbatim"};if(PEM_PRIVATE.test(a))return{dangerous:!0,reason:"the content is a PEM private key"};const i=1===s.split("\n").length;if(i&&BARE_TOKEN.test(s)&&!BARE_HEX.test(s))return{dangerous:!0,reason:"the content is a bare high-entropy token (a raw secret)"};if(i&&BARE_HEX.test(s))return{dangerous:!0,reason:"the content is an unlabelled hex blob (a raw digest or key)"};let c=null;try{c=JSON.parse(a)}catch{c=null}if(c&&"object"==typeof c&&!Array.isArray(c)){if("string"==typeof c.kind&&c.kind.startsWith("aegiscode."))return inspectArtifact(c,r);try{fp.assertNoLeak(c,r||"")}catch(e){return{dangerous:!0,reason:e&&e.message||"failed the leak check"}}}return{dangerous:!1,reason:null}}function inspectArtifact(e,t){const r=new Set(["sha256","attestation","code"]);for(const[n,o]of Object.entries(e)){if(null==o)continue;const e=Array.isArray(o)?o.join("\0"):String(o);if(t&&e.includes(String(t)))return{dangerous:!0,reason:`the link carries the authorship key verbatim in "${n}"`};if(!r.has(n)&&fp.longHexRun(e))return{dangerous:!0,reason:`the link carries a long hex run in "${n}"`}}return void 0===e.sha256||/^[0-9a-f]{64}$/.test(String(e.sha256))?void 0===e.attestation||/^[0-9a-f]{32}$/.test(String(e.attestation))?{dangerous:!1,reason:null}:{dangerous:!0,reason:"the link's attestation is not a 32-hex tag"}:{dangerous:!0,reason:"the link's sha256 is not a 64-hex digest"}}function assertPublishable(e,t,r={}){const n=inspect(e,t,r);if(n.dangerous)throw new Error(`vault: refusing to publish ${e} — ${n.reason}. The vault carries sealed records only: a key that reaches cloud storage can mint records indistinguishable from yours, so it is never a backup. Keep it in ${authorship.defaultKeyPath(r.env||process.env)} (0600) and back it up to a local disk or a password manager.`);return!0}function baseName(e,t=null){const r=e&&e.behaviour?String(e.behaviour):"unobserved",n=String(t||e&&e.createdAt||(new Date).toISOString()).replace(/[:.]/g,"-");return`${e.keyFingerprint}-${r}.${n}`}function driveUrl(e){return e?`https://drive.google.com/open?id=${encodeURIComponent(e)}`:null}function sha256(e){return crypto.createHash("sha256").update(e,"utf8").digest("hex")}function readRecord({file:e=null,record:t=null,secret:r=null,env:n=process.env}){if(e){const t=path.resolve(e);if(!fs.existsSync(t))throw new Error(`vault: no record at ${t}`);const o=fs.readFileSync(t,"utf8");let a;assertPublishable(t,o,{secret:r,keyPath:authorship.defaultKeyPath(n),env:n});try{a=JSON.parse(o)}catch(e){throw new Error(`vault: ${t} is not JSON — ${e.message}`)}return{text:o,record:a,file:t,serialised:o}}if(t){const e=JSON.stringify(t,null,2)+"\n";return{text:e,record:t,file:null,serialised:e}}throw new Error("vault: publish needs a record file or a record")}async function publish(e={}){const t=e.env||process.env,r=e.argv||[],n=vaultTarget(t,r),o=Boolean(e.dryRun)||has(r,"--dry-run"),a=void 0===e.index?!has(r,"--no-index"):Boolean(e.index),s=e.secret||null,{text:i,record:c,file:l}=readRecord({...e,secret:s,env:t});let u;try{u=fp.id(c)}catch(e){throw new Error(`vault: not a sealed φ(α) record — ${e&&e.message||e}`)}const d=authorship.defaultKeyPath(t);assertPublishable(path.basename(l||"record.json"),i,{secret:s,keyPath:d,env:t});const h=`${baseName(c)}.json`,E=`${h}${ANCHOR_SUFFIX}`,p=`${RECORDS_DIR}/${h}`,f=`${RECORDS_DIR}/${E}`,N=sha256(i),y={v:1,kind:ANCHOR_KIND,id:u,keyFingerprint:c.keyFingerprint,behaviour:c.behaviour||null,code:c.code||null,createdAt:c.createdAt,attestation:c.attestation,sha256:N,bytes:Buffer.byteLength(i,"utf8"),backend:n.backend,remote:n.remote,root:n.root,path:n.backend===BACKEND_CLOUD?`${CLOUD_PREFIX}/${p}`:`${n.root}/${p}`,key:p,emittedAt:new Date(e.now||Date.now()).toISOString(),driveId:null,url:null,index:a?`${n.root}/${RECORDS_DIR}/${INDEX_NAME}`:null},A=transportFor(n,e);if(o)return{ok:!0,dryRun:!0,backend:n.backend,anchor:y,url:null,remotePath:y.path,commands:n.backend===BACKEND_CLOUD?[`PUT ${n.apiBase}${CLOUD_PREFIX}/${p}`,`PUT ${n.apiBase}${CLOUD_PREFIX}/${f}`]:[`rclone copyto ${l||"<record>"} ${remoteSpec(n,p)}`,`rclone copyto <anchor> ${remoteSpec(n,f)}`]};l?await A.putFile(p,l):await A.put(p,i,{name:h});const g=(await A.list(RECORDS_DIR)).find((e=>String(e.Name)===h))||null;g&&(y.driveId=g.ID||null,y.url=g.url||(n.backend===BACKEND_CLOUD?null:driveUrl(g.ID)));const O=l?`${l}${ANCHOR_SUFFIX}`:null,R=JSON.stringify(y,null,2)+"\n";await A.put(f,R,{name:E}),O&&fs.writeFileSync(O,R);let _=null;return a&&(_=await appendIndex(n,y,A)),{ok:!0,dryRun:!1,backend:n.backend,anchor:y,url:y.url,localAnchor:O,remotePath:y.path,bytes:y.bytes,sha256:N,indexLines:_}}function rcloneCat(e,t){try{return rcloneRun(e,["cat",remoteSpecOf(e,t)])}catch(e){if("ERCLONE"===e.code&&/not found|does not exist|error 404/i.test(e.stderr||e.message))return null;throw e}}function listRaw(e,t){let r;try{r=rcloneRun(e,["lsjson",remoteSpecOf(e,t),"--files-only"])}catch(e){if("ERCLONE"===e.code&&/not found|does not exist|error 404|directory not found/i.test(e.stderr||e.message))return[];throw e}const n=String(r).trim();if(!n)return[];const o=JSON.parse(n);return Array.isArray(o)?o:[]}async function appendIndex(e,t,r=transportFor(e)){const n=`${RECORDS_DIR}/${INDEX_NAME}`,o=await r.cat(n)||"",a=JSON.stringify({kind:INDEX_KIND,id:t.id,keyFingerprint:t.keyFingerprint,sha256:t.sha256,path:t.path,url:t.url,driveId:t.driveId,emittedAt:t.emittedAt});return await r.put(n,o+a+"\n",{name:INDEX_NAME}),(o.trim()?o.trim().split("\n").length:0)+1}function localAnchor(e){const t=`${path.resolve(e)}${ANCHOR_SUFFIX}`;if(!fs.existsSync(t))return null;try{return JSON.parse(fs.readFileSync(t,"utf8"))}catch{return null}}async function checkAnchor(e={}){const t=e.env||process.env,r=e.argv||[],n=e.anchor||(e.file?localAnchor(e.file):null);if(!n)return{ok:!1,reason:"not linked — no anchor beside this record (publish it first)",present:!1,unchanged:null,attested:null};const o=transportFor(vaultTarget(t,r,n),e),a=await o.cat(n.key||n.path);if(null===a)return{ok:!1,reason:`no copy at ${n.path}`,present:!1,unchanged:!1,attested:null,anchor:n};const s=sha256(a)===n.sha256;let i=null,c=null;try{const n=e.key||authorship.resolveKey({argv:r,env:t});if(n.secret){const e=fp.verify(JSON.parse(a),n.secret);i=e.ok,c=e.reason}else c="no authorship key on this machine to recompute with"}catch(e){c=e&&e.message||String(e)}return{ok:s&&!1!==i,anchor:n,present:!0,unchanged:s,attested:i,attestationReason:c,remotePath:n.path,url:n.url,reason:s?!1===i?`the published copy does not verify: ${c}`:null:"the published copy is not the bytes that were sealed (sha256 differs)"}}async function list(e={}){const t=vaultTarget(e.env||process.env,e.argv||[]),r=transportFor(t,e),n=RECORDS_DIR,o=await r.list(n),a=o.filter((e=>String(e.Name).endsWith(ANCHOR_SUFFIX))),s=o.filter((e=>!String(e.Name).endsWith(ANCHOR_SUFFIX)&&String(e.Name).endsWith(".json")&&e.Name!==INDEX_NAME)),i=[];for(const e of s){const t=a.find((t=>String(t.Name)===`${e.Name}${ANCHOR_SUFFIX}`));let o=null;if(t){const e=await r.cat(`${n}/${t.Name}`);try{o=JSON.parse(e)}catch{o={unreadable:!0}}}i.push({name:e.Name,bytes:e.Size,emittedAt:e.ModTime,id:o?o.id:null,keyFingerprint:o?o.keyFingerprint:null,sha256:o?o.sha256:null,driveId:o&&o.driveId||e.ID||null,url:o&&o.url||e.url||driveUrl(e.ID),linked:Boolean(o)})}return{ok:!0,backend:t.backend,remote:t.remote,root:t.root,where:r.describe,records:i}}async function audit(e={}){const t=e.env||process.env,r=e.argv||[],n=vaultTarget(t,r),o=transportFor(n,e),a=Number(flag(r,"--max"))||500;let s;try{s=await o.listRecursive("")}catch(e){return{ok:!1,backend:n.backend,where:o.describe,error:e&&e.message||String(e),findings:[],checked:0}}const i=e.secret||null,c=[],l=[];let u=0;for(const t of s){const r=String(t.Path||t.Name);if(u>=a){l.push({path:r,reason:`stopped after ${a} files`});continue}if(Number(t.Size)>2097152){l.push({path:r,reason:"larger than 2097152 bytes"});continue}let n;u+=1;try{n=await o.cat(r)}catch(e){l.push({path:r,reason:e&&e.message||String(e)});continue}const s=inspect(r,n,{secret:i});s.dangerous&&c.push({path:r,reason:s.reason})}return{ok:0===c.length,backend:n.backend,remote:n.remote,root:n.root,where:o.describe,checked:u,files:s.length,uninspected:l,findings:c}}function rcloneLsjsonRecursive(e,t){const r=rcloneRun(e,["lsjson",remoteSpecOf(e,t),"--files-only","--recursive"]),n=String(r).trim();if(!n)return[];const o=JSON.parse(n);return Array.isArray(o)?o:[]}module.exports={DEFAULT_REMOTE:DEFAULT_REMOTE,DEFAULT_ROOT:DEFAULT_ROOT,DEFAULT_BACKEND:DEFAULT_BACKEND,BACKEND_CLOUD:BACKEND_CLOUD,BACKEND_RCLONE:BACKEND_RCLONE,CLOUD_PREFIX:CLOUD_PREFIX,BACKEND_ENV:BACKEND_ENV,API_BASE_ENV:API_BASE_ENV,RECORDS_DIR:RECORDS_DIR,INDEX_NAME:INDEX_NAME,ANCHOR_SUFFIX:ANCHOR_SUFFIX,ANCHOR_KIND:ANCHOR_KIND,INDEX_KIND:INDEX_KIND,RCLONE_ENV:RCLONE_ENV,REMOTE_ENV:REMOTE_ENV,ROOT_ENV:ROOT_ENV,inspect:inspect,assertPublishable:assertPublishable,publish:publish,checkAnchor:checkAnchor,list:list,audit:audit,localAnchor:localAnchor,relativeToRoot:relativeToRoot,remoteSpecOf:remoteSpecOf,baseName:baseName,driveUrl:driveUrl,vaultTarget:vaultTarget,rcloneBinary:rcloneBinary,rcloneCat:rcloneCat,transportFor:transportFor,cloudApiKey:cloudApiKey,backendFor:backendFor,sha256:sha256,flag:flag,has:has};
105
+ */}function relativeToRoot(e,t){let r=String(t||"").replace(/^\/+/,"");const n=`${e.remote}:`;return r.startsWith(n)&&(r=r.slice(n.length)),r===e.root?"":(r.startsWith(`${e.root}/`)&&(r=r.slice(e.root.length+1)),r)}function remoteSpecOf(e,t){const r=relativeToRoot(e,t);return r?remoteSpec(e,r):remoteSpec(e)}function rcloneRun(e,t,{timeout:r=6e4}={}){try{return execFileSync(e.rclone,t,{encoding:"utf8",timeout:r,stdio:["ignore","pipe","pipe"],maxBuffer:33554432,env:e.env?{...process.env,...e.env}:process.env})}catch(e){const r=String(e&&e.stderr||"").trim().split("\n").filter(e=>!/NOTICE:/.test(e)).pop()||e&&e.message||String(e),n=new Error(`vault: rclone ${t[0]} failed — ${r}`);throw n.code="ERCLONE",n.stderr=String(e&&e.stderr||""),n}}function tempDir(){return fs.mkdtempSync(path.join(os.tmpdir(),"aegis-vault-"))}function cloudApiKey(e={}){if(e.apiKey)return String(e.apiKey).trim();const t=e.env||process.env;try{const e=require("./credentials.js");return String(e.resolveApiKey({env:t,dir:e.aegisHome(t)}).key||"").trim()}catch{return""}}async function cloudRun(e,t,r,{body:n=null,raw:o=!1,timeout:a=6e4,fetchImpl:s=null,apiKey:i=null}={}){const c=i||"";if(!c){const e=new Error("vault: no AEGIS account key on this machine — the aegiscloud vault is the account you already have. Run `aegiscode login`, or publish to a folder you own with `--backend rclone --remote <name>`.");throw e.code="ENOKEY",e}const l=s||("function"==typeof fetch?fetch:null);if(!l){const e=new Error("vault: this Node has no global fetch — upgrade to Node 22+ to use the aegiscloud vault");throw e.code="ENOFETCH",e}const u=new AbortController,d=setTimeout(()=>u.abort(),a);let h;try{h=await l(`${e.apiBase}${CLOUD_PREFIX}${r}`,{method:t,headers:{"Content-Type":"application/json","X-API-Key":c,Authorization:`Bearer ${c}`},body:null===n?void 0:JSON.stringify(n),signal:u.signal})}catch(t){const r=new Error(`vault: could not reach ${e.apiBase} — ${t&&t.message||t}`);throw r.code="ENETWORK",r}finally{clearTimeout(d)}const p=await h.text();let f=null;try{f=p?JSON.parse(p):null}catch{f=null}if(!h.ok){if(404===h.status&&(""===r||r.startsWith("?"))){const t=new Error(`vault: ${e.apiBase} does not serve the account vault yet (${CLOUD_PREFIX} is missing on this server). Publish to a folder you own instead: \`--backend rclone --remote <name> --root <folder>\`.`);throw t.code="ENOVAULT",t.status=404,t}const n=f&&(f.error||f.message)||p.slice(0,200)||`HTTP ${h.status}`,o=new Error(`vault: ${t} ${CLOUD_PREFIX}${r} failed — ${n}`);throw o.code="ECLOUD",o.status=h.status,o}return o?p:null===f?{}:f}function cloudObject(e,t){return`/${String(t||"").split("/").filter(Boolean).map(e=>encodeURIComponent(e)).join("/")}`}function transportFor(e,t={}){if("aegiscloud"===e.backend){const r=cloudApiKey(t),n=(n,o,a)=>cloudRun(e,n,o,{...a,fetchImpl:t.fetch,apiKey:r});return{backend:"aegiscloud",async put(t,r){await n("PUT",cloudObject(e,remoteObjectName(t)),{body:{content:r}})},async putFile(e,t){await this.put(e,fs.readFileSync(t,"utf8"))},async cat(t){try{const r=await n("GET",cloudObject(e,remoteObjectName(t)));return r&&"string"==typeof r.content?r.content:null}catch(e){if(404===e.status)return null;throw e}},async list(t){const r=await n("GET",`?dir=${encodeURIComponent(relativeToRoot(e,t))}`);return Array.isArray(r&&r.files)?r.files:[]},async listRecursive(t){const r=await n("GET",`?dir=${encodeURIComponent(relativeToRoot(e,t))}&recursive=1`);return Array.isArray(r&&r.files)?r.files:[]},describe:`${e.apiBase} (account vault)`}}return{backend:"rclone",async put(t,r,{name:n="object"}={}){const o=tempDir();try{const a=path.join(o,n);fs.writeFileSync(a,r),rcloneRun(e,["copyto",a,remoteSpecOf(e,t)])}finally{fs.rmSync(o,{recursive:!0,force:!0})}},async putFile(t,r){rcloneRun(e,["copyto",r,remoteSpecOf(e,t)])},async cat(t){try{return rcloneRun(e,["cat",remoteSpecOf(e,t)])}catch(e){if("ERCLONE"===e.code&&/not found|does not exist|error 404/i.test(e.stderr||e.message))return null;throw e}},list:async t=>listRaw(e,t),listRecursive:async t=>rcloneLsjsonRecursive(e,t),describe:`${e.remote}:${e.root}`}}function remoteObjectName(e){return relativeToRoot({remote:"",root:""},e).replace(/^\/+/,"")}function inspect(e,t,{secret:r=null,keyPath:n=null}={}){const o=String(e||"");for(const e of KEY_PATH_PATTERNS)if(e.test(o))return{dangerous:!0,reason:`the path looks like key material (${e})`};if(n&&path.resolve(o)===path.resolve(n))return{dangerous:!0,reason:"this path IS the authorship key"};const a=String(null==t?"":t),s=a.trim();if(r&&s.includes(String(r)))return{dangerous:!0,reason:"the content carries the authorship key verbatim"};if(PEM_PRIVATE.test(a))return{dangerous:!0,reason:"the content is a PEM private key"};const i=1===s.split("\n").length;if(i&&BARE_TOKEN.test(s)&&!BARE_HEX.test(s))return{dangerous:!0,reason:"the content is a bare high-entropy token (a raw secret)"};if(i&&BARE_HEX.test(s))return{dangerous:!0,reason:"the content is an unlabelled hex blob (a raw digest or key)"};let c=null;try{c=JSON.parse(a)}catch{c=null}if(c&&"object"==typeof c&&!Array.isArray(c)){if("string"==typeof c.kind&&c.kind.startsWith("aegiscode."))return inspectArtifact(c,r);try{fp.assertNoLeak(c,r||"")}catch(e){return{dangerous:!0,reason:e&&e.message||"failed the leak check"}}}return{dangerous:!1,reason:null}}function inspectArtifact(e,t){const r=new Set(["sha256","attestation","code"]);for(const[n,o]of Object.entries(e)){if(null==o)continue;const e=Array.isArray(o)?o.join("\0"):String(o);if(t&&e.includes(String(t)))return{dangerous:!0,reason:`the link carries the authorship key verbatim in "${n}"`};if(!r.has(n)&&fp.longHexRun(e))return{dangerous:!0,reason:`the link carries a long hex run in "${n}"`}}return void 0===e.sha256||/^[0-9a-f]{64}$/.test(String(e.sha256))?void 0===e.attestation||/^[0-9a-f]{32}$/.test(String(e.attestation))?{dangerous:!1,reason:null}:{dangerous:!0,reason:"the link's attestation is not a 32-hex tag"}:{dangerous:!0,reason:"the link's sha256 is not a 64-hex digest"}}function assertPublishable(e,t,r={}){const n=inspect(e,t,r);if(n.dangerous)throw new Error(`vault: refusing to publish ${e} — ${n.reason}. The vault carries sealed records only: a key that reaches cloud storage can mint records indistinguishable from yours, so it is never a backup. Keep it in ${authorship.defaultKeyPath(r.env||process.env)} (0600) and back it up to a local disk or a password manager.`);return!0}function baseName(e,t=null){const r=e&&e.behaviour?String(e.behaviour):"unobserved",n=String(t||e&&e.createdAt||(new Date).toISOString()).replace(/[:.]/g,"-");return`${e.keyFingerprint}-${r}.${n}`}function driveUrl(e){return e?`https://drive.google.com/open?id=${encodeURIComponent(e)}`:null}function sha256(e){return crypto.createHash("sha256").update(e,"utf8").digest("hex")}function readRecord({file:e=null,record:t=null,secret:r=null,env:n=process.env}){if(e){const t=path.resolve(e);if(!fs.existsSync(t))throw new Error(`vault: no record at ${t}`);const o=fs.readFileSync(t,"utf8");let a;assertPublishable(t,o,{secret:r,keyPath:authorship.defaultKeyPath(n),env:n});try{a=JSON.parse(o)}catch(e){throw new Error(`vault: ${t} is not JSON — ${e.message}`)}return{text:o,record:a,file:t,serialised:o}}if(t){const e=JSON.stringify(t,null,2)+"\n";return{text:e,record:t,file:null,serialised:e}}throw new Error("vault: publish needs a record file or a record")}async function publish(e={}){const t=e.env||process.env,r=e.argv||[],n=vaultTarget(t,r),o=Boolean(e.dryRun)||has(r,"--dry-run"),a=void 0===e.index?!has(r,"--no-index"):Boolean(e.index),s=e.secret||null,{text:i,record:c,file:l}=readRecord({...e,secret:s,env:t});let u;try{u=fp.id(c)}catch(e){throw new Error(`vault: not a sealed φ(α) record — ${e&&e.message||e}`)}const d=authorship.defaultKeyPath(t);assertPublishable(path.basename(l||"record.json"),i,{secret:s,keyPath:d,env:t});const h=`${baseName(c)}.json`,p=`${h}${ANCHOR_SUFFIX}`,f=`records/${h}`,E=`records/${p}`,g=sha256(i),y={v:1,kind:ANCHOR_KIND,id:u,keyFingerprint:c.keyFingerprint,behaviour:c.behaviour||null,code:c.code||null,createdAt:c.createdAt,attestation:c.attestation,sha256:g,bytes:Buffer.byteLength(i,"utf8"),backend:n.backend,remote:n.remote,root:n.root,path:"aegiscloud"===n.backend?`${CLOUD_PREFIX}/${f}`:`${n.root}/${f}`,key:f,emittedAt:new Date(e.now||Date.now()).toISOString(),driveId:null,url:null,index:a?`${n.root}/records/${INDEX_NAME}`:null},N=transportFor(n,e);if(o)return{ok:!0,dryRun:!0,backend:n.backend,anchor:y,url:null,remotePath:y.path,commands:"aegiscloud"===n.backend?[`PUT ${n.apiBase}${CLOUD_PREFIX}/${f}`,`PUT ${n.apiBase}${CLOUD_PREFIX}/${E}`]:[`rclone copyto ${l||"<record>"} ${remoteSpec(n,f)}`,`rclone copyto <anchor> ${remoteSpec(n,E)}`]};l?await N.putFile(f,l):await N.put(f,i,{name:h});const m=(await N.list("records")).find(e=>String(e.Name)===h)||null;m&&(y.driveId=m.ID||null,y.url=m.url||("aegiscloud"===n.backend?null:driveUrl(m.ID)));const A=l?`${l}${ANCHOR_SUFFIX}`:null,v=JSON.stringify(y,null,2)+"\n";await N.put(E,v,{name:p}),A&&fs.writeFileSync(A,v);let S=null;return a&&(S=await appendIndex(n,y,N)),{ok:!0,dryRun:!1,backend:n.backend,anchor:y,url:y.url,localAnchor:A,remotePath:y.path,bytes:y.bytes,sha256:g,indexLines:S}}function rcloneCat(e,t){try{return rcloneRun(e,["cat",remoteSpecOf(e,t)])}catch(e){if("ERCLONE"===e.code&&/not found|does not exist|error 404/i.test(e.stderr||e.message))return null;throw e}}function listRaw(e,t){let r;try{r=rcloneRun(e,["lsjson",remoteSpecOf(e,t),"--files-only"])}catch(e){if("ERCLONE"===e.code&&/not found|does not exist|error 404|directory not found/i.test(e.stderr||e.message))return[];throw e}const n=String(r).trim();if(!n)return[];const o=JSON.parse(n);return Array.isArray(o)?o:[]}async function appendIndex(e,t,r=transportFor(e)){const n=`records/${INDEX_NAME}`,o=await r.cat(n)||"",a=JSON.stringify({kind:INDEX_KIND,id:t.id,keyFingerprint:t.keyFingerprint,sha256:t.sha256,path:t.path,url:t.url,driveId:t.driveId,emittedAt:t.emittedAt});return await r.put(n,o+a+"\n",{name:INDEX_NAME}),(o.trim()?o.trim().split("\n").length:0)+1}function localAnchor(e){const t=`${path.resolve(e)}${ANCHOR_SUFFIX}`;if(!fs.existsSync(t))return null;try{return JSON.parse(fs.readFileSync(t,"utf8"))}catch{return null}}async function checkAnchor(e={}){const t=e.env||process.env,r=e.argv||[],n=e.anchor||(e.file?localAnchor(e.file):null);if(!n)return{ok:!1,reason:"not linked — no anchor beside this record (publish it first)",present:!1,unchanged:null,attested:null};const o=transportFor(vaultTarget(t,r,n),e),a=await o.cat(n.key||n.path);if(null===a)return{ok:!1,reason:`no copy at ${n.path}`,present:!1,unchanged:!1,attested:null,anchor:n};const s=sha256(a)===n.sha256;let i=null,c=null;try{const n=e.key||authorship.resolveKey({argv:r,env:t});if(n.secret){const e=fp.verify(JSON.parse(a),n.secret);i=e.ok,c=e.reason}else c="no authorship key on this machine to recompute with"}catch(e){c=e&&e.message||String(e)}return{ok:s&&!1!==i,anchor:n,present:!0,unchanged:s,attested:i,attestationReason:c,remotePath:n.path,url:n.url,reason:s?!1===i?`the published copy does not verify: ${c}`:null:"the published copy is not the bytes that were sealed (sha256 differs)"}}async function list(e={}){const t=vaultTarget(e.env||process.env,e.argv||[]),r=transportFor(t,e),n="records",o=await r.list(n),a=o.filter(e=>String(e.Name).endsWith(ANCHOR_SUFFIX)),s=o.filter(e=>!String(e.Name).endsWith(ANCHOR_SUFFIX)&&String(e.Name).endsWith(".json")&&e.Name!==INDEX_NAME),i=[];for(const e of s){const t=a.find(t=>String(t.Name)===`${e.Name}${ANCHOR_SUFFIX}`);let o=null;if(t){const e=await r.cat(`${n}/${t.Name}`);try{o=JSON.parse(e)}catch{o={unreadable:!0}}}i.push({name:e.Name,bytes:e.Size,emittedAt:e.ModTime,id:o?o.id:null,keyFingerprint:o?o.keyFingerprint:null,sha256:o?o.sha256:null,driveId:o&&o.driveId||e.ID||null,url:o&&o.url||e.url||driveUrl(e.ID),linked:Boolean(o)})}return{ok:!0,backend:t.backend,remote:t.remote,root:t.root,where:r.describe,records:i}}async function audit(e={}){const t=e.env||process.env,r=e.argv||[],n=vaultTarget(t,r),o=transportFor(n,e),a=Number(flag(r,"--max"))||500;let s;try{s=await o.listRecursive("")}catch(e){return{ok:!1,backend:n.backend,where:o.describe,error:e&&e.message||String(e),findings:[],checked:0}}const i=e.secret||null,c=[],l=[];let u=0;for(const t of s){const r=String(t.Path||t.Name);if(u>=a){l.push({path:r,reason:`stopped after ${a} files`});continue}if(Number(t.Size)>2097152){l.push({path:r,reason:"larger than 2097152 bytes"});continue}let n;u+=1;try{n=await o.cat(r)}catch(e){l.push({path:r,reason:e&&e.message||String(e)});continue}const s=inspect(r,n,{secret:i});s.dangerous&&c.push({path:r,reason:s.reason})}return{ok:0===c.length,backend:n.backend,remote:n.remote,root:n.root,where:o.describe,checked:u,files:s.length,uninspected:l,findings:c}}function rcloneLsjsonRecursive(e,t){const r=rcloneRun(e,["lsjson",remoteSpecOf(e,t),"--files-only","--recursive"]),n=String(r).trim();if(!n)return[];const o=JSON.parse(n);return Array.isArray(o)?o:[]}module.exports={DEFAULT_REMOTE:"gdrive",DEFAULT_ROOT:"AEGIS-AGPL",DEFAULT_BACKEND:"aegiscloud",BACKEND_CLOUD:"aegiscloud",BACKEND_RCLONE:"rclone",CLOUD_PREFIX:CLOUD_PREFIX,BACKEND_ENV:BACKEND_ENV,API_BASE_ENV:API_BASE_ENV,RECORDS_DIR:"records",INDEX_NAME:INDEX_NAME,ANCHOR_SUFFIX:ANCHOR_SUFFIX,ANCHOR_KIND:ANCHOR_KIND,INDEX_KIND:INDEX_KIND,RCLONE_ENV:RCLONE_ENV,REMOTE_ENV:REMOTE_ENV,ROOT_ENV:ROOT_ENV,inspect:inspect,assertPublishable:assertPublishable,publish:publish,checkAnchor:checkAnchor,list:list,audit:audit,localAnchor:localAnchor,relativeToRoot:relativeToRoot,remoteSpecOf:remoteSpecOf,baseName:baseName,driveUrl:driveUrl,vaultTarget:vaultTarget,rcloneBinary:rcloneBinary,rcloneCat:rcloneCat,transportFor:transportFor,cloudApiKey:cloudApiKey,backendFor:backendFor,sha256:sha256,flag:flag,has:has};
@@ -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 haystack(e){if(!e||"object"!=typeof e)return"";const t=[e.title,e.summary,e.cwd,e.id].filter((e=>"string"==typeof e&&e)),s=Array.isArray(e.messages)?e.messages:[];for(const e of s)if(e&&"user"===e.role&&"string"==typeof e.content&&e.content){t.push(e.content.slice(0,400));break}return t.join("\n")}function scoreSession(e,t){const s=String(e||"").trim().toLowerCase();if(!s)return{matched:!0,score:0,field:"all"};const r="string"==typeof(t&&t.title)?t.title.toLowerCase():"",n=haystack(t).toLowerCase();if(r&&r===s)return{matched:!0,score:1e3,field:"title"};if(r&&r.startsWith(s))return{matched:!0,score:900,field:"title"};const o=r?r.indexOf(s):-1;if(-1!==o)return{matched:!0,score:700-o,field:"title"};const i=n.indexOf(s);if(-1!==i)return{matched:!0,score:Math.max(1,400-i),field:"body"};if(r){let e=100,t=-2,n=-1,o=!0;for(const i of s){const s=r.indexOf(i,n+1);if(-1===s){o=!1;break}e+=s===t+1?15:5,0===s&&(e+=20),t=s,n=s}if(o)return{matched:!0,score:e,field:"title"}}return{matched:!1,score:0,field:null}}function rankSessions(e,t){const s=Array.isArray(t)?t:[],r=String(e||"").trim();if(!r)return s.slice();const n=[];for(let e=0;e<s.length;e+=1){const t=s[e],o=scoreSession(r,t);o.matched&&n.push({s:t,i:e,score:o.score})}return n.sort(((e,t)=>t.score-e.score||e.i-t.i)),n.map((e=>e.s))}function matchReason(e,t){const s=String(e||"").trim();if(!s)return null;const r=scoreSession(s,t);return r.matched?"title"===r.field?"title":"body"===r.field?"content":null:null}module.exports={haystack:haystack,scoreSession:scoreSession,rankSessions:rankSessions,matchReason:matchReason};
3
+ "use strict";function haystack(e){if(!e||"object"!=typeof e)return"";const t=[e.title,e.summary,e.cwd,e.id].filter(e=>"string"==typeof e&&e),s=Array.isArray(e.messages)?e.messages:[];for(const e of s)if(e&&"user"===e.role&&"string"==typeof e.content&&e.content){t.push(e.content.slice(0,400));break}return t.join("\n")}function scoreSession(e,t){const s=String(e||"").trim().toLowerCase();if(!s)return{matched:!0,score:0,field:"all"};const r="string"==typeof(t&&t.title)?t.title.toLowerCase():"",n=haystack(t).toLowerCase();if(r&&r===s)return{matched:!0,score:1e3,field:"title"};if(r&&r.startsWith(s))return{matched:!0,score:900,field:"title"};const o=r?r.indexOf(s):-1;if(-1!==o)return{matched:!0,score:700-o,field:"title"};const i=n.indexOf(s);if(-1!==i)return{matched:!0,score:Math.max(1,400-i),field:"body"};if(r){let e=100,t=-2,n=-1,o=!0;for(const i of s){const s=r.indexOf(i,n+1);if(-1===s){o=!1;break}e+=s===t+1?15:5,0===s&&(e+=20),t=s,n=s}if(o)return{matched:!0,score:e,field:"title"}}return{matched:!1,score:0,field:null}}function rankSessions(e,t){const s=Array.isArray(t)?t:[],r=String(e||"").trim();if(!r)return s.slice();const n=[];for(let e=0;e<s.length;e+=1){const t=s[e],o=scoreSession(r,t);o.matched&&n.push({s:t,i:e,score:o.score})}return n.sort((e,t)=>t.score-e.score||e.i-t.i),n.map(e=>e.s)}function matchReason(e,t){const s=String(e||"").trim();if(!s)return null;const r=scoreSession(s,t);return r.matched?"title"===r.field?"title":"body"===r.field?"content":null:null}module.exports={haystack:haystack,scoreSession:scoreSession,rankSessions:rankSessions,matchReason:matchReason};
@@ -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"),{aegisHome:aegisHome}=require("./credentials.js"),STORE_FILE="sessions.json",STORE_VERSION=2,MAX_MESSAGES_PER_SESSION=2e3;function storeDir(e){return e||aegisHome()}function storeFile(e){return path.join(storeDir(e),STORE_FILE)}function nextSeq(e){const t=("number"==typeof e.__seq?e.__seq:0)+1;return e.__seq=t,t}function toEpochMs(e){if("number"==typeof e&&Number.isFinite(e))return e;if("string"==typeof e&&e.trim()){const t=Date.parse(e);if(Number.isFinite(t))return t}return 0}function load(e){try{const t=JSON.parse(fs.readFileSync(storeFile(e),"utf8"));if(t&&"object"==typeof t&&!Array.isArray(t))return t}catch{}return{}}function atomicWrite(e,t){fs.mkdirSync(path.dirname(e),{recursive:!0});const n=`${e}.tmp-${process.pid}`;fs.writeFileSync(n,JSON.stringify(t,null,2),{mode:384}),fs.renameSync(n,e);try{fs.chmodSync(e,384)}catch{}}const LOCK_STALE_MS=3e4,LOCK_WAIT_MS=(()=>{const e=Number(process.env.AEGIS_STORE_LOCK_WAIT_MS);return Number.isFinite(e)&&e>0?e:15e3})(),SLEEP_CELL=new Int32Array(new SharedArrayBuffer(4));function lockFile(e){return`${storeFile(e)}.lock`}function acquireLock(e){const t=lockFile(e);try{fs.mkdirSync(path.dirname(t),{recursive:!0})}catch{return!1}const n=Date.now()+LOCK_WAIT_MS,s=Math.max(200,Math.ceil(LOCK_WAIT_MS/5)+200);for(let e=0;e<s;e++)try{const e=fs.openSync(t,"wx");return fs.writeSync(e,String(process.pid)),fs.closeSync(e),!0}catch{let e=null;try{e=Date.now()-fs.statSync(t).mtimeMs}catch{continue}if(lockAbandoned(t,e)){try{fs.unlinkSync(t)}catch{}continue}if(Date.now()>=n)return!1;Atomics.wait(SLEEP_CELL,0,0,5)}return!1}function pidAlive(e){try{return process.kill(e,0),!0}catch(e){return e&&"EPERM"===e.code}}function lockAbandoned(e,t){let n=0;try{n=Number(String(fs.readFileSync(e,"utf8")).trim())}catch{n=0}return Number.isInteger(n)&&n>0?!pidAlive(n):t>LOCK_STALE_MS}function releaseLock(e){try{fs.unlinkSync(lockFile(e))}catch{}}function mutate(e,t){if(!acquireLock(e))throw new Error(`session store is locked by another writer: ${lockFile(e)} (waited ${LOCK_WAIT_MS}ms — refusing to write unlocked and overwrite it)`);try{const n=load(e),s=t(n);return save(e,n),s}finally{releaseLock(e)}}function save(e,t){atomicWrite(storeFile(e),t)}function trimMessages(e){return Array.isArray(e)?e.length<=MAX_MESSAGES_PER_SESSION?e:e.slice(e.length-MAX_MESSAGES_PER_SESSION):[]}function upsertSession(e,t){const n=t&&t.id;if(!n)throw new Error("session.id is required");return mutate(e,(e=>{const s=e[n]||{messages:[]};e[n]={...s,...t,id:n,version:2};const r=t&&!0===t.seed,i="string"==typeof s.title&&s.title;return!0===s.named&&i?(e[n].title=s.title,e[n].named=!0):r&&i&&s.title&&(e[n].title=s.title),delete e[n].seed,!1!==t.pending&&(e[n].pending=!0),e[n].updatedAt||(e[n].updatedAt=Date.now()),e[n].seq=nextSeq(e),e[n]}))}function appendMessage(e,t,n){if(!t)throw new Error("sessionId is required");return mutate(e,(e=>{const s=e[t]||{id:t,messages:[]},r=Array.isArray(s.messages)?s.messages:[];return s.messages=trimMessages(r.concat(n)),s.updatedAt=Date.now(),s.pending=!0,s.seq=nextSeq(e),e[t]=s,s}))}function recordExchange(e,t){const n=t||{};if(!n.sessionId)return null;const s=n.sessionId;return mutate(e,(e=>{const t=e[s]||{id:s,messages:[]},r=Array.isArray(t.messages)?t.messages:[],i=n.ts||(new Date).toISOString(),o={role:"user",content:null==n.prompt?"":String(n.prompt),ts:i},a={role:"assistant",content:null==n.reply?"":String(n.reply),ts:i};return n.tokens&&(a.tokens=n.tokens),"number"==typeof n.costUsd&&(a.costUsd=n.costUsd),n.status&&(a.status=n.status),n.model&&(a.model=n.model),n.provider&&(a.provider=n.provider),n.origin&&(o.origin=n.origin,a.origin=n.origin),t.messages=trimMessages(r.concat([o,a])),t.title=t.title||String(n.prompt||"").slice(0,60),n.cwd&&(t.cwd=n.cwd),t.origin=n.origin||t.origin||"unknown",t.updatedAt=Date.now(),t.pending=!0===n.pending,t.seq=nextSeq(e),e[s]=t,t}))}function setTitle(e,t,n,s){const r=String(null==n?"":n).trim().slice(0,200);if(!t||!r)return null;const i=s&&!0===s.named;return mutate(e,(e=>{const n=e[t];return n?(n.title=r,i&&(n.named=!0),n.updatedAt=Date.now(),n.seq=nextSeq(e),n):null}))}function listSessions(e){const t=load(e);return Object.values(t).filter((e=>e&&e.id)).sort(((e,t)=>(t.updatedAt||0)-(e.updatedAt||0)||(t.seq||0)-(e.seq||0)))}function getSession(e,t){return load(e)[t]||null}function deleteSession(e,t){return mutate(e,(e=>(delete e[t],{ok:!0})))}function markSynced(e,t,n){return mutate(e,(e=>{const s=e[t];return s?(s.pending=!1,s.lastSyncedAt=Date.now(),n&&n.remoteId&&(s.remoteId=n.remoteId),s.seq=nextSeq(e),s):null}))}function markPending(e,t){return mutate(e,(e=>{const n=e[t];return n?(n.pending=!0,n.seq=nextSeq(e),n):null}))}function listPending(e){return listSessions(e).filter((e=>!1!==e.pending))}function mergeRemoteSessions(e,t){const n=Array.isArray(t)?t:[];return n.length?mutate(e,(e=>{let t=0;for(const s of n){const n=s&&(s.session_id||s.id);if(!n)continue;const r=e[n],i=toEpochMs(s.updated_at??s.updatedAt);r&&(r.pending||(r.updatedAt||0)>=i)||(e[n]={id:n,title:s.title||r&&r.title||"",messages:Array.isArray(s.messages)?s.messages:[],updatedAt:i||Date.now(),pending:!1,lastSyncedAt:Date.now(),remoteId:s.session_id||s.id,origin:s.source||r&&r.origin||"cloud",version:2},e[n].seq=nextSeq(e),t+=1)}return t})):0}function listSummaries(e,t=8){return listSessions(e).slice(0,t).map((e=>{const t=Array.isArray(e.messages)?e.messages:[],n=t.find((e=>e&&"user"===e.role));return{id:e.id,cwd:(e.cwd||"").split(/[\\/]/).filter(Boolean).pop()||"~",summary:String(e.title||n&&n.content||"").slice(0,60),time:new Date(e.updatedAt||Date.now()).toISOString(),own:!0,origin:e.origin||"unknown",messages:t.length,pending:!0===e.pending,dir:String(e.cwd||"")}}))}function readTranscript(e,t){const n=getSession(e,t);return n?(Array.isArray(n.messages)?n.messages:[]).filter((e=>e&&("user"===e.role||"assistant"===e.role))).map((e=>({role:e.role,text:null==e.content?"":String(e.content)}))):[]}function adopt(e,t){const n=storeFile(t);if(!(()=>{try{return fs.existsSync(n)}catch{return!1}})())return{adopted:!1,sessions:0,from:n,reason:"no legacy store"};const s=(()=>{try{const e=JSON.parse(fs.readFileSync(n,"utf8"));return e&&"object"==typeof e&&!Array.isArray(e)?e:{}}catch{return{}}})(),r=Object.values(s).filter((e=>e&&e.id));if(!r.length)return{adopted:!1,sessions:0,from:n,reason:"legacy store empty"};let i=0;return mutate(e,(e=>{for(const t of r)e[t.id]||(e[t.id]={...t,adoptedFrom:n,version:2},e[t.id].seq=nextSeq(e),i+=1);return e.__seq=Math.max(e.__seq||0,s.__seq||0),e.version=2,null})),i?{adopted:!0,sessions:i,from:n}:{adopted:!1,sessions:0,from:n,reason:"already adopted"}}function toMarkdown(e){const t=e&&(e.title||e.id)||"session",n=e&&Array.isArray(e.messages)?e.messages:[],s=[`# ${t}`,""];for(const e of n){const t=e&&e.role||"unknown",n=t.charAt(0).toUpperCase()+t.slice(1),r=e&&(e.content||e.text)||"";s.push(`## ${n}`,"",r,"")}return s.join("\n")}function toJson(e){return JSON.stringify(e,null,2)}module.exports={STORE_FILE:STORE_FILE,STORE_VERSION:2,MAX_MESSAGES_PER_SESSION:MAX_MESSAGES_PER_SESSION,storeDir:storeDir,storeFile:storeFile,lockFile:lockFile,LOCK_STALE_MS:LOCK_STALE_MS,LOCK_WAIT_MS:LOCK_WAIT_MS,toEpochMs:toEpochMs,load:load,save:save,upsertSession:upsertSession,appendMessage:appendMessage,recordExchange:recordExchange,setTitle:setTitle,listSessions:listSessions,getSession:getSession,deleteSession:deleteSession,markSynced:markSynced,markPending:markPending,listPending:listPending,mergeRemoteSessions:mergeRemoteSessions,listSummaries:listSummaries,readTranscript:readTranscript,adopt:adopt,toMarkdown:toMarkdown,toJson:toJson};
3
+ "use strict";const fs=require("node:fs"),path=require("node:path"),{aegisHome:aegisHome}=require("./credentials.js"),STORE_FILE="sessions.json",STORE_VERSION=2,MAX_MESSAGES_PER_SESSION=2e3;function storeDir(e){return e||aegisHome()}function storeFile(e){return path.join(storeDir(e),STORE_FILE)}function nextSeq(e){const t=("number"==typeof e.__seq?e.__seq:0)+1;return e.__seq=t,t}function toEpochMs(e){if("number"==typeof e&&Number.isFinite(e))return e;if("string"==typeof e&&e.trim()){const t=Date.parse(e);if(Number.isFinite(t))return t}return 0}function load(e){try{const t=JSON.parse(fs.readFileSync(storeFile(e),"utf8"));if(t&&"object"==typeof t&&!Array.isArray(t))return t}catch{}return{}}function atomicWrite(e,t){fs.mkdirSync(path.dirname(e),{recursive:!0});const n=`${e}.tmp-${process.pid}`;fs.writeFileSync(n,JSON.stringify(t,null,2),{mode:384}),fs.renameSync(n,e);try{fs.chmodSync(e,384)}catch{}}const LOCK_STALE_MS=3e4,LOCK_WAIT_MS=(()=>{const e=Number(process.env.AEGIS_STORE_LOCK_WAIT_MS);return Number.isFinite(e)&&e>0?e:15e3})(),SLEEP_CELL=new Int32Array(new SharedArrayBuffer(4));function lockFile(e){return`${storeFile(e)}.lock`}function acquireLock(e){const t=lockFile(e);try{fs.mkdirSync(path.dirname(t),{recursive:!0})}catch{return!1}const n=Date.now()+LOCK_WAIT_MS,s=Math.max(200,Math.ceil(LOCK_WAIT_MS/5)+200);for(let e=0;e<s;e++)try{const e=fs.openSync(t,"wx");return fs.writeSync(e,String(process.pid)),fs.closeSync(e),!0}catch{let e=null;try{e=Date.now()-fs.statSync(t).mtimeMs}catch{continue}if(lockAbandoned(t,e)){try{fs.unlinkSync(t)}catch{}continue}if(Date.now()>=n)return!1;Atomics.wait(SLEEP_CELL,0,0,5)}return!1}function pidAlive(e){try{return process.kill(e,0),!0}catch(e){return e&&"EPERM"===e.code}}function lockAbandoned(e,t){let n=0;try{n=Number(String(fs.readFileSync(e,"utf8")).trim())}catch{n=0}return Number.isInteger(n)&&n>0?!pidAlive(n):t>3e4}function releaseLock(e){try{fs.unlinkSync(lockFile(e))}catch{}}function mutate(e,t){if(!acquireLock(e))throw new Error(`session store is locked by another writer: ${lockFile(e)} (waited ${LOCK_WAIT_MS}ms — refusing to write unlocked and overwrite it)`);try{const n=load(e),s=t(n);return save(e,n),s}finally{releaseLock(e)}}function save(e,t){atomicWrite(storeFile(e),t)}function trimMessages(e){return Array.isArray(e)?e.length<=2e3?e:e.slice(e.length-2e3):[]}function upsertSession(e,t){const n=t&&t.id;if(!n)throw new Error("session.id is required");return mutate(e,e=>{const s=e[n]||{messages:[]};e[n]={...s,...t,id:n,version:2};const r=t&&!0===t.seed,i="string"==typeof s.title&&s.title;return!0===s.named&&i?(e[n].title=s.title,e[n].named=!0):r&&i&&s.title&&(e[n].title=s.title),delete e[n].seed,!1!==t.pending&&(e[n].pending=!0),e[n].updatedAt||(e[n].updatedAt=Date.now()),e[n].seq=nextSeq(e),e[n]})}function appendMessage(e,t,n){if(!t)throw new Error("sessionId is required");return mutate(e,e=>{const s=e[t]||{id:t,messages:[]},r=Array.isArray(s.messages)?s.messages:[];return s.messages=trimMessages(r.concat(n)),s.updatedAt=Date.now(),s.pending=!0,s.seq=nextSeq(e),e[t]=s,s})}function recordExchange(e,t){const n=t||{};if(!n.sessionId)return null;const s=n.sessionId;return mutate(e,e=>{const t=e[s]||{id:s,messages:[]},r=Array.isArray(t.messages)?t.messages:[],i=n.ts||(new Date).toISOString(),o={role:"user",content:null==n.prompt?"":String(n.prompt),ts:i},a={role:"assistant",content:null==n.reply?"":String(n.reply),ts:i};return n.tokens&&(a.tokens=n.tokens),"number"==typeof n.costUsd&&(a.costUsd=n.costUsd),n.status&&(a.status=n.status),n.model&&(a.model=n.model),n.provider&&(a.provider=n.provider),n.origin&&(o.origin=n.origin,a.origin=n.origin),t.messages=trimMessages(r.concat([o,a])),t.title=t.title||String(n.prompt||"").slice(0,60),n.cwd&&(t.cwd=n.cwd),t.origin=n.origin||t.origin||"unknown",t.updatedAt=Date.now(),t.pending=!0===n.pending,t.seq=nextSeq(e),e[s]=t,t})}function setTitle(e,t,n,s){const r=String(null==n?"":n).trim().slice(0,200);if(!t||!r)return null;const i=s&&!0===s.named;return mutate(e,e=>{const n=e[t];return n?(n.title=r,i&&(n.named=!0),n.updatedAt=Date.now(),n.seq=nextSeq(e),n):null})}function listSessions(e){const t=load(e);return Object.values(t).filter(e=>e&&e.id).sort((e,t)=>(t.updatedAt||0)-(e.updatedAt||0)||(t.seq||0)-(e.seq||0))}function getSession(e,t){return load(e)[t]||null}function deleteSession(e,t){return mutate(e,e=>(delete e[t],{ok:!0}))}function markSynced(e,t,n){return mutate(e,e=>{const s=e[t];return s?(s.pending=!1,s.lastSyncedAt=Date.now(),n&&n.remoteId&&(s.remoteId=n.remoteId),s.seq=nextSeq(e),s):null})}function markPending(e,t){return mutate(e,e=>{const n=e[t];return n?(n.pending=!0,n.seq=nextSeq(e),n):null})}function listPending(e){return listSessions(e).filter(e=>!1!==e.pending)}function mergeRemoteSessions(e,t){const n=Array.isArray(t)?t:[];return n.length?mutate(e,e=>{let t=0;for(const s of n){const n=s&&(s.session_id||s.id);if(!n)continue;const r=e[n],i=toEpochMs(s.updated_at??s.updatedAt);r&&(r.pending||(r.updatedAt||0)>=i)||(e[n]={id:n,title:s.title||r&&r.title||"",messages:Array.isArray(s.messages)?s.messages:[],updatedAt:i||Date.now(),pending:!1,lastSyncedAt:Date.now(),remoteId:s.session_id||s.id,origin:s.source||r&&r.origin||"cloud",version:2},e[n].seq=nextSeq(e),t+=1)}return t}):0}function listSummaries(e,t=8){return listSessions(e).slice(0,t).map(e=>{const t=Array.isArray(e.messages)?e.messages:[],n=t.find(e=>e&&"user"===e.role);return{id:e.id,cwd:(e.cwd||"").split(/[\\/]/).filter(Boolean).pop()||"~",summary:String(e.title||n&&n.content||"").slice(0,60),time:new Date(e.updatedAt||Date.now()).toISOString(),own:!0,origin:e.origin||"unknown",messages:t.length,pending:!0===e.pending,dir:String(e.cwd||"")}})}function readTranscript(e,t){const n=getSession(e,t);return n?(Array.isArray(n.messages)?n.messages:[]).filter(e=>e&&("user"===e.role||"assistant"===e.role)).map(e=>({role:e.role,text:null==e.content?"":String(e.content)})):[]}function adopt(e,t){const n=storeFile(t);if(!(()=>{try{return fs.existsSync(n)}catch{return!1}})())return{adopted:!1,sessions:0,from:n,reason:"no legacy store"};const s=(()=>{try{const e=JSON.parse(fs.readFileSync(n,"utf8"));return e&&"object"==typeof e&&!Array.isArray(e)?e:{}}catch{return{}}})(),r=Object.values(s).filter(e=>e&&e.id);if(!r.length)return{adopted:!1,sessions:0,from:n,reason:"legacy store empty"};let i=0;return mutate(e,e=>{for(const t of r)e[t.id]||(e[t.id]={...t,adoptedFrom:n,version:2},e[t.id].seq=nextSeq(e),i+=1);return e.__seq=Math.max(e.__seq||0,s.__seq||0),e.version=2,null}),i?{adopted:!0,sessions:i,from:n}:{adopted:!1,sessions:0,from:n,reason:"already adopted"}}function toMarkdown(e){const t=e&&(e.title||e.id)||"session",n=e&&Array.isArray(e.messages)?e.messages:[],s=[`# ${t}`,""];for(const e of n){const t=e&&e.role||"unknown",n=t.charAt(0).toUpperCase()+t.slice(1),r=e&&(e.content||e.text)||"";s.push(`## ${n}`,"",r,"")}return s.join("\n")}function toJson(e){return JSON.stringify(e,null,2)}module.exports={STORE_FILE:STORE_FILE,STORE_VERSION:2,MAX_MESSAGES_PER_SESSION:2e3,storeDir:storeDir,storeFile:storeFile,lockFile:lockFile,LOCK_STALE_MS:3e4,LOCK_WAIT_MS:LOCK_WAIT_MS,toEpochMs:toEpochMs,load:load,save:save,upsertSession:upsertSession,appendMessage:appendMessage,recordExchange:recordExchange,setTitle:setTitle,listSessions:listSessions,getSession:getSession,deleteSession:deleteSession,markSynced:markSynced,markPending:markPending,listPending:listPending,mergeRemoteSessions:mergeRemoteSessions,listSummaries:listSummaries,readTranscript:readTranscript,adopt:adopt,toMarkdown:toMarkdown,toJson:toJson};
@@ -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 fsDefault=require("node:fs"),os=require("node:os"),path=require("node:path"),SKILL_FILE="SKILL.md",DEFAULT_ROOTS=Object.freeze([Object.freeze({rel:[".aegis","skills"],scope:"user"}),Object.freeze({rel:[".aegiscode","skills"],scope:"user"}),Object.freeze({rel:[".claude","skills"],scope:"user"})]),PROJECT_ROOTS=Object.freeze([Object.freeze({rel:[".aegis","skills"],scope:"project"}),Object.freeze({rel:[".aegiscode","skills"],scope:"project"})]),NAME_RE=/^[a-z0-9]+(?:-[a-z0-9]+)*$/,MAX_NAME=64,MAX_DESCRIPTION=300;function isPlainObject(e){return Boolean(e)&&"object"==typeof e&&!Array.isArray(e)}function validateName(e){const t="string"==typeof e?e.trim():"";return t?t.length>MAX_NAME?{ok:!1,reason:`name is longer than ${MAX_NAME} characters`}:NAME_RE.test(t)?{ok:!0,name:t}:{ok:!1,reason:"name must be lowercase letters, digits and single hyphens (for example: release-notes)"}:{ok:!1,reason:"a skill needs a name"}}function parseFrontmatter(e){const t="string"==typeof e?e:"",r=/^---\r?\n([\s\S]*?)\r?\n---\r?\n?/.exec(t);if(!r)return{front:{},body:t,hasFrontmatter:!1};const n={};for(const e of r[1].split(/\r?\n/)){const t=/^([A-Za-z0-9_-]+)\s*:\s*(.*)$/.exec(e);if(!t)continue;const r=t[2].trim().replace(/^['"]|['"]$/g,"");r&&(n[t[1]]=r)}return{front:n,body:t.slice(r[0].length),hasFrontmatter:!0}}function describeOf(e,t){const r=e.front.description||"";if(r)return r.slice(0,MAX_DESCRIPTION);const n=String(e.body||"").split(/\r?\n/).map((e=>e.trim())).find((e=>e&&!e.startsWith("#")));return n?n.slice(0,MAX_DESCRIPTION):`skill ${t}`}function rootsFor(e={}){const t=e.home||os.homedir(),r=e.cwd||process.cwd(),n="win32"===e.platform?path.win32.join:path.join,o=[];for(const e of PROJECT_ROOTS)o.push({dir:n(r,...e.rel),scope:e.scope});for(const e of DEFAULT_ROOTS)o.push({dir:n(t,...e.rel),scope:e.scope});return o}function defaultCreateDir(e={}){const t=e.home||os.homedir();return("win32"===e.platform?path.win32.join:path.join)(t,".aegiscode","skills")}function scan(e={}){const t=e.fs||fsDefault,r=rootsFor(e),n=new Set,o=[];for(const e of r)n.has(e.dir)||(n.add(e.dir),o.push(e));const s=[],i=[];for(const e of o){let r;try{r=t.readdirSync(e.dir,{withFileTypes:!0})}catch{i.push(e.dir);continue}for(const n of r){if(!n.isDirectory())continue;const r=n.name,o=path.join(e.dir,r,SKILL_FILE);let i;try{i=t.readFileSync(o,"utf8")}catch{continue}const a=parseFrontmatter(i),c=a.front.name;s.push({name:r,declaredName:c||null,description:describeOf(a,r),scope:e.scope,path:o,dir:path.join(e.dir,r),hasFrontmatter:a.hasFrontmatter,warning:a.hasFrontmatter?null:"no --- frontmatter block; add name: and description:",bodyPreview:a.body.trim().split(/\r?\n/).slice(0,6).join("\n"),lines:i.split(/\r?\n/).length})}}return s.sort(((e,t)=>e.scope!==t.scope?"user"===e.scope?-1:1:e.name.localeCompare(t.name))),{entries:s,roots:o.map((e=>e.dir)),missing:i}}function find(e,t={}){const r=String(e||"").trim();if(!r)return null;const{entries:n}=scan(t);return n.find((e=>e.name===r))||null}function renderSkill(e={}){const t=String(e.name||"").trim(),r=String(e.description||"").trim()||`Use when the user asks for ${t}.`,n=String(e.body||"").trim()||[`# ${t}`,"","\x3c!-- What this skill does. Be concrete: the steps, the commands, and what",' "done" looks like. The model reads this file when the description above'," matches the task. --\x3e"].join("\n");return["---",`name: ${t}`,`description: ${r.replace(/\r?\n/g," ")}`,"---","",n,""].join("\n")}function create(e={},t={}){const r=t.fs||fsDefault,n=validateName(e.name);if(!n.ok)return{ok:!1,reason:n.reason};const o=n.name,s=String(null==e.description?"":e.description).trim();if(s.length>MAX_DESCRIPTION)return{ok:!1,reason:`description is longer than ${MAX_DESCRIPTION} characters`};const i=String(e.targetDir||"").trim()||defaultCreateDir(t),a=path.join(i,o),c=path.join(a,SKILL_FILE);try{r.mkdirSync(a,{recursive:!0})}catch(e){return{ok:!1,reason:`could not create ${a}: ${e&&e.message?e.message:e}`}}try{r.writeFileSync(c,renderSkill({name:o,description:s,body:e.body}),{encoding:"utf8",flag:"wx"})}catch(e){return e&&"EEXIST"===e.code?{ok:!1,reason:`a skill named "${o}" already exists at ${c}`,exists:!0,path:c}:{ok:!1,reason:`could not write ${c}: ${e&&e.message?e.message:e}`}}return{ok:!0,name:o,dir:a,path:c}}function remove(e,t={}){const r=t.fs||fsDefault,n=find(e,t);if(!n)return{ok:!1,reason:`no skill named "${e}" was found`};try{r.rmSync(n.dir,{recursive:!0,force:!0})}catch(e){return{ok:!1,reason:`could not remove ${n.dir}: ${e&&e.message?e.message:e}`}}return{ok:!0,name:n.name,dir:n.dir}}const DEFAULT_IMPORT_TIMEOUT_MS=1e4,MAX_IMPORT_BYTES=262144;async function fetchSkillText(e,t={}){const r=t.fetch||("function"==typeof fetch?fetch:null);if(!r)throw new Error("network fetch is not available in this runtime");const n=Number.isFinite(t.importTimeoutMs)?t.importTimeoutMs:DEFAULT_IMPORT_TIMEOUT_MS,o="function"==typeof AbortController?new AbortController:null,s=o?setTimeout((()=>o.abort()),n):null;let i;s&&"function"==typeof s.unref&&s.unref();try{i=await r(e,o?{signal:o.signal}:void 0)}catch(t){if(o&&o.signal.aborted)throw new Error(`timed out after ${n/1e3}s fetching ${e}`);throw new Error(t&&t.message||`could not fetch ${e}`)}finally{s&&clearTimeout(s)}if(!i||!1===i.ok){const t=i&&i.status;throw new Error(`fetch failed${t?` (${t})`:""} for ${e}`)}const a=i.headers&&"function"==typeof i.headers.get?Number(i.headers.get("content-length")):NaN;if(Number.isFinite(a)&&a>MAX_IMPORT_BYTES)throw new Error(`refused: ${e} declares ${a} bytes, over the ${MAX_IMPORT_BYTES}-byte limit for a skill`);const c=await i.text();if(Buffer.byteLength(c,"utf8")>MAX_IMPORT_BYTES)throw new Error(`refused: the response is over the ${MAX_IMPORT_BYTES}-byte limit for a skill`);return c}async function importFromUrl(e={},t={}){const r=t.fs||fsDefault,n=String(e.url||"").trim();let o,s;try{o=new URL(n)}catch{return{ok:!1,reason:"not a valid URL"}}if("http:"!==o.protocol&&"https:"!==o.protocol)return{ok:!1,reason:"only http:// and https:// URLs are supported"};try{s=await fetchSkillText(o.toString(),t)}catch(e){return{ok:!1,reason:e&&e.message||`could not fetch ${n}`}}const i=parseFrontmatter(s),a=String(e.name||i.front.name||"").trim(),c=validateName(a);if(!c.ok)return{ok:!1,reason:a?c.reason:"could not determine a name — the fetched file has no name: frontmatter; pass one explicitly"};const l=c.name,f=String(e.targetDir||"").trim()||defaultCreateDir(t),d=path.join(f,l),u=path.join(d,SKILL_FILE);try{r.mkdirSync(d,{recursive:!0})}catch(e){return{ok:!1,reason:`could not create ${d}: ${e&&e.message?e.message:e}`}}try{r.writeFileSync(u,s,{encoding:"utf8",flag:"wx"})}catch(e){return e&&"EEXIST"===e.code?{ok:!1,reason:`a skill named "${l}" already exists at ${u}`,exists:!0,path:u}:{ok:!1,reason:`could not write ${u}: ${e&&e.message?e.message:e}`}}return{ok:!0,name:l,dir:d,path:u,source:o.toString()}}module.exports={SKILL_FILE:SKILL_FILE,DEFAULT_ROOTS:DEFAULT_ROOTS,PROJECT_ROOTS:PROJECT_ROOTS,NAME_RE:NAME_RE,MAX_NAME:MAX_NAME,MAX_DESCRIPTION:MAX_DESCRIPTION,MAX_IMPORT_BYTES:MAX_IMPORT_BYTES,validateName:validateName,parseFrontmatter:parseFrontmatter,describeOf:describeOf,rootsFor:rootsFor,defaultCreateDir:defaultCreateDir,scan:scan,find:find,renderSkill:renderSkill,create:create,remove:remove,importFromUrl:importFromUrl,isPlainObject:isPlainObject};
3
+ "use strict";const fsDefault=require("node:fs"),os=require("node:os"),path=require("node:path"),SKILL_FILE="SKILL.md",DEFAULT_ROOTS=Object.freeze([Object.freeze({rel:[".aegis","skills"],scope:"user"}),Object.freeze({rel:[".aegiscode","skills"],scope:"user"}),Object.freeze({rel:[".claude","skills"],scope:"user"})]),PROJECT_ROOTS=Object.freeze([Object.freeze({rel:[".aegis","skills"],scope:"project"}),Object.freeze({rel:[".aegiscode","skills"],scope:"project"})]),NAME_RE=/^[a-z0-9]+(?:-[a-z0-9]+)*$/,MAX_NAME=64,MAX_DESCRIPTION=300;function isPlainObject(e){return Boolean(e)&&"object"==typeof e&&!Array.isArray(e)}function validateName(e){const t="string"==typeof e?e.trim():"";return t?t.length>64?{ok:!1,reason:"name is longer than 64 characters"}:NAME_RE.test(t)?{ok:!0,name:t}:{ok:!1,reason:"name must be lowercase letters, digits and single hyphens (for example: release-notes)"}:{ok:!1,reason:"a skill needs a name"}}function parseFrontmatter(e){const t="string"==typeof e?e:"",r=/^---\r?\n([\s\S]*?)\r?\n---\r?\n?/.exec(t);if(!r)return{front:{},body:t,hasFrontmatter:!1};const n={};for(const e of r[1].split(/\r?\n/)){const t=/^([A-Za-z0-9_-]+)\s*:\s*(.*)$/.exec(e);if(!t)continue;const r=t[2].trim().replace(/^['"]|['"]$/g,"");r&&(n[t[1]]=r)}return{front:n,body:t.slice(r[0].length),hasFrontmatter:!0}}function describeOf(e,t){const r=e.front.description||"";if(r)return r.slice(0,300);const n=String(e.body||"").split(/\r?\n/).map(e=>e.trim()).find(e=>e&&!e.startsWith("#"));return n?n.slice(0,300):`skill ${t}`}function rootsFor(e={}){const t=e.home||os.homedir(),r=e.cwd||process.cwd(),n="win32"===e.platform?path.win32.join:path.join,o=[];for(const e of PROJECT_ROOTS)o.push({dir:n(r,...e.rel),scope:e.scope});for(const e of DEFAULT_ROOTS)o.push({dir:n(t,...e.rel),scope:e.scope});return o}function defaultCreateDir(e={}){const t=e.home||os.homedir();return("win32"===e.platform?path.win32.join:path.join)(t,".aegiscode","skills")}function scan(e={}){const t=e.fs||fsDefault,r=rootsFor(e),n=new Set,o=[];for(const e of r)n.has(e.dir)||(n.add(e.dir),o.push(e));const s=[],i=[];for(const e of o){let r;try{r=t.readdirSync(e.dir,{withFileTypes:!0})}catch{i.push(e.dir);continue}for(const n of r){if(!n.isDirectory())continue;const r=n.name,o=path.join(e.dir,r,"SKILL.md");let i;try{i=t.readFileSync(o,"utf8")}catch{continue}const a=parseFrontmatter(i),c=a.front.name;s.push({name:r,declaredName:c||null,description:describeOf(a,r),scope:e.scope,path:o,dir:path.join(e.dir,r),hasFrontmatter:a.hasFrontmatter,warning:a.hasFrontmatter?null:"no --- frontmatter block; add name: and description:",bodyPreview:a.body.trim().split(/\r?\n/).slice(0,6).join("\n"),lines:i.split(/\r?\n/).length})}}return s.sort((e,t)=>e.scope!==t.scope?"user"===e.scope?-1:1:e.name.localeCompare(t.name)),{entries:s,roots:o.map(e=>e.dir),missing:i}}function find(e,t={}){const r=String(e||"").trim();if(!r)return null;const{entries:n}=scan(t);return n.find(e=>e.name===r)||null}function renderSkill(e={}){const t=String(e.name||"").trim(),r=String(e.description||"").trim()||`Use when the user asks for ${t}.`,n=String(e.body||"").trim()||[`# ${t}`,"","\x3c!-- What this skill does. Be concrete: the steps, the commands, and what",' "done" looks like. The model reads this file when the description above'," matches the task. --\x3e"].join("\n");return["---",`name: ${t}`,`description: ${r.replace(/\r?\n/g," ")}`,"---","",n,""].join("\n")}function create(e={},t={}){const r=t.fs||fsDefault,n=validateName(e.name);if(!n.ok)return{ok:!1,reason:n.reason};const o=n.name,s=String(null==e.description?"":e.description).trim();if(s.length>300)return{ok:!1,reason:"description is longer than 300 characters"};const i=String(e.targetDir||"").trim()||defaultCreateDir(t),a=path.join(i,o),c=path.join(a,"SKILL.md");try{r.mkdirSync(a,{recursive:!0})}catch(e){return{ok:!1,reason:`could not create ${a}: ${e&&e.message?e.message:e}`}}try{r.writeFileSync(c,renderSkill({name:o,description:s,body:e.body}),{encoding:"utf8",flag:"wx"})}catch(e){return e&&"EEXIST"===e.code?{ok:!1,reason:`a skill named "${o}" already exists at ${c}`,exists:!0,path:c}:{ok:!1,reason:`could not write ${c}: ${e&&e.message?e.message:e}`}}return{ok:!0,name:o,dir:a,path:c}}function remove(e,t={}){const r=t.fs||fsDefault,n=find(e,t);if(!n)return{ok:!1,reason:`no skill named "${e}" was found`};try{r.rmSync(n.dir,{recursive:!0,force:!0})}catch(e){return{ok:!1,reason:`could not remove ${n.dir}: ${e&&e.message?e.message:e}`}}return{ok:!0,name:n.name,dir:n.dir}}const DEFAULT_IMPORT_TIMEOUT_MS=1e4,MAX_IMPORT_BYTES=262144;async function fetchSkillText(e,t={}){const r=t.fetch||("function"==typeof fetch?fetch:null);if(!r)throw new Error("network fetch is not available in this runtime");const n=Number.isFinite(t.importTimeoutMs)?t.importTimeoutMs:1e4,o="function"==typeof AbortController?new AbortController:null,s=o?setTimeout(()=>o.abort(),n):null;let i;s&&"function"==typeof s.unref&&s.unref();try{i=await r(e,o?{signal:o.signal}:void 0)}catch(t){if(o&&o.signal.aborted)throw new Error(`timed out after ${n/1e3}s fetching ${e}`);throw new Error(t&&t.message||`could not fetch ${e}`)}finally{s&&clearTimeout(s)}if(!i||!1===i.ok){const t=i&&i.status;throw new Error(`fetch failed${t?` (${t})`:""} for ${e}`)}const a=i.headers&&"function"==typeof i.headers.get?Number(i.headers.get("content-length")):NaN;if(Number.isFinite(a)&&a>262144)throw new Error(`refused: ${e} declares ${a} bytes, over the 262144-byte limit for a skill`);const c=await i.text();if(Buffer.byteLength(c,"utf8")>262144)throw new Error("refused: the response is over the 262144-byte limit for a skill");return c}async function importFromUrl(e={},t={}){const r=t.fs||fsDefault,n=String(e.url||"").trim();let o,s;try{o=new URL(n)}catch{return{ok:!1,reason:"not a valid URL"}}if("http:"!==o.protocol&&"https:"!==o.protocol)return{ok:!1,reason:"only http:// and https:// URLs are supported"};try{s=await fetchSkillText(o.toString(),t)}catch(e){return{ok:!1,reason:e&&e.message||`could not fetch ${n}`}}const i=parseFrontmatter(s),a=String(e.name||i.front.name||"").trim(),c=validateName(a);if(!c.ok)return{ok:!1,reason:a?c.reason:"could not determine a name — the fetched file has no name: frontmatter; pass one explicitly"};const l=c.name,f=String(e.targetDir||"").trim()||defaultCreateDir(t),d=path.join(f,l),m=path.join(d,"SKILL.md");try{r.mkdirSync(d,{recursive:!0})}catch(e){return{ok:!1,reason:`could not create ${d}: ${e&&e.message?e.message:e}`}}try{r.writeFileSync(m,s,{encoding:"utf8",flag:"wx"})}catch(e){return e&&"EEXIST"===e.code?{ok:!1,reason:`a skill named "${l}" already exists at ${m}`,exists:!0,path:m}:{ok:!1,reason:`could not write ${m}: ${e&&e.message?e.message:e}`}}return{ok:!0,name:l,dir:d,path:m,source:o.toString()}}module.exports={SKILL_FILE:"SKILL.md",DEFAULT_ROOTS:DEFAULT_ROOTS,PROJECT_ROOTS:PROJECT_ROOTS,NAME_RE:NAME_RE,MAX_NAME:64,MAX_DESCRIPTION:300,MAX_IMPORT_BYTES:262144,validateName:validateName,parseFrontmatter:parseFrontmatter,describeOf:describeOf,rootsFor:rootsFor,defaultCreateDir:defaultCreateDir,scan:scan,find:find,renderSkill:renderSkill,create:create,remove:remove,importFromUrl:importFromUrl,isPlainObject:isPlainObject};
@@ -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 TOPUP_MIN_EUR=2,TOPUP_MAX_EUR=1e3,TOPUP_DEFAULT_EUR=10,TOPUP_POLL_MS=4e3,TOPUP_POLL_TRIES=30;function bankAmount(e){if(null==e)return null;if("number"==typeof e)return isFinite(e)?e:null;if("string"==typeof e){const t=Number(e.trim());return""!==e.trim()&&isFinite(t)?t:null}if("object"!=typeof e)return null;if(null!=e.balance_micros){const t=Number(e.balance_micros);return isFinite(t)?t/1e6:null}for(const t of["balance_eur","balance","bank","balance_eur_cents"]){if(!(t in e))continue;const n=Number(e[t]);if(isFinite(n))return"balance_eur_cents"===t?n/100:n}return e.data?bankAmount(e.data):null}function parseTopupAmount(e,t){const n=String(null==e?"":e).trim();if(!n)return{ok:!0,amount:null==t?10:Number(t),message:null};const u=n.replace(/[€$]|eur(o|os)?\b/gi,"").trim(),r=Number(u);return isFinite(r)&&""!==u?Number.isInteger(r)?r<TOPUP_MIN_EUR||r>TOPUP_MAX_EUR?{ok:!1,amount:null,message:`${r} EUR is outside the accepted range — top-ups are ${TOPUP_MIN_EUR}..${TOPUP_MAX_EUR} EUR`}:{ok:!0,amount:r,message:null}:{ok:!1,amount:null,message:`${r} EUR is not whole — Stripe charges whole euro here (e.g. /topup 20)`}:{ok:!1,amount:null,message:`"${n}" is not an amount — give a number of euro, e.g. /topup 20`}}function classifyTopupError(e){const t=e&&(e.status||e.response&&e.response.status)||0,n=e&&e.data||{},u=e&&e.message?e.message:String(e);return Boolean(n.setup_required)||503===t?{status:t||503,message:u,hint:"this deployment has no payment provider configured — top-ups are unavailable here, not on your side",setupRequired:!0}:400===t?{status:t,message:u,hint:`pick an amount between ${TOPUP_MIN_EUR} and ${TOPUP_MAX_EUR} EUR`,setupRequired:!1}:401===t||403===t?{status:t,message:u,hint:"the account key was refused — save a fresh one (aegiscode login) and try again",setupRequired:!1}:402===t?{status:t,message:u,hint:"the server refused the checkout for this account — see /billing for the account state",setupRequired:!1}:t?{status:t,message:u,hint:null,setupRequired:!1}:{status:0,message:u,hint:"the server could not be reached — check the connection and retry",setupRequired:!1}}async function startTopup(e,t){const n=null==t?10:Number(t);if(!e||"function"!=typeof e.tokenBankTopup)return{ok:!1,url:null,status:0,amount:n,setupRequired:!1,message:"this host has no billing client",hint:null};try{const t=await e.tokenBankTopup(n),u=t&&t.url?String(t.url):null;return u?{ok:!0,url:u,status:0,message:null,hint:null,setupRequired:!1,amount:n}:{ok:!1,url:null,status:0,amount:n,setupRequired:!1,message:"the server accepted the request but returned no checkout URL",hint:"check the account in the browser at /billing, then retry"}}catch(e){return{ok:!1,url:null,amount:n,...classifyTopupError(e)}}}function createCreditWatch(e,t){const n=(t||{}).maxTries||30,u={baseline:null,credited:null,tries:0,stopped:!1};return{get baseline(){return u.baseline},get credited(){return u.credited},get tries(){return u.tries},stop(){u.stopped=!0},async tick(){const t=(e,t)=>({state:e,amount:null==t?null:t,baseline:u.baseline});if(u.stopped)return t(null!=u.credited?"credited":"stopped",u.credited);if(u.tries+=1,u.tries>n)return u.stopped=!0,t("expired",null);let r=null;try{r=bankAmount(await e.tokenBankBalance())}catch{return t("pending",null)}return null===r?t("pending",null):null===u.baseline?(u.baseline=r,t("pending",null)):r>u.baseline?(u.stopped=!0,u.credited=r,t("credited",r)):t("pending",null)}}}module.exports={TOPUP_MIN_EUR:TOPUP_MIN_EUR,TOPUP_MAX_EUR:TOPUP_MAX_EUR,TOPUP_DEFAULT_EUR:10,TOPUP_POLL_MS:4e3,TOPUP_POLL_TRIES:30,bankAmount:bankAmount,parseTopupAmount:parseTopupAmount,classifyTopupError:classifyTopupError,startTopup:startTopup,createCreditWatch:createCreditWatch};
3
+ "use strict";const TOPUP_MIN_EUR=2,TOPUP_MAX_EUR=1e3,TOPUP_DEFAULT_EUR=10,TOPUP_POLL_MS=4e3,TOPUP_POLL_TRIES=30;function bankAmount(e){if(null==e)return null;if("number"==typeof e)return isFinite(e)?e:null;if("string"==typeof e){const t=Number(e.trim());return""!==e.trim()&&isFinite(t)?t:null}if("object"!=typeof e)return null;if(null!=e.balance_micros){const t=Number(e.balance_micros);return isFinite(t)?t/1e6:null}for(const t of["balance_eur","balance","bank","balance_eur_cents"]){if(!(t in e))continue;const n=Number(e[t]);if(isFinite(n))return"balance_eur_cents"===t?n/100:n}return e.data?bankAmount(e.data):null}function parseTopupAmount(e,t){const n=String(null==e?"":e).trim();if(!n)return{ok:!0,amount:null==t?10:Number(t),message:null};const u=n.replace(/[€$]|eur(o|os)?\b/gi,"").trim(),r=Number(u);return isFinite(r)&&""!==u?Number.isInteger(r)?r<2||r>1e3?{ok:!1,amount:null,message:`${r} EUR is outside the accepted range — top-ups are 2..1000 EUR`}:{ok:!0,amount:r,message:null}:{ok:!1,amount:null,message:`${r} EUR is not whole — Stripe charges whole euro here (e.g. /topup 20)`}:{ok:!1,amount:null,message:`"${n}" is not an amount — give a number of euro, e.g. /topup 20`}}function classifyTopupError(e){const t=e&&(e.status||e.response&&e.response.status)||0,n=e&&e.data||{},u=e&&e.message?e.message:String(e);return Boolean(n.setup_required)||503===t?{status:t||503,message:u,hint:"this deployment has no payment provider configured — top-ups are unavailable here, not on your side",setupRequired:!0}:400===t?{status:t,message:u,hint:"pick an amount between 2 and 1000 EUR",setupRequired:!1}:401===t||403===t?{status:t,message:u,hint:"the account key was refused — save a fresh one (aegiscode login) and try again",setupRequired:!1}:402===t?{status:t,message:u,hint:"the server refused the checkout for this account — see /billing for the account state",setupRequired:!1}:t?{status:t,message:u,hint:null,setupRequired:!1}:{status:0,message:u,hint:"the server could not be reached — check the connection and retry",setupRequired:!1}}async function startTopup(e,t){const n=null==t?10:Number(t);if(!e||"function"!=typeof e.tokenBankTopup)return{ok:!1,url:null,status:0,amount:n,setupRequired:!1,message:"this host has no billing client",hint:null};try{const t=await e.tokenBankTopup(n),u=t&&t.url?String(t.url):null;return u?{ok:!0,url:u,status:0,message:null,hint:null,setupRequired:!1,amount:n}:{ok:!1,url:null,status:0,amount:n,setupRequired:!1,message:"the server accepted the request but returned no checkout URL",hint:"check the account in the browser at /billing, then retry"}}catch(e){return{ok:!1,url:null,amount:n,...classifyTopupError(e)}}}function createCreditWatch(e,t){const n=(t||{}).maxTries||30,u={baseline:null,credited:null,tries:0,stopped:!1};return{get baseline(){return u.baseline},get credited(){return u.credited},get tries(){return u.tries},stop(){u.stopped=!0},async tick(){const t=(e,t)=>({state:e,amount:null==t?null:t,baseline:u.baseline});if(u.stopped)return t(null!=u.credited?"credited":"stopped",u.credited);if(u.tries+=1,u.tries>n)return u.stopped=!0,t("expired",null);let r=null;try{r=bankAmount(await e.tokenBankBalance())}catch{return t("pending",null)}return null===r?t("pending",null):null===u.baseline?(u.baseline=r,t("pending",null)):r>u.baseline?(u.stopped=!0,u.credited=r,t("credited",r)):t("pending",null)}}}module.exports={TOPUP_MIN_EUR:2,TOPUP_MAX_EUR:1e3,TOPUP_DEFAULT_EUR:10,TOPUP_POLL_MS:4e3,TOPUP_POLL_TRIES:30,bankAmount:bankAmount,parseTopupAmount:parseTopupAmount,classifyTopupError:classifyTopupError,startTopup:startTopup,createCreditWatch:createCreditWatch};
@@ -1,3 +1,3 @@
1
1
  // SPDX-License-Identifier: AGPL-3.0-or-later
2
2
  // Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
3
- "use strict";const crypto=require("node:crypto"),MIN_STROKES=3,MAX_STROKES=64,MAX_SAMPLES=2e4,DEFAULT_IDLE_GAP_MS=140,TOUCH_VERSION=1,SIG_LENGTH=16,AXES=Object.freeze([{name:"samples",mode:"linear",tol:3},{name:"durationMs",mode:"linear",tol:150},{name:"straightness",mode:"linear",tol:.15},{name:"verticalBias",mode:"linear",tol:.15},{name:"pauseRatio",mode:"linear",tol:.15},{name:"dtCv",mode:"linear",tol:.15},{name:"turnMean",mode:"linear",tol:.12},{name:"speedSkew",mode:"linear",tol:.5},{name:"reversalRate",mode:"linear",tol:.1},{name:"pathPerSample",mode:"log",tol:1.25}]),THRESHOLD=1,AXIS_NAMES=Object.freeze(AXES.map((e=>e.name)));function parseXi2(e,{now:t=(()=>Date.now()),device:n=null}={}){const s=[];let a=null;const o=()=>{if(!a)return;const e=a.valuators;void 0===e[0]&&void 0===e[1]||s.push({type:a.type,device:a.device,dx:Number(e[0]||0),dy:Number(e[1]||0),t:a.t}),a=null};for(const n of String(e).split("\n")){const e=n.replace(/\u001b\[[0-9;]*m/g,""),r=/^\s*EVENT\s+type\s+(\d+)\s*(?:\(([^)]*)\))?/.exec(e);if(r){o(),a={type:Number(r[1]),name:r[2]||"",device:null,valuators:{},t:t()};continue}const i=/^\s*device:\s*(\d+)/.exec(e);if(i&&a){a.device=Number(i[1]);continue}if(a){const t=/^\s*(\d+):\s*(-?[\d.]+)\s*(?:\((-?[\d.]+)\))?\s*$/.exec(e);if(t){a.valuators[Number(t[1])]=Number(t[2]);continue}continue}const u=/^\s*(?:motion|raw motion)\s+id\s+(\d+)\s+\[[^\]]*\]\s*(.*)$/.exec(e);if(u){const e={};for(const t of u[2].matchAll(/(\d+):\s*(-?\d+)/g))e[Number(t[1])]=Number(t[2]);void 0===e[0]&&void 0===e[1]||s.push({type:0,device:Number(u[1]),dx:Number(e[0]||0),dy:Number(e[1]||0),t:t()})}}return o(),(null===n?s:s.filter((e=>e.device===n))).slice(0,2e4)}function segmentStrokes(e,{idleGapMs:t=DEFAULT_IDLE_GAP_MS}={}){const n=[];let s=[];for(const a of e)s.length&&a.t-s[s.length-1].t>t&&(n.push(s),s=[]),s.push(a);return s.length&&n.push(s),n.filter((e=>e.length>1)).slice(0,MAX_STROKES)}const mean=e=>e.length?e.reduce(((e,t)=>e+t),0)/e.length:0;function strokeFeatures(e){const t=e.length;let n=0,s=0,a=0,o=0,r=0,i=0;const u=[],l=[];let c=0,m=0,d=null;for(let h=0;h<t;h++){const t=e[h],S=Math.hypot(t.dx,t.dy);if(n+=S,s+=t.dx,a+=t.dy,0===S&&o++,h>0){const n=Math.max(1,e[h].t-e[h-1].t);l.push(n),u.push(S/n);const s=Math.atan2(t.dy,t.dx);if(null!==d){let e=s-d;for(;e>Math.PI;)e-=2*Math.PI;for(;e<-Math.PI;)e+=2*Math.PI;r+=Math.abs(e)}d=s}const f=Math.sign(t.dx),p=Math.sign(t.dy);f&&c&&f!==c&&i++,p&&m&&p!==m&&i++,f&&(c=f),p&&(m=p)}const h=Math.hypot(s,a),S=Math.max(1,e[t-1].t-e[0].t),f=mean(u),p=mean(l),M=mean(l.map((e=>(e-p)**2)));return{samples:t,durationMs:S,straightness:n?h/n:0,verticalBias:n?Math.abs(a)/n:0,pauseRatio:o/t,dtCv:p?Math.sqrt(M)/p:0,turnMean:t>1?r/(t-1):0,speedSkew:f?Math.max(...u)/f-1:0,reversalRate:i/t,pathPerSample:n/t}}function binValue(e,t){const n=Number.isFinite(t)?t:0;return"log"===e.mode?n<=0?0:Math.round(Math.log(n)/Math.log(e.tol)):Math.round(n/e.tol)}function binDistance(e,t,n){if("log"===e.mode){const s=Math.log(e.tol),a=t*s,o=n*s;return Math.abs(a-o)}return Math.abs(t-n)}function quantise(e){const t={};for(const n of AXES)t[n.name]=binValue(n,e[n.name]);return t}function medians(e){const t={};for(const n of AXES){const s=e.map((e=>Number(e[n.name])||0)).sort(((e,t)=>e-t)),a=Math.floor(s.length/2),o=s.length%2?s[a]:(s[a-1]+s[a])/2;t[n.name]=Number.isFinite(o)?o:0}return t}function signatureBody(e){const t=quantise(e);return TOUCH_VERSION+"\n"+AXIS_NAMES.map((e=>`${e}=${t[e]}`)).join("\n")}function signatureFromMedians(e,t){return!e||Number(t)<MIN_STROKES?null:crypto.createHash("sha256").update(signatureBody(e),"utf8").digest("hex").slice(0,SIG_LENGTH)}function touchSignature(e){const t=(Array.isArray(e)?e:[]).filter((e=>e&&Number.isFinite(Number(e.samples))&&Number(e.samples)>1)).slice(0,MAX_STROKES);return t.length<MIN_STROKES?null:signatureFromMedians(medians(t),t.length)}function profile(e,t={}){const n=segmentStrokes(e,t),s=n.map(strokeFeatures),a=touchSignature(s),o=s.length?medians(s):null;return Object.freeze({version:TOUCH_VERSION,kind:"gesture-dynamics",notice:"not a fingerprint: this machine has no fingerprint sensor, and the trackpad exposes no contact geometry through X. These are habits of motion, learned not measured.",signature:a,samples:s.length,strokes:n.length,medians:o?Object.freeze({...o}):null,bins:o?Object.freeze(quantise(o)):null,axes:AXES})}function compareTouch(e,t,{threshold:n=1}={}){const s={score:0,withinTolerance:!1,distance:1/0,worst:[],comparable:!1};if(!e||!t)return s;const a=e.bins||(e.medians?quantise(e.medians):null),o=t.bins||(t.medians?quantise(t.medians):null);if(!a||!o)return s;const r=[];let i=0,u=0;for(const e of AXES){if(void 0===a[e.name]||void 0===o[e.name])continue;const t=binDistance(e,a[e.name],o[e.name]);i+=t,u++,r.push({axis:e.name,bins:t,a:a[e.name],b:o[e.name]})}if(!u)return s;const l=i/u;return r.sort(((e,t)=>t.bins-e.bins)),{score:Number((1/(1+l)).toFixed(4)),withinTolerance:l<=n,distance:Number(l.toFixed(4)),worst:r.slice(0,3),comparable:!0}}module.exports={parseXi2:parseXi2,segmentStrokes:segmentStrokes,strokeFeatures:strokeFeatures,quantise:quantise,medians:medians,touchSignature:touchSignature,signatureBody:signatureBody,signatureFromMedians:signatureFromMedians,profile:profile,compareTouch:compareTouch,binValue:binValue,binDistance:binDistance,AXES:AXES,AXIS_NAMES:AXIS_NAMES,TOUCH_VERSION:TOUCH_VERSION,SIG_LENGTH:SIG_LENGTH,MIN_STROKES:MIN_STROKES,MAX_STROKES:MAX_STROKES,DEFAULT_IDLE_GAP_MS:DEFAULT_IDLE_GAP_MS,THRESHOLD:1};
3
+ "use strict";const crypto=require("node:crypto"),MIN_STROKES=3,MAX_STROKES=64,MAX_SAMPLES=2e4,DEFAULT_IDLE_GAP_MS=140,TOUCH_VERSION=1,SIG_LENGTH=16,AXES=Object.freeze([{name:"samples",mode:"linear",tol:3},{name:"durationMs",mode:"linear",tol:150},{name:"straightness",mode:"linear",tol:.15},{name:"verticalBias",mode:"linear",tol:.15},{name:"pauseRatio",mode:"linear",tol:.15},{name:"dtCv",mode:"linear",tol:.15},{name:"turnMean",mode:"linear",tol:.12},{name:"speedSkew",mode:"linear",tol:.5},{name:"reversalRate",mode:"linear",tol:.1},{name:"pathPerSample",mode:"log",tol:1.25}]),THRESHOLD=1,AXIS_NAMES=Object.freeze(AXES.map(e=>e.name));function parseXi2(e,{now:t=()=>Date.now(),device:n=null}={}){const s=[];let a=null;const o=()=>{if(!a)return;const e=a.valuators;void 0===e[0]&&void 0===e[1]||s.push({type:a.type,device:a.device,dx:Number(e[0]||0),dy:Number(e[1]||0),t:a.t}),a=null};for(const n of String(e).split("\n")){const e=n.replace(/\u001b\[[0-9;]*m/g,""),r=/^\s*EVENT\s+type\s+(\d+)\s*(?:\(([^)]*)\))?/.exec(e);if(r){o(),a={type:Number(r[1]),name:r[2]||"",device:null,valuators:{},t:t()};continue}const i=/^\s*device:\s*(\d+)/.exec(e);if(i&&a){a.device=Number(i[1]);continue}if(a){const t=/^\s*(\d+):\s*(-?[\d.]+)\s*(?:\((-?[\d.]+)\))?\s*$/.exec(e);if(t){a.valuators[Number(t[1])]=Number(t[2]);continue}continue}const u=/^\s*(?:motion|raw motion)\s+id\s+(\d+)\s+\[[^\]]*\]\s*(.*)$/.exec(e);if(u){const e={};for(const t of u[2].matchAll(/(\d+):\s*(-?\d+)/g))e[Number(t[1])]=Number(t[2]);void 0===e[0]&&void 0===e[1]||s.push({type:0,device:Number(u[1]),dx:Number(e[0]||0),dy:Number(e[1]||0),t:t()})}}return o(),(null===n?s:s.filter(e=>e.device===n)).slice(0,2e4)}function segmentStrokes(e,{idleGapMs:t=140}={}){const n=[];let s=[];for(const a of e)s.length&&a.t-s[s.length-1].t>t&&(n.push(s),s=[]),s.push(a);return s.length&&n.push(s),n.filter(e=>e.length>1).slice(0,64)}const mean=e=>e.length?e.reduce((e,t)=>e+t,0)/e.length:0;function strokeFeatures(e){const t=e.length;let n=0,s=0,a=0,o=0,r=0,i=0;const u=[],l=[];let c=0,m=0,d=null;for(let h=0;h<t;h++){const t=e[h],f=Math.hypot(t.dx,t.dy);if(n+=f,s+=t.dx,a+=t.dy,0===f&&o++,h>0){const n=Math.max(1,e[h].t-e[h-1].t);l.push(n),u.push(f/n);const s=Math.atan2(t.dy,t.dx);if(null!==d){let e=s-d;for(;e>Math.PI;)e-=2*Math.PI;for(;e<-Math.PI;)e+=2*Math.PI;r+=Math.abs(e)}d=s}const p=Math.sign(t.dx),g=Math.sign(t.dy);p&&c&&p!==c&&i++,g&&m&&g!==m&&i++,p&&(c=p),g&&(m=g)}const h=Math.hypot(s,a),f=Math.max(1,e[t-1].t-e[0].t),p=mean(u),g=mean(l),b=mean(l.map(e=>(e-g)**2));return{samples:t,durationMs:f,straightness:n?h/n:0,verticalBias:n?Math.abs(a)/n:0,pauseRatio:o/t,dtCv:g?Math.sqrt(b)/g:0,turnMean:t>1?r/(t-1):0,speedSkew:p?Math.max(...u)/p-1:0,reversalRate:i/t,pathPerSample:n/t}}function binValue(e,t){const n=Number.isFinite(t)?t:0;return"log"===e.mode?n<=0?0:Math.round(Math.log(n)/Math.log(e.tol)):Math.round(n/e.tol)}function binDistance(e,t,n){if("log"===e.mode){const s=Math.log(e.tol),a=t*s,o=n*s;return Math.abs(a-o)}return Math.abs(t-n)}function quantise(e){const t={};for(const n of AXES)t[n.name]=binValue(n,e[n.name]);return t}function medians(e){const t={};for(const n of AXES){const s=e.map(e=>Number(e[n.name])||0).sort((e,t)=>e-t),a=Math.floor(s.length/2),o=s.length%2?s[a]:(s[a-1]+s[a])/2;t[n.name]=Number.isFinite(o)?o:0}return t}function signatureBody(e){const t=quantise(e);return"1\n"+AXIS_NAMES.map(e=>`${e}=${t[e]}`).join("\n")}function signatureFromMedians(e,t){return!e||Number(t)<3?null:crypto.createHash("sha256").update(signatureBody(e),"utf8").digest("hex").slice(0,16)}function touchSignature(e){const t=(Array.isArray(e)?e:[]).filter(e=>e&&Number.isFinite(Number(e.samples))&&Number(e.samples)>1).slice(0,64);return t.length<3?null:signatureFromMedians(medians(t),t.length)}function profile(e,t={}){const n=segmentStrokes(e,t),s=n.map(strokeFeatures),a=touchSignature(s),o=s.length?medians(s):null;return Object.freeze({version:1,kind:"gesture-dynamics",notice:"not a fingerprint: this machine has no fingerprint sensor, and the trackpad exposes no contact geometry through X. These are habits of motion, learned not measured.",signature:a,samples:s.length,strokes:n.length,medians:o?Object.freeze({...o}):null,bins:o?Object.freeze(quantise(o)):null,axes:AXES})}function compareTouch(e,t,{threshold:n=1}={}){const s={score:0,withinTolerance:!1,distance:1/0,worst:[],comparable:!1};if(!e||!t)return s;const a=e.bins||(e.medians?quantise(e.medians):null),o=t.bins||(t.medians?quantise(t.medians):null);if(!a||!o)return s;const r=[];let i=0,u=0;for(const e of AXES){if(void 0===a[e.name]||void 0===o[e.name])continue;const t=binDistance(e,a[e.name],o[e.name]);i+=t,u++,r.push({axis:e.name,bins:t,a:a[e.name],b:o[e.name]})}if(!u)return s;const l=i/u;return r.sort((e,t)=>t.bins-e.bins),{score:Number((1/(1+l)).toFixed(4)),withinTolerance:l<=n,distance:Number(l.toFixed(4)),worst:r.slice(0,3),comparable:!0}}module.exports={parseXi2:parseXi2,segmentStrokes:segmentStrokes,strokeFeatures:strokeFeatures,quantise:quantise,medians:medians,touchSignature:touchSignature,signatureBody:signatureBody,signatureFromMedians:signatureFromMedians,profile:profile,compareTouch:compareTouch,binValue:binValue,binDistance:binDistance,AXES:AXES,AXIS_NAMES:AXIS_NAMES,TOUCH_VERSION:1,SIG_LENGTH:16,MIN_STROKES:3,MAX_STROKES:64,DEFAULT_IDLE_GAP_MS:140,THRESHOLD: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
- const https=require("node:https"),fs=require("node:fs");let platformHelpers=null;try{platformHelpers=require("./platform.js")}catch{platformHelpers=null}const REGISTRY="https://registry.npmjs.org",PKG="aegiscode",CHECK_INTERVAL_MS=864e5,TIMEOUT_MS=2500;function isNewer(e,t){const n=e=>String(e||"").trim().replace(/^v/,"").split("-")[0].split(".").map((e=>Number.parseInt(e,10)||0)),s=n(e),r=n(t);for(let e=0;e<Math.max(s.length,r.length);e++){const t=s[e]||0,n=r[e]||0;if(t!==n)return t>n}return!1}const REASONS=Object.freeze({TIMEOUT:"timeout",NETWORK:"network",NOT_FOUND:"not-found",FORBIDDEN:"forbidden",HTTP:"http",MALFORMED:"malformed",TOO_LARGE:"too-large"});function isTransientReason(e,t=null){return e===REASONS.TIMEOUT||e===REASONS.NETWORK||e===REASONS.HTTP&&(!t||t>=500||429===t)}function fetchLatestDetailed({pkg:e=PKG,timeoutMs:t=TIMEOUT_MS}={}){return new Promise((n=>{let s=!1;const r=e=>{s||(s=!0,n(e))},o=(e,t=null)=>r({ok:!1,latest:null,reason:e,status:t});try{const n=https.get(`${REGISTRY}/${e}`,{headers:{accept:"application/vnd.npm.install-v1+json"},timeout:t},(e=>{const t=e.statusCode;if(200!==t)return e.resume(),o(404===t?REASONS.NOT_FOUND:401===t||403===t?REASONS.FORBIDDEN:REASONS.HTTP,t);let s="";e.setEncoding("utf8"),e.on("data",(e=>{s+=e,s.length>2e6&&(n.destroy(),o(REASONS.TOO_LARGE,t))})),e.on("end",(()=>{try{const e=JSON.parse(s)["dist-tags"],n=e&&e.latest||null;if(!n)return o(REASONS.MALFORMED,t);(e=>{r({ok:!0,latest:e,reason:null,status:200})})(n)}catch{o(REASONS.MALFORMED,t)}}))}));n.on("timeout",(()=>{n.destroy(),o(REASONS.TIMEOUT)})),n.on("error",(()=>o(REASONS.NETWORK)))}catch{o(REASONS.NETWORK)}}))}function fetchLatest(e={}){return fetchLatestDetailed(e).then((e=>e.ok?e.latest:null))}const DEFAULT_API_BASE="https://aegiscloud.org",VERSION_BODY_CAP=65536;function fetchServerVersionDetailed({base:e=DEFAULT_API_BASE,clientVersion:t=null,timeoutMs:n=TIMEOUT_MS,getImpl:s=null}={}){return new Promise((r=>{let o=!1;const l=e=>{o||(o=!0,r(e))},a=(e,t=null)=>l({ok:!1,minClient:null,latestCli:null,latestDesktop:null,upgradeRequired:null,decomposed:null,downloadUrl:"",reason:e,status:t}),i=(e,n)=>{const s=e&&"string"==typeof e.min_client?e.min_client:null;if(!s)return a(REASONS.MALFORMED,n);l({ok:!0,minClient:s,latestCli:"string"==typeof e.latest_cli?e.latest_cli:"",latestDesktop:"string"==typeof e.latest_desktop?e.latest_desktop:"",upgradeRequired:t&&"boolean"==typeof e.upgrade_required?e.upgrade_required:null,decomposed:t&&"boolean"==typeof e.decomposed?e.decomposed:null,downloadUrl:"string"==typeof e.download_url?e.download_url:"",reason:null,status:n})};try{const r=`${String(e||DEFAULT_API_BASE).replace(/\/+$/,"")}/api/v1/version`,l={accept:"application/json"};t&&(l["X-AEGIS-Version"]=String(t));const c=e=>{const t=e.statusCode;if(200!==t)return e.resume(),a(404===t?REASONS.NOT_FOUND:401===t||403===t?REASONS.FORBIDDEN:REASONS.HTTP,t);let n="";e.setEncoding("utf8"),e.on("data",(s=>{n+=s,n.length>VERSION_BODY_CAP&&(e.destroy(),a(REASONS.TOO_LARGE,t))})),e.on("end",(()=>{if(!o)try{i(JSON.parse(n),t)}catch{a(REASONS.MALFORMED,t)}}))};if("function"==typeof s)return void Promise.resolve(s({url:r,headers:l,timeoutMs:n})).then((e=>{const t=e&&null!=e.status?e.status:0;if(!t)return a(REASONS.NETWORK);if(200!==t)return a(404===t?REASONS.NOT_FOUND:401===t||403===t?REASONS.FORBIDDEN:REASONS.HTTP,t);const n=e&&"string"==typeof e.text?e.text:"";if(n.length>VERSION_BODY_CAP)return a(REASONS.TOO_LARGE,t);try{i(JSON.parse(n),t)}catch{a(REASONS.MALFORMED,t)}})).catch((()=>a(REASONS.NETWORK)));const u=require(/^http:\/\//i.test(r)?"node:http":"node:https").get(r,{headers:l,timeout:n},c);u.on("timeout",(()=>{u.destroy(),a(REASONS.TIMEOUT)})),u.on("error",(()=>a(REASONS.NETWORK)))}catch{a(REASONS.NETWORK)}}))}function fetchServerVersion(e={}){return fetchServerVersionDetailed(e).then((e=>e.ok?e.minClient:null))}async function serverUpdateVerdict({current:e,base:t=DEFAULT_API_BASE,timeoutMs:n=TIMEOUT_MS,getImpl:s=null}={}){const r=await fetchServerVersionDetailed({base:t,clientVersion:e,timeoutMs:n,getImpl:s});if(!r.ok)return{ok:!1,behind:!1,latest:null,required:null,decomposed:null,downloadUrl:"",reason:r.reason,status:r.status};const o=r.minClient||null,l=!0===r.upgradeRequired||!1!==r.upgradeRequired&&!!o&&isNewer(o,e);return{ok:!0,behind:l,latest:l&&(r.latestCli||r.latestDesktop)||o,latestCli:r.latestCli,latestDesktop:r.latestDesktop,required:o,decomposed:r.decomposed,downloadUrl:r.downloadUrl,reason:null,status:r.status}}function updateNotice({current:e,cache:t,save:n,now:s=Date.now(),fetchImpl:r=fetchLatest,intervalMs:o=864e5}={}){const l=t||{};"number"==typeof l.checkedAt&&s-l.checkedAt<o||Promise.resolve(r()).then((e=>{e&&"function"==typeof n&&n({checkedAt:s,latest:e})})).catch((()=>{}));const a=l.latest||null,i=!0===l.decomposed;return{latest:a,behind:!(!a||!isNewer(a,e)),decomposed:i}}function installSpawn(e,t={}){if(!e||"string"!=typeof e.command||!e.command)return null;const n=t&&"object"==typeof t?t:{},s="string"==typeof n.platform&&n.platform?n.platform:process.platform,r=n.env&&"object"==typeof n.env?n.env:process.env,o=void 0===n.helpers?platformHelpers:n.helpers,l=Array.isArray(e.args)?e.args.map(String):[],a=[e.command,...l].join(" ");if("win32"===s){const e=o&&"function"==typeof o.shellSpec?o.shellSpec({platform:s,env:r}):{cmd:"cmd.exe",arg:"/d /s /c"};return{command:e.cmd,args:[...String(e.arg).split(" "),a],shell:!1,script:a}}let i=e.command;if(o&&"function"==typeof o.resolveExecutable)try{const t=o.resolveExecutable(e.command,{platform:s,env:r,..."function"==typeof n.exists?{exists:n.exists}:{}});t&&(i=t)}catch{}return{command:i,args:l.slice(),shell:!1,script:a}}function updatePlan({current:e,latest:t,behind:n,channel:s="npm",pkg:r=PKG,method:o="npm"}={}){const l=String(null==e?"":e),a=t?String(t):null;if(!Boolean(n)||!Boolean(a))return{channel:s,method:o,current:l,latest:a,behind:!1,action:"none",applier:"none",instruction:null,apply:null};const i=APPLIERS[o]||APPLIERS.npm;return{channel:s,method:o,current:l,latest:a,behind:!0,action:i.action,applier:i.name,instruction:i.instruction(r),apply:i.apply?i.apply(r):null}}const APPLIERS=Object.freeze({npm:Object.freeze({name:"npm",action:"npm-update",instruction:e=>`npm i -g ${e}@latest`,apply:e=>({command:"npm",args:["i","-g",`${e}@latest`]})}),pip:Object.freeze({name:"pip",action:"pip-update",instruction:e=>`pip install -U ${e}`,apply:e=>({command:"win32"===process.platform?"python":"python3",args:["-m","pip","install","-U",e]})}),npx:Object.freeze({name:"none",action:"npx-update",instruction:()=>"already fetched fresh on every run — restart to pick up the new version",apply:null}),source:Object.freeze({name:"git",action:"source-update",instruction:()=>"git pull && npm ci (this copy is a source checkout)",apply:null})});function detectInstallMethod({env:e={},argv:t=[],pkg:n=PKG,fileExists:s=(()=>!1),entry:r=""}={}){const o=String(e&&e.AEGIS_INSTALL_METHOD||"").trim().toLowerCase();if(o&&Object.prototype.hasOwnProperty.call(APPLIERS,o))return o;const l=t.map((e=>String(e))).join(" ");return/\bnpx\b/.test(l)||/_npx[\\/]/.test(l)||/_npx[\\/]/.test(r)?"npx":/[\\/]pipx[\\/]venvs[\\/]/.test(r)||/[\\/]site-packages[\\/]/.test(r)?"pip":/[\\/]node_modules[\\/]/.test(r)?"npm":s(".git")&&s("client/update.js")?"source":"npm"}async function checkPublished({current:e,cache:t,save:n,now:s=Date.now(),fetchImpl:r=fetchLatestDetailed,intervalMs:o=864e5,timeoutMs:l=TIMEOUT_MS,pkg:a=PKG}={}){const i=t||null;if(Boolean(i)&&"number"==typeof i.checkedAt&&s-i.checkedAt<o){const t=i.latest||null;return{ok:Boolean(t),latest:t,behind:!(!t||!isNewer(t,e)),reason:t?null:i.reason||null,status:t?200:null==i.status?null:i.status,cached:!0,checkedAt:i.checkedAt}}let c;try{c=await r({pkg:a,timeoutMs:l})}catch(e){c={ok:!1,latest:null,reason:REASONS.NETWORK,status:null,error:String(e&&e.message||e)}}const u={checkedAt:s,latest:c&&c.latest?c.latest:null,reason:c&&c.reason||null,status:c&&null!=c.status?c.status:null};if("function"==typeof n)try{n(u)}catch{}return{ok:Boolean(c&&c.ok&&c.latest),latest:u.latest,behind:!(!u.latest||!isNewer(u.latest,e)),reason:u.reason,status:u.status,cached:!1,checkedAt:s}}function updateLine({current:e,latest:t,behind:n,pkg:s=PKG,method:r="npm"}){const o=updatePlan({current:e,latest:t,behind:n,channel:"npm",pkg:s,method:r});if(!o.behind)return null;const l=`Update available: ${o.current} → ${o.latest}`;return o.apply?`${l} run: ${o.instruction}`:`${l} ${o.instruction}`}function serverNotice({current:e,cache:t,save:n,now:s=Date.now(),verdictImpl:r=serverUpdateVerdict,intervalMs:o=864e5}={}){const l=t||{};return"number"==typeof l.checkedAt&&s-l.checkedAt<o||Promise.resolve().then((()=>r({current:e}))).then((e=>{e&&"function"==typeof n&&n({checkedAt:s,behind:Boolean(e.behind),decomposed:!0===e.decomposed,required:e.required||null,latest:e.latest||null,downloadUrl:e.downloadUrl||"",reason:e.reason||null})})).catch((()=>{})),{behind:Boolean(l.behind),decomposed:!0===l.decomposed,latest:l.latest||null,required:l.required||null,downloadUrl:l.downloadUrl||""}}function serverUpdateLine({behind:e,latest:t,required:n,decomposed:s,downloadUrl:r}={}){if(s)return`${t||n?`This version is DECOMPOSED — update to v${t||n}.`:"This version is DECOMPOSED — update to the latest release."}${r?` ${r}`:""}`;if(!e)return null;const o=t||n||"";return`${o?`This build is no longer served — update to v${o}.`:"This build is no longer served — update to the latest release."}${r?` ${r}`:""}`}module.exports={isNewer:isNewer,fetchLatest:fetchLatest,fetchLatestDetailed:fetchLatestDetailed,fetchServerVersion:fetchServerVersion,fetchServerVersionDetailed:fetchServerVersionDetailed,serverUpdateVerdict:serverUpdateVerdict,serverNotice:serverNotice,serverUpdateLine:serverUpdateLine,isTransientReason:isTransientReason,updateNotice:updateNotice,checkPublished:checkPublished,updatePlan:updatePlan,installSpawn:installSpawn,updateLine:updateLine,detectInstallMethod:detectInstallMethod,APPLIERS:APPLIERS,PKG:PKG,CHECK_INTERVAL_MS:864e5,REASONS:REASONS,DEFAULT_API_BASE:DEFAULT_API_BASE};
3
+ const https=require("node:https"),fs=require("node:fs");let platformHelpers=null;try{platformHelpers=require("./platform.js")}catch{platformHelpers=null}const REGISTRY="https://registry.npmjs.org",PKG="aegiscode",CHECK_INTERVAL_MS=864e5,TIMEOUT_MS=2500;function isNewer(e,t){const n=e=>String(e||"").trim().replace(/^v/,"").split("-")[0].split(".").map(e=>Number.parseInt(e,10)||0),s=n(e),r=n(t);for(let e=0;e<Math.max(s.length,r.length);e++){const t=s[e]||0,n=r[e]||0;if(t!==n)return t>n}return!1}const REASONS=Object.freeze({TIMEOUT:"timeout",NETWORK:"network",NOT_FOUND:"not-found",FORBIDDEN:"forbidden",HTTP:"http",MALFORMED:"malformed",TOO_LARGE:"too-large"});function isTransientReason(e,t=null){return e===REASONS.TIMEOUT||e===REASONS.NETWORK||e===REASONS.HTTP&&(!t||t>=500||429===t)}function fetchLatestDetailed({pkg:e=PKG,timeoutMs:t=2500}={}){return new Promise(n=>{let s=!1;const r=e=>{s||(s=!0,n(e))},o=(e,t=null)=>r({ok:!1,latest:null,reason:e,status:t});try{const n=https.get(`${REGISTRY}/${e}`,{headers:{accept:"application/vnd.npm.install-v1+json"},timeout:t},e=>{const t=e.statusCode;if(200!==t)return e.resume(),o(404===t?REASONS.NOT_FOUND:401===t||403===t?REASONS.FORBIDDEN:REASONS.HTTP,t);let s="";e.setEncoding("utf8"),e.on("data",e=>{s+=e,s.length>2e6&&(n.destroy(),o(REASONS.TOO_LARGE,t))}),e.on("end",()=>{try{const e=JSON.parse(s)["dist-tags"],n=e&&e.latest||null;if(!n)return o(REASONS.MALFORMED,t);(e=>{r({ok:!0,latest:e,reason:null,status:200})})(n)}catch{o(REASONS.MALFORMED,t)}})});n.on("timeout",()=>{n.destroy(),o(REASONS.TIMEOUT)}),n.on("error",()=>o(REASONS.NETWORK))}catch{o(REASONS.NETWORK)}})}function fetchLatest(e={}){return fetchLatestDetailed(e).then(e=>e.ok?e.latest:null)}const DEFAULT_API_BASE="https://aegiscloud.org",VERSION_BODY_CAP=65536;function fetchServerVersionDetailed({base:e=DEFAULT_API_BASE,clientVersion:t=null,timeoutMs:n=2500,getImpl:s=null}={}){return new Promise(r=>{let o=!1;const l=e=>{o||(o=!0,r(e))},a=(e,t=null)=>l({ok:!1,minClient:null,latestCli:null,latestDesktop:null,upgradeRequired:null,decomposed:null,downloadUrl:"",reason:e,status:t}),i=(e,n)=>{const s=e&&"string"==typeof e.min_client?e.min_client:null;if(!s)return a(REASONS.MALFORMED,n);l({ok:!0,minClient:s,latestCli:"string"==typeof e.latest_cli?e.latest_cli:"",latestDesktop:"string"==typeof e.latest_desktop?e.latest_desktop:"",upgradeRequired:t&&"boolean"==typeof e.upgrade_required?e.upgrade_required:null,decomposed:t&&"boolean"==typeof e.decomposed?e.decomposed:null,downloadUrl:"string"==typeof e.download_url?e.download_url:"",reason:null,status:n})};try{const r=`${String(e||DEFAULT_API_BASE).replace(/\/+$/,"")}/api/v1/version`,l={accept:"application/json"};t&&(l["X-AEGIS-Version"]=String(t));const c=e=>{const t=e.statusCode;if(200!==t)return e.resume(),a(404===t?REASONS.NOT_FOUND:401===t||403===t?REASONS.FORBIDDEN:REASONS.HTTP,t);let n="";e.setEncoding("utf8"),e.on("data",s=>{n+=s,n.length>65536&&(e.destroy(),a(REASONS.TOO_LARGE,t))}),e.on("end",()=>{if(!o)try{i(JSON.parse(n),t)}catch{a(REASONS.MALFORMED,t)}})};if("function"==typeof s)return void Promise.resolve(s({url:r,headers:l,timeoutMs:n})).then(e=>{const t=e&&null!=e.status?e.status:0;if(!t)return a(REASONS.NETWORK);if(200!==t)return a(404===t?REASONS.NOT_FOUND:401===t||403===t?REASONS.FORBIDDEN:REASONS.HTTP,t);const n=e&&"string"==typeof e.text?e.text:"";if(n.length>65536)return a(REASONS.TOO_LARGE,t);try{i(JSON.parse(n),t)}catch{a(REASONS.MALFORMED,t)}}).catch(()=>a(REASONS.NETWORK));const u=require(/^http:\/\//i.test(r)?"node:http":"node:https").get(r,{headers:l,timeout:n},c);u.on("timeout",()=>{u.destroy(),a(REASONS.TIMEOUT)}),u.on("error",()=>a(REASONS.NETWORK))}catch{a(REASONS.NETWORK)}})}function fetchServerVersion(e={}){return fetchServerVersionDetailed(e).then(e=>e.ok?e.minClient:null)}async function serverUpdateVerdict({current:e,base:t=DEFAULT_API_BASE,timeoutMs:n=2500,getImpl:s=null}={}){const r=await fetchServerVersionDetailed({base:t,clientVersion:e,timeoutMs:n,getImpl:s});if(!r.ok)return{ok:!1,behind:!1,latest:null,required:null,decomposed:null,downloadUrl:"",reason:r.reason,status:r.status};const o=r.minClient||null,l=!0===r.upgradeRequired||!1!==r.upgradeRequired&&!!o&&isNewer(o,e);return{ok:!0,behind:l,latest:l&&(r.latestCli||r.latestDesktop)||o,latestCli:r.latestCli,latestDesktop:r.latestDesktop,required:o,decomposed:r.decomposed,downloadUrl:r.downloadUrl,reason:null,status:r.status}}function updateNotice({current:e,cache:t,save:n,now:s=Date.now(),fetchImpl:r=fetchLatest,intervalMs:o=864e5}={}){const l=t||{};"number"==typeof l.checkedAt&&s-l.checkedAt<o||Promise.resolve(r()).then(e=>{e&&"function"==typeof n&&n({checkedAt:s,latest:e})}).catch(()=>{});const a=l.latest||null,i=!0===l.decomposed;return{latest:a,behind:!(!a||!isNewer(a,e)),decomposed:i}}function installSpawn(e,t={}){if(!e||"string"!=typeof e.command||!e.command)return null;const n=t&&"object"==typeof t?t:{},s="string"==typeof n.platform&&n.platform?n.platform:process.platform,r=n.env&&"object"==typeof n.env?n.env:process.env,o=void 0===n.helpers?platformHelpers:n.helpers,l=Array.isArray(e.args)?e.args.map(String):[],a=[e.command,...l].join(" ");if("win32"===s){const e=o&&"function"==typeof o.shellSpec?o.shellSpec({platform:s,env:r}):{cmd:"cmd.exe",arg:"/d /s /c"};return{command:e.cmd,args:[...String(e.arg).split(" "),a],shell:!1,script:a}}let i=e.command;if(o&&"function"==typeof o.resolveExecutable)try{const t=o.resolveExecutable(e.command,{platform:s,env:r,..."function"==typeof n.exists?{exists:n.exists}:{}});t&&(i=t)}catch{}return{command:i,args:l.slice(),shell:!1,script:a}}function updatePlan({current:e,latest:t,behind:n,channel:s="npm",pkg:r=PKG,method:o="npm"}={}){const l=String(null==e?"":e),a=t?String(t):null;if(!Boolean(n)||!Boolean(a))return{channel:s,method:o,current:l,latest:a,behind:!1,action:"none",applier:"none",instruction:null,apply:null};const i=APPLIERS[o]||APPLIERS.npm;return{channel:s,method:o,current:l,latest:a,behind:!0,action:i.action,applier:i.name,instruction:i.instruction(r),apply:i.apply?i.apply(r):null}}const APPLIERS=Object.freeze({npm:Object.freeze({name:"npm",action:"npm-update",instruction:e=>`npm i -g ${e}@latest`,apply:e=>({command:"npm",args:["i","-g",`${e}@latest`]})}),pip:Object.freeze({name:"pip",action:"pip-update",instruction:e=>`pip install -U ${e}`,apply:e=>({command:"win32"===process.platform?"python":"python3",args:["-m","pip","install","-U",e]})}),npx:Object.freeze({name:"none",action:"npx-update",instruction:()=>"already fetched fresh on every run — restart to pick up the new version",apply:null}),source:Object.freeze({name:"git",action:"source-update",instruction:()=>"git pull && npm ci (this copy is a source checkout)",apply:null})});function detectInstallMethod({env:e={},argv:t=[],pkg:n=PKG,fileExists:s=()=>!1,entry:r=""}={}){const o=String(e&&e.AEGIS_INSTALL_METHOD||"").trim().toLowerCase();if(o&&Object.prototype.hasOwnProperty.call(APPLIERS,o))return o;const l=t.map(e=>String(e)).join(" ");return/\bnpx\b/.test(l)||/_npx[\\/]/.test(l)||/_npx[\\/]/.test(r)?"npx":/[\\/]pipx[\\/]venvs[\\/]/.test(r)||/[\\/]site-packages[\\/]/.test(r)?"pip":/[\\/]node_modules[\\/]/.test(r)?"npm":s(".git")&&s("client/update.js")?"source":"npm"}async function checkPublished({current:e,cache:t,save:n,now:s=Date.now(),fetchImpl:r=fetchLatestDetailed,intervalMs:o=864e5,timeoutMs:l=2500,pkg:a=PKG}={}){const i=t||null;if(Boolean(i)&&"number"==typeof i.checkedAt&&s-i.checkedAt<o){const t=i.latest||null;return{ok:Boolean(t),latest:t,behind:!(!t||!isNewer(t,e)),reason:t?null:i.reason||null,status:t?200:null==i.status?null:i.status,cached:!0,checkedAt:i.checkedAt}}let c;try{c=await r({pkg:a,timeoutMs:l})}catch(e){c={ok:!1,latest:null,reason:REASONS.NETWORK,status:null,error:String(e&&e.message||e)}}const u={checkedAt:s,latest:c&&c.latest?c.latest:null,reason:c&&c.reason||null,status:c&&null!=c.status?c.status:null};if("function"==typeof n)try{n(u)}catch{}return{ok:Boolean(c&&c.ok&&c.latest),latest:u.latest,behind:!(!u.latest||!isNewer(u.latest,e)),reason:u.reason,status:u.status,cached:!1,checkedAt:s}}function updateLine({current:e,latest:t,behind:n,pkg:s=PKG,method:r="npm"}){const o=updatePlan({current:e,latest:t,behind:n,channel:"npm",pkg:s,method:r});if(!o.behind)return null;const l=`Update available: ${o.current} → ${o.latest}`;return o.apply?`${l} run: ${o.instruction}`:`${l} ${o.instruction}`}function serverNotice({current:e,cache:t,save:n,now:s=Date.now(),verdictImpl:r=serverUpdateVerdict,intervalMs:o=864e5}={}){const l=t||{};return"number"==typeof l.checkedAt&&s-l.checkedAt<o||Promise.resolve().then(()=>r({current:e})).then(e=>{e&&"function"==typeof n&&n({checkedAt:s,behind:Boolean(e.behind),decomposed:!0===e.decomposed,required:e.required||null,latest:e.latest||null,downloadUrl:e.downloadUrl||"",reason:e.reason||null})}).catch(()=>{}),{behind:Boolean(l.behind),decomposed:!0===l.decomposed,latest:l.latest||null,required:l.required||null,downloadUrl:l.downloadUrl||""}}function serverUpdateLine({behind:e,latest:t,required:n,decomposed:s,downloadUrl:r}={}){if(s)return`${t||n?`This version is DECOMPOSED — update to v${t||n}.`:"This version is DECOMPOSED — update to the latest release."}${r?` ${r}`:""}`;if(!e)return null;const o=t||n||"";return`${o?`This build is no longer served — update to v${o}.`:"This build is no longer served — update to the latest release."}${r?` ${r}`:""}`}module.exports={isNewer:isNewer,fetchLatest:fetchLatest,fetchLatestDetailed:fetchLatestDetailed,fetchServerVersion:fetchServerVersion,fetchServerVersionDetailed:fetchServerVersionDetailed,serverUpdateVerdict:serverUpdateVerdict,serverNotice:serverNotice,serverUpdateLine:serverUpdateLine,isTransientReason:isTransientReason,updateNotice:updateNotice,checkPublished:checkPublished,updatePlan:updatePlan,installSpawn:installSpawn,updateLine:updateLine,detectInstallMethod:detectInstallMethod,APPLIERS:APPLIERS,PKG:PKG,CHECK_INTERVAL_MS:864e5,REASONS:REASONS,DEFAULT_API_BASE:DEFAULT_API_BASE};
@@ -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"),credentials=require("./credentials.js"),USER_MODELS_FILE="models.json",FILE_MODE=384,MAX_MODELS_PER_PROVIDER=32,MAX_PROVIDERS=64,PROVIDER_RE=/^[a-z0-9][a-z0-9._-]{0,63}$/,MODEL_RE=/^[A-Za-z0-9][A-Za-z0-9._/-]{0,95}$/;function userModelsDir(e){return e&&e.dir||credentials.aegisHome(e&&e.env)}function userModelsPath(e){return path.join(userModelsDir(e),USER_MODELS_FILE)}function badValue(e,r,o){return new Error(`aegiscode: ${e} ${JSON.stringify(String(r))} is not usable — ${o}`)}function sanitizeProvider(e){const r=String(null==e?"":e).trim().toLowerCase();if(!r)throw badValue("provider",e,"the provider id is empty");if(!PROVIDER_RE.test(r))throw badValue("provider",e,"a provider id is lowercase letters, digits, dot, dash or underscore (the id `/byok` prints)");return r}function sanitizeModel(e){const r=String(null==e?"":e).trim();if(!r)throw badValue("model id",e,"the model id is empty");if(/:/.test(r))throw badValue("model id",e,"'provider:model' is how a picked model is addressed, so a model id cannot contain a colon");if(!MODEL_RE.test(r))throw badValue("model id",e,"a model id has no spaces — it is the string sent to the vendor (e.g. deepseek-v4.2-preview, claude-opus-9-1)");return r}function isPlainObject(e){return Boolean(e)&&"object"==typeof e&&!Array.isArray(e)}function load(e){const r=userModelsPath(e),o=[];let s;try{s=JSON.parse(fs.readFileSync(r,"utf8"))}catch(s){return s&&"ENOENT"===s.code||o.push({provider:null,model:null,reason:`unreadable: ${s&&s.message||s}`}),{dir:userModelsDir(e),file:r,map:{},invalid:o}}const i={};if(!isPlainObject(s))return o.push({provider:null,model:null,reason:"the file must be an object of provider → [model ids]"}),{dir:userModelsDir(e),file:r,map:i,invalid:o};for(const[e,t]of Object.entries(s)){if("version"===e||"$schema"===e)continue;let s;try{s=sanitizeProvider(e)}catch(r){o.push({provider:e,model:null,reason:r.message});continue}const d=Array.isArray(t)?t:[t],n=new Set,a=[];for(const e of d){let i;try{i=sanitizeModel(e)}catch(r){o.push({provider:s,model:e,reason:r.message});continue}n.has(i)||(n.add(i),a.push(i))}a.length&&(i[s]=a)}return{dir:userModelsDir(e),file:r,map:i,invalid:o}}function readUserModels(e){return load(e).map}function userModelIdsFor(e,r){let o;try{o=sanitizeProvider(e)}catch{return[]}const s=readUserModels(r);return Array.isArray(s[o])?s[o].slice():[]}function writeMap(e,r){const o=userModelsPath(r);fs.mkdirSync(path.dirname(o),{recursive:!0});const s=`${o}.tmp-${process.pid}`;fs.writeFileSync(s,JSON.stringify(e,null,2)+"\n",{mode:FILE_MODE}),fs.renameSync(s,o);try{fs.chmodSync(o,FILE_MODE)}catch{}return e}function addUserModel(e,r,o){const s=sanitizeProvider(e),i=sanitizeModel(r),t=readUserModels(o),d=Array.isArray(t[s])?t[s].slice():[];if(d.includes(i))return{file:userModelsPath(o),provider:s,model:i,added:!1,models:d};if(d.length>=32)throw new Error(`aegiscode: ${s} already carries ${d.length} user models (the cap) — remove one with /model-rm before adding another.`);if(!t[s]&&Object.keys(t).length>=64)throw new Error(`aegiscode: ${Object.keys(t).length} providers already carry user models (the cap).`);const n=[...d,i];return writeMap({...t,[s]:n},o),{file:userModelsPath(o),provider:s,model:i,added:!0,models:n}}function removeUserModel(e,r,o){const s=sanitizeProvider(e),i=sanitizeModel(r),t=readUserModels(o),d=Array.isArray(t[s])?t[s].slice():[];if(!d.includes(i))return{file:userModelsPath(o),provider:s,model:i,removed:!1,models:d};const n=d.filter((e=>e!==i)),a={...t};return n.length?a[s]=n:delete a[s],writeMap(a,o),{file:userModelsPath(o),provider:s,model:i,removed:!0,models:n}}function modelIdsOf(e){return(Array.isArray(e&&e.models)?e.models:[]).map((e=>"string"==typeof e?e:e&&e.id)).map((e=>"string"==typeof e?e.trim():"")).filter(Boolean)}function providerArray(e){return Array.isArray(e)?e:Array.isArray(e&&e.providers)?e.providers:null}function withUserModels(e,r){const o=providerArray(e);if(!o)return[];const s=void 0===r?readUserModels():isPlainObject(r)?r:{},i=[];for(const e of o){if(!e||"object"!=typeof e)continue;const r="string"==typeof e.id?e.id.trim():"",o=r&&Array.isArray(s[r])?s[r]:null;if(!o||!o.length){i.push(e);continue}const t=new Set(modelIdsOf(e)),d=o.map((e=>String(e).trim())).filter((e=>e&&!t.has(e)));if(!d.length){i.push(e);continue}const n=Array.isArray(e.models)?e.models:[];i.push({...e,models:[...n,...d]})}return i}function unmatchedUserProviders(e,r){const o=providerArray(e)||[],s=void 0===r?readUserModels():isPlainObject(r)?r:{},i=new Set(o.map((e=>e&&"string"==typeof e.id?e.id.trim():"")).filter(Boolean));return Object.keys(s).filter((e=>!i.has(e)))}module.exports={USER_MODELS_FILE:USER_MODELS_FILE,MAX_MODELS_PER_PROVIDER:32,userModelsDir:userModelsDir,userModelsPath:userModelsPath,sanitizeProvider:sanitizeProvider,sanitizeModel:sanitizeModel,load:load,readUserModels:readUserModels,userModelIdsFor:userModelIdsFor,addUserModel:addUserModel,removeUserModel:removeUserModel,withUserModels:withUserModels,unmatchedUserProviders:unmatchedUserProviders};
3
+ "use strict";const fs=require("node:fs"),path=require("node:path"),credentials=require("./credentials.js"),USER_MODELS_FILE="models.json",FILE_MODE=384,MAX_MODELS_PER_PROVIDER=32,MAX_PROVIDERS=64,PROVIDER_RE=/^[a-z0-9][a-z0-9._-]{0,63}$/,MODEL_RE=/^[A-Za-z0-9][A-Za-z0-9._/-]{0,95}$/;function userModelsDir(e){return e&&e.dir||credentials.aegisHome(e&&e.env)}function userModelsPath(e){return path.join(userModelsDir(e),"models.json")}function badValue(e,r,o){return new Error(`aegiscode: ${e} ${JSON.stringify(String(r))} is not usable — ${o}`)}function sanitizeProvider(e){const r=String(null==e?"":e).trim().toLowerCase();if(!r)throw badValue("provider",e,"the provider id is empty");if(!PROVIDER_RE.test(r))throw badValue("provider",e,"a provider id is lowercase letters, digits, dot, dash or underscore (the id `/byok` prints)");return r}function sanitizeModel(e){const r=String(null==e?"":e).trim();if(!r)throw badValue("model id",e,"the model id is empty");if(/:/.test(r))throw badValue("model id",e,"'provider:model' is how a picked model is addressed, so a model id cannot contain a colon");if(!MODEL_RE.test(r))throw badValue("model id",e,"a model id has no spaces — it is the string sent to the vendor (e.g. deepseek-v4.2-preview, claude-opus-9-1)");return r}function isPlainObject(e){return Boolean(e)&&"object"==typeof e&&!Array.isArray(e)}function load(e){const r=userModelsPath(e),o=[];let s;try{s=JSON.parse(fs.readFileSync(r,"utf8"))}catch(s){return s&&"ENOENT"===s.code||o.push({provider:null,model:null,reason:`unreadable: ${s&&s.message||s}`}),{dir:userModelsDir(e),file:r,map:{},invalid:o}}const i={};if(!isPlainObject(s))return o.push({provider:null,model:null,reason:"the file must be an object of provider → [model ids]"}),{dir:userModelsDir(e),file:r,map:i,invalid:o};for(const[e,t]of Object.entries(s)){if("version"===e||"$schema"===e)continue;let s;try{s=sanitizeProvider(e)}catch(r){o.push({provider:e,model:null,reason:r.message});continue}const d=Array.isArray(t)?t:[t],n=new Set,a=[];for(const e of d){let i;try{i=sanitizeModel(e)}catch(r){o.push({provider:s,model:e,reason:r.message});continue}n.has(i)||(n.add(i),a.push(i))}a.length&&(i[s]=a)}return{dir:userModelsDir(e),file:r,map:i,invalid:o}}function readUserModels(e){return load(e).map}function userModelIdsFor(e,r){let o;try{o=sanitizeProvider(e)}catch{return[]}const s=readUserModels(r);return Array.isArray(s[o])?s[o].slice():[]}function writeMap(e,r){const o=userModelsPath(r);fs.mkdirSync(path.dirname(o),{recursive:!0});const s=`${o}.tmp-${process.pid}`;fs.writeFileSync(s,JSON.stringify(e,null,2)+"\n",{mode:384}),fs.renameSync(s,o);try{fs.chmodSync(o,384)}catch{}return e}function addUserModel(e,r,o){const s=sanitizeProvider(e),i=sanitizeModel(r),t=readUserModels(o),d=Array.isArray(t[s])?t[s].slice():[];if(d.includes(i))return{file:userModelsPath(o),provider:s,model:i,added:!1,models:d};if(d.length>=32)throw new Error(`aegiscode: ${s} already carries ${d.length} user models (the cap) — remove one with /model-rm before adding another.`);if(!t[s]&&Object.keys(t).length>=64)throw new Error(`aegiscode: ${Object.keys(t).length} providers already carry user models (the cap).`);const n=[...d,i];return writeMap({...t,[s]:n},o),{file:userModelsPath(o),provider:s,model:i,added:!0,models:n}}function removeUserModel(e,r,o){const s=sanitizeProvider(e),i=sanitizeModel(r),t=readUserModels(o),d=Array.isArray(t[s])?t[s].slice():[];if(!d.includes(i))return{file:userModelsPath(o),provider:s,model:i,removed:!1,models:d};const n=d.filter(e=>e!==i),a={...t};return n.length?a[s]=n:delete a[s],writeMap(a,o),{file:userModelsPath(o),provider:s,model:i,removed:!0,models:n}}function modelIdsOf(e){return(Array.isArray(e&&e.models)?e.models:[]).map(e=>"string"==typeof e?e:e&&e.id).map(e=>"string"==typeof e?e.trim():"").filter(Boolean)}function providerArray(e){return Array.isArray(e)?e:Array.isArray(e&&e.providers)?e.providers:null}function withUserModels(e,r){const o=providerArray(e);if(!o)return[];const s=void 0===r?readUserModels():isPlainObject(r)?r:{},i=[];for(const e of o){if(!e||"object"!=typeof e)continue;const r="string"==typeof e.id?e.id.trim():"",o=r&&Array.isArray(s[r])?s[r]:null;if(!o||!o.length){i.push(e);continue}const t=new Set(modelIdsOf(e)),d=o.map(e=>String(e).trim()).filter(e=>e&&!t.has(e));if(!d.length){i.push(e);continue}const n=Array.isArray(e.models)?e.models:[];i.push({...e,models:[...n,...d]})}return i}function unmatchedUserProviders(e,r){const o=providerArray(e)||[],s=void 0===r?readUserModels():isPlainObject(r)?r:{},i=new Set(o.map(e=>e&&"string"==typeof e.id?e.id.trim():"").filter(Boolean));return Object.keys(s).filter(e=>!i.has(e))}module.exports={USER_MODELS_FILE:"models.json",MAX_MODELS_PER_PROVIDER:32,userModelsDir:userModelsDir,userModelsPath:userModelsPath,sanitizeProvider:sanitizeProvider,sanitizeModel:sanitizeModel,load:load,readUserModels:readUserModels,userModelIdsFor:userModelIdsFor,addUserModel:addUserModel,removeUserModel:removeUserModel,withUserModels:withUserModels,unmatchedUserProviders:unmatchedUserProviders};
@@ -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 MAX_FILE_BYTES=33554432,MAX_TEXT_BYTES=524288,MAX_IMAGE_BYTES=5242880,MAX_ATTACHMENTS=8,IMAGE_TOKEN_COST=850,PNG_SIG=Buffer.from([137,80,78,71,13,10,26,10]),JPEG_SIG=Buffer.from([255,216,255]),GIF87=Buffer.from("GIF87a","ascii"),GIF89=Buffer.from("GIF89a","ascii"),PDF_SIG=Buffer.from("%PDF-","ascii"),BMP_SIG=Buffer.from("BM","ascii");function startsWith(t,e){return!(!Buffer.isBuffer(t)||t.length<e.length)&&0===t.compare(e,0,e.length,0,e.length)}function isWebp(t){return Buffer.isBuffer(t)&&t.length>=12&&"RIFF"===t.toString("ascii",0,4)&&"WEBP"===t.toString("ascii",8,12)}function looksLikeText(t,e=8192){if(!Buffer.isBuffer(t)||0===t.length)return!1;const i=t.subarray(0,Math.min(t.length,e));if(i.includes(0))return!1;const n=new TextDecoder("utf-8",{fatal:!0});try{n.decode(i)}catch{return!1}return!0}function sniff(t){return startsWith(t,PNG_SIG)?{kind:"image",mime:"image/png",ext:"png"}:startsWith(t,JPEG_SIG)?{kind:"image",mime:"image/jpeg",ext:"jpg"}:startsWith(t,GIF87)||startsWith(t,GIF89)?{kind:"image",mime:"image/gif",ext:"gif"}:isWebp(t)?{kind:"image",mime:"image/webp",ext:"webp"}:startsWith(t,PDF_SIG)?{kind:"pdf",mime:"application/pdf",ext:"pdf"}:startsWith(t,BMP_SIG)&&t.length>14?{kind:"image",mime:"image/bmp",ext:"bmp"}:looksLikeText(t)?{kind:"text",mime:"text/plain",ext:"txt"}:{kind:"binary",mime:"application/octet-stream",ext:""}}function isVisionMime(t){return"image/png"===t||"image/jpeg"===t||"image/webp"===t||"image/gif"===t}function toDataUrl(t,e){return Buffer.isBuffer(t)?`data:${e||"application/octet-stream"};base64,${t.toString("base64")}`:null}function imagePart(t,e){const i=toDataUrl(t,e);return i?{type:"image_url",image_url:{url:i}}:null}function flattenContent(t){if(null==t)return"";if("string"==typeof t)return t;if(!Array.isArray(t))return String(t);const e=[];for(const i of t)i&&"object"==typeof i&&("string"==typeof i.text?e.push(i.text):"image_url"===i.type&&e.push("[image]"));return e.join("\n")}function imageCount(t){if(!Array.isArray(t))return 0;let e=0;for(const i of t)i&&"image_url"===i.type&&(e+=1);return e}function effectiveMime(t){if(t&&"string"==typeof t.mime&&t.mime)return t.mime;const e=t&&"string"==typeof t.dataUrl?t.dataUrl:"",i=/^data:([^;,]+)[;,]/.exec(e);return i?i[1].toLowerCase():""}function buildContent(t,e){const i=Array.isArray(e)?e.filter(Boolean):[];if(!i.length)return"string"==typeof t?t:"";const n=[],r="string"==typeof t?t:"";r.trim()&&n.push({type:"text",text:r});for(const t of i)if("image"===t.kind&&t.dataUrl&&isVisionMime(effectiveMime(t)))n.push({type:"image_url",image_url:{url:t.dataUrl}});else if("image"===t.kind){const e=effectiveMime(t)||"unknown image type",i=t.path?`[attached image, not inline (${e} is not a vision format): ${t.path}]\nThe file is not attached inline; use a tool to inspect it.`:`[attached image, not inline (${e} is not a vision format)]`;n.push({type:"text",text:i})}else"text"===t.kind&&"string"==typeof t.text?n.push({type:"text",text:`--- ${t.name} ---\n${t.text}`}):"pdf"===t.kind?n.push({type:"text",text:`[attached PDF: ${t.path}]\nUse a tool to read this file.`}):t.path&&n.push({type:"text",text:`[attached file: ${t.path}]`});return 1===n.length&&"text"===n[0].type?n[0].text:n.length?n:r}function pathLines(t){return(Array.isArray(t)?t:[]).map((t=>t&&t.path?/[\s"']/.test(t.path)?`"${t.path}"`:t.path:"")).filter(Boolean).join("\n")}function describe(t){return t&&"object"==typeof t?`${String(t.name||t.path||"file")} · ${humanBytes(Number(t.size)||0)}`:""}function humanBytes(t){const e=Number(t)||0;return e<1024?`${e} B`:e<1048576?`${Math.round(e/1024)} KB`:`${(e/1048576).toFixed(1)} MB`}module.exports={MAX_FILE_BYTES:33554432,MAX_TEXT_BYTES:524288,MAX_IMAGE_BYTES:5242880,MAX_ATTACHMENTS:8,IMAGE_TOKEN_COST:850,sniff:sniff,looksLikeText:looksLikeText,isVisionMime:isVisionMime,toDataUrl:toDataUrl,imagePart:imagePart,flattenContent:flattenContent,imageCount:imageCount,buildContent:buildContent,pathLines:pathLines,describe:describe,humanBytes:humanBytes};
3
+ "use strict";const MAX_FILE_BYTES=33554432,MAX_TEXT_BYTES=524288,MAX_IMAGE_BYTES=5242880,MAX_ATTACHMENTS=8,IMAGE_TOKEN_COST=850,PNG_SIG=Buffer.from([137,80,78,71,13,10,26,10]),JPEG_SIG=Buffer.from([255,216,255]),GIF87=Buffer.from("GIF87a","ascii"),GIF89=Buffer.from("GIF89a","ascii"),PDF_SIG=Buffer.from("%PDF-","ascii"),BMP_SIG=Buffer.from("BM","ascii");function startsWith(t,e){return!(!Buffer.isBuffer(t)||t.length<e.length)&&0===t.compare(e,0,e.length,0,e.length)}function isWebp(t){return Buffer.isBuffer(t)&&t.length>=12&&"RIFF"===t.toString("ascii",0,4)&&"WEBP"===t.toString("ascii",8,12)}function looksLikeText(t,e=8192){if(!Buffer.isBuffer(t)||0===t.length)return!1;const i=t.subarray(0,Math.min(t.length,e));if(i.includes(0))return!1;const n=new TextDecoder("utf-8",{fatal:!0});try{n.decode(i)}catch{return!1}return!0}function sniff(t){return startsWith(t,PNG_SIG)?{kind:"image",mime:"image/png",ext:"png"}:startsWith(t,JPEG_SIG)?{kind:"image",mime:"image/jpeg",ext:"jpg"}:startsWith(t,GIF87)||startsWith(t,GIF89)?{kind:"image",mime:"image/gif",ext:"gif"}:isWebp(t)?{kind:"image",mime:"image/webp",ext:"webp"}:startsWith(t,PDF_SIG)?{kind:"pdf",mime:"application/pdf",ext:"pdf"}:startsWith(t,BMP_SIG)&&t.length>14?{kind:"image",mime:"image/bmp",ext:"bmp"}:looksLikeText(t)?{kind:"text",mime:"text/plain",ext:"txt"}:{kind:"binary",mime:"application/octet-stream",ext:""}}function isVisionMime(t){return"image/png"===t||"image/jpeg"===t||"image/webp"===t||"image/gif"===t}function toDataUrl(t,e){return Buffer.isBuffer(t)?`data:${e||"application/octet-stream"};base64,${t.toString("base64")}`:null}function imagePart(t,e){const i=toDataUrl(t,e);return i?{type:"image_url",image_url:{url:i}}:null}function flattenContent(t){if(null==t)return"";if("string"==typeof t)return t;if(!Array.isArray(t))return String(t);const e=[];for(const i of t)i&&"object"==typeof i&&("string"==typeof i.text?e.push(i.text):"image_url"===i.type&&e.push("[image]"));return e.join("\n")}function imageCount(t){if(!Array.isArray(t))return 0;let e=0;for(const i of t)i&&"image_url"===i.type&&(e+=1);return e}function effectiveMime(t){if(t&&"string"==typeof t.mime&&t.mime)return t.mime;const e=t&&"string"==typeof t.dataUrl?t.dataUrl:"",i=/^data:([^;,]+)[;,]/.exec(e);return i?i[1].toLowerCase():""}function buildContent(t,e){const i=Array.isArray(e)?e.filter(Boolean):[];if(!i.length)return"string"==typeof t?t:"";const n=[],r="string"==typeof t?t:"";r.trim()&&n.push({type:"text",text:r});for(const t of i)if("image"===t.kind&&t.dataUrl&&isVisionMime(effectiveMime(t)))n.push({type:"image_url",image_url:{url:t.dataUrl}});else if("image"===t.kind){const e=effectiveMime(t)||"unknown image type",i=t.path?`[attached image, not inline (${e} is not a vision format): ${t.path}]\nThe file is not attached inline; use a tool to inspect it.`:`[attached image, not inline (${e} is not a vision format)]`;n.push({type:"text",text:i})}else"text"===t.kind&&"string"==typeof t.text?n.push({type:"text",text:`--- ${t.name} ---\n${t.text}`}):"pdf"===t.kind?n.push({type:"text",text:`[attached PDF: ${t.path}]\nUse a tool to read this file.`}):t.path&&n.push({type:"text",text:`[attached file: ${t.path}]`});return 1===n.length&&"text"===n[0].type?n[0].text:n.length?n:r}function pathLines(t){return(Array.isArray(t)?t:[]).map(t=>t&&t.path?/[\s"']/.test(t.path)?`"${t.path}"`:t.path:"").filter(Boolean).join("\n")}function describe(t){return t&&"object"==typeof t?`${String(t.name||t.path||"file")} · ${humanBytes(Number(t.size)||0)}`:""}function humanBytes(t){const e=Number(t)||0;return e<1024?`${e} B`:e<1048576?`${Math.round(e/1024)} KB`:`${(e/1048576).toFixed(1)} MB`}module.exports={MAX_FILE_BYTES:33554432,MAX_TEXT_BYTES:524288,MAX_IMAGE_BYTES:5242880,MAX_ATTACHMENTS:8,IMAGE_TOKEN_COST:850,sniff:sniff,looksLikeText:looksLikeText,isVisionMime:isVisionMime,toDataUrl:toDataUrl,imagePart:imagePart,flattenContent:flattenContent,imageCount:imageCount,buildContent:buildContent,pathLines:pathLines,describe:describe,humanBytes:humanBytes};
@@ -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 queue=require("./queue.js"),gitScope=require("./git-scope.js"),DEFAULT_ROUNDS=40,MAX_ROUND_STOPS=3,WRITE_TOOLS=new Set(["writeFile","editFile"]),DEFAULT_AUTO_CONTINUES=3;function autoContinueLimit(e=process.env){const t=Number.parseInt(e&&e.AEGIS_AUTO_CONTINUE_MAX,10);return Number.isFinite(t)&&t>0?t:3}const AUTO_ROUNDS_OFF=new Set(["0","false","off","no"]);function autoRoundsDefault(e=process.env){const t=e&&e.AEGIS_AUTO_ROUNDS;if(null==t)return!0;const o=String(t).trim().toLowerCase();return!o||!AUTO_ROUNDS_OFF.has(o)}function autoContinuePlan({on:e=!1,used:t=0,limit:o=3}={}){const n=Number.isFinite(o)&&o>0?Math.floor(o):3,r=Number.isFinite(t)&&t>0?Math.floor(t):0;return e?r>=n?{auto:!1,used:0,cap:n}:{auto:!0,used:r+1,cap:n}:{auto:!1,used:r,cap:n}}function writtenPath(e){const t=e&&e.args||{},o=t.file_path||t.path;return o?String(o):""}const DEFAULT_MODEL="nexus-brain",MODEL_CLASSES=Object.freeze(["aegis","byok","local","pro"]),AEGIS_MODEL_RE=/^(?:nexus|aegis)-brain(?:-(?:smart|neo))?$/,AEGIS_MODEL_IDS=Object.freeze(["nexus-brain","aegis-brain"]);function isAegisModel(e){return AEGIS_MODEL_RE.test(String(null==e?"":e).trim())}function normalizeClass(e){return String(null==e?"":e).trim().toLowerCase()||"aegis"}function looksLikeByokModel(e){const t=String(null==e?"":e).trim(),o=t.indexOf(":");return o>0&&o<t.length-1}function modelRefusal(e,t){const o=String(null==e?"":e).trim(),n=normalizeClass(t);if(!MODEL_CLASSES.includes(n))return`"${t}" is not a model class the queue serves (${MODEL_CLASSES.join("/")})`;if("aegis"===n)return!o||isAegisModel(o)?"":`the autonomous queue's Aegis Cloud class runs pooled-brain models only (${DEFAULT_MODEL}, ${AEGIS_MODEL_IDS.join("/")} aliases); "${o}" is not one`;if("byok"===n)return o?looksLikeByokModel(o)?"":`"${o}" is not a byok model id — it must be "<provider>:<model>" (pick one from /models)`:'a byok task needs a model, as "<provider>:<model>" (pick one from /models)';if("pro"===n){if(!o)return"";let e;try{e=require("./claude-pro.js").PRO_MODELS}catch{return"a pro task's model cannot be checked right now — queue it with no --model to let the claude CLI pick"}const t=(Array.isArray(e)?e:[]).map((e=>String(e&&e.id).trim()));return t.includes(o.toLowerCase())?"":`the autonomous queue's Pro class runs the subscription through the claude CLI, which accepts only its own model aliases (${t.join("/")}); "${o}" is not one`}return o?"":"a local task needs a model — the tag of whatever is pulled into the local daemon"}const AUTONOMOUS_REQUEST_RE=/\bautonomously\b|\bon your own\b|\bwithout asking\b|\bend[- ]to[- ]end\b|\bno (?:more )?questions\b|\bfully autonomous\b|\bqueue it\b/i;function isAutonomousRequest(e){return AUTONOMOUS_REQUEST_RE.test(String(e||""))}function maxRounds(e=process.env,t){const o=Number.parseInt(t,10);if(Number.isFinite(o)&&o>0)return o;const n=Number.parseInt(e&&e.AEGIS_AUTONOMOUS_MAX_ROUNDS||"",10);return Number.isFinite(n)&&n>0?n:DEFAULT_ROUNDS}function withRoundHorizon(e,t,o){const n="AEGIS_AUTONOMOUS_MAX_ROUNDS",r=[];for(const e of[t,process.env])e&&-1===r.indexOf(e)&&r.push(e);const s=r.map((e=>({target:e,had:Object.prototype.hasOwnProperty.call(e,n),prev:e[n]})));try{for(const t of r)t[n]=String(e)}catch{}const i=()=>{for(const e of s)try{e.had?e.target[n]=e.prev:delete e.target[n]}catch{}};let a;try{a=o()}catch(e){throw i(),e}return a&&"function"==typeof a.then?a.then((e=>(i(),e)),(e=>{throw i(),e})):(i(),a)}function resolveModel({model:e,env:t,cls:o}={}){const n=String(e||"").trim();if("aegis"!==normalizeClass(o))return n;if(n)return n;const r=t||process.env,s=String(r.AEGIS_AUTONOMOUS_MODEL||r.AEGIS_MODEL||"").trim();return isAegisModel(s)?s:DEFAULT_MODEL}function ignoredEnvModel({model:e,env:t,cls:o}={}){if("aegis"!==normalizeClass(o))return"";if(String(e||"").trim())return"";const n=t||process.env,r=String(n.AEGIS_AUTONOMOUS_MODEL||n.AEGIS_MODEL||"").trim();return!r||isAegisModel(r)?"":`${String(n.AEGIS_AUTONOMOUS_MODEL||"").trim()?"AEGIS_AUTONOMOUS_MODEL":"AEGIS_MODEL"}="${r}" is not an Aegis Cloud model — running on ${DEFAULT_MODEL} instead`}function resolveFanout(e={},t=process.env){const o=e||{};if(!0===o.autonomous||!1===o.singlePass)return!0;const n=t||process.env;return/^(1|true|yes|on)$/i.test(String(n.AEGIS_AUTONOMOUS_FANOUT||"").trim())}function resolveEffort({effort:e,env:t,fanout:o}={}){const n=t||process.env;return String(e||n.AEGIS_AUTONOMOUS_EFFORT||"").trim()||(o?"high":"medium")}function autonomousDirective(e=DEFAULT_ROUNDS){return["# Autonomous mode",`You are running autonomously, not in a conversation: there is no user to answer a question or approve a plan. You have up to ${e} tool rounds this turn; use as many as the task needs.`,"Work the task end to end:","1. Plan in one line, then start acting in the same turn — never end a turn on a plan.","2. Read only what you need to make the change (no fishing through the repo).","2b. If this demand has been made before, establish whether it was met: check recalled memory, the queue file, PLAN.md, and git history for the earlier attempt. When it was fixed and the problem is back, state how it was fixed then and why it regressed, and fix that cause — a blind re-fix is a regression, not a resolution.","3. Make the change with Write/Edit/Bash, then VERIFY it: re-read the result and run the relevant test/command.","4. If verification fails, fix it and verify again — loop until it passes or you are genuinely blocked.",'5. Do not ask for permission, do not hand the work back, do not stop at "let me check…".',"6. Finish with a short report: what changed (file paths), the command you ran to verify, its result, and any remaining blocker."].join("\n")}function digestLine(e,t){const o=String(e.task||"").replace(/\s+/g," ").trim().slice(0,120),n=Boolean(t&&t.ok&&t.stoppedOnRounds)?"⏸":t&&t.ok?"✓":"✗",r=t&&Array.isArray(t.files)&&t.files.slice(0,6)||[],s=r.length?` — touched: ${r.join(", ")}${t.files.length>r.length?", …":""}`:"",i=!t||t.ok?"":` — ${String(t&&t.error||"failed").slice(0,120)}`;return`- #${e.id} ${n} ${o}${s}${i}`}function appendDigest(e,t,{keep:o=6}={}){return String(e||"").split("\n").filter(Boolean).concat(t).slice(-o).join("\n")}function taskPrompt(e,{carry:t="",rounds:o=DEFAULT_ROUNDS}={}){const n=[autonomousDirective(o)];return t&&n.push("# Earlier tasks in this run\nWork already done by this queue — do not redo it, build on it:\n"+t),n.push("# Task\n"+String(e.task||"").trim()),n.join("\n\n")}function assistantText(e){if(!e||"object"!=typeof e)return"";const t=Array.isArray(e.choices)?e.choices[0]:null,o=t&&t.message?t.message.content:e.content;return"string"==typeof o?o:Array.isArray(o)?o.map((e=>"string"==typeof e?e:e&&"string"==typeof e.text?e.text:"")).join(""):""}function errorText(e){return e?"string"==typeof e?e:String(e.message||e.error||e):"unknown error"}function createQueueWorker({engine:e,env:t=process.env,log:o=(()=>{}),git:n=gitScope,now:r=Date.now,canFanOut:s=(()=>!0)}={}){if(!e||"function"!=typeof e.chat)throw new Error("autonomous: a local engine with chat() is required");const i=e=>{try{o(e)}catch{}},a=()=>{try{return!1!==s()}catch{return!1}};async function u(o,{carry:s="",commit:u}={}){const c=o.cwd||process.cwd(),d=normalizeClass(o.class),h=modelRefusal(o.model,d);if(h){const e={ok:!1,error:h,model:o.model,class:d,ms:0};return i({type:"finish",taskId:o.id,ok:!1,result:e}),e}const p=resolveModel({model:o.model,env:t,cls:d}),f=ignoredEnvModel({model:o.model,env:t,cls:d});f&&i({type:"note",taskId:o.id,note:f});const g="aegis"===d&&resolveFanout(o,t),k=g&&a();g&&!k&&i({type:"note",taskId:o.id,note:"fan-out needs Pro (the cloud drain that keeps running after you close the laptop) — this task ran as a single pass"});const O=resolveEffort({effort:o.effort,env:t,fanout:k}),S=maxRounds(t,o.maxRounds);let y=null,E=0;const A=new Set,_=e=>{if(e&&"object"==typeof e)if(e.approval)y=e.approval;else if(e.tool){if("done"===e.tool.phase&&(E+=1,WRITE_TOOLS.has(e.tool.name)&&!1!==e.tool.ok)){const t=writtenPath(e.tool);t&&A.add(t)}i({type:"tool",taskId:o.id,tool:e.tool})}else"string"==typeof e.delta?i({type:"delta",taskId:o.id,text:e.delta}):"string"==typeof e.reasoning&&i({type:"reasoning",taskId:o.id,text:e.reasoning})},v=void 0===u?Boolean(o.commit):Boolean(u),M=v?l((()=>n.gitStatusSnapshot(c)),null):null;i({type:"start",taskId:o.id,model:p,class:d,cwd:c,rounds:S,fanout:k,effort:O});const w=r();let D;try{const n=await withRoundHorizon(S,t,(()=>e.chat({class:d,model:p,prompt:taskPrompt(o,{carry:s,rounds:S}),autonomous:k,singlePass:!k,effort:O,workers:k&&o.workers||void 0,env:{cwd:c},maxRounds:S,sessionId:m(o.id),stream:!0},_)));D={ok:!0,output:assistantText(n),usage:n&&n.usage||null,stoppedOnRounds:Boolean(n&&n.stoppedOnRounds),rounds:E||void 0},y&&(D.ok=!1,D.error=`tool approval was requested for "${y.tool||y.name||"a tool"}" with no one to answer it — construct the queue engine with approvals disabled (getConfirmMode: () => false)`)}catch(e){D={ok:!1,error:errorText(e)}}return D.ms=Math.max(0,r()-w),v&&(D.commit=l((()=>n.scopedCommit(c,{message:commitMessage(o),before:M,written:[...A]})),{ok:!1,error:"git-scope unavailable"}),D.files=function(e,t){return!e||e.error?[]:Array.isArray(e.paths)?e.paths:[...t]}(D.commit,A)),i({type:"finish",taskId:o.id,ok:D.ok,result:D}),D}function l(e,t){try{return e()}catch{return t}}async function c({commit:e,max:o=0,stopOnError:n=!1,carry:r=""}={}){const s=queue.acquireLock(t);if(!s.ok)return i({type:"locked",holder:s.holder}),{ok:!1,locked:!0,holder:s.holder,ran:[],carry:r};const a=[];try{for(;!(o>0&&a.length>=o);){const o=queue.loadQueue(t),s=queue.recoverStale(o);s.length&&(queue.saveQueue(t,o),i({type:"recovered",ids:s}));const u=queue.pending(o)[0];if(!u)break;const l=await d(u,{commit:e,carry:r});if(r=l.carry,a.push(l),!l.ok&&n)break}}finally{queue.releaseLock(t)}return{ok:!0,ran:a,carry:r}}async function d(e,{commit:o,carry:n=""}={}){const s=queue.loadQueue(t),i=queue.markRunning(s,e.id,{now:r()});if(!i)return{ok:!1,error:`unknown task #${e.id}`,carry:n};const a=Number(i.roundStops)||0;queue.saveQueue(t,s);const l=await u(i,{carry:n,commit:o}),c=Boolean(l.ok&&l.stoppedOnRounds),d=c?a+1:0,m=c&&d>3,h=m?{...l,ok:!1,error:`stopped at its tool-round horizon ${d} times in a row without finishing — raise AEGIS_AUTONOMOUS_MAX_ROUNDS or split the task into smaller ones`}:l,p=m?"error":c?"pending":h.ok?"done":"error",f=queue.loadQueue(t);queue.settle(f,i.id,{status:p,result:{ok:h.ok,output:h.output||"",usage:h.usage||null,ms:h.ms,commit:h.commit||null,files:h.files||[]},error:h.ok?null:h.error,now:r()});const g=queue.findTask(f,i.id);return g&&(g.roundStops=d),queue.saveQueue(t,f),queue.appendRun(t,{id:i.id,task:i.task,cwd:i.cwd,model:resolveModel({model:i.model,env:t}),status:"pending"===p?"stopped":p,at:new Date(r()).toISOString(),ms:h.ms,usage:h.usage||null,files:h.files||[],error:h.ok?null:h.error}),{...h,id:i.id,carry:appendDigest(n,digestLine(i,h))}}const m=e=>`queue-${e}`;return{runTask:u,runOne:d,proceed:c,reconcile:async function({cwd:e=process.cwd(),auto:o=!1,commit:n,max:r=0,stopOnError:s=!1}={}){const a=queue.reconcilePlan(e,{write:!0});if(!a.ok)return{ok:!1,error:a.reason};if(a.healed&&a.healed.changed&&i({type:"healed",phases:a.healed.added}),null==a.next)return{ok:!0,exhausted:!0};const u=`Work Phase ${a.next} from PLAN.md`,l=queue.loadQueue(t).find((t=>t.cwd===e&&String(t.task).startsWith(u)&&"done"!==t.status));if(l){if(i({type:"already-queued",phase:a.next,id:l.id,status:l.status}),!o)return{ok:!0,phase:a.next,id:l.id,existing:!0}}else{const o=queue.addTask(t,{task:`${u} ("${a.title}") at ${e}. Read the full "## Phase ${a.next}" section in PLAN.md at the repo root for the spec, exit criteria and constraints, and implement it exactly as scoped there. Keep the repo's checks green (\`npm run check\`, plus that package's tests). When every exit criterion is met, mark the "## Phase ${a.next}" heading with ✅ in PLAN.md and update its line in the top Status checklist.`,cwd:e,source:"reconcile",model:resolveModel({env:t})});i({type:"queued",phase:a.next,id:o.id,title:a.title})}if(!o)return{ok:!0,phase:a.next,title:a.title};const d=await c({commit:n,max:r,stopOnError:s});return{ok:!0,phase:a.next,title:a.title,...d}},cancel:function(t){if(null==t)return{ok:!1,error:"cancel needs a task id"};if("function"!=typeof e.cancel)return{ok:!1,error:"this engine cannot cancel a turn"};const o=e.cancel(m(t));return{ok:Boolean(o&&o.ok),sessionId:m(t)}},sessionIdFor:m,resolveModel:e=>resolveModel({...e,env:t})}}function commitMessage(e){const t=String(e.task||"queued task").split("\n")[0].replace(/\s+/g," ").trim();return`autonomous: ${t.slice(0,66)}${t.length>66?"…":""}`}module.exports={DEFAULT_MODEL:DEFAULT_MODEL,DEFAULT_ROUNDS:DEFAULT_ROUNDS,MAX_ROUND_STOPS:3,MODEL_CLASSES:MODEL_CLASSES,AEGIS_MODEL_IDS:AEGIS_MODEL_IDS,isAegisModel:isAegisModel,normalizeClass:normalizeClass,looksLikeByokModel:looksLikeByokModel,modelRefusal:modelRefusal,WRITE_TOOLS:WRITE_TOOLS,writtenPath:writtenPath,isAutonomousRequest:isAutonomousRequest,maxRounds:maxRounds,withRoundHorizon:withRoundHorizon,DEFAULT_AUTO_CONTINUES:3,autoContinueLimit:autoContinueLimit,autoRoundsDefault:autoRoundsDefault,autoContinuePlan:autoContinuePlan,resolveModel:resolveModel,ignoredEnvModel:ignoredEnvModel,resolveEffort:resolveEffort,resolveFanout:resolveFanout,autonomousDirective:autonomousDirective,taskPrompt:taskPrompt,appendDigest:appendDigest,digestLine:digestLine,assistantText:assistantText,errorText:errorText,commitMessage:commitMessage,createQueueWorker:createQueueWorker};
3
+ "use strict";const queue=require("./queue.js"),gitScope=require("./git-scope.js"),DEFAULT_ROUNDS=40,MAX_ROUND_STOPS=3,WRITE_TOOLS=new Set(["writeFile","editFile"]),DEFAULT_AUTO_CONTINUES=3;function autoContinueLimit(e=process.env){const t=Number.parseInt(e&&e.AEGIS_AUTO_CONTINUE_MAX,10);return Number.isFinite(t)&&t>0?t:3}const AUTO_ROUNDS_OFF=new Set(["0","false","off","no"]);function autoRoundsDefault(e=process.env){const t=e&&e.AEGIS_AUTO_ROUNDS;if(null==t)return!0;const o=String(t).trim().toLowerCase();return!o||!AUTO_ROUNDS_OFF.has(o)}function autoContinuePlan({on:e=!1,used:t=0,limit:o=3}={}){const n=Number.isFinite(o)&&o>0?Math.floor(o):3,r=Number.isFinite(t)&&t>0?Math.floor(t):0;return e?r>=n?{auto:!1,used:0,cap:n}:{auto:!0,used:r+1,cap:n}:{auto:!1,used:r,cap:n}}function writtenPath(e){const t=e&&e.args||{},o=t.file_path||t.path;return o?String(o):""}const DEFAULT_MODEL="nexus-brain",MODEL_CLASSES=Object.freeze(["aegis","byok","local","pro"]),AEGIS_MODEL_RE=/^(?:nexus|aegis)-brain(?:-(?:smart|neo))?$/,AEGIS_MODEL_IDS=Object.freeze(["nexus-brain","aegis-brain"]);function isAegisModel(e){return AEGIS_MODEL_RE.test(String(null==e?"":e).trim())}function normalizeClass(e){return String(null==e?"":e).trim().toLowerCase()||"aegis"}function looksLikeByokModel(e){const t=String(null==e?"":e).trim(),o=t.indexOf(":");return o>0&&o<t.length-1}function modelRefusal(e,t){const o=String(null==e?"":e).trim(),n=normalizeClass(t);if(!MODEL_CLASSES.includes(n))return`"${t}" is not a model class the queue serves (${MODEL_CLASSES.join("/")})`;if("aegis"===n)return!o||isAegisModel(o)?"":`the autonomous queue's Aegis Cloud class runs pooled-brain models only (nexus-brain, ${AEGIS_MODEL_IDS.join("/")} aliases); "${o}" is not one`;if("byok"===n)return o?looksLikeByokModel(o)?"":`"${o}" is not a byok model id — it must be "<provider>:<model>" (pick one from /models)`:'a byok task needs a model, as "<provider>:<model>" (pick one from /models)';if("pro"===n){if(!o)return"";let e;try{e=require("./claude-pro.js").PRO_MODELS}catch{return"a pro task's model cannot be checked right now — queue it with no --model to let the claude CLI pick"}const t=(Array.isArray(e)?e:[]).map(e=>String(e&&e.id).trim());return t.includes(o.toLowerCase())?"":`the autonomous queue's Pro class runs the subscription through the claude CLI, which accepts only its own model aliases (${t.join("/")}); "${o}" is not one`}return o?"":"a local task needs a model — the tag of whatever is pulled into the local daemon"}const AUTONOMOUS_REQUEST_RE=/\bautonomously\b|\bon your own\b|\bwithout asking\b|\bend[- ]to[- ]end\b|\bno (?:more )?questions\b|\bfully autonomous\b|\bqueue it\b/i;function isAutonomousRequest(e){return AUTONOMOUS_REQUEST_RE.test(String(e||""))}function maxRounds(e=process.env,t){const o=Number.parseInt(t,10);if(Number.isFinite(o)&&o>0)return o;const n=Number.parseInt(e&&e.AEGIS_AUTONOMOUS_MAX_ROUNDS||"",10);return Number.isFinite(n)&&n>0?n:40}function withRoundHorizon(e,t,o){const n="AEGIS_AUTONOMOUS_MAX_ROUNDS",r=[];for(const e of[t,process.env])e&&-1===r.indexOf(e)&&r.push(e);const s=r.map(e=>({target:e,had:Object.prototype.hasOwnProperty.call(e,n),prev:e[n]}));try{for(const t of r)t[n]=String(e)}catch{}const i=()=>{for(const e of s)try{e.had?e.target[n]=e.prev:delete e.target[n]}catch{}};let a;try{a=o()}catch(e){throw i(),e}return a&&"function"==typeof a.then?a.then(e=>(i(),e),e=>{throw i(),e}):(i(),a)}function resolveModel({model:e,env:t,cls:o}={}){const n=String(e||"").trim();if("aegis"!==normalizeClass(o))return n;if(n)return n;const r=t||process.env,s=String(r.AEGIS_AUTONOMOUS_MODEL||r.AEGIS_MODEL||"").trim();return isAegisModel(s)?s:"nexus-brain"}function ignoredEnvModel({model:e,env:t,cls:o}={}){if("aegis"!==normalizeClass(o))return"";if(String(e||"").trim())return"";const n=t||process.env,r=String(n.AEGIS_AUTONOMOUS_MODEL||n.AEGIS_MODEL||"").trim();return!r||isAegisModel(r)?"":`${String(n.AEGIS_AUTONOMOUS_MODEL||"").trim()?"AEGIS_AUTONOMOUS_MODEL":"AEGIS_MODEL"}="${r}" is not an Aegis Cloud model — running on nexus-brain instead`}function resolveFanout(e={},t=process.env){const o=e||{};if(!0===o.autonomous||!1===o.singlePass)return!0;const n=t||process.env;return/^(1|true|yes|on)$/i.test(String(n.AEGIS_AUTONOMOUS_FANOUT||"").trim())}function resolveEffort({effort:e,env:t,fanout:o}={}){const n=t||process.env;return String(e||n.AEGIS_AUTONOMOUS_EFFORT||"").trim()||(o?"high":"medium")}function autonomousDirective(e=40){return["# Autonomous mode",`You are running autonomously, not in a conversation: there is no user to answer a question or approve a plan. You have up to ${e} tool rounds this turn; use as many as the task needs.`,"Work the task end to end:","1. Plan in one line, then start acting in the same turn — never end a turn on a plan.","2. Read only what you need to make the change (no fishing through the repo).","2b. If this demand has been made before, establish whether it was met: check recalled memory, the queue file, PLAN.md, and git history for the earlier attempt. When it was fixed and the problem is back, state how it was fixed then and why it regressed, and fix that cause — a blind re-fix is a regression, not a resolution.","3. Make the change with Write/Edit/Bash, then VERIFY it: re-read the result and run the relevant test/command.","4. If verification fails, fix it and verify again — loop until it passes or you are genuinely blocked.",'5. Do not ask for permission, do not hand the work back, do not stop at "let me check…".',"6. Finish with a short report: what changed (file paths), the command you ran to verify, its result, and any remaining blocker."].join("\n")}function digestLine(e,t){const o=String(e.task||"").replace(/\s+/g," ").trim().slice(0,120),n=Boolean(t&&t.ok&&t.stoppedOnRounds)?"⏸":t&&t.ok?"✓":"✗",r=t&&Array.isArray(t.files)&&t.files.slice(0,6)||[],s=r.length?` — touched: ${r.join(", ")}${t.files.length>r.length?", …":""}`:"",i=!t||t.ok?"":` — ${String(t&&t.error||"failed").slice(0,120)}`;return`- #${e.id} ${n} ${o}${s}${i}`}function appendDigest(e,t,{keep:o=6}={}){return String(e||"").split("\n").filter(Boolean).concat(t).slice(-o).join("\n")}function taskPrompt(e,{carry:t="",rounds:o=40}={}){const n=[autonomousDirective(o)];return t&&n.push("# Earlier tasks in this run\nWork already done by this queue — do not redo it, build on it:\n"+t),n.push("# Task\n"+String(e.task||"").trim()),n.join("\n\n")}function assistantText(e){if(!e||"object"!=typeof e)return"";const t=Array.isArray(e.choices)?e.choices[0]:null,o=t&&t.message?t.message.content:e.content;return"string"==typeof o?o:Array.isArray(o)?o.map(e=>"string"==typeof e?e:e&&"string"==typeof e.text?e.text:"").join(""):""}function errorText(e){return e?"string"==typeof e?e:String(e.message||e.error||e):"unknown error"}function createQueueWorker({engine:e,env:t=process.env,log:o=()=>{},git:n=gitScope,now:r=Date.now,canFanOut:s=()=>!0}={}){if(!e||"function"!=typeof e.chat)throw new Error("autonomous: a local engine with chat() is required");const i=e=>{try{o(e)}catch{}};async function a(o,{carry:a="",commit:l}={}){const c=o.cwd||process.cwd(),m=normalizeClass(o.class),h=modelRefusal(o.model,m);if(h){const e={ok:!1,error:h,model:o.model,class:m,ms:0};return i({type:"finish",taskId:o.id,ok:!1,result:e}),e}const p=resolveModel({model:o.model,env:t,cls:m}),f=ignoredEnvModel({model:o.model,env:t,cls:m});f&&i({type:"note",taskId:o.id,note:f});const g="aegis"===m&&resolveFanout(o,t),k=g&&(()=>{try{return!1!==s()}catch{return!1}})();g&&!k&&i({type:"note",taskId:o.id,note:"fan-out needs Pro (the cloud drain that keeps running after you close the laptop) — this task ran as a single pass"});const S=resolveEffort({effort:o.effort,env:t,fanout:k}),O=maxRounds(t,o.maxRounds);let y=null,E=0;const A=new Set,v=e=>{if(e&&"object"==typeof e)if(e.approval)y=e.approval;else if(e.tool){if("done"===e.tool.phase&&(E+=1,WRITE_TOOLS.has(e.tool.name)&&!1!==e.tool.ok)){const t=writtenPath(e.tool);t&&A.add(t)}i({type:"tool",taskId:o.id,tool:e.tool})}else"string"==typeof e.delta?i({type:"delta",taskId:o.id,text:e.delta}):"string"==typeof e.reasoning&&i({type:"reasoning",taskId:o.id,text:e.reasoning})},w=void 0===l?Boolean(o.commit):Boolean(l),_=w?u(()=>n.gitStatusSnapshot(c),null):null;i({type:"start",taskId:o.id,model:p,class:m,cwd:c,rounds:O,fanout:k,effort:S});const M=r();let b;try{const n=await withRoundHorizon(O,t,()=>e.chat({class:m,model:p,prompt:taskPrompt(o,{carry:a,rounds:O}),autonomous:k,singlePass:!k,effort:S,workers:k&&o.workers||void 0,env:{cwd:c},maxRounds:O,sessionId:d(o.id),stream:!0},v));b={ok:!0,output:assistantText(n),usage:n&&n.usage||null,stoppedOnRounds:Boolean(n&&n.stoppedOnRounds),rounds:E||void 0},y&&(b.ok=!1,b.error=`tool approval was requested for "${y.tool||y.name||"a tool"}" with no one to answer it — construct the queue engine with approvals disabled (getConfirmMode: () => false)`)}catch(e){b={ok:!1,error:errorText(e)}}return b.ms=Math.max(0,r()-M),w&&(b.commit=u(()=>n.scopedCommit(c,{message:commitMessage(o),before:_,written:[...A]}),{ok:!1,error:"git-scope unavailable"}),b.files=function(e,t){return!e||e.error?[]:Array.isArray(e.paths)?e.paths:[...t]}(b.commit,A)),i({type:"finish",taskId:o.id,ok:b.ok,result:b}),b}function u(e,t){try{return e()}catch{return t}}async function l({commit:e,max:o=0,stopOnError:n=!1,carry:r=""}={}){const s=queue.acquireLock(t);if(!s.ok)return i({type:"locked",holder:s.holder}),{ok:!1,locked:!0,holder:s.holder,ran:[],carry:r};const a=[];try{for(;!(o>0&&a.length>=o);){const o=queue.loadQueue(t),s=queue.recoverStale(o);s.length&&(queue.saveQueue(t,o),i({type:"recovered",ids:s}));const u=queue.pending(o)[0];if(!u)break;const l=await c(u,{commit:e,carry:r});if(r=l.carry,a.push(l),!l.ok&&n)break}}finally{queue.releaseLock(t)}return{ok:!0,ran:a,carry:r}}async function c(e,{commit:o,carry:n=""}={}){const s=queue.loadQueue(t),i=queue.markRunning(s,e.id,{now:r()});if(!i)return{ok:!1,error:`unknown task #${e.id}`,carry:n};const u=Number(i.roundStops)||0;queue.saveQueue(t,s);const l=await a(i,{carry:n,commit:o}),c=Boolean(l.ok&&l.stoppedOnRounds),d=c?u+1:0,m=c&&d>3,h=m?{...l,ok:!1,error:`stopped at its tool-round horizon ${d} times in a row without finishing — raise AEGIS_AUTONOMOUS_MAX_ROUNDS or split the task into smaller ones`}:l,p=m?"error":c?"pending":h.ok?"done":"error",f=queue.loadQueue(t);queue.settle(f,i.id,{status:p,result:{ok:h.ok,output:h.output||"",usage:h.usage||null,ms:h.ms,commit:h.commit||null,files:h.files||[]},error:h.ok?null:h.error,now:r()});const g=queue.findTask(f,i.id);return g&&(g.roundStops=d),queue.saveQueue(t,f),queue.appendRun(t,{id:i.id,task:i.task,cwd:i.cwd,model:resolveModel({model:i.model,env:t}),status:"pending"===p?"stopped":p,at:new Date(r()).toISOString(),ms:h.ms,usage:h.usage||null,files:h.files||[],error:h.ok?null:h.error}),{...h,id:i.id,carry:appendDigest(n,digestLine(i,h))}}const d=e=>`queue-${e}`;return{runTask:a,runOne:c,proceed:l,reconcile:async function({cwd:e=process.cwd(),auto:o=!1,commit:n,max:r=0,stopOnError:s=!1}={}){const a=queue.reconcilePlan(e,{write:!0});if(!a.ok)return{ok:!1,error:a.reason};if(a.healed&&a.healed.changed&&i({type:"healed",phases:a.healed.added}),null==a.next)return{ok:!0,exhausted:!0};const u=`Work Phase ${a.next} from PLAN.md`,c=queue.loadQueue(t).find(t=>t.cwd===e&&String(t.task).startsWith(u)&&"done"!==t.status);if(c){if(i({type:"already-queued",phase:a.next,id:c.id,status:c.status}),!o)return{ok:!0,phase:a.next,id:c.id,existing:!0}}else{const o=queue.addTask(t,{task:`${u} ("${a.title}") at ${e}. Read the full "## Phase ${a.next}" section in PLAN.md at the repo root for the spec, exit criteria and constraints, and implement it exactly as scoped there. Keep the repo's checks green (\`npm run check\`, plus that package's tests). When every exit criterion is met, mark the "## Phase ${a.next}" heading with ✅ in PLAN.md and update its line in the top Status checklist.`,cwd:e,source:"reconcile",model:resolveModel({env:t})});i({type:"queued",phase:a.next,id:o.id,title:a.title})}if(!o)return{ok:!0,phase:a.next,title:a.title};const d=await l({commit:n,max:r,stopOnError:s});return{ok:!0,phase:a.next,title:a.title,...d}},cancel:function(t){if(null==t)return{ok:!1,error:"cancel needs a task id"};if("function"!=typeof e.cancel)return{ok:!1,error:"this engine cannot cancel a turn"};const o=e.cancel(d(t));return{ok:Boolean(o&&o.ok),sessionId:d(t)}},sessionIdFor:d,resolveModel:e=>resolveModel({...e,env:t})}}function commitMessage(e){const t=String(e.task||"queued task").split("\n")[0].replace(/\s+/g," ").trim();return`autonomous: ${t.slice(0,66)}${t.length>66?"…":""}`}module.exports={DEFAULT_MODEL:"nexus-brain",DEFAULT_ROUNDS:40,MAX_ROUND_STOPS:3,MODEL_CLASSES:MODEL_CLASSES,AEGIS_MODEL_IDS:AEGIS_MODEL_IDS,isAegisModel:isAegisModel,normalizeClass:normalizeClass,looksLikeByokModel:looksLikeByokModel,modelRefusal:modelRefusal,WRITE_TOOLS:WRITE_TOOLS,writtenPath:writtenPath,isAutonomousRequest:isAutonomousRequest,maxRounds:maxRounds,withRoundHorizon:withRoundHorizon,DEFAULT_AUTO_CONTINUES:3,autoContinueLimit:autoContinueLimit,autoRoundsDefault:autoRoundsDefault,autoContinuePlan:autoContinuePlan,resolveModel:resolveModel,ignoredEnvModel:ignoredEnvModel,resolveEffort:resolveEffort,resolveFanout:resolveFanout,autonomousDirective:autonomousDirective,taskPrompt:taskPrompt,appendDigest:appendDigest,digestLine:digestLine,assistantText:assistantText,errorText:errorText,commitMessage:commitMessage,createQueueWorker:createQueueWorker};
@@ -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");let envFileLib=null;try{envFileLib=require("../../../client/env-file.js")}catch{try{envFileLib=require("../../vendor/env-file.js")}catch{envFileLib=null}}function claudeConfigDir(e){const n=e||process.env,t=n&&n.CLAUDE_CONFIG_DIR;return t&&String(t).trim()?String(t).trim():path.join(os.homedir(),".claude")}function claudeOAuthToken(e){return envFileLib?envFileLib.resolveForeignSecret("CLAUDE_CODE_OAUTH_TOKEN",{env:e}):""}const SHADOWING_ENV_VARS=Object.freeze(["ANTHROPIC_API_KEY","ANTHROPIC_AUTH_TOKEN"]);function isAnthropicConsoleKey(e){return"string"==typeof e&&/^sk-ant-[A-Za-z0-9_-]{8,}$/.test(e.trim())}function childEnvPlan(e,n,t){const s={...e||{}},o=[],i=envFileLib&&"function"==typeof envFileLib.credentialLooksUsable?envFileLib.credentialLooksUsable:null,r=!(!t||!t.hasSubscription);if(i)for(const e of SHADOWING_ENV_VARS){const n=s[e];if("string"!=typeof n)continue;let t=null;if(i(n)?r&&"ANTHROPIC_API_KEY"===e&&!isAnthropicConsoleKey(n)&&(t="not-a-console-key"):t="too-short",!t)continue;delete s[e];const a=n.trim().length;a>0&&o.push({name:e,length:a,reason:t})}return n&&(s.CLAUDE_CODE_OAUTH_TOKEN=n),{env:s,dropped:o}}function envDroppedLine(e){const n=Array.isArray(e)?e:[];if(!n.length)return null;const t=n.filter((e=>e&&"not-a-console-key"===e.reason)),s=n.filter((e=>!e||"not-a-console-key"!==e.reason)),o=[];if(s.length){const e=s.map((e=>`${e.name} (${e.length} character${1===e.length?"":"s"})`)).join(", ");o.push(`${e}: too short to be a credential, and the CLI would have spent it instead of your subscription`)}if(t.length){const e=t.map((e=>`${e.name} (${e.length} characters)`)).join(", ");o.push(`${e}: not an Anthropic console key (\`sk-ant-\`), and the CLI would have spent it instead of your subscription`)}return`aegis: not passed to the claude child — ${o.join("; ")}`}function shadowingValue(e,n){const t=e||{},s=envFileLib&&"function"==typeof envFileLib.credentialLooksUsable?envFileLib.credentialLooksUsable:null;if(!s)return null;const o=!(!n||!n.hasSubscription);for(const e of SHADOWING_ENV_VARS){const n=t[e];if("string"!=typeof n)continue;let i=null;if(s(n)?o&&"ANTHROPIC_API_KEY"===e&&!isAnthropicConsoleKey(n)&&(i="not-a-console-key"):i="too-short",i)return{name:e,length:n.trim().length,reason:i}}return null}function claudeProStatus(e){const n=e||{},t=n.env||process.env,s=path.join(n.dir||claudeConfigDir(t),".credentials.json"),o={claude:n.claudeVersion||null,file:s,exists:!1,kind:null,subscription:null,expiresAt:0,loggedIn:!1};let i;try{i=JSON.parse(fs.readFileSync(s,"utf8")),o.exists=!0}catch{i=null}const r=i&&i.claudeAiOauth;r&&(r.accessToken||r.refreshToken)?(o.kind="oauth",o.subscription=r.subscriptionType||null,o.expiresAt=Number(r.refreshTokenExpiresAt)||0,o.loggedIn=!0):i&&"string"==typeof i.token&&i.token?(o.kind="apikey",o.loggedIn=!0):claudeOAuthToken(t)&&(o.kind="env-token",o.loggedIn=!0),o.subscriptionPresent=o.loggedIn&&"apikey"!==o.kind,o.shadowed=shadowingValue(t,{hasSubscription:o.subscriptionPresent});const a=childEnvPlan(t,null,{hasSubscription:o.subscriptionPresent});return o.credentialPresent=o.loggedIn||"string"==typeof a.env.ANTHROPIC_API_KEY||"string"==typeof a.env.ANTHROPIC_AUTH_TOKEN||"string"==typeof a.env.CLAUDE_CODE_OAUTH_TOKEN,o}const PRO_MODELS=Object.freeze([{id:"default",label:"Default (recommended)",note:"the CLI picks for the subscription"},{id:"sonnet",label:"Sonnet",note:"alias the CLI resolves · latest Sonnet"},{id:"opus",label:"Opus",note:"alias the CLI resolves · latest Opus"},{id:"opusplan",label:"Opus Plan",note:"alias the CLI resolves · plan with Opus, act on Sonnet"},{id:"haiku",label:"Haiku",note:"alias the CLI resolves · latest Haiku"},{id:"fable",label:"Fable",note:"alias the CLI resolves · needs usage credits"},{id:"claude-sonnet-5-5",label:"Claude Sonnet 5.5",note:"full name · Anthropic"},{id:"claude-sonnet-4-6",label:"Claude Sonnet 4.6",note:"full name · Anthropic"},{id:"claude-sonnet-4-5-20250929",label:"Claude Sonnet 4.5",note:"full name · Anthropic · dated snapshot"},{id:"claude-opus-5",label:"Claude Opus 5",note:"full name · Anthropic"},{id:"claude-opus-4-7",label:"Claude Opus 4.7",note:"full name · Anthropic"},{id:"claude-opus-4-6",label:"Claude Opus 4.6",note:"full name · Anthropic"},{id:"claude-opus-4-5-20251101",label:"Claude Opus 4.5",note:"full name · Anthropic · dated snapshot"}]);function turnArgs(e){const n=[],t=e||{};return t.system&&String(t.system).trim()&&n.push("--append-system-prompt",String(t.system)),n}function createStreamParser(e){const n=e||{},t=new Map;let s="",o="",i=0,r=null;const a=e=>[...t.values()].find((n=>"collecting"===n.phase&&n.index===e))||[...t.values()].find((e=>"collecting"===e.phase));return{line(e){let l;try{l=JSON.parse(e)}catch{return}if("control_request"===l.type&&l.request){const e=l.request;if("can_use_tool"!==e.subtype)return;return n.onAsk?void n.onAsk({requestId:l.request_id,toolName:e.tool_name,input:e.input||{},toolUseId:e.tool_use_id,displayName:e.display_name,description:e.description,suggestions:Array.isArray(e.permission_suggestions)?e.permission_suggestions:[]}):void(n.onAskUnavailable&&n.onAskUnavailable({requestId:l.request_id,request:e}))}if("stream_event"===l.type&&l.event){const e=l.event;if("content_block_start"===e.type&&e.content_block)"tool_use"===e.content_block.type&&t.set(e.content_block.id,{id:e.content_block.id,index:null==e.index?0:e.index,name:e.content_block.name,args:"",startedAt:Date.now(),phase:"collecting"});else if("content_block_delta"===e.type&&e.delta){if("text_delta"===e.delta.type){const t=(e.delta.text||"").replace(/\x00/g,"");s+=t,n.onText&&t&&n.onText(t)}else if("thinking_delta"===e.delta.type){const t=(e.delta.thinking||"").replace(/\x00/g,"");o+=t,n.onThinking&&t&&n.onThinking(t);const s=e.delta.estimated_tokens;"number"==typeof s&&s>0&&Number.isFinite(s)&&(i+=s,n.onThinkingProgress&&n.onThinkingProgress(s))}else if("input_json_delta"===e.delta.type){const n=a(null==e.index?0:e.index);n&&(n.args+=e.delta.partial_json||"")}}else if("content_block_stop"===e.type){const s=a(null==e.index?0:e.index);s&&(e=>{let s=e.args;try{s=e.args?JSON.parse(e.args):{}}catch{s={}}t.set(e.id,{...e,args:s,phase:"run"}),n.onTool&&n.onTool({id:e.id,name:e.name,args:s,phase:"run"})})(s)}}else if("user"===l.type&&l.message){const e=Array.isArray(l.message.content)?l.message.content:[];for(const s of e){if(!s||"tool_result"!==s.type||!s.tool_use_id)continue;const e=t.get(s.tool_use_id);if(!e)continue;const o=Math.max(0,Date.now()-(e.startedAt||Date.now()));n.onTool&&n.onTool({id:e.id,name:e.name,phase:"done",elapsed:o,error:!!s.is_error}),t.delete(s.tool_use_id)}}else"result"===l.type&&(r=l,n.onDone&&n.onDone({text:s||l.result||"",error:l.is_error?l.result||(Array.isArray(l.errors)?l.errors.find((e=>"string"==typeof e&&e.trim())):void 0)||"api error":void 0,usage:l.usage||null,costUsd:"number"==typeof l.total_cost_usd?l.total_cost_usd:void 0,durationMs:l.duration_ms,sessionId:l.session_id,thinking:o||"",thinkingTokens:i}))},get text(){return s},get thinking(){return o},get thinkingTokens(){return i},get resultLine(){return r}}}function loadSeam(e){const n=e||__dirname,t=[path.join(n,"..","..","..","one","src"),path.join(n,"..","..","vendor","one","src"),path.join(n,"..","..","..","..","one","src")],s=new Set(["aegisone","aegiscode"]),o=path.join(n,"..","..","..","..");try{const e=JSON.parse(fs.readFileSync(path.join(o,"package.json"),"utf8"));e&&s.has(e.name)&&t.push(path.join(o,"src"))}catch{}for(const e of t)try{const n=require(path.join(e,"child.js")),t=require(path.join(e,"permissions.js"));if("function"==typeof n.claudeArgv&&"function"==typeof t.resolvePosture)return{child:n,permissions:t}}catch{}throw new Error("aegis: the Claude child argv builder (one/src/child.js + one/src/permissions.js) is missing from this install — refusing to build a second argv, because a second argv is a second policy.")}function seamAvailable(e){try{return loadSeam(e),{ok:!0,error:null}}catch(e){return{ok:!1,error:e&&e.message||String(e)}}}function proMessage(e,n,t){const s={content:e||""},o="string"==typeof n?n:"";return o&&(s.reasoning_content=o),"number"==typeof t&&t>0&&Number.isFinite(t)&&(s.thinking_tokens=t),s}function runClaudePro(e,n){const t=e||{},s=n||{},o=s.seam||loadSeam(s.dir),i=s.spawn||require("node:child_process").spawn;let r=void 0===t.permissionMode||null===t.permissionMode?null:String(t.permissionMode);if(null===r)try{const e=o.permissions.storedPermissionFacts();r=e&&"string"==typeof e.permissionMode?e.permissionMode:null}catch{}const a=o.permissions.resolvePosture({rules:t.rules,gate:t.gate,interactive:!1,childKind:o.permissions.CHILD_KINDS.HEADLESS,permissionMode:r,env:t.env||process.env}),l=o.child.claudeArgv({posture:a,prompt:t.prompt,model:t.model||void 0,resumeSessionId:t.resumeSessionId,sessionId:t.sessionId,addDir:t.addDir,askBridge:"function"==typeof t.onAsk,extra:[...turnArgs(t),"--include-partial-messages","--verbose"]});return new Promise((e=>{if(t.signal&&t.signal.aborted)return void e({choices:[{message:{content:""},finish_reason:"stop"}],stopped:!0});const n=t.env||process.env,o=claudeOAuthToken(n);let r=!1;try{r=!!claudeProStatus({env:n}).subscriptionPresent}catch{}const a=childEnvPlan(n,o,{hasSubscription:r}),c=a.env,d=envDroppedLine(a.dropped);if(d&&t.onDelta)try{t.onDelta({delta:"",note:d})}catch{}let u;try{u=i(s.executable||"claude",l.argv,{cwd:t.cwd||process.cwd(),stdio:[l.record.askBridge?"pipe":"ignore","pipe","pipe"],env:c})}catch(n){return void e({choices:[{message:{content:""},finish_reason:"error"}],error:`claude: could not start the child (${n&&n.message||n})`,...a.dropped.length?{envDropped:a.dropped}:{}})}if(t.onSpawn)try{t.onSpawn(u,l.record)}catch{}let p=!1,h="",g="",m=null;const f=Number(t.idleTimeoutMs)||6e5,_=l.record.askBridge,v=e=>{if(!_||!u.stdin||u.stdin.destroyed)return!1;try{return u.stdin.write(`${JSON.stringify(e)}\n`),!0}catch{return!1}};_&&v({type:"user",message:{role:"user",content:[{type:"text",text:String(t.prompt||"")}]}});const y=(e,n,t)=>{v({type:"control_response",response:{subtype:"success",request_id:e,response:"session"===n||"once"===n||"always"===n?{behavior:"allow"}:{behavior:"deny",message:t||"AEGIS_USER_DENIED"}}})},k=n=>{if(!p){if(p=!0,m&&clearTimeout(m),t.signal&&t.signal.removeEventListener("abort",A),_&&u.stdin&&!u.stdin.destroyed)try{u.stdin.end()}catch{}e(a.dropped.length?{...n,envDropped:a.dropped}:n)}},A=()=>{try{u.kill("SIGTERM")}catch{}setTimeout((()=>{try{u.kill("SIGKILL")}catch{}}),1500)};t.signal&&t.signal.addEventListener("abort",A,{once:!0});const b=()=>{m&&clearTimeout(m),m=setTimeout((()=>{A(),k({choices:[{message:{content:""},finish_reason:"stop"}],error:`claude: the child went silent for ${Math.round(f/1e3)}s and was stopped`})}),f)};b();const S=createStreamParser({onText:e=>{b(),t.onDelta&&t.onDelta({delta:e})},onThinking:e=>{b(),t.onDelta&&t.onDelta({reasoning:e})},onThinkingProgress:e=>{b(),t.onDelta&&t.onDelta({thinkingTokens:e})},onTool:e=>{b(),t.onDelta&&t.onDelta({delta:"",tool:{name:e.name,args:e.args,ok:"done"===e.phase?!e.error:void 0,id:e.id,cwd:t.cwd,phase:e.phase}})},onAsk:e=>{b(),Promise.resolve().then((()=>t.onAsk(e))).then((n=>y(e.requestId,"session"===n||"once"===n||"always"===n?n:"deny","AEGIS_USER_DENIED")),(n=>{y(e.requestId,"deny",`AEGIS_USER_DENIED (${n&&n.message||String(n)})`)})).catch((()=>{}))},onAskUnavailable:e=>{y(e.requestId,"deny","AEGIS_NO_APPROVAL_CHANNEL")},onDone:e=>{e.error?k({choices:[{message:{content:e.text||""},finish_reason:"error"}],usage:e.usage||void 0,error:e.error,...l.record.resumeSessionId&&isStaleResumeError(e.error)?{resumeStale:!0,resumeSessionId:l.record.resumeSessionId}:{}}):k({choices:[{message:proMessage(e.text||"",e.thinking,e.thinkingTokens),finish_reason:"stop"}],usage:e.usage||void 0,costUsd:e.costUsd,durationMs:e.durationMs,sessionId:e.sessionId,childRecord:l.record})}});u.stdout.on("data",(e=>{b(),g+=e.toString("utf8");const n=g.split("\n");g=n.pop()||"";for(const e of n){const n=e.trim();n&&S.line(n)}})),_&&u.stdin&&u.stdin.on("error",(()=>{})),u.stderr.on("data",(e=>{b(),h.length<8192&&(h+=e.toString("utf8"))})),u.on("error",(e=>{k({choices:[{message:{content:""},finish_reason:"error"}],error:`claude: could not run the child (${e&&e.message||e}). Install it with \`npm i -g @anthropic-ai/claude-code\`, then sign in with \`claude auth login\`.`})})),u.on("close",(e=>{g.trim()&&S.line(g.trim()),k({choices:[{message:proMessage(S.text,S.thinking,S.thinkingTokens),finish_reason:"stop"}],usage:S.resultLine&&S.resultLine.usage||void 0,childRecord:l.record,error:S.text||0===e?void 0:`claude: the child exited with status ${e}${h.trim()?` — ${h.trim().split("\n").slice(-3).join(" ")}`:""}`})}))}))}function isStaleResumeError(e){return!!e&&/no conversation found with session id/i.test(String(e))}function childLine(e,n){if(!e)return"";try{return loadSeam(n).child.childRecordLine(e)}catch{const n=e.skipFlag||"no permission flag";return`aegis: claude child [${e.kind}] ${n}`}}module.exports={claudeConfigDir:claudeConfigDir,claudeOAuthToken:claudeOAuthToken,claudeProStatus:claudeProStatus,childEnvPlan:childEnvPlan,envDroppedLine:envDroppedLine,shadowingValue:shadowingValue,SHADOWING_ENV_VARS:SHADOWING_ENV_VARS,PRO_MODELS:PRO_MODELS,turnArgs:turnArgs,createStreamParser:createStreamParser,loadSeam:loadSeam,seamAvailable:seamAvailable,childLine:childLine,isStaleResumeError:isStaleResumeError,runClaudePro:runClaudePro};
3
+ "use strict";const fs=require("node:fs"),os=require("node:os"),path=require("node:path");let envFileLib=null;try{envFileLib=require("../../../client/env-file.js")}catch{try{envFileLib=require("../../vendor/env-file.js")}catch{envFileLib=null}}function claudeConfigDir(e){const n=e||process.env,t=n&&n.CLAUDE_CONFIG_DIR;return t&&String(t).trim()?String(t).trim():path.join(os.homedir(),".claude")}function claudeOAuthToken(e){return envFileLib?envFileLib.resolveForeignSecret("CLAUDE_CODE_OAUTH_TOKEN",{env:e}):""}const SHADOWING_ENV_VARS=Object.freeze(["ANTHROPIC_API_KEY","ANTHROPIC_AUTH_TOKEN"]);function isAnthropicConsoleKey(e){return"string"==typeof e&&/^sk-ant-[A-Za-z0-9_-]{8,}$/.test(e.trim())}function childEnvPlan(e,n,t){const s={...e||{}},o=[],i=envFileLib&&"function"==typeof envFileLib.credentialLooksUsable?envFileLib.credentialLooksUsable:null,r=!(!t||!t.hasSubscription);if(i)for(const e of SHADOWING_ENV_VARS){const n=s[e];if("string"!=typeof n)continue;let t=null;if(i(n)?r&&"ANTHROPIC_API_KEY"===e&&!isAnthropicConsoleKey(n)&&(t="not-a-console-key"):t="too-short",!t)continue;delete s[e];const a=n.trim().length;a>0&&o.push({name:e,length:a,reason:t})}return n&&(s.CLAUDE_CODE_OAUTH_TOKEN=n),{env:s,dropped:o}}function envDroppedLine(e){const n=Array.isArray(e)?e:[];if(!n.length)return null;const t=n.filter(e=>e&&"not-a-console-key"===e.reason),s=n.filter(e=>!e||"not-a-console-key"!==e.reason),o=[];if(s.length){const e=s.map(e=>`${e.name} (${e.length} character${1===e.length?"":"s"})`).join(", ");o.push(`${e}: too short to be a credential, and the CLI would have spent it instead of your subscription`)}if(t.length){const e=t.map(e=>`${e.name} (${e.length} characters)`).join(", ");o.push(`${e}: not an Anthropic console key (\`sk-ant-\`), and the CLI would have spent it instead of your subscription`)}return`aegis: not passed to the claude child — ${o.join("; ")}`}function shadowingValue(e,n){const t=e||{},s=envFileLib&&"function"==typeof envFileLib.credentialLooksUsable?envFileLib.credentialLooksUsable:null;if(!s)return null;const o=!(!n||!n.hasSubscription);for(const e of SHADOWING_ENV_VARS){const n=t[e];if("string"!=typeof n)continue;let i=null;if(s(n)?o&&"ANTHROPIC_API_KEY"===e&&!isAnthropicConsoleKey(n)&&(i="not-a-console-key"):i="too-short",i)return{name:e,length:n.trim().length,reason:i}}return null}function claudeProStatus(e){const n=e||{},t=n.env||process.env,s=path.join(n.dir||claudeConfigDir(t),".credentials.json"),o={claude:n.claudeVersion||null,file:s,exists:!1,kind:null,subscription:null,expiresAt:0,loggedIn:!1};let i;try{i=JSON.parse(fs.readFileSync(s,"utf8")),o.exists=!0}catch{i=null}const r=i&&i.claudeAiOauth;r&&(r.accessToken||r.refreshToken)?(o.kind="oauth",o.subscription=r.subscriptionType||null,o.expiresAt=Number(r.refreshTokenExpiresAt)||0,o.loggedIn=!0):i&&"string"==typeof i.token&&i.token?(o.kind="apikey",o.loggedIn=!0):claudeOAuthToken(t)&&(o.kind="env-token",o.loggedIn=!0),o.subscriptionPresent=o.loggedIn&&"apikey"!==o.kind,o.shadowed=shadowingValue(t,{hasSubscription:o.subscriptionPresent});const a=childEnvPlan(t,null,{hasSubscription:o.subscriptionPresent});return o.credentialPresent=o.loggedIn||"string"==typeof a.env.ANTHROPIC_API_KEY||"string"==typeof a.env.ANTHROPIC_AUTH_TOKEN||"string"==typeof a.env.CLAUDE_CODE_OAUTH_TOKEN,o}const PRO_MODELS=Object.freeze([{id:"default",label:"Default (recommended)",note:"the CLI picks for the subscription"},{id:"sonnet",label:"Sonnet",note:"alias the CLI resolves · latest Sonnet"},{id:"opus",label:"Opus",note:"alias the CLI resolves · latest Opus"},{id:"opusplan",label:"Opus Plan",note:"alias the CLI resolves · plan with Opus, act on Sonnet"},{id:"haiku",label:"Haiku",note:"alias the CLI resolves · latest Haiku"},{id:"fable",label:"Fable",note:"alias the CLI resolves · needs usage credits"},{id:"claude-sonnet-5-5",label:"Claude Sonnet 5.5",note:"full name · Anthropic"},{id:"claude-sonnet-4-6",label:"Claude Sonnet 4.6",note:"full name · Anthropic"},{id:"claude-sonnet-4-5-20250929",label:"Claude Sonnet 4.5",note:"full name · Anthropic · dated snapshot"},{id:"claude-opus-5",label:"Claude Opus 5",note:"full name · Anthropic"},{id:"claude-opus-4-7",label:"Claude Opus 4.7",note:"full name · Anthropic"},{id:"claude-opus-4-6",label:"Claude Opus 4.6",note:"full name · Anthropic"},{id:"claude-opus-4-5-20251101",label:"Claude Opus 4.5",note:"full name · Anthropic · dated snapshot"}]);function turnArgs(e){const n=[],t=e||{};return t.system&&String(t.system).trim()&&n.push("--append-system-prompt",String(t.system)),n}function createStreamParser(e){const n=e||{},t=new Map;let s="",o="",i=0,r=null;const a=e=>[...t.values()].find(n=>"collecting"===n.phase&&n.index===e)||[...t.values()].find(e=>"collecting"===e.phase);return{line(e){let l;try{l=JSON.parse(e)}catch{return}if("control_request"===l.type&&l.request){const e=l.request;if("can_use_tool"!==e.subtype)return;return n.onAsk?void n.onAsk({requestId:l.request_id,toolName:e.tool_name,input:e.input||{},toolUseId:e.tool_use_id,displayName:e.display_name,description:e.description,suggestions:Array.isArray(e.permission_suggestions)?e.permission_suggestions:[]}):void(n.onAskUnavailable&&n.onAskUnavailable({requestId:l.request_id,request:e}))}if("stream_event"===l.type&&l.event){const e=l.event;if("content_block_start"===e.type&&e.content_block)"tool_use"===e.content_block.type&&t.set(e.content_block.id,{id:e.content_block.id,index:null==e.index?0:e.index,name:e.content_block.name,args:"",startedAt:Date.now(),phase:"collecting"});else if("content_block_delta"===e.type&&e.delta){if("text_delta"===e.delta.type){const t=(e.delta.text||"").replace(/\x00/g,"");s+=t,n.onText&&t&&n.onText(t)}else if("thinking_delta"===e.delta.type){const t=(e.delta.thinking||"").replace(/\x00/g,"");o+=t,n.onThinking&&t&&n.onThinking(t);const s=e.delta.estimated_tokens;"number"==typeof s&&s>0&&Number.isFinite(s)&&(i+=s,n.onThinkingProgress&&n.onThinkingProgress(s))}else if("input_json_delta"===e.delta.type){const n=a(null==e.index?0:e.index);n&&(n.args+=e.delta.partial_json||"")}}else if("content_block_stop"===e.type){const s=a(null==e.index?0:e.index);s&&(e=>{let s=e.args;try{s=e.args?JSON.parse(e.args):{}}catch{s={}}t.set(e.id,{...e,args:s,phase:"run"}),n.onTool&&n.onTool({id:e.id,name:e.name,args:s,phase:"run"})})(s)}}else if("user"===l.type&&l.message){const e=Array.isArray(l.message.content)?l.message.content:[];for(const s of e){if(!s||"tool_result"!==s.type||!s.tool_use_id)continue;const e=t.get(s.tool_use_id);if(!e)continue;const o=Math.max(0,Date.now()-(e.startedAt||Date.now()));n.onTool&&n.onTool({id:e.id,name:e.name,phase:"done",elapsed:o,error:!!s.is_error}),t.delete(s.tool_use_id)}}else"result"===l.type&&(r=l,n.onDone&&n.onDone({text:s||l.result||"",error:l.is_error?l.result||(Array.isArray(l.errors)?l.errors.find(e=>"string"==typeof e&&e.trim()):void 0)||"api error":void 0,usage:l.usage||null,costUsd:"number"==typeof l.total_cost_usd?l.total_cost_usd:void 0,durationMs:l.duration_ms,sessionId:l.session_id,thinking:o||"",thinkingTokens:i}))},get text(){return s},get thinking(){return o},get thinkingTokens(){return i},get resultLine(){return r}}}function loadSeam(e){const n=e||__dirname,t=[path.join(n,"..","..","..","one","src"),path.join(n,"..","..","vendor","one","src"),path.join(n,"..","..","..","..","one","src")],s=new Set(["aegisone","aegiscode"]),o=path.join(n,"..","..","..","..");try{const e=JSON.parse(fs.readFileSync(path.join(o,"package.json"),"utf8"));e&&s.has(e.name)&&t.push(path.join(o,"src"))}catch{}for(const e of t)try{const n=require(path.join(e,"child.js")),t=require(path.join(e,"permissions.js"));if("function"==typeof n.claudeArgv&&"function"==typeof t.resolvePosture)return{child:n,permissions:t}}catch{}throw new Error("aegis: the Claude child argv builder (one/src/child.js + one/src/permissions.js) is missing from this install — refusing to build a second argv, because a second argv is a second policy.")}function seamAvailable(e){try{return loadSeam(e),{ok:!0,error:null}}catch(e){return{ok:!1,error:e&&e.message||String(e)}}}function proMessage(e,n,t){const s={content:e||""},o="string"==typeof n?n:"";return o&&(s.reasoning_content=o),"number"==typeof t&&t>0&&Number.isFinite(t)&&(s.thinking_tokens=t),s}function runClaudePro(e,n){const t=e||{},s=n||{},o=s.seam||loadSeam(s.dir),i=s.spawn||require("node:child_process").spawn;let r=void 0===t.permissionMode||null===t.permissionMode?null:String(t.permissionMode);if(null===r)try{const e=o.permissions.storedPermissionFacts();r=e&&"string"==typeof e.permissionMode?e.permissionMode:null}catch{}const a=o.permissions.resolvePosture({rules:t.rules,gate:t.gate,interactive:!1,childKind:o.permissions.CHILD_KINDS.HEADLESS,permissionMode:r,env:t.env||process.env}),l=o.child.claudeArgv({posture:a,prompt:t.prompt,model:t.model||void 0,resumeSessionId:t.resumeSessionId,sessionId:t.sessionId,addDir:t.addDir,askBridge:"function"==typeof t.onAsk,extra:[...turnArgs(t),"--include-partial-messages","--verbose"]});return new Promise(e=>{if(t.signal&&t.signal.aborted)return void e({choices:[{message:{content:""},finish_reason:"stop"}],stopped:!0});const n=t.env||process.env,o=claudeOAuthToken(n);let r=!1;try{r=!!claudeProStatus({env:n}).subscriptionPresent}catch{}const a=childEnvPlan(n,o,{hasSubscription:r}),c=a.env,d=envDroppedLine(a.dropped);if(d&&t.onDelta)try{t.onDelta({delta:"",note:d})}catch{}let u;try{u=i(s.executable||"claude",l.argv,{cwd:t.cwd||process.cwd(),stdio:[l.record.askBridge?"pipe":"ignore","pipe","pipe"],env:c})}catch(n){return void e({choices:[{message:{content:""},finish_reason:"error"}],error:`claude: could not start the child (${n&&n.message||n})`,...a.dropped.length?{envDropped:a.dropped}:{}})}if(t.onSpawn)try{t.onSpawn(u,l.record)}catch{}let p=!1,h="",g="",m=null;const f=Number(t.idleTimeoutMs)||6e5,_=l.record.askBridge,v=e=>{if(!_||!u.stdin||u.stdin.destroyed)return!1;try{return u.stdin.write(`${JSON.stringify(e)}\n`),!0}catch{return!1}};_&&v({type:"user",message:{role:"user",content:[{type:"text",text:String(t.prompt||"")}]}});const y=(e,n,t)=>{v({type:"control_response",response:{subtype:"success",request_id:e,response:"session"===n||"once"===n||"always"===n?{behavior:"allow"}:{behavior:"deny",message:t||"AEGIS_USER_DENIED"}}})},k=n=>{if(!p){if(p=!0,m&&clearTimeout(m),t.signal&&t.signal.removeEventListener("abort",A),_&&u.stdin&&!u.stdin.destroyed)try{u.stdin.end()}catch{}e(a.dropped.length?{...n,envDropped:a.dropped}:n)}},A=()=>{try{u.kill("SIGTERM")}catch{}setTimeout(()=>{try{u.kill("SIGKILL")}catch{}},1500)};t.signal&&t.signal.addEventListener("abort",A,{once:!0});const b=()=>{m&&clearTimeout(m),m=setTimeout(()=>{A(),k({choices:[{message:{content:""},finish_reason:"stop"}],error:`claude: the child went silent for ${Math.round(f/1e3)}s and was stopped`})},f)};b();const S=createStreamParser({onText:e=>{b(),t.onDelta&&t.onDelta({delta:e})},onThinking:e=>{b(),t.onDelta&&t.onDelta({reasoning:e})},onThinkingProgress:e=>{b(),t.onDelta&&t.onDelta({thinkingTokens:e})},onTool:e=>{b(),t.onDelta&&t.onDelta({delta:"",tool:{name:e.name,args:e.args,ok:"done"===e.phase?!e.error:void 0,id:e.id,cwd:t.cwd,phase:e.phase}})},onAsk:e=>{b(),Promise.resolve().then(()=>t.onAsk(e)).then(n=>y(e.requestId,"session"===n||"once"===n||"always"===n?n:"deny","AEGIS_USER_DENIED"),n=>{y(e.requestId,"deny",`AEGIS_USER_DENIED (${n&&n.message||String(n)})`)}).catch(()=>{})},onAskUnavailable:e=>{y(e.requestId,"deny","AEGIS_NO_APPROVAL_CHANNEL")},onDone:e=>{e.error?k({choices:[{message:{content:e.text||""},finish_reason:"error"}],usage:e.usage||void 0,error:e.error,...l.record.resumeSessionId&&isStaleResumeError(e.error)?{resumeStale:!0,resumeSessionId:l.record.resumeSessionId}:{}}):k({choices:[{message:proMessage(e.text||"",e.thinking,e.thinkingTokens),finish_reason:"stop"}],usage:e.usage||void 0,costUsd:e.costUsd,durationMs:e.durationMs,sessionId:e.sessionId,childRecord:l.record})}});u.stdout.on("data",e=>{b(),g+=e.toString("utf8");const n=g.split("\n");g=n.pop()||"";for(const e of n){const n=e.trim();n&&S.line(n)}}),_&&u.stdin&&u.stdin.on("error",()=>{}),u.stderr.on("data",e=>{b(),h.length<8192&&(h+=e.toString("utf8"))}),u.on("error",e=>{k({choices:[{message:{content:""},finish_reason:"error"}],error:`claude: could not run the child (${e&&e.message||e}). Install it with \`npm i -g @anthropic-ai/claude-code\`, then sign in with \`claude auth login\`.`})}),u.on("close",e=>{g.trim()&&S.line(g.trim()),k({choices:[{message:proMessage(S.text,S.thinking,S.thinkingTokens),finish_reason:"stop"}],usage:S.resultLine&&S.resultLine.usage||void 0,childRecord:l.record,error:S.text||0===e?void 0:`claude: the child exited with status ${e}${h.trim()?` — ${h.trim().split("\n").slice(-3).join(" ")}`:""}`})})})}function isStaleResumeError(e){return!!e&&/no conversation found with session id/i.test(String(e))}function childLine(e,n){if(!e)return"";try{return loadSeam(n).child.childRecordLine(e)}catch{const n=e.skipFlag||"no permission flag";return`aegis: claude child [${e.kind}] ${n}`}}module.exports={claudeConfigDir:claudeConfigDir,claudeOAuthToken:claudeOAuthToken,claudeProStatus:claudeProStatus,childEnvPlan:childEnvPlan,envDroppedLine:envDroppedLine,shadowingValue:shadowingValue,SHADOWING_ENV_VARS:SHADOWING_ENV_VARS,PRO_MODELS:PRO_MODELS,turnArgs:turnArgs,createStreamParser:createStreamParser,loadSeam:loadSeam,seamAvailable:seamAvailable,childLine:childLine,isStaleResumeError:isStaleResumeError,runClaudePro:runClaudePro};
@@ -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 CHARS_PER_TOKEN=4,MESSAGE_OVERHEAD=4,IMAGE_COST=850;function estimateTokens(e){if(null==e)return 0;const t="string"==typeof e?e:String(e);return Math.max(0,Math.ceil(t.length/CHARS_PER_TOKEN))}function messageTokens(e){if(!e)return 0;const t=null!=e.content?e.content:null!=e.text?e.text:"";if(Array.isArray(t)){let e=MESSAGE_OVERHEAD;for(const s of t)s&&"object"==typeof s&&("string"==typeof s.text?e+=estimateTokens(s.text):("image_url"===s.type||s.image_url)&&(e+=IMAGE_COST));return e}return MESSAGE_OVERHEAD+estimateTokens(t)}function trimContext({messages:e=[],system:t="",budgetTokens:s=8192,reserveTokens:n=0,fixedTokens:o=0}={}){const E=Math.max(0,s-n),r=[],i=Math.max(0,Number(o)||0);let a=i;t&&(a+=MESSAGE_OVERHEAD+estimateTokens(t));for(let t=e.length-1;t>=0;t--){const s=messageTokens(e[t]);if(a+s>E&&r.length>0)break;r.unshift(e[t]),a+=s}return{messages:r,system:t,dropped:e.length-r.length,estimatedTokens:a,fixedTokens:i}}module.exports={CHARS_PER_TOKEN:CHARS_PER_TOKEN,MESSAGE_OVERHEAD:MESSAGE_OVERHEAD,IMAGE_COST:IMAGE_COST,estimateTokens:estimateTokens,messageTokens:messageTokens,trimContext:trimContext};
3
+ "use strict";const CHARS_PER_TOKEN=4,MESSAGE_OVERHEAD=4,IMAGE_COST=850;function estimateTokens(e){if(null==e)return 0;const t="string"==typeof e?e:String(e);return Math.max(0,Math.ceil(t.length/4))}function messageTokens(e){if(!e)return 0;const t=null!=e.content?e.content:null!=e.text?e.text:"";if(Array.isArray(t)){let e=4;for(const s of t)s&&"object"==typeof s&&("string"==typeof s.text?e+=estimateTokens(s.text):("image_url"===s.type||s.image_url)&&(e+=850));return e}return 4+estimateTokens(t)}function trimContext({messages:e=[],system:t="",budgetTokens:s=8192,reserveTokens:n=0,fixedTokens:o=0}={}){const r=Math.max(0,s-n),i=[],a=Math.max(0,Number(o)||0);let m=a;t&&(m+=4+estimateTokens(t));for(let t=e.length-1;t>=0;t--){const s=messageTokens(e[t]);if(m+s>r&&i.length>0)break;i.unshift(e[t]),m+=s}return{messages:i,system:t,dropped:e.length-i.length,estimatedTokens:m,fixedTokens:a}}module.exports={CHARS_PER_TOKEN:4,MESSAGE_OVERHEAD:4,IMAGE_COST:850,estimateTokens:estimateTokens,messageTokens:messageTokens,trimContext:trimContext};