@capybara-hq/kernel 0.1.0-rc.142 → 0.1.0-rc.144

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 (238) hide show
  1. package/dist/admin/admin-agents.controller.d.ts +3 -5
  2. package/dist/admin/admin-agents.controller.js +1 -1
  3. package/dist/admin/admin-connectors.controller.d.ts +3 -5
  4. package/dist/admin/admin-connectors.controller.js +1 -1
  5. package/dist/admin/admin-items.schemas.d.ts +6 -6
  6. package/dist/admin/admin-items.schemas.js +5 -9
  7. package/dist/admin/admin.controller.d.ts +18 -12
  8. package/dist/admin/admin.controller.js +29 -15
  9. package/dist/admin/admin.schemas.d.ts +12 -3
  10. package/dist/admin/admin.schemas.js +17 -6
  11. package/dist/agents/admin-agents.d.ts +10 -8
  12. package/dist/agents/admin-agents.js +13 -9
  13. package/dist/agents/agents.module.js +3 -0
  14. package/dist/agents/agents.service.js +1 -1
  15. package/dist/agents/org-templates.d.ts +3 -1
  16. package/dist/agents/org-templates.js +7 -3
  17. package/dist/agents/pending-connector-requests.d.ts +10 -4
  18. package/dist/agents/pending-connector-requests.js +29 -7
  19. package/dist/automations/automations.controller.d.ts +9 -5
  20. package/dist/automations/automations.controller.js +21 -4
  21. package/dist/automations/automations.schemas.d.ts +19 -0
  22. package/dist/automations/automations.schemas.js +9 -0
  23. package/dist/automations/automations.service.d.ts +25 -8
  24. package/dist/automations/automations.service.js +40 -34
  25. package/dist/automations/events/acceptance.d.ts +6 -1
  26. package/dist/automations/events/acceptance.js +30 -11
  27. package/dist/automations/store.d.ts +17 -0
  28. package/dist/automations/store.js +35 -0
  29. package/dist/catalog/admin-catalog.controller.d.ts +64 -2
  30. package/dist/catalog/admin-catalog.controller.js +17 -0
  31. package/dist/catalog/catalog-import.module.js +3 -0
  32. package/dist/catalog/catalog-scope.service.d.ts +3 -1
  33. package/dist/catalog/catalog-scope.service.js +11 -7
  34. package/dist/catalog/catalog.module.js +3 -0
  35. package/dist/catalog/catalog.service.d.ts +3 -1
  36. package/dist/catalog/catalog.service.js +8 -4
  37. package/dist/catalog/cli.js +2 -2
  38. package/dist/catalog/component-promotion.d.ts +3 -1
  39. package/dist/catalog/component-promotion.js +7 -3
  40. package/dist/catalog/component-scope.service.d.ts +3 -1
  41. package/dist/catalog/component-scope.service.js +7 -3
  42. package/dist/catalog/enable-requests.d.ts +10 -8
  43. package/dist/catalog/enable-requests.js +40 -21
  44. package/dist/catalog/marketplaces.service.d.ts +1 -1
  45. package/dist/catalog/owned-items.d.ts +3 -1
  46. package/dist/catalog/owned-items.js +13 -9
  47. package/dist/catalog/platform-components.d.ts +6 -1
  48. package/dist/catalog/platform-components.js +9 -3
  49. package/dist/catalog/plugin-connectors.d.ts +8 -4
  50. package/dist/catalog/plugin-connectors.js +12 -6
  51. package/dist/catalog/plugin-import.d.ts +3 -1
  52. package/dist/catalog/plugin-import.js +14 -5
  53. package/dist/catalog/plugin-install.d.ts +3 -1
  54. package/dist/catalog/plugin-install.js +8 -4
  55. package/dist/catalog/plugin-package.js +2 -1
  56. package/dist/catalog/plugin-upgrade.d.ts +3 -1
  57. package/dist/catalog/plugin-upgrade.js +8 -4
  58. package/dist/catalog/request-hints.d.ts +19 -0
  59. package/dist/catalog/request-hints.js +34 -0
  60. package/dist/catalog/request-rules.d.ts +9 -5
  61. package/dist/catalog/request-rules.js +16 -9
  62. package/dist/catalog/requests.service.d.ts +3 -1
  63. package/dist/catalog/requests.service.js +28 -9
  64. package/dist/catalog/scope-orgs.d.ts +2 -1
  65. package/dist/catalog/scope-orgs.js +2 -2
  66. package/dist/catalog/scope-sync.d.ts +3 -1
  67. package/dist/catalog/scope-sync.js +12 -2
  68. package/dist/catalog/scope-writer.d.ts +6 -3
  69. package/dist/catalog/scope-writer.js +28 -10
  70. package/dist/catalog/unshare.d.ts +3 -2
  71. package/dist/catalog/unshare.js +4 -4
  72. package/dist/client/client-access.service.js +29 -1
  73. package/dist/config/schema.d.ts +12 -0
  74. package/dist/config/schema.js +56 -0
  75. package/dist/ctx/create-ctx.d.ts +2 -19
  76. package/dist/ctx/create-ctx.js +3 -93
  77. package/dist/ctx/durable-relay.d.ts +2 -5
  78. package/dist/ctx/durable-relay.js +56 -29
  79. package/dist/db/extension-handoff-schema.js +5 -0
  80. package/dist/db/kernel-schema.d.ts +74 -0
  81. package/dist/db/migrator.js +36 -0
  82. package/dist/erasure/account-batches.js +2 -0
  83. package/dist/erasure/account-residual.js +1 -0
  84. package/dist/erasure/org-catalog.js +8 -3
  85. package/dist/erasure/org-rules.js +1 -0
  86. package/dist/evals/evals.schemas.d.ts +15 -5
  87. package/dist/evals/evals.schemas.js +17 -10
  88. package/dist/evals/runs.controller.d.ts +4 -12
  89. package/dist/evals/runs.controller.js +14 -11
  90. package/dist/evals/runs.service.d.ts +29 -25
  91. package/dist/evals/runs.service.js +73 -61
  92. package/dist/evals/trajectory.controller.d.ts +10 -6
  93. package/dist/evals/trajectory.controller.js +11 -4
  94. package/dist/evals/trajectory.service.d.ts +17 -9
  95. package/dist/evals/trajectory.service.js +52 -35
  96. package/dist/extensions/admin-ops.d.ts +6 -1
  97. package/dist/extensions/admin-ops.js +21 -7
  98. package/dist/extensions/blobs.d.ts +2 -0
  99. package/dist/extensions/blobs.js +11 -0
  100. package/dist/extensions/deployment-config.d.ts +6 -1
  101. package/dist/extensions/deployment-config.js +13 -2
  102. package/dist/extensions/enabled.d.ts +5 -0
  103. package/dist/extensions/extensions.module.js +3 -0
  104. package/dist/extensions/grant-epoch.d.ts +108 -0
  105. package/dist/extensions/grant-epoch.js +214 -0
  106. package/dist/extensions/host.d.ts +29 -9
  107. package/dist/extensions/host.js +148 -42
  108. package/dist/extensions/instance.d.ts +3 -3
  109. package/dist/extensions/instance.js +1 -1
  110. package/dist/extensions/isolated/authorization.d.ts +54 -2
  111. package/dist/extensions/isolated/authorization.js +148 -35
  112. package/dist/extensions/isolated/child-session.js +0 -1
  113. package/dist/extensions/isolated/revision.js +1 -1
  114. package/dist/extensions/org-config.d.ts +3 -1
  115. package/dist/extensions/org-config.js +13 -4
  116. package/dist/extensions/org-overrides.d.ts +6 -1
  117. package/dist/extensions/org-overrides.js +13 -2
  118. package/dist/extensions/package-digest.job.d.ts +34 -0
  119. package/dist/extensions/package-digest.job.js +121 -0
  120. package/dist/extensions/package.js +10 -6
  121. package/dist/extensions/permission-set.d.ts +14 -78
  122. package/dist/extensions/permission-set.js +17 -143
  123. package/dist/extensions/permission-view.d.ts +13 -1
  124. package/dist/extensions/permission-view.js +20 -0
  125. package/dist/extensions/registry.js +4 -1
  126. package/dist/extensions/resolve.d.ts +7 -8
  127. package/dist/extensions/resolve.js +7 -8
  128. package/dist/extensions/revision-approvals.d.ts +167 -0
  129. package/dist/extensions/revision-approvals.js +353 -0
  130. package/dist/extensions/revision-grants.d.ts +197 -0
  131. package/dist/extensions/revision-grants.js +584 -0
  132. package/dist/extensions/state.module.js +12 -1
  133. package/dist/identity/accounts.d.ts +10 -4
  134. package/dist/identity/accounts.js +18 -5
  135. package/dist/inbox/inbox-items.service.d.ts +6 -1
  136. package/dist/inbox/inbox-items.service.js +29 -10
  137. package/dist/inbox/inbox.module.js +3 -0
  138. package/dist/inbox/inbox.service.d.ts +3 -1
  139. package/dist/inbox/inbox.service.js +9 -2
  140. package/dist/inbox/org-notices.d.ts +4 -3
  141. package/dist/inbox/org-notices.js +9 -6
  142. package/dist/inbox/platform-inbox.service.d.ts +3 -1
  143. package/dist/inbox/platform-inbox.service.js +11 -3
  144. package/dist/inbox/platform-notices.d.ts +3 -2
  145. package/dist/inbox/platform-notices.js +10 -4
  146. package/dist/infra/config/kernel-config.service.js +4 -1
  147. package/dist/infra/database/extension-effect-key-lock.js +7 -0
  148. package/dist/infra/paging/paged-read.d.ts +34 -4
  149. package/dist/infra/paging/paged-read.js +38 -1
  150. package/dist/invalidation/audiences.d.ts +32 -0
  151. package/dist/invalidation/audiences.js +43 -0
  152. package/dist/invalidation/hints.d.ts +6 -0
  153. package/dist/invalidation/hints.js +7 -1
  154. package/dist/invalidation/invalidation-hints.d.ts +12 -1
  155. package/dist/invalidation/invalidation-hints.js +46 -5
  156. package/dist/invalidation/invalidation-hints.module.d.ts +2 -0
  157. package/dist/invalidation/invalidation-hints.module.js +4 -1
  158. package/dist/invalidation/me-stream.d.ts +1 -11
  159. package/dist/invalidation/me-stream.js +12 -41
  160. package/dist/invalidation/org-intent-bridge.d.ts +18 -0
  161. package/dist/invalidation/org-intent-bridge.js +46 -0
  162. package/dist/models/enablement.d.ts +3 -1
  163. package/dist/models/enablement.js +25 -5
  164. package/dist/orgs/invitations.controller.d.ts +4 -7
  165. package/dist/orgs/invitations.controller.js +8 -5
  166. package/dist/orgs/invitations.service.d.ts +17 -3
  167. package/dist/orgs/invitations.service.js +35 -13
  168. package/dist/orgs/members.service.d.ts +35 -0
  169. package/dist/orgs/members.service.js +52 -3
  170. package/dist/orgs/offboarding.d.ts +3 -1
  171. package/dist/orgs/offboarding.js +7 -3
  172. package/dist/orgs/orgs.controller.d.ts +11 -4
  173. package/dist/orgs/orgs.controller.js +25 -5
  174. package/dist/orgs/orgs.module.js +3 -0
  175. package/dist/orgs/orgs.schemas.d.ts +14 -0
  176. package/dist/orgs/orgs.schemas.js +19 -2
  177. package/dist/orgs/orgs.service.d.ts +24 -2
  178. package/dist/orgs/orgs.service.js +47 -4
  179. package/dist/orgs/security-settings.service.d.ts +14 -6
  180. package/dist/orgs/security-settings.service.js +18 -13
  181. package/dist/orgs/settings.controller.d.ts +7 -4
  182. package/dist/platform/exclusions.js +15 -0
  183. package/dist/platform/ops/accounts.ops.js +7 -16
  184. package/dist/platform/ops/admin-items.ops.js +7 -7
  185. package/dist/platform/ops/automations.ops.js +6 -4
  186. package/dist/platform/ops/evals.ops.js +30 -15
  187. package/dist/platform/ops/org-settings.ops.js +2 -2
  188. package/dist/platform/ops/orgs.ops.js +44 -27
  189. package/dist/push/delivery.d.ts +3 -1
  190. package/dist/push/delivery.js +7 -3
  191. package/dist/push/push-processor.js +8 -1
  192. package/dist/roles/worker.module.js +3 -0
  193. package/dist/runtime/step-log.d.ts +1 -1
  194. package/dist/runtime/step-log.js +5 -4
  195. package/dist/runtime/stream-limit.d.ts +13 -0
  196. package/dist/runtime/stream-limit.js +40 -0
  197. package/dist/runtime/stream.controller.d.ts +2 -0
  198. package/dist/runtime/stream.controller.js +2 -0
  199. package/dist/runtime/stream.d.ts +1 -0
  200. package/dist/runtime/stream.js +15 -6
  201. package/dist/sandbox/permission-authority.module.js +6 -1
  202. package/dist/sandbox/permission-transitions.d.ts +3 -1
  203. package/dist/sandbox/permission-transitions.js +17 -2
  204. package/dist/setup/kernel-checks.d.ts +3 -3
  205. package/dist/setup/kernel-checks.js +4 -4
  206. package/dist/setup/setup-check-registry.d.ts +16 -5
  207. package/dist/setup/setup-check-registry.js +11 -3
  208. package/dist/setup/setup-checks.service.d.ts +1 -2
  209. package/dist/setup/setup-checks.service.js +7 -6
  210. package/dist/skills/agent-skills.service.d.ts +6 -1
  211. package/dist/skills/agent-skills.service.js +12 -3
  212. package/dist/skills/changes.service.d.ts +6 -1
  213. package/dist/skills/changes.service.js +11 -3
  214. package/dist/skills/conversation-catalog.d.ts +3 -0
  215. package/dist/skills/conversation-catalog.js +2 -0
  216. package/dist/skills/skills.module.js +3 -0
  217. package/dist/skills/skills.service.d.ts +3 -1
  218. package/dist/skills/skills.service.js +8 -4
  219. package/dist/tools/admin-connectors.d.ts +10 -8
  220. package/dist/tools/admin-connectors.js +12 -10
  221. package/dist/tools/approvals.service.d.ts +12 -1
  222. package/dist/tools/approvals.service.js +36 -9
  223. package/dist/tools/builtins/automations.d.ts +1 -1
  224. package/dist/tools/builtins/automations.js +1 -1
  225. package/dist/tools/connectors.service.d.ts +3 -1
  226. package/dist/tools/connectors.service.js +29 -7
  227. package/dist/tools/tools.module.js +3 -0
  228. package/dist/ui/admin-ui.controller.d.ts +3 -1
  229. package/dist/ui/admin-ui.controller.js +3 -1
  230. package/dist/ui/ui-stream.d.ts +2 -0
  231. package/dist/ui/ui-stream.js +20 -6
  232. package/dist/ui/views.controller.d.ts +4 -2
  233. package/dist/ui/views.controller.js +4 -2
  234. package/package.json +3 -3
  235. package/src/migrations/0234_extension_grant_epoch.sql +141 -0
  236. package/src/migrations/0235_extension_revision_grants.sql +166 -0
  237. package/src/migrations/0236_paged_table_idx.sql +33 -0
  238. package/src/migrations/0237_extension_handoff_health.sql +18 -0
