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,816 @@
1
+ /**
2
+ * Codebase Context Integration
3
+ *
4
+ * Provides intelligent code selection for context management.
5
+ * Analyzes repository structure and selects relevant code based on:
6
+ * - Task relevance (semantic matching)
7
+ * - Architectural importance (entry points, core modules)
8
+ * - Token budget constraints
9
+ *
10
+ * Key features:
11
+ * - Budget-aware context building (select code that fits)
12
+ * - Importance scoring (imports, exports, modification frequency)
13
+ * - Incremental expansion (start minimal, expand as needed)
14
+ * - Semantic relevance matching (keyword + structure analysis)
15
+ */
16
+ import * as fs from 'fs/promises';
17
+ import * as path from 'path';
18
+ // =============================================================================
19
+ // CONSTANTS
20
+ // =============================================================================
21
+ const DEFAULT_CONFIG = {
22
+ root: process.cwd(),
23
+ includePatterns: ['**/*.ts', '**/*.tsx', '**/*.js', '**/*.jsx', '**/*.py', '**/*.go', '**/*.rs'],
24
+ excludePatterns: [
25
+ '**/node_modules/**',
26
+ '**/dist/**',
27
+ '**/build/**',
28
+ '**/.git/**',
29
+ '**/coverage/**',
30
+ '**/__pycache__/**',
31
+ '**/target/**',
32
+ '**/vendor/**',
33
+ ],
34
+ maxFileSize: 100 * 1024, // 100KB
35
+ tokensPerChar: 0.25, // Approximate: 4 chars per token
36
+ entryPointPatterns: [
37
+ '**/index.ts', '**/index.tsx', '**/index.js',
38
+ '**/main.ts', '**/main.py', '**/main.go',
39
+ '**/app.ts', '**/app.tsx', '**/app.py',
40
+ '**/server.ts', '**/server.js',
41
+ '**/cli.ts', '**/cli.js',
42
+ ],
43
+ coreModulePatterns: [
44
+ '**/src/**', '**/lib/**', '**/core/**',
45
+ '**/services/**', '**/modules/**',
46
+ ],
47
+ analyzeDependencies: true,
48
+ cacheResults: true,
49
+ cacheTTL: 5 * 60 * 1000, // 5 minutes
50
+ };
51
+ // =============================================================================
52
+ // CODEBASE CONTEXT MANAGER
53
+ // =============================================================================
54
+ /**
55
+ * Manages intelligent code selection for context building.
56
+ *
57
+ * @example
58
+ * ```typescript
59
+ * const codebase = createCodebaseContext({ root: './my-project' });
60
+ *
61
+ * // Analyze the repository
62
+ * const repoMap = await codebase.analyze();
63
+ *
64
+ * // Select relevant code for a task within budget
65
+ * const selection = await codebase.selectRelevantCode({
66
+ * task: 'implement user authentication',
67
+ * maxTokens: 8000,
68
+ * strategy: 'relevance_first',
69
+ * });
70
+ *
71
+ * // Use selected code in context
72
+ * const context = selection.chunks.map(c => c.content).join('\n\n');
73
+ * ```
74
+ */
75
+ export class CodebaseContextManager {
76
+ config;
77
+ repoMap = null;
78
+ cache = new Map();
79
+ listeners = [];
80
+ constructor(config = {}) {
81
+ this.config = { ...DEFAULT_CONFIG, ...config };
82
+ }
83
+ // ===========================================================================
84
+ // ANALYSIS
85
+ // ===========================================================================
86
+ /**
87
+ * Analyze a repository and build its structure map.
88
+ */
89
+ async analyze(root) {
90
+ const repoRoot = root ?? this.config.root;
91
+ this.emit({ type: 'analysis.started', root: repoRoot });
92
+ // Check cache
93
+ if (this.config.cacheResults) {
94
+ const cached = this.cache.get(repoRoot);
95
+ if (cached && cached.expires > Date.now()) {
96
+ this.emit({ type: 'cache.hit', root: repoRoot });
97
+ this.repoMap = cached.map;
98
+ return cached.map;
99
+ }
100
+ this.emit({ type: 'cache.miss', root: repoRoot });
101
+ }
102
+ try {
103
+ const chunks = new Map();
104
+ const entryPoints = [];
105
+ const coreModules = [];
106
+ const dependencyGraph = new Map();
107
+ const reverseDependencyGraph = new Map();
108
+ // Discover files
109
+ const files = await this.discoverFiles(repoRoot);
110
+ // Process each file
111
+ for (const filePath of files) {
112
+ const chunk = await this.processFile(repoRoot, filePath);
113
+ if (chunk) {
114
+ chunks.set(chunk.id, chunk);
115
+ // Track entry points
116
+ if (chunk.type === 'entry_point') {
117
+ entryPoints.push(filePath);
118
+ }
119
+ // Build dependency graph
120
+ if (this.config.analyzeDependencies) {
121
+ const deps = this.extractDependencies(chunk.content, filePath);
122
+ dependencyGraph.set(filePath, deps);
123
+ // Build reverse graph
124
+ for (const dep of deps) {
125
+ if (!reverseDependencyGraph.has(dep)) {
126
+ reverseDependencyGraph.set(dep, new Set());
127
+ }
128
+ reverseDependencyGraph.get(dep).add(filePath);
129
+ }
130
+ }
131
+ }
132
+ }
133
+ // Calculate total tokens
134
+ let totalTokens = 0;
135
+ for (const chunk of chunks.values()) {
136
+ totalTokens += chunk.tokenCount;
137
+ }
138
+ // Adjust importance based on dependency graph
139
+ this.adjustImportanceByConnectivity(chunks, reverseDependencyGraph);
140
+ // Identify core modules
141
+ const moduleDirs = new Set();
142
+ for (const filePath of files) {
143
+ const dir = path.dirname(filePath);
144
+ if (this.matchesPatterns(dir, this.config.coreModulePatterns)) {
145
+ moduleDirs.add(dir);
146
+ }
147
+ }
148
+ coreModules.push(...moduleDirs);
149
+ const repoMap = {
150
+ root: repoRoot,
151
+ chunks,
152
+ entryPoints,
153
+ coreModules,
154
+ dependencyGraph,
155
+ reverseDependencyGraph,
156
+ totalTokens,
157
+ analyzedAt: new Date(),
158
+ };
159
+ // Cache result
160
+ if (this.config.cacheResults) {
161
+ this.cache.set(repoRoot, {
162
+ map: repoMap,
163
+ expires: Date.now() + this.config.cacheTTL,
164
+ });
165
+ }
166
+ this.repoMap = repoMap;
167
+ this.emit({
168
+ type: 'analysis.completed',
169
+ totalFiles: chunks.size,
170
+ totalTokens,
171
+ });
172
+ return repoMap;
173
+ }
174
+ catch (error) {
175
+ this.emit({ type: 'analysis.error', error: error });
176
+ throw error;
177
+ }
178
+ }
179
+ /**
180
+ * Discover files matching include patterns.
181
+ */
182
+ async discoverFiles(root) {
183
+ const files = [];
184
+ const walk = async (dir) => {
185
+ const entries = await fs.readdir(dir, { withFileTypes: true });
186
+ for (const entry of entries) {
187
+ const fullPath = path.join(dir, entry.name);
188
+ const relativePath = path.relative(root, fullPath);
189
+ // Check exclusions first
190
+ if (this.matchesPatterns(relativePath, this.config.excludePatterns)) {
191
+ continue;
192
+ }
193
+ if (entry.isDirectory()) {
194
+ await walk(fullPath);
195
+ }
196
+ else if (entry.isFile()) {
197
+ if (this.matchesPatterns(relativePath, this.config.includePatterns)) {
198
+ files.push(relativePath);
199
+ }
200
+ }
201
+ }
202
+ };
203
+ await walk(root);
204
+ return files;
205
+ }
206
+ /**
207
+ * Process a single file into a code chunk.
208
+ */
209
+ async processFile(root, relativePath) {
210
+ const fullPath = path.join(root, relativePath);
211
+ try {
212
+ const stat = await fs.stat(fullPath);
213
+ // Skip large files
214
+ if (stat.size > this.config.maxFileSize) {
215
+ return null;
216
+ }
217
+ const content = await fs.readFile(fullPath, 'utf-8');
218
+ const tokenCount = Math.ceil(content.length * this.config.tokensPerChar);
219
+ const type = this.determineChunkType(relativePath, content);
220
+ const symbols = this.extractSymbols(content, relativePath);
221
+ const dependencies = this.extractDependencyNames(content);
222
+ // Calculate base importance
223
+ const importance = this.calculateBaseImportance(type, relativePath);
224
+ return {
225
+ id: relativePath,
226
+ filePath: relativePath,
227
+ content,
228
+ tokenCount,
229
+ importance,
230
+ type,
231
+ symbols,
232
+ dependencies,
233
+ lastModified: stat.mtime,
234
+ };
235
+ }
236
+ catch {
237
+ return null;
238
+ }
239
+ }
240
+ /**
241
+ * Determine the type of a code chunk.
242
+ */
243
+ determineChunkType(filePath, content) {
244
+ const lower = filePath.toLowerCase();
245
+ // Entry points
246
+ if (this.matchesPatterns(filePath, this.config.entryPointPatterns)) {
247
+ return 'entry_point';
248
+ }
249
+ // Tests
250
+ if (lower.includes('.test.') ||
251
+ lower.includes('.spec.') ||
252
+ lower.includes('__tests__') ||
253
+ lower.includes('/test/')) {
254
+ return 'test';
255
+ }
256
+ // Types/interfaces
257
+ if (lower.includes('/types') ||
258
+ lower.endsWith('.d.ts') ||
259
+ (content.includes('interface ') && !content.includes('function '))) {
260
+ return 'types';
261
+ }
262
+ // Config
263
+ if (lower.includes('config') ||
264
+ lower.includes('settings') ||
265
+ lower.endsWith('.json')) {
266
+ return 'config';
267
+ }
268
+ // Documentation
269
+ if (lower.endsWith('.md') || lower.endsWith('.txt')) {
270
+ return 'documentation';
271
+ }
272
+ // Utilities
273
+ if (lower.includes('/utils/') ||
274
+ lower.includes('/helpers/') ||
275
+ lower.includes('/lib/')) {
276
+ return 'utility';
277
+ }
278
+ // Core modules (default for src/, services/, etc.)
279
+ if (this.matchesPatterns(filePath, this.config.coreModulePatterns)) {
280
+ return 'core_module';
281
+ }
282
+ return 'other';
283
+ }
284
+ /**
285
+ * Calculate base importance for a chunk type.
286
+ */
287
+ calculateBaseImportance(type, filePath) {
288
+ const typeScores = {
289
+ entry_point: 0.95,
290
+ core_module: 0.8,
291
+ types: 0.7,
292
+ config: 0.6,
293
+ utility: 0.5,
294
+ documentation: 0.3,
295
+ test: 0.2,
296
+ other: 0.4,
297
+ };
298
+ let score = typeScores[type];
299
+ // Boost for shallow directory depth (closer to root = more important)
300
+ const depth = filePath.split('/').length;
301
+ score += Math.max(0, (5 - depth) * 0.02);
302
+ // Boost for index files
303
+ if (path.basename(filePath).startsWith('index.')) {
304
+ score += 0.1;
305
+ }
306
+ return Math.min(1, score);
307
+ }
308
+ /**
309
+ * Extract exported symbols from code.
310
+ */
311
+ extractSymbols(content, filePath) {
312
+ const symbols = [];
313
+ const ext = path.extname(filePath);
314
+ if (['.ts', '.tsx', '.js', '.jsx'].includes(ext)) {
315
+ // Match exports
316
+ const exportPatterns = [
317
+ /export\s+(?:default\s+)?(?:class|function|const|let|var|interface|type|enum)\s+(\w+)/g,
318
+ /export\s+\{\s*([^}]+)\s*\}/g,
319
+ ];
320
+ for (const pattern of exportPatterns) {
321
+ let match;
322
+ while ((match = pattern.exec(content)) !== null) {
323
+ const captured = match[1];
324
+ if (captured.includes(',')) {
325
+ // Multiple exports
326
+ symbols.push(...captured.split(',').map((s) => s.trim().split(' ')[0]));
327
+ }
328
+ else {
329
+ symbols.push(captured);
330
+ }
331
+ }
332
+ }
333
+ }
334
+ else if (ext === '.py') {
335
+ // Python: class and def at module level
336
+ const pyPatterns = [
337
+ /^class\s+(\w+)/gm,
338
+ /^def\s+(\w+)/gm,
339
+ ];
340
+ for (const pattern of pyPatterns) {
341
+ let match;
342
+ while ((match = pattern.exec(content)) !== null) {
343
+ symbols.push(match[1]);
344
+ }
345
+ }
346
+ }
347
+ return symbols;
348
+ }
349
+ /**
350
+ * Extract dependency file paths from imports.
351
+ */
352
+ extractDependencies(content, currentFile) {
353
+ const deps = new Set();
354
+ const ext = path.extname(currentFile);
355
+ const dir = path.dirname(currentFile);
356
+ if (['.ts', '.tsx', '.js', '.jsx'].includes(ext)) {
357
+ // Match import statements
358
+ const importPattern = /import\s+.*?\s+from\s+['"]([^'"]+)['"]/g;
359
+ let match;
360
+ while ((match = importPattern.exec(content)) !== null) {
361
+ const importPath = match[1];
362
+ // Only track relative imports
363
+ if (importPath.startsWith('.')) {
364
+ const resolved = path.normalize(path.join(dir, importPath));
365
+ // Add possible extensions
366
+ for (const tryExt of ['', '.ts', '.tsx', '.js', '.jsx', '/index.ts', '/index.js']) {
367
+ const tryPath = resolved + tryExt;
368
+ deps.add(tryPath);
369
+ }
370
+ }
371
+ }
372
+ }
373
+ return deps;
374
+ }
375
+ /**
376
+ * Extract dependency names (for symbol matching).
377
+ */
378
+ extractDependencyNames(content) {
379
+ const deps = [];
380
+ // Extract imported names
381
+ const patterns = [
382
+ /import\s+\{\s*([^}]+)\s*\}\s+from/g,
383
+ /import\s+(\w+)\s+from/g,
384
+ ];
385
+ for (const pattern of patterns) {
386
+ let match;
387
+ while ((match = pattern.exec(content)) !== null) {
388
+ const captured = match[1];
389
+ if (captured.includes(',')) {
390
+ deps.push(...captured.split(',').map((s) => s.trim().split(' ')[0]));
391
+ }
392
+ else {
393
+ deps.push(captured);
394
+ }
395
+ }
396
+ }
397
+ return deps;
398
+ }
399
+ /**
400
+ * Adjust importance based on how many files depend on each chunk.
401
+ */
402
+ adjustImportanceByConnectivity(chunks, reverseDeps) {
403
+ // Find max dependents for normalization
404
+ let maxDependents = 1;
405
+ for (const deps of reverseDeps.values()) {
406
+ maxDependents = Math.max(maxDependents, deps.size);
407
+ }
408
+ // Adjust importance
409
+ for (const [filePath, chunk] of chunks) {
410
+ const dependents = reverseDeps.get(filePath)?.size ?? 0;
411
+ const connectivityBoost = (dependents / maxDependents) * 0.2;
412
+ chunk.importance = Math.min(1, chunk.importance + connectivityBoost);
413
+ }
414
+ }
415
+ /**
416
+ * Check if a path matches any of the given patterns.
417
+ */
418
+ matchesPatterns(filePath, patterns) {
419
+ for (const pattern of patterns) {
420
+ if (this.matchesGlob(filePath, pattern)) {
421
+ return true;
422
+ }
423
+ }
424
+ return false;
425
+ }
426
+ /**
427
+ * Simple glob matching (supports * and **).
428
+ */
429
+ matchesGlob(filePath, pattern) {
430
+ // Convert glob to regex
431
+ const regexStr = pattern
432
+ .replace(/\*\*/g, '<<<DOUBLESTAR>>>')
433
+ .replace(/\*/g, '[^/]*')
434
+ .replace(/<<<DOUBLESTAR>>>/g, '.*')
435
+ .replace(/\?/g, '.');
436
+ const regex = new RegExp(`^${regexStr}$`);
437
+ return regex.test(filePath);
438
+ }
439
+ // ===========================================================================
440
+ // SELECTION
441
+ // ===========================================================================
442
+ /**
443
+ * Select relevant code chunks for a task within a token budget.
444
+ */
445
+ async selectRelevantCode(options) {
446
+ // Ensure we have an analyzed repo
447
+ if (!this.repoMap) {
448
+ await this.analyze();
449
+ }
450
+ const repoMap = this.repoMap;
451
+ const { maxTokens, task, priorityFiles = [], minImportance = 0, includeTypes = true, includeTests = false, strategy = 'importance_first', } = options;
452
+ // Get all candidate chunks
453
+ let candidates = Array.from(repoMap.chunks.values()).filter((chunk) => {
454
+ if (chunk.importance < minImportance)
455
+ return false;
456
+ if (!includeTypes && chunk.type === 'types')
457
+ return false;
458
+ if (!includeTests && chunk.type === 'test')
459
+ return false;
460
+ return true;
461
+ });
462
+ // Calculate relevance scores if task is provided
463
+ if (task) {
464
+ candidates = candidates.map((chunk) => ({
465
+ ...chunk,
466
+ relevance: this.calculateRelevance(chunk, task),
467
+ }));
468
+ }
469
+ // Sort based on strategy
470
+ candidates = this.sortByStrategy(candidates, strategy, task);
471
+ // Select within budget
472
+ const selected = [];
473
+ let totalTokens = 0;
474
+ const excluded = [];
475
+ // Prioritize specific files first
476
+ for (const priorityFile of priorityFiles) {
477
+ const chunk = repoMap.chunks.get(priorityFile);
478
+ if (chunk && totalTokens + chunk.tokenCount <= maxTokens) {
479
+ selected.push(chunk);
480
+ totalTokens += chunk.tokenCount;
481
+ candidates = candidates.filter((c) => c.id !== priorityFile);
482
+ }
483
+ }
484
+ // Fill remaining budget
485
+ for (const chunk of candidates) {
486
+ if (selected.some((s) => s.id === chunk.id))
487
+ continue;
488
+ if (totalTokens + chunk.tokenCount <= maxTokens) {
489
+ selected.push(chunk);
490
+ totalTokens += chunk.tokenCount;
491
+ }
492
+ else {
493
+ excluded.push(chunk.id);
494
+ }
495
+ }
496
+ const result = {
497
+ chunks: selected,
498
+ totalTokens,
499
+ budgetRemaining: maxTokens - totalTokens,
500
+ excluded,
501
+ stats: {
502
+ filesConsidered: repoMap.chunks.size,
503
+ filesSelected: selected.length,
504
+ coveragePercent: (selected.length / repoMap.chunks.size) * 100,
505
+ averageImportance: selected.reduce((sum, c) => sum + c.importance, 0) / selected.length || 0,
506
+ },
507
+ };
508
+ this.emit({
509
+ type: 'selection.completed',
510
+ selected: selected.length,
511
+ budget: maxTokens,
512
+ });
513
+ return result;
514
+ }
515
+ /**
516
+ * Calculate task relevance for a chunk.
517
+ */
518
+ calculateRelevance(chunk, task) {
519
+ const taskLower = task.toLowerCase();
520
+ const taskWords = taskLower.split(/\s+/).filter((w) => w.length > 2);
521
+ let score = 0;
522
+ // Check file path
523
+ const pathLower = chunk.filePath.toLowerCase();
524
+ for (const word of taskWords) {
525
+ if (pathLower.includes(word)) {
526
+ score += 0.3;
527
+ }
528
+ }
529
+ // Check symbols
530
+ for (const symbol of chunk.symbols) {
531
+ const symbolLower = symbol.toLowerCase();
532
+ for (const word of taskWords) {
533
+ if (symbolLower.includes(word) || word.includes(symbolLower)) {
534
+ score += 0.2;
535
+ }
536
+ }
537
+ }
538
+ // Check content (limited to avoid expensive full-text search)
539
+ const contentSample = chunk.content.slice(0, 2000).toLowerCase();
540
+ for (const word of taskWords) {
541
+ if (contentSample.includes(word)) {
542
+ score += 0.1;
543
+ }
544
+ }
545
+ return Math.min(1, score);
546
+ }
547
+ /**
548
+ * Sort candidates by selection strategy.
549
+ */
550
+ sortByStrategy(candidates, strategy, task) {
551
+ switch (strategy) {
552
+ case 'importance_first':
553
+ return candidates.sort((a, b) => b.importance - a.importance);
554
+ case 'relevance_first':
555
+ if (!task)
556
+ return this.sortByStrategy(candidates, 'importance_first');
557
+ return candidates.sort((a, b) => {
558
+ const relDiff = (b.relevance ?? 0) - (a.relevance ?? 0);
559
+ if (Math.abs(relDiff) > 0.1)
560
+ return relDiff;
561
+ return b.importance - a.importance;
562
+ });
563
+ case 'breadth_first':
564
+ // Group by directory, pick one from each, then repeat
565
+ const byDir = new Map();
566
+ for (const chunk of candidates) {
567
+ const dir = path.dirname(chunk.filePath);
568
+ if (!byDir.has(dir))
569
+ byDir.set(dir, []);
570
+ byDir.get(dir).push(chunk);
571
+ }
572
+ // Sort each directory's files by importance
573
+ for (const files of byDir.values()) {
574
+ files.sort((a, b) => b.importance - a.importance);
575
+ }
576
+ // Interleave
577
+ const result = [];
578
+ let hasMore = true;
579
+ let index = 0;
580
+ while (hasMore) {
581
+ hasMore = false;
582
+ for (const files of byDir.values()) {
583
+ if (index < files.length) {
584
+ result.push(files[index]);
585
+ hasMore = true;
586
+ }
587
+ }
588
+ index++;
589
+ }
590
+ return result;
591
+ case 'depth_first':
592
+ // Start with entry points, then follow dependencies
593
+ return candidates.sort((a, b) => {
594
+ // Entry points first
595
+ if (a.type === 'entry_point' && b.type !== 'entry_point')
596
+ return -1;
597
+ if (b.type === 'entry_point' && a.type !== 'entry_point')
598
+ return 1;
599
+ // Then by importance
600
+ return b.importance - a.importance;
601
+ });
602
+ default:
603
+ return candidates;
604
+ }
605
+ }
606
+ // ===========================================================================
607
+ // INCREMENTAL EXPANSION
608
+ // ===========================================================================
609
+ /**
610
+ * Expand context by adding related files to current selection.
611
+ */
612
+ async expandContext(currentChunks, options) {
613
+ if (!this.repoMap) {
614
+ await this.analyze();
615
+ }
616
+ const repoMap = this.repoMap;
617
+ const currentIds = new Set(currentChunks.map((c) => c.id));
618
+ const candidates = [];
619
+ for (const chunk of currentChunks) {
620
+ // Get dependencies
621
+ if (options.direction === 'dependencies' || options.direction === 'both') {
622
+ const deps = repoMap.dependencyGraph.get(chunk.filePath);
623
+ if (deps) {
624
+ for (const dep of deps) {
625
+ if (!currentIds.has(dep)) {
626
+ const depChunk = repoMap.chunks.get(dep);
627
+ if (depChunk) {
628
+ candidates.push(depChunk);
629
+ currentIds.add(dep);
630
+ }
631
+ }
632
+ }
633
+ }
634
+ }
635
+ // Get dependents
636
+ if (options.direction === 'dependents' || options.direction === 'both') {
637
+ const dependents = repoMap.reverseDependencyGraph.get(chunk.filePath);
638
+ if (dependents) {
639
+ for (const dep of dependents) {
640
+ if (!currentIds.has(dep)) {
641
+ const depChunk = repoMap.chunks.get(dep);
642
+ if (depChunk) {
643
+ candidates.push(depChunk);
644
+ currentIds.add(dep);
645
+ }
646
+ }
647
+ }
648
+ }
649
+ }
650
+ }
651
+ // Filter by query if provided
652
+ let filtered = candidates;
653
+ if (options.query) {
654
+ filtered = candidates.filter((c) => this.calculateRelevance(c, options.query) > 0);
655
+ }
656
+ // Sort by importance and select within budget
657
+ filtered.sort((a, b) => b.importance - a.importance);
658
+ const toAdd = [];
659
+ let addedTokens = 0;
660
+ for (const chunk of filtered) {
661
+ if (addedTokens + chunk.tokenCount <= options.maxTokensToAdd) {
662
+ toAdd.push(chunk);
663
+ addedTokens += chunk.tokenCount;
664
+ }
665
+ }
666
+ return toAdd;
667
+ }
668
+ // ===========================================================================
669
+ // UTILITIES
670
+ // ===========================================================================
671
+ /**
672
+ * Get a chunk by file path.
673
+ */
674
+ getChunk(filePath) {
675
+ return this.repoMap?.chunks.get(filePath);
676
+ }
677
+ /**
678
+ * Get all chunks.
679
+ */
680
+ getAllChunks() {
681
+ return this.repoMap ? Array.from(this.repoMap.chunks.values()) : [];
682
+ }
683
+ /**
684
+ * Get entry points.
685
+ */
686
+ getEntryPoints() {
687
+ if (!this.repoMap)
688
+ return [];
689
+ return this.repoMap.entryPoints
690
+ .map((ep) => this.repoMap.chunks.get(ep))
691
+ .filter((c) => c !== undefined);
692
+ }
693
+ /**
694
+ * Estimate tokens for a string.
695
+ */
696
+ estimateTokens(content) {
697
+ return Math.ceil(content.length * this.config.tokensPerChar);
698
+ }
699
+ /**
700
+ * Get the current repo map.
701
+ */
702
+ getRepoMap() {
703
+ return this.repoMap;
704
+ }
705
+ /**
706
+ * Clear cached data.
707
+ */
708
+ clearCache() {
709
+ this.cache.clear();
710
+ this.repoMap = null;
711
+ }
712
+ /**
713
+ * Subscribe to events.
714
+ */
715
+ on(listener) {
716
+ this.listeners.push(listener);
717
+ return () => {
718
+ const idx = this.listeners.indexOf(listener);
719
+ if (idx >= 0)
720
+ this.listeners.splice(idx, 1);
721
+ };
722
+ }
723
+ emit(event) {
724
+ for (const listener of this.listeners) {
725
+ try {
726
+ listener(event);
727
+ }
728
+ catch {
729
+ // Ignore listener errors
730
+ }
731
+ }
732
+ }
733
+ }
734
+ // =============================================================================
735
+ // FACTORY FUNCTIONS
736
+ // =============================================================================
737
+ /**
738
+ * Create a codebase context manager.
739
+ *
740
+ * @example
741
+ * ```typescript
742
+ * const codebase = createCodebaseContext({
743
+ * root: './my-project',
744
+ * includePatterns: ['src/**\/*.ts'],
745
+ * excludePatterns: ['node_modules/**'],
746
+ * });
747
+ *
748
+ * // Analyze repo
749
+ * await codebase.analyze();
750
+ *
751
+ * // Select code for task
752
+ * const selection = await codebase.selectRelevantCode({
753
+ * task: 'fix authentication bug',
754
+ * maxTokens: 10000,
755
+ * strategy: 'relevance_first',
756
+ * });
757
+ *
758
+ * console.log(`Selected ${selection.chunks.length} files`);
759
+ * console.log(`Using ${selection.totalTokens} tokens`);
760
+ * ```
761
+ */
762
+ export function createCodebaseContext(config = {}) {
763
+ return new CodebaseContextManager(config);
764
+ }
765
+ /**
766
+ * Build context string from selected chunks.
767
+ */
768
+ export function buildContextFromChunks(chunks, options = {}) {
769
+ const { includeFilePaths = true, includeSeparators = true, maxTotalTokens, } = options;
770
+ const parts = [];
771
+ let totalTokens = 0;
772
+ for (const chunk of chunks) {
773
+ if (maxTotalTokens && totalTokens + chunk.tokenCount > maxTotalTokens) {
774
+ break;
775
+ }
776
+ if (includeSeparators && parts.length > 0) {
777
+ parts.push('\n---\n');
778
+ }
779
+ if (includeFilePaths) {
780
+ parts.push(`// File: ${chunk.filePath}\n`);
781
+ }
782
+ parts.push(chunk.content);
783
+ totalTokens += chunk.tokenCount;
784
+ }
785
+ return parts.join('');
786
+ }
787
+ /**
788
+ * Create a summary of the repo structure.
789
+ */
790
+ export function summarizeRepoStructure(repoMap) {
791
+ const lines = [
792
+ `Repository: ${repoMap.root}`,
793
+ `Total files: ${repoMap.chunks.size}`,
794
+ `Total tokens: ${repoMap.totalTokens.toLocaleString()}`,
795
+ ``,
796
+ `Entry points:`,
797
+ ];
798
+ for (const ep of repoMap.entryPoints.slice(0, 5)) {
799
+ lines.push(` - ${ep}`);
800
+ }
801
+ lines.push(``, `Core modules:`);
802
+ for (const mod of repoMap.coreModules.slice(0, 5)) {
803
+ lines.push(` - ${mod}`);
804
+ }
805
+ // Type breakdown
806
+ const byType = new Map();
807
+ for (const chunk of repoMap.chunks.values()) {
808
+ byType.set(chunk.type, (byType.get(chunk.type) ?? 0) + 1);
809
+ }
810
+ lines.push(``, `File types:`);
811
+ for (const [type, count] of byType) {
812
+ lines.push(` - ${type}: ${count}`);
813
+ }
814
+ return lines.join('\n');
815
+ }
816
+ //# sourceMappingURL=codebase-context.js.map