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

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 (35) hide show
  1. package/bootstrap.json +7 -7
  2. package/dist/admin/admin.schemas.d.ts +1 -0
  3. package/dist/conversations/events.d.ts +8 -0
  4. package/dist/conversations/events.js +11 -0
  5. package/dist/db/kernel-schema.d.ts +3 -0
  6. package/dist/identity/settings.d.ts +5 -0
  7. package/dist/identity/settings.js +4 -0
  8. package/dist/models/purposes.js +5 -0
  9. package/dist/orgs/settings.service.d.ts +2 -0
  10. package/dist/platform/ops/org-settings.ops.js +1 -1
  11. package/dist/runtime/compaction-model.d.ts +57 -0
  12. package/dist/runtime/compaction-model.js +87 -0
  13. package/dist/runtime/compaction.service.d.ts +23 -8
  14. package/dist/runtime/compaction.service.js +15 -10
  15. package/dist/runtime/context/compaction.d.ts +19 -2
  16. package/dist/runtime/context/compaction.js +23 -2
  17. package/dist/runtime/context/idle-compaction-rules.d.ts +17 -2
  18. package/dist/runtime/context/idle-compaction-rules.js +20 -5
  19. package/dist/runtime/idle-arm.d.ts +12 -2
  20. package/dist/runtime/idle-arm.js +66 -18
  21. package/dist/runtime/idle-compaction-jobs.d.ts +24 -3
  22. package/dist/runtime/idle-compaction.d.ts +11 -3
  23. package/dist/runtime/idle-compaction.js +61 -30
  24. package/dist/runtime/model-call.d.ts +52 -16
  25. package/dist/runtime/model-call.js +71 -24
  26. package/dist/runtime/run-finish.d.ts +12 -3
  27. package/dist/runtime/run-finish.js +14 -7
  28. package/dist/runtime/run-queue.d.ts +5 -2
  29. package/dist/runtime/run-queue.js +7 -4
  30. package/dist/runtime/run-steps.d.ts +4 -1
  31. package/dist/runtime/run-steps.js +9 -2
  32. package/dist/runtime/run-worker.js +4 -2
  33. package/dist/runtime/runtime.module.js +3 -0
  34. package/package.json +1 -1
  35. package/src/migrations/0200_runs_idle_mode.sql +4 -0
package/bootstrap.json CHANGED
@@ -3,15 +3,15 @@
3
3
  "schemaVersion": 1,
4
4
  "marketplace": {
5
5
  "url": "https://github.com/capybara-hq/plugins.git",
6
- "commit": "5ace2e570721d3ab278f7fd2bffc3d40ec88503a"
6
+ "commit": "eba4a5dc5a2a33208d87b634d7124910eaccdc6c"
7
7
  },
