@gencode/agents 0.0.1

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 (353) hide show
  1. package/dist/bootstrap/bootstrap-layout.d.ts +23 -0
  2. package/dist/bootstrap/bootstrap-layout.d.ts.map +1 -0
  3. package/dist/bootstrap/bootstrap-layout.js +151 -0
  4. package/dist/bootstrap/bootstrap-layout.js.map +1 -0
  5. package/dist/bootstrap/bootstrap.d.ts +36 -0
  6. package/dist/bootstrap/bootstrap.d.ts.map +1 -0
  7. package/dist/bootstrap/bootstrap.js +136 -0
  8. package/dist/bootstrap/bootstrap.js.map +1 -0
  9. package/dist/bootstrap/templates/AGENTS_MD.d.ts +2 -0
  10. package/dist/bootstrap/templates/AGENTS_MD.d.ts.map +1 -0
  11. package/dist/bootstrap/templates/AGENTS_MD.js +223 -0
  12. package/dist/bootstrap/templates/AGENTS_MD.js.map +1 -0
  13. package/dist/bootstrap/templates/BOOTSTRAP_MD.d.ts +2 -0
  14. package/dist/bootstrap/templates/BOOTSTRAP_MD.d.ts.map +1 -0
  15. package/dist/bootstrap/templates/BOOTSTRAP_MD.js +66 -0
  16. package/dist/bootstrap/templates/BOOTSTRAP_MD.js.map +1 -0
  17. package/dist/bootstrap/templates/HEARTBEAT_MD.d.ts +2 -0
  18. package/dist/bootstrap/templates/HEARTBEAT_MD.d.ts.map +1 -0
  19. package/dist/bootstrap/templates/HEARTBEAT_MD.js +16 -0
  20. package/dist/bootstrap/templates/HEARTBEAT_MD.js.map +1 -0
  21. package/dist/bootstrap/templates/IDENTITY_MD.d.ts +2 -0
  22. package/dist/bootstrap/templates/IDENTITY_MD.d.ts.map +1 -0
  23. package/dist/bootstrap/templates/IDENTITY_MD.js +31 -0
  24. package/dist/bootstrap/templates/IDENTITY_MD.js.map +1 -0
  25. package/dist/bootstrap/templates/SOUL_MD.d.ts +2 -0
  26. package/dist/bootstrap/templates/SOUL_MD.d.ts.map +1 -0
  27. package/dist/bootstrap/templates/SOUL_MD.js +47 -0
  28. package/dist/bootstrap/templates/SOUL_MD.js.map +1 -0
  29. package/dist/bootstrap/templates/TOOLS_MD.d.ts +2 -0
  30. package/dist/bootstrap/templates/TOOLS_MD.d.ts.map +1 -0
  31. package/dist/bootstrap/templates/TOOLS_MD.js +51 -0
  32. package/dist/bootstrap/templates/TOOLS_MD.js.map +1 -0
  33. package/dist/bootstrap/templates/USER_MD.d.ts +2 -0
  34. package/dist/bootstrap/templates/USER_MD.d.ts.map +1 -0
  35. package/dist/bootstrap/templates/USER_MD.js +27 -0
  36. package/dist/bootstrap/templates/USER_MD.js.map +1 -0
  37. package/dist/bootstrap/templates/index.d.ts +3 -0
  38. package/dist/bootstrap/templates/index.d.ts.map +1 -0
  39. package/dist/bootstrap/templates/index.js +26 -0
  40. package/dist/bootstrap/templates/index.js.map +1 -0
  41. package/dist/commands/compact.d.ts +28 -0
  42. package/dist/commands/compact.d.ts.map +1 -0
  43. package/dist/commands/compact.js +57 -0
  44. package/dist/commands/compact.js.map +1 -0
  45. package/dist/commands/help.d.ts +3 -0
  46. package/dist/commands/help.d.ts.map +1 -0
  47. package/dist/commands/help.js +50 -0
  48. package/dist/commands/help.js.map +1 -0
  49. package/dist/commands/index.d.ts +6 -0
  50. package/dist/commands/index.d.ts.map +1 -0
  51. package/dist/commands/index.js +32 -0
  52. package/dist/commands/index.js.map +1 -0
  53. package/dist/commands/new.d.ts +3 -0
  54. package/dist/commands/new.d.ts.map +1 -0
  55. package/dist/commands/new.js +4 -0
  56. package/dist/commands/new.js.map +1 -0
  57. package/dist/commands/registry.d.ts +11 -0
  58. package/dist/commands/registry.d.ts.map +1 -0
  59. package/dist/commands/registry.js +122 -0
  60. package/dist/commands/registry.js.map +1 -0
  61. package/dist/commands/reset.d.ts +3 -0
  62. package/dist/commands/reset.d.ts.map +1 -0
  63. package/dist/commands/reset.js +4 -0
  64. package/dist/commands/reset.js.map +1 -0
  65. package/dist/commands/skill.d.ts +7 -0
  66. package/dist/commands/skill.d.ts.map +1 -0
  67. package/dist/commands/skill.js +23 -0
  68. package/dist/commands/skill.js.map +1 -0
  69. package/dist/commands/types.d.ts +57 -0
  70. package/dist/commands/types.d.ts.map +1 -0
  71. package/dist/commands/types.js +2 -0
  72. package/dist/commands/types.js.map +1 -0
  73. package/dist/config/agents-config.d.ts +85 -0
  74. package/dist/config/agents-config.d.ts.map +1 -0
  75. package/dist/config/agents-config.js +257 -0
  76. package/dist/config/agents-config.js.map +1 -0
  77. package/dist/config/index.d.ts +9 -0
  78. package/dist/config/index.d.ts.map +1 -0
  79. package/dist/config/index.js +9 -0
  80. package/dist/config/index.js.map +1 -0
  81. package/dist/config/types.d.ts +87 -0
  82. package/dist/config/types.d.ts.map +1 -0
  83. package/dist/config/types.js +6 -0
  84. package/dist/config/types.js.map +1 -0
  85. package/dist/history/compaction.d.ts +42 -0
  86. package/dist/history/compaction.d.ts.map +1 -0
  87. package/dist/history/compaction.js +135 -0
  88. package/dist/history/compaction.js.map +1 -0
  89. package/dist/history/index.d.ts +57 -0
  90. package/dist/history/index.d.ts.map +1 -0
  91. package/dist/history/index.js +145 -0
  92. package/dist/history/index.js.map +1 -0
  93. package/dist/history/limit.d.ts +13 -0
  94. package/dist/history/limit.d.ts.map +1 -0
  95. package/dist/history/limit.js +32 -0
  96. package/dist/history/limit.js.map +1 -0
  97. package/dist/history/repair.d.ts +13 -0
  98. package/dist/history/repair.d.ts.map +1 -0
  99. package/dist/history/repair.js +25 -0
  100. package/dist/history/repair.js.map +1 -0
  101. package/dist/history/token-estimate.d.ts +22 -0
  102. package/dist/history/token-estimate.d.ts.map +1 -0
  103. package/dist/history/token-estimate.js +38 -0
  104. package/dist/history/token-estimate.js.map +1 -0
  105. package/dist/index.d.ts +41 -0
  106. package/dist/index.d.ts.map +1 -0
  107. package/dist/index.js +35 -0
  108. package/dist/index.js.map +1 -0
  109. package/dist/llm/client.d.ts +53 -0
  110. package/dist/llm/client.d.ts.map +1 -0
  111. package/dist/llm/client.js +214 -0
  112. package/dist/llm/client.js.map +1 -0
  113. package/dist/llm/openai-completions-compat.d.ts +23 -0
  114. package/dist/llm/openai-completions-compat.d.ts.map +1 -0
  115. package/dist/llm/openai-completions-compat.js +602 -0
  116. package/dist/llm/openai-completions-compat.js.map +1 -0
  117. package/dist/llm/openai-stream-error.d.ts +11 -0
  118. package/dist/llm/openai-stream-error.d.ts.map +1 -0
  119. package/dist/llm/openai-stream-error.js +77 -0
  120. package/dist/llm/openai-stream-error.js.map +1 -0
  121. package/dist/loop-detection/session-state.d.ts +5 -0
  122. package/dist/loop-detection/session-state.d.ts.map +1 -0
  123. package/dist/loop-detection/session-state.js +16 -0
  124. package/dist/loop-detection/session-state.js.map +1 -0
  125. package/dist/loop-detection/tool-loop-detection.d.ts +122 -0
  126. package/dist/loop-detection/tool-loop-detection.d.ts.map +1 -0
  127. package/dist/loop-detection/tool-loop-detection.js +516 -0
  128. package/dist/loop-detection/tool-loop-detection.js.map +1 -0
  129. package/dist/memory/builtin-provider.d.ts +5 -0
  130. package/dist/memory/builtin-provider.d.ts.map +1 -0
  131. package/dist/memory/builtin-provider.js +42 -0
  132. package/dist/memory/builtin-provider.js.map +1 -0
  133. package/dist/memory/config.d.ts +50 -0
  134. package/dist/memory/config.d.ts.map +1 -0
  135. package/dist/memory/config.js +46 -0
  136. package/dist/memory/config.js.map +1 -0
  137. package/dist/memory/embedding-registry.d.ts +37 -0
  138. package/dist/memory/embedding-registry.d.ts.map +1 -0
  139. package/dist/memory/embedding-registry.js +56 -0
  140. package/dist/memory/embedding-registry.js.map +1 -0
  141. package/dist/memory/embeddings.d.ts +11 -0
  142. package/dist/memory/embeddings.d.ts.map +1 -0
  143. package/dist/memory/embeddings.js +40 -0
  144. package/dist/memory/embeddings.js.map +1 -0
  145. package/dist/memory/fs-utils.d.ts +12 -0
  146. package/dist/memory/fs-utils.d.ts.map +1 -0
  147. package/dist/memory/fs-utils.js +24 -0
  148. package/dist/memory/fs-utils.js.map +1 -0
  149. package/dist/memory/hybrid.d.ts +43 -0
  150. package/dist/memory/hybrid.d.ts.map +1 -0
  151. package/dist/memory/hybrid.js +80 -0
  152. package/dist/memory/hybrid.js.map +1 -0
  153. package/dist/memory/internal.d.ts +28 -0
  154. package/dist/memory/internal.d.ts.map +1 -0
  155. package/dist/memory/internal.js +270 -0
  156. package/dist/memory/internal.js.map +1 -0
  157. package/dist/memory/manager-search.d.ts +61 -0
  158. package/dist/memory/manager-search.d.ts.map +1 -0
  159. package/dist/memory/manager-search.js +106 -0
  160. package/dist/memory/manager-search.js.map +1 -0
  161. package/dist/memory/manager.d.ts +126 -0
  162. package/dist/memory/manager.d.ts.map +1 -0
  163. package/dist/memory/manager.js +1006 -0
  164. package/dist/memory/manager.js.map +1 -0
  165. package/dist/memory/memory-schema.d.ts +11 -0
  166. package/dist/memory/memory-schema.d.ts.map +1 -0
  167. package/dist/memory/memory-schema.js +78 -0
  168. package/dist/memory/memory-schema.js.map +1 -0
  169. package/dist/memory/memory.d.ts +46 -0
  170. package/dist/memory/memory.d.ts.map +1 -0
  171. package/dist/memory/memory.js +127 -0
  172. package/dist/memory/memory.js.map +1 -0
  173. package/dist/memory/mmr.d.ts +22 -0
  174. package/dist/memory/mmr.d.ts.map +1 -0
  175. package/dist/memory/mmr.js +112 -0
  176. package/dist/memory/mmr.js.map +1 -0
  177. package/dist/memory/provider-registry.d.ts +29 -0
  178. package/dist/memory/provider-registry.d.ts.map +1 -0
  179. package/dist/memory/provider-registry.js +58 -0
  180. package/dist/memory/provider-registry.js.map +1 -0
  181. package/dist/memory/provider.d.ts +40 -0
  182. package/dist/memory/provider.d.ts.map +1 -0
  183. package/dist/memory/provider.js +2 -0
  184. package/dist/memory/provider.js.map +1 -0
  185. package/dist/memory/session-files.d.ts +13 -0
  186. package/dist/memory/session-files.d.ts.map +1 -0
  187. package/dist/memory/session-files.js +116 -0
  188. package/dist/memory/session-files.js.map +1 -0
  189. package/dist/memory/sqlite-vec.d.ts +10 -0
  190. package/dist/memory/sqlite-vec.d.ts.map +1 -0
  191. package/dist/memory/sqlite-vec.js +20 -0
  192. package/dist/memory/sqlite-vec.js.map +1 -0
  193. package/dist/memory/sqlite.d.ts +2 -0
  194. package/dist/memory/sqlite.d.ts.map +1 -0
  195. package/dist/memory/sqlite.js +12 -0
  196. package/dist/memory/sqlite.js.map +1 -0
  197. package/dist/memory/temporal-decay.d.ts +26 -0
  198. package/dist/memory/temporal-decay.d.ts.map +1 -0
  199. package/dist/memory/temporal-decay.js +119 -0
  200. package/dist/memory/temporal-decay.js.map +1 -0
  201. package/dist/memory/watch-bridge.d.ts +20 -0
  202. package/dist/memory/watch-bridge.d.ts.map +1 -0
  203. package/dist/memory/watch-bridge.js +128 -0
  204. package/dist/memory/watch-bridge.js.map +1 -0
  205. package/dist/plugins/boundary-file-read.d.ts +13 -0
  206. package/dist/plugins/boundary-file-read.d.ts.map +1 -0
  207. package/dist/plugins/boundary-file-read.js +31 -0
  208. package/dist/plugins/boundary-file-read.js.map +1 -0
  209. package/dist/plugins/config-state.d.ts +35 -0
  210. package/dist/plugins/config-state.d.ts.map +1 -0
  211. package/dist/plugins/config-state.js +97 -0
  212. package/dist/plugins/config-state.js.map +1 -0
  213. package/dist/plugins/discovery.d.ts +21 -0
  214. package/dist/plugins/discovery.d.ts.map +1 -0
  215. package/dist/plugins/discovery.js +425 -0
  216. package/dist/plugins/discovery.js.map +1 -0
  217. package/dist/plugins/hooks.d.ts +112 -0
  218. package/dist/plugins/hooks.d.ts.map +1 -0
  219. package/dist/plugins/hooks.js +19 -0
  220. package/dist/plugins/hooks.js.map +1 -0
  221. package/dist/plugins/index.d.ts +20 -0
  222. package/dist/plugins/index.d.ts.map +1 -0
  223. package/dist/plugins/index.js +11 -0
  224. package/dist/plugins/index.js.map +1 -0
  225. package/dist/plugins/loader.d.ts +60 -0
  226. package/dist/plugins/loader.d.ts.map +1 -0
  227. package/dist/plugins/loader.js +224 -0
  228. package/dist/plugins/loader.js.map +1 -0
  229. package/dist/plugins/manager.d.ts +20 -0
  230. package/dist/plugins/manager.d.ts.map +1 -0
  231. package/dist/plugins/manager.js +33 -0
  232. package/dist/plugins/manager.js.map +1 -0
  233. package/dist/plugins/manifest-registry.d.ts +15 -0
  234. package/dist/plugins/manifest-registry.d.ts.map +1 -0
  235. package/dist/plugins/manifest-registry.js +37 -0
  236. package/dist/plugins/manifest-registry.js.map +1 -0
  237. package/dist/plugins/manifest.d.ts +6 -0
  238. package/dist/plugins/manifest.d.ts.map +1 -0
  239. package/dist/plugins/manifest.js +80 -0
  240. package/dist/plugins/manifest.js.map +1 -0
  241. package/dist/plugins/path-safety.d.ts +6 -0
  242. package/dist/plugins/path-safety.d.ts.map +1 -0
  243. package/dist/plugins/path-safety.js +32 -0
  244. package/dist/plugins/path-safety.js.map +1 -0
  245. package/dist/plugins/runtime-context.d.ts +12 -0
  246. package/dist/plugins/runtime-context.d.ts.map +1 -0
  247. package/dist/plugins/runtime-context.js +2 -0
  248. package/dist/plugins/runtime-context.js.map +1 -0
  249. package/dist/plugins/runtime.d.ts +12 -0
  250. package/dist/plugins/runtime.d.ts.map +1 -0
  251. package/dist/plugins/runtime.js +13 -0
  252. package/dist/plugins/runtime.js.map +1 -0
  253. package/dist/plugins/schema-validator.d.ts +17 -0
  254. package/dist/plugins/schema-validator.d.ts.map +1 -0
  255. package/dist/plugins/schema-validator.js +26 -0
  256. package/dist/plugins/schema-validator.js.map +1 -0
  257. package/dist/plugins/tool-hooks.d.ts +4 -0
  258. package/dist/plugins/tool-hooks.d.ts.map +1 -0
  259. package/dist/plugins/tool-hooks.js +60 -0
  260. package/dist/plugins/tool-hooks.js.map +1 -0
  261. package/dist/plugins/tools.d.ts +20 -0
  262. package/dist/plugins/tools.d.ts.map +1 -0
  263. package/dist/plugins/tools.js +42 -0
  264. package/dist/plugins/tools.js.map +1 -0
  265. package/dist/plugins/types.d.ts +61 -0
  266. package/dist/plugins/types.d.ts.map +1 -0
  267. package/dist/plugins/types.js +2 -0
  268. package/dist/plugins/types.js.map +1 -0
  269. package/dist/plugins/utils.d.ts +4 -0
  270. package/dist/plugins/utils.d.ts.map +1 -0
  271. package/dist/plugins/utils.js +22 -0
  272. package/dist/plugins/utils.js.map +1 -0
  273. package/dist/runner/runner.d.ts +14 -0
  274. package/dist/runner/runner.d.ts.map +1 -0
  275. package/dist/runner/runner.js +893 -0
  276. package/dist/runner/runner.js.map +1 -0
  277. package/dist/session/session.d.ts +45 -0
  278. package/dist/session/session.d.ts.map +1 -0
  279. package/dist/session/session.js +167 -0
  280. package/dist/session/session.js.map +1 -0
  281. package/dist/skills/skills.d.ts +23 -0
  282. package/dist/skills/skills.d.ts.map +1 -0
  283. package/dist/skills/skills.js +109 -0
  284. package/dist/skills/skills.js.map +1 -0
  285. package/dist/subagent/registry-persist.d.ts +31 -0
  286. package/dist/subagent/registry-persist.d.ts.map +1 -0
  287. package/dist/subagent/registry-persist.js +115 -0
  288. package/dist/subagent/registry-persist.js.map +1 -0
  289. package/dist/subagent/registry.d.ts +52 -0
  290. package/dist/subagent/registry.d.ts.map +1 -0
  291. package/dist/subagent/registry.js +122 -0
  292. package/dist/subagent/registry.js.map +1 -0
  293. package/dist/subagent/types.d.ts +20 -0
  294. package/dist/subagent/types.d.ts.map +1 -0
  295. package/dist/subagent/types.js +2 -0
  296. package/dist/subagent/types.js.map +1 -0
  297. package/dist/system-prompt/builder.d.ts +50 -0
  298. package/dist/system-prompt/builder.d.ts.map +1 -0
  299. package/dist/system-prompt/builder.js +335 -0
  300. package/dist/system-prompt/builder.js.map +1 -0
  301. package/dist/tools/apply-patch.d.ts +15 -0
  302. package/dist/tools/apply-patch.d.ts.map +1 -0
  303. package/dist/tools/apply-patch.js +425 -0
  304. package/dist/tools/apply-patch.js.map +1 -0
  305. package/dist/tools/bash.d.ts +11 -0
  306. package/dist/tools/bash.d.ts.map +1 -0
  307. package/dist/tools/bash.js +13 -0
  308. package/dist/tools/bash.js.map +1 -0
  309. package/dist/tools/cron.d.ts +23 -0
  310. package/dist/tools/cron.d.ts.map +1 -0
  311. package/dist/tools/cron.js +37 -0
  312. package/dist/tools/cron.js.map +1 -0
  313. package/dist/tools/exec.d.ts +18 -0
  314. package/dist/tools/exec.d.ts.map +1 -0
  315. package/dist/tools/exec.js +125 -0
  316. package/dist/tools/exec.js.map +1 -0
  317. package/dist/tools/files.d.ts +37 -0
  318. package/dist/tools/files.d.ts.map +1 -0
  319. package/dist/tools/files.js +191 -0
  320. package/dist/tools/files.js.map +1 -0
  321. package/dist/tools/image.d.ts +14 -0
  322. package/dist/tools/image.d.ts.map +1 -0
  323. package/dist/tools/image.js +26 -0
  324. package/dist/tools/image.js.map +1 -0
  325. package/dist/tools/index.d.ts +35 -0
  326. package/dist/tools/index.d.ts.map +1 -0
  327. package/dist/tools/index.js +53 -0
  328. package/dist/tools/index.js.map +1 -0
  329. package/dist/tools/memory.d.ts +41 -0
  330. package/dist/tools/memory.d.ts.map +1 -0
  331. package/dist/tools/memory.js +114 -0
  332. package/dist/tools/memory.js.map +1 -0
  333. package/dist/tools/process-registry.d.ts +47 -0
  334. package/dist/tools/process-registry.d.ts.map +1 -0
  335. package/dist/tools/process-registry.js +252 -0
  336. package/dist/tools/process-registry.js.map +1 -0
  337. package/dist/tools/process.d.ts +17 -0
  338. package/dist/tools/process.d.ts.map +1 -0
  339. package/dist/tools/process.js +114 -0
  340. package/dist/tools/process.js.map +1 -0
  341. package/dist/tools/subagent-spawn.d.ts +44 -0
  342. package/dist/tools/subagent-spawn.d.ts.map +1 -0
  343. package/dist/tools/subagent-spawn.js +100 -0
  344. package/dist/tools/subagent-spawn.js.map +1 -0
  345. package/dist/tools/subagents.d.ts +30 -0
  346. package/dist/tools/subagents.d.ts.map +1 -0
  347. package/dist/tools/subagents.js +101 -0
  348. package/dist/tools/subagents.js.map +1 -0
  349. package/dist/types.d.ts +241 -0
  350. package/dist/types.d.ts.map +1 -0
  351. package/dist/types.js +6 -0
  352. package/dist/types.js.map +1 -0
  353. package/package.json +46 -0
