@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,20 +1,27 @@
1
1
  import { normalizeStoredDefinition } from "../agents/definition.js";
2
2
  import { ApiError } from "../errors.js";
3
3
  import { childRunDefinition } from "../runtime/subagents/definition.js";
4
- /** The follow-up narrowing on the last sub-agent task message of `events`, if any. */
5
- function lastTaskNarrowing(events) {
6
- const task = events.findLast((e) => e.type === "user_message" && e.payload.dispatch !== undefined);
4
+ /**
5
+ * The follow-up narrowing of run `runId`: the one on the last sub-agent task message up to the
6
+ * run's last event (its terminal event when it has one), if any. A task message logged after the
7
+ * run (a later follow-up's, which a live snapshot may hold) never narrows this run's definition.
8
+ * Without any event of the run, every event counts.
9
+ */
10
+ export function runTaskNarrowing(events, runId) {
11
+ const end = events.findLast((e) => e.runId === runId)?.seq ?? Number.POSITIVE_INFINITY;
12
+ const task = events.findLast((e) => e.seq <= end &&
13
+ e.type === "user_message" &&
14
+ e.payload.dispatch !== undefined);
7
15
  return task?.payload?.dispatch?.narrowed;
8
16
  }
9
17
  const TERMINAL = new Set(["run_finished", "run_failed", "run_aborted"]);
10
- /** 读事件的分页大小。 */
18
+ /** The page size when reading events. */
11
19
  const PAGE = 1000;
12
20
  /**
13
- * 给某次运行建用例快照。会话不在该组织、或运行不属于该会话 → `conversation.not_found`;
14
- * 运行还没有终态事件 → `eval.run_not_finished`(409);序列化后超过 `maxBytes` 字节 → `eval.case_too_large`(413)。
15
- * `maxBytes` 由调用方传入(`evals.maxCaseBytes`)。
21
+ * The conversation and the run's agent version; `conversation.not_found` when the conversation is
22
+ * not in the org or the run is not the conversation's.
16
23
  */
17
- export async function takeSnapshot(db, orgId, conversationId, runId, maxBytes) {
24
+ async function conversationRun(db, orgId, conversationId, runId) {
18
25
  const conv = await db
19
26
  .selectFrom("conversations")
20
27
  .select(["agent_id", "kind", "source"])
@@ -32,51 +39,16 @@ export async function takeSnapshot(db, orgId, conversationId, runId, maxBytes) {
32
39
  if (!conv || !run) {
33
40
  throw new ApiError("conversation.not_found", "Conversation or run not found");
34
41
  }
35
- const end = await db
36
- .selectFrom("conversation_events")
37
- .select("seq")
38
- .where("conversation_id", "=", conversationId)
39
- .where("run_id", "=", runId)
40
- .where("type", "in", [...TERMINAL])
41
- .orderBy("seq")
42
- .executeTakeFirst();
43
- if (!end)
44
- throw new ApiError("eval.run_not_finished", "The run has not finished yet");
45
- const endSeq = Number(end.seq);
46
- const tooLarge = () => new ApiError("eval.case_too_large", `The run's snapshot is larger than the ${maxBytes}-byte limit`);
47
- const events = [];
48
- /** 已读事件序列化后的字节数(快照总大小的下界):一超过上限就停,不把超大的对话整个读进内存。 */
49
- let bytes = 0;
50
- let after = 0;
51
- for (;;) {
52
- const rows = await db
53
- .selectFrom("conversation_events")
54
- .select(["seq", "type", "run_id", "payload", "created_at"])
55
- .where("conversation_id", "=", conversationId)
56
- .where("seq", ">", String(after))
57
- .where("seq", "<=", String(endSeq))
58
- .orderBy("seq")
59
- .limit(PAGE)
60
- .execute();
61
- for (const r of rows) {
62
- const e = {
63
- seq: Number(r.seq),
64
- type: r.type,
65
- payload: r.payload,
66
- runId: r.run_id,
67
- createdAt: new Date(r.created_at).toISOString(),
68
- };
69
- bytes += Buffer.byteLength(JSON.stringify(e));
70
- if (bytes > maxBytes)
71
- throw tooLarge();
72
- events.push(e);
73
- }
74
- const last = rows.at(-1);
75
- if (rows.length < PAGE || !last)
76
- break;
77
- after = Number(last.seq);
78
- }
79
- const versions = new Set([run.agent_version]);
42
+ return { conv, agentVersion: run.agent_version };
43
+ }
44
+ /**
45
+ * The snapshot of `events`: the agent versions they reference (each `run_started` and the run's
46
+ * own), the tool specs of every `model_call`'s `tools` / `catalog`, and a sub-agent's frozen
47
+ * definition and parent call. Shared by {@link takeSnapshot} and {@link liveSnapshot}.
48
+ */
49
+ async function snapshotOf(db, ids, conv, agentVersion, events) {
50
+ const { orgId, conversationId, runId } = ids;
51
+ const versions = new Set([agentVersion]);
80
52
  const hashes = new Set();
81
53
  for (const e of events) {
82
54
  if (e.type === "run_started") {
@@ -119,13 +91,13 @@ export async function takeSnapshot(db, orgId, conversationId, runId, maxBytes) {
119
91
  .where("child_run_id", "=", runId)
120
92
  .executeTakeFirst()
121
93
  : undefined;
122
- const snapshot = {
94
+ return {
123
95
  version: 1,
124
96
  orgId,
125
97
  conversationId,
126
98
  runId,
127
99
  agentId: conv.agent_id,
128
- agentVersion: run.agent_version,
100
+ agentVersion,
129
101
  source: conv.source,
130
102
  events,
131
103
  definitions,
@@ -133,8 +105,8 @@ export async function takeSnapshot(db, orgId, conversationId, runId, maxBytes) {
133
105
  ...(started !== undefined && {
134
106
  subagent: {
135
107
  // this run's definition: the frozen one with its follow-up's narrowing (final review
136
- // I1); the run's task message is the last one up to its terminal event
137
- definition: childRunDefinition(normalizeStoredDefinition(started.definition), lastTaskNarrowing(events)),
108
+ // I1); the run's task message is the last one up to the run's last event
109
+ definition: childRunDefinition(normalizeStoredDefinition(started.definition), runTaskNarrowing(events, runId)),
138
110
  preamble: started.preamble,
139
111
  ...(invokedSkill !== undefined && { invokedSkill }),
140
112
  },
@@ -147,10 +119,91 @@ export async function takeSnapshot(db, orgId, conversationId, runId, maxBytes) {
147
119
  },
148
120
  }),
149
121
  };
122
+ }
123
+ /**
124
+ * Takes a case snapshot of a run. The conversation not in the org, or the run not the
125
+ * conversation's → `conversation.not_found`; the run without a terminal event yet →
126
+ * `eval.run_not_finished` (409); over `maxBytes` bytes serialized → `eval.case_too_large` (413).
127
+ * The caller passes `maxBytes` (`evals.maxCaseBytes`).
128
+ */
129
+ export async function takeSnapshot(db, orgId, conversationId, runId, maxBytes) {
130
+ const { conv, agentVersion } = await conversationRun(db, orgId, conversationId, runId);
131
+ const end = await db
132
+ .selectFrom("conversation_events")
133
+ .select("seq")
134
+ .where("conversation_id", "=", conversationId)
135
+ .where("run_id", "=", runId)
136
+ .where("type", "in", [...TERMINAL])
137
+ .orderBy("seq")
138
+ .executeTakeFirst();
139
+ if (!end)
140
+ throw new ApiError("eval.run_not_finished", "The run has not finished yet");
141
+ const endSeq = Number(end.seq);
142
+ const tooLarge = () => new ApiError("eval.case_too_large", `The run's snapshot is larger than the ${maxBytes}-byte limit`);
143
+ const events = [];
144
+ /**
145
+ * Serialized bytes of the events read so far (a lower bound of the snapshot's size): stop as
146
+ * soon as it is over the limit, never reading a huge conversation into memory whole.
147
+ */
148
+ let bytes = 0;
149
+ let after = 0;
150
+ for (;;) {
151
+ const rows = await db
152
+ .selectFrom("conversation_events")
153
+ .select(["seq", "type", "run_id", "payload", "created_at"])
154
+ .where("conversation_id", "=", conversationId)
155
+ .where("seq", ">", String(after))
156
+ .where("seq", "<=", String(endSeq))
157
+ .orderBy("seq")
158
+ .limit(PAGE)
159
+ .execute();
160
+ for (const r of rows) {
161
+ const e = {
162
+ seq: Number(r.seq),
163
+ type: r.type,
164
+ payload: r.payload,
165
+ runId: r.run_id,
166
+ createdAt: new Date(r.created_at).toISOString(),
167
+ };
168
+ bytes += Buffer.byteLength(JSON.stringify(e));
169
+ if (bytes > maxBytes)
170
+ throw tooLarge();
171
+ events.push(e);
172
+ }
173
+ const last = rows.at(-1);
174
+ if (rows.length < PAGE || !last)
175
+ break;
176
+ after = Number(last.seq);
177
+ }
178
+ const snapshot = await snapshotOf(db, { orgId, conversationId, runId }, conv, agentVersion, events);
150
179
  if (Buffer.byteLength(JSON.stringify(snapshot)) > maxBytes)
151
180
  throw tooLarge();
152
181
  return snapshot;
153
182
  }
183
+ /**
184
+ * A snapshot of events the caller already holds, for a request built live rather than stored (the
185
+ * in-context compaction summary, idle compaction spec §9.4): no terminal event is required and no
186
+ * byte cap applies, since nothing is stored. `runId` is the run of the call the request rebuilds;
187
+ * `conversation.not_found` as in {@link takeSnapshot}. `agentId` is the caller's check: a
188
+ * conversation whose agent differs is not found either.
189
+ */
190
+ export async function liveSnapshot(db, input) {
191
+ const { orgId, conversationId, runId } = input;
192
+ const { conv, agentVersion } = await conversationRun(db, orgId, conversationId, runId);
193
+ if (conv.agent_id !== input.agentId) {
194
+ throw new ApiError("conversation.not_found", "Conversation or run not found");
195
+ }
196
+ const events = [...input.events]
197
+ .sort((a, b) => a.seq - b.seq)
198
+ .map((e) => ({
199
+ seq: e.seq,
200
+ type: e.type,
201
+ payload: e.payload,
202
+ runId: e.runId,
203
+ createdAt: new Date(e.createdAt).toISOString(),
204
+ }));
205
+ return snapshotOf(db, { orgId, conversationId, runId }, conv, agentVersion, events);
206
+ }
154
207
  /**
155
208
  * Reads a stored snapshot (`eval_cases.snapshot`): each version's definition goes through
156
209
  * `normalizeStoredDefinition` (missing turned-off lists read as empty). Other fields as they are.
@@ -45,9 +45,10 @@ export declare const EVAL_REPLAY_HOOKS: unique symbol;
45
45
  /**
46
46
  * The loop deps of a full-run replay: the run's own step deps without anything live that a replay
47
47
  * must never trigger, then the replay's overrides. Removed: plugin hooks (P-18), sub-agent and
48
- * compaction progress on a live stream, fork dispatch (run-replay passes the recorded reports) and
49
- * the live permission context recorder (permission context replay spec B4): a replay gets only the
50
- * recorded feeder `overrides.permissionContext`, and none at all for a recording without markers.
48
+ * compaction progress on a live stream, fork dispatch (run-replay passes the recorded reports), the
49
+ * in-context summary's live snapshot and the live permission context recorder (permission context
50
+ * replay spec B4): a replay gets only the recorded feeder `overrides.permissionContext`, and none
51
+ * at all for a recording without markers.
51
52
  */
52
53
  export declare function replayLoopDeps(stepDeps: LoopDeps, overrides: Parameters<RunReplayDeps["loop"]>[0]): LoopDeps;
53
54
  export declare class EvalWorker {
@@ -73,14 +73,18 @@ const isPluginUnloaded = (err) => err instanceof ExtensionUnloadedError ||
73
73
  /**
74
74
  * The loop deps of a full-run replay: the run's own step deps without anything live that a replay
75
75
  * must never trigger, then the replay's overrides. Removed: plugin hooks (P-18), sub-agent and
76
- * compaction progress on a live stream, fork dispatch (run-replay passes the recorded reports) and
77
- * the live permission context recorder (permission context replay spec B4): a replay gets only the
78
- * recorded feeder `overrides.permissionContext`, and none at all for a recording without markers.
76
+ * compaction progress on a live stream, fork dispatch (run-replay passes the recorded reports), the
77
+ * in-context summary's live snapshot and the live permission context recorder (permission context
78
+ * replay spec B4): a replay gets only the recorded feeder `overrides.permissionContext`, and none
79
+ * at all for a recording without markers.
79
80
  */
80
81
  export function replayLoopDeps(stepDeps, overrides) {
81
82
  const { db: _snapshot, hooks: _noHooks, subagentProgress: _noProgress, compactionProgress: _noCompactionProgress, skillForks: _noForks, permissionContext: _noLivePermissionContext,
82
83
  // a replay never reads a device for a streaming Write's base
83
- writeBase: _noWriteBase, ...replayDeps } = stepDeps;
84
+ writeBase: _noWriteBase,
85
+ // a replayed compaction summarizes the transcript (idle compaction spec §9.4): the replay
86
+ // conversation has no live snapshot of its own
87
+ liveSnapshot: _noLiveSnapshot, ...replayDeps } = stepDeps;
84
88
  // the object rest above copied `db` as a value: read it through the step deps' getter
85
89
  // instead, so the loop always resolves the context-aware handle
86
90
  return {
@@ -2,8 +2,9 @@ import { type DroppedUiContribution, type ExtensionManifest, type ExtensionPoint
2
2
  import type { Redis } from "ioredis";
3
3
  import type { core } from "zod";
4
4
  import type { KernelAppOptions } from "../app.js";
5
+ import { TRIGGER_EVENTS_BACKEND } from "../automations/events/token.js";
5
6
  import type { BusSubscriber } from "../ctx/bus.js";
6
- import { type DeviceAccessBackend, type Route } from "../ctx/create-ctx.js";
7
+ import { type DeviceAccessBackend, type Route, type TriggersBackend } from "../ctx/create-ctx.js";
7
8
  import { type ExtensionNetSeams } from "../ctx/net.js";
8
9
  import type { Keyring } from "../ctx/secrets.js";
9
10
  import { DEVICE_ACCESS_BACKEND } from "../device-access/token.js";
@@ -19,7 +20,7 @@ import { OrgNetworkAllowances } from "../orgs/network-allowances.service.js";
19
20
  import { DeviceReports } from "../sandbox/device-reports.js";
20
21
  import { ShareLiveness } from "../shares/liveness.js";
21
22
  import { EmbedTokens } from "../ui/embed-token.js";
22
- import type { UiActionHandler, UiRender } from "../ui/registry.js";
23
+ import type { UiActionHandler, UiQueryHandler, UiRender } from "../ui/registry.js";
23
24
  import { ExtensionApprovals, type PendingExtension } from "./approvals.js";
24
25
  import { deploymentConfigHash } from "./config-hash.js";
25
26
  import { EffectiveConfigs } from "./effective-config.js";
@@ -45,6 +46,8 @@ export interface LoadedUiContribution {
45
46
  after?: string;
46
47
  render?: UiRender;
47
48
  action?: UiActionHandler;
49
+ /** A component's `ctx.ui.query` handler. */
50
+ query?: UiQueryHandler;
48
51
  }
49
52
  export type { ExtensionPointEntry } from "./registry.js";
50
53
  /** One item of {@link ExtensionHost.inspect}. */
@@ -288,11 +291,15 @@ export declare class ExtensionHost {
288
291
  * of use: its module imports the sandbox, devices and tools modules, which import this one (a
289
292
  * module cycle otherwise).
290
293
  * Absent (a hand-built host) or not found (the CLI): `ctx.deviceAccess` calls are refused.
294
+ * `TriggerEventsService` (`ctx.triggers`, {@link TRIGGER_EVENTS_BACKEND}) likewise.
291
295
  */
292
296
  modules?: {
293
297
  get(token: typeof DEVICE_ACCESS_BACKEND, opts: {
294
298
  strict: false;
295
299
  }): DeviceAccessBackend;
300
+ get(token: typeof TRIGGER_EVENTS_BACKEND, opts: {
301
+ strict: false;
302
+ }): TriggersBackend;
296
303
  },
297
304
  /** Tests only: `ctx.net`'s DNS and dispatcher seams (`EXTENSION_NET_SEAMS`). */
298
305
  netSeams?: ExtensionNetSeams);
@@ -14,6 +14,7 @@ import { fileURLToPath, pathToFileURL } from "node:url";
14
14
  import { EXTENSION_POINT_CARDINALITY, parseExtensionPoint, SDK_VERSION, } from "@capybara-hq/plugin-sdk";
15
15
  import { Inject, Injectable, Optional } from "@nestjs/common";
16
16
  import { ModuleRef } from "@nestjs/core";
17
+ import { TRIGGER_EVENTS_BACKEND } from "../automations/events/token.js";
17
18
  import { changedPaths, configFields, secretValues, unreachableSecrets } from "../config/fields.js";
18
19
  import { pluginSchemaName, queryEnabledPlugins, } from "../ctx/create-ctx.js";
19
20
  import { EXTENSION_NET_SEAMS } from "../ctx/net.js";
@@ -434,6 +435,7 @@ let ExtensionHost = class ExtensionHost {
434
435
  * of use: its module imports the sandbox, devices and tools modules, which import this one (a
435
436
  * module cycle otherwise).
436
437
  * Absent (a hand-built host) or not found (the CLI): `ctx.deviceAccess` calls are refused.
438
+ * `TriggerEventsService` (`ctx.triggers`, {@link TRIGGER_EVENTS_BACKEND}) likewise.
437
439
  */
438
440
  modules,
439
441
  /** Tests only: `ctx.net`'s DNS and dispatcher seams (`EXTENSION_NET_SEAMS`). */
@@ -480,6 +482,14 @@ let ExtensionHost = class ExtensionHost {
480
482
  return undefined;
481
483
  }
482
484
  },
485
+ triggers: () => {
486
+ try {
487
+ return modules?.get(TRIGGER_EVENTS_BACKEND, { strict: false });
488
+ }
489
+ catch {
490
+ return undefined;
491
+ }
492
+ },
483
493
  locks,
484
494
  runWorkers: c.roles.includes("worker"),
485
495
  log,
@@ -2152,6 +2162,7 @@ let ExtensionHost = class ExtensionHost {
2152
2162
  const served = c.kind === "view" || c.kind === "component";
2153
2163
  const render = served ? i.uiViews.get(c.id) : undefined;
2154
2164
  const action = served ? i.uiActions.get(c.id) : undefined;
2165
+ const query = c.kind === "component" ? i.uiQueries.get(c.id) : undefined;
2155
2166
  return {
2156
2167
  plugin: i.name,
2157
2168
  contribution: c,
@@ -2159,6 +2170,7 @@ let ExtensionHost = class ExtensionHost {
2159
2170
  ...(after !== undefined && { after }),
2160
2171
  ...(render !== undefined && { render }),
2161
2172
  ...(action !== undefined && { action }),
2173
+ ...(query !== undefined && { query }),
2162
2174
  };
2163
2175
  }));
2164
2176
  }
@@ -1,6 +1,6 @@
1
1
  import { type DroppedUiContribution, type ExtensionManifest, type ExtensionPointRef, type ResolvedUiContribution, type StaticExtensionManifest } from "@capybara-hq/plugin-sdk";
2
2
  import { type ExtensionPointAccess, type KernelDeps, type KernelExtensionContext, LiveConfig, type RegisteredSetupCheck, type RegisteredTool, type Route } from "../ctx/create-ctx.js";
3
- import type { UiActionHandler, UiRender } from "../ui/registry.js";
3
+ import type { UiActionHandler, UiQueryHandler, UiRender } from "../ui/registry.js";
4
4
  import type { RegisteredHook } from "./hooks.js";
5
5
  import { InflightTracker } from "./inflight.js";
6
6
  import type { Registration } from "./ledger.js";
@@ -77,6 +77,8 @@ export declare class ExtensionInstance {
77
77
  get hooks(): readonly RegisteredHook[];
78
78
  get uiViews(): ReadonlyMap<string, UiRender>;
79
79
  get uiActions(): ReadonlyMap<string, UiActionHandler>;
80
+ /** Query handlers registered through `ctx.ui.query` (empty after revocation). */
81
+ get uiQueries(): ReadonlyMap<string, UiQueryHandler>;
80
82
  /** Setup checks registered through `ctx.setup.check` (empty after revocation). */
81
83
  get setupChecks(): ReadonlyMap<string, RegisteredSetupCheck>;
82
84
  /** The instance's `ctx.signal`: aborted when it is revoked or disposed. */
@@ -127,6 +127,10 @@ export class ExtensionInstance {
127
127
  get uiActions() {
128
128
  return this.ctx.uiActions;
129
129
  }
130
+ /** Query handlers registered through `ctx.ui.query` (empty after revocation). */
131
+ get uiQueries() {
132
+ return this.ctx.uiQueries;
133
+ }
130
134
  /** Setup checks registered through `ctx.setup.check` (empty after revocation). */
131
135
  get setupChecks() {
132
136
  return this.ctx.setupChecks;
@@ -1,5 +1,5 @@
1
1
  /** 插件经 ctx 做的一项登记的种类(C17)。 */
2
- export type RegistrationKind = "tool" | "route" | "queue" | "bus" | "lease" | "ui.view" | "ui.action" | "provide" | "hook" | "setup.check";
2
+ export type RegistrationKind = "tool" | "route" | "queue" | "bus" | "lease" | "ui.view" | "ui.action" | "ui.query" | "provide" | "hook" | "setup.check";
3
3
  /** 账上的一项:撤销时调用 `dispose()`。 */
4
4
  export interface Registration {
5
5
  kind: RegistrationKind;
@@ -78,6 +78,14 @@ export interface PermissionSet {
78
78
  deviceAccess?: {
79
79
  services: string[];
80
80
  };
81
+ /**
82
+ * The event types the extension may emit (`permissions.triggers.emit`, collaboration spec
83
+ * §4.2): one blocking key per type, so an upgrade adding a type waits for approval. Absent
84
+ * when not declared.
85
+ */
86
+ triggers?: {
87
+ emit: string[];
88
+ };
81
89
  };
82
90
  /**
83
91
  * 安装记录包迁移警告的摘要(`warningsDigest`,Ruling P4);没有警告或不是安装记录时省略。
@@ -125,7 +133,8 @@ export declare function buildPermissionSet(input: {
125
133
  * `config.deployment.secret:apiKey`, `table:todos`, `permissions.tools:write`,
126
134
  * `permissions.http.<access>:<METHOD> <path>` (`permissions.http.public:POST /events`),
127
135
  * `ui.view:tasks`, `ui.embed:board`, `permissions.client`, `ui.component:hud`,
128
- * `permissions.dialin:capybara-device/6`, `permissions.deviceaccess:browser`.
136
+ * `permissions.dialin:capybara-device/6`, `permissions.deviceaccess:browser`,
137
+ * `permissions.triggers:item.created`.
129
138
  * Tolerates old snapshots missing fields (read as empty), so format changes never throw.
130
139
  */
131
140
  export declare function permissionKeys(set: PermissionSet): string[];
@@ -150,6 +159,13 @@ export declare const DIAL_IN_KEY_PREFIX = "permissions.dialin:";
150
159
  * catalog permission keys require (`PERMISSION_KEY_RE`).
151
160
  */
152
161
  export declare const DEVICE_ACCESS_KEY_PREFIX = "permissions.deviceaccess:";
162
+ /**
163
+ * Key prefix of an event type the extension emits (`permissions.triggers.emit`): blocking, not
164
+ * sensitive (an event only reaches automations an org built on it, collaboration spec §4.2).
165
+ * Lower-case letters and dots before the colon, as catalog permission keys require
166
+ * (`PERMISSION_KEY_RE`).
167
+ */
168
+ export declare const TRIGGERS_KEY_PREFIX = "permissions.triggers:";
153
169
  /** Key prefix of a client component (`ui.component:<id>`): sensitive and blocking. */
154
170
  export declare const UI_COMPONENT_KEY_PREFIX = "ui.component:";
155
171
  /** 渲染 schema 视图的权限键前缀:记入快照但不卡加载(见 {@link blockingKeys})。 */
@@ -121,6 +121,8 @@ export function buildPermissionSet(input) {
121
121
  ...(p.deviceAccess
122
122
  ? { deviceAccess: { services: sortedUnique(p.deviceAccess.services) } }
123
123
  : {}),
124
+ // only when declared, likewise
125
+ ...(p.triggers ? { triggers: { emit: sortedUnique(p.triggers.emit) } } : {}),
124
126
  },
125
127
  ...(input.warningsDigest ? { warningsDigest: input.warningsDigest } : {}),
126
128
  };
@@ -130,7 +132,8 @@ export function buildPermissionSet(input) {
130
132
  * `config.deployment.secret:apiKey`, `table:todos`, `permissions.tools:write`,
131
133
  * `permissions.http.<access>:<METHOD> <path>` (`permissions.http.public:POST /events`),
132
134
  * `ui.view:tasks`, `ui.embed:board`, `permissions.client`, `ui.component:hud`,
133
- * `permissions.dialin:capybara-device/6`, `permissions.deviceaccess:browser`.
135
+ * `permissions.dialin:capybara-device/6`, `permissions.deviceaccess:browser`,
136
+ * `permissions.triggers:item.created`.
134
137
  * Tolerates old snapshots missing fields (read as empty), so format changes never throw.
135
138
  */
136
139
  export function permissionKeys(set) {
@@ -181,6 +184,8 @@ export function permissionKeys(set) {
181
184
  keys.push(`${DIAL_IN_KEY_PREFIX}${p.dialIn.protocol}`);
182
185
  for (const svc of p.deviceAccess?.services ?? [])
183
186
  keys.push(`${DEVICE_ACCESS_KEY_PREFIX}${svc}`);
187
+ for (const t of p.triggers?.emit ?? [])
188
+ keys.push(`${TRIGGERS_KEY_PREFIX}${t}`);
184
189
  if (s.warningsDigest)
185
190
  keys.push(`${WARNINGS_KEY_PREFIX}${s.warningsDigest}`);
186
191
  return sortedUnique(keys);
@@ -206,6 +211,13 @@ export const DIAL_IN_KEY_PREFIX = "permissions.dialin:";
206
211
  * catalog permission keys require (`PERMISSION_KEY_RE`).
207
212
  */
208
213
  export const DEVICE_ACCESS_KEY_PREFIX = "permissions.deviceaccess:";
214
+ /**
215
+ * Key prefix of an event type the extension emits (`permissions.triggers.emit`): blocking, not
216
+ * sensitive (an event only reaches automations an org built on it, collaboration spec §4.2).
217
+ * Lower-case letters and dots before the colon, as catalog permission keys require
218
+ * (`PERMISSION_KEY_RE`).
219
+ */
220
+ export const TRIGGERS_KEY_PREFIX = "permissions.triggers:";
209
221
  /** Key prefix of a client component (`ui.component:<id>`): sensitive and blocking. */
210
222
  export const UI_COMPONENT_KEY_PREFIX = "ui.component:";
211
223
  /** 渲染 schema 视图的权限键前缀:记入快照但不卡加载(见 {@link blockingKeys})。 */
@@ -13,7 +13,7 @@ import type { ExtensionSource } from "./sources.js";
13
13
  export declare function reviewHash(set: PermissionSet, warnings?: readonly PackageWarning[]): string;
14
14
  /** 权限清单展示用的一组:按类别分组,`sensitive` 标出需要管理员特别留意的类别。 */
15
15
  export interface PermissionGroup {
16
- category: "provides" | "requires" | "optional" | "config" | "tables" | "secrets" | "storage" | "http" | "publicRoutes" | "embedRoutes" | "tools" | "hooks" | "models" | "network" | "ui" | "components" | "client" | "dialIn" | "deviceAccess";
16
+ category: "provides" | "requires" | "optional" | "config" | "tables" | "secrets" | "storage" | "http" | "publicRoutes" | "embedRoutes" | "tools" | "hooks" | "models" | "network" | "ui" | "components" | "client" | "dialIn" | "deviceAccess" | "triggers";
17
17
  /**
18
18
  * Sensitive category: secrets, public routes, tools, hooks, client components, client code,
19
19
  * device services; also
@@ -1,7 +1,7 @@
1
1
  import { createHash } from "node:crypto";
2
2
  import { pluginSchemaName } from "../ctx/create-ctx.js";
3
3
  import { isDestructiveSql, splitSqlStatements } from "../db/sql-statements.js";
4
- import { CLIENT_KEY, DEVICE_ACCESS_KEY_PREFIX, DIAL_IN_KEY_PREFIX, permissionKeys, UI_COMPONENT_KEY_PREFIX, WARNINGS_KEY_PREFIX, } from "./permission-set.js";
4
+ import { CLIENT_KEY, DEVICE_ACCESS_KEY_PREFIX, DIAL_IN_KEY_PREFIX, permissionKeys, TRIGGERS_KEY_PREFIX, UI_COMPONENT_KEY_PREFIX, WARNINGS_KEY_PREFIX, } from "./permission-set.js";
5
5
  /**
6
6
  * Review digest: the first 16 hex digits of `sha256(permissionKeys(set).join("\n"))`; with migration
7
7
  * warnings their digest (kind, file, line and statement) is folded in, without warnings it equals the
@@ -109,6 +109,7 @@ function keyItem(key) {
109
109
  ["ui.view:", "ui", "view:"],
110
110
  [DIAL_IN_KEY_PREFIX, "dialIn", ""],
111
111
  [DEVICE_ACCESS_KEY_PREFIX, "deviceAccess", ""],
112
+ [TRIGGERS_KEY_PREFIX, "triggers", ""],
112
113
  ];
113
114
  for (const [prefix, category, itemPrefix] of table) {
114
115
  const rest = after(prefix);
@@ -188,6 +189,8 @@ export function permissionGroups(set) {
188
189
  { category: "dialIn", items: p.dialIn ? [p.dialIn.protocol] : [] },
189
190
  // long-lived services the extension runs in conversations' devices
190
191
  { category: "deviceAccess", items: p.deviceAccess?.services ?? [] },
192
+ // the event types it emits for the orgs' event automations (not sensitive)
193
+ { category: "triggers", items: p.triggers?.emit ?? [] },
191
194
  ];
192
195
  return groups
193
196
  .filter((g) => g.items.length > 0)
@@ -0,0 +1,124 @@
1
+ import { KernelDb } from "../infra/database/kernel-db.js";
2
+ import { TransactionHost } from "../infra/database/transaction-host.js";
3
+ import { OutboxService } from "../infra/outbox/outbox.service.js";
4
+ import type { KernelLogger } from "../log.js";
5
+ import { StorageService } from "../storage/storage.service.js";
6
+ /**
7
+ * Blob and staging objects of the file library (file library spec §1, §3 and its builder
8
+ * amendment), all relative to the org's kernel prefix (`kernel/<orgId>/`): every blob the kernel
9
+ * writes is `blobs/<blobId>` (a key no upload form can write; a delivery's bytes and a finalized
10
+ * upload's verified copy alike), and an upload stages at `uploads/<fileId>` (a migrated upload kept
11
+ * its old key in `files.staging_key`). A staging object is never a blob. Deleting either kind is
12
+ * owed through the outbox by the transaction that stops using it; the handlers re-read the rows.
13
+ */
14
+ /** The object key of a blob the kernel writes, relative to the org prefix. */
15
+ export declare const blobObjectKey: (blobId: string) => string;
16
+ /** The staging key a new upload is presigned to, relative to the org prefix. */
17
+ export declare const stagingObjectKey: (fileId: string) => string;
18
+ /**
19
+ * How long a presigned upload form stays valid (seconds). Within it the uploader can write the
20
+ * staging object again; finalize copies the verified bytes to a kernel-owned key, so that only
21
+ * ever changes the uploader's own staging object.
22
+ */
23
+ export declare const FILE_UPLOAD_TTL_SECONDS = 300;
24
+ /** When an owed deletion of a file's staging object may run: after its upload form expired. */
25
+ export declare function afterUploadForm(fileCreatedAt: Date): Date | undefined;
26
+ /** The maintenance job that deletes one blob in `deleting` status (its object, then its row). */
27
+ export declare const BLOB_DELETE_JOB = "blob-delete";
28
+ /** The maintenance job that deletes one upload's staging object no blob adopted. */
29
+ export declare const FILE_STAGING_DELETE_JOB = "file-staging-delete";
30
+ /**
31
+ * The maintenance job that releases what a dropped upload held (a discard, the draft cleanup): its
32
+ * staging object, or its blob when nothing else points at it. Deferred and owed for every dropped
33
+ * upload alike, so the request that drops it does the same work whatever the org holds.
34
+ */
35
+ export declare const FILE_RELEASE_JOB = "file-release";
36
+ /** Deterministic outbox / BullMQ id of a dropped upload's release (no `:`). */
37
+ export declare const fileReleaseJobId: (fileId: string) => string;
38
+ /**
39
+ * How long after now a deferred job owed by a request runs: never due within the request, so no
40
+ * outbox fast path runs while the caller waits (its timing would depend on what the job found).
41
+ */
42
+ export declare const DEFERRED_JOB_DELAY_MS = 60000;
43
+ /** The run time of a job a request owes: {@link DEFERRED_JOB_DELAY_MS} from now at the earliest. */
44
+ export declare function deferred(at?: Date): Date;
45
+ /** Deterministic outbox / BullMQ id of a blob's deletion (no `:`). */
46
+ export declare const blobDeleteJobId: (blobId: string) => string;
47
+ /** Deterministic outbox / BullMQ id of a staging object's deletion (no `:`). */
48
+ export declare const fileStagingDeleteJobId: (fileId: string) => string;
49
+ /** The data of a {@link BLOB_DELETE_JOB}. */
50
+ export interface BlobDeleteData {
51
+ orgId: string;
52
+ blobId: string;
53
+ }
54
+ /** The data of a {@link FILE_RELEASE_JOB}. */
55
+ export interface FileReleaseData {
56
+ orgId: string;
57
+ fileId: string;
58
+ }
59
+ /** The data of a {@link FILE_STAGING_DELETE_JOB}. */
60
+ export interface FileStagingDeleteData {
61
+ orgId: string;
62
+ fileId: string;
63
+ objectKey: string;
64
+ }
65
+ /** Owes the deletion of a blob already set to `deleting`, in the caller's transaction. */
66
+ export declare function oweBlobDelete(outbox: Pick<OutboxService, "add">, orgId: string, blobId: string, runAt?: Date): Promise<void>;
67
+ /** Owes the deferred release of a dropped upload, in the caller's transaction. */
68
+ export declare function oweFileRelease(outbox: Pick<OutboxService, "add">, orgId: string, fileId: string, runAt: Date): Promise<void>;
69
+ /** Owes the deletion of a file's staging object, in the caller's transaction. */
70
+ export declare function oweStagingDelete(outbox: Pick<OutboxService, "add">, orgId: string, fileId: string, objectKey: string, runAt?: Date): Promise<void>;
71
+ /**
72
+ * Runs the {@link BLOB_DELETE_JOB} and {@link FILE_STAGING_DELETE_JOB} jobs (the maintenance
73
+ * processor dispatches them here). Delivered twice, each is harmless: deleting a missing object is
74
+ * a no-op and the rows are read again first.
75
+ *
76
+ * - A staging object is deleted only when the key is the file's own staging key, the file is no
77
+ * longer an upload in progress, and no blob of the org names that key (a blob adopted it).
78
+ * - A blob is deleted only while its row is `deleting` and no file or share points at it, checked
79
+ * under `FOR UPDATE` on the blob row, which the same transaction sets `gone` (so nothing, the
80
+ * blob sweep's restore included, ever takes it for live bytes again); then its object goes, then
81
+ * its row. A retry after a failed object delete finds it `gone` and goes on (references checked
82
+ * again). The invariant that
83
+ * makes the check final: every transaction that inserts or moves a reference to a blob (a file
84
+ * row, a share, a repoint) first calls `BlobsService.lockReady`, which locks the blob `FOR SHARE`
85
+ * and requires `ready`, so once a `deleting` blob is seen unreferenced under the lock, nothing can
86
+ * point at it again. A blob still referenced is left alone and logged: nothing turns a
87
+ * referenced blob into `deleting`, so that is a bug to look at, never bytes to drop.
88
+ */
89
+ export declare class BlobObjects {
90
+ private readonly db;
91
+ readonly txHost: TransactionHost;
92
+ private readonly storage;
93
+ private readonly outbox;
94
+ private readonly log;
95
+ constructor(db: KernelDb, txHost: TransactionHost, storage: Pick<StorageService, "kernel">, outbox: Pick<OutboxService, "add">, log: Pick<KernelLogger, "warn">);
96
+ /**
97
+ * Releases what a dropped (`deleted`) upload held: without a blob, its staging object (as
98
+ * {@link deleteStaging} does); with one, the blob when no other file or share points at it,
99
+ * checked under `FOR UPDATE` on the blob (a new reference passes `BlobsService.lockReady`, so it
100
+ * either committed first and is seen, or finds the blob `deleting`): the file lets go of it, the
101
+ * blob becomes `deleting` and its deletion is owed. A file not `deleted` is left alone.
102
+ */
103
+ releaseFile(data: FileReleaseData): Promise<void>;
104
+ /**
105
+ * The transaction of {@link releaseFile}: the staging key to delete when the file has no blob,
106
+ * else null (the blob released, or kept because something else points at it).
107
+ */
108
+ releaseBlob(data: FileReleaseData): Promise<string | null>;
109
+ /** Deletes one staging object; see the class comment. */
110
+ deleteStaging(data: FileStagingDeleteData): Promise<void>;
111
+ /** Deletes one `deleting` blob, its object first; see the class comment. */
112
+ deleteBlob(data: BlobDeleteData): Promise<void>;
113
+ /**
114
+ * Under `FOR UPDATE` on the blob: when it is `deleting` (or `gone`: a retry) and nothing points
115
+ * at it, sets it `gone` and returns its object key; else null (logged when it is still
116
+ * referenced).
117
+ */
118
+ claimUnreferenced(data: BlobDeleteData): Promise<string | null>;
119
+ /** The last step of {@link deleteBlob}: the row, while it is `gone` and nothing points at it. */
120
+ dropRow(data: BlobDeleteData): Promise<void>;
121
+ }
122
+ /** {@link BlobObjects} for the maintenance worker (storage and the database only). */
123
+ export declare class BlobObjectsModule {
124
+ }