@retinue/agentkit 0.1.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 (405) hide show
  1. package/LICENSE +22 -0
  2. package/README.md +310 -0
  3. package/dist/adapters/bullmq/consumer.d.ts +33 -0
  4. package/dist/adapters/bullmq/consumer.js +41 -0
  5. package/dist/adapters/bullmq/dispatcher.d.ts +74 -0
  6. package/dist/adapters/bullmq/dispatcher.js +160 -0
  7. package/dist/adapters/bullmq/export.d.ts +31 -0
  8. package/dist/adapters/bullmq/export.js +53 -0
  9. package/dist/adapters/bullmq/extraction.d.ts +42 -0
  10. package/dist/adapters/bullmq/extraction.js +63 -0
  11. package/dist/adapters/bullmq/index.d.ts +13 -0
  12. package/dist/adapters/bullmq/index.js +13 -0
  13. package/dist/adapters/bullmq/lock.d.ts +77 -0
  14. package/dist/adapters/bullmq/lock.js +126 -0
  15. package/dist/adapters/bullmq/queue.d.ts +50 -0
  16. package/dist/adapters/bullmq/queue.js +81 -0
  17. package/dist/adapters/memory/artifact-exports.d.ts +11 -0
  18. package/dist/adapters/memory/artifact-exports.js +102 -0
  19. package/dist/adapters/memory/artifacts.d.ts +15 -0
  20. package/dist/adapters/memory/artifacts.js +134 -0
  21. package/dist/adapters/memory/blobs.d.ts +7 -0
  22. package/dist/adapters/memory/blobs.js +27 -0
  23. package/dist/adapters/memory/evaluation.d.ts +18 -0
  24. package/dist/adapters/memory/evaluation.js +148 -0
  25. package/dist/adapters/memory/files.d.ts +27 -0
  26. package/dist/adapters/memory/files.js +0 -0
  27. package/dist/adapters/memory/flows.d.ts +16 -0
  28. package/dist/adapters/memory/flows.js +117 -0
  29. package/dist/adapters/memory/hitl.d.ts +9 -0
  30. package/dist/adapters/memory/hitl.js +130 -0
  31. package/dist/adapters/memory/idempotency.d.ts +13 -0
  32. package/dist/adapters/memory/idempotency.js +32 -0
  33. package/dist/adapters/memory/index.d.ts +39 -0
  34. package/dist/adapters/memory/index.js +107 -0
  35. package/dist/adapters/memory/knowledge.d.ts +43 -0
  36. package/dist/adapters/memory/knowledge.js +248 -0
  37. package/dist/adapters/memory/mcp.d.ts +9 -0
  38. package/dist/adapters/memory/mcp.js +37 -0
  39. package/dist/adapters/memory/message-store.d.ts +17 -0
  40. package/dist/adapters/memory/message-store.js +70 -0
  41. package/dist/adapters/memory/principal-memory.d.ts +7 -0
  42. package/dist/adapters/memory/principal-memory.js +83 -0
  43. package/dist/adapters/memory/runtime.d.ts +29 -0
  44. package/dist/adapters/memory/runtime.js +0 -0
  45. package/dist/adapters/memory/sessions.d.ts +29 -0
  46. package/dist/adapters/memory/sessions.js +0 -0
  47. package/dist/adapters/memory/skills.d.ts +10 -0
  48. package/dist/adapters/memory/skills.js +41 -0
  49. package/dist/adapters/memory/thread-summary.d.ts +7 -0
  50. package/dist/adapters/memory/thread-summary.js +29 -0
  51. package/dist/adapters/memory/usage-limits.d.ts +13 -0
  52. package/dist/adapters/memory/usage-limits.js +72 -0
  53. package/dist/adapters/memory/usage.d.ts +16 -0
  54. package/dist/adapters/memory/usage.js +279 -0
  55. package/dist/adapters/otel/index.d.ts +111 -0
  56. package/dist/adapters/otel/index.js +133 -0
  57. package/dist/adapters/postgres/artifact-exports.d.ts +12 -0
  58. package/dist/adapters/postgres/artifact-exports.js +117 -0
  59. package/dist/adapters/postgres/artifacts.d.ts +16 -0
  60. package/dist/adapters/postgres/artifacts.js +172 -0
  61. package/dist/adapters/postgres/checkpoint-store.d.ts +16 -0
  62. package/dist/adapters/postgres/checkpoint-store.js +34 -0
  63. package/dist/adapters/postgres/config.d.ts +15 -0
  64. package/dist/adapters/postgres/config.js +187 -0
  65. package/dist/adapters/postgres/conversation-store.d.ts +4 -0
  66. package/dist/adapters/postgres/conversation-store.js +82 -0
  67. package/dist/adapters/postgres/evaluation.d.ts +17 -0
  68. package/dist/adapters/postgres/evaluation.js +193 -0
  69. package/dist/adapters/postgres/file-content.d.ts +30 -0
  70. package/dist/adapters/postgres/file-content.js +111 -0
  71. package/dist/adapters/postgres/files.d.ts +19 -0
  72. package/dist/adapters/postgres/files.js +209 -0
  73. package/dist/adapters/postgres/flows.d.ts +20 -0
  74. package/dist/adapters/postgres/flows.js +206 -0
  75. package/dist/adapters/postgres/hitl.d.ts +5 -0
  76. package/dist/adapters/postgres/hitl.js +247 -0
  77. package/dist/adapters/postgres/index.d.ts +35 -0
  78. package/dist/adapters/postgres/index.js +35 -0
  79. package/dist/adapters/postgres/knowledge.d.ts +48 -0
  80. package/dist/adapters/postgres/knowledge.js +255 -0
  81. package/dist/adapters/postgres/memory.d.ts +14 -0
  82. package/dist/adapters/postgres/memory.js +194 -0
  83. package/dist/adapters/postgres/message-store.d.ts +11 -0
  84. package/dist/adapters/postgres/message-store.js +145 -0
  85. package/dist/adapters/postgres/migrations.d.ts +69 -0
  86. package/dist/adapters/postgres/migrations.js +1594 -0
  87. package/dist/adapters/postgres/pg-executor.d.ts +19 -0
  88. package/dist/adapters/postgres/pg-executor.js +32 -0
  89. package/dist/adapters/postgres/retention.d.ts +26 -0
  90. package/dist/adapters/postgres/retention.js +59 -0
  91. package/dist/adapters/postgres/rollups.d.ts +17 -0
  92. package/dist/adapters/postgres/rollups.js +267 -0
  93. package/dist/adapters/postgres/run-coordinator.d.ts +5 -0
  94. package/dist/adapters/postgres/run-coordinator.js +98 -0
  95. package/dist/adapters/postgres/run-event-log.d.ts +26 -0
  96. package/dist/adapters/postgres/run-event-log.js +30 -0
  97. package/dist/adapters/postgres/run-store.d.ts +4 -0
  98. package/dist/adapters/postgres/run-store.js +199 -0
  99. package/dist/adapters/postgres/schema.d.ts +39 -0
  100. package/dist/adapters/postgres/schema.js +70 -0
  101. package/dist/adapters/postgres/session-state.d.ts +7 -0
  102. package/dist/adapters/postgres/session-state.js +99 -0
  103. package/dist/adapters/postgres/sql.d.ts +8 -0
  104. package/dist/adapters/postgres/sql.js +2 -0
  105. package/dist/adapters/postgres/transaction.d.ts +37 -0
  106. package/dist/adapters/postgres/transaction.js +93 -0
  107. package/dist/adapters/postgres/unit-of-work.d.ts +18 -0
  108. package/dist/adapters/postgres/unit-of-work.js +8 -0
  109. package/dist/adapters/postgres/usage-limits.d.ts +15 -0
  110. package/dist/adapters/postgres/usage-limits.js +136 -0
  111. package/dist/adapters/postgres/usage.d.ts +15 -0
  112. package/dist/adapters/postgres/usage.js +226 -0
  113. package/dist/adapters/redis/index.d.ts +9 -0
  114. package/dist/adapters/redis/index.js +9 -0
  115. package/dist/adapters/redis/realtime.d.ts +74 -0
  116. package/dist/adapters/redis/realtime.js +112 -0
  117. package/dist/adapters/supabase/index.d.ts +88 -0
  118. package/dist/adapters/supabase/index.js +84 -0
  119. package/dist/adapters/supabase/realtime.d.ts +30 -0
  120. package/dist/adapters/supabase/realtime.js +53 -0
  121. package/dist/adapters/supabase/rls.d.ts +99 -0
  122. package/dist/adapters/supabase/rls.js +216 -0
  123. package/dist/adapters/supabase/storage.d.ts +50 -0
  124. package/dist/adapters/supabase/storage.js +207 -0
  125. package/dist/agents/agent.d.ts +66 -0
  126. package/dist/agents/agent.js +209 -0
  127. package/dist/agents/define.d.ts +21 -0
  128. package/dist/agents/define.js +63 -0
  129. package/dist/agents/engine.d.ts +98 -0
  130. package/dist/agents/engine.js +462 -0
  131. package/dist/agents/index.d.ts +50 -0
  132. package/dist/agents/index.js +17 -0
  133. package/dist/artifacts/index.d.ts +114 -0
  134. package/dist/artifacts/index.js +219 -0
  135. package/dist/authorization/index.d.ts +76 -0
  136. package/dist/authorization/index.js +76 -0
  137. package/dist/capabilities/index.d.ts +120 -0
  138. package/dist/capabilities/index.js +167 -0
  139. package/dist/capabilities/runtime.d.ts +89 -0
  140. package/dist/capabilities/runtime.js +84 -0
  141. package/dist/citations/index.d.ts +161 -0
  142. package/dist/citations/index.js +182 -0
  143. package/dist/context/assembler.d.ts +82 -0
  144. package/dist/context/assembler.js +129 -0
  145. package/dist/context/compaction.d.ts +45 -0
  146. package/dist/context/compaction.js +55 -0
  147. package/dist/context/index.d.ts +75 -0
  148. package/dist/context/index.js +17 -0
  149. package/dist/core/content-parts.d.ts +194 -0
  150. package/dist/core/content-parts.js +23 -0
  151. package/dist/core/context.d.ts +51 -0
  152. package/dist/core/context.js +9 -0
  153. package/dist/core/env.d.ts +25 -0
  154. package/dist/core/env.js +41 -0
  155. package/dist/core/errors.d.ts +30 -0
  156. package/dist/core/errors.js +65 -0
  157. package/dist/core/events.d.ts +139 -0
  158. package/dist/core/events.js +99 -0
  159. package/dist/core/ids.d.ts +52 -0
  160. package/dist/core/ids.js +13 -0
  161. package/dist/core/index.d.ts +9 -0
  162. package/dist/core/index.js +9 -0
  163. package/dist/core/tokens.d.ts +22 -0
  164. package/dist/core/tokens.js +22 -0
  165. package/dist/core/validation.d.ts +34 -0
  166. package/dist/core/validation.js +176 -0
  167. package/dist/documents/extraction.d.ts +121 -0
  168. package/dist/documents/extraction.js +293 -0
  169. package/dist/documents/index.d.ts +199 -0
  170. package/dist/documents/index.js +65 -0
  171. package/dist/documents/parsers/pdf.d.ts +47 -0
  172. package/dist/documents/parsers/pdf.js +508 -0
  173. package/dist/documents/parsers/text.d.ts +59 -0
  174. package/dist/documents/parsers/text.js +325 -0
  175. package/dist/documents/read-tool.d.ts +52 -0
  176. package/dist/documents/read-tool.js +109 -0
  177. package/dist/documents/render.d.ts +29 -0
  178. package/dist/documents/render.js +59 -0
  179. package/dist/documents/vision.d.ts +159 -0
  180. package/dist/documents/vision.js +214 -0
  181. package/dist/entries/adapters-bullmq.d.ts +8 -0
  182. package/dist/entries/adapters-bullmq.js +8 -0
  183. package/dist/entries/adapters-otel.d.ts +13 -0
  184. package/dist/entries/adapters-otel.js +13 -0
  185. package/dist/entries/adapters-postgres.d.ts +10 -0
  186. package/dist/entries/adapters-postgres.js +10 -0
  187. package/dist/entries/adapters-redis.d.ts +3 -0
  188. package/dist/entries/adapters-redis.js +3 -0
  189. package/dist/entries/context.d.ts +20 -0
  190. package/dist/entries/context.js +20 -0
  191. package/dist/entries/flows.d.ts +15 -0
  192. package/dist/entries/flows.js +15 -0
  193. package/dist/entries/hitl.d.ts +10 -0
  194. package/dist/entries/hitl.js +10 -0
  195. package/dist/entries/knowledge.d.ts +18 -0
  196. package/dist/entries/knowledge.js +19 -0
  197. package/dist/entries/mcp.d.ts +10 -0
  198. package/dist/entries/mcp.js +10 -0
  199. package/dist/entries/observability.d.ts +14 -0
  200. package/dist/entries/observability.js +16 -0
  201. package/dist/entries/persistence.d.ts +11 -0
  202. package/dist/entries/persistence.js +11 -0
  203. package/dist/entries/providers.d.ts +14 -0
  204. package/dist/entries/providers.js +14 -0
  205. package/dist/entries/runtime.d.ts +13 -0
  206. package/dist/entries/runtime.js +13 -0
  207. package/dist/entries/server.d.ts +24 -0
  208. package/dist/entries/server.js +24 -0
  209. package/dist/entries/tools.d.ts +21 -0
  210. package/dist/entries/tools.js +21 -0
  211. package/dist/entries/usage.d.ts +10 -0
  212. package/dist/entries/usage.js +10 -0
  213. package/dist/evaluation/gate.d.ts +168 -0
  214. package/dist/evaluation/gate.js +180 -0
  215. package/dist/evaluation/graders.d.ts +125 -0
  216. package/dist/evaluation/graders.js +203 -0
  217. package/dist/evaluation/index.d.ts +120 -0
  218. package/dist/evaluation/index.js +183 -0
  219. package/dist/evaluation/judge.d.ts +75 -0
  220. package/dist/evaluation/judge.js +111 -0
  221. package/dist/export/index.d.ts +162 -0
  222. package/dist/export/index.js +363 -0
  223. package/dist/export/markdown.d.ts +19 -0
  224. package/dist/export/markdown.js +29 -0
  225. package/dist/export/pdf.d.ts +73 -0
  226. package/dist/export/pdf.js +407 -0
  227. package/dist/files/context.d.ts +97 -0
  228. package/dist/files/context.js +185 -0
  229. package/dist/files/index.d.ts +210 -0
  230. package/dist/files/index.js +338 -0
  231. package/dist/files/read-tool.d.ts +81 -0
  232. package/dist/files/read-tool.js +163 -0
  233. package/dist/files/turn-parts.d.ts +96 -0
  234. package/dist/files/turn-parts.js +171 -0
  235. package/dist/flows/index.d.ts +270 -0
  236. package/dist/flows/index.js +62 -0
  237. package/dist/flows/interpreter.d.ts +146 -0
  238. package/dist/flows/interpreter.js +426 -0
  239. package/dist/flows/runner.d.ts +145 -0
  240. package/dist/flows/runner.js +270 -0
  241. package/dist/graphql/index.d.ts +8 -0
  242. package/dist/graphql/index.js +8 -0
  243. package/dist/graphql/resolvers.d.ts +237 -0
  244. package/dist/graphql/resolvers.js +253 -0
  245. package/dist/graphql/schema.d.ts +11 -0
  246. package/dist/graphql/schema.js +258 -0
  247. package/dist/graphql/sse.d.ts +77 -0
  248. package/dist/graphql/sse.js +100 -0
  249. package/dist/hitl/approved-execution.d.ts +127 -0
  250. package/dist/hitl/approved-execution.js +177 -0
  251. package/dist/hitl/index.d.ts +79 -0
  252. package/dist/hitl/index.js +12 -0
  253. package/dist/hitl/service.d.ts +221 -0
  254. package/dist/hitl/service.js +268 -0
  255. package/dist/idempotency/index.d.ts +70 -0
  256. package/dist/idempotency/index.js +59 -0
  257. package/dist/index.d.ts +103 -0
  258. package/dist/index.js +60 -0
  259. package/dist/knowledge/chunking.d.ts +57 -0
  260. package/dist/knowledge/chunking.js +158 -0
  261. package/dist/knowledge/index.d.ts +119 -0
  262. package/dist/knowledge/index.js +166 -0
  263. package/dist/knowledge/retrieval.d.ts +146 -0
  264. package/dist/knowledge/retrieval.js +170 -0
  265. package/dist/loadtest/harness.d.ts +168 -0
  266. package/dist/loadtest/harness.js +507 -0
  267. package/dist/loadtest/index.d.ts +13 -0
  268. package/dist/loadtest/index.js +13 -0
  269. package/dist/loadtest/injection.d.ts +89 -0
  270. package/dist/loadtest/injection.js +147 -0
  271. package/dist/loadtest/metrics.d.ts +197 -0
  272. package/dist/loadtest/metrics.js +160 -0
  273. package/dist/loadtest/runbooks.d.ts +28 -0
  274. package/dist/loadtest/runbooks.js +159 -0
  275. package/dist/loadtest/scenario.d.ts +104 -0
  276. package/dist/loadtest/scenario.js +208 -0
  277. package/dist/mcp/egress.d.ts +53 -0
  278. package/dist/mcp/egress.js +115 -0
  279. package/dist/mcp/index.d.ts +93 -0
  280. package/dist/mcp/index.js +33 -0
  281. package/dist/mcp/provider.d.ts +62 -0
  282. package/dist/mcp/provider.js +0 -0
  283. package/dist/models/index.d.ts +98 -0
  284. package/dist/models/index.js +74 -0
  285. package/dist/models/pricing.d.ts +24 -0
  286. package/dist/models/pricing.js +37 -0
  287. package/dist/models/provider-factory.d.ts +31 -0
  288. package/dist/models/provider-factory.js +67 -0
  289. package/dist/models/streaming.d.ts +145 -0
  290. package/dist/models/streaming.js +272 -0
  291. package/dist/models/vision.d.ts +38 -0
  292. package/dist/models/vision.js +62 -0
  293. package/dist/persistence/index.d.ts +1654 -0
  294. package/dist/persistence/index.js +226 -0
  295. package/dist/principal-memory/index.d.ts +106 -0
  296. package/dist/principal-memory/index.js +89 -0
  297. package/dist/retention/index.d.ts +89 -0
  298. package/dist/retention/index.js +70 -0
  299. package/dist/runtime/checkpoint.d.ts +37 -0
  300. package/dist/runtime/checkpoint.js +22 -0
  301. package/dist/runtime/index.d.ts +118 -0
  302. package/dist/runtime/index.js +69 -0
  303. package/dist/runtime/retry.d.ts +95 -0
  304. package/dist/runtime/retry.js +126 -0
  305. package/dist/runtime/serialization.d.ts +85 -0
  306. package/dist/runtime/serialization.js +95 -0
  307. package/dist/runtime/streaming.d.ts +54 -0
  308. package/dist/runtime/streaming.js +115 -0
  309. package/dist/runtime/worker.d.ts +130 -0
  310. package/dist/runtime/worker.js +405 -0
  311. package/dist/security/checklist.d.ts +53 -0
  312. package/dist/security/checklist.js +204 -0
  313. package/dist/security/findings.d.ts +56 -0
  314. package/dist/security/findings.js +168 -0
  315. package/dist/security/index.d.ts +14 -0
  316. package/dist/security/index.js +14 -0
  317. package/dist/security/prompt-safety.d.ts +100 -0
  318. package/dist/security/prompt-safety.js +133 -0
  319. package/dist/server/boot.d.ts +32 -0
  320. package/dist/server/boot.js +36 -0
  321. package/dist/server/cli-worker.d.ts +37 -0
  322. package/dist/server/cli-worker.js +151 -0
  323. package/dist/server/cli.d.ts +27 -0
  324. package/dist/server/cli.js +74 -0
  325. package/dist/server/config.d.ts +42 -0
  326. package/dist/server/config.js +127 -0
  327. package/dist/server/health.d.ts +59 -0
  328. package/dist/server/health.js +90 -0
  329. package/dist/server/host.d.ts +39 -0
  330. package/dist/server/host.js +124 -0
  331. package/dist/server/index.d.ts +15 -0
  332. package/dist/server/index.js +15 -0
  333. package/dist/server/main.d.ts +16 -0
  334. package/dist/server/main.js +31 -0
  335. package/dist/server/sse-route.d.ts +21 -0
  336. package/dist/server/sse-route.js +282 -0
  337. package/dist/skills/index.d.ts +67 -0
  338. package/dist/skills/index.js +31 -0
  339. package/dist/skills/resolver.d.ts +54 -0
  340. package/dist/skills/resolver.js +121 -0
  341. package/dist/teams/index.d.ts +93 -0
  342. package/dist/teams/index.js +207 -0
  343. package/dist/telemetry/index.d.ts +157 -0
  344. package/dist/telemetry/index.js +71 -0
  345. package/dist/telemetry/instrument.d.ts +108 -0
  346. package/dist/telemetry/instrument.js +232 -0
  347. package/dist/telemetry/log-events.d.ts +17 -0
  348. package/dist/telemetry/log-events.js +58 -0
  349. package/dist/telemetry/metrics.d.ts +123 -0
  350. package/dist/telemetry/metrics.js +135 -0
  351. package/dist/telemetry/noop.d.ts +39 -0
  352. package/dist/telemetry/noop.js +143 -0
  353. package/dist/telemetry/redaction.d.ts +64 -0
  354. package/dist/telemetry/redaction.js +153 -0
  355. package/dist/telemetry/spans.d.ts +56 -0
  356. package/dist/telemetry/spans.js +78 -0
  357. package/dist/telemetry/trace-context.d.ts +55 -0
  358. package/dist/telemetry/trace-context.js +60 -0
  359. package/dist/toolkit/compute.d.ts +53 -0
  360. package/dist/toolkit/compute.js +152 -0
  361. package/dist/toolkit/data.d.ts +98 -0
  362. package/dist/toolkit/data.js +235 -0
  363. package/dist/toolkit/http.d.ts +113 -0
  364. package/dist/toolkit/http.js +205 -0
  365. package/dist/toolkit/index.d.ts +21 -0
  366. package/dist/toolkit/index.js +17 -0
  367. package/dist/toolkit/web.d.ts +107 -0
  368. package/dist/toolkit/web.js +147 -0
  369. package/dist/tools/define.d.ts +25 -0
  370. package/dist/tools/define.js +45 -0
  371. package/dist/tools/delegating.d.ts +132 -0
  372. package/dist/tools/delegating.js +211 -0
  373. package/dist/tools/index.d.ts +129 -0
  374. package/dist/tools/index.js +33 -0
  375. package/dist/tools/library/compute.d.ts +11 -0
  376. package/dist/tools/library/compute.js +46 -0
  377. package/dist/tools/library/data.d.ts +16 -0
  378. package/dist/tools/library/data.js +92 -0
  379. package/dist/tools/library/http.d.ts +28 -0
  380. package/dist/tools/library/http.js +71 -0
  381. package/dist/tools/library/index.d.ts +97 -0
  382. package/dist/tools/library/index.js +134 -0
  383. package/dist/tools/library/knowledge.d.ts +39 -0
  384. package/dist/tools/library/knowledge.js +58 -0
  385. package/dist/tools/library/web.d.ts +19 -0
  386. package/dist/tools/library/web.js +65 -0
  387. package/dist/tools/meta-tools.d.ts +19 -0
  388. package/dist/tools/meta-tools.js +36 -0
  389. package/dist/tools/registry.d.ts +146 -0
  390. package/dist/tools/registry.js +291 -0
  391. package/dist/usage/index.d.ts +105 -0
  392. package/dist/usage/index.js +20 -0
  393. package/dist/usage/quota.d.ts +258 -0
  394. package/dist/usage/quota.js +510 -0
  395. package/dist/usage/recorder.d.ts +29 -0
  396. package/dist/usage/recorder.js +96 -0
  397. package/dist/usage/rollups.d.ts +121 -0
  398. package/dist/usage/rollups.js +157 -0
  399. package/dist/worker/export.d.ts +57 -0
  400. package/dist/worker/export.js +81 -0
  401. package/dist/worker/extraction.d.ts +57 -0
  402. package/dist/worker/extraction.js +84 -0
  403. package/dist/worker/main.d.ts +103 -0
  404. package/dist/worker/main.js +159 -0
  405. package/package.json +187 -0
