@capybara-hq/kernel 0.1.0-rc.5 → 0.1.0-rc.6

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 (63) hide show
  1. package/dist/admin/admin.controller.d.ts +13 -2
  2. package/dist/admin/admin.controller.js +29 -4
  3. package/dist/agents/agents.service.d.ts +3 -1
  4. package/dist/agents/agents.service.js +8 -6
  5. package/dist/agents/from-template.service.js +3 -3
  6. package/dist/agents/models.controller.d.ts +34 -5
  7. package/dist/agents/models.controller.js +50 -6
  8. package/dist/agents/readiness.controller.d.ts +5 -5
  9. package/dist/agents/readiness.controller.js +6 -6
  10. package/dist/catalog/marketplaces.service.d.ts +1 -1
  11. package/dist/config/schema.d.ts +4 -0
  12. package/dist/config/schema.js +24 -0
  13. package/dist/conversations/conversations.service.d.ts +4 -3
  14. package/dist/conversations/conversations.service.js +9 -8
  15. package/dist/ctx/create-ctx.d.ts +15 -1
  16. package/dist/ctx/create-ctx.js +23 -2
  17. package/dist/db/kernel-schema.d.ts +24 -0
  18. package/dist/errors.d.ts +3 -0
  19. package/dist/errors.js +3 -0
  20. package/dist/evals/run-replay.js +4 -2
  21. package/dist/evals/runs.service.d.ts +2 -1
  22. package/dist/evals/runs.service.js +13 -12
  23. package/dist/evals/step-replay.d.ts +2 -1
  24. package/dist/evals/step-replay.js +3 -2
  25. package/dist/extensions/config-hash.d.ts +10 -0
  26. package/dist/extensions/config-hash.js +38 -0
  27. package/dist/extensions/extensions.module.js +6 -12
  28. package/dist/extensions/host.d.ts +6 -10
  29. package/dist/extensions/host.js +22 -50
  30. package/dist/extensions/state.module.d.ts +9 -0
  31. package/dist/extensions/state.module.js +38 -0
  32. package/dist/http/api.module.js +2 -0
  33. package/dist/http/plugin-dispatch.d.ts +4 -1
  34. package/dist/http/plugin-dispatch.js +14 -2
  35. package/dist/infra/config/kernel-config.service.js +3 -0
  36. package/dist/infra/events/kernel-events.d.ts +8 -0
  37. package/dist/models/embeddings.d.ts +82 -0
  38. package/dist/models/embeddings.js +326 -0
  39. package/dist/models/enablement.controller.d.ts +40 -0
  40. package/dist/models/enablement.controller.js +74 -0
  41. package/dist/models/enablement.d.ts +99 -0
  42. package/dist/models/enablement.js +263 -0
  43. package/dist/models/models.module.d.ts +5 -1
  44. package/dist/models/models.module.js +16 -4
  45. package/dist/models/purposes.d.ts +18 -4
  46. package/dist/models/purposes.js +46 -9
  47. package/dist/platform/exclusions.js +18 -0
  48. package/dist/runtime/hook-calls.d.ts +8 -1
  49. package/dist/runtime/hook-calls.js +40 -9
  50. package/dist/runtime/model-call.d.ts +8 -3
  51. package/dist/runtime/model-call.js +28 -5
  52. package/dist/runtime/providers.d.ts +146 -32
  53. package/dist/runtime/providers.js +321 -67
  54. package/dist/runtime/run-worker.d.ts +1 -1
  55. package/dist/runtime/run-worker.js +4 -4
  56. package/dist/runtime/subagents/definition.js +3 -3
  57. package/dist/runtime/usage-report-jobs.d.ts +88 -0
  58. package/dist/runtime/usage-report-jobs.js +158 -0
  59. package/dist/runtime/usage-report.d.ts +33 -38
  60. package/dist/runtime/usage-report.js +152 -84
  61. package/dist/tools/pipeline.js +6 -0
  62. package/package.json +3 -3
  63. package/src/migrations/0089_model_kinds_usage.sql +38 -0
