@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
@@ -19,6 +19,7 @@ import { KernelDb } from "../infra/database/kernel-db.js";
19
19
  import { TransactionHost, withOrderedLocks } from "../infra/database/transaction-host.js";
20
20
  import { Transactional } from "../infra/database/transactional.decorator.js";
21
21
  import { KERNEL_LOGGER } from "../infra/tokens.js";
22
+ import { DEFAULT_PRICE_CURRENCY, PriceCurrency } from "../models/price-snapshot.js";
22
23
  import { applyDevicesNetworkPatch, applyDevicesOutsideSandboxPatch, configuredDeviceSandbox, DEVICES_ALLOWED_PROFILES_PATCH, DEVICES_ALLOWED_PROFILES_SETTING, DEVICES_NETWORK_PATCH, DEVICES_NETWORK_SETTING, DEVICES_OUTSIDE_SANDBOX_PATCH, DEVICES_OUTSIDE_SANDBOX_SETTING, DEVICES_PROJECT_REACH_PATCH, DEVICES_PROJECT_REACH_SETTING, orgDeviceSandboxOf, readDeviceSandboxSettingsView, readStoredDeviceSandbox, resolveDeviceSandboxSettings, } from "../sandbox/device-sandbox-settings.js";
23
24
  import { devicesFollowingDefault, needsFullCeiling, needsOpenNetwork, PermissionCeilingWrites, reachNarrowed, } from "../sandbox/permission-ceiling-writes.js";
24
25
  import { EXTERNAL_SHARING_SETTING, ExternalSharingValue, HTML_CDN_ALLOWLIST_DEFAULT, HtmlCdnAllowlistSchema, readExternalSharing, readHtmlCdnAllowlist, readShareMaxExpiry, SHARE_MAX_EXPIRY_DEFAULT, SHARE_MAX_EXPIRY_SETTING, ShareMaxExpiryDays, } from "../shares/settings.js";
@@ -27,7 +28,6 @@ import { mergeArrangement, UiArrangementPatchSchema, UiArrangementSchema, } from
27
28
  import { audit } from "./audit.js";
28
29
  import { SuperAdminLock } from "./super-admin.js";
29
30
  /** 币种代码:ISO 4217 的三位大写字母(如 USD、CNY)。 */
30
- const CurrencyCode = z.string().regex(/^[A-Z]{3}$/, "must be a 3-letter ISO 4217 currency code");
31
31
  /** 沙箱 cpu(核)与内存(MB)覆盖的范围(C19)。 */
32
32
  export const SANDBOX_CPU_RANGE = { min: 0.25, max: 64 };
33
33
  export const SANDBOX_MEMORY_MB_RANGE = { min: 256, max: 262_144 };
