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

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 (204) hide show
  1. package/dist/admin/account-erasures.d.ts +37 -0
  2. package/dist/admin/account-erasures.js +119 -0
  3. package/dist/admin/admin.controller.d.ts +35 -2
  4. package/dist/admin/admin.controller.js +75 -18
  5. package/dist/admin/admin.module.js +10 -0
  6. package/dist/admin/admin.schemas.d.ts +51 -0
  7. package/dist/admin/admin.schemas.js +20 -0
  8. package/dist/admin/erasure-dispositions.d.ts +23 -0
  9. package/dist/admin/erasure-dispositions.js +76 -0
  10. package/dist/admin/health.service.d.ts +6 -0
  11. package/dist/admin/health.service.js +27 -1
  12. package/dist/admin/usage.service.d.ts +5 -0
  13. package/dist/admin/usage.service.js +21 -2
  14. package/dist/agents/agents.service.d.ts +1 -1
  15. package/dist/catalog/plugin-import.d.ts +3 -1
  16. package/dist/catalog/plugin-import.js +19 -15
  17. package/dist/channels/connections.service.d.ts +1 -1
  18. package/dist/client/client-reports.service.js +12 -0
  19. package/dist/config/schema.d.ts +9 -1
  20. package/dist/config/schema.js +51 -1
  21. package/dist/conversations/conversations.service.d.ts +9 -1
  22. package/dist/conversations/conversations.service.js +112 -15
  23. package/dist/conversations/event-log.d.ts +2 -0
  24. package/dist/conversations/event-log.js +77 -0
  25. package/dist/conversations/events.d.ts +11 -0
  26. package/dist/conversations/events.js +13 -1
  27. package/dist/conversations/prompt-suggestions.js +4 -0
  28. package/dist/conversations/titles.js +3 -2
  29. package/dist/ctx/create-ctx.d.ts +3 -2
  30. package/dist/ctx/create-ctx.js +10 -7
  31. package/dist/db/extension-db.d.ts +30 -0
  32. package/dist/db/extension-db.js +91 -0
  33. package/dist/db/extension-schema-transfer.d.ts +6 -0
  34. package/dist/db/extension-schema-transfer.js +141 -0
  35. package/dist/db/kernel-schema.d.ts +73 -12
  36. package/dist/db/migrator.d.ts +6 -0
  37. package/dist/db/migrator.js +39 -4
  38. package/dist/db/pool.d.ts +4 -0
  39. package/dist/db/pool.js +36 -1
  40. package/dist/devices/devices.service.d.ts +13 -1
  41. package/dist/devices/devices.service.js +122 -9
  42. package/dist/erasure/account-batches.d.ts +9 -0
  43. package/dist/erasure/account-batches.js +567 -0
  44. package/dist/erasure/account-files.d.ts +34 -0
  45. package/dist/erasure/account-files.js +217 -0
  46. package/dist/erasure/account-residual.d.ts +15 -0
  47. package/dist/erasure/account-residual.js +149 -0
  48. package/dist/erasure/account-worker.d.ts +32 -0
  49. package/dist/erasure/account-worker.js +392 -0
  50. package/dist/erasure/device-cleanup.d.ts +23 -0
  51. package/dist/erasure/device-cleanup.js +221 -0
  52. package/dist/erasure/erasure.module.d.ts +2 -0
  53. package/dist/{conversations/event-org-backfill.module.js → erasure/erasure.module.js} +6 -10
  54. package/dist/erasure/external-evidence.d.ts +4 -0
  55. package/dist/erasure/external-evidence.js +28 -0
  56. package/dist/erasure/jobs.d.ts +5 -0
  57. package/dist/erasure/jobs.js +20 -0
  58. package/dist/erasure/org-batches.d.ts +11 -0
  59. package/dist/erasure/org-batches.js +159 -0
  60. package/dist/erasure/org-catalog.d.ts +2 -0
  61. package/dist/erasure/org-catalog.js +34 -0
  62. package/dist/erasure/org-rules.d.ts +14 -0
  63. package/dist/erasure/org-rules.js +227 -0
  64. package/dist/erasure/org-worker.d.ts +38 -0
  65. package/dist/erasure/org-worker.js +501 -0
  66. package/dist/erasure/requests.d.ts +61 -0
  67. package/dist/erasure/requests.js +180 -0
  68. package/dist/erasure/sweep.job.d.ts +19 -0
  69. package/dist/erasure/sweep.job.js +130 -0
  70. package/dist/erasure/worker.d.ts +17 -0
  71. package/dist/erasure/worker.js +110 -0
  72. package/dist/errors.d.ts +4 -0
  73. package/dist/errors.js +4 -0
  74. package/dist/evals/judge.d.ts +5 -0
  75. package/dist/evals/judge.js +16 -1
  76. package/dist/evals/run-replay.js +12 -1
  77. package/dist/evals/step-replay.d.ts +5 -3
  78. package/dist/evals/step-replay.js +9 -5
  79. package/dist/evals/worker.d.ts +2 -0
  80. package/dist/evals/worker.js +60 -16
  81. package/dist/extensions/admin-ops.d.ts +3 -1
  82. package/dist/extensions/admin-ops.js +11 -7
  83. package/dist/extensions/extensions.module.js +3 -0
  84. package/dist/extensions/host.d.ts +4 -1
  85. package/dist/extensions/host.js +29 -6
  86. package/dist/extensions/instance.d.ts +3 -0
  87. package/dist/extensions/instance.js +3 -1
  88. package/dist/extensions/migrate-lock.d.ts +4 -1
  89. package/dist/extensions/migrate-lock.js +19 -2
  90. package/dist/files/blob-objects.d.ts +7 -3
  91. package/dist/files/blob-objects.js +39 -22
  92. package/dist/files/blob-sweep.job.d.ts +11 -0
  93. package/dist/files/blob-sweep.job.js +67 -6
  94. package/dist/http/api.module.js +5 -1
  95. package/dist/identity/accounts.js +3 -0
  96. package/dist/identity/api-tokens.js +5 -0
  97. package/dist/identity/auth.guard.d.ts +1 -0
  98. package/dist/identity/auth.guard.js +1 -0
  99. package/dist/identity/erasure-admission.d.ts +3 -0
  100. package/dist/identity/erasure-admission.js +14 -0
  101. package/dist/identity/external.js +5 -0
  102. package/dist/identity/sessions.js +5 -0
  103. package/dist/identity/settings.d.ts +86 -1
  104. package/dist/identity/settings.js +38 -4
  105. package/dist/infra/config/kernel-config.service.js +1 -0
  106. package/dist/infra/metrics/kernel-metrics.d.ts +18 -0
  107. package/dist/infra/metrics/kernel-metrics.js +54 -0
  108. package/dist/infra/metrics/operational-metrics.d.ts +31 -0
  109. package/dist/infra/metrics/operational-metrics.js +188 -0
  110. package/dist/infra/outbox/registry.d.ts +23 -14
  111. package/dist/infra/outbox/registry.js +12 -15
  112. package/dist/infra/throttler/credential-throttler.js +8 -1
  113. package/dist/infra/throttler/named-throttlers.d.ts +6 -0
  114. package/dist/infra/throttler/named-throttlers.js +6 -0
  115. package/dist/infra/throttler/principal-throttler.guard.d.ts +10 -0
  116. package/dist/infra/throttler/principal-throttler.guard.js +50 -0
  117. package/dist/infra/throttler/redis-throttler-storage.d.ts +1 -0
  118. package/dist/infra/throttler/redis-throttler-storage.js +27 -5
  119. package/dist/infra/throttler/throttler.guard.d.ts +2 -3
  120. package/dist/infra/throttler/throttler.guard.js +2 -3
  121. package/dist/infra/throttler/throttler.module.js +3 -2
  122. package/dist/kernel.js +4 -0
  123. package/dist/lifecycle/kernel-lifecycle.d.ts +3 -1
  124. package/dist/lifecycle/kernel-lifecycle.js +26 -21
  125. package/dist/models/budget-admission.d.ts +31 -0
  126. package/dist/models/budget-admission.js +149 -0
  127. package/dist/models/budget-counters.d.ts +28 -0
  128. package/dist/models/budget-counters.js +117 -0
  129. package/dist/models/budget-policy.d.ts +88 -0
  130. package/dist/models/budget-policy.js +78 -0
  131. package/dist/models/embeddings.js +13 -2
  132. package/dist/models/images.js +12 -2
  133. package/dist/models/purposes.d.ts +5 -2
  134. package/dist/models/purposes.js +9 -5
  135. package/dist/orgs/invitations.service.d.ts +1 -1
  136. package/dist/orgs/members.service.d.ts +28 -1
  137. package/dist/orgs/members.service.js +74 -11
  138. package/dist/orgs/offboarding.js +4 -6
  139. package/dist/orgs/org-owner.d.ts +2 -0
  140. package/dist/orgs/org-owner.js +21 -6
  141. package/dist/orgs/orgs.controller.d.ts +22 -0
  142. package/dist/orgs/orgs.controller.js +24 -0
  143. package/dist/orgs/orgs.module.js +4 -0
  144. package/dist/orgs/orgs.schemas.js +7 -0
  145. package/dist/orgs/orgs.service.d.ts +5 -1
  146. package/dist/orgs/orgs.service.js +28 -3
  147. package/dist/orgs/settings.controller.js +6 -1
  148. package/dist/orgs/settings.service.d.ts +58 -1
  149. package/dist/orgs/settings.service.js +74 -9
  150. package/dist/platform/exclusions.js +20 -1
  151. package/dist/platform/ops/accounts.ops.js +58 -1
  152. package/dist/platform/ops/admin.ops.js +13 -5
  153. package/dist/platform/ops/org-settings.ops.js +11 -4
  154. package/dist/platform/ops/orgs.ops.js +28 -0
  155. package/dist/platform/ops/retention.d.ts +16 -0
  156. package/dist/platform/ops/retention.js +21 -0
  157. package/dist/retention/jobs.d.ts +21 -0
  158. package/dist/retention/jobs.js +48 -0
  159. package/dist/retention/policy.d.ts +70 -0
  160. package/dist/retention/policy.js +103 -0
  161. package/dist/retention/purge-batch.d.ts +17 -0
  162. package/dist/retention/purge-batch.js +355 -0
  163. package/dist/retention/report-obligations.d.ts +12 -0
  164. package/dist/retention/report-obligations.js +71 -0
  165. package/dist/retention/sweep.job.d.ts +17 -0
  166. package/dist/retention/sweep.job.js +95 -0
  167. package/dist/retention/worker.d.ts +29 -0
  168. package/dist/retention/worker.js +306 -0
  169. package/dist/roles/worker.module.js +12 -8
  170. package/dist/runtime/maintenance.d.ts +5 -3
  171. package/dist/runtime/maintenance.js +19 -12
  172. package/dist/runtime/model-call.d.ts +3 -1
  173. package/dist/runtime/model-call.js +25 -3
  174. package/dist/runtime/providers.d.ts +7 -2
  175. package/dist/runtime/providers.js +76 -10
  176. package/dist/runtime/quota.d.ts +12 -12
  177. package/dist/runtime/quota.js +42 -37
  178. package/dist/runtime/run-finish.js +2 -0
  179. package/dist/runtime/run-principal.d.ts +9 -0
  180. package/dist/runtime/run-principal.js +18 -0
  181. package/dist/runtime/run-worker.js +48 -10
  182. package/dist/runtime/usage-report-jobs.d.ts +4 -1
  183. package/dist/runtime/usage-report-jobs.js +36 -13
  184. package/dist/runtime/usage-report.d.ts +5 -3
  185. package/dist/runtime/usage-report.js +37 -19
  186. package/dist/sandbox/review/classifier.d.ts +2 -2
  187. package/dist/sandbox/review/classifier.js +6 -2
  188. package/dist/sandbox/sandbox.service.js +18 -7
  189. package/dist/storage/purge.js +5 -1
  190. package/dist/storage/storage.service.d.ts +17 -1
  191. package/dist/storage/storage.service.js +75 -4
  192. package/dist/tools/builtins/vision/read-image.js +3 -0
  193. package/dist/tools/builtins/web/extract.js +3 -0
  194. package/dist/tools/pipeline.js +5 -1
  195. package/package.json +3 -1
  196. package/src/migrations/0216_model_budget_counters.sql +24 -0
  197. package/src/migrations/0217_retention.sql +44 -0
  198. package/src/migrations/0218_data_erasure.sql +41 -0
  199. package/src/migrations/0219_event_org_constraint_check.sql +29 -0
  200. package/src/migrations/0220_require_event_org.sql +18 -0
  201. package/src/migrations/0221_drop_connector_declaration_policy.sql +2 -0
  202. package/dist/conversations/event-org-backfill.d.ts +0 -111
  203. package/dist/conversations/event-org-backfill.js +0 -264
  204. package/dist/conversations/event-org-backfill.module.d.ts +0 -3
