@theokit/sdk 1.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (369) hide show
  1. package/CHANGELOG.md +1571 -0
  2. package/LICENSE +201 -0
  3. package/README.md +80 -0
  4. package/bin/theokit-migrate-config.mjs +269 -0
  5. package/bin/theokit-migrate-memory.mjs +116 -0
  6. package/dist/agent-builder.d.ts +52 -0
  7. package/dist/agent-factory.d.ts +39 -0
  8. package/dist/agent.d.ts +175 -0
  9. package/dist/batch.d.ts +11 -0
  10. package/dist/budget.d.ts +48 -0
  11. package/dist/cache.d.ts +74 -0
  12. package/dist/cron-1yxL3K2S.d.cts +221 -0
  13. package/dist/cron-BYVdYzob.d.ts +221 -0
  14. package/dist/cron.cjs +14655 -0
  15. package/dist/cron.cjs.map +1 -0
  16. package/dist/cron.d.cts +3 -0
  17. package/dist/cron.d.ts +71 -0
  18. package/dist/cron.js +14652 -0
  19. package/dist/cron.js.map +1 -0
  20. package/dist/define-tool.d.ts +35 -0
  21. package/dist/errors-CK8brCJ1.d.cts +448 -0
  22. package/dist/errors-CvAeEWgE.d.ts +448 -0
  23. package/dist/errors.cjs +255 -0
  24. package/dist/errors.cjs.map +1 -0
  25. package/dist/errors.d.cts +3 -0
  26. package/dist/errors.d.ts +356 -0
  27. package/dist/errors.js +238 -0
  28. package/dist/errors.js.map +1 -0
  29. package/dist/eval.cjs +14826 -0
  30. package/dist/eval.cjs.map +1 -0
  31. package/dist/eval.d.cts +35 -0
  32. package/dist/eval.d.ts +35 -0
  33. package/dist/eval.js +14821 -0
  34. package/dist/eval.js.map +1 -0
  35. package/dist/generate-object.d.ts +67 -0
  36. package/dist/handoff.d.ts +55 -0
  37. package/dist/index.cjs +17127 -0
  38. package/dist/index.cjs.map +1 -0
  39. package/dist/index.d.cts +1878 -0
  40. package/dist/index.d.ts +24 -0
  41. package/dist/index.js +17095 -0
  42. package/dist/index.js.map +1 -0
  43. package/dist/internal/agent-loop/loop-types.d.ts +29 -0
  44. package/dist/internal/agent-loop/loop.d.ts +2 -0
  45. package/dist/internal/agent-loop/message-builders.d.ts +6 -0
  46. package/dist/internal/agent-loop/tool-dispatch.d.ts +4 -0
  47. package/dist/internal/agent-loop/usage-and-cost.d.ts +25 -0
  48. package/dist/internal/budget/calendar-window.d.ts +19 -0
  49. package/dist/internal/budget/compute-cost.d.ts +28 -0
  50. package/dist/internal/budget/enforcement.d.ts +32 -0
  51. package/dist/internal/budget/ledger.d.ts +25 -0
  52. package/dist/internal/budget/normalize-usage.d.ts +27 -0
  53. package/dist/internal/budget/pricing-registry.d.ts +36 -0
  54. package/dist/internal/budget/registry.d.ts +16 -0
  55. package/dist/internal/budget/usage-accumulator.d.ts +31 -0
  56. package/dist/internal/cache/cosine.d.ts +14 -0
  57. package/dist/internal/cache/embed-helper.d.ts +15 -0
  58. package/dist/internal/cache/key.d.ts +15 -0
  59. package/dist/internal/cache/lookup.d.ts +28 -0
  60. package/dist/internal/cache/store-handler.d.ts +24 -0
  61. package/dist/internal/cache/store-json.d.ts +48 -0
  62. package/dist/internal/cache/store.d.ts +54 -0
  63. package/dist/internal/cache/telemetry.d.ts +20 -0
  64. package/dist/internal/cache/ttl.d.ts +11 -0
  65. package/dist/internal/catalog/fixtures.d.ts +16 -0
  66. package/dist/internal/catalog/local-models.d.ts +24 -0
  67. package/dist/internal/cron/run-job.d.ts +1 -0
  68. package/dist/internal/cron/scheduler.d.ts +1 -0
  69. package/dist/internal/cron/store.d.ts +1 -0
  70. package/dist/internal/cron/validate.d.ts +1 -0
  71. package/dist/internal/env.d.ts +1 -0
  72. package/dist/internal/errors/mappers/anthropic.d.ts +30 -0
  73. package/dist/internal/errors/mappers/bedrock.d.ts +16 -0
  74. package/dist/internal/errors/mappers/ollama.d.ts +41 -0
  75. package/dist/internal/errors/mappers/openai-compatible.d.ts +25 -0
  76. package/dist/internal/errors/mappers/shared.d.ts +10 -0
  77. package/dist/internal/errors/mappers/vertex.d.ts +15 -0
  78. package/dist/internal/eval/aggregate.d.ts +9 -0
  79. package/dist/internal/eval/dataset-iter.d.ts +9 -0
  80. package/dist/internal/eval/runner.d.ts +9 -0
  81. package/dist/internal/eval/single-flight.d.ts +16 -0
  82. package/dist/internal/eval/telemetry.d.ts +23 -0
  83. package/dist/internal/fixture-mode.d.ts +16 -0
  84. package/dist/internal/handoff/dispatcher.d.ts +29 -0
  85. package/dist/internal/handoff/registry.d.ts +23 -0
  86. package/dist/internal/handoff/telemetry.d.ts +18 -0
  87. package/dist/internal/handoff/tool-injector.d.ts +34 -0
  88. package/dist/internal/http.d.ts +1 -0
  89. package/dist/internal/ids.d.ts +1 -0
  90. package/dist/internal/judge/judge-call.d.ts +35 -0
  91. package/dist/internal/judge/parse-verdict.d.ts +11 -0
  92. package/dist/internal/judge/types.d.ts +17 -0
  93. package/dist/internal/llm/anthropic-shared.d.ts +89 -0
  94. package/dist/internal/llm/anthropic.d.ts +9 -0
  95. package/dist/internal/llm/bedrock-anthropic.d.ts +36 -0
  96. package/dist/internal/llm/bedrock-token-cache.d.ts +18 -0
  97. package/dist/internal/llm/credential-pool-context.d.ts +11 -0
  98. package/dist/internal/llm/credential-pool-types.d.ts +22 -0
  99. package/dist/internal/llm/credential-pool.d.ts +18 -0
  100. package/dist/internal/llm/fallback-client.d.ts +1 -0
  101. package/dist/internal/llm/fault-injection.d.ts +50 -0
  102. package/dist/internal/llm/finish.d.ts +1 -0
  103. package/dist/internal/llm/model-identifier.d.ts +24 -0
  104. package/dist/internal/llm/ollama-native.d.ts +27 -0
  105. package/dist/internal/llm/openai.d.ts +9 -0
  106. package/dist/internal/llm/pool-aware-client.d.ts +16 -0
  107. package/dist/internal/llm/router.d.ts +17 -0
  108. package/dist/internal/llm/sse.d.ts +9 -0
  109. package/dist/internal/llm/stream-relay.d.ts +17 -0
  110. package/dist/internal/llm/types.d.ts +70 -0
  111. package/dist/internal/llm/vertex-anthropic.d.ts +40 -0
  112. package/dist/internal/llm/vertex-auth.d.ts +30 -0
  113. package/dist/internal/llm/vertex-gemini.d.ts +28 -0
  114. package/dist/internal/llm/vertex-router.d.ts +21 -0
  115. package/dist/internal/mcp/client.d.ts +16 -0
  116. package/dist/internal/memory/active-memory-cache.d.ts +10 -0
  117. package/dist/internal/memory/active-memory.d.ts +45 -0
  118. package/dist/internal/memory/adapters/catalog.d.ts +1 -0
  119. package/dist/internal/memory/adapters/deepinfra-embedding.d.ts +2 -0
  120. package/dist/internal/memory/adapters/mistral-embedding.d.ts +2 -0
  121. package/dist/internal/memory/adapters/ollama-embedding.d.ts +34 -0
  122. package/dist/internal/memory/adapters/openai-compatible.d.ts +23 -0
  123. package/dist/internal/memory/adapters/openai-embedding.d.ts +2 -0
  124. package/dist/internal/memory/adapters/openrouter-embedding.d.ts +2 -0
  125. package/dist/internal/memory/adapters/voyage-embedding.d.ts +2 -0
  126. package/dist/internal/memory/atomic-write.d.ts +7 -0
  127. package/dist/internal/memory/chunk-markdown.d.ts +2 -0
  128. package/dist/internal/memory/circuit-breaker.d.ts +22 -0
  129. package/dist/internal/memory/cwd-mutex.d.ts +1 -0
  130. package/dist/internal/memory/dreaming/diary.d.ts +4 -0
  131. package/dist/internal/memory/dreaming/phases.d.ts +15 -0
  132. package/dist/internal/memory/dreaming/run.d.ts +10 -0
  133. package/dist/internal/memory/embedding-adapter.d.ts +42 -0
  134. package/dist/internal/memory/embedding-cache.d.ts +1 -0
  135. package/dist/internal/memory/index-db.d.ts +10 -0
  136. package/dist/internal/memory/index-manager-dispatch.d.ts +23 -0
  137. package/dist/internal/memory/index-manager.d.ts +68 -0
  138. package/dist/internal/memory/index-schema.d.ts +21 -0
  139. package/dist/internal/memory/lance-index.d.ts +32 -0
  140. package/dist/internal/memory/lance-memory-adapter.d.ts +43 -0
  141. package/dist/internal/memory/markdown-store.d.ts +16 -0
  142. package/dist/internal/memory/memory-index.d.ts +52 -0
  143. package/dist/internal/memory/migrate-sqlite-to-lance.d.ts +15 -0
  144. package/dist/internal/memory/migration.d.ts +9 -0
  145. package/dist/internal/memory/reader.d.ts +8 -0
  146. package/dist/internal/memory/session-loader.d.ts +1 -0
  147. package/dist/internal/memory/session-summary-writer.d.ts +2 -0
  148. package/dist/internal/memory/sqlite-vec-loader.d.ts +3 -0
  149. package/dist/internal/memory/tools.d.ts +14 -0
  150. package/dist/internal/memory/transcript-store.d.ts +1 -0
  151. package/dist/internal/memory/types.d.ts +17 -0
  152. package/dist/internal/memory/vec-index.d.ts +28 -0
  153. package/dist/internal/memory/wiki-loader.d.ts +2 -0
  154. package/dist/internal/observability/tracer-loader.d.ts +20 -0
  155. package/dist/internal/persistence/atomic-write.d.ts +1 -0
  156. package/dist/internal/persistence/conversation-storage-fs.d.ts +37 -0
  157. package/dist/internal/persistence/conversation-storage-memory.d.ts +24 -0
  158. package/dist/internal/persistence/cwd-mutex.d.ts +1 -0
  159. package/dist/internal/persistence/file-lock.d.ts +14 -0
  160. package/dist/internal/persistence/fts5-sanitize.d.ts +16 -0
  161. package/dist/internal/persistence/markdown-config-loader.d.ts +35 -0
  162. package/dist/internal/persistence/paths.d.ts +19 -0
  163. package/dist/internal/persistence/persistence-schema.d.ts +17 -0
  164. package/dist/internal/persistence/schema-version.d.ts +13 -0
  165. package/dist/internal/persistence/sqlite-wal.d.ts +10 -0
  166. package/dist/internal/personality/context.d.ts +17 -0
  167. package/dist/internal/personality/registry.d.ts +17 -0
  168. package/dist/internal/personality/store.d.ts +27 -0
  169. package/dist/internal/personality/switch.d.ts +36 -0
  170. package/dist/internal/personality/types.d.ts +18 -0
  171. package/dist/internal/plugins/context.d.ts +31 -0
  172. package/dist/internal/plugins/manager.d.ts +37 -0
  173. package/dist/internal/plugins/types.d.ts +102 -0
  174. package/dist/internal/providers/builtin/anthropic.d.ts +2 -0
  175. package/dist/internal/providers/builtin/bedrock.d.ts +25 -0
  176. package/dist/internal/providers/builtin/gemini.d.ts +10 -0
  177. package/dist/internal/providers/builtin/index.d.ts +19 -0
  178. package/dist/internal/providers/builtin/llamacpp.d.ts +1 -0
  179. package/dist/internal/providers/builtin/lmstudio.d.ts +1 -0
  180. package/dist/internal/providers/builtin/ollama.d.ts +17 -0
  181. package/dist/internal/providers/builtin/openai.d.ts +2 -0
  182. package/dist/internal/providers/builtin/openrouter.d.ts +2 -0
  183. package/dist/internal/providers/builtin/vertex.d.ts +27 -0
  184. package/dist/internal/providers/discovery.d.ts +14 -0
  185. package/dist/internal/providers/index.d.ts +8 -0
  186. package/dist/internal/providers/registry.d.ts +12 -0
  187. package/dist/internal/providers/types.d.ts +27 -0
  188. package/dist/internal/runtime/abort-utils.d.ts +21 -0
  189. package/dist/internal/runtime/agent-factory-registry.d.ts +16 -0
  190. package/dist/internal/runtime/agent-registry-store.d.ts +61 -0
  191. package/dist/internal/runtime/agent-registry.d.ts +34 -0
  192. package/dist/internal/runtime/agent-session-store.d.ts +3 -0
  193. package/dist/internal/runtime/agent-session.d.ts +2 -0
  194. package/dist/internal/runtime/async-local-storage.d.ts +20 -0
  195. package/dist/internal/runtime/async-semaphore.d.ts +24 -0
  196. package/dist/internal/runtime/budget.d.ts +36 -0
  197. package/dist/internal/runtime/cloud-agent.d.ts +1 -0
  198. package/dist/internal/runtime/cloud-config-serializer.d.ts +3 -0
  199. package/dist/internal/runtime/cloud-payload-types.d.ts +56 -0
  200. package/dist/internal/runtime/cloud-run.d.ts +1 -0
  201. package/dist/internal/runtime/cloud-tool-parity.d.ts +1 -0
  202. package/dist/internal/runtime/context-aggregator.d.ts +26 -0
  203. package/dist/internal/runtime/context-discovery-runner.d.ts +27 -0
  204. package/dist/internal/runtime/context-discovery.d.ts +21 -0
  205. package/dist/internal/runtime/context-frontmatter.d.ts +16 -0
  206. package/dist/internal/runtime/context-import-resolver.d.ts +24 -0
  207. package/dist/internal/runtime/context-loaders.d.ts +42 -0
  208. package/dist/internal/runtime/context-manager.d.ts +11 -0
  209. package/dist/internal/runtime/context-mdc-parser.d.ts +24 -0
  210. package/dist/internal/runtime/default-model.d.ts +1 -0
  211. package/dist/internal/runtime/fixture-events.d.ts +12 -0
  212. package/dist/internal/runtime/fixture-responder.d.ts +1 -0
  213. package/dist/internal/runtime/fixture-run-base.d.ts +45 -0
  214. package/dist/internal/runtime/fixture-scripts.d.ts +21 -0
  215. package/dist/internal/runtime/fixture-types.d.ts +1 -0
  216. package/dist/internal/runtime/fork-agent.d.ts +15 -0
  217. package/dist/internal/runtime/hooks-executor.d.ts +35 -0
  218. package/dist/internal/runtime/hooks-frontmatter.d.ts +26 -0
  219. package/dist/internal/runtime/hooks-source.d.ts +22 -0
  220. package/dist/internal/runtime/live-agent-registry.d.ts +87 -0
  221. package/dist/internal/runtime/local-agent-bootstrap.d.ts +37 -0
  222. package/dist/internal/runtime/local-agent-dispatch.d.ts +57 -0
  223. package/dist/internal/runtime/local-agent-invalidate.d.ts +8 -0
  224. package/dist/internal/runtime/local-agent-memory-direct.d.ts +12 -0
  225. package/dist/internal/runtime/local-agent-memory-hooks.d.ts +41 -0
  226. package/dist/internal/runtime/local-agent-memory.d.ts +1 -0
  227. package/dist/internal/runtime/local-agent-personality-extensions.d.ts +19 -0
  228. package/dist/internal/runtime/local-agent-plugins.d.ts +13 -0
  229. package/dist/internal/runtime/local-agent-runtime-extensions.d.ts +13 -0
  230. package/dist/internal/runtime/local-agent-task-wrap.d.ts +11 -0
  231. package/dist/internal/runtime/local-agent.d.ts +1 -0
  232. package/dist/internal/runtime/local-run.d.ts +1 -0
  233. package/dist/internal/runtime/memory-store.d.ts +4 -0
  234. package/dist/internal/runtime/plugin-frontmatter.d.ts +17 -0
  235. package/dist/internal/runtime/plugins-manager.d.ts +1 -0
  236. package/dist/internal/runtime/post-run-lifecycle.d.ts +1 -0
  237. package/dist/internal/runtime/providers-manager.d.ts +1 -0
  238. package/dist/internal/runtime/real-cloud-run.d.ts +2 -0
  239. package/dist/internal/runtime/real-local-run.d.ts +2 -0
  240. package/dist/internal/runtime/run-registry.d.ts +5 -0
  241. package/dist/internal/runtime/run-until.d.ts +22 -0
  242. package/dist/internal/runtime/shell-tool.d.ts +7 -0
  243. package/dist/internal/runtime/skill-frontmatter.d.ts +1 -0
  244. package/dist/internal/runtime/skills-manager.d.ts +1 -0
  245. package/dist/internal/runtime/spawn-collect.d.ts +8 -0
  246. package/dist/internal/runtime/subagents-loader.d.ts +1 -0
  247. package/dist/internal/runtime/system-prompt/escape.d.ts +1 -0
  248. package/dist/internal/runtime/system-prompt/local-assembly.d.ts +1 -0
  249. package/dist/internal/runtime/system-prompt/pipeline.d.ts +1 -0
  250. package/dist/internal/runtime/system-prompt/providers/active-memory-provider.d.ts +1 -0
  251. package/dist/internal/runtime/system-prompt/providers/base-provider.d.ts +1 -0
  252. package/dist/internal/runtime/system-prompt/providers/context-provider.d.ts +1 -0
  253. package/dist/internal/runtime/system-prompt/providers/memory-provider.d.ts +1 -0
  254. package/dist/internal/runtime/system-prompt/providers/skills-provider.d.ts +1 -0
  255. package/dist/internal/runtime/system-prompt/safe-call.d.ts +1 -0
  256. package/dist/internal/runtime/system-prompt/types.d.ts +5 -0
  257. package/dist/internal/runtime/system-prompt.d.ts +1 -0
  258. package/dist/internal/runtime/validate-agent-options.d.ts +1 -0
  259. package/dist/internal/runtime/workspace-dir.d.ts +9 -0
  260. package/dist/internal/runtime/yaml-frontmatter.d.ts +20 -0
  261. package/dist/internal/scorers/llm-judge.d.ts +24 -0
  262. package/dist/internal/security/index.d.ts +11 -0
  263. package/dist/internal/security/path-guard.d.ts +56 -0
  264. package/dist/internal/security/redact.d.ts +21 -0
  265. package/dist/internal/structured-output-helpers.d.ts +54 -0
  266. package/dist/internal/task/registry.d.ts +61 -0
  267. package/dist/internal/task/ring-buffer.d.ts +10 -0
  268. package/dist/internal/task/store.d.ts +59 -0
  269. package/dist/internal/task/subscribe.d.ts +15 -0
  270. package/dist/internal/task/telemetry.d.ts +27 -0
  271. package/dist/internal/telemetry/adapter-registry.d.ts +2 -0
  272. package/dist/internal/telemetry/adapters/langfuse.d.ts +2 -0
  273. package/dist/internal/telemetry/adapters/posthog.d.ts +2 -0
  274. package/dist/internal/telemetry/adapters/sentry.d.ts +2 -0
  275. package/dist/internal/telemetry/safe-require.d.ts +1 -0
  276. package/dist/internal/telemetry/tracer.d.ts +18 -0
  277. package/dist/internal/tool-dispatch/repair-middleware.d.ts +34 -0
  278. package/dist/internal/tool-dispatch/strip-think.d.ts +22 -0
  279. package/dist/internal/tool-registry/personality-filter.d.ts +37 -0
  280. package/dist/internal/workflow/ctx.d.ts +19 -0
  281. package/dist/internal/workflow/error-shape.d.ts +7 -0
  282. package/dist/internal/workflow/executor.d.ts +15 -0
  283. package/dist/internal/workflow/index.d.ts +12 -0
  284. package/dist/internal/workflow/retry-policy.d.ts +14 -0
  285. package/dist/internal/workflow/run-id.d.ts +9 -0
  286. package/dist/internal/workflow/single-flight.d.ts +18 -0
  287. package/dist/internal/workflow/snapshot-store.d.ts +23 -0
  288. package/dist/internal/workflow/step-agent.d.ts +12 -0
  289. package/dist/internal/workflow/step-branch.d.ts +10 -0
  290. package/dist/internal/workflow/step-dowhile.d.ts +8 -0
  291. package/dist/internal/workflow/step-fn.d.ts +10 -0
  292. package/dist/internal/workflow/step-foreach.d.ts +11 -0
  293. package/dist/internal/workflow/step-parallel.d.ts +17 -0
  294. package/dist/internal/workflow/step-sleep.d.ts +7 -0
  295. package/dist/internal/workflow/telemetry.d.ts +23 -0
  296. package/dist/internal/zod/to-json-schema.d.ts +21 -0
  297. package/dist/memory-adapter-helpers.d.ts +28 -0
  298. package/dist/memory.d.ts +123 -0
  299. package/dist/migrate.d.ts +33 -0
  300. package/dist/path-safety.cjs +126 -0
  301. package/dist/path-safety.cjs.map +1 -0
  302. package/dist/path-safety.d.cts +15 -0
  303. package/dist/path-safety.d.ts +15 -0
  304. package/dist/path-safety.js +120 -0
  305. package/dist/path-safety.js.map +1 -0
  306. package/dist/run-DkCD5DeO.d.cts +2181 -0
  307. package/dist/run-DkCD5DeO.d.ts +2181 -0
  308. package/dist/scorers.d.ts +75 -0
  309. package/dist/security.d.ts +67 -0
  310. package/dist/stream-object.d.ts +74 -0
  311. package/dist/task-store.cjs +237 -0
  312. package/dist/task-store.cjs.map +1 -0
  313. package/dist/task-store.d.cts +8 -0
  314. package/dist/task-store.d.ts +8 -0
  315. package/dist/task-store.js +233 -0
  316. package/dist/task-store.js.map +1 -0
  317. package/dist/task.d.ts +87 -0
  318. package/dist/theokit.d.ts +84 -0
  319. package/dist/tools/_path-scope.d.cts +8 -0
  320. package/dist/tools/_path-scope.d.ts +8 -0
  321. package/dist/tools/_subprocess.d.cts +28 -0
  322. package/dist/tools/_subprocess.d.ts +28 -0
  323. package/dist/tools/git-diff.d.cts +22 -0
  324. package/dist/tools/git-diff.d.ts +22 -0
  325. package/dist/tools/index.d.cts +29 -0
  326. package/dist/tools/index.d.ts +29 -0
  327. package/dist/tools/list-dir.d.cts +26 -0
  328. package/dist/tools/list-dir.d.ts +26 -0
  329. package/dist/tools/read-file.d.cts +31 -0
  330. package/dist/tools/read-file.d.ts +31 -0
  331. package/dist/tools/run-vitest.d.cts +46 -0
  332. package/dist/tools/run-vitest.d.ts +46 -0
  333. package/dist/tools/search-text.d.cts +32 -0
  334. package/dist/tools/search-text.d.ts +32 -0
  335. package/dist/tools.cjs +690 -0
  336. package/dist/tools.cjs.map +1 -0
  337. package/dist/tools.js +683 -0
  338. package/dist/tools.js.map +1 -0
  339. package/dist/trajectory-helpers.d.ts +31 -0
  340. package/dist/types/agent.d.ts +771 -0
  341. package/dist/types/batch.d.ts +112 -0
  342. package/dist/types/budget.d.ts +88 -0
  343. package/dist/types/cache.d.ts +76 -0
  344. package/dist/types/context.d.ts +93 -0
  345. package/dist/types/conversation-storage.d.ts +76 -0
  346. package/dist/types/conversation.d.ts +90 -0
  347. package/dist/types/cron.d.ts +150 -0
  348. package/dist/types/eval.d.ts +132 -0
  349. package/dist/types/goal-events.d.ts +95 -0
  350. package/dist/types/handoff.d.ts +135 -0
  351. package/dist/types/index.d.ts +20 -0
  352. package/dist/types/mcp.d.ts +64 -0
  353. package/dist/types/memory-adapter.d.ts +175 -0
  354. package/dist/types/messages.d.ts +154 -0
  355. package/dist/types/providers.d.ts +102 -0
  356. package/dist/types/run.d.ts +215 -0
  357. package/dist/types/task.d.ts +131 -0
  358. package/dist/types/theokit.d.ts +61 -0
  359. package/dist/types/trajectory.d.ts +49 -0
  360. package/dist/types/updates.d.ts +148 -0
  361. package/dist/types/usage.d.ts +61 -0
  362. package/dist/types/workflow.d.ts +217 -0
  363. package/dist/workflow.cjs +2405 -0
  364. package/dist/workflow.cjs.map +1 -0
  365. package/dist/workflow.d.cts +97 -0
  366. package/dist/workflow.d.ts +97 -0
  367. package/dist/workflow.js +2398 -0
  368. package/dist/workflow.js.map +1 -0
  369. package/package.json +183 -0
