@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,2181 @@
1
+ import { ZodType } from 'zod';
2
+
3
+ /**
4
+ * Public event types emitted by {@link SDKAgent.runUntil} (ADRs D115-D117).
5
+ *
6
+ * Discriminated union by `type` field so consumers can `switch (event.type)`
7
+ * with full TypeScript exhaustiveness. Mirrors the
8
+ * {@link import("../stream-object.js").StreamObjectEvent} pattern (ADR D39).
9
+ *
10
+ * @public
11
+ */
12
+ /**
13
+ * Single event emitted while iterating a goal-driven loop. Five variants:
14
+ *
15
+ * - `turn_start` — the agent is about to invoke `send()`. Emitted once
16
+ * per turn.
17
+ * - `agent_response` — the agent's `send()` resolved; carries the text
18
+ * reply.
19
+ * - `judge_verdict` — the auxiliary judge model evaluated the response.
20
+ * `parseFailed: true` indicates the judge returned a malformed reply
21
+ * (fail-safe verdict = `continue`, see ADR D121).
22
+ * - `continuation` — the judge ruled `continue`; carries the prompt that
23
+ * was sent on THIS turn (i.e., the input that produced the agent
24
+ * response just yielded). Useful for consumers who want to audit the
25
+ * exact continuation message that drove each iteration. The prompt
26
+ * for the NEXT turn is composed lazily at the start of that turn
27
+ * from the latest `agent_response.content`.
28
+ * - `status_change` — transition of the overall goal state. Always
29
+ * emitted once at start (`active`) and once at end
30
+ * (`completed | failed | paused`).
31
+ *
32
+ * @public
33
+ */
34
+ type GoalEvent = {
35
+ type: "turn_start";
36
+ turn: number;
37
+ goal: string;
38
+ } | {
39
+ type: "agent_response";
40
+ turn: number;
41
+ content: string;
42
+ } | {
43
+ type: "judge_verdict";
44
+ turn: number;
45
+ verdict: "done" | "continue" | "skipped";
46
+ reason: string;
47
+ parseFailed: boolean;
48
+ } | {
49
+ type: "continuation";
50
+ turn: number;
51
+ prompt: string;
52
+ } | {
53
+ type: "status_change";
54
+ status: "active" | "paused" | "completed" | "failed";
55
+ reason: string;
56
+ };
57
+ /**
58
+ * Return value of the `runUntil` async generator. Consumer reads via
59
+ * `const { value } = await gen.next()` (when `done: true`).
60
+ *
61
+ * @public
62
+ */
63
+ interface GoalResult {
64
+ status: "completed" | "failed" | "paused";
65
+ turnsUsed: number;
66
+ finalResponse: string | undefined;
67
+ }
68
+ /**
69
+ * Return type of {@link import("../internal/runtime/local-agent.js").LocalAgent.runUntil}.
70
+ * Extracted so the LocalAgent method signature stays a single line (G8 LoC budget).
71
+ *
72
+ * @public
73
+ */
74
+ type RunUntilIterator = AsyncGenerator<GoalEvent, GoalResult, void>;
75
+ /**
76
+ * Per-call configuration for `Agent.runUntil`.
77
+ *
78
+ * @public
79
+ */
80
+ interface GoalOptions {
81
+ /** Hard cap on iterations. Default `20`. */
82
+ maxTurns?: number;
83
+ /** Bail after N consecutive judge parse failures. Default `3` (ADR D121). */
84
+ maxConsecutiveJudgeFailures?: number;
85
+ /** Judge model identifier. Default `"openai/gpt-4o-mini"` (ADR D119). */
86
+ judgeModel?: string;
87
+ /** Override env for the judge auxiliary agent. Default `OPENROUTER_API_KEY` (EC-A). */
88
+ judgeApiKey?: string;
89
+ /** Optional subgoals fed to the judge prompt. */
90
+ subgoals?: string[];
91
+ /**
92
+ * Cancel mid-loop via `AbortController.signal`. The generator yields
93
+ * a `status_change: paused` event and returns at the next turn
94
+ * boundary (ADR D117).
95
+ */
96
+ signal?: AbortSignal;
97
+ }
98
+
99
+ /**
100
+ * Pluggable persistence for conversation history (Production-Readiness #1, ADRs D303-D306).
101
+ *
102
+ * The default {@link FileSystemConversationStorage} writes append-only JSONL
103
+ * to `<cwd>/.theokit/agents/<id>/messages.jsonl`. Custom adapters back the
104
+ * SDK against Postgres, Redis, Durable Objects, or any other store — required
105
+ * for serverless deploys (Vercel, Cloudflare Workers) and multi-host setups
106
+ * (K8s replicas, TheoCloud) where the filesystem is ephemeral or not shared.
107
+ *
108
+ * @public
109
+ */
110
+ /**
111
+ * Persisted message envelope used by {@link ConversationStorageAdapter}.
112
+ *
113
+ * The shape is deliberately narrower than the full {@link SDKMessage} variant
114
+ * tree — only durable content survives. `role` covers all message origins the
115
+ * SDK persists today (user/assistant) plus the forward-compat slots for
116
+ * tool-shaped messages (ADR D310 / EC-10).
117
+ *
118
+ * @public
119
+ */
120
+ interface StoredMessage {
121
+ /** Origin of the message. `tool_call` / `tool_result` reserved for forward compat. */
122
+ role: "user" | "assistant" | "system" | "tool_call" | "tool_result";
123
+ /** UTF-8 payload. May be empty string (e.g., a tool with no return value). */
124
+ content: string;
125
+ /** Optional epoch-ms timestamp. Implementations MAY default to `Date.now()` on append. */
126
+ at?: number;
127
+ }
128
+ /**
129
+ * Pluggable conversation persistence contract.
130
+ *
131
+ * Implementations MUST be safe under concurrent append from a single process
132
+ * — the SDK runtime serializes per-(agent,cwd) but adapters serving multiple
133
+ * processes are responsible for their own atomicity.
134
+ *
135
+ * All methods return `Promise<>` even for synchronous backends (in-memory).
136
+ * Polymorphism uniformity beats the ~1μs microtask cost (ADR D306).
137
+ *
138
+ * @public
139
+ */
140
+ interface ConversationStorageAdapter {
141
+ /**
142
+ * Return the full message history for a conversation, in insertion order.
143
+ * MUST return `[]` (not throw) when the conversation does not exist.
144
+ */
145
+ getMessages(conversationId: string): Promise<readonly StoredMessage[]>;
146
+ /**
147
+ * Append a single message to the conversation.
148
+ * MUST be atomic — concurrent appends MUST NOT corrupt the log.
149
+ * MUST create the conversation lazily if it does not exist.
150
+ */
151
+ appendMessage(conversationId: string, message: StoredMessage): Promise<void>;
152
+ /**
153
+ * Delete the entire conversation. MUST be idempotent (delete-of-missing = ok).
154
+ */
155
+ deleteConversation(conversationId: string): Promise<void>;
156
+ /**
157
+ * Optional: list conversation ids. Used by housekeeping flows.
158
+ * Implementations that cannot enumerate (e.g., wildcards too expensive on
159
+ * production Redis) MAY return `undefined` to signal "not supported".
160
+ */
161
+ listConversationIds?(opts?: {
162
+ limit?: number;
163
+ }): Promise<readonly string[] | undefined>;
164
+ /**
165
+ * Optional FS-specific compaction trigger (ADR D304). The default FS adapter
166
+ * trims old turns past a soft cap; other backends typically no-op.
167
+ */
168
+ compact?(conversationId: string, maxTurns: number): Promise<void>;
169
+ /**
170
+ * Optional: dispose underlying handles (close DB pool, etc.).
171
+ * MUST be safe to call multiple times.
172
+ */
173
+ dispose?(): Promise<void>;
174
+ }
175
+
176
+ /**
177
+ * Public types for `Agent.create({ handoffs })` + `Handoff.create()` +
178
+ * `Agent.handoffTo()` (Adoption Roadmap #4; ADRs D214-D229).
179
+ *
180
+ * Pattern: handoff-as-tool. Each handoff destination becomes a synthetic
181
+ * `transfer_to_<receiver>` function tool exposed to the LLM. Runtime
182
+ * intercepts the tool call and routes the next turn to the receiver.
183
+ *
184
+ * @public
185
+ */
186
+
187
+ /**
188
+ * Context handed to `onHandoff` callbacks and `isEnabled` predicates.
189
+ * Read-only snapshot of the handoff dispatch state.
190
+ */
191
+ interface HandoffContext {
192
+ readonly senderAgentId: string;
193
+ readonly receiverAgentId: string;
194
+ /** Depth counter AT dispatch time (post-increment; first handoff = 1). */
195
+ readonly currentDepth: number;
196
+ /** Chain of agentIds traversed so far in this send(). Always ends with sender. */
197
+ readonly chain: ReadonlyArray<string>;
198
+ }
199
+ /**
200
+ * The transcript wrapper passed to `inputFilter`. `messages` is widened to
201
+ * `unknown[]` so this type doesn't import from `messages.ts` (avoids cycle
202
+ * — implementations cast to `SDKMessage[]` internally).
203
+ */
204
+ interface HandoffHistory {
205
+ readonly messages: ReadonlyArray<unknown>;
206
+ }
207
+ /**
208
+ * Options accepted by `Handoff.create(target, opts?)`.
209
+ *
210
+ * @public
211
+ */
212
+ interface HandoffOptions<TInput extends ZodType = ZodType> {
213
+ /** Override the default tool name `transfer_to_<receiver.name>` (D215). */
214
+ readonly toolName?: string;
215
+ /** Override the default tool description. */
216
+ readonly toolDescription?: string;
217
+ /**
218
+ * Side-effect callback fired BEFORE the receiver takes over.
219
+ *
220
+ * **Semantics (D227):** throwing aborts the handoff — the synthetic tool
221
+ * returns `tool_error: onHandoff_failed: <message>` so the LLM sees the
222
+ * conflict. Logger-style consumers MUST wrap their own try/catch to
223
+ * swallow exceptions.
224
+ */
225
+ readonly onHandoff?: (ctx: HandoffContext, parsed: TInput extends ZodType ? unknown : undefined) => void | Promise<void>;
226
+ /**
227
+ * Zod schema for the handoff tool-call arguments (structured payload).
228
+ * When set, LLM-provided args are validated before `onHandoff` fires.
229
+ *
230
+ * **Edge case (D229):** empty/null `inputJson` parses as `{}` before
231
+ * Zod refinements fire — required-field schemas still throw normally.
232
+ */
233
+ readonly inputType?: TInput;
234
+ /**
235
+ * Filter the history passed to the receiver (D216 default = full; D219).
236
+ *
237
+ * **Resilience (D228):** if this callback throws, the runtime logs once
238
+ * to stderr and falls back to the un-filtered history. Use this for
239
+ * privacy redaction; if you need fatal-on-failure semantics, throw in
240
+ * `onHandoff` instead.
241
+ */
242
+ readonly inputFilter?: (history: HandoffHistory) => HandoffHistory | Promise<HandoffHistory>;
243
+ /**
244
+ * Restrict the receiver's tools for the post-handoff turn ONLY (D224).
245
+ * Subsequent receiver-internal turns use the receiver's full tool set.
246
+ */
247
+ readonly tools?: ReadonlyArray<string>;
248
+ /**
249
+ * Dynamically enable/disable this handoff. Bool = static; predicate =
250
+ * called per-`Agent.send()` to evaluate.
251
+ */
252
+ readonly isEnabled?: boolean | ((ctx: HandoffContext) => boolean | Promise<boolean>);
253
+ }
254
+ /**
255
+ * Result of a single handoff dispatch (for telemetry / observability).
256
+ *
257
+ * @public
258
+ */
259
+ interface HandoffResult {
260
+ readonly from: string;
261
+ readonly to: string;
262
+ readonly depth: number;
263
+ readonly toolName: string;
264
+ readonly reasonFromLlm?: string;
265
+ }
266
+ /** Throw when handoff depth exceeds `maxHandoffDepth` (default 5; D218). */
267
+ declare class HandoffLoopError extends Error {
268
+ readonly name = "HandoffLoopError";
269
+ readonly depth: number;
270
+ readonly chain: ReadonlyArray<string>;
271
+ constructor(depth: number, chain: ReadonlyArray<string>);
272
+ }
273
+ /** Throw when the same (sender, receiver) pair invoked twice in one send() (D221). */
274
+ declare class HandoffPairLoopError extends Error {
275
+ readonly name = "HandoffPairLoopError";
276
+ readonly senderAgentId: string;
277
+ readonly receiverAgentId: string;
278
+ constructor(senderAgentId: string, receiverAgentId: string);
279
+ }
280
+ /** Throw when an agent's `handoffs[]` includes a self-reference (EC-6). */
281
+ declare class HandoffSelfReferenceError extends Error {
282
+ readonly name = "HandoffSelfReferenceError";
283
+ readonly agentId: string;
284
+ constructor(agentId: string);
285
+ }
286
+ /** Throw when receiver is disposed at dispatch time (EC-5). */
287
+ declare class HandoffReceiverDisposedError extends Error {
288
+ readonly name = "HandoffReceiverDisposedError";
289
+ readonly receiverAgentId: string;
290
+ constructor(receiverAgentId: string);
291
+ }
292
+ /** Throw when two handoffs in the same parent collide on tool name (D215). */
293
+ declare class HandoffNameCollisionError extends Error {
294
+ readonly name = "HandoffNameCollisionError";
295
+ readonly conflictingName: string;
296
+ constructor(conflictingName: string);
297
+ }
298
+ /**
299
+ * Public `Handoff` shape — what `Handoff.create()` returns. Read-only
300
+ * accessors only; behavior lives in the engine.
301
+ *
302
+ * @public
303
+ */
304
+ interface HandoffDescriptor<TInput extends ZodType = ZodType> {
305
+ readonly target: SDKAgent;
306
+ readonly options: HandoffOptions<TInput>;
307
+ /** Resolved tool name (after applying toolName override or default `transfer_to_<receiver>`). */
308
+ readonly resolvedToolName: string;
309
+ }
310
+
311
+ /**
312
+ * Public `MemoryAdapter` contract (T1.1, ADRs D141 / D147).
313
+ *
314
+ * The plugin extension point `{ kind: "memory" }` (ADR D98) declares a
315
+ * `createProvider` factory; this file types its return value formally.
316
+ * Adapters implement `write` / `recall` / `delete` plus optional methods
317
+ * gated by `capabilities`. `MemoryId` is a branded string prefixed with
318
+ * the adapter id so cross-adapter use throws on `extractRawId` (EC-B).
319
+ *
320
+ * Each provider-specific package (`@theokit-memory-supermemory`, etc)
321
+ * exports a factory returning a `Plugin { kind: "memory" }` whose
322
+ * `createProvider` resolves to a `MemoryAdapter` instance.
323
+ *
324
+ * @public
325
+ */
326
+ /**
327
+ * Branded provider memory ID. Format: `${adapterId}:${rawProviderId}`.
328
+ * Use `mkMemoryId` / `extractRawId` from `../memory-adapter-helpers.js`
329
+ * to construct and unwrap with cross-adapter safety (EC-B).
330
+ *
331
+ * @public
332
+ */
333
+ type MemoryId = string & {
334
+ readonly __brand: "MemoryId";
335
+ };
336
+ /**
337
+ * Portable identity context. `userId` is the only required field —
338
+ * the lowest common denominator across Supermemory / Honcho / Mem0.
339
+ * Adapter implementations translate the optional fields to their
340
+ * provider's native primitives (Honcho session, Mem0 run_id, etc).
341
+ *
342
+ * @public
343
+ */
344
+ interface MemoryContext {
345
+ /** End-user identity. */
346
+ userId: string;
347
+ /** Agent / persona writing the memory. */
348
+ agentId?: string;
349
+ /** Logical conversation / run boundary. */
350
+ sessionId?: string;
351
+ /** Tenant / workspace partition. */
352
+ tenantId?: string;
353
+ /** Free-form tags for filtering / categorization. */
354
+ tags?: string[];
355
+ /** Provider-passthrough metadata. */
356
+ metadata?: Record<string, unknown>;
357
+ }
358
+ /**
359
+ * A single memory fact returned by `recall` or `get`.
360
+ *
361
+ * @public
362
+ */
363
+ interface MemoryFact {
364
+ id: MemoryId;
365
+ content: string;
366
+ /** Semantic relevance score (provider-defined scale) when result of `recall`. */
367
+ score?: number;
368
+ /** ISO 8601 timestamp of creation. */
369
+ createdAt?: string;
370
+ metadata?: Record<string, unknown>;
371
+ }
372
+ /**
373
+ * Versioned snapshot of a memory's history. Only emitted by providers
374
+ * with `capabilities.history === true` (Mem0 today).
375
+ *
376
+ * @public
377
+ */
378
+ interface MemoryRevision {
379
+ id: MemoryId;
380
+ content: string;
381
+ version: number;
382
+ changedAt: string;
383
+ }
384
+ /**
385
+ * Statically declared adapter feature flags. Consumers feature-detect
386
+ * at compile time via `if (adapter.capabilities.history)`.
387
+ *
388
+ * @public
389
+ */
390
+ interface MemoryAdapterCapabilities {
391
+ /** Returns prior versions of a memory via `history(id)`. */
392
+ history: boolean;
393
+ /** First-class `sessionId` scoping. */
394
+ sessions: boolean;
395
+ /** First-class `tenantId` scoping. */
396
+ tenancy: boolean;
397
+ /** Provider performs reasoning over memory (e.g., Honcho dialectic). */
398
+ reasoning: boolean;
399
+ /** Exposes LLM-callable function-calling schemas. */
400
+ toolSchemas: boolean;
401
+ /** Supports background prefetch (currently informational). */
402
+ prefetch: boolean;
403
+ }
404
+ /**
405
+ * One assistant-turn message in the canonical `{role, content}` shape
406
+ * an adapter may receive instead of a flat string when writing a turn.
407
+ *
408
+ * @public
409
+ */
410
+ interface MemoryTurnMessage {
411
+ role: "user" | "assistant" | "system";
412
+ content: string;
413
+ }
414
+ /**
415
+ * OpenAI-format function-calling schema exposed to the LLM.
416
+ *
417
+ * @public
418
+ */
419
+ interface MemoryToolSchema {
420
+ name: string;
421
+ description: string;
422
+ parameters: Record<string, unknown>;
423
+ }
424
+ /**
425
+ * Portable third-party memory adapter contract. Implementations live
426
+ * in `@theokit-memory-*` packages; the SDK never imports them.
427
+ *
428
+ * @public
429
+ */
430
+ interface MemoryAdapter {
431
+ /** Short identifier — matches the `${adapterId}` prefix in `MemoryId`. */
432
+ readonly id: string;
433
+ readonly capabilities: MemoryAdapterCapabilities;
434
+ /** Synchronous availability probe — no network, no I/O. */
435
+ isAvailable(): boolean;
436
+ /** One-shot initialization. Idempotent: safe to call multiple times. */
437
+ initialize?(): Promise<void>;
438
+ /**
439
+ * Persist a fact or full turn to memory. Returns the stored
440
+ * `MemoryId`. Throws `MemoryAdapterError(code: "invalid_input")` on
441
+ * empty content or invalid identifiers in `ctx`.
442
+ */
443
+ write(content: string | MemoryTurnMessage[], ctx: MemoryContext): Promise<MemoryId>;
444
+ /**
445
+ * Semantic recall — top-`k` facts ordered by relevance. Returns
446
+ * empty array when `k === 0` or no matches.
447
+ */
448
+ recall(query: string, ctx: MemoryContext, k?: number): Promise<MemoryFact[]>;
449
+ /**
450
+ * Delete a memory by id. Throws `MemoryAdapterError(code:
451
+ * "invalid_input")` when the id was minted by a different adapter
452
+ * (EC-B). Throws `code: "not_found"` when the id does not exist.
453
+ */
454
+ delete(id: MemoryId): Promise<void>;
455
+ list?(ctx: MemoryContext, opts?: {
456
+ cursor?: string;
457
+ limit?: number;
458
+ }): AsyncIterable<MemoryFact>;
459
+ get?(id: MemoryId): Promise<MemoryFact | null>;
460
+ history?(id: MemoryId): Promise<MemoryRevision[]>;
461
+ /** Empty array when `capabilities.toolSchemas === false`. */
462
+ getToolSchemas?(): MemoryToolSchema[];
463
+ handleToolCall?(name: string, args: Record<string, unknown>, ctx: MemoryContext): Promise<string>;
464
+ /** Graceful shutdown — flush queues, close connections. */
465
+ shutdown?(): Promise<void>;
466
+ }
467
+ /**
468
+ * Direct memory API exposed on `SDKAgent.memory`. Resolves to whichever
469
+ * memory adapter(s) are registered via `Agent.create({ plugins: [...] })`.
470
+ *
471
+ * @public
472
+ */
473
+ interface AgentMemory {
474
+ /**
475
+ * Persist a fact. Returns the first adapter's id; in multi-adapter
476
+ * setups all adapters receive the write (fan-out).
477
+ */
478
+ write(content: string | MemoryTurnMessage[], ctx?: Partial<MemoryContext>): Promise<MemoryId>;
479
+ /** Semantic recall — merged + deduped across registered adapters. */
480
+ recall(query: string, ctx?: Partial<MemoryContext>, k?: number): Promise<MemoryFact[]>;
481
+ /** Delete a memory by id — routes to the owning adapter via prefix. */
482
+ delete(id: MemoryId): Promise<void>;
483
+ /** Returns the first registered adapter or `null` when none exists. */
484
+ adapter(): MemoryAdapter | null;
485
+ }
486
+
487
+ /**
488
+ * Context manager backend.
489
+ *
490
+ * - `"file"` — Read `.theokit/context.json` from the workspace (local) or the
491
+ * cloned repo (cloud).
492
+ *
493
+ * @public
494
+ */
495
+ type ContextManagerKind = "file";
496
+ /**
497
+ * Context configuration accepted by `Agent.create()` via {@link AgentOptions.context}.
498
+ *
499
+ * @public
500
+ */
501
+ interface ContextSettings {
502
+ /** Which backend reads context. Defaults to `"file"`. */
503
+ manager?: ContextManagerKind;
504
+ /** Hard cap on tokens emitted into the agent's system prompt. */
505
+ maxTokens?: number;
506
+ /**
507
+ * Per-file truncation cap in characters. Default 40_000 (~10k tokens).
508
+ * Larger files are truncated with 70%/20% head/tail + marker (ADR D155).
509
+ *
510
+ * @public
511
+ */
512
+ maxBytesPerFile?: number;
513
+ /**
514
+ * Aggregate cap across all context files in characters. Default 120_000.
515
+ * When total exceeds this, lower-priority sources are dropped (ADR D155).
516
+ *
517
+ * Note: context snapshot is **refresh-time** (EC-T); modifying context
518
+ * files mid-flight does not auto-update. Call `agent.reload()` to pick
519
+ * up changes.
520
+ *
521
+ * @public
522
+ */
523
+ maxBytesTotal?: number;
524
+ }
525
+ /**
526
+ * Inclusion state of a single context source in a {@link ContextSnapshot}.
527
+ *
528
+ * @public
529
+ */
530
+ type ContextSourceStatus = "included" | "excluded" | "summarized";
531
+ /**
532
+ * A single context source resolved by the context manager.
533
+ *
534
+ * @public
535
+ */
536
+ interface ContextSource {
537
+ /** Stable identifier — usually the filename without extension. */
538
+ name: string;
539
+ /** Path relative to the workspace root, when applicable. */
540
+ path?: string;
541
+ /** Whether the source was included, dropped, or summarized to fit the budget. */
542
+ status: ContextSourceStatus;
543
+ /** Free-text reason when `status !== "included"`. */
544
+ reason?: string;
545
+ }
546
+ /**
547
+ * Token budget used by the context manager for a single agent.
548
+ *
549
+ * @public
550
+ */
551
+ interface ContextBudget {
552
+ maxTokens?: number;
553
+ /**
554
+ * Either a token count or a list of token strings extracted from source
555
+ * content. Normalized to `<tokens>` in golden comparisons.
556
+ */
557
+ usedTokens?: number | string[];
558
+ }
559
+ /**
560
+ * Result of `agent.context.snapshot()`. Public and secret-free by design — safe
561
+ * to log and persist. Raw secrets, local absolute paths, and exact token values
562
+ * are never present.
563
+ *
564
+ * @public
565
+ */
566
+ interface ContextSnapshot {
567
+ runtime: "local" | "cloud";
568
+ sources: ContextSource[];
569
+ budget?: ContextBudget;
570
+ }
571
+ /**
572
+ * Public context manager handle exposed as `agent.context`.
573
+ *
574
+ * @public
575
+ */
576
+ interface SDKContextManager {
577
+ /** Inspect what the context manager actually loaded for the agent. */
578
+ snapshot(): Promise<ContextSnapshot>;
579
+ }
580
+
581
+ /**
582
+ * MCP server configuration accepted by `Agent.create()` and `agent.send()`.
583
+ *
584
+ * @public
585
+ */
586
+ type McpStdioServerConfig = {
587
+ type?: "stdio";
588
+ command: string;
589
+ args?: string[];
590
+ env?: Record<string, string>;
591
+ /** Local agents only. Cloud rejects this field. */
592
+ cwd?: string;
593
+ };
594
+ /**
595
+ * OAuth-style auth bundle for HTTP/SSE MCP servers.
596
+ *
597
+ * @public
598
+ */
599
+ interface McpAuthConfig {
600
+ CLIENT_ID: string;
601
+ CLIENT_SECRET?: string;
602
+ scopes?: string[];
603
+ /**
604
+ * OAuth 2.1 PKCE flow configuration (ADR D41, v1.2+). When present, the
605
+ * SDK runs the PKCE flow on first use and stores tokens via keychain or
606
+ * file. Without this, the SDK relies on `CLIENT_SECRET` + manual headers.
607
+ */
608
+ oauth?: McpOAuthConfig;
609
+ }
610
+ /**
611
+ * OAuth 2.1 PKCE flow descriptor. See ADR D41.
612
+ *
613
+ * @public
614
+ */
615
+ interface McpOAuthConfig {
616
+ /** Authorization endpoint (e.g. https://api.notion.com/v1/oauth/authorize). */
617
+ authorizationEndpoint: string;
618
+ /** Token endpoint (e.g. https://api.notion.com/v1/oauth/token). */
619
+ tokenEndpoint: string;
620
+ /** Where the OAuth `code` is received. */
621
+ redirectMode: "manual" | "localhost";
622
+ /** Localhost callback port (0 = random free port, default). */
623
+ localhostPort?: number;
624
+ /** Flow timeout in ms (default 300_000 = 5min). */
625
+ timeoutMs?: number;
626
+ }
627
+ /**
628
+ * HTTP or SSE MCP server.
629
+ *
630
+ * @public
631
+ */
632
+ type McpHttpServerConfig = {
633
+ type?: "http" | "sse";
634
+ url: string;
635
+ /** Passed through. `Authorization` works here. */
636
+ headers?: Record<string, string>;
637
+ auth?: McpAuthConfig;
638
+ };
639
+ /**
640
+ * Union of MCP server configs. See `docs.md` for the full reference.
641
+ *
642
+ * @public
643
+ */
644
+ type McpServerConfig = McpStdioServerConfig | McpHttpServerConfig;
645
+
646
+ /**
647
+ * Capability slot a provider can fulfill.
648
+ *
649
+ * @public
650
+ */
651
+ type ProviderCapability = "chat" | "web_search" | "image" | "embedding";
652
+ /**
653
+ * A single user-declared routing rule. Maps a capability to a provider, and
654
+ * optionally pins a specific model.
655
+ *
656
+ * @public
657
+ */
658
+ interface ProviderRoute {
659
+ capability: ProviderCapability;
660
+ provider: string;
661
+ model?: string;
662
+ }
663
+ /**
664
+ * Provider routing configuration accepted by `Agent.create()` via
665
+ * {@link AgentOptions.providers}.
666
+ *
667
+ * @public
668
+ */
669
+ interface ProviderRoutingSettings {
670
+ /** Explicit `{ capability → provider }` map. First match wins per capability. */
671
+ routes: ProviderRoute[];
672
+ /** Provider names to try in order when a route has no provider available. */
673
+ fallback?: string[];
674
+ /**
675
+ * Multiple API keys per provider for same-provider key rotation
676
+ * (credential pool — ADRs D123-D133). When a key hits HTTP 429, 402,
677
+ * or 401, the SDK rotates to the next entry transparently before
678
+ * falling back to a different provider.
679
+ *
680
+ * Example:
681
+ * ```ts
682
+ * apiKeys: { openrouter: ["sk-or-...", "sk-or-..."], anthropic: ["..."] }
683
+ * ```
684
+ *
685
+ * Empty arrays and empty strings are filtered out. If a provider has
686
+ * exactly 1 effective key, the pool is transparent (no rotation behavior).
687
+ *
688
+ * Conflicts with the single-key shape `AgentOptions.apiKey: "..."` —
689
+ * use one OR the other, not both.
690
+ *
691
+ * @public
692
+ */
693
+ apiKeys?: Record<string, string[]>;
694
+ /**
695
+ * Rotation strategy per provider for the credential pool. Default is
696
+ * `"fill_first"` (use entries[0] until exhausted). Only consulted when
697
+ * `apiKeys[provider]` has ≥2 entries.
698
+ *
699
+ * @public
700
+ */
701
+ credentialPoolStrategy?: Record<string, "fill_first" | "round_robin" | "least_used" | "random">;
702
+ }
703
+ /**
704
+ * Plugins configuration accepted by `Agent.create()` via
705
+ * {@link AgentOptions.plugins}.
706
+ *
707
+ * @public
708
+ */
709
+ interface PluginsSettings {
710
+ /** Plugin names to enable. Plugin discovery is plugin-provider specific. */
711
+ enabled?: string[];
712
+ }
713
+ /**
714
+ * Resolved routing decision returned by `agent.providers.routes()`. Public and
715
+ * secret-free by design — safe to log.
716
+ *
717
+ * @public
718
+ */
719
+ interface ResolvedProviderRoute {
720
+ capability: string;
721
+ provider: string;
722
+ model?: string;
723
+ /** Why the runtime picked this provider (e.g. `"explicit-model-provider"`). */
724
+ reason: string;
725
+ }
726
+ /**
727
+ * Public providers manager handle exposed as `agent.providers`.
728
+ *
729
+ * @public
730
+ */
731
+ interface SDKProvidersManager {
732
+ /** Inspect which provider serves each capability for this agent. */
733
+ routes(): Promise<ResolvedProviderRoute[]>;
734
+ }
735
+ /**
736
+ * Provider catalog entry returned by `Theokit.providers.list()`.
737
+ *
738
+ * @public
739
+ */
740
+ interface SDKProvider {
741
+ name: string;
742
+ displayName: string;
743
+ capabilities: string[];
744
+ isAvailable: boolean;
745
+ /** JSON Schema describing the env vars / fields needed to enable this provider. */
746
+ setupSchema: object;
747
+ }
748
+
749
+ /**
750
+ * One slot in a {@link ModelSelection.params} array.
751
+ *
752
+ * @public
753
+ */
754
+ interface ModelParameterValue {
755
+ id: string;
756
+ value: string;
757
+ }
758
+ /**
759
+ * Identifies a model plus optional per-model parameters (e.g. reasoning effort).
760
+ *
761
+ * Use `Theokit.models.list()` to discover valid ids and parameter definitions.
762
+ *
763
+ * @public
764
+ */
765
+ interface ModelSelection {
766
+ id: string;
767
+ params?: ModelParameterValue[];
768
+ }
769
+ /**
770
+ * Which on-disk settings layers a local agent loads.
771
+ *
772
+ * @public
773
+ */
774
+ type SettingSource = "project" | "user" | "team" | "mdm" | "plugins" | "all";
775
+ /**
776
+ * Local agent configuration.
777
+ *
778
+ * @public
779
+ */
780
+ interface LocalOptions {
781
+ cwd?: string | string[];
782
+ settingSources?: SettingSource[];
783
+ sandboxOptions?: {
784
+ enabled: boolean;
785
+ };
786
+ }
787
+ /**
788
+ * Repo to clone into a cloud agent's VM.
789
+ *
790
+ * @public
791
+ */
792
+ interface CloudRepo {
793
+ url: string;
794
+ startingRef?: string;
795
+ prUrl?: string;
796
+ }
797
+ /**
798
+ * Cloud execution environment.
799
+ *
800
+ * @public
801
+ */
802
+ interface CloudEnv {
803
+ type: "cloud" | "pool" | "machine";
804
+ name?: string;
805
+ }
806
+ /**
807
+ * Cloud agent configuration.
808
+ *
809
+ * @public
810
+ */
811
+ interface CloudOptions {
812
+ env?: CloudEnv;
813
+ repos?: CloudRepo[];
814
+ workOnCurrentBranch?: boolean;
815
+ autoCreatePR?: boolean;
816
+ skipReviewerRequest?: boolean;
817
+ /**
818
+ * Short-lived credentials scoped to the agent. Encrypted at rest, deleted
819
+ * with the agent. Names must not start with `THEOKIT_`.
820
+ */
821
+ envVars?: Record<string, string>;
822
+ }
823
+ /**
824
+ * Subagent definition. The parent agent spawns these via its Agent tool.
825
+ *
826
+ * @public
827
+ */
828
+ interface AgentDefinition {
829
+ description: string;
830
+ prompt: string;
831
+ model?: ModelSelection | "inherit";
832
+ mcpServers?: Array<string | Record<string, McpServerConfig>>;
833
+ }
834
+ /**
835
+ * Public skill metadata exposed to the system-prompt resolver. Mirrors the
836
+ * shape returned by `agent.skills.list()` — name + description only, never
837
+ * full skill bodies.
838
+ *
839
+ * @public
840
+ */
841
+ interface SystemPromptSkillRef {
842
+ name: string;
843
+ description: string;
844
+ }
845
+ /**
846
+ * Public skill listing handle exposed as `agent.skills`. Populated when
847
+ * `settingSources` includes `"project"` so the SDK discovers
848
+ * `.theokit/skills/<name>/SKILL.md` files OR when `skills.enabled` is set
849
+ * explicitly on the agent options.
850
+ *
851
+ * @public
852
+ */
853
+ interface SDKAgentSkills {
854
+ list(): Promise<ReadonlyArray<SystemPromptSkillRef>>;
855
+ }
856
+ /**
857
+ * Public plugin metadata returned by `agent.plugins.list()`. Mirrors the
858
+ * `.theokit/plugins/<name>/MANIFEST.json` allow-listed shape; never exposes
859
+ * raw plugin bodies, credentials, or internal hooks.
860
+ *
861
+ * @public
862
+ */
863
+ interface SDKPluginMetadata {
864
+ name: string;
865
+ description?: string;
866
+ }
867
+ /**
868
+ * Public plugin listing handle exposed as `agent.plugins`. Populated when
869
+ * `settingSources` includes `"plugins"` OR when `plugins.enabled` is set
870
+ * on the agent options.
871
+ *
872
+ * @public
873
+ */
874
+ interface SDKAgentPlugins {
875
+ list(): Promise<ReadonlyArray<SDKPluginMetadata>>;
876
+ }
877
+ /**
878
+ * Public view of a recalled memory fact exposed to the system-prompt resolver.
879
+ *
880
+ * @public
881
+ */
882
+ interface SystemPromptMemoryFact {
883
+ text: string;
884
+ }
885
+ /**
886
+ * Context passed to a {@link SystemPromptResolver}. Field order is a
887
+ * compatibility contract: new fields are appended, never reordered.
888
+ *
889
+ * @public
890
+ */
891
+ interface SystemPromptContext {
892
+ agentId: string;
893
+ cwd: string | undefined;
894
+ model: ModelSelection | undefined;
895
+ skills: ReadonlyArray<SystemPromptSkillRef>;
896
+ userMessage: string;
897
+ /** Recalled durable facts when memory is enabled. Appended in v1.1. */
898
+ memory: ReadonlyArray<SystemPromptMemoryFact>;
899
+ }
900
+ /**
901
+ * Resolver function that produces the system prompt dynamically. Receives
902
+ * the {@link SystemPromptContext} and returns a string (or a Promise of one).
903
+ *
904
+ * The SDK does NOT impose a timeout on the resolver — wrap your own
905
+ * `Promise.race` if you call into slow resources. Errors propagate to the
906
+ * caller of `agent.send()`.
907
+ *
908
+ * @public
909
+ */
910
+ type SystemPromptResolver = (ctx: SystemPromptContext) => string | Promise<string>;
911
+ /**
912
+ * Skills configuration accepted by `Agent.create()` via
913
+ * {@link AgentOptions.skills}.
914
+ *
915
+ * Skills are discovered from `.theokit/skills/<name>/SKILL.md` when
916
+ * `local.settingSources` includes `"project"`.
917
+ *
918
+ * @public
919
+ */
920
+ interface SkillsSettings {
921
+ /**
922
+ * Names of skills the parent agent may invoke. When omitted, every
923
+ * discovered skill is enabled.
924
+ */
925
+ enabled?: string[];
926
+ /**
927
+ * Whether the SDK auto-injects the loaded skill list (name + description) as a
928
+ * `<skills>` block in the LLM system prompt. Default `true`.
929
+ *
930
+ * Set to `false` when supplying a custom `systemPrompt` resolver that formats
931
+ * skills itself.
932
+ */
933
+ autoInject?: boolean;
934
+ }
935
+ /**
936
+ * Memory configuration accepted by `Agent.create()` via {@link AgentOptions.memory}.
937
+ *
938
+ * Persists durable facts under `.theokit/memory/<namespace>/<scope>-<userId>.json`.
939
+ *
940
+ * @public
941
+ */
942
+ interface MemorySettings {
943
+ enabled: boolean;
944
+ namespace?: string;
945
+ userId?: string;
946
+ scope?: "agent" | "user" | "team";
947
+ storePath?: string;
948
+ /**
949
+ * Whether the SDK auto-injects recalled facts as a `<memory>` block in the
950
+ * LLM system prompt. Default `true`.
951
+ */
952
+ autoInject?: boolean;
953
+ /**
954
+ * Index + tools configuration (memory-system-openclaw-parity).
955
+ *
956
+ * When `tools !== false`, the SDK registers `memory_search` and
957
+ * `memory_get` with the LLM. Backed by SQLite + FTS5 (and sqlite-vec
958
+ * when an embedding provider is configured).
959
+ */
960
+ index?: {
961
+ /** Whether to register `memory_search` + `memory_get` tools. Default `true`. */
962
+ tools?: boolean;
963
+ /**
964
+ * Vector index backend (ADR D43). Default `"sqlite-vec"`. Set to
965
+ * `"lance"` to use `@lancedb/lancedb` (optional peer dep) for scale.
966
+ */
967
+ backend?: "sqlite-vec" | "lance";
968
+ /** Embedding provider config. When omitted, the index runs in FTS-only mode. */
969
+ embedding?: {
970
+ provider: "openai" | "mistral" | "openrouter" | "voyage" | "deepinfra";
971
+ model?: string;
972
+ };
973
+ };
974
+ /**
975
+ * Active Memory blocking recall (Phase 7). When `enabled: true`, runs
976
+ * before each `send()` and prepends an `<active-memory>` block.
977
+ */
978
+ activeRecall?: {
979
+ enabled?: boolean;
980
+ queryMode?: "message" | "recent" | "full";
981
+ timeoutMs?: number;
982
+ maxSummaryChars?: number;
983
+ persistTranscripts?: boolean;
984
+ };
985
+ }
986
+ /**
987
+ * Inline custom tool — registered with the LLM under the given name + schema
988
+ * and dispatched locally to {@link CustomTool.handler} when the model emits a
989
+ * `tool_use` for it.
990
+ *
991
+ * Local runtime only (SDK v1.0). Cloud agents reject `tools` (handlers cannot
992
+ * cross the wire — use MCP servers or subagents for cloud tool surfaces).
993
+ *
994
+ * Handlers MUST be re-passed on `Agent.resume()` because closures cannot be
995
+ * persisted. The tool catalog (name + description + schema) is NOT serialized.
996
+ *
997
+ * @public
998
+ */
999
+ interface CustomTool {
1000
+ /**
1001
+ * Tool name surfaced to the LLM. Must match `^[a-zA-Z][a-zA-Z0-9_-]{0,63}$`
1002
+ * and must not collide with `shell`, `memory_search`, `memory_get`, or any
1003
+ * `mcp_*` prefix (reserved for the SDK's built-in tools).
1004
+ */
1005
+ name: string;
1006
+ /** Description surfaced to the LLM. Required — drives tool-selection accuracy. */
1007
+ description: string;
1008
+ /** JSON Schema (Draft-7 subset) describing the `input` argument. Must be `type: "object"`. */
1009
+ inputSchema: Record<string, unknown>;
1010
+ /**
1011
+ * Local handler invoked when the model emits `tool_use` for this tool.
1012
+ * Returns a string (becomes the `tool_result.content` surfaced back to the
1013
+ * model). Throws → SDK converts to `tool_result` with `isError: true` and
1014
+ * the error `message` as content.
1015
+ */
1016
+ handler: (input: Record<string, unknown>) => string | Promise<string>;
1017
+ }
1018
+ /**
1019
+ * Telemetry configuration for an agent. When `enabled: true`, the SDK emits
1020
+ * OpenTelemetry spans for `agent.send`, `llm.call`, `tool.call`, and
1021
+ * `memory.search`. See ADR D34.
1022
+ *
1023
+ * Privacy: content (prompts, responses, tool args) is OMITTED by default —
1024
+ * only timing/counts/IDs are recorded. Opt in via `includeContent: true`
1025
+ * to add prompt/response/args events to the spans (consumer's
1026
+ * responsibility to sanitize PII).
1027
+ *
1028
+ * `@opentelemetry/api` is an OPTIONAL peer dependency. Without it
1029
+ * installed, telemetry is a no-op even when `enabled: true`.
1030
+ *
1031
+ * @public
1032
+ */
1033
+ interface TelemetrySettings {
1034
+ /** Master switch. Default `false`. */
1035
+ enabled: boolean;
1036
+ /** Whether to include prompts/responses/tool args as span events. Default `false`. */
1037
+ includeContent?: boolean;
1038
+ /** Exporter selection. Default `"console"`. Custom exporters are passed-through. */
1039
+ exporter?: "console" | "otlp" | unknown;
1040
+ /** Service name on emitted spans. Default `"theokit-sdk"`. */
1041
+ serviceName?: string;
1042
+ /**
1043
+ * Auto-detect and register OTel exporters for installed observability
1044
+ * libs (Langfuse, Sentry, PostHog) via `createRequire` feature-detect.
1045
+ * Default `true`. See ADR D42.
1046
+ */
1047
+ autoDetect?: boolean;
1048
+ /**
1049
+ * Per-adapter opt-out. Lowercase names: `"langfuse" | "sentry" | "posthog"`.
1050
+ * Default `[]`.
1051
+ */
1052
+ disable?: string[];
1053
+ }
1054
+ /**
1055
+ * Top-level options accepted by `Agent.create()`.
1056
+ *
1057
+ * Pass either `local` or `cloud` to pick a runtime.
1058
+ *
1059
+ * @public
1060
+ */
1061
+ interface AgentOptions {
1062
+ model?: ModelSelection;
1063
+ /** Falls back to `THEOKIT_API_KEY`. */
1064
+ apiKey?: string;
1065
+ name?: string;
1066
+ /**
1067
+ * When `true`, `Agent.prompt` (and any helper that goes through `run.wait()`)
1068
+ * rejects with `AgentRunError` instead of resolving with `{ status: 'error' }`.
1069
+ * Cancelled runs (`status: 'cancelled'`) still resolve — cancel ≠ error.
1070
+ * If `result.error` is undefined despite `status: 'error'` (malformed RunResult),
1071
+ * the defensive guard resolves normally (no throw).
1072
+ *
1073
+ * Default `false` (backwards-compatible).
1074
+ *
1075
+ * @public
1076
+ */
1077
+ throwOnError?: boolean;
1078
+ /**
1079
+ * System prompt for the agent. Either a plain string or a resolver
1080
+ * function that receives the {@link SystemPromptContext} and returns the
1081
+ * prompt dynamically. Override per-call via {@link SendOptions.systemPrompt}.
1082
+ *
1083
+ * Subagents do NOT inherit this — they use {@link AgentDefinition.prompt}.
1084
+ */
1085
+ systemPrompt?: string | SystemPromptResolver;
1086
+ local?: LocalOptions;
1087
+ cloud?: CloudOptions;
1088
+ mcpServers?: Record<string, McpServerConfig>;
1089
+ agents?: Record<string, AgentDefinition>;
1090
+ agentId?: string;
1091
+ /** Context manager configuration. See `agent.context`. */
1092
+ context?: ContextSettings;
1093
+ /** Provider routing configuration. See `agent.providers`. */
1094
+ providers?: ProviderRoutingSettings;
1095
+ /** Plugins to enable. Plugin sources must also be active via `local.settingSources`. */
1096
+ plugins?: PluginsSettings;
1097
+ /** Skills configuration. See `agent.skills`. */
1098
+ skills?: SkillsSettings;
1099
+ /** Memory configuration. Persists durable facts; auto-recalled on send. */
1100
+ memory?: MemorySettings;
1101
+ /**
1102
+ * Inline custom tools. Local runtime only — cloud agents reject any non-empty
1103
+ * `tools` array. Handlers are not persisted; pass them again on resume.
1104
+ * See {@link CustomTool}.
1105
+ */
1106
+ tools?: CustomTool[];
1107
+ /**
1108
+ * Telemetry (OpenTelemetry) configuration. Default disabled. See
1109
+ * {@link TelemetrySettings} and ADR D34.
1110
+ */
1111
+ telemetry?: TelemetrySettings;
1112
+ /**
1113
+ * Arbitrary metadata bag for caller-supplied provenance. Currently used by
1114
+ * the fork primitive (ADR D114) to tag `metadata.forkOrigin` and
1115
+ * `metadata.parentAgentId` so memory writes downstream can be attributed.
1116
+ *
1117
+ * Not persisted to the agent registry — informational only at runtime.
1118
+ *
1119
+ * @public
1120
+ */
1121
+ metadata?: Record<string, unknown>;
1122
+ /**
1123
+ * Default `MemoryContext` for third-party memory adapter plugins
1124
+ * (ADR D141). When set, `pre_user_send` / `post_assistant_reply`
1125
+ * hooks receive this context unless the caller overrides it. The
1126
+ * `agent.memory` direct API also defaults to it.
1127
+ *
1128
+ * @public
1129
+ */
1130
+ memoryContext?: MemoryContext;
1131
+ /**
1132
+ * Maximum byte length of the `<memory-context>` block injected by
1133
+ * `pre_user_send` adapter hooks (EC-A). Larger recalls are sliced
1134
+ * with `…[truncated]`. Default 16_000 (~4k tokens). Set lower for
1135
+ * cheaper turns; higher for longer-context models.
1136
+ *
1137
+ * @public
1138
+ */
1139
+ maxRecallContextBytes?: number;
1140
+ /**
1141
+ * Declarative handoff destinations (Adoption Roadmap #4; ADRs D214-D229).
1142
+ * Each entry is either a raw `SDKAgent` (auto-wrapped with defaults) OR a
1143
+ * `HandoffDescriptor` from `Handoff.create(target, opts?)`.
1144
+ *
1145
+ * Runtime injects synthetic `transfer_to_<receiver.name>` tools per
1146
+ * destination (D214/D215). When the LLM invokes one, the receiver takes
1147
+ * over the next turn (peer-to-peer, D217).
1148
+ *
1149
+ * @public
1150
+ */
1151
+ handoffs?: ReadonlyArray<SDKAgent | HandoffDescriptor>;
1152
+ /**
1153
+ * Maximum chain depth across handoffs per `agent.send()` call (D218).
1154
+ * Default 5. Exceeding throws `HandoffLoopError`. Set to 0 to disable
1155
+ * the handoff tools entirely (EC-8 / handoffs never fire).
1156
+ *
1157
+ * @public
1158
+ */
1159
+ maxHandoffDepth?: number;
1160
+ /**
1161
+ * Production-Readiness #6 — quota / abuse gates (ADRs D322-D323).
1162
+ *
1163
+ * `onBeforeCreate` fires BEFORE the agent is registered or persisted —
1164
+ * throw to block creation. `onBeforeSend` fires BEFORE each `agent.send`
1165
+ * (after `pre_user_send` adapter hooks, before any LLM call or storage
1166
+ * write) — throw to block the send.
1167
+ *
1168
+ * Unlike `onTool*` (observation), these hooks are BLOCKERS — errors
1169
+ * propagate as rejection on `Agent.create` / `agent.send`. Use them for
1170
+ * per-user conversation caps, per-conversation message caps, abuse
1171
+ * detection.
1172
+ *
1173
+ * @public
1174
+ */
1175
+ onBeforeCreate?: (event: {
1176
+ conversationId: string;
1177
+ userId?: string;
1178
+ }) => Promise<void> | void;
1179
+ /**
1180
+ * Fires before each `agent.send`. `previousMessageCount` is the count of
1181
+ * messages already persisted BEFORE the current send adds the user
1182
+ * message. Throw to block.
1183
+ *
1184
+ * @public
1185
+ */
1186
+ onBeforeSend?: (event: {
1187
+ conversationId: string;
1188
+ previousMessageCount: number;
1189
+ }) => Promise<void> | void;
1190
+ /**
1191
+ * Production-Readiness #4 — tool lifecycle hooks (ADRs D315-D317).
1192
+ *
1193
+ * `onToolStart` fires BEFORE the handler runs. `onToolEnd` fires after a
1194
+ * successful handler return. `onToolError` fires when validation fails OR
1195
+ * the handler throws — `event.error` is always an `Error` instance.
1196
+ *
1197
+ * Hook errors are SWALLOWED with a stderr warn (do not abort the run).
1198
+ * The `callId` is unique per tool invocation and identical across the
1199
+ * start/end (or start/error) pair, so consumers can correlate.
1200
+ *
1201
+ * Use cases: cost tracking, audit logs, per-tool retry/alerting,
1202
+ * latency telemetry.
1203
+ *
1204
+ * @public
1205
+ */
1206
+ onToolStart?: (event: {
1207
+ toolName: string;
1208
+ args: unknown;
1209
+ conversationId: string;
1210
+ callId: string;
1211
+ }) => void | Promise<void>;
1212
+ /** Fires when a tool handler returns successfully. */
1213
+ onToolEnd?: (event: {
1214
+ toolName: string;
1215
+ args: unknown;
1216
+ result: unknown;
1217
+ conversationId: string;
1218
+ callId: string;
1219
+ durationMs: number;
1220
+ }) => void | Promise<void>;
1221
+ /**
1222
+ * Fires when a tool handler throws OR schema validation rejects the args.
1223
+ * `event.error` is always an `Error` instance (D315/EC-6 — validation
1224
+ * reasons are wrapped in `new Error(reason)`).
1225
+ *
1226
+ * `attempt` is always `1` in v1 (D317 — reserved for future retry policy).
1227
+ */
1228
+ onToolError?: (event: {
1229
+ toolName: string;
1230
+ args: unknown;
1231
+ error: Error;
1232
+ conversationId: string;
1233
+ callId: string;
1234
+ durationMs: number;
1235
+ attempt: number;
1236
+ }) => void | Promise<void>;
1237
+ /**
1238
+ * Pluggable conversation persistence (Production-Readiness #1; ADRs D303-D306).
1239
+ *
1240
+ * Default: undefined → `FileSystemConversationStorage` writing to
1241
+ * `<cwd>/.theokit/agents/<id>/messages.jsonl` (byte-identical to pre-D303
1242
+ * behavior). Pass `InMemoryConversationStorage` for tests, or a custom
1243
+ * adapter (Postgres/Redis/Durable Objects) for serverless and multi-host
1244
+ * deploys.
1245
+ *
1246
+ * NOTE: not persisted in the registry snapshot — closures don't serialize.
1247
+ * On `Agent.resume`, pass the adapter again. If the agent was originally
1248
+ * created with a custom `conversationStorage`, resume without it throws
1249
+ * `ConfigurationError(code: "conversation_storage_required")` (D325) to
1250
+ * avoid silent FS fallback that would lose history.
1251
+ *
1252
+ * @public
1253
+ */
1254
+ conversationStorage?: ConversationStorageAdapter;
1255
+ }
1256
+ /**
1257
+ * Artifact produced inside an agent's workspace. Cloud-only.
1258
+ *
1259
+ * @public
1260
+ */
1261
+ interface SDKArtifact {
1262
+ path: string;
1263
+ sizeBytes: number;
1264
+ updatedAt: string;
1265
+ }
1266
+ /**
1267
+ * Handle returned by `Agent.create()` and `Agent.resume()`.
1268
+ *
1269
+ * @public
1270
+ */
1271
+ interface SDKAgent {
1272
+ readonly agentId: string;
1273
+ readonly model: ModelSelection | undefined;
1274
+ /**
1275
+ * Context manager for this agent. Populated when context is enabled via
1276
+ * {@link AgentOptions.context}. See {@link SDKContextManager}.
1277
+ */
1278
+ readonly context?: SDKContextManager;
1279
+ /**
1280
+ * Provider routing inspector for this agent. Populated when at least one
1281
+ * provider route is configured (via {@link AgentOptions.providers}, plugins,
1282
+ * or model-implied providers). See {@link SDKProvidersManager}.
1283
+ */
1284
+ readonly providers?: SDKProvidersManager;
1285
+ /**
1286
+ * Skill listing for this agent. Populated when project-scoped skills are
1287
+ * enabled (`settingSources: ["project"]`) or when `skills.enabled` is set.
1288
+ * See {@link SDKAgentSkills}.
1289
+ */
1290
+ readonly skills?: SDKAgentSkills;
1291
+ /**
1292
+ * Plugin listing for this agent. Populated when project-scoped plugins are
1293
+ * enabled (`settingSources: ["plugins"]`) or when `plugins.enabled` is set.
1294
+ * See {@link SDKAgentPlugins}.
1295
+ */
1296
+ readonly plugins?: SDKAgentPlugins;
1297
+ send(message: string | SDKUserMessage, options?: SendOptions): Promise<Run>;
1298
+ /** Fire-and-forget disposal. */
1299
+ close(): void;
1300
+ /** Re-read filesystem config (context, hooks, project MCP, subagents) without disposing. */
1301
+ reload(): Promise<void>;
1302
+ /**
1303
+ * Async disposal. Idempotent — calling more than once is a no-op (per ADR D5).
1304
+ * Prefer `await using agent = await Agent.create(...)` over explicit
1305
+ * `dispose()` for resource safety.
1306
+ */
1307
+ dispose(): Promise<void>;
1308
+ /**
1309
+ * `await using` support per ADR D5. Identical semantics to `dispose()` —
1310
+ * idempotent across both surfaces.
1311
+ */
1312
+ [Symbol.asyncDispose](): Promise<void>;
1313
+ /** Cloud-only. Local returns an empty array. */
1314
+ listArtifacts(): Promise<SDKArtifact[]>;
1315
+ /** Cloud-only. Local throws `UnsupportedRunOperationError`. */
1316
+ downloadArtifact(path: string): Promise<Buffer>;
1317
+ /**
1318
+ * Signal that prompt cache should be invalidated. By default deferred —
1319
+ * applied at the start of the next `send()`. Pass `{ applyNow: true }` to
1320
+ * force immediate disposal (caller must `Agent.create()` again to use).
1321
+ *
1322
+ * Cache invalidation is a cost regression (provider charges full price
1323
+ * for the rebuilt cache; see ADRs D94-D95). Use sparingly and deliberately.
1324
+ *
1325
+ * Cloud agents: no-op (cloud runtime reconstructs state per request).
1326
+ *
1327
+ * @public
1328
+ */
1329
+ invalidateCache?(reason: string, options?: InvalidateCacheOptions): Promise<void>;
1330
+ /**
1331
+ * Goal-driven Ralph loop (ADRs D115-D121). Iterates `agent.send` →
1332
+ * judge → continuation until the auxiliary judge model returns `done`,
1333
+ * the judge fails too many times in a row, max turns are exhausted,
1334
+ * or the caller aborts via `AbortSignal`.
1335
+ *
1336
+ * Yields {@link import("./goal-events.js").GoalEvent} per state
1337
+ * transition; returns a {@link import("./goal-events.js").GoalResult}
1338
+ * summary as the generator's final value.
1339
+ *
1340
+ * Cloud agents throw {@link import("../errors.js").UnsupportedRunOperationError}
1341
+ * **synchronously** (no AsyncGenerator returned) — wrap in try/catch
1342
+ * if you support both runtimes.
1343
+ *
1344
+ * Caveat: do not call `agent.dispose()` mid-iteration; the next `send`
1345
+ * propagates the disposal error through the generator to the consumer.
1346
+ *
1347
+ * @public
1348
+ */
1349
+ runUntil?(goal: string, options?: GoalOptions): RunUntilIterator;
1350
+ /**
1351
+ * Fork a short-lived sub-agent with parent's credentials + system
1352
+ * prompt byte-identical (ADR D112 — cache hit) and a restricted tool
1353
+ * whitelist (ADR D111 — AsyncLocalStorage isolation).
1354
+ *
1355
+ * Cloud agents throw {@link import("../errors.js").UnsupportedRunOperationError}.
1356
+ *
1357
+ * @public
1358
+ */
1359
+ fork?(options: undefined): Promise<undefined>;
1360
+ /**
1361
+ * Direct API to third-party memory adapter(s) registered via
1362
+ * `plugins: [...]` (ADR D141 / D142). Returns `null` when no adapter
1363
+ * is registered. In multi-adapter setups `write` fans out to all;
1364
+ * `recall` merges + dedupes; `delete` routes by `MemoryId` prefix.
1365
+ *
1366
+ * @public
1367
+ */
1368
+ memory?: AgentMemory;
1369
+ /**
1370
+ * Activate a personality preset for the next `send` (Hermes #26).
1371
+ * Reserved names `"none"`, `"default"`, and `"neutral"` clear the
1372
+ * active preset. Returns the resolved preset (or `null` when cleared).
1373
+ *
1374
+ * Persistence: pass `{ save: true }` to persist across process
1375
+ * restarts (stored under `$THEOKIT_HOME/personality.json`).
1376
+ *
1377
+ * History: by default the conversation history is preserved across
1378
+ * the switch. Pass `{ reset: true }` to also clear the session.
1379
+ *
1380
+ * Cloud agents throw {@link import("../errors.js").UnsupportedRunOperationError}.
1381
+ *
1382
+ * @public
1383
+ */
1384
+ usePersonality?(name: string, opts?: {
1385
+ save?: boolean;
1386
+ reset?: boolean;
1387
+ }): Promise<PersonalityPreset | null>;
1388
+ }
1389
+ /**
1390
+ * Resolved personality preset surfaced via {@link SDKAgent.usePersonality}
1391
+ * (Hermes #26, ADRs D160-D169). Re-declared here so the public DTS bundle
1392
+ * never crosses the `internal/` path boundary. The implementation type in
1393
+ * `internal/personality/types.ts` is structurally identical.
1394
+ *
1395
+ * @public
1396
+ */
1397
+ interface PersonalityPreset {
1398
+ readonly name: string;
1399
+ readonly description: string | undefined;
1400
+ readonly tools: ReadonlyArray<string> | undefined;
1401
+ readonly model: string | undefined;
1402
+ readonly tags: ReadonlyArray<string> | undefined;
1403
+ readonly systemPrompt: string;
1404
+ readonly source: "project" | "user";
1405
+ readonly sourcePath: string;
1406
+ }
1407
+ /**
1408
+ * Options for {@link SDKAgent.invalidateCache}.
1409
+ *
1410
+ * @public
1411
+ */
1412
+ interface InvalidateCacheOptions {
1413
+ /**
1414
+ * When `true`, dispose the agent immediately so caller must recreate it
1415
+ * to continue. Default `false` (deferred — applied on next `send()`).
1416
+ */
1417
+ applyNow?: boolean;
1418
+ }
1419
+ /**
1420
+ * Metadata returned by `Agent.list()` and `Agent.get()`.
1421
+ *
1422
+ * @public
1423
+ */
1424
+ type SDKAgentInfo = {
1425
+ agentId: string;
1426
+ name: string;
1427
+ summary: string;
1428
+ lastModified: number;
1429
+ status?: "running" | "finished" | "error";
1430
+ createdAt?: number;
1431
+ archived?: boolean;
1432
+ } & ({
1433
+ runtime?: undefined;
1434
+ } | {
1435
+ runtime: "local";
1436
+ cwd?: string;
1437
+ } | {
1438
+ runtime: "cloud";
1439
+ env?: CloudEnv;
1440
+ repos?: string[];
1441
+ });
1442
+ /**
1443
+ * Options for `Agent.list()`.
1444
+ *
1445
+ * @public
1446
+ */
1447
+ type ListAgentsOptions = {
1448
+ limit?: number;
1449
+ cursor?: string;
1450
+ } & ({
1451
+ runtime?: undefined;
1452
+ } | {
1453
+ runtime: "local";
1454
+ cwd?: string;
1455
+ } | {
1456
+ runtime: "cloud";
1457
+ prUrl?: string;
1458
+ includeArchived?: boolean;
1459
+ apiKey?: string;
1460
+ });
1461
+ /**
1462
+ * Options for `Agent.get()`.
1463
+ *
1464
+ * @public
1465
+ */
1466
+ interface GetAgentOptions {
1467
+ cwd?: string;
1468
+ apiKey?: string;
1469
+ }
1470
+ /**
1471
+ * Options for `Agent.listRuns()`.
1472
+ *
1473
+ * @public
1474
+ */
1475
+ type ListRunsOptions = {
1476
+ limit?: number;
1477
+ cursor?: string;
1478
+ } & ({
1479
+ runtime?: "local";
1480
+ cwd?: string;
1481
+ } | {
1482
+ runtime: "cloud";
1483
+ apiKey?: string;
1484
+ });
1485
+ /**
1486
+ * Options for `Agent.getRun()`. Cloud requires the parent `agentId`.
1487
+ *
1488
+ * @public
1489
+ */
1490
+ type GetRunOptions = {
1491
+ runtime?: "local";
1492
+ cwd?: string;
1493
+ } | {
1494
+ runtime: "cloud";
1495
+ agentId: string;
1496
+ apiKey?: string;
1497
+ };
1498
+ /**
1499
+ * Options for archive/unarchive/delete.
1500
+ *
1501
+ * @public
1502
+ */
1503
+ interface AgentOperationOptions {
1504
+ cwd?: string;
1505
+ apiKey?: string;
1506
+ }
1507
+ /**
1508
+ * Paginated list shape.
1509
+ *
1510
+ * @public
1511
+ */
1512
+ interface ListResult<T> {
1513
+ items: T[];
1514
+ nextCursor?: string;
1515
+ }
1516
+
1517
+ /**
1518
+ * Single tool call event. The internal `args` and `result` shapes are NOT stable.
1519
+ *
1520
+ * @public
1521
+ */
1522
+ interface ToolCall {
1523
+ callId: string;
1524
+ name: string;
1525
+ args?: unknown;
1526
+ result?: unknown;
1527
+ }
1528
+ /**
1529
+ * Incremental text token from the assistant.
1530
+ *
1531
+ * @public
1532
+ */
1533
+ interface TextDeltaUpdate {
1534
+ type: "text-delta";
1535
+ text: string;
1536
+ }
1537
+ /**
1538
+ * Incremental reasoning token.
1539
+ *
1540
+ * @public
1541
+ */
1542
+ interface ThinkingDeltaUpdate {
1543
+ type: "thinking-delta";
1544
+ text: string;
1545
+ }
1546
+ /**
1547
+ * Emitted when a reasoning block completes.
1548
+ *
1549
+ * @public
1550
+ */
1551
+ interface ThinkingCompletedUpdate {
1552
+ type: "thinking-completed";
1553
+ thinkingDurationMs: number;
1554
+ }
1555
+ /**
1556
+ * Tool call started — args committed.
1557
+ *
1558
+ * @public
1559
+ */
1560
+ interface ToolCallStartedUpdate {
1561
+ type: "tool-call-started";
1562
+ callId: string;
1563
+ toolCall: ToolCall;
1564
+ modelCallId: string;
1565
+ }
1566
+ /**
1567
+ * Tool call arguments streaming in incrementally.
1568
+ *
1569
+ * @public
1570
+ */
1571
+ interface PartialToolCallUpdate {
1572
+ type: "partial-tool-call";
1573
+ callId: string;
1574
+ toolCall: ToolCall;
1575
+ modelCallId: string;
1576
+ }
1577
+ /**
1578
+ * Tool call completed.
1579
+ *
1580
+ * @public
1581
+ */
1582
+ interface ToolCallCompletedUpdate {
1583
+ type: "tool-call-completed";
1584
+ callId: string;
1585
+ toolCall: ToolCall;
1586
+ modelCallId: string;
1587
+ }
1588
+ /**
1589
+ * Token count delta for usage tracking.
1590
+ *
1591
+ * @public
1592
+ */
1593
+ interface TokenDeltaUpdate {
1594
+ type: "token-delta";
1595
+ tokens: number;
1596
+ }
1597
+ /**
1598
+ * Conversation step started.
1599
+ *
1600
+ * @public
1601
+ */
1602
+ interface StepStartedUpdate {
1603
+ type: "step-started";
1604
+ stepId: number;
1605
+ }
1606
+ /**
1607
+ * Conversation step completed.
1608
+ *
1609
+ * @public
1610
+ */
1611
+ interface StepCompletedUpdate {
1612
+ type: "step-completed";
1613
+ stepId: number;
1614
+ stepDurationMs: number;
1615
+ }
1616
+ /**
1617
+ * Turn ended with usage summary.
1618
+ *
1619
+ * @public
1620
+ */
1621
+ interface TurnEndedUpdate {
1622
+ type: "turn-ended";
1623
+ usage?: {
1624
+ inputTokens: number;
1625
+ outputTokens: number;
1626
+ cacheReadTokens: number;
1627
+ cacheWriteTokens: number;
1628
+ };
1629
+ }
1630
+ /**
1631
+ * User message appended to the conversation.
1632
+ *
1633
+ * @public
1634
+ */
1635
+ interface UserMessageAppendedUpdate {
1636
+ type: "user-message-appended";
1637
+ userMessage: UserMessage;
1638
+ }
1639
+ /** @public */
1640
+ interface SummaryUpdate {
1641
+ type: "summary";
1642
+ summary: string;
1643
+ }
1644
+ /** @public */
1645
+ interface SummaryStartedUpdate {
1646
+ type: "summary-started";
1647
+ }
1648
+ /** @public */
1649
+ interface SummaryCompletedUpdate {
1650
+ type: "summary-completed";
1651
+ }
1652
+ /** @public */
1653
+ interface ShellOutputDeltaUpdate {
1654
+ type: "shell-output-delta";
1655
+ event: Record<string, unknown>;
1656
+ }
1657
+ /**
1658
+ * Lowest-level raw update from a run. Pass `onDelta` to `agent.send()` to
1659
+ * consume these. Finer-grained than `SDKMessage` events.
1660
+ *
1661
+ * @public
1662
+ */
1663
+ type InteractionUpdate = TextDeltaUpdate | ThinkingDeltaUpdate | ThinkingCompletedUpdate | ToolCallStartedUpdate | ToolCallCompletedUpdate | PartialToolCallUpdate | TokenDeltaUpdate | StepStartedUpdate | StepCompletedUpdate | TurnEndedUpdate | UserMessageAppendedUpdate | SummaryUpdate | SummaryStartedUpdate | SummaryCompletedUpdate | ShellOutputDeltaUpdate;
1664
+
1665
+ /**
1666
+ * Plain assistant message in a conversation history.
1667
+ *
1668
+ * @public
1669
+ */
1670
+ interface AssistantMessage {
1671
+ text: string;
1672
+ }
1673
+ /**
1674
+ * Reasoning step in a conversation history.
1675
+ *
1676
+ * @public
1677
+ */
1678
+ interface ThinkingMessage {
1679
+ text: string;
1680
+ thinkingDurationMs?: number;
1681
+ }
1682
+ /**
1683
+ * User-authored message in a conversation history.
1684
+ *
1685
+ * @public
1686
+ */
1687
+ interface UserMessage {
1688
+ text: string;
1689
+ }
1690
+ /**
1691
+ * Shell command executed during a run.
1692
+ *
1693
+ * @public
1694
+ */
1695
+ interface ShellCommand {
1696
+ command: string;
1697
+ workingDirectory?: string;
1698
+ }
1699
+ /**
1700
+ * Output of a shell command.
1701
+ *
1702
+ * @public
1703
+ */
1704
+ interface ShellOutput {
1705
+ stdout: string;
1706
+ stderr: string;
1707
+ exitCode: number;
1708
+ }
1709
+ /**
1710
+ * Single step inside an agent turn.
1711
+ *
1712
+ * @public
1713
+ */
1714
+ type ConversationStep = {
1715
+ type: "assistantMessage";
1716
+ message: AssistantMessage;
1717
+ } | {
1718
+ type: "toolCall";
1719
+ message: ToolCall;
1720
+ } | {
1721
+ type: "thinkingMessage";
1722
+ message: ThinkingMessage;
1723
+ };
1724
+ /**
1725
+ * Agent turn: user message + assistant/tool/thinking steps.
1726
+ *
1727
+ * @public
1728
+ */
1729
+ interface AgentConversationTurn {
1730
+ userMessage?: UserMessage;
1731
+ steps: ConversationStep[];
1732
+ }
1733
+ /**
1734
+ * Shell turn: a command and its output.
1735
+ *
1736
+ * @public
1737
+ */
1738
+ interface ShellConversationTurn {
1739
+ shellCommand?: ShellCommand;
1740
+ shellOutput?: ShellOutput;
1741
+ }
1742
+ /**
1743
+ * Structured per-turn view of a run.
1744
+ *
1745
+ * @public
1746
+ */
1747
+ type ConversationTurn = {
1748
+ type: "agentConversationTurn";
1749
+ turn: AgentConversationTurn;
1750
+ } | {
1751
+ type: "shellConversationTurn";
1752
+ turn: ShellConversationTurn;
1753
+ };
1754
+
1755
+ /**
1756
+ * Plain text content block emitted by the assistant or user.
1757
+ *
1758
+ * @public
1759
+ */
1760
+ interface TextBlock {
1761
+ type: "text";
1762
+ text: string;
1763
+ }
1764
+ /**
1765
+ * Tool invocation block emitted by the assistant.
1766
+ *
1767
+ * @public
1768
+ */
1769
+ interface ToolUseBlock {
1770
+ type: "tool_use";
1771
+ id: string;
1772
+ name: string;
1773
+ /** Tool args are not part of the stable schema. Treat as unknown and parse defensively. */
1774
+ input: unknown;
1775
+ }
1776
+ /**
1777
+ * Init metadata. Emitted once at the start of a run.
1778
+ *
1779
+ * @public
1780
+ */
1781
+ interface SDKSystemMessage {
1782
+ type: "system";
1783
+ subtype?: "init";
1784
+ agent_id: string;
1785
+ run_id: string;
1786
+ model?: ModelSelection;
1787
+ tools?: string[];
1788
+ }
1789
+ /**
1790
+ * Echo of the user prompt for this run.
1791
+ *
1792
+ * @public
1793
+ */
1794
+ interface SDKUserMessageEvent {
1795
+ type: "user";
1796
+ agent_id: string;
1797
+ run_id: string;
1798
+ message: {
1799
+ role: "user";
1800
+ content: TextBlock[];
1801
+ };
1802
+ }
1803
+ /**
1804
+ * Model text output for this run.
1805
+ *
1806
+ * @public
1807
+ */
1808
+ interface SDKAssistantMessage {
1809
+ type: "assistant";
1810
+ agent_id: string;
1811
+ run_id: string;
1812
+ message: {
1813
+ role: "assistant";
1814
+ content: Array<TextBlock | ToolUseBlock>;
1815
+ };
1816
+ }
1817
+ /**
1818
+ * Reasoning content.
1819
+ *
1820
+ * @public
1821
+ */
1822
+ interface SDKThinkingMessage {
1823
+ type: "thinking";
1824
+ agent_id: string;
1825
+ run_id: string;
1826
+ text: string;
1827
+ thinking_duration_ms?: number;
1828
+ }
1829
+ /**
1830
+ * Tool invocation lifecycle event. Emitted at start with `args`, then again on
1831
+ * completion with `result`.
1832
+ *
1833
+ * Tool `args` and `result` are NOT part of the stable schema — treat as unknown.
1834
+ *
1835
+ * @public
1836
+ */
1837
+ interface SDKToolUseMessage {
1838
+ type: "tool_call";
1839
+ agent_id: string;
1840
+ run_id: string;
1841
+ call_id: string;
1842
+ name: string;
1843
+ status: "running" | "completed" | "error";
1844
+ args?: unknown;
1845
+ result?: unknown;
1846
+ truncated?: {
1847
+ args?: boolean;
1848
+ result?: boolean;
1849
+ };
1850
+ }
1851
+ /**
1852
+ * Cloud run lifecycle transitions.
1853
+ *
1854
+ * @public
1855
+ */
1856
+ interface SDKStatusMessage {
1857
+ type: "status";
1858
+ agent_id: string;
1859
+ run_id: string;
1860
+ status: "CREATING" | "RUNNING" | "FINISHED" | "ERROR" | "CANCELLED" | "EXPIRED";
1861
+ message?: string;
1862
+ }
1863
+ /**
1864
+ * Task-level milestones and summaries.
1865
+ *
1866
+ * @public
1867
+ */
1868
+ interface SDKTaskMessage {
1869
+ type: "task";
1870
+ agent_id: string;
1871
+ run_id: string;
1872
+ status?: string;
1873
+ text?: string;
1874
+ }
1875
+ /**
1876
+ * Awaiting user input or approval.
1877
+ *
1878
+ * @public
1879
+ */
1880
+ interface SDKRequestMessage {
1881
+ type: "request";
1882
+ agent_id: string;
1883
+ run_id: string;
1884
+ request_id: string;
1885
+ }
1886
+ /**
1887
+ * Partial object emitted during `Agent.streamObject<T>` streaming (ADR D45).
1888
+ * `partial` is `DeepPartial<z.infer<T>>` at the typed iterator level but
1889
+ * erased to `unknown` here because SDKMessage union is non-generic.
1890
+ *
1891
+ * @public
1892
+ */
1893
+ interface SDKObjectDelta {
1894
+ type: "object_delta";
1895
+ agent_id: string;
1896
+ run_id: string;
1897
+ partial: unknown;
1898
+ attempt: number;
1899
+ }
1900
+ /**
1901
+ * Discriminated union of all stream events. Discriminate on `type`.
1902
+ *
1903
+ * All events include `agent_id` and `run_id`.
1904
+ *
1905
+ * @public
1906
+ */
1907
+ type SDKMessage = SDKSystemMessage | SDKUserMessageEvent | SDKAssistantMessage | SDKThinkingMessage | SDKToolUseMessage | SDKStatusMessage | SDKTaskMessage | SDKRequestMessage | SDKObjectDelta;
1908
+
1909
+ /**
1910
+ * Public type contract for token usage + cost tracking (ADRs D376-D379).
1911
+ *
1912
+ * Surfaces via `RunResult.usage` + `RunResult.cost` after every Run.
1913
+ * Re-exported through the package barrel; consumers import from
1914
+ * `@theokit/sdk`.
1915
+ *
1916
+ * @public
1917
+ */
1918
+ /**
1919
+ * Token usage observed during a Run. 5 closed buckets (D376) cover
1920
+ * 100% of providers in 2026: OpenAI Chat / OpenAI Responses (o-series
1921
+ * with reasoning) / Anthropic Messages (with prompt caching).
1922
+ *
1923
+ * `totalTokens` is derived (`inputTokens + outputTokens`); EC-10
1924
+ * invariant: SDK must never emit `totalTokens !== inputTokens + outputTokens`.
1925
+ *
1926
+ * `requests[]` is the per-request breakdown (mirror openai-agents-python)
1927
+ * — populated only when the run made > 1 LLM call.
1928
+ */
1929
+ interface TokenUsage {
1930
+ readonly inputTokens: number;
1931
+ readonly outputTokens: number;
1932
+ readonly cacheReadTokens?: number;
1933
+ readonly cacheWriteTokens?: number;
1934
+ readonly reasoningTokens?: number;
1935
+ readonly totalTokens: number;
1936
+ /** Per-request breakdown; absent when the run made a single LLM call. */
1937
+ readonly requests?: ReadonlyArray<Omit<TokenUsage, "requests">>;
1938
+ }
1939
+ /**
1940
+ * Cost confidence level (D377).
1941
+ * - `actual`: returned by a provider billing API (e.g. OpenRouter `/generation`).
1942
+ * - `estimated`: computed from bundled pricing snapshot.
1943
+ * - `included`: subscription-included route (Codex CLI, Claude Pro).
1944
+ * - `unknown`: pricing data unavailable; `amountUsd` is undefined.
1945
+ */
1946
+ type CostStatus = "actual" | "estimated" | "included" | "unknown";
1947
+ /** Source of the cost figure for caller-side audit. */
1948
+ type CostSource = "openrouter_api" | "litellm_snapshot" | "user_override" | "subscription_included" | "unknown";
1949
+ /**
1950
+ * Cost breakdown attached to `RunResult.cost`. When `status === "unknown"`,
1951
+ * `amountUsd` is `undefined` — DO NOT default to 0 (mentira). UI exibe
1952
+ * `n/a` para unknown, `~$1.23` para estimated, `$1.23` para actual.
1953
+ */
1954
+ interface CostBreakdown {
1955
+ readonly amountUsd: number | undefined;
1956
+ readonly status: CostStatus;
1957
+ readonly currency: "USD";
1958
+ readonly source: CostSource;
1959
+ readonly pricingVersion: string | undefined;
1960
+ readonly notes?: ReadonlyArray<string>;
1961
+ /** Per-bucket detail (in USD) for caller analytics. */
1962
+ readonly detail?: {
1963
+ readonly input?: number;
1964
+ readonly output?: number;
1965
+ readonly cacheRead?: number;
1966
+ readonly cacheWrite?: number;
1967
+ readonly reasoning?: number;
1968
+ };
1969
+ }
1970
+
1971
+ /**
1972
+ * Lifecycle status of a {@link Run}.
1973
+ *
1974
+ * @public
1975
+ */
1976
+ type RunStatus = "running" | "finished" | "error" | "cancelled";
1977
+ /**
1978
+ * Operations that may or may not be supported on a given {@link Run}, or on
1979
+ * its parent agent.
1980
+ *
1981
+ * Runtime-specific availability — query at runtime with `run.supports(op)` and
1982
+ * read the human reason via `run.unsupportedReason(op)`.
1983
+ *
1984
+ * @public
1985
+ */
1986
+ type RunOperation = "stream" | "wait" | "cancel" | "conversation" | "listArtifacts" | "downloadArtifact" | "runUntil" | "fork" | "usePersonality" | "workflow";
1987
+ /**
1988
+ * Git metadata attached to cloud runs.
1989
+ *
1990
+ * @public
1991
+ */
1992
+ interface RunGitInfo {
1993
+ branches: Array<{
1994
+ repoUrl: string;
1995
+ branch?: string;
1996
+ prUrl?: string;
1997
+ }>;
1998
+ }
1999
+ /**
2000
+ * Terminal result of a {@link Run}.
2001
+ *
2002
+ * @public
2003
+ */
2004
+ interface RunResult {
2005
+ id: string;
2006
+ status: "finished" | "error" | "cancelled";
2007
+ result?: string;
2008
+ model?: ModelSelection;
2009
+ durationMs?: number;
2010
+ git?: RunGitInfo;
2011
+ /**
2012
+ * Structured error detail, populated when `status === "error"`. Surfaces
2013
+ * the diagnostic that emit-error-event pushes into the stream so callers
2014
+ * that don't drain `run.stream()` still get the cause via `run.wait()`.
2015
+ *
2016
+ * For successful runs (`status: "finished"`) this is undefined.
2017
+ *
2018
+ * @public
2019
+ */
2020
+ error?: RunErrorDetail;
2021
+ /**
2022
+ * Token usage observed for this run (ADR D376). Populated in every
2023
+ * status where ≥1 LLM call completed — including partial-failure
2024
+ * runs (EC-5). `undefined` only when zero LLM calls executed (e.g.,
2025
+ * abort before send).
2026
+ *
2027
+ * @public
2028
+ */
2029
+ usage?: TokenUsage;
2030
+ /**
2031
+ * Estimated/actual USD cost for this run (ADR D377). Always paired
2032
+ * with `usage` when populated. `cost.status` tells caller how to
2033
+ * trust the figure.
2034
+ *
2035
+ * @public
2036
+ */
2037
+ cost?: CostBreakdown;
2038
+ }
2039
+ /**
2040
+ * Structured error attached to a {@link RunResult} when the underlying run
2041
+ * transitioned to `"error"` status. `message` is always present; `code` is
2042
+ * a stable identifier suitable for branching (e.g. `"llm_4xx"`,
2043
+ * `"tool_dispatch_failed"`, `"mcp_init_failed"`); `cause` is the raw error
2044
+ * for further inspection when available.
2045
+ *
2046
+ * @public
2047
+ */
2048
+ interface RunErrorDetail {
2049
+ message: string;
2050
+ code?: string;
2051
+ cause?: unknown;
2052
+ }
2053
+ /**
2054
+ * Dimensions of an inline image attachment.
2055
+ *
2056
+ * @public
2057
+ */
2058
+ interface SDKImageDimension {
2059
+ width: number;
2060
+ height: number;
2061
+ }
2062
+ /**
2063
+ * Either a remote URL or inline base64 payload.
2064
+ *
2065
+ * @public
2066
+ */
2067
+ type SDKImage = {
2068
+ url: string;
2069
+ dimension?: SDKImageDimension;
2070
+ } | {
2071
+ data: string;
2072
+ mimeType: string;
2073
+ dimension?: SDKImageDimension;
2074
+ };
2075
+ /**
2076
+ * Structured form of `agent.send()`'s message argument. Use it to send images
2077
+ * alongside text.
2078
+ *
2079
+ * @public
2080
+ */
2081
+ interface SDKUserMessage {
2082
+ text: string;
2083
+ images?: SDKImage[];
2084
+ }
2085
+ /**
2086
+ * Per-send overrides and callbacks.
2087
+ *
2088
+ * @public
2089
+ */
2090
+ interface SendOptions {
2091
+ model?: ModelSelection;
2092
+ /**
2093
+ * Per-call system prompt override. Wins over `AgentOptions.systemPrompt`.
2094
+ * String only — for dynamic resolvers, configure on `AgentOptions`. An
2095
+ * empty string is honoured (it explicitly clears the system context).
2096
+ */
2097
+ systemPrompt?: string;
2098
+ /** Fully replaces creation-time servers for this run (not merged). */
2099
+ mcpServers?: Record<string, McpServerConfig>;
2100
+ /**
2101
+ * Per-call inline custom tools. Fully replaces `AgentOptions.tools` for
2102
+ * this run (not merged). Local runtime only — cloud agents reject any
2103
+ * non-empty per-call tools array with the same error code as creation
2104
+ * (`cloud_custom_tools_rejected`). Semantics:
2105
+ * - `undefined` → fall back to `AgentOptions.tools`
2106
+ * - `[]` → explicitly clear (no custom tools for this run)
2107
+ * - `[t1, t2]` → use exactly these tools for this run
2108
+ */
2109
+ tools?: CustomTool[];
2110
+ onStep?: (args: {
2111
+ step: ConversationStep;
2112
+ }) => void | Promise<void>;
2113
+ onDelta?: (args: {
2114
+ update: InteractionUpdate;
2115
+ }) => void | Promise<void>;
2116
+ /** Local agents only. Expire a stuck active run before starting this message. */
2117
+ local?: {
2118
+ force?: boolean;
2119
+ };
2120
+ /**
2121
+ * Optional `AbortSignal` propagated to memory adapter `pre_user_send`
2122
+ * hooks (EC-H). Note: the LLM HTTP call itself is NOT cancellable
2123
+ * mid-stream — same constraint as `Agent.batch` (ADR D140).
2124
+ *
2125
+ * @public
2126
+ */
2127
+ signal?: AbortSignal;
2128
+ /**
2129
+ * Opt-in task wrapping (ADRs D363, D374). When truthy, the entire
2130
+ * run is registered as a `Task` in the SDK's observable registry —
2131
+ * caller can list / inspect / cancel / subscribe via the `Task`
2132
+ * namespace. Default behavior (no `task` option) is byte-identical
2133
+ * to v1.1 (no Task overhead).
2134
+ *
2135
+ * Accepts:
2136
+ * - `true` — auto-generate task id; no extra metadata.
2137
+ * - `{ id, meta }` — user-supplied id (D368 grammar enforced) and/or
2138
+ * metadata attached to the handle's `meta` field.
2139
+ *
2140
+ * The work-fn `signal` is **merged** with `options.signal` (whichever
2141
+ * aborts first wins). Local agents only — CloudAgent throws
2142
+ * `UnsupportedTaskOperationError` (D370).
2143
+ *
2144
+ * @public
2145
+ */
2146
+ task?: true | {
2147
+ id?: string;
2148
+ meta?: Record<string, unknown>;
2149
+ };
2150
+ }
2151
+ /**
2152
+ * Handle to a single prompt submission.
2153
+ *
2154
+ * @public
2155
+ */
2156
+ interface Run {
2157
+ readonly id: string;
2158
+ readonly agentId: string;
2159
+ readonly status: RunStatus;
2160
+ readonly result?: string;
2161
+ readonly model?: ModelSelection;
2162
+ readonly durationMs?: number;
2163
+ readonly git?: RunGitInfo;
2164
+ readonly createdAt?: number;
2165
+ /** AsyncGenerator of normalized stream events. Discriminate on `event.type`. */
2166
+ stream(): AsyncGenerator<SDKMessage, void>;
2167
+ /** Resolves to the terminal {@link RunResult}. */
2168
+ wait(): Promise<RunResult>;
2169
+ /** Move status to `"cancelled"`, abort the stream, stop in-flight tool calls. */
2170
+ cancel(): Promise<void>;
2171
+ /** Structured per-turn view of the conversation. */
2172
+ conversation(): Promise<ConversationTurn[]>;
2173
+ /** Whether the given operation is available on this run's runtime. */
2174
+ supports(operation: RunOperation): boolean;
2175
+ /** Human-readable reason that `supports(operation)` returned `false`. */
2176
+ unsupportedReason(operation: RunOperation): string | undefined;
2177
+ /** Subscribe to status changes. Returns an unsubscribe function. */
2178
+ onDidChangeStatus(listener: (status: RunStatus) => void): () => void;
2179
+ }
2180
+
2181
+ export { HandoffReceiverDisposedError as $, type AgentOptions as A, type ContextBudget as B, type CloudOptions as C, type ContextManagerKind as D, type ContextSnapshot as E, type ContextSource as F, type GetAgentOptions as G, type HandoffOptions as H, type ContextSourceStatus as I, type ConversationStep as J, type ConversationTurn as K, type LocalOptions as L, type ModelSelection as M, type CostBreakdown as N, type CostSource as O, type ProviderRoutingSettings as P, type CostStatus as Q, type RunResult as R, type SystemPromptResolver as S, type GoalEvent as T, type GoalOptions as U, type GoalResult as V, type HandoffContext as W, type HandoffHistory as X, HandoffLoopError as Y, HandoffNameCollisionError as Z, HandoffPairLoopError as _, type MemorySettings as a, type ThinkingMessage as a$, type HandoffResult as a0, HandoffSelfReferenceError as a1, type InteractionUpdate as a2, type InvalidateCacheOptions as a3, type McpAuthConfig as a4, type McpHttpServerConfig as a5, type McpOAuthConfig as a6, type McpStdioServerConfig as a7, type MemoryAdapter as a8, type MemoryAdapterCapabilities as a9, type SDKRequestMessage as aA, type SDKStatusMessage as aB, type SDKSystemMessage as aC, type SDKTaskMessage as aD, type SDKThinkingMessage as aE, type SDKToolUseMessage as aF, type SDKUserMessage as aG, type SDKUserMessageEvent as aH, type SendOptions as aI, type SettingSource as aJ, type ShellCommand as aK, type ShellConversationTurn as aL, type ShellOutput as aM, type ShellOutputDeltaUpdate as aN, type StepCompletedUpdate as aO, type StepStartedUpdate as aP, type SummaryCompletedUpdate as aQ, type SummaryStartedUpdate as aR, type SummaryUpdate as aS, type SystemPromptContext as aT, type SystemPromptMemoryFact as aU, type SystemPromptSkillRef as aV, type TelemetrySettings as aW, type TextBlock as aX, type TextDeltaUpdate as aY, type ThinkingCompletedUpdate as aZ, type ThinkingDeltaUpdate as a_, type MemoryContext as aa, type MemoryFact as ab, type MemoryRevision as ac, type MemoryToolSchema as ad, type MemoryTurnMessage as ae, type ModelParameterValue as af, type PartialToolCallUpdate as ag, type PersonalityPreset as ah, type ProviderCapability as ai, type ProviderRoute as aj, type ResolvedProviderRoute as ak, type RunErrorDetail as al, type RunGitInfo as am, type RunOperation as an, type RunStatus as ao, type RunUntilIterator as ap, type SDKAgentPlugins as aq, type SDKAgentSkills as ar, type SDKArtifact as as, type SDKAssistantMessage as at, type SDKContextManager as au, type SDKImage as av, type SDKImageDimension as aw, type SDKObjectDelta as ax, type SDKPluginMetadata as ay, type SDKProvidersManager as az, type CustomTool as b, type TokenDeltaUpdate as b0, type TokenUsage as b1, type ToolCall as b2, type ToolCallCompletedUpdate as b3, type ToolCallStartedUpdate as b4, type ToolUseBlock as b5, type TurnEndedUpdate as b6, type UserMessage as b7, type UserMessageAppendedUpdate as b8, type McpServerConfig as c, type AgentDefinition as d, type ContextSettings as e, type PluginsSettings as f, type SkillsSettings as g, type SDKAgent as h, type ListAgentsOptions as i, type ListResult as j, type SDKAgentInfo as k, type ListRunsOptions as l, type Run as m, type GetRunOptions as n, type AgentOperationOptions as o, type HandoffDescriptor as p, type ConversationStorageAdapter as q, type StoredMessage as r, type MemoryId as s, type SDKProvider as t, type SDKMessage as u, type AgentConversationTurn as v, type AgentMemory as w, type AssistantMessage as x, type CloudEnv as y, type CloudRepo as z };