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 GENERIC_TITLE="New conversation",TITLE_SYSTEM='You name conversations. Write a short descriptive title (2 to 6 words) that captures the topic of the conversation. Never repeat the user\'s words verbatim — if the message is just a greeting or has no clear topic, name it something like "New conversation". Sentence case, no quotes, no markdown, no trailing punctuation, no explanation.',isGenericTitle=e=>!e||String(e).trim().toLowerCase()===GENERIC_TITLE.toLowerCase(),GREETINGS=new Set(["hey","heey","heyy","heyyy","hi","hii","hello","hej","hejj","yo","sup","hola","howdy","hai","heyo","hiya","wassup","greetings","namaste","ahoy","hallo"]);function isTopicless(e){const t=String(e).trim().toLowerCase().replace(/[^a-z0-9\s]/g," ").replace(/\s+/g," ").trim();if(!t)return!0;const i=t.split(" ");return!!/^(good (morning|afternoon|evening)|whats up|wassup|hey there|hello there|hi there|how are you)\b/.test(t)||i.length<=2&&t.length<=12&&GREETINGS.has(i[0])}function looksLikeEcho(e,t){const i=e=>String(e).toLowerCase().replace(/[^a-z0-9\s]/g,"").replace(/\s+/g," ").trim(),n=i(e),r=i(t);if(!n||!r)return!1;if(n===r)return!0;if(r.length<=14&&(n.startsWith(r)||r.startsWith(n)))return!0;if(r.length<=24){const i=e=>new Set((String(e).toLowerCase().match(/[a-z0-9]+/g)||[]).filter((e=>!ECHO_STOP.has(e)))),n=i(e),r=i(t);if(n.size&&n.size===r.size&&[...n].every((e=>r.has(e))))return!0}return!1}const SEED_MAX=60;function isSeedTitle(e,t){const i=String(null==e?"":e).replace(/\s+/g," ").trim(),n=String(null==t?"":t).replace(/\s+/g," ").trim();if(!i||!n)return!1;const r=n.slice(0,SEED_MAX);return i===r||!!(r.length===SEED_MAX&&i.length>=SEED_MAX-8&&r.startsWith(i))}const ECHO_STOP=new Set(["the","a","an","to","of","in","on","at","for","and","or","is","are","be","it","its","my","our","please","can","you","just","do","that","this"]);function cleanTitle(e){return String(null==e?"":e).replace(/\s+/g," ").trim().replace(/["'`“”‘’]/g,"").replace(/[*_#]/g,"").replace(/^\s*(?:title|name)\s*[:\-–]\s*/i,"").replace(/[.\s]+$/g,"").slice(0,60).trim()}const titlePromptOf=e=>`Write a short title for a conversation that begins with: "${String(e).slice(0,500)}"`,FILLER=/^(?:please|pls|plz|hey|hi|hello|ok(?:ay)?|so|now|just|also|and|then|maybe|well|um|uh|can you|could you|would you|will you|i want you to|i want to|i need you to|i need to|i'?d like you to|i would like you to|i'?d like to|help me|help|let'?s|lets|go ahead and)\b[\s,:;-]*/i,TRAILING_STOP=new Set(["the","a","an","in","on","at","to","for","of","and","or","with","is","are","my","our","this","that","please","can","you","could","would","i","we","just","do","it"]);function deriveTitle(e){let t=String(null==e?"":e).trim().replace(/\s+/g," ");if(!t)return GENERIC_TITLE;for(let e=0;e<6;e++){const e=t.replace(FILLER,"").trim();if(e===t)break;t=e}const i=t.split(" ").filter(Boolean);if(!i.length)return GENERIC_TITLE;const n=i.slice(0,6);for(;n.length>2&&TRAILING_STOP.has(n[n.length-1].toLowerCase().replace(/[^a-z0-9]/g,""));)n.pop();let r=n.join(" ").replace(/[.,!?;:]+$/,"").trim();return r?(r=r[0].toUpperCase()+r.slice(1),r.slice(0,60).trim()||GENERIC_TITLE):GENERIC_TITLE}async function nameConversation(e,{callModel:t,signal:i}={}){const n=null==e?"":String(e);if(!n.trim())return"";if(isTopicless(n))return GENERIC_TITLE;if(!("function"!=typeof t||i&&i.aborted)){let e=null;try{e=await t(titlePromptOf(n),{system:TITLE_SYSTEM,signal:i,naming:!0})}catch{e=null}const r=cleanTitle(e);if(r)return looksLikeEcho(r,n)?GENERIC_TITLE:r}return deriveTitle(n)}async function refineTitle(e,t,i={}){const n=i&&!0===i.named,r=i&&!0===i.seeded,o=isSeedTitle(e,t);if(n&&!o)return null;if(!r&&!isGenericTitle(e)&&!o)return null;if(!String(t||"").trim()||isTopicless(t))return null;const s=cleanTitle(await nameConversation(t,i));return!s||isGenericTitle(s)?null:s}async function nameSession(e,t,i,n,r={}){if(!e||"function"!=typeof e.setTitle)return null;if(!i)return null;const o="function"==typeof e.getSession?e.getSession(t,i):null,s=o&&o.title,l=!(!o||o.named);if(l&&s&&!isGenericTitle(s)&&!isSeedTitle(s,n)&&!looksLikeEcho(s,n)){try{e.setTitle(t,i,s,{named:!0})}catch{return null}return null}const a={...r,seeded:l},c=await refineTitle(s,n,a);if(c){try{e.setTitle(t,i,c,{named:!0})}catch{return null}return c}if(isTopicless(n)&&o&&!o.named&&!isGenericTitle(s)){try{e.setTitle(t,i,GENERIC_TITLE)}catch{return null}return GENERIC_TITLE}return null}module.exports={GENERIC_TITLE:GENERIC_TITLE,TITLE_SYSTEM:TITLE_SYSTEM,isGenericTitle:isGenericTitle,isTopicless:isTopicless,isSeedTitle:isSeedTitle,looksLikeEcho:looksLikeEcho,cleanTitle:cleanTitle,titlePromptOf:titlePromptOf,deriveTitle:deriveTitle,nameConversation:nameConversation,refineTitle:refineTitle,nameSession:nameSession};
3
+ "use strict";const GENERIC_TITLE="New conversation",TITLE_SYSTEM='You name conversations. Write a short descriptive title (2 to 6 words) that captures the topic of the conversation. Never repeat the user\'s words verbatim — if the message is just a greeting or has no clear topic, name it something like "New conversation". Sentence case, no quotes, no markdown, no trailing punctuation, no explanation.',isGenericTitle=e=>!e||String(e).trim().toLowerCase()===GENERIC_TITLE.toLowerCase(),GREETINGS=new Set(["hey","heey","heyy","heyyy","hi","hii","hello","hej","hejj","yo","sup","hola","howdy","hai","heyo","hiya","wassup","greetings","namaste","ahoy","hallo"]);function isTopicless(e){const t=String(e).trim().toLowerCase().replace(/[^a-z0-9\s]/g," ").replace(/\s+/g," ").trim();if(!t)return!0;const i=t.split(" ");return!!/^(good (morning|afternoon|evening)|whats up|wassup|hey there|hello there|hi there|how are you)\b/.test(t)||i.length<=2&&t.length<=12&&GREETINGS.has(i[0])}function looksLikeEcho(e,t){const i=e=>String(e).toLowerCase().replace(/[^a-z0-9\s]/g,"").replace(/\s+/g," ").trim(),n=i(e),r=i(t);if(!n||!r)return!1;if(n===r)return!0;if(r.length<=14&&(n.startsWith(r)||r.startsWith(n)))return!0;if(r.length<=24){const i=e=>new Set((String(e).toLowerCase().match(/[a-z0-9]+/g)||[]).filter(e=>!ECHO_STOP.has(e))),n=i(e),r=i(t);if(n.size&&n.size===r.size&&[...n].every(e=>r.has(e)))return!0}return!1}const SEED_MAX=60;function isSeedTitle(e,t){const i=String(null==e?"":e).replace(/\s+/g," ").trim(),n=String(null==t?"":t).replace(/\s+/g," ").trim();if(!i||!n)return!1;const r=n.slice(0,60);return i===r||!!(60===r.length&&i.length>=52&&r.startsWith(i))}const ECHO_STOP=new Set(["the","a","an","to","of","in","on","at","for","and","or","is","are","be","it","its","my","our","please","can","you","just","do","that","this"]);function cleanTitle(e){return String(null==e?"":e).replace(/\s+/g," ").trim().replace(/["'`“”‘’]/g,"").replace(/[*_#]/g,"").replace(/^\s*(?:title|name)\s*[:\-–]\s*/i,"").replace(/[.\s]+$/g,"").slice(0,60).trim()}const titlePromptOf=e=>`Write a short title for a conversation that begins with: "${String(e).slice(0,500)}"`,FILLER=/^(?:please|pls|plz|hey|hi|hello|ok(?:ay)?|so|now|just|also|and|then|maybe|well|um|uh|can you|could you|would you|will you|i want you to|i want to|i need you to|i need to|i'?d like you to|i would like you to|i'?d like to|help me|help|let'?s|lets|go ahead and)\b[\s,:;-]*/i,TRAILING_STOP=new Set(["the","a","an","in","on","at","to","for","of","and","or","with","is","are","my","our","this","that","please","can","you","could","would","i","we","just","do","it"]);function deriveTitle(e){let t=String(null==e?"":e).trim().replace(/\s+/g," ");if(!t)return GENERIC_TITLE;for(let e=0;e<6;e++){const e=t.replace(FILLER,"").trim();if(e===t)break;t=e}const i=t.split(" ").filter(Boolean);if(!i.length)return GENERIC_TITLE;const n=i.slice(0,6);for(;n.length>2&&TRAILING_STOP.has(n[n.length-1].toLowerCase().replace(/[^a-z0-9]/g,""));)n.pop();let r=n.join(" ").replace(/[.,!?;:]+$/,"").trim();return r?(r=r[0].toUpperCase()+r.slice(1),r.slice(0,60).trim()||GENERIC_TITLE):GENERIC_TITLE}async function nameConversation(e,{callModel:t,signal:i}={}){const n=null==e?"":String(e);if(!n.trim())return"";if(isTopicless(n))return GENERIC_TITLE;if(!("function"!=typeof t||i&&i.aborted)){let e=null;try{e=await t(titlePromptOf(n),{system:TITLE_SYSTEM,signal:i,naming:!0})}catch{e=null}const r=cleanTitle(e);if(r)return looksLikeEcho(r,n)?GENERIC_TITLE:r}return deriveTitle(n)}async function refineTitle(e,t,i={}){const n=i&&!0===i.named,r=i&&!0===i.seeded,o=isSeedTitle(e,t);if(n&&!o)return null;if(!r&&!isGenericTitle(e)&&!o)return null;if(!String(t||"").trim()||isTopicless(t))return null;const s=cleanTitle(await nameConversation(t,i));return!s||isGenericTitle(s)?null:s}async function nameSession(e,t,i,n,r={}){if(!e||"function"!=typeof e.setTitle)return null;if(!i)return null;const o="function"==typeof e.getSession?e.getSession(t,i):null,s=o&&o.title,l=!(!o||o.named);if(l&&s&&!isGenericTitle(s)&&!isSeedTitle(s,n)&&!looksLikeEcho(s,n)){try{e.setTitle(t,i,s,{named:!0})}catch{return null}return null}const a={...r,seeded:l},c=await refineTitle(s,n,a);if(c){try{e.setTitle(t,i,c,{named:!0})}catch{return null}return c}if(isTopicless(n)&&o&&!o.named&&!isGenericTitle(s)){try{e.setTitle(t,i,GENERIC_TITLE)}catch{return null}return GENERIC_TITLE}return null}module.exports={GENERIC_TITLE:GENERIC_TITLE,TITLE_SYSTEM:TITLE_SYSTEM,isGenericTitle:isGenericTitle,isTopicless:isTopicless,isSeedTitle:isSeedTitle,looksLikeEcho:looksLikeEcho,cleanTitle:cleanTitle,titlePromptOf:titlePromptOf,deriveTitle:deriveTitle,nameConversation:nameConversation,refineTitle:refineTitle,nameSession:nameSession};
@@ -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"),{spawnSync:spawnSync}=require("node:child_process"),IS_WIN32="win32"===process.platform,DEFAULT_PATHEXT=".COM;.EXE;.BAT;.CMD";function defaultExists(e){try{return fs.statSync(e).isFile()}catch{return!1}}function defaultProbe(e,t=[],r={}){try{const n=spawnSync(e,t,{encoding:"utf8",timeout:r.timeout||5e3,windowsHide:!0,env:r.env});return n.error||0!==n.status?null:"string"==typeof n.stdout?n.stdout:""}catch{return null}}function defaultDirExists(e){try{return fs.statSync(e).isDirectory()}catch{return!1}}function defaultDirNonEmpty(e){try{return fs.readdirSync(e).length>0}catch{return!1}}function defaultReadText(e){try{return fs.readFileSync(e,"utf8")}catch{return null}}function defaultRun(e,t=[],r={}){try{const n=spawnSync(e,t,{encoding:"utf8",windowsHide:!0,timeout:r.timeout||1e4,env:r.env});if(n.error)return{ok:!1,error:n.error,output:""};if(0!==n.status){const t=String(n.stderr||"").trim();return{ok:!1,error:new Error(`${e} exited ${n.status}${t?`: ${t}`:""}`),status:n.status,output:String(n.stdout||"")}}return{ok:!0,error:null,output:String(n.stdout||"")}}catch(e){return{ok:!1,error:e,output:""}}}function seams(e){const t=e&&"object"==typeof e?e:{},r="string"==typeof t.platform&&t.platform?t.platform:process.platform;return{o:t,platform:r,env:t.env&&"object"==typeof t.env?t.env:process.env,win32:"win32"===r,exists:"function"==typeof t.exists?t.exists:defaultExists,probe:"function"==typeof t.probe?t.probe:defaultProbe,injectedProbe:"function"==typeof t.probe,kill:"function"==typeof t.kill?t.kill:(...e)=>process.kill(...e),run:"function"==typeof t.run?t.run:defaultRun}}function envValue(e,t,r){if(!e||"object"!=typeof e)return;const n=void 0!==e[t]?e[t]:e[t.toUpperCase()];if(void 0!==n)return n;if("win32"!==r)return;const o=t.toLowerCase();for(const t of Object.keys(e))if(t.toLowerCase()===o)return e[t]}function pathEntries(e,t,r,n){const o=String(envValue(e,"PATH",t)||"").split("win32"===t?";":":"),s=[];for(const e of o){const t=e.trim().replace(/^"|"$/g,"");t&&s.push(n.isAbsolute(t)?t:n.join(r,t))}return s}function extList(e,t){const r=String(envValue(e,"PATHEXT",t)||DEFAULT_PATHEXT).split(";").map((e=>e.trim())).filter(Boolean).map((e=>e.startsWith(".")?e:`.${e}`));return r.length?r:DEFAULT_PATHEXT.split(";")}function resolveExecutable(e,t={}){const{platform:r,env:n,exists:o,win32:s,o:i}=seams(t);if("string"!=typeof e||!e.trim())return null;const a=e.trim(),l="string"==typeof i.cwd&&i.cwd?i.cwd:process.cwd(),u=s?path.win32:path;if(s?a.includes("/")||a.includes("\\")||/^[a-zA-Z]:/.test(a):a.includes("/")){const e=u.isAbsolute(a)?a:u.join(l,a);return o(e)?e:null}const c=s?["",...extList(n,r)]:[""];for(const e of pathEntries(n,r,l,u))for(const t of c){const r=u.join(e,a+t);if(o(r))return r}return null}function shellSpec(e={}){const{platform:t,env:r,win32:n}=seams(e);return n?{cmd:envValue(r,"ComSpec",t)||envValue(r,"COMSPEC",t)||"cmd.exe",arg:"/d /s /c",kind:"cmd"}:{cmd:envValue(r,"SHELL",t)||"/bin/sh",arg:"-c",kind:"posix"}}function killTree(e,t={}){const{platform:r,env:n,win32:o,kill:s,run:i,o:a}=seams(t),l="number"==typeof e?e:e&&e.pid,u=a.signal||"SIGTERM",c=!1!==a.detached,f=a.timeout||1e4;if(!Number.isInteger(l)||l<=0)return{ok:!1,method:"none",pid:Number.isInteger(l)?l:null,error:new Error(`killTree: no usable pid (got ${JSON.stringify(e&&e.pid)})`),gone:!1};if(o){const e=i("taskkill",["/PID",String(l),"/T","/F"],{env:n,platform:r,timeout:f})||{};return!1===e.ok?{ok:!1,method:"taskkill",pid:l,error:e.error||new Error("taskkill failed"),gone:!1}:{ok:!0,method:"taskkill",pid:l,error:null,gone:!1}}let p=null;if(c)try{return s(-l,u),{ok:!0,method:"group",pid:l,error:null,gone:!1}}catch(e){p=e;const t=e&&e.code;if("ESRCH"!==t&&"EPERM"!==t)return{ok:!1,method:"group",pid:l,error:e,gone:!1}}try{return s(l,u),{ok:!0,method:"signal",pid:l,error:null,groupError:p,gone:!1}}catch(e){return{ok:!1,method:"signal",pid:l,error:e,groupError:p,gone:"ESRCH"===(e&&e.code)}}}function isAlive(e,t={}){const{platform:r,env:n,win32:o,probe:s,kill:i}=seams(t),a="number"==typeof e?e:Number(e);if(!Number.isInteger(a)||a<=0)return!1;if(o){const e=s("tasklist",["/FI",`PID eq ${a}`,"/NH","/FO","CSV"],{env:n,platform:r});if(null==e)return!1;const t=String(e).trim();return!!t&&new RegExp(`(^|[^0-9])${a}([^0-9]|$)`).test(t)}try{return i(a,0),!0}catch(e){return Boolean(e&&"EPERM"===e.code)}}function hasDisplay(e={}){const{platform:t,env:r,win32:n,probe:o,injectedProbe:s}=seams(e);return!!(n||"darwin"===t||envValue(r,"DISPLAY",t)||envValue(r,"WAYLAND_DISPLAY",t)||s&&null!==o("xdpyinfo",[],{env:r,platform:t}))}function normalizeLocale(e){if(null==e)return"";const t=String(e).trim();if(!t)return"";const r=t.split("@")[0].split(".")[0];if(/^(c|posix)$/i.test(r))return"";const n=/^([A-Za-z]{2,3})(?:[_-]([A-Za-z0-9]{2,8}))?$/.exec(r);if(!n)return"";const o=n[1].toLowerCase();return"c"===o||"posix"===o?"":n[2]?`${o}-${n[2].toUpperCase()}`:o}function appLocale(e={}){const{platform:t,env:r,o:n}=seams(e);if("string"==typeof n.locale)return normalizeLocale(n.locale);const o=n.env&&"object"==typeof n.env;for(const e of["LC_ALL","LC_CTYPE","LC_MESSAGES","LANG"]){const n=normalizeLocale(envValue(r,e,t));if(n)return n}const s=String(envValue(r,"LANGUAGE",t)||"");if(s)for(const e of s.split(":")){const t=normalizeLocale(e);if(t)return t}if(o)return"";try{return normalizeLocale((new Intl.DateTimeFormat).resolvedOptions().locale)}catch{return""}}function languageName(e,t={}){const{o:r}=seams(t);if("string"==typeof r.languageName)return r.languageName;const n=normalizeLocale(e);if(!n)return"";const o=n.split("-")[0];try{return new Intl.DisplayNames(["en"],{type:"language"}).of(o)||""}catch{return""}}function homeDir(e={}){const{platform:t,env:r,o:n}=seams(e);if("string"==typeof n.home)return n.home.trim();const o="win32"===t?["USERPROFILE","HOME"]:["HOME","USERPROFILE"];for(const e of o){const n=envValue(r,e,t);if(n&&String(n).trim())return String(n).trim()}try{return os.homedir()||""}catch{return""}}function hasPosixModes(e={}){const{win32:t}=seams(e);return!t}function winShellFolderDesktop(e,t){const r=e("reg",["query","HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Shell Folders","/v","Desktop"]);if(!r)return"";const n=/^\s*Desktop\s+REG_(?:EXPAND_)?SZ\s+(.+)$/im.exec(r),o=n&&n[1].trim();return o&&t(o)?o:""}function desktopDir(e={}){const{platform:t,env:r,win32:n,probe:o,o:s}=seams(e),i=n?path.win32:path.posix,a=homeDir(e),l="function"==typeof s.dirExists?s.dirExists:defaultDirExists,u="function"==typeof s.dirNonEmpty?s.dirNonEmpty:defaultDirNonEmpty;if(n){const e=winShellFolderDesktop(o,l);if(e)return e}const c="function"==typeof s.readText?s.readText:defaultReadText,f=[],p=e=>{e&&String(e).trim()&&f.push(String(e).trim())};if(n){const e=envValue(r,"OneDrive",t)||envValue(r,"OneDriveConsumer",t);e&&p(i.join(e,"Desktop")),a&&p(i.join(a,"OneDrive","Desktop")),a&&p(i.join(a,"Desktop"));const n=a?i.join(a,"Desktop"):"",o=f.indexOf(n);o>0&&l(n)&&u(n)&&f.slice(0,o).every((e=>!l(e)||!u(e)))&&(f.splice(o,1),f.unshift(n))}else if("darwin"===t)a&&p(i.join(a,"Desktop"));else{if(p(envValue(r,"XDG_DESKTOP_DIR",t)),a){const e=c(i.join(a,".config","user-dirs.dirs")),t=e&&/^\s*XDG_DESKTOP_DIR\s*=\s*"?([^"\n]+)"?\s*$/m.exec(e);t&&p(t[1].replace(/\$HOME\b|\${HOME}/g,a))}a&&p(i.join(a,"Desktop"))}for(const e of f)if(l(e))return e;return a&&(n||"darwin"===t)?i.join(a,"Desktop"):""}function applyDesktopAlias(e,{home:t,desktopdir:r,win32:n,P:o}){if(!t||!r)return e;const s=o.join(t,"Desktop"),i=e=>n?e.toLowerCase():e;if(i(s)===i(r))return e;if(i(e)===i(s))return r;const a=s+o.sep;return i(e).startsWith(i(a))?r+o.sep+e.slice(a.length):e}const WIN_DRIVE_RE=/^[A-Za-z]:[\\/]/,WIN_BARE_DRIVE_RE=/^[A-Za-z]:$/,WIN_UNC_RE=/^\\\\[^\\?.]/;function resolvePath(e,t={}){const{platform:r,win32:n,o:o}=seams(t),s=n?path.win32:path.posix,i=e=>({ok:!1,path:null,error:e,expandedHome:!1});if("string"!=typeof e||!e.trim())return i(`a path is required (got ${JSON.stringify(e)})`);const a=e.trim();let l=a,u=!1;if("~"===a||a.startsWith("~/")||n&&a.startsWith("~\\")){const e=homeDir(t);if(!e)return i(`cannot expand "~" in ${JSON.stringify(a)}: this machine reports no home directory. Pass a full absolute path instead.`);l="~"===a?e:s.join(e,a.slice(2)),u=!0}else if(a.startsWith("~"))return i(`${JSON.stringify(a)} names another user's home directory, which cannot be resolved from here. Use "~" for this user, or pass a full absolute path.`);if(l=applyDesktopAlias(l,{home:homeDir(t),desktopdir:o.desktopdir,win32:n,P:s}),!u){const e=homeDir(t),o=e?` This machine's home directory is ${e}.`:"";if(n){if((l.startsWith("/")||l.startsWith("\\"))&&!WIN_UNC_RE.test(l))return i(`${JSON.stringify(a)} is not an absolute path on this machine, which runs ${r}. A leading slash here means "the root of the current drive", so writing to it would silently land somewhere other than where you meant. Use a drive-qualified path (C:\\Users\\you\\Desktop\\file.txt) or "~/…".${o}`)}else if(WIN_DRIVE_RE.test(l)||WIN_BARE_DRIVE_RE.test(l)||WIN_UNC_RE.test(l))return i(`${JSON.stringify(a)} is a Windows path, but this machine runs ${r}. Use a posix path (/home/you/file.txt) or "~/…".${o}`)}const c="string"==typeof o.cwd&&o.cwd.trim()?o.cwd.trim():process.cwd(),f=s.isAbsolute(l)?s.resolve(l):s.resolve(c,l);return s.isAbsolute(f)?{ok:!0,path:f,error:null,expandedHome:u}:i(`${JSON.stringify(a)} is relative and the working directory (${JSON.stringify(c)}) is not absolute, so it cannot be resolved. Pass an absolute path.`)}function baseName(e){if("string"!=typeof e)return"";const t=e.trim().replace(/[/\\]+$/,"");if(!t)return"";if(/^[A-Za-z]:$/.test(t))return"";const r=Math.max(t.lastIndexOf("/"),t.lastIndexOf("\\"));return-1===r?t:t.slice(r+1)}const api={IS_WIN32:IS_WIN32,seams:seams,resolveExecutable:resolveExecutable,shellSpec:shellSpec,killTree:killTree,isAlive:isAlive,hasDisplay:hasDisplay,homeDir:homeDir,desktopDir:desktopDir,resolvePath:resolvePath,baseName:baseName,hasPosixModes:hasPosixModes,appLocale:appLocale,languageName:languageName,normalizeLocale:normalizeLocale};module.exports=api;
3
+ "use strict";const fs=require("node:fs"),os=require("node:os"),path=require("node:path"),{spawnSync:spawnSync}=require("node:child_process"),IS_WIN32="win32"===process.platform,DEFAULT_PATHEXT=".COM;.EXE;.BAT;.CMD";function defaultExists(e){try{return fs.statSync(e).isFile()}catch{return!1}}function defaultProbe(e,t=[],r={}){try{const n=spawnSync(e,t,{encoding:"utf8",timeout:r.timeout||5e3,windowsHide:!0,env:r.env});return n.error||0!==n.status?null:"string"==typeof n.stdout?n.stdout:""}catch{return null}}function defaultDirExists(e){try{return fs.statSync(e).isDirectory()}catch{return!1}}function defaultDirNonEmpty(e){try{return fs.readdirSync(e).length>0}catch{return!1}}function defaultReadText(e){try{return fs.readFileSync(e,"utf8")}catch{return null}}function defaultRun(e,t=[],r={}){try{const n=spawnSync(e,t,{encoding:"utf8",windowsHide:!0,timeout:r.timeout||1e4,env:r.env});if(n.error)return{ok:!1,error:n.error,output:""};if(0!==n.status){const t=String(n.stderr||"").trim();return{ok:!1,error:new Error(`${e} exited ${n.status}${t?`: ${t}`:""}`),status:n.status,output:String(n.stdout||"")}}return{ok:!0,error:null,output:String(n.stdout||"")}}catch(e){return{ok:!1,error:e,output:""}}}function seams(e){const t=e&&"object"==typeof e?e:{},r="string"==typeof t.platform&&t.platform?t.platform:process.platform;return{o:t,platform:r,env:t.env&&"object"==typeof t.env?t.env:process.env,win32:"win32"===r,exists:"function"==typeof t.exists?t.exists:defaultExists,probe:"function"==typeof t.probe?t.probe:defaultProbe,injectedProbe:"function"==typeof t.probe,kill:"function"==typeof t.kill?t.kill:(...e)=>process.kill(...e),run:"function"==typeof t.run?t.run:defaultRun}}function envValue(e,t,r){if(!e||"object"!=typeof e)return;const n=void 0!==e[t]?e[t]:e[t.toUpperCase()];if(void 0!==n)return n;if("win32"!==r)return;const o=t.toLowerCase();for(const t of Object.keys(e))if(t.toLowerCase()===o)return e[t]}function pathEntries(e,t,r,n){const o=String(envValue(e,"PATH",t)||"").split("win32"===t?";":":"),s=[];for(const e of o){const t=e.trim().replace(/^"|"$/g,"");t&&s.push(n.isAbsolute(t)?t:n.join(r,t))}return s}function extList(e,t){const r=String(envValue(e,"PATHEXT",t)||DEFAULT_PATHEXT).split(";").map(e=>e.trim()).filter(Boolean).map(e=>e.startsWith(".")?e:`.${e}`);return r.length?r:DEFAULT_PATHEXT.split(";")}function resolveExecutable(e,t={}){const{platform:r,env:n,exists:o,win32:s,o:i}=seams(t);if("string"!=typeof e||!e.trim())return null;const a=e.trim(),l="string"==typeof i.cwd&&i.cwd?i.cwd:process.cwd(),u=s?path.win32:path;if(s?a.includes("/")||a.includes("\\")||/^[a-zA-Z]:/.test(a):a.includes("/")){const e=u.isAbsolute(a)?a:u.join(l,a);return o(e)?e:null}const c=s?["",...extList(n,r)]:[""];for(const e of pathEntries(n,r,l,u))for(const t of c){const r=u.join(e,a+t);if(o(r))return r}return null}function shellSpec(e={}){const{platform:t,env:r,win32:n}=seams(e);return n?{cmd:envValue(r,"ComSpec",t)||envValue(r,"COMSPEC",t)||"cmd.exe",arg:"/d /s /c",kind:"cmd"}:{cmd:envValue(r,"SHELL",t)||"/bin/sh",arg:"-c",kind:"posix"}}function killTree(e,t={}){const{platform:r,env:n,win32:o,kill:s,run:i,o:a}=seams(t),l="number"==typeof e?e:e&&e.pid,u=a.signal||"SIGTERM",c=!1!==a.detached,f=a.timeout||1e4;if(!Number.isInteger(l)||l<=0)return{ok:!1,method:"none",pid:Number.isInteger(l)?l:null,error:new Error(`killTree: no usable pid (got ${JSON.stringify(e&&e.pid)})`),gone:!1};if(o){const e=i("taskkill",["/PID",String(l),"/T","/F"],{env:n,platform:r,timeout:f})||{};return!1===e.ok?{ok:!1,method:"taskkill",pid:l,error:e.error||new Error("taskkill failed"),gone:!1}:{ok:!0,method:"taskkill",pid:l,error:null,gone:!1}}let p=null;if(c)try{return s(-l,u),{ok:!0,method:"group",pid:l,error:null,gone:!1}}catch(e){p=e;const t=e&&e.code;if("ESRCH"!==t&&"EPERM"!==t)return{ok:!1,method:"group",pid:l,error:e,gone:!1}}try{return s(l,u),{ok:!0,method:"signal",pid:l,error:null,groupError:p,gone:!1}}catch(e){return{ok:!1,method:"signal",pid:l,error:e,groupError:p,gone:"ESRCH"===(e&&e.code)}}}function isAlive(e,t={}){const{platform:r,env:n,win32:o,probe:s,kill:i}=seams(t),a="number"==typeof e?e:Number(e);if(!Number.isInteger(a)||a<=0)return!1;if(o){const e=s("tasklist",["/FI",`PID eq ${a}`,"/NH","/FO","CSV"],{env:n,platform:r});if(null==e)return!1;const t=String(e).trim();return!!t&&new RegExp(`(^|[^0-9])${a}([^0-9]|$)`).test(t)}try{return i(a,0),!0}catch(e){return Boolean(e&&"EPERM"===e.code)}}function hasDisplay(e={}){const{platform:t,env:r,win32:n,probe:o,injectedProbe:s}=seams(e);return!!(n||"darwin"===t||envValue(r,"DISPLAY",t)||envValue(r,"WAYLAND_DISPLAY",t)||s&&null!==o("xdpyinfo",[],{env:r,platform:t}))}function normalizeLocale(e){if(null==e)return"";const t=String(e).trim();if(!t)return"";const r=t.split("@")[0].split(".")[0];if(/^(c|posix)$/i.test(r))return"";const n=/^([A-Za-z]{2,3})(?:[_-]([A-Za-z0-9]{2,8}))?$/.exec(r);if(!n)return"";const o=n[1].toLowerCase();return"c"===o||"posix"===o?"":n[2]?`${o}-${n[2].toUpperCase()}`:o}function appLocale(e={}){const{platform:t,env:r,o:n}=seams(e);if("string"==typeof n.locale)return normalizeLocale(n.locale);const o=n.env&&"object"==typeof n.env;for(const e of["LC_ALL","LC_CTYPE","LC_MESSAGES","LANG"]){const n=normalizeLocale(envValue(r,e,t));if(n)return n}const s=String(envValue(r,"LANGUAGE",t)||"");if(s)for(const e of s.split(":")){const t=normalizeLocale(e);if(t)return t}if(o)return"";try{return normalizeLocale((new Intl.DateTimeFormat).resolvedOptions().locale)}catch{return""}}function languageName(e,t={}){const{o:r}=seams(t);if("string"==typeof r.languageName)return r.languageName;const n=normalizeLocale(e);if(!n)return"";const o=n.split("-")[0];try{return new Intl.DisplayNames(["en"],{type:"language"}).of(o)||""}catch{return""}}function homeDir(e={}){const{platform:t,env:r,o:n}=seams(e);if("string"==typeof n.home)return n.home.trim();const o="win32"===t?["USERPROFILE","HOME"]:["HOME","USERPROFILE"];for(const e of o){const n=envValue(r,e,t);if(n&&String(n).trim())return String(n).trim()}try{return os.homedir()||""}catch{return""}}function hasPosixModes(e={}){const{win32:t}=seams(e);return!t}function winShellFolderDesktop(e,t){const r=e("reg",["query","HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Shell Folders","/v","Desktop"]);if(!r)return"";const n=/^\s*Desktop\s+REG_(?:EXPAND_)?SZ\s+(.+)$/im.exec(r),o=n&&n[1].trim();return o&&t(o)?o:""}function desktopDir(e={}){const{platform:t,env:r,win32:n,probe:o,o:s}=seams(e),i=n?path.win32:path.posix,a=homeDir(e),l="function"==typeof s.dirExists?s.dirExists:defaultDirExists,u="function"==typeof s.dirNonEmpty?s.dirNonEmpty:defaultDirNonEmpty;if(n){const e=winShellFolderDesktop(o,l);if(e)return e}const c="function"==typeof s.readText?s.readText:defaultReadText,f=[],p=e=>{e&&String(e).trim()&&f.push(String(e).trim())};if(n){const e=envValue(r,"OneDrive",t)||envValue(r,"OneDriveConsumer",t);e&&p(i.join(e,"Desktop")),a&&p(i.join(a,"OneDrive","Desktop")),a&&p(i.join(a,"Desktop"));const n=a?i.join(a,"Desktop"):"",o=f.indexOf(n);o>0&&l(n)&&u(n)&&f.slice(0,o).every(e=>!l(e)||!u(e))&&(f.splice(o,1),f.unshift(n))}else if("darwin"===t)a&&p(i.join(a,"Desktop"));else{if(p(envValue(r,"XDG_DESKTOP_DIR",t)),a){const e=c(i.join(a,".config","user-dirs.dirs")),t=e&&/^\s*XDG_DESKTOP_DIR\s*=\s*"?([^"\n]+)"?\s*$/m.exec(e);t&&p(t[1].replace(/\$HOME\b|\${HOME}/g,a))}a&&p(i.join(a,"Desktop"))}for(const e of f)if(l(e))return e;return a&&(n||"darwin"===t)?i.join(a,"Desktop"):""}function applyDesktopAlias(e,{home:t,desktopdir:r,win32:n,P:o}){if(!t||!r)return e;const s=o.join(t,"Desktop"),i=e=>n?e.toLowerCase():e;if(i(s)===i(r))return e;if(i(e)===i(s))return r;const a=s+o.sep;return i(e).startsWith(i(a))?r+o.sep+e.slice(a.length):e}const WIN_DRIVE_RE=/^[A-Za-z]:[\\/]/,WIN_BARE_DRIVE_RE=/^[A-Za-z]:$/,WIN_UNC_RE=/^\\\\[^\\?.]/;function resolvePath(e,t={}){const{platform:r,win32:n,o:o}=seams(t),s=n?path.win32:path.posix,i=e=>({ok:!1,path:null,error:e,expandedHome:!1});if("string"!=typeof e||!e.trim())return i(`a path is required (got ${JSON.stringify(e)})`);const a=e.trim();let l=a,u=!1;if("~"===a||a.startsWith("~/")||n&&a.startsWith("~\\")){const e=homeDir(t);if(!e)return i(`cannot expand "~" in ${JSON.stringify(a)}: this machine reports no home directory. Pass a full absolute path instead.`);l="~"===a?e:s.join(e,a.slice(2)),u=!0}else if(a.startsWith("~"))return i(`${JSON.stringify(a)} names another user's home directory, which cannot be resolved from here. Use "~" for this user, or pass a full absolute path.`);if(l=applyDesktopAlias(l,{home:homeDir(t),desktopdir:o.desktopdir,win32:n,P:s}),!u){const e=homeDir(t),o=e?` This machine's home directory is ${e}.`:"";if(n){if((l.startsWith("/")||l.startsWith("\\"))&&!WIN_UNC_RE.test(l))return i(`${JSON.stringify(a)} is not an absolute path on this machine, which runs ${r}. A leading slash here means "the root of the current drive", so writing to it would silently land somewhere other than where you meant. Use a drive-qualified path (C:\\Users\\you\\Desktop\\file.txt) or "~/…".${o}`)}else if(WIN_DRIVE_RE.test(l)||WIN_BARE_DRIVE_RE.test(l)||WIN_UNC_RE.test(l))return i(`${JSON.stringify(a)} is a Windows path, but this machine runs ${r}. Use a posix path (/home/you/file.txt) or "~/…".${o}`)}const c="string"==typeof o.cwd&&o.cwd.trim()?o.cwd.trim():process.cwd(),f=s.isAbsolute(l)?s.resolve(l):s.resolve(c,l);return s.isAbsolute(f)?{ok:!0,path:f,error:null,expandedHome:u}:i(`${JSON.stringify(a)} is relative and the working directory (${JSON.stringify(c)}) is not absolute, so it cannot be resolved. Pass an absolute path.`)}function baseName(e){if("string"!=typeof e)return"";const t=e.trim().replace(/[/\\]+$/,"");if(!t)return"";if(/^[A-Za-z]:$/.test(t))return"";const r=Math.max(t.lastIndexOf("/"),t.lastIndexOf("\\"));return-1===r?t:t.slice(r+1)}const api={IS_WIN32:IS_WIN32,seams:seams,resolveExecutable:resolveExecutable,shellSpec:shellSpec,killTree:killTree,isAlive:isAlive,hasDisplay:hasDisplay,homeDir:homeDir,desktopDir:desktopDir,resolvePath:resolvePath,baseName:baseName,hasPosixModes:hasPosixModes,appLocale:appLocale,languageName:languageName,normalizeLocale:normalizeLocale};module.exports=api;
@@ -1,3 +1,3 @@
1
1
  // SPDX-License-Identifier: AGPL-3.0-or-later
2
2
  // Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
3
- "use strict";const fs=require("node:fs"),path=require("node:path"),{aegisHome:aegisHome}=require("./credentials.js"),PREFS_FILE="preferences.json",PREFS_VERSION=1,SHARED_PREF_KEYS=Object.freeze(["themeIndex","model","modelClass","currentModelId","models","modelAutoSync","effort","vim","memoryPersist","confirmMode","permissionMode","sandboxPolicy","devMode","speech","accountUsername"]),LEGACY_MEMORY_PERSIST_NAMESPACE="__memoryPersist",LEGACY_CONFIRM_MODE_NAMESPACE="__confirmMode",SECRET_KEY_RE=/(^|[^a-z0-9])(api[_-]?key|apikey|key|keys|token|secret|password|passwd|credential|credentials|authorization|bearer|private[_-]?key|access[_-]?key|session[_-]?key)([^a-z0-9]|$)/i,SECRET_VALUE_RES=[/\baegis_[A-Za-z0-9_\-]{12,}/,/\bsk-[A-Za-z0-9_\-]{12,}/,/\bghp_[A-Za-z0-9_\-]{20,}/,/\bxox[baprs]-[A-Za-z0-9\-]{10,}/,/\beyJ[A-Za-z0-9_\-]{16,}\.[A-Za-z0-9_\-]{8,}/,/^[A-Za-z0-9+/]{48,}={0,2}$/];function prefsDir(e){const r=e||{};return r.dir&&String(r.dir).trim()?path.resolve(String(r.dir).trim()):aegisHome(r.env)}function prefsFile(e){const r=e||{};return r.file&&String(r.file).trim()?path.resolve(String(r.file).trim()):path.join(prefsDir(r),PREFS_FILE)}function scanForSecrets(e,r="",t=[]){if(null==e)return t;if("string"==typeof e)return SECRET_VALUE_RES.some((r=>r.test(e)))&&t.push(r||"(root)"),t;if("object"!=typeof e)return t;if(Array.isArray(e))return e.forEach(((e,o)=>scanForSecrets(e,`${r}[${o}]`,t))),t;for(const[o,s]of Object.entries(e)){const e=r?`${r}.${o}`:o;SECRET_KEY_RE.test(o)&&null!=s&&""!==s&&!1!==s?t.push(e):scanForSecrets(s,e,t)}return t}function assertNoSecrets(e,r="shared preference store"){const t=scanForSecrets(e);if(t.length)throw new Error(`${r} must not carry key material — refusing to write (found: ${t.join(", ")}). Secrets belong in the host-local credential store, where the OS can protect them.`);return e}function readJson(e,r){try{const t=JSON.parse(fs.readFileSync(e,"utf8"));return t&&"object"==typeof t&&!Array.isArray(t)?t:r}catch{return r}}function load(e){return readJson(prefsFile(e),{})}function write(e,r){assertNoSecrets(e);const t=prefsFile(r);fs.mkdirSync(path.dirname(t),{recursive:!0});const o=`${t}.tmp-${process.pid}`;fs.writeFileSync(o,JSON.stringify(e,null,2)+"\n",{mode:384}),fs.renameSync(o,t);try{fs.chmodSync(t,384)}catch{}return e}function set(e,r){const t={...load(r),...e||{}};for(const e of Object.keys(t))void 0===t[e]&&delete t[e];return void 0===t.version&&(t.version=1),write(t,r)}function get(e,r,t){const o=load(r)[e];return void 0===o?t:o}function has(e,r){return void 0!==load(r)[e]}function remove(e,r){const t=load(r);return delete t[e],write(t,r)}function extractNonSecretHalf(e){const r={},t=(e||{})[LEGACY_MEMORY_PERSIST_NAMESPACE];t&&"object"==typeof t&&"boolean"==typeof t.enabled&&(r.memoryPersist=t.enabled);const o=(e||{})[LEGACY_CONFIRM_MODE_NAMESPACE];return o&&"object"==typeof o&&"boolean"==typeof o.enabled&&(r.confirmMode=o.enabled),r}function adopt(e){const r=e||{},t=prefsFile(r),o=r.legacyDir,s=o?path.join(String(o),"settings.json"):null;if(s&&path.resolve(s)===t)return{adopted:!1,keys:[],from:s,reason:"shared store is the legacy file"};if(!s||!fs.existsSync(s))return{adopted:!1,keys:[],from:s,reason:"no legacy settings file"};const n=load(r),a=extractNonSecretHalf(readJson(s,{})),i=Object.keys(a).filter((e=>void 0===n[e]));if(!i.length)return{adopted:!1,keys:[],from:s,reason:Object.keys(a).length?"shared store already carries these preferences":"legacy store has no shared preferences"};const c={};for(const e of i)c[e]=a[e];return c.adopted={from:s,at:(new Date).toISOString(),names:i.slice().sort()},write({...n,...c},r),{adopted:!0,keys:i.slice().sort(),from:s}}module.exports={PREFS_FILE:PREFS_FILE,PREFS_VERSION:1,SHARED_PREF_KEYS:SHARED_PREF_KEYS,LEGACY_MEMORY_PERSIST_NAMESPACE:LEGACY_MEMORY_PERSIST_NAMESPACE,prefsDir:prefsDir,prefsFile:prefsFile,load:load,set:set,get:get,has:has,remove:remove,scanForSecrets:scanForSecrets,assertNoSecrets:assertNoSecrets,extractNonSecretHalf:extractNonSecretHalf,adopt:adopt};
3
+ "use strict";const fs=require("node:fs"),path=require("node:path"),{aegisHome:aegisHome}=require("./credentials.js"),PREFS_FILE="preferences.json",PREFS_VERSION=1,SHARED_PREF_KEYS=Object.freeze(["themeIndex","model","modelClass","currentModelId","models","modelAutoSync","effort","vim","memoryPersist","confirmMode","permissionMode","sandboxPolicy","devMode","speech","accountUsername"]),LEGACY_MEMORY_PERSIST_NAMESPACE="__memoryPersist",LEGACY_CONFIRM_MODE_NAMESPACE="__confirmMode",SECRET_KEY_RE=/(^|[^a-z0-9])(api[_-]?key|apikey|key|keys|token|secret|password|passwd|credential|credentials|authorization|bearer|private[_-]?key|access[_-]?key|session[_-]?key)([^a-z0-9]|$)/i,SECRET_VALUE_RES=[/\baegis_[A-Za-z0-9_\-]{12,}/,/\bsk-[A-Za-z0-9_\-]{12,}/,/\bghp_[A-Za-z0-9_\-]{20,}/,/\bxox[baprs]-[A-Za-z0-9\-]{10,}/,/\beyJ[A-Za-z0-9_\-]{16,}\.[A-Za-z0-9_\-]{8,}/,/^[A-Za-z0-9+/]{48,}={0,2}$/];function prefsDir(e){const r=e||{};return r.dir&&String(r.dir).trim()?path.resolve(String(r.dir).trim()):aegisHome(r.env)}function prefsFile(e){const r=e||{};return r.file&&String(r.file).trim()?path.resolve(String(r.file).trim()):path.join(prefsDir(r),PREFS_FILE)}function scanForSecrets(e,r="",t=[]){if(null==e)return t;if("string"==typeof e)return SECRET_VALUE_RES.some(r=>r.test(e))&&t.push(r||"(root)"),t;if("object"!=typeof e)return t;if(Array.isArray(e))return e.forEach((e,o)=>scanForSecrets(e,`${r}[${o}]`,t)),t;for(const[o,s]of Object.entries(e)){const e=r?`${r}.${o}`:o;SECRET_KEY_RE.test(o)&&null!=s&&""!==s&&!1!==s?t.push(e):scanForSecrets(s,e,t)}return t}function assertNoSecrets(e,r="shared preference store"){const t=scanForSecrets(e);if(t.length)throw new Error(`${r} must not carry key material — refusing to write (found: ${t.join(", ")}). Secrets belong in the host-local credential store, where the OS can protect them.`);return e}function readJson(e,r){try{const t=JSON.parse(fs.readFileSync(e,"utf8"));return t&&"object"==typeof t&&!Array.isArray(t)?t:r}catch{return r}}function load(e){return readJson(prefsFile(e),{})}function write(e,r){assertNoSecrets(e);const t=prefsFile(r);fs.mkdirSync(path.dirname(t),{recursive:!0});const o=`${t}.tmp-${process.pid}`;fs.writeFileSync(o,JSON.stringify(e,null,2)+"\n",{mode:384}),fs.renameSync(o,t);try{fs.chmodSync(t,384)}catch{}return e}function set(e,r){const t={...load(r),...e||{}};for(const e of Object.keys(t))void 0===t[e]&&delete t[e];return void 0===t.version&&(t.version=1),write(t,r)}function get(e,r,t){const o=load(r)[e];return void 0===o?t:o}function has(e,r){return void 0!==load(r)[e]}function remove(e,r){const t=load(r);return delete t[e],write(t,r)}function extractNonSecretHalf(e){const r={},t=(e||{}).__memoryPersist;t&&"object"==typeof t&&"boolean"==typeof t.enabled&&(r.memoryPersist=t.enabled);const o=(e||{}).__confirmMode;return o&&"object"==typeof o&&"boolean"==typeof o.enabled&&(r.confirmMode=o.enabled),r}function adopt(e){const r=e||{},t=prefsFile(r),o=r.legacyDir,s=o?path.join(String(o),"settings.json"):null;if(s&&path.resolve(s)===t)return{adopted:!1,keys:[],from:s,reason:"shared store is the legacy file"};if(!s||!fs.existsSync(s))return{adopted:!1,keys:[],from:s,reason:"no legacy settings file"};const n=load(r),i=extractNonSecretHalf(readJson(s,{})),a=Object.keys(i).filter(e=>void 0===n[e]);if(!a.length)return{adopted:!1,keys:[],from:s,reason:Object.keys(i).length?"shared store already carries these preferences":"legacy store has no shared preferences"};const c={};for(const e of a)c[e]=i[e];return c.adopted={from:s,at:(new Date).toISOString(),names:a.slice().sort()},write({...n,...c},r),{adopted:!0,keys:a.slice().sort(),from:s}}module.exports={PREFS_FILE:PREFS_FILE,PREFS_VERSION:1,SHARED_PREF_KEYS:SHARED_PREF_KEYS,LEGACY_MEMORY_PERSIST_NAMESPACE:"__memoryPersist",prefsDir:prefsDir,prefsFile:prefsFile,load:load,set:set,get:get,has:has,remove:remove,scanForSecrets:scanForSecrets,assertNoSecrets:assertNoSecrets,extractNonSecretHalf:extractNonSecretHalf,adopt:adopt};
@@ -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};