@@ -0,0 +1,88 @@
1
+ import type { Logger } from "@capybara-hq/plugin-sdk";
2
+ import { type OnApplicationShutdown } from "@nestjs/common";
3
+ import type { JobsOptions, Queue } from "bullmq";
4
+ import type { KernelSchemaDb } from "../db/kernel-schema.js";
5
+ import { KernelConfigService } from "../infra/config/kernel-config.service.js";
6
+ import { KernelDb } from "../infra/database/kernel-db.js";
7
+ import { KernelEvents } from "../infra/events/kernel-events.js";
8
+ /**
9
+ * The producer half of `usage.report` delivery for `model_usage` rows, and the queue's ids and job
10
+ * options shared with the reporter (`usage-report.ts`). The `ctx.models` broker sits below the
11
+ * extension host and must not register a queue there (CLI contexts that build the extensions
12
+ * module never connect to Redis eagerly), so it only announces a row (`model_usage.recorded`) and
13
+ * {@link ModelUsageJobs} enqueues it here.
14
+ */
15
+ /** Queue of `usage.report` deliveries (no `:` in the name). */
16
+ export declare const USAGE_REPORT_QUEUE = "cap-kernel-usage-report";
17
+ /** The job name of every delivery. */
18
+ export declare const USAGE_REPORT_JOB = "usage-report";
19
+ /** One job per `usage` event (no `:`: conversation ids are UUIDs, seq is a number). */
20
+ export declare const usageReportJobId: (conversationId: string, seq: number) => string;
21
+ /** One job per `model_usage` row (spec B §5.4; row ids are UUIDs, so no clash with the above). */
22
+ export declare const modelUsageJobId: (usageId: string) => string;
23
+ /**
24
+ * Job data: ids only (the payload is read when the job runs): a conversation `usage` event
25
+ * (`conversationId` + `seq`), or a `model_usage` row (`usageId`).
26
+ */
27
+ export type UsageReportJob = ({
28
+ conversationId: string;
29
+ seq: number;
30
+ usageId?: undefined;
31
+ } | {
32
+ usageId: string;
33
+ conversationId?: undefined;
34
+ seq?: undefined;
35
+ }) & {
36
+ /** Plugins not yet succeeded; absent = every subscriber (decided on the first attempt). */
37
+ pending?: string[];
38
+ /**
39
+ * Targets dropped so far (plugin → why), accumulated across attempts (m-2): when the job would
40
+ * otherwise complete it fails naming them, and `pending` is then exactly these plugins, so a
41
+ * manual retry reaches only them (m-1). A later delivery to one of them removes it.
42
+ */
43
+ dropped?: Record<string, string>;
44
+ };
45
+ /** First attempt plus 5 retries (F11). */
46
+ export declare const USAGE_REPORT_ATTEMPTS = 6;
47
+ /** Retry backoff: 2 s, doubling (2, 4, 8, 16, 32 s). */
48
+ export declare const USAGE_REPORT_BACKOFF_MS = 2000;
49
+ /** The delivery retry policy: attempts and the first exponential backoff. */
50
+ export interface UsageReportRetry {
51
+ attempts: number;
52
+ backoffMs: number;
53
+ }
54
+ /** Optional provider: the {@link UsageReportRetry} instead of the defaults above (tests). */
55
+ export declare const USAGE_REPORT_RETRY: unique symbol;
56
+ /** The options of one delivery job: its id, the retry policy and the retention of finished jobs. */
57
+ export declare function usageReportJobOpts(jobId: string, retry: UsageReportRetry, keepHours: number): JobsOptions;
58
+ /**
59
+ * Plugins that subscribe to `usage.report` according to deployment state: an approved permission
60
+ * snapshot that declares the `usage.report` hook, for a plugin the deployment still knows: an enabled
61
+ * install, or a config-declared plugin with a replica status row that is not `unloaded`. With `orgId`, only plugins
62
+ * the organization enabled (org config rows and required bootstrap plugins).
63
+ */
64
+ export declare function queryUsageSubscribers(db: KernelSchemaDb, orgId?: string): Promise<Set<string>>;
65
+ /**
66
+ * Enqueues the `usage.report` delivery of `model_usage` rows on `model_usage.recorded` (fast path;
67
+ * the reporter's sweep re-enqueues rows still unreported, so a lost event or enqueue is caught up).
68
+ */
69
+ export declare class ModelUsageJobs implements OnApplicationShutdown {
70
+ private readonly kdb;
71
+ private readonly queue;
72
+ private readonly config;
73
+ private readonly log;
74
+ private readonly retry;
75
+ private readonly unsubscribe;
76
+ /** Set at shutdown: a late event enqueues nothing (the sweep offers the row later). */
77
+ private closed;
78
+ constructor(kdb: KernelDb, queue: Queue<UsageReportJob>, config: Pick<KernelConfigService, "get">, log: Logger, retry: UsageReportRetry | undefined, events: KernelEvents);
79
+ onApplicationShutdown(): void;
80
+ /**
81
+ * Enqueues the delivery of one row (job `usage-model-<rowId>`). Without any subscriber nothing is
82
+ * enqueued (the sweep marks the row). Never throws: a failure only logs; the sweep catches up.
83
+ */
84
+ enqueue(usageId: string): Promise<void>;
85
+ }
86
+ /** The usage report queue and its `model_usage` producer (no dependency on the extension host). */
87
+ export declare class UsageReportJobsModule {
88
+ }
@@ -0,0 +1,158 @@
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 { getQueueToken } from "@nestjs/bullmq";
11
+ import { Inject, Injectable, Module, Optional } from "@nestjs/common";
12
+ import { sql } from "kysely";
13
+ import { enabledExtensionsQuery } from "../extensions/enabled.js";
14
+ import { KernelConfigService } from "../infra/config/kernel-config.service.js";
15
+ import { KernelDb } from "../infra/database/kernel-db.js";
16
+ import { KernelEvents } from "../infra/events/kernel-events.js";
17
+ import { QueueModule } from "../infra/queue/queue.module.js";
18
+ import { KERNEL_LOGGER } from "../infra/tokens.js";
19
+ /**
20
+ * The producer half of `usage.report` delivery for `model_usage` rows, and the queue's ids and job
21
+ * options shared with the reporter (`usage-report.ts`). The `ctx.models` broker sits below the
22
+ * extension host and must not register a queue there (CLI contexts that build the extensions
23
+ * module never connect to Redis eagerly), so it only announces a row (`model_usage.recorded`) and
24
+ * {@link ModelUsageJobs} enqueues it here.
25
+ */
26
+ /** Queue of `usage.report` deliveries (no `:` in the name). */
27
+ export const USAGE_REPORT_QUEUE = "cap-kernel-usage-report";
28
+ /** The job name of every delivery. */
29
+ export const USAGE_REPORT_JOB = "usage-report";
30
+ /** One job per `usage` event (no `:`: conversation ids are UUIDs, seq is a number). */
31
+ export const usageReportJobId = (conversationId, seq) => `usage-${conversationId}-${seq}`;
32
+ /** One job per `model_usage` row (spec B §5.4; row ids are UUIDs, so no clash with the above). */
33
+ export const modelUsageJobId = (usageId) => `usage-model-${usageId}`;
34
+ /** First attempt plus 5 retries (F11). */
35
+ export const USAGE_REPORT_ATTEMPTS = 6;
36
+ /** Retry backoff: 2 s, doubling (2, 4, 8, 16, 32 s). */
37
+ export const USAGE_REPORT_BACKOFF_MS = 2000;
38
+ /** Optional provider: the {@link UsageReportRetry} instead of the defaults above (tests). */
39
+ export const USAGE_REPORT_RETRY = Symbol("USAGE_REPORT_RETRY");
40
+ /** Failed jobs (given up) are kept for inspection, at most {@link KEEP_FAILED_MAX} of them. */
41
+ const KEEP_FAILED_S = 7 * 86_400;
42
+ /** Upper bound on kept failed jobs (I-2): a long outage of a billing endpoint cannot grow Redis. */
43
+ const KEEP_FAILED_MAX = 100_000;
44
+ /**
45
+ * Upper bound on kept finished jobs (Redis memory). At the default retention it only bites above
46
+ * ~1.1 usage events per second sustained for a day; dedupe needs the jobs only for the sweeper overlap.
47
+ */
48
+ const KEEP_COMPLETED_MAX = 100_000;
49
+ /** The options of one delivery job: its id, the retry policy and the retention of finished jobs. */
50
+ export function usageReportJobOpts(jobId, retry, keepHours) {
51
+ return {
52
+ jobId,
53
+ attempts: retry.attempts,
54
+ backoff: { type: "exponential", delay: retry.backoffMs },
55
+ removeOnComplete: { age: keepHours * 3600, count: KEEP_COMPLETED_MAX },
56
+ removeOnFail: { age: KEEP_FAILED_S, count: KEEP_FAILED_MAX },
57
+ };
58
+ }
59
+ /**
60
+ * Plugins that subscribe to `usage.report` according to deployment state: an approved permission
61
+ * snapshot that declares the `usage.report` hook, for a plugin the deployment still knows: an enabled
62
+ * install, or a config-declared plugin with a replica status row that is not `unloaded`. With `orgId`, only plugins
63
+ * the organization enabled (org config rows and required bootstrap plugins).
64
+ */
65
+ export async function queryUsageSubscribers(db, orgId) {
66
+ let q = db
67
+ .selectFrom("extension_permission_snapshots as s")
68
+ .select("s.plugin")
69
+ .where(sql `s.permissions -> 'permissions' -> 'hooks' ? 'usage.report'`)
70
+ .where((eb) => eb.or([
71
+ eb.exists(eb
72
+ .selectFrom("extension_installs as i")
73
+ .select(sql `1`.as("one"))
74
+ .whereRef("i.name", "=", "s.plugin")
75
+ .where("i.desired_state", "=", "enabled")),
76
+ // config-declared plugins still declared (and not unloaded) on some replica; installs are
77
+ // covered by desired_state above (their replica rows linger as `unloaded` when disabled)
78
+ eb.exists(eb
79
+ .selectFrom("extension_replica_status as r")
80
+ .select(sql `1`.as("one"))
81
+ .whereRef("r.plugin", "=", "s.plugin")
82
+ .where("r.source", "=", "config")
83
+ .where("r.state", "<>", "unloaded")),
84
+ ]));
85
+ if (orgId !== undefined) {
86
+ q = q.where("s.plugin", "in", enabledExtensionsQuery(db, orgId));
87
+ }
88
+ return new Set((await q.execute()).map((r) => r.plugin));
89
+ }
90
+ /**
91
+ * Enqueues the `usage.report` delivery of `model_usage` rows on `model_usage.recorded` (fast path;
92
+ * the reporter's sweep re-enqueues rows still unreported, so a lost event or enqueue is caught up).
93
+ */
94
+ let ModelUsageJobs = class ModelUsageJobs {
95
+ kdb;
96
+ queue;
97
+ config;
98
+ log;
99
+ retry;
100
+ unsubscribe;
101
+ /** Set at shutdown: a late event enqueues nothing (the sweep offers the row later). */
102
+ closed = false;
103
+ constructor(kdb, queue, config, log, retry = {
104
+ attempts: USAGE_REPORT_ATTEMPTS,
105
+ backoffMs: USAGE_REPORT_BACKOFF_MS,
106
+ }, events) {
107
+ this.kdb = kdb;
108
+ this.queue = queue;
109
+ this.config = config;
110
+ this.log = log;
111
+ this.retry = retry;
112
+ this.unsubscribe = events.on("model_usage.recorded", ({ id }) => this.enqueue(id));
113
+ }
114
+ onApplicationShutdown() {
115
+ this.closed = true;
116
+ this.unsubscribe();
117
+ }
118
+ /**
119
+ * Enqueues the delivery of one row (job `usage-model-<rowId>`). Without any subscriber nothing is
120
+ * enqueued (the sweep marks the row). Never throws: a failure only logs; the sweep catches up.
121
+ */
122
+ async enqueue(usageId) {
123
+ if (this.closed)
124
+ return;
125
+ try {
126
+ if ((await queryUsageSubscribers(this.kdb.db)).size === 0)
127
+ return;
128
+ await this.queue.add(USAGE_REPORT_JOB, { usageId }, usageReportJobOpts(modelUsageJobId(usageId), this.retry, this.config.get().hooks.usageReportKeepHours));
129
+ }
130
+ catch (err) {
131
+ this.log.warn("cannot enqueue model usage report", { usageId, err });
132
+ }
133
+ }
134
+ };
135
+ ModelUsageJobs = __decorate([
136
+ Injectable(),
137
+ __param(0, Inject(KernelDb)),
138
+ __param(1, Inject(getQueueToken(USAGE_REPORT_QUEUE))),
139
+ __param(2, Inject(KernelConfigService)),
140
+ __param(3, Inject(KERNEL_LOGGER)),
141
+ __param(4, Optional()),
142
+ __param(4, Inject(USAGE_REPORT_RETRY)),
143
+ __param(5, Inject(KernelEvents))
144
+ ], ModelUsageJobs);
145
+ export { ModelUsageJobs };
146
+ /** The usage report queue's registration, shared by the producer and the reporter's module. */
147
+ const USAGE_REPORT_QUEUE_MODULE = QueueModule.registerQueue(USAGE_REPORT_QUEUE);
148
+ /** The usage report queue and its `model_usage` producer (no dependency on the extension host). */
149
+ let UsageReportJobsModule = class UsageReportJobsModule {
150
+ };
151
+ UsageReportJobsModule = __decorate([
152
+ Module({
153
+ imports: [USAGE_REPORT_QUEUE_MODULE],
154
+ providers: [ModelUsageJobs],
155
+ exports: [ModelUsageJobs, USAGE_REPORT_QUEUE_MODULE],
156
+ })
157
+ ], UsageReportJobsModule);
158
+ export { UsageReportJobsModule };
@@ -6,34 +6,8 @@ import { KernelConfigService } from "../infra/config/kernel-config.service.js";
6
6
  import { KernelDb } from "../infra/database/kernel-db.js";
