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