@@ -1,3 +1,6 @@
1
+ import { waitWithin } from "../close-within.js";
2
+ import { recordThrottle } from "../metrics/kernel-metrics.js";
3
+ import { API_DEFAULT_THROTTLER } from "./named-throttlers.js";
1
4
  /**
2
5
  * One atomic EVAL: when the counter already reached the limit the attempt is rejected and
3
6
  * NOT counted (a rejected attempt must not push the count further, so the window ends on
@@ -67,6 +70,8 @@ for i = nClear + 1, #KEYS do
67
70
  end
68
71
  return 0
69
72
  `;
73
+ const DEFAULT_QUOTA_TIMEOUT_MS = 250;
74
+ const THROTTLE_WARNING_INTERVAL_MS = 60_000;
70
75
  const NOT_BLOCKED = {
71
76
  totalHits: 0,
72
77
  timeToExpire: 0,
@@ -84,16 +89,26 @@ export const throttlerRedisKey = (key, throttlerName) => `throttler:{${key}}:${t
84
89
  export class RedisThrottlerStorage {
85
90
  redis;
86
91
  log;
92
+ lastWarning = {};
87
93
  constructor(redis, log) {
88
94
  this.redis = redis;
89
95
  this.log = log;
90
96
  }
91
97
  /** `ttl` is in milliseconds (the throttler convention); `blockDuration` is unused. */