@@ -0,0 +1,233 @@
1
+ import { mkdirSync, readdirSync } from 'fs';
2
+ import { readFile, unlink, mkdir, open, rename } from 'fs/promises';
3
+ import { join, dirname } from 'path';
4
+
5
+ // src/internal/task/store.ts
6
+
7
+ // src/errors.ts
8
+ var TheokitAgentError = class extends Error {
9
+ name = "TheokitAgentError";
10
+ isRetryable;
11
+ code;
12
+ protoErrorCode;
13
+ metadata;
14
+ constructor(message, options = {}) {
15
+ super(message, options.cause !== void 0 ? { cause: options.cause } : void 0);
16
+ this.isRetryable = options.isRetryable ?? false;
17
+ if (options.code !== void 0) this.code = options.code;
18
+ if (options.protoErrorCode !== void 0) this.protoErrorCode = options.protoErrorCode;
19
+ if (options.metadata !== void 0) this.metadata = options.metadata;
20
+ }
21
+ };
22
+ var InvalidTaskIdError = class extends TheokitAgentError {
23
+ name = "InvalidTaskIdError";
24
+ taskId;
25
+ constructor(message, taskId, options = {}) {
26
+ super(message, {
27
+ ...options,
28
+ isRetryable: false,
29
+ code: "invalid_task_id"
30
+ });
31
+ this.taskId = taskId;
32
+ }
33
+ };
34
+
35
+ // src/types/task.ts
36
+ var TASK_ID_GRAMMAR = /^[a-z0-9][a-z0-9_-]*$/;
37
+ function isValidTaskId(id, allowReserved) {
38
+ if (!TASK_ID_GRAMMAR.test(id)) return false;
39
+ return true;
40
+ }
41
+ async function replaceFileAtomic(filePath, content) {
42
+ const tmp = `${filePath}.${process.pid}.${Math.random().toString(36).slice(2, 10)}.tmp`;
43
+ const handle = await open(tmp, "w");
44
+ try {
45
+ await handle.writeFile(content, "utf8");
46
+ await handle.sync();
47
+ } finally {
48
+ await handle.close();
49
+ }
50
+ try {
51
+ await rename(tmp, filePath);
52
+ } catch (cause) {
53
+ await unlink(tmp).catch(() => void 0);
54
+ throw cause;
55
+ }
56
+ }
57
+ async function atomicWriteText(filePath, content) {
58
+ await mkdir(dirname(filePath), { recursive: true });
59
+ await replaceFileAtomic(filePath, content);
60
+ }
61
+
62
+ // src/internal/task/store.ts
63
+ var JSON_LOAD_CAP = 256;
64
+ var DEFAULT_LIST_LIMIT = 100;
65
+ function assertValidIdForStore(id) {
66
+ if (!isValidTaskId(
67
+ id)) {
68
+ throw new InvalidTaskIdError(`store rejects invalid task id: ${id}`, id);
69
+ }
70
+ }
71
+ function terminalTimestamp(h) {
72
+ if (h.state === "finished") return h.finishedAt;
73
+ if (h.state === "error") return h.erroredAt;
74
+ if (h.state === "cancelled") return h.cancelledAt;
75
+ return void 0;
76
+ }
77
+ function isTerminal(state) {
78
+ return state === "finished" || state === "error" || state === "cancelled";
79
+ }
80
+ function matchesState(h, filter) {
81
+ if (filter.state === void 0) return true;
82
+ const states = Array.isArray(filter.state) ? filter.state : [filter.state];
83
+ return states.includes(h.state);
84
+ }
85
+ function matchesKind(h, filter) {
86
+ if (filter.kind === void 0) return true;
87
+ const kinds = Array.isArray(filter.kind) ? filter.kind : [filter.kind];
88
+ return kinds.includes(h.kind);
89
+ }
90
+ function matchesTime(h, filter) {
91
+ if (filter.submittedAfter !== void 0 && h.submittedAt <= filter.submittedAfter) return false;
92
+ if (filter.submittedBefore !== void 0 && h.submittedAt >= filter.submittedBefore) return false;
93
+ return true;
94
+ }
95
+ function matchesFilter(h, filter) {
96
+ return matchesState(h, filter) && matchesKind(h, filter) && matchesTime(h, filter);
97
+ }
98
+ function applyFilter(values, filter) {
99
+ const limit = filter.limit ?? DEFAULT_LIST_LIMIT;
100
+ const out = [];
101
+ for (const h of values) {
102
+ if (matchesFilter(h, filter)) {
103
+ out.push(h);
104
+ if (out.length >= limit) break;
105
+ }
106
+ }
107
+ return out;
108
+ }
109
+ var InMemoryTaskStore = class {
110
+ map = /* @__PURE__ */ new Map();
111
+ async insert(handle) {
112
+ assertValidIdForStore(handle.id);
113
+ this.map.set(handle.id, handle);
114
+ }
115
+ async update(id, mutate) {
116
+ assertValidIdForStore(id);
117
+ const existing = this.map.get(id);
118
+ if (existing === void 0) return void 0;
119
+ const next = mutate(existing);
120
+ this.map.set(id, next);
121
+ return next;
122
+ }
123
+ async get(id) {
124
+ assertValidIdForStore(id);
125
+ return this.map.get(id);
126
+ }
127
+ async list(filter) {
128
+ return applyFilter(this.map.values(), filter);
129
+ }
130
+ async delete(id) {
131
+ assertValidIdForStore(id);
132
+ return this.map.delete(id);
133
+ }
134
+ async evictTerminalOlderThan(epochMs) {
135
+ let count = 0;
136
+ for (const [id, h] of this.map.entries()) {
137
+ if (!isTerminal(h.state)) continue;
138
+ const ts = terminalTimestamp(h);
139
+ if (ts !== void 0 && ts < epochMs) {
140
+ this.map.delete(id);
141
+ count++;
142
+ }
143
+ }
144
+ return count;
145
+ }
146
+ };
147
+ var JsonFileTaskStore = class {
148
+ constructor(dir) {
149
+ this.dir = dir;
150
+ try {
151
+ mkdirSync(dir, { recursive: true });
152
+ } catch (err) {
153
+ if (err.code !== "EEXIST") throw err;
154
+ }
155
+ }
156
+ dir;
157
+ filePath(id) {
158
+ return join(this.dir, `${id}.json`);
159
+ }
160
+ async insert(handle) {
161
+ assertValidIdForStore(handle.id);
162
+ await atomicWriteText(this.filePath(handle.id), JSON.stringify(handle));
163
+ }
164
+ async update(id, mutate) {
165
+ assertValidIdForStore(id);
166
+ const existing = await this.get(id);
167
+ if (existing === void 0) return void 0;
168
+ const next = mutate(existing);
169
+ await atomicWriteText(this.filePath(id), JSON.stringify(next));
170
+ return next;
171
+ }
172
+ async get(id) {
173
+ assertValidIdForStore(id);
174
+ try {
175
+ const raw = await readFile(this.filePath(id), "utf8");
176
+ return JSON.parse(raw);
177
+ } catch (err) {
178
+ const code = err.code;
179
+ if (code === "ENOENT") return void 0;
180
+ process.stderr.write(`[task-store] failed to read ${id}: ${err.message}
181
+ `);
182
+ return void 0;
183
+ }
184
+ }
185
+ async list(filter) {
186
+ let entries;
187
+ try {
188
+ entries = readdirSync(this.dir);
189
+ } catch (err) {
190
+ if (err.code === "ENOENT") return [];
191
+ throw err;
192
+ }
193
+ const candidates = entries.filter((name) => name.endsWith(".json") && !name.includes(".tmp")).slice(0, JSON_LOAD_CAP);
194
+ const loaded = await Promise.all(
195
+ candidates.map(async (name) => {
196
+ const id = name.slice(0, -".json".length);
197
+ if (!isValidTaskId(id)) return void 0;
198
+ return this.get(id);
199
+ })
200
+ );
201
+ const handles = loaded.filter((h) => h !== void 0);
202
+ return applyFilter(handles, filter);
203
+ }
204
+ async delete(id) {
205
+ assertValidIdForStore(id);
206
+ try {
207
+ await unlink(this.filePath(id));
208
+ return true;
209
+ } catch (err) {
210
+ if (err.code === "ENOENT") return false;
211
+ throw err;
212
+ }
213
+ }
214
+ async evictTerminalOlderThan(epochMs) {
215
+ const handles = await this.list({ state: ["finished", "error", "cancelled"], limit: 256 });
216
+ let count = 0;
217
+ for (const h of handles) {
218
+ const ts = terminalTimestamp(h);
219
+ if (ts !== void 0 && ts < epochMs) {
220
+ if (await this.delete(h.id)) count++;
221
+ }
222
+ }
223
+ return count;
224
+ }
225
+ };
226
+ function getTaskStoreFor(options) {
227
+ if (options.backend === "memory") return new InMemoryTaskStore();
228
+ return new JsonFileTaskStore(options.dir);
229
+ }
230
+
231
+ export { InMemoryTaskStore, JsonFileTaskStore, getTaskStoreFor };
232
+ //# sourceMappingURL=task-store.js.map
233
+ //# sourceMappingURL=task-store.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/errors.ts","../src/types/task.ts","../src/internal/persistence/atomic-write.ts","../src/internal/task/store.ts"],"names":["unlink"],"mappings":";;;;;;;AAmFO,IAAM,iBAAA,GAAN,cAAgC,KAAA,CAAM;AAAA,EACzB,IAAA,GAAe,mBAAA;AAAA,EACxB,WAAA;AAAA,EACA,IAAA;AAAA,EACA,cAAA;AAAA,EACA,QAAA;AAAA,EAET,WAAA,CACE,OAAA,EACA,OAAA,GAMI,EAAC,EACL;AACA,IAAA,KAAA,CAAM,OAAA,EAAS,QAAQ,KAAA,KAAU,MAAA,GAAY,EAAE,KAAA,EAAO,OAAA,CAAQ,KAAA,EAAM,GAAI,MAAS,CAAA;AACjF,IAAA,IAAA,CAAK,WAAA,GAAc,QAAQ,WAAA,IAAe,KAAA;AAC1C,IAAA,IAAI,OAAA,CAAQ,IAAA,KAAS,MAAA,EAAW,IAAA,CAAK,OAAO,OAAA,CAAQ,IAAA;AACpD,IAAA,IAAI,OAAA,CAAQ,cAAA,KAAmB,MAAA,EAAW,IAAA,CAAK,iBAAiB,OAAA,CAAQ,cAAA;AACxE,IAAA,IAAI,OAAA,CAAQ,QAAA,KAAa,MAAA,EAAW,IAAA,CAAK,WAAW,OAAA,CAAQ,QAAA;AAAA,EAC9D;AACF,CAAA;AA0UO,IAAM,kBAAA,GAAN,cAAiC,iBAAA,CAAkB;AAAA,EACtC,IAAA,GAAe,oBAAA;AAAA,EACxB,MAAA;AAAA,EAET,WAAA,CAAY,OAAA,EAAiB,MAAA,EAAgB,OAAA,GAA+B,EAAC,EAAG;AAC9E,IAAA,KAAA,CAAM,OAAA,EAAS;AAAA,MACb,GAAG,OAAA;AAAA,MACH,WAAA,EAAa,KAAA;AAAA,MACb,IAAA,EAAM;AAAA,KACP,CAAA;AACD,IAAA,IAAA,CAAK,MAAA,GAAS,MAAA;AAAA,EAChB;AACF,CAAA;;;AC/TA,IAAM,eAAA,GAAkB,uBAAA;AAajB,SAAS,aAA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;AACF,MAAA,MAAMA,MAAAA,CAAO,IAAA,CAAK,QAAA,CAAS,EAAE,CAAC,CAAA;AAC9B,MAAA,OAAO,IAAA;AAAA,IACT,SAAS,GAAA,EAAK;AACZ,MAAA,IAAK,GAAA,CAA8B,IAAA,KAAS,QAAA,EAAU,OAAO,KAAA;AAC7D,MAAA,MAAM,GAAA;AAAA,IACR;AAAA,EACF;AAAA,EAEA,MAAM,uBAAuB,OAAA,EAAkC;AAC7D,IAAA,MAAM,OAAA,GAAU,MAAM,IAAA,CAAK,IAAA,CAAK,EAAE,KAAA,EAAO,CAAC,UAAA,EAAY,OAAA,EAAS,WAAW,CAAA,EAAG,KAAA,EAAO,KAAK,CAAA;AACzF,IAAA,IAAI,KAAA,GAAQ,CAAA;AACZ,IAAA,KAAA,MAAW,KAAK,OAAA,EAAS;AACvB,MAAA,MAAM,EAAA,GAAK,kBAAkB,CAAC,CAAA;AAC9B,MAAA,IAAI,EAAA,KAAO,MAAA,IAAa,EAAA,GAAK,OAAA,EAAS;AACpC,QAAA,IAAI,MAAM,IAAA,CAAK,MAAA,CAAO,CAAA,CAAE,EAAE,CAAA,EAAG,KAAA,EAAA;AAAA,MAC/B;AAAA,IACF;AACA,IAAA,OAAO,KAAA;AAAA,EACT;AACF;AAGO,SAAS,gBAAgB,OAAA,EAAsC;AACpE,EAAA,IAAI,OAAA,CAAQ,OAAA,KAAY,QAAA,EAAU,OAAO,IAAI,iBAAA,EAAkB;AAC/D,EAAA,OAAO,IAAI,iBAAA,CAAkB,OAAA,CAAQ,GAAG,CAAA;AAC1C","file":"task-store.js","sourcesContent":["import type { RunOperation } from \"./types/run.js\";\n\n/**\n * Finite, machine-readable error codes for provider-originated errors\n * (ADR D66). Consumers can `switch (err.metadata?.code)` exhaustively\n * — adding a new variant is an explicit decision + test coverage.\n *\n * @public\n */\nexport type ErrorCode =\n | \"rate_limit\"\n | \"auth_failed\"\n | \"invalid_request\"\n | \"timeout\"\n | \"server_error\"\n | \"context_too_long\"\n | \"content_filtered\"\n | \"model_unavailable\"\n | \"network\"\n | \"unknown\";\n\n/**\n * Codes used by {@link AgentRunError} (Production-Readiness #3, ADR D311).\n *\n * Superset of {@link ErrorCode} extended with codes that do NOT originate\n * from a provider HTTP response:\n *\n * - `quota_exceeded` — billing limit hit (provider 402 or signalled error)\n * - `tool_runtime_error` — custom tool handler threw inside dispatch\n * - `aborted` — caller's `AbortSignal` fired (Phase 4)\n * - `invalid_model` — model id rejected by provider (400 \"model not found\")\n * - `safety_blocked` — provider safety filter blocked req or resp\n * - `provider_unreachable` — DNS/TCP/timeout/5xx at transport boundary\n *\n * The `& {}` tail keeps the literal-union ergonomics (autocomplete) while\n * accepting any string for forward compatibility with constructor calls\n * that pass arbitrary code values (legacy callers).\n *\n * @public\n */\nexport type AgentRunErrorCode =\n | ErrorCode\n | \"quota_exceeded\"\n | \"tool_runtime_error\"\n | \"aborted\"\n | \"invalid_model\"\n | \"safety_blocked\"\n | \"provider_unreachable\"\n | (string & {});\n\n/**\n * Structured context for errors that originated from a provider HTTP\n * call (ADR D65). Lets callers retry with the right backoff (`retryAfter`),\n * surface actionable diagnostics (`provider`, `endpoint`), and inspect the\n * raw response body when needed (`raw`, capped at ~2KB by the mapper).\n *\n * @public\n */\nexport interface ErrorMetadata {\n /** Provider canonical name (e.g., `\"anthropic\"`, `\"openai\"`, `\"openrouter\"`, `\"gemini\"`). */\n provider: string;\n /** HTTP endpoint that failed (e.g., `\"/v1/messages\"`, `\"/v1/chat/completions\"`). */\n endpoint: string;\n /** Machine-readable error code (finite enum). */\n code: ErrorCode;\n /** HTTP status code if applicable. */\n statusCode?: number;\n /** Seconds to wait before retry, per provider's `retry-after` header (numeric form only). */\n retryAfter?: number;\n /** Raw response body for debugging (truncated to ~2KB by the mapper). */\n raw?: unknown;\n}\n\n/**\n * Base class for all errors thrown by `@theokit/sdk`.\n *\n * Use `isRetryable` to drive retry/backoff logic. `code` and `protoErrorCode`\n * are populated for server-originated errors when available. `metadata`\n * (ADR D65) carries structured `{ provider, endpoint, code, ... }` when\n * the error originated from a provider HTTP call.\n *\n * @public\n */\nexport class TheokitAgentError extends Error {\n override readonly name: string = \"TheokitAgentError\";\n readonly isRetryable: boolean;\n readonly code?: string;\n readonly protoErrorCode?: string;\n readonly metadata?: ErrorMetadata;\n\n constructor(\n message: string,\n options: {\n isRetryable?: boolean;\n code?: string;\n protoErrorCode?: string;\n cause?: unknown;\n metadata?: ErrorMetadata;\n } = {},\n ) {\n super(message, options.cause !== undefined ? { cause: options.cause } : undefined);\n this.isRetryable = options.isRetryable ?? false;\n if (options.code !== undefined) this.code = options.code;\n if (options.protoErrorCode !== undefined) this.protoErrorCode = options.protoErrorCode;\n if (options.metadata !== undefined) this.metadata = options.metadata;\n }\n}\n\n/**\n * Invalid API key, not logged in, insufficient permissions.\n *\n * @public\n */\nexport class AuthenticationError extends TheokitAgentError {\n override readonly name: string = \"AuthenticationError\";\n\n constructor(\n message: string,\n options: { code?: string; cause?: unknown; metadata?: ErrorMetadata } = {},\n ) {\n super(message, { ...options, isRetryable: false });\n }\n}\n\n/**\n * Too many requests or usage limits exceeded.\n *\n * @public\n */\nexport class RateLimitError extends TheokitAgentError {\n override readonly name: string = \"RateLimitError\";\n\n constructor(\n message: string,\n options: { code?: string; cause?: unknown; metadata?: ErrorMetadata } = {},\n ) {\n super(message, { ...options, isRetryable: true });\n }\n}\n\n/**\n * Invalid model, bad request parameters, malformed options.\n *\n * @public\n */\nexport class ConfigurationError extends TheokitAgentError {\n override readonly name: string = \"ConfigurationError\";\n\n constructor(\n message: string,\n options: { code?: string; cause?: unknown; metadata?: ErrorMetadata } = {},\n ) {\n super(message, { ...options, isRetryable: false });\n }\n}\n\n/**\n * Thrown when creating a cloud agent for a repo whose SCM provider is not\n * connected. Use `helpUrl` to point the user at the right reconnect flow.\n *\n * @public\n */\nexport class IntegrationNotConnectedError extends ConfigurationError {\n override readonly name: string = \"IntegrationNotConnectedError\";\n readonly provider: string;\n readonly helpUrl: string;\n\n constructor(\n message: string,\n options: {\n provider: string;\n helpUrl: string;\n code?: string;\n cause?: unknown;\n metadata?: ErrorMetadata;\n },\n ) {\n super(message, options);\n this.provider = options.provider;\n this.helpUrl = options.helpUrl;\n }\n}\n\n/**\n * Service unavailable, timeout, transport-level failure.\n *\n * @public\n */\nexport class NetworkError extends TheokitAgentError {\n override readonly name: string = \"NetworkError\";\n\n constructor(\n message: string,\n options: { code?: string; cause?: unknown; metadata?: ErrorMetadata } = {},\n ) {\n super(message, { ...options, isRetryable: true });\n }\n}\n\n/**\n * Catch-all for unclassified server or runtime errors.\n *\n * @public\n */\nexport class UnknownAgentError extends TheokitAgentError {\n override readonly name: string = \"UnknownAgentError\";\n\n constructor(\n message: string,\n options: { code?: string; cause?: unknown; metadata?: ErrorMetadata } = {},\n ) {\n super(message, { ...options, isRetryable: false });\n }\n}\n\n/**\n * Thrown by `Agent.prompt` (and helpers that go through `run.wait()`) when\n * the option `{ throwOnError: true }` is set and the run terminates with\n * `status: 'error'`. Carries the structured `RunResult.error` fields so\n * callers can `catch` once and branch on `code` / `provider` instead of\n * unwrapping the run.\n *\n * Extends {@link TheokitAgentError} per ADR D65 — no new hierarchy.\n *\n * @example\n * try {\n * await Agent.prompt(msg, { apiKey, model, throwOnError: true });\n * } catch (err) {\n * if (err instanceof AgentRunError && err.code === 'auth_failed') {\n * // bad key\n * }\n * }\n *\n * @public\n */\nexport class AgentRunError extends TheokitAgentError {\n override readonly name: string = \"AgentRunError\";\n readonly provider?: string;\n readonly raw?: string;\n /** Provider's request id (`x-request-id` / `request-id` header). Useful for support tickets. */\n readonly requestId?: string;\n /** SDK conversation id this error was raised inside. */\n readonly conversationId?: string;\n\n constructor(\n message: string,\n options: {\n code: AgentRunErrorCode;\n provider?: string;\n raw?: string;\n requestId?: string;\n conversationId?: string;\n retriable?: boolean;\n cause?: unknown;\n metadata?: ErrorMetadata;\n },\n ) {\n super(message, {\n code: options.code,\n cause: options.cause,\n metadata: options.metadata,\n // D311: most AgentRunErrors are not retriable (auth, validation, abort).\n // Provider mappers (D314) override per-status — explicit `retriable` wins\n // over the implicit default when supplied.\n isRetryable: options.retriable ?? defaultRetriableForCode(options.code),\n });\n if (options.provider !== undefined) this.provider = options.provider;\n if (options.raw !== undefined) this.raw = options.raw;\n if (options.requestId !== undefined) this.requestId = options.requestId;\n if (options.conversationId !== undefined) this.conversationId = options.conversationId;\n }\n\n /**\n * Production-Readiness #3 (ADR D311): alias for `isRetryable` exposed as\n * `retriable` to match the handoff contract. Future v2 will deprecate\n * `isRetryable` in favor of this.\n */\n get retriable(): boolean {\n return this.isRetryable;\n }\n\n /**\n * D312: provider's `Retry-After` header in **milliseconds**. Mappers store\n * the header value (seconds) in `metadata.retryAfter`; this getter\n * multiplies by 1000 so the result composes with `Date.now()`/`setTimeout`.\n *\n * Returns `undefined` when no hint was provided. `0` is a legitimate value\n * — use `=== undefined` check rather than truthy check.\n */\n get retryAfterMs(): number | undefined {\n if (this.metadata?.retryAfter === undefined) return undefined;\n return this.metadata.retryAfter * 1000;\n }\n\n /**\n * D313: alias for `metadata.raw`. Provider response body for debugging.\n * Available but NEVER serialized into `.message` (anti-leak invariant).\n */\n get providerError(): unknown {\n return this.metadata?.raw;\n }\n}\n\n/**\n * D311 helper: choose a sensible default `isRetryable` value when the\n * caller did not supply `retriable` explicitly. Conservative defaults —\n * provider mappers override per-status when they know better.\n *\n * @internal\n */\nfunction defaultRetriableForCode(code: AgentRunErrorCode): boolean {\n switch (code) {\n case \"rate_limit\":\n case \"timeout\":\n case \"server_error\":\n case \"network\":\n case \"provider_unreachable\":\n return true;\n default:\n return false;\n }\n}\n\n/**\n * Thrown when a {@link Run} or agent operation is not available on the current\n * runtime. Check first with `run.supports(operation)`.\n *\n * Extends {@link TheokitAgentError} (so error-catching code that branches on\n * `instanceof TheokitAgentError` continues to work) but is never retryable —\n * an unsupported operation will not become supported on retry.\n *\n * @public\n */\nexport class UnsupportedRunOperationError extends TheokitAgentError {\n override readonly name: string = \"UnsupportedRunOperationError\";\n readonly operation: RunOperation;\n\n constructor(\n message: string,\n operation: RunOperation,\n options: { code?: string; cause?: unknown } = {},\n ) {\n super(message, {\n ...options,\n isRetryable: false,\n code: options.code ?? \"unsupported_run_operation\",\n });\n this.operation = operation;\n }\n}\n\n/**\n * Thrown when every credential in a per-provider pool is in cooldown\n * and no healthy key is available (ADR D133). The caller's\n * {@link import(\"./internal/llm/fallback-client.js\").FallbackLlmClient}\n * catches this and tries the next provider in the fallback chain.\n *\n * `metadata.nextRetryAt` (epoch ms) tells callers when the soonest\n * pool entry resumes — useful for manual retry scheduling.\n *\n * @public\n */\nexport class CredentialPoolExhaustedError extends TheokitAgentError {\n override readonly name: string = \"CredentialPoolExhaustedError\";\n readonly provider: string;\n readonly nextRetryAt: number | undefined;\n\n constructor(\n message: string,\n options: {\n provider: string;\n nextRetryAt?: number;\n code?: string;\n cause?: unknown;\n metadata?: ErrorMetadata;\n },\n ) {\n super(message, {\n ...options,\n isRetryable: true,\n code: options.code ?? \"credential_pool_exhausted\",\n });\n this.provider = options.provider;\n this.nextRetryAt = options.nextRetryAt;\n }\n}\n\n/**\n * Finite error codes specific to memory adapter operations (ADR D141).\n *\n * @public\n */\nexport type MemoryAdapterErrorCode =\n | \"auth_failed\"\n | \"rate_limited\"\n | \"not_found\"\n | \"network\"\n | \"invalid_input\"\n | \"unknown\";\n\n/**\n * Error raised by `@theokit-memory-*` adapters. Carries `adapterId`\n * so callers can branch on which provider failed (ADR D141).\n *\n * @public\n */\nexport class MemoryAdapterError extends TheokitAgentError {\n override readonly name: string = \"MemoryAdapterError\";\n readonly adapterId: string;\n\n constructor(\n message: string,\n options: {\n adapterId: string;\n code: MemoryAdapterErrorCode;\n cause?: unknown;\n metadata?: ErrorMetadata;\n },\n ) {\n super(message, {\n isRetryable: options.code === \"rate_limited\" || options.code === \"network\",\n code: options.code,\n ...(options.cause !== undefined ? { cause: options.cause } : {}),\n ...(options.metadata !== undefined ? { metadata: options.metadata } : {}),\n });\n this.adapterId = options.adapterId;\n }\n}\n\n/**\n * Thrown when a user-supplied task ID violates the grammar\n * `^[a-z0-9][a-z0-9_-]*$` (D368) OR starts with a reserved adapter\n * prefix (`wf-` / `b-` / `cron-`, EC-5).\n *\n * @public\n */\nexport class InvalidTaskIdError extends TheokitAgentError {\n override readonly name: string = \"InvalidTaskIdError\";\n readonly taskId: string;\n\n constructor(message: string, taskId: string, options: { cause?: unknown } = {}) {\n super(message, {\n ...options,\n isRetryable: false,\n code: \"invalid_task_id\",\n });\n this.taskId = taskId;\n }\n}\n\n/**\n * Thrown when `Task.subscribe(id)` is called for a task that has been\n * evicted, never submitted, or evicted after retention (D373).\n *\n * @public\n */\nexport class TaskNotFoundError extends TheokitAgentError {\n override readonly name: string = \"TaskNotFoundError\";\n readonly taskId: string;\n\n constructor(taskId: string, options: { cause?: unknown } = {}) {\n super(`Task not found: ${taskId}`, {\n ...options,\n isRetryable: false,\n code: \"task_not_found\",\n });\n this.taskId = taskId;\n }\n}\n\n/**\n * Thrown when `CloudAgent` is asked to wrap a task (D370). Cloud\n * task observability is deferred until Theo PaaS GA.\n *\n * @public\n */\nexport class UnsupportedTaskOperationError extends TheokitAgentError {\n override readonly name: string = \"UnsupportedTaskOperationError\";\n readonly operation: string;\n\n constructor(operation: string, options: { cause?: unknown } = {}) {\n super(\n `Task operation \"${operation}\" is not supported on CloudAgent (pre-release; see ADR D370)`,\n {\n ...options,\n isRetryable: false,\n code: \"task_op_unsupported\",\n },\n );\n this.operation = operation;\n }\n}\n\n/**\n * Thrown by `Budget` enforcement (ADR D386) when a `mode: \"block\"`\n * budget would be exceeded by the upcoming LLM call. Caller pega\n * tipado para retry-after-window-reset or surface to the user.\n *\n * @public\n */\nexport class BudgetExceededError extends TheokitAgentError {\n override readonly name: string = \"BudgetExceededError\";\n readonly budgetName: string;\n readonly window: import(\"./types/budget.js\").BudgetWindow;\n readonly spentUsd: number;\n readonly limitUsd: number;\n readonly mode: import(\"./types/budget.js\").BudgetMode;\n\n constructor(args: {\n budgetName: string;\n window: import(\"./types/budget.js\").BudgetWindow;\n spentUsd: number;\n limitUsd: number;\n mode: import(\"./types/budget.js\").BudgetMode;\n cause?: unknown;\n }) {\n super(\n `Budget \"${args.budgetName}\" exceeded for window ${args.window}: spent $${args.spentUsd.toFixed(4)} > limit $${args.limitUsd.toFixed(4)}`,\n {\n ...(args.cause !== undefined ? { cause: args.cause } : {}),\n isRetryable: false,\n code: \"budget_exceeded\",\n },\n );\n this.budgetName = args.budgetName;\n this.window = args.window;\n this.spentUsd = args.spentUsd;\n this.limitUsd = args.limitUsd;\n this.mode = args.mode;\n }\n}\n\n/**\n * Thrown when `CloudAgent.send({ budget })` is invoked (D388). Cloud\n * budget surface waits for Theo PaaS GA.\n *\n * @public\n */\nexport class UnsupportedBudgetOperationError extends TheokitAgentError {\n override readonly name: string = \"UnsupportedBudgetOperationError\";\n readonly operation: string;\n\n constructor(operation: string, options: { cause?: unknown } = {}) {\n super(\n `Budget operation \"${operation}\" is not supported on CloudAgent (pre-release; see ADR D388)`,\n {\n ...options,\n isRetryable: false,\n code: \"budget_op_unsupported\",\n },\n );\n this.operation = operation;\n }\n}\n","/**\n * Public type contract for the Task observability registry (ADRs D361-D374).\n *\n * Tasks are an opt-in observability layer over async work in the SDK\n * (`Agent.send`, `Agent.batch`, `Workflow.run`, `Cron` fires). They have\n * a closed 5-state lifecycle (D362), discriminated events (D366), and a\n * pluggable store (D364). The `Task` facade in `task.ts` is the public\n * surface; consumers import these types from `@theokit/sdk`.\n *\n * @public\n */\n\n/**\n * Closed enum of the 5 lifecycle states (D362).\n *\n * Transitions are acyclic:\n * queued → running → (finished | error | cancelled)\n * queued → cancelled (direct, no run started)\n */\nexport type TaskState = \"queued\" | \"running\" | \"finished\" | \"error\" | \"cancelled\";\n\n/** Discriminator of the runtime that produced a task (D374). */\nexport type TaskKind = \"run\" | \"batch\" | \"workflow\" | \"cron\" | \"custom\";\n\n/** Discriminated union of task lifecycle events (D366). */\nexport type TaskEvent =\n | {\n readonly type: \"submitted\";\n readonly taskId: string;\n readonly kind: TaskKind;\n readonly submittedAt: number;\n readonly meta?: Record<string, unknown>;\n /** D372 — flag set on the first yielded event when the ring buffer was at cap. */\n readonly truncated?: boolean;\n }\n | { readonly type: \"started\"; readonly taskId: string; readonly startedAt: number }\n | {\n readonly type: \"progress\";\n readonly taskId: string;\n readonly at: number;\n readonly payload: unknown;\n }\n | {\n readonly type: \"finished\";\n readonly taskId: string;\n readonly finishedAt: number;\n readonly result: unknown;\n }\n | {\n readonly type: \"errored\";\n readonly taskId: string;\n readonly erroredAt: number;\n readonly error: { readonly code: string; readonly message: string };\n }\n | {\n readonly type: \"cancelled\";\n readonly taskId: string;\n readonly cancelledAt: number;\n readonly reason?: string;\n };\n\n/** Public read-only view of a task entry in the registry. */\nexport interface TaskHandle {\n readonly id: string;\n readonly kind: TaskKind;\n readonly state: TaskState;\n readonly submittedAt: number;\n readonly startedAt?: number;\n readonly finishedAt?: number;\n readonly cancelledAt?: number;\n readonly erroredAt?: number;\n readonly result?: unknown;\n readonly error?: { readonly code: string; readonly message: string };\n readonly meta?: Record<string, unknown>;\n /**\n * EC-7 — cross-process best-effort cancel flag. Set by CLI\n * `theokit tasks cancel` via JsonFileTaskStore. The owning process\n * polls at checkpoints and honors via AbortController. Always\n * `undefined` for in-process cancel paths (which go directly through\n * AbortController).\n */\n readonly cancelRequested?: boolean;\n}\n\n/** Query filter for `Task.list`. */\nexport interface TaskFilter {\n readonly state?: TaskState | readonly TaskState[];\n readonly kind?: TaskKind | readonly TaskKind[];\n readonly submittedAfter?: number;\n readonly submittedBefore?: number;\n /** Defaults to 100. JsonFileTaskStore hard-caps loaded entries at 256 (D364). */\n readonly limit?: number;\n}\n\n/** Options for `Task.submit`. */\nexport interface TaskSubmitOptions {\n /**\n * Optional user-supplied ID. Must match grammar `^[a-z0-9][a-z0-9_-]*$`\n * and MUST NOT start with the reserved prefixes `wf-` / `b-` / `cron-`\n * (D368, EC-5). When omitted, `crypto.randomUUID()` is used.\n */\n readonly id?: string;\n readonly meta?: Record<string, unknown>;\n /**\n * Optional caller-provided AbortSignal. If already aborted at submit\n * time, the registry short-circuits to `cancelled` without acquiring\n * a semaphore slot (EC-4).\n */\n readonly signal?: AbortSignal;\n}\n\n/** Options shape for `TaskStore` factory (D364). */\nexport type TaskStoreOptions =\n | { readonly backend: \"memory\" }\n | { readonly backend: \"json\"; readonly dir: string };\n\n/** Result of `Task.cancel` (D365 — idempotent). */\nexport interface TaskCancelResult {\n readonly cancelled: boolean;\n readonly alreadyTerminal: boolean;\n}\n\n/**\n * Grammar for user-supplied task IDs (D368).\n * `crypto.randomUUID()` outputs do NOT match this (UUIDs have dashes\n * AND uppercase letters in their canonical form on some Node versions),\n * but the registry normalizes auto-generated IDs to lowercase before\n * insertion, so they pass the same regex.\n */\nconst TASK_ID_GRAMMAR = /^[a-z0-9][a-z0-9_-]*$/;\n\n/** Reserved prefixes for adapter-generated IDs (D368, EC-5). */\nconst RESERVED_PREFIXES = [\"wf-\", \"b-\", \"cron-\"] as const;\n\n/**\n * Validates a task ID against the public grammar + reserved prefixes.\n * Throws `InvalidTaskIdError` from `../errors.js` on rejection.\n *\n * Adapter callers (workflow/batch/cron) MUST set `allowReserved: true`\n * to register their own IDs; user-facing surfaces (`Task.submit`,\n * `agent.send({ task: { id } })`) leave it false.\n */\nexport function isValidTaskId(id: string, allowReserved: boolean): boolean {\n if (!TASK_ID_GRAMMAR.test(id)) return false;\n if (allowReserved) return true;\n for (const prefix of RESERVED_PREFIXES) {\n if (id.startsWith(prefix)) return false;\n }\n return true;\n}\n\n/** Re-exported for adapter implementations + tests. */\nexport const TASK_RESERVED_PREFIXES: readonly string[] = RESERVED_PREFIXES;\n","import { mkdir, open, rename, unlink } from \"node:fs/promises\";\nimport { dirname } from \"node:path\";\n\n/**\n * Atomic file replacement: write content to a per-call unique tmp path,\n * fsync, then rename over the target. Crash mid-write leaves either the old\n * file intact or the new file complete — never a half-written file.\n *\n * The tmp suffix is `<pid>.<rand>.tmp` so parallel processes (and concurrent\n * burst writes within one process) never collide on the same tmp path — a\n * race that would manifest as `ENOENT` on `rename` after the rival process\n * already moved its tmp into place.\n *\n * Mirrors OpenClaw's `replaceFileAtomic` from\n * `referencia/openclaw/packages/memory-host-sdk/src/host/fs-utils.ts` with\n * the multi-writer robustness fix.\n *\n * @internal\n */\nexport async function replaceFileAtomic(filePath: string, content: string): Promise<void> {\n const tmp = `${filePath}.${process.pid}.${Math.random().toString(36).slice(2, 10)}.tmp`;\n const handle = await open(tmp, \"w\");\n try {\n await handle.writeFile(content, \"utf8\");\n await handle.sync();\n } finally {\n await handle.close();\n }\n try {\n await rename(tmp, filePath);\n } catch (cause) {\n // Cleanup tmp on rename failure so we don't leak stale .tmp files.\n await unlink(tmp).catch(() => undefined);\n throw cause;\n }\n}\n\n/**\n * Options for `atomicWriteJson`.\n *\n * @internal\n */\nexport interface AtomicWriteJsonOptions {\n /** Indent passed to `JSON.stringify`. Default: 2. */\n indent?: number;\n /** Whether to append a trailing newline (POSIX convention). Default: true. */\n trailingNewline?: boolean;\n}\n\n/**\n * Typed JSON atomic write helper.\n *\n * Serializes `data` to JSON, then delegates to `replaceFileAtomic`. The\n * parent directory is auto-created (recursive `mkdir`) to make this helper\n * safe for callers who haven't ensured the directory exists (EC-4 in the\n * persistence-state-hardening plan).\n *\n * Throws `TypeError` on circular refs or `undefined` data (propagates from\n * `JSON.stringify`).\n *\n * @internal\n */\nexport async function atomicWriteJson<T>(\n filePath: string,\n data: T,\n options?: AtomicWriteJsonOptions,\n): Promise<void> {\n const indent = options?.indent ?? 2;\n const trailingNewline = options?.trailingNewline ?? true;\n const json = JSON.stringify(data, null, indent);\n if (json === undefined) {\n throw new TypeError(\"atomicWriteJson: cannot serialize undefined\");\n }\n const content = trailingNewline ? `${json}\\n` : json;\n await mkdir(dirname(filePath), { recursive: true });\n await replaceFileAtomic(filePath, content);\n}\n\n/**\n * Atomic text write. Same crash-safety guarantees as `replaceFileAtomic` +\n * auto-mkdir of the parent directory. Used by `theokit-migrate-config`\n * (T4.1, EC-2 MUST FIX) so a crash mid-migration leaves previous MD files\n * intact rather than corrupting them.\n *\n * @internal\n */\nexport async function atomicWriteText(filePath: string, content: string): Promise<void> {\n await mkdir(dirname(filePath), { recursive: true });\n await replaceFileAtomic(filePath, content);\n}\n","/**\n * `TaskStore` interface + 2 implementations (ADR D364).\n *\n * - `InMemoryTaskStore` — default, transient, single-process.\n * - `JsonFileTaskStore` — opt-in, one JSON file per task under a\n * dedicated dir; single-process invariant (EC-15 documented).\n *\n * Edge cases absorbed:\n * - EC-1: constructor auto-creates dir (mkdirSync recursive idempotent).\n * - EC-2: every method validates the task id against the public\n * grammar (D368) BEFORE doing any path I/O — path-traversal defense.\n * - EC-6: `list()` returns `[]` on ENOENT (fresh install path).\n * - EC-8: `list()` skips `.tmp.*` orphan files left by interrupted\n * atomic writes.\n * - EC-14 (DOCUMENT): `list()` JSDoc documents the 256-row hard cap\n * and the `submittedBefore` paging idiom.\n * - EC-15 (DOCUMENT): `JsonFileTaskStore` JSDoc documents the\n * single-process invariant; v0.2 SQLite covers cross-process.\n *\n * @internal\n */\n\nimport { mkdirSync, readdirSync } from \"node:fs\";\nimport { readFile, unlink } from \"node:fs/promises\";\nimport { join } from \"node:path\";\n\nimport { InvalidTaskIdError } from \"../../errors.js\";\nimport {\n isValidTaskId,\n type TaskFilter,\n type TaskHandle,\n type TaskState,\n type TaskStoreOptions,\n} from \"../../types/task.js\";\nimport { atomicWriteText } from \"../persistence/atomic-write.js\";\n\nconst JSON_LOAD_CAP = 256;\nconst DEFAULT_LIST_LIMIT = 100;\n\n/** Storage interface used by `TaskRegistry`. */\nexport interface TaskStore {\n insert(handle: TaskHandle): Promise<void>;\n update(id: string, mutate: (h: TaskHandle) => TaskHandle): Promise<TaskHandle | undefined>;\n get(id: string): Promise<TaskHandle | undefined>;\n /**\n * Returns at most `filter.limit ?? 100` matching handles. JsonFile\n * backend hard-caps loaded entries at 256 — callers needing larger\n * pages must use `submittedBefore` to walk the timeline.\n */\n list(filter: TaskFilter): Promise<TaskHandle[]>;\n delete(id: string): Promise<boolean>;\n /** Removes terminal handles whose terminal-timestamp is older than `epochMs`. */\n evictTerminalOlderThan(epochMs: number): Promise<number>;\n}\n\nfunction assertValidIdForStore(id: string): void {\n if (!isValidTaskId(id, /* allowReserved */ true)) {\n throw new InvalidTaskIdError(`store rejects invalid task id: ${id}`, id);\n }\n}\n\nfunction terminalTimestamp(h: TaskHandle): number | undefined {\n if (h.state === \"finished\") return h.finishedAt;\n if (h.state === \"error\") return h.erroredAt;\n if (h.state === \"cancelled\") return h.cancelledAt;\n return undefined;\n}\n\nfunction isTerminal(state: TaskState): boolean {\n return state === \"finished\" || state === \"error\" || state === \"cancelled\";\n}\n\nfunction matchesState(h: TaskHandle, filter: TaskFilter): boolean {\n if (filter.state === undefined) return true;\n const states = Array.isArray(filter.state) ? filter.state : [filter.state];\n return states.includes(h.state);\n}\nfunction matchesKind(h: TaskHandle, filter: TaskFilter): boolean {\n if (filter.kind === undefined) return true;\n const kinds = Array.isArray(filter.kind) ? filter.kind : [filter.kind];\n return kinds.includes(h.kind);\n}\nfunction matchesTime(h: TaskHandle, filter: TaskFilter): boolean {\n if (filter.submittedAfter !== undefined && h.submittedAt <= filter.submittedAfter) return false;\n if (filter.submittedBefore !== undefined && h.submittedAt >= filter.submittedBefore) return false;\n return true;\n}\nfunction matchesFilter(h: TaskHandle, filter: TaskFilter): boolean {\n return matchesState(h, filter) && matchesKind(h, filter) && matchesTime(h, filter);\n}\n\nfunction applyFilter(values: Iterable<TaskHandle>, filter: TaskFilter): TaskHandle[] {\n const limit = filter.limit ?? DEFAULT_LIST_LIMIT;\n const out: TaskHandle[] = [];\n for (const h of values) {\n if (matchesFilter(h, filter)) {\n out.push(h);\n if (out.length >= limit) break;\n }\n }\n return out;\n}\n\n/* ─── InMemory ─── */\n\nexport class InMemoryTaskStore implements TaskStore {\n private readonly map = new Map<string, TaskHandle>();\n\n async insert(handle: TaskHandle): Promise<void> {\n assertValidIdForStore(handle.id);\n this.map.set(handle.id, handle);\n }\n\n async update(id: string, mutate: (h: TaskHandle) => TaskHandle): Promise<TaskHandle | undefined> {\n assertValidIdForStore(id);\n const existing = this.map.get(id);\n if (existing === undefined) return undefined;\n const next = mutate(existing);\n this.map.set(id, next);\n return next;\n }\n\n async get(id: string): Promise<TaskHandle | undefined> {\n assertValidIdForStore(id);\n return this.map.get(id);\n }\n\n async list(filter: TaskFilter): Promise<TaskHandle[]> {\n return applyFilter(this.map.values(), filter);\n }\n\n async delete(id: string): Promise<boolean> {\n assertValidIdForStore(id);\n return this.map.delete(id);\n }\n\n async evictTerminalOlderThan(epochMs: number): Promise<number> {\n let count = 0;\n for (const [id, h] of this.map.entries()) {\n if (!isTerminal(h.state)) continue;\n const ts = terminalTimestamp(h);\n if (ts !== undefined && ts < epochMs) {\n this.map.delete(id);\n count++;\n }\n }\n return count;\n }\n}\n\n/* ─── JsonFile (opt-in) ───\n *\n * IMPORTANT (EC-15): `JsonFileTaskStore` is **single-process**.\n * Concurrent writers from multiple Node processes against the same\n * directory may corrupt entries (atomic-write protects per-file, but\n * the `list()` scan + `update()` read-modify-write cycle is not\n * serialised across processes). Use only when the `TaskRegistry`\n * runs in exactly one process. v0.2 will add a SQLite backend with\n * the same interface for cross-process scenarios (D364 + D61).\n */\nexport class JsonFileTaskStore implements TaskStore {\n constructor(private readonly dir: string) {\n // EC-1: idempotent mkdir; ignore EEXIST.\n try {\n mkdirSync(dir, { recursive: true });\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code !== \"EEXIST\") throw err;\n }\n }\n\n private filePath(id: string): string {\n return join(this.dir, `${id}.json`);\n }\n\n async insert(handle: TaskHandle): Promise<void> {\n assertValidIdForStore(handle.id);\n await atomicWriteText(this.filePath(handle.id), JSON.stringify(handle));\n }\n\n async update(id: string, mutate: (h: TaskHandle) => TaskHandle): Promise<TaskHandle | undefined> {\n assertValidIdForStore(id);\n const existing = await this.get(id);\n if (existing === undefined) return undefined;\n const next = mutate(existing);\n await atomicWriteText(this.filePath(id), JSON.stringify(next));\n return next;\n }\n\n async get(id: string): Promise<TaskHandle | undefined> {\n assertValidIdForStore(id);\n try {\n const raw = await readFile(this.filePath(id), \"utf8\");\n return JSON.parse(raw) as TaskHandle;\n } catch (err) {\n const code = (err as NodeJS.ErrnoException).code;\n if (code === \"ENOENT\") return undefined;\n // Corrupt JSON or other I/O error — log + degrade gracefully (D50/EC-7 cache pattern).\n process.stderr.write(`[task-store] failed to read ${id}: ${(err as Error).message}\\n`);\n return undefined;\n }\n }\n\n async list(filter: TaskFilter): Promise<TaskHandle[]> {\n let entries: string[];\n try {\n entries = readdirSync(this.dir);\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === \"ENOENT\") return []; // EC-6\n throw err;\n }\n // EC-8: skip orphan .tmp files left by interrupted atomic writes.\n const candidates = entries\n .filter((name) => name.endsWith(\".json\") && !name.includes(\".tmp\"))\n .slice(0, JSON_LOAD_CAP);\n\n const loaded = await Promise.all(\n candidates.map(async (name) => {\n const id = name.slice(0, -\".json\".length);\n if (!isValidTaskId(id, true)) return undefined;\n return this.get(id);\n }),\n );\n const handles = loaded.filter((h): h is TaskHandle => h !== undefined);\n return applyFilter(handles, filter);\n }\n\n async delete(id: string): Promise<boolean> {\n assertValidIdForStore(id);\n try {\n await unlink(this.filePath(id));\n return true;\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === \"ENOENT\") return false;\n throw err;\n }\n }\n\n async evictTerminalOlderThan(epochMs: number): Promise<number> {\n const handles = await this.list({ state: [\"finished\", \"error\", \"cancelled\"], limit: 256 });\n let count = 0;\n for (const h of handles) {\n const ts = terminalTimestamp(h);\n if (ts !== undefined && ts < epochMs) {\n if (await this.delete(h.id)) count++;\n }\n }\n return count;\n }\n}\n\n/** Factory used by `TaskRegistry.configure` (D364). */\nexport function getTaskStoreFor(options: TaskStoreOptions): TaskStore {\n if (options.backend === \"memory\") return new InMemoryTaskStore();\n return new JsonFileTaskStore(options.dir);\n}\n"]}
package/dist/task.d.ts ADDED
@@ -0,0 +1,87 @@
1
+ /**
2
+ * `Task` — observable async work registry (Adoption Roadmap gap #2,
3
+ * ADRs D361-D374).
4
+ *
5
+ * Static facade delegating to the in-process `TaskRegistry` singleton.
6
+ * The lifecycle of any task is the 5-state machine `queued | running |
7
+ * finished | error | cancelled` (D362). Wrapping `Agent.send` /
8
+ * `Agent.batch` / `Workflow.run` / `Cron` fires is opt-in via the
9
+ * `{ task: true }` option on each (D363).
10
+ *
11
+ * @public
12
+ */
13
+ import type { TaskCancelResult, TaskEvent, TaskFilter, TaskHandle, TaskKind, TaskStoreOptions, TaskSubmitOptions } from "./types/task.js";
14
+ export interface TaskWorkContext {
15
+ readonly signal: AbortSignal;
16
+ emit(payload: unknown): void;
17
+ }
18
+ export type TaskWorkFn<T> = (ctx: TaskWorkContext) => Promise<T> | T;
19
+ /**
20
+ * Registry-level configuration. May only be applied BEFORE the first
21
+ * `Task.submit` of the process — see EC-13. Subsequent calls emit a
22
+ * single stderr line and become no-ops.
23
+ */
24
+ export interface TaskConfigureOptions {
25
+ readonly store?: TaskStoreOptions;
26
+ readonly maxConcurrent?: number;
27
+ readonly retentionMs?: number;
28
+ }
29
+ export declare class Task {
30
+ private constructor();
31
+ /**
32
+ * Configure the registry. **Must be called before the first `submit`**
33
+ * (EC-13). Available knobs: pluggable store (D364), concurrency cap
34
+ * (D369), and retention (D373).
35
+ */
36
+ static configure(opts: TaskConfigureOptions): void;
37
+ /**
38
+ * Submit a unit of asynchronous work to the registry.
39
+ *
40
+ * The `work` function receives `{ signal, emit }` — `signal` is the
41
+ * AbortSignal honored on cancel; `emit(payload)` produces a
42
+ * `progress` event observable via `Task.subscribe`.
43
+ *
44
+ * Returns a `TaskHandle` in `state: "queued"`. Subsequent state
45
+ * transitions are observable via `Task.subscribe(handle.id)` OR
46
+ * polled via `Task.get(handle.id)`.
47
+ *
48
+ * **Idempotency (D367):** submitting twice with the same `id` returns
49
+ * the existing handle without re-invoking work.
50
+ *
51
+ * **Grammar (D368):** user-supplied ids must match
52
+ * `^[a-z0-9][a-z0-9_-]*$` and must not start with reserved prefixes
53
+ * `wf-` / `b-` / `cron-`. Otherwise `InvalidTaskIdError` is thrown.
54
+ *
55
+ * **Pre-aborted signal (EC-4):** if `options.signal` is already
56
+ * aborted, the task short-circuits to `cancelled` without acquiring
57
+ * a semaphore slot and without invoking `work`.
58
+ */
59
+ static submit<T>(kind: TaskKind, work: TaskWorkFn<T>, options?: TaskSubmitOptions): Promise<TaskHandle>;
60
+ /** Returns matching handles, capped at `filter.limit ?? 100`. */
61
+ static list(filter?: TaskFilter): Promise<TaskHandle[]>;
62
+ /** Returns a single handle by id, or `undefined` if unknown / evicted. */
63
+ static get(id: string): Promise<TaskHandle | undefined>;
64
+ /**
65
+ * Idempotent cancel (D365). Returns:
66
+ * - `{ cancelled: true, alreadyTerminal: false }` — transitioned
67
+ * queued/running task to `cancelled`.
68
+ * - `{ cancelled: false, alreadyTerminal: true }` — task already
69
+ * terminal.
70
+ * - `{ cancelled: false, alreadyTerminal: false }` — task unknown.
71
+ *
72
+ * Never throws.
73
+ */
74
+ static cancel(id: string, reason?: string): Promise<TaskCancelResult>;
75
+ /**
76
+ * Subscribe to a task's event stream. The returned `AsyncIterable<TaskEvent>`
77
+ * starts by replaying buffered events (ring buffer cap 64, D372) and
78
+ * then yields live events until a terminal event (finished / errored
79
+ * / cancelled) is emitted, at which point it closes automatically.
80
+ *
81
+ * Calling `.return()` on the iterator (or `break` in a `for await`)
82
+ * cleans up the subscriber callback (EC-10).
83
+ *
84
+ * Throws `TaskNotFoundError` if the id is unknown or has been evicted.
85
+ */
86
+ static subscribe(id: string): AsyncIterable<TaskEvent>;
87
+ }
@@ -0,0 +1,84 @@
1
+ import type { SDKProvider } from "./types/providers.js";
2
+ import type { SDKModel, SDKRepository, SDKUser } from "./types/theokit.js";
3
+ /**
4
+ * Options shared by every `Theokit.*` request.
5
+ *
6
+ * @public
7
+ */
8
+ export interface TheokitRequestOptions {
9
+ /** Override the `THEOKIT_API_KEY` env var for this call. */
10
+ apiKey?: string;
11
+ /**
12
+ * Target a specific provider for catalog reads. When set to a provider
13
+ * with `authType: "none"` (e.g. `"ollama"`, `"lmstudio"`, `"llamacpp"`),
14
+ * `Theokit.models.list({ provider })` reads from the provider's local
15
+ * `/v1/models` endpoint instead of the TheoCloud catalog. ADR D184.
16
+ *
17
+ * @public
18
+ */
19
+ provider?: string;
20
+ }
21
+ /**
22
+ * Account-level and catalog reads. All methods accept an optional `apiKey`
23
+ * and otherwise fall back to the `THEOKIT_API_KEY` environment variable.
24
+ *
25
+ * @public
26
+ */
27
+ export declare class Theokit {
28
+ private constructor();
29
+ /**
30
+ * Return the user behind the current API key.
31
+ *
32
+ * @public
33
+ */
34
+ static me(options?: TheokitRequestOptions): Promise<SDKUser>;
35
+ /**
36
+ * Model catalog reads.
37
+ *
38
+ * @public
39
+ */
40
+ static readonly models: {
41
+ list: (options?: TheokitRequestOptions) => Promise<SDKModel[]>;
42
+ };
43
+ /**
44
+ * Connected GitHub repositories for the calling user's team. Cloud only.
45
+ *
46
+ * @public
47
+ */
48
+ static readonly repositories: {
49
+ list: (options?: TheokitRequestOptions) => Promise<SDKRepository[]>;
50
+ };
51
+ /**
52
+ * Provider catalog. Lists every provider known to the platform, including
53
+ * plugin-registered ones, with capability and availability metadata.
54
+ *
55
+ * @public
56
+ */
57
+ static readonly providers: {
58
+ list: (options?: TheokitRequestOptions) => Promise<SDKProvider[]>;
59
+ };
60
+ /**
61
+ * Local introspection of bundled SDK assets (ADR D201). Unlike the
62
+ * cloud-catalog `providers.list()` (which hits the TheoCloud HTTP API),
63
+ * `inspect.*` reads the SDK's own bundled registries — useful for
64
+ * tooling (e.g. `@theokit/cli`'s `theokit inspect`) that needs to know
65
+ * what's available WITHOUT a network round-trip.
66
+ *
67
+ * @public
68
+ */
69
+ static readonly inspect: {
70
+ builtinProviders: () => Array<{
71
+ readonly name: string;
72
+ readonly apiMode: string;
73
+ readonly authType: string;
74
+ readonly baseUrl: string;
75
+ readonly aliases?: ReadonlyArray<string>;
76
+ readonly envVars: ReadonlyArray<string>;
77
+ }>;
78
+ embeddingAdapters: () => Array<{
79
+ readonly id: string;
80
+ readonly transport: string;
81
+ readonly defaultModel: string;
82
+ }>;
83
+ };
84
+ }
@@ -0,0 +1,8 @@
1
+ /**
2
+ * Shared `safePathJoin + assertNoSymlinkEscape` helper for built-in coding
3
+ * tools (git-diff, run-vitest, list-dir, read-file, search-text). Returns a
4
+ * pre-formatted `path_traversal` JSON string on failure or `null` on pass.
5
+ *
6
+ * @internal
7
+ */
8
+ export declare function checkPathScope(path: string | undefined, projectRoot: string): string | null;
@@ -0,0 +1,8 @@
1
+ /**
2
+ * Shared `safePathJoin + assertNoSymlinkEscape` helper for built-in coding
3
+ * tools (git-diff, run-vitest, list-dir, read-file, search-text). Returns a
4
+ * pre-formatted `path_traversal` JSON string on failure or `null` on pass.
5
+ *
6
+ * @internal
7
+ */
8
+ export declare function checkPathScope(path: string | undefined, projectRoot: string): string | null;
@@ -0,0 +1,28 @@
1
+ /**
2
+ * Shared subprocess-watch helpers for built-in coding tools (git-diff,
3
+ * run-vitest). Wires the on(close)/on(error) settle pattern in a single
4
+ * place to eliminate the cross-file clone flagged by jscpd.
5
+ *
6
+ * @internal
7
+ */
8
+ /**
9
+ * Settle gate — guarantees the supplied callback fires exactly once across
10
+ * the close/error/timeout race. Clears the timer on settle.
11
+ */
12
+ interface SettleGate {
13
+ /** True after first settle; subsequent calls are no-ops. */
14
+ settled: () => boolean;
15
+ /** Settle the gate, clear the timer, and call `onSettle()`. */
16
+ fire: (onSettle: () => void) => void;
17
+ }
18
+ /**
19
+ * Wire SIGKILL-on-timeout for a detached process group. Returns the settle
20
+ * gate so caller listeners can short-circuit when the timeout already fired.
21
+ */
22
+ export declare function armTimeoutKill<T>(child: ChildProcess, timeoutMs: number, onTimeout: () => T, resolve: (value: T) => void): SettleGate;
23
+ /**
24
+ * Attach a close+error pair of listeners that resolve via the supplied
25
+ * callbacks. Honors the gate so timeout-vs-close races settle exactly once.
26
+ */
27
+ export declare function attachChildSettlers<T>(child: ChildProcess, gate: SettleGate, onClose: (code: number | null) => T, onError: (err: Error) => T, resolve: (value: T) => void): void;
28
+ export {};
@@ -0,0 +1,28 @@
1
+ /**
2
+ * Shared subprocess-watch helpers for built-in coding tools (git-diff,
3
+ * run-vitest). Wires the on(close)/on(error) settle pattern in a single
4
+ * place to eliminate the cross-file clone flagged by jscpd.
5
+ *
6
+ * @internal
7
+ */
8
+ /**
9
+ * Settle gate — guarantees the supplied callback fires exactly once across
10
+ * the close/error/timeout race. Clears the timer on settle.
11
+ */
12
+ interface SettleGate {
13
+ /** True after first settle; subsequent calls are no-ops. */
14
+ settled: () => boolean;
15
+ /** Settle the gate, clear the timer, and call `onSettle()`. */
16
+ fire: (onSettle: () => void) => void;
17
+ }
18
+ /**
19
+ * Wire SIGKILL-on-timeout for a detached process group. Returns the settle
20
+ * gate so caller listeners can short-circuit when the timeout already fired.
21
+ */
22
+ export declare function armTimeoutKill<T>(child: ChildProcess, timeoutMs: number, onTimeout: () => T, resolve: (value: T) => void): SettleGate;
23
+ /**
24
+ * Attach a close+error pair of listeners that resolve via the supplied
25
+ * callbacks. Honors the gate so timeout-vs-close races settle exactly once.
26
+ */
27
+ export declare function attachChildSettlers<T>(child: ChildProcess, gate: SettleGate, onClose: (code: number | null) => T, onError: (err: Error) => T, resolve: (value: T) => void): void;
28
+ export {};
@@ -0,0 +1,22 @@
1
+ /**
2
+ * `git_diff` — built-in tool for coding agents.
3
+ *
4
+ * Returns the unified diff of the working tree (or staged changes when
5
+ * `cached=true`). Implemented as a thin `git diff` subprocess wrapper
6
+ * with a couple of hard limits:
7
+ *
8
+ * - 30s wall clock timeout (kills the process group on expiry)
9
+ * - 5 MB stdout cap (truncate + flag `truncated=true`)
10
+ * - Path scope validated through `safePathJoin` + `assertNoSymlinkEscape`
11
+ *
12
+ * Result shape (always a JSON string):
13
+ * - `{ ok: true, diff: string, truncated?: boolean }`
14
+ * - `{ ok: false, error: 'not_a_repo' | 'path_traversal' | 'timeout' }`
15
+ */
16
+ import type { CustomTool } from "../types/agent.js";
17
+ export interface CreateGitDiffToolOptions {
18
+ projectRoot: string;
19
+ timeoutMs?: number;
20
+ maxStdoutBytes?: number;
21
+ }
22
+ export declare function createGitDiffTool(opts: CreateGitDiffToolOptions): CustomTool;
@@ -0,0 +1,22 @@
1
+ /**
2
+ * `git_diff` — built-in tool for coding agents.
3
+ *
4
+ * Returns the unified diff of the working tree (or staged changes when
5
+ * `cached=true`). Implemented as a thin `git diff` subprocess wrapper
6
+ * with a couple of hard limits:
7
+ *
8
+ * - 30s wall clock timeout (kills the process group on expiry)
9
+ * - 5 MB stdout cap (truncate + flag `truncated=true`)
10
+ * - Path scope validated through `safePathJoin` + `assertNoSymlinkEscape`
11
+ *
12
+ * Result shape (always a JSON string):
13
+ * - `{ ok: true, diff: string, truncated?: boolean }`
14
+ * - `{ ok: false, error: 'not_a_repo' | 'path_traversal' | 'timeout' }`
15
+ */
16
+ import type { CustomTool } from "../types/agent.js";
17
+ export interface CreateGitDiffToolOptions {
18
+ projectRoot: string;
19
+ timeoutMs?: number;
20
+ maxStdoutBytes?: number;
21
+ }
22
+ export declare function createGitDiffTool(opts: CreateGitDiffToolOptions): CustomTool;
@@ -0,0 +1,29 @@
1
+ /**
2
+ * Built-in tools for `@theokit/sdk` agents (`@theokit/sdk/tools`).
3
+ *
4
+ * Each factory returns a `CustomTool` ready to drop into `Agent.create`
5
+ * or `createAgentFactory({ tools: [...] })`. All five share three
6
+ * design rules:
7
+ *
8
+ * 1. **Project-scoped**. Every factory takes `{ projectRoot }` and
9
+ * gates every I/O call against that boundary via the SDK's
10
+ * `safePathJoin` + `assertNoSymlinkEscape` primitives.
11
+ *
12
+ * 2. **Sensitive files refused**. `.env*` (except `.env.example`),
13
+ * `.git/`, `node_modules/`, `.theo/`, and lock files are blocked
14
+ * via `isForbiddenPath`.
15
+ *
16
+ * 3. **JSON returns, never throws on user mistakes**. Handlers return
17
+ * `{ ok: true, ... }` or `{ ok: false, error: '...' }`. Real
18
+ * exceptions are reserved for SDK-side bugs (input parse errors,
19
+ * unexpected fs failures).
20
+ *
21
+ * Consumers: TheoKit Studio (the embedded coding agent), `cli-bot`
22
+ * (the SDK's reference example), and any future coding-agent built on
23
+ * `@theokit/sdk`.
24
+ */
25
+ export { type CreateGitDiffToolOptions, createGitDiffTool } from "./git-diff.js";
26
+ export { type CreateListDirToolOptions, createListDirTool } from "./list-dir.js";
27
+ export { type CreateReadFileToolOptions, createReadFileTool } from "./read-file.js";
28
+ export { type CreateRunVitestToolOptions, createRunVitestTool, type VitestSummary, } from "./run-vitest.js";
29
+ export { type CreateSearchTextToolOptions, createSearchTextTool } from "./search-text.js";