@@ -6,6 +6,7 @@ import { KernelConfigService } from "../infra/config/kernel-config.service.js";
6
6
  import { KernelDb } from "../infra/database/kernel-db.js";
7
7
  import { TransactionHost } from "../infra/database/transaction-host.js";
8
8
  import { LockService } from "../infra/lock/lock.service.js";
9
+ import { type Page, type Paged } from "../infra/paging/paged-read.js";
9
10
  import { PricesService } from "../models/prices.js";
10
11
  import { ModelPurposesService } from "../models/purposes.js";
11
12
  import { OrgLock } from "../orgs/org-lock.js";
@@ -133,11 +134,6 @@ export declare function caseBase(db: KernelSchemaDb, s: CaseSnapshot): Promise<{
133
134
  } | null>;
134
135
  /** 候选 agent 版本的定义(没给版本 → undefined)。 */
135
136
  export declare function versionDefinition(db: KernelSchemaDb, agentId: string, version: number | undefined): Promise<AgentDefinition | undefined>;
136
- /**
137
- * 轻量列表的 `asOf`:本次读取时数据库的当前时间往前留的余量(毫秒)。下一次轮询以它为 `updatedSince`:
138
- * 写结果的事务在读取之前开始、之后才提交时,`updated_at` 早于读取时间,留出余量才不会漏掉;重复的行由调用方按 id 合并。
139
- */
140
- export declare const RESULTS_ASOF_OVERLAP_MS = 15000;
141
137
  /**
142
138
  * 评测运行(D5、C7):估算、启动(校验候选、预建结果、每个用例入队一个任务)、查看、结果分页、取消。
143
139
  * 执行在 `evals/worker.ts`。写操作在事务里锁组织行并复核角色(`evals.manage`)。
@@ -203,36 +199,44 @@ export declare class EvalRunsService {
203
199
  private summaries;
204
200
  private static toView;
205
201
  get(orgId: string, runId: string): Promise<EvalRunView>;
206
- listForSet(orgId: string, setId: string): Promise<EvalRunView[]>;
202
+ /**
203
+ * One page of the set's runs, newest first (`(created_at, id)` descending), by page number on a
204
+ * snapshot (table pagination spec §2.3). Runs are only appended and their sort key never
205
+ * changes, but their ids are random, so the snapshot is a point in time: `asOf` is the database
206
+ * time of the first read, a page lists the runs created at or before it, and later runs count in
207
+ * `newer`. Known caveat (as the audit log's): a run whose transaction started before the
208
+ * snapshot and commits after it may appear inside the snapshot.
209
+ */
210
+ listForSet(orgId: string, setId: string, q: {
211
+ page: number;
212
+ size: number;
213
+ asOf?: string;
214
+ }): Promise<Paged<EvalRunView>>;
207
215
  /**
208
216
  * 查看结果的审计 `eval.results_viewed`(结果里有回放出来的对话内容):每位查看者每次运行每小时一条——Redis
209
217
  * `SET NX EX` 去重(多副本共享),轻量轮询因此不会刷审计。Redis 不可用时照写(宁多不漏)。
210
218
  */
