@capybara-hq/kernel 0.1.0-rc.109 → 0.1.0-rc.110

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 (51) hide show
  1. package/dist/admin/admin.schemas.d.ts +3 -0
  2. package/dist/background/wake-rules.js +2 -0
  3. package/dist/conversations/conversations.service.js +4 -2
  4. package/dist/conversations/event-log.js +11 -1
  5. package/dist/conversations/events.d.ts +5 -0
  6. package/dist/conversations/events.js +11 -2
  7. package/dist/conversations/prompt-suggestion-store.d.ts +3 -1
  8. package/dist/conversations/prompt-suggestion-store.js +5 -1
  9. package/dist/db/kernel-schema.d.ts +7 -0
  10. package/dist/identity/accounts.d.ts +8 -9
  11. package/dist/identity/accounts.js +18 -3
  12. package/dist/identity/me.controller.d.ts +4 -2
  13. package/dist/identity/me.controller.js +4 -2
  14. package/dist/identity/me.schemas.d.ts +3 -0
  15. package/dist/identity/me.schemas.js +5 -0
  16. package/dist/identity/settings.d.ts +15 -0
  17. package/dist/identity/settings.js +12 -0
  18. package/dist/infra/outbox/registry.d.ts +14 -0
  19. package/dist/infra/outbox/registry.js +14 -0
  20. package/dist/orgs/settings.service.d.ts +6 -0
  21. package/dist/platform/ops/org-settings.ops.js +1 -1
  22. package/dist/platform/ops/platform.ops.js +9 -3
  23. package/dist/push/recipients.js +4 -2
  24. package/dist/runtime/abort.d.ts +22 -3
  25. package/dist/runtime/abort.js +37 -17
  26. package/dist/runtime/compaction.service.d.ts +43 -12
  27. package/dist/runtime/compaction.service.js +60 -16
  28. package/dist/runtime/context/idle-compaction-rules.d.ts +94 -0
  29. package/dist/runtime/context/idle-compaction-rules.js +84 -0
  30. package/dist/runtime/idle-arm.d.ts +38 -0
  31. package/dist/runtime/idle-arm.js +269 -0
  32. package/dist/runtime/idle-compaction-jobs.d.ts +25 -0
  33. package/dist/runtime/idle-compaction-jobs.js +21 -0
  34. package/dist/runtime/idle-compaction.d.ts +43 -0
  35. package/dist/runtime/idle-compaction.js +316 -0
  36. package/dist/runtime/idle-return.d.ts +62 -0
  37. package/dist/runtime/idle-return.js +170 -0
  38. package/dist/runtime/maintenance.d.ts +5 -2
  39. package/dist/runtime/maintenance.js +14 -4
  40. package/dist/runtime/model-call.d.ts +113 -5
  41. package/dist/runtime/model-call.js +119 -71
  42. package/dist/runtime/run-finish.d.ts +16 -1
  43. package/dist/runtime/run-finish.js +27 -4
  44. package/dist/runtime/run-queue.d.ts +56 -2
  45. package/dist/runtime/run-queue.js +257 -8
  46. package/dist/runtime/run-worker.d.ts +22 -8
  47. package/dist/runtime/run-worker.js +75 -28
  48. package/dist/runtime/runtime.module.js +11 -0
  49. package/dist/runtime/waits.js +1 -1
  50. package/package.json +1 -1
  51. package/src/migrations/0195_idle_compaction.sql +7 -0