7
7
  import { LockService } from "../infra/lock/lock.service.js";
8
8
  import type { KernelLogger } from "../log.js";
9
- /** Queue of `usage.report` deliveries (no `:` in the name). */
10
- export declare const USAGE_REPORT_QUEUE = "cap-kernel-usage-report";
11
- /** One job per `usage` event (no `:`: conversation ids are UUIDs, seq is a number). */
12
- export declare const usageReportJobId: (conversationId: string, seq: number) => string;
13
- /** Job data: ids only (the payload is read from the event log when the job runs). */
14
- export interface UsageReportJob {
15
- conversationId: string;
16
- seq: number;
17
- /** Plugins not yet succeeded; absent = every subscriber (decided on the first attempt). */
18
- pending?: string[];
19
- /**
20
- * Targets dropped so far (plugin → why), accumulated across attempts (m-2): when the job would
21
- * otherwise complete it fails naming them, and `pending` is then exactly these plugins, so a
22
- * manual retry reaches only them (m-1). A later delivery to one of them removes it.
23
- */
24
- dropped?: Record<string, string>;
25
- }
26
- /** First attempt plus 5 retries (F11). */
27
- export declare const USAGE_REPORT_ATTEMPTS = 6;
28
- /** Retry backoff: 2 s, doubling (2, 4, 8, 16, 32 s). */
29
- export declare const USAGE_REPORT_BACKOFF_MS = 2000;
30
- /** The delivery retry policy of {@link UsageReporter}: attempts and the first exponential backoff. */
31
- export interface UsageReportRetry {
32
- attempts: number;
33
- backoffMs: number;
34
- }
35
- /** Optional provider: the {@link UsageReportRetry} instead of the defaults above (tests). */
36
- export declare const USAGE_REPORT_RETRY: unique symbol;
9
+ import { type UsageReportJob, type UsageReportRetry } from "./usage-report-jobs.js";
10
+ export { ModelUsageJobs, modelUsageJobId, queryUsageSubscribers, USAGE_REPORT_ATTEMPTS, USAGE_REPORT_BACKOFF_MS, USAGE_REPORT_QUEUE, USAGE_REPORT_RETRY, type UsageReportJob, UsageReportJobsModule, type UsageReportRetry, usageReportJobId, } from "./usage-report-jobs.js";
37
11
  /** The sweeper's cron job name (no `:`; every minute, once across replicas). */
