@capybara-hq/kernel 0.1.0-rc.105 → 0.1.0-rc.107

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 (359) hide show
  1. package/dist/admin/admin.schemas.d.ts +3 -0
  2. package/dist/agents/agents.schemas.d.ts +9 -9
  3. package/dist/{schedules/schedules.controller.d.ts → automations/automations.controller.d.ts} +37 -32
  4. package/dist/{schedules/schedules.controller.js → automations/automations.controller.js} +68 -57
  5. package/dist/automations/automations.module.d.ts +16 -0
  6. package/dist/{schedules/schedules.module.js → automations/automations.module.js} +18 -15
  7. package/dist/{schedules/schedules.schemas.d.ts → automations/automations.schemas.d.ts} +151 -50
  8. package/dist/automations/automations.schemas.js +253 -0
  9. package/dist/{schedules/scheduled-tasks.service.d.ts → automations/automations.service.d.ts} +99 -52
  10. package/dist/{schedules/scheduled-tasks.service.js → automations/automations.service.js} +303 -134
  11. package/dist/{schedules → automations}/calendar.d.ts +8 -8
  12. package/dist/{schedules → automations}/calendar.js +2 -2
  13. package/dist/automations/effective-settings.d.ts +28 -0
  14. package/dist/automations/effective-settings.js +25 -0
  15. package/dist/automations/errors.d.ts +19 -0
  16. package/dist/automations/errors.js +19 -0
  17. package/dist/automations/events/coalesce.d.ts +28 -0
  18. package/dist/automations/events/coalesce.js +131 -0
  19. package/dist/automations/events/deadline.d.ts +10 -0
  20. package/dist/automations/events/deadline.js +24 -0
  21. package/dist/automations/events/dispatcher.d.ts +74 -0
  22. package/dist/automations/events/dispatcher.js +353 -0
  23. package/dist/automations/events/events.module.d.ts +7 -0
  24. package/dist/automations/events/events.module.js +26 -0
  25. package/dist/automations/events/guards.d.ts +32 -0
  26. package/dist/automations/events/guards.js +87 -0
  27. package/dist/automations/events/sweep.job.d.ts +49 -0
  28. package/dist/automations/events/sweep.job.js +202 -0
  29. package/dist/automations/events/token.d.ts +5 -0
  30. package/dist/automations/events/token.js +5 -0
  31. package/dist/automations/events/trigger-events.service.d.ts +47 -0
  32. package/dist/automations/events/trigger-events.service.js +254 -0
  33. package/dist/{schedules → automations}/fire.d.ts +57 -17
  34. package/dist/{schedules → automations}/fire.js +311 -79
  35. package/dist/{schedules → automations}/grant-rules.d.ts +1 -1
  36. package/dist/{schedules → automations}/grant-rules.js +5 -5
  37. package/dist/automations/job-ids.d.ts +113 -0
  38. package/dist/automations/job-ids.js +117 -0
  39. package/dist/{schedules → automations}/pause.d.ts +3 -3
  40. package/dist/{schedules → automations}/pause.js +3 -3
  41. package/dist/{schedules → automations}/run-tracker.d.ts +21 -10
  42. package/dist/{schedules → automations}/run-tracker.js +68 -56
  43. package/dist/{schedules → automations}/scan.job.d.ts +12 -8
  44. package/dist/{schedules → automations}/scan.job.js +39 -23
  45. package/dist/{schedules → automations}/schedule-math.d.ts +19 -12
  46. package/dist/{schedules → automations}/schedule-math.js +17 -7
  47. package/dist/{schedules → automations}/store.d.ts +57 -27
  48. package/dist/{schedules → automations}/store.js +102 -52
  49. package/dist/automations/store.module.d.ts +6 -0
  50. package/dist/{schedules → automations}/store.module.js +9 -9
  51. package/dist/automations/types.d.ts +178 -0
  52. package/dist/{schedules → automations}/unattended.d.ts +22 -11
  53. package/dist/{schedules → automations}/unattended.js +53 -30
  54. package/dist/catalog/marketplaces.service.d.ts +1 -1
  55. package/dist/channels/channels.module.js +7 -6
  56. package/dist/channels/file-delivery.d.ts +26 -11
  57. package/dist/channels/file-delivery.js +32 -11
  58. package/dist/channels/outbound.d.ts +8 -8
  59. package/dist/channels/outbound.js +32 -30
  60. package/dist/channels/threads.d.ts +1 -1
  61. package/dist/channels/threads.js +1 -1
  62. package/dist/config/schema.d.ts +8 -1
  63. package/dist/config/schema.js +56 -6
  64. package/dist/conversations/approval-profile.d.ts +2 -2
  65. package/dist/conversations/approval-profile.js +3 -3
  66. package/dist/conversations/artifacts.d.ts +20 -17
  67. package/dist/conversations/artifacts.js +30 -37
  68. package/dist/conversations/attachments.controller.d.ts +6 -19
  69. package/dist/conversations/attachments.controller.js +8 -59
  70. package/dist/conversations/attachments.service.d.ts +30 -74
  71. package/dist/conversations/attachments.service.js +51 -193
  72. package/dist/conversations/conversations.controller.d.ts +7 -1
  73. package/dist/conversations/conversations.controller.js +26 -10
  74. package/dist/conversations/conversations.module.js +4 -0
  75. package/dist/conversations/conversations.service.d.ts +112 -35
  76. package/dist/conversations/conversations.service.js +160 -43
  77. package/dist/conversations/event-log.d.ts +1 -0
  78. package/dist/conversations/events.d.ts +95 -27
  79. package/dist/conversations/events.js +108 -10
  80. package/dist/conversations/files.d.ts +66 -64
  81. package/dist/conversations/files.js +127 -147
  82. package/dist/conversations/message-context.d.ts +2 -2
  83. package/dist/conversations/message-context.js +1 -1
  84. package/dist/conversations/permission-profile-store.d.ts +2 -1
  85. package/dist/conversations/permission-profiles.controller.d.ts +3 -0
  86. package/dist/conversations/permission-profiles.service.js +1 -1
  87. package/dist/conversations/prompt-suggestion-request.d.ts +1 -1
  88. package/dist/conversations/prompt-suggestion-request.js +4 -2
  89. package/dist/conversations/prompt-suggestions.d.ts +3 -3
  90. package/dist/conversations/prompt-suggestions.js +11 -10
  91. package/dist/conversations/queue.d.ts +7 -4
  92. package/dist/conversations/queue.js +6 -2
  93. package/dist/conversations/queue.service.d.ts +5 -5
  94. package/dist/conversations/queue.service.js +27 -16
  95. package/dist/ctx/create-ctx.d.ts +23 -2
  96. package/dist/ctx/create-ctx.js +78 -3
  97. package/dist/db/kernel-schema.d.ts +184 -27
  98. package/dist/devices/device-project-files.service.d.ts +88 -0
  99. package/dist/devices/device-project-files.service.js +249 -0
  100. package/dist/devices/device-projects.service.d.ts +40 -0
  101. package/dist/devices/device-projects.service.js +16 -13
  102. package/dist/devices/devices.controller.d.ts +9 -3
  103. package/dist/devices/devices.controller.js +27 -5
  104. package/dist/devices/devices.module.js +9 -1
  105. package/dist/devices/devices.schemas.js +6 -1
  106. package/dist/devices/dto.d.ts +15 -0
  107. package/dist/devices/dto.js +11 -0
  108. package/dist/devices/project-paths.d.ts +29 -0
  109. package/dist/devices/project-paths.js +66 -0
  110. package/dist/devices/project-rules.d.ts +5 -1
  111. package/dist/devices/project-rules.js +5 -1
  112. package/dist/errors.d.ts +53 -13
  113. package/dist/errors.js +53 -13
  114. package/dist/evals/canonical-json.d.ts +7 -0
  115. package/dist/evals/canonical-json.js +21 -0
  116. package/dist/evals/reconstruct.d.ts +10 -1
  117. package/dist/evals/reconstruct.js +20 -1
  118. package/dist/evals/recorded-tools.d.ts +0 -2
  119. package/dist/evals/recorded-tools.js +1 -16
  120. package/dist/evals/snapshot.d.ts +26 -3
  121. package/dist/evals/snapshot.js +110 -57
  122. package/dist/evals/worker.d.ts +4 -3
  123. package/dist/evals/worker.js +8 -4
  124. package/dist/extensions/host.d.ts +9 -2
  125. package/dist/extensions/host.js +12 -0
  126. package/dist/extensions/instance.d.ts +3 -1
  127. package/dist/extensions/instance.js +4 -0
  128. package/dist/extensions/ledger.d.ts +1 -1
  129. package/dist/extensions/permission-set.d.ts +17 -1
  130. package/dist/extensions/permission-set.js +13 -1
  131. package/dist/extensions/permission-view.d.ts +1 -1
  132. package/dist/extensions/permission-view.js +4 -1
  133. package/dist/files/blob-objects.d.ts +124 -0
  134. package/dist/files/blob-objects.js +341 -0
  135. package/dist/files/blob-sweep.job.d.ts +122 -0
  136. package/dist/files/blob-sweep.job.js +389 -0
  137. package/dist/files/blobs.service.d.ts +135 -0
  138. package/dist/files/blobs.service.js +300 -0
  139. package/dist/files/conversation-media.d.ts +41 -0
  140. package/dist/files/conversation-media.js +124 -0
  141. package/dist/files/deliveries.d.ts +64 -0
  142. package/dist/files/deliveries.js +156 -0
  143. package/dist/files/deliveries.module.d.ts +6 -0
  144. package/dist/files/deliveries.module.js +24 -0
  145. package/dist/files/draft-cleanup.job.d.ts +26 -0
  146. package/dist/files/draft-cleanup.job.js +93 -0
  147. package/dist/files/files.module.d.ts +1 -1
  148. package/dist/files/files.module.js +3 -2
  149. package/dist/files/hash-job.d.ts +127 -0
  150. package/dist/files/hash-job.js +447 -0
  151. package/dist/files/library-backfill.d.ts +63 -0
  152. package/dist/files/library-backfill.js +143 -0
  153. package/dist/files/library-files.service.d.ts +255 -0
  154. package/dist/files/library-files.service.js +883 -0
  155. package/dist/files/library-jobs.module.d.ts +8 -0
  156. package/dist/files/library-jobs.module.js +27 -0
  157. package/dist/files/library-query.d.ts +127 -0
  158. package/dist/files/library-query.js +322 -0
  159. package/dist/files/library-read.module.d.ts +9 -0
  160. package/dist/files/library-read.module.js +30 -0
  161. package/dist/files/library.controller.d.ts +77 -0
  162. package/dist/files/library.controller.js +235 -0
  163. package/dist/files/library.module.d.ts +9 -0
  164. package/dist/files/library.module.js +29 -0
  165. package/dist/files/library.schemas.d.ts +46 -0
  166. package/dist/files/library.schemas.js +49 -0
  167. package/dist/files/previewers.controller.d.ts +20 -0
  168. package/dist/files/previewers.controller.js +47 -0
  169. package/dist/files/previewers.d.ts +25 -11
  170. package/dist/files/previewers.js +43 -27
  171. package/dist/files/referenced-files.d.ts +150 -0
  172. package/dist/files/referenced-files.js +234 -0
  173. package/dist/git/gateway.js +2 -2
  174. package/dist/html/html-document.controller.d.ts +8 -1
  175. package/dist/html/html-document.controller.js +19 -1
  176. package/dist/html/html-document.service.d.ts +19 -4
  177. package/dist/html/html-document.service.js +43 -22
  178. package/dist/html/html-token.d.ts +10 -1
  179. package/dist/html/html-token.js +14 -0
  180. package/dist/html/html.module.js +8 -1
  181. package/dist/http/api.module.js +10 -5
  182. package/dist/http/request-signal.d.ts +8 -0
  183. package/dist/http/request-signal.js +14 -0
  184. package/dist/identity/settings.d.ts +26 -0
  185. package/dist/identity/settings.js +33 -2
  186. package/dist/inbox/inbox.module.js +2 -2
  187. package/dist/inbox/inbox.service.d.ts +8 -8
  188. package/dist/inbox/inbox.service.js +7 -7
  189. package/dist/infra/config/kernel-config.service.js +10 -5
  190. package/dist/infra/outbox/registry.d.ts +111 -2
  191. package/dist/infra/outbox/registry.js +104 -9
  192. package/dist/infra/throttler/named-throttlers.d.ts +2 -0
  193. package/dist/infra/throttler/named-throttlers.js +14 -0
  194. package/dist/kernel.module.js +3 -0
  195. package/dist/lifecycle/kernel-lifecycle.js +6 -0
  196. package/dist/models/purposes.js +1 -1
  197. package/dist/orgs/offboarding.js +1 -1
  198. package/dist/orgs/roles.d.ts +1 -1
  199. package/dist/orgs/roles.js +3 -3
  200. package/dist/orgs/settings.controller.d.ts +1 -1
  201. package/dist/orgs/settings.service.d.ts +75 -13
  202. package/dist/orgs/settings.service.js +104 -26
  203. package/dist/platform/exclusions.js +45 -8
  204. package/dist/platform/file-ref.d.ts +18 -3
  205. package/dist/platform/file-ref.js +22 -11
  206. package/dist/platform/operation.js +6 -2
  207. package/dist/platform/ops/admin.ops.js +5 -2
  208. package/dist/platform/ops/{schedules.ops.d.ts → automations.ops.d.ts} +4 -4
  209. package/dist/platform/ops/automations.ops.js +560 -0
  210. package/dist/platform/ops/devices.ops.d.ts +3 -1
  211. package/dist/platform/ops/devices.ops.js +77 -3
  212. package/dist/platform/ops/files.ops.d.ts +18 -0
  213. package/dist/platform/ops/files.ops.js +267 -0
  214. package/dist/platform/ops/inbox.ops.js +4 -4
  215. package/dist/platform/ops/org-settings.ops.js +6 -2
  216. package/dist/platform/ops/orgs.ops.js +2 -1
  217. package/dist/platform/ops/platform.ops.js +4 -4
  218. package/dist/platform/ops/shares.ops.js +2 -2
  219. package/dist/platform/platform-ops.module.d.ts +3 -2
  220. package/dist/platform/platform-ops.module.js +10 -5
  221. package/dist/platform/route-schemas.js +6 -3
  222. package/dist/push/jobs.d.ts +3 -3
  223. package/dist/push/jobs.js +2 -2
  224. package/dist/push/preferences.service.js +1 -1
  225. package/dist/push/push-owed.d.ts +3 -3
  226. package/dist/push/push-owed.js +6 -6
  227. package/dist/push/push.schemas.d.ts +4 -4
  228. package/dist/push/push.schemas.js +3 -3
  229. package/dist/push/recipients.d.ts +4 -4
  230. package/dist/push/recipients.js +23 -23
  231. package/dist/push/texts.d.ts +3 -3
  232. package/dist/push/texts.js +2 -2
  233. package/dist/push/triggers.d.ts +1 -1
  234. package/dist/roles/worker.module.js +18 -4
  235. package/dist/runtime/compaction-settings.service.d.ts +13 -1
  236. package/dist/runtime/compaction-settings.service.js +16 -1
  237. package/dist/runtime/compaction.service.d.ts +3 -1
  238. package/dist/runtime/compaction.service.js +3 -1
  239. package/dist/runtime/context/build.d.ts +24 -1
  240. package/dist/runtime/context/build.js +33 -11
  241. package/dist/runtime/context/cache-expiry.d.ts +31 -0
  242. package/dist/runtime/context/cache-expiry.js +60 -0
  243. package/dist/runtime/context/cache-ttl.d.ts +18 -0
  244. package/dist/runtime/context/cache-ttl.js +30 -0
  245. package/dist/runtime/context/compaction.d.ts +9 -2
  246. package/dist/runtime/context/compaction.js +64 -21
  247. package/dist/runtime/context/in-context-compaction.d.ts +156 -0
  248. package/dist/runtime/context/in-context-compaction.js +310 -0
  249. package/dist/runtime/context/run-context.d.ts +38 -0
  250. package/dist/runtime/context/run-context.js +54 -0
  251. package/dist/runtime/hook-calls.d.ts +2 -1
  252. package/dist/runtime/hook-calls.js +5 -2
  253. package/dist/runtime/maintenance.d.ts +16 -4
  254. package/dist/runtime/maintenance.js +79 -18
  255. package/dist/runtime/model-call.d.ts +34 -5
  256. package/dist/runtime/model-call.js +207 -22
  257. package/dist/runtime/providers.js +11 -1
  258. package/dist/runtime/run-finish.d.ts +4 -4
  259. package/dist/runtime/run-finish.js +3 -3
  260. package/dist/runtime/run-queue.js +12 -7
  261. package/dist/runtime/run-steps.d.ts +4 -2
  262. package/dist/runtime/run-steps.js +10 -5
  263. package/dist/runtime/run-worker.js +7 -1
  264. package/dist/runtime/runtime.module.js +6 -3
  265. package/dist/runtime/subagents/dispatch.js +11 -3
  266. package/dist/sandbox/browse-roots.d.ts +8 -0
  267. package/dist/sandbox/browse-roots.js +22 -0
  268. package/dist/sandbox/network-grants.d.ts +4 -4
  269. package/dist/sandbox/network-grants.js +7 -7
  270. package/dist/sandbox/operation-authority.d.ts +10 -3
  271. package/dist/sandbox/operation-authority.js +20 -10
  272. package/dist/sandbox/operation-intents.d.ts +3 -1
  273. package/dist/sandbox/operation-intents.js +11 -4
  274. package/dist/sandbox/permission-call-grants.js +2 -2
  275. package/dist/sandbox/permission-facts.js +1 -1
  276. package/dist/sandbox/review/classifier.d.ts +2 -2
  277. package/dist/sandbox/review/classifier.js +22 -11
  278. package/dist/sandbox/review/permission-candidate.d.ts +1 -1
  279. package/dist/sandbox/review/permission-candidate.js +1 -1
  280. package/dist/sandbox/sandbox.service.d.ts +15 -5
  281. package/dist/sandbox/sandbox.service.js +14 -8
  282. package/dist/shares/liveness.d.ts +26 -12
  283. package/dist/shares/liveness.js +79 -20
  284. package/dist/shares/revoke.d.ts +16 -11
  285. package/dist/shares/revoke.js +18 -14
  286. package/dist/shares/share-objects.d.ts +16 -21
  287. package/dist/shares/share-objects.js +25 -55
  288. package/dist/shares/share-open.service.d.ts +8 -4
  289. package/dist/shares/share-open.service.js +14 -11
  290. package/dist/shares/shares.controller.d.ts +16 -5
  291. package/dist/shares/shares.controller.js +39 -5
  292. package/dist/shares/shares.module.d.ts +4 -4
  293. package/dist/shares/shares.module.js +7 -6
  294. package/dist/shares/shares.schemas.d.ts +4 -0
  295. package/dist/shares/shares.schemas.js +2 -0
  296. package/dist/shares/shares.service.d.ts +93 -54
  297. package/dist/shares/shares.service.js +292 -131
  298. package/dist/shares/sweep.job.d.ts +18 -39
  299. package/dist/shares/sweep.job.js +47 -206
  300. package/dist/storage/purge.d.ts +1 -1
  301. package/dist/storage/purge.js +2 -2
  302. package/dist/tools/approvals.service.d.ts +6 -6
  303. package/dist/tools/approvals.service.js +19 -19
  304. package/dist/tools/builtin-names.d.ts +12 -12
  305. package/dist/tools/builtin-names.js +29 -29
  306. package/dist/tools/builtins/artifacts.d.ts +21 -13
  307. package/dist/tools/builtins/artifacts.js +81 -51
  308. package/dist/tools/builtins/{schedules.d.ts → automations.d.ts} +35 -33
  309. package/dist/tools/builtins/{schedules.js → automations.js} +236 -105
  310. package/dist/tools/builtins/builtin-tools.d.ts +15 -9
  311. package/dist/tools/builtins/builtin-tools.js +33 -22
  312. package/dist/tools/builtins/conversation-files.d.ts +23 -13
  313. package/dist/tools/builtins/conversation-files.js +62 -83
  314. package/dist/tools/builtins/image/generate.d.ts +7 -1
  315. package/dist/tools/builtins/image/generate.js +1 -1
  316. package/dist/tools/builtins/platform.js +1 -0
  317. package/dist/tools/builtins/sandbox/common.d.ts +6 -2
  318. package/dist/tools/builtins/sandbox/deliver.js +6 -7
  319. package/dist/tools/builtins/sandbox/fetch-attachment.d.ts +6 -5
  320. package/dist/tools/builtins/sandbox/fetch-attachment.js +19 -12
  321. package/dist/tools/call-scope.d.ts +1 -1
  322. package/dist/tools/git-asks.js +1 -1
  323. package/dist/tools/git-push-policy.d.ts +3 -3
  324. package/dist/tools/git-push-policy.js +6 -6
  325. package/dist/tools/network-asks.d.ts +3 -3
  326. package/dist/tools/network-asks.js +3 -3
  327. package/dist/tools/pipeline.d.ts +4 -4
  328. package/dist/tools/pipeline.js +2 -2
  329. package/dist/tools/policy.d.ts +3 -3
  330. package/dist/tools/policy.js +3 -3
  331. package/dist/tools/tools.module.js +15 -9
  332. package/dist/ui/call-extension.d.ts +6 -4
  333. package/dist/ui/call-extension.js +5 -4
  334. package/dist/ui/embed-token.js +6 -3
  335. package/dist/ui/registry.d.ts +21 -5
  336. package/dist/ui/registry.js +24 -6
  337. package/dist/ui/ui.schemas.d.ts +22 -0
  338. package/dist/ui/ui.schemas.js +22 -4
  339. package/dist/ui/views.controller.d.ts +13 -3
  340. package/dist/ui/views.controller.js +33 -2
  341. package/dist/ui/views.d.ts +29 -1
  342. package/dist/ui/views.js +131 -7
  343. package/package.json +3 -3
  344. package/src/migrations/0188_automations_rename.sql +309 -0
  345. package/src/migrations/0189_event_automations.sql +136 -0
  346. package/src/migrations/0190_file_library.sql +285 -0
  347. package/src/migrations/0191_file_library_copy.sql +4 -0
  348. package/dist/platform/ops/schedules.ops.js +0 -509
  349. package/dist/schedules/effective-settings.d.ts +0 -22
  350. package/dist/schedules/effective-settings.js +0 -18
  351. package/dist/schedules/errors.d.ts +0 -8
  352. package/dist/schedules/errors.js +0 -8
  353. package/dist/schedules/job-ids.d.ts +0 -81
  354. package/dist/schedules/job-ids.js +0 -95
  355. package/dist/schedules/schedules.module.d.ts +0 -16
  356. package/dist/schedules/schedules.schemas.js +0 -213
  357. package/dist/schedules/store.module.d.ts +0 -6
  358. package/dist/schedules/types.d.ts +0 -110
  359. /package/dist/{schedules → automations}/types.js +0 -0