@@ -0,0 +1,269 @@
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 { AccountsService } from "../identity/accounts.js";
12
+ import { COMPACTION_SETTINGS } from "../identity/settings.js";
13
+ import { KernelDb } from "../infra/database/kernel-db.js";
14
+ import { KERNEL_LOGGER } from "../infra/tokens.js";
15
+ import { CompactionSettingsService } from "./compaction-settings.service.js";
16
+ import { deriveCacheExpiry } from "./context/cache-expiry.js";
17
+ import { idleArmDecision, } from "./context/idle-compaction-rules.js";
18
+ import { inContextSummaryAllowed, unansweredAfterReply } from "./context/in-context-compaction.js";
19
+ import { ProviderRegistry } from "./providers.js";
20
+ /**
21
+ * Facts not read yet, set so that they pass: {@link idleArmDecision} over the facts read so far
22
+ * plus these fails only on a fact already read, so the reads stop at the first failing one while
23
+ * the rules stay in one place.
24
+ */
25
+ const PASSING = {
26
+ conversationKind: "chat",
27
+ trigger: undefined,
28
+ automationRunId: null,
29
+ outcome: "completed",
30
+ settings: COMPACTION_SETTINGS.parse({}),
31
+ personalOff: false,
32
+ expiry: {
33
+ callSeq: 0,
34
+ t0: 0,
35
+ ttl: Number.POSITIVE_INFINITY,
36
+ expiresAt: Number.POSITIVE_INFINITY,
37
+ fireAt: Number.POSITIVE_INFINITY,
38
+ isMinimum: false,
39
+ },
40
+ lastCall: {
41
+ provider: "",
42
+ model: "",
43
+ window: 0,
44
+ input: Number.POSITIVE_INFINITY,
45
+ cacheRead: 0,
46
+ cacheWrite: 0,
47
+ output: 0,
48
+ },
49
+ inContextAllowed: true,
50
+ fitPlan: false,
51
+ settled: true,
52
+ };
53
+ const toEvent = (r) => ({
54
+ conversationId: r.conversation_id,
55
+ seq: Number(r.seq),
56
+ type: r.type,
57
+ runId: r.run_id,
58
+ payload: r.payload,
59
+ createdAt: r.created_at,
60
+ });
61
+ const EVENT_COLUMNS = [
62
+ "conversation_id",
63
+ "seq",
64
+ "type",
65
+ "run_id",
66
+ "payload",
67
+ "created_at",
68
+ ];
69
+ const modelKey = (provider, model) => `${provider}\u0000${model}`;
70
+ /**
71
+ * The arm decision of idle compaction at a chat run's finish (idle compaction spec §4.2, S4–S7):
72
+ * gathers {@link IdleArmFacts} and asks {@link idleArmDecision} whether the run's terminal
73
+ * transaction owes an `idle-compaction` job. The run worker calls it before `RunFinish.finish`,
74
+ * outside any transaction (the model registry may list a provider's models over the network).
75
+ */
76
+ let IdleArm = class IdleArm {
77
+ kdb;
78
+ compaction;
79
+ accounts;
80
+ models;
81
+ log;
82
+ constructor(kdb, compaction, accounts, models, log) {
83
+ this.kdb = kdb;
84
+ this.compaction = compaction;
85
+ this.accounts = accounts;
86
+ this.models = models;
87
+ this.log = log;
88
+ }
89
+ /**
90
+ * The intent `RunFinish.finishIn` owes the job from, or undefined when the run does not arm.
91
+ * Never throws: any failure is logged at `warn` and arms nothing, so arming never fails or holds
92
+ * up a finish (Review Focus 6). Reads cheapest first and stops at the first failing fact.
93
+ */
94
+ async decide(run, conv, outcome) {
95
+ try {
96
+ return await this.decideOrSkip(run.id, conv, outcome);
97
+ }
98
+ catch (err) {
99
+ this.log.warn("idle compaction arm failed; no job owed", {
100
+ context: "IdleCompaction",
101
+ conversationId: conv.id,
102
+ runId: run.id,
103
+ err,
104
+ });
105
+ return undefined;
106
+ }
107
+ }
108
+ async decideOrSkip(runId, conv, outcome) {
109
+ const t = this.kdb.db;
110
+ const known = { conversationKind: conv.kind, outcome };
111
+ const skip = (reason) => {
112
+ this.log.debug("idle compaction not armed", {
113
+ context: "IdleCompaction",
114
+ conversationId: conv.id,
115
+ runId,
116
+ reason,
117
+ });
118
+ return undefined;
119
+ };
120
+ const failing = () => {
121
+ const d = idleArmDecision({ ...PASSING, ...known });
122
+ return d.arm ? undefined : d.reason;
123
+ };
124
+ let reason = failing();
125
+ if (reason !== undefined)
126
+ return skip(reason);
127
+ // S5: the trigger and the automation lineage
128
+ const row = await t
129
+ .selectFrom("runs")
130
+ .select("automation_run_id")
131
+ .where("id", "=", runId)
132
+ .executeTakeFirst();
133
+ if (row === undefined)
134
+ return undefined;
135
+ const started = await t
136
+ .selectFrom("conversation_events")
137
+ .select("payload")
138
+ .where("conversation_id", "=", conv.id)
139
+ .where("run_id", "=", runId)
140
+ .where("type", "=", "run_started")
141
+ .executeTakeFirst();
142
+ known.automationRunId = row.automation_run_id;
143
+ known.trigger = started?.payload?.trigger;
144
+ reason = failing();
145
+ if (reason !== undefined)
146
+ return skip(reason);
147
+ known.settings = await this.compaction.resolve(conv.org_id);
148
+ reason = failing();
149
+ if (reason !== undefined)
150
+ return skip(reason);
151
+ known.personalOff =
152
+ conv.account_id !== null && (await this.accounts.idleCompactionOff(conv.account_id));
153
+ reason = failing();
154
+ if (reason !== undefined)
155
+ return skip(reason);
156
+ // S6: the cache expiry over the run's step calls, and the last one's size
157
+ const calls = (await t
158
+ .selectFrom("conversation_events")
159
+ .select(EVENT_COLUMNS)
160
+ .where("conversation_id", "=", conv.id)
161
+ .where("run_id", "=", runId)
162
+ .where("type", "in", ["model_call", "usage"])
163
+ .orderBy("seq")
164
+ .execute()).map(toEvent);
165
+ const infos = new Map();
166
+ for (const e of calls) {
167
+ if (e.type !== "model_call")
168
+ continue;
169
+ const key = modelKey(e.payload.provider, e.payload.model);
170
+ if (infos.has(key))
171
+ continue;
172
+ const { info } = await this.models.resolve(conv.org_id, {
173
+ provider: e.payload.provider,
174
+ model: e.payload.model,
175
+ });
176
+ infos.set(key, info);
177
+ }
178
+ const infoOf = (provider, model) => infos.get(modelKey(provider, model));
179
+ known.expiry = deriveCacheExpiry(calls, (p, m) => infoOf(p, m)?.cache);
180
+ const last = lastStepCall(calls);
181
+ const lastInfo = last && infoOf(last.call.payload.provider, last.call.payload.model);
182
+ known.lastCall =
183
+ last && lastInfo
184
+ ? {
185
+ provider: last.call.payload.provider,
186
+ model: last.call.payload.model,
187
+ window: lastInfo.contextWindow,
188
+ input: last.usage.payload.inputTokens,
189
+ cacheRead: last.usage.payload.cacheReadTokens,
190
+ cacheWrite: last.usage.payload.cacheWriteTokens,
191
+ output: last.usage.payload.outputTokens,
192
+ }
193
+ : null;
194
+ reason = failing();
195
+ if (reason !== undefined || last === undefined || lastInfo === undefined) {
196
+ return skip(reason ?? "no_cache");
197
+ }
198
+ // S7: the in-context quality gate (ruling R8) and the settled point (ruling R9)
199
+ known.inContextAllowed = inContextSummaryAllowed(last.call.payload.provider, lastInfo.id);
200
+ // a fit plan reshaped the last request's prefix: the fire-time in-context build skips it
201
+ known.fitPlan = last.call.payload.request.fit !== undefined;
202
+ reason = failing();
203
+ if (reason !== undefined)
204
+ return skip(reason);
205
+ const latestCallSeq = Math.max(...calls.filter((e) => e.type === "model_call").map((e) => e.seq));
206
+ const tail = (await t
207
+ .selectFrom("conversation_events")
208
+ .select(EVENT_COLUMNS)
209
+ .where("conversation_id", "=", conv.id)
210
+ .where("seq", ">=", String(latestCallSeq))
211
+ .orderBy("seq")
212
+ .execute()).map(toEvent);
213
+ // at the run's end: anything after the last reply the model has not answered (a tool result,
214
+ // a message or finished task the run did not absorb) is unsettled
215
+ known.settled = !unansweredAfterReply(tail, {
216
+ coversUpToSeq: Number.POSITIVE_INFINITY,
217
+ absorbedUpToSeq: Number.POSITIVE_INFINITY,
218
+ openers: [],
219
+ });
220
+ const d = idleArmDecision({ ...PASSING, ...known });
221
+ if (!d.arm)
222
+ return skip(d.reason);
223
+ this.log.debug("idle compaction armed", {
224
+ context: "IdleCompaction",
225
+ conversationId: conv.id,
226
+ runId,
227
+ runAt: d.runAt,
228
+ expiresAt: d.expiresAt,
229
+ });
230
+ return {
231
+ orgId: conv.org_id,
232
+ cacheCallSeq: d.cacheCallSeq,
233
+ expiresAt: d.expiresAt,
234
+ runAt: d.runAt,
235
+ };
236
+ }
237
+ };
238
+ IdleArm = __decorate([
239
+ Injectable(),
240
+ __param(0, Inject(KernelDb)),
241
+ __param(1, Inject(CompactionSettingsService)),
242
+ __param(2, Inject(AccountsService)),
243
+ __param(3, Inject(ProviderRegistry)),
244
+ __param(4, Inject(KERNEL_LOGGER))
245
+ ], IdleArm);
246
+ export { IdleArm };
247
+ /**
248
+ * The run's latest step call with its usage: a `model_call` paired with the next `usage` of the
249
+ * same step whose `purpose` is absent (as `deriveCacheExpiry` pairs them; a retry attempt replaces
250
+ * a failed one).
251
+ */
252
+ function lastStepCall(events) {
253
+ const open = new Map();
254
+ let last;
255
+ for (const e of events) {
256
+ if (e.type === "model_call") {
257
+ open.set(e.payload.step, e);
258
+ continue;
259
+ }
260
+ if (e.type !== "usage" || e.payload.purpose !== undefined)
261
+ continue;
262
+ const call = open.get(e.payload.step);
263
+ if (call === undefined)
264
+ continue;
265
+ open.delete(e.payload.step);
266
+ last = { call, usage: e };
267
+ }
268
+ return last;
269
+ }
@@ -0,0 +1,25 @@
1
+ import type { OutboxService } from "../infra/outbox/outbox.service.js";
2
+ /**
3
+ * The delayed idle compaction job (idle compaction spec §4.2, §4.3): owed by the terminal
4
+ * transaction of a chat run that passed the arm decision (`RunFinish.finishIn`, S4), due shortly
5
+ * before the run's prompt cache expires, on the maintenance queue. A leaf module, so the run finish
6
+ * and the job's consumer import the name without importing each other.
7
+ */
8
+ export declare const IDLE_COMPACTION_JOB = "idle-compaction";
9
+ /** One job per arming run (no `:`): a duplicate owe of the same run is a no-op. */
10
+ export declare const idleCompactionJobId: (runId: string) => string;
11
+ /** The `idle-compaction` job's data. */
12
+ export interface IdleCompactionJobData {
13
+ orgId: string;
14
+ conversationId: string;
15
+ /** The run that armed the job. */
16
+ runId: string;
17
+ /** The seq of that run's terminal `run_finished` event (S4). */
18
+ armedSeq: number;
19
+ /** The seq of the `model_call` the cache expiry was derived from (`CacheExpiry.callSeq`). */
20
+ cacheCallSeq: number;
21
+ /** When the prompt cache entry expires, epoch ms. */
22
+ expiresAt: number;
23
+ }
24
+ /** Owes the idle compaction job in the caller's transaction (throws outside one), due at `runAt`. */
25
+ export declare function oweIdleCompaction(outbox: Pick<OutboxService, "add">, data: IdleCompactionJobData, runAt: number): Promise<boolean>;
@@ -0,0 +1,21 @@
1
+ import { MAINTENANCE_QUEUE_NAME } from "./maintenance-queue.js";
2
+ /**
3
+ * The delayed idle compaction job (idle compaction spec §4.2, §4.3): owed by the terminal
4
+ * transaction of a chat run that passed the arm decision (`RunFinish.finishIn`, S4), due shortly
5
+ * before the run's prompt cache expires, on the maintenance queue. A leaf module, so the run finish
6
+ * and the job's consumer import the name without importing each other.
7
+ */
8
+ export const IDLE_COMPACTION_JOB = "idle-compaction";
9
+ /** One job per arming run (no `:`): a duplicate owe of the same run is a no-op. */
10
+ export const idleCompactionJobId = (runId) => `idle-compact-${runId}`;
11
+ /** Owes the idle compaction job in the caller's transaction (throws outside one), due at `runAt`. */
12
+ export function oweIdleCompaction(outbox, data, runAt) {
13
+ return outbox.add({
14
+ queue: MAINTENANCE_QUEUE_NAME,
15
+ name: IDLE_COMPACTION_JOB,
16
+ jobId: idleCompactionJobId(data.runId),
17
+ data,
18
+ runAt: new Date(runAt),
19
+ orgId: data.orgId,
20
+ });
21
+ }
@@ -0,0 +1,43 @@
1
+ import { AccountsService } from "../identity/accounts.js";
2
+ import { KernelDb } from "../infra/database/kernel-db.js";
3
+ import type { KernelLogger } from "../log.js";
4
+ import { CompactionService } from "./compaction.service.js";
5
+ import { CompactionSettingsService } from "./compaction-settings.service.js";
6
+ import { type IdleFireOutcome } from "./context/idle-compaction-rules.js";
7
+ import type { IdleCompactionJobData } from "./idle-compaction-jobs.js";
8
+ import { ProviderRegistry } from "./providers.js";
9
+ import { RunQueue } from "./run-queue.js";
10
+ /**
11
+ * One delivery of the delayed `idle-compaction` job (idle compaction spec §4.3, §5.1): re-reads
12
+ * the conversation, decides through {@link idleFireDecision} and starts the idle compact run
13
+ * through {@link RunQueue.startIdleCompaction}, which repeats the liveness, staleness and activity
14
+ * checks under the conversation row lock. Runs in the maintenance processor (worker role only)
15
+ * inside `runJob` with the job's org scope. Holds no state between deliveries: every fact comes
16
+ * from the database and the event log, so a duplicate delivery on another replica sees the first
17
+ * delivery's run (an event after `armedSeq`, or an active run) and ends `obsolete` or `busy`.
18
+ */
19
+ export declare class IdleCompactionJob {
20
+ private readonly kdb;
21
+ private readonly compaction;
22
+ private readonly accounts;
23
+ private readonly models;
24
+ private readonly compactions;
25
+ private readonly runs;
26
+ private readonly log;
27
+ constructor(kdb: KernelDb, compaction: Pick<CompactionSettingsService, "resolve">, accounts: Pick<AccountsService, "idleCompactionOff">, models: Pick<ProviderRegistry, "resolve">, compactions: Pick<CompactionService, "probeIdle">, runs: Pick<RunQueue, "startIdleCompaction">, log: Pick<KernelLogger, "info" | "warn">);
28
+ /**
29
+ * One delivery of `idle-compact-<runId>` (spec §4.3): gathers {@link IdleFireFacts} cheapest
30
+ * first, stopping at the first failing check, decides, and starts the run. Logs one `info` line,
31
+ * context=IdleCompaction. A database failure throws (BullMQ retries the job within its attempts).
32
+ */
33
+ fire(data: IdleCompactionJobData, now?: number): Promise<IdleFireOutcome | "started">;
34
+ private decide;
35
+ /**
36
+ * Check 1's reads: the conversation (live, chat, owned), and its agent when the org is live, the
37
+ * owner's account active and the agent visible to them (the idle run runs as the owner:
38
+ * `RunQueue`'s rule for a person's message); `agent` undefined = not live.
39
+ */
40
+ private readLive;
41
+ /** S1: an event after `armedSeq` that `isIdleNeutralEvent` rejects, in SQL. */
42
+ private staleAfter;
43
+ }
@@ -0,0 +1,316 @@
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 { visibleTo } from "../agents/agent-lookup.js";
12
+ import { normalizeStoredDefinition } from "../agents/definition.js";
13
+ import { effectiveDefinition, readSelection, sameModel } from "../conversations/selection.js";
14
+ import { AccountsService } from "../identity/accounts.js";
15
+ import { COMPACTION_SETTINGS } from "../identity/settings.js";
16
+ import { KernelDb } from "../infra/database/kernel-db.js";
17
+ import { KERNEL_LOGGER } from "../infra/tokens.js";
18
+ import { CompactionService } from "./compaction.service.js";
19
+ import { CompactionSettingsService } from "./compaction-settings.service.js";
20
+ import { CACHE_EXPIRY_MARGIN_MS, CACHE_FIRE_RATIO } from "./context/cache-expiry.js";
21
+ import { idleFireDecision, } from "./context/idle-compaction-rules.js";
22
+ import { ProviderRegistry } from "./providers.js";
23
+ import { ACTIVE_RUN_STATUSES } from "./run-jobs.js";
24
+ import { isLive, orgIsLive } from "./run-liveness.js";
25
+ import { RunQueue } from "./run-queue.js";
26
+ /**
27
+ * Facts not read yet, set so that they pass: {@link idleFireDecision} over the facts read so far
28
+ * plus these fails only on a fact already read, so the reads stop at the first failing check while
29
+ * the rules stay in one place (as `IdleArm` does for the arm decision). `now` and `expiresAt` need
30
+ * no read but join the known facts only at check 5 (`expiresAt` +∞ until then), so a late job that
31
+ * also fails an earlier check reports that check's outcome (spec §4.3 order).
32
+ */
33
+ const PASSING = {
34
+ live: true,
35
+ stale: false,
36
+ busy: false,
37
+ enabled: true,
38
+ now: 0,
39
+ expiresAt: Number.POSITIVE_INFINITY,
40
+ backoff: false,
41
+ sameModel: true,
42
+ probe: {
43
+ estimate: Number.POSITIVE_INFINITY,
44
+ window: 0,
45
+ growth: Number.POSITIVE_INFINITY,
46
+ planned: true,
47
+ },
48
+ inContext: true,
49
+ settings: COMPACTION_SETTINGS.parse({}),
50
+ };
51
+ /**
52
+ * One delivery of the delayed `idle-compaction` job (idle compaction spec §4.3, §5.1): re-reads
53
+ * the conversation, decides through {@link idleFireDecision} and starts the idle compact run
54
+ * through {@link RunQueue.startIdleCompaction}, which repeats the liveness, staleness and activity
55
+ * checks under the conversation row lock. Runs in the maintenance processor (worker role only)
56
+ * inside `runJob` with the job's org scope. Holds no state between deliveries: every fact comes
57
+ * from the database and the event log, so a duplicate delivery on another replica sees the first
58
+ * delivery's run (an event after `armedSeq`, or an active run) and ends `obsolete` or `busy`.
59
+ */
60
+ let IdleCompactionJob = class IdleCompactionJob {
61
+ kdb;
62
+ compaction;
63
+ accounts;
64
+ models;
65
+ compactions;
66
+ runs;
67
+ log;
68
+ constructor(kdb, compaction, accounts, models, compactions, runs, log) {
69
+ this.kdb = kdb;
70
+ this.compaction = compaction;
71
+ this.accounts = accounts;
72
+ this.models = models;
73
+ this.compactions = compactions;
74
+ this.runs = runs;
75
+ this.log = log;
76
+ }
77
+ /**
78
+ * One delivery of `idle-compact-<runId>` (spec §4.3): gathers {@link IdleFireFacts} cheapest
79
+ * first, stopping at the first failing check, decides, and starts the run. Logs one `info` line,
80
+ * context=IdleCompaction. A database failure throws (BullMQ retries the job within its attempts).
81
+ */
82
+ async fire(data, now = Date.now()) {
83
+ const extra = {};
84
+ const outcome = await this.decide(data, now, extra);
85
+ this.log.info("idle compaction job", {
86
+ context: "IdleCompaction",
87
+ outcome,
88
+ orgId: data.orgId,
89
+ conversationId: data.conversationId,
90
+ runId: data.runId,
91
+ ...extra,
92
+ });
93
+ return outcome;
94
+ }
95
+ // runs under the job's org scope (`runJob`); every org-owned row is read with that org
96
+ async decide(data, now, extra) {
97
+ const t = this.kdb.db;
98
+ const { orgId, conversationId, armedSeq } = data;
99
+ const known = {};
100
+ const failing = () => {
101
+ const d = idleFireDecision({ ...PASSING, ...known });
102
+ return d.fire ? undefined : d.outcome;
103
+ };
104
+ // the armed call: its lifetime (for the log) and its model (check 7)
105
+ const call = await t
106
+ .selectFrom("conversation_events")
107
+ .select("payload")
108
+ .where("conversation_id", "=", conversationId)
109
+ .where("seq", "=", String(data.cacheCallSeq))
110
+ .where("type", "=", "model_call")
111
+ .executeTakeFirst();
112
+ const armed = call?.payload;
113
+ const lifetime = (ttl) => {
114
+ if (ttl === undefined || extra.ttl !== undefined)
115
+ return;
116
+ extra.ttl = ttl;
117
+ // the arm decision's fire time, `min(t0 + 0.9 L, expiresAt - 30 s)` with t0 = expiresAt - L
118
+ const t0 = data.expiresAt - ttl * 1000;
119
+ const runAt = Math.min(t0 + CACHE_FIRE_RATIO * ttl * 1000, data.expiresAt - CACHE_EXPIRY_MARGIN_MS);
120
+ extra.lateMs = now - runAt;
121
+ };
122
+ lifetime(armed?.request?.cacheTtl);
123
+ // check 1: org, conversation (chat), agent; the owner can still send in it
124
+ const { conv, agent } = await this.readLive(orgId, conversationId);
125
+ known.live = conv !== undefined && agent !== undefined;
126
+ let outcome = failing();
127
+ if (outcome !== undefined || !conv || conv.account_id === null || !agent) {
128
+ return outcome ?? "gone";
129
+ }
130
+ // check 2 (S1): an event after the armed seq other than a run-less side-call usage
131
+ const stale = () => this.staleAfter(conversationId, armedSeq);
132
+ known.stale = await stale();
133
+ outcome = failing();
134
+ if (outcome !== undefined)
135
+ return outcome;
136
+ // check 3 (S14): an active run (queued, running, waiting), an unconsumed message, a queue head
137
+ const [active, unconsumed, head] = await Promise.all([
138
+ t
139
+ .selectFrom("runs")
140
+ .select("id")
141
+ .where("conversation_id", "=", conversationId)
142
+ .where("status", "in", ACTIVE_RUN_STATUSES)
143
+ .limit(1)
144
+ .executeTakeFirst(),
145
+ t
146
+ .selectFrom("conversation_events")
147
+ .select("seq")
148
+ .where("conversation_id", "=", conversationId)
149
+ .where("type", "=", "user_message")
150
+ .where("seq", ">", conv.consumed_seq)
151
+ .limit(1)
152
+ .executeTakeFirst(),
153
+ t
154
+ .selectFrom("conversation_queue")
155
+ .select("id")
156
+ .where("conversation_id", "=", conversationId)
157
+ .limit(1)
158
+ .executeTakeFirst(),
159
+ ]);
160
+ known.busy = active !== undefined || unconsumed !== undefined || head !== undefined;
161
+ outcome = failing();
162
+ if (outcome !== undefined)
163
+ return outcome;
164
+ // check 4: the effective settings and the owner's preference, read live
165
+ const settings = await this.compaction.resolve(orgId);
166
+ known.settings = settings;
167
+ known.enabled =
168
+ settings.enabled &&
169
+ settings.idleEnabled &&
170
+ !(await this.accounts.idleCompactionOff(conv.account_id));
171
+ outcome = failing();
172
+ if (outcome !== undefined)
173
+ return outcome;
174
+ // check 5 needs no read: the job's time against the armed call's expiry
175
+ known.now = now;
176
+ known.expiresAt = data.expiresAt;
177
+ outcome = failing();
178
+ if (outcome !== undefined)
179
+ return outcome;
180
+ // check 6: the latest compaction record after the latest summary is a failure
181
+ const latest = await t
182
+ .selectFrom("conversation_events")
183
+ .select("type")
184
+ .where("conversation_id", "=", conversationId)
185
+ .where("type", "in", ["compaction_summary", "compaction_failed"])
186
+ .orderBy("seq", "desc")
187
+ .limit(1)
188
+ .executeTakeFirst();
189
+ known.backoff = latest?.type === "compaction_failed";
190
+ outcome = failing();
191
+ if (outcome !== undefined)
192
+ return outcome;
193
+ // check 7: the effective definition (the agent's current version under the conversation's
194
+ // model selection, what the idle run will use) resolves, is enabled, and is the armed call's
195
+ const version = await t
196
+ .selectFrom("agent_versions")
197
+ .select("definition")
198
+ .where("agent_id", "=", conv.agent_id)
199
+ .where("version", "=", agent.current_version)
200
+ .executeTakeFirst();
201
+ const definition = version &&
202
+ effectiveDefinition(normalizeStoredDefinition(version.definition), await readSelection(t, conversationId));
203
+ let resolved = false;
204
+ if (definition && armed && sameModel(definition.model, armed)) {
205
+ try {
206
+ const { info } = await this.models.resolve(orgId, definition.model);
207
+ lifetime(info.cache?.defaultTtl);
208
+ resolved = true;
209
+ }
210
+ catch (err) {
211
+ // unknown, disabled, or a provider list that failed: no model to compact with now
212
+ this.log.warn("idle compaction model not available", {
213
+ context: "IdleCompaction",
214
+ conversationId,
215
+ model: definition.model,
216
+ err,
217
+ });
218
+ }
219
+ }
220
+ known.sameModel = resolved;
221
+ outcome = failing();
222
+ if (outcome !== undefined || !definition)
223
+ return outcome ?? "no_model";
224
+ // checks 8 and 9 (S13): the compaction's dry run (reads every event and the media: last)
225
+ const probe = await this.compactions.probeIdle({
226
+ orgId,
227
+ conversationId,
228
+ agentId: conv.agent_id,
229
+ agent: definition,
230
+ agentVersion: agent.current_version,
231
+ source: conv.source,
232
+ conversationKind: "chat",
233
+ absorbedUpToSeq: Number(conv.consumed_seq),
234
+ });
235
+ // an unavailable model or storage during the dry run: nothing to compact with now
236
+ known.probe = probe;
237
+ known.inContext = probe?.inContext ?? false;
238
+ if (probe)
239
+ extra.estimate = probe.estimate;
240
+ outcome = failing();
241
+ if (outcome !== undefined)
242
+ return outcome;
243
+ // §5.1: the run, under the conversation row lock (checks 1-3 again); a refusal is a message,
244
+ // a run or a queued message that arrived in between
245
+ const idleRunId = await this.runs.startIdleCompaction(conversationId, armedSeq);
246
+ if (idleRunId === null) {
247
+ // label the refusal by the first check it now fails (the order of checks 1-3)
248
+ if ((await this.readLive(orgId, conversationId)).agent === undefined)
249
+ return "gone";
250
+ return (await stale()) ? "obsolete" : "busy";
251
+ }
252
+ extra.idleRunId = idleRunId;
253
+ return "started";
254
+ }
255
+ /**
256
+ * Check 1's reads: the conversation (live, chat, owned), and its agent when the org is live, the
257
+ * owner's account active and the agent visible to them (the idle run runs as the owner:
258
+ * `RunQueue`'s rule for a person's message); `agent` undefined = not live.
259
+ */
260
+ async readLive(orgId, conversationId) {
261
+ const t = this.kdb.db;
262
+ const conv = await t
263
+ .selectFrom("conversations")
264
+ .select(["account_id", "agent_id", "kind", "consumed_seq", "source", "deleted_at"])
265
+ .where("id", "=", conversationId)
266
+ .where("org_id", "=", orgId)
267
+ .executeTakeFirst();
268
+ let agent;
269
+ if (conv && isLive(conv.deleted_at) && conv.kind === "chat" && conv.account_id !== null) {
270
+ const ownerId = conv.account_id;
271
+ const [orgLive, owner, row] = await Promise.all([
272
+ orgIsLive(t, orgId),
273
+ t
274
+ .selectFrom("accounts")
275
+ .select("id")
276
+ .where("id", "=", ownerId)
277
+ .where("status", "=", "active")
278
+ .executeTakeFirst(),
279
+ t
280
+ .selectFrom("agents")
281
+ .select("current_version")
282
+ .where("id", "=", conv.agent_id)
283
+ .where("org_id", "=", orgId)
284
+ .where("deleted_at", "is", null)
285
+ .where(visibleTo(ownerId))
286
+ .executeTakeFirst(),
287
+ ]);
288
+ if (orgLive && owner !== undefined)
289
+ agent = row;
290
+ }
291
+ return { conv, agent };
292
+ }
293
+ /** S1: an event after `armedSeq` that `isIdleNeutralEvent` rejects, in SQL. */
294
+ async staleAfter(conversationId, armedSeq) {
295
+ const later = await this.kdb.db
296
+ .selectFrom("conversation_events")
297
+ .select("seq")
298
+ .where("conversation_id", "=", conversationId)
299
+ .where("seq", ">", String(armedSeq))
300
+ .where((eb) => eb.not(eb.and([eb("type", "=", "usage"), eb("run_id", "is", null)])))
301
+ .limit(1)
302
+ .executeTakeFirst();
303
+ return later !== undefined;
304
+ }
305
+ };
306
+ IdleCompactionJob = __decorate([
307
+ Injectable(),
308
+ __param(0, Inject(KernelDb)),
309
+ __param(1, Inject(CompactionSettingsService)),
310
+ __param(2, Inject(AccountsService)),
311
+ __param(3, Inject(ProviderRegistry)),
312
+ __param(4, Inject(CompactionService)),
313
+ __param(5, Inject(RunQueue)),
314
+ __param(6, Inject(KERNEL_LOGGER))
315
+ ], IdleCompactionJob);
316
+ export { IdleCompactionJob };