211
219
  private viewed;
212
- /** 结果分页的公共部分:按 id 升序,`after` 为上一页最后一条的 id;`updatedSince` 只取之后有变化的。 */
220
+ /**
221
+ * The run's results (ordered by id by the caller). A run's results are all inserted when it starts and then
222
+ * updated in place, so its pages need no snapshot (table pagination spec §2.3).
223
+ */
213
224
  private resultsQuery;
214
- /** 结果分页(完整行):按 id 升序,`after` 为上一页最后一条的 id。写查看审计(去重见 {@link viewed})。 */
225
+ /** The total of the run's results, after refusing a page past the count cap. */
226
+ private resultsCount;
227
+ /** One page of the results, full rows, by page number. Audits the view (deduplicated: {@link viewed}). */
215
228
  results(orgId: string, actor: string, runId: string, q: {
216
- after?: string;
217
- limit: number;
218
- updatedSince?: string;
219
- }, actorTokenId?: string, auditDetail?: Record<string, unknown>): Promise<{
220
- results: EvalResultView[];
221
- next: string | null;
222
- }>;
229
+ page: number;
230
+ size: number;
231
+ }, actorTokenId?: string, auditDetail?: Record<string, unknown>): Promise<Page<EvalResultView>>;
223
232
  /**
224
- * 结果分页(轻量,结果表与轮询用):不含内容块。`asOf` 作为下一次轮询的 `updatedSince`(已留余量,
225
- * 见 {@link RESULTS_ASOF_OVERLAP_MS};重复的行由调用方按 id 合并)。
233
+ * One page of the results without content blocks (the results table and its polling, which
234
+ * reads the page again), by page number.
226
235
  */
