aegisone 1.0.64 → 1.0.66

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (374) hide show
  1. package/README.md +1 -1
  2. package/bin/aegis.js +1 -1
  3. package/package.json +1 -1
  4. package/scripts/bump.mjs +1 -1
  5. package/scripts/bundle.js +1 -1
  6. package/scripts/postinstall.mjs +1 -1
  7. package/scripts/predist.mjs +1 -1
  8. package/src/child.js +1 -1
  9. package/src/dispatch.js +1 -1
  10. package/src/doctor.js +1 -1
  11. package/src/probes.js +1 -1
  12. package/src/productupdate.js +1 -1
  13. package/src/protocol.js +1 -1
  14. package/src/release.js +1 -1
  15. package/src/selfhost.js +1 -1
  16. package/vendor/cli/bin/aegiscode.js +47 -5
  17. package/vendor/cli/package.json +1 -1
  18. package/vendor/cli/scripts/check.mjs +1 -1
  19. package/vendor/cli/scripts/demo.mjs +1 -1
  20. package/vendor/cli/scripts/postinstall.mjs +1 -1
  21. package/vendor/cli/scripts/predist.mjs +1 -1
  22. package/vendor/cli/scripts/runtests.mjs +1 -1
  23. package/vendor/cli/src/app.js +1 -1
  24. package/vendor/cli/src/art.js +1 -1
  25. package/vendor/cli/src/autonomous.js +574 -10
  26. package/vendor/cli/src/chatflow.js +1 -1
  27. package/vendor/cli/src/checkpoint.js +1 -1
  28. package/vendor/cli/src/clipboard.js +1 -1
  29. package/vendor/cli/src/cloudsync.js +1 -1
  30. package/vendor/cli/src/commands.js +2 -2
  31. package/vendor/cli/src/config.js +1 -1
  32. package/vendor/cli/src/connect.js +1 -1
  33. package/vendor/cli/src/devrun.js +1 -1
  34. package/vendor/cli/src/diff.js +1 -1
  35. package/vendor/cli/src/diffview.js +1 -1
  36. package/vendor/cli/src/dream-cmd.js +3 -0
  37. package/vendor/cli/src/dream.js +1 -1
  38. package/vendor/cli/src/engine.js +1 -1
  39. package/vendor/cli/src/events.js +1 -1
  40. package/vendor/cli/src/export.js +1 -1
  41. package/vendor/cli/src/fingerprint.js +1 -1
  42. package/vendor/cli/src/format.js +1 -1
  43. package/vendor/cli/src/fuzzy.js +1 -1
  44. package/vendor/cli/src/history.js +1 -1
  45. package/vendor/cli/src/init.js +1 -1
  46. package/vendor/cli/src/limits.js +1 -1
  47. package/vendor/cli/src/markdown.js +1 -1
  48. package/vendor/cli/src/models.js +1 -1
  49. package/vendor/cli/src/overlays.js +1 -1
  50. package/vendor/cli/src/panels.js +1 -1
  51. package/vendor/cli/src/ping.js +1 -1
  52. package/vendor/cli/src/presence.js +1 -1
  53. package/vendor/cli/src/provenance.lock.json +3 -3
  54. package/vendor/cli/src/render.js +1 -1
  55. package/vendor/cli/src/screen.js +1 -1
  56. package/vendor/cli/src/screens.js +1 -1
  57. package/vendor/cli/src/secret.js +1 -1
  58. package/vendor/cli/src/securefs.js +1 -1
  59. package/vendor/cli/src/settings.js +1 -1
  60. package/vendor/cli/src/signup.js +1 -1
  61. package/vendor/cli/src/summarize.js +1 -1
  62. package/vendor/cli/src/sysdiag.js +1 -1
  63. package/vendor/cli/src/theme.js +1 -1
  64. package/vendor/cli/src/title.js +1 -1
  65. package/vendor/cli/src/todos.js +1 -1
  66. package/vendor/cli/src/tokens.js +1 -1
  67. package/vendor/cli/src/topup.js +1 -1
  68. package/vendor/cli/src/update.js +1 -1
  69. package/vendor/cli/vendor/client/aegis.js +1 -1
  70. package/vendor/cli/vendor/client/attest.js +1 -1
  71. package/vendor/cli/vendor/client/authorship-key.js +1 -1
  72. package/vendor/cli/vendor/client/auto-provision.js +1 -1
  73. package/vendor/cli/vendor/client/brain-catalog.js +1 -1
  74. package/vendor/cli/vendor/client/byok-catalog.js +1 -1
  75. package/vendor/cli/vendor/client/catalog-client.js +1 -1
  76. package/vendor/cli/vendor/client/conversation-export.js +1 -1
  77. package/vendor/cli/vendor/client/credentials.js +1 -1
  78. package/vendor/cli/vendor/client/credits.js +1 -1
  79. package/vendor/cli/vendor/client/drive-connect.js +1 -1
  80. package/vendor/cli/vendor/client/env-file.js +1 -1
  81. package/vendor/cli/vendor/client/fingerprint.js +1 -1
  82. package/vendor/cli/vendor/client/foreign-memory.js +1 -1
  83. package/vendor/cli/vendor/client/foreign-sessions.js +1 -1
  84. package/vendor/cli/vendor/client/google-signin.js +1 -1
  85. package/vendor/cli/vendor/client/hooks.js +1 -1
  86. package/vendor/cli/vendor/client/model-discovery.js +1 -1
  87. package/vendor/cli/vendor/client/model-sync.js +1 -1
  88. package/vendor/cli/vendor/client/naming.js +1 -1
  89. package/vendor/cli/vendor/client/platform.js +1 -1
  90. package/vendor/cli/vendor/client/prefs.js +1 -1
  91. package/vendor/cli/vendor/client/presence.js +1 -1
  92. package/vendor/cli/vendor/client/record-vault.js +2 -2
  93. package/vendor/cli/vendor/client/session-search.js +1 -1
  94. package/vendor/cli/vendor/client/session-store.js +1 -1
  95. package/vendor/cli/vendor/client/skills.js +1 -1
  96. package/vendor/cli/vendor/client/topup.js +1 -1
  97. package/vendor/cli/vendor/client/touch.js +1 -1
  98. package/vendor/cli/vendor/client/update.js +1 -1
  99. package/vendor/cli/vendor/client/user-models.js +1 -1
  100. package/vendor/cli/vendor/desktop/lib/local/attachments.js +1 -1
  101. package/vendor/cli/vendor/desktop/lib/local/autonomous.js +1 -1
  102. package/vendor/cli/vendor/desktop/lib/local/claude-pro.js +1 -1
  103. package/vendor/cli/vendor/desktop/lib/local/context.js +1 -1
  104. package/vendor/cli/vendor/desktop/lib/local/engine.js +1 -1
  105. package/vendor/cli/vendor/desktop/lib/local/entitlement.js +1 -1
  106. package/vendor/cli/vendor/desktop/lib/local/integrity.js +1 -1
  107. package/vendor/cli/vendor/desktop/lib/local/local.js +1 -1
  108. package/vendor/cli/vendor/desktop/lib/local/perm-rules.js +5 -0
  109. package/vendor/cli/vendor/desktop/lib/local/perm-store.js +5 -0
  110. package/vendor/cli/vendor/desktop/lib/local/perm-write.js +5 -0
  111. package/vendor/cli/vendor/desktop/lib/local/pro-sessions.js +3 -1
  112. package/vendor/cli/vendor/desktop/lib/local/prompt.js +1 -1
  113. package/vendor/cli/vendor/desktop/lib/local/queue.js +1 -1
  114. package/vendor/cli/vendor/desktop/lib/local/repeat-guard.js +1 -1
  115. package/vendor/cli/vendor/desktop/lib/local/session-rounds.js +1 -1
  116. package/vendor/cli/vendor/desktop/lib/local/spill.js +1 -1
  117. package/vendor/cli/vendor/desktop/lib/local/turn-guard.js +1 -1
  118. package/vendor/cli/vendor/desktop/lib/local/verify-stop.js +1 -1
  119. package/vendor/cli/vendor/desktop/lib/local/worktree-lock.js +1 -1
  120. package/vendor/cli/vendor/desktop/lib/settings.js +1 -1
  121. package/vendor/cli/vendor/desktop/main.js +82 -1
  122. package/vendor/cli/vendor/desktop/renderer/usage.js +1 -1
  123. package/vendor/cli/vendor/hosts/install.js +1 -1
  124. package/vendor/cli/vendor/hosts/openai-shim.js +1 -1
  125. package/vendor/cli/vendor/hosts/spec.js +1 -1
  126. package/vendor/cli/vendor/hosts/targets.js +1 -1
  127. package/vendor/cli/vendor/mcp/admission.js +1 -1
  128. package/vendor/cli/vendor/mcp/server.js +1 -1
  129. package/vendor/cli/vendor/mcp/tools.js +1 -1
  130. package/vendor/cli/vendor/one/src/child.js +1 -1
  131. package/vendor/cli/vendor/one/src/protocol.js +1 -1
  132. package/vendor/cli/vendor/one/src/selfhost.js +1 -1
  133. package/vendor/desktop/bin/aegis.js +1 -1
  134. package/vendor/desktop/lib/auto.js +1 -1
  135. package/vendor/desktop/lib/avatar/companion.js +1 -1
  136. package/vendor/desktop/lib/avatar/cosmetics.js +1 -1
  137. package/vendor/desktop/lib/avatar/holder-turn.js +1 -1
  138. package/vendor/desktop/lib/avatar/holders.js +1 -1
  139. package/vendor/desktop/lib/avatar/identity.js +1 -1
  140. package/vendor/desktop/lib/avatar/level.js +1 -1
  141. package/vendor/desktop/lib/avatar/mirror.js +1 -1
  142. package/vendor/desktop/lib/avatar/persona.js +1 -1
  143. package/vendor/desktop/lib/avatar/profile.js +1 -1
  144. package/vendor/desktop/lib/avatar/register.js +1 -1
  145. package/vendor/desktop/lib/avatar/store.js +1 -1
  146. package/vendor/desktop/lib/avatar/transfer.js +1 -1
  147. package/vendor/desktop/lib/avatar/turn.js +1 -1
  148. package/vendor/desktop/lib/avatar/voice.js +1 -1
  149. package/vendor/desktop/lib/avatar/xp.js +1 -1
  150. package/vendor/desktop/lib/deep-link.js +1 -1
  151. package/vendor/desktop/lib/local/attachments.js +1 -1
  152. package/vendor/desktop/lib/local/autonomous.js +1 -1
  153. package/vendor/desktop/lib/local/claude-pro.js +1 -1
  154. package/vendor/desktop/lib/local/cli-face.js +1 -1
  155. package/vendor/desktop/lib/local/context.js +1 -1
  156. package/vendor/desktop/lib/local/engine.js +1 -1
  157. package/vendor/desktop/lib/local/entitlement.js +1 -1
  158. package/vendor/desktop/lib/local/integrity.js +1 -1
  159. package/vendor/desktop/lib/local/local.js +1 -1
  160. package/vendor/desktop/lib/local/perm-rules.js +5 -0
  161. package/vendor/desktop/lib/local/perm-store.js +5 -0
  162. package/vendor/desktop/lib/local/perm-write.js +5 -0
  163. package/vendor/desktop/lib/local/pro-sessions.js +3 -1
  164. package/vendor/desktop/lib/local/prompt.js +1 -1
  165. package/vendor/desktop/lib/local/pty-host.js +1 -1
  166. package/vendor/desktop/lib/local/queue.js +1 -1
  167. package/vendor/desktop/lib/local/repeat-guard.js +1 -1
  168. package/vendor/desktop/lib/local/session-rounds.js +1 -1
  169. package/vendor/desktop/lib/local/spill.js +1 -1
  170. package/vendor/desktop/lib/local/telemetry.js +1 -1
  171. package/vendor/desktop/lib/local/turn-guard.js +1 -1
  172. package/vendor/desktop/lib/local/verify-stop.js +1 -1
  173. package/vendor/desktop/lib/local/worktree-lock.js +1 -1
  174. package/vendor/desktop/lib/provider-key-mirror.js +1 -1
  175. package/vendor/desktop/lib/quick-launcher.js +1 -1
  176. package/vendor/desktop/lib/settings.js +1 -1
  177. package/vendor/desktop/lib/skills-host.js +1 -1
  178. package/vendor/desktop/lib/speech-host.js +1 -1
  179. package/vendor/desktop/lib/sync/memory-store.js +1 -1
  180. package/vendor/desktop/lib/sync/persist-gate.js +1 -1
  181. package/vendor/desktop/lib/window-state.js +1 -1
  182. package/vendor/desktop/main.js +82 -1
  183. package/vendor/desktop/package.json +1 -1
  184. package/vendor/desktop/preload.js +3 -1
  185. package/vendor/desktop/renderer/app.js +3 -3
  186. package/vendor/desktop/renderer/avatar/assemble.js +1 -1
  187. package/vendor/desktop/renderer/avatar/avatar.js +1 -1
  188. package/vendor/desktop/renderer/avatar/cards.js +1 -1
  189. package/vendor/desktop/renderer/avatar/hud.js +1 -1
  190. package/vendor/desktop/renderer/avatar/pane.js +1 -1
  191. package/vendor/desktop/renderer/avatar/parts.js +1 -1
  192. package/vendor/desktop/renderer/commands.js +1 -1
  193. package/vendor/desktop/renderer/companion.js +1 -1
  194. package/vendor/desktop/renderer/composer-triggers.js +1 -1
  195. package/vendor/desktop/renderer/dictation.js +1 -1
  196. package/vendor/desktop/renderer/diff.js +1 -1
  197. package/vendor/desktop/renderer/diffview.js +1 -1
  198. package/vendor/desktop/renderer/fingerprint.js +2 -2
  199. package/vendor/desktop/renderer/index.html +10 -4
  200. package/vendor/desktop/renderer/library.js +1 -1
  201. package/vendor/desktop/renderer/markdown.js +1 -1
  202. package/vendor/desktop/renderer/palette-filter.js +1 -1
  203. package/vendor/desktop/renderer/provider-toolbar.js +1 -1
  204. package/vendor/desktop/renderer/providers.js +1 -1
  205. package/vendor/desktop/renderer/pty-frame.css +35 -0
  206. package/vendor/desktop/renderer/pty-frame.html +47 -0
  207. package/vendor/desktop/renderer/pty-panel.js +1 -1
  208. package/vendor/desktop/renderer/pty-window.html +72 -0
  209. package/vendor/desktop/renderer/pty-window.js +3 -0
  210. package/vendor/desktop/renderer/quick.js +1 -1
  211. package/vendor/desktop/renderer/settings-skills.js +1 -1
  212. package/vendor/desktop/renderer/shortcuts.js +1 -1
  213. package/vendor/desktop/renderer/stream-policy.js +1 -1
  214. package/vendor/desktop/renderer/style.css +77 -3
  215. package/vendor/desktop/renderer/transcript-view.js +1 -1
  216. package/vendor/desktop/renderer/usage.js +1 -1
  217. package/vendor/desktop/renderer/welcome-rows.js +1 -1
  218. package/vendor/desktop/vendor/aegis.js +1 -1
  219. package/vendor/desktop/vendor/attest.js +1 -1
  220. package/vendor/desktop/vendor/authorship-key.js +1 -1
  221. package/vendor/desktop/vendor/auto-provision.js +1 -1
  222. package/vendor/desktop/vendor/brain-catalog.js +1 -1
  223. package/vendor/desktop/vendor/byok-catalog.js +1 -1
  224. package/vendor/desktop/vendor/catalog-client.js +1 -1
  225. package/vendor/desktop/vendor/conversation-export.js +1 -1
  226. package/vendor/desktop/vendor/credentials.js +1 -1
  227. package/vendor/desktop/vendor/credits.js +1 -1
  228. package/vendor/desktop/vendor/drive-connect.js +1 -1
  229. package/vendor/desktop/vendor/env-file.js +1 -1
  230. package/vendor/desktop/vendor/faces/cli/bin/aegiscode.js +2 -2
  231. package/vendor/desktop/vendor/faces/cli/package.json +1 -1
  232. package/vendor/desktop/vendor/faces/cli/scripts/check.mjs +1 -1
  233. package/vendor/desktop/vendor/faces/cli/scripts/demo.mjs +1 -1
  234. package/vendor/desktop/vendor/faces/cli/scripts/postinstall.mjs +1 -1
  235. package/vendor/desktop/vendor/faces/cli/scripts/predist.mjs +1 -1
  236. package/vendor/desktop/vendor/faces/cli/scripts/runtests.mjs +1 -1
  237. package/vendor/desktop/vendor/faces/cli/src/app.js +1 -1
  238. package/vendor/desktop/vendor/faces/cli/src/art.js +1 -1
  239. package/vendor/desktop/vendor/faces/cli/src/autonomous.js +1 -1
  240. package/vendor/desktop/vendor/faces/cli/src/caps.js +1 -1
  241. package/vendor/desktop/vendor/faces/cli/src/chatflow.js +1 -1
  242. package/vendor/desktop/vendor/faces/cli/src/checkpoint.js +1 -1
  243. package/vendor/desktop/vendor/faces/cli/src/clipboard.js +1 -1
  244. package/vendor/desktop/vendor/faces/cli/src/cloudsync.js +1 -1
  245. package/vendor/desktop/vendor/faces/cli/src/commands.js +2 -2
  246. package/vendor/desktop/vendor/faces/cli/src/config.js +1 -1
  247. package/vendor/desktop/vendor/faces/cli/src/connect.js +1 -1
  248. package/vendor/desktop/vendor/faces/cli/src/devrun.js +1 -1
  249. package/vendor/desktop/vendor/faces/cli/src/diff.js +1 -1
  250. package/vendor/desktop/vendor/faces/cli/src/diffview.js +1 -1
  251. package/vendor/desktop/vendor/faces/cli/src/dream-cmd.js +3 -0
  252. package/vendor/desktop/vendor/faces/cli/src/dream.js +1 -1
  253. package/vendor/desktop/vendor/faces/cli/src/engine.js +1 -1
  254. package/vendor/desktop/vendor/faces/cli/src/events.js +1 -1
  255. package/vendor/desktop/vendor/faces/cli/src/export.js +1 -1
  256. package/vendor/desktop/vendor/faces/cli/src/fingerprint.js +1 -1
  257. package/vendor/desktop/vendor/faces/cli/src/format.js +1 -1
  258. package/vendor/desktop/vendor/faces/cli/src/fuzzy.js +1 -1
  259. package/vendor/desktop/vendor/faces/cli/src/history.js +1 -1
  260. package/vendor/desktop/vendor/faces/cli/src/init.js +1 -1
  261. package/vendor/desktop/vendor/faces/cli/src/limits.js +1 -1
  262. package/vendor/desktop/vendor/faces/cli/src/markdown.js +1 -1
  263. package/vendor/desktop/vendor/faces/cli/src/mcp.js +1 -1
  264. package/vendor/desktop/vendor/faces/cli/src/models.js +1 -1
  265. package/vendor/desktop/vendor/faces/cli/src/overlays.js +1 -1
  266. package/vendor/desktop/vendor/faces/cli/src/panels.js +1 -1
  267. package/vendor/desktop/vendor/faces/cli/src/permissions.js +1 -1
  268. package/vendor/desktop/vendor/faces/cli/src/ping.js +1 -1
  269. package/vendor/desktop/vendor/faces/cli/src/presence.js +1 -1
  270. package/vendor/desktop/vendor/faces/cli/src/provenance.js +1 -1
  271. package/vendor/desktop/vendor/faces/cli/src/provenance.lock.json +3 -3
  272. package/vendor/desktop/vendor/faces/cli/src/render.js +1 -1
  273. package/vendor/desktop/vendor/faces/cli/src/screen.js +1 -1
  274. package/vendor/desktop/vendor/faces/cli/src/screens.js +1 -1
  275. package/vendor/desktop/vendor/faces/cli/src/secret.js +1 -1
  276. package/vendor/desktop/vendor/faces/cli/src/securefs.js +1 -1
  277. package/vendor/desktop/vendor/faces/cli/src/settings.js +1 -1
  278. package/vendor/desktop/vendor/faces/cli/src/signup.js +1 -1
  279. package/vendor/desktop/vendor/faces/cli/src/summarize.js +1 -1
  280. package/vendor/desktop/vendor/faces/cli/src/sysdiag.js +1 -1
  281. package/vendor/desktop/vendor/faces/cli/src/theme.js +1 -1
  282. package/vendor/desktop/vendor/faces/cli/src/title.js +1 -1
  283. package/vendor/desktop/vendor/faces/cli/src/todos.js +1 -1
  284. package/vendor/desktop/vendor/faces/cli/src/tokens.js +1 -1
  285. package/vendor/desktop/vendor/faces/cli/src/topup.js +1 -1
  286. package/vendor/desktop/vendor/faces/cli/src/update.js +1 -1
  287. package/vendor/desktop/vendor/faces/cli/vendor/client/aegis.js +1 -1
  288. package/vendor/desktop/vendor/faces/cli/vendor/client/attest.js +1 -1
  289. package/vendor/desktop/vendor/faces/cli/vendor/client/authorship-key.js +1 -1
  290. package/vendor/desktop/vendor/faces/cli/vendor/client/auto-provision.js +1 -1
  291. package/vendor/desktop/vendor/faces/cli/vendor/client/brain-catalog.js +1 -1
  292. package/vendor/desktop/vendor/faces/cli/vendor/client/byok-catalog.js +1 -1
  293. package/vendor/desktop/vendor/faces/cli/vendor/client/catalog-client.js +1 -1
  294. package/vendor/desktop/vendor/faces/cli/vendor/client/conversation-export.js +1 -1
  295. package/vendor/desktop/vendor/faces/cli/vendor/client/credentials.js +1 -1
  296. package/vendor/desktop/vendor/faces/cli/vendor/client/credits.js +1 -1
  297. package/vendor/desktop/vendor/faces/cli/vendor/client/drive-connect.js +1 -1
  298. package/vendor/desktop/vendor/faces/cli/vendor/client/env-file.js +1 -1
  299. package/vendor/desktop/vendor/faces/cli/vendor/client/fingerprint.js +1 -1
  300. package/vendor/desktop/vendor/faces/cli/vendor/client/foreign-memory.js +1 -1
  301. package/vendor/desktop/vendor/faces/cli/vendor/client/foreign-sessions.js +1 -1
  302. package/vendor/desktop/vendor/faces/cli/vendor/client/google-signin.js +1 -1
  303. package/vendor/desktop/vendor/faces/cli/vendor/client/hooks.js +1 -1
  304. package/vendor/desktop/vendor/faces/cli/vendor/client/model-discovery.js +1 -1
  305. package/vendor/desktop/vendor/faces/cli/vendor/client/model-sync.js +1 -1
  306. package/vendor/desktop/vendor/faces/cli/vendor/client/naming.js +1 -1
  307. package/vendor/desktop/vendor/faces/cli/vendor/client/platform.js +1 -1
  308. package/vendor/desktop/vendor/faces/cli/vendor/client/prefs.js +1 -1
  309. package/vendor/desktop/vendor/faces/cli/vendor/client/presence.js +1 -1
  310. package/vendor/desktop/vendor/faces/cli/vendor/client/record-vault.js +2 -2
  311. package/vendor/desktop/vendor/faces/cli/vendor/client/session-search.js +1 -1
  312. package/vendor/desktop/vendor/faces/cli/vendor/client/session-store.js +1 -1
  313. package/vendor/desktop/vendor/faces/cli/vendor/client/skills.js +1 -1
  314. package/vendor/desktop/vendor/faces/cli/vendor/client/topup.js +1 -1
  315. package/vendor/desktop/vendor/faces/cli/vendor/client/touch.js +1 -1
  316. package/vendor/desktop/vendor/faces/cli/vendor/client/update.js +1 -1
  317. package/vendor/desktop/vendor/faces/cli/vendor/client/user-models.js +1 -1
  318. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/attachments.js +1 -1
  319. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/autonomous.js +1 -1
  320. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/claude-pro.js +1 -1
  321. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/context.js +1 -1
  322. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/engine.js +1 -1
  323. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/entitlement.js +1 -1
  324. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/exec-plan.js +1 -1
  325. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/integrity.js +1 -1
  326. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/local.js +1 -1
  327. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/perm-rules.js +2 -0
  328. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/perm-store.js +3 -1
  329. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/perm-write.js +2 -0
  330. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/pro-sessions.js +3 -1
  331. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/prompt.js +1 -1
  332. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/queue.js +1 -1
  333. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/repeat-guard.js +1 -1
  334. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/session-rounds.js +1 -1
  335. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/shell.js +1 -1
  336. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/spill.js +1 -1
  337. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/tools.js +1 -1
  338. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/turn-guard.js +1 -1
  339. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/verify-stop.js +1 -1
  340. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/worktree-lock.js +1 -1
  341. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/settings.js +1 -1
  342. package/vendor/desktop/vendor/faces/cli/vendor/desktop/main.js +3 -3
  343. package/vendor/desktop/vendor/faces/cli/vendor/desktop/renderer/usage.js +1 -1
  344. package/vendor/desktop/vendor/faces/cli/vendor/hosts/install.js +1 -1
  345. package/vendor/desktop/vendor/faces/cli/vendor/hosts/openai-shim.js +1 -1
  346. package/vendor/desktop/vendor/faces/cli/vendor/hosts/spec.js +1 -1
  347. package/vendor/desktop/vendor/faces/cli/vendor/hosts/targets.js +1 -1
  348. package/vendor/desktop/vendor/faces/cli/vendor/mcp/admission.js +1 -1
  349. package/vendor/desktop/vendor/faces/cli/vendor/mcp/server.js +1 -1
  350. package/vendor/desktop/vendor/faces/cli/vendor/mcp/tools.js +1 -1
  351. package/vendor/desktop/vendor/faces/cli/vendor/one/src/child.js +1 -1
  352. package/vendor/desktop/vendor/faces/cli/vendor/one/src/protocol.js +1 -1
  353. package/vendor/desktop/vendor/faces/cli/vendor/one/src/selfhost.js +1 -1
  354. package/vendor/desktop/vendor/fingerprint.js +1 -1
  355. package/vendor/desktop/vendor/foreign-memory.js +1 -1
  356. package/vendor/desktop/vendor/foreign-sessions.js +1 -1
  357. package/vendor/desktop/vendor/google-signin.js +1 -1
  358. package/vendor/desktop/vendor/hooks.js +1 -1
  359. package/vendor/desktop/vendor/model-discovery.js +1 -1
  360. package/vendor/desktop/vendor/model-sync.js +1 -1
  361. package/vendor/desktop/vendor/naming.js +1 -1
  362. package/vendor/desktop/vendor/platform.js +1 -1
  363. package/vendor/desktop/vendor/prefs.js +1 -1
  364. package/vendor/desktop/vendor/presence.js +1 -1
  365. package/vendor/desktop/vendor/protocol.js +1 -1
  366. package/vendor/desktop/vendor/record-vault.js +2 -2
  367. package/vendor/desktop/vendor/selfhost.js +1 -1
  368. package/vendor/desktop/vendor/session-search.js +1 -1
  369. package/vendor/desktop/vendor/session-store.js +1 -1
  370. package/vendor/desktop/vendor/skills.js +1 -1
  371. package/vendor/desktop/vendor/topup.js +1 -1
  372. package/vendor/desktop/vendor/touch.js +1 -1
  373. package/vendor/desktop/vendor/update.js +1 -1
  374. package/vendor/desktop/vendor/user-models.js +1 -1
@@ -1,3 +1,3 @@
1
1
  // SPDX-License-Identifier: AGPL-3.0-or-later
2
2
  // Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
