@theokit/sdk 1.5.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 (369) hide show
  1. package/CHANGELOG.md +1571 -0
  2. package/LICENSE +201 -0
  3. package/README.md +80 -0
  4. package/bin/theokit-migrate-config.mjs +269 -0
  5. package/bin/theokit-migrate-memory.mjs +116 -0
  6. package/dist/agent-builder.d.ts +52 -0
  7. package/dist/agent-factory.d.ts +39 -0
  8. package/dist/agent.d.ts +175 -0
  9. package/dist/batch.d.ts +11 -0
  10. package/dist/budget.d.ts +48 -0
  11. package/dist/cache.d.ts +74 -0
  12. package/dist/cron-1yxL3K2S.d.cts +221 -0
  13. package/dist/cron-BYVdYzob.d.ts +221 -0
  14. package/dist/cron.cjs +14655 -0
  15. package/dist/cron.cjs.map +1 -0
  16. package/dist/cron.d.cts +3 -0
  17. package/dist/cron.d.ts +71 -0
  18. package/dist/cron.js +14652 -0
  19. package/dist/cron.js.map +1 -0
  20. package/dist/define-tool.d.ts +35 -0
  21. package/dist/errors-CK8brCJ1.d.cts +448 -0
  22. package/dist/errors-CvAeEWgE.d.ts +448 -0
  23. package/dist/errors.cjs +255 -0
  24. package/dist/errors.cjs.map +1 -0
  25. package/dist/errors.d.cts +3 -0
  26. package/dist/errors.d.ts +356 -0
  27. package/dist/errors.js +238 -0
  28. package/dist/errors.js.map +1 -0
  29. package/dist/eval.cjs +14826 -0
  30. package/dist/eval.cjs.map +1 -0
  31. package/dist/eval.d.cts +35 -0
  32. package/dist/eval.d.ts +35 -0
  33. package/dist/eval.js +14821 -0
  34. package/dist/eval.js.map +1 -0
  35. package/dist/generate-object.d.ts +67 -0
  36. package/dist/handoff.d.ts +55 -0
  37. package/dist/index.cjs +17127 -0
  38. package/dist/index.cjs.map +1 -0
  39. package/dist/index.d.cts +1878 -0
  40. package/dist/index.d.ts +24 -0
  41. package/dist/index.js +17095 -0
  42. package/dist/index.js.map +1 -0
  43. package/dist/internal/agent-loop/loop-types.d.ts +29 -0
  44. package/dist/internal/agent-loop/loop.d.ts +2 -0
  45. package/dist/internal/agent-loop/message-builders.d.ts +6 -0
  46. package/dist/internal/agent-loop/tool-dispatch.d.ts +4 -0
  47. package/dist/internal/agent-loop/usage-and-cost.d.ts +25 -0
  48. package/dist/internal/budget/calendar-window.d.ts +19 -0
  49. package/dist/internal/budget/compute-cost.d.ts +28 -0
  50. package/dist/internal/budget/enforcement.d.ts +32 -0
  51. package/dist/internal/budget/ledger.d.ts +25 -0
  52. package/dist/internal/budget/normalize-usage.d.ts +27 -0
  53. package/dist/internal/budget/pricing-registry.d.ts +36 -0
  54. package/dist/internal/budget/registry.d.ts +16 -0
  55. package/dist/internal/budget/usage-accumulator.d.ts +31 -0
  56. package/dist/internal/cache/cosine.d.ts +14 -0
  57. package/dist/internal/cache/embed-helper.d.ts +15 -0
  58. package/dist/internal/cache/key.d.ts +15 -0
  59. package/dist/internal/cache/lookup.d.ts +28 -0
  60. package/dist/internal/cache/store-handler.d.ts +24 -0
  61. package/dist/internal/cache/store-json.d.ts +48 -0
  62. package/dist/internal/cache/store.d.ts +54 -0
  63. package/dist/internal/cache/telemetry.d.ts +20 -0
  64. package/dist/internal/cache/ttl.d.ts +11 -0
  65. package/dist/internal/catalog/fixtures.d.ts +16 -0
  66. package/dist/internal/catalog/local-models.d.ts +24 -0
  67. package/dist/internal/cron/run-job.d.ts +1 -0
  68. package/dist/internal/cron/scheduler.d.ts +1 -0
  69. package/dist/internal/cron/store.d.ts +1 -0
  70. package/dist/internal/cron/validate.d.ts +1 -0
  71. package/dist/internal/env.d.ts +1 -0
  72. package/dist/internal/errors/mappers/anthropic.d.ts +30 -0
  73. package/dist/internal/errors/mappers/bedrock.d.ts +16 -0
  74. package/dist/internal/errors/mappers/ollama.d.ts +41 -0
  75. package/dist/internal/errors/mappers/openai-compatible.d.ts +25 -0
  76. package/dist/internal/errors/mappers/shared.d.ts +10 -0
  77. package/dist/internal/errors/mappers/vertex.d.ts +15 -0
  78. package/dist/internal/eval/aggregate.d.ts +9 -0
  79. package/dist/internal/eval/dataset-iter.d.ts +9 -0
  80. package/dist/internal/eval/runner.d.ts +9 -0
  81. package/dist/internal/eval/single-flight.d.ts +16 -0
  82. package/dist/internal/eval/telemetry.d.ts +23 -0
  83. package/dist/internal/fixture-mode.d.ts +16 -0
  84. package/dist/internal/handoff/dispatcher.d.ts +29 -0
  85. package/dist/internal/handoff/registry.d.ts +23 -0
  86. package/dist/internal/handoff/telemetry.d.ts +18 -0
  87. package/dist/internal/handoff/tool-injector.d.ts +34 -0
  88. package/dist/internal/http.d.ts +1 -0
  89. package/dist/internal/ids.d.ts +1 -0
  90. package/dist/internal/judge/judge-call.d.ts +35 -0
  91. package/dist/internal/judge/parse-verdict.d.ts +11 -0
  92. package/dist/internal/judge/types.d.ts +17 -0
  93. package/dist/internal/llm/anthropic-shared.d.ts +89 -0
  94. package/dist/internal/llm/anthropic.d.ts +9 -0
  95. package/dist/internal/llm/bedrock-anthropic.d.ts +36 -0
  96. package/dist/internal/llm/bedrock-token-cache.d.ts +18 -0
  97. package/dist/internal/llm/credential-pool-context.d.ts +11 -0
  98. package/dist/internal/llm/credential-pool-types.d.ts +22 -0
  99. package/dist/internal/llm/credential-pool.d.ts +18 -0
  100. package/dist/internal/llm/fallback-client.d.ts +1 -0
  101. package/dist/internal/llm/fault-injection.d.ts +50 -0
  102. package/dist/internal/llm/finish.d.ts +1 -0
  103. package/dist/internal/llm/model-identifier.d.ts +24 -0
  104. package/dist/internal/llm/ollama-native.d.ts +27 -0
  105. package/dist/internal/llm/openai.d.ts +9 -0
  106. package/dist/internal/llm/pool-aware-client.d.ts +16 -0
  107. package/dist/internal/llm/router.d.ts +17 -0
  108. package/dist/internal/llm/sse.d.ts +9 -0
  109. package/dist/internal/llm/stream-relay.d.ts +17 -0
  110. package/dist/internal/llm/types.d.ts +70 -0
  111. package/dist/internal/llm/vertex-anthropic.d.ts +40 -0
  112. package/dist/internal/llm/vertex-auth.d.ts +30 -0
  113. package/dist/internal/llm/vertex-gemini.d.ts +28 -0
  114. package/dist/internal/llm/vertex-router.d.ts +21 -0
  115. package/dist/internal/mcp/client.d.ts +16 -0
  116. package/dist/internal/memory/active-memory-cache.d.ts +10 -0
  117. package/dist/internal/memory/active-memory.d.ts +45 -0
  118. package/dist/internal/memory/adapters/catalog.d.ts +1 -0
  119. package/dist/internal/memory/adapters/deepinfra-embedding.d.ts +2 -0
  120. package/dist/internal/memory/adapters/mistral-embedding.d.ts +2 -0
  121. package/dist/internal/memory/adapters/ollama-embedding.d.ts +34 -0
  122. package/dist/internal/memory/adapters/openai-compatible.d.ts +23 -0
  123. package/dist/internal/memory/adapters/openai-embedding.d.ts +2 -0
  124. package/dist/internal/memory/adapters/openrouter-embedding.d.ts +2 -0
  125. package/dist/internal/memory/adapters/voyage-embedding.d.ts +2 -0
  126. package/dist/internal/memory/atomic-write.d.ts +7 -0
  127. package/dist/internal/memory/chunk-markdown.d.ts +2 -0
  128. package/dist/internal/memory/circuit-breaker.d.ts +22 -0
  129. package/dist/internal/memory/cwd-mutex.d.ts +1 -0
  130. package/dist/internal/memory/dreaming/diary.d.ts +4 -0
  131. package/dist/internal/memory/dreaming/phases.d.ts +15 -0
  132. package/dist/internal/memory/dreaming/run.d.ts +10 -0
  133. package/dist/internal/memory/embedding-adapter.d.ts +42 -0
  134. package/dist/internal/memory/embedding-cache.d.ts +1 -0
  135. package/dist/internal/memory/index-db.d.ts +10 -0
  136. package/dist/internal/memory/index-manager-dispatch.d.ts +23 -0
  137. package/dist/internal/memory/index-manager.d.ts +68 -0
  138. package/dist/internal/memory/index-schema.d.ts +21 -0
  139. package/dist/internal/memory/lance-index.d.ts +32 -0
  140. package/dist/internal/memory/lance-memory-adapter.d.ts +43 -0
  141. package/dist/internal/memory/markdown-store.d.ts +16 -0
  142. package/dist/internal/memory/memory-index.d.ts +52 -0
  143. package/dist/internal/memory/migrate-sqlite-to-lance.d.ts +15 -0
  144. package/dist/internal/memory/migration.d.ts +9 -0
  145. package/dist/internal/memory/reader.d.ts +8 -0
  146. package/dist/internal/memory/session-loader.d.ts +1 -0
  147. package/dist/internal/memory/session-summary-writer.d.ts +2 -0
  148. package/dist/internal/memory/sqlite-vec-loader.d.ts +3 -0
  149. package/dist/internal/memory/tools.d.ts +14 -0
  150. package/dist/internal/memory/transcript-store.d.ts +1 -0
  151. package/dist/internal/memory/types.d.ts +17 -0
  152. package/dist/internal/memory/vec-index.d.ts +28 -0
  153. package/dist/internal/memory/wiki-loader.d.ts +2 -0
  154. package/dist/internal/observability/tracer-loader.d.ts +20 -0
  155. package/dist/internal/persistence/atomic-write.d.ts +1 -0
  156. package/dist/internal/persistence/conversation-storage-fs.d.ts +37 -0
  157. package/dist/internal/persistence/conversation-storage-memory.d.ts +24 -0
  158. package/dist/internal/persistence/cwd-mutex.d.ts +1 -0
  159. package/dist/internal/persistence/file-lock.d.ts +14 -0
  160. package/dist/internal/persistence/fts5-sanitize.d.ts +16 -0
  161. package/dist/internal/persistence/markdown-config-loader.d.ts +35 -0
  162. package/dist/internal/persistence/paths.d.ts +19 -0
  163. package/dist/internal/persistence/persistence-schema.d.ts +17 -0
  164. package/dist/internal/persistence/schema-version.d.ts +13 -0
  165. package/dist/internal/persistence/sqlite-wal.d.ts +10 -0
  166. package/dist/internal/personality/context.d.ts +17 -0
  167. package/dist/internal/personality/registry.d.ts +17 -0
  168. package/dist/internal/personality/store.d.ts +27 -0
  169. package/dist/internal/personality/switch.d.ts +36 -0
  170. package/dist/internal/personality/types.d.ts +18 -0
  171. package/dist/internal/plugins/context.d.ts +31 -0
  172. package/dist/internal/plugins/manager.d.ts +37 -0
  173. package/dist/internal/plugins/types.d.ts +102 -0
  174. package/dist/internal/providers/builtin/anthropic.d.ts +2 -0
  175. package/dist/internal/providers/builtin/bedrock.d.ts +25 -0
  176. package/dist/internal/providers/builtin/gemini.d.ts +10 -0
  177. package/dist/internal/providers/builtin/index.d.ts +19 -0
  178. package/dist/internal/providers/builtin/llamacpp.d.ts +1 -0
  179. package/dist/internal/providers/builtin/lmstudio.d.ts +1 -0
  180. package/dist/internal/providers/builtin/ollama.d.ts +17 -0
  181. package/dist/internal/providers/builtin/openai.d.ts +2 -0
  182. package/dist/internal/providers/builtin/openrouter.d.ts +2 -0
  183. package/dist/internal/providers/builtin/vertex.d.ts +27 -0
  184. package/dist/internal/providers/discovery.d.ts +14 -0
  185. package/dist/internal/providers/index.d.ts +8 -0
  186. package/dist/internal/providers/registry.d.ts +12 -0
  187. package/dist/internal/providers/types.d.ts +27 -0
  188. package/dist/internal/runtime/abort-utils.d.ts +21 -0
  189. package/dist/internal/runtime/agent-factory-registry.d.ts +16 -0
  190. package/dist/internal/runtime/agent-registry-store.d.ts +61 -0
  191. package/dist/internal/runtime/agent-registry.d.ts +34 -0
  192. package/dist/internal/runtime/agent-session-store.d.ts +3 -0
  193. package/dist/internal/runtime/agent-session.d.ts +2 -0
  194. package/dist/internal/runtime/async-local-storage.d.ts +20 -0
  195. package/dist/internal/runtime/async-semaphore.d.ts +24 -0
  196. package/dist/internal/runtime/budget.d.ts +36 -0
  197. package/dist/internal/runtime/cloud-agent.d.ts +1 -0
  198. package/dist/internal/runtime/cloud-config-serializer.d.ts +3 -0
  199. package/dist/internal/runtime/cloud-payload-types.d.ts +56 -0
  200. package/dist/internal/runtime/cloud-run.d.ts +1 -0
  201. package/dist/internal/runtime/cloud-tool-parity.d.ts +1 -0
  202. package/dist/internal/runtime/context-aggregator.d.ts +26 -0
  203. package/dist/internal/runtime/context-discovery-runner.d.ts +27 -0
  204. package/dist/internal/runtime/context-discovery.d.ts +21 -0
  205. package/dist/internal/runtime/context-frontmatter.d.ts +16 -0
  206. package/dist/internal/runtime/context-import-resolver.d.ts +24 -0
  207. package/dist/internal/runtime/context-loaders.d.ts +42 -0
  208. package/dist/internal/runtime/context-manager.d.ts +11 -0
  209. package/dist/internal/runtime/context-mdc-parser.d.ts +24 -0
  210. package/dist/internal/runtime/default-model.d.ts +1 -0
  211. package/dist/internal/runtime/fixture-events.d.ts +12 -0
  212. package/dist/internal/runtime/fixture-responder.d.ts +1 -0
  213. package/dist/internal/runtime/fixture-run-base.d.ts +45 -0
  214. package/dist/internal/runtime/fixture-scripts.d.ts +21 -0
  215. package/dist/internal/runtime/fixture-types.d.ts +1 -0
  216. package/dist/internal/runtime/fork-agent.d.ts +15 -0
  217. package/dist/internal/runtime/hooks-executor.d.ts +35 -0
  218. package/dist/internal/runtime/hooks-frontmatter.d.ts +26 -0
  219. package/dist/internal/runtime/hooks-source.d.ts +22 -0
  220. package/dist/internal/runtime/live-agent-registry.d.ts +87 -0
  221. package/dist/internal/runtime/local-agent-bootstrap.d.ts +37 -0
  222. package/dist/internal/runtime/local-agent-dispatch.d.ts +57 -0
  223. package/dist/internal/runtime/local-agent-invalidate.d.ts +8 -0
  224. package/dist/internal/runtime/local-agent-memory-direct.d.ts +12 -0
  225. package/dist/internal/runtime/local-agent-memory-hooks.d.ts +41 -0
  226. package/dist/internal/runtime/local-agent-memory.d.ts +1 -0
  227. package/dist/internal/runtime/local-agent-personality-extensions.d.ts +19 -0
  228. package/dist/internal/runtime/local-agent-plugins.d.ts +13 -0
  229. package/dist/internal/runtime/local-agent-runtime-extensions.d.ts +13 -0
  230. package/dist/internal/runtime/local-agent-task-wrap.d.ts +11 -0
  231. package/dist/internal/runtime/local-agent.d.ts +1 -0
  232. package/dist/internal/runtime/local-run.d.ts +1 -0
  233. package/dist/internal/runtime/memory-store.d.ts +4 -0
  234. package/dist/internal/runtime/plugin-frontmatter.d.ts +17 -0
  235. package/dist/internal/runtime/plugins-manager.d.ts +1 -0
  236. package/dist/internal/runtime/post-run-lifecycle.d.ts +1 -0
  237. package/dist/internal/runtime/providers-manager.d.ts +1 -0
  238. package/dist/internal/runtime/real-cloud-run.d.ts +2 -0
  239. package/dist/internal/runtime/real-local-run.d.ts +2 -0
  240. package/dist/internal/runtime/run-registry.d.ts +5 -0
  241. package/dist/internal/runtime/run-until.d.ts +22 -0
  242. package/dist/internal/runtime/shell-tool.d.ts +7 -0
  243. package/dist/internal/runtime/skill-frontmatter.d.ts +1 -0
  244. package/dist/internal/runtime/skills-manager.d.ts +1 -0
  245. package/dist/internal/runtime/spawn-collect.d.ts +8 -0
  246. package/dist/internal/runtime/subagents-loader.d.ts +1 -0
  247. package/dist/internal/runtime/system-prompt/escape.d.ts +1 -0
  248. package/dist/internal/runtime/system-prompt/local-assembly.d.ts +1 -0
  249. package/dist/internal/runtime/system-prompt/pipeline.d.ts +1 -0
  250. package/dist/internal/runtime/system-prompt/providers/active-memory-provider.d.ts +1 -0
  251. package/dist/internal/runtime/system-prompt/providers/base-provider.d.ts +1 -0
  252. package/dist/internal/runtime/system-prompt/providers/context-provider.d.ts +1 -0
  253. package/dist/internal/runtime/system-prompt/providers/memory-provider.d.ts +1 -0
  254. package/dist/internal/runtime/system-prompt/providers/skills-provider.d.ts +1 -0
  255. package/dist/internal/runtime/system-prompt/safe-call.d.ts +1 -0
  256. package/dist/internal/runtime/system-prompt/types.d.ts +5 -0
  257. package/dist/internal/runtime/system-prompt.d.ts +1 -0
  258. package/dist/internal/runtime/validate-agent-options.d.ts +1 -0
  259. package/dist/internal/runtime/workspace-dir.d.ts +9 -0
  260. package/dist/internal/runtime/yaml-frontmatter.d.ts +20 -0
  261. package/dist/internal/scorers/llm-judge.d.ts +24 -0
  262. package/dist/internal/security/index.d.ts +11 -0
  263. package/dist/internal/security/path-guard.d.ts +56 -0
  264. package/dist/internal/security/redact.d.ts +21 -0
  265. package/dist/internal/structured-output-helpers.d.ts +54 -0
  266. package/dist/internal/task/registry.d.ts +61 -0
  267. package/dist/internal/task/ring-buffer.d.ts +10 -0
  268. package/dist/internal/task/store.d.ts +59 -0
  269. package/dist/internal/task/subscribe.d.ts +15 -0
  270. package/dist/internal/task/telemetry.d.ts +27 -0
  271. package/dist/internal/telemetry/adapter-registry.d.ts +2 -0
  272. package/dist/internal/telemetry/adapters/langfuse.d.ts +2 -0
  273. package/dist/internal/telemetry/adapters/posthog.d.ts +2 -0
  274. package/dist/internal/telemetry/adapters/sentry.d.ts +2 -0
  275. package/dist/internal/telemetry/safe-require.d.ts +1 -0
  276. package/dist/internal/telemetry/tracer.d.ts +18 -0
  277. package/dist/internal/tool-dispatch/repair-middleware.d.ts +34 -0
  278. package/dist/internal/tool-dispatch/strip-think.d.ts +22 -0
  279. package/dist/internal/tool-registry/personality-filter.d.ts +37 -0
  280. package/dist/internal/workflow/ctx.d.ts +19 -0
  281. package/dist/internal/workflow/error-shape.d.ts +7 -0
  282. package/dist/internal/workflow/executor.d.ts +15 -0
  283. package/dist/internal/workflow/index.d.ts +12 -0
  284. package/dist/internal/workflow/retry-policy.d.ts +14 -0
  285. package/dist/internal/workflow/run-id.d.ts +9 -0
  286. package/dist/internal/workflow/single-flight.d.ts +18 -0
  287. package/dist/internal/workflow/snapshot-store.d.ts +23 -0
  288. package/dist/internal/workflow/step-agent.d.ts +12 -0
  289. package/dist/internal/workflow/step-branch.d.ts +10 -0
  290. package/dist/internal/workflow/step-dowhile.d.ts +8 -0
  291. package/dist/internal/workflow/step-fn.d.ts +10 -0
  292. package/dist/internal/workflow/step-foreach.d.ts +11 -0
  293. package/dist/internal/workflow/step-parallel.d.ts +17 -0
  294. package/dist/internal/workflow/step-sleep.d.ts +7 -0
  295. package/dist/internal/workflow/telemetry.d.ts +23 -0
  296. package/dist/internal/zod/to-json-schema.d.ts +21 -0
  297. package/dist/memory-adapter-helpers.d.ts +28 -0
  298. package/dist/memory.d.ts +123 -0
  299. package/dist/migrate.d.ts +33 -0
  300. package/dist/path-safety.cjs +126 -0
  301. package/dist/path-safety.cjs.map +1 -0
  302. package/dist/path-safety.d.cts +15 -0
  303. package/dist/path-safety.d.ts +15 -0
  304. package/dist/path-safety.js +120 -0
  305. package/dist/path-safety.js.map +1 -0
  306. package/dist/run-DkCD5DeO.d.cts +2181 -0
  307. package/dist/run-DkCD5DeO.d.ts +2181 -0
  308. package/dist/scorers.d.ts +75 -0
  309. package/dist/security.d.ts +67 -0
  310. package/dist/stream-object.d.ts +74 -0
  311. package/dist/task-store.cjs +237 -0
  312. package/dist/task-store.cjs.map +1 -0
  313. package/dist/task-store.d.cts +8 -0
  314. package/dist/task-store.d.ts +8 -0
  315. package/dist/task-store.js +233 -0
  316. package/dist/task-store.js.map +1 -0
  317. package/dist/task.d.ts +87 -0
  318. package/dist/theokit.d.ts +84 -0
  319. package/dist/tools/_path-scope.d.cts +8 -0
  320. package/dist/tools/_path-scope.d.ts +8 -0
  321. package/dist/tools/_subprocess.d.cts +28 -0
  322. package/dist/tools/_subprocess.d.ts +28 -0
  323. package/dist/tools/git-diff.d.cts +22 -0
  324. package/dist/tools/git-diff.d.ts +22 -0
  325. package/dist/tools/index.d.cts +29 -0
  326. package/dist/tools/index.d.ts +29 -0
  327. package/dist/tools/list-dir.d.cts +26 -0
  328. package/dist/tools/list-dir.d.ts +26 -0
  329. package/dist/tools/read-file.d.cts +31 -0
  330. package/dist/tools/read-file.d.ts +31 -0
  331. package/dist/tools/run-vitest.d.cts +46 -0
  332. package/dist/tools/run-vitest.d.ts +46 -0
  333. package/dist/tools/search-text.d.cts +32 -0
  334. package/dist/tools/search-text.d.ts +32 -0
  335. package/dist/tools.cjs +690 -0
  336. package/dist/tools.cjs.map +1 -0
  337. package/dist/tools.js +683 -0
  338. package/dist/tools.js.map +1 -0
  339. package/dist/trajectory-helpers.d.ts +31 -0
  340. package/dist/types/agent.d.ts +771 -0
  341. package/dist/types/batch.d.ts +112 -0
  342. package/dist/types/budget.d.ts +88 -0
  343. package/dist/types/cache.d.ts +76 -0
  344. package/dist/types/context.d.ts +93 -0
  345. package/dist/types/conversation-storage.d.ts +76 -0
  346. package/dist/types/conversation.d.ts +90 -0
  347. package/dist/types/cron.d.ts +150 -0
  348. package/dist/types/eval.d.ts +132 -0
  349. package/dist/types/goal-events.d.ts +95 -0
  350. package/dist/types/handoff.d.ts +135 -0
  351. package/dist/types/index.d.ts +20 -0
  352. package/dist/types/mcp.d.ts +64 -0
  353. package/dist/types/memory-adapter.d.ts +175 -0
  354. package/dist/types/messages.d.ts +154 -0
  355. package/dist/types/providers.d.ts +102 -0
  356. package/dist/types/run.d.ts +215 -0
  357. package/dist/types/task.d.ts +131 -0
  358. package/dist/types/theokit.d.ts +61 -0
  359. package/dist/types/trajectory.d.ts +49 -0
  360. package/dist/types/updates.d.ts +148 -0
  361. package/dist/types/usage.d.ts +61 -0
  362. package/dist/types/workflow.d.ts +217 -0
  363. package/dist/workflow.cjs +2405 -0
  364. package/dist/workflow.cjs.map +1 -0
  365. package/dist/workflow.d.cts +97 -0
  366. package/dist/workflow.d.ts +97 -0
  367. package/dist/workflow.js +2398 -0
  368. package/dist/workflow.js.map +1 -0
  369. package/package.json +183 -0
