@capybara-hq/kernel 0.1.0-rc.113 → 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 (96) hide show
  1. package/bootstrap.json +7 -7
  2. package/dist/admin/admin.schemas.d.ts +1 -0
  3. package/dist/catalog/marketplaces.service.d.ts +1 -1
  4. package/dist/channels/actions.js +2 -0
  5. package/dist/channels/cards.d.ts +4 -3
  6. package/dist/channels/cards.js +18 -3
  7. package/dist/channels/phrases.d.ts +15 -0
  8. package/dist/channels/phrases.js +9 -0
  9. package/dist/conversations/conversations.service.js +7 -0
  10. package/dist/conversations/events.d.ts +21 -0
  11. package/dist/conversations/events.js +35 -3
  12. package/dist/ctx/create-ctx.d.ts +1 -1
  13. package/dist/ctx/create-ctx.js +6 -1
  14. package/dist/db/kernel-schema.d.ts +29 -0
  15. package/dist/device-access/device-access.service.d.ts +74 -3
  16. package/dist/device-access/device-access.service.js +221 -7
  17. package/dist/devices/devices.service.js +3 -0
  18. package/dist/errors.d.ts +6 -0
  19. package/dist/errors.js +6 -0
  20. package/dist/extensions/permission-set.d.ts +11 -1
  21. package/dist/extensions/permission-set.js +15 -1
  22. package/dist/extensions/permission-view.d.ts +3 -2
  23. package/dist/extensions/permission-view.js +15 -2
  24. package/dist/identity/settings.d.ts +5 -0
  25. package/dist/identity/settings.js +4 -0
  26. package/dist/infra/outbox/registry.d.ts +14 -0
  27. package/dist/infra/outbox/registry.js +14 -0
  28. package/dist/models/purposes.js +5 -0
  29. package/dist/orgs/offboarding.js +5 -1
  30. package/dist/orgs/settings.service.d.ts +2 -0
  31. package/dist/platform/ops/org-settings.ops.js +1 -1
  32. package/dist/roles/worker.module.js +3 -0
  33. package/dist/runtime/compaction-model.d.ts +57 -0
  34. package/dist/runtime/compaction-model.js +87 -0
  35. package/dist/runtime/compaction.service.d.ts +23 -8
  36. package/dist/runtime/compaction.service.js +15 -10
  37. package/dist/runtime/context/compaction.d.ts +19 -2
  38. package/dist/runtime/context/compaction.js +23 -2
  39. package/dist/runtime/context/idle-compaction-rules.d.ts +17 -2
  40. package/dist/runtime/context/idle-compaction-rules.js +20 -5
  41. package/dist/runtime/idle-arm.d.ts +12 -2
  42. package/dist/runtime/idle-arm.js +66 -18
  43. package/dist/runtime/idle-compaction-jobs.d.ts +24 -3
  44. package/dist/runtime/idle-compaction.d.ts +11 -3
  45. package/dist/runtime/idle-compaction.js +61 -30
  46. package/dist/runtime/maintenance.d.ts +4 -2
  47. package/dist/runtime/maintenance.js +14 -4
  48. package/dist/runtime/model-call.d.ts +52 -16
  49. package/dist/runtime/model-call.js +71 -24
  50. package/dist/runtime/run-finish.d.ts +12 -3
  51. package/dist/runtime/run-finish.js +14 -7
  52. package/dist/runtime/run-queue.d.ts +5 -2
  53. package/dist/runtime/run-queue.js +7 -4
  54. package/dist/runtime/run-steps.d.ts +4 -1
  55. package/dist/runtime/run-steps.js +9 -2
  56. package/dist/runtime/run-worker.js +4 -2
  57. package/dist/runtime/runtime.module.js +3 -0
  58. package/dist/sandbox/device-sandbox.d.ts +12 -0
  59. package/dist/sandbox/device-sandbox.js +2 -0
  60. package/dist/sandbox/device-services.d.ts +42 -2
  61. package/dist/sandbox/device-services.js +74 -14
  62. package/dist/sandbox/loopback-expiry.job.d.ts +21 -0
  63. package/dist/sandbox/loopback-expiry.job.js +50 -0
  64. package/dist/sandbox/loopback-grant-records.d.ts +143 -0
  65. package/dist/sandbox/loopback-grant-records.js +239 -0
  66. package/dist/sandbox/loopback-grants.d.ts +119 -0
  67. package/dist/sandbox/loopback-grants.js +454 -0
  68. package/dist/sandbox/loopback-live-ports.d.ts +12 -0
  69. package/dist/sandbox/loopback-live-ports.js +43 -0
  70. package/dist/sandbox/permission-call-types.d.ts +3 -2
  71. package/dist/sandbox/permission-ceiling-writes.js +13 -1
  72. package/dist/sandbox/permission-facts.d.ts +4 -0
  73. package/dist/sandbox/permission-facts.js +4 -0
  74. package/dist/sandbox/review/classifier.d.ts +26 -4
  75. package/dist/sandbox/review/classifier.js +31 -4
  76. package/dist/sandbox/review/index.d.ts +3 -3
  77. package/dist/sandbox/review/index.js +2 -2
  78. package/dist/sandbox/review/permission-candidate.d.ts +5 -4
  79. package/dist/sandbox/review/permission-candidate.js +6 -5
  80. package/dist/sandbox/review/review.service.d.ts +69 -0
  81. package/dist/sandbox/review/review.service.js +117 -0
  82. package/dist/sandbox/sandbox.module.d.ts +1 -1
  83. package/dist/sandbox/sandbox.module.js +13 -2
  84. package/dist/tools/approvals.service.d.ts +82 -6
  85. package/dist/tools/approvals.service.js +233 -11
  86. package/dist/tools/call-scope.d.ts +9 -1
  87. package/dist/tools/loopback-asks.d.ts +52 -0
  88. package/dist/tools/loopback-asks.js +70 -0
  89. package/dist/tools/network-asks.d.ts +2 -1
  90. package/dist/tools/network-asks.js +10 -5
  91. package/dist/tools/pipeline.d.ts +59 -3
  92. package/dist/tools/pipeline.js +403 -40
  93. package/dist/tools/tools.module.js +3 -0
  94. package/package.json +2 -2
  95. package/src/migrations/0199_device_loopback_grants.sql +59 -0
  96. package/src/migrations/0200_runs_idle_mode.sql +4 -0