3
- "use strict";const fs=require("node:fs"),os=require("node:os"),path=require("node:path");let envFileLib=null;try{envFileLib=require("../../../client/env-file.js")}catch{try{envFileLib=require("../../vendor/env-file.js")}catch{envFileLib=null}}function claudeConfigDir(e){const n=e||process.env,t=n&&n.CLAUDE_CONFIG_DIR;return t&&String(t).trim()?String(t).trim():path.join(os.homedir(),".claude")}function claudeOAuthToken(e){return envFileLib?envFileLib.resolveForeignSecret("CLAUDE_CODE_OAUTH_TOKEN",{env:e}):""}const SHADOWING_ENV_VARS=Object.freeze(["ANTHROPIC_API_KEY","ANTHROPIC_AUTH_TOKEN"]);function isAnthropicConsoleKey(e){return"string"==typeof e&&/^sk-ant-[A-Za-z0-9_-]{8,}$/.test(e.trim())}function childEnvPlan(e,n,t){const s={...e||{}},o=[],i=envFileLib&&"function"==typeof envFileLib.credentialLooksUsable?envFileLib.credentialLooksUsable:null,r=!(!t||!t.hasSubscription);if(i)for(const e of SHADOWING_ENV_VARS){const n=s[e];if("string"!=typeof n)continue;let t=null;if(i(n)?r&&"ANTHROPIC_API_KEY"===e&&!isAnthropicConsoleKey(n)&&(t="not-a-console-key"):t="too-short",!t)continue;delete s[e];const a=n.trim().length;a>0&&o.push({name:e,length:a,reason:t})}return n&&(s.CLAUDE_CODE_OAUTH_TOKEN=n),{env:s,dropped:o}}function envDroppedLine(e){const n=Array.isArray(e)?e:[];if(!n.length)return null;const t=n.filter((e=>e&&"not-a-console-key"===e.reason)),s=n.filter((e=>!e||"not-a-console-key"!==e.reason)),o=[];if(s.length){const e=s.map((e=>`${e.name} (${e.length} character${1===e.length?"":"s"})`)).join(", ");o.push(`${e}: too short to be a credential, and the CLI would have spent it instead of your subscription`)}if(t.length){const e=t.map((e=>`${e.name} (${e.length} characters)`)).join(", ");o.push(`${e}: not an Anthropic console key (\`sk-ant-\`), and the CLI would have spent it instead of your subscription`)}return`aegis: not passed to the claude child — ${o.join("; ")}`}function shadowingValue(e,n){const t=e||{},s=envFileLib&&"function"==typeof envFileLib.credentialLooksUsable?envFileLib.credentialLooksUsable:null;if(!s)return null;const o=!(!n||!n.hasSubscription);for(const e of SHADOWING_ENV_VARS){const n=t[e];if("string"!=typeof n)continue;let i=null;if(s(n)?o&&"ANTHROPIC_API_KEY"===e&&!isAnthropicConsoleKey(n)&&(i="not-a-console-key"):i="too-short",i)return{name:e,length:n.trim().length,reason:i}}return null}function claudeProStatus(e){const n=e||{},t=n.env||process.env,s=path.join(n.dir||claudeConfigDir(t),".credentials.json"),o={claude:n.claudeVersion||null,file:s,exists:!1,kind:null,subscription:null,expiresAt:0,loggedIn:!1};let i;try{i=JSON.parse(fs.readFileSync(s,"utf8")),o.exists=!0}catch{i=null}const r=i&&i.claudeAiOauth;r&&(r.accessToken||r.refreshToken)?(o.kind="oauth",o.subscription=r.subscriptionType||null,o.expiresAt=Number(r.refreshTokenExpiresAt)||0,o.loggedIn=!0):i&&"string"==typeof i.token&&i.token?(o.kind="apikey",o.loggedIn=!0):claudeOAuthToken(t)&&(o.kind="env-token",o.loggedIn=!0),o.subscriptionPresent=o.loggedIn&&"apikey"!==o.kind,o.shadowed=shadowingValue(t,{hasSubscription:o.subscriptionPresent});const a=childEnvPlan(t,null,{hasSubscription:o.subscriptionPresent});return o.credentialPresent=o.loggedIn||"string"==typeof a.env.ANTHROPIC_API_KEY||"string"==typeof a.env.ANTHROPIC_AUTH_TOKEN||"string"==typeof a.env.CLAUDE_CODE_OAUTH_TOKEN,o}const PRO_MODELS=Object.freeze([{id:"default",label:"Default (recommended)",note:"the CLI picks for the subscription"},{id:"sonnet",label:"Sonnet",note:"alias the CLI resolves · latest Sonnet"},{id:"opus",label:"Opus",note:"alias the CLI resolves · latest Opus"},{id:"opusplan",label:"Opus Plan",note:"alias the CLI resolves · plan with Opus, act on Sonnet"},{id:"haiku",label:"Haiku",note:"alias the CLI resolves · latest Haiku"},{id:"fable",label:"Fable",note:"alias the CLI resolves · needs usage credits"},{id:"claude-sonnet-5-5",label:"Claude Sonnet 5.5",note:"full name · Anthropic"},{id:"claude-sonnet-4-6",label:"Claude Sonnet 4.6",note:"full name · Anthropic"},{id:"claude-sonnet-4-5-20250929",label:"Claude Sonnet 4.5",note:"full name · Anthropic · dated snapshot"},{id:"claude-opus-5",label:"Claude Opus 5",note:"full name · Anthropic"},{id:"claude-opus-4-7",label:"Claude Opus 4.7",note:"full name · Anthropic"},{id:"claude-opus-4-6",label:"Claude Opus 4.6",note:"full name · Anthropic"},{id:"claude-opus-4-5-20251101",label:"Claude Opus 4.5",note:"full name · Anthropic · dated snapshot"}]);function turnArgs(e){const n=[],t=e||{};return t.system&&String(t.system).trim()&&n.push("--append-system-prompt",String(t.system)),n}function createStreamParser(e){const n=e||{},t=new Map;let s="",o="",i=0,r=null;const a=e=>[...t.values()].find((n=>"collecting"===n.phase&&n.index===e))||[...t.values()].find((e=>"collecting"===e.phase));return{line(e){let l;try{l=JSON.parse(e)}catch{return}if("control_request"===l.type&&l.request){const e=l.request;if("can_use_tool"!==e.subtype)return;return n.onAsk?void n.onAsk({requestId:l.request_id,toolName:e.tool_name,input:e.input||{},toolUseId:e.tool_use_id,displayName:e.display_name,description:e.description,suggestions:Array.isArray(e.permission_suggestions)?e.permission_suggestions:[]}):void(n.onAskUnavailable&&n.onAskUnavailable({requestId:l.request_id,request:e}))}if("stream_event"===l.type&&l.event){const e=l.event;if("content_block_start"===e.type&&e.content_block)"tool_use"===e.content_block.type&&t.set(e.content_block.id,{id:e.content_block.id,index:null==e.index?0:e.index,name:e.content_block.name,args:"",startedAt:Date.now(),phase:"collecting"});else if("content_block_delta"===e.type&&e.delta){if("text_delta"===e.delta.type){const t=(e.delta.text||"").replace(/\x00/g,"");s+=t,n.onText&&t&&n.onText(t)}else if("thinking_delta"===e.delta.type){const t=(e.delta.thinking||"").replace(/\x00/g,"");o+=t,n.onThinking&&t&&n.onThinking(t);const s=e.delta.estimated_tokens;"number"==typeof s&&s>0&&Number.isFinite(s)&&(i+=s,n.onThinkingProgress&&n.onThinkingProgress(s))}else if("input_json_delta"===e.delta.type){const n=a(null==e.index?0:e.index);n&&(n.args+=e.delta.partial_json||"")}}else if("content_block_stop"===e.type){const s=a(null==e.index?0:e.index);s&&(e=>{let s=e.args;try{s=e.args?JSON.parse(e.args):{}}catch{s={}}t.set(e.id,{...e,args:s,phase:"run"}),n.onTool&&n.onTool({id:e.id,name:e.name,args:s,phase:"run"})})(s)}}else if("user"===l.type&&l.message){const e=Array.isArray(l.message.content)?l.message.content:[];for(const s of e){if(!s||"tool_result"!==s.type||!s.tool_use_id)continue;const e=t.get(s.tool_use_id);if(!e)continue;const o=Math.max(0,Date.now()-(e.startedAt||Date.now()));n.onTool&&n.onTool({id:e.id,name:e.name,phase:"done",elapsed:o,error:!!s.is_error}),t.delete(s.tool_use_id)}}else"result"===l.type&&(r=l,n.onDone&&n.onDone({text:s||l.result||"",error:l.is_error?l.result||(Array.isArray(l.errors)?l.errors.find((e=>"string"==typeof e&&e.trim())):void 0)||"api error":void 0,usage:l.usage||null,costUsd:"number"==typeof l.total_cost_usd?l.total_cost_usd:void 0,durationMs:l.duration_ms,sessionId:l.session_id,thinking:o||"",thinkingTokens:i}))},get text(){return s},get thinking(){return o},get thinkingTokens(){return i},get resultLine(){return r}}}function loadSeam(e){const n=e||__dirname,t=[path.join(n,"..","..","..","one","src"),path.join(n,"..","..","vendor","one","src"),path.join(n,"..","..","..","..","one","src")],s=new Set(["aegisone","aegiscode"]),o=path.join(n,"..","..","..","..");try{const e=JSON.parse(fs.readFileSync(path.join(o,"package.json"),"utf8"));e&&s.has(e.name)&&t.push(path.join(o,"src"))}catch{}for(const e of t)try{const n=require(path.join(e,"child.js")),t=require(path.join(e,"permissions.js"));if("function"==typeof n.claudeArgv&&"function"==typeof t.resolvePosture)return{child:n,permissions:t}}catch{}throw new Error("aegis: the Claude child argv builder (one/src/child.js + one/src/permissions.js) is missing from this install — refusing to build a second argv, because a second argv is a second policy.")}function seamAvailable(e){try{return loadSeam(e),{ok:!0,error:null}}catch(e){return{ok:!1,error:e&&e.message||String(e)}}}function proMessage(e,n,t){const s={content:e||""},o="string"==typeof n?n:"";return o&&(s.reasoning_content=o),"number"==typeof t&&t>0&&Number.isFinite(t)&&(s.thinking_tokens=t),s}function runClaudePro(e,n){const t=e||{},s=n||{},o=s.seam||loadSeam(s.dir),i=s.spawn||require("node:child_process").spawn;let r=void 0===t.permissionMode||null===t.permissionMode?null:String(t.permissionMode);if(null===r)try{const e=o.permissions.storedPermissionFacts();r=e&&"string"==typeof e.permissionMode?e.permissionMode:null}catch{}const a=o.permissions.resolvePosture({rules:t.rules,gate:t.gate,interactive:!1,childKind:o.permissions.CHILD_KINDS.HEADLESS,permissionMode:r,env:t.env||process.env}),l=o.child.claudeArgv({posture:a,prompt:t.prompt,model:t.model||void 0,resumeSessionId:t.resumeSessionId,sessionId:t.sessionId,addDir:t.addDir,askBridge:"function"==typeof t.onAsk,extra:[...turnArgs(t),"--include-partial-messages","--verbose"]});return new Promise((e=>{if(t.signal&&t.signal.aborted)return void e({choices:[{message:{content:""},finish_reason:"stop"}],stopped:!0});const n=t.env||process.env,o=claudeOAuthToken(n);let r=!1;try{r=!!claudeProStatus({env:n}).subscriptionPresent}catch{}const a=childEnvPlan(n,o,{hasSubscription:r}),c=a.env,d=envDroppedLine(a.dropped);if(d&&t.onDelta)try{t.onDelta({delta:"",note:d})}catch{}let u;try{u=i(s.executable||"claude",l.argv,{cwd:t.cwd||process.cwd(),stdio:[l.record.askBridge?"pipe":"ignore","pipe","pipe"],env:c})}catch(n){return void e({choices:[{message:{content:""},finish_reason:"error"}],error:`claude: could not start the child (${n&&n.message||n})`,...a.dropped.length?{envDropped:a.dropped}:{}})}if(t.onSpawn)try{t.onSpawn(u,l.record)}catch{}let p=!1,h="",g="",m=null;const f=Number(t.idleTimeoutMs)||6e5,_=l.record.askBridge,v=e=>{if(!_||!u.stdin||u.stdin.destroyed)return!1;try{return u.stdin.write(`${JSON.stringify(e)}\n`),!0}catch{return!1}};_&&v({type:"user",message:{role:"user",content:[{type:"text",text:String(t.prompt||"")}]}});const y=(e,n,t)=>{v({type:"control_response",response:{subtype:"success",request_id:e,response:"session"===n||"once"===n||"always"===n?{behavior:"allow"}:{behavior:"deny",message:t||"AEGIS_USER_DENIED"}}})},k=n=>{if(!p){if(p=!0,m&&clearTimeout(m),t.signal&&t.signal.removeEventListener("abort",A),_&&u.stdin&&!u.stdin.destroyed)try{u.stdin.end()}catch{}e(a.dropped.length?{...n,envDropped:a.dropped}:n)}},A=()=>{try{u.kill("SIGTERM")}catch{}setTimeout((()=>{try{u.kill("SIGKILL")}catch{}}),1500)};t.signal&&t.signal.addEventListener("abort",A,{once:!0});const b=()=>{m&&clearTimeout(m),m=setTimeout((()=>{A(),k({choices:[{message:{content:""},finish_reason:"stop"}],error:`claude: the child went silent for ${Math.round(f/1e3)}s and was stopped`})}),f)};b();const S=createStreamParser({onText:e=>{b(),t.onDelta&&t.onDelta({delta:e})},onThinking:e=>{b(),t.onDelta&&t.onDelta({reasoning:e})},onThinkingProgress:e=>{b(),t.onDelta&&t.onDelta({thinkingTokens:e})},onTool:e=>{b(),t.onDelta&&t.onDelta({delta:"",tool:{name:e.name,args:e.args,ok:"done"===e.phase?!e.error:void 0,id:e.id,cwd:t.cwd,phase:e.phase}})},onAsk:e=>{b(),Promise.resolve().then((()=>t.onAsk(e))).then((n=>y(e.requestId,"session"===n||"once"===n||"always"===n?n:"deny","AEGIS_USER_DENIED")),(n=>{y(e.requestId,"deny",`AEGIS_USER_DENIED (${n&&n.message||String(n)})`)})).catch((()=>{}))},onAskUnavailable:e=>{y(e.requestId,"deny","AEGIS_NO_APPROVAL_CHANNEL")},onDone:e=>{e.error?k({choices:[{message:{content:e.text||""},finish_reason:"error"}],usage:e.usage||void 0,error:e.error,...l.record.resumeSessionId&&isStaleResumeError(e.error)?{resumeStale:!0,resumeSessionId:l.record.resumeSessionId}:{}}):k({choices:[{message:proMessage(e.text||"",e.thinking,e.thinkingTokens),finish_reason:"stop"}],usage:e.usage||void 0,costUsd:e.costUsd,durationMs:e.durationMs,sessionId:e.sessionId,childRecord:l.record})}});u.stdout.on("data",(e=>{b(),g+=e.toString("utf8");const n=g.split("\n");g=n.pop()||"";for(const e of n){const n=e.trim();n&&S.line(n)}})),_&&u.stdin&&u.stdin.on("error",(()=>{})),u.stderr.on("data",(e=>{b(),h.length<8192&&(h+=e.toString("utf8"))})),u.on("error",(e=>{k({choices:[{message:{content:""},finish_reason:"error"}],error:`claude: could not run the child (${e&&e.message||e}). Install it with \`npm i -g @anthropic-ai/claude-code\`, then sign in with \`claude auth login\`.`})})),u.on("close",(e=>{g.trim()&&S.line(g.trim()),k({choices:[{message:proMessage(S.text,S.thinking,S.thinkingTokens),finish_reason:"stop"}],usage:S.resultLine&&S.resultLine.usage||void 0,childRecord:l.record,error:S.text||0===e?void 0:`claude: the child exited with status ${e}${h.trim()?` — ${h.trim().split("\n").slice(-3).join(" ")}`:""}`})}))}))}function isStaleResumeError(e){return!!e&&/no conversation found with session id/i.test(String(e))}function childLine(e,n){if(!e)return"";try{return loadSeam(n).child.childRecordLine(e)}catch{const n=e.skipFlag||"no permission flag";return`aegis: claude child [${e.kind}] ${n}`}}module.exports={claudeConfigDir:claudeConfigDir,claudeOAuthToken:claudeOAuthToken,claudeProStatus:claudeProStatus,childEnvPlan:childEnvPlan,envDroppedLine:envDroppedLine,shadowingValue:shadowingValue,SHADOWING_ENV_VARS:SHADOWING_ENV_VARS,PRO_MODELS:PRO_MODELS,turnArgs:turnArgs,createStreamParser:createStreamParser,loadSeam:loadSeam,seamAvailable:seamAvailable,childLine:childLine,isStaleResumeError:isStaleResumeError,runClaudePro:runClaudePro};
3
+ "use strict";const fs=require("node:fs"),os=require("node:os"),path=require("node:path");let envFileLib=null;try{envFileLib=require("../../../client/env-file.js")}catch{try{envFileLib=require("../../vendor/env-file.js")}catch{envFileLib=null}}function claudeConfigDir(e){const n=e||process.env,t=n&&n.CLAUDE_CONFIG_DIR;return t&&String(t).trim()?String(t).trim():path.join(os.homedir(),".claude")}function claudeOAuthToken(e){return envFileLib?envFileLib.resolveForeignSecret("CLAUDE_CODE_OAUTH_TOKEN",{env:e}):""}const SHADOWING_ENV_VARS=Object.freeze(["ANTHROPIC_API_KEY","ANTHROPIC_AUTH_TOKEN"]);function isAnthropicConsoleKey(e){return"string"==typeof e&&/^sk-ant-[A-Za-z0-9_-]{8,}$/.test(e.trim())}function childEnvPlan(e,n,t){const s={...e||{}},o=[],i=envFileLib&&"function"==typeof envFileLib.credentialLooksUsable?envFileLib.credentialLooksUsable:null,r=!(!t||!t.hasSubscription);if(i)for(const e of SHADOWING_ENV_VARS){const n=s[e];if("string"!=typeof n)continue;let t=null;if(i(n)?r&&"ANTHROPIC_API_KEY"===e&&!isAnthropicConsoleKey(n)&&(t="not-a-console-key"):t="too-short",!t)continue;delete s[e];const a=n.trim().length;a>0&&o.push({name:e,length:a,reason:t})}return n&&(s.CLAUDE_CODE_OAUTH_TOKEN=n),{env:s,dropped:o}}function envDroppedLine(e){const n=Array.isArray(e)?e:[];if(!n.length)return null;const t=n.filter(e=>e&&"not-a-console-key"===e.reason),s=n.filter(e=>!e||"not-a-console-key"!==e.reason),o=[];if(s.length){const e=s.map(e=>`${e.name} (${e.length} character${1===e.length?"":"s"})`).join(", ");o.push(`${e}: too short to be a credential, and the CLI would have spent it instead of your subscription`)}if(t.length){const e=t.map(e=>`${e.name} (${e.length} characters)`).join(", ");o.push(`${e}: not an Anthropic console key (\`sk-ant-\`), and the CLI would have spent it instead of your subscription`)}return`aegis: not passed to the claude child — ${o.join("; ")}`}function shadowingValue(e,n){const t=e||{},s=envFileLib&&"function"==typeof envFileLib.credentialLooksUsable?envFileLib.credentialLooksUsable:null;if(!s)return null;const o=!(!n||!n.hasSubscription);for(const e of SHADOWING_ENV_VARS){const n=t[e];if("string"!=typeof n)continue;let i=null;if(s(n)?o&&"ANTHROPIC_API_KEY"===e&&!isAnthropicConsoleKey(n)&&(i="not-a-console-key"):i="too-short",i)return{name:e,length:n.trim().length,reason:i}}return null}function claudeProStatus(e){const n=e||{},t=n.env||process.env,s=path.join(n.dir||claudeConfigDir(t),".credentials.json"),o={claude:n.claudeVersion||null,file:s,exists:!1,kind:null,subscription:null,expiresAt:0,loggedIn:!1};let i;try{i=JSON.parse(fs.readFileSync(s,"utf8")),o.exists=!0}catch{i=null}const r=i&&i.claudeAiOauth;r&&(r.accessToken||r.refreshToken)?(o.kind="oauth",o.subscription=r.subscriptionType||null,o.expiresAt=Number(r.refreshTokenExpiresAt)||0,o.loggedIn=!0):i&&"string"==typeof i.token&&i.token?(o.kind="apikey",o.loggedIn=!0):claudeOAuthToken(t)&&(o.kind="env-token",o.loggedIn=!0),o.subscriptionPresent=o.loggedIn&&"apikey"!==o.kind,o.shadowed=shadowingValue(t,{hasSubscription:o.subscriptionPresent});const a=childEnvPlan(t,null,{hasSubscription:o.subscriptionPresent});return o.credentialPresent=o.loggedIn||"string"==typeof a.env.ANTHROPIC_API_KEY||"string"==typeof a.env.ANTHROPIC_AUTH_TOKEN||"string"==typeof a.env.CLAUDE_CODE_OAUTH_TOKEN,o}const PRO_MODELS=Object.freeze([{id:"default",label:"Default (recommended)",note:"the CLI picks for the subscription"},{id:"sonnet",label:"Sonnet",note:"alias the CLI resolves · latest Sonnet"},{id:"opus",label:"Opus",note:"alias the CLI resolves · latest Opus"},{id:"opusplan",label:"Opus Plan",note:"alias the CLI resolves · plan with Opus, act on Sonnet"},{id:"haiku",label:"Haiku",note:"alias the CLI resolves · latest Haiku"},{id:"fable",label:"Fable",note:"alias the CLI resolves · needs usage credits"},{id:"claude-sonnet-5-5",label:"Claude Sonnet 5.5",note:"full name · Anthropic"},{id:"claude-sonnet-4-6",label:"Claude Sonnet 4.6",note:"full name · Anthropic"},{id:"claude-sonnet-4-5-20250929",label:"Claude Sonnet 4.5",note:"full name · Anthropic · dated snapshot"},{id:"claude-opus-5",label:"Claude Opus 5",note:"full name · Anthropic"},{id:"claude-opus-4-7",label:"Claude Opus 4.7",note:"full name · Anthropic"},{id:"claude-opus-4-6",label:"Claude Opus 4.6",note:"full name · Anthropic"},{id:"claude-opus-4-5-20251101",label:"Claude Opus 4.5",note:"full name · Anthropic · dated snapshot"}]);function turnArgs(e){const n=[],t=e||{};return t.system&&String(t.system).trim()&&n.push("--append-system-prompt",String(t.system)),n}function createStreamParser(e){const n=e||{},t=new Map;let s="",o="",i=0,r=null;const a=e=>[...t.values()].find(n=>"collecting"===n.phase&&n.index===e)||[...t.values()].find(e=>"collecting"===e.phase);return{line(e){let l;try{l=JSON.parse(e)}catch{return}if("control_request"===l.type&&l.request){const e=l.request;if("can_use_tool"!==e.subtype)return;return n.onAsk?void n.onAsk({requestId:l.request_id,toolName:e.tool_name,input:e.input||{},toolUseId:e.tool_use_id,displayName:e.display_name,description:e.description,suggestions:Array.isArray(e.permission_suggestions)?e.permission_suggestions:[]}):void(n.onAskUnavailable&&n.onAskUnavailable({requestId:l.request_id,request:e}))}if("stream_event"===l.type&&l.event){const e=l.event;if("content_block_start"===e.type&&e.content_block)"tool_use"===e.content_block.type&&t.set(e.content_block.id,{id:e.content_block.id,index:null==e.index?0:e.index,name:e.content_block.name,args:"",startedAt:Date.now(),phase:"collecting"});else if("content_block_delta"===e.type&&e.delta){if("text_delta"===e.delta.type){const t=(e.delta.text||"").replace(/\x00/g,"");s+=t,n.onText&&t&&n.onText(t)}else if("thinking_delta"===e.delta.type){const t=(e.delta.thinking||"").replace(/\x00/g,"");o+=t,n.onThinking&&t&&n.onThinking(t);const s=e.delta.estimated_tokens;"number"==typeof s&&s>0&&Number.isFinite(s)&&(i+=s,n.onThinkingProgress&&n.onThinkingProgress(s))}else if("input_json_delta"===e.delta.type){const n=a(null==e.index?0:e.index);n&&(n.args+=e.delta.partial_json||"")}}else if("content_block_stop"===e.type){const s=a(null==e.index?0:e.index);s&&(e=>{let s=e.args;try{s=e.args?JSON.parse(e.args):{}}catch{s={}}t.set(e.id,{...e,args:s,phase:"run"}),n.onTool&&n.onTool({id:e.id,name:e.name,args:s,phase:"run"})})(s)}}else if("user"===l.type&&l.message){const e=Array.isArray(l.message.content)?l.message.content:[];for(const s of e){if(!s||"tool_result"!==s.type||!s.tool_use_id)continue;const e=t.get(s.tool_use_id);if(!e)continue;const o=Math.max(0,Date.now()-(e.startedAt||Date.now()));n.onTool&&n.onTool({id:e.id,name:e.name,phase:"done",elapsed:o,error:!!s.is_error}),t.delete(s.tool_use_id)}}else"result"===l.type&&(r=l,n.onDone&&n.onDone({text:s||l.result||"",error:l.is_error?l.result||(Array.isArray(l.errors)?l.errors.find(e=>"string"==typeof e&&e.trim()):void 0)||"api error":void 0,usage:l.usage||null,costUsd:"number"==typeof l.total_cost_usd?l.total_cost_usd:void 0,durationMs:l.duration_ms,sessionId:l.session_id,thinking:o||"",thinkingTokens:i}))},get text(){return s},get thinking(){return o},get thinkingTokens(){return i},get resultLine(){return r}}}function loadSeam(e){const n=e||__dirname,t=[path.join(n,"..","..","..","one","src"),path.join(n,"..","..","vendor","one","src"),path.join(n,"..","..","..","..","one","src")],s=new Set(["aegisone","aegiscode"]),o=path.join(n,"..","..","..","..");try{const e=JSON.parse(fs.readFileSync(path.join(o,"package.json"),"utf8"));e&&s.has(e.name)&&t.push(path.join(o,"src"))}catch{}for(const e of t)try{const n=require(path.join(e,"child.js")),t=require(path.join(e,"permissions.js"));if("function"==typeof n.claudeArgv&&"function"==typeof t.resolvePosture)return{child:n,permissions:t}}catch{}throw new Error("aegis: the Claude child argv builder (one/src/child.js + one/src/permissions.js) is missing from this install — refusing to build a second argv, because a second argv is a second policy.")}function seamAvailable(e){try{return loadSeam(e),{ok:!0,error:null}}catch(e){return{ok:!1,error:e&&e.message||String(e)}}}function proMessage(e,n,t){const s={content:e||""},o="string"==typeof n?n:"";return o&&(s.reasoning_content=o),"number"==typeof t&&t>0&&Number.isFinite(t)&&(s.thinking_tokens=t),s}function runClaudePro(e,n){const t=e||{},s=n||{},o=s.seam||loadSeam(s.dir),i=s.spawn||require("node:child_process").spawn;let r=void 0===t.permissionMode||null===t.permissionMode?null:String(t.permissionMode);if(null===r)try{const e=o.permissions.storedPermissionFacts();r=e&&"string"==typeof e.permissionMode?e.permissionMode:null}catch{}const a=o.permissions.resolvePosture({rules:t.rules,gate:t.gate,interactive:!1,childKind:o.permissions.CHILD_KINDS.HEADLESS,permissionMode:r,env:t.env||process.env}),l=o.child.claudeArgv({posture:a,prompt:t.prompt,model:t.model||void 0,resumeSessionId:t.resumeSessionId,sessionId:t.sessionId,addDir:t.addDir,askBridge:"function"==typeof t.onAsk,extra:[...turnArgs(t),"--include-partial-messages","--verbose"]});return new Promise(e=>{if(t.signal&&t.signal.aborted)return void e({choices:[{message:{content:""},finish_reason:"stop"}],stopped:!0});const n=t.env||process.env,o=claudeOAuthToken(n);let r=!1;try{r=!!claudeProStatus({env:n}).subscriptionPresent}catch{}const a=childEnvPlan(n,o,{hasSubscription:r}),c=a.env,d=envDroppedLine(a.dropped);if(d&&t.onDelta)try{t.onDelta({delta:"",note:d})}catch{}let u;try{u=i(s.executable||"claude",l.argv,{cwd:t.cwd||process.cwd(),stdio:[l.record.askBridge?"pipe":"ignore","pipe","pipe"],env:c})}catch(n){return void e({choices:[{message:{content:""},finish_reason:"error"}],error:`claude: could not start the child (${n&&n.message||n})`,...a.dropped.length?{envDropped:a.dropped}:{}})}if(t.onSpawn)try{t.onSpawn(u,l.record)}catch{}let p=!1,h="",g="",m=null;const f=Number(t.idleTimeoutMs)||6e5,_=l.record.askBridge,v=e=>{if(!_||!u.stdin||u.stdin.destroyed)return!1;try{return u.stdin.write(`${JSON.stringify(e)}\n`),!0}catch{return!1}};_&&v({type:"user",message:{role:"user",content:[{type:"text",text:String(t.prompt||"")}]}});const y=(e,n,t)=>{v({type:"control_response",response:{subtype:"success",request_id:e,response:"session"===n||"once"===n||"always"===n?{behavior:"allow"}:{behavior:"deny",message:t||"AEGIS_USER_DENIED"}}})},k=n=>{if(!p){if(p=!0,m&&clearTimeout(m),t.signal&&t.signal.removeEventListener("abort",A),_&&u.stdin&&!u.stdin.destroyed)try{u.stdin.end()}catch{}e(a.dropped.length?{...n,envDropped:a.dropped}:n)}},A=()=>{try{u.kill("SIGTERM")}catch{}setTimeout(()=>{try{u.kill("SIGKILL")}catch{}},1500)};t.signal&&t.signal.addEventListener("abort",A,{once:!0});const b=()=>{m&&clearTimeout(m),m=setTimeout(()=>{A(),k({choices:[{message:{content:""},finish_reason:"stop"}],error:`claude: the child went silent for ${Math.round(f/1e3)}s and was stopped`})},f)};b();const S=createStreamParser({onText:e=>{b(),t.onDelta&&t.onDelta({delta:e})},onThinking:e=>{b(),t.onDelta&&t.onDelta({reasoning:e})},onThinkingProgress:e=>{b(),t.onDelta&&t.onDelta({thinkingTokens:e})},onTool:e=>{b(),t.onDelta&&t.onDelta({delta:"",tool:{name:e.name,args:e.args,ok:"done"===e.phase?!e.error:void 0,id:e.id,cwd:t.cwd,phase:e.phase}})},onAsk:e=>{b(),Promise.resolve().then(()=>t.onAsk(e)).then(n=>y(e.requestId,"session"===n||"once"===n||"always"===n?n:"deny","AEGIS_USER_DENIED"),n=>{y(e.requestId,"deny",`AEGIS_USER_DENIED (${n&&n.message||String(n)})`)}).catch(()=>{})},onAskUnavailable:e=>{y(e.requestId,"deny","AEGIS_NO_APPROVAL_CHANNEL")},onDone:e=>{e.error?k({choices:[{message:{content:e.text||""},finish_reason:"error"}],usage:e.usage||void 0,error:e.error,...l.record.resumeSessionId&&isStaleResumeError(e.error)?{resumeStale:!0,resumeSessionId:l.record.resumeSessionId}:{}}):k({choices:[{message:proMessage(e.text||"",e.thinking,e.thinkingTokens),finish_reason:"stop"}],usage:e.usage||void 0,costUsd:e.costUsd,durationMs:e.durationMs,sessionId:e.sessionId,childRecord:l.record})}});u.stdout.on("data",e=>{b(),g+=e.toString("utf8");const n=g.split("\n");g=n.pop()||"";for(const e of n){const n=e.trim();n&&S.line(n)}}),_&&u.stdin&&u.stdin.on("error",()=>{}),u.stderr.on("data",e=>{b(),h.length<8192&&(h+=e.toString("utf8"))}),u.on("error",e=>{k({choices:[{message:{content:""},finish_reason:"error"}],error:`claude: could not run the child (${e&&e.message||e}). Install it with \`npm i -g @anthropic-ai/claude-code\`, then sign in with \`claude auth login\`.`})}),u.on("close",e=>{g.trim()&&S.line(g.trim()),k({choices:[{message:proMessage(S.text,S.thinking,S.thinkingTokens),finish_reason:"stop"}],usage:S.resultLine&&S.resultLine.usage||void 0,childRecord:l.record,error:S.text||0===e?void 0:`claude: the child exited with status ${e}${h.trim()?` — ${h.trim().split("\n").slice(-3).join(" ")}`:""}`})})})}function isStaleResumeError(e){return!!e&&/no conversation found with session id/i.test(String(e))}function childLine(e,n){if(!e)return"";try{return loadSeam(n).child.childRecordLine(e)}catch{const n=e.skipFlag||"no permission flag";return`aegis: claude child [${e.kind}] ${n}`}}module.exports={claudeConfigDir:claudeConfigDir,claudeOAuthToken:claudeOAuthToken,claudeProStatus:claudeProStatus,childEnvPlan:childEnvPlan,envDroppedLine:envDroppedLine,shadowingValue:shadowingValue,SHADOWING_ENV_VARS:SHADOWING_ENV_VARS,PRO_MODELS:PRO_MODELS,turnArgs:turnArgs,createStreamParser:createStreamParser,loadSeam:loadSeam,seamAvailable:seamAvailable,childLine:childLine,isStaleResumeError:isStaleResumeError,runClaudePro:runClaudePro};
@@ -1,3 +1,3 @@
1
1
  // SPDX-License-Identifier: AGPL-3.0-or-later
2
2
  // Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