92
98
  async increment(key, ttl, limit, _blockDuration, throttlerName) {
99
+ const policy = throttlerName === API_DEFAULT_THROTTLER.name ? "default" : "route";
93
100
  try {
94
- const [hits, pttl, blocked] = (await this.redis.eval(INCREMENT_LUA, 1, throttlerRedisKey(key, throttlerName), ttl, limit));
101
+ if (policy === "default" && this.redis.status !== "ready") {
102
+ throw new Error("Default API quota Redis connection is unavailable");
103
+ }
104
+ const attempt = this.redis.eval(INCREMENT_LUA, 1, throttlerRedisKey(key, throttlerName), ttl, limit);
105
+ if (policy === "default" && !(await waitWithin(attempt, DEFAULT_QUOTA_TIMEOUT_MS))) {
106
+ throw new Error("Default API quota Redis request timed out");
107
+ }
108
+ const [hits, pttl, blocked] = (await attempt);
95
109
  // seconds, at least 1 and at most the window: the Retry-After value
96
110
  const timeToExpire = Math.min(Math.max(Math.ceil(pttl / 1000), 1), Math.ceil(ttl / 1000));
111
+ recordThrottle(policy, blocked === 1 ? "limited" : "allowed");
97
112
  return {
98
113
  totalHits: hits,
99
114
  timeToExpire,
@@ -102,10 +117,17 @@ export class RedisThrottlerStorage {
102
117
  };
103
118
  }
104
119
  catch (err) {
105
- this.log.warn("throttler storage unavailable, request allowed (fail-open)", {
106
- throttler: throttlerName,
107
- err,
108
- });
120
+ recordThrottle(policy, "unavailable");
121
+ const now = performance.now();
122
+ const previous = this.lastWarning[policy];
123
+ if (previous === undefined || now - previous >= THROTTLE_WARNING_INTERVAL_MS) {
124
+ this.lastWarning[policy] = now;
125
+ this.log.warn("throttler storage unavailable, request allowed (fail-open)", {
126
+ policy,
127
+ throttler: throttlerName,
128
+ err,
129
+ });
130
+ }
109
131
  return NOT_BLOCKED;
110
132
  }
111
133
  }
@@ -5,9 +5,8 @@ import { ThrottlerGuard, type ThrottlerModuleOptions, type ThrottlerRequest, typ
5
5
  export declare function selectedThrottlers(context: ExecutionContext): readonly string[];
6
6
  /**
7
7
  * Opts a route (or controller) in to the named throttlers `names` (see `NAMED_THROTTLERS`).
8
- * Throttling is per-route opt-in because the kernel limits only credential-checking routes today;
9
- * health and SSE stay unlimited; extension routes are limited by the plugin dispatch itself
10
- * (public writes only).
8
+ * These route-specific limits run in addition to the authenticated API's default quota.
9
+ * Extension routes outside Nest keep the plugin dispatch's own limits.
11
10
  */
12
11
  export declare const Throttled: (...names: string[]) => <TFunction extends Function, Y>(target: TFunction | object, propertyKey?: string | symbol, descriptor?: TypedPropertyDescriptor<Y>) => void;
13
12
  /**
@@ -21,9 +21,8 @@ export function selectedThrottlers(context) {
21
21
  }
22
22
  /**
23
23
  * Opts a route (or controller) in to the named throttlers `names` (see `NAMED_THROTTLERS`).
24
- * Throttling is per-route opt-in because the kernel limits only credential-checking routes today;
25
- * health and SSE stay unlimited; extension routes are limited by the plugin dispatch itself
26
- * (public writes only).
24
+ * These route-specific limits run in addition to the authenticated API's default quota.
25
+ * Extension routes outside Nest keep the plugin dispatch's own limits.
27
26
  */
28
27
  export const Throttled = (...names) => {
29
28
  for (const n of names) {
@@ -9,6 +9,7 @@ import { ThrottlerModule } from "@nestjs/throttler";
9
9
  import { KERNEL_LOGGER, REDIS } from "../tokens.js";
10
10
  import { CredentialThrottler } from "./credential-throttler.js";
11
11
  import { NAMED_THROTTLERS, throttlerKey } from "./named-throttlers.js";
12
+ import { PrincipalThrottlerGuard } from "./principal-throttler.guard.js";
12
13
  import { RedisThrottlerStorage } from "./redis-throttler-storage.js";
13
14
  import { KernelThrottlerGuard, selectedThrottlers } from "./throttler.guard.js";
14
15
  /**
@@ -46,8 +47,8 @@ KernelThrottlerModule = __decorate([
46
47
  }),
47
48
  }),
48
49
  ],
49
- providers: [KernelThrottlerGuard, CredentialThrottler],
50
- exports: [KernelThrottlerGuard, CredentialThrottler],
50
+ providers: [KernelThrottlerGuard, CredentialThrottler, PrincipalThrottlerGuard],
51
+ exports: [KernelThrottlerGuard, CredentialThrottler, PrincipalThrottlerGuard],
51
52
  })
52
53
  ], KernelThrottlerModule);
53
54
  export { KernelThrottlerModule };
package/dist/kernel.js CHANGED
@@ -1,4 +1,5 @@
1
1
  import { fileURLToPath } from "node:url";
2
+ import { extensionDbIdentity } from "./db/extension-db.js";
2
3
  import { canMigrateKernel, migrate, verifyMigrations } from "./db/migrator.js";
3
4
  import { createDb } from "./db/pool.js";
4
5
  import { ExtensionHost } from "./extensions/host.js";
@@ -49,6 +50,9 @@ export async function migrateAll(config, opts = {}) {
49
50
  });
50
51
  const plugins = await ExtensionHost.migrateOnly(config.extensions, {
51
52
  dbUrl: config.db.url,
53
+ ...(config.db.extensionsUrl !== undefined && {
54
+ extensionIdentity: extensionDbIdentity(config.db),
55
+ }),
52
56
  connectTimeoutMs,
53
57
  autoApprove: config.extensionPermissions.autoApprove,
54
58
  ...(opts.resolveFrom !== undefined && { resolveFrom: opts.resolveFrom }),
@@ -10,6 +10,7 @@ import { ChannelJobs } from "../channels/jobs.js";
10
10
  import { ChannelOutbound } from "../channels/outbound.js";
11
11
  import { PromptSuggestionQueue } from "../conversations/prompt-suggestions.js";
12
12
  import { TitleQueue } from "../conversations/titles.js";
13
+ import { type ExtensionDbIdentity } from "../db/extension-db.js";
13
14
  import { ExtensionBlobs } from "../extensions/blobs.js";
14
15
  import { BootstrapService } from "../extensions/bootstrap.js";
15
16
  import { BootstrapDefaultsService } from "../extensions/bootstrap-defaults.js";
@@ -76,6 +77,7 @@ export declare class KernelLifecycle implements OnApplicationBootstrap, BeforeAp
76
77
  private readonly kdb;
77
78
  private readonly shutdown;
78
79
  private readonly host;
80
+ private readonly extensionDbIdentity;
79
81
  private readonly registry;
80
82
  private readonly installs;
81
83
  private readonly blobs;
@@ -111,7 +113,7 @@ export declare class KernelLifecycle implements OnApplicationBootstrap, BeforeAp
111
113
  private bootstrapPackages;
112
114
  /** The merged bootstrap manifest, read once per start. */
113
115
  private mergedManifest;
114
- constructor(permissionConfig: PermissionConfigPublication, accounts: AccountsService, configService: KernelConfigService, log: KernelLogger, options: KernelAppOptions, pool: Kysely<any>, redis: Redis, kdb: KernelDb, shutdown: GracefulShutdown, host: ExtensionHost, registry: ExtensionRegistry, installs: ExtensionInstalls, blobs: ExtensionBlobs, extensionLifecycle: ExtensionLifecycle, replicaStatus: ReplicaStatusStore, bootstrap: BootstrapService, bootstrapDefaults: BootstrapDefaultsService, marketplaces: MarketplacesService, pluginImport: PluginImport, pluginUpdater: PlatformPluginUpdater, bus: Pick<ExtensionContext["bus"], "publish" | "subscribe">, usageReport: UsageReporter, titles: TitleQueue, suggestions: PromptSuggestionQueue, channelJobs: ChannelJobs, channelOutbound: ChannelOutbound, presence: ReplicaPresence, worker?: WorkerRole | undefined, gateway?: GatewayRole | undefined);
116
+ constructor(permissionConfig: PermissionConfigPublication, accounts: AccountsService, configService: KernelConfigService, log: KernelLogger, options: KernelAppOptions, pool: Kysely<any>, redis: Redis, kdb: KernelDb, shutdown: GracefulShutdown, host: ExtensionHost, extensionDbIdentity: ExtensionDbIdentity, registry: ExtensionRegistry, installs: ExtensionInstalls, blobs: ExtensionBlobs, extensionLifecycle: ExtensionLifecycle, replicaStatus: ReplicaStatusStore, bootstrap: BootstrapService, bootstrapDefaults: BootstrapDefaultsService, marketplaces: MarketplacesService, pluginImport: PluginImport, pluginUpdater: PlatformPluginUpdater, bus: Pick<ExtensionContext["bus"], "publish" | "subscribe">, usageReport: UsageReporter, titles: TitleQueue, suggestions: PromptSuggestionQueue, channelJobs: ChannelJobs, channelOutbound: ChannelOutbound, presence: ReplicaPresence, worker?: WorkerRole | undefined, gateway?: GatewayRole | undefined);
115
117
  /** The kernel HTTP application (set up by `buildKernelApp` before `init()`). */
116
118
  get http(): KernelHttpApp;
117
119
  attachHttp(http: KernelHttpApp): void;
@@ -17,6 +17,7 @@ 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 { ConfiguredExtensionDbIdentity } from "../db/extension-db.js";
20
21
  import { ExtensionBlobs } from "../extensions/blobs.js";
21
22
  import { BootstrapFailedError, BootstrapService, } from "../extensions/bootstrap.js";
22
23
  import { BootstrapDefaultsService } from "../extensions/bootstrap-defaults.js";
@@ -98,6 +99,7 @@ let KernelLifecycle = class KernelLifecycle {
98
99
  kdb;
99
100
  shutdown;
100
101
  host;
102
+ extensionDbIdentity;
101
103
  registry;
102
104
  installs;
103
105
  blobs;
@@ -135,7 +137,7 @@ let KernelLifecycle = class KernelLifecycle {
135
137
  mergedManifest;
136
138
  constructor(permissionConfig, accounts, configService, log, options,
137
139
  // biome-ignore lint/suspicious/noExplicitAny: the pool carries no schema types
138
- pool, redis, kdb, shutdown, host, registry, installs, blobs, extensionLifecycle, replicaStatus, bootstrap, bootstrapDefaults, marketplaces, pluginImport, pluginUpdater, bus,
140
+ pool, redis, kdb, shutdown, host, extensionDbIdentity, registry, installs, blobs, extensionLifecycle, replicaStatus, bootstrap, bootstrapDefaults, marketplaces, pluginImport, pluginUpdater, bus,
139
141
  // the producers closed on every role (their consumers are the worker role's)
140
142
  usageReport, titles, suggestions, channelJobs, channelOutbound,
141
143
  // this process's presence beat, on every role (admin overview spec §5.1)
@@ -153,6 +155,7 @@ let KernelLifecycle = class KernelLifecycle {
153
155
  this.kdb = kdb;
154
156
  this.shutdown = shutdown;
155
157
  this.host = host;
158
+ this.extensionDbIdentity = extensionDbIdentity;
156
159
  this.registry = registry;
157
160
  this.installs = installs;
158
161
  this.blobs = blobs;
@@ -294,6 +297,7 @@ let KernelLifecycle = class KernelLifecycle {
294
297
  : ensureMigrated({
295
298
  db: this.kdb.db,
296
299
  dbUrl: config.db.url,
300
+ extensionDb: this.extensionDbIdentity.resolve(d.name),
297
301
  connectTimeoutMs: config.db.connectTimeoutMs,
298
302
  bus: this.bus,
299
303
  log: this.log,
@@ -572,26 +576,27 @@ KernelLifecycle = __decorate([
572
576
  __param(7, Inject(KernelDb)),
573
577
  __param(8, Inject(GracefulShutdown)),
574
578
  __param(9, Inject(ExtensionHost)),
575
- __param(10, Inject(ExtensionRegistry)),
576
- __param(11, Inject(ExtensionInstalls)),
577
- __param(12, Inject(ExtensionBlobs)),
578
- __param(13, Inject(ExtensionLifecycle)),
579
- __param(14, Inject(ReplicaStatusStore)),
580
- __param(15, Inject(BootstrapService)),
581
- __param(16, Inject(BootstrapDefaultsService)),
582
- __param(17, Inject(MarketplacesService)),
583
- __param(18, Inject(PluginImport)),
584
- __param(19, Inject(PlatformPluginUpdater)),
585
- __param(20, Inject(KERNEL_BUS)),
586
- __param(21, Inject(UsageReporter)),
587
- __param(22, Inject(TitleQueue)),
588
- __param(23, Inject(PromptSuggestionQueue)),
589
- __param(24, Inject(ChannelJobs)),
590
- __param(25, Inject(ChannelOutbound)),
591
- __param(26, Inject(ReplicaPresence)),
592
- __param(27, Optional()),
593
- __param(27, Inject(WorkerRole)),
579
+ __param(10, Inject(ConfiguredExtensionDbIdentity)),
580
+ __param(11, Inject(ExtensionRegistry)),
581
+ __param(12, Inject(ExtensionInstalls)),
582
+ __param(13, Inject(ExtensionBlobs)),
583
+ __param(14, Inject(ExtensionLifecycle)),
584
+ __param(15, Inject(ReplicaStatusStore)),
585
+ __param(16, Inject(BootstrapService)),
586
+ __param(17, Inject(BootstrapDefaultsService)),
587
+ __param(18, Inject(MarketplacesService)),
588
+ __param(19, Inject(PluginImport)),
589
+ __param(20, Inject(PlatformPluginUpdater)),
590
+ __param(21, Inject(KERNEL_BUS)),
591
+ __param(22, Inject(UsageReporter)),
592
+ __param(23, Inject(TitleQueue)),
593
+ __param(24, Inject(PromptSuggestionQueue)),
594
+ __param(25, Inject(ChannelJobs)),
595
+ __param(26, Inject(ChannelOutbound)),
596
+ __param(27, Inject(ReplicaPresence)),
594
597
  __param(28, Optional()),
595
- __param(28, Inject(GatewayRole))
598
+ __param(28, Inject(WorkerRole)),
599
+ __param(29, Optional()),
600
+ __param(29, Inject(GatewayRole))
596
601
  ], KernelLifecycle);
597
602
  export { KernelLifecycle };
@@ -0,0 +1,31 @@
1
+ import type { KernelSchemaDb } from "../db/kernel-schema.js";
2
+ import { ApiError } from "../errors.js";
3
+ import { CacheService } from "../infra/cache/cache.service.js";
4
+ import { KernelDb } from "../infra/database/kernel-db.js";
5
+ import type { KernelLogger } from "../log.js";
6
+ export type ModelBudgetSite = {
7
+ conversationId: string;
8
+ runId?: string;
9
+ } | {
10
+ evalRunId: string;
11
+ };
12
+ export interface ModelBudgetErrorDetail {
13
+ scope?: "org" | "member";
14
+ constraint?: "tokens" | "spend";
15
+ resetAt?: string;
16
+ }
17
+ export declare class ModelBudgetRefused extends ApiError {
18
+ readonly budgetDetail?: ModelBudgetErrorDetail | undefined;
19
+ constructor(code: "model.budget_exceeded" | "model.budget_currency_mismatch" | "model.budget_unavailable", message: string, budgetDetail?: ModelBudgetErrorDetail | undefined);
20
+ }
21
+ /** The account comes only from rows resolved by the kernel or its own invocation claim. */
22
+ export declare function readModelBudgetAccount(db: KernelSchemaDb, orgId: string, site?: ModelBudgetSite): Promise<string | null>;
23
+ export declare class ModelBudgetAdmission {
24
+ readonly cacheService: CacheService;
25
+ private readonly db;
26
+ private readonly log;
27
+ constructor(cacheService: CacheService, db: KernelDb, log: Pick<KernelLogger, "warn">);
28
+ private readPlatformPolicy;
29
+ private readOrgPolicy;
30
+ check(orgId: string, site?: ModelBudgetSite): Promise<void>;
31
+ }
@@ -0,0 +1,149 @@
1
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
2
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
4
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
5
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
6
+ };
7
+ var __param = (this && this.__param) || function (paramIndex, decorator) {
8
+ return function (target, key) { decorator(target, key, paramIndex); }
9
+ };
10
+ import { Inject, Injectable } from "@nestjs/common";
11
+ import { ApiError } from "../errors.js";
12
+ import { CacheService } from "../infra/cache/cache.service.js";
13
+ import { Cacheable } from "../infra/cache/cacheable.decorator.js";
14
+ import { KernelDb } from "../infra/database/kernel-db.js";
15
+ import { KERNEL_LOGGER } from "../infra/tokens.js";
16
+ import { readStoredOrgSettings } from "../orgs/settings.service.js";
17
+ import { currentExecutionClaim } from "../runtime/run-execution.js";
18
+ import { runPrincipalAccount } from "../runtime/run-principal.js";
19
+ import { readSettledModelUsage } from "./budget-counters.js";
20
+ import { compareBudgetAmounts, orgModelBudgetCacheKey, PLATFORM_MODEL_BUDGET_CACHE_KEY, readPlatformModelBudgets, resolveModelBudgets, } from "./budget-policy.js";
21
+ export class ModelBudgetRefused extends ApiError {
22
+ budgetDetail;
23
+ constructor(code, message, budgetDetail) {
24
+ super(code, message, budgetDetail ? [budgetDetail] : undefined);
25
+ this.budgetDetail = budgetDetail;
26
+ }
27
+ }
28
+ /** The account comes only from rows resolved by the kernel or its own invocation claim. */
29
+ export async function readModelBudgetAccount(db, orgId, site) {
30
+ const claim = currentExecutionClaim();
31
+ const source = site && "evalRunId" in site ? site : claim?.orgId === orgId ? claim : site;
32
+ if (!source)
33
+ return null;
34
+ if ("evalRunId" in source) {
35
+ const evalRun = await db
36
+ .selectFrom("eval_runs")
37
+ .select("created_by")
38
+ .where("id", "=", source.evalRunId)
39
+ .where("org_id", "=", orgId)
40
+ .executeTakeFirstOrThrow();
41
+ return evalRun.created_by;
42
+ }
43
+ if (source.runId) {
44
+ const run = await db
45
+ .selectFrom("runs")
46
+ .innerJoin("conversations", "conversations.id", "runs.conversation_id")
47
+ .select([
48
+ "runs.id",
49
+ "runs.budget_run_id",
50
+ "runs.trigger_account_id",
51
+ "runs.compact_origin",
52
+ "conversations.kind",
53
+ ])
54
+ .where("runs.id", "=", source.runId)
55
+ .where("runs.conversation_id", "=", source.conversationId)
56
+ .where("conversations.org_id", "=", orgId)
57
+ .executeTakeFirstOrThrow();
58
+ return (await runPrincipalAccount(db, run, run.kind)) ?? null;
59
+ }
60
+ const conversation = await db
61
+ .selectFrom("conversations")
62
+ .select("account_id")
63
+ .where("id", "=", source.conversationId)
64
+ .where("org_id", "=", orgId)
65
+ .executeTakeFirstOrThrow();
66
+ return conversation.account_id;
67
+ }
68
+ function hasBudget(budget) {
69
+ return (budget.tokens !== undefined || budget.spend !== undefined || budget.currencyConflict === true);
70
+ }
71
+ function hasMemberOverrides(raw) {
72
+ if (!raw || typeof raw !== "object" || !("memberModelBudgets" in raw))
73
+ return false;
74
+ return Object.keys(raw.memberModelBudgets ?? {}).length > 0;
75
+ }
76
+ function enforce(scope, budget, total, currency, resetAt) {
77
+ if (budget.currencyConflict || (budget.spend && budget.spend.currency !== currency)) {
78
+ throw new ModelBudgetRefused("model.budget_currency_mismatch", "The configured spend budget uses a different currency from model pricing. Ask an organization or platform administrator to align the currencies before retrying.", { scope, constraint: "spend" });
79
+ }
80
+ const constraint = budget.tokens !== undefined && BigInt(total.tokens) >= BigInt(budget.tokens)
81
+ ? "tokens"
82
+ : budget.spend &&
83
+ compareBudgetAmounts(total.amounts[budget.spend.currency] ?? "0", budget.spend.amount) >=
84
+ 0
85
+ ? "spend"
86
+ : undefined;
87
+ if (constraint) {
88
+ const who = scope === "org" ? "organization" : "member";
89
+ throw new ModelBudgetRefused("model.budget_exceeded", `The monthly ${who} ${constraint === "tokens" ? "token" : "spend"} budget has been reached. Wait until ${resetAt} UTC or ask an organization administrator to change the budget.`, { scope, constraint, resetAt });
90
+ }
91
+ }
92
+ let ModelBudgetAdmission = class ModelBudgetAdmission {
93
+ cacheService;
94
+ db;
95
+ log;
96
+ constructor(cacheService, db, log) {
97
+ this.cacheService = cacheService;
98
+ this.db = db;
99
+ this.log = log;
100
+ }
101
+ readPlatformPolicy() {
102
+ return readPlatformModelBudgets(this.db.db, { strict: true });
103
+ }
104
+ async readOrgPolicy(orgId) {
105
+ return (await readStoredOrgSettings(this.db.db, orgId)) ?? null;
106
+ }
107
+ async check(orgId, site) {
108
+ try {
109
+ const [platform, raw] = await Promise.all([
110
+ this.readPlatformPolicy(),
111
+ this.readOrgPolicy(orgId),
112
+ ]);
113
+ const defaults = resolveModelBudgets(platform, raw);
114
+ const accountId = hasBudget(defaults.member) || hasMemberOverrides(raw)
115
+ ? await readModelBudgetAccount(this.db.db, orgId, site)
116
+ : null;
117
+ const { org, member } = accountId === null ? defaults : resolveModelBudgets(platform, raw, accountId);
118
+ const memberApplies = accountId !== null && hasBudget(member);
119
+ if (!hasBudget(org) && !memberApplies)
120
+ return;
121
+ const totals = await readSettledModelUsage(this.db.db, orgId, memberApplies ? accountId : null, new Date());
122
+ enforce("org", org, totals.org, totals.priceCurrency, totals.resetAt);
123
+ if (memberApplies) {
124
+ if (!totals.member)
125
+ throw new Error("Member usage totals were missing");
126
+ enforce("member", member, totals.member, totals.priceCurrency, totals.resetAt);
127
+ }
128
+ }
129
+ catch (error) {
130
+ if (error instanceof ModelBudgetRefused)
131
+ throw error;
132
+ this.log.warn("could not check model budget", { orgId, err: error });
133
+ throw new ModelBudgetRefused("model.budget_unavailable", "Model usage budgets could not be checked. Try again later or ask an administrator to check model usage accounting.");
134
+ }
135
+ }
136
+ };
137
+ __decorate([
138
+ Cacheable({ key: PLATFORM_MODEL_BUDGET_CACHE_KEY, ttl: 30 })
139
+ ], ModelBudgetAdmission.prototype, "readPlatformPolicy", null);
140
+ __decorate([
141
+ Cacheable({ key: orgModelBudgetCacheKey("#{0}"), ttl: 30, cacheNull: true })
142
+ ], ModelBudgetAdmission.prototype, "readOrgPolicy", null);
143
+ ModelBudgetAdmission = __decorate([
144
+ Injectable(),
145
+ __param(0, Inject(CacheService)),
146
+ __param(1, Inject(KernelDb)),
147
+ __param(2, Inject(KERNEL_LOGGER))
148
+ ], ModelBudgetAdmission);
149
+ export { ModelBudgetAdmission };
@@ -0,0 +1,28 @@
1
+ import type { ModelUsage } from "@capybara-hq/plugin-sdk";
2
+ import type { KernelSchemaDb } from "../db/kernel-schema.js";
3
+ import { type PriceSnapshot } from "./price-snapshot.js";
4
+ export interface SettledUsageTotals {
5
+ tokens: string;
6
+ amounts: Record<string, string>;
7
+ unpricedTokens: string;
8
+ historicalUnknownTokens: string;
9
+ }
10
+ export interface SettledModelUsage {
11
+ priceCurrency: string;
12
+ periodStart: string;
13
+ resetAt: string;
14
+ coverageStart: string;
15
+ org: SettledUsageTotals;
16
+ member: SettledUsageTotals | null;
17
+ }
18
+ export declare function settledUsageBucket(snapshot: PriceSnapshot | null): string;
19
+ /** Caller owns the usage transaction and has established that this usage record is new. */
20
+ export declare function recordSettledModelUsage(db: KernelSchemaDb, input: {
21
+ orgId: string;
22
+ usageSourceId: string;
23
+ accountId: string | null;
24
+ at: Date;
25
+ usage: ModelUsage;
26
+ snapshot: PriceSnapshot | null;
27
+ }): Promise<void>;
28
+ export declare function readSettledModelUsage(db: KernelSchemaDb, orgId: string, accountId: string | null, at: Date): Promise<SettledModelUsage>;
@@ -0,0 +1,117 @@
1
+ import { createHash } from "node:crypto";
2
+ import { sql } from "kysely";
3
+ import { jsonArrayFrom } from "kysely/helpers/postgres";
4
+ import { DEFAULT_PRICE_CURRENCY, PriceCurrency, snapshotCost, } from "./price-snapshot.js";
5
+ function monthStart(at) {
6
+ const start = new Date(at);
7
+ start.setUTCDate(1);
8
+ start.setUTCHours(0, 0, 0, 0);
9
+ return start;
10
+ }
11
+ export function settledUsageBucket(snapshot) {
12
+ return snapshot?.status === "priced" ? snapshot.currency : (snapshot?.status ?? "unknown");
13
+ }
14
+ /** Caller owns the usage transaction and has established that this usage record is new. */
15
+ export async function recordSettledModelUsage(db, input) {
16
+ const { orgId, usageSourceId, accountId, at, usage, snapshot } = input;
17
+ const shard = createHash("sha256").update(usageSourceId).digest().readUInt8(0) % 16;
18
+ const cost = snapshotCost(snapshot, usage);
19
+ const tokens = BigInt(usage.inputTokens) +
20
+ BigInt(usage.outputTokens) +
21
+ BigInt(usage.cacheReadTokens) +
22
+ BigInt(usage.cacheWriteTokens);
23
+ const bucket = settledUsageBucket(snapshot);
24
+ const row = {
25
+ org_id: orgId,
26
+ period_start: monthStart(at).toISOString().slice(0, 10),
27
+ bucket,
28
+ tokens: tokens.toString(),
29
+ amount: cost.amounts[bucket] ?? "0",
30
+ };
31
+ await db
32
+ .insertInto("model_budget_org_usage")
33
+ .values({ ...row, shard })
34
+ .onConflict((oc) => oc.columns(["org_id", "period_start", "bucket", "shard"]).doUpdateSet({
35
+ tokens: sql `model_budget_org_usage.tokens + excluded.tokens`,
36
+ amount: sql `model_budget_org_usage.amount + excluded.amount`,
37
+ }))
38
+ .execute();
39
+ if (accountId !== null) {
40
+ await db
41
+ .insertInto("model_budget_member_usage")
42
+ .values({ ...row, account_id: accountId })
43
+ .onConflict((oc) => oc.columns(["org_id", "account_id", "period_start", "bucket"]).doUpdateSet({
44
+ tokens: sql `model_budget_member_usage.tokens + excluded.tokens`,
45
+ amount: sql `model_budget_member_usage.amount + excluded.amount`,
46
+ }))
47
+ .execute();
48
+ }
49
+ }
50
+ function totals(rows) {
51
+ const result = {
52
+ tokens: "0",
53
+ unpricedTokens: "0",
54
+ historicalUnknownTokens: "0",
55
+ amounts: {},
56
+ };
57
+ let tokens = 0n;
58
+ for (const row of rows) {
59
+ tokens += BigInt(row.tokens);
60
+ if (row.bucket === "unpriced")
61
+ result.unpricedTokens = row.tokens;
62
+ else if (row.bucket === "unknown")
63
+ result.historicalUnknownTokens = row.tokens;
64
+ else
65
+ result.amounts[row.bucket] = row.amount;
66
+ }
67
+ result.tokens = tokens.toString();
68
+ return result;
69
+ }
70
+ export async function readSettledModelUsage(db, orgId, accountId, at) {
71
+ const start = monthStart(at);
72
+ const period = start.toISOString().slice(0, 10);
73
+ const reset = new Date(start);
74
+ reset.setUTCMonth(reset.getUTCMonth() + 1);
75
+ // Cast before JSON aggregation so the driver never parses large integer or decimal values as floats.
76
+ const columns = [
77
+ "bucket",
78
+ sql `tokens::text`.as("tokens"),
79
+ sql `amount::text`.as("amount"),
80
+ ];
81
+ const result = await db
82
+ .selectFrom("_migrations")
83
+ .where("name", "=", "0216_model_budget_counters.sql")
84
+ .select("applied_at")
85
+ .select((eb) => [
86
+ eb
87
+ .selectFrom("deployment_settings")
88
+ .select("value")
89
+ .where("key", "=", "priceCurrency")
90
+ .as("price_currency"),
91
+ jsonArrayFrom(eb
92
+ .selectFrom("model_budget_org_usage")
93
+ .select([
94
+ "bucket",
95
+ sql `sum(tokens)::text`.as("tokens"),
96
+ sql `sum(amount)::text`.as("amount"),
97
+ ])
98
+ .groupBy("bucket")
99
+ .where("org_id", "=", orgId)
100
+ .where("period_start", "=", period)).as("org"),
101
+ jsonArrayFrom(eb
102
+ .selectFrom("model_budget_member_usage")
103
+ .select(columns)
104
+ .where("org_id", "=", orgId)
105
+ .where("period_start", "=", period)
106
+ .where("account_id", "=", sql `${accountId}`)).as("member"),
107
+ ])
108
+ .executeTakeFirstOrThrow();
109
+ return {
110
+ priceCurrency: PriceCurrency.safeParse(result.price_currency).data ?? DEFAULT_PRICE_CURRENCY,
111
+ periodStart: start.toISOString(),
112
+ resetAt: reset.toISOString(),
113
+ coverageStart: new Date(Math.max(result.applied_at.getTime(), start.getTime())).toISOString(),
114
+ org: totals(result.org),
115
+ member: accountId === null ? null : totals(result.member),
116
+ };
117
+ }
@@ -0,0 +1,88 @@
1
+ import { z } from "zod";
2
+ import type { KernelSchemaDb } from "../db/kernel-schema.js";
3
+ export declare const ModelBudgetSchema: z.ZodObject<{
4
+ tokens: z.ZodOptional<z.ZodNumber>;
5
+ spend: z.ZodOptional<z.ZodObject<{
6
+ amount: z.ZodString;
7
+ currency: z.ZodString;
8
+ }, z.core.$strict>>;
9
+ }, z.core.$strict>;
10
+ export type ModelBudget = z.infer<typeof ModelBudgetSchema> & {
11
+ currencyConflict?: boolean;
12
+ };
13
+ export declare const PlatformModelBudgetsSchema: z.ZodObject<{
14
+ orgDefault: z.ZodOptional<z.ZodObject<{
15
+ tokens: z.ZodOptional<z.ZodNumber>;
16
+ spend: z.ZodOptional<z.ZodObject<{
17
+ amount: z.ZodString;
18
+ currency: z.ZodString;
19
+ }, z.core.$strict>>;
20
+ }, z.core.$strict>>;
21
+ orgCeiling: z.ZodOptional<z.ZodObject<{
22
+ tokens: z.ZodOptional<z.ZodNumber>;
23
+ spend: z.ZodOptional<z.ZodObject<{
24
+ amount: z.ZodString;
25
+ currency: z.ZodString;
26
+ }, z.core.$strict>>;
27
+ }, z.core.$strict>>;
28
+ memberDefault: z.ZodOptional<z.ZodObject<{
29
+ tokens: z.ZodOptional<z.ZodNumber>;
30
+ spend: z.ZodOptional<z.ZodObject<{
31
+ amount: z.ZodString;
32
+ currency: z.ZodString;
33
+ }, z.core.$strict>>;
34
+ }, z.core.$strict>>;
35
+ memberCeiling: z.ZodOptional<z.ZodObject<{
36
+ tokens: z.ZodOptional<z.ZodNumber>;
37
+ spend: z.ZodOptional<z.ZodObject<{
38
+ amount: z.ZodString;
39
+ currency: z.ZodString;
40
+ }, z.core.$strict>>;
41
+ }, z.core.$strict>>;
42
+ }, z.core.$strict>;
43
+ export type PlatformModelBudgets = z.infer<typeof PlatformModelBudgetsSchema>;
44
+ export declare const OrgModelBudgetsSchema: z.ZodObject<{
45
+ org: z.ZodOptional<z.ZodObject<{
46
+ tokens: z.ZodOptional<z.ZodNumber>;
47
+ spend: z.ZodOptional<z.ZodObject<{
48
+ amount: z.ZodString;
49
+ currency: z.ZodString;
50
+ }, z.core.$strict>>;
51
+ }, z.core.$strict>>;
52
+ memberDefault: z.ZodOptional<z.ZodObject<{
53
+ tokens: z.ZodOptional<z.ZodNumber>;
54
+ spend: z.ZodOptional<z.ZodObject<{
55
+ amount: z.ZodString;
56
+ currency: z.ZodString;
57
+ }, z.core.$strict>>;
58
+ }, z.core.$strict>>;
59
+ }, z.core.$strict>;
60
+ export declare const MemberBudgetBody: z.ZodObject<{
61
+ budget: z.ZodNullable<z.ZodObject<{
62
+ tokens: z.ZodOptional<z.ZodNumber>;
63
+ spend: z.ZodOptional<z.ZodObject<{
64
+ amount: z.ZodString;
65
+ currency: z.ZodString;
66
+ }, z.core.$strict>>;
67
+ }, z.core.$strict>>;
68
+ }, z.core.$strict>;
69
+ export declare const PLATFORM_MODEL_BUDGET_CACHE_KEY = "model-budget:platform";
70
+ export declare const orgModelBudgetCacheKey: (orgId: string) => string;
71
+ export declare function readPlatformModelBudgets(db: KernelSchemaDb, opts?: {
72
+ strict: boolean;
73
+ }): Promise<PlatformModelBudgets>;
74
+ /** Compare unsigned decimal strings from settings or PostgreSQL without rounding. */
75
+ export declare function compareBudgetAmounts(a: string, b: string): number;
76
+ export declare const StoredMemberBudgetsSchema: z.ZodOptional<z.ZodCustom<Record<string, unknown>, Record<string, unknown>>>;
77
+ export declare function readMemberBudget(raw: unknown, accountId: string): {
78
+ tokens?: number | undefined;
79
+ spend?: {
80
+ amount: string;
81
+ currency: string;
82
+ } | undefined;
83
+ } | null;
84
+ /** Resolves the member default when the caller supplies no account. Org-only admission ignores it. */
85
+ export declare function resolveModelBudgets(platform: PlatformModelBudgets, raw: unknown, accountId?: string | null): {
86
+ org: ModelBudget;
87
+ member: ModelBudget;
88
+ };