@@ -203,7 +203,7 @@ export const DEPLOYMENT_SETTINGS = z.object({
203
203
  /** 按组织覆盖运行并发上限(orgId → 上限);未列出的组织用 `runtime.orgConcurrency`。 */
204
204
  runConcurrencyOverrides: z.record(z.string().min(1), z.number().int().positive()).default({}),
205
205
  /** 模型价格表(`model_prices`)的币种;只用于显示估算成本,不做换算。 */
206
- priceCurrency: CurrencyCode.default("USD"),
206
+ priceCurrency: PriceCurrency.default(DEFAULT_PRICE_CURRENCY),
207
207
  /** 按组织覆盖沙箱 cpu / 内存(orgId → 覆盖,C19);只对之后新建的沙箱生效。组织管理员只读。 */
208
208
  sandboxLimitOverrides: z.record(z.string().min(1), SANDBOX_LIMIT_OVERRIDE).default({}),
209
209
  /**
@@ -288,7 +288,7 @@ export const DEPLOYMENT_SETTINGS_PATCH = z
288
288
  runConcurrencyOverrides: z
289
289
  .record(z.string().min(1), z.number().int().positive().nullable())
290
290
  .optional(),
291
- priceCurrency: CurrencyCode.optional(),
291
+ priceCurrency: PriceCurrency.optional(),
292
292
  sandboxLimitOverrides: z
293
293
  .record(z.string().min(1), SANDBOX_LIMIT_OVERRIDE.nullable())
294
294
  .optional(),
package/dist/index.d.ts CHANGED
@@ -64,7 +64,7 @@ export type { RlsMode } from "./infra/database/scoped-dialect.js";
64
64
  export { onProcessFault } from "./infra/health/process-fault.js";
65
65
  export { GUARD_CIRCUIT_LIMIT, GUARD_CIRCUIT_WINDOW_MS, installProcessGuards, type ProcessGuardDeps, } from "./infra/lifecycle/process-guards.js";
66
66
  export { handleShutdownSignals, type ShutdownSignalHandle, type ShutdownSignalOptions, } from "./infra/lifecycle/shutdown-signals.js";
67
- export { KERNEL_MIGRATIONS_DIR, KERNEL_SCHEMA, migrateAll } from "./kernel.js";
67
+ export { KERNEL_MIGRATIONS_DIR, KERNEL_SCHEMA, migrateAll, prepareKernelDatabase, } from "./kernel.js";
68
68
  export { createLogger, type KernelLogger, LOG_FORMATS, LOG_LEVELS, type LogFormat, type LoggerOptions, type LogLevel, type LogOutput, } from "./log.js";
69
69
  export { createConfiguredLogger, loggerOptionsFromConfig } from "./log-config.js";
70
70
  export { type ContextJob, type JobWrapper, type LogContext, logContext, setJobWrapper, setTraceContextSource, withJobContext, withLogContext, } from "./log-context.js";
package/dist/index.js CHANGED
@@ -61,7 +61,7 @@ export { asPlatform, currentScope, setUnscopedQueryCheck, withOrgScope, } from "
61
61
  export { onProcessFault } from "./infra/health/process-fault.js";
62
62
  export { GUARD_CIRCUIT_LIMIT, GUARD_CIRCUIT_WINDOW_MS, installProcessGuards, } from "./infra/lifecycle/process-guards.js";
63
63
  export { handleShutdownSignals, } from "./infra/lifecycle/shutdown-signals.js";
64
- export { KERNEL_MIGRATIONS_DIR, KERNEL_SCHEMA, migrateAll } from "./kernel.js";
64
+ export { KERNEL_MIGRATIONS_DIR, KERNEL_SCHEMA, migrateAll, prepareKernelDatabase, } from "./kernel.js";
65
65
  export { createLogger, LOG_FORMATS, LOG_LEVELS, } from "./log.js";
66
66
  export { createConfiguredLogger, loggerOptionsFromConfig } from "./log-config.js";
67
67
  export { logContext, setJobWrapper, setTraceContextSource, withJobContext, withLogContext, } from "./log-context.js";
@@ -88,6 +88,20 @@ export declare const OUTBOX_JOBS: {
88
88
  readonly removeOnFail: true;
89
89
  };
90
90
  };
91
+ readonly "conversation-events-org-backfill": {
92
+ readonly queue: "cap-kernel-maintenance";
93
+ readonly idempotent: "Locks up to 5,000 NULL org_id rows after its (conversation_id, seq) cursor with FOR UPDATE SKIP LOCKED and fills each from its conversation's org_id; rows already filled are skipped and the next batch is owed atomically under a deterministic cursor job id";
94
+ readonly processedIn: "packages/kernel/src/runtime/maintenance.ts";
95
+ readonly opts: {
96
+ readonly attempts: 5;
97
+ readonly backoff: {
98
+ readonly type: "exponential";
99
+ readonly delay: 5000;
100
+ };
101
+ readonly removeOnComplete: true;
102
+ readonly removeOnFail: true;
103
+ };
104
+ };
91
105
  readonly "file-release": {
92
106
  readonly queue: "cap-kernel-maintenance";
93
107
  readonly idempotent: "Re-reads the deleted file under its row lock and releases its blob only while nothing else points at it, or deletes its own staging key; a second run finds nothing to do";
@@ -86,6 +86,21 @@ export const OUTBOX_JOBS = {
86
86
  removeOnFail: true,
87
87
  },
88
88
  },
89
+ // `conversations/event-org-backfill.ts` EVENT_ORG_BACKFILL_JOB: batched backfill of
90
+ // `conversation_events.org_id` from `conversations`, owed by the periodic kickoff under
91
+ // `eventOrgBackfillJobId(null)` and chained per 5,000-row batch under `eventOrgBackfillJobId(last)`
92
+ "conversation-events-org-backfill": {
93
+ queue: "cap-kernel-maintenance",
94
+ idempotent: "Locks up to 5,000 NULL org_id rows after its (conversation_id, seq) cursor with FOR UPDATE SKIP LOCKED and fills each from its conversation's org_id; rows already filled are skipped and the next batch is owed atomically under a deterministic cursor job id",
95
+ processedIn: "packages/kernel/src/runtime/maintenance.ts",
96
+ // removed either way, so a later kickoff during a rolling deploy can owe the first batch again
97
+ opts: {
98
+ attempts: 5,
99
+ backoff: { type: "exponential", delay: 5_000 },
100
+ removeOnComplete: true,
101
+ removeOnFail: true,
102
+ },
103
+ },
89
104
  // `files/blob-objects.ts` FILE_RELEASE_JOB: owed, deferred, by every discard and draft cleanup
90
105
  // of an upload, under `fileReleaseJobId`
91
106
  "file-release": {
package/dist/kernel.d.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import type { QueryExecutorProvider } from "kysely";
1
2
  import type { KernelConfig } from "./config/schema.js";
2
3
  import type { PendingExtension } from "./extensions/approvals.js";
3
4
  /**
@@ -9,6 +10,11 @@ import type { PendingExtension } from "./extensions/approvals.js";
9
10
  export declare const KERNEL_MIGRATIONS_DIR: string;
10
11
  /** The kernel's PG schema. */
11
12
  export declare const KERNEL_SCHEMA = "capybara";
13
+ /** Only a login with migration privileges can initialize the kernel schema at startup. */
14
+ export declare function prepareKernelDatabase(db: KernelConfig["db"], opts?: {
15
+ pool?: QueryExecutorProvider;
16
+ signal?: AbortSignal;
17
+ }): Promise<void>;
12
18
  /**
13
19
  * Runs the kernel migrations and those of every configured extension (no extension `setup`, no
14
20
  * Redis connection). Extensions whose permissions await approval are not migrated (unless
package/dist/kernel.js CHANGED
@@ -1,5 +1,6 @@
1
1
  import { fileURLToPath } from "node:url";
2
- import { migrate } from "./db/migrator.js";
2
+ import { canMigrateKernel, migrate, verifyMigrations } from "./db/migrator.js";
3
+ import { createDb } from "./db/pool.js";
3
4
  import { ExtensionHost } from "./extensions/host.js";
4
5
  /**
5
6
  * The kernel migrations directory. `src/` and `dist/` are both one level below the package root,
@@ -10,6 +11,32 @@ import { ExtensionHost } from "./extensions/host.js";
10
11
  export const KERNEL_MIGRATIONS_DIR = fileURLToPath(new URL("../src/migrations/", import.meta.url));
11
12
  /** The kernel's PG schema. */
12
13
  export const KERNEL_SCHEMA = "capybara";
14
+ const coreMigrations = { schema: KERNEL_SCHEMA, dir: KERNEL_MIGRATIONS_DIR };
15
+ /** Only a login with migration privileges can initialize the kernel schema at startup. */
16
+ export async function prepareKernelDatabase(db, opts = {}) {
17
+ if (db.migrationUrl !== undefined)
18
+ throw new Error("db.migrationUrl may only be set for capybara migrate");
19
+ const prepare = async (pool) => {
20
+ if (await canMigrateKernel(pool)) {
21
+ await migrate(db.url, coreMigrations, {
22
+ connectTimeoutMs: db.connectTimeoutMs,
23
+ signal: opts.signal,
24
+ });
25
+ }
26
+ else {
27
+ await verifyMigrations(pool, coreMigrations);
28
+ }
29
+ };
30
+ if (opts.pool !== undefined)
31
+ return prepare(opts.pool);
32
+ const pool = createDb(db.url, 1, undefined, { connectTimeoutMs: db.connectTimeoutMs });
33
+ try {
34
+ await prepare(pool);
35
+ }
36
+ finally {
37
+ await pool.destroy();
38
+ }
39
+ }
13
40
  /**
14
41
  * Runs the kernel migrations and those of every configured extension (no extension `setup`, no
15
42
  * Redis connection). Extensions whose permissions await approval are not migrated (unless
@@ -17,7 +44,9 @@ export const KERNEL_SCHEMA = "capybara";
17
44
  */
18
45
  export async function migrateAll(config, opts = {}) {
19
46
  const connectTimeoutMs = config.db.connectTimeoutMs;
20
- const kernel = await migrate(config.db.url, { schema: KERNEL_SCHEMA, dir: KERNEL_MIGRATIONS_DIR }, { connectTimeoutMs });
47
+ const kernel = await migrate(config.db.migrationUrl ?? config.db.url, coreMigrations, {
48
+ connectTimeoutMs,
49
+ });
21
50
  const plugins = await ExtensionHost.migrateOnly(config.extensions, {
22
51
  dbUrl: config.db.url,
23
52
  connectTimeoutMs,
@@ -17,7 +17,6 @@ import { ChannelJobs } from "../channels/jobs.js";
17
17
  import { ChannelOutbound } from "../channels/outbound.js";
18
18
  import { PromptSuggestionQueue } from "../conversations/prompt-suggestions.js";
19
19
  import { TitleQueue } from "../conversations/titles.js";
20
- import { migrate } from "../db/migrator.js";
21
20
  import { ExtensionBlobs } from "../extensions/blobs.js";
22
21
  import { BootstrapFailedError, BootstrapService, } from "../extensions/bootstrap.js";
23
22
  import { BootstrapDefaultsService } from "../extensions/bootstrap-defaults.js";
@@ -39,7 +38,7 @@ import { rlsEnforceProblem } from "../infra/database/rls-role.js";
39
38
  import { GracefulShutdown } from "../infra/lifecycle/graceful-shutdown.service.js";
40
39
  import { ReplicaPresence } from "../infra/presence/replica-presence.js";
41
40
  import { KERNEL_BUS, KERNEL_LOGGER, KERNEL_POOL, REDIS } from "../infra/tokens.js";
42
- import { KERNEL_MIGRATIONS_DIR, KERNEL_SCHEMA } from "../kernel.js";
41
+ import { prepareKernelDatabase } from "../kernel.js";
43
42
  import { GatewayRole } from "../roles/gateway-role.js";
44
43
  import { WorkerRole } from "../roles/worker-role.js";
45
44
  import { UsageReporter } from "../runtime/usage-report.js";
@@ -231,7 +230,7 @@ let KernelLifecycle = class KernelLifecycle {
231
230
  }
232
231
  }
233
232
  // In flight for the stop: aborted when the shutdown begins, which then waits for its session to end
234
- await this.shutdown.trackInFlight(migrate(config.db.url, { schema: KERNEL_SCHEMA, dir: KERNEL_MIGRATIONS_DIR }, { connectTimeoutMs: config.db.connectTimeoutMs, signal: this.shutdown.signal }));
233
+ await this.shutdown.trackInFlight(prepareKernelDatabase(config.db, { pool: this.pool, signal: this.shutdown.signal }));
235
234
  this.checkpoint();
236
235
  const publication = await this.shutdown.trackInFlight(this.permissionConfig.initialize({
237
236
  ...(opts.permissionConfigActivation !== undefined && {
@@ -67,6 +67,7 @@ export declare class ModelEmbeddings {
67
67
  * host's hook registry (`model.request`), absent only for a ctx built without a host (tests).
68
68
  */
69
69
  embed(plugin: string, declared: DeclaredModelPurposes, request: ExtensionEmbedRequest, signal: AbortSignal, hooks: HookRunner | undefined): Promise<ExtensionEmbedResult>;
70
+ private embedInOrg;
70
71
  /** `ctx.models.describe` for `plugin`: null when the purpose maps to no model the org can use. */
71
72
  describe(plugin: string, declared: DeclaredModelPurposes, req: {
72
73
  orgId: string;
@@ -14,6 +14,7 @@ import { isExtensionEnabled } from "../extensions/enabled.js";
14
14
  import { audit } from "../identity/audit.js";
15
15
  import { KernelConfigService } from "../infra/config/kernel-config.service.js";
16
16
  import { KernelDb } from "../infra/database/kernel-db.js";
17
+ import { withOrgScope } from "../infra/database/org-scope.js";
17
18
  import { TransactionHost } from "../infra/database/transaction-host.js";
18
19
  import { Transactional } from "../infra/database/transactional.decorator.js";
19
20
  import { KERNEL_LOGGER } from "../infra/tokens.js";
@@ -21,6 +22,7 @@ import { embeddingDeniedAudit } from "../runtime/hook-calls.js";
21
22
  import { modelDeniedText } from "../runtime/model-call.js";
22
23
  import { ModelRequestDenied, ProviderRegistry, prepareEmbedding, supportsEmbedding, } from "../runtime/providers.js";
23
24
  import { UsageReportJobs } from "../runtime/usage-report-jobs.js";
25
+ import { readPriceSnapshot } from "./price-snapshot.js";
24
26
  import { ModelPurposesService } from "./purposes.js";
25
27
  /** Most texts one `ctx.models.embed` call may carry (the kernel splits them by `maxBatch`). */
26
28
  export const EMBED_MAX_INPUTS = 2048;
@@ -140,6 +142,9 @@ let ModelEmbeddings = class ModelEmbeddings {
140
142
  // a copy, read once: the texts the hooks see are the texts sent, whatever the extension does
141
143
  // with its own request object meanwhile
142
144
  const req = { ...request, input: request.input.slice() };
145
+ return withOrgScope(req.orgId, () => this.embedInOrg(plugin, declared, req, signal, hooks));
146
+ }
147
+ async embedInOrg(plugin, declared, req, signal, hooks) {
143
148
  await this.admit(plugin, declared, req.orgId, req.purpose);
144
149
  const t = await this.target(req.orgId, req.purpose);
145
150
  const dimensions = req.dimensions ?? t.info.defaultDimensions;
@@ -237,10 +242,13 @@ let ModelEmbeddings = class ModelEmbeddings {
237
242
  }
238
243
  /** One `model_usage` row with its owed `usage.report` delivery. */
239
244
  async record(plugin, orgId, purpose, model, inputTokens) {
245
+ const ref = { provider: model.provider, model: model.id };
246
+ const priceSnapshot = await readPriceSnapshot(this.kdb.db, ref);
240
247
  const row = await this.kdb.db
241
248
  .insertInto("model_usage")
242
249
  .values({
243
250
  org_id: orgId,
251
+ price_snapshot: JSON.stringify(priceSnapshot),
244
252
  extension: plugin,
245
253
  purpose,
246
254
  provider: model.provider,
@@ -90,6 +90,7 @@ export declare class ModelImages {
90
90
  * (`model.request`, `model.response`), absent only for a ctx built without a host (tests).
91
91
  */
92
92
  generateForExtension(plugin: string, declared: DeclaredModelPurposes, request: ExtensionImageGenerateRequest, signal: AbortSignal, hooks: HookRunner | undefined): Promise<ExtensionImageGenerateResult>;
93
+ private generateInOrg;
93
94
  /**
94
95
  * `ctx.models.describe` of an image generation purpose for `plugin`: the org's effective target
95
96
  * with its `imageGeneration` facts, or null when the purpose maps to no model the org can use.
@@ -14,6 +14,7 @@ import { isExtensionEnabled } from "../extensions/enabled.js";
14
14
  import { audit } from "../identity/audit.js";
15
15
  import { KernelConfigService } from "../infra/config/kernel-config.service.js";
16
16
  import { KernelDb } from "../infra/database/kernel-db.js";
17
+ import { withOrgScope } from "../infra/database/org-scope.js";
17
18
  import { TransactionHost } from "../infra/database/transaction-host.js";
18
19
  import { Transactional } from "../infra/database/transactional.decorator.js";
19
20
  import { KERNEL_LOGGER } from "../infra/tokens.js";
@@ -22,6 +23,7 @@ import { modelDeniedText, trustedUsage } from "../runtime/model-call.js";
22
23
  import { ModelRequestDenied, ProviderRegistry, prepareImageGeneration, } from "../runtime/providers.js";
23
24
  import { UsageReportJobs } from "../runtime/usage-report-jobs.js";
24
25
  import { imageInputCaps } from "./image-usable.js";
26
+ import { readPriceSnapshot } from "./price-snapshot.js";
25
27
  import { ModelPurposesService } from "./purposes.js";
26
28
  /** Standard padded base64 (the check `validateImageGenerateResult` applies to results). */
27
29
  const BASE64 = /^[A-Za-z0-9+/]+={0,2}$/;
@@ -88,6 +90,9 @@ let ModelImages = class ModelImages {
88
90
  */
89
91
  async generateForExtension(plugin, declared, request, signal, hooks) {
90
92
  checkExtensionRequest(request);
93
+ return withOrgScope(request.orgId, () => this.generateInOrg(plugin, declared, request, signal, hooks));
94
+ }
95
+ async generateInOrg(plugin, declared, request, signal, hooks) {
91
96
  // a copy, read once: what the hooks see is what is sent, whatever the extension does with its
92
97
  // own request object meanwhile
93
98
  const { orgId, purpose } = request;
@@ -174,10 +179,12 @@ let ModelImages = class ModelImages {
174
179
  * and images) with its owed `usage.report` delivery, in one transaction.
175
180
  */
176
181
  async recordExtensionUsage(plugin, orgId, purpose, ref, res) {
182
+ const priceSnapshot = await readPriceSnapshot(this.kdb.db, ref);
177
183
  const row = await this.kdb.db
178
184
  .insertInto("model_usage")
179
185
  .values({
180
186
  org_id: orgId,
187
+ price_snapshot: JSON.stringify(priceSnapshot),
181
188
  extension: plugin,
182
189
  purpose,
183
190
  kind: "image_generation",
@@ -0,0 +1,43 @@
1
+ import type { ModelUsage } from "@capybara-hq/plugin-sdk";
2
+ import { z } from "zod";
3
+ import type { KernelSchemaDb } from "../db/kernel-schema.js";
4
+ export declare const PriceCurrency: z.ZodString;
5
+ export declare const DEFAULT_PRICE_CURRENCY = "USD";
6
+ export declare const PriceSnapshotSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{
7
+ version: z.ZodLiteral<1>;
8
+ currency: z.ZodString;
9
+ status: z.ZodLiteral<"priced">;
10
+ inputPerMTok: z.ZodString;
11
+ outputPerMTok: z.ZodString;
12
+ cacheReadPerMTok: z.ZodNullable<z.ZodString>;
13
+ cacheWritePerMTok: z.ZodNullable<z.ZodString>;
14
+ cacheWritePerMTokByTtl: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodString>>;
15
+ }, z.core.$strip>, z.ZodObject<{
16
+ version: z.ZodLiteral<1>;
17
+ currency: z.ZodString;
18
+ status: z.ZodLiteral<"unpriced">;
19
+ }, z.core.$strip>], "status">;
20
+ export type PriceSnapshot = z.infer<typeof PriceSnapshotSchema>;
21
+ interface ModelRef {
22
+ provider: string;
23
+ model: string;
24
+ }
25
+ /** Read the setting and the requested rates in one statement in the caller's usage transaction. */
26
+ export declare function readPriceSnapshots(db: KernelSchemaDb, models: readonly ModelRef[]): Promise<(ref: ModelRef) => PriceSnapshot>;
27
+ export declare function readPriceSnapshot(db: KernelSchemaDb, model: ModelRef): Promise<PriceSnapshot>;
28
+ export interface UsageCost {
29
+ /** Exact decimal amounts in each recorded currency. */
30
+ amounts: Record<string, string>;
31
+ unpricedTokens: number;
32
+ historicalUnknownTokens: number;
33
+ }
34
+ export declare const emptyUsageCost: () => UsageCost;
35
+ export declare function addUsageCost(target: UsageCost, source: UsageCost): void;
36
+ type UsageTokens = Record<"inputTokens" | "outputTokens" | "cacheReadTokens" | "cacheWriteTokens", number | string>;
37
+ export interface GroupedCacheWrite {
38
+ ttl: number;
39
+ tokens: number | string;
40
+ }
41
+ export declare function snapshotCost(snapshot: unknown, usage: ModelUsage): UsageCost;
42
+ export declare function groupedSnapshotCost(snapshot: unknown, usage: UsageTokens, classifiedWrites: readonly GroupedCacheWrite[]): UsageCost;
43
+ export {};
@@ -0,0 +1,145 @@
1
+ import { validateCacheWriteByTtl } from "@capybara-hq/plugin-sdk";
2
+ import { sql } from "kysely";
3
+ import { jsonArrayFrom } from "kysely/helpers/postgres";
4
+ import { z } from "zod";
5
+ import { priceKey } from "./prices.js";
6
+ export const PriceCurrency = z
7
+ .string()
8
+ .regex(/^[A-Z]{3}$/, "must be a 3-letter ISO 4217 currency code");
9
+ export const DEFAULT_PRICE_CURRENCY = "USD";
10
+ const base = z.object({
11
+ version: z.literal(1),
12
+ currency: PriceCurrency,
13
+ });
14
+ const rate = z.string().regex(/^\d+(?:\.\d+)?$/);
15
+ export const PriceSnapshotSchema = z.discriminatedUnion("status", [
16
+ base.extend({
17
+ status: z.literal("priced"),
18
+ inputPerMTok: rate,
19
+ outputPerMTok: rate,
20
+ cacheReadPerMTok: rate.nullable(),
21
+ cacheWritePerMTok: rate.nullable(),
22
+ cacheWritePerMTokByTtl: z.record(z.string(), rate).optional(),
23
+ }),
24
+ base.extend({ status: z.literal("unpriced") }),
25
+ ]);
26
+ /** Read the setting and the requested rates in one statement in the caller's usage transaction. */
27
+ export async function readPriceSnapshots(db, models) {
28
+ const { currency: stored, prices } = await db
29
+ .selectNoFrom((eb) => [
30
+ eb
31
+ .selectFrom("deployment_settings")
32
+ .select("value")
33
+ .where("key", "=", "priceCurrency")
34
+ .as("currency"),
35
+ jsonArrayFrom(eb
36
+ .selectFrom("model_prices")
37
+ .select([
38
+ "provider",
39
+ "model",
40
+ sql `input_per_mtok::text`.as("input_per_mtok"),
41
+ sql `output_per_mtok::text`.as("output_per_mtok"),
42
+ sql `cache_read_per_mtok::text`.as("cache_read_per_mtok"),
43
+ sql `cache_write_per_mtok::text`.as("cache_write_per_mtok"),
44
+ sql `(
45
+ SELECT coalesce(jsonb_object_agg(key, value), '{}'::jsonb)
46
+ FROM jsonb_each_text(cache_write_per_mtok_by_ttl)
47
+ )`.as("cache_write_per_mtok_by_ttl"),
48
+ ])
49
+ .where((p) => p.or(models.map(({ provider, model }) => p.and([p("provider", "=", provider), p("model", "=", model)]))))).as("prices"),
50
+ ])
51
+ .executeTakeFirstOrThrow();
52
+ const currency = PriceCurrency.safeParse(stored).data ?? DEFAULT_PRICE_CURRENCY;
53
+ const snapshots = new Map();
54
+ for (const row of prices) {
55
+ snapshots.set(priceKey(row.provider, row.model), {
56
+ version: 1,
57
+ status: "priced",
58
+ currency,
59
+ inputPerMTok: row.input_per_mtok,
60
+ outputPerMTok: row.output_per_mtok,
61
+ cacheReadPerMTok: row.cache_read_per_mtok,
62
+ cacheWritePerMTok: row.cache_write_per_mtok,
63
+ cacheWritePerMTokByTtl: row.cache_write_per_mtok_by_ttl,
64
+ });
65
+ }
66
+ return (ref) => snapshots.get(priceKey(ref.provider, ref.model)) ?? {
67
+ version: 1,
68
+ status: "unpriced",
69
+ currency,
70
+ };
71
+ }
72
+ export async function readPriceSnapshot(db, model) {
73
+ return (await readPriceSnapshots(db, [model]))(model);
74
+ }
75
+ export const emptyUsageCost = () => ({
76
+ amounts: {},
77
+ unpricedTokens: 0,
78
+ historicalUnknownTokens: 0,
79
+ });
80
+ function decimal(text) {
81
+ const point = text.indexOf(".");
82
+ return {
83
+ units: BigInt(text.replace(".", "")),
84
+ scale: point < 0 ? 0 : text.length - point - 1,
85
+ };
86
+ }
87
+ function addDecimal(a, b) {
88
+ const scale = Math.max(a.scale, b.scale);
89
+ return {
90
+ units: a.units * 10n ** BigInt(scale - a.scale) + b.units * 10n ** BigInt(scale - b.scale),
91
+ scale,
92
+ };
93
+ }
94
+ function decimalText({ units, scale }) {
95
+ if (scale === 0)
96
+ return String(units);
97
+ const digits = String(units < 0n ? -units : units).padStart(scale + 1, "0");
98
+ const fraction = digits.slice(-scale).replace(/0+$/, "");
99
+ return `${units < 0n ? "-" : ""}${digits.slice(0, -scale)}${fraction ? `.${fraction}` : ""}`;
100
+ }
101
+ export function addUsageCost(target, source) {
102
+ for (const [currency, amount] of Object.entries(source.amounts)) {
103
+ target.amounts[currency] = decimalText(addDecimal(decimal(target.amounts[currency] ?? "0"), decimal(amount)));
104
+ }
105
+ target.unpricedTokens += source.unpricedTokens;
106
+ target.historicalUnknownTokens += source.historicalUnknownTokens;
107
+ }
108
+ export function snapshotCost(snapshot, usage) {
109
+ const classified = validateCacheWriteByTtl(usage) === null ? usage.cacheWriteByTtl : undefined;
110
+ return groupedSnapshotCost(snapshot, usage, classified ?? []);
111
+ }
112
+ export function groupedSnapshotCost(snapshot, usage, classifiedWrites) {
113
+ const cost = emptyUsageCost();
114
+ const price = PriceSnapshotSchema.safeParse(snapshot).data;
115
+ const input = BigInt(usage.inputTokens);
116
+ const output = BigInt(usage.outputTokens);
117
+ const read = BigInt(usage.cacheReadTokens);
118
+ let write = BigInt(usage.cacheWriteTokens);
119
+ if (price?.status !== "priced") {
120
+ const tokens = Number(input + output + read + write);
121
+ if (price?.status === "unpriced")
122
+ cost.unpricedTokens = tokens;
123
+ else
124
+ cost.historicalUnknownTokens = tokens;
125
+ return cost;
126
+ }
127
+ // Rates are currency units per million tokens, so rate times tokens gives exact micro-units.
128
+ let micros = { units: 0n, scale: 0 };
129
+ const add = (tokens, rate) => {
130
+ const exact = decimal(rate);
131
+ micros = addDecimal(micros, { units: tokens * exact.units, scale: exact.scale });
132
+ };
133
+ const writeRate = price.cacheWritePerMTok ?? price.inputPerMTok;
134
+ add(input, price.inputPerMTok);
135
+ add(output, price.outputPerMTok);
136
+ add(read, price.cacheReadPerMTok ?? price.inputPerMTok);
137
+ for (const { ttl, tokens } of classifiedWrites) {
138
+ const count = BigInt(tokens);
139
+ add(count, price.cacheWritePerMTokByTtl?.[ttl] ?? writeRate);
140
+ write -= count;
141
+ }
142
+ add(write, writeRate);
143
+ cost.amounts[price.currency] = decimalText({ units: micros.units, scale: micros.scale + 6 });
144
+ return cost;
145
+ }
@@ -215,7 +215,7 @@ let AdminOperations = class AdminOperations {
215
215
  }),
216
216
  defineOperation({
217
217
  id: "admin.usage",
218
- description: "What the platform used over the last 7 days (super admin): today and the 6 days before, as calendar days in tz (an IANA zone such as Asia/Shanghai; use the person's own zone). days has one entry per day, oldest first: runs (every run, sub-agent and eval replay runs included), tokens (input, output, cacheRead, cacheWrite of every model call, and embedding) and cost. cost is an estimate from the model prices the super admin entered (models.prices), in currency; it is null when tokens were used and none of them had a price, and costPartial is true when some tokens had no price (the costs then count only the priced ones). orgs lists the 10 orgs that used the most tokens (runs, tokens, cost each); otherOrgs sums the rest (count, runs, tokens, cost). Totals only: never per account, agent or conversation. The answer may be up to 5 minutes old. admin.usage_unavailable means the database took too long: try again later.",
218
+ description: "What the platform used over the last 7 days (super admin): today and the 6 days before, as calendar days in tz (an IANA zone such as Asia/Shanghai; use the person's own zone). days has one entry per day, oldest first: runs (every run, sub-agent and eval replay runs included), tokens (input, output, cacheRead, cacheWrite of every model call, and embedding), images generated, and cost. Each cost estimate has exact decimal amounts by recorded currency, unpricedTokens and historicalUnknownTokens. The top-level cost covers the whole week. Never add amounts in different currencies. orgs lists the 10 orgs that used the most tokens (runs, tokens, cost each); otherOrgs sums the rest (count, runs, tokens, cost). Totals only: never per account, agent or conversation. The answer may be up to 5 minutes old. admin.usage_unavailable means the database took too long: try again later.",
219
219
  input: UsageQuery.strict(),
220
220
  example: { tz: "Asia/Shanghai" },
221
221
  authz: { superAdmin: true },
@@ -83,6 +83,15 @@ async function resolveInboxItem(db, orgId, itemId) {
83
83
  };
84
84
  }
85
85
  async function resolveConversation(db, orgId, conversationId, seq) {
86
+ const conv = await db
87
+ .selectFrom("conversations")
88
+ .select(["kind", "account_id", "deleted_at"])
89
+ .where("id", "=", conversationId)
90
+ .where("org_id", "=", orgId)
91
+ .executeTakeFirst();
92
+ if (!conv || conv.kind === "eval" || conv.deleted_at !== null)
93
+ return null;
94
+ // org-filter: conversationId was verified in orgId above
86
95
  const event = await db
87
96
  .selectFrom("conversation_events")
88
97
  .select(["type", "payload", "run_id"])
@@ -94,14 +103,6 @@ async function resolveConversation(db, orgId, conversationId, seq) {
94
103
  const trigger = pushTriggerOf({ type: event.type, payload: event.payload });
95
104
  if (trigger === null)
96
105
  return null;
97
- const conv = await db
98
- .selectFrom("conversations")
99
- .select(["kind", "account_id", "deleted_at"])
100
- .where("id", "=", conversationId)
101
- .where("org_id", "=", orgId)
102
- .executeTakeFirst();
103
- if (!conv || conv.kind === "eval" || conv.deleted_at !== null)
104
- return null;
105
106
  if (trigger.category === "replies" && conv.kind !== "chat")
106
107
  return null;
107
108
  if (!(await orgLive(db, orgId)))
@@ -20,6 +20,8 @@ import { ClientReportsCron } from "../client/client-reports.cron.js";
20
20
  import { AttachmentsModule } from "../conversations/attachments.module.js";
21
21
  import { AttachmentCleanupJob } from "../conversations/attachments.service.js";
22
22
  import { EventLogModule } from "../conversations/event-log.js";
23
+ import { EventOrgBackfillKickoffJob } from "../conversations/event-org-backfill.js";
24
+ import { EventOrgBackfillModule } from "../conversations/event-org-backfill.module.js";
23
25
  import { PromptSuggestionsModule } from "../conversations/prompt-suggestions.js";
24
26
  import { TitlesModule } from "../conversations/titles.js";
25
27
  import { ConversationNoticeSweepJob, ConversationNoticesModule, } from "../device-access/conversation-notice-delivery.js";
@@ -105,6 +107,8 @@ let WorkerModule = WorkerModule_1 = class WorkerModule {
105
107
  LibraryFilesModule,
106
108
  // the hashing and catch-up copy the kickoff owes
107
109
  FileLibraryJobsModule,
110
+ // the batched conversation_events.org_id backfill the kickoff owes
111
+ EventOrgBackfillModule,
108
112
  IdentityModule,
109
113
  StorageModule,
110
114
  SandboxModule,
@@ -130,6 +134,8 @@ let WorkerModule = WorkerModule_1 = class WorkerModule {
130
134
  // the daily blob sweep and the hourly kickoff of hashing and the catch-up copy (§7, §9)
131
135
  BlobSweepJob,
132
136
  FileLibraryKickoffJob,
137
+ // the periodic kickoff of the batched conversation_events.org_id backfill (issue #1175)
138
+ EventOrgBackfillKickoffJob,
133
139
  StoragePurgeJob,
134
140
  SandboxSweepJobs,
135
141
  BackgroundTaskPollJob,
@@ -144,6 +144,7 @@ let IdleArm = class IdleArm {
144
144
  .executeTakeFirst();
145
145
  if (row === undefined)
146
146
  return undefined;
147
+ // org-filter: conv is the finishing run's conversation, already resolved in its org
147
148
  const started = await t
148
149
  .selectFrom("conversation_events")
149
150
  .select("payload")
@@ -167,6 +168,7 @@ let IdleArm = class IdleArm {
167
168
  if (reason !== undefined)
168
169
  return skip(reason);
169
170
  // S6: the cache expiry over the run's step calls, and the last one's size
171
+ // org-filter: conv is the finishing run's conversation, already resolved in its org
170
172
  const calls = (await t
171
173
  .selectFrom("conversation_events")
172
174
  .select(EVENT_COLUMNS)
@@ -239,6 +241,7 @@ let IdleArm = class IdleArm {
239
241
  if (reason !== undefined)
240
242
  return skip(reason);
241
243
  const latestCallSeq = Math.max(...calls.filter((e) => e.type === "model_call").map((e) => e.seq));
244
+ // org-filter: conv is the finishing run's conversation, already resolved in its org
242
245
  const tail = (await t
243
246
  .selectFrom("conversation_events")
244
247
  .select(EVENT_COLUMNS)
@@ -13,7 +13,7 @@ import { RunQueue } from "./run-queue.js";
13
13
  * the conversation, decides through {@link idleFireDecision} and starts the idle compact run
14
14
  * through {@link RunQueue.startIdleCompaction}, which repeats the liveness, staleness and activity
15
15
  * checks under the conversation row lock. Runs in the maintenance processor (worker role only)
16
- * inside `runJob` with the job's org scope. Holds no state between deliveries: every fact comes
16
+ * under the arming run's persisted org scope. Holds no state between deliveries: every fact comes
17
17
  * from the database and the event log, so a duplicate delivery on another replica sees the first
18
18
  * delivery's run (an event after `armedSeq`, or an active run) and ends `obsolete` or `busy`.
19
19
  *
@@ -56,7 +56,7 @@ const PASSING = {
56
56
  * the conversation, decides through {@link idleFireDecision} and starts the idle compact run
57
57
  * through {@link RunQueue.startIdleCompaction}, which repeats the liveness, staleness and activity
58
58
  * checks under the conversation row lock. Runs in the maintenance processor (worker role only)
59
- * inside `runJob` with the job's org scope. Holds no state between deliveries: every fact comes
59
+ * under the arming run's persisted org scope. Holds no state between deliveries: every fact comes
60
60
  * from the database and the event log, so a duplicate delivery on another replica sees the first
61
61
  * delivery's run (an event after `armedSeq`, or an active run) and ends `obsolete` or `busy`.
62
62
  *
@@ -104,7 +104,7 @@ let IdleCompactionJob = class IdleCompactionJob {
104
104
  });
105
105
  return outcome;
106
106
  }
107
- // runs under the job's org scope (`runJob`); every org-owned row is read with that org
107
+ // The maintenance processor resolves the org from the arming run.
108
108
  async decide(data, now, extra) {
109
109
  const t = this.kdb.db;
110
110
  const { orgId, conversationId, armedSeq } = data;
@@ -117,6 +117,7 @@ let IdleCompactionJob = class IdleCompactionJob {
117
117
  return d.fire ? undefined : d.outcome;
118
118
  };
119
119
  // cache mode: the armed call, its lifetime (for the log) and its model (check 7)
120
+ // org-filter: idle compaction job runs inside the conversation's org scope (data.orgId)
120
121
  const call = cache &&
121
122
  (await t
122
123
  .selectFrom("conversation_events")
@@ -150,6 +151,7 @@ let IdleCompactionJob = class IdleCompactionJob {
150
151
  if (outcome !== undefined)
151
152
  return outcome;
152
153
  // check 3 (S14): an active run (queued, running, waiting), an unconsumed message, a queue head
154
+ // org-filter: readLive verified conversationId belongs to orgId above
153
155
  const [active, unconsumed, head] = await Promise.all([
154
156
  t
155
157
  .selectFrom("runs")
@@ -195,6 +197,7 @@ let IdleCompactionJob = class IdleCompactionJob {
195
197
  if (outcome !== undefined)
196
198
  return outcome;
197
199
  // check 6: the latest compaction record after the latest summary is a failure
200
+ // org-filter: readLive verified conversationId belongs to orgId above
198
201
  const latest = await t
199
202
  .selectFrom("conversation_events")
200
203
  .select("type")
@@ -321,6 +324,7 @@ let IdleCompactionJob = class IdleCompactionJob {
321
324
  return { conv, agent };
322
325
  }
323
326
  /** S1: an event after `armedSeq` that `isIdleNeutralEvent` rejects, in SQL. */
327
+ // org-filter: callers verified conversationId in orgId before checking staleness
324
328
  async staleAfter(conversationId, armedSeq) {
325
329
  const later = await this.kdb.db
326
330
  .selectFrom("conversation_events")