3
- "use strict";const CHARS_PER_TOKEN=4,MESSAGE_OVERHEAD=4,IMAGE_COST=850;function estimateTokens(e){if(null==e)return 0;const t="string"==typeof e?e:String(e);return Math.max(0,Math.ceil(t.length/CHARS_PER_TOKEN))}function messageTokens(e){if(!e)return 0;const t=null!=e.content?e.content:null!=e.text?e.text:"";if(Array.isArray(t)){let e=MESSAGE_OVERHEAD;for(const s of t)s&&"object"==typeof s&&("string"==typeof s.text?e+=estimateTokens(s.text):("image_url"===s.type||s.image_url)&&(e+=IMAGE_COST));return e}return MESSAGE_OVERHEAD+estimateTokens(t)}function trimContext({messages:e=[],system:t="",budgetTokens:s=8192,reserveTokens:n=0,fixedTokens:o=0}={}){const E=Math.max(0,s-n),r=[],i=Math.max(0,Number(o)||0);let a=i;t&&(a+=MESSAGE_OVERHEAD+estimateTokens(t));for(let t=e.length-1;t>=0;t--){const s=messageTokens(e[t]);if(a+s>E&&r.length>0)break;r.unshift(e[t]),a+=s}return{messages:r,system:t,dropped:e.length-r.length,estimatedTokens:a,fixedTokens:i}}module.exports={CHARS_PER_TOKEN:CHARS_PER_TOKEN,MESSAGE_OVERHEAD:MESSAGE_OVERHEAD,IMAGE_COST:IMAGE_COST,estimateTokens:estimateTokens,messageTokens:messageTokens,trimContext:trimContext};
3
+ "use strict";const CHARS_PER_TOKEN=4,MESSAGE_OVERHEAD=4,IMAGE_COST=850;function estimateTokens(e){if(null==e)return 0;const t="string"==typeof e?e:String(e);return Math.max(0,Math.ceil(t.length/4))}function messageTokens(e){if(!e)return 0;const t=null!=e.content?e.content:null!=e.text?e.text:"";if(Array.isArray(t)){let e=4;for(const s of t)s&&"object"==typeof s&&("string"==typeof s.text?e+=estimateTokens(s.text):("image_url"===s.type||s.image_url)&&(e+=850));return e}return 4+estimateTokens(t)}function trimContext({messages:e=[],system:t="",budgetTokens:s=8192,reserveTokens:n=0,fixedTokens:o=0}={}){const r=Math.max(0,s-n),i=[],a=Math.max(0,Number(o)||0);let m=a;t&&(m+=4+estimateTokens(t));for(let t=e.length-1;t>=0;t--){const s=messageTokens(e[t]);if(m+s>r&&i.length>0)break;i.unshift(e[t]),m+=s}return{messages:i,system:t,dropped:e.length-i.length,estimatedTokens:m,fixedTokens:a}}module.exports={CHARS_PER_TOKEN:4,MESSAGE_OVERHEAD:4,IMAGE_COST:850,estimateTokens:estimateTokens,messageTokens:messageTokens,trimContext:trimContext};
@@ -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{randomUUID:randomUUID}=require("node:crypto"),os=require("node:os"),fs=require("node:fs"),toolsModule=require("./tools.js"),attachmentsModule=require("./attachments.js"),{flattenContent:flattenContent}=attachmentsModule,promptModule=require("./prompt.js"),localTransport=require("./local.js"),{ShellSession:ShellSession}=require("./shell.js"),{planExec:planExec}=require("./exec-plan.js"),claudePro=require("./claude-pro.js"),{agentSystemPrompt:agentSystemPrompt,agentRoleLabel:agentRoleLabel}=require("./agents.js"),{beginTurnGuard:beginTurnGuard,recordWrite:recordWrite,blocksDestructive:blocksDestructive}=require("./turn-guard.js"),repeatGuard=require("./repeat-guard.js"),verifyGuard=require("./verify-stop.js"),{acquireWorktreeLock:acquireWorktreeLock,releaseWorktreeLock:releaseWorktreeLock}=require("./worktree-lock.js"),covenant=require("./covenant.js");let envFile=null;try{envFile=require("../../../client/env-file.js")}catch{try{envFile=require("../../vendor/env-file.js")}catch{envFile=null}}let platformLib=null;try{platformLib=require("../../../client/platform.js")}catch{try{platformLib=require("../../vendor/platform.js")}catch{platformLib=null}}let credentialsLib=null;try{credentialsLib=require("../../../client/credentials.js")}catch{try{credentialsLib=require("../../vendor/credentials.js")}catch{credentialsLib=null}}const PRO_TOOL_MAP=Object.freeze({Write:"writeFile",Edit:"editFile",MultiEdit:"editFile",NotebookEdit:"editFile",Bash:"exec",BashOutput:"exec"}),PRO_PLAN_MODE_SAFE=Object.freeze(new Set(["Read","Glob","Grep"]));function proAskArgs(e,t){const o=e&&"object"==typeof e?e:{};return"exec"===t?"string"==typeof o.command?{command:o.command}:{}:"writeFile"===t?"string"==typeof o.file_path?{file_path:o.file_path,content:o.content}:{}:"editFile"===t?Array.isArray(o.edits)?{file_path:o.file_path,edits:o.edits}:"string"==typeof o.file_path?{file_path:o.file_path,old_string:o.old_string,new_string:o.new_string,replace_all:!0===o.replace_all}:{}:o}function normalizeToolArgs(e,t,o,r){const n=e&&"function"==typeof e.normalizeArgs&&e.normalizeArgs||"function"==typeof toolsModule.normalizeArgs&&toolsModule.normalizeArgs||null;return n?n(t,o,r):{ok:!0,args:o&&"object"==typeof o?o:{},error:null}}function detectVcs(e){if(!e)return null;try{const t=require("node:fs"),o=require("node:path");let r=o.resolve(String(e));for(let e=0;e<8;e+=1){if(t.existsSync(o.join(r,".git")))return"git";const e=o.dirname(r);if(e===r)break;r=e}return""}catch{return null}}function hostEnv(e={},t={},o=null){const r=e||{},n=t||{},s=(e,t)=>null!=n[e]?n[e]:t;let a=r.homedir,i=r.cwd;try{a||(a=os.homedir()),i||(i=process.cwd())}catch{}let l=r.shell,c=r.shellKind;try{if(!l||!c){const e=require("./shell.js").resolveSessionShell();l=l||e.cmd,c=c||e.kind}}catch{}let d=r.desktopdir;try{!d&&platformLib&&(d=platformLib.desktopDir())}catch{}let u=r.dataDir;try{!u&&credentialsLib&&(u=credentialsLib.aegisHome())}catch{}let f=r.locale,p=r.localeName;try{!f&&platformLib&&"function"==typeof platformLib.appLocale&&(f=platformLib.appLocale()),f&&!p&&platformLib&&"function"==typeof platformLib.languageName&&(p=platformLib.languageName(f))}catch{}return{platform:s("platform",r.platform||process.platform),arch:s("arch",r.arch||process.arch),homedir:s("homedir",a),desktopdir:s("desktopdir",d),dataDir:s("dataDir",u),locale:s("locale",f),localeName:s("localeName",p),languages:s("languages",r.languages),cwd:s("cwd",i),vcs:s("vcs",null!=r.vcs?r.vcs:detectVcs(i)),shell:s("shell",l),shellKind:s("shellKind",c),roots:s("roots",r.roots),appVersion:s("appVersion",r.appVersion),model:s("model",o&&o.model)}}function requireSharedBrain(){const e=[()=>require("../../../client/brain-catalog.js"),()=>require("../../vendor/brain-catalog.js")];let t=null;for(const o of e)try{return o()}catch(e){t=e}throw t}function requireSharedByokCatalog(){const e=[()=>require("../../../client/byok-catalog.js"),()=>require("../../vendor/byok-catalog.js")];let t=null;for(const o of e)try{return o()}catch(e){t=e}throw t}function requireSharedUserModels(){const e=[()=>require("../../../client/user-models.js"),()=>require("../../vendor/user-models.js")];let t=null;for(const o of e)try{return o()}catch(e){t=e}throw t}function requireSharedCatalogClient(){const e=[()=>require("../../../client/catalog-client.js"),()=>require("../../vendor/catalog-client.js")];let t=null;for(const o of e)try{return o()}catch(e){t=e}throw t}function requireSharedModelDiscovery(){const e=[()=>require("../../../client/model-discovery.js"),()=>require("../../vendor/model-discovery.js")];let t=null;for(const o of e)try{return o()}catch(e){t=e}throw t}function requireSharedModelSync(){const e=[()=>require("../../../client/model-sync.js"),()=>require("../../vendor/model-sync.js")];let t=null;for(const o of e)try{return o()}catch(e){t=e}throw t}function requireSharedModelAutoSync(){const e=[()=>require("../../../client/model-autosync.js"),()=>require("../../vendor/model-autosync.js")];let t=null;for(const o of e)try{return o()}catch(e){t=e}throw t}const WORKTREE_LOCK_WAIT_MS=1500,MAX_SUBAGENT_DEPTH=4,CLASSES=[{class:"aegis",label:"Aegis Cloud",kind:"cloud"},{class:"byok",label:"Bring your own key",kind:"cloud"},{class:"local",label:"Local model",kind:"local"},{class:"pro",label:"Claude Code Pro",kind:"subscription"}],BYOK_NAMESPACE_PREFIX="byok:";function byokNamespace(e){return`${BYOK_NAMESPACE_PREFIX}${e}`}function splitByokModel(e){const t="string"==typeof e?e:"",o=t.indexOf(":");return o<0?{provider:"",model:t}:{provider:t.slice(0,o),model:t.slice(o+1)}}function providerKeyRecord(e){const t={key:"",env:"",rejected:null};if(!envFile||"function"!=typeof envFile.providerKeyFromEnv)return t;try{const o=envFile.providerKeyFromEnv(e)||t;return{key:"string"==typeof o.key?o.key:"",env:"string"==typeof o.env?o.env:"",rejected:"string"==typeof o.rejected&&o.rejected?o.rejected:null}}catch{return t}}function providerKeyFromEnv(e){if(!envFile||"function"!=typeof envFile.providerKeyFromEnv)return"";try{return envFile.providerKeyFromEnv(e).key||""}catch{return""}}const DEEPSEEK_REASONING_MODEL_RE=/^deepseek-(v4(\.\d+)?-(flash|pro)|flash|pro|reasoner)$/,EFFORT_TOKEN_BUDGET={low:8192,medium:16384,high:32768,max:32768},DEEPSEEK_EFFORT={low:"low",medium:"high",high:"high"},DEEPSEEK_EFFORT_EXTRA={max:"max"},EFFORT_IDENTITY={low:"low",medium:"medium",high:"high"},EFFORT_INERT_RE=/non-reasoning/i,EFFORT_DIALECTS=[{provider:"deepseek",re:DEEPSEEK_REASONING_MODEL_RE,field:"effort",map:DEEPSEEK_EFFORT,extra:DEEPSEEK_EFFORT_EXTRA},{provider:"openai",re:/^(gpt-5|o[0-9])/i,field:"reasoning_effort",map:EFFORT_IDENTITY},{provider:"groq",re:/^(openai\/gpt-oss|qwen\/qwen3)/i,field:"reasoning_effort",map:EFFORT_IDENTITY},{provider:"xai",re:/^grok-(4\.[5-9]|[5-9])/,field:"reasoning_effort",map:EFFORT_IDENTITY},{provider:"google",re:/^gemini-(2\.5|3|[4-9])/,field:"reasoning_effort",map:{...EFFORT_IDENTITY,medium:"high"}}],AUTONOMOUS_IDLE_TIMEOUT_MS=9e5;function reasoningBudget(e,t,o){const r=Number(t);return Number.isFinite(r)&&r>0?r:DEEPSEEK_REASONING_MODEL_RE.test(String(e||""))?EFFORT_TOKEN_BUDGET["low"===o||"medium"===o||"max"===o?o:"high"]:void 0}function nativeEffort(e,t,o){const r=String(t||"");if(EFFORT_INERT_RE.test(r))return;if(null===o)return;const n="low"===o||"medium"===o?o:"max"===o?"max":"high";for(const t of EFFORT_DIALECTS)if(t.provider===e&&t.re.test(r)){const e=Object.prototype.hasOwnProperty.call(t.map,n)?t.map[n]:t.extra&&Object.prototype.hasOwnProperty.call(t.extra,n)?t.extra[n]:void 0;if(void 0===e)return;return{field:t.field,level:e}}}function normalizeCatalog(e){return Array.isArray(e)?e.map((e=>"string"==typeof e?{id:e}:e)).filter((e=>e&&e.id)):[]}const{offerableCatalog:offerableCatalog}=requireSharedBrain(),{withByokAdditions:withByokAdditions,canonicalModelId:canonicalModelId,nexusFallbackModel:nexusFallbackModel}=requireSharedByokCatalog(),{withUserModels:withUserModels,unmatchedUserProviders:unmatchedUserProviders,load:loadUserModels,addUserModel:addUserModel,removeUserModel:removeUserModel}=requireSharedUserModels(),{withCatalog:withCatalog}=requireSharedCatalogClient(),{discoverModels:discoverVendorModels,canDiscover:canDiscoverVendorModels,endpointFor:vendorEndpointFor,discoverableProviders:discoverableProviders}=requireSharedModelDiscovery(),modelSync=requireSharedModelSync(),{createModelAutoSync:createModelAutoSync}=requireSharedModelAutoSync();function parseArgs(e){if(null==e)return{};if("object"==typeof e)return e;try{const t=JSON.parse(String(e));return t&&"object"==typeof t?t:{}}catch{return{}}}function extractToolCalls(e){if(!e)return[];if(Array.isArray(e.toolCalls)&&e.toolCalls.length)return e.toolCalls.map((e=>({id:e.id||"",name:e.name||"",args:parseArgs(e.args)}))).filter((e=>e.name));const t=e.choices&&e.choices[0]&&e.choices[0].message,o=t&&t.tool_calls||[];return Array.isArray(o)?o.map((e=>{const t=e&&e.function||{};return{id:e&&e.id||"",name:t.name||e&&e.name||"",args:parseArgs(t.arguments)}})).filter((e=>e.name)):[]}function proTurnPrompt(e){const t=Array.isArray(e.prompt)?flattenContent(e.prompt):e.prompt;if("string"==typeof t&&t.trim())return t;const o=Array.isArray(e.messages)?e.messages:[];for(let e=o.length-1;e>=0;e-=1){const t=o[e];if(!t||"user"!==t.role)continue;const r=flattenContent(t.content);if(r.trim())return r}return t}function assistantText(e){const t=e&&e.choices&&e.choices[0]&&e.choices[0].message;return t&&"string"==typeof t.content&&t.content||""}function finishReasonOf(e){const t=e&&e.choices&&e.choices[0];return t&&t.finish_reason||e&&e.stop_reason||""}function isTruncated(e){const t=finishReasonOf(e);return"length"===t||"max_tokens"===t}function reasoningTextOf(e){if(!e)return"";const t=e.choices&&e.choices[0],o=t&&t.message||{};if(Array.isArray(o.content)){const e=o.content.filter((e=>e&&("thinking"===e.type||"reasoning"===e.type))).map((e=>e.thinking||e.text||"")).join("");if(e)return e}const r=o.content&&"object"==typeof o.content?o.content.reasoning_content:"",n=[o.reasoning_content,o.reasoning,t&&t.reasoning_content,e.reasoning_content,e.reasoning,r];for(const e of n)if("string"==typeof e&&e)return e;return""}function reasoningTokensOf(e){if(!e)return 0;const t=e.choices&&e.choices[0],o=t&&t.message||{},r=e.usage||{},n=r.completion_tokens_details||r.output_tokens_details||{},s=[o.thinking_tokens,o.reasoning_tokens,t&&t.thinking_tokens,e.thinking_tokens,n.reasoning_tokens,n.thinking_tokens];for(const e of s)if("number"==typeof e&&Number.isFinite(e)&&e>0)return e;return 0}function reasonedButSilent(e){return!assistantText(e)&&(""!==reasoningTextOf(e)||reasoningTokensOf(e)>0)}const REASONING_RETRY_FLOOR=32768;function retryBudgetFor(e,t){const o=doubledBudget(e.maxTokens);return t&&ladderRung(e.maxTokens)?Math.max(o,REASONING_RETRY_FLOOR):o}function ladderRung(e){const t=Number(e);return Number.isFinite(t)&&Object.values(EFFORT_TOKEN_BUDGET).includes(t)}function doubledBudget(e){const t=Number(e)||0;return t>0?2*t:8192}function statedCapOf(e){const t=e=>{const t=Number(e);return Number.isFinite(t)&&t>0?t:void 0};return e&&Object.prototype.hasOwnProperty.call(e,"statedMaxTokens")?t(e.statedMaxTokens):t(e&&e.maxTokens)}const EMPTY_TURN_NUDGE="Your previous reply came back empty — it contained no answer and no tool call. Write your answer now, using only the information already gathered above. No tools are available in this reply, so do not call any: respond in plain prose or markdown.",THOUGHT_ONLY_NUDGE="Your previous round was spent entirely on hidden reasoning and produced no visible reply. Answer the user directly and briefly now. Do not reason, explain, or think first — write only the answer, no tools.",FINAL_ANSWER_NUDGE="Write your answer now, in plain prose, using only what is already in this conversation. If your information is incomplete, say what you have and what is missing — an incomplete answer is the expected outcome here and is better than none. No tools, no preface.",RECOVERY_ROUNDS=2,UNMUTATED_TURN_NUDGE="You ended the turn without changing any file, but this request asked for a change. The tools are still available in this reply: make the edit now with editFile or writeFile. If you already know what to change, change it — describing the fix is not the fix. If you genuinely cannot, say precisely what blocks you.",MUTATION_INTENT_RE=new RegExp("\\b(?:fix|implement|add|create|write|refactor|rename|remove|delete|replace|update|patch|migrate|convert|make\\s+(?:it|them|this|that|the|sure)|change|correct|resolve|repair|address|apply|introduce|support|wire\\s+up)\\b","i");function wantsMutation(e,t,o){if(t)return!1;if(!(o>0))return!1;const r=String(e||"");return!!r.trim()&&!/\?\s*$/.test(r.trim())&&MUTATION_INTENT_RE.test(r)}function emptyTurnError({cls:e,model:t,finishReason:o,reasoningChars:r,reasoningTokens:n,effort:s,recoveryRounds:a}){const i=Number(a)||0,l=Number(n)||0,c=new Error(`The model returned no answer after ${e}/${t} was asked to summarise its results`+(i?`, and ${i} extra recovery call${1===i?"":"s"} with a larger budget and a changed ask came back empty too`:"")+` (stop reason: ${o||"none"}`+(s?`, effort: ${s}`:"")+(r?`, hidden reasoning: ${r} chars and no visible text`:l>0?`, ~${l} thinking tokens billed and no visible text`:"")+"). "+(r||l>0?"Every one of those calls spent its output on hidden reasoning instead of writing a word, so this is the model rather than the budget: pick a model that answers without a thinking pass, or ask for a smaller piece of work.":"No visible text came back from any of those calls. Send the request again, in smaller pieces, or from a different model."));return c.status=502,c}function createLocalEngine({aegis:e,settings:t,tools:o,promptBuilder:r,recallProvider:n,env:s,getConfirmMode:a,getPermissionMode:i,sandbox:l,localTransport:c=localTransport,fetchImpl:d,gitScope:u,permissionRules:f}){const p=new Map,m=o||toolsModule,h=r&&r.buildSystemPrompt||promptModule.buildSystemPrompt,y=f&&"function"==typeof f.rulesVerdict?f.rulesVerdict:null,g=f&&"function"==typeof f.alwaysAllow?f.alwaysAllow:null,k=f&&"function"==typeof f.subjectFor?f.subjectFor:null,v=require("./session-rounds.js"),b=()=>{if("function"==typeof a)return!1!==a();if(t&&"function"==typeof t.getConfirmMode){const e=t.getConfirmMode();return void 0===e||Boolean(e)}return!0},w=()=>"function"==typeof i?"plan"===i():!(!t||"function"!=typeof t.getPermissionMode)&&"plan"===t.getPermissionMode();function E(e,t){return`${e} was not executed — this session is in plan mode (read-only). Plan mode may read files, search, run read-only shell commands and deploy subagents to research, but may not create, edit or delete files, run a mutating command, or install packages`+(t?` (this command: ${t})`:"")+". Do NOT retry it or attempt the same effect by another route. Finish your research and present a plan in plain text; the user exits plan mode (`/permissions mode off`) before any edit can run."}const _=new Map,S=new Map,T=new Map,A=200,x=new Map,M=require("./pro-sessions.js"),O=new Map,N=new Map;function F(e,t){if("function"!=typeof k)return e;let o="";try{o=String(k(e,t||{})||"")}catch{o=""}return`${e}\0${o}`}function R(e,t,o){_.has(e)||_.set(e,new Set),_.get(e).add(F(t,o))}function D(e,t){const o=S.get(e);return Boolean(o&&o.has(t))}function I(e,t){S.has(e)||S.set(e,new Set),S.get(e).add(t)}function U(e){if(!e)return null;try{return{existed:!0,content:fs.readFileSync(e,"utf8")}}catch(e){return e&&"ENOENT"===e.code?{existed:!1,content:null}:null}}function L(e){return`${e} was not executed — the user denied this tool for this conversation. Do NOT retry it and do NOT attempt the same effect by another route (another command, a writeFile instead of an edit, a subagent). Stop calling tools and reply in plain text: say what you were trying to do, what you need, and that the user can re-enable ${e} to let it proceed.`}function C(e,t,o,r){return new Promise((n=>{if(o&&o.aborted)return void n("cancel");const s=randomUUID();let a=!1;const i=()=>l("cancel"),l=e=>{a||(a=!0,O.delete(s),o&&o.removeEventListener("abort",i),n(e))};o&&o.addEventListener("abort",i,{once:!0}),O.set(s,{resolve:l}),"function"==typeof t?t({delta:"",approval:{id:s,sessionId:e,tool:r.tool,args:r.args,diff:r.diff||null,canPersist:"function"==typeof g}}):l("cancel")}))}function P(e,t,o,r){return new Promise((n=>{if(o&&o.aborted)return void n(!1);const s=randomUUID();let a=!1;const i=()=>l(!1),l=e=>{a||(a=!0,N.delete(s),o&&o.removeEventListener("abort",i),n(e))};o&&o.addEventListener("abort",i,{once:!0}),N.set(s,{resolve:l}),"function"==typeof t?t({delta:"",rounds:{id:s,sessionId:e,spent:r.spent,extensions:r.extensions,max:r.max,size:r.size}}):l(!1)}))}async function $(e,t,o,r,n){const s=normalizeToolArgs(m,e,t,o||{});if(!s.ok)return{ok:!1,error:s.error};t=s.args;const a=o&&o.guard;if(a&&"exec"===e){const e=blocksDestructive(a,t&&t.command);if(!e.ok)return{ok:!1,error:e.reason}}const i=o&&o.repeat,l=i?repeatGuard.check(i,e,t):null;if(l&&"refuse"===l.action)return{ok:!1,error:l.error};const c=covenant.preActionAssert({tool:e,args:t||{}});if(!c.allowed){const o=covenant.bindRefusal({tool:e,args:t||{}},c);return{ok:!1,error:`refused by the ÆGIS covenant — ${c.clause} (${c.label}): ${c.reason}`,covenant:o}}const d="writeFile"===e||"editFile"===e,u=d?U(t&&t.file_path):null,f=await m.executeTool(e,t,o);a&&d&&f&&!1!==f.ok&&recordWrite(a,t&&t.file_path),i&&d&&f&&!1!==f.ok&&repeatGuard.recordWrite(i,t&&t.file_path);const p=o&&o.verify;if(p&&(verifyGuard.EXEC_TOOLS.has(e)&&f&&!1!==f.ok?verifyGuard.recordExec(p):d&&f&&!1!==f.ok&&verifyGuard.recordMutation(p,t&&t.file_path)),d&&u&&f&&!1!==f.ok){const o=U(t&&t.file_path);o&&function(e,t){if(!e)return;T.has(e)||T.set(e,[]);const o=T.get(e);o.push(t),o.length>A&&o.shift()}(r,{id:n||randomUUID(),tool:e,path:t&&t.file_path,before:u,after:o,at:Date.now()})}return l&&l.note?q(f,l.note):f}function q(e,t){if(!e||"object"!=typeof e)return{ok:!0,content:`${t}\n${null==e?"":e}`};if(!1===e.ok||!0===e.isError){const o=e.error||e.content||"";return{...e,error:`${t}\n${o}`,content:`${t}\n${o}`}}const o=null!=e.content?e.content:null!=e.output?e.output:"";return{...e,content:`${t}\n${o}`}}async function j(e,{toolCtx:t,rootSessionId:o,rootOnDelta:r,signal:n}){const{name:s}=e,a=normalizeToolArgs(m,s,e.args,t||{});if(!a.ok)return{ok:!1,error:a.error};const i=a.args;if(!m.MUTATING_TOOLS.has(s))return $(s,i,t,o,e.id);if(w()){if("exec"===s){const r=planExec(i&&i.command,{baseCwd:t&&t.cwd||void 0});return r.oneShot?$(s,i,t,o,e.id):{ok:!1,error:E(s,r.reason)}}return{ok:!1,error:E(s)}}if(!b())return $(s,i,t,o,e.id);if(function(e,t,o){const r=_.get(e);return Boolean(r&&r.has(F(t,o)))}(o,s,i))return $(s,i,t,o,e.id);if("function"==typeof y){let r;try{r=y(s,i)}catch(e){r={verdict:null,source:"error",error:e&&e.message||String(e)}}if(r&&"deny"===r.verdict)return I(o,s),{ok:!1,error:L(s),permissionRule:r.rule||null};if(r&&"allow"===r.verdict)return $(s,i,t,o,e.id)}if(D(o,s))return{ok:!1,error:L(s)};let l=null;if(("writeFile"===s||"editFile"===s)&&(l=m.previewMutation(s,i,t||{}),!l.ok))return{ok:!1,error:l.error};const c=await C(o,r,n,{tool:s,args:i,diff:l&&l.diff});if("deny"===c)return I(o,s),{ok:!1,error:L(s)};if("session"!==c&&"once"!==c&&"always"!==c)return{ok:!1,error:`${s} was not executed — the request was cancelled.`};let d=null;if("always"===c){let e=null;if("function"==typeof g)try{e=g(s,i)}catch(t){e={ok:!1,reason:t&&t.message||String(t)}}else e={ok:!1,reason:"no durable store is wired on this host"};d=e&&e.ok?`[permission_rule] stored ${e.rule} — this command will not ask again`:`[permission_rule] nothing was stored — ${e&&e.reason||"unknown reason"}; this call was allowed once only`}if("session"===c&&R(o,s,i),l){const e=m.applyChecked(s,i,l,t||{});return e&&!1!==e.ok&&t&&t.guard&&recordWrite(t.guard,i&&i.file_path),d?q(e,d):e}const u=await $(s,i,t,o,e.id);return d?q(u,d):u}function B(e){return hostEnv(s||{},e&&e.env||{},e)}function K(e){const t=[],o=e=>String(e||"").replace(/[\\/]+$/,""),r=o(e),n=e=>{const n=o(e);n&&n!==r&&!t.includes(n)&&t.push(n)};let s=u;if(void 0===s)try{s=require("./git-scope.js")}catch{s=null}try{s&&"function"==typeof s.gitRoot&&n(s.gitRoot(e))}catch{}try{credentialsLib&&"function"==typeof credentialsLib.aegisHome&&n(credentialsLib.aegisHome())}catch{}return t}async function G(t,o){if("aegis"===t){const t=!o.singlePass&&(!!o.autonomous||void 0);return e.chatCompletion({prompt:o.prompt,system:o.system,messages:o.messages,model:o.model,mode:o.mode,maxTokens:o.statedMaxTokens,stream:!1!==o.stream,includeUsage:!0,onStream:o.onDelta,onReasoning:o.onReasoning,idleTimeoutMs:o.idleTimeoutMs,signal:o.signal,extra:{aegis_recall:!0,...o.recallDeep?{aegis_recall_deep:!0}:{},session:o.sessionId,...void 0===t?{}:{brain:t},...!1===t?{mode:"brain"}:{},...o.effort?{effort:o.effort}:{},...!0===t&&o.workers?{workers:o.workers}:{},...o.tools.length?{tools:o.tools}:{},...o.toolChoice?{tool_choice:o.toolChoice}:{}},agentKey:o.tools.length&&(process.env.AEGIS_AGENT_KEY||"").trim()||void 0})}if("byok"===t){const{provider:t,model:r}=splitByokModel(o.model),n=canonicalModelId(t,r),s=nativeEffort(t,n,o.effort);try{return await e.byokChatCompletion({provider:t,model:n,providerKey:o.apiKey,baseURL:o.cfg&&o.cfg.baseURL,prompt:o.prompt,system:o.system,messages:o.messages,maxTokens:o.maxTokens,tools:o.tools,toolChoice:o.toolChoice,effort:s&&"effort"===s.field?s.level:void 0,reasoningEffort:s&&"reasoning_effort"===s.field?s.level:void 0,stream:!0,onStream:o.onDelta,signal:o.signal})}catch(e){if(e&&402===e.status){const e=new Error("byok: this account has no AEGIS balance left, and the BYOK handling fee is billed there — your provider key is still valid, this is not a key problem. Top up the account, then try again (or /class aegis to use the pooled lane).");throw e.status=402,e}throw e}}if("local"===t){const e=o.cfg&&o.cfg.baseURL||c.DEFAULT_BASE,t=t=>c.chat({baseURL:e,model:o.model,prompt:o.prompt,system:o.system,messages:o.messages,maxTokens:o.maxTokens,signal:o.signal,onDelta:o.onDelta,...t&&o.tools.length?{tools:o.tools,toolChoice:o.toolChoice}:{}});try{return await t(!0)}catch(e){if(o.tools.length&&e&&400===e.status)return t(!1);throw e}}if("pro"===t){const e=o.sessionKey||o.rootSessionId||o.sessionId;let t=null;if(e&&(t=x.get(e)||null,!t)){try{t=M.get(e,s)||null}catch{}t&&x.set(e,t)}const r=K(o.cwd),n=e=>claudePro.runClaudePro({prompt:proTurnPrompt(o),model:o.model&&"default"!==o.model?o.model:void 0,system:o.system,cwd:o.cwd,addDir:r,resumeSessionId:e||void 0,gate:b(),onAsk:async e=>{if(!e||!e.requestId)return"deny";const t=o.rootSessionId,r=o.rootOnDelta,n=PRO_TOOL_MAP[String(e.toolName||"")]||null,s=n||String(e.toolName||"unknown"),a=proAskArgs(e.input||{},s),i=covenant.preActionAssert({tool:s,args:a});if(!i.allowed)return r&&r({delta:"",note:`aegis: refused by the ÆGIS covenant — ${i.clause} (${i.label}): ${i.reason}`}),"deny";if(w()){if("exec"===s){const e=planExec(a&&a.command,{baseCwd:o.cwd||void 0});return e.oneShot?"once":(r&&r({delta:"",note:E(s,e.reason)}),"deny")}if(n&&m.MUTATING_TOOLS.has(s))return r&&r({delta:"",note:E(s)}),"deny";if(!n&&!PRO_PLAN_MODE_SAFE.has(s))return r&&r({delta:"",note:E(s)}),"deny"}if(!b())return"once";if("function"==typeof y){let e;try{e=y(s,a)}catch{e=null}if(e&&"deny"===e.verdict)return r&&r({delta:"",note:L(s)}),"deny";if(e&&"allow"===e.verdict)return"once"}if(D(t,s))return r&&r({delta:"",note:L(s)}),"deny";const l=await C(t,r,o.signal,{tool:s,args:a,diff:null});if("deny"===l)return I(t,s),"deny";if("session"!==l&&"once"!==l&&"always"!==l)return"deny";if("session"===l&&R(t,s,a),"always"===l&&"function"==typeof g)try{g(s,a)}catch{}return l},signal:o.signal,onDelta:o.onDelta,onSpawn:(e,t)=>{o.onDelta&&t&&o.onDelta({delta:"",note:claudePro.childLine(t)})}});let a=await n(t);if(a&&a.resumeStale){x.delete(e);try{M.del(e,s)}catch{}o.onDelta&&o.onDelta({delta:"",note:"aegis: the remembered Claude session no longer exists on this machine — continuing as a new conversation (earlier turns are not in its context)"}),a=await n(null)}if(e&&a&&a.sessionId&&!a.error){x.set(e,a.sessionId);try{M.set(e,a.sessionId,s)}catch{}}return a}throw new Error(`dispatch: unknown model class ${JSON.stringify(t)} — this build ships 'aegis', 'byok', 'local' and 'pro' only`)}async function Y(o,r){const s=o&&o.class,a=o&&o.model,i=reasoningBudget("byok"===s?splitByokModel(a).model:a,o&&o.maxTokens,o&&o.effort),d=statedCapOf(o),u="aegis"===s&&Boolean(o&&o.autonomous),f=Boolean(o&&o.roundsAsk),y=o&&o.sessionId||randomUUID(),g=Number.isInteger(o&&o.depth)?o.depth:0,k=o&&o.rootSessionId||y,b=o&&o.rootOnDelta||r,w="function"==typeof r?e=>e&&r({reasoning:e}):void 0,E=new AbortController,_=p.get(y)||null;p.set(y,E);const S=E.signal,T=!(o&&!1===o.tools),A=T?m.toolsFor({includeSubagent:g<4}):[],x=o&&o.toolChoice||null,M=o&&o.system||h(B(o)),O=n?await n({payload:o,env:B(o),system:M}):null,N="string"==typeof O?O:O&&"string"==typeof O.system?O.system:M,F=Array.isArray(o&&o.messages)?o.messages.filter(Boolean).slice():[];let R=F.length,D=o&&o.prompt||"";const I=String(D||""),U=Array.isArray(o&&o.attachments)?o.attachments.filter((e=>e&&"object"==typeof e)).slice(0,attachmentsModule.MAX_ATTACHMENTS):[];let L=U.length?attachmentsModule.buildContent(D,U):D,C=null;const $=B(o),q=((e,t)=>{if(null==l)return null;const o="function"==typeof l.policy?l.policy():l.policy;if(!o)return null;const r=require("./sandbox.js"),n=e&&e.cwd||process.cwd(),s=r.normalize(o,n);if("off"===s.mode)return null;let a=[];try{let e=null;try{e=require("node:os").homedir()}catch{e=null}a=r.autoGrants(n,{home:e,addDirs:(()=>{try{return K(n)}catch{return[]}})()})}catch{a=[]}if(a.length){const e=new Set;for(const t of s.fileSystem.entries)t&&t.path&&"path"===t.path.type&&t.path.path&&e.add(`${t.access}:${t.path.path}`);for(const t of a){const o=`${t.access}:${t.path.path}`;e.has(o)||(e.add(o),s.fileSystem.entries.push(t))}}return"local"===t&&"restricted"===s.network&&(s.network="open",s.networkExempt="local"),{policy:s,state:l.state||r.detect({appDir:l.appDir}),workspace:n,appDir:l.appDir,strict:!0===l.strict}})($,s),Y=$.cwd,z={getShell:()=>C||(C=new ShellSession({cwd:$.cwd,sandbox:q})),signal:S,cwd:Y,desktopdir:$.desktopdir,sandbox:q,repeat:repeatGuard.beginRepeatGuard({cwd:Y}),verify:verifyGuard.beginVerifyGuard({cwd:Y}),guard:beginTurnGuard(Y)};try{const n="byok"===s?splitByokModel(a):null;let l=null;const p="byok"===s?t.get(byokNamespace(n.provider))||{}:"local"===s&&t.get("local")||{},h="byok"===s?t.rawKey(byokNamespace(n.provider)):null,E="byok"!==s?null:h||providerKeyFromEnv(n.provider);if(!("byok"!==s||n.provider&&n.model)){const e=new Error('byok: model must be "<provider>:<model>" (pick one from /models) — got '+JSON.stringify(a||""));throw e.status=400,e}if("byok"===s&&!E){const t="anthropic"===n.provider?claudePro.claudeProStatus({env:process.env}):null,o=providerKeyRecord(n.provider).rejected,r=nexusFallbackModel({provider:n.provider,providerKey:E,providerKeyRefused:o,aegisKey:E?"":e.apiKey});if(!r){const e=new Error(o?`${o}. That is why this turn has no ${n.provider} key: an env value that short is a paste that lost its payload, not a credential. Fix ${o.split(" ")[0]} in ~/.aegiscode/.env (or the shell that exported it) — or skip keys entirely: /byok-key ${n.provider} <key> to set one here.`:t&&t.loggedIn?`No Anthropic API key on this machine — an "anthropic:…" id is served by your own console key, which a Claude subscription is not. Use the subscription instead: /class pro (it spends your Claude Code ${t.subscription||"Pro"} plan through the claude CLI) — or add a real console key: /byok-key anthropic <key>.`:`No key for "${n.provider}" yet. Easiest fix: /class aegis (uses your AEGIS key, no setup) — or add this provider's own key: /byok-key ${n.provider} <key>.`);throw e.status=400,e}l={from:n.provider,model:r}}if("byok"===s&&!e.apiKey){const e=new Error("No AEGIS key connected yet. Easiest fix: /class aegis (skips BYOK entirely) — or add your AEGIS key with /login, then try again.");throw e.status=401,e}if("local"===s){const e=c.remoteRefusal(p.baseURL||c.DEFAULT_BASE);if(e)throw e}if("byok"===s&&"custom"===n.provider&&!(p.baseURL||"").trim()){const e=new Error('No endpoint saved for the "custom" provider — its key is on this machine but the address it dials is not, and no default exists for a vendor AEGIS does not know. Fix: /model-add custom <https-base-url> <api-key> <model-id> (writes both halves), or the endpoint field in Settings › Provider (custom).');throw e.status=400,e.code="custom_endpoint_missing",e}const _=l?"aegis":s,M={cls:_,model:l?l.model:a,mode:o&&o.mode,maxTokens:i,statedMaxTokens:d,autonomous:u,sessionId:y,signal:S,onDelta:r,cfg:p,apiKey:E,toolChoice:x,pooledFrom:l?l.from:void 0,cwd:Y,rootSessionId:k,sessionKey:o&&o.sessionKey||void 0,rootOnDelta:b,effort:o&&o.effort,workers:o&&o.workers,recallDeep:o&&!0===o.recallDeep,singlePass:o&&!0===o.singlePass,onReasoning:w,idleTimeoutMs:u?9e5:void 0,stream:!o||!1!==o.stream};let O=!1,C=!1;const $=u?"AEGIS_AUTONOMOUS_MAX_ROUNDS":"AEGIS_CHAT_MAX_ROUNDS",q=(()=>{const e=Number.parseInt(process.env[$]||"",10);return Number.isFinite(e)&&e>0?e:0})(),B=q||(u?40:24);let K=v.keyFor(o,F),V=v.take(K);if(!V&&!v.isStatedKey(o)){const e=v.adopt();e&&(V=e.entry,K=e.key)}if(V){const e=v.resumePreamble(V);0===F.length?Array.isArray(V.messages)&&V.messages.length&&F.push(...V.messages):Array.isArray(V.added)&&V.added.length&&F.push(...V.added),D?(D=`${e}\n\n${D}`,L=U.length?attachmentsModule.buildContent(D,U):D):(F.push({role:"user",content:e}),L=""),b&&b({delta:`\n\n[resuming work this session left unfinished at ${V.rounds} tool rounds`+(V.interruptions>1?` (cut off ${V.interruptions}×)`:"")+"…]\n"})}let H=q||B+(V?v.bonus(B):0),X=0;const J=B,Q=8;let Z=0;const ee={calls:0},te=["input_tokens","output_tokens","prompt_tokens","completion_tokens","total_tokens","cache_read_input_tokens","cache_creation_input_tokens","prompt_cache_hit_tokens","prompt_cache_miss_tokens","reasoning_tokens","thinking_tokens"],oe=e=>{const t=e&&e.usage;if(t&&"object"==typeof t){ee.calls+=1;for(const e of te)"number"==typeof t[e]&&Number.isFinite(t[e])&&(ee[e]=(ee[e]||0)+t[e]);if("number"!=typeof t.total_tokens){const e=(t.prompt_tokens??t.input_tokens??0)+(t.completion_tokens??t.output_tokens??0);e&&(ee.total_tokens=(ee.total_tokens||0)+e)}}},re=e=>{if(!e||"object"!=typeof e)return e;const t=l?{...e,pooled_from:l.from,pooled_model:l.model,pooled_notice:requireSharedByokCatalog().nexusFallbackNotice({pooled_from:l.from,pooled_model:l.model})}:e;return ee.calls?{...t,usage:{...ee}}:t},ne=()=>{if(""===L)return;const e=F[F.length-1],t=e&&"user"===e.role?flattenContent(e.content):null;e&&"user"===e.role&&t===flattenContent(L)||F.push({role:"user",content:L}),D="",L=""};R=F.length;const se=m&&m.MUTATING_TOOLS||new Set;let ae=0,ie=0,le=!1,ce=!1;for(;;){if(X>=H){if(f&&Z<Q&&!S.aborted&&await P(k,b,S,{spent:H,extensions:Z+1,max:Q,size:J})){Z+=1;const e=H;H+=J,F.push({role:"user",content:`You have used all ${e} tool rounds allowed for this turn; ${J} more have been granted (do not restart). Continue the task from exactly where you stopped — do not re-plan, do not repeat work already done, and finish with an answer.`});continue}const e=f?"":`, or raise ${$} for a longer single turn`,t=`[stopped at ${H} tool rounds`+(ee.total_tokens?`, ${ee.total_tokens.toLocaleString()} tokens`:"")+". This session holds the work: your next message here resumes it automatically"+` (with a continuation preamble)${e}.]`,o=v.record(K,{rounds:X,tokens:ee.total_tokens||0,note:t,chain:V?V.interruptions:0,messages:F,added:F.slice(R)});return b&&b({delta:`\n\n${t}`}),re({model:M.model,choices:[{message:{content:t},finish_reason:"length"}],stoppedOnRounds:!0,heldForSession:!0,heldRounds:o.rounds,sessionInterruptions:o.interruptions,resumedFrom:K})}X+=1;const e={...M,system:N,messages:F,prompt:L,tools:A,recallDeep:M.recallDeep&&1===X};let t;if(t=await G(_,e),oe(t),S.aborted)return re(t);if(!O&&!assistantText(t)&&(isTruncated(t)||reasonedButSilent(t))){O=!0;const o=reasonedButSilent(t);if(t=await G(_,{...e,singlePass:!0,recallDeep:!1,effort:o?"high":e.effort,maxTokens:retryBudgetFor(e,o),statedMaxTokens:e.statedMaxTokens?doubledBudget(e.statedMaxTokens):void 0}),oe(t),S.aborted)return re(t)}const n=A.length?extractToolCalls(t):[];if(!n.length){if(assistantText(t)||C||!T){if(!le&&T&&wantsMutation(I,ie>0,ae)){le=!0,ne(),F.push({role:"assistant",content:assistantText(t)}),F.push({role:"user",content:UNMUTATED_TURN_NUDGE}),b&&b({delta:""});continue}if(z.verify&&!ce){const e=verifyGuard.shouldNudge(z.verify);if(e.nudge){ce=!0,ne(),F.push({role:"assistant",content:assistantText(t)}),F.push({role:"user",content:e.text}),b&&b({delta:""});continue}}return re(t)}C=!0,ne(),F.push({role:"user",content:reasonedButSilent(t)?THOUGHT_ONLY_NUDGE:EMPTY_TURN_NUDGE});const o={...e,singlePass:!0,recallDeep:!1,messages:F,prompt:"",tools:[]};t=await G(_,o);let r=o.maxTokens,n=o.effort;if(oe(t),S.aborted)return re(t);if(!assistantText(t)&&(isTruncated(t)||reasonedButSilent(t))){const e=reasonedButSilent(t);if(r=retryBudgetFor(o,e),n=e?"high":o.effort,t=await G(_,{...o,effort:n,maxTokens:r,statedMaxTokens:o.statedMaxTokens?doubledBudget(o.statedMaxTokens):void 0}),oe(t),S.aborted)return re(t)}const i=(()=>{const e=Number(r)||0;if(!e)return r;const t={maxTokens:r};return o.statedMaxTokens&&(t.statedMaxTokens=o.statedMaxTokens),Math.max(e,retryBudgetFor(t,!0))})();let l=0;for(;!assistantText(t)&&l<2&&!S.aborted;){const e=reasonedButSilent(t);if(l+=1,F.push({role:"user",content:e?1===l?THOUGHT_ONLY_NUDGE:FINAL_ANSWER_NUDGE:EMPTY_TURN_NUDGE}),e&&(n="high"),r=i,t=await G(_,{...o,messages:F,effort:n,maxTokens:r,statedMaxTokens:o.statedMaxTokens?doubledBudget(o.statedMaxTokens):void 0}),oe(t),S.aborted)return re(t)}if(!assistantText(t))throw emptyTurnError({cls:s,model:a,effort:n,recoveryRounds:l,finishReason:finishReasonOf(t),reasoningChars:reasoningTextOf(t).length,reasoningTokens:reasoningTokensOf(t)});return re(t)}ne(),F.push({role:"assistant",content:assistantText(t),tool_calls:n.map((e=>({id:e.id,type:"function",function:{name:e.name,arguments:JSON.stringify(e.args)}})))});const i=new WeakMap,l=e=>{if("exec"!==e.name)return null;if(i.has(e))return i.get(e);const t=planExec(e.args&&e.args.command,{baseCwd:Y});return i.set(e,t),t},c=e=>{if(!se.has(e.name))return!0;const t=l(e);return Boolean(t&&t.oneShot)},u=[];for(const e of n){const t=u[u.length-1];c(e)&&t&&t.parallel?t.calls.push(e):u.push({parallel:c(e),calls:[e]})}const p=async e=>{r&&r({delta:"",tool:{name:e.name,args:e.args,id:e.id,cwd:Y,phase:"run"}});const t=l(e),n=t&&t.oneShot?{...z,oneShotExec:!0,cwd:t.cwd||z.cwd}:z,i=e.name===m.SUBAGENT_TOOL?await W(e.args,{cls:s,model:a,statedMaxTokens:d,effort:o&&o.effort,mode:o&&o.mode,parentSignal:S,depth:g,rootSessionId:k,rootOnDelta:b}):await j(e,{toolCtx:n,rootSessionId:k,rootOnDelta:b,signal:S});return i&&i.usage&&oe({usage:i.usage}),r&&r({delta:"",tool:{name:e.name,args:e.args,ok:i.ok,id:e.id,cwd:Y,phase:"done"}}),i};for(const e of u){const t=e.parallel&&e.calls.length>1?await Promise.all(e.calls.map((e=>p(e)))):[await p(e.calls[0])];e.calls.forEach(((e,o)=>{const r=t[o];se.has(e.name)&&(ae+=1,r&&r.ok&&(ie+=1)),F.push({role:"tool",tool_call_id:e.id,name:e.name,content:m.toolResultText(r)})}))}}}catch(e){throw S.aborted&&e&&"object"==typeof e&&(e.aegisCancelled=!0),e}finally{C&&C.dispose(),p.get(y)===E&&(_&&!_.signal.aborted?p.set(y,_):p.delete(y))}}async function W({description:e,subagent_type:t,prompt:o}={},{cls:r,model:n,statedMaxTokens:s,effort:a,mode:i,parentSignal:l,depth:c,rootSessionId:d,rootOnDelta:u}={}){const f=String(o||e||"").trim();if(!f)return{ok:!1,error:"task requires a prompt"};const p=t&&"general"!==t?agentRoleLabel(t):"general",m=agentSystemPrompt(t),h=randomUUID();let y;if(l){if(l.aborted)return{ok:!1,error:"aborted"};y=()=>z(h),l.addEventListener("abort",y,{once:!0})}try{const e=await Y({class:r,model:n,mode:i,system:m,prompt:f,sessionId:h,depth:(c||0)+1,rootSessionId:d,rootOnDelta:u,statedMaxTokens:s,effort:a},(()=>{})),t=assistantText(e),o=e&&e.usage?{usage:e.usage}:{};return t?{ok:!0,output:t,...o}:{ok:!1,error:`subagent (${p}) produced no output`,...o}}catch(e){return{ok:!1,error:`subagent (${p}) failed: ${e&&e.message?e.message:e}`}}finally{l&&y&&l.removeEventListener("abort",y)}}function z(e){const t=p.get(e);return t&&t.abort(),{ok:Boolean(t)}}function V(e){const o=String(null==e?"":e).trim().toLowerCase();if(!o)return"";try{if(t&&"function"==typeof t.rawKey){const e=t.rawKey(byokNamespace(o));if("string"==typeof e&&e.trim())return e.trim()}}catch{}return providerKeyFromEnv(o)}async function H(t){let o=[];try{const t=await e.byokProviders();o=withUserModels(withCatalog(withByokAdditions(t&&t.providers||[])))}catch(e){return{ok:!1,providers:[],missing:0,stale:0,skipped:[],failed:[],error:e&&e.message||String(e)}}const r={};for(const e of modelSync.askableProviders(o,t)){const t=V(e);t&&(r[e]=t)}return modelSync.plan(o,{keys:r,fetchImpl:d,only:t})}const X=createModelAutoSync({getPref:()=>{try{return t&&"function"==typeof t.getSharedPref?t.getSharedPref("modelAutoSync"):null}catch{return null}},plan:e=>H(e),apply:(e,t)=>modelSync.apply(e,{only:t})});return{CLASSES:CLASSES,listClasses:async function(){return CLASSES.map((o=>{if("aegis"===o.class)return{...o,configured:Boolean(e.apiKey)};if("byok"===o.class){const e=(t.list()||[]).some((e=>!(!e||"string"!=typeof e.provider||!e.provider.startsWith("byok:"))&&(!!e.configured||Boolean(providerKeyFromEnv(e.provider.slice(BYOK_NAMESPACE_PREFIX.length))))));return{...o,configured:e}}if("local"===o.class)return{...o,configured:!0};if("pro"===o.class){const e=claudePro.claudeProStatus({env:process.env}),t=claudePro.seamAvailable();return{...o,configured:e.loggedIn,status:e,seam:t}}return{...o,configured:!1}}))},listModels:async function(o){if("aegis"===o){if(!e.apiKey)return{class:o,models:[],needsKey:!0};const t=await e.listModels();return{class:o,models:offerableCatalog(normalizeCatalog(t&&t.models))}}if("byok"===o){let r=[],n=null,s=!1,a=null;try{const t=await e.byokProviders();r=withUserModels(withCatalog(withByokAdditions(t&&t.providers||[]))),n=t&&t.fee||null}catch(e){r=[],s=!0,a=e&&e.message||String(e)}const i=[];for(const e of r){if(!e||!e.id)continue;const o=t.get(byokNamespace(e.id))||{},r=providerKeyRecord(e.id),n=r.key||"",s=Array.isArray(e.models)?e.models:[];for(const t of s){const s="string"==typeof t?t:t&&t.id;s&&i.push({id:`${e.id}:${s}`,label:`${e.label||e.id} — ${s}`,provider:e.id,configured:Boolean(o.configured||n),keyRejected:r.rejected||null})}}return{class:o,models:i,providers:r,needsProviderKey:i.length>0&&!i.some((e=>e.configured)),needsAegisKey:!e.apiKey,fee:n,providersFailed:s,providersError:a,unmatchedProviders:unmatchedUserProviders(r)}}if("local"===o){const e=(t.get("local")||{}).baseURL||c.DEFAULT_BASE,r=await c.probe(e);if(!r.running)return{class:o,models:[],baseURL:r.baseURL,needsDaemon:!0};let n=[],s=!0;try{n=await c.listTags(e)}catch{s=!1}return{class:o,models:n,baseURL:r.baseURL,listed:s}}if("pro"===o){const e=claudePro.claudeProStatus({env:process.env});return{class:o,models:claudePro.PRO_MODELS.map((t=>({id:t.id,label:t.label,note:t.note,configured:e.loggedIn}))),needsProviderKey:!1,needsAegisKey:!1,subscription:e.subscription,loggedIn:e.loggedIn,credentialFile:e.file,shadowed:e.shadowed||null,seam:claudePro.seamAvailable()}}throw new Error(`listModels: unknown model class ${JSON.stringify(o)} — this build ships 'aegis', 'byok', 'local' and 'pro' only`)},chat:Y,cancel:z,respondApproval:function(e,t){const o=O.get(e);return o?(O.delete(e),o.resolve("session"===t||"once"===t||"always"===t?t:"deny"),{ok:!0}):{ok:!1}},respondRoundsAsk:function(e,t){const o=N.get(e);return o?(N.delete(e),o.resolve(!0===t||"continue"===t),{ok:!0}):{ok:!1}},clearSessionApprovals:function(e){_.delete(e),S.delete(e),T.delete(e),x.delete(e);try{M.del(e,s)}catch{}return{ok:!0}},listUndoable:function(e){return(T.get(e)||[]).map((e=>({id:e.id,tool:e.tool,path:e.path,at:e.at}))).reverse()},undoMutation:function(e,t){const o=T.get(e)||[],r=t?o.findIndex((e=>e.id===t)):o.length-1;if(-1===r)return{ok:!1,error:t?`no undo record "${t}" for this conversation`:"nothing to undo in this conversation"};const n=o[r],s=U(n.path);if(!s||s.existed!==n.after.existed||s.content!==n.after.content)return{ok:!1,error:`${n.path} has changed since ${n.tool} ran — undo refused rather than overwriting work this session did not do. Resolve it by hand, or undo a different entry.`};try{n.before.existed?fs.writeFileSync(n.path,n.before.content,"utf8"):fs.unlinkSync(n.path)}catch(e){return{ok:!1,error:`undo failed: ${e&&e.message||e}`}}return o.splice(r,1),{ok:!0,path:n.path,restored:n.before.existed?"content":"deleted"}},settings:t,unloadLocalModels:function(){return c.unloadAll()},userModels:()=>loadUserModels(),addUserModel:(e,t)=>addUserModel(e,t),removeUserModel:(e,t)=>removeUserModel(e,t),discoverModels:async e=>{const t=String(null==e?"":e).trim().toLowerCase(),o=V(t),r=await discoverVendorModels(t,{key:o,fetchImpl:d});if(!r||!r.ok)return r;const n=[];try{const e=loadUserModels().map;for(const o of Array.isArray(e[t])?e[t]:[])n.push(o)}catch{}return{...r,declared:n,endpoint:(vendorEndpointFor(t)||{}).url||""}},modelSyncPlan:async e=>H(e),modelSyncApply:(e,t)=>modelSync.apply(e,{only:t}),modelAutoSync:X,modelAutoSyncRun:e=>X.runIfDue(e),modelAutoSyncStatus:()=>X.status(),addUserModels:(e,t)=>{const o=Array.isArray(t)?t:[],r={provider:e,added:0,already:[],failed:[],capped:0,file:""};for(const t of o)try{const o=addUserModel(e,t);r.file=o.file||r.file,o.added?r.added+=1:r.already.push(o.model)}catch(e){const n=e&&e.message||String(e);if(/the cap/.test(n)){r.capped=o.length-r.added-r.already.length-r.failed.length;break}r.failed.push({id:String(t),reason:n})}return r},canDiscoverModels:e=>canDiscoverVendorModels(e),discoverableProviders:()=>discoverableProviders()}}module.exports={CLASSES:CLASSES,createLocalEngine:createLocalEngine,extractToolCalls:extractToolCalls,parseArgs:parseArgs,reasoningBudget:reasoningBudget,nativeEffort:nativeEffort,hostEnv:hostEnv};
3
+ "use strict";const{randomUUID:randomUUID}=require("node:crypto"),os=require("node:os"),fs=require("node:fs"),toolsModule=require("./tools.js"),attachmentsModule=require("./attachments.js"),{flattenContent:flattenContent}=attachmentsModule,promptModule=require("./prompt.js"),localTransport=require("./local.js"),{ShellSession:ShellSession}=require("./shell.js"),{planExec:planExec}=require("./exec-plan.js"),claudePro=require("./claude-pro.js"),{agentSystemPrompt:agentSystemPrompt,agentRoleLabel:agentRoleLabel}=require("./agents.js"),{beginTurnGuard:beginTurnGuard,recordWrite:recordWrite,blocksDestructive:blocksDestructive}=require("./turn-guard.js"),repeatGuard=require("./repeat-guard.js"),verifyGuard=require("./verify-stop.js"),{acquireWorktreeLock:acquireWorktreeLock,releaseWorktreeLock:releaseWorktreeLock}=require("./worktree-lock.js"),covenant=require("./covenant.js");let envFile=null;try{envFile=require("../../../client/env-file.js")}catch{try{envFile=require("../../vendor/env-file.js")}catch{envFile=null}}let platformLib=null;try{platformLib=require("../../../client/platform.js")}catch{try{platformLib=require("../../vendor/platform.js")}catch{platformLib=null}}let credentialsLib=null;try{credentialsLib=require("../../../client/credentials.js")}catch{try{credentialsLib=require("../../vendor/credentials.js")}catch{credentialsLib=null}}const PRO_TOOL_MAP=Object.freeze({Write:"writeFile",Edit:"editFile",MultiEdit:"editFile",NotebookEdit:"editFile",Bash:"exec",BashOutput:"exec"}),PRO_PLAN_MODE_SAFE=Object.freeze(new Set(["Read","Glob","Grep"]));function proAskArgs(e,t){const o=e&&"object"==typeof e?e:{};return"exec"===t?"string"==typeof o.command?{command:o.command}:{}:"writeFile"===t?"string"==typeof o.file_path?{file_path:o.file_path,content:o.content}:{}:"editFile"===t?Array.isArray(o.edits)?{file_path:o.file_path,edits:o.edits}:"string"==typeof o.file_path?{file_path:o.file_path,old_string:o.old_string,new_string:o.new_string,replace_all:!0===o.replace_all}:{}:o}function normalizeToolArgs(e,t,o,r){const n=e&&"function"==typeof e.normalizeArgs&&e.normalizeArgs||"function"==typeof toolsModule.normalizeArgs&&toolsModule.normalizeArgs||null;return n?n(t,o,r):{ok:!0,args:o&&"object"==typeof o?o:{},error:null}}function detectVcs(e){if(!e)return null;try{const t=require("node:fs"),o=require("node:path");let r=o.resolve(String(e));for(let e=0;e<8;e+=1){if(t.existsSync(o.join(r,".git")))return"git";const e=o.dirname(r);if(e===r)break;r=e}return""}catch{return null}}function hostEnv(e={},t={},o=null){const r=e||{},n=t||{},s=(e,t)=>null!=n[e]?n[e]:t;let a=r.homedir,i=r.cwd;try{a||(a=os.homedir()),i||(i=process.cwd())}catch{}let l=r.shell,c=r.shellKind;try{if(!l||!c){const e=require("./shell.js").resolveSessionShell();l=l||e.cmd,c=c||e.kind}}catch{}let d=r.desktopdir;try{!d&&platformLib&&(d=platformLib.desktopDir())}catch{}let u=r.dataDir;try{!u&&credentialsLib&&(u=credentialsLib.aegisHome())}catch{}let f=r.locale,p=r.localeName;try{!f&&platformLib&&"function"==typeof platformLib.appLocale&&(f=platformLib.appLocale()),f&&!p&&platformLib&&"function"==typeof platformLib.languageName&&(p=platformLib.languageName(f))}catch{}return{platform:s("platform",r.platform||process.platform),arch:s("arch",r.arch||process.arch),homedir:s("homedir",a),desktopdir:s("desktopdir",d),dataDir:s("dataDir",u),locale:s("locale",f),localeName:s("localeName",p),languages:s("languages",r.languages),cwd:s("cwd",i),vcs:s("vcs",null!=r.vcs?r.vcs:detectVcs(i)),shell:s("shell",l),shellKind:s("shellKind",c),roots:s("roots",r.roots),appVersion:s("appVersion",r.appVersion),model:s("model",o&&o.model)}}function requireSharedBrain(){const e=[()=>require("../../../client/brain-catalog.js"),()=>require("../../vendor/brain-catalog.js")];let t=null;for(const o of e)try{return o()}catch(e){t=e}throw t}function requireSharedByokCatalog(){const e=[()=>require("../../../client/byok-catalog.js"),()=>require("../../vendor/byok-catalog.js")];let t=null;for(const o of e)try{return o()}catch(e){t=e}throw t}function requireSharedUserModels(){const e=[()=>require("../../../client/user-models.js"),()=>require("../../vendor/user-models.js")];let t=null;for(const o of e)try{return o()}catch(e){t=e}throw t}function requireSharedCatalogClient(){const e=[()=>require("../../../client/catalog-client.js"),()=>require("../../vendor/catalog-client.js")];let t=null;for(const o of e)try{return o()}catch(e){t=e}throw t}function requireSharedModelDiscovery(){const e=[()=>require("../../../client/model-discovery.js"),()=>require("../../vendor/model-discovery.js")];let t=null;for(const o of e)try{return o()}catch(e){t=e}throw t}function requireSharedModelSync(){const e=[()=>require("../../../client/model-sync.js"),()=>require("../../vendor/model-sync.js")];let t=null;for(const o of e)try{return o()}catch(e){t=e}throw t}function requireSharedModelAutoSync(){const e=[()=>require("../../../client/model-autosync.js"),()=>require("../../vendor/model-autosync.js")];let t=null;for(const o of e)try{return o()}catch(e){t=e}throw t}const WORKTREE_LOCK_WAIT_MS=1500,MAX_SUBAGENT_DEPTH=4,CLASSES=[{class:"aegis",label:"Aegis Cloud",kind:"cloud"},{class:"byok",label:"Bring your own key",kind:"cloud"},{class:"local",label:"Local model",kind:"local"},{class:"pro",label:"Claude Code Pro",kind:"subscription"}],BYOK_NAMESPACE_PREFIX="byok:";function byokNamespace(e){return`byok:${e}`}function splitByokModel(e){const t="string"==typeof e?e:"",o=t.indexOf(":");return o<0?{provider:"",model:t}:{provider:t.slice(0,o),model:t.slice(o+1)}}function providerKeyRecord(e){const t={key:"",env:"",rejected:null};if(!envFile||"function"!=typeof envFile.providerKeyFromEnv)return t;try{const o=envFile.providerKeyFromEnv(e)||t;return{key:"string"==typeof o.key?o.key:"",env:"string"==typeof o.env?o.env:"",rejected:"string"==typeof o.rejected&&o.rejected?o.rejected:null}}catch{return t}}function providerKeyFromEnv(e){if(!envFile||"function"!=typeof envFile.providerKeyFromEnv)return"";try{return envFile.providerKeyFromEnv(e).key||""}catch{return""}}const DEEPSEEK_REASONING_MODEL_RE=/^deepseek-(v4(\.\d+)?-(flash|pro)|flash|pro|reasoner)$/,EFFORT_TOKEN_BUDGET={low:8192,medium:16384,high:32768,max:32768},DEEPSEEK_EFFORT={low:"low",medium:"high",high:"high"},DEEPSEEK_EFFORT_EXTRA={max:"max"},EFFORT_IDENTITY={low:"low",medium:"medium",high:"high"},EFFORT_INERT_RE=/non-reasoning/i,EFFORT_DIALECTS=[{provider:"deepseek",re:DEEPSEEK_REASONING_MODEL_RE,field:"effort",map:DEEPSEEK_EFFORT,extra:DEEPSEEK_EFFORT_EXTRA},{provider:"openai",re:/^(gpt-5|o[0-9])/i,field:"reasoning_effort",map:EFFORT_IDENTITY},{provider:"groq",re:/^(openai\/gpt-oss|qwen\/qwen3)/i,field:"reasoning_effort",map:EFFORT_IDENTITY},{provider:"xai",re:/^grok-(4\.[5-9]|[5-9])/,field:"reasoning_effort",map:EFFORT_IDENTITY},{provider:"google",re:/^gemini-(2\.5|3|[4-9])/,field:"reasoning_effort",map:{...EFFORT_IDENTITY,medium:"high"}}],AUTONOMOUS_IDLE_TIMEOUT_MS=9e5;function reasoningBudget(e,t,o){const r=Number(t);return Number.isFinite(r)&&r>0?r:DEEPSEEK_REASONING_MODEL_RE.test(String(e||""))?EFFORT_TOKEN_BUDGET["low"===o||"medium"===o||"max"===o?o:"high"]:void 0}function nativeEffort(e,t,o){const r=String(t||"");if(EFFORT_INERT_RE.test(r))return;if(null===o)return;const n="low"===o||"medium"===o?o:"max"===o?"max":"high";for(const t of EFFORT_DIALECTS)if(t.provider===e&&t.re.test(r)){const e=Object.prototype.hasOwnProperty.call(t.map,n)?t.map[n]:t.extra&&Object.prototype.hasOwnProperty.call(t.extra,n)?t.extra[n]:void 0;if(void 0===e)return;return{field:t.field,level:e}}}function normalizeCatalog(e){return Array.isArray(e)?e.map(e=>"string"==typeof e?{id:e}:e).filter(e=>e&&e.id):[]}const{offerableCatalog:offerableCatalog}=requireSharedBrain(),{withByokAdditions:withByokAdditions,canonicalModelId:canonicalModelId,nexusFallbackModel:nexusFallbackModel}=requireSharedByokCatalog(),{withUserModels:withUserModels,unmatchedUserProviders:unmatchedUserProviders,load:loadUserModels,addUserModel:addUserModel,removeUserModel:removeUserModel}=requireSharedUserModels(),{withCatalog:withCatalog}=requireSharedCatalogClient(),{discoverModels:discoverVendorModels,canDiscover:canDiscoverVendorModels,endpointFor:vendorEndpointFor,discoverableProviders:discoverableProviders}=requireSharedModelDiscovery(),modelSync=requireSharedModelSync(),{createModelAutoSync:createModelAutoSync}=requireSharedModelAutoSync();function parseArgs(e){if(null==e)return{};if("object"==typeof e)return e;try{const t=JSON.parse(String(e));return t&&"object"==typeof t?t:{}}catch{return{}}}function extractToolCalls(e){if(!e)return[];if(Array.isArray(e.toolCalls)&&e.toolCalls.length)return e.toolCalls.map(e=>({id:e.id||"",name:e.name||"",args:parseArgs(e.args)})).filter(e=>e.name);const t=e.choices&&e.choices[0]&&e.choices[0].message,o=t&&t.tool_calls||[];return Array.isArray(o)?o.map(e=>{const t=e&&e.function||{};return{id:e&&e.id||"",name:t.name||e&&e.name||"",args:parseArgs(t.arguments)}}).filter(e=>e.name):[]}function proTurnPrompt(e){const t=Array.isArray(e.prompt)?flattenContent(e.prompt):e.prompt;if("string"==typeof t&&t.trim())return t;const o=Array.isArray(e.messages)?e.messages:[];for(let e=o.length-1;e>=0;e-=1){const t=o[e];if(!t||"user"!==t.role)continue;const r=flattenContent(t.content);if(r.trim())return r}return t}function assistantText(e){const t=e&&e.choices&&e.choices[0]&&e.choices[0].message;return t&&"string"==typeof t.content&&t.content||""}function finishReasonOf(e){const t=e&&e.choices&&e.choices[0];return t&&t.finish_reason||e&&e.stop_reason||""}function isTruncated(e){const t=finishReasonOf(e);return"length"===t||"max_tokens"===t}function reasoningTextOf(e){if(!e)return"";const t=e.choices&&e.choices[0],o=t&&t.message||{};if(Array.isArray(o.content)){const e=o.content.filter(e=>e&&("thinking"===e.type||"reasoning"===e.type)).map(e=>e.thinking||e.text||"").join("");if(e)return e}const r=o.content&&"object"==typeof o.content?o.content.reasoning_content:"",n=[o.reasoning_content,o.reasoning,t&&t.reasoning_content,e.reasoning_content,e.reasoning,r];for(const e of n)if("string"==typeof e&&e)return e;return""}function reasoningTokensOf(e){if(!e)return 0;const t=e.choices&&e.choices[0],o=t&&t.message||{},r=e.usage||{},n=r.completion_tokens_details||r.output_tokens_details||{},s=[o.thinking_tokens,o.reasoning_tokens,t&&t.thinking_tokens,e.thinking_tokens,n.reasoning_tokens,n.thinking_tokens];for(const e of s)if("number"==typeof e&&Number.isFinite(e)&&e>0)return e;return 0}function reasonedButSilent(e){return!assistantText(e)&&(""!==reasoningTextOf(e)||reasoningTokensOf(e)>0)}const REASONING_RETRY_FLOOR=32768;function retryBudgetFor(e,t){const o=doubledBudget(e.maxTokens);return t&&ladderRung(e.maxTokens)?Math.max(o,32768):o}function ladderRung(e){const t=Number(e);return Number.isFinite(t)&&Object.values(EFFORT_TOKEN_BUDGET).includes(t)}function doubledBudget(e){const t=Number(e)||0;return t>0?2*t:8192}function statedCapOf(e){const t=e=>{const t=Number(e);return Number.isFinite(t)&&t>0?t:void 0};return e&&Object.prototype.hasOwnProperty.call(e,"statedMaxTokens")?t(e.statedMaxTokens):t(e&&e.maxTokens)}const EMPTY_TURN_NUDGE="Your previous reply came back empty — it contained no answer and no tool call. Write your answer now, using only the information already gathered above. No tools are available in this reply, so do not call any: respond in plain prose or markdown.",THOUGHT_ONLY_NUDGE="Your previous round was spent entirely on hidden reasoning and produced no visible reply. Answer the user directly and briefly now. Do not reason, explain, or think first — write only the answer, no tools.",FINAL_ANSWER_NUDGE="Write your answer now, in plain prose, using only what is already in this conversation. If your information is incomplete, say what you have and what is missing — an incomplete answer is the expected outcome here and is better than none. No tools, no preface.",RECOVERY_ROUNDS=2,UNMUTATED_TURN_NUDGE="You ended the turn without changing any file, but this request asked for a change. The tools are still available in this reply: make the edit now with editFile or writeFile. If you already know what to change, change it — describing the fix is not the fix. If you genuinely cannot, say precisely what blocks you.",MUTATION_INTENT_RE=new RegExp("\\b(?:fix|implement|add|create|write|refactor|rename|remove|delete|replace|update|patch|migrate|convert|make\\s+(?:it|them|this|that|the|sure)|change|correct|resolve|repair|address|apply|introduce|support|wire\\s+up)\\b","i");function wantsMutation(e,t,o){if(t)return!1;if(!(o>0))return!1;const r=String(e||"");return!!r.trim()&&!/\?\s*$/.test(r.trim())&&MUTATION_INTENT_RE.test(r)}function emptyTurnError({cls:e,model:t,finishReason:o,reasoningChars:r,reasoningTokens:n,effort:s,recoveryRounds:a}){const i=Number(a)||0,l=Number(n)||0,c=new Error(`The model returned no answer after ${e}/${t} was asked to summarise its results`+(i?`, and ${i} extra recovery call${1===i?"":"s"} with a larger budget and a changed ask came back empty too`:"")+` (stop reason: ${o||"none"}`+(s?`, effort: ${s}`:"")+(r?`, hidden reasoning: ${r} chars and no visible text`:l>0?`, ~${l} thinking tokens billed and no visible text`:"")+"). "+(r||l>0?"Every one of those calls spent its output on hidden reasoning instead of writing a word, so this is the model rather than the budget: pick a model that answers without a thinking pass, or ask for a smaller piece of work.":"No visible text came back from any of those calls. Send the request again, in smaller pieces, or from a different model."));return c.status=502,c}function createLocalEngine({aegis:e,settings:t,tools:o,promptBuilder:r,recallProvider:n,env:s,getConfirmMode:a,getPermissionMode:i,sandbox:l,localTransport:c=localTransport,fetchImpl:d,gitScope:u,permissionRules:f}){const p=new Map,m=o||toolsModule,h=r&&r.buildSystemPrompt||promptModule.buildSystemPrompt,y=f&&"function"==typeof f.rulesVerdict?f.rulesVerdict:null,g=f&&"function"==typeof f.alwaysAllow?f.alwaysAllow:null,k=f&&"function"==typeof f.subjectFor?f.subjectFor:null,v=require("./session-rounds.js"),b=()=>{if("function"==typeof a)return!1!==a();if(t&&"function"==typeof t.getConfirmMode){const e=t.getConfirmMode();return void 0===e||Boolean(e)}return!0},w=()=>"function"==typeof i?"plan"===i():!(!t||"function"!=typeof t.getPermissionMode)&&"plan"===t.getPermissionMode();function E(e,t){return`${e} was not executed — this session is in plan mode (read-only). Plan mode may read files, search, run read-only shell commands and deploy subagents to research, but may not create, edit or delete files, run a mutating command, or install packages`+(t?` (this command: ${t})`:"")+". Do NOT retry it or attempt the same effect by another route. Finish your research and present a plan in plain text; the user exits plan mode (`/permissions mode off`) before any edit can run."}const S=new Map,_=new Map,T=new Map,x=new Map,A=require("./pro-sessions.js"),M=new Map,O=new Map;function N(e,t){if("function"!=typeof k)return e;let o="";try{o=String(k(e,t||{})||"")}catch{o=""}return`${e}\0${o}`}function F(e,t,o){S.has(e)||S.set(e,new Set),S.get(e).add(N(t,o))}function D(e,t){const o=_.get(e);return Boolean(o&&o.has(t))}function R(e,t){_.has(e)||_.set(e,new Set),_.get(e).add(t)}function U(e){if(!e)return null;try{return{existed:!0,content:fs.readFileSync(e,"utf8")}}catch(e){return e&&"ENOENT"===e.code?{existed:!1,content:null}:null}}function I(e){return`${e} was not executed — the user denied this tool for this conversation. Do NOT retry it and do NOT attempt the same effect by another route (another command, a writeFile instead of an edit, a subagent). Stop calling tools and reply in plain text: say what you were trying to do, what you need, and that the user can re-enable ${e} to let it proceed.`}function L(e,t,o,r){return new Promise(n=>{if(o&&o.aborted)return void n("cancel");const s=randomUUID();let a=!1;const i=()=>l("cancel"),l=e=>{a||(a=!0,M.delete(s),o&&o.removeEventListener("abort",i),n(e))};o&&o.addEventListener("abort",i,{once:!0}),M.set(s,{resolve:l}),"function"==typeof t?t({delta:"",approval:{id:s,sessionId:e,tool:r.tool,args:r.args,diff:r.diff||null,canPersist:"function"==typeof g}}):l("cancel")})}function C(e,t,o,r){return new Promise(n=>{if(o&&o.aborted)return void n(!1);const s=randomUUID();let a=!1;const i=()=>l(!1),l=e=>{a||(a=!0,O.delete(s),o&&o.removeEventListener("abort",i),n(e))};o&&o.addEventListener("abort",i,{once:!0}),O.set(s,{resolve:l}),"function"==typeof t?t({delta:"",rounds:{id:s,sessionId:e,spent:r.spent,extensions:r.extensions,max:r.max,size:r.size}}):l(!1)})}async function P(e,t,o,r,n){const s=normalizeToolArgs(m,e,t,o||{});if(!s.ok)return{ok:!1,error:s.error};t=s.args;const a=o&&o.guard;if(a&&"exec"===e){const e=blocksDestructive(a,t&&t.command);if(!e.ok)return{ok:!1,error:e.reason}}const i=o&&o.repeat,l=i?repeatGuard.check(i,e,t):null;if(l&&"refuse"===l.action)return{ok:!1,error:l.error};const c=covenant.preActionAssert({tool:e,args:t||{}});if(!c.allowed){const o=covenant.bindRefusal({tool:e,args:t||{}},c);return{ok:!1,error:`refused by the ÆGIS covenant — ${c.clause} (${c.label}): ${c.reason}`,covenant:o}}const d="writeFile"===e||"editFile"===e,u=d?U(t&&t.file_path):null,f=await m.executeTool(e,t,o);a&&d&&f&&!1!==f.ok&&recordWrite(a,t&&t.file_path),i&&d&&f&&!1!==f.ok&&repeatGuard.recordWrite(i,t&&t.file_path);const p=o&&o.verify;if(p&&(verifyGuard.EXEC_TOOLS.has(e)&&f&&!1!==f.ok?verifyGuard.recordExec(p):d&&f&&!1!==f.ok&&verifyGuard.recordMutation(p,t&&t.file_path)),d&&u&&f&&!1!==f.ok){const o=U(t&&t.file_path);o&&function(e,t){if(!e)return;T.has(e)||T.set(e,[]);const o=T.get(e);o.push(t),o.length>200&&o.shift()}(r,{id:n||randomUUID(),tool:e,path:t&&t.file_path,before:u,after:o,at:Date.now()})}return l&&l.note?$(f,l.note):f}function $(e,t){if(!e||"object"!=typeof e)return{ok:!0,content:`${t}\n${null==e?"":e}`};if(!1===e.ok||!0===e.isError){const o=e.error||e.content||"";return{...e,error:`${t}\n${o}`,content:`${t}\n${o}`}}const o=null!=e.content?e.content:null!=e.output?e.output:"";return{...e,content:`${t}\n${o}`}}async function q(e,{toolCtx:t,rootSessionId:o,rootOnDelta:r,signal:n}){const{name:s}=e,a=normalizeToolArgs(m,s,e.args,t||{});if(!a.ok)return{ok:!1,error:a.error};const i=a.args;if(!m.MUTATING_TOOLS.has(s))return P(s,i,t,o,e.id);if(w()){if("exec"===s){const r=planExec(i&&i.command,{baseCwd:t&&t.cwd||void 0});return r.oneShot?P(s,i,t,o,e.id):{ok:!1,error:E(s,r.reason)}}return{ok:!1,error:E(s)}}if(!b())return P(s,i,t,o,e.id);if(function(e,t,o){const r=S.get(e);return Boolean(r&&r.has(N(t,o)))}(o,s,i))return P(s,i,t,o,e.id);if("function"==typeof y){let r;try{r=y(s,i)}catch(e){r={verdict:null,source:"error",error:e&&e.message||String(e)}}if(r&&"deny"===r.verdict)return R(o,s),{ok:!1,error:I(s),permissionRule:r.rule||null};if(r&&"allow"===r.verdict)return P(s,i,t,o,e.id)}if(D(o,s))return{ok:!1,error:I(s)};let l=null;if(("writeFile"===s||"editFile"===s)&&(l=m.previewMutation(s,i,t||{}),!l.ok))return{ok:!1,error:l.error};const c=await L(o,r,n,{tool:s,args:i,diff:l&&l.diff});if("deny"===c)return R(o,s),{ok:!1,error:I(s)};if("session"!==c&&"once"!==c&&"always"!==c)return{ok:!1,error:`${s} was not executed — the request was cancelled.`};let d=null;if("always"===c){let e=null;if("function"==typeof g)try{e=g(s,i)}catch(t){e={ok:!1,reason:t&&t.message||String(t)}}else e={ok:!1,reason:"no durable store is wired on this host"};d=e&&e.ok?`[permission_rule] stored ${e.rule} — this command will not ask again`:`[permission_rule] nothing was stored — ${e&&e.reason||"unknown reason"}; this call was allowed once only`}if("session"===c&&F(o,s,i),l){const e=m.applyChecked(s,i,l,t||{});return e&&!1!==e.ok&&t&&t.guard&&recordWrite(t.guard,i&&i.file_path),d?$(e,d):e}const u=await P(s,i,t,o,e.id);return d?$(u,d):u}function j(e){return hostEnv(s||{},e&&e.env||{},e)}function B(e){const t=[],o=e=>String(e||"").replace(/[\\/]+$/,""),r=o(e),n=e=>{const n=o(e);n&&n!==r&&!t.includes(n)&&t.push(n)};let s=u;if(void 0===s)try{s=require("./git-scope.js")}catch{s=null}try{s&&"function"==typeof s.gitRoot&&n(s.gitRoot(e))}catch{}try{credentialsLib&&"function"==typeof credentialsLib.aegisHome&&n(credentialsLib.aegisHome())}catch{}return t}async function G(t,o){if("aegis"===t){const t=!o.singlePass&&(!!o.autonomous||void 0);return e.chatCompletion({prompt:o.prompt,system:o.system,messages:o.messages,model:o.model,mode:o.mode,maxTokens:o.statedMaxTokens,stream:!1!==o.stream,includeUsage:!0,onStream:o.onDelta,onReasoning:o.onReasoning,idleTimeoutMs:o.idleTimeoutMs,signal:o.signal,extra:{aegis_recall:!0,...o.recallDeep?{aegis_recall_deep:!0}:{},session:o.sessionId,...void 0===t?{}:{brain:t},...!1===t?{mode:"brain"}:{},...o.effort?{effort:o.effort}:{},...!0===t&&o.workers?{workers:o.workers}:{},...o.tools.length?{tools:o.tools}:{},...o.toolChoice?{tool_choice:o.toolChoice}:{}},agentKey:o.tools.length&&(process.env.AEGIS_AGENT_KEY||"").trim()||void 0})}if("byok"===t){const{provider:t,model:r}=splitByokModel(o.model),n=canonicalModelId(t,r),s=nativeEffort(t,n,o.effort);try{return await e.byokChatCompletion({provider:t,model:n,providerKey:o.apiKey,baseURL:o.cfg&&o.cfg.baseURL,prompt:o.prompt,system:o.system,messages:o.messages,maxTokens:o.maxTokens,tools:o.tools,toolChoice:o.toolChoice,effort:s&&"effort"===s.field?s.level:void 0,reasoningEffort:s&&"reasoning_effort"===s.field?s.level:void 0,stream:!0,onStream:o.onDelta,signal:o.signal})}catch(e){if(e&&402===e.status){const e=new Error("byok: this account has no AEGIS balance left, and the BYOK handling fee is billed there — your provider key is still valid, this is not a key problem. Top up the account, then try again (or /class aegis to use the pooled lane).");throw e.status=402,e}throw e}}if("local"===t){const e=o.cfg&&o.cfg.baseURL||c.DEFAULT_BASE,t=t=>c.chat({baseURL:e,model:o.model,prompt:o.prompt,system:o.system,messages:o.messages,maxTokens:o.maxTokens,signal:o.signal,onDelta:o.onDelta,...t&&o.tools.length?{tools:o.tools,toolChoice:o.toolChoice}:{}});try{return await t(!0)}catch(e){if(o.tools.length&&e&&400===e.status)return t(!1);throw e}}if("pro"===t){const e=o.sessionKey||o.rootSessionId||o.sessionId;let t=null;if(e&&(t=x.get(e)||null,!t)){try{t=A.get(e,s)||null}catch{}t&&x.set(e,t)}const r=B(o.cwd),n=e=>claudePro.runClaudePro({prompt:proTurnPrompt(o),model:o.model&&"default"!==o.model?o.model:void 0,system:o.system,cwd:o.cwd,addDir:r,resumeSessionId:e||void 0,gate:b(),onAsk:async e=>{if(!e||!e.requestId)return"deny";const t=o.rootSessionId,r=o.rootOnDelta,n=PRO_TOOL_MAP[String(e.toolName||"")]||null,s=n||String(e.toolName||"unknown"),a=proAskArgs(e.input||{},s),i=covenant.preActionAssert({tool:s,args:a});if(!i.allowed)return r&&r({delta:"",note:`aegis: refused by the ÆGIS covenant — ${i.clause} (${i.label}): ${i.reason}`}),"deny";if(w()){if("exec"===s){const e=planExec(a&&a.command,{baseCwd:o.cwd||void 0});return e.oneShot?"once":(r&&r({delta:"",note:E(s,e.reason)}),"deny")}if(n&&m.MUTATING_TOOLS.has(s))return r&&r({delta:"",note:E(s)}),"deny";if(!n&&!PRO_PLAN_MODE_SAFE.has(s))return r&&r({delta:"",note:E(s)}),"deny"}if(!b())return"once";if("function"==typeof y){let e;try{e=y(s,a)}catch{e=null}if(e&&"deny"===e.verdict)return r&&r({delta:"",note:I(s)}),"deny";if(e&&"allow"===e.verdict)return"once"}if(D(t,s))return r&&r({delta:"",note:I(s)}),"deny";const l=await L(t,r,o.signal,{tool:s,args:a,diff:null});if("deny"===l)return R(t,s),"deny";if("session"!==l&&"once"!==l&&"always"!==l)return"deny";if("session"===l&&F(t,s,a),"always"===l&&"function"==typeof g)try{g(s,a)}catch{}return l},signal:o.signal,onDelta:o.onDelta,onSpawn:(e,t)=>{o.onDelta&&t&&o.onDelta({delta:"",note:claudePro.childLine(t)})}});let a=await n(t);if(a&&a.resumeStale){x.delete(e);try{A.del(e,s)}catch{}o.onDelta&&o.onDelta({delta:"",note:"aegis: the remembered Claude session no longer exists on this machine — continuing as a new conversation (earlier turns are not in its context)"}),a=await n(null)}if(e&&a&&a.sessionId&&!a.error){x.set(e,a.sessionId);try{A.set(e,a.sessionId,s)}catch{}}return a}throw new Error(`dispatch: unknown model class ${JSON.stringify(t)} — this build ships 'aegis', 'byok', 'local' and 'pro' only`)}async function K(o,r){const s=o&&o.class,a=o&&o.model,i=reasoningBudget("byok"===s?splitByokModel(a).model:a,o&&o.maxTokens,o&&o.effort),d=statedCapOf(o),u="aegis"===s&&Boolean(o&&o.autonomous),f=Boolean(o&&o.roundsAsk),y=o&&o.sessionId||randomUUID(),g=Number.isInteger(o&&o.depth)?o.depth:0,k=o&&o.rootSessionId||y,b=o&&o.rootOnDelta||r,w="function"==typeof r?e=>e&&r({reasoning:e}):void 0,E=new AbortController,S=p.get(y)||null;p.set(y,E);const _=E.signal,T=!(o&&!1===o.tools),x=T?m.toolsFor({includeSubagent:g<4}):[],A=o&&o.toolChoice||null,M=o&&o.system||h(j(o)),O=n?await n({payload:o,env:j(o),system:M}):null,N="string"==typeof O?O:O&&"string"==typeof O.system?O.system:M,F=Array.isArray(o&&o.messages)?o.messages.filter(Boolean).slice():[];let D=F.length,R=o&&o.prompt||"";const U=String(R||""),I=Array.isArray(o&&o.attachments)?o.attachments.filter(e=>e&&"object"==typeof e).slice(0,attachmentsModule.MAX_ATTACHMENTS):[];let L=I.length?attachmentsModule.buildContent(R,I):R,P=null;const $=j(o),K=((e,t)=>{if(null==l)return null;const o="function"==typeof l.policy?l.policy():l.policy;if(!o)return null;const r=require("./sandbox.js"),n=e&&e.cwd||process.cwd(),s=r.normalize(o,n);if("off"===s.mode)return null;let a=[];try{let e=null;try{e=require("node:os").homedir()}catch{e=null}a=r.autoGrants(n,{home:e,addDirs:(()=>{try{return B(n)}catch{return[]}})()})}catch{a=[]}if(a.length){const e=new Set;for(const t of s.fileSystem.entries)t&&t.path&&"path"===t.path.type&&t.path.path&&e.add(`${t.access}:${t.path.path}`);for(const t of a){const o=`${t.access}:${t.path.path}`;e.has(o)||(e.add(o),s.fileSystem.entries.push(t))}}return"local"===t&&"restricted"===s.network&&(s.network="open",s.networkExempt="local"),{policy:s,state:l.state||r.detect({appDir:l.appDir}),workspace:n,appDir:l.appDir,strict:!0===l.strict}})($,s),W=$.cwd,z={getShell:()=>P||(P=new ShellSession({cwd:$.cwd,sandbox:K})),signal:_,cwd:W,desktopdir:$.desktopdir,sandbox:K,repeat:repeatGuard.beginRepeatGuard({cwd:W}),verify:verifyGuard.beginVerifyGuard({cwd:W}),guard:beginTurnGuard(W)};try{const n="byok"===s?splitByokModel(a):null;let l=null;const p="byok"===s?t.get(byokNamespace(n.provider))||{}:"local"===s&&t.get("local")||{},h="byok"===s?t.rawKey(byokNamespace(n.provider)):null,E="byok"!==s?null:h||providerKeyFromEnv(n.provider);if(!("byok"!==s||n.provider&&n.model)){const e=new Error('byok: model must be "<provider>:<model>" (pick one from /models) — got '+JSON.stringify(a||""));throw e.status=400,e}if("byok"===s&&!E){const t="anthropic"===n.provider?claudePro.claudeProStatus({env:process.env}):null,o=providerKeyRecord(n.provider).rejected,r=nexusFallbackModel({provider:n.provider,providerKey:E,providerKeyRefused:o,aegisKey:E?"":e.apiKey});if(!r){const e=new Error(o?`${o}. That is why this turn has no ${n.provider} key: an env value that short is a paste that lost its payload, not a credential. Fix ${o.split(" ")[0]} in ~/.aegiscode/.env (or the shell that exported it) — or skip keys entirely: /byok-key ${n.provider} <key> to set one here.`:t&&t.loggedIn?`No Anthropic API key on this machine — an "anthropic:…" id is served by your own console key, which a Claude subscription is not. Use the subscription instead: /class pro (it spends your Claude Code ${t.subscription||"Pro"} plan through the claude CLI) — or add a real console key: /byok-key anthropic <key>.`:`No key for "${n.provider}" yet. Easiest fix: /class aegis (uses your AEGIS key, no setup) — or add this provider's own key: /byok-key ${n.provider} <key>.`);throw e.status=400,e}l={from:n.provider,model:r}}if("byok"===s&&!e.apiKey){const e=new Error("No AEGIS key connected yet. Easiest fix: /class aegis (skips BYOK entirely) — or add your AEGIS key with /login, then try again.");throw e.status=401,e}if("local"===s){const e=c.remoteRefusal(p.baseURL||c.DEFAULT_BASE);if(e)throw e}if("byok"===s&&"custom"===n.provider&&!(p.baseURL||"").trim()){const e=new Error('No endpoint saved for the "custom" provider — its key is on this machine but the address it dials is not, and no default exists for a vendor AEGIS does not know. Fix: /model-add custom <https-base-url> <api-key> <model-id> (writes both halves), or the endpoint field in Settings › Provider (custom).');throw e.status=400,e.code="custom_endpoint_missing",e}const S=l?"aegis":s,M={cls:S,model:l?l.model:a,mode:o&&o.mode,maxTokens:i,statedMaxTokens:d,autonomous:u,sessionId:y,signal:_,onDelta:r,cfg:p,apiKey:E,toolChoice:A,pooledFrom:l?l.from:void 0,cwd:W,rootSessionId:k,sessionKey:o&&o.sessionKey||void 0,rootOnDelta:b,effort:o&&o.effort,workers:o&&o.workers,recallDeep:o&&!0===o.recallDeep,singlePass:o&&!0===o.singlePass,onReasoning:w,idleTimeoutMs:u?9e5:void 0,stream:!o||!1!==o.stream};let O=!1,P=!1;const $=u?"AEGIS_AUTONOMOUS_MAX_ROUNDS":"AEGIS_CHAT_MAX_ROUNDS",j=(()=>{const e=Number.parseInt(process.env[$]||"",10);return Number.isFinite(e)&&e>0?e:0})(),B=j||(u?40:24);let K=v.keyFor(o,F),V=v.take(K);if(!V&&!v.isStatedKey(o)){const e=v.adopt();e&&(V=e.entry,K=e.key)}if(V){const e=v.resumePreamble(V);0===F.length?Array.isArray(V.messages)&&V.messages.length&&F.push(...V.messages):Array.isArray(V.added)&&V.added.length&&F.push(...V.added),R?(R=`${e}\n\n${R}`,L=I.length?attachmentsModule.buildContent(R,I):R):(F.push({role:"user",content:e}),L=""),b&&b({delta:`\n\n[resuming work this session left unfinished at ${V.rounds} tool rounds`+(V.interruptions>1?` (cut off ${V.interruptions}×)`:"")+"…]\n"})}let H=j||B+(V?v.bonus(B):0),X=0;const J=B,Q=8;let Z=0;const ee={calls:0},te=["input_tokens","output_tokens","prompt_tokens","completion_tokens","total_tokens","cache_read_input_tokens","cache_creation_input_tokens","prompt_cache_hit_tokens","prompt_cache_miss_tokens","reasoning_tokens","thinking_tokens"],oe=e=>{const t=e&&e.usage;if(t&&"object"==typeof t){ee.calls+=1;for(const e of te)"number"==typeof t[e]&&Number.isFinite(t[e])&&(ee[e]=(ee[e]||0)+t[e]);if("number"!=typeof t.total_tokens){const e=(t.prompt_tokens??t.input_tokens??0)+(t.completion_tokens??t.output_tokens??0);e&&(ee.total_tokens=(ee.total_tokens||0)+e)}}},re=e=>{if(!e||"object"!=typeof e)return e;const t=l?{...e,pooled_from:l.from,pooled_model:l.model,pooled_notice:requireSharedByokCatalog().nexusFallbackNotice({pooled_from:l.from,pooled_model:l.model})}:e;return ee.calls?{...t,usage:{...ee}}:t},ne=()=>{if(""===L)return;const e=F[F.length-1],t=e&&"user"===e.role?flattenContent(e.content):null;e&&"user"===e.role&&t===flattenContent(L)||F.push({role:"user",content:L}),R="",L=""};D=F.length;const se=m&&m.MUTATING_TOOLS||new Set;let ae=0,ie=0,le=!1,ce=!1;for(;;){if(X>=H){if(f&&Z<Q&&!_.aborted&&await C(k,b,_,{spent:H,extensions:Z+1,max:Q,size:J})){Z+=1;const e=H;H+=J,F.push({role:"user",content:`You have used all ${e} tool rounds allowed for this turn; ${J} more have been granted (do not restart). Continue the task from exactly where you stopped — do not re-plan, do not repeat work already done, and finish with an answer.`});continue}const e=f?"":`, or raise ${$} for a longer single turn`,t=`[stopped at ${H} tool rounds`+(ee.total_tokens?`, ${ee.total_tokens.toLocaleString()} tokens`:"")+". This session holds the work: your next message here resumes it automatically"+` (with a continuation preamble)${e}.]`,o=v.record(K,{rounds:X,tokens:ee.total_tokens||0,note:t,chain:V?V.interruptions:0,messages:F,added:F.slice(D)});return b&&b({delta:`\n\n${t}`}),re({model:M.model,choices:[{message:{content:t},finish_reason:"length"}],stoppedOnRounds:!0,heldForSession:!0,heldRounds:o.rounds,sessionInterruptions:o.interruptions,resumedFrom:K})}X+=1;const e={...M,system:N,messages:F,prompt:L,tools:x,recallDeep:M.recallDeep&&1===X};let t;if(t=await G(S,e),oe(t),_.aborted)return re(t);if(!O&&!assistantText(t)&&(isTruncated(t)||reasonedButSilent(t))){O=!0;const o=reasonedButSilent(t);if(t=await G(S,{...e,singlePass:!0,recallDeep:!1,effort:o?"high":e.effort,maxTokens:retryBudgetFor(e,o),statedMaxTokens:e.statedMaxTokens?doubledBudget(e.statedMaxTokens):void 0}),oe(t),_.aborted)return re(t)}const n=x.length?extractToolCalls(t):[];if(!n.length){if(assistantText(t)||P||!T){if(!le&&T&&wantsMutation(U,ie>0,ae)){le=!0,ne(),F.push({role:"assistant",content:assistantText(t)}),F.push({role:"user",content:UNMUTATED_TURN_NUDGE}),b&&b({delta:""});continue}if(z.verify&&!ce){const e=verifyGuard.shouldNudge(z.verify);if(e.nudge){ce=!0,ne(),F.push({role:"assistant",content:assistantText(t)}),F.push({role:"user",content:e.text}),b&&b({delta:""});continue}}return re(t)}P=!0,ne(),F.push({role:"user",content:reasonedButSilent(t)?THOUGHT_ONLY_NUDGE:EMPTY_TURN_NUDGE});const o={...e,singlePass:!0,recallDeep:!1,messages:F,prompt:"",tools:[]};t=await G(S,o);let r=o.maxTokens,n=o.effort;if(oe(t),_.aborted)return re(t);if(!assistantText(t)&&(isTruncated(t)||reasonedButSilent(t))){const e=reasonedButSilent(t);if(r=retryBudgetFor(o,e),n=e?"high":o.effort,t=await G(S,{...o,effort:n,maxTokens:r,statedMaxTokens:o.statedMaxTokens?doubledBudget(o.statedMaxTokens):void 0}),oe(t),_.aborted)return re(t)}const i=(()=>{const e=Number(r)||0;if(!e)return r;const t={maxTokens:r};return o.statedMaxTokens&&(t.statedMaxTokens=o.statedMaxTokens),Math.max(e,retryBudgetFor(t,!0))})();let l=0;for(;!assistantText(t)&&l<2&&!_.aborted;){const e=reasonedButSilent(t);if(l+=1,F.push({role:"user",content:e?1===l?THOUGHT_ONLY_NUDGE:FINAL_ANSWER_NUDGE:EMPTY_TURN_NUDGE}),e&&(n="high"),r=i,t=await G(S,{...o,messages:F,effort:n,maxTokens:r,statedMaxTokens:o.statedMaxTokens?doubledBudget(o.statedMaxTokens):void 0}),oe(t),_.aborted)return re(t)}if(!assistantText(t))throw emptyTurnError({cls:s,model:a,effort:n,recoveryRounds:l,finishReason:finishReasonOf(t),reasoningChars:reasoningTextOf(t).length,reasoningTokens:reasoningTokensOf(t)});return re(t)}ne(),F.push({role:"assistant",content:assistantText(t),tool_calls:n.map(e=>({id:e.id,type:"function",function:{name:e.name,arguments:JSON.stringify(e.args)}}))});const i=new WeakMap,l=e=>{if("exec"!==e.name)return null;if(i.has(e))return i.get(e);const t=planExec(e.args&&e.args.command,{baseCwd:W});return i.set(e,t),t},c=e=>{if(!se.has(e.name))return!0;const t=l(e);return Boolean(t&&t.oneShot)},u=[];for(const e of n){const t=u[u.length-1];c(e)&&t&&t.parallel?t.calls.push(e):u.push({parallel:c(e),calls:[e]})}const p=async e=>{r&&r({delta:"",tool:{name:e.name,args:e.args,id:e.id,cwd:W,phase:"run"}});const t=l(e),n=t&&t.oneShot?{...z,oneShotExec:!0,cwd:t.cwd||z.cwd}:z,i=e.name===m.SUBAGENT_TOOL?await Y(e.args,{cls:s,model:a,statedMaxTokens:d,effort:o&&o.effort,mode:o&&o.mode,parentSignal:_,depth:g,rootSessionId:k,rootOnDelta:b}):await q(e,{toolCtx:n,rootSessionId:k,rootOnDelta:b,signal:_});return i&&i.usage&&oe({usage:i.usage}),r&&r({delta:"",tool:{name:e.name,args:e.args,ok:i.ok,id:e.id,cwd:W,phase:"done"}}),i};for(const e of u){const t=e.parallel&&e.calls.length>1?await Promise.all(e.calls.map(e=>p(e))):[await p(e.calls[0])];e.calls.forEach((e,o)=>{const r=t[o];se.has(e.name)&&(ae+=1,r&&r.ok&&(ie+=1)),F.push({role:"tool",tool_call_id:e.id,name:e.name,content:m.toolResultText(r)})})}}}catch(e){throw _.aborted&&e&&"object"==typeof e&&(e.aegisCancelled=!0),e}finally{P&&P.dispose(),p.get(y)===E&&(S&&!S.signal.aborted?p.set(y,S):p.delete(y))}}async function Y({description:e,subagent_type:t,prompt:o}={},{cls:r,model:n,statedMaxTokens:s,effort:a,mode:i,parentSignal:l,depth:c,rootSessionId:d,rootOnDelta:u}={}){const f=String(o||e||"").trim();if(!f)return{ok:!1,error:"task requires a prompt"};const p=t&&"general"!==t?agentRoleLabel(t):"general",m=agentSystemPrompt(t),h=randomUUID();let y;if(l){if(l.aborted)return{ok:!1,error:"aborted"};y=()=>W(h),l.addEventListener("abort",y,{once:!0})}try{const e=await K({class:r,model:n,mode:i,system:m,prompt:f,sessionId:h,depth:(c||0)+1,rootSessionId:d,rootOnDelta:u,statedMaxTokens:s,effort:a},()=>{}),t=assistantText(e),o=e&&e.usage?{usage:e.usage}:{};return t?{ok:!0,output:t,...o}:{ok:!1,error:`subagent (${p}) produced no output`,...o}}catch(e){return{ok:!1,error:`subagent (${p}) failed: ${e&&e.message?e.message:e}`}}finally{l&&y&&l.removeEventListener("abort",y)}}function W(e){const t=p.get(e);return t&&t.abort(),{ok:Boolean(t)}}function z(e){const o=String(null==e?"":e).trim().toLowerCase();if(!o)return"";try{if(t&&"function"==typeof t.rawKey){const e=t.rawKey(byokNamespace(o));if("string"==typeof e&&e.trim())return e.trim()}}catch{}return providerKeyFromEnv(o)}async function V(t){let o=[];try{const t=await e.byokProviders();o=withUserModels(withCatalog(withByokAdditions(t&&t.providers||[])))}catch(e){return{ok:!1,providers:[],missing:0,stale:0,skipped:[],failed:[],error:e&&e.message||String(e)}}const r={};for(const e of modelSync.askableProviders(o,t)){const t=z(e);t&&(r[e]=t)}return modelSync.plan(o,{keys:r,fetchImpl:d,only:t})}const H=createModelAutoSync({getPref:()=>{try{return t&&"function"==typeof t.getSharedPref?t.getSharedPref("modelAutoSync"):null}catch{return null}},plan:e=>V(e),apply:(e,t)=>modelSync.apply(e,{only:t})});return{CLASSES:CLASSES,listClasses:async function(){return CLASSES.map(o=>{if("aegis"===o.class)return{...o,configured:Boolean(e.apiKey)};if("byok"===o.class){const e=(t.list()||[]).some(e=>!(!e||"string"!=typeof e.provider||!e.provider.startsWith("byok:"))&&(!!e.configured||Boolean(providerKeyFromEnv(e.provider.slice(5)))));return{...o,configured:e}}if("local"===o.class)return{...o,configured:!0};if("pro"===o.class){const e=claudePro.claudeProStatus({env:process.env}),t=claudePro.seamAvailable();return{...o,configured:e.loggedIn,status:e,seam:t}}return{...o,configured:!1}})},listModels:async function(o){if("aegis"===o){if(!e.apiKey)return{class:o,models:[],needsKey:!0};const t=await e.listModels();return{class:o,models:offerableCatalog(normalizeCatalog(t&&t.models))}}if("byok"===o){let r=[],n=null,s=!1,a=null;try{const t=await e.byokProviders();r=withUserModels(withCatalog(withByokAdditions(t&&t.providers||[]))),n=t&&t.fee||null}catch(e){r=[],s=!0,a=e&&e.message||String(e)}const i=[];for(const e of r){if(!e||!e.id)continue;const o=t.get(byokNamespace(e.id))||{},r=providerKeyRecord(e.id),n=r.key||"",s=Array.isArray(e.models)?e.models:[];for(const t of s){const s="string"==typeof t?t:t&&t.id;s&&i.push({id:`${e.id}:${s}`,label:`${e.label||e.id} — ${s}`,provider:e.id,configured:Boolean(o.configured||n),keyRejected:r.rejected||null})}}return{class:o,models:i,providers:r,needsProviderKey:i.length>0&&!i.some(e=>e.configured),needsAegisKey:!e.apiKey,fee:n,providersFailed:s,providersError:a,unmatchedProviders:unmatchedUserProviders(r)}}if("local"===o){const e=(t.get("local")||{}).baseURL||c.DEFAULT_BASE,r=await c.probe(e);if(!r.running)return{class:o,models:[],baseURL:r.baseURL,needsDaemon:!0};let n=[],s=!0;try{n=await c.listTags(e)}catch{s=!1}return{class:o,models:n,baseURL:r.baseURL,listed:s}}if("pro"===o){const e=claudePro.claudeProStatus({env:process.env});return{class:o,models:claudePro.PRO_MODELS.map(t=>({id:t.id,label:t.label,note:t.note,configured:e.loggedIn})),needsProviderKey:!1,needsAegisKey:!1,subscription:e.subscription,loggedIn:e.loggedIn,credentialFile:e.file,shadowed:e.shadowed||null,seam:claudePro.seamAvailable()}}throw new Error(`listModels: unknown model class ${JSON.stringify(o)} — this build ships 'aegis', 'byok', 'local' and 'pro' only`)},chat:K,cancel:W,respondApproval:function(e,t){const o=M.get(e);return o?(M.delete(e),o.resolve("session"===t||"once"===t||"always"===t?t:"deny"),{ok:!0}):{ok:!1}},respondRoundsAsk:function(e,t){const o=O.get(e);return o?(O.delete(e),o.resolve(!0===t||"continue"===t),{ok:!0}):{ok:!1}},clearSessionApprovals:function(e){S.delete(e),_.delete(e),T.delete(e),x.delete(e);try{A.del(e,s)}catch{}return{ok:!0}},listUndoable:function(e){return(T.get(e)||[]).map(e=>({id:e.id,tool:e.tool,path:e.path,at:e.at})).reverse()},undoMutation:function(e,t){const o=T.get(e)||[],r=t?o.findIndex(e=>e.id===t):o.length-1;if(-1===r)return{ok:!1,error:t?`no undo record "${t}" for this conversation`:"nothing to undo in this conversation"};const n=o[r],s=U(n.path);if(!s||s.existed!==n.after.existed||s.content!==n.after.content)return{ok:!1,error:`${n.path} has changed since ${n.tool} ran — undo refused rather than overwriting work this session did not do. Resolve it by hand, or undo a different entry.`};try{n.before.existed?fs.writeFileSync(n.path,n.before.content,"utf8"):fs.unlinkSync(n.path)}catch(e){return{ok:!1,error:`undo failed: ${e&&e.message||e}`}}return o.splice(r,1),{ok:!0,path:n.path,restored:n.before.existed?"content":"deleted"}},settings:t,unloadLocalModels:function(){return c.unloadAll()},userModels:()=>loadUserModels(),addUserModel:(e,t)=>addUserModel(e,t),removeUserModel:(e,t)=>removeUserModel(e,t),discoverModels:async e=>{const t=String(null==e?"":e).trim().toLowerCase(),o=z(t),r=await discoverVendorModels(t,{key:o,fetchImpl:d});if(!r||!r.ok)return r;const n=[];try{const e=loadUserModels().map;for(const o of Array.isArray(e[t])?e[t]:[])n.push(o)}catch{}return{...r,declared:n,endpoint:(vendorEndpointFor(t)||{}).url||""}},modelSyncPlan:async e=>V(e),modelSyncApply:(e,t)=>modelSync.apply(e,{only:t}),modelAutoSync:H,modelAutoSyncRun:e=>H.runIfDue(e),modelAutoSyncStatus:()=>H.status(),addUserModels:(e,t)=>{const o=Array.isArray(t)?t:[],r={provider:e,added:0,already:[],failed:[],capped:0,file:""};for(const t of o)try{const o=addUserModel(e,t);r.file=o.file||r.file,o.added?r.added+=1:r.already.push(o.model)}catch(e){const n=e&&e.message||String(e);if(/the cap/.test(n)){r.capped=o.length-r.added-r.already.length-r.failed.length;break}r.failed.push({id:String(t),reason:n})}return r},canDiscoverModels:e=>canDiscoverVendorModels(e),discoverableProviders:()=>discoverableProviders()}}module.exports={CLASSES:CLASSES,createLocalEngine:createLocalEngine,extractToolCalls:extractToolCalls,parseArgs:parseArgs,reasoningBudget:reasoningBudget,nativeEffort:nativeEffort,hostEnv:hostEnv};
@@ -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 FREE_MAX_WORKERS=1,PAID_PLANS=Object.freeze(["pro","unlimited"]),TIER_NAMES=Object.freeze({pro:"Pro",unlimited:"Unlimited"});function tierName(e){return TIER_NAMES[normalizePlan(e)]||null}const LEGACY_PLAN_ALIASES=Object.freeze({cloud:"pro",memory:"pro",s:"pro",heavy:"pro",team:"pro",starter:"free"}),PRO_VALUE="Pro puts the drain in the cloud, so the job keeps running after you close the laptop",FREE_HONESTY="Everything on your machine is free, permanently. The cloud drain is what you pay for.",BYOK_FEE_NOTE="Bring your own key is relayed through AEGIS, not dialled from here — the routing, prompt assembly and caching are billed as a flat handling fee, on top of your provider's own bill.";function ratePerMillion(e){return`$${(1e3*Number(e)).toFixed(2)}/M`}function byokFeeLine(e){const n=e&&"object"==typeof e?e:null;if(!n)return"";const r=Number(n.in_usd_per_1k),a=Number(n.out_usd_per_1k);if(!Number.isFinite(r)||!Number.isFinite(a))return"";if(!0===n.disabled)return"Bring your own key is relayed free on this deployment right now.";const o=`Bring your own key: relayed through AEGIS, handled at ${ratePerMillion(r)} in / ${ratePerMillion(a)} out, on top of your provider's bill — no fee at all on Unlimited, and no fee at all during the free 1-month Unlimited trial`;let l="";if(!0===n.require_account)l="and needs an AEGIS account key (X-AEGIS-Key) for the fee to be billed";else{const e=Number(n.anonymous_daily_calls);Number.isFinite(e)&&e>0&&(l=`with ${e} relayed turns/24h before an AEGIS account is required`)}return l?`${o} — ${l}.`:`${o}.`}const CAMPAIGN="queue_cap",UPGRADE_URL="https://aegiscloud.org/go/upgrade?s=desktop&c=queue_cap",BALANCE_CAMPAIGN="topup_bank",BALANCE_URL="https://aegiscloud.org/go/topup?s=desktop&c=topup_bank",SIGNUP_SOURCES=Object.freeze(["desktop","cli","mcp"]),DEFAULT_HOST="desktop";function goUrl(e,n,r){const a=String(null==r?"":r).trim().toLowerCase(),o=SIGNUP_SOURCES.includes(a)?a:DEFAULT_HOST;return`https://aegiscloud.org/go/${String(e).trim().toLowerCase()}?s=${o}&c=${n}`}function promptUrlFor(e){return{upgrade:goUrl("upgrade",CAMPAIGN,e),balance:goUrl("topup",BALANCE_CAMPAIGN,e)}}const DEFAULT_TTL_MS=6e4;function normalizePlan(e){const n=String(null==e?"":e).trim().toLowerCase();return n?PAID_PLANS.includes(n)?n:LEGACY_PLAN_ALIASES[n]||"free":"free"}const ASK_EXAMPLE="Do X autonomously";function isPaidPlan(e){return"free"!==normalizePlan(e)}function fanoutRefusal(){return`Fan-out needs Pro: ${PRO_VALUE}. Write it in the message: "${ASK_EXAMPLE}". Unlock: Pro, or any Token Bank balance. Free keeps the local drain on your own key — one worker per task, while this window is open.`}function balanceRefusal(){return`Your AEGIS balance is empty — ${PRO_VALUE}. Write it in the message: "${ASK_EXAMPLE}". Unlock: top up the Token Bank, or upgrade to Pro. Local drains stay free: one worker per task, on your own key, while this window is open.`}function balanceOf(e){if(!e||"object"!=typeof e)return{balanceKnown:!1,balanceMicros:null};let n=null;return null!=e.balance_micros?n=Number(e.balance_micros):null!=e.balance_eur&&(n=1e6*Number(e.balance_eur)),null!=n&&Number.isFinite(n)?{balanceKnown:!0,balanceMicros:Math.trunc(n)}:{balanceKnown:!1,balanceMicros:null}}function classifyProbe(e,n){if(n){const e=balanceOf(n&&n.data),r=n.status,a=n&&n.data||{},o=String(a.error||a.code||""),l=String(n&&n.message||"");return 400===r||401===r||/api_key required|invalid api key|unauthor/i.test(`${o} ${l}`)?{source:"no-key",plan:"free",degraded:!1,...e}:{source:"unreachable",plan:"free",degraded:!0,...e}}const r=e&&"object"==typeof e?e:{},a=balanceOf(r);if(!1===r.valid)return{source:"no-key",plan:"free",degraded:!1,...a};const o=null!=r.plan_effective&&String(r.plan_effective).trim()?r.plan_effective:r.plan,l=String(null==o?"":o).trim();return l?{source:"server-plan",plan:normalizePlan(l),degraded:!1,...a}:{source:"no-plan-field",plan:"free",degraded:!0,...a}}function createEntitlement({probe:e,now:n=Date.now,ttlMs:r=6e4,host:a=DEFAULT_HOST}={}){const o=promptUrlFor(a);let l=Object.freeze({pro:!1,entitled:!1,balanceKnown:!1,balanceMicros:null,balanceZero:!1,wall:"plan",plan:"free",tier:null,tierName:null,planRaw:null,maxWorkers:1,source:"unresolved",degraded:!0,checkedAt:null,campaign:CAMPAIGN,host:SIGNUP_SOURCES.includes(String(a).toLowerCase())?String(a).toLowerCase():DEFAULT_HOST,upgradeUrl:o.upgrade,refusal:null}),t=null;function i({source:e,plan:r,degraded:a,planRaw:l,balanceKnown:t=!1,balanceMicros:i=null}){const u=normalizePlan(r),c="free"!==u,s=t&&Number.isFinite(i)&&i>0,d=c||s,f=t&&!s,p=d?null:f?"balance":"plan";return Object.freeze({pro:c,entitled:d,balanceKnown:Boolean(t),balanceMicros:t?i:null,balanceZero:f,wall:p,plan:c?u:"free",tier:c?u:null,tierName:c&&TIER_NAMES[u]||null,planRaw:null==l?null:String(l),maxWorkers:d?null:1,source:e,degraded:Boolean(a),checkedAt:n(),campaign:"balance"===p?BALANCE_CAMPAIGN:CAMPAIGN,upgradeUrl:"balance"===p?o.balance:o.upgrade,refusal:d?null:"balance"===p?balanceRefusal():fanoutRefusal()})}return{refresh:async function({force:a=!1}={}){if(null!=l.checkedAt&&n()-l.checkedAt<r&&!a)return l;if(t)return t;t=(async()=>{if("function"!=typeof e)return l=i({source:"no-probe",plan:"free",degraded:!0}),l;try{const n=await e(),r=classifyProbe(n,null);l=i({...r,planRaw:n&&n.plan})}catch(e){const n=classifyProbe(null,e);l=i(n)}return l})();try{return await t}finally{t=null}},current:function(){return l},gateFanout:function({workers:e,fanout:n}={}){const r=Number.isInteger(e)?e:null;return!0===n||null!=r&&r>1?l.entitled?{ok:!0,workers:r,fanout:!0}:{ok:!1,code:"balance"===l.wall?"fanout_requires_balance":"fanout_requires_pro",reason:l.refusal||fanoutRefusal(),campaign:l.campaign,upgradeUrl:l.upgradeUrl,wall:l.wall,pro:!1,entitled:!1,maxWorkers:1,entitlement:l}:{ok:!0,workers:r,fanout:Boolean(n)}}}}module.exports={createEntitlement:createEntitlement,normalizePlan:normalizePlan,isPaidPlan:isPaidPlan,tierName:tierName,TIER_NAMES:TIER_NAMES,classifyProbe:classifyProbe,fanoutRefusal:fanoutRefusal,balanceRefusal:balanceRefusal,ASK_EXAMPLE:ASK_EXAMPLE,balanceOf:balanceOf,FREE_MAX_WORKERS:1,PAID_PLANS:PAID_PLANS,LEGACY_PLAN_ALIASES:LEGACY_PLAN_ALIASES,CAMPAIGN:CAMPAIGN,UPGRADE_URL:UPGRADE_URL,BALANCE_CAMPAIGN:BALANCE_CAMPAIGN,BALANCE_URL:BALANCE_URL,PRO_VALUE:PRO_VALUE,FREE_HONESTY:FREE_HONESTY,BYOK_FEE_NOTE:BYOK_FEE_NOTE,byokFeeLine:byokFeeLine,DEFAULT_TTL_MS:6e4,SIGNUP_SOURCES:SIGNUP_SOURCES,DEFAULT_HOST:DEFAULT_HOST,goUrl:goUrl,promptUrlFor:promptUrlFor};
3
+ "use strict";const FREE_MAX_WORKERS=1,PAID_PLANS=Object.freeze(["pro","unlimited"]),TIER_NAMES=Object.freeze({pro:"Pro",unlimited:"Unlimited"});function tierName(e){return TIER_NAMES[normalizePlan(e)]||null}const LEGACY_PLAN_ALIASES=Object.freeze({cloud:"pro",memory:"pro",s:"pro",heavy:"pro",team:"pro",starter:"free"}),PRO_VALUE="Pro puts the drain in the cloud, so the job keeps running after you close the laptop",FREE_HONESTY="Everything on your machine is free, permanently. The cloud drain is what you pay for.",BYOK_FEE_NOTE="Bring your own key is relayed through AEGIS, not dialled from here — the routing, prompt assembly and caching are billed as a flat handling fee, on top of your provider's own bill.";function ratePerMillion(e){return`$${(1e3*Number(e)).toFixed(2)}/M`}function byokFeeLine(e){const n=e&&"object"==typeof e?e:null;if(!n)return"";const r=Number(n.in_usd_per_1k),a=Number(n.out_usd_per_1k);if(!Number.isFinite(r)||!Number.isFinite(a))return"";if(!0===n.disabled)return"Bring your own key is relayed free on this deployment right now.";const o=`Bring your own key: relayed through AEGIS, handled at ${ratePerMillion(r)} in / ${ratePerMillion(a)} out, on top of your provider's bill — no fee at all on Unlimited, and no fee at all during the free 1-month Unlimited trial`;let l="";if(!0===n.require_account)l="and needs an AEGIS account key (X-AEGIS-Key) for the fee to be billed";else{const e=Number(n.anonymous_daily_calls);Number.isFinite(e)&&e>0&&(l=`with ${e} relayed turns/24h before an AEGIS account is required`)}return l?`${o} — ${l}.`:`${o}.`}const CAMPAIGN="queue_cap",UPGRADE_URL="https://aegiscloud.org/go/upgrade?s=desktop&c=queue_cap",BALANCE_CAMPAIGN="topup_bank",BALANCE_URL="https://aegiscloud.org/go/topup?s=desktop&c=topup_bank",SIGNUP_SOURCES=Object.freeze(["desktop","cli","mcp"]),DEFAULT_HOST="desktop";function goUrl(e,n,r){const a=String(null==r?"":r).trim().toLowerCase(),o=SIGNUP_SOURCES.includes(a)?a:"desktop";return`https://aegiscloud.org/go/${String(e).trim().toLowerCase()}?s=${o}&c=${n}`}function promptUrlFor(e){return{upgrade:goUrl("upgrade",CAMPAIGN,e),balance:goUrl("topup","topup_bank",e)}}const DEFAULT_TTL_MS=6e4;function normalizePlan(e){const n=String(null==e?"":e).trim().toLowerCase();return n?PAID_PLANS.includes(n)?n:LEGACY_PLAN_ALIASES[n]||"free":"free"}const ASK_EXAMPLE="Do X autonomously";function isPaidPlan(e){return"free"!==normalizePlan(e)}function fanoutRefusal(){return`Fan-out needs Pro: ${PRO_VALUE}. Write it in the message: "${ASK_EXAMPLE}". Unlock: Pro, or any Token Bank balance. Free keeps the local drain on your own key — one worker per task, while this window is open.`}function balanceRefusal(){return`Your AEGIS balance is empty — ${PRO_VALUE}. Write it in the message: "${ASK_EXAMPLE}". Unlock: top up the Token Bank, or upgrade to Pro. Local drains stay free: one worker per task, on your own key, while this window is open.`}function balanceOf(e){if(!e||"object"!=typeof e)return{balanceKnown:!1,balanceMicros:null};let n=null;return null!=e.balance_micros?n=Number(e.balance_micros):null!=e.balance_eur&&(n=1e6*Number(e.balance_eur)),null!=n&&Number.isFinite(n)?{balanceKnown:!0,balanceMicros:Math.trunc(n)}:{balanceKnown:!1,balanceMicros:null}}function classifyProbe(e,n){if(n){const e=balanceOf(n&&n.data),r=n.status,a=n&&n.data||{},o=String(a.error||a.code||""),l=String(n&&n.message||"");return 400===r||401===r||/api_key required|invalid api key|unauthor/i.test(`${o} ${l}`)?{source:"no-key",plan:"free",degraded:!1,...e}:{source:"unreachable",plan:"free",degraded:!0,...e}}const r=e&&"object"==typeof e?e:{},a=balanceOf(r);if(!1===r.valid)return{source:"no-key",plan:"free",degraded:!1,...a};const o=null!=r.plan_effective&&String(r.plan_effective).trim()?r.plan_effective:r.plan,l=String(null==o?"":o).trim();return l?{source:"server-plan",plan:normalizePlan(l),degraded:!1,...a}:{source:"no-plan-field",plan:"free",degraded:!0,...a}}function createEntitlement({probe:e,now:n=Date.now,ttlMs:r=6e4,host:a="desktop"}={}){const o=promptUrlFor(a);let l=Object.freeze({pro:!1,entitled:!1,balanceKnown:!1,balanceMicros:null,balanceZero:!1,wall:"plan",plan:"free",tier:null,tierName:null,planRaw:null,maxWorkers:1,source:"unresolved",degraded:!0,checkedAt:null,campaign:CAMPAIGN,host:SIGNUP_SOURCES.includes(String(a).toLowerCase())?String(a).toLowerCase():"desktop",upgradeUrl:o.upgrade,refusal:null}),t=null;function i({source:e,plan:r,degraded:a,planRaw:l,balanceKnown:t=!1,balanceMicros:i=null}){const u=normalizePlan(r),c="free"!==u,s=t&&Number.isFinite(i)&&i>0,p=c||s,d=t&&!s,f=p?null:d?"balance":"plan";return Object.freeze({pro:c,entitled:p,balanceKnown:Boolean(t),balanceMicros:t?i:null,balanceZero:d,wall:f,plan:c?u:"free",tier:c?u:null,tierName:c&&TIER_NAMES[u]||null,planRaw:null==l?null:String(l),maxWorkers:p?null:1,source:e,degraded:Boolean(a),checkedAt:n(),campaign:"balance"===f?"topup_bank":CAMPAIGN,upgradeUrl:"balance"===f?o.balance:o.upgrade,refusal:p?null:"balance"===f?balanceRefusal():fanoutRefusal()})}return{refresh:async function({force:a=!1}={}){if(null!=l.checkedAt&&n()-l.checkedAt<r&&!a)return l;if(t)return t;t=(async()=>{if("function"!=typeof e)return l=i({source:"no-probe",plan:"free",degraded:!0}),l;try{const n=await e(),r=classifyProbe(n,null);l=i({...r,planRaw:n&&n.plan})}catch(e){const n=classifyProbe(null,e);l=i(n)}return l})();try{return await t}finally{t=null}},current:function(){return l},gateFanout:function({workers:e,fanout:n}={}){const r=Number.isInteger(e)?e:null;return!0===n||null!=r&&r>1?l.entitled?{ok:!0,workers:r,fanout:!0}:{ok:!1,code:"balance"===l.wall?"fanout_requires_balance":"fanout_requires_pro",reason:l.refusal||fanoutRefusal(),campaign:l.campaign,upgradeUrl:l.upgradeUrl,wall:l.wall,pro:!1,entitled:!1,maxWorkers:1,entitlement:l}:{ok:!0,workers:r,fanout:Boolean(n)}}}}module.exports={createEntitlement:createEntitlement,normalizePlan:normalizePlan,isPaidPlan:isPaidPlan,tierName:tierName,TIER_NAMES:TIER_NAMES,classifyProbe:classifyProbe,fanoutRefusal:fanoutRefusal,balanceRefusal:balanceRefusal,ASK_EXAMPLE:ASK_EXAMPLE,balanceOf:balanceOf,FREE_MAX_WORKERS:1,PAID_PLANS:PAID_PLANS,LEGACY_PLAN_ALIASES:LEGACY_PLAN_ALIASES,CAMPAIGN:CAMPAIGN,UPGRADE_URL:UPGRADE_URL,BALANCE_CAMPAIGN:"topup_bank",BALANCE_URL:BALANCE_URL,PRO_VALUE:PRO_VALUE,FREE_HONESTY:FREE_HONESTY,BYOK_FEE_NOTE:BYOK_FEE_NOTE,byokFeeLine:byokFeeLine,DEFAULT_TTL_MS:6e4,SIGNUP_SOURCES:SIGNUP_SOURCES,DEFAULT_HOST:"desktop",goUrl:goUrl,promptUrlFor:promptUrlFor};
@@ -134,7 +134,7 @@ const UNITS = Object.freeze([
134
134
  * (`tools/desktop-seal.mjs` in the source tree, `tools/obfuscate-faces.mjs`
135
135
  * after obfuscation), never by hand.
136
136
  */
137
- const SEALED = '25478904c5c5181aee2f2d4cb3b2ae8c4653b51f7de37e94f0aa4119d3775253';
137
+ const SEALED = 'fb7b17fcebd59e8eeea8107198b7259c11c5c280e34a97d2a82fddaf599b1838';
138
138
 
139
139
  /**
140
140
  * Ask the question. Never throws — a check that can break the program it is
@@ -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{estimateTokens:estimateTokens,trimContext:trimContext}=require("./context.js"),attachmentsModule=require("./attachments.js"),DEFAULT_BASE="http://localhost:11434",SSE_IDLE_TIMEOUT_MS=3e5,FIRST_BYTE_TIMEOUT_MS=SSE_IDLE_TIMEOUT_MS,HEADERS_DEADLINE_MS=3e5;function isHeadersDeadline(e){if(!e)return!1;const t=e.cause||e;if(!t)return!1;const n=String(t.code||""),s=String(t.name||"");return"UND_ERR_HEADERS_TIMEOUT"===n||"HeadersTimeoutError"===s}const PROBE_TIMEOUT_MS=1500;function normalizeBase(e){const t=String(null==e?"":e).trim();return t?/^[a-zA-Z][a-zA-Z0-9+.-]*:\/\//.test(t)?t:`http://${t}`:DEFAULT_BASE}function baseOf(e){return normalizeBase(e).replace(/\/+$/,"")}const DSML_RE_INVOKE=/<\s*|\s*(?:DSML\s*)?|\s*(?:invoke|call|tool_call)\b\s*([^>]*?)\s*>([\s\S]*?)<\s*\/\s*|\s*(?:DSML\s*)?|\s*(?:invoke|call|tool_call)\b\s*>/g,DSML_RE_PARAM=/<\s*|\s*(?:DSML\s*)?|\s*(?:parameter|param|arg)\b\s*([^>]*?)\s*>([\s\S]*?)<\s*\/\s*|\s*(?:DSML\s*)?|\s*(?:parameter|param|arg)\b\s*>/g,DSML_RE_LEADER=/<\s*\/?\s*|\s*(?:DSML\s*)?|\s*(?:(?:tool|function)[_▁ ]*calls?|reasoning)[_▁ ]*(?:begin|end)?\s*>/gi,DSML_RE_ANY_TAG=/<\s*\/?\s*|\s*(?:DSML\s*)?|\s*[A-Za-z_][A-Za-z0-9_]*[^>]{0,120}>/g,DSML_RE_SKELETON=/<\s*\/?\s*(?:tool_calls|function_calls|invoke|parameter|param|reasoning)\b[^>]{0,120}>/gi,DSML_RE_JSON_CALLS=/|[ \t]*(?:tool|function)[_▁ ]*calls?[_▁ ]*begin[ \t]*|([\s\S]*?)|[ \t]*(?:tool|function)[_▁ ]*calls?[_▁ ]*end[ \t]*|/gi,DSML_RE_JSON_CALLS_OPEN=/|[ \t]*(?:tool|function)[_▁ ]*calls?[_▁ ]*begin[ \t]*|/gi,DSML_RE_JSON_CALLS_CLOSE=/|[ \t]*(?:tool|function)[_▁ ]*calls?[_▁ ]*end[ \t]*|/gi,DSML_RE_ENVELOPE_TOKEN=/|[ \t]?[A-Za-z0-9_▁]*[ \t]?|/g,DSML_RE_DRIFT_INVOKE=/<\s*|\s*(?:DSML\s*)?|\s*(?:invoke|call|tool_call)\b\s*([^>]*?)\s*>/gi,DSML_RE_DRIFT_PARAM=/<\s*|\s*(?:DSML\s*)?|\s*(?:parameter|param|arg)\b\s*([^>]*?)\s*>/gi,DSML_RE_PARAM_CLOSE=/<\s*\/\s*|\s*(?:DSML\s*)?|\s*(?:parameter|param|arg)\b\s*>/gi,DSML_RE_ATTR=/([A-Za-z_][A-Za-z0-9_.-]*)\s*=\s*(?:"([^"]*)"|'([^']*)')/g,DSML_RE_STRUCT_TAG=/<\s*\/?\s*|\s*(?:DSML\s*)?|\s*(?:invoke|call|tool_call|parameter|param|arg|reasoning|(?:tool|function)[_▁ ]*calls?)\b/gi,DSML_RE_STRUCT_CLOSER=/<\s*\/\s*|\s*(?:DSML\s*)?|\s*(?:invoke|call|tool_call|parameter|param|arg|reasoning|(?:tool|function)[_▁ ]*calls?)\b/gi,DSML_RE_WRAPPER_TAG=/<\s*\/?\s*|\s*(?:DSML\s*)?|\s*(?!(?:invoke|call|tool_call|parameter|param|arg)\b)[A-Za-z_][A-Za-z0-9_]*[^>]{0,120}>/g,DSML_RE_TRAILING_LT=/<\s*\/?\s*$/,DSML_RE_OPEN_TOKEN=/^|[ \t]?[A-Za-z0-9_▁]*[ \t]?$/,DSML_HOLD_MAX=4194304;function dsmlAttrs(e){const t={};if(!e)return t;let n;for(DSML_RE_ATTR.lastIndex=0;n=DSML_RE_ATTR.exec(e);)t[n[1].toLowerCase()]=null!=n[2]?n[2]:n[3];return t}function dsmlJson(e){const t=String(null==e?"":e).trim();try{const e=JSON.parse(t);return void 0===e?t:e}catch{return t}}function dsmlArgs(e){const t={};let n;for(DSML_RE_PARAM.lastIndex=0;n=DSML_RE_PARAM.exec(e);){const e=dsmlAttrs(n[1]),s=e.name||e.key||`arg${Object.keys(t).length}`,o="false"===String(e.string||"").toLowerCase()||"true"===String(e.json||"").toLowerCase();t[s]=o?dsmlJson(n[2]):n[2]}return t}function decodeDeepSeekDSML(e){if("string"!=typeof e||!e||-1===e.indexOf("|"))return{text:e||"",calls:[]};const t=[];let n=e;DSML_RE_INVOKE.lastIndex=0;const s=[];let o;for(;o=DSML_RE_INVOKE.exec(n);){const e=dsmlAttrs(o[1]),n=e.name||e.function||e.tool||"";n&&t.push({name:n,args:dsmlArgs(o[2])}),s.push([o.index,o.index+o[0].length])}for(let e=s.length-1;e>=0;e--)n=n.slice(0,s[e][0])+n.slice(s[e][1]);return n=n.replace(DSML_RE_JSON_CALLS,((e,n)=>{const s=dsmlJson(n),o=Array.isArray(s)?s:s&&Array.isArray(s.tool_calls)?s.tool_calls:[];for(const e of o){const n=e&&e.function||e||{},s=n.name||e&&e.name||"";if(!s)continue;let o=null!=n.arguments?n.arguments:e&&e.arguments;"string"==typeof o&&(o=dsmlJson(o)),t.push({name:s,args:o&&"object"==typeof o?o:{}})}return""})),n=n.replace(DSML_RE_LEADER,""),{text:n,calls:t}}function decodeDeepSeekDSMLDrift(e){if("string"!=typeof e||!e||-1===e.indexOf("|"))return{text:e||"",calls:[]};const t=[];let n;for(DSML_RE_DRIFT_INVOKE.lastIndex=0;n=DSML_RE_DRIFT_INVOKE.exec(e);)t.push({at:n.index,attrs:n[1],body:DSML_RE_DRIFT_INVOKE.lastIndex});if(!t.length)return{text:e,calls:[]};const s=[];let o="",r=0;for(let n=0;n<t.length;n++){const a=n+1<t.length?t[n+1].at:e.length,l=e.slice(t[n].body,a),i=dsmlAttrs(t[n].attrs),c=i.name||i.function||i.tool||"",u={},f=[];let _;for(DSML_RE_DRIFT_PARAM.lastIndex=0;_=DSML_RE_DRIFT_PARAM.exec(l);)f.push({at:_.index,attrs:_[1],from:DSML_RE_DRIFT_PARAM.lastIndex});for(let e=0;e<f.length;e++){const t=e+1<f.length?f[e+1].at:l.length,n=l.slice(f[e].from,t).replace(DSML_RE_PARAM_CLOSE,""),s=dsmlAttrs(f[e].attrs),o=s.name||s.key||`arg${Object.keys(u).length}`,r="false"===String(s.string||"").toLowerCase();u[o]=r?dsmlJson(n):n}o+=e.slice(r,t[n].at),r=a,c&&s.push({name:c,args:u})}return o+=e.slice(r),{text:o,calls:s}}function dsmlResidue(e){return e?-1===e.indexOf("|")?e.replace(DSML_RE_SKELETON,""):e.replace(DSML_RE_ANY_TAG,"").replace(DSML_RE_SKELETON,"").replace(DSML_RE_ENVELOPE_TOKEN,""):e}function dsmlUnterminated(e){return!!DSML_RE_OPEN_TOKEN.test(e)||(e.match(DSML_RE_STRUCT_TAG)||[]).length>(e.match(DSML_RE_STRUCT_CLOSER)||[]).length}function dsmlHoldFrom(e){const t=e.search(/<\s*\/?\s*|/);if(-1!==t)return t;const n=e.search(DSML_RE_JSON_CALLS_OPEN);if(-1!==n&&-1===e.slice(n).search(DSML_RE_JSON_CALLS_CLOSE))return n;const s=DSML_RE_TRAILING_LT.exec(e);if(s)return s.index;const o=e.indexOf("|");return-1!==o&&dsmlUnterminated(e.slice(o))?o:-1}function decodePlainToolCallTags(e,t){if(!e||-1===e.indexOf("<"))return e;let n="",s=0;for(;;){const o=TEXT_TOOL_TAG_OPEN_RE.exec(e.slice(s));if(!o)break;const r=s+o.index,a=o[0];if(a.includes(DSML_TAG_MARK)){n+=e.slice(s,r+a.length),s=r+a.length;continue}const l=e.slice(r+a.length),i=TEXT_TOOL_TAG_CLOSE_RE.exec(l);if(!i)break;const c=textCallsIn(l.slice(0,i.index));if(n+=e.slice(s,r),s=r+a.length+i.index+i[0].length,c.length)for(const e of c)t.push(e);else n+=e.slice(r,s)}return n+e.slice(s)}function plainToolTagHoldAt(e){if(!e||-1===e.indexOf("<"))return-1;let t=0;for(;;){const n=TEXT_TOOL_TAG_OPEN_RE.exec(e.slice(t));if(!n)return-1;const s=t+n.index;if(n[0].includes(DSML_TAG_MARK)){t=s+n[0].length;continue}const o=e.slice(s+n[0].length);return TEXT_TOOL_TAG_CLOSE_RE.test(o)?-1:s}}function makeDeepSeekEnvelopeStripper(){let e="";const t=[],n=e=>dsmlResidue(decodePlainToolCallTags(e,t)),s=s=>{e+="string"==typeof s?s:"";const o=decodeDeepSeekDSML(e);e=o.text;for(const e of o.calls)t.push(e);e=e.replace(DSML_RE_WRAPPER_TAG,"");const r=dsmlHoldFrom(e);let a;-1!==r&&e.length-r<=DSML_HOLD_MAX?(a=e.slice(0,r),e=e.slice(r)):(a=e,e="");const l=plainToolTagHoldAt(a);return-1!==l&&(e=a.slice(l)+e,a=a.slice(0,l)),n(a)};return s.flush=()=>{const s=decodeDeepSeekDSML(e);e="";for(const e of s.calls)t.push(e);const o=decodeDeepSeekDSMLDrift(s.text);for(const e of o.calls)t.push(e);return n(o.text)},s.calls=()=>t.slice(),s}const TEXT_TOOL_TAG_OPEN_RE=/<\s*tool_calls?\b[^>]{0,80}>/i,TEXT_TOOL_TAG_CLOSE_RE=/<\s*\/\s*tool_calls?\s*>/i,TEXT_FENCE_RE=/```[ \t]*[A-Za-z0-9_+-]*[ \t]*\n?([\s\S]*?)```/,TEXT_FENCE_OPEN_RE=/```[ \t]*[A-Za-z0-9_+-]*[ \t]*\n?/,DSML_TAG_MARK="|";function asTextToolCall(e){if(!e||"object"!=typeof e)return null;let t=e;t.function&&"object"==typeof t.function&&(t={...t.function,name:t.function.name||t.name});const n=t.name||t.tool||t.tool_name||t.function_name,s="string"==typeof n?n.trim():"";if(!s)return null;let o=null!=t.arguments?t.arguments:null!=t.parameters?t.parameters:null!=t.args?t.args:null!=t.tool_input?t.tool_input:{};if("string"==typeof o){const e=o.trim()?safeJson(o):{};o=e&&"object"==typeof e?e:{}}return null!=o&&"object"==typeof o||(o={}),{name:s,args:o}}function safeJson(e){try{return JSON.parse(e)}catch{return null}}function textCallsIn(e){const t=String(e||"").trim().replace(/^json\s*/i,"").trim();if(!t)return[];const n=safeJson(t);if(!n)return[];const s=Array.isArray(n)?n:[n],o=[];for(const e of s){const t=asTextToolCall(e);t&&o.push(t)}return o}function nextTextToolEnvelope(e){const t=TEXT_FENCE_RE.exec(e);if(t)return{start:t.index,end:t.index+t[0].length,complete:!0,raw:t[0],body:t[1]};const n=TEXT_FENCE_OPEN_RE.exec(e);return n?{start:n.index,end:e.length,complete:!1,body:e.slice(n.index+n[0].length)}:null}function trailingHeadFrom(e,t=!1){if(!e)return-1;const n=e.search(TEXT_TOOL_HEAD_RE);if(-1!==n)return n;const s=/`{1,2}$/.exec(e);if(s)return s.index;const o=e.lastIndexOf("<");if(-1!==o&&couldBeTextToolHead(e.slice(o)))return o;if(t){const t=e.lastIndexOf("{");if(-1!==t&&/^\{\s*(?:"[^"]*"\s*:[\s\S]*|"[^"]*"?\s*|)$/.test(e.slice(t)))return t}return-1}function couldBeTextToolHead(e){const t=e.replace(/^[\s\uFEFF]+/,"");if(!t)return!0;if(t.length<=3&&"```".startsWith(t))return!0;if(t.startsWith("<")&&!TEXT_TOOL_HEAD_RE.test(t)){const e=t.slice(1).replace(/^\/?\s*/,"").toLowerCase();if(e.length<=10&&/^[a-z_]*$/.test(e))return"tool_call".startsWith(e)||"tool_calls".startsWith(e)}return!1}function balancedJsonEnd(e,t){let n=0,s=!1,o=!1;for(let r=t;r<e.length;r++){const t=e[r];if(s)o?o=!1:"\\"===t?o=!0:'"'===t&&(s=!1);else if('"'===t)s=!0;else if("{"===t||"["===t)n++;else if(("}"===t||"]"===t)&&(n--,n<=0))return r+1}return-1}function makeTextToolCallStripper({toolNames:e=null}={}){const t=e?new Set([...e].map((e=>String(e)))):null;let n="";const s=[],o=e=>Boolean(e.length)&&(!t||e.every((e=>t.has(e.name)))),r=(e,t)=>{const n=textCallsIn(t);if(!o(n))return e;for(const e of n)s.push(e);return""},a=e=>{n+="string"==typeof e?e:"";let a="",l=!1;for(;;){const e=nextTextToolEnvelope(n);if(e){if(a+=n.slice(0,e.start),n=n.slice(e.start),!e.complete){l=!0;break}a+=r(e.raw,e.body),n=n.slice(e.raw.length);continue}const i=TEXT_TOOL_TAG_OPEN_RE.exec(n);if(i){a+=n.slice(0,i.index),n=n.slice(i.index);const e=n.slice(i[0].length),t=TEXT_TOOL_TAG_CLOSE_RE.exec(e);if(!t){l=!0;break}const s=n.slice(0,i[0].length+t.index+t[0].length);a+=r(s,e.slice(0,t.index)),n=n.slice(s.length);continue}const c=t?/\{\s*"/.exec(n):null;if(!c)break;const u=balancedJsonEnd(n,c.index),f=n.slice(0,c.index);if(-1===u){a+=f,n=n.slice(c.index),l=!0;break}const _=textCallsIn(n.slice(c.index,u));if(a+=f,o(_))for(const e of _)s.push(e);else a+=n.slice(c.index,u);n=n.slice(u)}const i=l?0:trailingHeadFrom(n,Boolean(t));return-1===i?(a+=n,n=""):i>0&&(a+=n.slice(0,i),n=n.slice(i)),n.length>TEXT_TOOL_HOLD_MAX&&(a+=n,n=""),a};return a.flush=()=>{const e=n;if(n="",!e)return"";const s=nextTextToolEnvelope(e);if(s)return e.slice(0,s.start)+r(e.slice(s.start),s.body);const o=TEXT_TOOL_TAG_OPEN_RE.exec(e);if(!o){const n=t?/\{\s*"/.exec(e):null;if(!n)return e;const s=balancedJsonEnd(e,n.index);return-1===s?e:e.slice(0,n.index)+r(e.slice(n.index,s),e.slice(n.index,s))+e.slice(s)}const a=e.slice(o.index+o[0].length).replace(TEXT_TOOL_TAG_CLOSE_RE,"");return e.slice(0,o.index)+r(e.slice(o.index),a)},a.calls=()=>s.slice(),a}const TEXT_TOOL_HEAD_RE=/```|<\s*tool_calls?\b/i,TEXT_TOOL_HOLD_MAX=65536;function isLocalEndpoint(e){let t="",n="";if(""===String(null==e?"":e).trim())return!1;try{const s=new URL(normalizeBase(e));t=s.hostname.toLowerCase(),n=s.protocol.toLowerCase()}catch{return!1}if("http:"!==n&&"https:"!==n)return!1;if(!t)return!1;if(t.startsWith("[")&&t.endsWith("]")&&(t=t.slice(1,-1)),!t||/[\s/\\@]/.test(t))return!1;if("localhost"===t||t.endsWith(".localhost"))return!0;if(/\.(local|internal|lan)$/.test(t))return!0;if(t.includes(":"))return"::1"===t||"0:0:0:0:0:0:0:1"===t||!!/^f[cd][0-9a-f]{2}:/.test(t)||!!/^fe[89ab][0-9a-f]:/.test(t);const s=/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/.exec(t);if(s){const e=s.slice(1).map(Number);if(e.some((e=>e>255)))return!1;const[t,n]=e;return 127===t||10===t||172===t&&n>=16&&n<=31||192===t&&168===n||169===t&&254===n}return!t.includes(".")}function remoteRefusal(e){if(isLocalEndpoint(e))return null;const t=new Error(`local: ${JSON.stringify(String(e||""))} is not on this machine, so it is not the local class. Running a model you own is free because there is no vendor to pay — a remote URL here would be an unpaid turn instead. Use the aegis or byok class for remote models.`);return t.status=400,t}async function probe(e=DEFAULT_BASE){const t=baseOf(e);try{return{running:(await fetch(`${t}/api/tags`,{signal:AbortSignal.timeout(1500)})).ok,baseURL:t}}catch{return{running:!1,baseURL:t}}}async function listTags(e=DEFAULT_BASE){const t=await fetch(`${baseOf(e)}/api/tags`);if(!t.ok){const e=new Error(`local: /api/tags answered ${t.status}`);throw e.status=t.status,e}const n=await t.json();return(n&&n.models||[]).map((e=>({id:e&&e.name,...e&&e.details?{details:e.details}:{}}))).filter((e=>e.id))}const UNLOAD_TIMEOUT_MS=4e3,RESIDENT_TIMEOUT_MS=FIRST_BYTE_TIMEOUT_MS,DEFAULT_WARM_SECS=1800;async function unload(e,t){if(!t)return{ok:!1};const n=baseOf(e);if(!isLocalEndpoint(n))return{ok:!1};try{return{ok:(await fetch(`${n}/api/chat`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({model:String(t),messages:[],stream:!1,keep_alive:0}),signal:AbortSignal.timeout(UNLOAD_TIMEOUT_MS)})).ok}}catch{return{ok:!1}}}function normalizeRow(e){if(!e||"object"!=typeof e)return null;const t={role:e.role||"user"};return null!=e.content&&(t.content=e.content),e.name&&(t.name=e.name),e.tool_call_id&&(t.tool_call_id=e.tool_call_id),Array.isArray(e.tool_calls)&&e.tool_calls.length&&(t.tool_calls=e.tool_calls),t}function parseEvent(e){const t=String(e).split("\n");let n="",s=!1;for(const e of t){if(!e||e.startsWith(":"))continue;const t=e.indexOf(":"),o=-1===t?e:e.slice(0,t),r=-1===t?"":e.slice(t+1).replace(/^ /,"");"data"===o?(n+=r,s=!0):"event"!==o&&"id"!==o&&"retry"!==o||(s=!0)}if(!s||!n)return null;if("[DONE]"===n)return{done:!0};try{return{json:JSON.parse(n)}}catch{return null}}async function readSSE(e,t,{idleTimeoutMs:n=SSE_IDLE_TIMEOUT_MS}={}){const s=e.body.getReader(),o=new TextDecoder;let r="",a=null,l=()=>{};const i=new Promise(((e,t)=>{l=t})),c=()=>{a&&clearTimeout(a),a=setTimeout((()=>{l(new Error(`local: the model stopped responding — no output for ${Math.round(n/1e3)}s`))}),n)};c();try{for(;;){const e=await Promise.race([s.read(),i]);if(e.done)break;let n;for(r+=o.decode(e.value,{stream:!0}),r=r.replace(/\r\n/g,"\n");(n=r.indexOf("\n\n"))>=0;){const e=r.slice(0,n);r=r.slice(n+2);const s=parseEvent(e);if(s){if(s.done)return;s.json&&(c(),t(s.json))}}}}finally{a&&clearTimeout(a);try{await s.cancel()}catch{}}}const localCallQueues=new Map;function runSerialized(e,t){const n=(localCallQueues.get(e)||Promise.resolve()).then(t,t);return localCallQueues.set(e,n.then((()=>{}),(()=>{}))),n}const activeCountByKey=new Map,warmModelByBase=new Map;function swapWarmModel(e,t){if(!t)return;const n=warmModelByBase.get(e);warmModelByBase.set(e,t),n&&n!==t&&(activeCountByKey.get(`${e}|${n}`)||unload(e,n).catch((()=>{})))}async function unloadAll(){const e=[...warmModelByBase.entries()];warmModelByBase.clear(),await Promise.all(e.map((([e,t])=>unload(e,t))))}function warmSecsFor({warmSecs:e}={}){const t=Number(e);if(Number.isFinite(t)&&t>=0)return Math.floor(t);const n=Number(process.env&&process.env.AEGIS_LOCAL_WARM_SECS);return Number.isFinite(n)&&n>=0?Math.floor(n):DEFAULT_WARM_SECS}const residentMemo=new Map;function residentKey(e,t,n){return`${e}\0${t}\0${n}`}function residentSecsLeft(e,t,n,{dialer:s=fetch,now:o=Date.now()}={}){const r=residentMemo.get(residentKey(e,t,n));if(!r||r.dialer!==s)return 0;const a=Math.round((r.until-o)/1e3);return a<=0?(residentMemo.delete(residentKey(e,t,n)),0):a}function residentEntry(e,t,n,{dialer:s=fetch,now:o=Date.now()}={}){const r=residentMemo.get(residentKey(e,t,n));return r&&r.dialer===s&&r.until-o>0?r:null}function sameModel(e,t){const n=String(e||""),s=String(t||"");return!(!n||!s)&&(n===s||n.startsWith(`${s}:`)||n.startsWith(`${s}@`))}const WINDOW_TIMEOUT_MS=3e3;async function windowOf(e,t,{signal:n}={}){const s=new AbortController,o=()=>s.abort();if(n){if(n.aborted)return null;"function"==typeof n.addEventListener&&n.addEventListener("abort",o,{once:!0})}const r=setTimeout((()=>s.abort()),WINDOW_TIMEOUT_MS);r&&"function"==typeof r.unref&&r.unref();try{const n=await fetch(`${e}/api/ps`,{method:"GET",signal:s.signal});if(!n||!n.ok||"function"!=typeof n.json)return null;const o=await n.json(),r=(o&&o.models||[]).find((e=>sameModel(e&&(e.name||e.model),t))),a=r&&Number(r.context_length);return Number.isFinite(a)&&a>0?a:null}catch{return null}finally{clearTimeout(r),n&&"function"==typeof n.removeEventListener&&n.removeEventListener("abort",o)}}async function ensureResident({baseURL:e=DEFAULT_BASE,model:t,system:n="",signal:s,warmSecs:o,firstByteTimeoutMs:r}={}){const a=baseOf(e);if(!isLocalEndpoint(a))return{ok:!1,skipped:"remote"};if(!t||!String(t).trim())return{ok:!1,skipped:"no-model"};const l=warmSecsFor({warmSecs:o}),i="string"==typeof n?n:"",c={warmSecs:l,prefixSource:i?"turn-system":"none",prefixChars:i.length};if(l<=0)return{ok:!1,skipped:"warm-disabled",...c};const u=fetch,f=residentSecsLeft(a,t,i,{dialer:u});if(f>=Math.min(l,60)){const e=residentEntry(a,t,i,{dialer:u});return{ok:!0,already:!0,memo:!0,remainingSecs:f,contextLength:e&&e.contextLength||null,...c}}const _=new AbortController,d=()=>_.abort();s&&(s.aborted?_.abort():"function"==typeof s.addEventListener&&s.addEventListener("abort",d,{once:!0}));const m=Number(r),E=Number.isFinite(m)&&m>0?Math.min(m,RESIDENT_TIMEOUT_MS):RESIDENT_TIMEOUT_MS;let T=!1,p=null;const S=setTimeout((()=>{T=!0,_.abort()}),E);S&&"function"==typeof S.unref&&S.unref();try{try{const e=await fetch(`${a}/api/ps`,{method:"GET",signal:_.signal});if(e&&e.ok&&"function"==typeof e.json){const n=await e.json(),s=(n&&n.models||[]).find((e=>sameModel(e&&(e.name||e.model),t)));if(s&&Number.isFinite(s.context_length)&&s.context_length>0&&(p=s.context_length),s&&s.expires_at){const e=Math.round((new Date(s.expires_at).getTime()-Date.now())/1e3);if(Number.isFinite(e)&&e>=Math.min(l,60))return residentMemo.set(residentKey(a,t,i),{until:Date.now()+1e3*e,dialer:u,contextLength:p}),{ok:!0,already:!0,remainingSecs:e,contextLength:p,...c}}}}catch{}if(_.signal.aborted)return{ok:!1,aborted:!0,timeout:T,contextLength:p,...c};const e=i?[{role:"system",content:i},{role:"user",content:"PONG"}]:[{role:"user",content:"PONG"}],n=await fetch(`${a}/api/chat`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({model:String(t),keep_alive:l,stream:!1,messages:e,options:{num_predict:1}}),signal:_.signal});let s=null,o=null;if(n&&"function"==typeof n.text){const e=await n.text().catch((()=>""));try{const t=JSON.parse(e);Number.isFinite(t.prompt_eval_count)&&(s=t.prompt_eval_count),Number.isFinite(t.eval_count)&&(o=t.eval_count)}catch{}}return n&&n.ok&&(null==p&&(p=await windowOf(a,t,{signal:_.signal})||null),residentMemo.set(residentKey(a,t,i),{until:Date.now()+1e3*l,dialer:u,contextLength:p}),swapWarmModel(a,t)),{ok:!(!n||!n.ok),status:n&&n.status,pinned:!0,promptTokens:s,outputTokens:o,contextLength:p,...c}}catch(e){return{ok:!1,error:String(e&&e.message||e),timeout:T,contextLength:p,...c}}finally{clearTimeout(S),s&&"function"==typeof s.removeEventListener&&s.removeEventListener("abort",d)}}function stoppedTurn(e,{content:t="",usage:n=null}={}){const s={id:"local",model:String(e),choices:[{index:0,message:{role:"assistant",content:t},finish_reason:"stop"}]};return n&&(s.usage=n),s}function fitToWindowOf({rows:e,system:t,tools:n,contextLength:s,maxTokens:o}){const r=Number(s);if(!Number.isFinite(r)||r<=0)return null;const a=(Array.isArray(e)?e:[]).filter((e=>e&&"system"!==e.role)),l=Array.isArray(n)&&n.length?estimateTokens(JSON.stringify(n)):0,i=Number(o),c=Number.isFinite(i)&&i>0?i:Math.round(r/4),u=trimContext({messages:a,system:"string"==typeof t?t:"",budgetTokens:r,reserveTokens:c,fixedTokens:l});return{window:r,reserveTokens:c,toolTokens:l,dropped:u.dropped,messages:u.messages,over:u.estimatedTokens>Math.max(0,r-c),estimatedTokens:u.estimatedTokens}}async function chatOne({baseURL:e=DEFAULT_BASE,model:t,messages:n,system:s,prompt:o,maxTokens:r,temperature:a,tools:l,toolChoice:i,signal:c,onDelta:u,firstByteTimeoutMs:f=FIRST_BYTE_TIMEOUT_MS,contextLength:_}={}){const d=baseOf(e),m=remoteRefusal(d);if(m)throw m;if(!t||!String(t).trim()){const e=new Error("local: no model selected — pick one from the model list, or type a tag");throw e.status=400,e}const E=[];s&&E.push({role:"system",content:s});for(const e of Array.isArray(n)?n:[]){if(e&&"system"===e.role)continue;const t=normalizeRow(e);t&&E.push(t)}const T="string"==typeof o||Array.isArray(o)?o:"";if(!(""===T||Array.isArray(T)&&0===T.length)){const e=E[E.length-1],t=attachmentsModule.flattenContent(T),n=e?attachmentsModule.flattenContent(e.content):null;e&&"user"===e.role&&n===t||E.push({role:"user",content:T})}if(!E.length){const e=new Error("local: nothing to send — no prompt and no messages");throw e.status=400,e}let p=null;if(null!=_){const e=E[0]&&"system"===E[0].role?E[0]:null;if(p=fitToWindowOf({rows:E,system:e&&e.content||s||"",tools:l,contextLength:_,maxTokens:r}),p){const t=p.messages;E.length=0,e&&E.push(e),E.push(...t)}}const S={model:String(t),messages:E,stream:!0,stream_options:{include_usage:!0},...r?{max_tokens:r}:{},...null!=a?{temperature:a}:{},...l&&l.length?{tools:l}:{},...i?{tool_choice:i}:{}},g=new AbortController;let h=!1;const L=setTimeout((()=>{h=!0,g.abort()}),f);L&&"function"==typeof L.unref&&L.unref();const M=()=>g.abort();let y;c&&(c.aborted?g.abort():"function"==typeof c.addEventListener&&c.addEventListener("abort",M,{once:!0}));try{y=await fetch(`${d}/v1/chat/completions`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(S),signal:g.signal})}catch(e){if(h||isHeadersDeadline(e)){const e=h?`sent nothing in ${Math.round(f/1e3)}s`:`sent no response headers before this runtime's own ${Math.round(HEADERS_DEADLINE_MS/1e3)}s deadline`,n=new Error(`local: ${t} ${e} — the daemon is still loading the model, or its prompt prefill is longer than that. \`ollama ps\` shows which; a smaller prompt or a smaller model is the way through.`);throw n.status=0,n.code="timeout",n}if(c&&c.aborted||g.signal.aborted)return stoppedTurn(t);throw e}finally{clearTimeout(L)}if(!y.ok){let e="";try{e=await y.text()}catch{}const t=new Error(`local: chat/completions ${y.status}${e?` — ${e.slice(0,400)}`:""}`);throw t.status=y.status,t}let O="",A=null;const D=[],R=new Map,x=makeDeepSeekEnvelopeStripper(),b=makeTextToolCallStripper({toolNames:(Array.isArray(l)?l:[]).map((e=>e&&e.function&&e.function.name||e&&e.name||"")).filter(Boolean)});try{await readSSE(y,(e=>{e&&e.usage&&(A=e.usage);const t=e&&Array.isArray(e.choices)?e.choices[0]:null;if(!t)return;const n=t.delta||{};if("string"==typeof n.content&&n.content){const e=b(x(n.content));e&&(O+=e,"function"==typeof u&&u({text:e}))}const s=n.tool_calls||[];for(const e of s){const t=Number.isInteger(e.index)?e.index:D.length;let n=R.get(t);n||(n={id:"",type:"function",function:{name:"",arguments:""}},R.set(t,n)),e.id&&(n.id=e.id),e.type&&(n.type=e.type);const s=e.function||{};s.name&&(n.function.name=s.name),s.arguments&&(n.function.arguments+=s.arguments)}}),{idleTimeoutMs:SSE_IDLE_TIMEOUT_MS})}catch(e){if(c&&c.aborted)return stoppedTurn(t,{content:O,usage:A});throw e}finally{c&&"function"==typeof c.removeEventListener&&c.removeEventListener("abort",M)}const w=`${b(x.flush())||""}${b.flush()||""}`;w&&(O+=w,"function"==typeof u&&u({text:w}));for(const[e,t]of[...R.entries()].sort(((e,t)=>e[0]-t[0])))(t.function.name||t.function.arguments)&&(t.id||(t.id=`call_${e}`),D.push(t));const k={role:"assistant",content:O};D.length&&(k.tool_calls=D);const N=x.calls(),I=b.calls(),C={id:"local",model:String(t),choices:[{index:0,message:k,finish_reason:D.length?"tool_calls":"stop"}],...A?{usage:A}:{}};return(D.length||N.length||I.length)&&(C.toolCalls=[...D.map((e=>({id:e.id,name:e.function.name,args:e.function.arguments}))),...N.map((e=>({id:"",name:e.name,args:e.args||{}}))),...I.map((e=>({id:"",name:e.name,args:e.args||{}})))],(N.length||I.length)&&"tool_calls"!==C.choices[0].finish_reason&&(C.choices[0].finish_reason="tool_calls")),p&&(C.window={contextLength:p.window,dropped:p.dropped,toolTokens:p.toolTokens,estimatedTokens:p.estimatedTokens,reserveTokens:p.reserveTokens,over:p.over}),C}async function chat(e={}){const t=baseOf(e&&e.baseURL),n=e&&e.model,s=`${t}|${n}`;activeCountByKey.set(s,(activeCountByKey.get(s)||0)+1);try{let o=null;const r=await runSerialized(s,(async()=>{o=await ensureResident({baseURL:e&&e.baseURL,model:n,system:e&&e.system,signal:e&&e.signal,warmSecs:e&&e.warmSecs,firstByteTimeoutMs:e&&e.firstByteTimeoutMs});let s=o&&o.contextLength||null;const r=isLocalEndpoint(t)&&""!==String(n||"").trim();return!s&&r&&o&&!0!==o.ok&&!o.skipped&&(s=await windowOf(t,n,{signal:e&&e.signal})||null),chatOne({...e,contextLength:s})}));return swapWarmModel(t,n),o&&"object"==typeof r&&r&&(r.residency=o),r}finally{const e=(activeCountByKey.get(s)||1)-1;e<=0?activeCountByKey.delete(s):activeCountByKey.set(s,e)}}module.exports={DEFAULT_BASE:DEFAULT_BASE,DEFAULT_WARM_SECS:DEFAULT_WARM_SECS,RESIDENT_TIMEOUT_MS:RESIDENT_TIMEOUT_MS,SSE_IDLE_TIMEOUT_MS:SSE_IDLE_TIMEOUT_MS,FIRST_BYTE_TIMEOUT_MS:FIRST_BYTE_TIMEOUT_MS,PROBE_TIMEOUT_MS:1500,baseOf:baseOf,normalizeBase:normalizeBase,isLocalEndpoint:isLocalEndpoint,remoteRefusal:remoteRefusal,probe:probe,listTags:listTags,readSSE:readSSE,chat:chat,ensureResident:ensureResident,residentSecsLeft:residentSecsLeft,residentEntry:residentEntry,unload:unload,unloadAll:unloadAll,makeTextToolCallStripper:makeTextToolCallStripper,makeDeepSeekEnvelopeStripper:makeDeepSeekEnvelopeStripper,textCallsIn:textCallsIn,fitToWindowOf:fitToWindowOf,isHeadersDeadline:isHeadersDeadline,HEADERS_DEADLINE_MS:HEADERS_DEADLINE_MS,windowOf:windowOf,stoppedTurn:stoppedTurn};
3
+ "use strict";const{estimateTokens:estimateTokens,trimContext:trimContext}=require("./context.js"),attachmentsModule=require("./attachments.js"),DEFAULT_BASE="http://localhost:11434",SSE_IDLE_TIMEOUT_MS=3e5,FIRST_BYTE_TIMEOUT_MS=3e5,HEADERS_DEADLINE_MS=3e5;function isHeadersDeadline(e){if(!e)return!1;const t=e.cause||e;if(!t)return!1;const n=String(t.code||""),s=String(t.name||"");return"UND_ERR_HEADERS_TIMEOUT"===n||"HeadersTimeoutError"===s}const PROBE_TIMEOUT_MS=1500;function normalizeBase(e){const t=String(null==e?"":e).trim();return t?/^[a-zA-Z][a-zA-Z0-9+.-]*:\/\//.test(t)?t:`http://${t}`:DEFAULT_BASE}function baseOf(e){return normalizeBase(e).replace(/\/+$/,"")}const DSML_RE_INVOKE=/<\s*|\s*(?:DSML\s*)?|\s*(?:invoke|call|tool_call)\b\s*([^>]*?)\s*>([\s\S]*?)<\s*\/\s*|\s*(?:DSML\s*)?|\s*(?:invoke|call|tool_call)\b\s*>/g,DSML_RE_PARAM=/<\s*|\s*(?:DSML\s*)?|\s*(?:parameter|param|arg)\b\s*([^>]*?)\s*>([\s\S]*?)<\s*\/\s*|\s*(?:DSML\s*)?|\s*(?:parameter|param|arg)\b\s*>/g,DSML_RE_LEADER=/<\s*\/?\s*|\s*(?:DSML\s*)?|\s*(?:(?:tool|function)[_▁ ]*calls?|reasoning)[_▁ ]*(?:begin|end)?\s*>/gi,DSML_RE_ANY_TAG=/<\s*\/?\s*|\s*(?:DSML\s*)?|\s*[A-Za-z_][A-Za-z0-9_]*[^>]{0,120}>/g,DSML_RE_SKELETON=/<\s*\/?\s*(?:tool_calls|function_calls|invoke|parameter|param|reasoning)\b[^>]{0,120}>/gi,DSML_RE_JSON_CALLS=/|[ \t]*(?:tool|function)[_▁ ]*calls?[_▁ ]*begin[ \t]*|([\s\S]*?)|[ \t]*(?:tool|function)[_▁ ]*calls?[_▁ ]*end[ \t]*|/gi,DSML_RE_JSON_CALLS_OPEN=/|[ \t]*(?:tool|function)[_▁ ]*calls?[_▁ ]*begin[ \t]*|/gi,DSML_RE_JSON_CALLS_CLOSE=/|[ \t]*(?:tool|function)[_▁ ]*calls?[_▁ ]*end[ \t]*|/gi,DSML_RE_ENVELOPE_TOKEN=/|[ \t]?[A-Za-z0-9_▁]*[ \t]?|/g,DSML_RE_DRIFT_INVOKE=/<\s*|\s*(?:DSML\s*)?|\s*(?:invoke|call|tool_call)\b\s*([^>]*?)\s*>/gi,DSML_RE_DRIFT_PARAM=/<\s*|\s*(?:DSML\s*)?|\s*(?:parameter|param|arg)\b\s*([^>]*?)\s*>/gi,DSML_RE_PARAM_CLOSE=/<\s*\/\s*|\s*(?:DSML\s*)?|\s*(?:parameter|param|arg)\b\s*>/gi,DSML_RE_ATTR=/([A-Za-z_][A-Za-z0-9_.-]*)\s*=\s*(?:"([^"]*)"|'([^']*)')/g,DSML_RE_STRUCT_TAG=/<\s*\/?\s*|\s*(?:DSML\s*)?|\s*(?:invoke|call|tool_call|parameter|param|arg|reasoning|(?:tool|function)[_▁ ]*calls?)\b/gi,DSML_RE_STRUCT_CLOSER=/<\s*\/\s*|\s*(?:DSML\s*)?|\s*(?:invoke|call|tool_call|parameter|param|arg|reasoning|(?:tool|function)[_▁ ]*calls?)\b/gi,DSML_RE_WRAPPER_TAG=/<\s*\/?\s*|\s*(?:DSML\s*)?|\s*(?!(?:invoke|call|tool_call|parameter|param|arg)\b)[A-Za-z_][A-Za-z0-9_]*[^>]{0,120}>/g,DSML_RE_TRAILING_LT=/<\s*\/?\s*$/,DSML_RE_OPEN_TOKEN=/^|[ \t]?[A-Za-z0-9_▁]*[ \t]?$/,DSML_HOLD_MAX=4194304;function dsmlAttrs(e){const t={};if(!e)return t;let n;for(DSML_RE_ATTR.lastIndex=0;n=DSML_RE_ATTR.exec(e);)t[n[1].toLowerCase()]=null!=n[2]?n[2]:n[3];return t}function dsmlJson(e){const t=String(null==e?"":e).trim();try{const e=JSON.parse(t);return void 0===e?t:e}catch{return t}}function dsmlArgs(e){const t={};let n;for(DSML_RE_PARAM.lastIndex=0;n=DSML_RE_PARAM.exec(e);){const e=dsmlAttrs(n[1]),s=e.name||e.key||`arg${Object.keys(t).length}`,o="false"===String(e.string||"").toLowerCase()||"true"===String(e.json||"").toLowerCase();t[s]=o?dsmlJson(n[2]):n[2]}return t}function decodeDeepSeekDSML(e){if("string"!=typeof e||!e||-1===e.indexOf("|"))return{text:e||"",calls:[]};const t=[];let n=e;DSML_RE_INVOKE.lastIndex=0;const s=[];let o;for(;o=DSML_RE_INVOKE.exec(n);){const e=dsmlAttrs(o[1]),n=e.name||e.function||e.tool||"";n&&t.push({name:n,args:dsmlArgs(o[2])}),s.push([o.index,o.index+o[0].length])}for(let e=s.length-1;e>=0;e--)n=n.slice(0,s[e][0])+n.slice(s[e][1]);return n=n.replace(DSML_RE_JSON_CALLS,(e,n)=>{const s=dsmlJson(n),o=Array.isArray(s)?s:s&&Array.isArray(s.tool_calls)?s.tool_calls:[];for(const e of o){const n=e&&e.function||e||{},s=n.name||e&&e.name||"";if(!s)continue;let o=null!=n.arguments?n.arguments:e&&e.arguments;"string"==typeof o&&(o=dsmlJson(o)),t.push({name:s,args:o&&"object"==typeof o?o:{}})}return""}),n=n.replace(DSML_RE_LEADER,""),{text:n,calls:t}}function decodeDeepSeekDSMLDrift(e){if("string"!=typeof e||!e||-1===e.indexOf("|"))return{text:e||"",calls:[]};const t=[];let n;for(DSML_RE_DRIFT_INVOKE.lastIndex=0;n=DSML_RE_DRIFT_INVOKE.exec(e);)t.push({at:n.index,attrs:n[1],body:DSML_RE_DRIFT_INVOKE.lastIndex});if(!t.length)return{text:e,calls:[]};const s=[];let o="",r=0;for(let n=0;n<t.length;n++){const a=n+1<t.length?t[n+1].at:e.length,l=e.slice(t[n].body,a),i=dsmlAttrs(t[n].attrs),c=i.name||i.function||i.tool||"",u={},f=[];let d;for(DSML_RE_DRIFT_PARAM.lastIndex=0;d=DSML_RE_DRIFT_PARAM.exec(l);)f.push({at:d.index,attrs:d[1],from:DSML_RE_DRIFT_PARAM.lastIndex});for(let e=0;e<f.length;e++){const t=e+1<f.length?f[e+1].at:l.length,n=l.slice(f[e].from,t).replace(DSML_RE_PARAM_CLOSE,""),s=dsmlAttrs(f[e].attrs),o=s.name||s.key||`arg${Object.keys(u).length}`,r="false"===String(s.string||"").toLowerCase();u[o]=r?dsmlJson(n):n}o+=e.slice(r,t[n].at),r=a,c&&s.push({name:c,args:u})}return o+=e.slice(r),{text:o,calls:s}}function dsmlResidue(e){return e?-1===e.indexOf("|")?e.replace(DSML_RE_SKELETON,""):e.replace(DSML_RE_ANY_TAG,"").replace(DSML_RE_SKELETON,"").replace(DSML_RE_ENVELOPE_TOKEN,""):e}function dsmlUnterminated(e){return!!DSML_RE_OPEN_TOKEN.test(e)||(e.match(DSML_RE_STRUCT_TAG)||[]).length>(e.match(DSML_RE_STRUCT_CLOSER)||[]).length}function dsmlHoldFrom(e){const t=e.search(/<\s*\/?\s*|/);if(-1!==t)return t;const n=e.search(DSML_RE_JSON_CALLS_OPEN);if(-1!==n&&-1===e.slice(n).search(DSML_RE_JSON_CALLS_CLOSE))return n;const s=DSML_RE_TRAILING_LT.exec(e);if(s)return s.index;const o=e.indexOf("|");return-1!==o&&dsmlUnterminated(e.slice(o))?o:-1}function decodePlainToolCallTags(e,t){if(!e||-1===e.indexOf("<"))return e;let n="",s=0;for(;;){const o=TEXT_TOOL_TAG_OPEN_RE.exec(e.slice(s));if(!o)break;const r=s+o.index,a=o[0];if(a.includes(DSML_TAG_MARK)){n+=e.slice(s,r+a.length),s=r+a.length;continue}const l=e.slice(r+a.length),i=TEXT_TOOL_TAG_CLOSE_RE.exec(l);if(!i)break;const c=textCallsIn(l.slice(0,i.index));if(n+=e.slice(s,r),s=r+a.length+i.index+i[0].length,c.length)for(const e of c)t.push(e);else n+=e.slice(r,s)}return n+e.slice(s)}function plainToolTagHoldAt(e){if(!e||-1===e.indexOf("<"))return-1;let t=0;for(;;){const n=TEXT_TOOL_TAG_OPEN_RE.exec(e.slice(t));if(!n)return-1;const s=t+n.index;if(n[0].includes(DSML_TAG_MARK)){t=s+n[0].length;continue}const o=e.slice(s+n[0].length);return TEXT_TOOL_TAG_CLOSE_RE.test(o)?-1:s}}function makeDeepSeekEnvelopeStripper(){let e="";const t=[],n=e=>dsmlResidue(decodePlainToolCallTags(e,t)),s=s=>{e+="string"==typeof s?s:"";const o=decodeDeepSeekDSML(e);e=o.text;for(const e of o.calls)t.push(e);e=e.replace(DSML_RE_WRAPPER_TAG,"");const r=dsmlHoldFrom(e);let a;-1!==r&&e.length-r<=4194304?(a=e.slice(0,r),e=e.slice(r)):(a=e,e="");const l=plainToolTagHoldAt(a);return-1!==l&&(e=a.slice(l)+e,a=a.slice(0,l)),n(a)};return s.flush=()=>{const s=decodeDeepSeekDSML(e);e="";for(const e of s.calls)t.push(e);const o=decodeDeepSeekDSMLDrift(s.text);for(const e of o.calls)t.push(e);return n(o.text)},s.calls=()=>t.slice(),s}const TEXT_TOOL_TAG_OPEN_RE=/<\s*tool_calls?\b[^>]{0,80}>/i,TEXT_TOOL_TAG_CLOSE_RE=/<\s*\/\s*tool_calls?\s*>/i,TEXT_FENCE_RE=/```[ \t]*[A-Za-z0-9_+-]*[ \t]*\n?([\s\S]*?)```/,TEXT_FENCE_OPEN_RE=/```[ \t]*[A-Za-z0-9_+-]*[ \t]*\n?/,DSML_TAG_MARK="|";function asTextToolCall(e){if(!e||"object"!=typeof e)return null;let t=e;t.function&&"object"==typeof t.function&&(t={...t.function,name:t.function.name||t.name});const n=t.name||t.tool||t.tool_name||t.function_name,s="string"==typeof n?n.trim():"";if(!s)return null;let o=null!=t.arguments?t.arguments:null!=t.parameters?t.parameters:null!=t.args?t.args:null!=t.tool_input?t.tool_input:{};if("string"==typeof o){const e=o.trim()?safeJson(o):{};o=e&&"object"==typeof e?e:{}}return null!=o&&"object"==typeof o||(o={}),{name:s,args:o}}function safeJson(e){try{return JSON.parse(e)}catch{return null}}function textCallsIn(e){const t=String(e||"").trim().replace(/^json\s*/i,"").trim();if(!t)return[];const n=safeJson(t);if(!n)return[];const s=Array.isArray(n)?n:[n],o=[];for(const e of s){const t=asTextToolCall(e);t&&o.push(t)}return o}function nextTextToolEnvelope(e){const t=TEXT_FENCE_RE.exec(e);if(t)return{start:t.index,end:t.index+t[0].length,complete:!0,raw:t[0],body:t[1]};const n=TEXT_FENCE_OPEN_RE.exec(e);return n?{start:n.index,end:e.length,complete:!1,body:e.slice(n.index+n[0].length)}:null}function trailingHeadFrom(e,t=!1){if(!e)return-1;const n=e.search(TEXT_TOOL_HEAD_RE);if(-1!==n)return n;const s=/`{1,2}$/.exec(e);if(s)return s.index;const o=e.lastIndexOf("<");if(-1!==o&&couldBeTextToolHead(e.slice(o)))return o;if(t){const t=e.lastIndexOf("{");if(-1!==t&&/^\{\s*(?:"[^"]*"\s*:[\s\S]*|"[^"]*"?\s*|)$/.test(e.slice(t)))return t}return-1}function couldBeTextToolHead(e){const t=e.replace(/^[\s\uFEFF]+/,"");if(!t)return!0;if(t.length<=3&&"```".startsWith(t))return!0;if(t.startsWith("<")&&!TEXT_TOOL_HEAD_RE.test(t)){const e=t.slice(1).replace(/^\/?\s*/,"").toLowerCase();if(e.length<=10&&/^[a-z_]*$/.test(e))return"tool_call".startsWith(e)||"tool_calls".startsWith(e)}return!1}function balancedJsonEnd(e,t){let n=0,s=!1,o=!1;for(let r=t;r<e.length;r++){const t=e[r];if(s)o?o=!1:"\\"===t?o=!0:'"'===t&&(s=!1);else if('"'===t)s=!0;else if("{"===t||"["===t)n++;else if(("}"===t||"]"===t)&&(n--,n<=0))return r+1}return-1}function makeTextToolCallStripper({toolNames:e=null}={}){const t=e?new Set([...e].map(e=>String(e))):null;let n="";const s=[],o=e=>Boolean(e.length)&&(!t||e.every(e=>t.has(e.name))),r=(e,t)=>{const n=textCallsIn(t);if(!o(n))return e;for(const e of n)s.push(e);return""},a=e=>{n+="string"==typeof e?e:"";let a="",l=!1;for(;;){const e=nextTextToolEnvelope(n);if(e){if(a+=n.slice(0,e.start),n=n.slice(e.start),!e.complete){l=!0;break}a+=r(e.raw,e.body),n=n.slice(e.raw.length);continue}const i=TEXT_TOOL_TAG_OPEN_RE.exec(n);if(i){a+=n.slice(0,i.index),n=n.slice(i.index);const e=n.slice(i[0].length),t=TEXT_TOOL_TAG_CLOSE_RE.exec(e);if(!t){l=!0;break}const s=n.slice(0,i[0].length+t.index+t[0].length);a+=r(s,e.slice(0,t.index)),n=n.slice(s.length);continue}const c=t?/\{\s*"/.exec(n):null;if(!c)break;const u=balancedJsonEnd(n,c.index),f=n.slice(0,c.index);if(-1===u){a+=f,n=n.slice(c.index),l=!0;break}const d=textCallsIn(n.slice(c.index,u));if(a+=f,o(d))for(const e of d)s.push(e);else a+=n.slice(c.index,u);n=n.slice(u)}const i=l?0:trailingHeadFrom(n,Boolean(t));return-1===i?(a+=n,n=""):i>0&&(a+=n.slice(0,i),n=n.slice(i)),n.length>TEXT_TOOL_HOLD_MAX&&(a+=n,n=""),a};return a.flush=()=>{const e=n;if(n="",!e)return"";const s=nextTextToolEnvelope(e);if(s)return e.slice(0,s.start)+r(e.slice(s.start),s.body);const o=TEXT_TOOL_TAG_OPEN_RE.exec(e);if(!o){const n=t?/\{\s*"/.exec(e):null;if(!n)return e;const s=balancedJsonEnd(e,n.index);return-1===s?e:e.slice(0,n.index)+r(e.slice(n.index,s),e.slice(n.index,s))+e.slice(s)}const a=e.slice(o.index+o[0].length).replace(TEXT_TOOL_TAG_CLOSE_RE,"");return e.slice(0,o.index)+r(e.slice(o.index),a)},a.calls=()=>s.slice(),a}const TEXT_TOOL_HEAD_RE=/```|<\s*tool_calls?\b/i,TEXT_TOOL_HOLD_MAX=65536;function isLocalEndpoint(e){let t="",n="";if(""===String(null==e?"":e).trim())return!1;try{const s=new URL(normalizeBase(e));t=s.hostname.toLowerCase(),n=s.protocol.toLowerCase()}catch{return!1}if("http:"!==n&&"https:"!==n)return!1;if(!t)return!1;if(t.startsWith("[")&&t.endsWith("]")&&(t=t.slice(1,-1)),!t||/[\s/\\@]/.test(t))return!1;if("localhost"===t||t.endsWith(".localhost"))return!0;if(/\.(local|internal|lan)$/.test(t))return!0;if(t.includes(":"))return"::1"===t||"0:0:0:0:0:0:0:1"===t||!!/^f[cd][0-9a-f]{2}:/.test(t)||!!/^fe[89ab][0-9a-f]:/.test(t);const s=/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/.exec(t);if(s){const e=s.slice(1).map(Number);if(e.some(e=>e>255))return!1;const[t,n]=e;return 127===t||10===t||172===t&&n>=16&&n<=31||192===t&&168===n||169===t&&254===n}return!t.includes(".")}function remoteRefusal(e){if(isLocalEndpoint(e))return null;const t=new Error(`local: ${JSON.stringify(String(e||""))} is not on this machine, so it is not the local class. Running a model you own is free because there is no vendor to pay — a remote URL here would be an unpaid turn instead. Use the aegis or byok class for remote models.`);return t.status=400,t}async function probe(e=DEFAULT_BASE){const t=baseOf(e);try{return{running:(await fetch(`${t}/api/tags`,{signal:AbortSignal.timeout(1500)})).ok,baseURL:t}}catch{return{running:!1,baseURL:t}}}async function listTags(e=DEFAULT_BASE){const t=await fetch(`${baseOf(e)}/api/tags`);if(!t.ok){const e=new Error(`local: /api/tags answered ${t.status}`);throw e.status=t.status,e}const n=await t.json();return(n&&n.models||[]).map(e=>({id:e&&e.name,...e&&e.details?{details:e.details}:{}})).filter(e=>e.id)}const UNLOAD_TIMEOUT_MS=4e3,RESIDENT_TIMEOUT_MS=3e5,DEFAULT_WARM_SECS=1800;async function unload(e,t){if(!t)return{ok:!1};const n=baseOf(e);if(!isLocalEndpoint(n))return{ok:!1};try{return{ok:(await fetch(`${n}/api/chat`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({model:String(t),messages:[],stream:!1,keep_alive:0}),signal:AbortSignal.timeout(4e3)})).ok}}catch{return{ok:!1}}}function normalizeRow(e){if(!e||"object"!=typeof e)return null;const t={role:e.role||"user"};return null!=e.content&&(t.content=e.content),e.name&&(t.name=e.name),e.tool_call_id&&(t.tool_call_id=e.tool_call_id),Array.isArray(e.tool_calls)&&e.tool_calls.length&&(t.tool_calls=e.tool_calls),t}function parseEvent(e){const t=String(e).split("\n");let n="",s=!1;for(const e of t){if(!e||e.startsWith(":"))continue;const t=e.indexOf(":"),o=-1===t?e:e.slice(0,t),r=-1===t?"":e.slice(t+1).replace(/^ /,"");"data"===o?(n+=r,s=!0):"event"!==o&&"id"!==o&&"retry"!==o||(s=!0)}if(!s||!n)return null;if("[DONE]"===n)return{done:!0};try{return{json:JSON.parse(n)}}catch{return null}}async function readSSE(e,t,{idleTimeoutMs:n=3e5}={}){const s=e.body.getReader(),o=new TextDecoder;let r="",a=null,l=()=>{};const i=new Promise((e,t)=>{l=t}),c=()=>{a&&clearTimeout(a),a=setTimeout(()=>{l(new Error(`local: the model stopped responding — no output for ${Math.round(n/1e3)}s`))},n)};c();try{for(;;){const e=await Promise.race([s.read(),i]);if(e.done)break;let n;for(r+=o.decode(e.value,{stream:!0}),r=r.replace(/\r\n/g,"\n");(n=r.indexOf("\n\n"))>=0;){const e=r.slice(0,n);r=r.slice(n+2);const s=parseEvent(e);if(s){if(s.done)return;s.json&&(c(),t(s.json))}}}}finally{a&&clearTimeout(a);try{await s.cancel()}catch{}}}const localCallQueues=new Map;function runSerialized(e,t){const n=(localCallQueues.get(e)||Promise.resolve()).then(t,t);return localCallQueues.set(e,n.then(()=>{},()=>{})),n}const activeCountByKey=new Map,warmModelByBase=new Map;function swapWarmModel(e,t){if(!t)return;const n=warmModelByBase.get(e);warmModelByBase.set(e,t),n&&n!==t&&(activeCountByKey.get(`${e}|${n}`)||unload(e,n).catch(()=>{}))}async function unloadAll(){const e=[...warmModelByBase.entries()];warmModelByBase.clear(),await Promise.all(e.map(([e,t])=>unload(e,t)))}function warmSecsFor({warmSecs:e}={}){const t=Number(e);if(Number.isFinite(t)&&t>=0)return Math.floor(t);const n=Number(process.env&&process.env.AEGIS_LOCAL_WARM_SECS);return Number.isFinite(n)&&n>=0?Math.floor(n):1800}const residentMemo=new Map;function residentKey(e,t,n){return`${e}\0${t}\0${n}`}function residentSecsLeft(e,t,n,{dialer:s=fetch,now:o=Date.now()}={}){const r=residentMemo.get(residentKey(e,t,n));if(!r||r.dialer!==s)return 0;const a=Math.round((r.until-o)/1e3);return a<=0?(residentMemo.delete(residentKey(e,t,n)),0):a}function residentEntry(e,t,n,{dialer:s=fetch,now:o=Date.now()}={}){const r=residentMemo.get(residentKey(e,t,n));return r&&r.dialer===s&&r.until-o>0?r:null}function sameModel(e,t){const n=String(e||""),s=String(t||"");return!(!n||!s)&&(n===s||n.startsWith(`${s}:`)||n.startsWith(`${s}@`))}const WINDOW_TIMEOUT_MS=3e3;async function windowOf(e,t,{signal:n}={}){const s=new AbortController,o=()=>s.abort();if(n){if(n.aborted)return null;"function"==typeof n.addEventListener&&n.addEventListener("abort",o,{once:!0})}const r=setTimeout(()=>s.abort(),3e3);r&&"function"==typeof r.unref&&r.unref();try{const n=await fetch(`${e}/api/ps`,{method:"GET",signal:s.signal});if(!n||!n.ok||"function"!=typeof n.json)return null;const o=await n.json(),r=(o&&o.models||[]).find(e=>sameModel(e&&(e.name||e.model),t)),a=r&&Number(r.context_length);return Number.isFinite(a)&&a>0?a:null}catch{return null}finally{clearTimeout(r),n&&"function"==typeof n.removeEventListener&&n.removeEventListener("abort",o)}}async function ensureResident({baseURL:e=DEFAULT_BASE,model:t,system:n="",signal:s,warmSecs:o,firstByteTimeoutMs:r}={}){const a=baseOf(e);if(!isLocalEndpoint(a))return{ok:!1,skipped:"remote"};if(!t||!String(t).trim())return{ok:!1,skipped:"no-model"};const l=warmSecsFor({warmSecs:o}),i="string"==typeof n?n:"",c={warmSecs:l,prefixSource:i?"turn-system":"none",prefixChars:i.length};if(l<=0)return{ok:!1,skipped:"warm-disabled",...c};const u=fetch,f=residentSecsLeft(a,t,i,{dialer:u});if(f>=Math.min(l,60)){const e=residentEntry(a,t,i,{dialer:u});return{ok:!0,already:!0,memo:!0,remainingSecs:f,contextLength:e&&e.contextLength||null,...c}}const d=new AbortController,_=()=>d.abort();s&&(s.aborted?d.abort():"function"==typeof s.addEventListener&&s.addEventListener("abort",_,{once:!0}));const m=Number(r),p=Number.isFinite(m)&&m>0?Math.min(m,3e5):3e5;let E=!1,g=null;const T=setTimeout(()=>{E=!0,d.abort()},p);T&&"function"==typeof T.unref&&T.unref();try{try{const e=await fetch(`${a}/api/ps`,{method:"GET",signal:d.signal});if(e&&e.ok&&"function"==typeof e.json){const n=await e.json(),s=(n&&n.models||[]).find(e=>sameModel(e&&(e.name||e.model),t));if(s&&Number.isFinite(s.context_length)&&s.context_length>0&&(g=s.context_length),s&&s.expires_at){const e=Math.round((new Date(s.expires_at).getTime()-Date.now())/1e3);if(Number.isFinite(e)&&e>=Math.min(l,60))return residentMemo.set(residentKey(a,t,i),{until:Date.now()+1e3*e,dialer:u,contextLength:g}),{ok:!0,already:!0,remainingSecs:e,contextLength:g,...c}}}}catch{}if(d.signal.aborted)return{ok:!1,aborted:!0,timeout:E,contextLength:g,...c};const e=i?[{role:"system",content:i},{role:"user",content:"PONG"}]:[{role:"user",content:"PONG"}],n=await fetch(`${a}/api/chat`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({model:String(t),keep_alive:l,stream:!1,messages:e,options:{num_predict:1}}),signal:d.signal});let s=null,o=null;if(n&&"function"==typeof n.text){const e=await n.text().catch(()=>"");try{const t=JSON.parse(e);Number.isFinite(t.prompt_eval_count)&&(s=t.prompt_eval_count),Number.isFinite(t.eval_count)&&(o=t.eval_count)}catch{}}return n&&n.ok&&(null==g&&(g=await windowOf(a,t,{signal:d.signal})||null),residentMemo.set(residentKey(a,t,i),{until:Date.now()+1e3*l,dialer:u,contextLength:g}),swapWarmModel(a,t)),{ok:!(!n||!n.ok),status:n&&n.status,pinned:!0,promptTokens:s,outputTokens:o,contextLength:g,...c}}catch(e){return{ok:!1,error:String(e&&e.message||e),timeout:E,contextLength:g,...c}}finally{clearTimeout(T),s&&"function"==typeof s.removeEventListener&&s.removeEventListener("abort",_)}}function stoppedTurn(e,{content:t="",usage:n=null}={}){const s={id:"local",model:String(e),choices:[{index:0,message:{role:"assistant",content:t},finish_reason:"stop"}]};return n&&(s.usage=n),s}function fitToWindowOf({rows:e,system:t,tools:n,contextLength:s,maxTokens:o}){const r=Number(s);if(!Number.isFinite(r)||r<=0)return null;const a=(Array.isArray(e)?e:[]).filter(e=>e&&"system"!==e.role),l=Array.isArray(n)&&n.length?estimateTokens(JSON.stringify(n)):0,i=Number(o),c=Number.isFinite(i)&&i>0?i:Math.round(r/4),u=trimContext({messages:a,system:"string"==typeof t?t:"",budgetTokens:r,reserveTokens:c,fixedTokens:l});return{window:r,reserveTokens:c,toolTokens:l,dropped:u.dropped,messages:u.messages,over:u.estimatedTokens>Math.max(0,r-c),estimatedTokens:u.estimatedTokens}}async function chatOne({baseURL:e=DEFAULT_BASE,model:t,messages:n,system:s,prompt:o,maxTokens:r,temperature:a,tools:l,toolChoice:i,signal:c,onDelta:u,firstByteTimeoutMs:f=3e5,contextLength:d}={}){const _=baseOf(e),m=remoteRefusal(_);if(m)throw m;if(!t||!String(t).trim()){const e=new Error("local: no model selected — pick one from the model list, or type a tag");throw e.status=400,e}const p=[];s&&p.push({role:"system",content:s});for(const e of Array.isArray(n)?n:[]){if(e&&"system"===e.role)continue;const t=normalizeRow(e);t&&p.push(t)}const E="string"==typeof o||Array.isArray(o)?o:"";if(!(""===E||Array.isArray(E)&&0===E.length)){const e=p[p.length-1],t=attachmentsModule.flattenContent(E),n=e?attachmentsModule.flattenContent(e.content):null;e&&"user"===e.role&&n===t||p.push({role:"user",content:E})}if(!p.length){const e=new Error("local: nothing to send — no prompt and no messages");throw e.status=400,e}let g=null;if(null!=d){const e=p[0]&&"system"===p[0].role?p[0]:null;if(g=fitToWindowOf({rows:p,system:e&&e.content||s||"",tools:l,contextLength:d,maxTokens:r}),g){const t=g.messages;p.length=0,e&&p.push(e),p.push(...t)}}const T={model:String(t),messages:p,stream:!0,stream_options:{include_usage:!0},...r?{max_tokens:r}:{},...null!=a?{temperature:a}:{},...l&&l.length?{tools:l}:{},...i?{tool_choice:i}:{}},h=new AbortController;let S=!1;const L=setTimeout(()=>{S=!0,h.abort()},f);L&&"function"==typeof L.unref&&L.unref();const y=()=>h.abort();let M;c&&(c.aborted?h.abort():"function"==typeof c.addEventListener&&c.addEventListener("abort",y,{once:!0}));try{M=await fetch(`${_}/v1/chat/completions`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(T),signal:h.signal})}catch(e){if(S||isHeadersDeadline(e)){const e=S?`sent nothing in ${Math.round(f/1e3)}s`:`sent no response headers before this runtime's own ${Math.round(300)}s deadline`,n=new Error(`local: ${t} ${e} — the daemon is still loading the model, or its prompt prefill is longer than that. \`ollama ps\` shows which; a smaller prompt or a smaller model is the way through.`);throw n.status=0,n.code="timeout",n}if(c&&c.aborted||h.signal.aborted)return stoppedTurn(t);throw e}finally{clearTimeout(L)}if(!M.ok){let e="";try{e=await M.text()}catch{}const t=new Error(`local: chat/completions ${M.status}${e?` — ${e.slice(0,400)}`:""}`);throw t.status=M.status,t}let A="",O=null;const x=[],R=new Map,D=makeDeepSeekEnvelopeStripper(),b=makeTextToolCallStripper({toolNames:(Array.isArray(l)?l:[]).map(e=>e&&e.function&&e.function.name||e&&e.name||"").filter(Boolean)});try{await readSSE(M,e=>{e&&e.usage&&(O=e.usage);const t=e&&Array.isArray(e.choices)?e.choices[0]:null;if(!t)return;const n=t.delta||{};if("string"==typeof n.content&&n.content){const e=b(D(n.content));e&&(A+=e,"function"==typeof u&&u({text:e}))}const s=n.tool_calls||[];for(const e of s){const t=Number.isInteger(e.index)?e.index:x.length;let n=R.get(t);n||(n={id:"",type:"function",function:{name:"",arguments:""}},R.set(t,n)),e.id&&(n.id=e.id),e.type&&(n.type=e.type);const s=e.function||{};s.name&&(n.function.name=s.name),s.arguments&&(n.function.arguments+=s.arguments)}},{idleTimeoutMs:3e5})}catch(e){if(c&&c.aborted)return stoppedTurn(t,{content:A,usage:O});throw e}finally{c&&"function"==typeof c.removeEventListener&&c.removeEventListener("abort",y)}const w=`${b(D.flush())||""}${b.flush()||""}`;w&&(A+=w,"function"==typeof u&&u({text:w}));for(const[e,t]of[...R.entries()].sort((e,t)=>e[0]-t[0]))(t.function.name||t.function.arguments)&&(t.id||(t.id=`call_${e}`),x.push(t));const k={role:"assistant",content:A};x.length&&(k.tool_calls=x);const N=D.calls(),C=b.calls(),v={id:"local",model:String(t),choices:[{index:0,message:k,finish_reason:x.length?"tool_calls":"stop"}],...O?{usage:O}:{}};return(x.length||N.length||C.length)&&(v.toolCalls=[...x.map(e=>({id:e.id,name:e.function.name,args:e.function.arguments})),...N.map(e=>({id:"",name:e.name,args:e.args||{}})),...C.map(e=>({id:"",name:e.name,args:e.args||{}}))],(N.length||C.length)&&"tool_calls"!==v.choices[0].finish_reason&&(v.choices[0].finish_reason="tool_calls")),g&&(v.window={contextLength:g.window,dropped:g.dropped,toolTokens:g.toolTokens,estimatedTokens:g.estimatedTokens,reserveTokens:g.reserveTokens,over:g.over}),v}async function chat(e={}){const t=baseOf(e&&e.baseURL),n=e&&e.model,s=`${t}|${n}`;activeCountByKey.set(s,(activeCountByKey.get(s)||0)+1);try{let o=null;const r=await runSerialized(s,async()=>{o=await ensureResident({baseURL:e&&e.baseURL,model:n,system:e&&e.system,signal:e&&e.signal,warmSecs:e&&e.warmSecs,firstByteTimeoutMs:e&&e.firstByteTimeoutMs});let s=o&&o.contextLength||null;const r=isLocalEndpoint(t)&&""!==String(n||"").trim();return!s&&r&&o&&!0!==o.ok&&!o.skipped&&(s=await windowOf(t,n,{signal:e&&e.signal})||null),chatOne({...e,contextLength:s})});return swapWarmModel(t,n),o&&"object"==typeof r&&r&&(r.residency=o),r}finally{const e=(activeCountByKey.get(s)||1)-1;e<=0?activeCountByKey.delete(s):activeCountByKey.set(s,e)}}module.exports={DEFAULT_BASE:DEFAULT_BASE,DEFAULT_WARM_SECS:1800,RESIDENT_TIMEOUT_MS:3e5,SSE_IDLE_TIMEOUT_MS:3e5,FIRST_BYTE_TIMEOUT_MS:3e5,PROBE_TIMEOUT_MS:1500,baseOf:baseOf,normalizeBase:normalizeBase,isLocalEndpoint:isLocalEndpoint,remoteRefusal:remoteRefusal,probe:probe,listTags:listTags,readSSE:readSSE,chat:chat,ensureResident:ensureResident,residentSecsLeft:residentSecsLeft,residentEntry:residentEntry,unload:unload,unloadAll:unloadAll,makeTextToolCallStripper:makeTextToolCallStripper,makeDeepSeekEnvelopeStripper:makeDeepSeekEnvelopeStripper,textCallsIn:textCallsIn,fitToWindowOf:fitToWindowOf,isHeadersDeadline:isHeadersDeadline,HEADERS_DEADLINE_MS:3e5,windowOf:windowOf,stoppedTurn:stoppedTurn};
@@ -1,3 +1,8 @@
1
+ // SPDX-License-Identifier: AGPL-3.0-or-later
2
+ // Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
3
+ // AEGIS Code (aegiscode) — source: https://github.com/aegisinfo/aegiscode-plugin
4
+ // Conveying a modified copy, or running one as a network service, owes the
5
+ // corresponding source under this licence (§5/§13) — see LICENSING.md.
1
6
  // Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
2
7
  // AEGIS Code (aegiscode) — source: https://github.com/aegisinfo/aegiscode-plugin
3
8
  // SPDX-License-Identifier: AGPL-3.0-or-later
@@ -1,3 +1,8 @@
1
+ // SPDX-License-Identifier: AGPL-3.0-or-later
2
+ // Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
3
+ // AEGIS Code (aegiscode) — source: https://github.com/aegisinfo/aegiscode-plugin
4
+ // Conveying a modified copy, or running one as a network service, owes the
5
+ // corresponding source under this licence (§5/§13) — see LICENSING.md.
1
6
  // Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
2
7
  // AEGIS Code (aegiscode) — source: https://github.com/aegisinfo/aegiscode-plugin
3
8
  // SPDX-License-Identifier: AGPL-3.0-or-later
@@ -1,3 +1,8 @@
1
+ // SPDX-License-Identifier: AGPL-3.0-or-later
2
+ // Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
3
+ // AEGIS Code (aegiscode) — source: https://github.com/aegisinfo/aegiscode-plugin
4
+ // Conveying a modified copy, or running one as a network service, owes the
5
+ // corresponding source under this licence (§5/§13) — see LICENSING.md.
1
6
  // Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
2
7
  // AEGIS Code (aegiscode) — source: https://github.com/aegisinfo/aegiscode-plugin
3
8
  // SPDX-License-Identifier: AGPL-3.0-or-later
@@ -1,3 +1,5 @@
1
+ // SPDX-License-Identifier: AGPL-3.0-or-later
2
+ // Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
1
3
  // Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
2
4
  // SPDX-License-Identifier: AGPL-3.0-or-later
3
- "use strict";const fs=require("node:fs"),os=require("node:os"),path=require("node:path"),MAX_ENTRIES=200;function storePath(e=process.env){const t=e||{},r=process.env||{},n=t.AEGIS_PRO_SESSIONS_FILE||r.AEGIS_PRO_SESSIONS_FILE;if(n)return n;const s=t.AEGISCODE_HOME||t.AEGIS_HOME||r.AEGISCODE_HOME||r.AEGIS_HOME;return path.join(s?path.resolve(String(s).trim()):path.join(os.homedir(),".aegiscode"),"pro-sessions.json")}function read(e=process.env){try{const t=fs.readFileSync(storePath(e),"utf8"),r=JSON.parse(t);if(!r||"object"!=typeof r||Array.isArray(r))return{};const n={};for(const[e,t]of Object.entries(r))t&&"object"==typeof t&&"string"==typeof t.id&&t.id&&(n[e]={id:t.id,at:Number(t.at)||0});return n}catch{return{}}}function prune(e){const t=Object.keys(e);if(t.length<=MAX_ENTRIES)return e;t.sort(((t,r)=>(e[r].at||0)-(e[t].at||0)));const r={};for(const n of t.slice(0,MAX_ENTRIES))r[n]=e[n];return r}function write(e,t=process.env){try{const r=storePath(t);fs.mkdirSync(path.dirname(r),{recursive:!0});const n=`${r}.${process.pid}.tmp`;return fs.writeFileSync(n,JSON.stringify(prune(e),null,2),{mode:384}),fs.renameSync(n,r),!0}catch{return!1}}function get(e,t=process.env){if(!e)return null;const r=read(t);return r[e]?r[e].id:null}function set(e,t,r=process.env){if(!e||"string"!=typeof t||!t)return!1;const n=read(r);return n[e]={id:t,at:Date.now()},write(n,r)}function del(e,t=process.env){if(!e)return!1;const r=read(t);return!r[e]||(delete r[e],write(r,t))}module.exports={storePath:storePath,read:read,write:write,get:get,set:set,del:del,MAX_ENTRIES:MAX_ENTRIES};
5
+ "use strict";const fs=require("node:fs"),os=require("node:os"),path=require("node:path"),MAX_ENTRIES=200;function storePath(e=process.env){const t=e||{},r=process.env||{},n=t.AEGIS_PRO_SESSIONS_FILE||r.AEGIS_PRO_SESSIONS_FILE;if(n)return n;const s=t.AEGISCODE_HOME||t.AEGIS_HOME||r.AEGISCODE_HOME||r.AEGIS_HOME;return path.join(s?path.resolve(String(s).trim()):path.join(os.homedir(),".aegiscode"),"pro-sessions.json")}function read(e=process.env){try{const t=fs.readFileSync(storePath(e),"utf8"),r=JSON.parse(t);if(!r||"object"!=typeof r||Array.isArray(r))return{};const n={};for(const[e,t]of Object.entries(r))t&&"object"==typeof t&&"string"==typeof t.id&&t.id&&(n[e]={id:t.id,at:Number(t.at)||0});return n}catch{return{}}}function prune(e){const t=Object.keys(e);if(t.length<=200)return e;t.sort((t,r)=>(e[r].at||0)-(e[t].at||0));const r={};for(const n of t.slice(0,200))r[n]=e[n];return r}function write(e,t=process.env){try{const r=storePath(t);fs.mkdirSync(path.dirname(r),{recursive:!0});const n=`${r}.${process.pid}.tmp`;return fs.writeFileSync(n,JSON.stringify(prune(e),null,2),{mode:384}),fs.renameSync(n,r),!0}catch{return!1}}function get(e,t=process.env){if(!e)return null;const r=read(t);return r[e]?r[e].id:null}function set(e,t,r=process.env){if(!e||"string"!=typeof t||!t)return!1;const n=read(r);return n[e]={id:t,at:Date.now()},write(n,r)}function del(e,t=process.env){if(!e)return!1;const r=read(t);return!r[e]||(delete r[e],write(r,t))}module.exports={storePath:storePath,read:read,write:write,get:get,set:set,del:del,MAX_ENTRIES:200};