@@ -1,12 +1,14 @@
1
1
  import { createHash } from "node:crypto";
2
- import { isModelError, isRetryableKind, ModelError, sanitizeParams, } from "@capybara-hq/plugin-sdk";
2
+ import { isModelError, isRetryableKind, ModelError, sanitizeParams, validateCacheWriteByTtl, } from "@capybara-hq/plugin-sdk";
3
3
  import { MEDIA_EXCLUDED_MAX_IDS } from "../conversations/events.js";
4
4
  import { ApiError } from "../errors.js";
5
5
  import { ExtensionUnloadedError } from "../extensions/inflight.js";
6
6
  import { hasInvocation, skillLoadOffered } from "../skills/catalog.js";
7
7
  import { buildModelRequest, latestSummary, mediaRefs, planMedia, } from "./context/build.js";
8
+ import { selectCacheTtl } from "./context/cache-ttl.js";
8
9
  import { acceptSummary, buildCompactionRequest, chunkTranscript, compactionBackoff, compactionChunkSize, compactionInputBudget, compactionPlan, compactionRequestOverhead, extractSummary, MIN_COMPACTION_CHUNK_TOKENS, manualOpeningSeqs, manualTailBudget, nextTranscriptChunk, openingSeqs, shouldCompact, summarySavedTokens, turnsSinceSummary, } from "./context/compaction.js";
