attocode 0.1.0

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 (488) hide show
  1. package/CHANGELOG.md +48 -0
  2. package/LICENSE +21 -0
  3. package/README.md +164 -0
  4. package/dist/src/adapters.d.ts +83 -0
  5. package/dist/src/adapters.d.ts.map +1 -0
  6. package/dist/src/adapters.js +221 -0
  7. package/dist/src/adapters.js.map +1 -0
  8. package/dist/src/agent-tools/index.d.ts +7 -0
  9. package/dist/src/agent-tools/index.d.ts.map +1 -0
  10. package/dist/src/agent-tools/index.js +8 -0
  11. package/dist/src/agent-tools/index.js.map +1 -0
  12. package/dist/src/agent-tools/lsp-file-tools.d.ts +33 -0
  13. package/dist/src/agent-tools/lsp-file-tools.d.ts.map +1 -0
  14. package/dist/src/agent-tools/lsp-file-tools.js +200 -0
  15. package/dist/src/agent-tools/lsp-file-tools.js.map +1 -0
  16. package/dist/src/agent.d.ts +667 -0
  17. package/dist/src/agent.d.ts.map +1 -0
  18. package/dist/src/agent.js +2824 -0
  19. package/dist/src/agent.js.map +1 -0
  20. package/dist/src/cli.d.ts +36 -0
  21. package/dist/src/cli.d.ts.map +1 -0
  22. package/dist/src/cli.js +176 -0
  23. package/dist/src/cli.js.map +1 -0
  24. package/dist/src/commands/handler.d.ts +22 -0
  25. package/dist/src/commands/handler.d.ts.map +1 -0
  26. package/dist/src/commands/handler.js +1320 -0
  27. package/dist/src/commands/handler.js.map +1 -0
  28. package/dist/src/commands/init.d.ts +7 -0
  29. package/dist/src/commands/init.d.ts.map +1 -0
  30. package/dist/src/commands/init.js +153 -0
  31. package/dist/src/commands/init.js.map +1 -0
  32. package/dist/src/commands/types.d.ts +70 -0
  33. package/dist/src/commands/types.d.ts.map +1 -0
  34. package/dist/src/commands/types.js +8 -0
  35. package/dist/src/commands/types.js.map +1 -0
  36. package/dist/src/config.d.ts +22 -0
  37. package/dist/src/config.d.ts.map +1 -0
  38. package/dist/src/config.js +25 -0
  39. package/dist/src/config.js.map +1 -0
  40. package/dist/src/core/index.d.ts +32 -0
  41. package/dist/src/core/index.d.ts.map +1 -0
  42. package/dist/src/core/index.js +35 -0
  43. package/dist/src/core/index.js.map +1 -0
  44. package/dist/src/core/process-handlers.d.ts +43 -0
  45. package/dist/src/core/process-handlers.d.ts.map +1 -0
  46. package/dist/src/core/process-handlers.js +117 -0
  47. package/dist/src/core/process-handlers.js.map +1 -0
  48. package/dist/src/core/protocol/bridge.d.ts +117 -0
  49. package/dist/src/core/protocol/bridge.d.ts.map +1 -0
  50. package/dist/src/core/protocol/bridge.js +149 -0
  51. package/dist/src/core/protocol/bridge.js.map +1 -0
  52. package/dist/src/core/protocol/index.d.ts +8 -0
  53. package/dist/src/core/protocol/index.d.ts.map +1 -0
  54. package/dist/src/core/protocol/index.js +8 -0
  55. package/dist/src/core/protocol/index.js.map +1 -0
  56. package/dist/src/core/protocol/types.d.ts +539 -0
  57. package/dist/src/core/protocol/types.d.ts.map +1 -0
  58. package/dist/src/core/protocol/types.js +149 -0
  59. package/dist/src/core/protocol/types.js.map +1 -0
  60. package/dist/src/core/queues/atomic-counter.d.ts +36 -0
  61. package/dist/src/core/queues/atomic-counter.d.ts.map +1 -0
  62. package/dist/src/core/queues/atomic-counter.js +46 -0
  63. package/dist/src/core/queues/atomic-counter.js.map +1 -0
  64. package/dist/src/core/queues/event-queue.d.ts +126 -0
  65. package/dist/src/core/queues/event-queue.d.ts.map +1 -0
  66. package/dist/src/core/queues/event-queue.js +208 -0
  67. package/dist/src/core/queues/event-queue.js.map +1 -0
  68. package/dist/src/core/queues/index.d.ts +12 -0
  69. package/dist/src/core/queues/index.d.ts.map +1 -0
  70. package/dist/src/core/queues/index.js +15 -0
  71. package/dist/src/core/queues/index.js.map +1 -0
  72. package/dist/src/core/queues/submission-queue.d.ts +116 -0
  73. package/dist/src/core/queues/submission-queue.d.ts.map +1 -0
  74. package/dist/src/core/queues/submission-queue.js +236 -0
  75. package/dist/src/core/queues/submission-queue.js.map +1 -0
  76. package/dist/src/costs/index.d.ts +22 -0
  77. package/dist/src/costs/index.d.ts.map +1 -0
  78. package/dist/src/costs/index.js +22 -0
  79. package/dist/src/costs/index.js.map +1 -0
  80. package/dist/src/costs/model-registry.d.ts +80 -0
  81. package/dist/src/costs/model-registry.d.ts.map +1 -0
  82. package/dist/src/costs/model-registry.js +237 -0
  83. package/dist/src/costs/model-registry.js.map +1 -0
  84. package/dist/src/costs/types.d.ts +50 -0
  85. package/dist/src/costs/types.d.ts.map +1 -0
  86. package/dist/src/costs/types.js +2 -0
  87. package/dist/src/costs/types.js.map +1 -0
  88. package/dist/src/defaults.d.ts +114 -0
  89. package/dist/src/defaults.d.ts.map +1 -0
  90. package/dist/src/defaults.js +457 -0
  91. package/dist/src/defaults.js.map +1 -0
  92. package/dist/src/first-run.d.ts +35 -0
  93. package/dist/src/first-run.d.ts.map +1 -0
  94. package/dist/src/first-run.js +94 -0
  95. package/dist/src/first-run.js.map +1 -0
  96. package/dist/src/hello.d.ts +2 -0
  97. package/dist/src/hello.d.ts.map +1 -0
  98. package/dist/src/hello.js +4 -0
  99. package/dist/src/hello.js.map +1 -0
  100. package/dist/src/integrations/agent-registry.d.ts +160 -0
  101. package/dist/src/integrations/agent-registry.d.ts.map +1 -0
  102. package/dist/src/integrations/agent-registry.js +446 -0
  103. package/dist/src/integrations/agent-registry.js.map +1 -0
  104. package/dist/src/integrations/auto-compaction.d.ts +177 -0
  105. package/dist/src/integrations/auto-compaction.d.ts.map +1 -0
  106. package/dist/src/integrations/auto-compaction.js +428 -0
  107. package/dist/src/integrations/auto-compaction.js.map +1 -0
  108. package/dist/src/integrations/cancellation.d.ts +162 -0
  109. package/dist/src/integrations/cancellation.d.ts.map +1 -0
  110. package/dist/src/integrations/cancellation.js +339 -0
  111. package/dist/src/integrations/cancellation.js.map +1 -0
  112. package/dist/src/integrations/codebase-context.d.ts +319 -0
  113. package/dist/src/integrations/codebase-context.d.ts.map +1 -0
  114. package/dist/src/integrations/codebase-context.js +816 -0
  115. package/dist/src/integrations/codebase-context.js.map +1 -0
  116. package/dist/src/integrations/compaction.d.ts +192 -0
  117. package/dist/src/integrations/compaction.d.ts.map +1 -0
  118. package/dist/src/integrations/compaction.js +376 -0
  119. package/dist/src/integrations/compaction.js.map +1 -0
  120. package/dist/src/integrations/context-engineering.d.ts +246 -0
  121. package/dist/src/integrations/context-engineering.d.ts.map +1 -0
  122. package/dist/src/integrations/context-engineering.js +394 -0
  123. package/dist/src/integrations/context-engineering.js.map +1 -0
  124. package/dist/src/integrations/diff-utils.d.ts +105 -0
  125. package/dist/src/integrations/diff-utils.d.ts.map +1 -0
  126. package/dist/src/integrations/diff-utils.js +497 -0
  127. package/dist/src/integrations/diff-utils.js.map +1 -0
  128. package/dist/src/integrations/economics.d.ts +192 -0
  129. package/dist/src/integrations/economics.d.ts.map +1 -0
  130. package/dist/src/integrations/economics.js +431 -0
  131. package/dist/src/integrations/economics.js.map +1 -0
  132. package/dist/src/integrations/execution-policy.d.ts +189 -0
  133. package/dist/src/integrations/execution-policy.d.ts.map +1 -0
  134. package/dist/src/integrations/execution-policy.js +352 -0
  135. package/dist/src/integrations/execution-policy.js.map +1 -0
  136. package/dist/src/integrations/file-change-tracker.d.ts +161 -0
  137. package/dist/src/integrations/file-change-tracker.d.ts.map +1 -0
  138. package/dist/src/integrations/file-change-tracker.js +520 -0
  139. package/dist/src/integrations/file-change-tracker.js.map +1 -0
  140. package/dist/src/integrations/hierarchical-config.d.ts +212 -0
  141. package/dist/src/integrations/hierarchical-config.d.ts.map +1 -0
  142. package/dist/src/integrations/hierarchical-config.js +484 -0
  143. package/dist/src/integrations/hierarchical-config.js.map +1 -0
  144. package/dist/src/integrations/hooks.d.ts +114 -0
  145. package/dist/src/integrations/hooks.d.ts.map +1 -0
  146. package/dist/src/integrations/hooks.js +326 -0
  147. package/dist/src/integrations/hooks.js.map +1 -0
  148. package/dist/src/integrations/ignore.d.ts +143 -0
  149. package/dist/src/integrations/ignore.d.ts.map +1 -0
  150. package/dist/src/integrations/ignore.js +417 -0
  151. package/dist/src/integrations/ignore.js.map +1 -0
  152. package/dist/src/integrations/image-renderer.d.ts +119 -0
  153. package/dist/src/integrations/image-renderer.d.ts.map +1 -0
  154. package/dist/src/integrations/image-renderer.js +306 -0
  155. package/dist/src/integrations/image-renderer.js.map +1 -0
  156. package/dist/src/integrations/index.d.ts +42 -0
  157. package/dist/src/integrations/index.d.ts.map +1 -0
  158. package/dist/src/integrations/index.js +73 -0
  159. package/dist/src/integrations/index.js.map +1 -0
  160. package/dist/src/integrations/lsp.d.ts +196 -0
  161. package/dist/src/integrations/lsp.d.ts.map +1 -0
  162. package/dist/src/integrations/lsp.js +582 -0
  163. package/dist/src/integrations/lsp.js.map +1 -0
  164. package/dist/src/integrations/mcp-client.d.ts +270 -0
  165. package/dist/src/integrations/mcp-client.d.ts.map +1 -0
  166. package/dist/src/integrations/mcp-client.js +698 -0
  167. package/dist/src/integrations/mcp-client.js.map +1 -0
  168. package/dist/src/integrations/mcp-tool-search.d.ts +77 -0
  169. package/dist/src/integrations/mcp-tool-search.d.ts.map +1 -0
  170. package/dist/src/integrations/mcp-tool-search.js +220 -0
  171. package/dist/src/integrations/mcp-tool-search.js.map +1 -0
  172. package/dist/src/integrations/memory.d.ts +108 -0
  173. package/dist/src/integrations/memory.d.ts.map +1 -0
  174. package/dist/src/integrations/memory.js +288 -0
  175. package/dist/src/integrations/memory.js.map +1 -0
  176. package/dist/src/integrations/multi-agent.d.ts +150 -0
  177. package/dist/src/integrations/multi-agent.d.ts.map +1 -0
  178. package/dist/src/integrations/multi-agent.js +306 -0
  179. package/dist/src/integrations/multi-agent.js.map +1 -0
  180. package/dist/src/integrations/observability.d.ts +162 -0
  181. package/dist/src/integrations/observability.d.ts.map +1 -0
  182. package/dist/src/integrations/observability.js +406 -0
  183. package/dist/src/integrations/observability.js.map +1 -0
  184. package/dist/src/integrations/openrouter-pricing.d.ts +42 -0
  185. package/dist/src/integrations/openrouter-pricing.d.ts.map +1 -0
  186. package/dist/src/integrations/openrouter-pricing.js +124 -0
  187. package/dist/src/integrations/openrouter-pricing.js.map +1 -0
  188. package/dist/src/integrations/pending-plan.d.ts +171 -0
  189. package/dist/src/integrations/pending-plan.d.ts.map +1 -0
  190. package/dist/src/integrations/pending-plan.js +244 -0
  191. package/dist/src/integrations/pending-plan.js.map +1 -0
  192. package/dist/src/integrations/persistence.d.ts +48 -0
  193. package/dist/src/integrations/persistence.d.ts.map +1 -0
  194. package/dist/src/integrations/persistence.js +196 -0
  195. package/dist/src/integrations/persistence.js.map +1 -0
  196. package/dist/src/integrations/planning.d.ts +96 -0
  197. package/dist/src/integrations/planning.d.ts.map +1 -0
  198. package/dist/src/integrations/planning.js +338 -0
  199. package/dist/src/integrations/planning.js.map +1 -0
  200. package/dist/src/integrations/pty-shell.d.ts +169 -0
  201. package/dist/src/integrations/pty-shell.d.ts.map +1 -0
  202. package/dist/src/integrations/pty-shell.js +367 -0
  203. package/dist/src/integrations/pty-shell.js.map +1 -0
  204. package/dist/src/integrations/react.d.ts +139 -0
  205. package/dist/src/integrations/react.d.ts.map +1 -0
  206. package/dist/src/integrations/react.js +273 -0
  207. package/dist/src/integrations/react.js.map +1 -0
  208. package/dist/src/integrations/resources.d.ts +177 -0
  209. package/dist/src/integrations/resources.d.ts.map +1 -0
  210. package/dist/src/integrations/resources.js +311 -0
  211. package/dist/src/integrations/resources.js.map +1 -0
  212. package/dist/src/integrations/result-synthesizer.d.ts +389 -0
  213. package/dist/src/integrations/result-synthesizer.d.ts.map +1 -0
  214. package/dist/src/integrations/result-synthesizer.js +951 -0
  215. package/dist/src/integrations/result-synthesizer.js.map +1 -0
  216. package/dist/src/integrations/routing.d.ts +117 -0
  217. package/dist/src/integrations/routing.d.ts.map +1 -0
  218. package/dist/src/integrations/routing.js +347 -0
  219. package/dist/src/integrations/routing.js.map +1 -0
  220. package/dist/src/integrations/rules.d.ts +131 -0
  221. package/dist/src/integrations/rules.d.ts.map +1 -0
  222. package/dist/src/integrations/rules.js +284 -0
  223. package/dist/src/integrations/rules.js.map +1 -0
  224. package/dist/src/integrations/safety.d.ts +142 -0
  225. package/dist/src/integrations/safety.d.ts.map +1 -0
  226. package/dist/src/integrations/safety.js +342 -0
  227. package/dist/src/integrations/safety.js.map +1 -0
  228. package/dist/src/integrations/sandbox/basic.d.ts +74 -0
  229. package/dist/src/integrations/sandbox/basic.d.ts.map +1 -0
  230. package/dist/src/integrations/sandbox/basic.js +310 -0
  231. package/dist/src/integrations/sandbox/basic.js.map +1 -0
  232. package/dist/src/integrations/sandbox/docker.d.ts +94 -0
  233. package/dist/src/integrations/sandbox/docker.d.ts.map +1 -0
  234. package/dist/src/integrations/sandbox/docker.js +293 -0
  235. package/dist/src/integrations/sandbox/docker.js.map +1 -0
  236. package/dist/src/integrations/sandbox/index.d.ts +182 -0
  237. package/dist/src/integrations/sandbox/index.d.ts.map +1 -0
  238. package/dist/src/integrations/sandbox/index.js +382 -0
  239. package/dist/src/integrations/sandbox/index.js.map +1 -0
  240. package/dist/src/integrations/sandbox/landlock.d.ts +59 -0
  241. package/dist/src/integrations/sandbox/landlock.d.ts.map +1 -0
  242. package/dist/src/integrations/sandbox/landlock.js +326 -0
  243. package/dist/src/integrations/sandbox/landlock.js.map +1 -0
  244. package/dist/src/integrations/sandbox/seatbelt.d.ts +68 -0
  245. package/dist/src/integrations/sandbox/seatbelt.d.ts.map +1 -0
  246. package/dist/src/integrations/sandbox/seatbelt.js +298 -0
  247. package/dist/src/integrations/sandbox/seatbelt.js.map +1 -0
  248. package/dist/src/integrations/semantic-cache.d.ts +178 -0
  249. package/dist/src/integrations/semantic-cache.d.ts.map +1 -0
  250. package/dist/src/integrations/semantic-cache.js +372 -0
  251. package/dist/src/integrations/semantic-cache.js.map +1 -0
  252. package/dist/src/integrations/session-store.d.ts +183 -0
  253. package/dist/src/integrations/session-store.d.ts.map +1 -0
  254. package/dist/src/integrations/session-store.js +345 -0
  255. package/dist/src/integrations/session-store.js.map +1 -0
  256. package/dist/src/integrations/shared-blackboard.d.ts +403 -0
  257. package/dist/src/integrations/shared-blackboard.d.ts.map +1 -0
  258. package/dist/src/integrations/shared-blackboard.js +710 -0
  259. package/dist/src/integrations/shared-blackboard.js.map +1 -0
  260. package/dist/src/integrations/skills.d.ts +171 -0
  261. package/dist/src/integrations/skills.d.ts.map +1 -0
  262. package/dist/src/integrations/skills.js +403 -0
  263. package/dist/src/integrations/skills.js.map +1 -0
  264. package/dist/src/integrations/smart-decomposer.d.ts +322 -0
  265. package/dist/src/integrations/smart-decomposer.d.ts.map +1 -0
  266. package/dist/src/integrations/smart-decomposer.js +856 -0
  267. package/dist/src/integrations/smart-decomposer.js.map +1 -0
  268. package/dist/src/integrations/sourcegraph.d.ts +169 -0
  269. package/dist/src/integrations/sourcegraph.d.ts.map +1 -0
  270. package/dist/src/integrations/sourcegraph.js +379 -0
  271. package/dist/src/integrations/sourcegraph.js.map +1 -0
  272. package/dist/src/integrations/sqlite-store.d.ts +518 -0
  273. package/dist/src/integrations/sqlite-store.d.ts.map +1 -0
  274. package/dist/src/integrations/sqlite-store.js +1423 -0
  275. package/dist/src/integrations/sqlite-store.js.map +1 -0
  276. package/dist/src/integrations/streaming.d.ts +102 -0
  277. package/dist/src/integrations/streaming.d.ts.map +1 -0
  278. package/dist/src/integrations/streaming.js +362 -0
  279. package/dist/src/integrations/streaming.js.map +1 -0
  280. package/dist/src/integrations/thread-manager.d.ts +199 -0
  281. package/dist/src/integrations/thread-manager.d.ts.map +1 -0
  282. package/dist/src/integrations/thread-manager.js +357 -0
  283. package/dist/src/integrations/thread-manager.js.map +1 -0
  284. package/dist/src/main.d.ts +26 -0
  285. package/dist/src/main.d.ts.map +1 -0
  286. package/dist/src/main.js +170 -0
  287. package/dist/src/main.js.map +1 -0
  288. package/dist/src/modes/index.d.ts +10 -0
  289. package/dist/src/modes/index.d.ts.map +1 -0
  290. package/dist/src/modes/index.js +10 -0
  291. package/dist/src/modes/index.js.map +1 -0
  292. package/dist/src/modes/repl.d.ts +19 -0
  293. package/dist/src/modes/repl.d.ts.map +1 -0
  294. package/dist/src/modes/repl.js +393 -0
  295. package/dist/src/modes/repl.js.map +1 -0
  296. package/dist/src/modes/tui.d.ts +29 -0
  297. package/dist/src/modes/tui.d.ts.map +1 -0
  298. package/dist/src/modes/tui.js +272 -0
  299. package/dist/src/modes/tui.js.map +1 -0
  300. package/dist/src/modes.d.ts +179 -0
  301. package/dist/src/modes.d.ts.map +1 -0
  302. package/dist/src/modes.js +385 -0
  303. package/dist/src/modes.js.map +1 -0
  304. package/dist/src/observability/tracer.d.ts +111 -0
  305. package/dist/src/observability/tracer.d.ts.map +1 -0
  306. package/dist/src/observability/tracer.js +300 -0
  307. package/dist/src/observability/tracer.js.map +1 -0
  308. package/dist/src/observability/types.d.ts +271 -0
  309. package/dist/src/observability/types.d.ts.map +1 -0
  310. package/dist/src/observability/types.js +24 -0
  311. package/dist/src/observability/types.js.map +1 -0
  312. package/dist/src/paths.d.ts +101 -0
  313. package/dist/src/paths.d.ts.map +1 -0
  314. package/dist/src/paths.js +148 -0
  315. package/dist/src/paths.js.map +1 -0
  316. package/dist/src/persistence/index.d.ts +38 -0
  317. package/dist/src/persistence/index.d.ts.map +1 -0
  318. package/dist/src/persistence/index.js +48 -0
  319. package/dist/src/persistence/index.js.map +1 -0
  320. package/dist/src/persistence/migrator.d.ts +135 -0
  321. package/dist/src/persistence/migrator.d.ts.map +1 -0
  322. package/dist/src/persistence/migrator.js +303 -0
  323. package/dist/src/persistence/migrator.js.map +1 -0
  324. package/dist/src/persistence/schema.d.ts +101 -0
  325. package/dist/src/persistence/schema.d.ts.map +1 -0
  326. package/dist/src/persistence/schema.js +395 -0
  327. package/dist/src/persistence/schema.js.map +1 -0
  328. package/dist/src/providers/adapters/anthropic.d.ts +20 -0
  329. package/dist/src/providers/adapters/anthropic.d.ts.map +1 -0
  330. package/dist/src/providers/adapters/anthropic.js +124 -0
  331. package/dist/src/providers/adapters/anthropic.js.map +1 -0
  332. package/dist/src/providers/adapters/mock.d.ts +25 -0
  333. package/dist/src/providers/adapters/mock.d.ts.map +1 -0
  334. package/dist/src/providers/adapters/mock.js +133 -0
  335. package/dist/src/providers/adapters/mock.js.map +1 -0
  336. package/dist/src/providers/adapters/openai.d.ts +21 -0
  337. package/dist/src/providers/adapters/openai.d.ts.map +1 -0
  338. package/dist/src/providers/adapters/openai.js +126 -0
  339. package/dist/src/providers/adapters/openai.js.map +1 -0
  340. package/dist/src/providers/adapters/openrouter.d.ts +49 -0
  341. package/dist/src/providers/adapters/openrouter.d.ts.map +1 -0
  342. package/dist/src/providers/adapters/openrouter.js +363 -0
  343. package/dist/src/providers/adapters/openrouter.js.map +1 -0
  344. package/dist/src/providers/provider.d.ts +54 -0
  345. package/dist/src/providers/provider.d.ts.map +1 -0
  346. package/dist/src/providers/provider.js +111 -0
  347. package/dist/src/providers/provider.js.map +1 -0
  348. package/dist/src/providers/resilient-fetch.d.ts +99 -0
  349. package/dist/src/providers/resilient-fetch.d.ts.map +1 -0
  350. package/dist/src/providers/resilient-fetch.js +208 -0
  351. package/dist/src/providers/resilient-fetch.js.map +1 -0
  352. package/dist/src/providers/types.d.ts +227 -0
  353. package/dist/src/providers/types.d.ts.map +1 -0
  354. package/dist/src/providers/types.js +24 -0
  355. package/dist/src/providers/types.js.map +1 -0
  356. package/dist/src/session-picker.d.ts +28 -0
  357. package/dist/src/session-picker.d.ts.map +1 -0
  358. package/dist/src/session-picker.js +256 -0
  359. package/dist/src/session-picker.js.map +1 -0
  360. package/dist/src/test-sqlite.d.ts +2 -0
  361. package/dist/src/test-sqlite.d.ts.map +1 -0
  362. package/dist/src/test-sqlite.js +114 -0
  363. package/dist/src/test-sqlite.js.map +1 -0
  364. package/dist/src/tools/agent.d.ts +44 -0
  365. package/dist/src/tools/agent.d.ts.map +1 -0
  366. package/dist/src/tools/agent.js +110 -0
  367. package/dist/src/tools/agent.js.map +1 -0
  368. package/dist/src/tools/bash.d.ts +52 -0
  369. package/dist/src/tools/bash.d.ts.map +1 -0
  370. package/dist/src/tools/bash.js +141 -0
  371. package/dist/src/tools/bash.js.map +1 -0
  372. package/dist/src/tools/file.d.ts +47 -0
  373. package/dist/src/tools/file.d.ts.map +1 -0
  374. package/dist/src/tools/file.js +263 -0
  375. package/dist/src/tools/file.js.map +1 -0
  376. package/dist/src/tools/permission.d.ts +43 -0
  377. package/dist/src/tools/permission.d.ts.map +1 -0
  378. package/dist/src/tools/permission.js +216 -0
  379. package/dist/src/tools/permission.js.map +1 -0
  380. package/dist/src/tools/registry.d.ts +63 -0
  381. package/dist/src/tools/registry.d.ts.map +1 -0
  382. package/dist/src/tools/registry.js +250 -0
  383. package/dist/src/tools/registry.js.map +1 -0
  384. package/dist/src/tools/standard.d.ts +57 -0
  385. package/dist/src/tools/standard.d.ts.map +1 -0
  386. package/dist/src/tools/standard.js +113 -0
  387. package/dist/src/tools/standard.js.map +1 -0
  388. package/dist/src/tools/types.d.ts +146 -0
  389. package/dist/src/tools/types.d.ts.map +1 -0
  390. package/dist/src/tools/types.js +28 -0
  391. package/dist/src/tools/types.js.map +1 -0
  392. package/dist/src/tools/undo.d.ts +71 -0
  393. package/dist/src/tools/undo.d.ts.map +1 -0
  394. package/dist/src/tools/undo.js +123 -0
  395. package/dist/src/tools/undo.js.map +1 -0
  396. package/dist/src/tracing/cache-boundary-tracker.d.ts +189 -0
  397. package/dist/src/tracing/cache-boundary-tracker.d.ts.map +1 -0
  398. package/dist/src/tracing/cache-boundary-tracker.js +411 -0
  399. package/dist/src/tracing/cache-boundary-tracker.js.map +1 -0
  400. package/dist/src/tracing/trace-collector.d.ts +274 -0
  401. package/dist/src/tracing/trace-collector.d.ts.map +1 -0
  402. package/dist/src/tracing/trace-collector.js +727 -0
  403. package/dist/src/tracing/trace-collector.js.map +1 -0
  404. package/dist/src/tracing/types.d.ts +657 -0
  405. package/dist/src/tracing/types.d.ts.map +1 -0
  406. package/dist/src/tracing/types.js +39 -0
  407. package/dist/src/tracing/types.js.map +1 -0
  408. package/dist/src/tricks/failure-evidence.d.ts +268 -0
  409. package/dist/src/tricks/failure-evidence.d.ts.map +1 -0
  410. package/dist/src/tricks/failure-evidence.js +544 -0
  411. package/dist/src/tricks/failure-evidence.js.map +1 -0
  412. package/dist/src/tricks/json-utils.d.ts +77 -0
  413. package/dist/src/tricks/json-utils.d.ts.map +1 -0
  414. package/dist/src/tricks/json-utils.js +247 -0
  415. package/dist/src/tricks/json-utils.js.map +1 -0
  416. package/dist/src/tricks/kv-cache-context.d.ts +227 -0
  417. package/dist/src/tricks/kv-cache-context.d.ts.map +1 -0
  418. package/dist/src/tricks/kv-cache-context.js +377 -0
  419. package/dist/src/tricks/kv-cache-context.js.map +1 -0
  420. package/dist/src/tricks/recitation.d.ts +208 -0
  421. package/dist/src/tricks/recitation.d.ts.map +1 -0
  422. package/dist/src/tricks/recitation.js +374 -0
  423. package/dist/src/tricks/recitation.js.map +1 -0
  424. package/dist/src/tricks/reversible-compaction.d.ts +251 -0
  425. package/dist/src/tricks/reversible-compaction.d.ts.map +1 -0
  426. package/dist/src/tricks/reversible-compaction.js +555 -0
  427. package/dist/src/tricks/reversible-compaction.js.map +1 -0
  428. package/dist/src/tricks/serialization-diversity.d.ts +197 -0
  429. package/dist/src/tricks/serialization-diversity.d.ts.map +1 -0
  430. package/dist/src/tricks/serialization-diversity.js +460 -0
  431. package/dist/src/tricks/serialization-diversity.js.map +1 -0
  432. package/dist/src/tui/app.d.ts +42 -0
  433. package/dist/src/tui/app.d.ts.map +1 -0
  434. package/dist/src/tui/app.js +1076 -0
  435. package/dist/src/tui/app.js.map +1 -0
  436. package/dist/src/tui/components/ApprovalDialog.d.ts +28 -0
  437. package/dist/src/tui/components/ApprovalDialog.d.ts.map +1 -0
  438. package/dist/src/tui/components/ApprovalDialog.js +59 -0
  439. package/dist/src/tui/components/ApprovalDialog.js.map +1 -0
  440. package/dist/src/tui/components/InputArea.d.ts +35 -0
  441. package/dist/src/tui/components/InputArea.d.ts.map +1 -0
  442. package/dist/src/tui/components/InputArea.js +144 -0
  443. package/dist/src/tui/components/InputArea.js.map +1 -0
  444. package/dist/src/tui/components/MessageItem.d.ts +28 -0
  445. package/dist/src/tui/components/MessageItem.d.ts.map +1 -0
  446. package/dist/src/tui/components/MessageItem.js +27 -0
  447. package/dist/src/tui/components/MessageItem.js.map +1 -0
  448. package/dist/src/tui/components/ScrollableBox.d.ts +41 -0
  449. package/dist/src/tui/components/ScrollableBox.d.ts.map +1 -0
  450. package/dist/src/tui/components/ScrollableBox.js +101 -0
  451. package/dist/src/tui/components/ScrollableBox.js.map +1 -0
  452. package/dist/src/tui/components/ToolCallItem.d.ts +33 -0
  453. package/dist/src/tui/components/ToolCallItem.d.ts.map +1 -0
  454. package/dist/src/tui/components/ToolCallItem.js +91 -0
  455. package/dist/src/tui/components/ToolCallItem.js.map +1 -0
  456. package/dist/src/tui/components/index.d.ts +13 -0
  457. package/dist/src/tui/components/index.d.ts.map +1 -0
  458. package/dist/src/tui/components/index.js +15 -0
  459. package/dist/src/tui/components/index.js.map +1 -0
  460. package/dist/src/tui/event-display.d.ts +19 -0
  461. package/dist/src/tui/event-display.d.ts.map +1 -0
  462. package/dist/src/tui/event-display.js +178 -0
  463. package/dist/src/tui/event-display.js.map +1 -0
  464. package/dist/src/tui/index.d.ts +105 -0
  465. package/dist/src/tui/index.d.ts.map +1 -0
  466. package/dist/src/tui/index.js +214 -0
  467. package/dist/src/tui/index.js.map +1 -0
  468. package/dist/src/tui/input/CommandPalette.d.ts +55 -0
  469. package/dist/src/tui/input/CommandPalette.d.ts.map +1 -0
  470. package/dist/src/tui/input/CommandPalette.js +135 -0
  471. package/dist/src/tui/input/CommandPalette.js.map +1 -0
  472. package/dist/src/tui/input/index.d.ts +7 -0
  473. package/dist/src/tui/input/index.d.ts.map +1 -0
  474. package/dist/src/tui/input/index.js +7 -0
  475. package/dist/src/tui/input/index.js.map +1 -0
  476. package/dist/src/tui/theme/index.d.ts +45 -0
  477. package/dist/src/tui/theme/index.d.ts.map +1 -0
  478. package/dist/src/tui/theme/index.js +215 -0
  479. package/dist/src/tui/theme/index.js.map +1 -0
  480. package/dist/src/tui/types.d.ts +214 -0
  481. package/dist/src/tui/types.d.ts.map +1 -0
  482. package/dist/src/tui/types.js +27 -0
  483. package/dist/src/tui/types.js.map +1 -0
  484. package/dist/src/types.d.ts +905 -0
  485. package/dist/src/types.d.ts.map +1 -0
  486. package/dist/src/types.js +9 -0
  487. package/dist/src/types.js.map +1 -0
  488. package/package.json +89 -0
