@capybara-hq/kernel 0.1.0-rc.114 → 0.1.0-rc.116

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 (79) hide show
  1. package/bootstrap.json +9 -9
  2. package/dist/admin/admin.schemas.d.ts +1 -0
  3. package/dist/agents/agents.controller.d.ts +13 -1
  4. package/dist/agents/agents.controller.js +24 -2
  5. package/dist/catalog/catalog.service.d.ts +11 -1
  6. package/dist/catalog/catalog.service.js +36 -2
  7. package/dist/catalog/marketplaces.service.d.ts +1 -1
  8. package/dist/catalog/platform-components.js +13 -0
  9. package/dist/catalog/plugin-connectors.d.ts +35 -0
  10. package/dist/catalog/plugin-connectors.js +81 -0
  11. package/dist/channels/supervisor.d.ts +5 -1
  12. package/dist/channels/supervisor.js +17 -1
  13. package/dist/conversations/conversations.controller.d.ts +46 -14
  14. package/dist/conversations/conversations.controller.js +82 -47
  15. package/dist/conversations/conversations.service.d.ts +93 -59
  16. package/dist/conversations/conversations.service.js +255 -72
  17. package/dist/conversations/events.d.ts +39 -0
  18. package/dist/conversations/events.js +52 -2
  19. package/dist/conversations/inline-tokens.d.ts +87 -0
  20. package/dist/conversations/inline-tokens.js +154 -0
  21. package/dist/conversations/permission-profiles.controller.d.ts +14 -7
  22. package/dist/conversations/permission-profiles.controller.js +1 -5
  23. package/dist/conversations/prompt-suggestions.js +2 -4
  24. package/dist/conversations/queue.d.ts +0 -2
  25. package/dist/conversations/queue.service.js +9 -13
  26. package/dist/db/kernel-schema.d.ts +5 -0
  27. package/dist/errors.d.ts +12 -0
  28. package/dist/errors.js +12 -0
  29. package/dist/evals/snapshot.js +4 -2
  30. package/dist/files/library-files.service.d.ts +13 -0
  31. package/dist/files/library-files.service.js +33 -6
  32. package/dist/identity/settings.d.ts +5 -0
  33. package/dist/identity/settings.js +4 -0
  34. package/dist/models/purposes.js +5 -0
  35. package/dist/net/safe-fetch.js +1 -1
  36. package/dist/orgs/settings.service.d.ts +2 -0
  37. package/dist/platform/exclusions.js +6 -1
  38. package/dist/platform/ops/org-settings.ops.js +1 -1
  39. package/dist/runtime/compaction-model.d.ts +57 -0
  40. package/dist/runtime/compaction-model.js +87 -0
  41. package/dist/runtime/compaction.service.d.ts +23 -8
  42. package/dist/runtime/compaction.service.js +15 -10
  43. package/dist/runtime/context/build.d.ts +7 -2
  44. package/dist/runtime/context/build.js +17 -6
  45. package/dist/runtime/context/compaction.d.ts +22 -5
  46. package/dist/runtime/context/compaction.js +35 -15
  47. package/dist/runtime/context/idle-compaction-rules.d.ts +17 -2
  48. package/dist/runtime/context/idle-compaction-rules.js +20 -5
  49. package/dist/runtime/idle-arm.d.ts +12 -2
  50. package/dist/runtime/idle-arm.js +66 -18
  51. package/dist/runtime/idle-compaction-jobs.d.ts +24 -3
  52. package/dist/runtime/idle-compaction.d.ts +11 -3
  53. package/dist/runtime/idle-compaction.js +61 -30
  54. package/dist/runtime/model-call.d.ts +52 -16
  55. package/dist/runtime/model-call.js +71 -24
  56. package/dist/runtime/run-finish.d.ts +12 -3
  57. package/dist/runtime/run-finish.js +14 -7
  58. package/dist/runtime/run-queue.d.ts +5 -2
  59. package/dist/runtime/run-queue.js +7 -4
  60. package/dist/runtime/run-steps.d.ts +4 -1
  61. package/dist/runtime/run-steps.js +9 -2
  62. package/dist/runtime/run-worker.js +4 -2
  63. package/dist/runtime/runtime.module.js +3 -0
  64. package/dist/sandbox/review/classifier.js +5 -1
  65. package/dist/tools/connector-content.controller.d.ts +6 -2
  66. package/dist/tools/connector-content.controller.js +13 -3
  67. package/dist/tools/connector-content.d.ts +55 -15
  68. package/dist/tools/connector-content.js +112 -54
  69. package/dist/tools/connectors.service.d.ts +3 -2
  70. package/dist/tools/connectors.service.js +6 -20
  71. package/dist/tools/mentionable-connectors.d.ts +88 -0
  72. package/dist/tools/mentionable-connectors.js +218 -0
  73. package/dist/tools/pipeline.js +43 -6
  74. package/dist/tools/specs.d.ts +13 -4
  75. package/dist/tools/specs.js +22 -8
  76. package/dist/tools/tools.module.js +7 -0
  77. package/package.json +3 -3
  78. package/src/migrations/0200_runs_idle_mode.sql +4 -0
  79. package/src/migrations/0201_tool_specs_text.sql +8 -0
@@ -2,6 +2,7 @@ import type { ConversationKind } from "../db/kernel-schema.js";
2
2
  import { AccountsService } from "../identity/accounts.js";