38
12
  export declare const USAGE_SWEEP_JOB = "usage-report-sweep";
39
13
  /** The maintenance scheduler the sweep ran on before it became a `@LockedCron` (retired). */
@@ -46,13 +20,6 @@ export declare const USAGE_SWEEP_LAG_MS = 30000;
46
20
  * (`hooks.usageReportKeepHours` ≥ 1 h), so re-enqueued events dedupe on the kept job.
47
21
  */
48
22
  export declare const USAGE_SWEEP_OVERLAP_MS: number;
49
- /**
50
- * Plugins that subscribe to `usage.report` according to deployment state: an approved permission
51
- * snapshot that declares the `usage.report` hook, for a plugin the deployment still knows: an enabled
52
- * install, or a config-declared plugin with a replica status row that is not `unloaded`. With `orgId`, only plugins
53
- * the organization enabled (org config rows and required bootstrap plugins).
54
- */
55
- export declare function queryUsageSubscribers(db: KernelSchemaDb, orgId?: string): Promise<Set<string>>;
56
23
  /**
57
24
  * Of `plugins`, those that are **definitely** unservable right now (I-2, N-3): live replicas report
58
25
  * them (a `extension_replica_status` row with a heartbeat newer than `staleSeconds`), no live row is
@@ -91,11 +58,18 @@ export declare function narrowPending(stored: readonly string[] | undefined, fai
91
58
  * most 100 000. Each call runs through the instance's `inflight.run`, limited by `hooks.timeoutMs`;
92
59
  * when this replica stops, in-flight calls are aborted and the job goes back to the queue without
93
60
  * using up an attempt.
94
- * Handlers must be idempotent by `eventId` (`<conversationId>/<seq>`). Nothing is written to the event
95
- * log (never model-visible). Compaction calls log usage too (`purpose: "compaction"`) and are reported,
61
+ * Handlers must be idempotent by `eventId` (`<conversationId>/<seq>`, or a `model_usage` row id).
62
+ * Nothing is written to the event log (never model-visible). Compaction calls log usage too (`purpose: "compaction"`) and are reported,
96
63
  * as are conversation title calls (`purpose: "title"`, no run: `runId` is "") and `WebFetch`
97
64
  * extraction calls (`purpose: "web_fetch"`).
98
65
  * Single-step eval replays and judge requests log no usage: not reported (M7).
66
+ * - **Model usage outside conversations** (spec B §5.4): each `ctx.models.embed` call writes a
67
+ * `model_usage` row; on its `model_usage.recorded` event `ModelUsageJobs` (`usage-report-jobs.ts`)
68
+ * enqueues job `usage-model-<rowId>` (only while some plugin subscribes); the payload
69
+ * (`purpose: "embedding"`, `eventId` = the row id, the calling `extension`, no conversation fields)
70
+ * is read from the row when the job runs, and the row's `reported_at` is set once nothing is left
71
+ * to deliver; a job that gives up after its last attempt sets `report_failed_at`. The sweep
72
+ * re-enqueues recent rows that are neither (see {@link sweep}).
99
73
  */
