@capybara-hq/kernel 0.1.0-rc.129 → 0.1.0-rc.130

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 (101) hide show
  1. package/dist/admin/usage.service.d.ts +20 -37
  2. package/dist/admin/usage.service.js +99 -122
  3. package/dist/automations/unattended.js +2 -0
  4. package/dist/background/wake-rules.js +1 -0
  5. package/dist/channels/outbound.js +2 -0
  6. package/dist/config/schema.d.ts +2 -0
  7. package/dist/config/schema.js +17 -1
  8. package/dist/conversations/conversations.service.js +5 -0
  9. package/dist/conversations/event-log.d.ts +6 -2
  10. package/dist/conversations/event-log.js +23 -10
  11. package/dist/conversations/event-org-backfill.d.ts +111 -0
  12. package/dist/conversations/event-org-backfill.js +264 -0
  13. package/dist/conversations/event-org-backfill.module.d.ts +3 -0
  14. package/dist/conversations/event-org-backfill.module.js +18 -0
  15. package/dist/conversations/events.d.ts +14 -0
  16. package/dist/conversations/events.js +2 -0
  17. package/dist/conversations/files.js +1 -0
  18. package/dist/conversations/leak-check.js +1 -0
  19. package/dist/conversations/prompt-suggestion-store.js +1 -0
  20. package/dist/conversations/prompt-suggestions.js +1 -0
  21. package/dist/conversations/queue.js +1 -0
  22. package/dist/conversations/selection.js +1 -0
  23. package/dist/conversations/titles.js +1 -0
  24. package/dist/db/kernel-schema.d.ts +8 -15
  25. package/dist/db/migrator.d.ts +6 -0
  26. package/dist/db/migrator.js +58 -6
  27. package/dist/evals/run-replay.js +4 -2
  28. package/dist/evals/sets.service.d.ts +1 -7
  29. package/dist/evals/sets.service.js +6 -15
  30. package/dist/evals/snapshot.js +2 -0
  31. package/dist/evals/trajectory.d.ts +7 -10
  32. package/dist/evals/trajectory.js +31 -23
  33. package/dist/evals/trajectory.service.d.ts +1 -7
  34. package/dist/evals/trajectory.service.js +10 -19
  35. package/dist/evals/worker.d.ts +2 -0
  36. package/dist/evals/worker.js +15 -2
  37. package/dist/identity/settings.d.ts +1 -0
  38. package/dist/identity/settings.js +3 -3
  39. package/dist/index.d.ts +1 -1
  40. package/dist/index.js +1 -1
  41. package/dist/infra/outbox/registry.d.ts +14 -0
  42. package/dist/infra/outbox/registry.js +15 -0
  43. package/dist/kernel.d.ts +6 -0
  44. package/dist/kernel.js +31 -2
  45. package/dist/lifecycle/kernel-lifecycle.js +2 -3
  46. package/dist/models/embeddings.d.ts +1 -0
  47. package/dist/models/embeddings.js +8 -0
  48. package/dist/models/images.d.ts +1 -0
  49. package/dist/models/images.js +7 -0
  50. package/dist/models/price-snapshot.d.ts +43 -0
  51. package/dist/models/price-snapshot.js +145 -0
  52. package/dist/platform/ops/admin.ops.js +1 -1
  53. package/dist/push/recipients.js +9 -8
  54. package/dist/roles/worker.module.js +6 -0
  55. package/dist/runtime/idle-arm.js +3 -0
  56. package/dist/runtime/idle-compaction.d.ts +1 -1
  57. package/dist/runtime/idle-compaction.js +6 -2
  58. package/dist/runtime/idle-return.js +3 -0
  59. package/dist/runtime/maintenance.d.ts +3 -1
  60. package/dist/runtime/maintenance.js +18 -5
  61. package/dist/runtime/permission-context.service.js +1 -0
  62. package/dist/runtime/plugin-context.service.js +1 -0
  63. package/dist/runtime/project/knowledge.service.js +2 -0
  64. package/dist/runtime/run-context.service.js +4 -0
  65. package/dist/runtime/run-deletion.d.ts +1 -0
  66. package/dist/runtime/run-deletion.js +7 -3
  67. package/dist/runtime/run-queue.js +3 -0
  68. package/dist/runtime/run-worker.js +1 -0
  69. package/dist/runtime/stream.js +4 -3
  70. package/dist/runtime/subagents/deliveries.js +1 -0
  71. package/dist/runtime/subagents/dispatch.js +1 -0
  72. package/dist/runtime/subagents/progress.js +1 -0
  73. package/dist/runtime/subagents/skill-fork.js +2 -0
  74. package/dist/runtime/usage-report.js +1 -0
  75. package/dist/runtime/waits.d.ts +1 -1
  76. package/dist/runtime/waits.js +3 -1
  77. package/dist/sandbox/managed-device-context.js +1 -0
  78. package/dist/sandbox/operation-authority.js +2 -0
  79. package/dist/sandbox/operation-intents.js +1 -0
  80. package/dist/sandbox/permission-call-grants.js +2 -0
  81. package/dist/sandbox/permission-facts.js +2 -0
  82. package/dist/sandbox/review/classifier.js +1 -0
  83. package/dist/sandbox/review/review.service.js +1 -0
  84. package/dist/skills/catalog.js +1 -0
  85. package/dist/skills/invoke.js +2 -0
  86. package/dist/tools/admin-connectors.js +2 -2
  87. package/dist/tools/builtins/builtin-tools.js +1 -0
  88. package/dist/tools/builtins/skill-load.js +2 -0
  89. package/dist/tools/connector-account-policies.js +3 -3
  90. package/dist/tools/connectors.service.js +13 -25
  91. package/dist/tools/drift.js +8 -14
  92. package/dist/tools/policy.js +2 -2
  93. package/dist/tools/registry.js +1 -2
  94. package/dist/tools/tool-watch.processor.d.ts +1 -1
  95. package/dist/tools/tool-watch.processor.js +1 -1
  96. package/dist/tools/tool-watch.service.js +22 -7
  97. package/dist/ui/views.js +1 -0
  98. package/package.json +1 -1
  99. package/src/migrations/0213_contract_org_security_policy.sql +43 -0
  100. package/src/migrations/0214_model_usage_price_snapshot.sql +2 -0
  101. package/src/migrations/0215_conversation_events_org_id.sql +48 -0