@@ -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
  }),
@@ -50,6 +50,7 @@ import { RuntimeWorkersModule } from "../runtime/run-processors.js";
50
50
  import { RuntimeModule } from "../runtime/runtime.module.js";
51
51
  import { UsageReportModule } from "../runtime/usage-report.js";
52
52
  import { SandboxSweepJobs } from "../sandbox/jobs.js";
53
+ import { LoopbackExpiryJob } from "../sandbox/loopback-expiry.job.js";
53
54
  import { SandboxModule } from "../sandbox/sandbox.module.js";
54
55
  import { ShareObjectsModule } from "../shares/share-objects.js";
55
56
  import { ShareSweepJob } from "../shares/sweep.job.js";
@@ -138,6 +139,8 @@ let WorkerModule = WorkerModule_1 = class WorkerModule {
138
139
  BackgroundTaskPollJob,
139
140
  // owed conversation notices to devices' services (close tabs on delete design §4.3)
140
141
  ConversationNoticeSweepJob,
142
+ // loopback port grants past their 24 hours (browser loopback port grants design §4)
143
+ LoopbackExpiryJob,
141
144
  // legacy retirement (permission runtime cutover 8.5): bounded, retryable; the sandbox
142
145
  // service's inline gate holds without it
143
146
  RetireLegacyTasksJob,
@@ -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;
@@ -34,21 +34,36 @@ export function idleArmDecision(f) {
34
34
  return { arm: false, reason: "disabled" };
35
35
  if (f.personalOff)
36
36
  return { arm: false, reason: "personal_off" };
37
- if (f.expiry === null || f.lastCall === null)
37
+ const cache = f.mode === "cache";
38
+ if (cache && (f.expiry === null || f.lastCall === null)) {
38
39
  return { arm: false, reason: "no_cache" };
39
- if (f.expiry.ttl < IDLE_MIN_CACHE_TTL)
40
+ }
41
+ if (cache && f.expiry !== null && f.expiry.ttl < IDLE_MIN_CACHE_TTL) {
40
42
  return { arm: false, reason: "short_ttl" };
43
+ }
41
44
  const c = f.lastCall;
45
+ if (c === null)
46
+ return { arm: false, reason: "small" };
42
47
  if (c.input + c.cacheRead + c.cacheWrite + c.output < idleMinTokens(c.window, f.settings)) {
43
48
  return { arm: false, reason: "small" };
44
49
  }
50
+ if (!cache) {
51
+ return {
52
+ arm: true,
53
+ mode: "compaction_model",
54
+ runAt: f.now + f.settings.idleDelayMinutes * 60_000,
55
+ };
56
+ }
45
57
  if (!f.inContextAllowed)
46
58
  return { arm: false, reason: "quality_gate" };
47
59
  if (f.fitPlan)
48
60
  return { arm: false, reason: "fit_plan" };
49
61
  if (!f.settled)
50
62
  return { arm: false, reason: "unsettled" };
63
+ if (f.expiry === null)
64
+ return { arm: false, reason: "no_cache" };
51
65
  return {
66
+ mode: "cache",
52
67
  arm: true,
53
68
  runAt: f.expiry.fireAt,
54
69
  expiresAt: f.expiry.expiresAt,
@@ -65,11 +80,11 @@ export function idleFireDecision(f) {
65
80
  return { fire: false, outcome: "busy" };
66
81
  if (!f.enabled)
67
82
  return { fire: false, outcome: "disabled" };
68
- if (f.now >= f.expiresAt - CACHE_EXPIRY_MARGIN_MS)
83
+ if (f.mode === "cache" && f.now >= f.expiresAt - CACHE_EXPIRY_MARGIN_MS)
69
84
  return { fire: false, outcome: "expired" };
70
85
  if (f.backoff)
71
86
  return { fire: false, outcome: "backoff" };
72
- if (!f.sameModel)
87
+ if (!f.modelReady)
73
88
  return { fire: false, outcome: "no_model" };
74
89
  const p = f.probe;
75
90
  if (p === null ||
@@ -78,7 +93,7 @@ export function idleFireDecision(f) {
78
93
  p.growth < IDLE_MIN_GROWTH_TOKENS) {
79
94
  return { fire: false, outcome: "small" };
80
95
  }
81
- if (!f.inContext)
96
+ if (f.mode === "cache" && !f.inContext)
82
97
  return { fire: false, outcome: "no_prefix" };
83
98
  return { fire: true };
84
99
  }
@@ -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
  }