@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,103 @@
1
+ /**
2
+ * `@retinue/agentkit`
3
+ *
4
+ * The root is the **semver boundary** (REQ-040): what is exported here is API, and what is not exported here
5
+ * cannot be broken. That is why there are five values on it rather than three hundred and ninety-two.
6
+ *
7
+ * ## The rule
8
+ *
9
+ * **The root exports what a host uses on its first day; everything else is behind a documented subpath.**
10
+ *
11
+ * The root used to be every `create*` in the package, and nothing in the shape distinguished the four calls a
12
+ * host makes from the three hundred an adapter author makes once. A surface that large is not a promise anyone
13
+ * can keep: every name on it is something we cannot remove without a major version, including the ones nobody
14
+ * outside this repository has ever called.
15
+ *
16
+ * ## Types stay, and cost nothing
17
+ *
18
+ * Every type in the package is still exported from here, by `export type *` — which emits no import at all, so
19
+ * the root's runtime weight is unchanged (`ai` and `zod`, asserted by `root-import-weight.test.ts`). Types could
20
+ * not be subpathed without making the package unusable: a consumer holding an `ExecutionContext` should not have
21
+ * to know which layer defined it, and a type cannot be broken by being imported.
22
+ *
23
+ * So the split is: **types by subject, values by consumer**.
24
+ *
25
+ * ## Where everything went
26
+ *
27
+ * | Subpath | Who calls it |
28
+ * |---|---|
29
+ * | `./runtime` | A host composing its own engine rather than taking `createRuntime`'s defaults |
30
+ * | `./tools` | Anyone writing or dispatching a tool, plus the first-party library |
31
+ * | `./persistence` | A host wiring storage, and anything using the in-memory adapters |
32
+ * | `./context` | Prompt assembly, skills, per-principal memory, citations |
33
+ * | `./knowledge` | Retrieval, documents, files, artifacts, export |
34
+ * | `./hitl` | Approvals, questions, authorization |
35
+ * | `./usage` | Spend, quotas, rollups |
36
+ * | `./mcp` | Importing another server's tools |
37
+ * | `./observability` | Telemetry, retention, the security review, the harnesses |
38
+ * | `./server` | The reference GraphQL host, the SSE route, the worker |
39
+ * | `./providers` | The model providers |
40
+ * | `./adapters/{postgres,redis,bullmq,otel}` | One driver each |
41
+ */
42
+ export type * from "./core/index.js";
43
+ export type * from "./capabilities/index.js";
44
+ export type * from "./capabilities/runtime.js";
45
+ export type * from "./models/index.js";
46
+ export type * from "./agents/index.js";
47
+ export type * from "./runtime/index.js";
48
+ export type * from "./tools/index.js";
49
+ export type * from "./tools/library/index.js";
50
+ export type * from "./toolkit/index.js";
51
+ export type * from "./mcp/index.js";
52
+ export type * from "./authorization/index.js";
53
+ export type * from "./usage/index.js";
54
+ export type * from "./idempotency/index.js";
55
+ export type * from "./skills/index.js";
56
+ export type * from "./context/index.js";
57
+ export type * from "./hitl/index.js";
58
+ export type * from "./persistence/index.js";
59
+ export type * from "./adapters/memory/index.js";
60
+ export type * from "./worker/main.js";
61
+ export type * from "./worker/extraction.js";
62
+ export type * from "./worker/export.js";
63
+ export type * from "./principal-memory/index.js";
64
+ export type * from "./files/index.js";
65
+ export type * from "./files/context.js";
66
+ export type * from "./files/read-tool.js";
67
+ export type * from "./files/turn-parts.js";
68
+ export type * from "./documents/index.js";
69
+ export type * from "./artifacts/index.js";
70
+ export type * from "./export/index.js";
71
+ export type * from "./export/pdf.js";
72
+ export type * from "./export/markdown.js";
73
+ export type * from "./knowledge/index.js";
74
+ export type * from "./citations/index.js";
75
+ export type * from "./evaluation/index.js";
76
+ export type * from "./telemetry/index.js";
77
+ export type * from "./security/index.js";
78
+ export type * from "./retention/index.js";
79
+ export type * from "./loadtest/index.js";
80
+ export type * from "./flows/index.js";
81
+ export type * from "./flows/interpreter.js";
82
+ export type * from "./flows/runner.js";
83
+ export type * from "./teams/index.js";
84
+ export type * from "./graphql/index.js";
85
+ /**
86
+ * The five.
87
+ *
88
+ * - `createRuntime` composes one and gates access to what was actually wired.
89
+ * - `resolveCapabilities` is how a host declares what it enables, and is cross-checked against the wiring in
90
+ * both directions — a capability declared and unwired is as much a bug as one wired and undeclared.
91
+ * - `defineAgent` declares the agent. `defineTool` is deliberately *not* here: an agent is the thing you
92
+ * declare, a tool is a component of one, and everything about tools is at `./tools`.
93
+ * - `asId` builds a branded id. Every other export takes one, so a consumer that could not build one would be
94
+ * reduced to casting — which is opting out of the guarantee for everybody downstream.
95
+ * - `AgentPlatformError` and its guard are what a consumer catches. An error class reachable only by subpath
96
+ * means a `catch` block importing from somewhere the happy path never mentions.
97
+ */
98
+ export { createRuntime } from "./capabilities/runtime.js";
99
+ export { resolveCapabilities } from "./capabilities/index.js";
100
+ export { defineAgent } from "./agents/define.js";
101
+ export { asId } from "./core/ids.js";
102
+ export { AgentPlatformError, isAgentPlatformError } from "./core/errors.js";
103
+ //# sourceMappingURL=index.d.ts.map
package/dist/index.js ADDED
@@ -0,0 +1,60 @@
1
+ /**
2
+ * `@retinue/agentkit`
3
+ *
4
+ * The root is the **semver boundary** (REQ-040): what is exported here is API, and what is not exported here
5
+ * cannot be broken. That is why there are five values on it rather than three hundred and ninety-two.
6
+ *
7
+ * ## The rule
8
+ *
9
+ * **The root exports what a host uses on its first day; everything else is behind a documented subpath.**
10
+ *
11
+ * The root used to be every `create*` in the package, and nothing in the shape distinguished the four calls a
12
+ * host makes from the three hundred an adapter author makes once. A surface that large is not a promise anyone
13
+ * can keep: every name on it is something we cannot remove without a major version, including the ones nobody
14
+ * outside this repository has ever called.
15
+ *
16
+ * ## Types stay, and cost nothing
17
+ *
18
+ * Every type in the package is still exported from here, by `export type *` — which emits no import at all, so
19
+ * the root's runtime weight is unchanged (`ai` and `zod`, asserted by `root-import-weight.test.ts`). Types could
20
+ * not be subpathed without making the package unusable: a consumer holding an `ExecutionContext` should not have
21
+ * to know which layer defined it, and a type cannot be broken by being imported.
22
+ *
23
+ * So the split is: **types by subject, values by consumer**.
24
+ *
25
+ * ## Where everything went
26
+ *
27
+ * | Subpath | Who calls it |
28
+ * |---|---|
29
+ * | `./runtime` | A host composing its own engine rather than taking `createRuntime`'s defaults |
30
+ * | `./tools` | Anyone writing or dispatching a tool, plus the first-party library |
31
+ * | `./persistence` | A host wiring storage, and anything using the in-memory adapters |
32
+ * | `./context` | Prompt assembly, skills, per-principal memory, citations |
33
+ * | `./knowledge` | Retrieval, documents, files, artifacts, export |
34
+ * | `./hitl` | Approvals, questions, authorization |
35
+ * | `./usage` | Spend, quotas, rollups |
36
+ * | `./mcp` | Importing another server's tools |
37
+ * | `./observability` | Telemetry, retention, the security review, the harnesses |
38
+ * | `./server` | The reference GraphQL host, the SSE route, the worker |
39
+ * | `./providers` | The model providers |
40
+ * | `./adapters/{postgres,redis,bullmq,otel}` | One driver each |
41
+ */
42
+ /**
43
+ * The five.
44
+ *
45
+ * - `createRuntime` composes one and gates access to what was actually wired.
46
+ * - `resolveCapabilities` is how a host declares what it enables, and is cross-checked against the wiring in
47
+ * both directions — a capability declared and unwired is as much a bug as one wired and undeclared.
48
+ * - `defineAgent` declares the agent. `defineTool` is deliberately *not* here: an agent is the thing you
49
+ * declare, a tool is a component of one, and everything about tools is at `./tools`.
50
+ * - `asId` builds a branded id. Every other export takes one, so a consumer that could not build one would be
51
+ * reduced to casting — which is opting out of the guarantee for everybody downstream.
52
+ * - `AgentPlatformError` and its guard are what a consumer catches. An error class reachable only by subpath
53
+ * means a `catch` block importing from somewhere the happy path never mentions.
54
+ */
55
+ export { createRuntime } from "./capabilities/runtime.js";
56
+ export { resolveCapabilities } from "./capabilities/index.js";
57
+ export { defineAgent } from "./agents/define.js";
58
+ export { asId } from "./core/ids.js";
59
+ export { AgentPlatformError, isAgentPlatformError } from "./core/errors.js";
60
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,57 @@
1
+ /**
2
+ * Chunking extracted documents for retrieval (#135).
3
+ *
4
+ * The input is #131's `DocumentBlock[]`, which is the whole payoff of extracting to structure rather than a
5
+ * flat string: a chunker that only sees text has to guess where a section ends, and a chunker that sees blocks
6
+ * knows.
7
+ *
8
+ * Three decisions, each with a failure it avoids:
9
+ *
10
+ * - **Chunks respect block boundaries.** A chunk never starts mid-sentence or mid-table, because a retrieved
11
+ * fragment is quoted to a user and a half-sentence quoted as a citation is worse than no citation.
12
+ * - **A table is one chunk, whole.** Splitting a table separates a number from its column header, and a number
13
+ * without its header is the specific failure this platform's extraction design exists to avoid — see #131.
14
+ * A table too large for one chunk is split *by rows with its header repeated*, so every piece still says what
15
+ * its columns mean.
16
+ * - **The nearest preceding heading is prepended** to every chunk. "Revenue rose 9%" is unretrievable on its
17
+ * own and retrievable as "By region / EMEA / Revenue rose 9%" — and it is what makes a hit explicable.
18
+ *
19
+ * Overlap is by *block*, not by character: overlapping mid-sentence produces two chunks that both contain half
20
+ * a thought and neither contains the whole one.
21
+ */
22
+ import type { DocumentBlock } from "../documents/index.js";
23
+ export type ChunkingLimits = {
24
+ /** Target size in tokens. Chunks land near this, never far above it. */
25
+ readonly targetTokens: number;
26
+ /**
27
+ * Hard ceiling. A single block larger than this is split; nothing else is.
28
+ *
29
+ * Separate from the target because a block is indivisible in the good case, so "aim for 400" and "never
30
+ * exceed 800" are different statements and collapsing them would either split freely or overflow freely.
31
+ */
32
+ readonly maxTokens: number;
33
+ /** Blocks repeated at the start of the next chunk, so a thought spanning a boundary is retrievable. */
34
+ readonly overlapBlocks: number;
35
+ };
36
+ export declare const DEFAULT_CHUNKING_LIMITS: ChunkingLimits;
37
+ /**
38
+ * A token estimate — one definition, in `core/tokens.ts`.
39
+ *
40
+ * Shared with the context assembler on purpose: a chunk sized against one estimate and budgeted against a
41
+ * different one is a chunk that does not fit the budget it was measured for.
42
+ */
43
+ export type Chunk = {
44
+ readonly index: number;
45
+ readonly content: string;
46
+ readonly tokenCount: number;
47
+ /** The heading path this chunk sits under, for a citation that resolves. */
48
+ readonly locator?: string;
49
+ };
50
+ /**
51
+ * Chunk a document.
52
+ *
53
+ * Headings are not chunks of their own — a heading alone retrieves nothing useful. They become the locator and
54
+ * the prefix of the chunks beneath them, which is what makes an isolated sentence findable.
55
+ */
56
+ export declare const chunkDocument: (blocks: readonly DocumentBlock[], limits?: ChunkingLimits) => readonly Chunk[];
57
+ //# sourceMappingURL=chunking.d.ts.map
@@ -0,0 +1,158 @@
1
+ /**
2
+ * Chunking extracted documents for retrieval (#135).
3
+ *
4
+ * The input is #131's `DocumentBlock[]`, which is the whole payoff of extracting to structure rather than a
5
+ * flat string: a chunker that only sees text has to guess where a section ends, and a chunker that sees blocks
6
+ * knows.
7
+ *
8
+ * Three decisions, each with a failure it avoids:
9
+ *
10
+ * - **Chunks respect block boundaries.** A chunk never starts mid-sentence or mid-table, because a retrieved
11
+ * fragment is quoted to a user and a half-sentence quoted as a citation is worse than no citation.
12
+ * - **A table is one chunk, whole.** Splitting a table separates a number from its column header, and a number
13
+ * without its header is the specific failure this platform's extraction design exists to avoid — see #131.
14
+ * A table too large for one chunk is split *by rows with its header repeated*, so every piece still says what
15
+ * its columns mean.
16
+ * - **The nearest preceding heading is prepended** to every chunk. "Revenue rose 9%" is unretrievable on its
17
+ * own and retrievable as "By region / EMEA / Revenue rose 9%" — and it is what makes a hit explicable.
18
+ *
19
+ * Overlap is by *block*, not by character: overlapping mid-sentence produces two chunks that both contain half
20
+ * a thought and neither contains the whole one.
21
+ */
22
+ import { estimateTokens } from "../core/tokens.js";
23
+ import { renderBlock } from "../documents/render.js";
24
+ export const DEFAULT_CHUNKING_LIMITS = {
25
+ // ~400 tokens is roughly two paragraphs: large enough to carry an argument, small enough that a hit is
26
+ // mostly relevant rather than mostly padding.
27
+ targetTokens: 400,
28
+ maxTokens: 800,
29
+ overlapBlocks: 1,
30
+ };
31
+ /** The heading trail at a point in the document, e.g. `Quarterly Review > By region`. */
32
+ const headingPath = (trail) => trail.map((h) => h.text).join(" > ");
33
+ /**
34
+ * Split one oversized block.
35
+ *
36
+ * A table splits by rows with its header repeated; anything else splits by sentence. Sentences rather than
37
+ * characters because a chunk boundary mid-word is a retrieved fragment that reads as corrupt.
38
+ */
39
+ const splitBlock = (block, maxTokens) => {
40
+ if (block.kind === "table") {
41
+ const header = block.hasHeader ? block.rows[0] : undefined;
42
+ const body = block.hasHeader ? block.rows.slice(1) : block.rows;
43
+ const pieces = [];
44
+ let current = [];
45
+ const flush = () => {
46
+ if (current.length === 0)
47
+ return;
48
+ pieces.push(renderBlock({
49
+ kind: "table",
50
+ rows: header === undefined ? current : [header, ...current],
51
+ hasHeader: header !== undefined,
52
+ }));
53
+ current = [];
54
+ };
55
+ for (const row of body) {
56
+ current.push(row);
57
+ // The header counts against every piece's budget, which is the price of every piece being readable.
58
+ const rendered = renderBlock({
59
+ kind: "table",
60
+ rows: header === undefined ? current : [header, ...current],
61
+ hasHeader: header !== undefined,
62
+ });
63
+ if (estimateTokens(rendered) >= maxTokens)
64
+ flush();
65
+ }
66
+ flush();
67
+ return pieces.length === 0 ? [renderBlock(block)] : pieces;
68
+ }
69
+ const text = renderBlock(block);
70
+ // Split after sentence-ending punctuation followed by whitespace. Keeps the punctuation with its sentence.
71
+ const sentences = text.split(/(?<=[.!?])\s+/);
72
+ const pieces = [];
73
+ let current = "";
74
+ for (const sentence of sentences) {
75
+ const candidate = current === "" ? sentence : `${current} ${sentence}`;
76
+ if (estimateTokens(candidate) > maxTokens && current !== "") {
77
+ pieces.push(current);
78
+ current = sentence;
79
+ }
80
+ else
81
+ current = candidate;
82
+ }
83
+ if (current !== "")
84
+ pieces.push(current);
85
+ return pieces.length === 0 ? [text] : pieces;
86
+ };
87
+ /**
88
+ * Chunk a document.
89
+ *
90
+ * Headings are not chunks of their own — a heading alone retrieves nothing useful. They become the locator and
91
+ * the prefix of the chunks beneath them, which is what makes an isolated sentence findable.
92
+ */
93
+ export const chunkDocument = (blocks, limits = DEFAULT_CHUNKING_LIMITS) => {
94
+ const chunks = [];
95
+ const trail = [];
96
+ let pending = [];
97
+ let pendingTokens = 0;
98
+ const emit = () => {
99
+ if (pending.length === 0)
100
+ return;
101
+ const path = headingPath(trail);
102
+ // The heading path is prepended, not merely recorded: "Revenue rose 9%" is unretrievable alone and
103
+ // retrievable as "By region / EMEA / Revenue rose 9%".
104
+ const body = pending.map((p) => p.rendered).join("\n\n");
105
+ const content = path === "" ? body : `${path}\n\n${body}`;
106
+ chunks.push({
107
+ index: chunks.length,
108
+ content,
109
+ tokenCount: estimateTokens(content),
110
+ ...(path === "" ? {} : { locator: path }),
111
+ });
112
+ // Overlap by block, so a thought spanning the boundary appears whole in one of the two chunks. Overlapping
113
+ // mid-sentence would give two chunks that each contain half a thought and neither the whole one.
114
+ const overlap = limits.overlapBlocks > 0 ? pending.slice(-limits.overlapBlocks) : [];
115
+ pending = [...overlap];
116
+ pendingTokens = overlap.reduce((n, p) => n + estimateTokens(p.rendered), 0);
117
+ };
118
+ for (const block of blocks) {
119
+ if (block.kind === "heading") {
120
+ // A heading ends the section above it: a chunk spanning two sections would carry the wrong locator for
121
+ // half its content.
122
+ emit();
123
+ pending = [];
124
+ pendingTokens = 0;
125
+ while (trail.length > 0 && (trail[trail.length - 1]?.level ?? 0) >= block.level)
126
+ trail.pop();
127
+ trail.push({ level: block.level, text: block.text });
128
+ continue;
129
+ }
130
+ const rendered = renderBlock(block);
131
+ const tokens = estimateTokens(rendered);
132
+ if (tokens > limits.maxTokens) {
133
+ // Oversized: flush what is pending, then split this block into pieces that each stand alone.
134
+ emit();
135
+ pending = [];
136
+ pendingTokens = 0;
137
+ const path = headingPath(trail);
138
+ for (const piece of splitBlock(block, limits.maxTokens)) {
139
+ const content = path === "" ? piece : `${path}\n\n${piece}`;
140
+ chunks.push({
141
+ index: chunks.length,
142
+ content,
143
+ tokenCount: estimateTokens(content),
144
+ ...(path === "" ? {} : { locator: path }),
145
+ });
146
+ }
147
+ continue;
148
+ }
149
+ if (pendingTokens + tokens > limits.targetTokens && pending.length > 0)
150
+ emit();
151
+ pending.push({ rendered, block });
152
+ pendingTokens += tokens;
153
+ }
154
+ emit();
155
+ // Re-index, because `emit` numbers as it goes and the overlap means the count is not the block count.
156
+ return chunks.map((c, i) => ({ ...c, index: i }));
157
+ };
158
+ //# sourceMappingURL=chunking.js.map
@@ -0,0 +1,119 @@
1
+ /**
2
+ * The embedding pipeline (#135).
3
+ *
4
+ * Chunk, embed in batches, write. What makes it worth a module rather than a loop is the three properties the
5
+ * ACs are actually about:
6
+ *
7
+ * - **Every chunk records the model that embedded it** (AC-1). Not a global "current model" setting: a setting
8
+ * cannot tell you which rows are stale, which makes incremental re-indexing impossible.
9
+ * - **Re-indexing is derived from what is stored** (AC-5). `listStaleSources` asks the database which sources
10
+ * were embedded by something other than the current model, so an interrupted re-index resumes by asking
11
+ * again rather than by remembering where it was. There is no cursor to lose.
12
+ * - **Freshness is a stated target, measured** (AC-4). `FRESHNESS_TARGET_MS` is the number, `indexSource`
13
+ * reports how long it took, and the test asserts the report against the target rather than against a hope.
14
+ */
15
+ import type { TenantId } from "../core/ids.js";
16
+ import type { DocumentBlock } from "../documents/index.js";
17
+ import type { EmbeddingModelRef, KnowledgeSourceType, KnowledgeStore } from "../persistence/index.js";
18
+ import { type ChunkingLimits } from "./chunking.js";
19
+ /**
20
+ * How long newly added material may take to become findable — AC-4.
21
+ *
22
+ * Sixty seconds, and the number is a *commitment* rather than an observation: indexing runs on the worker tier,
23
+ * so the delay is queue latency plus embedding time, and a target far below queue latency would be a promise
24
+ * the architecture cannot keep. A user who attaches a document and asks about it immediately is the case this
25
+ * bounds, and a minute is what "shortly" honestly means for a document that has to be read, chunked and
26
+ * embedded.
27
+ */
28
+ export declare const FRESHNESS_TARGET_MS = 60000;
29
+ /** Chunks per embedding call. Providers cap batch size; 64 is comfortably inside every one of them. */
30
+ export declare const DEFAULT_EMBEDDING_BATCH = 64;
31
+ /**
32
+ * Turns text into vectors.
33
+ *
34
+ * A port, because the provider differs and because a test needs a deterministic one. `model` is on the provider
35
+ * rather than passed per call: a provider that could be asked for a different model per call would let two
36
+ * chunks of one document be embedded differently, and nothing downstream could tell.
37
+ */
38
+ export interface EmbeddingProvider {
39
+ readonly model: EmbeddingModelRef;
40
+ /** One vector per input, in order. A provider returning a different count is a bug worth catching loudly. */
41
+ embed(texts: readonly string[]): Promise<readonly (readonly number[])[]>;
42
+ }
43
+ export type IndexSourceInput = {
44
+ readonly sourceType: KnowledgeSourceType;
45
+ readonly sourceId: string;
46
+ readonly blocks: readonly DocumentBlock[];
47
+ /**
48
+ * Who may retrieve this source's chunks.
49
+ *
50
+ * Required. An optional subject would default to something, and the something would either be too narrow
51
+ * (nothing retrievable) or too wide (everything retrievable by everyone) — and the second failure is silent.
52
+ */
53
+ readonly authSubject: string;
54
+ };
55
+ export type IndexResult = {
56
+ readonly written: number;
57
+ readonly removed: number;
58
+ readonly batches: number;
59
+ /** Wall-clock, so the freshness target can be measured rather than assumed. */
60
+ readonly elapsedMs: number;
61
+ readonly model: EmbeddingModelRef;
62
+ };
63
+ export type EmbeddingPipelineDeps = {
64
+ readonly knowledge: KnowledgeStore;
65
+ readonly embeddings: EmbeddingProvider;
66
+ readonly chunking?: ChunkingLimits;
67
+ readonly batchSize?: number;
68
+ readonly clock?: () => string;
69
+ /** Injectable so a test measures elapsed time without waiting for it. */
70
+ readonly now?: () => number;
71
+ readonly log?: (message: string, detail?: Readonly<Record<string, unknown>>) => void;
72
+ };
73
+ /** Deterministic chunk id, so re-indexing the same source overwrites its own rows rather than duplicating. */
74
+ export declare const chunkId: (sourceType: string, sourceId: string, index: number) => string;
75
+ export declare const createEmbeddingPipeline: (deps: EmbeddingPipelineDeps) => {
76
+ model: EmbeddingModelRef;
77
+ freshnessTargetMs: number;
78
+ /**
79
+ * Index one source, replacing whatever was there.
80
+ *
81
+ * Replace rather than append: a changed document's old chunks must stop being searchable, because a stale
82
+ * chunk is a citation pointing at text that is no longer in the document.
83
+ */
84
+ indexSource(context: {
85
+ readonly tenantId: TenantId;
86
+ }, input: IndexSourceInput): Promise<IndexResult>;
87
+ /**
88
+ * One page of a re-index — AC-5.
89
+ *
90
+ * Deliberately not a loop over everything. A caller runs this repeatedly and stops when `remaining` is
91
+ * zero, which means an interruption at any point loses at most one page's work and no bookkeeping: the
92
+ * next call re-derives the work list from what is stored. There is no cursor to persist and therefore no
93
+ * cursor to lose.
94
+ *
95
+ * `reload` fetches a source's current blocks. It is the caller's, because where a source's content lives
96
+ * differs by type — an attachment's is an extracted document, an artifact's is its content — and this
97
+ * module has no business knowing all of them.
98
+ */
99
+ reindexBatch(context: {
100
+ readonly tenantId: TenantId;
101
+ }, input: {
102
+ readonly limit: number;
103
+ readonly reload: (source: {
104
+ readonly sourceType: KnowledgeSourceType;
105
+ readonly sourceId: string;
106
+ }) => Promise<{
107
+ readonly blocks: readonly DocumentBlock[];
108
+ readonly authSubject: string;
109
+ } | null>;
110
+ }): Promise<{
111
+ readonly reindexed: number;
112
+ readonly skipped: number;
113
+ readonly remaining: number;
114
+ }>;
115
+ };
116
+ export type EmbeddingPipeline = ReturnType<typeof createEmbeddingPipeline>;
117
+ export * from "./chunking.js";
118
+ export * from "./retrieval.js";
119
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1,166 @@
1
+ /**
2
+ * The embedding pipeline (#135).
3
+ *
4
+ * Chunk, embed in batches, write. What makes it worth a module rather than a loop is the three properties the
5
+ * ACs are actually about:
6
+ *
7
+ * - **Every chunk records the model that embedded it** (AC-1). Not a global "current model" setting: a setting
8
+ * cannot tell you which rows are stale, which makes incremental re-indexing impossible.
9
+ * - **Re-indexing is derived from what is stored** (AC-5). `listStaleSources` asks the database which sources
10
+ * were embedded by something other than the current model, so an interrupted re-index resumes by asking
11
+ * again rather than by remembering where it was. There is no cursor to lose.
12
+ * - **Freshness is a stated target, measured** (AC-4). `FRESHNESS_TARGET_MS` is the number, `indexSource`
13
+ * reports how long it took, and the test asserts the report against the target rather than against a hope.
14
+ */
15
+ import { AgentPlatformError } from "../core/errors.js";
16
+ import { DEFAULT_CHUNKING_LIMITS, chunkDocument } from "./chunking.js";
17
+ /**
18
+ * How long newly added material may take to become findable — AC-4.
19
+ *
20
+ * Sixty seconds, and the number is a *commitment* rather than an observation: indexing runs on the worker tier,
21
+ * so the delay is queue latency plus embedding time, and a target far below queue latency would be a promise
22
+ * the architecture cannot keep. A user who attaches a document and asks about it immediately is the case this
23
+ * bounds, and a minute is what "shortly" honestly means for a document that has to be read, chunked and
24
+ * embedded.
25
+ */
26
+ export const FRESHNESS_TARGET_MS = 60_000;
27
+ /** Chunks per embedding call. Providers cap batch size; 64 is comfortably inside every one of them. */
28
+ export const DEFAULT_EMBEDDING_BATCH = 64;
29
+ /** Deterministic chunk id, so re-indexing the same source overwrites its own rows rather than duplicating. */
30
+ export const chunkId = (sourceType, sourceId, index) => `${sourceType}:${sourceId}:${index}`;
31
+ export const createEmbeddingPipeline = (deps) => {
32
+ const limits = deps.chunking ?? DEFAULT_CHUNKING_LIMITS;
33
+ const batchSize = Math.max(1, deps.batchSize ?? DEFAULT_EMBEDDING_BATCH);
34
+ const clock = deps.clock ?? (() => new Date().toISOString());
35
+ const now = deps.now ?? (() => Date.now());
36
+ const log = deps.log ?? (() => { });
37
+ return {
38
+ model: deps.embeddings.model,
39
+ freshnessTargetMs: FRESHNESS_TARGET_MS,
40
+ /**
41
+ * Index one source, replacing whatever was there.
42
+ *
43
+ * Replace rather than append: a changed document's old chunks must stop being searchable, because a stale
44
+ * chunk is a citation pointing at text that is no longer in the document.
45
+ */
46
+ async indexSource(context, input) {
47
+ const started = now();
48
+ const chunks = chunkDocument(input.blocks, limits);
49
+ if (chunks.length === 0) {
50
+ // An empty document still removes its old chunks: extracting a document down to nothing is a reason for
51
+ // its previous content to stop being findable, not a reason to leave it.
52
+ const cleared = await deps.knowledge.deleteSource({
53
+ tenantId: context.tenantId,
54
+ sourceType: input.sourceType,
55
+ sourceId: input.sourceId,
56
+ });
57
+ return {
58
+ written: 0,
59
+ removed: cleared.removed,
60
+ batches: 0,
61
+ elapsedMs: now() - started,
62
+ model: deps.embeddings.model,
63
+ };
64
+ }
65
+ const embedded = [];
66
+ let batches = 0;
67
+ for (let offset = 0; offset < chunks.length; offset += batchSize) {
68
+ const batch = chunks.slice(offset, offset + batchSize);
69
+ const vectors = await deps.embeddings.embed(batch.map((c) => c.content));
70
+ batches += 1;
71
+ // A provider returning a different count has silently misaligned every vector with the wrong chunk,
72
+ // which is unrecoverable and undetectable later. Caught here, loudly.
73
+ if (vectors.length !== batch.length)
74
+ throw new AgentPlatformError({
75
+ code: "provider_unavailable",
76
+ message: `the embedding provider returned ${vectors.length} vectors for ${batch.length} inputs`,
77
+ retryable: true,
78
+ });
79
+ batch.forEach((chunk, i) => {
80
+ embedded.push({
81
+ id: chunkId(input.sourceType, input.sourceId, chunk.index),
82
+ sourceType: input.sourceType,
83
+ sourceId: input.sourceId,
84
+ chunkIndex: chunk.index,
85
+ content: chunk.content,
86
+ tokenCount: chunk.tokenCount,
87
+ authSubject: input.authSubject,
88
+ embeddingModel: deps.embeddings.model,
89
+ ...(chunk.locator === undefined ? {} : { locator: chunk.locator }),
90
+ createdAt: clock(),
91
+ embedding: vectors[i] ?? [],
92
+ });
93
+ });
94
+ }
95
+ const written = await deps.knowledge.replaceSource({
96
+ tenantId: context.tenantId,
97
+ sourceType: input.sourceType,
98
+ sourceId: input.sourceId,
99
+ chunks: embedded,
100
+ });
101
+ const elapsedMs = now() - started;
102
+ if (elapsedMs > FRESHNESS_TARGET_MS)
103
+ // Reported rather than thrown: the material *is* indexed, and the useful action is to know the target
104
+ // was missed rather than to fail a job that succeeded.
105
+ log("indexing exceeded the freshness target", {
106
+ sourceId: input.sourceId,
107
+ elapsedMs,
108
+ targetMs: FRESHNESS_TARGET_MS,
109
+ });
110
+ return { ...written, batches, elapsedMs, model: deps.embeddings.model };
111
+ },
112
+ /**
113
+ * One page of a re-index — AC-5.
114
+ *
115
+ * Deliberately not a loop over everything. A caller runs this repeatedly and stops when `remaining` is
116
+ * zero, which means an interruption at any point loses at most one page's work and no bookkeeping: the
117
+ * next call re-derives the work list from what is stored. There is no cursor to persist and therefore no
118
+ * cursor to lose.
119
+ *
120
+ * `reload` fetches a source's current blocks. It is the caller's, because where a source's content lives
121
+ * differs by type — an attachment's is an extracted document, an artifact's is its content — and this
122
+ * module has no business knowing all of them.
123
+ */
124
+ async reindexBatch(context, input) {
125
+ const stale = await deps.knowledge.listStaleSources({
126
+ tenantId: context.tenantId,
127
+ current: deps.embeddings.model,
128
+ limit: input.limit,
129
+ });
130
+ let reindexed = 0;
131
+ let skipped = 0;
132
+ for (const source of stale.items) {
133
+ const reloaded = await input.reload(source);
134
+ if (reloaded === null) {
135
+ // The source is gone. Its chunks go with it rather than staying stale forever, which would make the
136
+ // work list never drain and the re-index never finish.
137
+ await deps.knowledge.deleteSource({
138
+ tenantId: context.tenantId,
139
+ sourceType: source.sourceType,
140
+ sourceId: source.sourceId,
141
+ });
142
+ skipped += 1;
143
+ continue;
144
+ }
145
+ await this.indexSource(context, {
146
+ sourceType: source.sourceType,
147
+ sourceId: source.sourceId,
148
+ blocks: reloaded.blocks,
149
+ authSubject: reloaded.authSubject,
150
+ });
151
+ reindexed += 1;
152
+ }
153
+ // Asked again rather than computed, because sources may have been added or removed while this page ran —
154
+ // and a stale "remaining" is how a loop stops early or never stops.
155
+ const after = await deps.knowledge.listStaleSources({
156
+ tenantId: context.tenantId,
157
+ current: deps.embeddings.model,
158
+ limit: 1,
159
+ });
160
+ return { reindexed, skipped, remaining: after.items.length };
161
+ },
162
+ };
163
+ };
164
+ export * from "./chunking.js";
165
+ export * from "./retrieval.js";
166
+ //# sourceMappingURL=index.js.map