@@ -298,15 +298,6 @@ export interface ExtensionOrgOverridesTable {
298
298
  updated_by: string | null;
299
299
  updated_at: Ts;
300
300
  }
301
- /** An org admin's switch of one extension tool (0086, spec A §7). */
302
- export interface OrgToolSwitchesTable {
303
- org_id: string;
304
- plugin: string;
305
- tool: string;
306
- enabled: boolean;
307
- updated_by: string | null;
308
- updated_at: Ts;
309
- }
310
301
  /** Organization policy for a canonical tool or named per-call key. */
311
302
  export interface OrgToolPoliciesTable {
312
303
  org_id: string;
@@ -524,9 +515,11 @@ export interface ConversationSubject {
524
515
  }
525
516
  /** chat; eval (a hidden full-run replay conversation); subagent (0053: a sub-agent's conversation). */
526
517
  export type ConversationKind = "chat" | "eval" | "subagent";
527
- /** 0006_conversations.sql:会话事件日志,只追加。 */
518
+ /** 0006_conversations.sql: append-only conversation event log. */
528
519
  export interface ConversationEventsTable {
529
520
  conversation_id: string;
521
+ /** 0215: owning org (nullable during expand; populated by app and backfill before NOT NULL). */
522
+ org_id: ColumnType<string | null, string | null | undefined, string | null>;
530
523
  seq: Int8;
531
524
  type: string;
532
525
  run_id: string | null;
@@ -714,8 +707,8 @@ export interface ConnectorToolsTable {
714
707
  spec_hash: string;
715
708
  status: "enabled" | "disabled" | "pending_review";
716
709
  default_policy: "allow" | "ask" | "deny";
717
- /** The baseline kept independently of a migrated connector admin override. */
718
- declaration_policy: Generated<"allow" | "ask" | "deny" | null>;
710
+ /** Retained for the rc.157 rollout. The next contract drops this column. */
711
+ declaration_policy: ColumnType<null, never, never>;
719
712
  reviewed_at: TsNullable;
720
713
  /** 0013:工具来源(`resources` = 内核为支持 resources 的连接器补上的两个工具)。 */
721
714
  source: Generated<"connector" | "resources">;
@@ -723,8 +716,8 @@ export interface ConnectorToolsTable {
723
716
  pending_spec: ColumnType<unknown, string | null | undefined, string | null>;
724
717
  pending_spec_hash: string | null;
725
718
  pending_source: "connector" | "resources" | null;
726
- /** 0015:默认策略的来历(admin = 管理员设定,复核通过后保留;derived = 按注解重新推导)。 */
727
- policy_source: Generated<"derived" | "admin" | "template">;
719
+ /** Whether the default policy comes from annotations or from a connector template. */
720
+ policy_source: Generated<"derived" | "template">;
728
721
  /** 0015:远端不再提供该工具的时间(工具停用,行保留)。 */
729
722
  missing_since: TsNullable;
730
723
  }
@@ -1552,6 +1545,7 @@ export interface ModelUsageTable {
1552
1545
  /** 0160: the answer's cache write tokens (0 for an embedding call). */
1553
1546
  cache_write_tokens: Generated<number>;
1554
1547
  cache_write_by_ttl: Json<CacheWriteByTtl[] | null>;
1548
+ price_snapshot: Json<unknown>;
1555
1549
  occurred_at: Ts;
1556
1550
  reported_at: TsNullable;
1557
1551
  /** Set when the row's `usage.report` job gave up after its last attempt. */
@@ -1955,7 +1949,6 @@ export interface KernelDatabase {
1955
1949
  deployment_settings: DeploymentSettingsTable;
1956
1950
  extension_org_configs: ExtensionOrgConfigsTable;
1957
1951
  extension_org_overrides: ExtensionOrgOverridesTable;
1958
- org_tool_switches: OrgToolSwitchesTable;
1959
1952
  org_tool_policies: OrgToolPoliciesTable;
1960
1953
  org_git_push_denials: OrgGitPushDenialsTable;
1961
1954
  org_network_allowances: OrgNetworkAllowancesTable;
@@ -1,3 +1,4 @@
1
+ import { type QueryExecutorProvider } from "kysely";
1
2
  /** 迁移文件名:`NNNN_<snake_desc>.sql`(其他文件忽略)。 */
2
3
  export declare const MIGRATION_FILE_RE: RegExp;
3
4
  /** 迁移器所有者:目标 schema 与迁移文件目录。 */
@@ -5,6 +6,11 @@ export interface MigrationOwner {
5
6
  schema: string;
6
7
  dir: string;
7
8
  }
9
+ export declare function canMigrateKernel(db: QueryExecutorProvider): Promise<boolean>;
10
+ /** Verify the files expected by this binary without taking a migration lock or writing the journal.
11
+ * Extra entries are valid when a newer release has already migrated a shared database.
12
+ */
13
+ export declare function verifyMigrations(db: QueryExecutorProvider, { schema, dir }: MigrationOwner): Promise<void>;
8
14
  /**
9
15
  * 执行目录下尚未应用的 SQL 迁移。
10
16
  * 使用独立的 pg.Client(不走连接池),在该会话上持有 advisory lock(按 schema 名哈希);
@@ -1,12 +1,60 @@
1
1
  import { createHash } from "node:crypto";
2
2
  import { readdir, readFile } from "node:fs/promises";
3
3
  import { join } from "node:path";
4
+ import { sql } from "kysely";
4
5
  import pg from "pg";
5
6
  import { pgConnectOptions } from "./pool.js";
6
7
  /** 迁移文件名:`NNNN_<snake_desc>.sql`(其他文件忽略)。 */
7
8
  export const MIGRATION_FILE_RE = /^\d{4}_[a-z0-9_]+\.sql$/;
8
9
  const ident = (s) => `"${s.replaceAll('"', '""')}"`;
9
10
  const num = (name) => Number.parseInt(name.slice(0, 4), 10);
11
+ async function migrationFiles(dir) {
12
+ const names = (await readdir(dir)).filter((file) => MIGRATION_FILE_RE.test(file)).sort();
13
+ return Promise.all(names.map(async (name) => {
14
+ const content = await readFile(join(dir, name), "utf8");
15
+ return { name, content, checksum: createHash("sha256").update(content).digest("hex") };
16
+ }));
17
+ }
18
+ // Use the effective login on the actual connection, including when a URL sets a role.
19
+ const kernelMigrationPrivileges = `
20
+ select pg_catalog.has_database_privilege(current_user, current_database(), 'CREATE') as can_create,
21
+ exists (select from pg_catalog.pg_roles where rolname = 'capybara_owner') as has_owner_role,
22
+ current_user = pg_catalog.pg_get_userbyid(n.nspowner) as owns_schema
23
+ from (values ('capybara'::name)) as target(schema_name)
24
+ left join pg_catalog.pg_namespace n on n.nspname = target.schema_name
25
+ `;
26
+ export async function canMigrateKernel(db) {
27
+ const { rows: [privileges], } = await sql.raw(kernelMigrationPrivileges).execute(db);
28
+ if (privileges === undefined)
29
+ throw new Error("Could not read kernel migration privileges");
30
+ return privileges.can_create && (privileges.owns_schema ?? !privileges.has_owner_role);
31
+ }
32
+ const migrateHint = "Run capybara migrate with CAPYBARA_DB__MIGRATION_URL set to the schema owner URL for split roles.";
33
+ /** Verify the files expected by this binary without taking a migration lock or writing the journal.
34
+ * Extra entries are valid when a newer release has already migrated a shared database.
35
+ */
36
+ export async function verifyMigrations(db, { schema, dir }) {
37
+ const files = await migrationFiles(dir);
38
+ const journal = sql.id(schema, "_migrations");
39
+ let rows;
40
+ try {
41
+ rows = (await sql `select name, checksum from ${journal}`.execute(db)).rows;
42
+ }
43
+ catch (cause) {
44
+ const code = cause?.code;
45
+ if (code !== "42P01" && code !== "3F000" && code !== "42501")
46
+ throw cause;
47
+ throw new Error(`Cannot read the ${schema} migration journal. ${migrateHint} Check the runtime's journal grants.`, { cause });
48
+ }
49
+ const applied = new Map(rows.map(({ name, checksum }) => [name, checksum]));
50
+ for (const { name, checksum } of files) {
51
+ const stored = applied.get(name);
52
+ if (stored === undefined)
53
+ throw new Error(`Migration ${schema}/${name} is missing. ${migrateHint}`);
54
+ if (stored !== checksum)
55
+ throw new Error(`Migration ${schema}/${name} was modified after being applied (checksum mismatch)`);
56
+ }
57
+ }
10
58
  /**
11
59
  * 执行目录下尚未应用的 SQL 迁移。
12
60
  * 使用独立的 pg.Client(不走连接池),在该会话上持有 advisory lock(按 schema 名哈希);
@@ -23,11 +71,7 @@ export async function migrate(connectionString, owner, opts = {}) {
23
71
  const { signal } = opts;
24
72
  if (signal?.aborted)
25
73
  throw new Error(`Migration ${schema} aborted`);
26
- const names = (await readdir(dir)).filter((f) => MIGRATION_FILE_RE.test(f)).sort();
27
- const files = await Promise.all(names.map(async (name) => {
28
- const content = await readFile(join(dir, name), "utf8");
29
- return { name, content, checksum: createHash("sha256").update(content).digest("hex") };
30
- }));
74
+ const files = await migrationFiles(dir);
31
75
  const table = `${ident(schema)}._migrations`;
32
76
  // 读文件期间可能已中止(AbortSignal 不会对之后才挂上的监听器补发 abort):连接前再查一次。
33
77
  // 从这里到 client.connect() 之间没有 await,监听器挂上前不会错过中止。
@@ -83,7 +127,15 @@ export async function migrate(connectionString, owner, opts = {}) {
83
127
  if (opts.lockTimeoutMs !== undefined) {
84
128
  await client.query(`set lock_timeout = ${Math.max(1, Math.floor(opts.lockTimeoutMs))}`);
85
129
  }
86
- await client.query("select pg_advisory_lock(hashtext($1))", [`capybara-migrate:${schema}`]);
130
+ await client.query("select pg_catalog.pg_advisory_lock(pg_catalog.hashtext($1))", [
131
+ `capybara-migrate:${schema}`,
132
+ ]);
133
+ if (schema === "capybara") {
134
+ const { rows: [privileges], } = await client.query(kernelMigrationPrivileges);
135
+ if (privileges?.has_owner_role && !privileges.owns_schema) {
136
+ throw new Error(`The migration login must own the capybara schema. ${migrateHint}`);
137
+ }
138
+ }
87
139
  await client.query(`create schema if not exists ${ident(schema)}`);
88
140
  await client.query(`create table if not exists ${table} (
89
141
  name text primary key,
@@ -70,7 +70,7 @@ let EvalReplaySeeder = class EvalReplaySeeder {
70
70
  .executeTakeFirst();
71
71
  if (!live)
72
72
  throw new ReplayClaimLost();
73
- await this.db
73
+ const seeded = await this.db
74
74
  .insertInto("conversations")
75
75
  .values({
76
76
  id: conversationId,
@@ -83,12 +83,14 @@ let EvalReplaySeeder = class EvalReplaySeeder {
83
83
  eval_run_id: evalRunId,
84
84
  source: p.source,
85
85
  })
86
- .execute();
86
+ .returning("org_id")
87
+ .executeTakeFirstOrThrow();
87
88
  for (let i = 0; i < p.seeds.length; i += SEED_BATCH) {
88
89
  await this.db
89
90
  .insertInto("conversation_events")
90
91
  .values(p.seeds.slice(i, i + SEED_BATCH).map((e) => ({
91
92
  conversation_id: conversationId,
93
+ org_id: seeded.org_id,
92
94
  seq: e.seq,
93
95
  type: e.type,
94
96
  run_id: e.runId,
@@ -1,8 +1,6 @@
1
- import { SettingsService } from "../identity/settings.js";
2
1
  import { KernelConfigService } from "../infra/config/kernel-config.service.js";
3
2
  import { KernelDb } from "../infra/database/kernel-db.js";
4
3
  import { TransactionHost } from "../infra/database/transaction-host.js";
5
- import { PricesService } from "../models/prices.js";
6
4
  import { OrgLock } from "../orgs/org-lock.js";
7
5
  import { EvalBudget } from "./budget.js";
8
6
  import { type CaseSnapshot } from "./snapshot.js";
@@ -33,8 +31,6 @@ export interface EvalSetDetail extends EvalSetView {
33
31
  export interface EvalCaseDetail {
34
32
  case: EvalCaseView;
35
33
  trajectory: TrajectoryRun[];
36
- /** 成本的币种(部署设置 `priceCurrency`)。 */
37
- currency: string;
38
34
  /** A sub-agent's case: the parent call that dispatched its run (navigation only). */
39
35
  parent?: {
40
36
  conversationId: string;
@@ -74,13 +70,11 @@ export declare function caseTitle(s: CaseSnapshot): string;
74
70
  export declare class EvalSetsService {
75
71
  private readonly kdb;
76
72
  private readonly config;
77
- private readonly prices;
78
- private readonly settings;
79
73
  /** The org row lock (orgs/org-lock.ts): joins the caller's transaction. */
80
74
  private readonly orgLock;
81
75
  private readonly budget;
82
76
  readonly txHost: TransactionHost;
83
- constructor(kdb: KernelDb, config: Pick<KernelConfigService, "get">, prices: Pick<PricesService, "table">, settings: Pick<SettingsService, "get">,
77
+ constructor(kdb: KernelDb, config: Pick<KernelConfigService, "get">,
84
78
  /** The org row lock (orgs/org-lock.ts): joins the caller's transaction. */
85
79
  orgLock: Pick<OrgLock, "lockAndAuthorize">, budget: Pick<EvalBudget, "skipRun">, txHost: TransactionHost);
86
80
  /** The context-aware handle (the `@Transactional` method's transaction, else the pool). */
@@ -13,12 +13,10 @@ import { sql } from "kysely";
13
13
  import { typedInvocation } from "../conversations/events.js";
14
14
  import { ApiError } from "../errors.js";
15
15
  import { audit } from "../identity/audit.js";
16
- import { SettingsService } from "../identity/settings.js";
17
16
  import { KernelConfigService } from "../infra/config/kernel-config.service.js";
18
17
  import { KernelDb } from "../infra/database/kernel-db.js";
19
18
  import { TransactionHost } from "../infra/database/transaction-host.js";
20
19
  import { Transactional } from "../infra/database/transactional.decorator.js";
21
- import { PricesService } from "../models/prices.js";
22
20
  import { OrgLock } from "../orgs/org-lock.js";
23
21
  import { EvalBudget } from "./budget.js";
24
22
  import { casePlans } from "./plan.js";
@@ -100,18 +98,14 @@ function toCaseView(r) {
100
98
  let EvalSetsService = EvalSetsService_1 = class EvalSetsService {
101
99
  kdb;
102
100
  config;
103
- prices;
104
- settings;
105
101
  orgLock;
106
102
  budget;
107
103
  txHost;
108
- constructor(kdb, config, prices, settings,
104
+ constructor(kdb, config,
109
105
  /** The org row lock (orgs/org-lock.ts): joins the caller's transaction. */
110
106
  orgLock, budget, txHost) {
111
107
  this.kdb = kdb;
112
108
  this.config = config;
113
- this.prices = prices;
114
- this.settings = settings;
115
109
  this.orgLock = orgLock;
116
110
  this.budget = budget;
117
111
  this.txHost = txHost;
@@ -517,6 +511,7 @@ let EvalSetsService = EvalSetsService_1 = class EvalSetsService {
517
511
  q = q.where("r.created_at", "<", new Date(input.to));
518
512
  const minToolCalls = input.minToolCalls ?? 0;
519
513
  if (minToolCalls > 0) {
514
+ // org-filter: correlated to outer runs query joined with org-filtered conversations
520
515
  q = q.where((eb) => sql `(
521
516
  SELECT count(*) FROM capybara.conversation_events ev
522
517
  WHERE ev.conversation_id = ${eb.ref("r.conversation_id")}
@@ -575,7 +570,6 @@ let EvalSetsService = EvalSetsService_1 = class EvalSetsService {
575
570
  if (!row)
576
571
  throw caseNotFound();
577
572
  const snapshot = readSnapshot(row.snapshot);
578
- const [table, settings] = await Promise.all([this.prices.table(), this.settings.get()]);
579
573
  await audit(this.db, {
580
574
  actorAccountId: actor,
581
575
  ...(actorTokenId !== undefined && { actorTokenId }),
@@ -586,8 +580,7 @@ let EvalSetsService = EvalSetsService_1 = class EvalSetsService {
586
580
  });
587
581
  return {
588
582
  case: toCaseView(row),
589
- trajectory: buildTrajectory(toEvents(snapshot), table),
590
- currency: settings.priceCurrency,
583
+ trajectory: buildTrajectory(toEvents(snapshot)),
591
584
  ...(snapshot.parent !== undefined && { parent: snapshot.parent }),
592
585
  ...(snapshot.subagent?.invokedSkill !== undefined && {
593
586
  invokedSkill: snapshot.subagent.invokedSkill,
@@ -614,11 +607,9 @@ EvalSetsService = EvalSetsService_1 = __decorate([
614
607
  Injectable(),
615
608
  __param(0, Inject(KernelDb)),
616
609
  __param(1, Inject(KernelConfigService)),
617
- __param(2, Inject(PricesService)),
618
- __param(3, Inject(SettingsService)),
619
- __param(4, Inject(OrgLock)),
620
- __param(5, Inject(EvalBudget)),
621
- __param(6, Inject(TransactionHost))
610
+ __param(2, Inject(OrgLock)),
611
+ __param(3, Inject(EvalBudget)),
612
+ __param(4, Inject(TransactionHost))
622
613
  ], EvalSetsService);
623
614
  export { EvalSetsService };
624
615
  /**
@@ -130,6 +130,7 @@ async function snapshotOf(db, ids, conv, agentVersion, events) {
130
130
  */
131
131
  export async function takeSnapshot(db, orgId, conversationId, runId, maxBytes) {
132
132
  const { conv, agentVersion } = await conversationRun(db, orgId, conversationId, runId);
133
+ // org-filter: conversationRun verified conversationId belongs to orgId above
133
134
  const end = await db
134
135
  .selectFrom("conversation_events")
135
136
  .select("seq")
@@ -150,6 +151,7 @@ export async function takeSnapshot(db, orgId, conversationId, runId, maxBytes) {
150
151
  let bytes = 0;
151
152
  let after = 0;
152
153
  for (;;) {
154
+ // org-filter: conversationRun verified conversationId belongs to orgId above
153
155
  const rows = await db
154
156
  .selectFrom("conversation_events")
155
157
  .select(["seq", "type", "run_id", "payload", "created_at"])
@@ -1,10 +1,7 @@
1
1
  import type { ModelUsage } from "@capybara-hq/plugin-sdk";
2
2
  import type { ConversationEvent, EventPayload } from "../conversations/events.js";
3
- import { type PriceTable } from "../models/prices.js";
4
- /**
5
- * 轨迹读模型(D6、C2):由会话事件日志推出每次运行的步骤、模型调用与工具调用,纯函数、不读库。
6
- * 延迟与耗时只由事件的 `created_at` 推出,不加事件字段;成本读时按价格表算,不写日志。
7
- */
3
+ import { type UsageCost } from "../models/price-snapshot.js";
4
+ /** Build run, step and tool details from the recorded events, including snapshot cost. */
8
5
  /** 一次模型请求(一条 `model_call` 事件)。 */
9
6
  export interface TrajectoryModelCall {
10
7
  seq: number;
@@ -19,8 +16,8 @@ export interface TrajectoryModelCall {
19
16
  /** 该步写了 usage 且本次是最后一次尝试 → ok;运行未结束且该步还没有回复 → pending;其余为 failed。 */
20
17
  outcome: "ok" | "failed" | "pending";
21
18
  usage: ModelUsage | null;
22
- /** 估算成本(币种见响应的 `currency`);没有用量或没有价格时为 null。 */
23
- cost: number | null;
19
+ /** Cost from this call’s recorded usage. Null if the call has no usage. */
20
+ cost: UsageCost | null;
24
21
  request: EventPayload<"model_call">["request"];
25
22
  }
26
23
  /** A plugin policy hook's denial (`hook_denied`): cause and sanitized reason (raw errors: audit log). */
@@ -145,8 +142,8 @@ export interface TrajectoryRun {
145
142
  * its (possibly chunked) compaction calls, and it has no steps.
146
143
  */
147
144
  usage: ModelUsage;
148
- /** 各次成功调用的成本之和(含压缩调用);任一成功调用没有价格时为 null(部分求和会误导)。 */
149
- cost: number | null;
145
+ /** Recorded cost by currency, including auxiliary usage. */
146
+ cost: UsageCost;
150
147
  modelCalls: number;
151
148
  toolCalls: number;
152
149
  /** `endedAt − startedAt`(含等待审批 / 输入的时间);运行未结束为 null。 */
@@ -157,4 +154,4 @@ export interface TrajectoryRun {
157
154
  * 由会话事件推出各次运行的轨迹,按 `run_started` 的 seq 排序。没有 `run_started` 的运行(排队时就被中止 /
158
155
  * 判为孤儿,从未开始)不出现;没有 `runId` 的事件(用户消息等)不属于任何运行。
159
156
  */
160
- export declare function buildTrajectory(events: readonly ConversationEvent[], prices: PriceTable): TrajectoryRun[];
157
+ export declare function buildTrajectory(events: readonly ConversationEvent[]): TrajectoryRun[];
@@ -1,4 +1,4 @@
1
- import { costOf, priceKey } from "../models/prices.js";
1
+ import { addUsageCost, emptyUsageCost, snapshotCost, } from "../models/price-snapshot.js";
2
2
  const iso = (d) => d.toISOString();
3
3
  const denialOf = (e) => ({
4
4
  plugin: e.payload.plugin,
@@ -12,18 +12,34 @@ const zeroUsage = () => ({
12
12
  cacheReadTokens: 0,
13
13
  cacheWriteTokens: 0,
14
14
  });
15
+ /** Stored events can predate today's usage validation. */
16
+ function storedCount(value) {
17
+ if (typeof value !== "number" || !Number.isFinite(value))
18
+ return 0;
19
+ return Math.sign(value) * Math.round(Math.abs(value));
20
+ }
15
21
  const usageOf = (p) => ({
16
- inputTokens: p.inputTokens,
17
- outputTokens: p.outputTokens,
18
- cacheReadTokens: p.cacheReadTokens,
19
- cacheWriteTokens: p.cacheWriteTokens,
22
+ inputTokens: storedCount(p.inputTokens),
23
+ outputTokens: storedCount(p.outputTokens),
24
+ cacheReadTokens: storedCount(p.cacheReadTokens),
25
+ cacheWriteTokens: storedCount(p.cacheWriteTokens),
26
+ ...(p.outputImages !== undefined && { outputImages: storedCount(p.outputImages) }),
20
27
  ...(p.cacheWriteByTtl !== undefined && { cacheWriteByTtl: p.cacheWriteByTtl }),
21
28
  });
29
+ function sumUsage(total, usage) {
30
+ total.inputTokens += usage.inputTokens;
31
+ total.outputTokens += usage.outputTokens;
32
+ total.cacheReadTokens += usage.cacheReadTokens;
33
+ total.cacheWriteTokens += usage.cacheWriteTokens;
34
+ if (usage.outputImages !== undefined) {
35
+ total.outputImages = (total.outputImages ?? 0) + usage.outputImages;
36
+ }
37
+ }
22
38
  /**
23
39
  * 由会话事件推出各次运行的轨迹,按 `run_started` 的 seq 排序。没有 `run_started` 的运行(排队时就被中止 /
24
40
  * 判为孤儿,从未开始)不出现;没有 `runId` 的事件(用户消息等)不属于任何运行。
25
41
  */
26
- export function buildTrajectory(events, prices) {
42
+ export function buildTrajectory(events) {
27
43
  const sorted = [...events].sort((a, b) => a.seq - b.seq);
28
44
  const byRun = new Map();
29
45
  for (const e of sorted) {
@@ -50,7 +66,7 @@ export function buildTrajectory(events, prices) {
50
66
  forks.set(e.seq, e.payload.skill);
51
67
  }
52
68
  }
53
- return runs.map((r) => buildRun(r, prices, forks));
69
+ return runs.map((r) => buildRun(r, forks));
54
70
  }
55
71
  /** The run's fork span (phase D): from its fork dispatch or its fork report. */
56
72
  function skillForkOf(events, forks) {
@@ -82,7 +98,7 @@ function skillForkOf(events, forks) {
82
98
  report: report?.payload.text ?? null,
83
99
  };
84
100
  }
85
- function buildRun({ started, events }, prices, forks) {
101
+ function buildRun({ started, events }, forks) {
86
102
  const runId = started.runId ?? "";
87
103
  const endEvent = events.find((e) => e.type === "run_finished" || e.type === "run_failed" || e.type === "run_aborted");
88
104
  const end = endEvent === undefined
@@ -191,7 +207,7 @@ function buildRun({ started, events }, prices, forks) {
191
207
  }
192
208
  const totals = {
193
209
  usage: zeroUsage(),
194
- cost: 0,
210
+ cost: emptyUsageCost(),
195
211
  modelCalls: 0,
196
212
  toolCalls: 0,
197
213
  durationMs: endEvent === undefined ? null : ms(started.createdAt, endEvent.createdAt),
@@ -208,9 +224,7 @@ function buildRun({ started, events }, prices, forks) {
208
224
  const last = i === calls.length - 1;
209
225
  const ok = last && u !== undefined;
210
226
  const callUsage = ok ? usageOf(u.payload) : null;
211
- const cost = callUsage === null
212
- ? null
213
- : costOf(callUsage, prices.get(priceKey(c.payload.provider, c.payload.model)));
227
+ const cost = callUsage === null ? null : snapshotCost(u?.payload.priceSnapshot, callUsage);
214
228
  return {
215
229
  seq: c.seq,
216
230
  step,
@@ -302,11 +316,9 @@ function buildRun({ started, events }, prices, forks) {
302
316
  totals.modelCalls++;
303
317
  if (c.usage === null)
304
318
  continue;
305
- totals.usage.inputTokens += c.usage.inputTokens;
306
- totals.usage.outputTokens += c.usage.outputTokens;
307
- totals.usage.cacheReadTokens += c.usage.cacheReadTokens;
308
- totals.usage.cacheWriteTokens += c.usage.cacheWriteTokens;
309
- totals.cost = totals.cost === null || c.cost === null ? null : totals.cost + c.cost;
319
+ sumUsage(totals.usage, c.usage);
320
+ if (c.cost !== null)
321
+ addUsageCost(totals.cost, c.cost);
310
322
  }
311
323
  totals.toolCalls += toolOut.length;
312
324
  const modelDenied = modelDenials.get(step);
@@ -330,12 +342,8 @@ function buildRun({ started, events }, prices, forks) {
330
342
  });
331
343
  for (const c of compactions) {
332
344
  const u = usageOf(c.payload);
333
- totals.usage.inputTokens += u.inputTokens;
334
- totals.usage.outputTokens += u.outputTokens;
335
- totals.usage.cacheReadTokens += u.cacheReadTokens;
336
- totals.usage.cacheWriteTokens += u.cacheWriteTokens;
337
- const cost = costOf(u, prices.get(priceKey(c.payload.provider, c.payload.model)));
338
- totals.cost = totals.cost === null || cost === null ? null : totals.cost + cost;
345
+ sumUsage(totals.usage, u);
346
+ addUsageCost(totals.cost, snapshotCost(c.payload.priceSnapshot, u));
339
347
  }
340
348
  const skillFork = skillForkOf(events, forks);
341
349
  return {
@@ -1,9 +1,7 @@
1
1
  import { EventLog } from "../conversations/event-log.js";
2
2
  import type { ConversationKind } from "../db/kernel-schema.js";
3
3
  import type { PersonRef } from "../identity/account-avatar.js";
4
- import { SettingsService } from "../identity/settings.js";
5
4
  import { KernelDb } from "../infra/database/kernel-db.js";
6
- import { PricesService } from "../models/prices.js";
7
5
  import { type TrajectoryRun } from "./trajectory.js";
8
6
  /** 轨迹列表的一项(不含对话内容,列表不写审计)。 */
9
7
  export interface TrajectoryListItem {
@@ -40,8 +38,6 @@ export interface TrajectoryDetail {
40
38
  runs: TrajectoryRun[];
41
39
  /** Every account the events name (and the conversation's owner), by id; read time. */
42
40
  people: Record<string, PersonRef>;
43
- /** 成本的币种(部署设置 `priceCurrency`)。 */
44
- currency: string;
45
41
  /**
46
42
  * 只在按运行分页(给了 `limit` / `before`)时出现:更早一页的游标(本页最早一次运行的 id,作为 `before`
47
43
  * 传回);没有更早的运行时为 null。给 `runId` 时总是 null。不带窗口时没有这个字段(形状与以前一致)。
@@ -70,9 +66,7 @@ export type RunStatus = (typeof RUN_STATUSES)[number];
70
66
  export declare class TrajectoryService {
71
67
  private readonly db;
72
68
  private readonly eventLog;
73
- private readonly prices;
74
- private readonly settings;
75
- constructor(db: KernelDb, eventLog: EventLog, prices: PricesService, settings: SettingsService);
69
+ constructor(db: KernelDb, eventLog: EventLog);
76
70
  /** 调用者当前在组织里的角色;不是成员或组织已删除 → null。 */
77
71
  private role;
78
72
  /** 至少是 member(guest 不能看轨迹)。 */
@@ -15,9 +15,7 @@ import { EventLog } from "../conversations/event-log.js";
15
15
  import { peopleOfEvents } from "../conversations/event-people.js";
16
16
  import { ApiError } from "../errors.js";
17
17
  import { audit } from "../identity/audit.js";
18
- import { SettingsService } from "../identity/settings.js";
19
18
  import { KernelDb } from "../infra/database/kernel-db.js";
20
- import { PricesService } from "../models/prices.js";
21
19
  import { roleAtLeast } from "../orgs/roles.js";
22
20
  import { buildTrajectory } from "./trajectory.js";
23
21
  /** 运行的状态(`runs.status`),列表按最近一次运行的状态过滤用。 */
@@ -44,13 +42,9 @@ const notFound = () => new ApiError("trajectory.not_found", "Trajectory not foun
44
42
  let TrajectoryService = TrajectoryService_1 = class TrajectoryService {
45
43
  db;
46
44
  eventLog;
47
- prices;
48
- settings;
49
- constructor(db, eventLog, prices, settings) {
45
+ constructor(db, eventLog) {
50
46
  this.db = db;
51
47
  this.eventLog = eventLog;
52
- this.prices = prices;
53
- this.settings = settings;
54
48
  }
55
49
  /** 调用者当前在组织里的角色;不是成员或组织已删除 → null。 */
56
50
  async role(orgId, accountId) {
@@ -213,7 +207,9 @@ let TrajectoryService = TrajectoryService_1 = class TrajectoryService {
213
207
  let next;
214
208
  if (window === undefined) {
215
209
  for (let after = 0;;) {
216
- const page = await this.eventLog.readAfter(conversationId, after, EVENT_PAGE);
210
+ const page = await this.eventLog.readAfter(conversationId, after, EVENT_PAGE, {
211
+ includeUsagePricing: true,
212
+ });
217
213
  events.push(...page);
218
214
  const last = page.at(-1);
219
215
  if (page.length < EVENT_PAGE || last === undefined)
@@ -228,7 +224,9 @@ let TrajectoryService = TrajectoryService_1 = class TrajectoryService {
228
224
  let after = Math.min(...picked.runs.map((r) => r.triggerSeq));
229
225
  const ids = picked.runs.map((r) => r.id);
230
226
  while (ids.length > 0) {
231
- const page = await this.eventLog.readRunsAfter(conversationId, ids, after, EVENT_PAGE);
227
+ const page = await this.eventLog.readRunsAfter(conversationId, ids, after, EVENT_PAGE, {
228
+ includeUsagePricing: true,
229
+ });
232
230
  events.push(...page);
233
231
  const last = page.at(-1);
234
232
  if (page.length < EVENT_PAGE || last === undefined)
@@ -236,11 +234,7 @@ let TrajectoryService = TrajectoryService_1 = class TrajectoryService {
236
234
  after = last.seq;
237
235
  }
238
236
  }
239
- const [table, settings, parent] = await Promise.all([
240
- this.prices.table(),
241
- this.settings.get(),
242
- conv.kind === "subagent" ? this.firstDispatch(conv.id) : undefined,
243
- ]);
237
+ const parent = conv.kind === "subagent" ? await this.firstDispatch(conv.id) : undefined;
244
238
  await audit(this.db.db, {
245
239
  actorAccountId: accountId,
246
240
  ...(actorTokenId !== undefined && { actorTokenId }),
@@ -258,9 +252,8 @@ let TrajectoryService = TrajectoryService_1 = class TrajectoryService {
258
252
  kind: conv.kind,
259
253
  ...(parent !== undefined && { parent }),
260
254
  },
261
- runs: buildTrajectory(events, table),
255
+ runs: buildTrajectory(events),
262
256
  people: await peopleOfEvents(this.db.db, events, [conv.account_id]),
263
- currency: settings.priceCurrency,
264
257
  ...(next !== undefined && { next }),
265
258
  };
266
259
  }
@@ -354,8 +347,6 @@ let TrajectoryService = TrajectoryService_1 = class TrajectoryService {
354
347
  TrajectoryService = TrajectoryService_1 = __decorate([
355
348
  Injectable(),
356
349
  __param(0, Inject(KernelDb)),
357
- __param(1, Inject(EventLog)),
358
- __param(2, Inject(PricesService)),
359
- __param(3, Inject(SettingsService))
350
+ __param(1, Inject(EventLog))
360
351
  ], TrajectoryService);
361
352
  export { TrajectoryService };
@@ -72,6 +72,8 @@ export declare class EvalWorker {
72
72
  close(budgetMs: number): Promise<void>;
73
73
  /** One job: replays one case (the processor runs it in `runJob`). */
74
74
  process(job: Job<EvalJobData>, token: string | undefined): Promise<void>;
75
+ private inRunOrg;
76
+ private processInOrg;
75
77
  /** 单步回放每次请求前:运行仍在执行({@link runActive})且结果仍由本次执行认领。 */
76
78
  private mayRequest;
77
79
  /**
@@ -20,6 +20,7 @@ import { audit } from "../identity/audit.js";
20
20
  import { waitWithin } from "../infra/close-within.js";
21
21
  import { KernelConfigService } from "../infra/config/kernel-config.service.js";
22
22
  import { KernelDb } from "../infra/database/kernel-db.js";
23
+ import { asPlatform, withOrgScope } from "../infra/database/org-scope.js";
23
24
  import { TransactionHost } from "../infra/database/transaction-host.js";
24
25
  import { Transactional } from "../infra/database/transactional.decorator.js";
25
26
  import { KERNEL_LOGGER } from "../infra/tokens.js";
@@ -262,7 +263,7 @@ let EvalWorker = class EvalWorker {
262
263
  }
263
264
  this.d.log.error("eval job failed", { jobId: job.id, err });
264
265
  // 任务不会再执行:该用例剩下的结果记 error,运行不因此卡住
265
- void this.failCase(job.data, err).catch((e) => this.d.log.error("cannot mark failed eval job", { jobId: job.id, err: e }));
266
+ void this.inRunOrg(job.data, (data) => this.failCase(data, err)).catch((e) => this.d.log.error("cannot mark failed eval job", { jobId: job.id, err: e }));
266
267
  }
267
268
  /** 停止领取;中止本进程在执行的任务(回到队列由别的 worker 接着做),在 budgetMs 内等它们退出。 */
268
269
  async close(budgetMs) {
@@ -280,7 +281,19 @@ let EvalWorker = class EvalWorker {
280
281
  }
281
282
  /** One job: replays one case (the processor runs it in `runJob`). */
282
283
  async process(job, token) {
283
- const data = job.data;
284
+ await this.inRunOrg(job.data, (data) => this.processInOrg(job, token, data));
285
+ }
286
+ async inRunOrg(data, handle) {
287
+ // org-filter: deployment-wide lookup of the owner of a queued eval run
288
+ const run = await asPlatform("resolve the org of a queued eval run", () => this.d.db
289
+ .selectFrom("eval_runs")
290
+ .select("org_id")
291
+ .where("id", "=", data.runId)
292
+ .executeTakeFirst());
293
+ if (run)
294
+ await withOrgScope(run.org_id, () => handle({ ...data, orgId: run.org_id }));
295
+ }
296
+ async processInOrg(job, token, data) {
284
297
  const { runId, orgId } = data;
285
298
  const jobId = job.id ?? evalJobId(runId, data.caseId);
286
299
  if (!(await runActive(this.d.db, runId))) {
@@ -11,6 +11,7 @@ import { PermissionCeilingWrites } from "../sandbox/permission-ceiling-writes.js
11
11
  import { type ExternalSharingView, type ShareMaxExpiryView } from "../shares/settings.js";
12
12
  import { type UiArrangement } from "../ui/arrangement.js";
13
13
  import { SuperAdminLock } from "./super-admin.js";
14
+ /** 币种代码:ISO 4217 的三位大写字母(如 USD、CNY)。 */
14
15
  /** 沙箱 cpu(核)与内存(MB)覆盖的范围(C19)。 */
15
16
  export declare const SANDBOX_CPU_RANGE: {
16
17
  readonly min: 0.25;