@@ -0,0 +1,727 @@
1
+ /**
2
+ * Lesson 26: Trace Collector
3
+ *
4
+ * Central hub that coordinates tracing, metrics, and cache analysis.
5
+ * Subscribes to agent events and produces comprehensive JSONL output.
6
+ *
7
+ * Key responsibilities:
8
+ * 1. Capture full LLM request/response details
9
+ * 2. Track tool execution with timing
10
+ * 3. Analyze cache efficiency per request
11
+ * 4. Export structured JSONL for analysis
12
+ *
13
+ * @example
14
+ * ```typescript
15
+ * const collector = new TraceCollector({
16
+ * outputDir: '.traces',
17
+ * captureMessageContent: true,
18
+ * });
19
+ *
20
+ * collector.startSession('task-id', 'Write a fizzbuzz function', 'claude-3-sonnet');
21
+ *
22
+ * // During agent execution...
23
+ * collector.recordLLMRequest(requestData);
24
+ * collector.recordLLMResponse(responseData);
25
+ * collector.recordToolExecution(toolData);
26
+ *
27
+ * // When done
28
+ * const trace = await collector.endSession({ success: true });
29
+ * ```
30
+ */
31
+ import { mkdir, appendFile } from 'fs/promises';
32
+ import { join } from 'path';
33
+ import { createTracer } from '../observability/tracer.js';
34
+ import { createCacheBoundaryTracker } from './cache-boundary-tracker.js';
35
+ import { DEFAULT_TRACE_CONFIG } from './types.js';
36
+ // =============================================================================
37
+ // TRACE COLLECTOR
38
+ // =============================================================================
39
+ /**
40
+ * Central trace collection hub.
41
+ */
42
+ export class TraceCollector {
43
+ config;
44
+ tracer;
45
+ cacheTracker;
46
+ // Session state
47
+ sessionId = null;
48
+ traceId = null;
49
+ task = '';
50
+ model = '';
51
+ startTime = 0;
52
+ // Current iteration state
53
+ currentIteration = 0;
54
+ iterationSpan = null;
55
+ iterationStartTime = 0;
56
+ currentIterationTrace = null;
57
+ // Accumulated data
58
+ iterations = [];
59
+ pendingRequests = new Map();
60
+ pendingTools = new Map();
61
+ // JSONL output
62
+ outputPath = null;
63
+ writeQueue = Promise.resolve();
64
+ constructor(config = {}) {
65
+ this.config = { ...DEFAULT_TRACE_CONFIG, ...config };
66
+ this.tracer = createTracer('trace-collector');
67
+ this.cacheTracker = createCacheBoundaryTracker();
68
+ }
69
+ // ===========================================================================
70
+ // SESSION LIFECYCLE
71
+ // ===========================================================================
72
+ /**
73
+ * Start a new tracing session.
74
+ */
75
+ async startSession(sessionId, task, model, metadata = {}) {
76
+ if (this.sessionId) {
77
+ throw new Error('Session already in progress. Call endSession() first.');
78
+ }
79
+ this.sessionId = sessionId;
80
+ this.task = task;
81
+ this.model = model;
82
+ this.startTime = Date.now();
83
+ this.currentIteration = 0;
84
+ this.iterations = [];
85
+ this.cacheTracker.reset();
86
+ // Start root span
87
+ const rootSpan = this.tracer.startSpan('session', {
88
+ kind: 'internal',
89
+ attributes: {
90
+ 'session.id': sessionId,
91
+ 'session.task': task,
92
+ 'session.model': model,
93
+ },
94
+ });
95
+ this.traceId = rootSpan.traceId;
96
+ // Set up JSONL output
97
+ if (this.config.enabled) {
98
+ await this.initializeOutput();
99
+ await this.writeEntry({
100
+ _type: 'session.start',
101
+ _ts: new Date().toISOString(),
102
+ traceId: this.traceId,
103
+ sessionId,
104
+ task,
105
+ model,
106
+ metadata,
107
+ });
108
+ }
109
+ }
110
+ /**
111
+ * End the current session and return the complete trace.
112
+ */
113
+ async endSession(result) {
114
+ if (!this.sessionId || !this.traceId) {
115
+ throw new Error('No session in progress');
116
+ }
117
+ const endTime = Date.now();
118
+ const durationMs = endTime - this.startTime;
119
+ // End any pending iteration
120
+ if (this.iterationSpan) {
121
+ this.tracer.endSpan(this.iterationSpan);
122
+ this.iterationSpan = null;
123
+ }
124
+ // Calculate aggregated metrics
125
+ const metrics = this.calculateAggregatedMetrics();
126
+ // Build session trace
127
+ const sessionTrace = {
128
+ sessionId: this.sessionId,
129
+ traceId: this.traceId,
130
+ task: this.task,
131
+ model: this.model,
132
+ startTime: this.startTime,
133
+ endTime,
134
+ durationMs,
135
+ status: result.success ? 'completed' : 'failed',
136
+ iterations: this.iterations,
137
+ metrics,
138
+ result,
139
+ metadata: {},
140
+ };
141
+ // Write session end entry
142
+ if (this.config.enabled) {
143
+ await this.writeEntry({
144
+ _type: 'session.end',
145
+ _ts: new Date().toISOString(),
146
+ traceId: this.traceId,
147
+ sessionId: this.sessionId,
148
+ status: sessionTrace.status,
149
+ durationMs,
150
+ metrics: {
151
+ inputTokens: metrics.inputTokens,
152
+ outputTokens: metrics.outputTokens,
153
+ cacheReadTokens: metrics.cacheReadTokens,
154
+ cacheWriteTokens: metrics.cacheWriteTokens,
155
+ estimatedCost: metrics.estimatedCost,
156
+ toolCalls: metrics.toolCalls,
157
+ llmCalls: metrics.llmCalls,
158
+ duration: durationMs,
159
+ errors: metrics.errors,
160
+ retries: metrics.retries,
161
+ },
162
+ });
163
+ await this.flush();
164
+ }
165
+ // Reset state
166
+ this.sessionId = null;
167
+ this.traceId = null;
168
+ this.task = '';
169
+ this.model = '';
170
+ return sessionTrace;
171
+ }
172
+ // ===========================================================================
173
+ // EVENT RECORDING
174
+ // ===========================================================================
175
+ /**
176
+ * Record an event.
177
+ */
178
+ async record(event) {
179
+ if (!this.config.enabled || !this.sessionId)
180
+ return;
181
+ switch (event.type) {
182
+ case 'llm.request':
183
+ await this.recordLLMRequest(event.data);
184
+ break;
185
+ case 'llm.response':
186
+ await this.recordLLMResponse(event.data);
187
+ break;
188
+ case 'tool.start':
189
+ await this.recordToolStart(event.data);
190
+ break;
191
+ case 'tool.end':
192
+ await this.recordToolEnd(event.data);
193
+ break;
194
+ case 'iteration.start':
195
+ this.startIteration(event.data.iterationNumber);
196
+ break;
197
+ case 'iteration.end':
198
+ await this.endIteration();
199
+ break;
200
+ case 'error':
201
+ await this.recordError(event.data);
202
+ break;
203
+ }
204
+ }
205
+ /**
206
+ * Record an LLM request.
207
+ */
208
+ async recordLLMRequest(data) {
209
+ const span = this.tracer.startSpan('llm.request', {
210
+ kind: 'client',
211
+ attributes: {
212
+ 'llm.model': data.model,
213
+ 'llm.provider': data.provider,
214
+ 'llm.message_count': data.messages.length,
215
+ 'llm.tool_count': data.tools?.length ?? 0,
216
+ },
217
+ });
218
+ // Track cache boundaries
219
+ if (this.config.analyzeCacheBoundaries) {
220
+ this.cacheTracker.recordRequest({
221
+ systemPrompt: data.systemPrompt ?? data.messages.find(m => m.role === 'system')?.content ?? '',
222
+ messages: data.messages,
223
+ toolDefinitions: data.tools,
224
+ });
225
+ }
226
+ // Store pending request
227
+ this.pendingRequests.set(data.requestId, {
228
+ span,
229
+ data,
230
+ startTime: Date.now(),
231
+ });
232
+ // Estimate input tokens
233
+ const estimatedInputTokens = this.estimateInputTokens(data);
234
+ // Write JSONL entry
235
+ await this.writeEntry({
236
+ _type: 'llm.request',
237
+ _ts: new Date().toISOString(),
238
+ traceId: this.traceId,
239
+ requestId: data.requestId,
240
+ model: data.model,
241
+ messageCount: data.messages.length,
242
+ toolCount: data.tools?.length ?? 0,
243
+ estimatedInputTokens,
244
+ });
245
+ }
246
+ /**
247
+ * Record an LLM response.
248
+ */
249
+ async recordLLMResponse(data) {
250
+ const pending = this.pendingRequests.get(data.requestId);
251
+ if (!pending) {
252
+ console.warn(`No pending request found for ${data.requestId}`);
253
+ return;
254
+ }
255
+ const { span, data: requestData, startTime } = pending;
256
+ this.pendingRequests.delete(data.requestId);
257
+ // Update cache tracker with actual API response
258
+ let cacheBreakdown;
259
+ if (this.config.analyzeCacheBoundaries && data.usage.cacheReadTokens !== undefined) {
260
+ cacheBreakdown = this.cacheTracker.recordResponse({
261
+ cacheReadTokens: data.usage.cacheReadTokens,
262
+ cacheWriteTokens: data.usage.cacheWriteTokens ?? 0,
263
+ totalInputTokens: data.usage.inputTokens,
264
+ outputTokens: data.usage.outputTokens,
265
+ });
266
+ }
267
+ else {
268
+ cacheBreakdown = {
269
+ cacheReadTokens: data.usage.cacheReadTokens ?? 0,
270
+ cacheWriteTokens: data.usage.cacheWriteTokens ?? 0,
271
+ freshTokens: data.usage.inputTokens - (data.usage.cacheReadTokens ?? 0),
272
+ hitRate: data.usage.cacheReadTokens
273
+ ? data.usage.cacheReadTokens / data.usage.inputTokens
274
+ : 0,
275
+ estimatedSavings: 0,
276
+ breakpoints: [],
277
+ };
278
+ }
279
+ // Calculate token breakdown
280
+ const tokens = {
281
+ input: data.usage.inputTokens,
282
+ output: data.usage.outputTokens,
283
+ total: data.usage.inputTokens + data.usage.outputTokens,
284
+ breakdown: {
285
+ systemPrompt: this.estimateTokens(requestData.systemPrompt ?? ''),
286
+ messages: data.usage.inputTokens - this.estimateTokens(requestData.systemPrompt ?? ''),
287
+ toolDefinitions: requestData.tools ? this.estimateToolTokens(requestData.tools) : 0,
288
+ toolResults: 0,
289
+ },
290
+ };
291
+ // Build LLM request trace
292
+ const llmTrace = {
293
+ requestId: data.requestId,
294
+ traceId: this.traceId,
295
+ spanId: span.spanId,
296
+ timestamp: startTime,
297
+ durationMs: data.durationMs,
298
+ model: requestData.model,
299
+ provider: requestData.provider,
300
+ request: {
301
+ messages: this.config.captureMessageContent
302
+ ? this.traceMessages(requestData.messages)
303
+ : [],
304
+ tools: requestData.tools?.map(t => ({
305
+ name: t.name,
306
+ description: t.description,
307
+ parametersSchema: t.parametersSchema,
308
+ estimatedTokens: this.estimateTokens(JSON.stringify(t)),
309
+ })),
310
+ parameters: requestData.parameters,
311
+ },
312
+ response: {
313
+ content: this.config.captureMessageContent ? data.content : '[content not captured]',
314
+ toolCalls: data.toolCalls,
315
+ stopReason: data.stopReason,
316
+ },
317
+ tokens,
318
+ cache: cacheBreakdown,
319
+ // Store actual cost from provider (e.g., OpenRouter) when available
320
+ actualCost: data.usage.cost,
321
+ };
322
+ // Store in current iteration
323
+ if (this.currentIterationTrace) {
324
+ this.currentIterationTrace.llmRequest = llmTrace;
325
+ }
326
+ // Update span
327
+ this.tracer.setAttributes(span, {
328
+ 'llm.input_tokens': data.usage.inputTokens,
329
+ 'llm.output_tokens': data.usage.outputTokens,
330
+ 'llm.cache_read_tokens': data.usage.cacheReadTokens ?? 0,
331
+ 'llm.cache_hit_rate': cacheBreakdown.hitRate,
332
+ 'llm.stop_reason': data.stopReason,
333
+ 'llm.tool_calls': data.toolCalls?.length ?? 0,
334
+ });
335
+ this.tracer.endSpan(span);
336
+ // Write JSONL entry
337
+ await this.writeEntry({
338
+ _type: 'llm.response',
339
+ _ts: new Date().toISOString(),
340
+ traceId: this.traceId,
341
+ requestId: data.requestId,
342
+ durationMs: data.durationMs,
343
+ tokens,
344
+ cache: cacheBreakdown,
345
+ stopReason: data.stopReason,
346
+ toolCallCount: data.toolCalls?.length ?? 0,
347
+ });
348
+ }
349
+ /**
350
+ * Record tool execution start.
351
+ */
352
+ async recordToolStart(data) {
353
+ const span = this.tracer.startSpan(`tool.${data.toolName}`, {
354
+ kind: 'internal',
355
+ attributes: {
356
+ 'tool.name': data.toolName,
357
+ 'tool.execution_id': data.executionId,
358
+ },
359
+ });
360
+ this.pendingTools.set(data.executionId, {
361
+ span,
362
+ data,
363
+ startTime: Date.now(),
364
+ });
365
+ }
366
+ /**
367
+ * Record tool execution end.
368
+ */
369
+ async recordToolEnd(data) {
370
+ const pending = this.pendingTools.get(data.executionId);
371
+ if (!pending) {
372
+ console.warn(`No pending tool execution found for ${data.executionId}`);
373
+ return;
374
+ }
375
+ const { span, data: startData, startTime } = pending;
376
+ this.pendingTools.delete(data.executionId);
377
+ // Build tool trace
378
+ const toolTrace = {
379
+ executionId: data.executionId,
380
+ traceId: this.traceId,
381
+ spanId: span.spanId,
382
+ toolName: startData.toolName,
383
+ arguments: startData.arguments,
384
+ startTime,
385
+ durationMs: data.durationMs,
386
+ status: data.status,
387
+ };
388
+ // Add result or error
389
+ if (data.status === 'success' && data.result !== undefined) {
390
+ const resultStr = typeof data.result === 'string'
391
+ ? data.result
392
+ : JSON.stringify(data.result);
393
+ toolTrace.result = {
394
+ type: typeof data.result === 'string' ? 'string' : 'object',
395
+ value: this.config.captureToolResults
396
+ ? this.truncateResult(data.result)
397
+ : '[result not captured]',
398
+ truncated: resultStr.length > this.config.maxResultSize,
399
+ originalSize: resultStr.length,
400
+ };
401
+ }
402
+ if (data.error) {
403
+ toolTrace.error = {
404
+ name: data.error.name,
405
+ message: data.error.message,
406
+ stack: data.error.stack,
407
+ };
408
+ }
409
+ // Store in current iteration
410
+ if (this.currentIterationTrace) {
411
+ if (!this.currentIterationTrace.toolExecutions) {
412
+ this.currentIterationTrace.toolExecutions = [];
413
+ }
414
+ this.currentIterationTrace.toolExecutions.push(toolTrace);
415
+ }
416
+ // Update span
417
+ this.tracer.setAttributes(span, {
418
+ 'tool.status': data.status,
419
+ 'tool.duration_ms': data.durationMs,
420
+ });
421
+ if (data.status === 'error') {
422
+ this.tracer.setError(span, data.error ?? new Error('Unknown error'));
423
+ }
424
+ this.tracer.endSpan(span, {
425
+ code: data.status === 'success' ? 'ok' : 'error',
426
+ message: data.status === 'error' ? data.error?.message : undefined,
427
+ });
428
+ // Write JSONL entry
429
+ await this.writeEntry({
430
+ _type: 'tool.execution',
431
+ _ts: new Date().toISOString(),
432
+ traceId: this.traceId,
433
+ executionId: data.executionId,
434
+ toolName: startData.toolName,
435
+ durationMs: data.durationMs,
436
+ status: data.status,
437
+ resultSize: toolTrace.result?.originalSize,
438
+ });
439
+ }
440
+ /**
441
+ * Record an error.
442
+ */
443
+ async recordError(data) {
444
+ await this.writeEntry({
445
+ _type: 'error',
446
+ _ts: new Date().toISOString(),
447
+ traceId: this.traceId,
448
+ errorCode: data.code,
449
+ errorMessage: data.message,
450
+ context: data.context,
451
+ recoverable: data.recoverable,
452
+ });
453
+ }
454
+ // ===========================================================================
455
+ // ITERATION MANAGEMENT
456
+ // ===========================================================================
457
+ /**
458
+ * Start a new iteration.
459
+ */
460
+ startIteration(iterationNumber) {
461
+ this.currentIteration = iterationNumber;
462
+ this.iterationStartTime = Date.now();
463
+ this.iterationSpan = this.tracer.startSpan(`iteration.${iterationNumber}`, {
464
+ kind: 'internal',
465
+ attributes: {
466
+ 'iteration.number': iterationNumber,
467
+ },
468
+ });
469
+ this.currentIterationTrace = {
470
+ iterationNumber,
471
+ traceId: this.traceId,
472
+ spanId: this.iterationSpan.spanId,
473
+ startTime: this.iterationStartTime,
474
+ toolExecutions: [],
475
+ };
476
+ }
477
+ /**
478
+ * End the current iteration.
479
+ */
480
+ async endIteration() {
481
+ if (!this.iterationSpan || !this.currentIterationTrace)
482
+ return;
483
+ const endTime = Date.now();
484
+ const durationMs = endTime - this.iterationStartTime;
485
+ // Calculate iteration metrics
486
+ const llmRequest = this.currentIterationTrace.llmRequest;
487
+ // Use actual cost from provider if available, otherwise calculate
488
+ const actualCost = llmRequest?.actualCost;
489
+ const calculatedCost = this.calculateCost(llmRequest?.tokens.input ?? 0, llmRequest?.tokens.output ?? 0, llmRequest?.cache.cacheReadTokens ?? 0);
490
+ const metrics = {
491
+ inputTokens: llmRequest?.tokens.input ?? 0,
492
+ outputTokens: llmRequest?.tokens.output ?? 0,
493
+ cacheHitRate: llmRequest?.cache.hitRate ?? 0,
494
+ toolCallCount: this.currentIterationTrace.toolExecutions?.length ?? 0,
495
+ totalCost: actualCost ?? calculatedCost,
496
+ };
497
+ // Complete iteration trace
498
+ const iterationTrace = {
499
+ ...this.currentIterationTrace,
500
+ durationMs,
501
+ metrics,
502
+ };
503
+ this.iterations.push(iterationTrace);
504
+ // End span
505
+ this.tracer.setAttributes(this.iterationSpan, {
506
+ 'iteration.duration_ms': durationMs,
507
+ 'iteration.input_tokens': metrics.inputTokens,
508
+ 'iteration.output_tokens': metrics.outputTokens,
509
+ 'iteration.cache_hit_rate': metrics.cacheHitRate,
510
+ 'iteration.tool_calls': metrics.toolCallCount,
511
+ });
512
+ this.tracer.endSpan(this.iterationSpan);
513
+ this.iterationSpan = null;
514
+ this.currentIterationTrace = null;
515
+ }
516
+ // ===========================================================================
517
+ // JSONL OUTPUT
518
+ // ===========================================================================
519
+ /**
520
+ * Initialize output file.
521
+ */
522
+ async initializeOutput() {
523
+ if (!this.config.outputDir)
524
+ return;
525
+ await mkdir(this.config.outputDir, { recursive: true });
526
+ const filename = this.config.filePattern
527
+ .replace('{sessionId}', this.sessionId ?? 'unknown')
528
+ .replace('{timestamp}', Date.now().toString());
529
+ this.outputPath = join(this.config.outputDir, filename);
530
+ }
531
+ /**
532
+ * Write a JSONL entry.
533
+ */
534
+ async writeEntry(entry) {
535
+ if (!this.outputPath)
536
+ return;
537
+ // Queue writes to avoid race conditions
538
+ this.writeQueue = this.writeQueue.then(async () => {
539
+ try {
540
+ await appendFile(this.outputPath, JSON.stringify(entry) + '\n');
541
+ }
542
+ catch (err) {
543
+ console.error('Failed to write trace entry:', err);
544
+ }
545
+ });
546
+ }
547
+ /**
548
+ * Flush pending writes.
549
+ */
550
+ async flush() {
551
+ await this.writeQueue;
552
+ }
553
+ // ===========================================================================
554
+ // HELPER METHODS
555
+ // ===========================================================================
556
+ /**
557
+ * Convert messages to traced format.
558
+ */
559
+ traceMessages(messages) {
560
+ return messages.map(msg => ({
561
+ role: msg.role,
562
+ content: msg.content,
563
+ estimatedTokens: this.estimateTokens(msg.content),
564
+ toolCallId: msg.toolCallId,
565
+ toolCalls: msg.toolCalls,
566
+ contentHash: this.hashContent(msg.content),
567
+ }));
568
+ }
569
+ /**
570
+ * Estimate tokens from text.
571
+ */
572
+ estimateTokens(text) {
573
+ return Math.ceil(text.length / 4);
574
+ }
575
+ /**
576
+ * Estimate input tokens for a request.
577
+ */
578
+ estimateInputTokens(data) {
579
+ let tokens = 0;
580
+ for (const msg of data.messages) {
581
+ tokens += this.estimateTokens(msg.content);
582
+ }
583
+ if (data.tools) {
584
+ tokens += this.estimateToolTokens(data.tools);
585
+ }
586
+ return tokens;
587
+ }
588
+ /**
589
+ * Estimate tokens for tool definitions.
590
+ */
591
+ estimateToolTokens(tools) {
592
+ let tokens = 0;
593
+ for (const tool of tools) {
594
+ tokens += this.estimateTokens(tool.name);
595
+ tokens += this.estimateTokens(tool.description);
596
+ tokens += this.estimateTokens(JSON.stringify(tool.parametersSchema));
597
+ }
598
+ return tokens;
599
+ }
600
+ /**
601
+ * Truncate result if too large.
602
+ */
603
+ truncateResult(result) {
604
+ const str = typeof result === 'string' ? result : JSON.stringify(result);
605
+ if (str.length <= this.config.maxResultSize) {
606
+ return result;
607
+ }
608
+ return str.substring(0, this.config.maxResultSize) + '... [truncated]';
609
+ }
610
+ /**
611
+ * Calculate cost for tokens.
612
+ */
613
+ calculateCost(inputTokens, outputTokens, cachedTokens) {
614
+ // Claude 3 Sonnet pricing
615
+ const inputCostPer1k = 0.003;
616
+ const outputCostPer1k = 0.015;
617
+ const cachedCostPer1k = 0.0003; // ~10x cheaper
618
+ const uncachedInput = inputTokens - cachedTokens;
619
+ return ((uncachedInput / 1000) * inputCostPer1k +
620
+ (cachedTokens / 1000) * cachedCostPer1k +
621
+ (outputTokens / 1000) * outputCostPer1k);
622
+ }
623
+ /**
624
+ * Simple content hash.
625
+ */
626
+ hashContent(content) {
627
+ let hash = 0;
628
+ for (let i = 0; i < content.length; i++) {
629
+ const char = content.charCodeAt(i);
630
+ hash = ((hash << 5) - hash) + char;
631
+ hash = hash & hash;
632
+ }
633
+ return hash.toString(16);
634
+ }
635
+ /**
636
+ * Calculate aggregated metrics across all iterations.
637
+ */
638
+ calculateAggregatedMetrics() {
639
+ let inputTokens = 0;
640
+ let outputTokens = 0;
641
+ let cacheReadTokens = 0;
642
+ let cacheWriteTokens = 0;
643
+ let estimatedCost = 0;
644
+ let toolCalls = 0;
645
+ let totalCacheHitRate = 0;
646
+ let tokensSavedByCache = 0;
647
+ for (const iteration of this.iterations) {
648
+ inputTokens += iteration.metrics.inputTokens;
649
+ outputTokens += iteration.metrics.outputTokens;
650
+ cacheReadTokens += iteration.llmRequest?.cache.cacheReadTokens ?? 0;
651
+ cacheWriteTokens += iteration.llmRequest?.cache.cacheWriteTokens ?? 0;
652
+ estimatedCost += iteration.metrics.totalCost;
653
+ toolCalls += iteration.metrics.toolCallCount;
654
+ totalCacheHitRate += iteration.metrics.cacheHitRate;
655
+ }
656
+ const llmCalls = this.iterations.length;
657
+ const avgCacheHitRate = llmCalls > 0 ? totalCacheHitRate / llmCalls : 0;
658
+ // Cost saved by caching
659
+ const costWithoutCache = this.calculateCost(inputTokens, outputTokens, 0);
660
+ const costSavedByCache = costWithoutCache - estimatedCost;
661
+ tokensSavedByCache = cacheReadTokens; // Tokens that would have been re-sent
662
+ return {
663
+ inputTokens,
664
+ outputTokens,
665
+ cacheReadTokens,
666
+ cacheWriteTokens,
667
+ estimatedCost,
668
+ toolCalls,
669
+ llmCalls,
670
+ duration: Date.now() - this.startTime,
671
+ errors: 0, // TODO: track errors
672
+ retries: 0, // TODO: track retries
673
+ avgCacheHitRate,
674
+ tokensSavedByCache,
675
+ costSavedByCache,
676
+ };
677
+ }
678
+ // ===========================================================================
679
+ // PUBLIC ACCESSORS
680
+ // ===========================================================================
681
+ /**
682
+ * Get the underlying tracer.
683
+ */
684
+ getTracer() {
685
+ return this.tracer;
686
+ }
687
+ /**
688
+ * Get the cache tracker.
689
+ */
690
+ getCacheTracker() {
691
+ return this.cacheTracker;
692
+ }
693
+ /**
694
+ * Get current session ID.
695
+ */
696
+ getSessionId() {
697
+ return this.sessionId;
698
+ }
699
+ /**
700
+ * Get current trace ID.
701
+ */
702
+ getTraceId() {
703
+ return this.traceId;
704
+ }
705
+ /**
706
+ * Check if a session is active.
707
+ */
708
+ isSessionActive() {
709
+ return this.sessionId !== null;
710
+ }
711
+ /**
712
+ * Get iteration count.
713
+ */
714
+ getIterationCount() {
715
+ return this.iterations.length;
716
+ }
717
+ }
718
+ // =============================================================================
719
+ // FACTORY FUNCTION
720
+ // =============================================================================
721
+ /**
722
+ * Create a new trace collector.
723
+ */
724
+ export function createTraceCollector(config = {}) {
725
+ return new TraceCollector(config);
726
+ }
727
+ //# sourceMappingURL=trace-collector.js.map