@@ -0,0 +1,87 @@
1
+ /**
2
+ * Agent configuration types for AIMax multi-agent support.
3
+ * Compatible with the .aimax/agents.json config file.
4
+ */
5
+ /**
6
+ * Single agent configuration.
7
+ * Each agent can have its own model, skills, identity, and subagent settings.
8
+ */
9
+ export type AgentConfig = {
10
+ /** Unique agent identifier */
11
+ id: string;
12
+ /** Whether this is the default agent */
13
+ default?: boolean;
14
+ /** Display name (overrides identity.name) */
15
+ name?: string;
16
+ /** Model configuration (string or object with primary/fallbacks) */
17
+ model?: string | AgentModelConfig;
18
+ /** Skills allowlist (omit = all skills; empty = none) */
19
+ skills?: string[];
20
+ /** Identity configuration for display/persona */
21
+ identity?: {
22
+ name?: string;
23
+ theme?: string;
24
+ emoji?: string;
25
+ avatar?: string;
26
+ };
27
+ /** Subagent configuration for this agent */
28
+ subagents?: {
29
+ /** Allow spawning subagents under other agent ids. Use "*" to allow any. */
30
+ allowAgents?: string[];
31
+ /** Per-agent default model for spawned subagents (string or {primary,fallbacks}). */
32
+ model?: string | AgentModelConfig;
33
+ };
34
+ };
35
+ /**
36
+ * Model configuration with primary and optional fallbacks.
37
+ */
38
+ export type AgentModelConfig = {
39
+ primary: string;
40
+ fallbacks?: string[];
41
+ };
42
+ /**
43
+ * Routing binding configuration.
44
+ * Maps channel/account/peer to a specific agent.
45
+ */
46
+ export type AgentBinding = {
47
+ /** Target agent ID for this binding */
48
+ agentId: string;
49
+ /** Optional comment/description */
50
+ comment?: string;
51
+ /** Match conditions for this binding */
52
+ match: {
53
+ /** Channel type: H5 | WEB | KLPA | CRON */
54
+ channel: "H5" | "WEB" | "KLPA" | "CRON";
55
+ /** Account ID (optional, for multi-account routing) */
56
+ accountId?: string;
57
+ /** User ID (optional, for user-specific routing) */
58
+ userId?: string;
59
+ };
60
+ };
61
+ /**
62
+ * Root agents configuration structure.
63
+ * Stored in .aimax/agents.json
64
+ */
65
+ export type AgentsConfig = {
66
+ /** List of configured agents */
67
+ agents: AgentConfig[];
68
+ /** Routing bindings (channel -> agent mapping) */
69
+ bindings?: AgentBinding[];
70
+ /** Default configuration (optional) */
71
+ defaults?: {
72
+ model?: string | AgentModelConfig;
73
+ /**
74
+ * Maximum number of recent user turns to keep in context.
75
+ * 0 or undefined means no limit.
76
+ */
77
+ historyLimit?: number;
78
+ /** LLM-based history compaction settings */
79
+ compaction?: {
80
+ /** Whether to enable automatic LLM summarisation; defaults to true */
81
+ enabled?: boolean;
82
+ /** Fraction of context window that triggers compaction; defaults to 0.6 */
83
+ thresholdRatio?: number;
84
+ };
85
+ };
86
+ };
87
+ //# sourceMappingURL=types.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../src/config/types.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH;;;GAGG;AACH,MAAM,MAAM,WAAW,GAAG;IACxB,8BAA8B;IAC9B,EAAE,EAAE,MAAM,CAAC;IACX,wCAAwC;IACxC,OAAO,CAAC,EAAE,OAAO,CAAC;IAClB,6CAA6C;IAC7C,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,oEAAoE;IACpE,KAAK,CAAC,EAAE,MAAM,GAAG,gBAAgB,CAAC;IAClC,yDAAyD;IACzD,MAAM,CAAC,EAAE,MAAM,EAAE,CAAC;IAClB,iDAAiD;IACjD,QAAQ,CAAC,EAAE;QACT,IAAI,CAAC,EAAE,MAAM,CAAC;QACd,KAAK,CAAC,EAAE,MAAM,CAAC;QACf,KAAK,CAAC,EAAE,MAAM,CAAC;QACf,MAAM,CAAC,EAAE,MAAM,CAAC;KACjB,CAAC;IACF,4CAA4C;IAC5C,SAAS,CAAC,EAAE;QACV,4EAA4E;QAC5E,WAAW,CAAC,EAAE,MAAM,EAAE,CAAC;QACvB,qFAAqF;QACrF,KAAK,CAAC,EAAE,MAAM,GAAG,gBAAgB,CAAC;KACnC,CAAC;CACH,CAAC;AAEF;;GAEG;AACH,MAAM,MAAM,gBAAgB,GAAG;IAC7B,OAAO,EAAE,MAAM,CAAC;IAChB,SAAS,CAAC,EAAE,MAAM,EAAE,CAAC;CACtB,CAAC;AAEF;;;GAGG;AACH,MAAM,MAAM,YAAY,GAAG;IACzB,uCAAuC;IACvC,OAAO,EAAE,MAAM,CAAC;IAChB,mCAAmC;IACnC,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,wCAAwC;IACxC,KAAK,EAAE;QACL,2CAA2C;QAC3C,OAAO,EAAE,IAAI,GAAG,KAAK,GAAG,MAAM,GAAG,MAAM,CAAC;QACxC,uDAAuD;QACvD,SAAS,CAAC,EAAE,MAAM,CAAC;QACnB,oDAAoD;QACpD,MAAM,CAAC,EAAE,MAAM,CAAC;KACjB,CAAC;CACH,CAAC;AAEF;;;GAGG;AACH,MAAM,MAAM,YAAY,GAAG;IACzB,gCAAgC;IAChC,MAAM,EAAE,WAAW,EAAE,CAAC;IACtB,kDAAkD;IAClD,QAAQ,CAAC,EAAE,YAAY,EAAE,CAAC;IAC1B,uCAAuC;IACvC,QAAQ,CAAC,EAAE;QACT,KAAK,CAAC,EAAE,MAAM,GAAG,gBAAgB,CAAC;QAClC;;;WAGG;QACH,YAAY,CAAC,EAAE,MAAM,CAAC;QACtB,4CAA4C;QAC5C,UAAU,CAAC,EAAE;YACX,sEAAsE;YACtE,OAAO,CAAC,EAAE,OAAO,CAAC;YAClB,2EAA2E;YAC3E,cAAc,CAAC,EAAE,MAAM,CAAC;SACzB,CAAC;KACH,CAAC;CACH,CAAC"}
@@ -0,0 +1,6 @@
1
+ /**
2
+ * Agent configuration types for AIMax multi-agent support.
3
+ * Compatible with the .aimax/agents.json config file.
4
+ */
5
+ export {};
6
+ //# sourceMappingURL=types.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/config/types.ts"],"names":[],"mappings":"AAAA;;;GAGG"}
@@ -0,0 +1,42 @@
1
+ import type { MessageEntry } from "../types.js";
2
+ import type { PluginHookAgentContext, PluginHookRegistry } from "../plugins/hooks.js";
3
+ /** Ratio of context window that triggers compaction when history exceeds it */
4
+ export declare const DEFAULT_COMPACTION_THRESHOLD_RATIO = 0.6;
5
+ export type SummariseParams = {
6
+ entries: MessageEntry[];
7
+ llm: {
8
+ baseUrl: string;
9
+ apiKey: string;
10
+ model: string;
11
+ };
12
+ previousSummary?: string;
13
+ instructions?: string;
14
+ signal?: AbortSignal;
15
+ hooks?: PluginHookRegistry;
16
+ hookCtx?: PluginHookAgentContext;
17
+ };
18
+ /**
19
+ * Call the LLM to produce a summary of the provided entries.
20
+ * If `previousSummary` is given, the LLM is asked to incorporate it so the
21
+ * new summary builds on prior compaction rounds.
22
+ */
23
+ export declare function generateSummary(params: SummariseParams): Promise<string>;
24
+ /**
25
+ * Return true when the total estimated token count of `entries` exceeds the
26
+ * compaction threshold fraction of `contextWindowTokens`.
27
+ */
28
+ export declare function shouldCompact(params: {
29
+ entries: MessageEntry[];
30
+ contextWindowTokens: number;
31
+ thresholdRatio?: number;
32
+ }): boolean;
33
+ /**
34
+ * Partition `entries` into two slices:
35
+ * - `toKeep`: the most-recent entries that fit within the keep budget
36
+ * - `toSummarise`: the older entries that will be summarised
37
+ */
38
+ export declare function splitForCompaction(entries: MessageEntry[], contextWindowTokens: number): {
39
+ toKeep: MessageEntry[];
40
+ toSummarise: MessageEntry[];
41
+ };
42
+ //# sourceMappingURL=compaction.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"compaction.d.ts","sourceRoot":"","sources":["../../src/history/compaction.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAGhD,OAAO,KAAK,EAAE,sBAAsB,EAAE,kBAAkB,EAAE,MAAM,qBAAqB,CAAC;AAEtF,+EAA+E;AAC/E,eAAO,MAAM,kCAAkC,MAAM,CAAC;AAsBtD,MAAM,MAAM,eAAe,GAAG;IAC5B,OAAO,EAAE,YAAY,EAAE,CAAC;IACxB,GAAG,EAAE;QAAE,OAAO,EAAE,MAAM,CAAC;QAAC,MAAM,EAAE,MAAM,CAAC;QAAC,KAAK,EAAE,MAAM,CAAA;KAAE,CAAC;IACxD,eAAe,CAAC,EAAE,MAAM,CAAC;IACzB,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,MAAM,CAAC,EAAE,WAAW,CAAC;IACrB,KAAK,CAAC,EAAE,kBAAkB,CAAC;IAC3B,OAAO,CAAC,EAAE,sBAAsB,CAAC;CAClC,CAAC;AAEF;;;;GAIG;AACH,wBAAsB,eAAe,CAAC,MAAM,EAAE,eAAe,GAAG,OAAO,CAAC,MAAM,CAAC,CAwC9E;AA+CD;;;GAGG;AACH,wBAAgB,aAAa,CAAC,MAAM,EAAE;IACpC,OAAO,EAAE,YAAY,EAAE,CAAC;IACxB,mBAAmB,EAAE,MAAM,CAAC;IAC5B,cAAc,CAAC,EAAE,MAAM,CAAC;CACzB,GAAG,OAAO,CAKV;AAED;;;;GAIG;AACH,wBAAgB,kBAAkB,CAChC,OAAO,EAAE,YAAY,EAAE,EACvB,mBAAmB,EAAE,MAAM,GAC1B;IAAE,MAAM,EAAE,YAAY,EAAE,CAAC;IAAC,WAAW,EAAE,YAAY,EAAE,CAAA;CAAE,CAgBzD"}
@@ -0,0 +1,135 @@
1
+ import { estimateEntryTokens, estimateEntriesTokens } from "./token-estimate.js";
2
+ import { createLlmClient } from "../llm/client.js";
3
+ /** Ratio of context window that triggers compaction when history exceeds it */
4
+ export const DEFAULT_COMPACTION_THRESHOLD_RATIO = 0.6;
5
+ /**
6
+ * Ratio of context window reserved for the message slice kept after compaction.
7
+ * The older portion (beyond this budget) is summarised.
8
+ */
9
+ const KEEP_BUDGET_RATIO = 0.35;
10
+ const SUMMARIZATION_PROMPT = [
11
+ "You are a conversation history summariser. Compress the conversation below into a concise summary.",
12
+ "",
13
+ "MUST PRESERVE:",
14
+ "- Active tasks and their current status (including batch progress e.g. '5/17 items done')",
15
+ "- The last thing the user requested and what was being done about it",
16
+ "- Decisions made and their rationale",
17
+ "- TODOs, open questions, and constraints",
18
+ "- All opaque identifiers exactly as written: UUIDs, hashes, file paths, URLs, IPs, ports (never shorten or reconstruct them)",
19
+ "",
20
+ "Prioritise recent context over older history.",
21
+ "Output only the summary text — no preamble, no headings.",
22
+ ].join("\n");
23
+ /**
24
+ * Call the LLM to produce a summary of the provided entries.
25
+ * If `previousSummary` is given, the LLM is asked to incorporate it so the
26
+ * new summary builds on prior compaction rounds.
27
+ */
28
+ export async function generateSummary(params) {
29
+ const { entries, llm, previousSummary, instructions, signal, hooks, hookCtx } = params;
30
+ const userContent = buildSummarisationUserMessage(entries, previousSummary, instructions);
31
+ const MAX_ATTEMPTS = 3;
32
+ let lastError;
33
+ const client = createLlmClient({
34
+ baseUrl: llm.baseUrl,
35
+ apiKey: llm.apiKey,
36
+ defaultModel: llm.model,
37
+ hooks,
38
+ hookCtx,
39
+ });
40
+ for (let attempt = 1; attempt <= MAX_ATTEMPTS; attempt++) {
41
+ try {
42
+ const result = await client.chat({
43
+ system: SUMMARIZATION_PROMPT,
44
+ user: userContent,
45
+ temperature: 0,
46
+ maxTokens: 2048,
47
+ signal,
48
+ });
49
+ const text = result.text.trim();
50
+ if (!text) {
51
+ throw new Error("LLM summarisation returned empty content");
52
+ }
53
+ return text;
54
+ }
55
+ catch (err) {
56
+ if (err instanceof Error && err.name === "AbortError")
57
+ throw err;
58
+ lastError = err;
59
+ if (attempt < MAX_ATTEMPTS) {
60
+ // Simple backoff: 500ms, 1000ms between retries
61
+ await sleep(500 * attempt);
62
+ }
63
+ }
64
+ }
65
+ throw lastError;
66
+ }
67
+ function sleep(ms) {
68
+ return new Promise((resolve) => setTimeout(resolve, ms));
69
+ }
70
+ function buildSummarisationUserMessage(entries, previousSummary, instructions) {
71
+ const parts = [];
72
+ if (instructions?.trim()) {
73
+ parts.push(`[Extra instructions]\n${instructions.trim()}\n`);
74
+ }
75
+ if (previousSummary?.trim()) {
76
+ parts.push(`[Prior summary]\n${previousSummary.trim()}\n`);
77
+ parts.push("[Conversation to incorporate]");
78
+ }
79
+ else {
80
+ parts.push("[Conversation to summarise]");
81
+ }
82
+ for (const entry of entries) {
83
+ if (entry.role === "user") {
84
+ parts.push(`User: ${entry.content}`);
85
+ }
86
+ else if (entry.role === "assistant") {
87
+ const toolLine = entry.toolCalls && entry.toolCalls.length > 0
88
+ ? ` [called tools: ${entry.toolCalls.map((t) => t.name).join(", ")}]`
89
+ : "";
90
+ parts.push(`Assistant:${toolLine} ${entry.content}`.trimEnd());
91
+ }
92
+ else if (entry.role === "tool_result") {
93
+ const status = entry.isError ? "error" : "ok";
94
+ // Truncate very long tool outputs to avoid blowing the summarisation context
95
+ const truncated = entry.content.length > 2000
96
+ ? `${entry.content.slice(0, 2000)}… [truncated]`
97
+ : entry.content;
98
+ parts.push(`Tool(${entry.toolName})[${status}]: ${truncated}`);
99
+ }
100
+ }
101
+ return parts.join("\n");
102
+ }
103
+ /**
104
+ * Return true when the total estimated token count of `entries` exceeds the
105
+ * compaction threshold fraction of `contextWindowTokens`.
106
+ */
107
+ export function shouldCompact(params) {
108
+ const { entries, contextWindowTokens, thresholdRatio = DEFAULT_COMPACTION_THRESHOLD_RATIO } = params;
109
+ if (entries.length === 0)
110
+ return false;
111
+ const threshold = Math.floor(contextWindowTokens * thresholdRatio);
112
+ return estimateEntriesTokens(entries) > threshold;
113
+ }
114
+ /**
115
+ * Partition `entries` into two slices:
116
+ * - `toKeep`: the most-recent entries that fit within the keep budget
117
+ * - `toSummarise`: the older entries that will be summarised
118
+ */
119
+ export function splitForCompaction(entries, contextWindowTokens) {
120
+ const keepBudget = Math.floor(contextWindowTokens * KEEP_BUDGET_RATIO);
121
+ let accumulated = 0;
122
+ let keepFrom = entries.length; // default: summarise everything
123
+ for (let i = entries.length - 1; i >= 0; i--) {
124
+ const t = estimateEntryTokens(entries[i]);
125
+ if (accumulated + t > keepBudget)
126
+ break;
127
+ accumulated += t;
128
+ keepFrom = i;
129
+ }
130
+ return {
131
+ toKeep: entries.slice(keepFrom),
132
+ toSummarise: entries.slice(0, keepFrom),
133
+ };
134
+ }
135
+ //# sourceMappingURL=compaction.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"compaction.js","sourceRoot":"","sources":["../../src/history/compaction.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,mBAAmB,EAAE,qBAAqB,EAAE,MAAM,qBAAqB,CAAC;AACjF,OAAO,EAAE,eAAe,EAAE,MAAM,kBAAkB,CAAC;AAGnD,+EAA+E;AAC/E,MAAM,CAAC,MAAM,kCAAkC,GAAG,GAAG,CAAC;AAEtD;;;GAGG;AACH,MAAM,iBAAiB,GAAG,IAAI,CAAC;AAE/B,MAAM,oBAAoB,GAAG;IAC3B,oGAAoG;IACpG,EAAE;IACF,gBAAgB;IAChB,2FAA2F;IAC3F,sEAAsE;IACtE,sCAAsC;IACtC,0CAA0C;IAC1C,8HAA8H;IAC9H,EAAE;IACF,+CAA+C;IAC/C,0DAA0D;CAC3D,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;AAYb;;;;GAIG;AACH,MAAM,CAAC,KAAK,UAAU,eAAe,CAAC,MAAuB;IAC3D,MAAM,EAAE,OAAO,EAAE,GAAG,EAAE,eAAe,EAAE,YAAY,EAAE,MAAM,EAAE,KAAK,EAAE,OAAO,EAAE,GAAG,MAAM,CAAC;IAEvF,MAAM,WAAW,GAAG,6BAA6B,CAAC,OAAO,EAAE,eAAe,EAAE,YAAY,CAAC,CAAC;IAE1F,MAAM,YAAY,GAAG,CAAC,CAAC;IACvB,IAAI,SAAkB,CAAC;IACvB,MAAM,MAAM,GAAG,eAAe,CAAC;QAC7B,OAAO,EAAE,GAAG,CAAC,OAAO;QACpB,MAAM,EAAE,GAAG,CAAC,MAAM;QAClB,YAAY,EAAE,GAAG,CAAC,KAAK;QACvB,KAAK;QACL,OAAO;KACR,CAAC,CAAC;IAEH,KAAK,IAAI,OAAO,GAAG,CAAC,EAAE,OAAO,IAAI,YAAY,EAAE,OAAO,EAAE,EAAE,CAAC;QACzD,IAAI,CAAC;YACH,MAAM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2
+ import type { TranscriptEntry, MessageEntry, CompactionEntry } from "../types.js";
3
+ import type { PluginHookAgentContext, PluginHookRegistry } from "../plugins/hooks.js";
4
+ export type ManageHistoryParams = {
5
+ /** Full transcript entries including any prior compaction records */
6
+ entries: TranscriptEntry[];
7
+ modelInfo: {
8
+ model: string;
9
+ api: string;
10
+ };
11
+ contextWindowTokens: number;
12
+ llm: {
13
+ baseUrl: string;
14
+ apiKey: string;
15
+ model: string;
16
+ };
17
+ /** Max user turns to keep; 0/undefined = no limit */
18
+ historyLimit?: number;
19
+ /** Set to false to skip LLM-based compaction; defaults to true */
20
+ compactionEnabled?: boolean;
21
+ /** Fraction of context window that triggers compaction; defaults to 0.6 */
22
+ thresholdRatio?: number;
23
+ signal?: AbortSignal;
24
+ hooks?: PluginHookRegistry;
25
+ hookCtx?: PluginHookAgentContext;
26
+ };
27
+ export type HistoryManagementResult = {
28
+ /** Messages ready to pass to agent.replaceMessages() */
29
+ messages: AgentMessage[];
30
+ /** Summary text to inject into the system prompt (from existing or new compaction) */
31
+ priorSummary: string | undefined;
32
+ /** New compaction record to append to the transcript (undefined if no compaction ran) */
33
+ compactionEntry: CompactionEntry | undefined;
34
+ stats: {
35
+ originalCount: number;
36
+ keptCount: number;
37
+ estimatedTokens: number;
38
+ compacted: boolean;
39
+ };
40
+ };
41
+ /**
42
+ * Manage conversation history before each agent run:
43
+ * 1. Extract message entries that follow the last compaction record.
44
+ * 2. Apply the turn limit (drop oldest user turns beyond `historyLimit`).
45
+ * 3. Repair orphaned tool_result entries created by truncation.
46
+ * 4. If token count exceeds the threshold, generate an LLM summary and
47
+ * return a compaction record to persist.
48
+ */
49
+ export declare function manageHistory(params: ManageHistoryParams): Promise<HistoryManagementResult>;
50
+ /**
51
+ * Convert MessageEntry[] to AgentMessage[] for use with agent.replaceMessages().
52
+ */
53
+ export declare function entriesToMessages(entries: MessageEntry[], modelInfo: {
54
+ model: string;
55
+ api: string;
56
+ }): AgentMessage[];
57
+ //# sourceMappingURL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AS,EAAE,OAAO,CAAC;KACpB,CAAC;CACH,CAAC;AAEF;;;;;;;GAOG;AACH,wBAAsB,aAAa,CAAC,MAAM,EAAE,mBAAmB,GAAG,OAAO,CAAC,uBAAuB,CAAC,CAoFjG;AAaD;;GAEG;AACH,wBAAgB,iBAAiB,CAC/B,OAAO,EAAE,YAAY,EAAE,EACvB,SAAS,EAAE;IAAE,KAAK,EAAE,MAAM,CAAC;IAAC,GAAG,EAAE,MAAM,CAAA;CAAE,GACxC,YAAY,EAAE,CAEhB"}
@@ -0,0 +1,145 @@
1
+ import { estimateEntriesTokens } from "./token-estimate.js";
2
+ import { limitHistoryTurns } from "./limit.js";
3
+ import { repairToolPairing } from "./repair.js";
4
+ import { shouldCompact, splitForCompaction, generateSummary } from "./compaction.js";
5
+ // Zero-usage placeholder for reconstructed assistant messages.
6
+ // The actual usage figures are not meaningful for history replay.
7
+ const ZERO_USAGE = {
8
+ input: 0,
9
+ output: 0,
10
+ cacheRead: 0,
11
+ cacheWrite: 0,
12
+ totalTokens: 0,
13
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
14
+ };
15
+ /**
16
+ * Manage conversation history before each agent run:
17
+ * 1. Extract message entries that follow the last compaction record.
18
+ * 2. Apply the turn limit (drop oldest user turns beyond `historyLimit`).
19
+ * 3. Repair orphaned tool_result entries created by truncation.
20
+ * 4. If token count exceeds the threshold, generate an LLM summary and
21
+ * return a compaction record to persist.
22
+ */
23
+ export async function manageHistory(params) {
24
+ const { entries, modelInfo, contextWindowTokens, llm, historyLimit, compactionEnabled = true, thresholdRatio, signal, } = params;
25
+ // ── 1. Separate the latest compaction record from message entries ──────────
26
+ let existingSummary;
27
+ let messageEntries;
28
+ const lastCompactionIdx = findLastCompactionIndex(entries);
29
+ if (lastCompactionIdx >= 0) {
30
+ existingSummary = entries[lastCompactionIdx].content;
31
+ messageEntries = entries.slice(lastCompactionIdx + 1);
32
+ }
33
+ else {
34
+ messageEntries = entries;
35
+ }
36
+ const originalCount = entries.length;
37
+ // ── 2. Apply turn limit ────────────────────────────────────────────────────
38
+ const limited = limitHistoryTurns(messageEntries, historyLimit);
39
+ // ── 3. Repair orphaned tool_results caused by truncation ──────────────────
40
+ const repaired = repairToolPairing(limited);
41
+ // ── 4. Compaction if needed ────────────────────────────────────────────────
42
+ if (compactionEnabled &&
43
+ shouldCompact({ entries: repaired, contextWindowTokens, thresholdRatio })) {
44
+ const { toKeep, toSummarise } = splitForCompaction(repaired, contextWindowTokens);
45
+ if (toSummarise.length > 0) {
46
+ const newSummary = await generateSummary({
47
+ entries: toSummarise,
48
+ llm,
49
+ previousSummary: existingSummary,
50
+ signal,
51
+ hooks: params.hooks,
52
+ hookCtx: params.hookCtx,
53
+ });
54
+ const repairedToKeep = repairToolPairing(toKeep);
55
+ const compactionEntry = {
56
+ role: "compaction",
57
+ content: newSummary,
58
+ keptCount: repairedToKeep.length,
59
+ droppedCount: toSummarise.length,
60
+ timestamp: new Date().toISOString(),
61
+ };
62
+ return {
63
+ messages: entriesToMessages(repairedToKeep, modelInfo),
64
+ priorSummary: newSummary,
65
+ compactionEntry,
66
+ stats: {
67
+ originalCount,
68
+ keptCount: repairedToKeep.length,
69
+ estimatedTokens: estimateEntriesTokens(repairedToKeep),
70
+ compacted: true,
71
+ },
72
+ };
73
+ }
74
+ }
75
+ // ── No compaction ──────────────────────────────────────────────────────────
76
+ return {
77
+ messages: entriesToMessages(repaired, modelInfo),
78
+ priorSummary: existingSummary,
79
+ compactionEntry: undefined,
80
+ stats: {
81
+ originalCount,
82
+ keptCount: repaired.length,
83
+ estimatedTokens: estimateEntriesTokens(repaired),
84
+ compacted: false,
85
+ },
86
+ };
87
+ }
88
+ // ---------------------------------------------------------------------------
89
+ // Helpers
90
+ // ---------------------------------------------------------------------------
91
+ function findLastCompactionIndex(entries) {
92
+ for (let i = entries.length - 1; i >= 0; i--) {
93
+ if (entries[i].role === "compaction")
94
+ return i;
95
+ }
96
+ return -1;
97
+ }
98
+ /**
99
+ * Convert MessageEntry[] to AgentMessage[] for use with agent.replaceMessages().
100
+ */
101
+ export function entriesToMessages(entries, modelInfo) {
102
+ return entries.map((entry) => entryToMessage(entry, modelInfo));
103
+ }
104
+ function entryToMessage(entry, modelInfo) {
105
+ const timestamp = new Date(entry.timestamp).getTime();
106
+ if (isUserEntry(entry)) {
107
+ return { role: "user", content: entry.content, timestamp };
108
+ }
109
+ if (isAssistantEntry(entry)) {
110
+ const content = [];
111
+ if (entry.content) {
112
+ content.push({ type: "text", text: entry.content });
113
+ }
114
+ for (const tc of entry.toolCalls ?? []) {
115
+ content.push({ type: "toolCall", id: tc.id, name: tc.name, arguments: tc.arguments });
116
+ }
117
+ return {
118
+ role: "assistant",
119
+ content,
120
+ api: modelInfo.api,
121
+ provider: "openai",
122
+ model: modelInfo.model,
123
+ usage: ZERO_USAGE,
124
+ stopReason: "stop",
125
+ timestamp,
126
+ };
127
+ }
128
+ // tool_result
129
+ const tr = entry;
130
+ return {
131
+ role: "toolResult",
132
+ toolCallId: tr.toolCallId,
133
+ toolName: tr.toolName,
134
+ content: [{ type: "text", text: tr.content }],
135
+ isError: tr.isError,
136
+ timestamp,
137
+ };
138
+ }
139
+ function isUserEntry(entry) {
140
+ return entry.role === "user";
141
+ }
142
+ function isAssistantEntry(entry) {
143
+ return entry.role === "assistant";
144
+ }
145
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/history/index.ts"],"names":[],"mappings":"AASA,OAAO,EAAE,qBAAqB,EAAE,MAAM,qBAAqB,CAAC;AAC5D,OAAO,EAAE,iBAAiB,EAAE,MAAM,YAAY,CAAC;AAC/C,OAAO,EAAE,iBAAiB,EAAE,MAAM,aAAa,CAAC;AAChD,OAAO,EAAE,aAAa,EAAE,kBAAkB,EAAE,eAAe,EAAE,MAAM,iBAAiB,CAAC;AAGrF,+DAA+D;AAC/D,kEAAkE;AAClE,MAAM,UAAU,GAAG;IACjB,KA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AAE,CAAC,SAAS,EAAE,CAAC,CAAC;QACxF,CAAC;QACD,OAAO;YACL,IAAI,EAAE,WAAW;YACjB,OAAO;YACP,GAAG,EAAE,SAAS,CAAC,GAAG;YAClB,QAAQ,EAAE,QAAQ;YAClB,KAAK,EAAE,SAAS,CAAC,KAAK;YACtB,KAAK,EAAE,UAAU;YACjB,UAAU,EAAE,MAAM;YAClB,SAAS;SACM,CAAC;IACpB,CAAC;IAED,cAAc;IACd,MAAM,EAAE,GAAG,KAAwB,CAAC;IACpC,OAAO;QACL,IAAI,EAAE,YAAY;QAClB,UAAU,EAAE,EAAE,CAAC,UAAU;QACzB,QAAQ,EAAE,EAAE,CAAC,QAAQ;QACrB,OAAO,EAAE,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,EAAE,CAAC,OAAO,EAAE,CAAC;QAC7C,OAAO,EAAE,EAAE,CAAC,OAAO;QACnB,SAAS;KACM,CAAC;AACpB,CAAC;AAED,SAAS,WAAW,CAAC,KAAmB;IACtC,OAAO,KAAK,CAAC,IAAI,KAAK,MAAM,CAAC;AAC/B,CAAC;AAED,SAAS,gBAAgB,CAAC,KAAmB;IAC3C,OAAO,KAAK,CAAC,IAAI,KAAK,WAAW,CAAC;AACpC,CAAC"}
@@ -0,0 +1,13 @@
1
+ import type { MessageEntry } from "../types.js";
2
+ /**
3
+ * Limit conversation history to the last `limit` user turns (and their
4
+ * associated assistant/tool_result responses).
5
+ *
6
+ * Counting works from the end: each `user` entry increments the counter.
7
+ * Once the counter exceeds `limit`, the entries before that point are dropped.
8
+ *
9
+ * Returns the original array reference when no trimming is needed, avoiding
10
+ * an unnecessary copy.
11
+ */
12
+ export declare function limitHistoryTurns(entries: MessageEntry[], limit: number | undefined): MessageEntry[];
13
+ //# sourceMappingURL=limit.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"limit.d.ts","sourceRoot":"","sources":["../../src/history/limit.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAEhD;;;;;;;;;GASG;AACH,wBAAgB,iBAAiB,CAC/B,OAAO,EAAE,YAAY,EAAE,EACvB,KAAK,EAAE,MAAM,GAAG,SAAS,GACxB,YAAY,EAAE,CAuBhB"}
@@ -0,0 +1,32 @@
1
+ /**
2
+ * Limit conversation history to the last `limit` user turns (and their
3
+ * associated assistant/tool_result responses).
4
+ *
5
+ * Counting works from the end: each `user` entry increments the counter.
6
+ * Once the counter exceeds `limit`, the entries before that point are dropped.
7
+ *
8
+ * Returns the original array reference when no trimming is needed, avoiding
9
+ * an unnecessary copy.
10
+ */
11
+ export function limitHistoryTurns(entries, limit) {
12
+ if (!limit || limit <= 0 || entries.length === 0) {
13
+ return entries;
14
+ }
15
+ let userCount = 0;
16
+ // Tracks the index of the most-recently-seen user entry as we scan backward.
17
+ let lastUserIndex = entries.length;
18
+ for (let i = entries.length - 1; i >= 0; i--) {
19
+ if (entries[i].role === "user") {
20
+ userCount++;
21
+ if (userCount > limit) {
22
+ // We have seen one more user turn than allowed — drop everything before
23
+ // the index we saved on the previous iteration.
24
+ return entries.slice(lastUserIndex);
25
+ }
26
+ lastUserIndex = i;
27
+ }
28
+ }
29
+ // Fewer user turns than the limit — return as-is.
30
+ return entries;
31
+ }
32
+ //# sourceMappingURL=limit.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"limit.js","sourceRoot":"","sources":["../../src/history/limit.ts"],"names":[],"mappings":"AAEA;;;;;;;;;GASG;AACH,MAAM,UAAU,iBAAiB,CAC/B,OAAuB,EACvB,KAAyB;IAEzB,IAAI,CAAC,KAAK,IAAI,KAAK,IAAI,CAAC,IAAI,OAAO,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;QACjD,OAAO,OAAO,CAAC;IACjB,CAAC;IAED,IAAI,SAAS,GAAG,CAAC,CAAC;IAClB,6EAA6E;IAC7E,IAAI,aAAa,GAAG,OAAO,CAAC,MAAM,CAAC;IAEnC,KAAK,IAAI,CAAC,GAAG,OAAO,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC,IAAI,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC;QAC7C,IAAI,OAAO,CAAC,CAAC,CAAC,CAAC,IAAI,KAAK,MAAM,EAAE,CAAC;YAC/B,SAAS,EAAE,CAAC;YACZ,IAAI,SAAS,GAAG,KAAK,EAAE,CAAC;gBACtB,wEAAwE;gBACxE,gDAAgD;gBAChD,OAAO,OAAO,CAAC,KAAK,CAAC,aAAa,CAAC,CAAC;YACtC,CAAC;YACD,aAAa,GAAG,CAAC,CAAC;QACpB,CAAC;IACH,CAAC;IAED,kDAAkD;IAClD,OAAO,OAAO,CAAC;AACjB,CAAC"}
@@ -0,0 +1,13 @@
1
+ import type { MessageEntry } from "../types.js";
2
+ /**
3
+ * Remove orphaned tool_result entries whose matching assistant toolCall was
4
+ * dropped by history truncation.
5
+ *
6
+ * An orphaned tool_result has a `toolCallId` that cannot be found in any
7
+ * preceding AssistantEntry.toolCalls[].id within the provided slice.
8
+ * Sending such entries to the LLM causes "unexpected tool_use_id" errors.
9
+ *
10
+ * Returns the original array reference when nothing was dropped.
11
+ */
12
+ export declare function repairToolPairing(entries: MessageEntry[]): MessageEntry[];
13
+ //# sourceMappingURL=repair.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"repair.d.ts","sourceRoot":"","sources":["../../src/history/repair.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAEhD;;;;;;;;;GASG;AACH,wBAAgB,iBAAiB,CAAC,OAAO,EAAE,YAAY,EAAE,GAAG,YAAY,EAAE,CAiBzE"}
@@ -0,0 +1,25 @@
1
+ /**
2
+ * Remove orphaned tool_result entries whose matching assistant toolCall was
3
+ * dropped by history truncation.
4
+ *
5
+ * An orphaned tool_result has a `toolCallId` that cannot be found in any
6
+ * preceding AssistantEntry.toolCalls[].id within the provided slice.
7
+ * Sending such entries to the LLM causes "unexpected tool_use_id" errors.
8
+ *
9
+ * Returns the original array reference when nothing was dropped.
10
+ */
11
+ export function repairToolPairing(entries) {
12
+ // Collect all toolCall ids that are present in the slice.
13
+ const knownIds = new Set();
14
+ for (const entry of entries) {
15
+ if (entry.role === "assistant") {
16
+ for (const tc of entry.toolCalls ?? []) {
17
+ knownIds.add(tc.id);
18
+ }
19
+ }
20
+ }
21
+ const repaired = entries.filter((entry) => entry.role !== "tool_result" || knownIds.has(entry.toolCallId));
22
+ // Avoid allocating a new array when nothing was removed.
23
+ return repaired.length === entries.length ? entries : repaired;
24
+ }
25
+ //# sourceMappingURL=repair.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"repair.js","sourceRoot":"","sources":["../../src/history/repair.ts"],"names":[],"mappings":"AAEA;;;;;;;;;GASG;AACH,MAAM,UAAU,iBAAiB,CAAC,OAAuB;IACvD,0DAA0D;IAC1D,MAAM,QAAQ,GAAG,IAAI,GAAG,EAAU,CAAC;IACnC,KAAK,MAAM,KAAK,IAAI,OAAO,EAAE,CAAC;QAC5B,IAAI,KAAK,CAAC,IAAI,KAAK,WAAW,EAAE,CAAC;YAC/B,KAAK,MAAM,EAAE,IAAI,KAAK,CAAC,SAAS,IAAI,EAAE,EAAE,CAAC;gBACvC,QAAQ,CAAC,GAAG,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC;YACtB,CAAC;QACH,CAAC;IACH,CAAC;IAED,MAAM,QAAQ,GAAG,OAAO,CAAC,MAAM,CAC7B,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,IAAI,KAAK,aAAa,IAAI,QAAQ,CAAC,GAAG,CAAC,KAAK,CAAC,UAAU,CAAC,CAC1E,CAAC;IAEF,yDAAyD;IACzD,OAAO,QAAQ,CAAC,MAAM,KAAK,OAAO,CAAC,MAAM,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,QAAQ,CAAC;AACjE,CAAC"}
@@ -0,0 +1,22 @@
1
+ import type { MessageEntry } from "../types.js";
2
+ /**
3
+ * Safety margin applied on top of the chars/4 heuristic to compensate for
4
+ * tokeniser differences (multi-byte chars, code tokens, special tokens, etc.)
5
+ */
6
+ export declare const SAFETY_MARGIN = 1.2;
7
+ /**
8
+ * Estimate token count for a text string.
9
+ * Uses the chars/4 heuristic (rough average for English/mixed content) plus
10
+ * a 20% safety margin to reduce the risk of underestimation.
11
+ */
12
+ export declare function estimateTokens(text: string): number;
13
+ /**
14
+ * Estimate token count for a single MessageEntry.
15
+ * Tool results are measured separately because they can be very large.
16
+ */
17
+ export declare function estimateEntryTokens(entry: MessageEntry): number;
18
+ /**
19
+ * Estimate total token count for an array of MessageEntry items.
20
+ */
21
+ export declare function estimateEntriesTokens(entries: MessageEntry[]): number;
22
+ //# sourceMappingURL=token-estimate.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"token-estimate.d.ts","sourceRoot":"","sources":["../../src/history/token-estimate.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAEhD;;;GAGG;AACH,eAAO,MAAM,aAAa,MAAM,CAAC;AAEjC;;;;GAIG;AACH,wBAAgB,cAAc,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAEnD;AAED;;;GAGG;AACH,wBAAgB,mBAAmB,CAAC,KAAK,EAAE,YAAY,GAAG,MAAM,CAa/D;AAED;;GAEG;AACH,wBAAgB,qBAAqB,CAAC,OAAO,EAAE,YAAY,EAAE,GAAG,MAAM,CAErE"}