8
8
  "plugins": [
9
9
  {
10
10
  "name": "openai-compatible",
11
11
  "source": "npm",
12
12
  "npm": "@capybara-hq/plugin-openai-compatible",
13
- "version": "0.1.0-rc.15",
14
- "integrity": "sha512-GwDNf+46SwFdDOodWGJokorOWQCvO+0QJx5NhsXChWCnpezmLFiXxgmIuG2V1KNQnRSCvH1SJBUE5EsOTFRvKA==",
13
+ "version": "0.1.0-rc.16",
14
+ "integrity": "sha512-a0A0cFcv6gcf8Pa4GxYYrc7algrOxE+VlnzIvZo2z58ckZWwAoLXcj2USAcBrZRLRLN11mTmT7QwWfaKia1G+A==",
15
15
  "required": false
16
16
  },
17
17
  {
@@ -42,16 +42,16 @@
42
42
  "name": "deepseek",
43
43
  "source": "npm",
44
44
  "npm": "@capybara-hq/plugin-deepseek",
45
- "version": "0.1.0-rc.13",
46
- "integrity": "sha512-i6cPL8gTGCvPRdC5UzlKnJdYjrGfPUQHrpdJDp8q8cekMu6GReJQHBFb5dt3U+zlUfOX75IwoIlTPfeJwr/ACg==",
45
+ "version": "0.1.0-rc.14",
46
+ "integrity": "sha512-+kWGoKIzTanvC/PyKZGsEg8ZqjoV11W/ynAXekCaFnH4QTZ8FrRZrQdSDtARyyU73EfNNiEV2V8dUVxvemhS/w==",
47
47
  "required": false
48
48
  },
49
49
  {
50
50
  "name": "bailian",
51
51
  "source": "npm",
52
52
  "npm": "@capybara-hq/plugin-bailian",
53
- "version": "0.1.0-rc.14",
54
- "integrity": "sha512-m1e6FaD0ouHq/2vJkyQPyj3pz4PH7QpYNRlftOJYBaKve8EqKGz/uH44UGBtI+tROmDhdnZ5xn3FFlyyQIYCkA==",
53
+ "version": "0.1.0-rc.15",
54
+ "integrity": "sha512-Khi4XEy5gdyOfWEObqixyMYunF8eGwqewRvay5t/k7cYeCORsrHx7pVqti2/Uubf//oAM7hLLUMygRSiQo0uEw==",
55
55
  "required": false
56
56
  },
57
57
  {
@@ -91,6 +91,7 @@ export declare const DeploymentSettingsBody: z.ZodObject<{
91
91
  idleEnabled: z.ZodOptional<z.ZodBoolean>;
92
92
  idleMinTokensFloor: z.ZodOptional<z.ZodNumber>;
93
93
  idleMinWindowRatio: z.ZodOptional<z.ZodNumber>;
94
+ idleDelayMinutes: z.ZodOptional<z.ZodNumber>;
94
95
  }, z.core.$strict>>;
95
96
  promptCache: z.ZodOptional<z.ZodObject<{
96
97
  longTtl: z.ZodOptional<z.ZodBoolean>;
@@ -2137,6 +2137,10 @@ export declare const ConversationEventSchema: z.ZodDiscriminatedUnion<[z.ZodObje
2137
2137
  in_context: "in_context";
2138
2138
  transcript: "transcript";
2139
2139
  }>>;
2140
+ model: z.ZodOptional<z.ZodObject<{
2141
+ provider: z.ZodString;
2142
+ model: z.ZodString;
2143
+ }, z.core.$strip>>;
2140
2144
  step: z.ZodNumber;
2141
2145
  }, z.core.$strip>;
2142
2146
  }, z.core.$strip>, z.ZodObject<{
@@ -2144,6 +2148,10 @@ export declare const ConversationEventSchema: z.ZodDiscriminatedUnion<[z.ZodObje
2144
2148
  payload: z.ZodObject<{
2145
2149
  attempt: z.ZodNumber;
2146
2150
  reason: z.ZodString;
2151
+ model: z.ZodOptional<z.ZodObject<{
2152
+ provider: z.ZodString;
2153
+ model: z.ZodString;
2154
+ }, z.core.$strip>>;
2147
2155
  step: z.ZodNumber;
2148
2156
  }, z.core.$strip>;
2149
2157
  }, z.core.$strip>, z.ZodObject<{
@@ -1913,6 +1913,12 @@ export const ConversationEventSchema = z.discriminatedUnion("type", [
1913
1913
  * the log, so no `DriftReason`. Absent on summaries written before it (read as `transcript`).
1914
1914
  */
1915
1915
  method: z.enum(["transcript", "in_context"]).optional(),
1916
+ /**
1917
+ * The configured ref of the model that wrote the summary (compaction model spec §7.1): the
1918
+ * compaction model, or the conversation's on the fallback path. Not model-visible; absent
1919
+ * before it.
1920
+ */
1921
+ model: z.object({ provider: z.string(), model: z.string() }).optional(),
1916
1922
  /**
1917
1923
  * The step the compaction ran in (0 for a manual compact run), so a later compaction in the
1918
1924
  * same step takes the next idempotency key.
@@ -1922,6 +1928,11 @@ export const ConversationEventSchema = z.discriminatedUnion("type", [
1922
1928
  ev("compaction_failed", z.object({
1923
1929
  attempt: count,
1924
1930
  reason: z.string(),
1931
+ /**
1932
+ * The configured ref of the model whose call failed or was denied (compaction model spec
1933
+ * §7.1); not model-visible; absent when no call was built.
1934
+ */
1935
+ model: z.object({ provider: z.string(), model: z.string() }).optional(),
1925
1936
  /** The step the compaction ran in, as on `compaction_summary`. */
1926
1937
  step: count,
1927
1938
  })),
@@ -526,6 +526,7 @@ export interface RunRecoveryCursorsTable {
526
526
  since: TsNullable;
527
527
  run_id: string | null;
528
528
  }
529
+ export type IdleMode = "cache" | "compaction_model";
529
530
  export interface RunsTable {
530
531
  /** 0135: the worker acquisition currently authorized to mutate this run. */
531
532
  execution_id: string | null;
@@ -577,6 +578,8 @@ export interface RunsTable {
577
578
  * (the idle compaction job); null = an ordinary run, or a compact run from before 0195 (manual).
578
579
  */
579
580
  compact_origin: ColumnType<"manual" | "idle" | null, "manual" | "idle" | null | undefined, "manual" | "idle" | null>;
581
+ /** 0200: an idle compact run's mode (compaction model spec §6.1); null on every other run. */
582
+ idle_mode: ColumnType<IdleMode | null, IdleMode | null | undefined, IdleMode | null>;
580
583
  }
581
584
  /** 0053: one row per sub-agent dispatch (an `Agent` call of a parent run). */
582
585
  export interface SubagentDispatchesTable {
@@ -90,6 +90,7 @@ export declare const COMPACTION_SETTINGS: z.ZodObject<{
90
90
  idleEnabled: z.ZodDefault<z.ZodBoolean>;
91
91
  idleMinTokensFloor: z.ZodDefault<z.ZodNumber>;
92
92
  idleMinWindowRatio: z.ZodDefault<z.ZodNumber>;
93
+ idleDelayMinutes: z.ZodDefault<z.ZodNumber>;
93
94
  }, z.core.$strip>;
94
95
  export type CompactionSettings = z.infer<typeof COMPACTION_SETTINGS>;
95
96
  /**
@@ -106,6 +107,7 @@ export declare const COMPACTION_SETTINGS_PARTIAL: z.ZodObject<{
106
107
  idleEnabled: z.ZodOptional<z.ZodBoolean>;
107
108
  idleMinTokensFloor: z.ZodOptional<z.ZodNumber>;
108
109
  idleMinWindowRatio: z.ZodOptional<z.ZodNumber>;
110
+ idleDelayMinutes: z.ZodOptional<z.ZodNumber>;
109
111
  }, z.core.$strip>;
110
112
  /**
111
113
  * The patch form both settings writers take: the partial form above, strict, so a misspelled
@@ -121,6 +123,7 @@ export declare const COMPACTION_SETTINGS_PATCH: z.ZodObject<{
121
123
  idleEnabled: z.ZodOptional<z.ZodBoolean>;
122
124
  idleMinTokensFloor: z.ZodOptional<z.ZodNumber>;
123
125
  idleMinWindowRatio: z.ZodOptional<z.ZodNumber>;
126
+ idleDelayMinutes: z.ZodOptional<z.ZodNumber>;
124
127
  }, z.core.$strict>;
125
128
  export type CompactionSettingsPatch = z.infer<typeof COMPACTION_SETTINGS_PARTIAL>;
126
129
  /**
@@ -189,6 +192,7 @@ export declare const DEPLOYMENT_SETTINGS: z.ZodObject<{
189
192
  idleEnabled: z.ZodDefault<z.ZodBoolean>;
190
193
  idleMinTokensFloor: z.ZodDefault<z.ZodNumber>;
191
194
  idleMinWindowRatio: z.ZodDefault<z.ZodNumber>;
195
+ idleDelayMinutes: z.ZodDefault<z.ZodNumber>;
192
196
  }, z.core.$strip>>;
193
197
  promptCache: z.ZodPrefault<z.ZodObject<{
194
198
  longTtl: z.ZodDefault<z.ZodBoolean>;
@@ -299,6 +303,7 @@ export declare const DEPLOYMENT_SETTINGS_PATCH: z.ZodObject<{
299
303
  idleEnabled: z.ZodOptional<z.ZodBoolean>;
300
304
  idleMinTokensFloor: z.ZodOptional<z.ZodNumber>;
301
305
  idleMinWindowRatio: z.ZodOptional<z.ZodNumber>;
306
+ idleDelayMinutes: z.ZodOptional<z.ZodNumber>;
302
307
  }, z.core.$strict>>;
303
308
  promptCache: z.ZodOptional<z.ZodObject<{
304
309
  longTtl: z.ZodOptional<z.ZodBoolean>;
@@ -137,6 +137,7 @@ const COMPACTION_FIELDS = {
137
137
  idleEnabled: z.boolean(),
138
138
  idleMinTokensFloor: z.number().int().min(50_000).max(2_000_000),
139
139
  idleMinWindowRatio: z.number().min(0.1).max(0.9),
140
+ idleDelayMinutes: z.number().int().min(5).max(1440),
140
141
  };
141
142
  /**
142
143
  * Conversation compaction (context compaction spec §4.8): the platform's defaults and the bounds
@@ -153,6 +154,7 @@ export const COMPACTION_SETTINGS = z.object({
153
154
  idleEnabled: COMPACTION_FIELDS.idleEnabled.default(true),
154
155
  idleMinTokensFloor: COMPACTION_FIELDS.idleMinTokensFloor.default(200_000),
155
156
  idleMinWindowRatio: COMPACTION_FIELDS.idleMinWindowRatio.default(0.3),
157
+ idleDelayMinutes: COMPACTION_FIELDS.idleDelayMinutes.default(30),
156
158
  });
157
159
  /**
158
160
  * The partial form the platform and org patches carry: only the given fields, validated against
@@ -180,6 +182,7 @@ export function effectiveCompactionSettings(platform, org) {
180
182
  idleEnabled: org?.idleEnabled ?? platform.idleEnabled,
181
183
  idleMinTokensFloor: org?.idleMinTokensFloor ?? platform.idleMinTokensFloor,
182
184
  idleMinWindowRatio: org?.idleMinWindowRatio ?? platform.idleMinWindowRatio,
185
+ idleDelayMinutes: org?.idleDelayMinutes ?? platform.idleDelayMinutes,
183
186
  };
184
187
  }
185
188
  /**
@@ -882,6 +885,7 @@ let SettingsService = class SettingsService {
882
885
  idleEnabled: compactionPatch.idleEnabled ?? current.compaction.idleEnabled,
883
886
  idleMinTokensFloor: compactionPatch.idleMinTokensFloor ?? current.compaction.idleMinTokensFloor,
884
887
  idleMinWindowRatio: compactionPatch.idleMinWindowRatio ?? current.compaction.idleMinWindowRatio,
888
+ idleDelayMinutes: compactionPatch.idleDelayMinutes ?? current.compaction.idleDelayMinutes,
885
889
  };
886
890
  }
887
891
  if (promptCachePatch !== undefined) {
@@ -46,6 +46,11 @@ export const KERNEL_PURPOSES = [
46
46
  * current chat model (a sub-agent's call: the sub-agent's).
47
47
  */
48
48
  { purpose: "web_fetch", kind: "chat", label: { zh: "网页提取", en: "Web page extraction" } },
49
+ /**
50
+ * The compaction summarizer (compaction model spec); unmapped → the model whose next request the
51
+ * summary serves (the conversation's model, or the overflowed rung on the reactive path).
52
+ */
53
+ { purpose: "compaction", kind: "chat", label: { zh: "摘要压缩", en: "Compaction" } },
49
54
  {
50
55
  purpose: "subagent_fast",
51
56
  kind: "chat",
@@ -267,6 +267,7 @@ export declare const OrgSettingsSchema: z.ZodObject<{
267
267
  idleEnabled: z.ZodOptional<z.ZodBoolean>;
268
268
  idleMinTokensFloor: z.ZodOptional<z.ZodNumber>;
269
269
  idleMinWindowRatio: z.ZodOptional<z.ZodNumber>;
270
+ idleDelayMinutes: z.ZodOptional<z.ZodNumber>;
270
271
  }, z.core.$strip>>>;
271
272
  promptCache: z.ZodCatch<z.ZodOptional<z.ZodObject<{
272
273
  longTtl: z.ZodOptional<z.ZodBoolean>;
@@ -384,6 +385,7 @@ export declare const OrgSettingsPatchSchema: z.ZodObject<{
384
385
  idleEnabled: z.ZodOptional<z.ZodBoolean>;
385
386
  idleMinTokensFloor: z.ZodOptional<z.ZodNumber>;
386
387
  idleMinWindowRatio: z.ZodOptional<z.ZodNumber>;
388
+ idleDelayMinutes: z.ZodOptional<z.ZodNumber>;
387
389
  }, z.core.$strict>>>;
388
390
  promptCache: z.ZodOptional<z.ZodNullable<z.ZodObject<{
389
391
  longTtl: z.ZodOptional<z.ZodBoolean>;
@@ -57,7 +57,7 @@ let OrgSettingsOperations = class OrgSettingsOperations {
57
57
  }),
58
58
  defineOperation({
59
59
  id: "org-settings.update",
60
- description: "Change this org's settings (org admins). Give only the settings to change; null clears outsideSandbox, deviceNetwork or wakeOnBackgroundTask so they follow the deployment again (refused when the deployment value is wider than what this tool may set). outsideSandbox (allowed or off; the platform must allow it) and deviceNetwork ({ default?, ceiling?: open | allowlist, base?: platform | none, extraHosts?, excludedHosts? }, replaced whole, so send the stored fields you keep; neither default nor ceiling may be open where the platform's ceiling is allowlist, and the default may not be above the ceiling) may only narrow the org's devices here: allowing outside-sandbox runs where the org has them off, opening the default or the ceiling, adding an extra host, dropping an exclusion or moving base from none to platform is refused and needs a person in the organization settings on the web. theme: { id, personal } sets the org's default theme (a theme id from themes.list, or null to follow the platform) and whether members may pick their own (allowed) or not (locked); null clears it. uiArrangement: { <slot>: { hidden, order } } (a list slot) or { <slot>: { use } } (a single slot: shell.brand, conversation.empty, conversation.composer.frame) replaces that slot's entry, where hidden, order and use name contribution keys <extension>/<contribution> (hidden ones are not listed in the web UI but their pages still open by URL; use null is the built-in); null for a slot makes it follow the platform again; platform.page is refused. navigation: { pluginPages: [{ contribution: <extension>/<contribution>, section: primary or more }] } replaces where the org's plugin pages sit in the navigation (at most 3 primary, so send the whole list you keep); null clears it. externalSharing (on or off; null clears it, off) may only be turned off through this tool: turning it on needs a person in the organization settings on the web, and the platform must allow it. promptSuggestions (on or off; null clears it, absent meaning on: whether the composer suggests the person's next message after a completed run; the deployment's promptSuggestions must be on too) may be set either way through this tool. compaction ({ enabled?, threshold? (0.5 to 0.95), keepRecentTurns? (0 to 20), reserveTokens? (0 to 50000), maxOutputTokens? (1024 to 32000), idleEnabled? (compact idle conversations before a cache of 30 minutes or more expires), idleMinTokensFloor? (50000 to 2000000), idleMinWindowRatio? (0.1 to 0.9) }: the org's conversation compaction overrides, merged into the stored fields; null clears the override so the org follows the platform) may be set either way. promptCache ({ longTtl }: true or false; whether requests use the model's prompt cache tier of at least 30 minutes, such as 1 hour, where cache writes cost more; null clears it so the org follows the platform) may be set either way. Setting platformTool to off or read-only takes effect from the next call and cuts this Platform tool off in the org; an org admin switches it back on in the web settings.",
60
+ description: "Change this org's settings (org admins). Give only the settings to change; null clears outsideSandbox, deviceNetwork or wakeOnBackgroundTask so they follow the deployment again (refused when the deployment value is wider than what this tool may set). outsideSandbox (allowed or off; the platform must allow it) and deviceNetwork ({ default?, ceiling?: open | allowlist, base?: platform | none, extraHosts?, excludedHosts? }, replaced whole, so send the stored fields you keep; neither default nor ceiling may be open where the platform's ceiling is allowlist, and the default may not be above the ceiling) may only narrow the org's devices here: allowing outside-sandbox runs where the org has them off, opening the default or the ceiling, adding an extra host, dropping an exclusion or moving base from none to platform is refused and needs a person in the organization settings on the web. theme: { id, personal } sets the org's default theme (a theme id from themes.list, or null to follow the platform) and whether members may pick their own (allowed) or not (locked); null clears it. uiArrangement: { <slot>: { hidden, order } } (a list slot) or { <slot>: { use } } (a single slot: shell.brand, conversation.empty, conversation.composer.frame) replaces that slot's entry, where hidden, order and use name contribution keys <extension>/<contribution> (hidden ones are not listed in the web UI but their pages still open by URL; use null is the built-in); null for a slot makes it follow the platform again; platform.page is refused. navigation: { pluginPages: [{ contribution: <extension>/<contribution>, section: primary or more }] } replaces where the org's plugin pages sit in the navigation (at most 3 primary, so send the whole list you keep); null clears it. externalSharing (on or off; null clears it, off) may only be turned off through this tool: turning it on needs a person in the organization settings on the web, and the platform must allow it. promptSuggestions (on or off; null clears it, absent meaning on: whether the composer suggests the person's next message after a completed run; the deployment's promptSuggestions must be on too) may be set either way through this tool. compaction ({ enabled?, threshold? (0.5 to 0.95), keepRecentTurns? (0 to 20), reserveTokens? (0 to 50000), maxOutputTokens? (1024 to 32000), idleEnabled? (compact idle conversations in the background: after idleDelayMinutes with a compaction model, else before a cache of 30 minutes or more expires), idleMinTokensFloor? (50000 to 2000000), idleMinWindowRatio? (0.1 to 0.9), idleDelayMinutes? (5 to 1440; minutes after a run before an idle compaction when a compaction model is set) }: the org's conversation compaction overrides, merged into the stored fields; null clears the override so the org follows the platform) may be set either way. promptCache ({ longTtl }: true or false; whether requests use the model's prompt cache tier of at least 30 minutes, such as 1 hour, where cache writes cost more; null clears it so the org follows the platform) may be set either way. Setting platformTool to off or read-only takes effect from the next call and cuts this Platform tool off in the org; an org admin switches it back on in the web settings.",
61
61
  input: OrgSettingsPatchSchema.refine((i) => Object.values(i).some((v) => v !== undefined), {
62
62
  message: "give at least one setting",
63
63
  }),
@@ -0,0 +1,57 @@
1
+ import { type ModelInfo, type ParamValue } from "@capybara-hq/plugin-sdk";
2
+ import type { ModelRef } from "../agents/definition.js";
3
+ import type { CompactionSettings } from "../identity/settings.js";
4
+ import type { ModelPurposesService, PurposeTarget } from "../models/purposes.js";
5
+ import type { ModelStepDeps } from "./model-call.js";
6
+ import type { BoundProvider } from "./providers.js";
7
+ /** The org's effective `compaction` mapping, or null when it is unconfigured there. */
8
+ export interface CompactionModelPort {
9
+ target(orgId: string): Promise<PurposeTarget | null>;
10
+ }
11
+ /**
12
+ * Wraps `ModelPurposesService.resolve(orgId, "compaction")` (compaction model spec §4.2):
13
+ * `model.unconfigured` (unmapped, or a target the org cannot use) → null; any other error is
14
+ * rethrown. A `ProviderListError` passes `resolve` with the mapping, so the summarizer choice
15
+ * resolves the model again and falls back there. Reads PG each time (nothing cached): callers never
16
+ * hold a transaction open around it, since the resolve may list a provider's models.
17
+ */
18
+ export declare function compactionModelPort(purposes: Pick<ModelPurposesService, "resolve">): CompactionModelPort;
19
+ /** The model that writes one compaction's summary (compaction model spec §3, §5.1). */
20
+ export interface Summarizer {
21
+ /** The compaction model C, or the conversation model V (the fallback). */
22
+ source: "compaction_model" | "conversation";
23
+ /** The configured ref: what the hooks, the usage events and `compaction_summary.model` name. */
24
+ ref: ModelRef;
25
+ provider: BoundProvider;
26
+ info: ModelInfo;
27
+ /** The request parameters: C's mapping sanitized against `info.parameters`; `{}` for V. */
28
+ params: Record<string, ParamValue>;
29
+ /** The summary cap `Cmax` ({@link compactionSummaryCap}). */
30
+ cap: number;
31
+ }
32
+ /** Why V summarizes although the purpose was looked up (§4.2 table). */
33
+ export type SummarizerFallback =
34
+ /** No port, or no effective mapping the org can use. */
35
+ "unconfigured"
36
+ /** The mapping passed `resolve` (a provider list error) but the registry cannot resolve C. */
37
+ | "compaction_model_unavailable"
38
+ /** C's window leaves no useful chunk (§4.3). */
39
+ | "compaction_model_small";
40
+ /**
41
+ * §4.2 / §4.3: C when mapped, resolvable and eligible; else V with the reason (logged at `warn` for
42
+ * unavailable, `debug` for small, not at all for unconfigured; `context=Compaction`). Never throws
43
+ * for C's resolution or size; an error of the port other than unconfigured (a failed PG read)
44
+ * propagates, and `prepareCompaction` ends the compaction as unavailable (never on V).
45
+ *
46
+ * The cap is `min(setting, V max)` on V (today's) and `min(setting, C max, V max)` on C: a
47
+ * large-output summarizer never writes a longer summary than V would (§5.1). Eligibility is
48
+ * judged with C's cap and window against the settings' reserve.
49
+ */
50
+ export declare function chooseSummarizer(deps: Pick<ModelStepDeps, "compactionModel" | "registry" | "log">, orgId: string, conversation: {
51
+ ref: ModelRef;
52
+ provider: BoundProvider;
53
+ info: ModelInfo;
54
+ }, settings: Pick<CompactionSettings, "maxOutputTokens" | "reserveTokens">): Promise<{
55
+ summarizer: Summarizer;
56
+ fallback?: SummarizerFallback;
57
+ }>;
@@ -0,0 +1,87 @@
1
+ import { sanitizeParams } from "@capybara-hq/plugin-sdk";
2
+ import { ApiError } from "../errors.js";
3
+ import { compactionModelEligible, compactionSummaryCap } from "./context/compaction.js";
4
+ /**
5
+ * Wraps `ModelPurposesService.resolve(orgId, "compaction")` (compaction model spec §4.2):
6
+ * `model.unconfigured` (unmapped, or a target the org cannot use) → null; any other error is
7
+ * rethrown. A `ProviderListError` passes `resolve` with the mapping, so the summarizer choice
8
+ * resolves the model again and falls back there. Reads PG each time (nothing cached): callers never
9
+ * hold a transaction open around it, since the resolve may list a provider's models.
10
+ */
11
+ export function compactionModelPort(purposes) {
12
+ return {
13
+ async target(orgId) {
14
+ try {
15
+ return await purposes.resolve(orgId, "compaction");
16
+ }
17
+ catch (err) {
18
+ if (err instanceof ApiError && err.code === "model.unconfigured")
19
+ return null;
20
+ throw err;
21
+ }
22
+ },
23
+ };
24
+ }
25
+ /**
26
+ * §4.2 / §4.3: C when mapped, resolvable and eligible; else V with the reason (logged at `warn` for
27
+ * unavailable, `debug` for small, not at all for unconfigured; `context=Compaction`). Never throws
28
+ * for C's resolution or size; an error of the port other than unconfigured (a failed PG read)
29
+ * propagates, and `prepareCompaction` ends the compaction as unavailable (never on V).
30
+ *
31
+ * The cap is `min(setting, V max)` on V (today's) and `min(setting, C max, V max)` on C: a
32
+ * large-output summarizer never writes a longer summary than V would (§5.1). Eligibility is
33
+ * judged with C's cap and window against the settings' reserve.
34
+ */
35
+ export async function chooseSummarizer(deps, orgId, conversation, settings) {
36
+ const onConversation = (fallback) => ({
37
+ summarizer: {
38
+ source: "conversation",
39
+ ref: conversation.ref,
40
+ provider: conversation.provider,
41
+ info: conversation.info,
42
+ params: {},
43
+ cap: compactionSummaryCap(settings.maxOutputTokens, conversation.info.maxOutputTokens),
44
+ },
45
+ fallback,
46
+ });
47
+ if (deps.compactionModel === undefined)
48
+ return onConversation("unconfigured");
49
+ const target = await deps.compactionModel.target(orgId);
50
+ if (target === null)
51
+ return onConversation("unconfigured");
52
+ let provider;
53
+ let info;
54
+ try {
55
+ ({ provider, info } = await deps.registry.resolve(orgId, target.model));
56
+ }
57
+ catch (err) {
58
+ deps.log.warn("compaction model unavailable; summarizing with the conversation model", {
59
+ context: "Compaction",
60
+ reason: "compaction_model_unavailable",
61
+ model: target.model,
62
+ err,
63
+ });
64
+ return onConversation("compaction_model_unavailable");
65
+ }
66
+ const cap = compactionSummaryCap(settings.maxOutputTokens, conversation.info.maxOutputTokens, info.maxOutputTokens);
67
+ if (!compactionModelEligible(info.contextWindow, cap, settings.reserveTokens)) {
68
+ deps.log.debug?.("compaction model window too small; summarizing with the conversation model", {
69
+ context: "Compaction",
70
+ reason: "compaction_model_small",
71
+ model: target.model,
72
+ contextWindow: info.contextWindow,
73
+ });
74
+ return onConversation("compaction_model_small");
75
+ }
76
+ return {
77
+ summarizer: {
78
+ source: "compaction_model",
79
+ ref: target.model,
80
+ provider,
81
+ info,
82
+ // undeclared or unfitting values are dropped, as `ModelPurposesService.chat` does (§4.5)
83
+ params: sanitizeParams(info.parameters, target.params).value,
84
+ cap,
85
+ },
86
+ };
87
+ }
@@ -1,6 +1,7 @@
1
1
  import type { ConversationSource } from "@capybara-hq/plugin-sdk";
2
2
  import type { AgentDefinition } from "../agents/definition.js";
3
3
  import { EventLog } from "../conversations/event-log.js";
4
+ import type { IdleMode } from "../db/kernel-schema.js";
4
5
  import { KernelConfigService } from "../infra/config/kernel-config.service.js";
5
6
  import { CompactionSettingsService } from "./compaction-settings.service.js";
6
7
  import { RunSteps } from "./run-steps.js";
@@ -31,6 +32,17 @@ export interface ForceCompactionInput {
31
32
  * the idle compaction job (`idle`).
32
33
  */
33
34
  export type CompactOrigin = "manual" | "idle";
35
+ /**
36
+ * How {@link CompactionService.force} compacts: a person's compact run, or the idle job's in the
37
+ * mode it was armed in (compaction model spec §6.3). The mode is part of the idle origin, so an
38
+ * idle run cannot be started without one (a run never switches modes between arm, fire and run).
39
+ */
40
+ export type CompactRunKind = {
41
+ origin: "manual";
42
+ } | {
43
+ origin: "idle";
44
+ idleMode: IdleMode;
45
+ };
34
46
  /** What {@link CompactionService.probeIdle} reads from the conversation. */
35
47
  export type IdleProbeInput = Omit<ForceCompactionInput, "runId" | "signal" | "accountId">;
36
48
  /**
@@ -63,10 +75,11 @@ export interface ForcedCompaction {
63
75
  * The run writes only its outcome, with `step: 0`: `compaction_summary` / `compaction_failed` +
64
76
  * the summary calls' `usage`, or `compaction_skipped` when there is nothing to summarize
65
77
  * (maintainer decision 2026-11-28); no user message and no model step.
66
- * - `idle` adds `requireInContext: true` and never `manual` (ruling R13): the automatic plan, the
67
- * in-context summary only. Every early end (nothing to summarize, an unavailable model, an
68
- * in-context skip) writes nothing; a failed call writes `compaction_failed` (the backoff of later
69
- * idle attempts).
78
+ * - `idle` adds `idle: mode` and never `manual` (ruling R13): the automatic plan; in `cache` mode
79
+ * the in-context summary only, in `compaction_model` mode the compaction model's transcript
80
+ * summary only (compaction model spec §6.3, never V). Every early end (nothing to summarize, an
81
+ * unavailable model, an in-context skip, no compaction model) writes nothing; a failed call
82
+ * writes `compaction_failed` (the backoff of later idle attempts).
70
83
  */
71
84
  export declare class CompactionService {
72
85
  private readonly steps;
@@ -74,13 +87,15 @@ export declare class CompactionService {
74
87
  private readonly config;
75
88
  private readonly settings;
76
89
  constructor(steps: RunSteps, eventLog: EventLog, config: KernelConfigService, settings: CompactionSettingsService);
77
- force(input: ForceCompactionInput, origin?: CompactOrigin): Promise<ForcedCompaction>;
90
+ force(input: ForceCompactionInput, kind: CompactRunKind): Promise<ForcedCompaction>;
78
91
  /**
79
92
  * The idle compaction job's dry run (idle compaction spec §4.3 checks 8 and 9): the preparation
80
- * an idle compact run would do, with nothing written and no model call. Null when the model or
81
- * the attachment storage cannot be reached right now (the probe learns nothing).
93
+ * an idle compact run would do in `mode`, with nothing written and no model call. Null when the
94
+ * model or the attachment storage cannot be reached right now (the probe learns nothing), and in
95
+ * `compaction_model` mode when the compaction model does not summarize now. In `cache` mode a
96
+ * compaction model mapped since arming reports `inContext: false` (spec issue C3).
82
97
  */
83
- probeIdle(input: IdleProbeInput): Promise<IdleProbe | null>;
98
+ probeIdle(input: IdleProbeInput, mode: IdleMode): Promise<IdleProbe | null>;
84
99
  /** The step environment a compact run (or its probe) prepares, as a model step has it. */
85
100
  private environment;
86
101
  }
@@ -28,10 +28,11 @@ const PROBE_RUN_ID = "00000000-0000-0000-0000-000000000000";
28
28
  * The run writes only its outcome, with `step: 0`: `compaction_summary` / `compaction_failed` +
29
29
  * the summary calls' `usage`, or `compaction_skipped` when there is nothing to summarize
30
30
  * (maintainer decision 2026-11-28); no user message and no model step.
31
- * - `idle` adds `requireInContext: true` and never `manual` (ruling R13): the automatic plan, the
32
- * in-context summary only. Every early end (nothing to summarize, an unavailable model, an
33
- * in-context skip) writes nothing; a failed call writes `compaction_failed` (the backoff of later
34
- * idle attempts).
31
+ * - `idle` adds `idle: mode` and never `manual` (ruling R13): the automatic plan; in `cache` mode
32
+ * the in-context summary only, in `compaction_model` mode the compaction model's transcript
33
+ * summary only (compaction model spec §6.3, never V). Every early end (nothing to summarize, an
34
+ * unavailable model, an in-context skip, no compaction model) writes nothing; a failed call
35
+ * writes `compaction_failed` (the backoff of later idle attempts).
35
36
  */
36
37
  let CompactionService = class CompactionService {
37
38
  steps;
@@ -44,25 +45,29 @@ let CompactionService = class CompactionService {
44
45
  this.config = config;
45
46
  this.settings = settings;
46
47
  }
47
- async force(input, origin = "manual") {
48
+ async force(input, kind) {
48
49
  const env = await this.environment(input);
49
- const opts = origin === "manual" ? { force: true, manual: true } : { force: true, requireInContext: true };
50
+ const opts = kind.origin === "manual"
51
+ ? { force: true, manual: true }
52
+ : { force: true, idle: kind.idleMode };
50
53
  const out = await runCompaction(this.steps.deps, env.stepInput, env.events, this.config.get().runtime, env.compaction, env.tools, opts);
51
54
  return { summarySeq: out.summarySeq, failed: out.failed };
52
55
  }
53
56
  /**
54
57
  * The idle compaction job's dry run (idle compaction spec §4.3 checks 8 and 9): the preparation
55
- * an idle compact run would do, with nothing written and no model call. Null when the model or
56
- * the attachment storage cannot be reached right now (the probe learns nothing).
58
+ * an idle compact run would do in `mode`, with nothing written and no model call. Null when the
59
+ * model or the attachment storage cannot be reached right now (the probe learns nothing), and in
60
+ * `compaction_model` mode when the compaction model does not summarize now. In `cache` mode a
61
+ * compaction model mapped since arming reports `inContext: false` (spec issue C3).
57
62
  */
58
- async probeIdle(input) {
63
+ async probeIdle(input, mode) {
59
64
  const env = await this.environment({
60
65
  ...input,
61
66
  runId: PROBE_RUN_ID,
62
67
  // the probe sends nothing: a signal that never aborts
63
68
  signal: new AbortController().signal,
64
69
  });
65
- const prepared = await prepareCompaction(this.steps.deps, env.stepInput, env.events, this.config.get().runtime, env.compaction, env.tools, { force: true, requireInContext: true });
70
+ const prepared = await prepareCompaction(this.steps.deps, env.stepInput, env.events, this.config.get().runtime, env.compaction, env.tools, { force: true, idle: mode });
66
71
  if ("skipped" in prepared) {
67
72
  if (prepared.skipped !== "no_plan")
68
73
  return null;
@@ -1,4 +1,4 @@
1
- import type { ModelRequest } from "@capybara-hq/plugin-sdk";
1
+ import type { ModelRequest, ParamValue } from "@capybara-hq/plugin-sdk";
2
2
  import type { ConversationEvent } from "../../conversations/events.js";
3
3
  import type { CompactionSettings } from "../../identity/settings.js";
4
4
  /**
@@ -47,6 +47,20 @@ export declare function compactionChunkSize(budget: number, maxOutputTokens: num
47
47
  * transcript.
48
48
  */
49
49
  export declare const MIN_COMPACTION_CHUNK_TOKENS = 256;
50
+ /**
51
+ * A compaction model is eligible only if one summary chunk of it holds at least this many tokens
52
+ * (compaction model spec §4.3): a smaller chunk would split a long transcript into many calls.
53
+ */
54
+ export declare const MIN_COMPACTION_MODEL_CHUNK_TOKENS = 32000;
55
+ /**
56
+ * `Cmax` (compaction model spec §5.1): the summary cap is the setting bounded by the conversation
57
+ * model's output limit and, when a compaction model summarizes, by its output limit too. Omitting
58
+ * `summarizerMax` gives the cap of the conversation model alone; a large-output summarizer never
59
+ * raises it.
60
+ */
61
+ export declare function compactionSummaryCap(setting: number, conversationMax: number, summarizerMax?: number): number;
62
+ /** Compaction model spec §4.3: one chunk of the model's input budget reaches the floor. */
63
+ export declare function compactionModelEligible(window: number, cap: number, reserve: number): boolean;
50
64
  /**
51
65
  * Compaction trigger (context compaction spec §4.1): the calibrated estimate reaches the lower of
52
66
  * `threshold × window` and the input target `W - O_p - R_p` (the planning bounds,
@@ -148,10 +162,13 @@ export declare function chunkTranscript(transcript: string, chunkSize: number):
148
162
  * which the caller narrows to the model's own cap (context compaction spec §4.8); omitted, it is
149
163
  * the built-in default. `retry` is the one retry after a call stopped at the output token limit:
150
164
  * the same request with {@link compactionRetryNote} after the transcript (the cut-off answer is not
151
- * sent back, so the request stays inside the same input budget).
165
+ * sent back, so the request stays inside the same input budget). `params` are the summarizer's
166
+ * request parameters: a compaction model's mapping, sanitized against its declarations (compaction
167
+ * model spec §4.5); the conversation model summarizes with none (`{}`, the default).
152
168
  */
153
169
  export declare function buildCompactionRequest(transcript: string, model: string, maxOutputTokens?: number, opts?: {
154
170
  retry?: boolean;
171
+ params?: Record<string, ParamValue>;
155
172
  }): ModelRequest;
156
173
  /**
157
174
  * What a compaction saved (context compaction spec §4.9): the estimated transcript input minus the
@@ -134,6 +134,25 @@ export function compactionChunkSize(budget, maxOutputTokens) {
134
134
  * transcript.
135
135
  */
136
136
  export const MIN_COMPACTION_CHUNK_TOKENS = 256;
137
+ /**
138
+ * A compaction model is eligible only if one summary chunk of it holds at least this many tokens
139
+ * (compaction model spec §4.3): a smaller chunk would split a long transcript into many calls.
140
+ */
141
+ export const MIN_COMPACTION_MODEL_CHUNK_TOKENS = 32_000;
142
+ /**
143
+ * `Cmax` (compaction model spec §5.1): the summary cap is the setting bounded by the conversation
144
+ * model's output limit and, when a compaction model summarizes, by its output limit too. Omitting
145
+ * `summarizerMax` gives the cap of the conversation model alone; a large-output summarizer never
146
+ * raises it.
147
+ */
148
+ export function compactionSummaryCap(setting, conversationMax, summarizerMax) {
149
+ return Math.min(setting, conversationMax, summarizerMax ?? Number.POSITIVE_INFINITY);
150
+ }
151
+ /** Compaction model spec §4.3: one chunk of the model's input budget reaches the floor. */
152
+ export function compactionModelEligible(window, cap, reserve) {
153
+ return (compactionChunkSize(compactionInputBudget(window, cap, reserve), cap) >=
154
+ MIN_COMPACTION_MODEL_CHUNK_TOKENS);
155
+ }
137
156
  /**
138
157
  * Compaction trigger (context compaction spec §4.1): the calibrated estimate reaches the lower of
139
158
  * `threshold × window` and the input target `W - O_p - R_p` (the planning bounds,
@@ -693,7 +712,9 @@ function splitLine(line, max) {
693
712
  * which the caller narrows to the model's own cap (context compaction spec §4.8); omitted, it is
694
713
  * the built-in default. `retry` is the one retry after a call stopped at the output token limit:
695
714
  * the same request with {@link compactionRetryNote} after the transcript (the cut-off answer is not
696
- * sent back, so the request stays inside the same input budget).
715
+ * sent back, so the request stays inside the same input budget). `params` are the summarizer's
716
+ * request parameters: a compaction model's mapping, sanitized against its declarations (compaction
717
+ * model spec §4.5); the conversation model summarizes with none (`{}`, the default).
697
718
  */
698
719
  export function buildCompactionRequest(transcript, model, maxOutputTokens = COMPACTION_MAX_OUTPUT_TOKENS, opts = {}) {
699
720
  return {
@@ -712,7 +733,7 @@ export function buildCompactionRequest(transcript, model, maxOutputTokens = COMP
712
733
  ],
713
734
  tools: [],
714
735
  maxOutputTokens,
715
- params: {},
736
+ params: opts.params ?? {},
716
737
  purpose: "compaction",
717
738
  };
718
739
  }
@@ -1,6 +1,8 @@
1
1
  import type { ConversationEvent } from "../../conversations/events.js";
2
+ import type { IdleMode } from "../../db/kernel-schema.js";
2
3
  import type { CompactionSettings } from "../../identity/settings.js";
3
4
  import { type CacheExpiry } from "./cache-expiry.js";
5
+ export type { IdleMode };
4
6
  /** Idle compaction only beats the expiry of a cache that lives at least this long, in seconds. */
5
7
  export declare const IDLE_MIN_CACHE_TTL = 1800;
6
8
  /** The next request must have grown at least this much over the summarized part, in tokens. */
@@ -26,6 +28,10 @@ export interface IdleArmFacts {
26
28
  outcome: "completed" | "max_steps" | "max_duration" | "budget" | "max_output";
27
29
  /** Effective for the org. */
28
30
  settings: CompactionSettings;
31
+ /** How the job would compact: in the armed cache, or on the compaction model. */
32
+ mode: IdleMode;
33
+ /** The arm time in epoch ms (a compaction-model job fires `idleDelayMinutes` later). */
34
+ now: number;
29
35
  /** `accounts.idle_compaction = 'off'` of the owner. */
30
36
  personalOff: boolean;
31
37
  /** `deriveCacheExpiry` over the run's calls (S6). */
@@ -52,9 +58,14 @@ export interface IdleArmFacts {
52
58
  /** Whether a finished run owes an idle compaction job, and when it should fire. */
53
59
  export declare function idleArmDecision(f: IdleArmFacts): {
54
60
  arm: true;
61
+ mode: "cache";
55
62
  runAt: number;
56
63
  expiresAt: number;
57
64
  cacheCallSeq: number;
65
+ } | {
66
+ arm: true;
67
+ mode: "compaction_model";
68
+ runAt: number;
58
69
  } | {
59
70
  arm: false;
60
71
  reason: IdleArmSkip;
@@ -73,8 +84,12 @@ export interface IdleFireFacts {
73
84
  expiresAt: number;
74
85
  /** The latest compaction record after the latest summary is `compaction_failed`. */
75
86
  backoff: boolean;
76
- /** The effective definition's model resolves, is enabled and equals the armed call's. */
77
- sameModel: boolean;
87
+ mode: IdleMode;
88
+ /**
89
+ * cache: the effective model resolves and equals the armed call's; compaction_model: it resolves
90
+ * and the compaction model is the summarizer for it.
91
+ */
92
+ modelReady: boolean;
78
93
  probe: {
79
94
  estimate: number;
80
95
  window: number;