100
74
  export declare class UsageReporter {
101
75
  private readonly kdb;
@@ -151,11 +125,21 @@ export declare class UsageReporter {
151
125
  /**
152
126
  * One sweep (R13): re-enqueues the `usage` events created in `[watermark - overlap, now - lag]` in
153
127
  * pages, then advances the watermark to `now - lag`. With no subscriber it only advances. The first
154
- * sweep starts at `now - lag - overlap`. Returns the number of events offered to the queue.
128
+ * sweep starts at `now - lag - overlap`. Also re-enqueues the `model_usage` rows of the same
129
+ * window that are neither reported nor given up (spec B §5.4),
130
+ * or, with no subscriber, marks those rows reported (nobody to deliver to). Returns the number of
131
+ * events and rows offered to the queue.
155
132
  */
156
133
  sweep(opts?: {
157
134
  now?: number;
158
135
  }): Promise<number>;
136
+ /**
137
+ * The `model_usage` half of {@link sweep}: rows neither reported nor given up that occurred in
138
+ * the same window as the events (`[watermark - overlap, to]`), oldest first. Bounded like the
139
+ * event sweep, so a row whose job failed for good is never offered again, even after its failed
140
+ * job left Redis (no repeated backlog, no second delivery to plugins already served).
141
+ */
142
+ private sweepModelUsage;
159
143
  /**
160
144
  * Starts consuming (worker role only): `worker` is the `@Processor` worker of
161
145
  * {@link USAGE_REPORT_QUEUE} (built with the run queue's job lock and stalled detection).
@@ -170,6 +154,17 @@ export declare class UsageReporter {
170
154
  * closes. The queue itself closes with the application.
171
155
  */
172
156
  stop(): Promise<void>;
157
+ /** The payload of a job: a `usage` event's or a `model_usage` row's; null when it is gone. */
158
+ private payloadOfJob;
159
+ /**
160
+ * The payload of one `model_usage` row (spec B §5.4): purpose `embedding`, the calling extension,
161
+ * no conversation fields; `eventId` is the row id. Null when the row no longer exists.
162
+ */
163
+ private payloadOfUsage;
164
+ /** A `model_usage` job is done (delivered, or nothing left to deliver to): marks the row. */
165
+ private markReported;
166
+ /** A `model_usage` job gave up after its last attempt: the sweep never offers the row again. */
167
+ private markFailed;
173
168
  /** The payload of one usage event, read from the log; null when the event no longer exists. */
174
169
  private payloadOf;
175
170
  /**