227
236
  resultsLight(orgId: string, actor: string, runId: string, q: {
228
- after?: string;
229
- limit: number;
230
- updatedSince?: string;
231
- }, actorTokenId?: string, auditDetail?: Record<string, unknown>): Promise<{
232
- results: EvalResultLight[];
233
- next: string | null;
234
- asOf: string;
235
- }>;
237
+ page: number;
238
+ size: number;
239
+ }, actorTokenId?: string, auditDetail?: Record<string, unknown>): Promise<Page<EvalResultLight>>;
236
240
  /** 一条结果的完整行(查看器按需读取);不在该运行 / 本组织 → `eval.result_not_found`。写查看审计(去重)。 */
237
241
  result(orgId: string, actor: string, runId: string, resultId: string, actorTokenId?: string, auditDetail?: Record<string, unknown>): Promise<EvalResultView>;
238
242
  /**
@@ -20,6 +20,7 @@ import { KernelDb } from "../infra/database/kernel-db.js";
20
20
  import { TransactionHost } from "../infra/database/transaction-host.js";
21
21
  import { Transactional } from "../infra/database/transactional.decorator.js";
22
22
  import { LockService } from "../infra/lock/lock.service.js";
23
+ import { assertReadablePage, cappedCount, PAGED_NEWER_CAP, PAGED_TOTAL_CAP, pageOf, pageOffset, snapshotNow, } from "../infra/paging/paged-read.js";
23
24
  import { costOf, costOfUsageTotals, PricesService, priceKey, } from "../models/prices.js";
24
25
  import { ModelPurposesService } from "../models/purposes.js";
25
26
  import { OrgLock } from "../orgs/org-lock.js";
@@ -139,11 +140,6 @@ const LIGHT_COLUMNS = [
139
140
  sql `(diff->>'toolCallsMatch')::boolean`.as("tool_calls_match"),
140
141
  sql `(diff->>'textSimilarity')::float8`.as("text_similarity"),
141
142
  ];
142
- /**
143
- * 轻量列表的 `asOf`:本次读取时数据库的当前时间往前留的余量(毫秒)。下一次轮询以它为 `updatedSince`:
144
- * 写结果的事务在读取之前开始、之后才提交时,`updated_at` 早于读取时间,留出余量才不会漏掉;重复的行由调用方按 id 合并。
145
- */
146
- export const RESULTS_ASOF_OVERLAP_MS = 15_000;
147
143
  /** 查看结果的审计去重:每位查看者每次运行每小时一条(Redis 键带 TTL,多副本共享)。 */
148
144
  const RESULTS_VIEWED_TTL_SECONDS = 3600;
149
145
  const resultsViewedKey = (runId, accountId) => `capk:eval-results-viewed:${runId}:${accountId}`;
@@ -609,18 +605,40 @@ let EvalRunsService = EvalRunsService_1 = class EvalRunsService {
609
605
  const sums = await this.summaries(orgId, [r]);
610
606
  return EvalRunsService_1.toView(r, sums.get(r.id) ?? null);
611
607
  }