9
10
  import { applyFit, estimateAfterFit, planFit, planningBounds, planReactiveTrim, planSqueezedFit, sentOutputCap, } from "./context/fit.js";
11
+ import { buildInContextCompactionRequest, IN_CONTEXT_BOUNDARY_MODE, inContextCoversUpToSeq, inContextSummaryAllowed, latestModelCall, unansweredAfterReply, unansweredOpeners, withInContextRetryNote, } from "./context/in-context-compaction.js";
10
12
  import { guardToolPairs } from "./context/pairing.js";
11
13
  import { hasProjectSkills, overlongProjectSkills } from "./context/project-root.js";
12
14
  import { TOOLS_UNSUPPORTED_REMINDER, turnLimitReminder } from "./context/reminders.js";
@@ -355,8 +357,9 @@ wrapUpReason) {
355
357
  const resolved = await resolveAgentTools(deps, input, events);
356
358
  const tools = stepToolsOf(resolved, input, deps);
357
359
  const beforeCompaction = events.length;
358
- // the org's effective compaction settings, once for this step (org > platform > built-in)
359
- const compaction = await deps.compactionSettings.resolve(input.orgId);
360
+ // the org's effective compaction and prompt cache settings, once for this step (org >
361
+ // platform > built-in)
362
+ const { compaction, promptCache } = await deps.compactionSettings.resolveStep(input.orgId);
360
363
  events = await maybeCompact(deps, input, events, runtime, compaction, tools);
361
364
  // a sub-agent checks its budget again after a compaction call, so the step's own request is
362
365
  // not a second call over the cap (review M5; the loop checks before each step); the budget
@@ -401,7 +404,7 @@ wrapUpReason) {
401
404
  }