3
3
  import { KernelDb } from "../infra/database/kernel-db.js";
4
4
  import type { KernelLogger } from "../log.js";
5
+ import { ModelPurposesService } from "../models/purposes.js";
5
6
  import { CompactionSettingsService } from "./compaction-settings.service.js";
6
7
  import { type IdleArmFacts } from "./context/idle-compaction-rules.js";
7
8
  import { ProviderRegistry } from "./providers.js";
@@ -12,7 +13,12 @@ export type IdleArmOutcome = IdleArmFacts["outcome"];
12
13
  * The arm decision of idle compaction at a chat run's finish (idle compaction spec §4.2, S4–S7):
13
14
  * gathers {@link IdleArmFacts} and asks {@link idleArmDecision} whether the run's terminal
14
15
  * transaction owes an `idle-compaction` job. The run worker calls it before `RunFinish.finish`,
15
- * outside any transaction (the model registry may list a provider's models over the network).
16
+ * outside any transaction (the model registry and the `compaction` purpose may list a provider's
17
+ * models over the network).
18
+ *
19
+ * The job's mode (compaction model spec §6.1, §6.2): `compaction_model` when the summarizer a
20
+ * compaction would choose now against the last step call's model is the compaction model (usable
21
+ * and eligible, the same `chooseSummarizer` the compaction runs), else `cache`.
16
22
  */