@@ -0,0 +1,118 @@
1
+ /**
2
+ * Run lifecycle and execution limits — `docs/04-durable-runtime-and-hitl.md`.
3
+ */
4
+ import type { PlatformError } from "../core/errors.js";
5
+ import type { AgentId, ConversationId, PrincipalId, RunId, TenantId } from "../core/ids.js";
6
+ export declare const RUN_STATUSES: readonly ["queued", "running", "waiting-for-question", "waiting-for-approval", "retry-pending", "completed", "failed", "cancelled"];
7
+ export type RunStatus = (typeof RUN_STATUSES)[number];
8
+ /**
9
+ * The state machine from the specification. A transition absent from this map is a
10
+ * bug, not an undefined behaviour — the worker rejects it rather than guessing.
11
+ */
12
+ export declare const RUN_TRANSITIONS: Readonly<Record<RunStatus, readonly RunStatus[]>>;
13
+ export declare const canTransition: (from: RunStatus, to: RunStatus) => boolean;
14
+ export declare const isTerminal: (status: RunStatus) => boolean;
15
+ export type ExecutionLimits = {
16
+ readonly maxSteps: number;
17
+ readonly maxToolCalls: number;
18
+ readonly wallClockTimeoutMs: number;
19
+ readonly maxInputTokens: number;
20
+ readonly maxOutputTokens: number;
21
+ readonly costCeilingMinorUnits: number;
22
+ readonly maxRetries: number;
23
+ readonly retryBackoffMs: number;
24
+ /** Beyond this, a tool result is spilled to blob storage and referenced. */
25
+ readonly maxInlineToolOutputBytes: number;
26
+ /**
27
+ * Sampling temperature, when the agent wants to pin it (#160).
28
+ *
29
+ * Optional, because "leave the provider's default alone" is a real and common choice, and a required field
30
+ * would force every agent to invent a number. `0` is meaningful and distinct from absent — a graded run needs
31
+ * to be able to ask for it, which is what the evaluation harness's reproducibility argument rests on.
32
+ */
33
+ readonly temperature?: number;
34
+ };
35
+ /**
36
+ * The conversation a run belongs to, or a refusal — #198 AC-3.
37
+ *
38
+ * The whole point of making `conversationId` optional is that a run without one no longer invents one. That
39
+ * creates a second hazard immediately: a caller reaching for conversation-scoped data — history, compaction,
40
+ * thread summaries — and receiving *nothing* rather than an error.
41
+ *
42
+ * Silently empty is the worse failure. An automation whose history came back empty would look like a fresh
43
+ * conversation, the model would be prompted as if nothing had happened, and the run would produce a confident
44
+ * answer built on an absence nobody reported. That is the same class of defect as a scan reporting zero
45
+ * references for a directory it could not read.
46
+ *
47
+ * So this throws, naming the capability the caller asked for. Reaching for history on a run that has no
48
+ * conversation is a programming error, and the message says which one.
49
+ */
50
+ export declare const conversationScoped: (run: Run, capability: string) => ConversationId;
51
+ export type Run = {
52
+ readonly id: RunId;
53
+ readonly tenantId: TenantId;
54
+ /** Absent for a run that belongs to no conversation — see `NewRun.conversationId` (#198). */
55
+ readonly conversationId?: ConversationId;
56
+ readonly agentId: AgentId;
57
+ readonly agentVersion: number;
58
+ /** What this run was asked to do, for a run with no conversation to read — see `NewRun.input` (#202). */
59
+ readonly input?: unknown;
60
+ /** Per-run ceilings from admission, overriding the manifest's — see `NewRun.limits` (#202). */
61
+ readonly limits?: {
62
+ readonly maxSteps?: number;
63
+ readonly costCeilingMinorUnits?: number;
64
+ readonly wallClockTimeoutMs?: number;
65
+ };
66
+ readonly status: RunStatus;
67
+ readonly createdAt: string;
68
+ readonly startedAt?: string;
69
+ readonly finishedAt?: string;
70
+ readonly error?: PlatformError;
71
+ /** Identifies the worker holding the claim; used to reap stale streams. */
72
+ readonly claimedBy?: string;
73
+ readonly keepaliveAt?: string;
74
+ /** When the current claim's lease expires. A past value marks the run reclaimable. */
75
+ readonly leaseExpiresAt?: string;
76
+ /** Set when a cancel was requested; the owning worker observes it and stops. Durable so a
77
+ * cancel issued to one process is honored by whichever worker holds the run. */
78
+ readonly cancelRequestedAt?: string;
79
+ /**
80
+ * The caller this run was admitted for — #164.
81
+ *
82
+ * Absent for runs created before this was recorded, and for a caller that did not supply it. That absence is
83
+ * deliberately visible rather than defaulted: `buildContext` substituting an identity is the bug this exists
84
+ * to end, and a default here would move the substitution one layer down where it is harder to see.
85
+ */
86
+ readonly principalId?: PrincipalId;
87
+ readonly roleIds?: readonly string[];
88
+ };
89
+ /** Durable job enqueue. Adapters: BullMQ, in-memory for tests. */
90
+ export interface JobDispatcher {
91
+ /**
92
+ * `traceparent` and `enqueuedAt` are the trace hop (#143).
93
+ *
94
+ * On the port rather than smuggled through a side channel on the adapter, because the alternative was an
95
+ * instrumented wrapper remembering the last span it opened — which is wrong the moment two enqueues overlap,
96
+ * and overlapping enqueues are the normal case. Optional so every existing caller is unaffected and a job
97
+ * already sitting on the queue still runs; a job with no traceparent starts its own trace, which loses a link
98
+ * rather than a run.
99
+ */
100
+ enqueueRun(input: {
101
+ tenantId: TenantId;
102
+ runId: RunId;
103
+ readonly traceparent?: string;
104
+ readonly enqueuedAt?: string;
105
+ }): Promise<void>;
106
+ }
107
+ /** Atomic claim so two workers never process one run. Adapters: Redis, Postgres. */
108
+ export interface DistributedLockStore {
109
+ acquire(key: string, ttlMs: number): Promise<{
110
+ released: () => Promise<void>;
111
+ } | null>;
112
+ }
113
+ export * from "./retry.js";
114
+ export * from "./checkpoint.js";
115
+ export * from "./worker.js";
116
+ export * from "./streaming.js";
117
+ export * from "./serialization.js";
118
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1,69 @@
1
+ /**
2
+ * Run lifecycle and execution limits — `docs/04-durable-runtime-and-hitl.md`.
3
+ */
4
+ import { AgentPlatformError } from "../core/errors.js";
5
+ export const RUN_STATUSES = [
6
+ "queued",
7
+ "running",
8
+ "waiting-for-question",
9
+ "waiting-for-approval",
10
+ "retry-pending",
11
+ "completed",
12
+ "failed",
13
+ "cancelled",
14
+ ];
15
+ /**
16
+ * The state machine from the specification. A transition absent from this map is a
17
+ * bug, not an undefined behaviour — the worker rejects it rather than guessing.
18
+ */
19
+ export const RUN_TRANSITIONS = {
20
+ queued: ["running", "cancelled"],
21
+ running: [
22
+ "waiting-for-question",
23
+ "waiting-for-approval",
24
+ "retry-pending",
25
+ "completed",
26
+ "failed",
27
+ "cancelled",
28
+ ],
29
+ "waiting-for-question": ["queued", "cancelled"],
30
+ "waiting-for-approval": ["queued", "cancelled"],
31
+ "retry-pending": ["queued", "cancelled"],
32
+ completed: [],
33
+ failed: [],
34
+ cancelled: [],
35
+ };
36
+ export const canTransition = (from, to) => RUN_TRANSITIONS[from].includes(to);
37
+ export const isTerminal = (status) => RUN_TRANSITIONS[status].length === 0;
38
+ /**
39
+ * The conversation a run belongs to, or a refusal — #198 AC-3.
40
+ *
41
+ * The whole point of making `conversationId` optional is that a run without one no longer invents one. That
42
+ * creates a second hazard immediately: a caller reaching for conversation-scoped data — history, compaction,
43
+ * thread summaries — and receiving *nothing* rather than an error.
44
+ *
45
+ * Silently empty is the worse failure. An automation whose history came back empty would look like a fresh
46
+ * conversation, the model would be prompted as if nothing had happened, and the run would produce a confident
47
+ * answer built on an absence nobody reported. That is the same class of defect as a scan reporting zero
48
+ * references for a directory it could not read.
49
+ *
50
+ * So this throws, naming the capability the caller asked for. Reaching for history on a run that has no
51
+ * conversation is a programming error, and the message says which one.
52
+ */
53
+ export const conversationScoped = (run, capability) => {
54
+ if (run.conversationId !== undefined)
55
+ return run.conversationId;
56
+ throw new AgentPlatformError({
57
+ code: "invalid_input",
58
+ message: `${capability} needs a conversation, and run ${run.id} belongs to none. This is a run admitted without ` +
59
+ `a conversation — a triggered automation rather than a chat turn — so conversation-scoped capabilities ` +
60
+ `are unavailable to it. Either give the run a conversation, or turn ${capability} off for this runtime.`,
61
+ retryable: false,
62
+ });
63
+ };
64
+ export * from "./retry.js";
65
+ export * from "./checkpoint.js";
66
+ export * from "./worker.js";
67
+ export * from "./streaming.js";
68
+ export * from "./serialization.js";
69
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,95 @@
1
+ /**
2
+ * Claude/Anthropic-SDK-style retry policy — `docs/04-durable-runtime-and-hitl.md` → Retry policy.
3
+ *
4
+ * A single provider call is retried on transient failures with exponential backoff plus jitter,
5
+ * honoring any server-supplied `retry-after`, and only for the transient HTTP classes the spec
6
+ * enumerates (408/409/429/5xx/529). Deterministic 4xx validation errors fail fast.
7
+ *
8
+ * This layer retries *provider calls*, which are side-effect-free to repeat. External/destructive
9
+ * tool writes are made safe to retry separately, via idempotency keys (see `../idempotency`), so
10
+ * nothing here fires a side effect twice.
11
+ */
12
+ import { type PlatformError } from "../core/errors.js";
13
+ export type RetryPolicy = {
14
+ /** Total attempts including the first. `maxAttempts: 1` disables retrying. */
15
+ readonly maxAttempts: number;
16
+ /** Backoff for the first retry, before jitter. */
17
+ readonly baseDelayMs: number;
18
+ /** Upper bound on the computed (pre-`retry-after`) backoff. */
19
+ readonly maxDelayMs: number;
20
+ /** Geometric growth per attempt. */
21
+ readonly backoffFactor: number;
22
+ /** Fraction of the backoff shaved off by jitter, in `[0, 1]`. 0.25 mirrors the Anthropic SDK. */
23
+ readonly jitter: number;
24
+ /** A server `retry-after` is honored up to this ceiling, so a hostile value cannot stall a run. */
25
+ readonly retryAfterCapMs: number;
26
+ };
27
+ /** Mirrors the Anthropic TS SDK defaults: 0.5s base, 8s cap, x2, -25% jitter. */
28
+ export declare const DEFAULT_RETRY_POLICY: RetryPolicy;
29
+ /**
30
+ * The transient HTTP status classes, matching the spec and the Anthropic SDK's `shouldRetry`:
31
+ * `408` request timeout, `409` conflict, `429` rate limited, any `5xx`, and `529` overloaded.
32
+ */
33
+ export declare const isRetryableStatus: (status: number) => boolean;
34
+ /** Map a raw provider HTTP status to the platform error code the runtime reasons about. */
35
+ export declare const statusToErrorCode: (status: number) => PlatformError["code"];
36
+ /**
37
+ * Parse a `Retry-After` / `retry-after-ms` header into milliseconds. Accepts a delta-seconds
38
+ * integer, a millisecond value, or an HTTP-date (resolved against `now`). Returns `undefined`
39
+ * when absent or unparseable so the caller falls back to computed backoff.
40
+ */
41
+ export declare const parseRetryAfterMs: (headers: {
42
+ retryAfter?: string | number | null;
43
+ retryAfterMs?: string | number | null;
44
+ }, now: number) => number | undefined;
45
+ export type RetryDecision = {
46
+ readonly retry: true;
47
+ readonly attempt: number;
48
+ readonly maxAttempts: number;
49
+ readonly delayMs: number;
50
+ } | {
51
+ readonly retry: false;
52
+ readonly reason: "non-retryable" | "exhausted";
53
+ };
54
+ /**
55
+ * Compute the pre-jitter backoff for the retry that follows `attempt` (1-based). Exposed for tests
56
+ * and so a transport can preview the schedule.
57
+ */
58
+ export declare const backoffMs: (policy: RetryPolicy, attempt: number) => number;
59
+ /**
60
+ * Decide whether the failed `attempt` should be retried and, if so, how long to wait. `random`
61
+ * defaults to `Math.random`; inject a fixed value for deterministic tests. When the error carries
62
+ * `retryAfterMs`, the wait is at least that long (capped by `retryAfterCapMs`) — honoring the
63
+ * server without letting it stall the run indefinitely.
64
+ */
65
+ export declare const decideRetry: (input: {
66
+ readonly error: PlatformError;
67
+ readonly attempt: number;
68
+ readonly policy: RetryPolicy;
69
+ readonly random?: () => number;
70
+ }) => RetryDecision;
71
+ /** Normalize a thrown value to a `PlatformError`. Unclassified throws fail fast (non-retryable). */
72
+ export declare const toPlatformError: (value: unknown) => PlatformError;
73
+ export type RetryPendingInfo = {
74
+ readonly attempt: number;
75
+ readonly maxAttempts: number;
76
+ readonly delayMs: number;
77
+ readonly nextAttemptAt: string;
78
+ readonly error: PlatformError;
79
+ };
80
+ /**
81
+ * Run `operation` with the retry policy. `operation` receives the 1-based attempt number and MUST
82
+ * be safe to repeat (provider call, or an idempotent tool). Between attempts `onRetryPending` fires
83
+ * so the worker can persist a `retry-pending` status and publish a `run.retry-pending` event, then
84
+ * `sleep` waits out the backoff. Exhausting the budget rethrows the last error unchanged.
85
+ */
86
+ export declare const runWithRetry: <T>(input: {
87
+ readonly operation: (attempt: number) => Promise<T>;
88
+ readonly sleep: (ms: number) => Promise<void>;
89
+ readonly now: () => number;
90
+ readonly policy?: RetryPolicy;
91
+ readonly random?: () => number;
92
+ readonly startAttempt?: number;
93
+ readonly onRetryPending?: (info: RetryPendingInfo) => void | Promise<void>;
94
+ }) => Promise<T>;
95
+ //# sourceMappingURL=retry.d.ts.map
@@ -0,0 +1,126 @@
1
+ /**
2
+ * Claude/Anthropic-SDK-style retry policy — `docs/04-durable-runtime-and-hitl.md` → Retry policy.
3
+ *
4
+ * A single provider call is retried on transient failures with exponential backoff plus jitter,
5
+ * honoring any server-supplied `retry-after`, and only for the transient HTTP classes the spec
6
+ * enumerates (408/409/429/5xx/529). Deterministic 4xx validation errors fail fast.
7
+ *
8
+ * This layer retries *provider calls*, which are side-effect-free to repeat. External/destructive
9
+ * tool writes are made safe to retry separately, via idempotency keys (see `../idempotency`), so
10
+ * nothing here fires a side effect twice.
11
+ */
12
+ import { AgentPlatformError } from "../core/errors.js";
13
+ /** Mirrors the Anthropic TS SDK defaults: 0.5s base, 8s cap, x2, -25% jitter. */
14
+ export const DEFAULT_RETRY_POLICY = {
15
+ maxAttempts: 5,
16
+ baseDelayMs: 500,
17
+ maxDelayMs: 8_000,
18
+ backoffFactor: 2,
19
+ jitter: 0.25,
20
+ retryAfterCapMs: 60_000,
21
+ };
22
+ /**
23
+ * The transient HTTP status classes, matching the spec and the Anthropic SDK's `shouldRetry`:
24
+ * `408` request timeout, `409` conflict, `429` rate limited, any `5xx`, and `529` overloaded.
25
+ */
26
+ export const isRetryableStatus = (status) => status === 408 || status === 409 || status === 429 || status >= 500;
27
+ /** Map a raw provider HTTP status to the platform error code the runtime reasons about. */
28
+ export const statusToErrorCode = (status) => {
29
+ if (status === 408)
30
+ return "timeout";
31
+ if (status === 429)
32
+ return "rate_limited";
33
+ if (status === 529 || status === 503)
34
+ return "provider_unavailable";
35
+ if (status >= 500)
36
+ return "provider_error";
37
+ if (status === 409)
38
+ return "conflict";
39
+ return "provider_error";
40
+ };
41
+ /**
42
+ * Parse a `Retry-After` / `retry-after-ms` header into milliseconds. Accepts a delta-seconds
43
+ * integer, a millisecond value, or an HTTP-date (resolved against `now`). Returns `undefined`
44
+ * when absent or unparseable so the caller falls back to computed backoff.
45
+ */
46
+ export const parseRetryAfterMs = (headers, now) => {
47
+ const ms = headers.retryAfterMs;
48
+ if (ms !== undefined && ms !== null && ms !== "") {
49
+ const n = typeof ms === "number" ? ms : Number(ms);
50
+ if (Number.isFinite(n) && n >= 0)
51
+ return n;
52
+ }
53
+ const ra = headers.retryAfter;
54
+ if (ra === undefined || ra === null || ra === "")
55
+ return undefined;
56
+ const n = typeof ra === "number" ? ra : Number(ra);
57
+ if (Number.isFinite(n) && n >= 0)
58
+ return n * 1000;
59
+ const dateMs = Date.parse(String(ra));
60
+ if (Number.isFinite(dateMs))
61
+ return Math.max(0, dateMs - now);
62
+ return undefined;
63
+ };
64
+ /**
65
+ * Compute the pre-jitter backoff for the retry that follows `attempt` (1-based). Exposed for tests
66
+ * and so a transport can preview the schedule.
67
+ */
68
+ export const backoffMs = (policy, attempt) => Math.min(policy.baseDelayMs * policy.backoffFactor ** (attempt - 1), policy.maxDelayMs);
69
+ /**
70
+ * Decide whether the failed `attempt` should be retried and, if so, how long to wait. `random`
71
+ * defaults to `Math.random`; inject a fixed value for deterministic tests. When the error carries
72
+ * `retryAfterMs`, the wait is at least that long (capped by `retryAfterCapMs`) — honoring the
73
+ * server without letting it stall the run indefinitely.
74
+ */
75
+ export const decideRetry = (input) => {
76
+ const { error, attempt, policy } = input;
77
+ if (!error.retryable)
78
+ return { retry: false, reason: "non-retryable" };
79
+ if (attempt >= policy.maxAttempts)
80
+ return { retry: false, reason: "exhausted" };
81
+ const random = input.random ?? Math.random;
82
+ const jittered = backoffMs(policy, attempt) * (1 - random() * policy.jitter);
83
+ const honored = error.retryAfterMs !== undefined
84
+ ? Math.max(jittered, Math.min(error.retryAfterMs, policy.retryAfterCapMs))
85
+ : jittered;
86
+ return { retry: true, attempt, maxAttempts: policy.maxAttempts, delayMs: Math.round(honored) };
87
+ };
88
+ /** Normalize a thrown value to a `PlatformError`. Unclassified throws fail fast (non-retryable). */
89
+ export const toPlatformError = (value) => {
90
+ if (value instanceof AgentPlatformError)
91
+ return value.toPlatformError();
92
+ const message = value instanceof Error ? value.message : String(value);
93
+ return { code: "internal", message, retryable: false };
94
+ };
95
+ /**
96
+ * Run `operation` with the retry policy. `operation` receives the 1-based attempt number and MUST
97
+ * be safe to repeat (provider call, or an idempotent tool). Between attempts `onRetryPending` fires
98
+ * so the worker can persist a `retry-pending` status and publish a `run.retry-pending` event, then
99
+ * `sleep` waits out the backoff. Exhausting the budget rethrows the last error unchanged.
100
+ */
101
+ export const runWithRetry = async (input) => {
102
+ const policy = input.policy ?? DEFAULT_RETRY_POLICY;
103
+ let attempt = input.startAttempt ?? 1;
104
+ for (;;) {
105
+ try {
106
+ return await input.operation(attempt);
107
+ }
108
+ catch (thrown) {
109
+ const error = toPlatformError(thrown);
110
+ const decision = decideRetry({ error, attempt, policy, random: input.random });
111
+ if (!decision.retry)
112
+ throw new AgentPlatformError(error, { cause: thrown });
113
+ const nextAttemptAt = new Date(input.now() + decision.delayMs).toISOString();
114
+ await input.onRetryPending?.({
115
+ attempt,
116
+ maxAttempts: policy.maxAttempts,
117
+ delayMs: decision.delayMs,
118
+ nextAttemptAt,
119
+ error,
120
+ });
121
+ await input.sleep(decision.delayMs);
122
+ attempt += 1;
123
+ }
124
+ }
125
+ };
126
+ //# sourceMappingURL=retry.js.map
@@ -0,0 +1,85 @@
1
+ /**
2
+ * Per-conversation run serialization + turn commit — `docs/13-sessions-and-threads.md`.
3
+ *
4
+ * Runs within one conversation are serialized: at most one is `Running`, the rest queue FIFO, so
5
+ * session-state and message order stay deterministic. A turn reads session state at claim time and
6
+ * commits its state write in the same unit of work that finalizes the run, so state and messages
7
+ * never diverge. The agent binding makes resumption deterministic — a resumed thread runs the same
8
+ * agent, and the same version when pinned.
9
+ */
10
+ import type { ConversationId, RunId, TenantId } from "../core/ids.js";
11
+ import type { ConversationBinding, ConversationRunCoordinator, UnitOfWork } from "../persistence/index.js";
12
+ import type { JobDispatcher } from "./index.js";
13
+ import type { RunEventLog } from "../core/events.js";
14
+ /**
15
+ * Start `runId` now if the conversation is free, else enqueue it FIFO. Returns whether it started.
16
+ * The claim-or-enqueue is atomic, so two runs racing to start the same conversation cannot both win,
17
+ * and a run can never slip into an idle-but-unclaimed slot and strand itself.
18
+ */
19
+ export declare const startOrEnqueueRun: (coordinator: ConversationRunCoordinator, input: {
20
+ tenantId: TenantId;
21
+ /**
22
+ * Absent for a run that belongs to no conversation — #198.
23
+ *
24
+ * Then **no slot is claimed at all**, and the run is admitted directly. The SPEC first proposed a
25
+ * *tenant-level* slot for these; that was wrong and is corrected here. A tenant-level slot would serialise
26
+ * every automation a tenant owns — two unrelated webhooks would queue behind each other for no reason —
27
+ * and the reason there is a conversation slot in the first place is that turns in one conversation have an
28
+ * order a person can see. An automation has no such ordering requirement.
29
+ *
30
+ * Concurrency for these runs is bounded where it should be: the worker's own limits, and quotas.
31
+ */
32
+ conversationId?: ConversationId;
33
+ runId: RunId;
34
+ /**
35
+ * The durable log, so admission is *observable* — #170.
36
+ *
37
+ * `run.queued` was in `RUN_EVENT_TYPES`, mapped to a telemetry span, and mapped by the frontend reducer to
38
+ * the status `queued` — and **nothing emitted it**. So a client subscribing to a run saw nothing at all
39
+ * between sending a message and a worker picking it up: the one moment where "queued" is the only true
40
+ * thing to say, and the state the reducer had a case for could never be reached.
41
+ *
42
+ * Emitted here rather than by each caller because admission is the event. Two hosts emitting their own
43
+ * would be two answers to "when was this queued", and the one that forgot would look like a hang.
44
+ *
45
+ * Optional: a caller with no log still admits runs. Sequence 1 by definition — admission is the first thing
46
+ * that happens to a run, and the worker reconciles from the log before emitting, so its own first event
47
+ * continues from here rather than colliding.
48
+ */
49
+ eventLog?: RunEventLog;
50
+ now?: () => string;
51
+ }) => Promise<"started" | "queued">;
52
+ /**
53
+ * On a run reaching a terminal state, atomically release the conversation and promote the next queued
54
+ * run, then hand it to the dispatcher. Returns the promoted run, or null when the backlog is empty.
55
+ * Because release+promote is atomic, two runs can never both become active. This is the per-thread
56
+ * mailbox drain that guarantees FIFO execution.
57
+ */
58
+ export declare const advanceConversation: (coordinator: ConversationRunCoordinator, dispatcher: JobDispatcher, input: {
59
+ tenantId: TenantId;
60
+ conversationId: ConversationId;
61
+ runId: RunId;
62
+ }) => Promise<RunId | null>;
63
+ /**
64
+ * The agent version a resumed thread must run. `pinned` keeps the recorded version even when a newer
65
+ * one exists (deterministic continuation); `latest` tracks the newest. Throws if a pinned binding is
66
+ * missing its version — a data error, not a silent fallback.
67
+ */
68
+ export declare const resolveAgentVersionForResume: (binding: ConversationBinding, latestVersion: number) => number;
69
+ /** One write in a turn commit: `do` performs it, `undo` compensates it if a later step fails. */
70
+ export type CommitStep<T> = {
71
+ readonly do: () => Promise<T>;
72
+ readonly undo?: (result: T) => void | Promise<void>;
73
+ };
74
+ /**
75
+ * Commit a turn's writes together. Every step runs inside the unit of work; if any step throws, the
76
+ * already-applied steps are compensated in reverse — so session state and messages commit
77
+ * all-or-nothing. The Postgres `UnitOfWork` makes this a real transaction; the memory one compensates
78
+ * explicitly. Pass a `UnitOfWork` exposing `runTx` (the memory/Postgres adapters do) to get rollback.
79
+ */
80
+ export declare const commitTurn: (uow: UnitOfWork & {
81
+ runTx<T>(fn: (tx: {
82
+ onRollback(c: () => void | Promise<void>): void;
83
+ }) => Promise<T>): Promise<T>;
84
+ }, steps: ReadonlyArray<CommitStep<unknown>>) => Promise<void>;
85
+ //# sourceMappingURL=serialization.d.ts.map
@@ -0,0 +1,95 @@
1
+ /**
2
+ * Per-conversation run serialization + turn commit — `docs/13-sessions-and-threads.md`.
3
+ *
4
+ * Runs within one conversation are serialized: at most one is `Running`, the rest queue FIFO, so
5
+ * session-state and message order stay deterministic. A turn reads session state at claim time and
6
+ * commits its state write in the same unit of work that finalizes the run, so state and messages
7
+ * never diverge. The agent binding makes resumption deterministic — a resumed thread runs the same
8
+ * agent, and the same version when pinned.
9
+ */
10
+ import { AgentPlatformError } from "../core/errors.js";
11
+ /**
12
+ * Start `runId` now if the conversation is free, else enqueue it FIFO. Returns whether it started.
13
+ * The claim-or-enqueue is atomic, so two runs racing to start the same conversation cannot both win,
14
+ * and a run can never slip into an idle-but-unclaimed slot and strand itself.
15
+ */
16
+ export const startOrEnqueueRun = async (coordinator, input) => {
17
+ /**
18
+ * A conversation-less run skips the coordinator entirely, and is `started` by definition — there is nothing
19
+ * for it to be queued *behind*. Calling `claimOrEnqueue` with no conversation would mean inventing a slot key,
20
+ * which is the fabricated-identity failure this whole change exists to remove.
21
+ */
22
+ const status = input.conversationId === undefined
23
+ ? "started"
24
+ : (await coordinator.claimOrEnqueue({ ...input, conversationId: input.conversationId })).status;
25
+ if (input.eventLog !== undefined) {
26
+ /**
27
+ * Best-effort, and deliberately so.
28
+ *
29
+ * The run is already admitted by the time this runs; failing the request now would report an error for work
30
+ * that is going to happen anyway, and the caller would retry an admission that cannot be repeated. A missing
31
+ * `run.queued` costs a client one status label. Losing the run costs the answer.
32
+ */
33
+ try {
34
+ await input.eventLog.append({
35
+ tenantId: input.tenantId,
36
+ event: {
37
+ type: "run.queued",
38
+ runId: input.runId,
39
+ sequence: 1,
40
+ occurredAt: (input.now ?? (() => new Date().toISOString()))(),
41
+ },
42
+ });
43
+ }
44
+ catch {
45
+ // A duplicate sequence means this run was already admitted and logged — a retried request, which is not
46
+ // an error. Any other failure is a lost status label, which is not worth failing admission over.
47
+ }
48
+ }
49
+ return status;
50
+ };
51
+ /**
52
+ * On a run reaching a terminal state, atomically release the conversation and promote the next queued
53
+ * run, then hand it to the dispatcher. Returns the promoted run, or null when the backlog is empty.
54
+ * Because release+promote is atomic, two runs can never both become active. This is the per-thread
55
+ * mailbox drain that guarantees FIFO execution.
56
+ */
57
+ export const advanceConversation = async (coordinator, dispatcher, input) => {
58
+ const next = await coordinator.releaseAndPromote(input);
59
+ if (next === null)
60
+ return null;
61
+ await dispatcher.enqueueRun({ tenantId: input.tenantId, runId: next });
62
+ return next;
63
+ };
64
+ /**
65
+ * The agent version a resumed thread must run. `pinned` keeps the recorded version even when a newer
66
+ * one exists (deterministic continuation); `latest` tracks the newest. Throws if a pinned binding is
67
+ * missing its version — a data error, not a silent fallback.
68
+ */
69
+ export const resolveAgentVersionForResume = (binding, latestVersion) => {
70
+ if (binding.agentVersionPolicy === "latest")
71
+ return latestVersion;
72
+ if (binding.agentVersion === undefined)
73
+ throw new AgentPlatformError({
74
+ code: "invalid_input",
75
+ message: `Pinned conversation binding for ${binding.conversationId} has no agentVersion`,
76
+ retryable: false,
77
+ });
78
+ return binding.agentVersion;
79
+ };
80
+ /**
81
+ * Commit a turn's writes together. Every step runs inside the unit of work; if any step throws, the
82
+ * already-applied steps are compensated in reverse — so session state and messages commit
83
+ * all-or-nothing. The Postgres `UnitOfWork` makes this a real transaction; the memory one compensates
84
+ * explicitly. Pass a `UnitOfWork` exposing `runTx` (the memory/Postgres adapters do) to get rollback.
85
+ */
86
+ export const commitTurn = async (uow, steps) => {
87
+ await uow.runTx(async (tx) => {
88
+ for (const step of steps) {
89
+ const result = await step.do();
90
+ if (step.undo)
91
+ tx.onRollback(() => step.undo(result));
92
+ }
93
+ });
94
+ };
95
+ //# sourceMappingURL=serialization.js.map
@@ -0,0 +1,54 @@
1
+ /**
2
+ * Transport-neutral streaming — `docs/04-durable-runtime-and-hitl.md` → Transport events.
3
+ *
4
+ * The reconnect layer that sits under every transport (GraphQL subscription, SSE, …): a client
5
+ * reconnects, reads everything after its cursor from the durable `RunEventLog`, then follows the
6
+ * live feed — with catch-up and live de-duplicated by `sequence` so no part is missed or repeated.
7
+ * Nothing here knows about a wire format, which is what keeps the layer transport-agnostic.
8
+ */
9
+ import { type RealtimePublisher, type RunEvent, type RunEventLog, type RunEventType, type RunStreamState } from "../core/events.js";
10
+ import type { RunId, TenantId } from "../core/ids.js";
11
+ export declare const isTerminalEventType: (type: RunEventType) => boolean;
12
+ /** Live fan-in half of reconnect. `subscribe` must begin buffering at call time so the catch-up
13
+ * read cannot race ahead of live events. Adapters: the in-memory bus below, Supabase Realtime, Redis. */
14
+ export interface LiveEventSource {
15
+ subscribe(channel: string): AsyncIterable<RunEvent>;
16
+ }
17
+ /**
18
+ * The persisted snapshot a transport sends on connect: the projected state plus the cursor to
19
+ * resume streaming from. Built purely from the durable log, so it never disagrees with live deltas.
20
+ */
21
+ export declare const reconnectSnapshot: (input: {
22
+ readonly tenantId: TenantId;
23
+ readonly runId: RunId;
24
+ readonly log: RunEventLog;
25
+ }) => Promise<{
26
+ readonly state: RunStreamState;
27
+ readonly after: number;
28
+ }>;
29
+ /**
30
+ * Ordered, gap-free, duplicate-free event stream from `after`. Subscribes first (so no live event
31
+ * is lost during catch-up), replays the durable log, then follows live — skipping anything whose
32
+ * sequence was already delivered. Ends on the run's terminal event or when `signal` aborts.
33
+ */
34
+ export declare function openRunEventStream(input: {
35
+ readonly tenantId: TenantId;
36
+ readonly runId: RunId;
37
+ readonly channel: string;
38
+ readonly after: number;
39
+ readonly log: RunEventLog;
40
+ readonly live: LiveEventSource;
41
+ readonly signal?: {
42
+ readonly aborted: boolean;
43
+ };
44
+ }): AsyncIterable<RunEvent>;
45
+ /**
46
+ * In-memory event bus: a `RealtimePublisher` paired with a `LiveEventSource`. Each subscriber gets
47
+ * its own queue that starts filling the moment it subscribes, so `openRunEventStream` never races.
48
+ * Serves tests, single-process deployments and the SSE embedded profile (#37).
49
+ */
50
+ export declare const createMemoryEventBus: () => {
51
+ publisher: RealtimePublisher;
52
+ live: LiveEventSource;
53
+ };
54
+ //# sourceMappingURL=streaming.d.ts.map