402
405
  let laddered;
403
406
  try {
404
- laddered = await ladder(deps, input, events, runtime, compaction, tools, wrapUpReason, streamed);
407
+ laddered = await ladder(deps, input, events, runtime, compaction, promptCache.longTtl, tools, wrapUpReason, streamed);
405
408
  }
406
409
  catch (e) {
407
410
  // a forced compaction inside the ladder used up a sub-agent's budget (the same check as
@@ -587,7 +590,9 @@ function mediaLimits(deps) {
587
590
  * 调用方不变式:不得在「已记录 tool_call、尚未记录其 tool_result」之间构建请求——
588
591
  * 否则配对守卫会给进行中的调用补上 unknown 结果并发给模型。运行循环在工具结果落日志后才进入下一步。
589
592
  */
590
- function buildRequest(limits, events, input, info, params, runtime, tools, wrapUp) {
593
+ function buildRequest(limits, events, input, info, params, runtime, tools, wrapUp,
594
+ /** The prompt cache lifetime to ask for ({@link selectCacheTtl}); absent asks for none. */
595
+ cacheTtl) {
591
596
  const { request, meta, mediaTokens } = assembleModelRequest({
592
597
  events,
593
598
  agent: input.agent,
@@ -599,6 +604,7 @@ function buildRequest(limits, events, input, info, params, runtime, tools, wrapU
599
604
  tools: tools.list,
600
605
  toolSearch: tools.toolSearch,
601
606
  ...(wrapUp && { toolChoice: "none" }),
607
+ ...(cacheTtl !== undefined && { cacheTtl }),
602
608
  mediaInfo: tools.media.info,
603
609
  media: tools.media.bytes,
604
610
  mediaBudgetBytes: limits.budgetBytes,
@@ -724,6 +730,116 @@ function compactionOrdinal(events, runId, step) {
724
730
  function textTokens(text) {
725
731
  return estimateTokens([{ role: "user", content: [{ type: "text", text }] }], []);
726
732
  }
733
+ /**
734
+ * The in-context summary request of a compaction (idle compaction spec §9.4), or why the
735
+ * compaction summarizes the transcript: a manual compact run (ruling R13: it keeps the #990 plan),
736
+ * the reactive path's `transcriptOnly`, a model the quality
737
+ * gate does not list, a compaction model other than the last call's, no live snapshot, or a skip of
738
+ * {@link buildInContextCompactionRequest}. Media come from the step's own media cache (what the
739
+ * next step would send). Never throws.
740
+ */
741
+ async function inContextSummary(deps, input, events, ref, info, tools, settings, plan, opts) {
742
+ // ruling R13: only automatic compactions summarize in context; conditioned on `manual`, never
743
+ // on `force` (the reactive path forces too, and phase 2's idle compact run is not manual)
744
+ if (opts.manual === true)
745
+ return { skip: "manual" };
746
+ if (opts.transcriptOnly)
747
+ return { skip: "transcript_only" };
748
+ if (!inContextSummaryAllowed(ref.provider, info.id))
749
+ return { skip: "quality_gate" };
750
+ if (deps.liveSnapshot === undefined)
751
+ return { skip: "no_snapshot" };
752
+ const call = latestModelCall(events);
753
+ if (call === undefined)
754
+ return { skip: "no_model_call" };
755
+ // The compaction's ref (provider + configured model name) against the last call's recorded one;
756
+ // the builder compares the resolved `info.id` again. The two can differ only for an alias the
757
+ // registry resolves to another id: either mismatch skips to the transcript, so it fails safe.
758
+ if (call.payload.provider !== ref.provider || call.payload.model !== ref.model) {
759
+ return { skip: "model_mismatch" };
760
+ }
761
+ // cheap checks before the snapshot read (the builder repeats this one)
762
+ if (call.payload.request.fit !== undefined)
763
+ return { skip: "fit_plan" };
764
+ if (input.agentId === undefined || call.runId === null)
765
+ return { skip: "no_agent" };
766
+ let boundary;
767
+ let coversUpToSeq;
768
+ if (IN_CONTEXT_BOUNDARY_MODE === "all") {
769
+ boundary = { mode: "all" };
770
+ coversUpToSeq = inContextCoversUpToSeq(events, input.absorbedUpToSeq);
771
+ if (coversUpToSeq < plan.coversUpToSeq)
772
+ return { skip: "covers_unabsorbed" };
773
+ }
774
+ else {
775
+ const kept = events.find((e) => e.type === "user_message" && e.seq > plan.coversUpToSeq);
776
+ if (kept === undefined)
777
+ return { skip: "boundary_ambiguous" };
778
+ boundary = { mode: "marked", firstKeptSeq: kept.seq };
779
+ coversUpToSeq = plan.coversUpToSeq;
780
+ }
781
+ // the openers the summary re-renders, and so the ones the settled-point check admits (what is
782
+ // checked is what is re-rendered): only those after the reference call's reply, which the model
783
+ // has not answered (a turn-start compaction's)
784
+ const opening = unansweredOpeners(events, openingSeqs(events, input.runId, coversUpToSeq, input.absorbedUpToSeq));
785
+ // ruling R9: only at a settled point; a run opener is re-rendered after the summary (R9a)
786
+ if (unansweredAfterReply(events, {
787
+ coversUpToSeq,
788
+ absorbedUpToSeq: input.absorbedUpToSeq,
789
+ openers: opening,
790
+ })) {
791
+ return { skip: "pending_input" };
792
+ }
793
+ // review M1: the request holds only what the summary covers, so no event after an unabsorbed
794
+ // message is both summarized and kept in the tail
795
+ const included = events.filter((e) => e.seq <= coversUpToSeq);
796
+ let snapshot;
797
+ try {
798
+ snapshot = await deps.liveSnapshot(input.orgId, input.conversationId, call.runId, input.agentId, events);
799
+ }
800
+ catch (err) {
801
+ deps.log.warn("in-context summary snapshot failed", {
802
+ context: "Compaction",
803
+ conversationId: input.conversationId,
804
+ error: err instanceof Error ? err.message : String(err),
805
+ });
806
+ return { skip: "snapshot_failed" };
807
+ }
808
+ try {
809
+ const built = buildInContextCompactionRequest({
810
+ snapshot,
811
+ events: included,
812
+ absorbedUpToSeq: input.absorbedUpToSeq,
813
+ model: info,
814
+ mediaInfo: tools.media.info,
815
+ media: tools.media.bytes,
816
+ reserveTokens: settings.reserveTokens,
817
+ summaryCap: settings.summaryCap,
818
+ boundary,
819
+ retry: false,
820
+ // the fit check calibrates like the trigger does
821
+ calibration: lastActual(events),
822
+ });
823
+ if ("skip" in built)
824
+ return built;
825
+ return {
826
+ request: built.request,
827
+ // review M2: built once; the retry form only appends the note (the fit check above did not
828
+ // count its few tokens, which the reserve absorbs)
829
+ retryRequest: withInContextRetryNote(built.request, settings.summaryCap),
830
+ coversUpToSeq,
831
+ opening,
832
+ };
833
+ }
834
+ catch (err) {
835
+ deps.log.warn("in-context summary request failed to build", {
836
+ context: "Compaction",
837
+ conversationId: input.conversationId,
838
+ err,
839
+ });
840
+ return { skip: "build_failed" };
841
+ }
842
+ }
727
843
  /**
728
844
  * Compaction: summarize the earlier conversation with the main model (consumed non-streaming) when
729
845
  * the calibrated estimate crosses the trigger (context compaction spec §4.1). The hard line
@@ -816,7 +932,8 @@ export async function runCompaction(deps, input, events, runtime, compaction, to
816
932
  const tailBudget = bounds.target - estimateTokens([], built.system, built.tools);
817
933
  // a manual compaction ignores keepRecentTurns and keeps at most about a fifth of the window of
818
934
  // the latest turn (spec §4.7, maintainer decision 2026-11-28); the reactive path (`force`
819
- // without `manual`) plans like the proactive one
935
+ // without `manual`) plans like the proactive one. A manual compaction always summarizes the
936
+ // transcript with this plan (ruling R13); an automatic one may summarize in context below
820
937
  const manual = opts.manual === true;
821
938
  const plan = manual
822
939
  ? compactionPlan(events, compaction, manualTailBudget(info.contextWindow, tailBudget), {
@@ -846,11 +963,6 @@ export async function runCompaction(deps, input, events, runtime, compaction, to
846
963
  failed: false,
847
964
  };
848
965
  }
849
- // decided now and recorded in the summary (spec §4.2): the request never depends on later events
850
- // a manual compact run is started by no message: the turn it cuts into is the latest message run's
851
- const opening = manual
852
- ? manualOpeningSeqs(events, plan.coversUpToSeq, input.absorbedUpToSeq)
853
- : openingSeqs(events, input.runId, plan.coversUpToSeq, input.absorbedUpToSeq);
854
966
  const { runId, step, signal, conversationId } = input;
855
967
  const ref = modelRef;
856
968
  // §4.6 progress: from here the compaction is certain, so the conversation may show a row. It is
@@ -868,6 +980,30 @@ export async function runCompaction(deps, input, events, runtime, compaction, to
868
980
  // the summary call's output cap: the org's effective setting, never above the model's own cap
869
981
  // (context compaction spec §4.8)
870
982
  const summaryCap = Math.min(compaction.maxOutputTokens, info.maxOutputTokens);
983
+ // idle compaction spec §9.4: an automatic compaction tries the summary from the conversation's
984
+ // last request first (its cached prefix); a skip (always for a manual one, ruling R13)
985
+ // summarizes the transcript exactly as before
986
+ const inContext = await inContextSummary(deps, input, events, modelRef, info, tools, { reserveTokens: compaction.reserveTokens, summaryCap }, plan, opts);
987
+ const ic = "skip" in inContext ? null : inContext;
988
+ if ("skip" in inContext) {
989
+ deps.log.debug?.("in-context summary skipped", {
990
+ context: "Compaction",
991
+ conversationId,
992
+ reason: inContext.skip,
993
+ });
994
+ }
995
+ // review M6: the preparation awaited the snapshot read; an abort meanwhile sends no call
996
+ if (signal.aborted) {
997
+ deps.compactionProgress?.clear(runId);
998
+ throw new StepAborted();
999
+ }
1000
+ const coversUpToSeq = ic?.coversUpToSeq ?? plan.coversUpToSeq;
1001
+ // decided now and recorded in the summary (spec §4.2): the request never depends on later events;
1002
+ // a manual compact run is started by no message: the turn it cuts into is the latest message run's
1003
+ const opening = ic?.opening ??
1004
+ (manual
1005
+ ? manualOpeningSeqs(events, coversUpToSeq, input.absorbedUpToSeq)
1006
+ : openingSeqs(events, input.runId, coversUpToSeq, input.absorbedUpToSeq));
871
1007
  // the payload's attempt drives the backoff; the keys use the compaction's ordinal in the step
872
1008
  const attemptNo = consecutiveCompactionFailures(events) + 1;
873
1009
  const ordinal = compactionOrdinal(events, runId, step);
@@ -893,8 +1029,11 @@ export async function runCompaction(deps, input, events, runtime, compaction, to
893
1029
  const overhead = compactionRequestOverhead();
894
1030
  const allowance = Math.ceil(summaryCap / 2);
895
1031
  const baseChunkSize = compactionChunkSize(budget, summaryCap);
896
- // the whole transcript is one call unless it is over a usable base chunk size
897
- let remaining = baseChunkSize >= MIN_COMPACTION_CHUNK_TOKENS && textTokens(plan.transcript) > baseChunkSize
1032
+ // the whole transcript is one call unless it is over a usable base chunk size; the in-context
1033
+ // request is never chunked (spec §4.5): it is one request the model already accepted
1034
+ let remaining = ic === null &&
1035
+ baseChunkSize >= MIN_COMPACTION_CHUNK_TOKENS &&
1036
+ textTokens(plan.transcript) > baseChunkSize
898
1037
  ? plan.transcript
899
1038
  : null;
900
1039
  /** Whether this compaction is chunked (real `i/N` progress only in this path). */
@@ -962,7 +1101,11 @@ export async function runCompaction(deps, input, events, runtime, compaction, to
962
1101
  // the compaction (spec §4.5, issue #959)
963
1102
  let retry = false;
964
1103
  for (;;) {
965
- const request = buildCompactionRequest(callInput, info.id, summaryCap, { retry });
1104
+ const request = ic !== null
1105
+ ? retry
1106
+ ? ic.retryRequest
1107
+ : ic.request
1108
+ : buildCompactionRequest(callInput, info.id, summaryCap, { retry });
966
1109
  if (hookBase && deps.hooks?.has("model.request")) {
967
1110
  let verdict;
968
1111
  try {
@@ -998,7 +1141,7 @@ export async function runCompaction(deps, input, events, runtime, compaction, to
998
1141
  ...(chunked ? { chunk: chunkNo, chunks: plannedChunks } : {}),
999
1142
  chars: partial.length,
1000
1143
  });
1001
- });
1144
+ }, deps.log);
1002
1145
  usages.push({ chunk: multiChunk ? chunkNo : undefined, retry, usage: out.usage });
1003
1146
  if (hookBase && deps.hooks) {
1004
1147
  fireObserve(deps.hooks, "model.response", {
@@ -1011,6 +1154,13 @@ export async function runCompaction(deps, input, events, runtime, compaction, to
1011
1154
  latencyMs: Date.now() - sentAt,
1012
1155
  }, signal, deps.log);
1013
1156
  }
1157
+ // the in-context request declares the conversation's tools under toolChoice "none": a
1158
+ // reply that calls one anyway is no summary (idle compaction spec §9.4)
1159
+ if (out.content.some((b) => b.type === "tool_call")) {
1160
+ failure = "summary reply called a tool";
1161
+ failedChunk = multiChunk ? chunkNo : null;
1162
+ break;
1163
+ }
1014
1164
  if (out.stopReason === "max_tokens") {
1015
1165
  if (!retry) {
1016
1166
  deps.log.warn("compaction summary cut off at the output token limit; asking again", {
@@ -1138,6 +1288,11 @@ export async function runCompaction(deps, input, events, runtime, compaction, to
1138
1288
  if (failure !== null) {
1139
1289
  deps.log.warn("compaction failed", { conversationId, reason: failure });
1140
1290
  }
1291
+ // review M4: an in-context summary (boundary mode all) covers more than the plan's transcript:
1292
+ // what it saved is estimated from the transcript of everything it covers
1293
+ const savedFrom = ic === null
1294
+ ? plan.transcript
1295
+ : (compactionPlan(events.filter((e) => e.seq <= coversUpToSeq), { ...compaction, keepRecentTurns: 0 }, Number.POSITIVE_INFINITY)?.transcript ?? plan.transcript);
1141
1296
  const event = failure === null
1142
1297
  ? {
1143
1298
  type: "compaction_summary",
@@ -1145,13 +1300,14 @@ export async function runCompaction(deps, input, events, runtime, compaction, to
1145
1300
  // the manual compact run's run id is in it; a crash-retried attempt writes nothing twice
1146
1301
  idemKey: idem.compactionSummary(runId, step, ordinal),
1147
1302
  payload: {
1148
- coversUpToSeq: plan.coversUpToSeq,
1303
+ coversUpToSeq,
1149
1304
  text: summary,
1150
1305
  // the run's opening messages the summary covers: request building re-renders them
1151
1306
  ...(opening.length > 0 && { openingSeqs: opening }),
1152
1307
  // what compaction saved: the estimated transcript input minus the stored summary
1153
1308
  // output (context compaction spec §4.9)
1154
- savedTokens: summarySavedTokens(plan.transcript, summary),
1309
+ savedTokens: summarySavedTokens(savedFrom, summary),
1310
+ method: ic !== null ? "in_context" : "transcript",
1155
1311
  step,
1156
1312
  },
1157
1313
  }
@@ -1225,7 +1381,9 @@ async function mergeWritten(eventLog, conversationId, events, written) {
1225
1381
  * not configured in the org: spec B §5.3) goes straight to `agent.fallback` when there is one,
1226
1382
  * without the same-model retry.
1227
1383
  */
1228
- async function ladder(deps, input, events, runtime, compaction, tools, wrapUpReason, streamed) {
1384
+ async function ladder(deps, input, events, runtime, compaction,
1385
+ /** `promptCache.longTtl` for the run's organization: each rung picks its model's tier from it. */
1386
+ longTtl, tools, wrapUpReason, streamed) {
1229
1387
  const { conversationId, runId, step, signal, sink, agent } = input;
1230
1388
  const wrapUp = wrapUpReason !== null;
1231
1389
  const turnReminder = wrapUpReason === "budget"
@@ -1312,6 +1470,7 @@ async function ladder(deps, input, events, runtime, compaction, tools, wrapUpRea
1312
1470
  force: true,
1313
1471
  ref: rung.ref,
1314
1472
  fallback: rung.fallback,
1473
+ transcriptOnly: true,
1315
1474
  });
1316
1475
  if (evs !== before && (await budgetUsedUpAfterCompaction(deps, input, wrapUpReason))) {
1317
1476
  throw new BudgetUsedUp();
@@ -1348,7 +1507,9 @@ async function ladder(deps, input, events, runtime, compaction, tools, wrapUpRea
1348
1507
  evs = refreshed;
1349
1508
  const limits = mediaLimits(deps);
1350
1509
  await loadMedia(deps, limits, input, evs, info, tools);
1351
- const built = buildRequest(limits, evs, input, info, params.value, runtime, tools, wrapUp);
1510
+ const built = buildRequest(limits, evs, input, info, params.value, runtime, tools, wrapUp,
1511
+ // the rung's own model decides the tier (a fallback may offer none)
1512
+ selectCacheTtl(info.cache, longTtl));
1352
1513
  const { request, estimate } = built;
1353
1514
  const fitInput = {
1354
1515
  events: evs,
@@ -1379,6 +1540,7 @@ async function ladder(deps, input, events, runtime, compaction, tools, wrapUpRea
1379
1540
  force: true,
1380
1541
  ref: rung.ref,
1381
1542
  fallback: rung.fallback,
1543
+ transcriptOnly: true,
1382
1544
  });
1383
1545
  if (evs !== before) {
1384
1546
  if (await budgetUsedUpAfterCompaction(deps, input, wrapUpReason)) {
@@ -1492,7 +1654,7 @@ async function ladder(deps, input, events, runtime, compaction, tools, wrapUpRea
1492
1654
  sink({ kind: "tool_input", runId, step, callId: ev.id, text: ev.input });
1493
1655
  bases?.onInput(ev.id, ev.input);
1494
1656
  }
1495
- });
1657
+ }, deps.log);
1496
1658
  }
1497
1659
  finally {
1498
1660
  // the attempt's base reads end with it: aborted, then waited for (the abort reaches
@@ -1801,12 +1963,31 @@ export function deltaChars(ev) {
1801
1963
  return 0;
1802
1964
  }
1803
1965
  }
1966
+ /**
1967
+ * The provider's usage as the kernel records it: a `cacheWriteByTtl` that fails
1968
+ * `validateCacheWriteByTtl` is dropped with a warn (the rest of the usage stays), so the `usage`
1969
+ * event's schema never rejects a call the model already answered.
1970
+ */
1971
+ export function trustedUsage(usage, model, log) {
1972
+ if (usage.cacheWriteByTtl === undefined)
1973
+ return usage;
1974
+ const problem = validateCacheWriteByTtl(usage);
1975
+ if (problem === null)
1976
+ return usage;
1977
+ log?.warn("invalid cacheWriteByTtl from the provider; dropped", { model, problem });
1978
+ const { cacheWriteByTtl: _dropped, ...rest } = usage;
1979
+ return rest;
1980
+ }
1804
1981
  /**
1805
1982
  * 消费一次模型流,带空闲看门狗:两次事件之间超过 `idleMs` → 本地中止并按 `ModelError("timeout")` 抛出。
1806
1983
  * 外部 `signal` 触发 → `StepAborted`。每次 `next()` 都与停止信号竞速,供应商不响应 signal 也不会卡住。
1807
1984
  * 运行时与评测单步回放(`evals/step-replay.ts`)、评委共用。
1985
+ * The usage goes through {@link trustedUsage}, so a malformed `cacheWriteByTtl` never fails a call
1986
+ * after the model replied.
1808
1987
  */
1809
- export async function consumeModelStream(provider, request, idleMs, signal, onDelta) {
1988
+ export async function consumeModelStream(provider, request, idleMs, signal, onDelta,
1989
+ /** Where a dropped `cacheWriteByTtl` is reported. */
1990
+ log) {
1810
1991
  if (signal.aborted)
1811
1992
  throw new StepAborted();
1812
1993
  const local = new AbortController();
@@ -1844,7 +2025,11 @@ export async function consumeModelStream(provider, request, idleMs, signal, onDe
1844
2025
  arm();
1845
2026
  const ev = r.value;
1846
2027
  if (ev.type === "message_complete") {
1847
- return { content: ev.content, stopReason: ev.stopReason, usage: ev.usage };
2028
+ return {
2029
+ content: ev.content,
2030
+ stopReason: ev.stopReason,
2031
+ usage: trustedUsage(ev.usage, request.model, log),
2032
+ };
1848
2033
  }
1849
2034
  onDelta(ev);
1850
2035
  }
@@ -8,7 +8,7 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
8
8
  return function (target, key) { decorator(target, key, paramIndex); }
9
9
  };
10
10
  import { createHash } from "node:crypto";
11
- import { assertValidDeclarations, isModelError, isValidImageGenerationInfo, ModelError, parseExtensionPoint, } from "@capybara-hq/plugin-sdk";
11
+ import { assertValidDeclarations, isModelError, isValidImageGenerationInfo, ModelError, parseExtensionPoint, validateModelCache, } from "@capybara-hq/plugin-sdk";
12
12
  import { Inject, Injectable, Module, Optional } from "@nestjs/common";
13
13
  import { ApiError } from "../errors.js";
14
14
  import { deploymentConfigHash } from "../extensions/config-hash.js";
@@ -314,6 +314,16 @@ let ProviderRegistry = class ProviderRegistry {
314
314
  await this.warnDropped(provider, m.id, hash, problem, cause);
315
315
  continue;
316
316
  }
317
+ // an invalid cache declaration never drops the model: the kernel treats it as not caching
318
+ // (trustedCache) and says so once per list load (idle compaction spec §9.2)
319
+ const cacheProblem = kind === "chat" ? validateModelCache(m.cache) : null;
320
+ if (cacheProblem !== null) {
321
+ this.log?.warn("model cache declaration invalid; treated as not caching", {
322
+ provider,
323
+ model: m.id,
324
+ problem: cacheProblem,
325
+ });
326
+ }
317
327
  out.push({ ...m, kind });
318
328
  }
319
329
  return out;
@@ -1,9 +1,9 @@
1
+ import { AutomationRunTracker } from "../automations/run-tracker.js";
1
2
  import { type AppendEvent, EventLog } from "../conversations/event-log.js";
2
3
  import { GitRunEnd } from "../git/run-end.js";
3
4
  import { KernelDb } from "../infra/database/kernel-db.js";
4
5
  import { TransactionHost } from "../infra/database/transaction-host.js";
5
6
  import { OutboxService } from "../infra/outbox/outbox.service.js";
6
- import { ScheduledTaskRunTracker } from "../schedules/run-tracker.js";
7
7
  import { ApprovalsService } from "../tools/approvals.service.js";
8
8
  import { QuestionsService } from "../tools/questions.service.js";
9
9
  import { type TerminalStatus } from "./run-jobs.js";
@@ -29,7 +29,7 @@ export declare class RunFinish {
29
29
  private readonly kdb;
30
30
  private readonly eventLog;
31
31
  readonly txHost: TransactionHost;
32
- /** A scheduled task's run follows its kernel run's end in the same transaction (spec §6). */
32
+ /** An automation's run follows its kernel run's end in the same transaction (spec §6). */
33
33
  private readonly taskRuns;
34
34
  /** The run's git tickets are revoked and its fetch summaries written after the commit. */
35
35
  private readonly gitRunEnd;
@@ -40,8 +40,8 @@ export declare class RunFinish {
40
40
  /** ... and its pending input requests. */
41
41
  private readonly questions;
42
42
  constructor(kdb: KernelDb, eventLog: EventLog, txHost: TransactionHost,
43
- /** A scheduled task's run follows its kernel run's end in the same transaction (spec §6). */
44
- taskRuns: Pick<ScheduledTaskRunTracker, "onRunFinished">,
43
+ /** An automation's run follows its kernel run's end in the same transaction (spec §6). */
44
+ taskRuns: Pick<AutomationRunTracker, "onRunFinished">,
45
45
  /** The run's git tickets are revoked and its fetch summaries written after the commit. */
46
46
  gitRunEnd: Pick<GitRunEnd, "onRunFinished">,
47
47
  /** The run's end owes the conversation's ensure-run backstop (transactional outbox spec §6). */
@@ -9,6 +9,7 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
9
9
  };
10
10
  import { Inject, Injectable } from "@nestjs/common";
11
11
  import { sql } from "kysely";
12
+ import { AutomationRunTracker } from "../automations/run-tracker.js";
12
13
  import { EventLog } from "../conversations/event-log.js";
13
14
  import { pauseQueueIn } from "../conversations/queue.js";
14
15
  import { GitRunEnd } from "../git/run-end.js";
@@ -17,7 +18,6 @@ import { KernelDb } from "../infra/database/kernel-db.js";
17
18
  import { TransactionHost } from "../infra/database/transaction-host.js";
18
19
  import { Transactional } from "../infra/database/transactional.decorator.js";
19
20
  import { OutboxService } from "../infra/outbox/outbox.service.js";
20
- import { ScheduledTaskRunTracker } from "../schedules/run-tracker.js";
21
21
  import { ApprovalsService } from "../tools/approvals.service.js";
22
22
  import { QuestionsService } from "../tools/questions.service.js";
23
23
  import { ACTIVE_RUN_STATUSES, lockWaitRowsIn, oweEnsureRun, TERMINAL_STATUSES, } from "./run-jobs.js";
@@ -38,7 +38,7 @@ let RunFinish = class RunFinish {
38
38
  approvals;
39
39
  questions;
40
40
  constructor(kdb, eventLog, txHost,
41
- /** A scheduled task's run follows its kernel run's end in the same transaction (spec §6). */
41
+ /** An automation's run follows its kernel run's end in the same transaction (spec §6). */
42
42
  taskRuns,
43
43
  /** The run's git tickets are revoked and its fetch summaries written after the commit. */
44
44
  gitRunEnd,
@@ -209,7 +209,7 @@ RunFinish = __decorate([
209
209
  __param(0, Inject(KernelDb)),
210
210
  __param(1, Inject(EventLog)),
211
211
  __param(2, Inject(TransactionHost)),
212
- __param(3, Inject(ScheduledTaskRunTracker)),
212
+ __param(3, Inject(AutomationRunTracker)),
213
213
  __param(4, Inject(GitRunEnd)),
214
214
  __param(5, Inject(OutboxService)),
215
215
  __param(6, Inject(ApprovalsService)),
@@ -11,6 +11,8 @@ import { randomUUID } from "node:crypto";
11
11
  import { Inject, Injectable, Optional } from "@nestjs/common";
12
12
  import { sql } from "kysely";
13
13
  import { visibleTo } from "../agents/agent-lookup.js";
14
+ import { linkStartedRunIn } from "../automations/run-tracker.js";
15
+ import { automationRunAt } from "../automations/unattended.js";
14
16
  import { wakeDecisionIn } from "../background/wake-rules.js";
15
17
  import { EventLog } from "../conversations/event-log.js";
16
18
  import { dispatchQueuedIn, pauseQueueWith } from "../conversations/queue.js";
@@ -21,8 +23,6 @@ import { KernelDb } from "../infra/database/kernel-db.js";
21
23
  import { TransactionHost } from "../infra/database/transaction-host.js";
22
24
  import { Transactional } from "../infra/database/transactional.decorator.js";
23
25
  import { KERNEL_LOGGER } from "../infra/tokens.js";
24
- import { linkStartedRunIn } from "../schedules/run-tracker.js";
25
- import { scheduledTaskRunAt } from "../schedules/unattended.js";
26
26
  import { KyselyCheckpointSaver } from "./checkpointer.js";
27
27
  import { ConversationLock } from "./conversation-lock.js";
28
28
  import { notifyFinished, RunFinish } from "./run-finish.js";
@@ -337,8 +337,10 @@ let RunQueue = class RunQueue {
337
337
  if (!(await this.oweJob(conversationId, runId, jobId.id, "chat", conv.org_id)))
338
338
  return null;
339
339
  // scheduled tasks spec §4: a task's message makes the run unattended; a wake inherits it
340
- // from the run that produced its event; a person's message never does
341
- const taskRunId = await scheduledTaskRunAt(t, conversationId, trigger.seq);
340
+ // from the run that produced its event; a person's message never does. An event
341
+ // automation's message also records its last event (collaboration spec §4.7)
342
+ const lineage = await automationRunAt(t, conversationId, trigger.seq);
343
+ const taskRunId = lineage.automationRunId;
342
344
  await t
343
345
  .insertInto("runs")
344
346
  .values({
@@ -352,7 +354,8 @@ let RunQueue = class RunQueue {
352
354
  // a chat conversation always has its person-triggered run before any wake (a wake event
353
355
  // comes from a run of it or of its tree); null would only make the wake run its own window
354
356
  budget_run_id: isWake ? await budgetWindowOf(t, conversationId) : null,
355
- scheduled_task_run_id: taskRunId,
357
+ automation_run_id: taskRunId,
358
+ trigger_event_id: lineage.triggerEventId,
356
359
  })
357
360
  .execute();
358
361
  // the task run its message started follows this run from now on (spec §6)
@@ -473,6 +476,8 @@ let RunQueue = class RunQueue {
473
476
  if (!(await this.oweJob(conversationId, runId, jobId.id, "subagent", conv.org_id))) {
474
477
  return null;
475
478
  }
479
+ // a parent's message or a wake: unattended when the run behind it was (automations §4)
480
+ const lineage = await automationRunAt(t, conversationId, wake.seq);
476
481
  await t
477
482
  .insertInto("runs")
478
483
  .values({
@@ -484,8 +489,8 @@ let RunQueue = class RunQueue {
484
489
  trigger_seq: wake.seq,
485
490
  job_id: jobId.recorded,
486
491
  budget_run_id: await budgetWindowOf(t, rootId),
487
- // a parent's message or a wake: unattended when the run behind it was (scheduled tasks §4)
488
- scheduled_task_run_id: await scheduledTaskRunAt(t, conversationId, wake.seq),
492
+ automation_run_id: lineage.automationRunId,
493
+ trigger_event_id: lineage.triggerEventId,
489
494
  })
490
495
  .execute();
491
496
  return runId;
@@ -1,6 +1,6 @@
1
- import { AttachmentsService } from "../conversations/attachments.service.js";
2
1
  import { EventLog } from "../conversations/event-log.js";
3
2
  import { ExtensionHost } from "../extensions/host.js";
3
+ import { ConversationMedia } from "../files/conversation-media.js";
4
4
  import { KernelConfigService } from "../infra/config/kernel-config.service.js";
5
5
  import { KernelDb } from "../infra/database/kernel-db.js";
6
6
  import type { KernelLogger } from "../log.js";
@@ -38,7 +38,9 @@ export declare class AgentLoops {
38
38
  */
39
39
  export declare class RunSteps {
40
40
  readonly deps: LoopDeps;
41
- constructor(kdb: KernelDb, eventLog: EventLog, stepLog: StepLog, registry: ProviderRegistry, tools: ToolRegistry, config: KernelConfigService, log: KernelLogger, toolPipeline: ToolPipeline, host: ExtensionHost, subagents: SubagentsService, attachments: AttachmentsService, compactionSettings: CompactionSettingsService, compactionProgress: CompactionProgressService, permissionContext: PermissionContextRecorder, writeBase: WriteBaseService);
41
+ constructor(kdb: KernelDb, eventLog: EventLog, stepLog: StepLog, registry: ProviderRegistry, tools: ToolRegistry, config: KernelConfigService, log: KernelLogger, toolPipeline: ToolPipeline, host: ExtensionHost, subagents: SubagentsService,
42
+ /** The conversation's media: library files it refers to, and `read` copies. */
43
+ media: ConversationMedia, compactionSettings: CompactionSettingsService, compactionProgress: CompactionProgressService, permissionContext: PermissionContextRecorder, writeBase: WriteBaseService);
42
44
  }
43
45
  /**
44
46
  * The live request boundary of a run's steps (spec B2): every agent-history request construction
@@ -8,9 +8,10 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
8
8
  return function (target, key) { decorator(target, key, paramIndex); }
9
9
  };
10
10
  import { Inject, Injectable, Optional } from "@nestjs/common";
11
- import { AttachmentsService } from "../conversations/attachments.service.js";
12
11
  import { EventLog } from "../conversations/event-log.js";
12
+ import { liveSnapshot } from "../evals/snapshot.js";
13
13
  import { ExtensionHost } from "../extensions/host.js";
14
+ import { ConversationMedia } from "../files/conversation-media.js";
14
15
  import { KernelConfigService } from "../infra/config/kernel-config.service.js";
15
16
  import { KernelDb } from "../infra/database/kernel-db.js";
16
17
  import { KERNEL_LOGGER } from "../infra/tokens.js";
@@ -55,7 +56,9 @@ export { AgentLoops };
55
56
  */
56
57
  let RunSteps = class RunSteps {
57
58
  deps;
58
- constructor(kdb, eventLog, stepLog, registry, tools, config, log, toolPipeline, host, subagents, attachments, compactionSettings, compactionProgress, permissionContext, writeBase) {
59
+ constructor(kdb, eventLog, stepLog, registry, tools, config, log, toolPipeline, host, subagents,
60
+ /** The conversation's media: library files it refers to, and `read` copies. */
61
+ media, compactionSettings, compactionProgress, permissionContext, writeBase) {
59
62
  this.deps = {
60
63
  get db() {
61
64
  return kdb.db;
@@ -77,13 +80,15 @@ let RunSteps = class RunSteps {
77
80
  // phase D: a person's fork invocation dispatches its sub-agent in the run's first prepare
78
81
  skillForks: subagents.skillForks,
79
82
  media: {
80
- info: (orgId, conversationId, ids) => attachments.mediaInfo(orgId, conversationId, ids),
81
- fetch: (orgId, conversationId, ids, caps) => attachments.fetchMedia(orgId, conversationId, ids, caps),
83
+ info: (orgId, conversationId, ids) => media.mediaInfo(orgId, conversationId, ids),
84
+ fetch: (orgId, conversationId, ids, caps) => media.fetchMedia(orgId, conversationId, ids, caps),
82
85
  },
83
86
  // the request boundary of the recorded permission context (spec B2)
84
87
  ...livePermissionContext(permissionContext),
85
88
  // the display-only base of a streaming Write (streaming tool input spec §4.1)
86
89
  writeBase,
90
+ // the in-context summary's view of the conversation (idle compaction spec §9.4)
91
+ liveSnapshot: (orgId, conversationId, runId, agentId, events) => liveSnapshot(kdb.db, { orgId, conversationId, runId, agentId, events }),
87
92
  };
88
93
  }
89
94
  };
@@ -99,7 +104,7 @@ RunSteps = __decorate([
99
104
  __param(7, Inject(ToolPipeline)),
100
105
  __param(8, Inject(ExtensionHost)),
101
106
  __param(9, Inject(SubagentsService)),
102
- __param(10, Inject(AttachmentsService)),
107
+ __param(10, Inject(ConversationMedia)),
103
108
  __param(11, Inject(CompactionSettingsService)),
104
109
  __param(12, Inject(CompactionProgressService)),
105
110
  __param(13, Inject(PermissionContextRecorder)),
@@ -1172,11 +1172,17 @@ let RunWorker = class RunWorker {
1172
1172
  trigger: "subagent",
1173
1173
  triggerSeq: Number(run.trigger_seq),
1174
1174
  }),
1175
- // a scheduled task's message (scheduled tasks spec §6); display only
1175
+ // an automation's message (scheduled tasks spec §6), or an event automation's
1176
+ // (collaboration spec §4.6); display only
1176
1177
  ...(boundary?.type === "user_message" &&
1177
1178
  boundary.payload.schedule !== undefined && {
1178
1179
  trigger: "schedule",
1179
1180
  }),
1181
+ ...(boundary?.type === "user_message" &&
1182
+ boundary.payload.automationEvent !==
1183
+ undefined && {
1184
+ trigger: "automation_event",
1185
+ }),
1180
1186
  }),
1181
1187
  },
1182
1188
  },