17
23
  export declare class IdleArm {
18
24
  private readonly kdb;
@@ -20,7 +26,9 @@ export declare class IdleArm {
20
26
  private readonly accounts;
21
27
  private readonly models;
22
28
  private readonly log;
23
- constructor(kdb: KernelDb, compaction: Pick<CompactionSettingsService, "resolve">, accounts: Pick<AccountsService, "idleCompactionOff">, models: Pick<ProviderRegistry, "resolve">, log: Pick<KernelLogger, "debug" | "warn">);
29
+ /** The org's `compaction` purpose, read from PG on every decision (nothing cached). */
30
+ private readonly compactionModel;
31
+ constructor(kdb: KernelDb, compaction: Pick<CompactionSettingsService, "resolve">, accounts: Pick<AccountsService, "idleCompactionOff">, models: Pick<ProviderRegistry, "resolve">, purposes: Pick<ModelPurposesService, "resolve">, log: KernelLogger);
24
32
  /**
25
33
  * The intent `RunFinish.finishIn` owes the job from, or undefined when the run does not arm.
26
34
  * Never throws: any failure is logged at `warn` and arms nothing, so arming never fails or holds
@@ -35,4 +43,6 @@ export declare class IdleArm {
35
43
  account_id: string | null;
36
44
  }, outcome: IdleArmOutcome): Promise<IdleCompactionIntent | undefined>;
37
45
  private decideOrSkip;
46
+ /** The final decision over every fact gathered: the intent, or undefined with the skip logged. */
47
+ private armed;
38
48
  }
@@ -12,9 +12,11 @@ import { AccountsService } from "../identity/accounts.js";
12
12
  import { COMPACTION_SETTINGS } from "../identity/settings.js";
13
13
  import { KernelDb } from "../infra/database/kernel-db.js";
14
14
  import { KERNEL_LOGGER } from "../infra/tokens.js";
15
+ import { ModelPurposesService } from "../models/purposes.js";
16
+ import { chooseSummarizer, compactionModelPort, } from "./compaction-model.js";
15
17
  import { CompactionSettingsService } from "./compaction-settings.service.js";
16
18
  import { deriveCacheExpiry } from "./context/cache-expiry.js";
17
- import { idleArmDecision, } from "./context/idle-compaction-rules.js";
19
+ import { idleArmDecision, idleMinTokens, } from "./context/idle-compaction-rules.js";
18
20
  import { inContextSummaryAllowed, unansweredAfterReply } from "./context/in-context-compaction.js";
19
21
  import { ProviderRegistry } from "./providers.js";
20
22
  /**
@@ -28,6 +30,8 @@ const PASSING = {
28
30
  automationRunId: null,
29
31
  outcome: "completed",
30
32
  settings: COMPACTION_SETTINGS.parse({}),
33
+ mode: "cache",
34
+ now: 0,
31
35
  personalOff: false,
32
36
  expiry: {
33
37
  callSeq: 0,
@@ -71,7 +75,12 @@ const modelKey = (provider, model) => `${provider}\u0000${model}`;
71
75
  * The arm decision of idle compaction at a chat run's finish (idle compaction spec §4.2, S4–S7):
72
76
  * gathers {@link IdleArmFacts} and asks {@link idleArmDecision} whether the run's terminal
73
77
  * 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).
78
+ * outside any transaction (the model registry and the `compaction` purpose may list a provider's
79
+ * models over the network).
80
+ *
81
+ * The job's mode (compaction model spec §6.1, §6.2): `compaction_model` when the summarizer a
82
+ * compaction would choose now against the last step call's model is the compaction model (usable
83
+ * and eligible, the same `chooseSummarizer` the compaction runs), else `cache`.
75
84
  */
76
85
  let IdleArm = class IdleArm {
77
86
  kdb;
@@ -79,12 +88,15 @@ let IdleArm = class IdleArm {
79
88
  accounts;
80
89
  models;
81
90
  log;
82
- constructor(kdb, compaction, accounts, models, log) {
91
+ /** The org's `compaction` purpose, read from PG on every decision (nothing cached). */
92
+ compactionModel;
93
+ constructor(kdb, compaction, accounts, models, purposes, log) {
83
94
  this.kdb = kdb;
84
95
  this.compaction = compaction;
85
96
  this.accounts = accounts;
86
97
  this.models = models;
87
98
  this.log = log;
99
+ this.compactionModel = compactionModelPort(purposes);
88
100
  }
89
101
  /**
90
102
  * The intent `RunFinish.finishIn` owes the job from, or undefined when the run does not arm.
@@ -144,7 +156,8 @@ let IdleArm = class IdleArm {
144
156
  reason = failing();
145
157
  if (reason !== undefined)
146
158
  return skip(reason);
147
- known.settings = await this.compaction.resolve(conv.org_id);
159
+ const settings = await this.compaction.resolve(conv.org_id);
160
+ known.settings = settings;
148
161
  reason = failing();
149
162
  if (reason !== undefined)
150
163
  return skip(reason);
@@ -162,23 +175,44 @@ let IdleArm = class IdleArm {
162
175
  .where("type", "in", ["model_call", "usage"])
163
176
  .orderBy("seq")
164
177
  .execute()).map(toEvent);
165
- const infos = new Map();
178
+ const resolved = new Map();
166
179
  for (const e of calls) {
167
180
  if (e.type !== "model_call")
168
181
  continue;
169
182
  const key = modelKey(e.payload.provider, e.payload.model);
170
- if (infos.has(key))
183
+ if (resolved.has(key))
171
184
  continue;
172
- const { info } = await this.models.resolve(conv.org_id, {
185
+ resolved.set(key, await this.models.resolve(conv.org_id, {
173
186
  provider: e.payload.provider,
174
187
  model: e.payload.model,
175
- });
176
- infos.set(key, info);
188
+ }));
177
189
  }
178
- const infoOf = (provider, model) => infos.get(modelKey(provider, model));
179
- known.expiry = deriveCacheExpiry(calls, (p, m) => infoOf(p, m)?.cache);
190
+ const infoOf = (provider, model) => resolved.get(modelKey(provider, model))?.info;
180
191
  const last = lastStepCall(calls);
181
- const lastInfo = last && infoOf(last.call.payload.provider, last.call.payload.model);
192
+ const lastModel = last && resolved.get(modelKey(last.call.payload.provider, last.call.payload.model));
193
+ const lastInfo = lastModel?.info;
194
+ // a context under the size floor arms in neither mode: skip before the purpose read (and the
195
+ // summarizer choice's fallback warnings) a small finish would otherwise pay every time
196
+ if (last !== undefined && lastInfo !== undefined) {
197
+ const u = last.usage.payload;
198
+ const total = u.inputTokens + u.cacheReadTokens + u.cacheWriteTokens + u.outputTokens;
199
+ if (total < idleMinTokens(lastInfo.contextWindow, settings))
200
+ return skip("small");
201
+ }
202
+ // compaction model spec §6.1, C2: the mode is the summarizer a compaction would choose now,
203
+ // V = the last step call's model under the effective settings; a failed purpose read throws
204
+ // (no job, logged by `decide`)
205
+ if (last !== undefined && lastModel !== undefined) {
206
+ const { summarizer } = await chooseSummarizer({ compactionModel: this.compactionModel, registry: this.models, log: this.log }, conv.org_id, {
207
+ ref: { provider: last.call.payload.provider, model: last.call.payload.model },
208
+ provider: lastModel.provider,
209
+ info: lastModel.info,
210
+ }, settings);
211
+ known.mode = summarizer.source === "compaction_model" ? "compaction_model" : "cache";
212
+ }
213
+ // C4: the run's end is not written yet; the terminal transaction follows within milliseconds
214
+ known.now = Date.now();
215
+ known.expiry = deriveCacheExpiry(calls, (p, m) => infoOf(p, m)?.cache);
182
216
  known.lastCall =
183
217
  last && lastInfo
184
218
  ? {
@@ -195,6 +229,8 @@ let IdleArm = class IdleArm {
195
229
  if (reason !== undefined || last === undefined || lastInfo === undefined) {
196
230
  return skip(reason ?? "no_cache");
197
231
  }
232
+ if (known.mode === "compaction_model")
233
+ return this.armed(runId, conv, known);
198
234
  // S7: the in-context quality gate (ruling R8) and the settled point (ruling R9)
199
235
  known.inContextAllowed = inContextSummaryAllowed(last.call.payload.provider, lastInfo.id);
200
236
  // a fit plan reshaped the last request's prefix: the fire-time in-context build skips it
@@ -217,18 +253,29 @@ let IdleArm = class IdleArm {
217
253
  absorbedUpToSeq: Number.POSITIVE_INFINITY,
218
254
  openers: [],
219
255
  });
256
+ return this.armed(runId, conv, known);
257
+ }
258
+ /** The final decision over every fact gathered: the intent, or undefined with the skip logged. */
259
+ armed(runId, conv, known) {
220
260
  const d = idleArmDecision({ ...PASSING, ...known });
221
- if (!d.arm)
222
- return skip(d.reason);
261
+ const fields = { context: "IdleCompaction", conversationId: conv.id, runId };
262
+ if (!d.arm) {
263
+ this.log.debug("idle compaction not armed", { ...fields, reason: d.reason });
264
+ return undefined;
265
+ }
266
+ if (d.mode === "compaction_model") {
267
+ this.log.debug("idle compaction armed", { ...fields, mode: d.mode, runAt: d.runAt });
268
+ return { orgId: conv.org_id, mode: "compaction_model", runAt: d.runAt };
269
+ }
223
270
  this.log.debug("idle compaction armed", {
224
- context: "IdleCompaction",
225
- conversationId: conv.id,
226
- runId,
271
+ ...fields,
272
+ mode: d.mode,
227
273
  runAt: d.runAt,
228
274
  expiresAt: d.expiresAt,
229
275
  });
230
276
  return {
231
277
  orgId: conv.org_id,
278
+ mode: "cache",
232
279
  cacheCallSeq: d.cacheCallSeq,
233
280
  expiresAt: d.expiresAt,
234
281
  runAt: d.runAt,
@@ -241,7 +288,8 @@ IdleArm = __decorate([
241
288
  __param(1, Inject(CompactionSettingsService)),
242
289
  __param(2, Inject(AccountsService)),
243
290
  __param(3, Inject(ProviderRegistry)),
244
- __param(4, Inject(KERNEL_LOGGER))
291
+ __param(4, Inject(ModelPurposesService)),
292
+ __param(5, Inject(KERNEL_LOGGER))
245
293
  ], IdleArm);
246
294
  export { IdleArm };
247
295
  /**
@@ -8,18 +8,39 @@ import type { OutboxService } from "../infra/outbox/outbox.service.js";
8
8
  export declare const IDLE_COMPACTION_JOB = "idle-compaction";
9
9
  /** One job per arming run (no `:`): a duplicate owe of the same run is a no-op. */
10
10
  export declare const idleCompactionJobId: (runId: string) => string;
11
- /** The `idle-compaction` job's data. */
12
- export interface IdleCompactionJobData {
11
+ /** What every `idle-compaction` job carries. */
12
+ interface IdleCompactionJobBase {
13
13
  orgId: string;
14
14
  conversationId: string;
15
15
  /** The run that armed the job. */
16
16
  runId: string;
17
17
  /** The seq of that run's terminal `run_finished` event (S4). */
18
18
  armedSeq: number;
19
+ }
20
+ /**
21
+ * The `idle-compaction` job's data, by how the job compacts (compaction model spec §6.2): in the
22
+ * armed prompt cache (`cache`, with the call the expiry was derived from and the expiry), or on the
23
+ * compaction model (`compaction_model`, due `idleDelayMinutes` after the run, no expiry). A row
24
+ * owed by the previous release has no `mode`: readers take `data.mode ?? "cache"` (C5).
25
+ */
26
+ export type IdleCompactionJobData = (IdleCompactionJobBase & {
27
+ mode: "cache";
19
28
  /** The seq of the `model_call` the cache expiry was derived from (`CacheExpiry.callSeq`). */
20
29
  cacheCallSeq: number;
21
30
  /** When the prompt cache entry expires, epoch ms. */
22
31
  expiresAt: number;
23
- }
32
+ }) | (IdleCompactionJobBase & {
33
+ mode: "compaction_model";
34
+ });
35
+ /**
36
+ * A delivered job's data: {@link IdleCompactionJobData}, or a cache-mode row owed before `mode`
37
+ * existed (still in the outbox or the queue across the deploy, C5).
38
+ */
39
+ export type IdleCompactionJobInput = IdleCompactionJobData | (Omit<Extract<IdleCompactionJobData, {
40
+ mode: "cache";
41
+ }>, "mode"> & {
42
+ mode?: undefined;
43
+ });
24
44
  /** Owes the idle compaction job in the caller's transaction (throws outside one), due at `runAt`. */
25
45
  export declare function oweIdleCompaction(outbox: Pick<OutboxService, "add">, data: IdleCompactionJobData, runAt: number): Promise<boolean>;
46
+ export {};
@@ -1,10 +1,11 @@
1
1
  import { AccountsService } from "../identity/accounts.js";
2
2
  import { KernelDb } from "../infra/database/kernel-db.js";
3
3
  import type { KernelLogger } from "../log.js";
4
+ import { ModelPurposesService } from "../models/purposes.js";
4
5
  import { CompactionService } from "./compaction.service.js";
5
6
  import { CompactionSettingsService } from "./compaction-settings.service.js";
6
7
  import { type IdleFireOutcome } from "./context/idle-compaction-rules.js";
7
- import type { IdleCompactionJobData } from "./idle-compaction-jobs.js";
8
+ import type { IdleCompactionJobInput } from "./idle-compaction-jobs.js";
8
9
  import { ProviderRegistry } from "./providers.js";
9
10
  import { RunQueue } from "./run-queue.js";
10
11
  /**
@@ -15,6 +16,11 @@ import { RunQueue } from "./run-queue.js";
15
16
  * inside `runJob` with the job's org scope. Holds no state between deliveries: every fact comes
16
17
  * from the database and the event log, so a duplicate delivery on another replica sees the first
17
18
  * delivery's run (an event after `armedSeq`, or an active run) and ends `obsolete` or `busy`.
19
+ *
20
+ * The job's mode (compaction model spec §6.3): a `compaction_model` job has no expiry (a late
21
+ * delivery still runs), requires the compaction model at fire time (`chooseSummarizer` against the
22
+ * effective definition's model, read from PG on every delivery) and never falls back to the
23
+ * conversation model or to cache mode; the run it starts carries the mode (`runs.idle_mode`).
18
24
  */
19
25
  export declare class IdleCompactionJob {
20
26
  private readonly kdb;
@@ -24,13 +30,15 @@ export declare class IdleCompactionJob {
24
30
  private readonly compactions;
25
31
  private readonly runs;
26
32
  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">);
33
+ /** The org's `compaction` purpose, read from PG on every delivery (nothing cached). */
34
+ private readonly compactionModel;
35
+ constructor(kdb: KernelDb, compaction: Pick<CompactionSettingsService, "resolve">, accounts: Pick<AccountsService, "idleCompactionOff">, models: Pick<ProviderRegistry, "resolve">, purposes: Pick<ModelPurposesService, "resolve">, compactions: Pick<CompactionService, "probeIdle">, runs: Pick<RunQueue, "startIdleCompaction">, log: Pick<KernelLogger, "info" | "warn" | "error" | "debug">);
28
36
  /**
29
37
  * One delivery of `idle-compact-<runId>` (spec §4.3): gathers {@link IdleFireFacts} cheapest
30
38
  * first, stopping at the first failing check, decides, and starts the run. Logs one `info` line,
31
39
  * context=IdleCompaction. A database failure throws (BullMQ retries the job within its attempts).
32
40
  */
33
- fire(data: IdleCompactionJobData, now?: number): Promise<IdleFireOutcome | "started">;
41
+ fire(data: IdleCompactionJobInput, now?: number): Promise<IdleFireOutcome | "started">;
34
42
  private decide;
35
43
  /**
36
44
  * Check 1's reads: the conversation (live, chat, owned), and its agent when the org is live, the
@@ -15,7 +15,9 @@ import { AccountsService } from "../identity/accounts.js";
15
15
  import { COMPACTION_SETTINGS } from "../identity/settings.js";
16
16
  import { KernelDb } from "../infra/database/kernel-db.js";
17
17
  import { KERNEL_LOGGER } from "../infra/tokens.js";
18
+ import { ModelPurposesService } from "../models/purposes.js";
18
19
  import { CompactionService } from "./compaction.service.js";
20
+ import { chooseSummarizer, compactionModelPort, } from "./compaction-model.js";
19
21
  import { CompactionSettingsService } from "./compaction-settings.service.js";
20
22
  import { CACHE_EXPIRY_MARGIN_MS, CACHE_FIRE_RATIO } from "./context/cache-expiry.js";
21
23
  import { idleFireDecision, } from "./context/idle-compaction-rules.js";
@@ -38,7 +40,8 @@ const PASSING = {
38
40
  now: 0,
39
41
  expiresAt: Number.POSITIVE_INFINITY,
40
42
  backoff: false,
41
- sameModel: true,
43
+ mode: "cache",
44
+ modelReady: true,
42
45
  probe: {
43
46
  estimate: Number.POSITIVE_INFINITY,
44
47
  window: 0,
@@ -56,6 +59,11 @@ const PASSING = {
56
59
  * inside `runJob` with the job's org scope. Holds no state between deliveries: every fact comes
57
60
  * from the database and the event log, so a duplicate delivery on another replica sees the first
58
61
  * delivery's run (an event after `armedSeq`, or an active run) and ends `obsolete` or `busy`.
62
+ *
63
+ * The job's mode (compaction model spec §6.3): a `compaction_model` job has no expiry (a late
64
+ * delivery still runs), requires the compaction model at fire time (`chooseSummarizer` against the
65
+ * effective definition's model, read from PG on every delivery) and never falls back to the
66
+ * conversation model or to cache mode; the run it starts carries the mode (`runs.idle_mode`).
59
67
  */
60
68
  let IdleCompactionJob = class IdleCompactionJob {
61
69
  kdb;
@@ -65,7 +73,9 @@ let IdleCompactionJob = class IdleCompactionJob {
65
73
  compactions;
66
74
  runs;
67
75
  log;
68
- constructor(kdb, compaction, accounts, models, compactions, runs, log) {
76
+ /** The org's `compaction` purpose, read from PG on every delivery (nothing cached). */
77
+ compactionModel;
78
+ constructor(kdb, compaction, accounts, models, purposes, compactions, runs, log) {
69
79
  this.kdb = kdb;
70
80
  this.compaction = compaction;
71
81
  this.accounts = accounts;
@@ -73,6 +83,7 @@ let IdleCompactionJob = class IdleCompactionJob {
73
83
  this.compactions = compactions;
74
84
  this.runs = runs;
75
85
  this.log = log;
86
+ this.compactionModel = compactionModelPort(purposes);
76
87
  }
77
88
  /**
78
89
  * One delivery of `idle-compact-<runId>` (spec §4.3): gathers {@link IdleFireFacts} cheapest
@@ -80,7 +91,8 @@ let IdleCompactionJob = class IdleCompactionJob {
80
91
  * context=IdleCompaction. A database failure throws (BullMQ retries the job within its attempts).
81
92
  */
82
93
  async fire(data, now = Date.now()) {
83
- const extra = {};
94
+ // a row owed before `mode` existed is a cache-mode job (compaction model spec §6.3, C5)
95
+ const extra = { mode: data.mode ?? "cache" };
84
96
  const outcome = await this.decide(data, now, extra);
85
97
  this.log.info("idle compaction job", {
86
98
  context: "IdleCompaction",
@@ -96,27 +108,31 @@ let IdleCompactionJob = class IdleCompactionJob {
96
108
  async decide(data, now, extra) {
97
109
  const t = this.kdb.db;
98
110
  const { orgId, conversationId, armedSeq } = data;
99
- const known = {};
111
+ // a row owed before `mode` existed is a cache-mode job (compaction model spec §6.3, C5)
112
+ const cache = data.mode === "compaction_model" ? undefined : data;
113
+ const mode = cache === undefined ? "compaction_model" : "cache";
114
+ const known = { mode };
100
115
  const failing = () => {
101
116
  const d = idleFireDecision({ ...PASSING, ...known });
102
117
  return d.fire ? undefined : d.outcome;
103
118
  };
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();
119
+ // cache mode: the armed call, its lifetime (for the log) and its model (check 7)
120
+ const call = cache &&
121
+ (await t
122
+ .selectFrom("conversation_events")
123
+ .select("payload")
124
+ .where("conversation_id", "=", conversationId)
125
+ .where("seq", "=", String(cache.cacheCallSeq))
126
+ .where("type", "=", "model_call")
127
+ .executeTakeFirst());
112
128
  const armed = call?.payload;
113
129
  const lifetime = (ttl) => {
114
- if (ttl === undefined || extra.ttl !== undefined)
130
+ if (cache === undefined || ttl === undefined || extra.ttl !== undefined)
115
131
  return;
116
132
  extra.ttl = ttl;
117
133
  // 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);
134
+ const t0 = cache.expiresAt - ttl * 1000;
135
+ const runAt = Math.min(t0 + CACHE_FIRE_RATIO * ttl * 1000, cache.expiresAt - CACHE_EXPIRY_MARGIN_MS);
120
136
  extra.lateMs = now - runAt;
121
137
  };
122
138
  lifetime(armed?.request?.cacheTtl);
@@ -171,9 +187,10 @@ let IdleCompactionJob = class IdleCompactionJob {
171
187
  outcome = failing();
172
188
  if (outcome !== undefined)
173
189
  return outcome;
174
- // check 5 needs no read: the job's time against the armed call's expiry
190
+ // check 5 (cache mode only) needs no read: the job's time against the armed call's expiry
175
191
  known.now = now;
176
- known.expiresAt = data.expiresAt;
192
+ if (cache)
193
+ known.expiresAt = cache.expiresAt;
177
194
  outcome = failing();
178
195
  if (outcome !== undefined)
179
196
  return outcome;
@@ -191,7 +208,9 @@ let IdleCompactionJob = class IdleCompactionJob {
191
208
  if (outcome !== undefined)
192
209
  return outcome;
193
210
  // 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
211
+ // model selection, what the idle run will use) resolves and is enabled; in cache mode it is the
212
+ // armed call's model, in compaction-model mode the compaction model summarizes for it (C6: a
213
+ // model switch since arming does not end the job, the probe sizes against the new model)
195
214
  const version = await t
196
215
  .selectFrom("agent_versions")
197
216
  .select("definition")
@@ -200,12 +219,11 @@ let IdleCompactionJob = class IdleCompactionJob {
200
219
  .executeTakeFirst();
201
220
  const definition = version &&
202
221
  effectiveDefinition(normalizeStoredDefinition(version.definition), await readSelection(t, conversationId));
203
- let resolved = false;
204
- if (definition && armed && sameModel(definition.model, armed)) {
222
+ let ready = false;
223
+ if (definition && (cache === undefined || (armed && sameModel(definition.model, armed)))) {
224
+ let model;
205
225
  try {
206
- const { info } = await this.models.resolve(orgId, definition.model);
207
- lifetime(info.cache?.defaultTtl);
208
- resolved = true;
226
+ model = await this.models.resolve(orgId, definition.model);
209
227
  }
210
228
  catch (err) {
211
229
  // unknown, disabled, or a provider list that failed: no model to compact with now
@@ -216,12 +234,24 @@ let IdleCompactionJob = class IdleCompactionJob {
216
234
  err,
217
235
  });
218
236
  }
237
+ if (model && cache) {
238
+ lifetime(model.info.cache?.defaultTtl);
239
+ ready = true;
240
+ }
241
+ else if (model) {
242
+ // the same choice the idle run makes; a cleared, disabled, unavailable or too small
243
+ // compaction model ends the job (never V, never cache mode); a failed purpose read throws
244
+ const { summarizer } = await chooseSummarizer({ compactionModel: this.compactionModel, registry: this.models, log: this.log }, orgId, { ref: definition.model, provider: model.provider, info: model.info }, settings);
245
+ ready = summarizer.source === "compaction_model";
246
+ }
219
247
  }
220
- known.sameModel = resolved;
248
+ known.modelReady = ready;
221
249
  outcome = failing();
222
250
  if (outcome !== undefined || !definition)
223
251
  return outcome ?? "no_model";
224
- // checks 8 and 9 (S13): the compaction's dry run (reads every event and the media: last)
252
+ // checks 8 and 9 (S13): the compaction's dry run in the job's mode (reads every event and the
253
+ // media: last); in compaction-model mode a null probe (C gone since check 7) is `small`, and
254
+ // in cache mode a compaction model mapped since arming reports no in-context build (C3)
225
255
  const probe = await this.compactions.probeIdle({
226
256
  orgId,
227
257
  conversationId,
@@ -231,7 +261,7 @@ let IdleCompactionJob = class IdleCompactionJob {
231
261
  source: conv.source,
232
262
  conversationKind: "chat",
233
263
  absorbedUpToSeq: Number(conv.consumed_seq),
234
- });
264
+ }, mode);
235
265
  // an unavailable model or storage during the dry run: nothing to compact with now
236
266
  known.probe = probe;
237
267
  known.inContext = probe?.inContext ?? false;
@@ -242,7 +272,7 @@ let IdleCompactionJob = class IdleCompactionJob {
242
272
  return outcome;
243
273
  // §5.1: the run, under the conversation row lock (checks 1-3 again); a refusal is a message,
244
274
  // a run or a queued message that arrived in between
245
- const idleRunId = await this.runs.startIdleCompaction(conversationId, armedSeq);
275
+ const idleRunId = await this.runs.startIdleCompaction(conversationId, armedSeq, mode);
246
276
  if (idleRunId === null) {
247
277
  // label the refusal by the first check it now fails (the order of checks 1-3)
248
278
  if ((await this.readLive(orgId, conversationId)).agent === undefined)
@@ -309,8 +339,9 @@ IdleCompactionJob = __decorate([
309
339
  __param(1, Inject(CompactionSettingsService)),
310
340
  __param(2, Inject(AccountsService)),
311
341
  __param(3, Inject(ProviderRegistry)),
312
- __param(4, Inject(CompactionService)),
313
- __param(5, Inject(RunQueue)),
314
- __param(6, Inject(KERNEL_LOGGER))
342
+ __param(4, Inject(ModelPurposesService)),
343
+ __param(5, Inject(CompactionService)),
344
+ __param(6, Inject(RunQueue)),
345
+ __param(7, Inject(KERNEL_LOGGER))
315
346
  ], IdleCompactionJob);
316
347
  export { IdleCompactionJob };
@@ -3,10 +3,11 @@ import type { AgentDefinition, ModelRef } from "../agents/definition.js";
3
3
  import type { KernelConfig } from "../config/schema.js";
4
4
  import type { AppendEvent, EventLog } from "../conversations/event-log.js";
5
5
  import { type ConversationEvent } from "../conversations/events.js";
6
- import type { KernelSchemaDb } from "../db/kernel-schema.js";
6
+ import type { IdleMode, KernelSchemaDb } from "../db/kernel-schema.js";
7
7
  import type { CaseSnapshot } from "../evals/snapshot.js";
8
8
  import type { KernelConfigService } from "../infra/config/kernel-config.service.js";
9
9
  import type { ToolRegistry, UnavailableTool } from "../tools/registry.js";
10
+ import { type CompactionModelPort, type Summarizer } from "./compaction-model.js";
10
11
  import type { CompactionProgressSink } from "./compaction-progress.js";
11
12
  import type { CompactionSettings, CompactionSettingsService } from "./compaction-settings.service.js";
12
13
  import { type BuildModelRequestInput, type MediaBytes, type MediaInfo, type ModelCallMeta, type RequestTool } from "./context/build.js";
@@ -97,6 +98,13 @@ export interface ModelStepDeps {
97
98
  * Absent in eval replays and single-step replays, which have no live conversation to show it on.
98
99
  */
99
100
  compactionProgress?: CompactionProgressSink;
101
+ /**
102
+ * The org's `compaction` purpose (compaction model spec §4.2): read once per compaction, after
103
+ * the trigger passed and a plan exists. Absent = unmapped (test stubs, single-step replays): every
104
+ * compaction summarizes on the conversation model by today's rules. Live runs get it
105
+ * (`RunSteps`); full-run replays inherit it and resolve C through their billed registry.
106
+ */
107
+ compactionModel?: CompactionModelPort;
100
108
  /** The kernel logger (its `debug` level is optional here: SDK loggers have none). */
101
109
  log: Logger & {
102
110
  debug?(msg: string, fields?: Record<string, unknown>): void;
@@ -401,11 +409,15 @@ export interface CompactOptions {
401
409
  */
402
410
  transcriptOnly?: boolean;
403
411
  /**
404
- * The idle compact run (idle compaction spec §4.3 check 9): an in-context skip ends the
405
- * compaction with nothing written; never the transcript request. Implies nothing about `manual`
406
- * (ruling R13: a manual compaction is transcript-only, so the idle run never sets it).
412
+ * The idle compact run's mode (idle compaction spec §4.3 check 9, compaction model spec §6.3).
413
+ * `cache`: an in-context skip ends the compaction with nothing written; never the transcript
414
+ * request (a compaction model mapped since arming skips the in-context build, so it writes
415
+ * nothing either: spec issue C3). `compaction_model`: the summarizer must be the compaction
416
+ * model, else the compaction ends with nothing written (`no_compaction_model`); never V. Implies
417
+ * nothing about `manual` (ruling R13: a manual compaction is transcript-only, so the idle run
418
+ * never sets it).
407
419
  */
408
- requireInContext?: boolean;
420
+ idle?: IdleMode;
409
421
  }
410
422
  /** What one compaction execution wrote: the events, the summary's seq and whether it failed. */
411
423
  export interface CompactionOutcome {
@@ -443,7 +455,12 @@ export type InContextFallback = InContextSkip
443
455
  * Input the model has not answered follows the last reply (ruling R9, {@link
444
456
  * unansweredAfterReply}): a tool result, or an absorbed message other than a run opener.
445
457
  */
446
- | "pending_input";
458
+ | "pending_input"
459
+ /**
460
+ * A configured, usable, eligible compaction model summarizes instead (compaction model spec
461
+ * §4.4, decision Q2): always the transcript.
462
+ */
463
+ | "compaction_model";
447
464
  /** The in-context summary call of one compaction. */
448
465
  export interface InContextSummary {
449
466
  request: ModelRequest;
@@ -460,13 +477,18 @@ export interface InContextSummary {
460
477
  * compaction spec §4.3 checks 8 and 9).
461
478
  */
462
479
  export interface PreparedCompaction {
463
- provider: BoundProvider;
480
+ /** The conversation model V: what the next request is built for (`opts.ref` or the agent's). */
464
481
  info: ModelInfo;
465
- /** The model the compaction summarizes with (`opts.ref` or the agent's main model). */
482
+ /** V's ref (`opts.ref` or the agent's main model): the estimate, the plan and the fit use it. */
466
483
  ref: ModelRef;
484
+ /**
485
+ * Who writes the summary (compaction model spec §3): the compaction model C, or V. The call
486
+ * part uses only it (request, hooks, usage, stream, chunk budget).
487
+ */
488
+ summarizer: Summarizer;
467
489
  /** The calibrated estimate of the next step's request (what the trigger compares). */
468
490
  estimate: number;
469
- /** The model's context window. */
491
+ /** V's context window. */
470
492
  window: number;
471
493
  /** The estimated tokens of the plan's transcript: what no summary covers yet. */
472
494
  growthTokens: number;
@@ -476,7 +498,7 @@ export interface PreparedCompaction {
476
498
  };
477
499
  /** Whether the manual rule planned it (`opts.manual`). */
478
500
  manual: boolean;
479
- /** The summary call's output cap (context compaction spec §4.8). */
501
+ /** The summary call's output cap (context compaction spec §4.8): `summarizer.cap`. */
480
502
  summaryCap: number;
481
503
  /** The in-context summary request, or why the compaction would summarize the transcript. */
482
504
  inContext: InContextSummary | {
@@ -503,14 +525,24 @@ export type CompactionPrepareSkip =
503
525
  | {
504
526
  skipped: "unavailable";
505
527
  reason: string;
528
+ }
529
+ /**
530
+ * `opts.idle === "compaction_model"` and the summarizer is not the compaction model (unmapped,
531
+ * unavailable or too small now): the idle run never falls back to V (compaction model spec §6.3).
532
+ */
533
+ | {
534
+ skipped: "no_compaction_model";
506
535
  };
507
536
  /**
508
537
  * The preparation of one compaction (idle compaction spec §4.3): resolve the model, load the media,
509
538
  * build the next step's request and calibrate its estimate, apply the trigger and the backoff (unless
510
- * `opts.force`), plan, and build the in-context summary request ({@link inContextSummary}). It writes
511
- * nothing and sends no model call; the outcomes a manual compaction records (`compaction_skipped`,
512
- * `compaction_failed` for an unavailable model) are {@link runCompaction}'s. `hooks.planned` runs once
513
- * the plan exists, before the in-context build reads the live snapshot.
539
+ * `opts.force`), plan, choose the summarizer ({@link chooseSummarizer}: the org's compaction model
540
+ * when it is usable and eligible, else V), and build the in-context summary request
541
+ * ({@link inContextSummary}; skipped when the compaction model summarizes). It writes nothing and
542
+ * sends no model call; the outcomes a manual compaction records (`compaction_skipped`,
543
+ * `compaction_failed` for an unavailable model) are {@link runCompaction}'s. `hooks.planned` runs
544
+ * once the summarizer is chosen (an idle run in compaction-model mode without one ends before it),
545
+ * before the in-context build reads the live snapshot.
514
546
  */
515
547
  export declare function prepareCompaction(deps: ModelStepDeps, input: ModelStepInput, events: ConversationEvent[], runtime: Runtime, compaction: CompactionSettings, tools: StepTools, opts?: CompactOptions, hooks?: {
516
548
  planned?: () => void;
@@ -526,8 +558,12 @@ export declare function prepareCompaction(deps: ModelStepDeps, input: ModelStepI
526
558
  *
527
559
  * `opts.force` (the reactive path, spec §4.4, and a manual compact run, spec §4.7) bypasses the
528
560
  * trigger, `enabled` and the backoff, and `opts.ref` makes it summarise with the rung's model rather
529
- * than the agent's main model. `opts.requireInContext` (the idle compact run, idle compaction spec
530
- * §4.3) ends the compaction with nothing written when the in-context summary does not apply.
561
+ * than the agent's main model. `opts.idle` (the idle compact run, idle compaction spec §4.3)
562
+ * ends the compaction with nothing written when its summarizer does not apply: the in-context
563
+ * summary in `cache` mode, the compaction model in `compaction_model` mode. The summary calls go
564
+ * to the prepared summarizer (compaction model spec §3): the org's compaction model when one is
565
+ * usable and eligible, else the conversation model; a failed or denied call on it is never
566
+ * retried on the other (decision Q1).
531
567
  *
532
568
  * The one execution every path runs: the automatic step path through {@link maybeCompact} and a
533
569
  * compact run (manual or idle) through `CompactionService.force`. The preparation is