612
- async listForSet(orgId, setId) {
608
+ /**
609
+ * One page of the set's runs, newest first (`(created_at, id)` descending), by page number on a
610
+ * snapshot (table pagination spec §2.3). Runs are only appended and their sort key never
611
+ * changes, but their ids are random, so the snapshot is a point in time: `asOf` is the database
612
+ * time of the first read, a page lists the runs created at or before it, and later runs count in
613
+ * `newer`. Known caveat (as the audit log's): a run whose transaction started before the
614
+ * snapshot and commits after it may appear inside the snapshot.
615
+ */
616
+ async listForSet(orgId, setId, q) {
617
+ assertReadablePage(q.page, q.size);
613
618
  await this.liveSet(orgId, setId);
614
- const rows = await this.d.db
619
+ const asOf = q.asOf ?? (await snapshotNow(this.d.db));
620
+ const runs = this.d.db
615
621
  .selectFrom("eval_runs")
616
- .select(RUN_COLUMNS)
617
622
  .where("set_id", "=", setId)
618
- .where("org_id", "=", orgId)
623
+ .where("org_id", "=", orgId);
624
+ const snapshot = runs.where(sql `created_at <= ${asOf}::timestamptz`);
625
+ const counted = await cappedCount(this.d.db, snapshot, PAGED_TOTAL_CAP);
626
+ const rows = await snapshot
627
+ .select(RUN_COLUMNS)
619
628
  .orderBy("created_at", "desc")
620
629
  .orderBy("id", "desc")
630
+ .offset(pageOffset(q.page, q.size))
631
+ .limit(q.size)
621
632
  .execute();
633
+ const newer = q.asOf === undefined
634
+ ? { count: 0 }
635
+ : await cappedCount(this.d.db, runs.where(sql `created_at > ${asOf}::timestamptz`), PAGED_NEWER_CAP);
622
636
  const sums = await this.summaries(orgId, rows);
623
- return rows.map((r) => EvalRunsService_1.toView(r, sums.get(r.id) ?? null));
637
+ return {
638
+ ...pageOf(rows.map((r) => EvalRunsService_1.toView(r, sums.get(r.id) ?? null)), q, counted),
639
+ asOf,
640
+ newer: newer.count,
641
+ };
624
642
  }
625
643
  /**
626
644
  * 查看结果的审计 `eval.results_viewed`(结果里有回放出来的对话内容):每位查看者每次运行每小时一条——Redis
@@ -645,69 +663,63 @@ let EvalRunsService = EvalRunsService_1 = class EvalRunsService {
645
663
  ...(auditDetail !== undefined && { detail: auditDetail }),
646
664
  });
647
665
  }
648
- /** 结果分页的公共部分:按 id 升序,`after` 为上一页最后一条的 id;`updatedSince` 只取之后有变化的。 */
649
- resultsQuery(orgId, runId, q) {
650
- let query = this.d.db
666
+ /**
667
+ * The run's results (ordered by id by the caller). A run's results are all inserted when it starts and then
668
+ * updated in place, so its pages need no snapshot (table pagination spec §2.3).
669
+ */
670
+ resultsQuery(orgId, runId) {
671
+ return this.d.db
651
672
  .selectFrom("eval_results")
652
673
  .where("run_id", "=", runId)
653
- .where("org_id", "=", orgId)
654
- .orderBy("id")
655
- .limit(q.limit + 1);
656
- if (q.after !== undefined) {
657
- if (!UUID.test(q.after))
658
- throw new ApiError("validation_failed", "Invalid cursor");
659
- query = query.where("id", ">", q.after);
660
- }
661
- if (q.updatedSince !== undefined) {
662
- const since = new Date(q.updatedSince);
663
- if (Number.isNaN(since.getTime())) {
664
- throw new ApiError("validation_failed", "Invalid updatedSince");
665
- }
666
- query = query.where("updated_at", ">=", since);
667
- }
668
- return query;
674
+ .where("org_id", "=", orgId);
669
675
  }
670
- /** 结果分页(完整行):按 id 升序,`after` 为上一页最后一条的 id。写查看审计(去重见 {@link viewed})。 */
676
+ /** The total of the run's results, after refusing a page past the count cap. */
677
+ async resultsCount(orgId, runId, q) {
678
+ assertReadablePage(q.page, q.size);
679
+ return cappedCount(this.d.db, this.resultsQuery(orgId, runId), PAGED_TOTAL_CAP);
680
+ }
681
+ /** One page of the results, full rows, by page number. Audits the view (deduplicated: {@link viewed}). */
671
682
  async results(orgId, actor, runId, q, actorTokenId, auditDetail) {
672
683
  await this.get(orgId, runId);
673
- const rows = await this.resultsQuery(orgId, runId, q).selectAll().execute();
674
- const page = rows.slice(0, q.limit);
684
+ const counted = await this.resultsCount(orgId, runId, q);
685
+ const rows = await this.resultsQuery(orgId, runId)
686
+ .selectAll()
687
+ .orderBy("id")
688
+ .offset(pageOffset(q.page, q.size))
689
+ .limit(q.size)
690
+ .execute();
675
691
  await this.viewed(orgId, runId, actor, actorTokenId, auditDetail);
676
- return {
677
- results: page.map(resultView),
678
- next: rows.length > q.limit ? (page.at(-1)?.id ?? null) : null,
679
- };
692
+ return pageOf(rows.map(resultView), q, counted);
680
693
  }
681
694
  /**
682
- * 结果分页(轻量,结果表与轮询用):不含内容块。`asOf` 作为下一次轮询的 `updatedSince`(已留余量,
683
- * 见 {@link RESULTS_ASOF_OVERLAP_MS};重复的行由调用方按 id 合并)。
695
+ * One page of the results without content blocks (the results table and its polling, which
696
+ * reads the page again), by page number.
684
697
  */
685
698
  async resultsLight(orgId, actor, runId, q, actorTokenId, auditDetail) {
686
699
  await this.get(orgId, runId);
687
- const now = await sql `SELECT now() AS now`.execute(this.d.db);
688
- const asOf = new Date(new Date(now.rows[0]?.now ?? Date.now()).getTime() - RESULTS_ASOF_OVERLAP_MS);
689
- const rows = await this.resultsQuery(orgId, runId, q).select(LIGHT_COLUMNS).execute();
690
- const page = rows.slice(0, q.limit);
700
+ const counted = await this.resultsCount(orgId, runId, q);
701
+ const rows = await this.resultsQuery(orgId, runId)
702
+ .select(LIGHT_COLUMNS)
703
+ .orderBy("id")
704
+ .offset(pageOffset(q.page, q.size))
705
+ .limit(q.size)
706
+ .execute();
691
707
  await this.viewed(orgId, runId, actor, actorTokenId, auditDetail);
692
- return {
693
- results: page.map((r) => ({
694
- id: r.id,
695
- caseId: r.case_id,
696
- step: r.step,
697
- modelCallSeq: r.model_call_seq === null ? null : Number(r.model_call_seq),
698
- status: r.status,
699
- judgeStatus: r.judge_status,
700
- verdict: r.verdict === "pass" || r.verdict === "fail" ? r.verdict : null,
701
- label: r.label,
702
- driftCount: Number(r.drift_count),
703
- errorCode: r.error_code,
704
- toolCallsMatch: r.tool_calls_match,
705
- textSimilarity: r.text_similarity === null ? null : Number(r.text_similarity),
706
- updatedAt: new Date(r.updated_at).toISOString(),
707
- })),
708
- next: rows.length > q.limit ? (page.at(-1)?.id ?? null) : null,
709
- asOf: asOf.toISOString(),
710
- };
708
+ return pageOf(rows.map((r) => ({
709
+ id: r.id,
710
+ caseId: r.case_id,
711
+ step: r.step,
712
+ modelCallSeq: r.model_call_seq === null ? null : Number(r.model_call_seq),
713
+ status: r.status,
714
+ judgeStatus: r.judge_status,
715
+ verdict: r.verdict === "pass" || r.verdict === "fail" ? r.verdict : null,
716
+ label: r.label,
717
+ driftCount: Number(r.drift_count),
718
+ errorCode: r.error_code,
719
+ toolCallsMatch: r.tool_calls_match,
720
+ textSimilarity: r.text_similarity === null ? null : Number(r.text_similarity),
721
+ updatedAt: new Date(r.updated_at).toISOString(),
722
+ })), q, counted);
711
723
  }
712
724
  /** 一条结果的完整行(查看器按需读取);不在该运行 / 本组织 → `eval.result_not_found`。写查看审计(去重)。 */
713
725
  async result(orgId, actor, runId, resultId, actorTokenId, auditDetail) {
@@ -1,8 +1,16 @@
1
1
  import { z } from "zod";
2
2
  import { type Principal } from "../identity/principal.js";
3
+ import { type Paged } from "../infra/paging/paged-read.js";
3
4
  import { type OrgContext } from "../orgs/org.guard.js";
4
5
  import { type TrajectoryDetail, type TrajectoryListItem, TrajectoryService } from "./trajectory.service.js";
6
+ /**
7
+ * The trajectory list: page numbers on a snapshot (table pagination spec §2.3). `asOf` is a point
8
+ * in time (the `asOf` an earlier page returned): conversations move up as they are used, so the
9
+ * snapshot is not a row.
10
+ */
5
11
  declare const ListQuery: z.ZodObject<{
12
+ page: z.ZodDefault<z.ZodCoercedNumber<unknown>>;
13
+ size: z.ZodDefault<z.ZodCoercedNumber<unknown>>;
6
14
  agentId: z.ZodOptional<z.ZodString>;
7
15
  kind: z.ZodOptional<z.ZodEnum<{
8
16
  chat: "chat";
@@ -16,8 +24,7 @@ declare const ListQuery: z.ZodObject<{
16
24
  running: "running";
17
25
  waiting: "waiting";
18
26
  }>>;
19
- before: z.ZodOptional<z.ZodString>;
20
- limit: z.ZodDefault<z.ZodCoercedNumber<unknown>>;
27
+ asOf: z.ZodOptional<z.ZodISODateTime>;
21
28
  }, z.core.$strip>;
22
29
  /** 详情的运行窗口:`runId` 与 `before` / `limit` 互斥;都不给时读全对话(形状不变)。 */
23
30
  declare const DetailQuery: z.ZodObject<{
@@ -32,10 +39,7 @@ declare const DetailQuery: z.ZodObject<{
32
39
  export declare class TrajectoryController {
33
40
  private readonly trajectories;
34
41
  constructor(trajectories: TrajectoryService);
35
- list(principal: Principal, org: OrgContext, q: z.infer<typeof ListQuery>): Promise<{
36
- items: TrajectoryListItem[];
37
- next: string | null;
38
- }>;
42
+ list(principal: Principal, org: OrgContext, q: z.infer<typeof ListQuery>): Promise<Paged<TrajectoryListItem>>;
39
43
  get(principal: Principal, org: OrgContext, conversationId: string, q: z.infer<typeof DetailQuery>): Promise<TrajectoryDetail>;
40
44
  }
41
45
  export {};
@@ -10,16 +10,22 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
10
10
  import { Controller, Get, Inject, Param } from "@nestjs/common";
11
11
  import { z } from "zod";
12
12
  import { CurrentPrincipal, patTokenId, requireUser, } from "../identity/principal.js";
13
+ import { PageQueryFields, timeAsOf } from "../infra/paging/paged-read.js";
13
14
  import { createZodDto } from "../infra/validation/create-zod-dto.js";
14
15
  import { ZQuery } from "../infra/validation/zod-params.js";
15
16
  import { CurrentOrg, OrgAction } from "../orgs/org.guard.js";
16
17
  import { RUN_STATUSES, TrajectoryService, } from "./trajectory.service.js";
18
+ /**
19
+ * The trajectory list: page numbers on a snapshot (table pagination spec §2.3). `asOf` is a point
20
+ * in time (the `asOf` an earlier page returned): conversations move up as they are used, so the
21
+ * snapshot is not a row.
22
+ */
17
23
  const ListQuery = z.object({
18
24
  agentId: z.string().min(1).max(100).optional(),
19
25
  kind: z.enum(["chat", "eval"]).optional(),
20
26
  status: z.enum(RUN_STATUSES).optional(),
21
- before: z.string().min(1).max(100).optional(),
22
- limit: z.coerce.number().int().min(1).max(100).default(50),
27
+ ...PageQueryFields,
28
+ asOf: timeAsOf(),
23
29
  });
24
30
  /** 详情的运行窗口:`runId` 与 `before` / `limit` 互斥;都不给时读全对话(形状不变)。 */
25
31
  const DetailQuery = z
@@ -50,11 +56,12 @@ let TrajectoryController = class TrajectoryController {
50
56
  async list(principal, org, q) {
51
57
  const user = requireUser(principal);
52
58
  return this.trajectories.list(org.orgId, user.account.id, {
53
- limit: q.limit,
59
+ page: q.page,
60
+ size: q.size,
61
+ ...(q.asOf !== undefined && { asOf: q.asOf }),
54
62
  ...(q.agentId !== undefined && { agentId: q.agentId }),
55
63
  ...(q.kind !== undefined && { kind: q.kind }),
56
64
  ...(q.status !== undefined && { status: q.status }),
57
- ...(q.before !== undefined && { before: q.before }),
58
65
  });
59
66
  }
60
67
  async get(principal, org, conversationId, q) {
@@ -2,6 +2,7 @@ import { type AgentConversationKind } from "../conversations/conversation-agent.
2
2
  import { EventLog } from "../conversations/event-log.js";
3
3
  import type { PersonRef } from "../identity/account-avatar.js";
4
4
  import { KernelDb } from "../infra/database/kernel-db.js";
5
+ import { type Paged } from "../infra/paging/paged-read.js";
5
6
  import { type TrajectoryRun } from "./trajectory.js";
6
7
  /** 轨迹列表的一项(不含对话内容,列表不写审计)。 */
7
8
  export interface TrajectoryListItem {
@@ -74,20 +75,27 @@ export declare class TrajectoryService {
74
75
  /** 组织 admin / owner,或该 agent 当前的负责人(且至少是 member)。agent 已删除或不在本组织 → false。 */
75
76
  canView(orgId: string, accountId: string, agentId: string): Promise<boolean>;
76
77
  /**
77
- * 列出可查看的对话(admin 看全部,其余只看自己负责的 agent),按 (updated_at, id) 倒序;`kind` 缺省为 `chat`。
78
- * `before` 是上一页的 `next`(对话 id):从该对话当前的 (updated_at, id) 之后继续。
78
+ * One page of the conversations the account may view (an org admin all of them, anyone else
79
+ * those of the agents they own), last active first (`(updated_at, id)` descending), by page
80
+ * number on a snapshot (table pagination spec §2.3); `kind` defaults to `chat`.
81
+ *
82
+ * Conversations move up as they are used, so the snapshot is a point in time, not a row: `asOf`
83
+ * is the database time of the first read (ISO 8601 with microseconds), and a page lists only
84
+ * conversations last updated at or before it. A conversation used after the snapshot leaves the
85
+ * snapshot (it shifts later rows by one) and counts in `newer` until a new snapshot is read.
86
+ * Known caveat (accepted, as the audit log's): a write whose transaction started before the
87
+ * snapshot and commits after it may carry an `updated_at` at or before `asOf` and appear inside
88
+ * the snapshot.
79
89
  */
80
90
  list(orgId: string, accountId: string, q: {
81
91
  agentId?: string;
82
92
  kind?: "chat" | "eval";
83
- /** 只列最近一次运行是该状态的对话(没有运行的对话不列)。 */
93
+ /** Only conversations whose latest run has this status (conversations without runs are not listed). */
84
94
  status?: RunStatus;
85
- before?: string;
86
- limit: number;
87
- }): Promise<{
88
- items: TrajectoryListItem[];
89
- next: string | null;
90
- }>;
95
+ page: number;
96
+ size: number;
97
+ asOf?: string;
98
+ }): Promise<Paged<TrajectoryListItem>>;
91
99
  /**
92
100
  * 一个对话的轨迹;无权或不存在 → `trajectory.not_found`。成功时(含窗口为空)写审计 `trajectory.viewed`。
93
101
  * 不给 `window` 时读全对话;给了只读窗口内(且已开始)的运行的事件,响应带 `next`。
@@ -17,6 +17,7 @@ import { peopleOfEvents } from "../conversations/event-people.js";
17
17
  import { ApiError } from "../errors.js";
18
18
  import { audit } from "../identity/audit.js";
19
19
  import { KernelDb } from "../infra/database/kernel-db.js";
20
+ import { assertReadablePage, cappedCount, PAGED_NEWER_CAP, PAGED_TOTAL_CAP, pageOf, pageOffset, snapshotNow, } from "../infra/paging/paged-read.js";
20
21
  import { roleAtLeast } from "../orgs/roles.js";
21
22
  import { buildTrajectory } from "./trajectory.js";
22
23
  /** 运行的状态(`runs.status`),列表按最近一次运行的状态过滤用。 */
@@ -80,58 +81,72 @@ let TrajectoryService = TrajectoryService_1 = class TrajectoryService {
80
81
  return roleAtLeast(role, "admin") || agent.owner_account_id === accountId;
81
82
  }
82
83
  /**
83
- * 列出可查看的对话(admin 看全部,其余只看自己负责的 agent),按 (updated_at, id) 倒序;`kind` 缺省为 `chat`。
84
- * `before` 是上一页的 `next`(对话 id):从该对话当前的 (updated_at, id) 之后继续。
84
+ * One page of the conversations the account may view (an org admin all of them, anyone else
85
+ * those of the agents they own), last active first (`(updated_at, id)` descending), by page
86
+ * number on a snapshot (table pagination spec §2.3); `kind` defaults to `chat`.
87
+ *
88
+ * Conversations move up as they are used, so the snapshot is a point in time, not a row: `asOf`
89
+ * is the database time of the first read (ISO 8601 with microseconds), and a page lists only
90
+ * conversations last updated at or before it. A conversation used after the snapshot leaves the
91
+ * snapshot (it shifts later rows by one) and counts in `newer` until a new snapshot is read.
92
+ * Known caveat (accepted, as the audit log's): a write whose transaction started before the
93
+ * snapshot and commits after it may carry an `updated_at` at or before `asOf` and appear inside
94
+ * the snapshot.
85
95
  */
86
96
  async list(orgId, accountId, q) {
97
+ assertReadablePage(q.page, q.size);
98
+ const asOf = q.asOf ?? (await snapshotNow(this.db.db));
99
+ const empty = {
100
+ ...pageOf([], q, { count: 0, capped: false }),
101
+ asOf,
102
+ newer: 0,
103
+ };
87
104
  const role = await this.role(orgId, accountId);
88
105
  if (!TrajectoryService_1.isMember(role))
89
- return { items: [], next: null };
106
+ return empty;
90
107
  const admin = roleAtLeast(role, "admin");
91
- // 评测对话只给组织管理员(Ruling S1-c)
108
+ // eval conversations are for org admins only (Ruling S1-c)
92
109
  if (q.kind === "eval" && !admin)
93
- return { items: [], next: null };
94
- let query = this.db
110
+ return empty;
111
+ // the count, the rows and `newer` share these joins (an agent without its current version
112
+ // row is in none of them)
113
+ let matching = this.db
95
114
  .selectFrom("conversations as c")
96
115
  .innerJoin("agents as a", "a.id", "c.agent_id")
97
116
  .innerJoin("agent_versions as v", (j) => j.onRef("v.agent_id", "=", "a.id").onRef("v.version", "=", "a.current_version"))
98
- .select([
99
- "c.id",
100
- "c.agent_id",
101
- "c.account_id",
102
- "c.title",
103
- "c.updated_at",
104
- sql `v.definition ->> 'name'`.as("agent_name"),
105
- ])
106
117
  .where("c.org_id", "=", orgId)
107
118
  .where("c.kind", "=", q.kind ?? "chat")
108
119
  .where("a.org_id", "=", orgId)
109
- .where("a.deleted_at", "is", null)
110
- .orderBy("c.updated_at", "desc")
111
- .orderBy("c.id", "desc")
112
- .limit(q.limit + 1);
120
+ .where("a.deleted_at", "is", null);
113
121
  if (!admin)
114
- query = query.where("a.owner_account_id", "=", accountId);
122
+ matching = matching.where("a.owner_account_id", "=", accountId);
115
123
  if (q.agentId !== undefined)
116
- query = query.where("c.agent_id", "=", q.agentId);
124
+ matching = matching.where("c.agent_id", "=", q.agentId);
117
125
  if (q.status !== undefined) {
118
126
  const status = q.status;
119
- // 与下面取 lastRun 的排序一致:最近一次运行 = created_at、id 最大的一条
120
- query = query.where((eb) => sql `(
127
+ // the latest run as below (lastRun): the one with the largest created_at, then id
128
+ matching = matching.where((eb) => sql `(
121
129
  SELECT r.status FROM capybara.runs r WHERE r.conversation_id = ${eb.ref("c.id")}
122
130
  ORDER BY r.created_at DESC, r.id DESC LIMIT 1
123
131
  ) = ${status}`);
124
132
  }
125
- if (q.before !== undefined) {
126
- const before = q.before;
127
- query = query.where((eb) => sql `(${eb.ref("c.updated_at")}, ${eb.ref("c.id")}) < (
128
- SELECT x.updated_at, x.id FROM capybara.conversations x
129
- WHERE x.id = ${before} AND x.org_id = ${orgId}
130
- )`);
131
- }
132
- const rows = await query.execute();
133
- const page = rows.slice(0, q.limit);
134
- const ids = page.map((r) => r.id);
133
+ const snapshot = matching.where(sql `c.updated_at <= ${asOf}::timestamptz`);
134
+ const counted = await cappedCount(this.db.db, snapshot, PAGED_TOTAL_CAP);
135
+ const rows = await snapshot
136
+ .select([
137
+ "c.id",
138
+ "c.agent_id",
139
+ "c.account_id",
140
+ "c.title",
141
+ "c.updated_at",
142
+ sql `v.definition ->> 'name'`.as("agent_name"),
143
+ ])
144
+ .orderBy("c.updated_at", "desc")
145
+ .orderBy("c.id", "desc")
146
+ .offset(pageOffset(q.page, q.size))
147
+ .limit(q.size)
148
+ .execute();
149
+ const ids = rows.map((r) => r.id);
135
150
  const lastRuns = ids.length === 0
136
151
  ? []
137
152
  : await this.db
@@ -144,7 +159,7 @@ let TrajectoryService = TrajectoryService_1 = class TrajectoryService {
144
159
  .orderBy("id", "desc")
145
160
  .execute();
146
161
  const byConv = new Map(lastRuns.map((r) => [r.conversation_id, r]));
147
- const items = page.map((r) => {
162
+ const items = rows.map((r) => {
148
163
  const run = byConv.get(r.id);
149
164
  return {
150
165
  conversationId: r.id,
@@ -163,8 +178,10 @@ let TrajectoryService = TrajectoryService_1 = class TrajectoryService {
163
178
  },
164
179
  };
165
180
  });
166
- const next = rows.length > q.limit ? (page.at(-1)?.id ?? null) : null;
167
- return { items, next };
181
+ const newer = q.asOf === undefined
182
+ ? { count: 0 }
183
+ : await cappedCount(this.db.db, matching.where(sql `c.updated_at > ${asOf}::timestamptz`), PAGED_NEWER_CAP);
184
+ return { ...pageOf(items, q, counted), asOf, newer: newer.count };
168
185
  }
169
186
  /**
170
187
  * 一个对话的轨迹;无权或不存在 → `trajectory.not_found`。成功时(含窗口为空)写审计 `trajectory.viewed`。
@@ -5,6 +5,7 @@ import { KernelConfigService } from "../infra/config/kernel-config.service.js";
5
5
  import { KernelDb } from "../infra/database/kernel-db.js";
6
6
  import { TransactionHost } from "../infra/database/transaction-host.js";
7
7
  import { OutboxService } from "../infra/outbox/outbox.service.js";
8
+ import { type HintPublisher } from "../invalidation/audiences.js";
8
9
  import type { KernelLogger } from "../log.js";
9
10
  import { OrgLock } from "../orgs/org-lock.js";
10
11
  import { ExtensionAdmin, type PublishBus } from "./admin-view.js";
@@ -85,6 +86,8 @@ export declare class ExtensionAdminOps {
85
86
  private readonly singleProvider;
86
87
  /** The plugin scope sync a deploy owes (`oweDeployedExtensionSync`). */
87
88
  private readonly outbox;
89
+ /** A platform enable, disable or new version publishes `platform-caps` after the commit. */
90
+ private readonly hints;
88
91
  constructor(kdb: KernelDb, txHost: TransactionHost,
89
92
  /** The super admin lock (identity/super-admin.ts): joins the transaction. */
90
93
  adminLock: SuperAdminLock,
@@ -111,7 +114,9 @@ export declare class ExtensionAdminOps {
111
114
  /** One enabled provider per single-provider extension point (checked in the enable). */
112
115
  singleProvider: SingleProviderGuard,
113
116
  /** The plugin scope sync a deploy owes (`oweDeployedExtensionSync`). */
114
- outbox: Pick<OutboxService, "add" | "addMany">);
117
+ outbox: Pick<OutboxService, "add" | "addMany">,
118
+ /** A platform enable, disable or new version publishes `platform-caps` after the commit. */
119
+ hints: HintPublisher);
115
120
  private get db();
116
121
  /**
117
122
  * New install or version change (upgrade / downgrade): the install record points at package