@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
@@ -0,0 +1,1878 @@
1
+ import { T as TheokitAgentError, B as BudgetOptions, a as BudgetHandle, b as BudgetSnapshot } from './errors-CK8brCJ1.cjs';
2
+ export { A as AgentRunError, c as AgentRunErrorCode, d as AuthenticationError, e as BudgetExceedEvent, f as BudgetExceededError, g as BudgetLimit, h as BudgetMode, i as BudgetScope, j as BudgetThresholdEvent, k as BudgetWindow, C as ConfigurationError, E as ErrorCode, l as ErrorMetadata, I as IntegrationNotConnectedError, m as InvalidTaskIdError, M as MemoryAdapterError, n as MemoryAdapterErrorCode, N as NetworkError, R as RateLimitError, o as TaskNotFoundError, U as UnknownAgentError, p as UnsupportedBudgetOperationError, q as UnsupportedRunOperationError, r as UnsupportedTaskOperationError } from './errors-CK8brCJ1.cjs';
3
+ import { A as AgentOptions, R as RunResult, M as ModelSelection, L as LocalOptions, P as ProviderRoutingSettings, S as SystemPromptResolver, C as CloudOptions, a as MemorySettings, b as CustomTool, c as McpServerConfig, d as AgentDefinition, e as ContextSettings, f as PluginsSettings, g as SkillsSettings, h as SDKAgent, i as ListAgentsOptions, j as ListResult, k as SDKAgentInfo, G as GetAgentOptions, l as ListRunsOptions, m as Run, n as GetRunOptions, o as AgentOperationOptions, H as HandoffOptions, p as HandoffDescriptor, q as ConversationStorageAdapter, r as StoredMessage, s as MemoryId, t as SDKProvider, u as SDKMessage } from './run-DkCD5DeO.cjs';
4
+ export { v as AgentConversationTurn, w as AgentMemory, x as AssistantMessage, y as CloudEnv, z as CloudRepo, B as ContextBudget, D as ContextManagerKind, E as ContextSnapshot, F as ContextSource, I as ContextSourceStatus, J as ConversationStep, K as ConversationTurn, N as CostBreakdown, O as CostSource, Q as CostStatus, T as GoalEvent, U as GoalOptions, V as GoalResult, W as HandoffContext, X as HandoffHistory, Y as HandoffLoopError, Z as HandoffNameCollisionError, _ as HandoffPairLoopError, $ as HandoffReceiverDisposedError, a0 as HandoffResult, a1 as HandoffSelfReferenceError, a2 as InteractionUpdate, a3 as InvalidateCacheOptions, a4 as McpAuthConfig, a5 as McpHttpServerConfig, a6 as McpOAuthConfig, a7 as McpStdioServerConfig, a8 as MemoryAdapter, a9 as MemoryAdapterCapabilities, aa as MemoryContext, ab as MemoryFact, ac as MemoryRevision, ad as MemoryToolSchema, ae as MemoryTurnMessage, af as ModelParameterValue, ag as PartialToolCallUpdate, ah as PersonalityPreset, ai as ProviderCapability, aj as ProviderRoute, ak as ResolvedProviderRoute, al as RunErrorDetail, am as RunGitInfo, an as RunOperation, ao as RunStatus, ap as RunUntilIterator, aq as SDKAgentPlugins, ar as SDKAgentSkills, as as SDKArtifact, at as SDKAssistantMessage, au as SDKContextManager, av as SDKImage, aw as SDKImageDimension, ax as SDKObjectDelta, ay as SDKPluginMetadata, az as SDKProvidersManager, aA as SDKRequestMessage, aB as SDKStatusMessage, aC as SDKSystemMessage, aD as SDKTaskMessage, aE as SDKThinkingMessage, aF as SDKToolUseMessage, aG as SDKUserMessage, aH as SDKUserMessageEvent, aI as SendOptions, aJ as SettingSource, aK as ShellCommand, aL as ShellConversationTurn, aM as ShellOutput, aN as ShellOutputDeltaUpdate, aO as StepCompletedUpdate, aP as StepStartedUpdate, aQ as SummaryCompletedUpdate, aR as SummaryStartedUpdate, aS as SummaryUpdate, aT as SystemPromptContext, aU as SystemPromptMemoryFact, aV as SystemPromptSkillRef, aW as TelemetrySettings, aX as TextBlock, aY as TextDeltaUpdate, aZ as ThinkingCompletedUpdate, a_ as ThinkingDeltaUpdate, a$ as ThinkingMessage, b0 as TokenDeltaUpdate, b1 as TokenUsage, b2 as ToolCall, b3 as ToolCallCompletedUpdate, b4 as ToolCallStartedUpdate, b5 as ToolUseBlock, b6 as TurnEndedUpdate, b7 as UserMessage, b8 as UserMessageAppendedUpdate } from './run-DkCD5DeO.cjs';
5
+ import * as zod from 'zod';
6
+ import { ZodType, z } from 'zod';
7
+ export { C as Cron, a as CronCreateOptions, b as CronGetOptions, c as CronJob, d as CronJobStatus, e as CronListOptions, f as CronOperationOptions, g as CronRunOptions, h as CronRuntime, i as CronSchedulerStatus, j as CronStartOptions } from './cron-1yxL3K2S.cjs';
8
+
9
+ /**
10
+ * Public types for `Agent.batch` (ADRs D134-D140).
11
+ *
12
+ * Run N prompts in parallel with bounded concurrency. Each prompt gets
13
+ * a fresh agent (create → send → wait → dispose). Failures isolated
14
+ * per-prompt; the batch never aborts on a single failure.
15
+ *
16
+ * @public
17
+ */
18
+
19
+ /**
20
+ * Single prompt in a batch. Plain string is shorthand for `{ prompt }`.
21
+ *
22
+ * @public
23
+ */
24
+ interface BatchItem {
25
+ /** Prompt text sent to the agent. */
26
+ prompt: string;
27
+ /** Per-prompt system prompt override (wins over `BatchOptions.systemPrompt`). */
28
+ systemPrompt?: string;
29
+ /**
30
+ * Caller-supplied metadata, round-tripped to `BatchResult.metadata`.
31
+ * Passed by reference — do NOT mutate while the batch is in-flight (EC-I).
32
+ */
33
+ metadata?: Record<string, unknown>;
34
+ }
35
+ /**
36
+ * Options accepted by `Agent.batch`. Extends `AgentOptions` — every
37
+ * prompt gets an agent created with these options (ADR D138 isolation),
38
+ * plus the batch-specific knobs below.
39
+ *
40
+ * @public
41
+ */
42
+ interface BatchOptions extends AgentOptions {
43
+ /**
44
+ * Maximum parallel agents. Default 4 (ADR D136). Must be a positive
45
+ * integer. Capped to `prompts.length` to avoid spinning idle workers.
46
+ */
47
+ concurrency?: number;
48
+ /** Optional filter applied post-collection. Return `false` to discard. */
49
+ filter?: (result: BatchResult) => boolean;
50
+ /**
51
+ * Streaming callback fired once per completed prompt (success OR failure).
52
+ * Caller exceptions are caught + logged to stderr without poisoning
53
+ * the batch (EC-5).
54
+ */
55
+ onResult?: (result: BatchResult) => void | Promise<void>;
56
+ /** Progress callback fired after each result. */
57
+ onProgress?: (progress: BatchProgress) => void;
58
+ /**
59
+ * Cancel pending prompts (ADR D140). In-flight prompts continue to
60
+ * completion (Node `AbortSignal` semantics). When `signal.reason` is
61
+ * an Error, it propagates to `BatchResult.error`; otherwise a generic
62
+ * "aborted" error is used.
63
+ */
64
+ signal?: AbortSignal;
65
+ /**
66
+ * Opt-in Task wrapping (ADRs D363, D374). When set, the batch is
67
+ * registered as a `Task` (kind="batch") in the SDK's observable
68
+ * registry. The parent task transitions `finished` when every
69
+ * prompt is resolved (success OR failure).
70
+ *
71
+ * Use cases: surfacing a long-running batch in the `theokit tasks
72
+ * list` CLI, programmatic `Task.cancel(id)` aborting the batch, or
73
+ * binding a user-facing job dashboard. v1 does NOT yet emit one
74
+ * task PER prompt (single parent only); per-prompt tasks land in
75
+ * v0.2.
76
+ *
77
+ * Auto-generated id uses the `b-` reserved prefix (D368, EC-5).
78
+ *
79
+ * @public
80
+ */
81
+ task?: true | {
82
+ id?: string;
83
+ meta?: Record<string, unknown>;
84
+ };
85
+ }
86
+ /**
87
+ * Per-prompt outcome. Discriminated union — check `ok` before reading
88
+ * `result` or `error`.
89
+ *
90
+ * @public
91
+ */
92
+ type BatchResult = {
93
+ ok: true;
94
+ index: number;
95
+ prompt: string;
96
+ result: RunResult;
97
+ metadata?: Record<string, unknown>;
98
+ durationMs: number;
99
+ } | {
100
+ ok: false;
101
+ index: number;
102
+ prompt: string;
103
+ error: TheokitAgentError;
104
+ metadata?: Record<string, unknown>;
105
+ durationMs: number;
106
+ };
107
+ /**
108
+ * Live progress snapshot delivered to `onProgress`.
109
+ *
110
+ * @public
111
+ */
112
+ interface BatchProgress {
113
+ total: number;
114
+ completed: number;
115
+ failed: number;
116
+ pending: number;
117
+ inFlight: number;
118
+ }
119
+
120
+ /**
121
+ * Options accepted by {@link Agent.streamObject}. Same shape as
122
+ * `Agent.generateObject` with the addition that the result is an
123
+ * `AsyncIterator<StreamObjectEvent<T>>` rather than a single Promise. See ADR D39.
124
+ *
125
+ * @public
126
+ */
127
+ interface StreamObjectOptions<T extends ZodType> {
128
+ schema: T;
129
+ prompt: string;
130
+ systemPrompt?: string;
131
+ model: ModelSelection;
132
+ apiKey?: string;
133
+ local: LocalOptions;
134
+ maxRetries?: number;
135
+ /**
136
+ * Optional provider routing forwarded to the transient agent. Required when
137
+ * `model.id` uses a prefix (e.g. `openai/gpt-4o-mini`) but the credential is
138
+ * for a unified gateway (e.g. OpenRouter). Without this, the SDK infers
139
+ * provider from the prefix and may fail with `provider_unresolved` even
140
+ * when the right env key is set under a different provider name.
141
+ */
142
+ providers?: ProviderRoutingSettings;
143
+ }
144
+ /**
145
+ * Recursive partial — `T` where every nested field becomes optional.
146
+ *
147
+ * @public
148
+ */
149
+ type DeepPartial<T> = T extends (infer U)[] ? Array<DeepPartial<U>> : T extends object ? {
150
+ [K in keyof T]?: DeepPartial<T[K]>;
151
+ } : T;
152
+ /**
153
+ * Event emitted by {@link Agent.streamObject}. Discriminate on `type`.
154
+ *
155
+ * - `partial` events fire zero or more times with monotonically increasing
156
+ * `attempt`, carrying best-effort schema-parsed snapshots of the model's
157
+ * accumulating output.
158
+ * - `complete` fires exactly once at the end, carrying the fully Zod-parsed
159
+ * object alongside usage and finishReason — semantically identical to a
160
+ * successful `Agent.generateObject()` return.
161
+ *
162
+ * @public
163
+ */
164
+ type StreamObjectEvent<T> = {
165
+ type: "partial";
166
+ partial: DeepPartial<T>;
167
+ attempt: number;
168
+ } | {
169
+ type: "complete";
170
+ object: T;
171
+ raw: unknown;
172
+ usage: {
173
+ inputTokens: number;
174
+ outputTokens: number;
175
+ };
176
+ finishReason: "tool_use" | "error";
177
+ };
178
+ /**
179
+ * Error thrown by {@link Agent.streamObject} when the model refuses to call
180
+ * the synthetic `output` tool or when all retries fail to produce a
181
+ * schema-valid object. Same code taxonomy as `GenerateObjectError`.
182
+ *
183
+ * @public
184
+ */
185
+ declare class StreamObjectError extends Error {
186
+ readonly name = "StreamObjectError";
187
+ readonly code: "no_tool_call" | "parse_failed";
188
+ readonly cause?: unknown;
189
+ constructor(code: "no_tool_call" | "parse_failed", message: string, cause?: unknown);
190
+ }
191
+
192
+ /**
193
+ * Options accepted by {@link Agent.generateObject}. Returns a typed object
194
+ * matching the supplied Zod schema. See ADR D33.
195
+ *
196
+ * @public
197
+ */
198
+ interface GenerateObjectOptions<T extends ZodType> {
199
+ /** Zod schema describing the expected object shape. */
200
+ schema: T;
201
+ /** User prompt — the model is asked to fill the schema given this prompt. */
202
+ prompt: string;
203
+ /** Optional system prompt steering the model. */
204
+ systemPrompt?: string;
205
+ /** Model selection. Required (transient agents need a model). */
206
+ model: ModelSelection;
207
+ /** API key. Falls back to env (THEOKIT_API_KEY etc). */
208
+ apiKey?: string;
209
+ /** Local runtime config (cwd, sandbox). Required to keep the transient agent local-only. */
210
+ local: LocalOptions;
211
+ /**
212
+ * Retry budget on parse failures. Default 1 (initial attempt + 1 retry).
213
+ * The transient agent is REUSED across retries so the registry sees a
214
+ * single entry (EC-3).
215
+ */
216
+ maxRetries?: number;
217
+ /**
218
+ * Optional provider routing forwarded to the transient agent. Required when
219
+ * `model.id` uses a prefix (e.g. `openai/gpt-4o-mini`) but the credential is
220
+ * for a unified gateway (e.g. OpenRouter). Without this, the SDK infers
221
+ * provider from the prefix and may fail with `provider_unresolved` even
222
+ * when the right env key is set under a different provider name.
223
+ */
224
+ providers?: ProviderRoutingSettings;
225
+ }
226
+ /**
227
+ * Successful return from {@link Agent.generateObject}.
228
+ *
229
+ * @public
230
+ */
231
+ interface GenerateObjectResult<T> {
232
+ /** Typed object parsed via the Zod schema. */
233
+ object: T;
234
+ /** Raw input the model passed to the synthetic tool, before Zod parse. */
235
+ raw: unknown;
236
+ /** Token usage of the LLM call(s) that produced the result. */
237
+ usage: {
238
+ inputTokens: number;
239
+ outputTokens: number;
240
+ };
241
+ /** Stop reason of the underlying agent run. */
242
+ finishReason: "tool_use" | "error";
243
+ }
244
+ /**
245
+ * Typed error thrown by {@link Agent.generateObject} when the model refuses
246
+ * to call the synthetic `output` tool or when retries are exhausted.
247
+ *
248
+ * @public
249
+ */
250
+ declare class GenerateObjectError extends Error {
251
+ readonly name = "GenerateObjectError";
252
+ readonly code: "no_tool_call" | "parse_failed";
253
+ readonly cause?: unknown;
254
+ constructor(code: "no_tool_call" | "parse_failed", message: string, cause?: unknown);
255
+ }
256
+
257
+ /**
258
+ * Fluent builder for {@link AgentOptions}. Chainable setters mutate internal
259
+ * state and return `this`. Three terminals:
260
+ *
261
+ * - `.build()` — synchronous snapshot (shallow clone) of accumulated options.
262
+ * - `.create()` — calls the injected `create` (Agent.create).
263
+ * - `.getOrCreate(agentId)` — calls the injected `getOrCreate` (Agent.getOrCreate).
264
+ *
265
+ * Validation runs inside the terminals via `validateAgentOptions`. See ADR D25.
266
+ *
267
+ * @public
268
+ */
269
+ declare class AgentBuilder {
270
+ private opts;
271
+ private readonly deps;
272
+ constructor(deps?: AgentBuilderDeps);
273
+ model(m: ModelSelection): this;
274
+ apiKey(k: string): this;
275
+ name(n: string): this;
276
+ systemPrompt(p: string | SystemPromptResolver): this;
277
+ local(l: LocalOptions): this;
278
+ cloud(c: CloudOptions): this;
279
+ memory(m: MemorySettings): this;
280
+ tools(t: CustomTool[]): this;
281
+ mcpServers(s: Record<string, McpServerConfig>): this;
282
+ agents(a: Record<string, AgentDefinition>): this;
283
+ context(c: ContextSettings): this;
284
+ providers(p: ProviderRoutingSettings): this;
285
+ plugins(p: PluginsSettings): this;
286
+ skills(s: SkillsSettings): this;
287
+ agentId(id: string): this;
288
+ /**
289
+ * Synchronous snapshot of the accumulated options. Returns a SHALLOW CLONE
290
+ * so external mutation of the result doesn't pollute the builder state (EC-2).
291
+ */
292
+ build(): AgentOptions;
293
+ /**
294
+ * Validate + create a fresh agent. Delegates to `Agent.create` via the
295
+ * injected `deps.create`. Throws if the builder was instantiated without
296
+ * deps (i.e., direct `new AgentBuilder()` instead of `Agent.builder()`).
297
+ */
298
+ create(): Promise<SDKAgent>;
299
+ /**
300
+ * Resume an existing agent or create one if the ID is unknown. Delegates to
301
+ * `Agent.getOrCreate` via the injected `deps.getOrCreate` (ADR D22).
302
+ */
303
+ getOrCreate(agentId: string): Promise<SDKAgent>;
304
+ }
305
+
306
+ /**
307
+ * Live-agent cache for production deploys (Production-Readiness #2, ADRs D307-D310).
308
+ *
309
+ * Caches `SDKAgent` instances by id with LRU eviction (when `size > maxAgents`)
310
+ * and an idle-timeout sweep (configurable interval, default 60s). Solves the
311
+ * "OOM at some point" failure mode of long-running Node servers that keep
312
+ * spawning fresh agents per conversation.
313
+ *
314
+ * **Distinct from `agent-registry.ts`** (the metadata registry that persists
315
+ * `RegisteredAgent` to `registry.json` per cwd). That module is the "address
316
+ * book"; this module is the "live cache". Conflating them violates SRP — see
317
+ * ADR D307.
318
+ *
319
+ * Defaults (ADR D308): `maxAgents: 100`, `idleTimeoutMs: 30 min`, sweep `60s`.
320
+ * Calibrated for indie/small-team Node deploys; high-traffic SaaS should
321
+ * `configure({ maxAgents: 1000 })`.
322
+ *
323
+ * @public (singleton exposed via `Agent.registry`)
324
+ */
325
+
326
+ type EvictReason = "lru" | "idle" | "explicit";
327
+ interface AgentRegistryOptions {
328
+ /**
329
+ * Maximum number of agents kept alive simultaneously. LRU eviction when
330
+ * exceeded. Default: 100.
331
+ *
332
+ * Setting `0` disables the cache entirely — every `Agent.getOrCreate`
333
+ * re-initializes (high cost, but predictable memory).
334
+ */
335
+ maxAgents?: number;
336
+ /**
337
+ * Idle timeout in milliseconds. Agents not used for this duration are
338
+ * evicted on the next sweep tick. Default: 1_800_000 (30 minutes).
339
+ * Set `0` to disable idle eviction.
340
+ */
341
+ idleTimeoutMs?: number;
342
+ /**
343
+ * Sweep interval in milliseconds. Default: 60_000 (60s).
344
+ * Lower = more responsive eviction but more CPU. Higher = staler entries.
345
+ */
346
+ sweepIntervalMs?: number;
347
+ /**
348
+ * Called whenever an agent is evicted. Listener errors are swallowed
349
+ * with a one-shot stderr warn (do not crash the eviction loop).
350
+ */
351
+ onEvict?: (id: string, reason: EvictReason) => void;
352
+ }
353
+ declare class LiveAgentRegistry {
354
+ #private;
355
+ /**
356
+ * Reconfigure registry behavior. Process-wide singleton (D310) — last
357
+ * configure call wins for all subsequent operations.
358
+ */
359
+ configure(opts: AgentRegistryOptions): void;
360
+ /**
361
+ * Lookup a cached agent. `get` is a use — refreshes `lastUsedAt` so the
362
+ * entry survives LRU eviction.
363
+ */
364
+ get(id: string): SDKAgent | undefined;
365
+ /**
366
+ * Insert or overwrite an agent in the cache. Triggers fire-and-forget LRU
367
+ * eviction when `size > maxAgents`.
368
+ *
369
+ * EC-4: when `id` already maps to a DIFFERENT agent instance, dispose the
370
+ * old one before overwriting (race protection against two `getOrCreate`
371
+ * calls creating two agents but only the second being cached — the first
372
+ * would leak file handles + lifecycle controllers).
373
+ */
374
+ set(id: string, agent: SDKAgent): void;
375
+ /**
376
+ * Explicitly evict an agent by id. Returns `true` when the entry was
377
+ * present (false = already gone). Calls `agent.dispose()` + `onEvict`
378
+ * with reason `"explicit"`.
379
+ */
380
+ evict(id: string): Promise<boolean>;
381
+ /**
382
+ * Evict every cached agent. Used by graceful shutdown (`process.on('SIGTERM')`)
383
+ * or end-of-test cleanup.
384
+ */
385
+ evictAll(): Promise<void>;
386
+ /** Number of currently cached agents. */
387
+ size(): number;
388
+ /** Ids of cached agents, newest first (by lastUsedAt). */
389
+ ids(): readonly string[];
390
+ }
391
+
392
+ /**
393
+ * Result of a one-shot {@link Agent.prompt} call.
394
+ *
395
+ * @public
396
+ */
397
+ type AgentPromptResult = RunResult;
398
+ /**
399
+ * Static façade for creating and managing Theo agents.
400
+ *
401
+ * @public
402
+ */
403
+ declare class Agent {
404
+ private constructor();
405
+ /**
406
+ * Live-agent cache for production deploys (Production-Readiness #2, ADRs D307-D310).
407
+ *
408
+ * Caches `SDKAgent` instances by id with LRU eviction (when `size > maxAgents`)
409
+ * and an idle-timeout sweep. Solves the OOM failure mode for long-running
410
+ * Node servers spawning fresh agents per conversation.
411
+ *
412
+ * Defaults: `maxAgents: 100`, `idleTimeoutMs: 30 min`, sweep `60s`.
413
+ * Configure for high-traffic SaaS:
414
+ *
415
+ * ```ts
416
+ * Agent.registry.configure({ maxAgents: 1000, idleTimeoutMs: 15 * 60_000 });
417
+ * process.on("SIGTERM", () => Agent.registry.evictAll());
418
+ * ```
419
+ *
420
+ * Cache hits are automatic in `Agent.getOrCreate` (T2.6). Disable the cache
421
+ * entirely via `configure({ maxAgents: 0 })` — every getOrCreate then
422
+ * re-initializes.
423
+ *
424
+ * @public
425
+ */
426
+ static readonly registry: LiveAgentRegistry;
427
+ /**
428
+ * Create a new agent. Pass either `local` or `cloud` to pick a runtime.
429
+ *
430
+ * @public
431
+ */
432
+ static create(options: AgentOptions): Promise<SDKAgent>;
433
+ /**
434
+ * One-shot prompt: create an agent, send a single message, wait, dispose.
435
+ *
436
+ * When `options.throwOnError === true`, rejects with `AgentRunError` if
437
+ * the run terminates with `status: 'error'` (instead of resolving with the
438
+ * error wrapped in the RunResult). Cancelled runs still resolve normally.
439
+ *
440
+ * @public
441
+ */
442
+ static prompt(message: string, options: AgentOptions): Promise<AgentPromptResult>;
443
+ /**
444
+ * Reattach to an existing agent by ID.
445
+ *
446
+ * @public
447
+ */
448
+ static resume(agentId: string, options?: Partial<AgentOptions>): Promise<SDKAgent>;
449
+ /**
450
+ * Start building an {@link AgentOptions} via fluent chain. See ADR D25.
451
+ * Terminals: `.build()`, `.create()`, `.getOrCreate(id)`.
452
+ *
453
+ * The builder receives `create` + `getOrCreate` as injected callbacks so
454
+ * that `agent-builder.ts` doesn't need a static import of `Agent` — keeps
455
+ * the module graph acyclic (G6).
456
+ *
457
+ * @public
458
+ */
459
+ static builder(): AgentBuilder;
460
+ /**
461
+ * Generate a typed object matching a Zod schema via a synthetic forced
462
+ * tool call (ADR D33). One-shot: create transient agent → send prompt →
463
+ * model calls `output` tool → parse args via Zod → return typed.
464
+ *
465
+ * @public
466
+ */
467
+ static generateObject<T extends zod.ZodType>(options: GenerateObjectOptions<T>): Promise<GenerateObjectResult<zod.z.infer<T>>>;
468
+ /**
469
+ * Stream a structured output object alongside intermediate `partial`
470
+ * deltas as the model accumulates its response (ADR D39). Returns an
471
+ * `AsyncIterator<StreamObjectEvent<T>>` that yields zero or more
472
+ * `partial` events and exactly one `complete` event at the end.
473
+ *
474
+ * The `complete` event carries the same `object: z.infer<T>` you would get
475
+ * from `Agent.generateObject` — same prompt + schema + model produces
476
+ * the same final object.
477
+ *
478
+ * @public
479
+ */
480
+ static streamObject<T extends zod.ZodType>(options: StreamObjectOptions<T>): AsyncGenerator<StreamObjectEvent<zod.z.infer<T>>, void, void>;
481
+ /**
482
+ * Run N prompts in parallel with bounded concurrency (ADRs D134-D140).
483
+ *
484
+ * Each prompt gets a fresh agent (create → send → wait → dispose). Failures
485
+ * are isolated per-prompt; the batch never throws on a single failure —
486
+ * inspect `result.ok` to discriminate success vs error. Default
487
+ * concurrency is 4. When `options.providers.apiKeys` has ≥2 keys per
488
+ * provider, all in-flight agents share a single credential pool via
489
+ * `AsyncLocalStorage` (EC-A) so rate-limit cooldowns are observed once
490
+ * instead of duplicated per agent.
491
+ *
492
+ * Streaming progress is opt-in via `onResult` / `onProgress`. `AbortSignal`
493
+ * cancels pending prompts; in-flight ones continue to completion (Node
494
+ * AbortSignal semantics). `signal.reason` propagates to `error` when set.
495
+ *
496
+ * @public
497
+ */
498
+ static batch(prompts: ReadonlyArray<string | BatchItem>, options: BatchOptions): Promise<BatchResult[]>;
499
+ /**
500
+ * Get an existing agent by ID, or create one with the supplied options if
501
+ * the ID is not yet registered. Eliminates the resume-vs-create boilerplate
502
+ * common to chat bots and other long-running agent consumers. See ADR D22.
503
+ *
504
+ * Resolution:
505
+ * 1. Try `Agent.resume(agentId, options)`. Return on success.
506
+ * 2. On `UnknownAgentError`, fall through to `Agent.create({ ...options, agentId })`.
507
+ * 3. On same-process race (`ConfigurationError(code: "agent_id_already_exists")`
508
+ * during step 2), retry `Agent.resume` once and return the winner's handle.
509
+ * 4. Any other error propagates verbatim.
510
+ *
511
+ * Caveats:
512
+ * - The function-level `agentId` always wins over `options.agentId`.
513
+ * - Options differ between calls? Last-call-wins for this handle (matches `Agent.resume`).
514
+ * - Disposed agents are NOT auto-deleted from the registry. To force a fresh
515
+ * agent, call `Agent.delete(agentId)` first.
516
+ *
517
+ * @public
518
+ */
519
+ static getOrCreate(agentId: string, options: AgentOptions): Promise<SDKAgent>;
520
+ /**
521
+ * List agents (local or cloud).
522
+ *
523
+ * @public
524
+ */
525
+ static list(options?: ListAgentsOptions): Promise<ListResult<SDKAgentInfo>>;
526
+ /**
527
+ * Get metadata for a single agent.
528
+ *
529
+ * @public
530
+ */
531
+ static get(agentId: string, _options?: GetAgentOptions): Promise<SDKAgentInfo>;
532
+ /**
533
+ * List runs for an agent.
534
+ *
535
+ * @public
536
+ */
537
+ static listRuns(agentId: string, _options?: ListRunsOptions): Promise<ListResult<Run>>;
538
+ /**
539
+ * Get a single run.
540
+ *
541
+ * @public
542
+ */
543
+ static getRun(runId: string, options?: GetRunOptions): Promise<Run>;
544
+ /**
545
+ * Archive a cloud agent.
546
+ *
547
+ * @public
548
+ */
549
+ static archive(agentId: string, _options?: AgentOperationOptions): Promise<void>;
550
+ /**
551
+ * Restore an archived cloud agent.
552
+ *
553
+ * @public
554
+ */
555
+ static unarchive(agentId: string, _options?: AgentOperationOptions): Promise<void>;
556
+ /**
557
+ * Permanently delete a cloud agent.
558
+ *
559
+ * @public
560
+ */
561
+ static delete(agentId: string, _options?: AgentOperationOptions): Promise<void>;
562
+ }
563
+
564
+ /**
565
+ * Handle returned by {@link createAgentFactory}. See ADR D23 for merge
566
+ * semantics.
567
+ *
568
+ * @public
569
+ */
570
+ interface AgentFactory {
571
+ /**
572
+ * Create a fresh agent for this session. Equivalent to `Agent.create(merged)`
573
+ * where `merged` is `common` ⊕ `overrides` ⊕ `{ agentId }`.
574
+ */
575
+ forSession(agentId: string, overrides?: Partial<AgentOptions>): Promise<SDKAgent>;
576
+ /**
577
+ * Resume an existing agent for this session, or create one if the ID is
578
+ * unknown. Equivalent to `Agent.getOrCreate(agentId, merged)`.
579
+ */
580
+ getOrCreate(agentId: string, overrides?: Partial<AgentOptions>): Promise<SDKAgent>;
581
+ }
582
+ /**
583
+ * Capture a common {@link AgentOptions} prefix and produce per-session agents
584
+ * with focused overrides. Useful for chat-bot patterns where most config is
585
+ * shared across users/sessions.
586
+ *
587
+ * Merge rules (ADR D23):
588
+ * - Top-level shallow merge with `overrides` winning.
589
+ * - Deep merge for `local`, `memory`, `cloud` (configuration objects with
590
+ * non-conflicting flat keys).
591
+ * - Total replace for `mcpServers`, `agents`, `tools`, `providers`,
592
+ * `plugins`, `skills`, `context` (collection-shaped).
593
+ * - The function-level `agentId` always wins over both `common.agentId` and
594
+ * `overrides.agentId`.
595
+ *
596
+ * The factory holds `common` by reference — mutating it after construction
597
+ * leaks to subsequent `forSession` calls (documented caveat).
598
+ *
599
+ * @public
600
+ */
601
+ declare function createAgentFactory(common: Partial<AgentOptions>): AgentFactory;
602
+
603
+ /**
604
+ * computeCost — apply pricing entries to a TokenUsage and produce a
605
+ * CostBreakdown (ADRs D377, D378).
606
+ *
607
+ * Edge cases absorbed:
608
+ * - EC-13: negative pricing → status="unknown" + note.
609
+ * - EC-14: reasoning tokens fall back to outputCostPerMillion when
610
+ * dedicated reasoning rate is undefined.
611
+ * - EC-12: money precision via microcent normalization (× 1e6).
612
+ * - "subscription_included" routes (Codex CLI, future Claude Pro) →
613
+ * return $0 with status="included".
614
+ * - Provider unknown / pricing missing → status="unknown" with
615
+ * undefined amountUsd (NÃO retorna 0 falso).
616
+ *
617
+ * @internal
618
+ */
619
+ interface ComputeArgs {
620
+ readonly usage: TokenUsage;
621
+ readonly provider: string;
622
+ readonly model: string;
623
+ readonly baseUrl?: string;
624
+ }
625
+ /**
626
+ * Returns CostBreakdown with `status="estimated"`, `"unknown"`, or
627
+ * `"included"`. Never throws; never returns 0 when pricing is missing.
628
+ */
629
+ declare function computeCost(args: ComputeArgs): CostBreakdown;
630
+
631
+ /**
632
+ * Budget enforcement (ADRs D383, D386, EC-7/8/9).
633
+ *
634
+ * - `preflightCheck(name, estimatedUsd)` — em `block` mode, throw
635
+ * `BudgetExceededError` antes da LLM call se qualquer limit seria
636
+ * excedido (EC-9 — caller chama dentro do mutex section).
637
+ * - `chargeAndCheckThresholds(name, actualUsd)` — apply charge ao
638
+ * ledger + invoca onThreshold/onExceed callbacks isolated em
639
+ * try/catch (EC-8).
640
+ *
641
+ * @internal
642
+ */
643
+ /**
644
+ * Throws BudgetExceededError if `mode === "block"` and any limit
645
+ * would be exceeded. No-op for audit/warn modes (post-charge checks
646
+ * handle those).
647
+ *
648
+ * Caller invokes this BEFORE the LLM call.
649
+ */
650
+ declare function preflightCheck(name: string, estimatedUsd: number): void;
651
+ /**
652
+ * Charge the budget + dispatch threshold/exceed callbacks (EC-8 isolated).
653
+ *
654
+ * - In `audit` mode: charge only, no callbacks.
655
+ * - In `warn` mode: charge + onThreshold (80/95) + onExceed (100). No throw.
656
+ * - In `block` mode: charge + onThreshold + onExceed. No throw post-call
657
+ * (preflightCheck already prevented exceed for the upcoming call;
658
+ * this protects against simultaneous-call races where multiple sends
659
+ * each pass preflight independently — last one to charge may still
660
+ * tip a limit. We document the case rather than retroactively throw).
661
+ */
662
+ declare function chargeAndCheckThresholds(name: string, actualUsd: number): Promise<void>;
663
+
664
+ /**
665
+ * normalizeUsage — convert provider-shaped raw `usage` object to
666
+ * canonical `TokenUsage`. Ports Hermes Agent's `normalize_usage`
667
+ * (referencia/hermes-agent/agent/usage_pricing.py:672-742).
668
+ *
669
+ * Handles 3 API shapes:
670
+ * - Anthropic Messages: 4 explicit buckets (input/output/cache_read/cache_creation).
671
+ * - OpenAI Chat Completions: prompt_tokens INCLUDES cache; subtract cached_tokens.
672
+ * - OpenAI Responses (Codex): input_tokens INCLUDES cache; same subtraction.
673
+ *
674
+ * Edge cases:
675
+ * - cline#10266 — OpenAI-compat proxies (OpenRouter, Vercel AI Gateway,
676
+ * Cline) routing Claude expose Anthropic-style top-level fields
677
+ * (cache_read_input_tokens / cache_creation_input_tokens). Both
678
+ * locations are checked with top-level fallback.
679
+ * - Null/undefined fields → 0 via `int()` coerce.
680
+ * - String token counts → parsed via int.
681
+ * - Negative values → clamped to 0 (defensive against proxy bugs).
682
+ *
683
+ * @internal
684
+ */
685
+ type ApiMode$1 = "anthropic_messages" | "openai_chat_completions" | "openai_responses";
686
+ declare function inferApiMode(provider: string): ApiMode$1;
687
+ declare function normalizeUsage(rawUsage: unknown, opts: {
688
+ provider: string;
689
+ apiMode?: ApiMode$1;
690
+ }): TokenUsage;
691
+
692
+ /**
693
+ * Pricing registry — bundled snapshot of LiteLLM JSON (ADR D379) with
694
+ * lazy load + alias normalization (EC-2).
695
+ *
696
+ * Snapshot lives in `pricing-data.json` (hand-curated 2026-05; refresh
697
+ * via `scripts/refresh-pricing.mjs`). All rates in USD per 1_000_000
698
+ * tokens (D378).
699
+ *
700
+ * Lookup precedence (EC-2):
701
+ * 1. Direct `provider/model` key
702
+ * 2. Strip date suffix (-YYYYMMDD or -YYYY-MM-DD)
703
+ * 3. Anthropic dot-to-dash normalization (claude-opus-4.7 → claude-opus-4-7)
704
+ * 4. Strip `openrouter/` prefix
705
+ *
706
+ * @internal
707
+ */
708
+ interface PricingEntry {
709
+ readonly provider: string;
710
+ readonly model: string;
711
+ readonly inputCostPerMillion: number;
712
+ readonly outputCostPerMillion: number;
713
+ readonly cacheReadCostPerMillion?: number;
714
+ readonly cacheWriteCostPerMillion?: number;
715
+ readonly reasoningCostPerMillion?: number;
716
+ readonly pricingVersion: string;
717
+ }
718
+ /**
719
+ * Returns the pricing entry for a given `{provider, model}` route.
720
+ * Tries direct lookup, then 3 alias normalizations (EC-2).
721
+ */
722
+ declare function getPricingEntry(opts: {
723
+ provider: string;
724
+ model: string;
725
+ baseUrl?: string;
726
+ }): PricingEntry | undefined;
727
+
728
+ /**
729
+ * UsageAccumulator — aggregate multi-step `LlmFinish` token counts
730
+ * into a canonical `TokenUsage` (ADR D376, mirror openai-agents-python
731
+ * `Usage.add`).
732
+ *
733
+ * Each `add(step)` merges in a per-step finish; `toTokenUsage()`
734
+ * produces the aggregated public shape with `requests[]` populated
735
+ * when there were ≥2 steps.
736
+ *
737
+ * @internal
738
+ */
739
+ interface StepUsage {
740
+ inputTokens?: number;
741
+ outputTokens?: number;
742
+ cacheReadTokens?: number;
743
+ cacheWriteTokens?: number;
744
+ reasoningTokens?: number;
745
+ }
746
+ declare class UsageAccumulator {
747
+ private input;
748
+ private output;
749
+ private cacheRead;
750
+ private cacheWrite;
751
+ private reasoning;
752
+ private readonly requests;
753
+ add(step: StepUsage): void;
754
+ /** Did we observe any usage at all? */
755
+ hasAny(): boolean;
756
+ toTokenUsage(): TokenUsage;
757
+ }
758
+
759
+ /**
760
+ * `Budget` — token cost enforcement primitive (Adoption Roadmap #1
761
+ * post-Tasks, ADRs D375-D388).
762
+ *
763
+ * Static facade delegating to the in-process registry + ledger.
764
+ * 3 modes: `audit` (log-only), `warn` (callbacks + log), `block`
765
+ * (preflight throw before LLM call).
766
+ *
767
+ * @public
768
+ */
769
+
770
+ declare class Budget {
771
+ private constructor();
772
+ /**
773
+ * Create a budget. `name` must match `^[a-z0-9][a-z0-9_-]*$` (EC-7).
774
+ * Throws `ConfigurationError` if name is invalid OR already exists
775
+ * (EC-16: duplicate surface caller bug).
776
+ *
777
+ * `limits` is stacked (D384) — ANY exceeded triggers enforcement.
778
+ * Empty `limits[]` is valid: pure tracking, no thresholds/exceed
779
+ * callbacks fire (EC-19).
780
+ *
781
+ * Default `mode` is `"warn"` (D383). For emergency stop, use
782
+ * `mode: "block", limits: [{ window: "1d", limitUsd: 0 }]` (EC-18).
783
+ */
784
+ static create(options: BudgetOptions): BudgetHandle;
785
+ /** Returns the handle for an active budget, or `undefined`. */
786
+ static get(name: string): BudgetHandle | undefined;
787
+ /** Returns all active budgets. */
788
+ static list(): readonly BudgetHandle[];
789
+ /**
790
+ * Deletes a budget from the registry. Returns `true` if it existed.
791
+ * In-flight `agent.send` calls referencing the name treat the
792
+ * subsequent charge as a silent no-op + stderr warn (EC-20).
793
+ */
794
+ static delete(name: string): boolean;
795
+ /**
796
+ * Returns per-window spend snapshot for all active budgets. Each
797
+ * entry has `{ name, window, spentUsd, limitUsd, ratio }`.
798
+ */
799
+ static snapshot(): readonly BudgetSnapshot[];
800
+ }
801
+
802
+ /**
803
+ * ProviderProfile + ApiMode types (T3.1, ADR D105).
804
+ *
805
+ * Profile is **data-only** — no methods. Adding a provider is declaring an
806
+ * object literal; the Transport layer (D106) consumes `apiMode` to pick
807
+ * the HTTP dialect.
808
+ *
809
+ * @public
810
+ */
811
+ type ApiMode = "chat_completions" | "anthropic_messages" | "responses_api" | "bedrock" | "bedrock_anthropic";
812
+ type AuthType = "api_key" | "oauth_device_code" | "oauth_external" | "aws_sdk" | "aws_bearer" | "gcp_oauth" | "none";
813
+ interface ProviderProfile {
814
+ name: string;
815
+ apiMode: ApiMode;
816
+ aliases?: ReadonlyArray<string>;
817
+ displayName?: string;
818
+ description?: string;
819
+ signupUrl?: string;
820
+ envVars: ReadonlyArray<string>;
821
+ authType: AuthType;
822
+ baseUrl: string;
823
+ modelsUrl?: string;
824
+ hostname?: string;
825
+ fallbackModels: ReadonlyArray<string>;
826
+ extraHeaders?: Record<string, string>;
827
+ bodyOverrides?: Record<string, unknown>;
828
+ }
829
+
830
+ type HookName = "pre_tool_call" | "post_tool_call" | "pre_llm_call" | "post_llm_call" | "on_session_start" | "on_session_end" | "transform_tool_result" | "transform_llm_output" | "pre_user_send" | "post_assistant_reply";
831
+ interface PreToolCallContext {
832
+ name: string;
833
+ args: Record<string, unknown>;
834
+ agentId: string;
835
+ runId: string;
836
+ }
837
+ interface PreToolCallDecision {
838
+ block: true;
839
+ message: string;
840
+ }
841
+ type HookHandler = (ctx: unknown) => unknown | Promise<unknown>;
842
+ type CommandHandler = (args: Record<string, unknown>) => Promise<string> | string;
843
+ interface CommandOptions {
844
+ description?: string;
845
+ }
846
+ interface PluginContext {
847
+ /** Register a custom tool. Equivalent to passing in `AgentOptions.tools`. */
848
+ registerTool(tool: CustomTool): void;
849
+ /** Register a slash-command-style handler. Consumed by CLI/bot wrappers; NOT used by the agent loop. */
850
+ registerCommand(name: string, handler: CommandHandler, opts?: CommandOptions): void;
851
+ /** Attach a hook handler. `pre_tool_call` supports veto via `PreToolCallDecision`. */
852
+ on(hook: HookName, handler: HookHandler): void;
853
+ /** Inject a user/system message into the next agent turn. v1 supports only `on_session_start` context. */
854
+ injectMessage(content: string, role?: "user" | "system"): void;
855
+ }
856
+ interface BasePlugin {
857
+ name: string;
858
+ version: string;
859
+ }
860
+ type Plugin = (BasePlugin & {
861
+ kind: "general";
862
+ register: (ctx: PluginContext) => void | Promise<void>;
863
+ }) | (BasePlugin & {
864
+ kind: "model-provider";
865
+ profile: ProviderProfile;
866
+ }) | (BasePlugin & {
867
+ kind: "memory";
868
+ createProvider: MemoryProviderFactory;
869
+ });
870
+ /**
871
+ * Identity helper for plugin authors. TS-only convenience — preserves
872
+ * inferred type without forcing manual `Plugin` annotation.
873
+ *
874
+ * @public
875
+ */
876
+ declare function definePlugin<P extends Plugin>(p: P): P;
877
+
878
+ /**
879
+ * Public type contract for `Cache.semantic / .asPlugin / .stats / .clear`
880
+ * (Adoption Roadmap #6; ADRs D249-D266).
881
+ *
882
+ * @public
883
+ */
884
+ interface CacheTTLConfig {
885
+ /** Default TTL applied to all entries. Format: `"1h" | "30m" | 86400 (seconds)`. */
886
+ readonly default: string | number;
887
+ /** Regex marking queries that must NEVER be cached (e.g. /weather|today|now/i). */
888
+ readonly exclude?: RegExp;
889
+ }
890
+ interface CachePersistenceOptions {
891
+ readonly backend: "memory" | "json";
892
+ /** Required when backend = "json". */
893
+ readonly dir?: string;
894
+ }
895
+ /**
896
+ * Embedder runtime shape — minimal subset of `EmbeddingRuntime` (D11) the
897
+ * Cache actually uses. Lets tests inject fake embedders without pulling
898
+ * the full memory subsystem.
899
+ */
900
+ interface CacheEmbedderRuntime {
901
+ readonly id: string;
902
+ readonly model: string;
903
+ readonly dimension: number;
904
+ embed(texts: ReadonlyArray<string>): Promise<number[][]>;
905
+ }
906
+ interface CacheSemanticOptions {
907
+ /** Embedder instance. REQUIRED in v1 — no autoselect (avoids surprise API calls). */
908
+ readonly embedder: CacheEmbedderRuntime;
909
+ /** Cosine distance threshold (0..2). Default 0.85; lower = stricter. */
910
+ readonly threshold?: number;
911
+ /** TTL config. Default `{ default: "1h" }`. */
912
+ readonly ttl?: CacheTTLConfig;
913
+ /** Multi-tenant namespace. Default `"global"`. */
914
+ readonly namespace?: string;
915
+ /** Default modelId attached to entries when caller doesn't override. */
916
+ readonly modelId?: string;
917
+ /** Max entries (LRU eviction). Default 1000. */
918
+ readonly maxEntries?: number;
919
+ /** Persistence backend. Default in-memory. */
920
+ readonly persistence?: CachePersistenceOptions;
921
+ }
922
+ interface CacheEntry {
923
+ readonly key: string;
924
+ readonly namespace: string;
925
+ readonly embedderId: string;
926
+ readonly modelId: string;
927
+ readonly prompt: string;
928
+ readonly response: string;
929
+ readonly vector: ReadonlyArray<number>;
930
+ readonly createdAt: number;
931
+ readonly expiresAt: number;
932
+ readonly accessedAt: number;
933
+ readonly accessCount: number;
934
+ }
935
+ interface CacheStats {
936
+ readonly entries: number;
937
+ readonly kvHits: number;
938
+ readonly semanticHits: number;
939
+ readonly misses: number;
940
+ readonly excluded: number;
941
+ readonly evicted: number;
942
+ readonly embedderFailures: number;
943
+ }
944
+ declare class CacheEmbedderError extends Error {
945
+ readonly name = "CacheEmbedderError";
946
+ readonly cause?: Error;
947
+ constructor(message: string, cause?: Error);
948
+ }
949
+ declare class CacheInvalidTtlError extends Error {
950
+ readonly input: string | number;
951
+ readonly name = "CacheInvalidTtlError";
952
+ constructor(input: string | number);
953
+ }
954
+
955
+ /**
956
+ * Public `Cache` class — semantic LLM response cache (Adoption Roadmap #6;
957
+ * ADRs D249-D266).
958
+ *
959
+ * Usage:
960
+ *
961
+ * import { Agent, Cache, definePlugin } from "@theokit/sdk";
962
+ *
963
+ * const cache = Cache.semantic({
964
+ * embedder: myEmbedderRuntime, // EmbeddingRuntime (D11)
965
+ * threshold: 0.85,
966
+ * ttl: { default: "1h", exclude: /weather|today|now/i },
967
+ * namespace: "my-app",
968
+ * modelId: "openai/gpt-4o-mini",
969
+ * });
970
+ *
971
+ * const agent = await Agent.create({
972
+ * model: { id: "openai/gpt-4o-mini" },
973
+ * plugins: [cache.asPlugin()],
974
+ * // ...
975
+ * });
976
+ *
977
+ * await agent.send("What is the capital of France?"); // miss → LLM
978
+ * await agent.send("Tell me the capital of France"); // semantic hit
979
+ *
980
+ * @public
981
+ */
982
+
983
+ declare class Cache {
984
+ private readonly embedder;
985
+ private readonly threshold;
986
+ private readonly ttl;
987
+ private readonly namespace;
988
+ private readonly modelId;
989
+ private readonly store;
990
+ private _plugin?;
991
+ private constructor();
992
+ static semantic(options: CacheSemanticOptions): Cache;
993
+ /**
994
+ * EC-4 absorbed: memoized so repeated `asPlugin()` calls return the SAME
995
+ * plugin descriptor — no duplicate hook registration.
996
+ */
997
+ asPlugin(): Plugin;
998
+ /**
999
+ * Explicit cache lookup — callers that want true LLM short-circuit
1000
+ * call this BEFORE `agent.send()`, then dispatch to the LLM only on miss.
1001
+ *
1002
+ * v1 plugin mode provides recall + context-inject (LLM still called).
1003
+ * v1.x will add transparent short-circuit via an agent-loop refactor.
1004
+ */
1005
+ consult(prompt: string): Promise<{
1006
+ hit: false;
1007
+ } | {
1008
+ hit: true;
1009
+ response: string;
1010
+ source: "kv" | "semantic";
1011
+ distance?: number;
1012
+ }>;
1013
+ /**
1014
+ * Explicit cache store — pair with `consult()` to manually feed the
1015
+ * cache after dispatching the LLM call yourself.
1016
+ */
1017
+ remember(prompt: string, response: string, opts?: {
1018
+ usedTools?: boolean;
1019
+ }): Promise<void>;
1020
+ /** Stats snapshot — primary observable for dogfood verification. */
1021
+ stats(): CacheStats;
1022
+ /** Clear all entries (and flush to disk if JSON backend). */
1023
+ clear(): Promise<void>;
1024
+ /** Force-evict expired entries. Returns count removed. */
1025
+ evictExpired(now?: number): number;
1026
+ }
1027
+
1028
+ /**
1029
+ * Spec accepted by {@link defineTool}. `inputSchema` is a Zod schema; the
1030
+ * `handler` argument type is inferred via `z.infer<T>` — no `as` casts.
1031
+ *
1032
+ * @public
1033
+ */
1034
+ interface DefineToolSpec<T extends ZodType> {
1035
+ /** Tool name surfaced to the LLM. Same constraints as {@link CustomTool.name}. */
1036
+ name: string;
1037
+ /** Description surfaced to the LLM. */
1038
+ description: string;
1039
+ /** Zod schema describing the input. Must be `z.object(...)` at the root for the LLM tool contract. */
1040
+ inputSchema: T;
1041
+ /** Handler invoked with the parsed input. Type is inferred via `z.infer<T>`. */
1042
+ handler: (input: z.infer<T>) => string | Promise<string>;
1043
+ }
1044
+ /**
1045
+ * Type-safe builder for {@link CustomTool}. Converts a Zod schema to JSON
1046
+ * Schema (for the LLM-facing `inputSchema` field), wraps the handler with a
1047
+ * runtime `schema.parse` step, and preserves type inference.
1048
+ *
1049
+ * Behaviour (ADR D24):
1050
+ * - JSON Schema conversion uses Zod 4's native `z.toJSONSchema` with
1051
+ * `unrepresentable: "any"` so transforms/refinements round-trip.
1052
+ * - Runtime parse failures throw `ZodError`; the SDK's tool-dispatch converts
1053
+ * them to `tool_result(isError)` with the Zod message.
1054
+ * - Handler signature is `(input: z.infer<T>)`, not `Record<string, unknown>`.
1055
+ * - `zod` loads lazily via `createRequire` — consumers who don't call
1056
+ * `defineTool` don't need `zod` installed.
1057
+ *
1058
+ * @public
1059
+ */
1060
+ declare function defineTool<T extends ZodType>(spec: DefineToolSpec<T>): CustomTool;
1061
+
1062
+ /**
1063
+ * Public `Handoff` class — factory for handoff descriptors (Adoption
1064
+ * Roadmap #4; ADRs D214-D229).
1065
+ *
1066
+ * Usage:
1067
+ *
1068
+ * import { Agent, Handoff } from "@theokit/sdk";
1069
+ *
1070
+ * const billing = await Agent.create({
1071
+ * name: "billing",
1072
+ * systemPrompt: "You handle billing questions.",
1073
+ * model: { id: "openai/gpt-4o-mini" },
1074
+ * apiKey: process.env.OPENROUTER_API_KEY,
1075
+ * });
1076
+ *
1077
+ * const triage = await Agent.create({
1078
+ * name: "triage",
1079
+ * systemPrompt: "Classify the user's intent and transfer to the right specialist.",
1080
+ * model: { id: "openai/gpt-4o-mini" },
1081
+ * apiKey: process.env.OPENROUTER_API_KEY,
1082
+ * handoffs: [
1083
+ * billing, // auto-wrapped as Handoff.create(billing)
1084
+ * Handoff.create(supportAgent, { inputFilter: redactCreditCards }),
1085
+ * ],
1086
+ * });
1087
+ *
1088
+ * @public
1089
+ */
1090
+
1091
+ /** Recommended system-prompt prefix for senders (D215 / EC-13). */
1092
+ declare const RECOMMENDED_HANDOFF_PROMPT_PREFIX: string;
1093
+ declare class Handoff {
1094
+ private constructor();
1095
+ /**
1096
+ * Build a `HandoffDescriptor` for a target agent. Wrap with custom options
1097
+ * (filter / inputType / callback / whitelist / etc); pass to
1098
+ * `Agent.create({ handoffs: [...] })`.
1099
+ *
1100
+ * Raw `SDKAgent` instances in `handoffs[]` are auto-wrapped by the runtime
1101
+ * — call `Handoff.create()` explicitly only when you need to customize.
1102
+ */
1103
+ static create<TInput extends ZodType = ZodType>(target: SDKAgent, options?: HandoffOptions<TInput>): HandoffDescriptor<TInput>;
1104
+ }
1105
+ /**
1106
+ * Imperative escape hatch (D225). Useful for tests / programmatic flows
1107
+ * that need deterministic handoff without LLM routing.
1108
+ *
1109
+ * NOTE: this is a STANDALONE helper rather than a method on `SDKAgent`
1110
+ * to avoid invasive refactor of the agent class. Behavior is identical
1111
+ * to invoking the corresponding synthetic tool would be.
1112
+ */
1113
+ declare function handoffTo(sender: SDKAgent, target: SDKAgent, message: string, options?: HandoffOptions): Promise<string>;
1114
+
1115
+ /**
1116
+ * Filesystem-backed implementation of {@link ConversationStorageAdapter}
1117
+ * (Production-Readiness #1, ADR D304).
1118
+ *
1119
+ * Default adapter when `AgentOptions.conversationStorage` is not provided.
1120
+ * Writes append-only JSONL to `<root>/.theokit/agents/<safeId>/messages.jsonl`,
1121
+ * preserving the pre-D303 byte-identical behavior (redaction D68 + JSONL
1122
+ * line granularity).
1123
+ *
1124
+ * Path safety: every conversationId flows through `sanitizeIdentifier` +
1125
+ * `safePathJoin` before touching disk. `deleteConversation` re-applies the
1126
+ * guard (EC-1) — without this the new `rm -rf` would escape via traversal.
1127
+ *
1128
+ * Listing: `listConversationIds` catches ENOENT (EC-2) so first-run deploys
1129
+ * without any `.theokit/agents/` directory return `[]` instead of crashing.
1130
+ *
1131
+ * @public
1132
+ */
1133
+
1134
+ interface FileSystemConversationStorageOptions {
1135
+ /** Root directory under which `.theokit/agents/<id>/` lives. Defaults to `process.cwd()`. */
1136
+ root?: string;
1137
+ }
1138
+ declare class FileSystemConversationStorage implements ConversationStorageAdapter {
1139
+ #private;
1140
+ constructor(opts?: FileSystemConversationStorageOptions);
1141
+ /** Exposed for tests + diagnostics. The path is sanitized at use sites. */
1142
+ get root(): string;
1143
+ getMessages(conversationId: string): Promise<readonly StoredMessage[]>;
1144
+ appendMessage(conversationId: string, message: StoredMessage): Promise<void>;
1145
+ deleteConversation(conversationId: string): Promise<void>;
1146
+ listConversationIds(opts?: {
1147
+ limit?: number;
1148
+ }): Promise<readonly string[]>;
1149
+ compact(conversationId: string, maxTurns: number): Promise<void>;
1150
+ dispose(): Promise<void>;
1151
+ }
1152
+
1153
+ /**
1154
+ * In-memory implementation of {@link ConversationStorageAdapter} (Production-Readiness #1, ADR D304).
1155
+ *
1156
+ * Intended for tests + ephemeral single-process dev/CLI usage. Holds messages
1157
+ * in a `Map<conversationId, StoredMessage[]>`. JavaScript's single-threaded
1158
+ * runtime makes per-conversation appends naturally atomic; no external mutex
1159
+ * needed.
1160
+ *
1161
+ * The adapter returns defensive copies from `getMessages` so callers cannot
1162
+ * mutate internal state by holding a reference to the returned array.
1163
+ *
1164
+ * @public
1165
+ */
1166
+
1167
+ declare class InMemoryConversationStorage implements ConversationStorageAdapter {
1168
+ #private;
1169
+ getMessages(conversationId: string): Promise<readonly StoredMessage[]>;
1170
+ appendMessage(conversationId: string, message: StoredMessage): Promise<void>;
1171
+ deleteConversation(conversationId: string): Promise<void>;
1172
+ listConversationIds(opts?: {
1173
+ limit?: number;
1174
+ }): Promise<readonly string[]>;
1175
+ dispose(): Promise<void>;
1176
+ }
1177
+
1178
+ /**
1179
+ * Public handle to an open memory index. Mirrors the internal `MemoryIndex`
1180
+ * contract structurally; defined here (NOT re-exported from internal/) so
1181
+ * the public DTS surface does not pull the internal/runtime cycle that
1182
+ * trips rollup-plugin-dts.
1183
+ *
1184
+ * @public
1185
+ */
1186
+ interface MemoryIndexHandle {
1187
+ sync(): Promise<{
1188
+ filesScanned: number;
1189
+ filesUpdated: number;
1190
+ chunksWritten: number;
1191
+ chunksEmbedded: number;
1192
+ }>;
1193
+ search(query: string, options?: {
1194
+ maxResults?: number;
1195
+ minScore?: number;
1196
+ sources?: ReadonlyArray<"memory" | "sessions" | "wiki">;
1197
+ }): Promise<ReadonlyArray<{
1198
+ path: string;
1199
+ startLine: number;
1200
+ endLine: number;
1201
+ score: number;
1202
+ textScore: number;
1203
+ vectorScore?: number;
1204
+ snippet: string;
1205
+ source: "memory" | "sessions" | "wiki";
1206
+ citation: string;
1207
+ }>>;
1208
+ status(): {
1209
+ backend: "fts-only" | "hybrid";
1210
+ filesIndexed: number;
1211
+ chunksIndexed: number;
1212
+ lastSyncMs?: number;
1213
+ };
1214
+ close(): Promise<void> | void;
1215
+ }
1216
+ /**
1217
+ * Public `Memory` namespace.
1218
+ *
1219
+ * Exposes operations users can run outside of `agent.send()` — most notably
1220
+ * the dreaming sweep (consolidation of facts via dedup + clustering).
1221
+ *
1222
+ * @public
1223
+ */
1224
+ interface DreamingSweepOptions {
1225
+ /** Workspace cwd holding `.theokit/memory/`. */
1226
+ cwd: string;
1227
+ /**
1228
+ * Embedding provider for semantic dedup + clustering. Required — dreaming
1229
+ * relies on real embeddings to score cosine similarity. Supported providers:
1230
+ * `"openai"`, `"mistral"`, `"openrouter"`, `"voyage"`, `"deepinfra"`,
1231
+ * `"ollama"` (local, ADR D183).
1232
+ */
1233
+ embedding: {
1234
+ provider: "openai" | "mistral" | "openrouter" | "voyage" | "deepinfra" | "ollama";
1235
+ model?: string;
1236
+ };
1237
+ /** Cosine-similarity threshold for the dedup phase. Default `0.95`. */
1238
+ dedupThreshold?: number;
1239
+ /** Cosine-similarity threshold for the clustering phase. Default `0.75`. */
1240
+ clusterThreshold?: number;
1241
+ }
1242
+ interface DreamingSweepResult {
1243
+ status: "ok" | "skipped" | "error";
1244
+ factsBefore: number;
1245
+ factsAfter: number;
1246
+ duplicatesRemoved: number;
1247
+ clustersCreated: number;
1248
+ notesWritten: number;
1249
+ }
1250
+ /**
1251
+ * Options for `Memory.openIndex`. Mirrors the internal `OpenIndexOptions`
1252
+ * but using only public types from the SDK surface.
1253
+ *
1254
+ * @public
1255
+ */
1256
+ interface OpenMemoryIndexOptions {
1257
+ /** Workspace cwd holding `.theokit/memory/`. */
1258
+ cwd: string;
1259
+ /** Override storage file path (SQLite) OR storage directory (Lance). */
1260
+ filePath?: string;
1261
+ /**
1262
+ * Embedding runtime — REQUIRED for `backend: "lance"`, optional for
1263
+ * `"sqlite-vec"` (when omitted, SQLite runs FTS-only without vector
1264
+ * recall).
1265
+ */
1266
+ embedding?: {
1267
+ provider: "openai" | "mistral" | "openrouter" | "voyage" | "deepinfra" | "ollama";
1268
+ model?: string;
1269
+ };
1270
+ /** Default `"sqlite-vec"`. Set to `"lance"` to opt into LanceDB (peer dep). */
1271
+ backend?: "sqlite-vec" | "lance";
1272
+ }
1273
+ declare const Memory: {
1274
+ /**
1275
+ * Open a memory index. Dispatches to SQLite-vec (default, zero deps) or
1276
+ * LanceDB (opt-in via `backend: "lance"`, requires `@lancedb/lancedb`
1277
+ * peer dep + an embedding runtime).
1278
+ *
1279
+ * Returns a `MemoryIndex` with `sync()`, `search(query, opts?)`,
1280
+ * `status()`, and `close()`. Use this when you want a direct index
1281
+ * handle outside of `Agent.create({ memory: ... })`.
1282
+ *
1283
+ * @throws ConfigurationError({code:"invalid_memory_backend"}) for typos
1284
+ * like `"lancedb"`.
1285
+ * @throws ConfigurationError({code:"lance_requires_embedding"}) when
1286
+ * `backend: "lance"` is requested without `embedding`.
1287
+ * @throws ConfigurationError({code:"lance_backend_unavailable"}) when
1288
+ * `backend: "lance"` is requested but the peer dep is absent.
1289
+ *
1290
+ * @public
1291
+ */
1292
+ openIndex(opts: OpenMemoryIndexOptions): Promise<MemoryIndexHandle>;
1293
+ /**
1294
+ * Run a dreaming sweep: dedup near-duplicate facts, cluster thematically
1295
+ * related ones, and write a consolidated note + diary entry.
1296
+ *
1297
+ * @public
1298
+ */
1299
+ runDreamingSweep(opts: DreamingSweepOptions): Promise<DreamingSweepResult>;
1300
+ };
1301
+
1302
+ /**
1303
+ * Runtime helpers for `MemoryAdapter` (T1.1, ADR D141).
1304
+ *
1305
+ * Kept separate from `types/memory-adapter.ts` so the types module
1306
+ * stays import-free of runtime code (dep-cruise rule
1307
+ * `types-dont-import-runtime`). Adapter authors call `mkMemoryId` to
1308
+ * construct a branded id and `extractRawId` to unwrap with cross-adapter
1309
+ * safety (EC-B).
1310
+ *
1311
+ * @public
1312
+ */
1313
+
1314
+ /**
1315
+ * Construct a branded `MemoryId` for an adapter. Embeds the adapter
1316
+ * identifier so `extractRawId` can reject ids minted by other adapters.
1317
+ *
1318
+ * @public
1319
+ */
1320
+ declare function mkMemoryId(adapterId: string, rawId: string): MemoryId;
1321
+ /**
1322
+ * Extract the raw provider id from a `MemoryId`, enforcing that the
1323
+ * prefix matches `expectedAdapterId`. Throws `MemoryAdapterError(code:
1324
+ * "invalid_input")` on mismatch — prevents `mem0.delete(supermemoryId)`
1325
+ * from accidentally deleting unrelated data (EC-B).
1326
+ *
1327
+ * @public
1328
+ */
1329
+ declare function extractRawId(id: MemoryId, expectedAdapterId: string): string;
1330
+
1331
+ /**
1332
+ * Options for {@link migrateSqliteToLance}.
1333
+ *
1334
+ * @public
1335
+ */
1336
+ interface MigrateOptions {
1337
+ cwd: string;
1338
+ dryRun?: boolean;
1339
+ batchSize?: number;
1340
+ logger?: (msg: string) => void;
1341
+ }
1342
+ /**
1343
+ * Outcome of {@link migrateSqliteToLance}.
1344
+ *
1345
+ * @public
1346
+ */
1347
+ interface MigrateResult {
1348
+ countSqlite: number;
1349
+ countLance: number;
1350
+ validated: boolean;
1351
+ sampleComparisons: ReadonlyArray<{
1352
+ id: string;
1353
+ match: boolean;
1354
+ }>;
1355
+ lancePath: string;
1356
+ committed: boolean;
1357
+ }
1358
+ /**
1359
+ * Migrate the Memory index from SQLite to LanceDB. ADR D44.
1360
+ *
1361
+ * @public
1362
+ */
1363
+ declare function migrateSqliteToLance(options: MigrateOptions): Promise<MigrateResult>;
1364
+
1365
+ /**
1366
+ * Public security namespace (T2.1, ADR D68).
1367
+ *
1368
+ * Two entry points:
1369
+ *
1370
+ * - `Security.redact(text, opts?)` — apply the canonical redactor to
1371
+ * arbitrary text. Useful when a consumer app (or example) writes its
1372
+ * own logs / metrics / paste-share artifacts that the SDK's wired
1373
+ * sinks (error metadata, telemetry, transcript, migration) don't
1374
+ * cover.
1375
+ * - `Security.addPattern(re)` — register a custom credential pattern
1376
+ * on top of the 12 builtins (OpenAI, Anthropic, GitHub PAT classic +
1377
+ * fine, GitLab, AWS, Google, Slack, Sentry, Stripe live + restricted)
1378
+ * plus the parametric `key=value` + `Bearer <token>` matchers.
1379
+ *
1380
+ * Redaction is ON by default. Disable with `THEOKIT_REDACT_SECRETS=false`
1381
+ * (a warning is emitted on stderr so the operator knows the SDK process
1382
+ * is vulnerable). The env var is snapshotted at module init — runtime
1383
+ * mutation cannot disable it, defending against prompt injection that
1384
+ * tries to flip the flag mid-run.
1385
+ */
1386
+ declare class Security {
1387
+ private constructor();
1388
+ /**
1389
+ * Redact known credential patterns from `text` and return the masked
1390
+ * string. Use this at any consumer output boundary the SDK does not
1391
+ * directly own (custom stdout loggers, app-level metrics, debug-share
1392
+ * artifacts, etc.).
1393
+ *
1394
+ * Coerces non-strings (objects via JSON.stringify, null/undefined → "").
1395
+ * Two-bucket masking: tokens shorter than 18 chars → `***`; longer
1396
+ * tokens preserve `prefix...suffix` for debuggability without revealing
1397
+ * the secret middle.
1398
+ *
1399
+ * @param text - The value to redact. Strings, objects, primitives all OK.
1400
+ * @param opts.codeFile - When `true`, skips the parametric `key=value`
1401
+ * matcher so file content like `.env.example` placeholders is left
1402
+ * intact. Built-in pattern matches still apply.
1403
+ *
1404
+ * @example
1405
+ * console.log(`[bot] received: ${Security.redact(userText)}`);
1406
+ * // → "[bot] received: please remember sk-abc...xyz1"
1407
+ */
1408
+ static redact(text: unknown, opts?: {
1409
+ codeFile?: boolean;
1410
+ }): string;
1411
+ /**
1412
+ * Register a custom redaction pattern. Additive — built-in patterns
1413
+ * (OpenAI, Anthropic, GitHub PAT, AWS, etc.) cannot be removed.
1414
+ *
1415
+ * @param re - RegExp with `/g` flag. Throws if `/g` is missing
1416
+ * (without /g, only first match is replaced and the rest
1417
+ * leaks).
1418
+ *
1419
+ * Process-global mutable state. The SDK is designed for single-tenant
1420
+ * processes (Theo PaaS user runtime, local CLI). Multi-tenant
1421
+ * deployments running multiple SDK consumers in the same Node process
1422
+ * share this list — patterns added by tenant A apply to tenant B's
1423
+ * redactions. Acceptable for v1; future isolate-aware refactor would
1424
+ * thread patterns through a context if needed.
1425
+ *
1426
+ * @example
1427
+ * Security.addPattern(/MYORG-[A-Z0-9]{32}/g);
1428
+ * // → text containing "MYORG-AAAA...AAAA" now masks like a builtin.
1429
+ */
1430
+ static addPattern(re: RegExp): void;
1431
+ }
1432
+
1433
+ /**
1434
+ * Public type contract for the Task observability registry (ADRs D361-D374).
1435
+ *
1436
+ * Tasks are an opt-in observability layer over async work in the SDK
1437
+ * (`Agent.send`, `Agent.batch`, `Workflow.run`, `Cron` fires). They have
1438
+ * a closed 5-state lifecycle (D362), discriminated events (D366), and a
1439
+ * pluggable store (D364). The `Task` facade in `task.ts` is the public
1440
+ * surface; consumers import these types from `@theokit/sdk`.
1441
+ *
1442
+ * @public
1443
+ */
1444
+ /**
1445
+ * Closed enum of the 5 lifecycle states (D362).
1446
+ *
1447
+ * Transitions are acyclic:
1448
+ * queued → running → (finished | error | cancelled)
1449
+ * queued → cancelled (direct, no run started)
1450
+ */
1451
+ type TaskState = "queued" | "running" | "finished" | "error" | "cancelled";
1452
+ /** Discriminator of the runtime that produced a task (D374). */
1453
+ type TaskKind = "run" | "batch" | "workflow" | "cron" | "custom";
1454
+ /** Discriminated union of task lifecycle events (D366). */
1455
+ type TaskEvent = {
1456
+ readonly type: "submitted";
1457
+ readonly taskId: string;
1458
+ readonly kind: TaskKind;
1459
+ readonly submittedAt: number;
1460
+ readonly meta?: Record<string, unknown>;
1461
+ /** D372 — flag set on the first yielded event when the ring buffer was at cap. */
1462
+ readonly truncated?: boolean;
1463
+ } | {
1464
+ readonly type: "started";
1465
+ readonly taskId: string;
1466
+ readonly startedAt: number;
1467
+ } | {
1468
+ readonly type: "progress";
1469
+ readonly taskId: string;
1470
+ readonly at: number;
1471
+ readonly payload: unknown;
1472
+ } | {
1473
+ readonly type: "finished";
1474
+ readonly taskId: string;
1475
+ readonly finishedAt: number;
1476
+ readonly result: unknown;
1477
+ } | {
1478
+ readonly type: "errored";
1479
+ readonly taskId: string;
1480
+ readonly erroredAt: number;
1481
+ readonly error: {
1482
+ readonly code: string;
1483
+ readonly message: string;
1484
+ };
1485
+ } | {
1486
+ readonly type: "cancelled";
1487
+ readonly taskId: string;
1488
+ readonly cancelledAt: number;
1489
+ readonly reason?: string;
1490
+ };
1491
+ /** Public read-only view of a task entry in the registry. */
1492
+ interface TaskHandle {
1493
+ readonly id: string;
1494
+ readonly kind: TaskKind;
1495
+ readonly state: TaskState;
1496
+ readonly submittedAt: number;
1497
+ readonly startedAt?: number;
1498
+ readonly finishedAt?: number;
1499
+ readonly cancelledAt?: number;
1500
+ readonly erroredAt?: number;
1501
+ readonly result?: unknown;
1502
+ readonly error?: {
1503
+ readonly code: string;
1504
+ readonly message: string;
1505
+ };
1506
+ readonly meta?: Record<string, unknown>;
1507
+ /**
1508
+ * EC-7 — cross-process best-effort cancel flag. Set by CLI
1509
+ * `theokit tasks cancel` via JsonFileTaskStore. The owning process
1510
+ * polls at checkpoints and honors via AbortController. Always
1511
+ * `undefined` for in-process cancel paths (which go directly through
1512
+ * AbortController).
1513
+ */
1514
+ readonly cancelRequested?: boolean;
1515
+ }
1516
+ /** Query filter for `Task.list`. */
1517
+ interface TaskFilter {
1518
+ readonly state?: TaskState | readonly TaskState[];
1519
+ readonly kind?: TaskKind | readonly TaskKind[];
1520
+ readonly submittedAfter?: number;
1521
+ readonly submittedBefore?: number;
1522
+ /** Defaults to 100. JsonFileTaskStore hard-caps loaded entries at 256 (D364). */
1523
+ readonly limit?: number;
1524
+ }
1525
+ /** Options for `Task.submit`. */
1526
+ interface TaskSubmitOptions {
1527
+ /**
1528
+ * Optional user-supplied ID. Must match grammar `^[a-z0-9][a-z0-9_-]*$`
1529
+ * and MUST NOT start with the reserved prefixes `wf-` / `b-` / `cron-`
1530
+ * (D368, EC-5). When omitted, `crypto.randomUUID()` is used.
1531
+ */
1532
+ readonly id?: string;
1533
+ readonly meta?: Record<string, unknown>;
1534
+ /**
1535
+ * Optional caller-provided AbortSignal. If already aborted at submit
1536
+ * time, the registry short-circuits to `cancelled` without acquiring
1537
+ * a semaphore slot (EC-4).
1538
+ */
1539
+ readonly signal?: AbortSignal;
1540
+ }
1541
+ /** Options shape for `TaskStore` factory (D364). */
1542
+ type TaskStoreOptions = {
1543
+ readonly backend: "memory";
1544
+ } | {
1545
+ readonly backend: "json";
1546
+ readonly dir: string;
1547
+ };
1548
+ /** Result of `Task.cancel` (D365 — idempotent). */
1549
+ interface TaskCancelResult {
1550
+ readonly cancelled: boolean;
1551
+ readonly alreadyTerminal: boolean;
1552
+ }
1553
+ /**
1554
+ * Validates a task ID against the public grammar + reserved prefixes.
1555
+ * Throws `InvalidTaskIdError` from `../errors.js` on rejection.
1556
+ *
1557
+ * Adapter callers (workflow/batch/cron) MUST set `allowReserved: true`
1558
+ * to register their own IDs; user-facing surfaces (`Task.submit`,
1559
+ * `agent.send({ task: { id } })`) leave it false.
1560
+ */
1561
+ declare function isValidTaskId(id: string, allowReserved: boolean): boolean;
1562
+ /** Re-exported for adapter implementations + tests. */
1563
+ declare const TASK_RESERVED_PREFIXES: readonly string[];
1564
+
1565
+ /**
1566
+ * `Task` — observable async work registry (Adoption Roadmap gap #2,
1567
+ * ADRs D361-D374).
1568
+ *
1569
+ * Static facade delegating to the in-process `TaskRegistry` singleton.
1570
+ * The lifecycle of any task is the 5-state machine `queued | running |
1571
+ * finished | error | cancelled` (D362). Wrapping `Agent.send` /
1572
+ * `Agent.batch` / `Workflow.run` / `Cron` fires is opt-in via the
1573
+ * `{ task: true }` option on each (D363).
1574
+ *
1575
+ * @public
1576
+ */
1577
+
1578
+ interface TaskWorkContext {
1579
+ readonly signal: AbortSignal;
1580
+ emit(payload: unknown): void;
1581
+ }
1582
+ type TaskWorkFn<T> = (ctx: TaskWorkContext) => Promise<T> | T;
1583
+ /**
1584
+ * Registry-level configuration. May only be applied BEFORE the first
1585
+ * `Task.submit` of the process — see EC-13. Subsequent calls emit a
1586
+ * single stderr line and become no-ops.
1587
+ */
1588
+ interface TaskConfigureOptions {
1589
+ readonly store?: TaskStoreOptions;
1590
+ readonly maxConcurrent?: number;
1591
+ readonly retentionMs?: number;
1592
+ }
1593
+ declare class Task {
1594
+ private constructor();
1595
+ /**
1596
+ * Configure the registry. **Must be called before the first `submit`**
1597
+ * (EC-13). Available knobs: pluggable store (D364), concurrency cap
1598
+ * (D369), and retention (D373).
1599
+ */
1600
+ static configure(opts: TaskConfigureOptions): void;
1601
+ /**
1602
+ * Submit a unit of asynchronous work to the registry.
1603
+ *
1604
+ * The `work` function receives `{ signal, emit }` — `signal` is the
1605
+ * AbortSignal honored on cancel; `emit(payload)` produces a
1606
+ * `progress` event observable via `Task.subscribe`.
1607
+ *
1608
+ * Returns a `TaskHandle` in `state: "queued"`. Subsequent state
1609
+ * transitions are observable via `Task.subscribe(handle.id)` OR
1610
+ * polled via `Task.get(handle.id)`.
1611
+ *
1612
+ * **Idempotency (D367):** submitting twice with the same `id` returns
1613
+ * the existing handle without re-invoking work.
1614
+ *
1615
+ * **Grammar (D368):** user-supplied ids must match
1616
+ * `^[a-z0-9][a-z0-9_-]*$` and must not start with reserved prefixes
1617
+ * `wf-` / `b-` / `cron-`. Otherwise `InvalidTaskIdError` is thrown.
1618
+ *
1619
+ * **Pre-aborted signal (EC-4):** if `options.signal` is already
1620
+ * aborted, the task short-circuits to `cancelled` without acquiring
1621
+ * a semaphore slot and without invoking `work`.
1622
+ */
1623
+ static submit<T>(kind: TaskKind, work: TaskWorkFn<T>, options?: TaskSubmitOptions): Promise<TaskHandle>;
1624
+ /** Returns matching handles, capped at `filter.limit ?? 100`. */
1625
+ static list(filter?: TaskFilter): Promise<TaskHandle[]>;
1626
+ /** Returns a single handle by id, or `undefined` if unknown / evicted. */
1627
+ static get(id: string): Promise<TaskHandle | undefined>;
1628
+ /**
1629
+ * Idempotent cancel (D365). Returns:
1630
+ * - `{ cancelled: true, alreadyTerminal: false }` — transitioned
1631
+ * queued/running task to `cancelled`.
1632
+ * - `{ cancelled: false, alreadyTerminal: true }` — task already
1633
+ * terminal.
1634
+ * - `{ cancelled: false, alreadyTerminal: false }` — task unknown.
1635
+ *
1636
+ * Never throws.
1637
+ */
1638
+ static cancel(id: string, reason?: string): Promise<TaskCancelResult>;
1639
+ /**
1640
+ * Subscribe to a task's event stream. The returned `AsyncIterable<TaskEvent>`
1641
+ * starts by replaying buffered events (ring buffer cap 64, D372) and
1642
+ * then yields live events until a terminal event (finished / errored
1643
+ * / cancelled) is emitted, at which point it closes automatically.
1644
+ *
1645
+ * Calling `.return()` on the iterator (or `break` in a `for await`)
1646
+ * cleans up the subscriber callback (EC-10).
1647
+ *
1648
+ * Throws `TaskNotFoundError` if the id is unknown or has been evicted.
1649
+ */
1650
+ static subscribe(id: string): AsyncIterable<TaskEvent>;
1651
+ }
1652
+
1653
+ /**
1654
+ * Account-level user info returned by `Theokit.me()`.
1655
+ *
1656
+ * @public
1657
+ */
1658
+ interface SDKUser {
1659
+ apiKeyName: string;
1660
+ userEmail?: string;
1661
+ createdAt: string;
1662
+ }
1663
+ /**
1664
+ * Per-model parameter definition discovered from `Theokit.models.list()`.
1665
+ *
1666
+ * @public
1667
+ */
1668
+ interface ModelParameterDefinition {
1669
+ id: string;
1670
+ displayName?: string;
1671
+ values: Array<{
1672
+ value: string;
1673
+ displayName?: string;
1674
+ }>;
1675
+ }
1676
+ /**
1677
+ * Preset variant for a model — pre-filled parameter combinations.
1678
+ *
1679
+ * @public
1680
+ */
1681
+ interface ModelVariant {
1682
+ params: Array<{
1683
+ id: string;
1684
+ value: string;
1685
+ }>;
1686
+ displayName: string;
1687
+ description?: string;
1688
+ isDefault?: boolean;
1689
+ }
1690
+ /**
1691
+ * Single model entry in the catalog.
1692
+ *
1693
+ * @public
1694
+ */
1695
+ interface ModelListItem {
1696
+ id: string;
1697
+ /** Short, plain-text model name. Mirrors `displayName` for typical SDKs. */
1698
+ name?: string;
1699
+ displayName: string;
1700
+ description?: string;
1701
+ parameters?: ModelParameterDefinition[];
1702
+ variants?: ModelVariant[];
1703
+ }
1704
+ /** @public */
1705
+ type SDKModel = ModelListItem;
1706
+ /**
1707
+ * GitHub repository connected to the team. Cloud-only.
1708
+ *
1709
+ * @public
1710
+ */
1711
+ interface SDKRepository {
1712
+ url: string;
1713
+ }
1714
+
1715
+ /**
1716
+ * Options shared by every `Theokit.*` request.
1717
+ *
1718
+ * @public
1719
+ */
1720
+ interface TheokitRequestOptions {
1721
+ /** Override the `THEOKIT_API_KEY` env var for this call. */
1722
+ apiKey?: string;
1723
+ /**
1724
+ * Target a specific provider for catalog reads. When set to a provider
1725
+ * with `authType: "none"` (e.g. `"ollama"`, `"lmstudio"`, `"llamacpp"`),
1726
+ * `Theokit.models.list({ provider })` reads from the provider's local
1727
+ * `/v1/models` endpoint instead of the TheoCloud catalog. ADR D184.
1728
+ *
1729
+ * @public
1730
+ */
1731
+ provider?: string;
1732
+ }
1733
+ /**
1734
+ * Account-level and catalog reads. All methods accept an optional `apiKey`
1735
+ * and otherwise fall back to the `THEOKIT_API_KEY` environment variable.
1736
+ *
1737
+ * @public
1738
+ */
1739
+ declare class Theokit {
1740
+ private constructor();
1741
+ /**
1742
+ * Return the user behind the current API key.
1743
+ *
1744
+ * @public
1745
+ */
1746
+ static me(options?: TheokitRequestOptions): Promise<SDKUser>;
1747
+ /**
1748
+ * Model catalog reads.
1749
+ *
1750
+ * @public
1751
+ */
1752
+ static readonly models: {
1753
+ list: (options?: TheokitRequestOptions) => Promise<SDKModel[]>;
1754
+ };
1755
+ /**
1756
+ * Connected GitHub repositories for the calling user's team. Cloud only.
1757
+ *
1758
+ * @public
1759
+ */
1760
+ static readonly repositories: {
1761
+ list: (options?: TheokitRequestOptions) => Promise<SDKRepository[]>;
1762
+ };
1763
+ /**
1764
+ * Provider catalog. Lists every provider known to the platform, including
1765
+ * plugin-registered ones, with capability and availability metadata.
1766
+ *
1767
+ * @public
1768
+ */
1769
+ static readonly providers: {
1770
+ list: (options?: TheokitRequestOptions) => Promise<SDKProvider[]>;
1771
+ };
1772
+ /**
1773
+ * Local introspection of bundled SDK assets (ADR D201). Unlike the
1774
+ * cloud-catalog `providers.list()` (which hits the TheoCloud HTTP API),
1775
+ * `inspect.*` reads the SDK's own bundled registries — useful for
1776
+ * tooling (e.g. `@theokit/cli`'s `theokit inspect`) that needs to know
1777
+ * what's available WITHOUT a network round-trip.
1778
+ *
1779
+ * @public
1780
+ */
1781
+ static readonly inspect: {
1782
+ builtinProviders: () => Array<{
1783
+ readonly name: string;
1784
+ readonly apiMode: string;
1785
+ readonly authType: string;
1786
+ readonly baseUrl: string;
1787
+ readonly aliases?: ReadonlyArray<string>;
1788
+ readonly envVars: ReadonlyArray<string>;
1789
+ }>;
1790
+ embeddingAdapters: () => Array<{
1791
+ readonly id: string;
1792
+ readonly transport: string;
1793
+ readonly defaultModel: string;
1794
+ }>;
1795
+ };
1796
+ }
1797
+
1798
+ /**
1799
+ * Public types for ShareGPT trajectory export (ADR D139).
1800
+ *
1801
+ * Output format for fine-tuning datasets — consumed by HuggingFace, Axolotl,
1802
+ * LLaMA-Factory, and most modern fine-tuning toolchains. Pure data shape;
1803
+ * no runtime dependency.
1804
+ *
1805
+ * @public
1806
+ */
1807
+ /**
1808
+ * One ShareGPT message in a conversation. `from` identifies the role and
1809
+ * `value` carries the textual content. Tool calls live in `tool_calls`
1810
+ * (assistant-only) and tool results re-enter as `from: "tool"` entries.
1811
+ *
1812
+ * @public
1813
+ */
1814
+ interface ShareGptMessage {
1815
+ /** "human" for user, "gpt" for assistant, "tool" for tool result, "system" for system. */
1816
+ from: "human" | "gpt" | "tool" | "system";
1817
+ /** The message text. Empty string is valid (preserves turn boundary). */
1818
+ value: string;
1819
+ /** Optional tool calls — only emitted when `from === "gpt"`. */
1820
+ tool_calls?: Array<{
1821
+ name: string;
1822
+ arguments: Record<string, unknown>;
1823
+ }>;
1824
+ }
1825
+ /**
1826
+ * One full ShareGPT-format trajectory — a single conversation plus
1827
+ * metadata. JSONL-friendly (one trajectory per line when serialized).
1828
+ *
1829
+ * @public
1830
+ */
1831
+ interface ShareGptTrajectory {
1832
+ conversations: ShareGptMessage[];
1833
+ metadata?: {
1834
+ model?: string;
1835
+ timestamp: string;
1836
+ durationMs: number;
1837
+ promptIndex: number;
1838
+ };
1839
+ /** `true` when the source `BatchResult.ok === true`. Always `true` in current shape. */
1840
+ completed: boolean;
1841
+ /** Token usage when surfaced by the underlying RunResult (provider-specific). */
1842
+ usage?: {
1843
+ inputTokens: number;
1844
+ outputTokens: number;
1845
+ };
1846
+ }
1847
+
1848
+ /**
1849
+ * `toShareGptTrajectory` — opt-in BatchResult → ShareGPT converter (ADR D139).
1850
+ *
1851
+ * Pure transformation. Returns `null` for failed results so callers can
1852
+ * filter via `.map(toShareGptTrajectory).filter(Boolean)`. Tool calls and
1853
+ * tool results are preserved when an SDKMessage trace is provided; otherwise
1854
+ * a minimal `human → gpt` trajectory is emitted from the final text.
1855
+ *
1856
+ * @public
1857
+ */
1858
+
1859
+ /**
1860
+ * Convert a successful `BatchResult` to ShareGPT-format trajectory.
1861
+ *
1862
+ * Behavior:
1863
+ * - `result.ok === false` → returns `null` (EC-11).
1864
+ * - First entry is always `{from: "human", value: result.prompt}`.
1865
+ * - When `options.messages` is supplied, each SDKMessage maps to one or
1866
+ * more ShareGPT entries (assistant text → gpt, tool_use → gpt + tool).
1867
+ * - Without `options.messages`, fall back to a single `{from: "gpt"}`
1868
+ * entry carrying `result.result.result` (the final text) when present.
1869
+ * - Malformed message entries are silently skipped (EC-F / EC-14).
1870
+ *
1871
+ * @public
1872
+ */
1873
+ declare function toShareGptTrajectory(result: BatchResult, options?: {
1874
+ messages?: SDKMessage[];
1875
+ model?: string;
1876
+ }): ShareGptTrajectory | null;
1877
+
1878
+ export { Agent, AgentBuilder, AgentDefinition, type AgentFactory, AgentOperationOptions, AgentOptions, type AgentPromptResult, type AgentRegistryOptions, type BatchItem, type BatchOptions, type BatchProgress, type BatchResult, Budget, BudgetHandle, BudgetOptions, BudgetSnapshot, Cache, CacheEmbedderError, type CacheEmbedderRuntime, type CacheEntry, CacheInvalidTtlError, type CachePersistenceOptions, type CacheSemanticOptions, type CacheStats, type CacheTTLConfig, CloudOptions, ContextSettings, ConversationStorageAdapter, CustomTool, type DeepPartial, type DefineToolSpec, type DreamingSweepOptions, type DreamingSweepResult, type EvictReason, FileSystemConversationStorage, GenerateObjectError, type GenerateObjectOptions, type GenerateObjectResult, GetAgentOptions, GetRunOptions, Handoff, HandoffDescriptor, HandoffOptions, type HookName, InMemoryConversationStorage, ListAgentsOptions, ListResult, ListRunsOptions, LiveAgentRegistry, LocalOptions, McpServerConfig, Memory, MemoryId, MemorySettings, type MigrateOptions, type MigrateResult, type ModelListItem, type ModelParameterDefinition, ModelSelection, type ModelVariant, type Plugin, type PluginContext, PluginsSettings, type PreToolCallContext, type PreToolCallDecision, type ProviderProfile, ProviderRoutingSettings, RECOMMENDED_HANDOFF_PROMPT_PREFIX, Run, RunResult, SDKAgent, SDKAgentInfo, SDKMessage, type SDKModel, SDKProvider, type SDKRepository, type SDKUser, Security, type ShareGptMessage, type ShareGptTrajectory, SkillsSettings, StoredMessage, StreamObjectError, type StreamObjectEvent, type StreamObjectOptions, SystemPromptResolver, TASK_RESERVED_PREFIXES, Task, type TaskCancelResult, type TaskConfigureOptions, type TaskEvent, type TaskFilter, type TaskHandle, type TaskKind, type TaskState, type TaskStoreOptions, type TaskSubmitOptions, type TaskWorkContext, type TaskWorkFn, Theokit, TheokitAgentError, type TheokitRequestOptions, UsageAccumulator, chargeAndCheckThresholds, computeCost, createAgentFactory, definePlugin, defineTool, extractRawId, getPricingEntry, handoffTo, inferApiMode, isValidTaskId, migrateSqliteToLance, mkMemoryId, normalizeUsage, preflightCheck, toShareGptTrajectory };