package/dist/tools.js ADDED
@@ -0,0 +1,683 @@
1
+ import { spawn } from 'child_process';
2
+ import { existsSync, realpathSync, lstatSync, readlinkSync } from 'fs';
3
+ import { join, resolve, sep, relative, dirname } from 'path';
4
+ import { z } from 'zod';
5
+ import { createRequire } from 'module';
6
+ import { readdir, open, readFile } from 'fs/promises';
7
+
8
+ // src/tools/git-diff.ts
9
+ var requireSdk = createRequire(import.meta.url);
10
+ var cachedZodHasNativeApi;
11
+ var cachedFallbackLib;
12
+ var triedFallback = false;
13
+ function toJsonSchema(schema, options = { unrepresentable: "any" }) {
14
+ const native = tryNativeZod4(schema, options);
15
+ if (native !== void 0) return native;
16
+ const fallback = tryFallbackLib(schema);
17
+ if (fallback !== void 0) return fallback;
18
+ throw new Error(
19
+ 'Zod \u2192 JSON Schema conversion failed: neither Zod 4\'s native `z.toJSONSchema` nor the `zod-to-json-schema` peer dep are available. On Zod 4: ensure `zod >= 4.0.0` is installed. On Zod 3: add `"zod-to-json-schema": "^3.24.0"` to your package.json.'
20
+ );
21
+ }
22
+ function tryNativeZod4(schema, options) {
23
+ if (cachedZodHasNativeApi === false) return void 0;
24
+ let z6;
25
+ try {
26
+ z6 = requireSdk("zod");
27
+ } catch {
28
+ cachedZodHasNativeApi = false;
29
+ return void 0;
30
+ }
31
+ if (typeof z6.toJSONSchema !== "function") {
32
+ cachedZodHasNativeApi = false;
33
+ return void 0;
34
+ }
35
+ try {
36
+ return z6.toJSONSchema(schema, options);
37
+ } catch {
38
+ cachedZodHasNativeApi = false;
39
+ return void 0;
40
+ }
41
+ }
42
+ function tryFallbackLib(schema) {
43
+ if (cachedFallbackLib !== void 0) {
44
+ return cachedFallbackLib(schema);
45
+ }
46
+ if (triedFallback) return void 0;
47
+ triedFallback = true;
48
+ try {
49
+ const mod = requireSdk("zod-to-json-schema");
50
+ const fn = typeof mod.zodToJsonSchema === "function" ? mod.zodToJsonSchema : typeof mod.default === "function" ? mod.default : void 0;
51
+ if (fn === void 0) return void 0;
52
+ cachedFallbackLib = fn;
53
+ return fn(schema);
54
+ } catch {
55
+ return void 0;
56
+ }
57
+ }
58
+
59
+ // src/define-tool.ts
60
+ function defineTool(spec) {
61
+ const inputSchema = toJsonSchema(spec.inputSchema, {
62
+ unrepresentable: "any"
63
+ });
64
+ return {
65
+ name: spec.name,
66
+ description: spec.description,
67
+ inputSchema,
68
+ handler: async (input) => {
69
+ const parsed = spec.inputSchema.parse(input);
70
+ return await spec.handler(parsed);
71
+ }
72
+ };
73
+ }
74
+
75
+ // src/errors.ts
76
+ var TheokitAgentError = class extends Error {
77
+ name = "TheokitAgentError";
78
+ isRetryable;
79
+ code;
80
+ protoErrorCode;
81
+ metadata;
82
+ constructor(message, options = {}) {
83
+ super(message, options.cause !== void 0 ? { cause: options.cause } : void 0);
84
+ this.isRetryable = options.isRetryable ?? false;
85
+ if (options.code !== void 0) this.code = options.code;
86
+ if (options.protoErrorCode !== void 0) this.protoErrorCode = options.protoErrorCode;
87
+ if (options.metadata !== void 0) this.metadata = options.metadata;
88
+ }
89
+ };
90
+ var ConfigurationError = class extends TheokitAgentError {
91
+ name = "ConfigurationError";
92
+ constructor(message, options = {}) {
93
+ super(message, { ...options, isRetryable: false });
94
+ }
95
+ };
96
+
97
+ // src/internal/security/path-guard.ts
98
+ var PathTraversalError = class extends ConfigurationError {
99
+ name = "PathTraversalError";
100
+ constructor(input, resolvedPath) {
101
+ super(`Path traversal attempt: ${input} \u2192 ${resolvedPath}`, {
102
+ code: "path_traversal"
103
+ });
104
+ }
105
+ };
106
+ var ForbiddenPathError = class extends ConfigurationError {
107
+ name = "ForbiddenPathError";
108
+ constructor(path) {
109
+ super(
110
+ `Path '${path}' is in the sensitive-file blocklist (.env, .git/, node_modules/, .theo/, lock files)`,
111
+ {
112
+ code: "forbidden_path"
113
+ }
114
+ );
115
+ }
116
+ };
117
+ function safePathJoin(base, ...parts) {
118
+ if (base === "") {
119
+ throw new Error("safePathJoin: base must be non-empty");
120
+ }
121
+ const baseResolved = resolve(base);
122
+ const target = resolve(base, ...parts);
123
+ if (target !== baseResolved && !target.startsWith(baseResolved + sep)) {
124
+ throw new PathTraversalError(parts.join("/"), target);
125
+ }
126
+ return target;
127
+ }
128
+ function assertNoSymlinkEscape(path, base) {
129
+ let baseResolved;
130
+ try {
131
+ baseResolved = realpathSync(base);
132
+ } catch {
133
+ baseResolved = resolve(base);
134
+ }
135
+ const resolved = realpathOfDeepestExisting(path);
136
+ if (resolved === void 0) return;
137
+ if (resolved !== baseResolved && !resolved.startsWith(baseResolved + sep)) {
138
+ throw new PathTraversalError(`symlink ${path}`, resolved);
139
+ }
140
+ }
141
+ function realpathOfDeepestExisting(path) {
142
+ try {
143
+ return realpathSync(path);
144
+ } catch {
145
+ }
146
+ try {
147
+ const stat = lstatSync(path);
148
+ if (stat.isSymbolicLink()) {
149
+ const target = readlinkSync(path);
150
+ const parentReal = realpathOfDeepestExisting(dirname(path));
151
+ const parentBase = parentReal ?? dirname(path);
152
+ return resolve(parentBase, target);
153
+ }
154
+ } catch {
155
+ }
156
+ let cursor = dirname(path);
157
+ let suffix = path.slice(cursor.length);
158
+ while (cursor !== dirname(cursor)) {
159
+ try {
160
+ const real = realpathSync(cursor);
161
+ return resolve(real, `.${suffix}`);
162
+ } catch {
163
+ suffix = path.slice(dirname(cursor).length);
164
+ cursor = dirname(cursor);
165
+ }
166
+ }
167
+ return void 0;
168
+ }
169
+ var LOCK_FILES = /* @__PURE__ */ new Set(["pnpm-lock.yaml", "package-lock.json", "yarn.lock", "bun.lockb"]);
170
+ function isForbiddenPath(input) {
171
+ const normalized = input.replace(/\\/g, "/").replace(/^\.\//, "");
172
+ if (normalized.length === 0) return false;
173
+ const segments = normalized.split("/").filter((s) => s.length > 0);
174
+ if (segments.length === 0) return false;
175
+ const first = segments[0];
176
+ if (first === ".env.example") return false;
177
+ if (first === ".env") return true;
178
+ if (/^\.env\./.test(first)) return true;
179
+ if (first === ".git") return true;
180
+ if (first === "node_modules") return true;
181
+ if (first === ".theo") return true;
182
+ const basename = segments[segments.length - 1];
183
+ if (LOCK_FILES.has(basename)) return true;
184
+ return false;
185
+ }
186
+
187
+ // src/tools/_path-scope.ts
188
+ function checkPathScope(path, projectRoot) {
189
+ if (path === void 0 || path === "") return null;
190
+ try {
191
+ const abs = safePathJoin(projectRoot, path);
192
+ assertNoSymlinkEscape(abs, projectRoot);
193
+ return null;
194
+ } catch (err) {
195
+ if (err instanceof PathTraversalError || err instanceof ForbiddenPathError) {
196
+ return JSON.stringify({ ok: false, error: "path_traversal", path });
197
+ }
198
+ throw err;
199
+ }
200
+ }
201
+
202
+ // src/tools/_subprocess.ts
203
+ function createSettleGate(timer) {
204
+ let done = false;
205
+ return {
206
+ settled: () => done,
207
+ fire: (onSettle) => {
208
+ if (done) return;
209
+ done = true;
210
+ clearTimeout(timer);
211
+ onSettle();
212
+ }
213
+ };
214
+ }
215
+ function armTimeoutKill(child, timeoutMs, onTimeout, resolve2) {
216
+ const timer = setTimeout(() => {
217
+ gate.fire(() => {
218
+ try {
219
+ process.kill(-(child.pid ?? 0), "SIGKILL");
220
+ } catch {
221
+ }
222
+ resolve2(onTimeout());
223
+ });
224
+ }, timeoutMs);
225
+ const gate = createSettleGate(timer);
226
+ return gate;
227
+ }
228
+ function attachChildSettlers(child, gate, onClose, onError, resolve2) {
229
+ child.on("close", (code) => {
230
+ gate.fire(() => resolve2(onClose(code)));
231
+ });
232
+ child.on("error", (err) => {
233
+ gate.fire(() => resolve2(onError(err)));
234
+ });
235
+ }
236
+
237
+ // src/tools/git-diff.ts
238
+ var DEFAULT_TIMEOUT_MS = 3e4;
239
+ var DEFAULT_MAX_STDOUT_BYTES = 5 * 1024 * 1024;
240
+ function createGitDiffTool(opts) {
241
+ const {
242
+ projectRoot,
243
+ timeoutMs = DEFAULT_TIMEOUT_MS,
244
+ maxStdoutBytes = DEFAULT_MAX_STDOUT_BYTES
245
+ } = opts;
246
+ return defineTool({
247
+ name: "git_diff",
248
+ description: "Return the unified diff of the project's working tree (or staged changes when cached=true). Scoped to a single file when 'path' is provided. Requires the project to be a git repository. Returns { ok, diff, truncated? } or { ok: false, error }.",
249
+ inputSchema: z.object({
250
+ path: z.string().optional().describe("Optional project-relative file or dir scope."),
251
+ cached: z.boolean().optional().describe("If true, show staged changes (git diff --cached). Default false.")
252
+ }),
253
+ handler: async ({ path, cached }) => {
254
+ if (!existsSync(join(projectRoot, ".git"))) {
255
+ return JSON.stringify({ ok: false, error: "not_a_repo" });
256
+ }
257
+ const scopeCheck = checkPathScope(path, projectRoot);
258
+ if (scopeCheck !== null) return scopeCheck;
259
+ const args = buildDiffArgs(cached, path);
260
+ const result = await runGitProcess(projectRoot, args, timeoutMs, maxStdoutBytes);
261
+ return formatGitResult(result, timeoutMs);
262
+ }
263
+ });
264
+ }
265
+ function buildDiffArgs(cached, path) {
266
+ const args = ["diff", "--no-color"];
267
+ if (cached === true) args.push("--cached");
268
+ if (path !== void 0 && path !== "") args.push("--", path);
269
+ return args;
270
+ }
271
+ function formatGitResult(result, timeoutMs) {
272
+ if (result.kind === "timeout") {
273
+ return JSON.stringify({ ok: false, error: "timeout", timeoutMs });
274
+ }
275
+ if (result.kind === "error") {
276
+ return JSON.stringify({ ok: false, error: "git_failed", stderr: result.stderr });
277
+ }
278
+ return JSON.stringify({ ok: true, diff: result.stdout, truncated: result.truncated });
279
+ }
280
+ function runGitProcess(cwd, args, timeoutMs, maxStdoutBytes) {
281
+ return new Promise((resolve2) => {
282
+ const child = spawn("git", args, { cwd, detached: true, stdio: ["ignore", "pipe", "pipe"] });
283
+ const stdoutChunks = [];
284
+ const stderrChunks = [];
285
+ let stdoutBytes = 0;
286
+ let truncated = false;
287
+ const gate = armTimeoutKill(
288
+ child,
289
+ timeoutMs,
290
+ () => ({ kind: "timeout" }),
291
+ resolve2
292
+ );
293
+ child.stdout.on("data", (chunk) => {
294
+ if (gate.settled()) return;
295
+ if (stdoutBytes >= maxStdoutBytes) {
296
+ truncated = true;
297
+ return;
298
+ }
299
+ const remaining = maxStdoutBytes - stdoutBytes;
300
+ if (chunk.length > remaining) {
301
+ stdoutChunks.push(chunk.subarray(0, remaining));
302
+ stdoutBytes = maxStdoutBytes;
303
+ truncated = true;
304
+ } else {
305
+ stdoutChunks.push(chunk);
306
+ stdoutBytes += chunk.length;
307
+ }
308
+ });
309
+ child.stderr.on("data", (chunk) => {
310
+ stderrChunks.push(chunk);
311
+ });
312
+ attachChildSettlers(
313
+ child,
314
+ gate,
315
+ (code) => {
316
+ const stdout = Buffer.concat(stdoutChunks).toString("utf-8");
317
+ const stderr = Buffer.concat(stderrChunks).toString("utf-8");
318
+ return code === 0 ? { kind: "ok", stdout, truncated } : { kind: "error", stderr };
319
+ },
320
+ (err) => ({ kind: "error", stderr: err.message }),
321
+ resolve2
322
+ );
323
+ });
324
+ }
325
+ var DEFAULT_MAX_ENTRIES = 500;
326
+ function createListDirTool(opts) {
327
+ const { projectRoot, max = DEFAULT_MAX_ENTRIES } = opts;
328
+ return defineTool({
329
+ name: "list_dir",
330
+ description: `Return the direct entries of a project-relative directory. Refuses paths outside the project root or in the sensitive-file blocklist (.env, .git/, node_modules/, .theo/, lock files). Caps at ${String(max)} entries by default; result carries truncated + totalCount.`,
331
+ inputSchema: z.object({
332
+ path: z.string().min(1).describe("Project-relative directory path. Use '.' for root.")
333
+ }),
334
+ handler: async ({ path }) => {
335
+ const relative = path === "" || path === "." ? "." : path;
336
+ if (relative !== "." && isForbiddenPath(relative)) {
337
+ return JSON.stringify({ ok: false, error: "forbidden_path", path });
338
+ }
339
+ const boundary = resolveDirBoundary(relative, projectRoot, path);
340
+ if ("error" in boundary) return boundary.error;
341
+ const readResult = await readDirSafe(boundary.absolutePath, path);
342
+ if ("error" in readResult) return readResult.error;
343
+ return formatListing(readResult.dirents, max);
344
+ }
345
+ });
346
+ }
347
+ function resolveDirBoundary(relative, projectRoot, originalPath) {
348
+ try {
349
+ const absolutePath = relative === "." ? projectRoot : safePathJoin(projectRoot, relative);
350
+ assertNoSymlinkEscape(absolutePath, projectRoot);
351
+ return { absolutePath };
352
+ } catch (err) {
353
+ if (err instanceof PathTraversalError || err instanceof ForbiddenPathError) {
354
+ return { error: JSON.stringify({ ok: false, error: "path_traversal", path: originalPath }) };
355
+ }
356
+ throw err;
357
+ }
358
+ }
359
+ async function readDirSafe(absolutePath, originalPath) {
360
+ try {
361
+ const dirents = await readdir(absolutePath, { withFileTypes: true });
362
+ return { dirents };
363
+ } catch (err) {
364
+ const e = err;
365
+ if (e.code === "ENOENT" || e.code === "ENOTDIR") {
366
+ return { error: JSON.stringify({ ok: false, error: "not_found", path: originalPath }) };
367
+ }
368
+ throw err;
369
+ }
370
+ }
371
+ function formatListing(dirents, max) {
372
+ const totalCount = dirents.length;
373
+ const truncated = totalCount > max;
374
+ const entries = dirents.slice(0, max).map((d) => ({
375
+ name: d.name,
376
+ type: d.isDirectory() ? "directory" : "file"
377
+ }));
378
+ return JSON.stringify({ ok: true, entries, truncated, totalCount });
379
+ }
380
+ var MAX_FILE_SIZE = 5 * 1024 * 1024;
381
+ var BINARY_PROBE_BYTES = 8 * 1024;
382
+ function createReadFileTool(opts) {
383
+ const { projectRoot } = opts;
384
+ return defineTool({
385
+ name: "read_file",
386
+ description: "Read a single project-relative text file as UTF-8. Refuses paths that escape the project root, are in the sensitive-file blocklist (.env, .git/, node_modules/, .theo/, lock files), or contain a null byte in the first 8 KB (binary file). Returns { ok, content } or { ok: false, error }.",
387
+ inputSchema: z.object({
388
+ path: z.string().min(1).describe("Project-relative file path.")
389
+ }),
390
+ handler: async ({ path }) => {
391
+ if (isForbiddenPath(path)) {
392
+ return JSON.stringify({ ok: false, error: "forbidden_path", path });
393
+ }
394
+ const boundary = resolveBoundary(path, projectRoot);
395
+ if ("error" in boundary) return boundary.error;
396
+ const opened = await openHandleSafe(boundary.absolutePath, path);
397
+ if ("error" in opened) return opened.error;
398
+ try {
399
+ return await readContent(opened.handle, path);
400
+ } finally {
401
+ await opened.handle.close();
402
+ }
403
+ }
404
+ });
405
+ }
406
+ function resolveBoundary(path, projectRoot) {
407
+ try {
408
+ const absolutePath = safePathJoin(projectRoot, path);
409
+ assertNoSymlinkEscape(absolutePath, projectRoot);
410
+ return { absolutePath };
411
+ } catch (err) {
412
+ if (err instanceof PathTraversalError || err instanceof ForbiddenPathError) {
413
+ return { error: JSON.stringify({ ok: false, error: "path_traversal", path }) };
414
+ }
415
+ throw err;
416
+ }
417
+ }
418
+ async function openHandleSafe(absolutePath, path) {
419
+ try {
420
+ const handle = await open(absolutePath, "r");
421
+ return { handle };
422
+ } catch (err) {
423
+ const e = err;
424
+ if (e.code === "ENOENT") {
425
+ return { error: JSON.stringify({ ok: false, error: "not_found", path }) };
426
+ }
427
+ throw err;
428
+ }
429
+ }
430
+ async function readContent(handle, path) {
431
+ const stat = await handle.stat();
432
+ if (stat.size > MAX_FILE_SIZE) {
433
+ return JSON.stringify({
434
+ ok: false,
435
+ error: "too_large",
436
+ path,
437
+ size: stat.size,
438
+ limit: MAX_FILE_SIZE
439
+ });
440
+ }
441
+ if (await isBinaryProbe(handle, Number(stat.size))) {
442
+ return JSON.stringify({ ok: false, error: "binary_file", path, size: stat.size });
443
+ }
444
+ const content = await handle.readFile({ encoding: "utf-8" });
445
+ return JSON.stringify({ ok: true, content, size: stat.size });
446
+ }
447
+ async function isBinaryProbe(handle, size) {
448
+ const probeLen = Math.min(BINARY_PROBE_BYTES, size);
449
+ if (probeLen <= 0) return false;
450
+ const probe = Buffer.alloc(probeLen);
451
+ const { bytesRead } = await handle.read(probe, 0, probeLen, 0);
452
+ for (let i = 0; i < bytesRead; i += 1) {
453
+ if (probe[i] === 0) return true;
454
+ }
455
+ return false;
456
+ }
457
+ var DEFAULT_TIMEOUT_MS2 = 12e4;
458
+ var DEFAULT_MAX_STDOUT_BYTES2 = 10 * 1024 * 1024;
459
+ function createRunVitestTool(opts) {
460
+ const {
461
+ projectRoot,
462
+ timeoutMs = DEFAULT_TIMEOUT_MS2,
463
+ maxStdoutBytes = DEFAULT_MAX_STDOUT_BYTES2
464
+ } = opts;
465
+ return defineTool({
466
+ name: "run_vitest",
467
+ description: "Run the project's vitest suite, optionally scoped to a file or pattern via 'path'. Returns parsed { ok, summary } or { ok: false, error }. Vitest stdout warnings are stripped \u2014 the parser extracts the trailing JSON report.",
468
+ inputSchema: z.object({
469
+ path: z.string().optional().describe("Optional vitest pattern or file path (project-relative).")
470
+ }),
471
+ handler: async ({ path }) => {
472
+ const scopeError = validateVitestScope(path, projectRoot);
473
+ if (scopeError !== null) return scopeError;
474
+ const args = ["--no-install", "vitest", "run", "--reporter=json"];
475
+ if (path !== void 0 && path !== "") args.push(path);
476
+ const result = await runProcess(projectRoot, "npx", args, timeoutMs, maxStdoutBytes);
477
+ return formatVitestResult(result, timeoutMs);
478
+ }
479
+ });
480
+ }
481
+ function validateVitestScope(path, projectRoot) {
482
+ if (path !== void 0 && path !== "" && isForbiddenPath(path)) {
483
+ return JSON.stringify({ ok: false, error: "forbidden_path", path });
484
+ }
485
+ return checkPathScope(path, projectRoot);
486
+ }
487
+ function formatVitestResult(result, timeoutMs) {
488
+ if (result.kind === "timeout") {
489
+ return JSON.stringify({ ok: false, error: "timeout", timeoutMs });
490
+ }
491
+ if (result.kind === "spawn_error") {
492
+ return JSON.stringify({ ok: false, error: "no_vitest", detail: result.message });
493
+ }
494
+ const summary = extractTrailingJson(result.stdout);
495
+ if (summary === null) {
496
+ return JSON.stringify({
497
+ ok: false,
498
+ error: "unparseable_output",
499
+ stderrPreview: result.stderr.slice(0, 500)
500
+ });
501
+ }
502
+ return JSON.stringify({ ok: true, summary });
503
+ }
504
+ function extractTrailingJson(stdout) {
505
+ const lines = stdout.split(/\r?\n/);
506
+ for (let i = lines.length - 1; i >= 0; i -= 1) {
507
+ const line = lines[i].trim();
508
+ if (line.length === 0) continue;
509
+ if (line[0] !== "{" && line[0] !== "[") continue;
510
+ try {
511
+ return JSON.parse(line);
512
+ } catch {
513
+ }
514
+ }
515
+ return null;
516
+ }
517
+ function appendCapped(chunks, chunk, current, cap) {
518
+ if (current >= cap) return current;
519
+ const remaining = cap - current;
520
+ if (chunk.length > remaining) {
521
+ chunks.push(chunk.subarray(0, remaining));
522
+ return cap;
523
+ }
524
+ chunks.push(chunk);
525
+ return current + chunk.length;
526
+ }
527
+ function runProcess(cwd, command, args, timeoutMs, maxStdoutBytes) {
528
+ return new Promise((resolve2) => {
529
+ const child = spawn(command, args, {
530
+ cwd,
531
+ detached: true,
532
+ stdio: ["ignore", "pipe", "pipe"]
533
+ });
534
+ const stdoutChunks = [];
535
+ const stderrChunks = [];
536
+ let stdoutBytes = 0;
537
+ const gate = armTimeoutKill(
538
+ child,
539
+ timeoutMs,
540
+ () => ({ kind: "timeout" }),
541
+ resolve2
542
+ );
543
+ child.stdout.on("data", (chunk) => {
544
+ if (gate.settled()) return;
545
+ stdoutBytes = appendCapped(stdoutChunks, chunk, stdoutBytes, maxStdoutBytes);
546
+ });
547
+ child.stderr.on("data", (chunk) => {
548
+ stderrChunks.push(chunk);
549
+ });
550
+ attachChildSettlers(
551
+ child,
552
+ gate,
553
+ (code) => ({
554
+ kind: "ok",
555
+ stdout: Buffer.concat(stdoutChunks).toString("utf-8"),
556
+ stderr: Buffer.concat(stderrChunks).toString("utf-8"),
557
+ exitCode: code ?? 0
558
+ }),
559
+ (err) => ({ kind: "spawn_error", message: err.message }),
560
+ resolve2
561
+ );
562
+ });
563
+ }
564
+ var DEFAULT_MAX_MATCHES = 100;
565
+ var DEFAULT_MAX_FILE_SIZE = 1024 * 1024;
566
+ var BINARY_PROBE_BYTES2 = 8 * 1024;
567
+ var PREVIEW_MAX = 200;
568
+ function createSearchTextTool(opts) {
569
+ const {
570
+ projectRoot,
571
+ maxMatches = DEFAULT_MAX_MATCHES,
572
+ maxFileSize = DEFAULT_MAX_FILE_SIZE
573
+ } = opts;
574
+ return defineTool({
575
+ name: "search_text",
576
+ description: `Search the project tree for a literal text query. Skips sensitive dirs (.env/.git/node_modules/.theo), binary files, and files over 1 MB. Returns up to ${String(maxMatches)} matches as { file, line, preview }. Use 'path' to scope the search to a subdirectory.`,
577
+ inputSchema: z.object({
578
+ query: z.string().min(1).describe("Literal text to search for. Case-sensitive."),
579
+ path: z.string().optional().describe("Optional project-relative directory to scope the search.")
580
+ }),
581
+ handler: async ({ query, path }) => {
582
+ const scope = resolveSearchScope(path, projectRoot);
583
+ if ("error" in scope) return scope.error;
584
+ const state = {
585
+ matches: [],
586
+ totalMatches: 0,
587
+ truncated: false,
588
+ query,
589
+ maxMatches,
590
+ maxFileSize,
591
+ projectRoot
592
+ };
593
+ await walk(scope.scopeAbs, state);
594
+ return JSON.stringify({
595
+ ok: true,
596
+ matches: state.matches,
597
+ truncated: state.truncated,
598
+ totalMatches: state.totalMatches
599
+ });
600
+ }
601
+ });
602
+ }
603
+ function resolveSearchScope(path, projectRoot) {
604
+ const scopeRel = path === void 0 || path === "" || path === "." ? "." : path;
605
+ try {
606
+ const scopeAbs = scopeRel === "." ? projectRoot : safePathJoin(projectRoot, scopeRel);
607
+ assertNoSymlinkEscape(scopeAbs, projectRoot);
608
+ return { scopeAbs };
609
+ } catch (err) {
610
+ if (err instanceof PathTraversalError || err instanceof ForbiddenPathError) {
611
+ return { error: JSON.stringify({ ok: false, error: "path_traversal", path }) };
612
+ }
613
+ throw err;
614
+ }
615
+ }
616
+ async function handleEntry(entry, absDir, state) {
617
+ const entryAbs = join(absDir, entry.name);
618
+ const entryRel = relative(state.projectRoot, entryAbs);
619
+ if (isForbiddenPath(entryRel)) return;
620
+ if (entry.isDirectory()) {
621
+ await walk(entryAbs, state);
622
+ return;
623
+ }
624
+ if (entry.isFile()) await scanFile(entryAbs, entryRel, state);
625
+ }
626
+ async function walk(absDir, state) {
627
+ if (state.truncated) return;
628
+ const entries = await readEntriesQuiet(absDir);
629
+ if (entries === null) return;
630
+ for (const entry of entries) {
631
+ if (state.truncated) return;
632
+ await handleEntry(entry, absDir, state);
633
+ }
634
+ }
635
+ async function readEntriesQuiet(absDir) {
636
+ try {
637
+ return await readdir(absDir, { withFileTypes: true });
638
+ } catch {
639
+ return null;
640
+ }
641
+ }
642
+ async function readBufferQuiet(absPath) {
643
+ try {
644
+ return await readFile(absPath);
645
+ } catch {
646
+ return null;
647
+ }
648
+ }
649
+ function isBinaryBuffer(buffer) {
650
+ const probeEnd = Math.min(buffer.length, BINARY_PROBE_BYTES2);
651
+ for (let i = 0; i < probeEnd; i += 1) {
652
+ if (buffer[i] === 0) return true;
653
+ }
654
+ return false;
655
+ }
656
+ function recordMatch(state, file, line, lineText) {
657
+ state.totalMatches += 1;
658
+ if (state.matches.length < state.maxMatches) {
659
+ state.matches.push({
660
+ file,
661
+ line,
662
+ preview: lineText.length > PREVIEW_MAX ? `${lineText.slice(0, PREVIEW_MAX)}\u2026` : lineText
663
+ });
664
+ return true;
665
+ }
666
+ state.truncated = true;
667
+ return false;
668
+ }
669
+ async function scanFile(absPath, relPath, state) {
670
+ const buffer = await readBufferQuiet(absPath);
671
+ if (buffer === null || buffer.length > state.maxFileSize) return;
672
+ if (isBinaryBuffer(buffer)) return;
673
+ const lines = buffer.toString("utf-8").split("\n");
674
+ for (let i = 0; i < lines.length; i += 1) {
675
+ const line = lines[i];
676
+ if (!line.includes(state.query)) continue;
677
+ if (!recordMatch(state, relPath, i + 1, line)) return;
678
+ }
679
+ }
680
+
681
+ export { createGitDiffTool, createListDirTool, createReadFileTool, createRunVitestTool, createSearchTextTool };
682
+ //# sourceMappingURL=tools.js.map
683
+ //# sourceMappingURL=tools.js.map