@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
@@ -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>;
@@ -80,6 +80,11 @@ export const PLATFORM_EXCLUSIONS = [
80
80
  category: "transport",
81
81
  reason: "Streams avatar image bytes",
82
82
  },
83
+ {
84
+ route: "GET /api/v1/orgs/:orgId/agents/:agentId/mentionable-connectors",
85
+ category: "internal",
86
+ reason: "Feeds the @ connector menu of the web input box; no operation gives it, an agent already has its connectors' tools",
87
+ },
83
88
  {
84
89
  route: "POST /api/v1/orgs/:orgId/agents/:agentId/owner",
85
90
  category: "human-only",
@@ -672,7 +677,7 @@ export const PLATFORM_EXCLUSIONS = [
672
677
  {
673
678
  route: "GET /api/v1/orgs/:orgId/connectors/resources",
674
679
  category: "internal",
675
- reason: "Feeds the @ reference picker of the web input box; no operation gives it, an agent reads connector resources through its connector tools",
680
+ reason: "Feeds the @ picker of the web input box, whose second level lists one connector's readable resources (`connectorId`); no operation gives it, an agent reads connector resources through its connector tools",
676
681
  },
677
682
  {
678
683
  route: "POST /api/v1/orgs/:orgId/connectors/:connectorId/prompts/:name",
@@ -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;
@@ -411,8 +411,13 @@ export declare function buildModelRequest(input: BuildModelRequestInput): {
411
411
  mediaTokens: number;
412
412
  };
413
413
  /**
414
- * 日志里 `ToolSearch` 加载过的工具 key(全部 `tool_result.loadedTools` 的并集,按首次出现顺序)。
415
- * 不看压缩摘要的边界:加载过的工具在摘要之后仍保持加载(模型可能凭摘要继续使用它们,且已发送的工具列表只追加)。
414
+ * The tool keys loaded in the log under tool search, in order of first appearance by seq: the union
415
+ * of every `tool_result.loadedTools` (what `ToolSearch` loaded) and every
416
+ * `user_message.payload.connectorMentions[].loadedTools` (a mentioned connector's offered tools,
417
+ * composer inline tokens spec §3.5). Read only when the step runs with tool search; a key the step
418
+ * does not offer is ignored by the caller. The compaction boundary is not looked at: loaded tools
419
+ * stay loaded after a summary (the model may keep using them from the summary, and the tool list
420
+ * sent is append-only).
416
421
  */
417
422
  export declare function loadedToolKeys(events: readonly ConversationEvent[]): string[];
418
423
  /** system 各块文本的 sha256(hex);按 JSON 数组哈希,避免块边界歧义。 */
@@ -1176,16 +1176,27 @@ export function buildModelRequest(input) {
1176
1176
  return { request, meta, mediaTokens };
1177
1177
  }
1178
1178
  /**
1179
- * 日志里 `ToolSearch` 加载过的工具 key(全部 `tool_result.loadedTools` 的并集,按首次出现顺序)。
1180
- * 不看压缩摘要的边界:加载过的工具在摘要之后仍保持加载(模型可能凭摘要继续使用它们,且已发送的工具列表只追加)。
1179
+ * The tool keys loaded in the log under tool search, in order of first appearance by seq: the union
1180
+ * of every `tool_result.loadedTools` (what `ToolSearch` loaded) and every
1181
+ * `user_message.payload.connectorMentions[].loadedTools` (a mentioned connector's offered tools,
1182
+ * composer inline tokens spec §3.5). Read only when the step runs with tool search; a key the step
1183
+ * does not offer is ignored by the caller. The compaction boundary is not looked at: loaded tools
1184
+ * stay loaded after a summary (the model may keep using them from the summary, and the tool list
1185
+ * sent is append-only).
1181
1186
  */
1182
1187
  export function loadedToolKeys(events) {
1183
1188
  const out = new Set();
1184
1189
  for (const e of [...events].sort((a, b) => a.seq - b.seq)) {
1185
- if (e.type !== "tool_result")
1186
- continue;
1187
- for (const k of e.payload.loadedTools ?? [])
1188
- out.add(k);
1190
+ if (e.type === "tool_result") {
1191
+ for (const k of e.payload.loadedTools ?? [])
1192
+ out.add(k);
1193
+ }
1194
+ else if (e.type === "user_message") {
1195
+ for (const m of e.payload.connectorMentions ?? []) {
1196
+ for (const k of m.loadedTools)
1197
+ out.add(k);
1198
+ }
1199
+ }
1189
1200
  }
1190
1201
  return [...out];
1191
1202
  }
@@ -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,
@@ -110,9 +124,9 @@ export declare function openingSeqs(events: readonly ConversationEvent[], runId:
110
124
  /**
111
125
  * The opening messages a manual compaction's summary re-renders (context compaction spec §4.7,
112
126
  * maintainer decision 2026-11-28): a compact run is started by no message, so its own run has none;
113
- * the turn it cuts into is the one the latest run a message started (trigger `message` or
114
- * `schedule`) opened, and {@link openingSeqs} of that run decides which of its opening messages the
115
- * summary covers. None when no such run is in the log.
127
+ * the turn it cuts into is the one the latest run a message started (trigger `message`,
128
+ * `schedule` or `automation_event`) opened, and {@link openingSeqs} of that run decides which of
129
+ * its opening messages the summary covers. None when no such run is in the log.
116
130
  */
117
131
  export declare function manualOpeningSeqs(events: readonly ConversationEvent[], coversUpToSeq: number, absorbedUpToSeq: number): number[];
118
132
  /**
@@ -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,
@@ -265,6 +284,13 @@ export function compactionPlan(events, settings, budget, opts = {}) {
265
284
  const parts = prev ? [`[Earlier summary]\n${prev.payload.text}`, ...lines] : lines;
266
285
  return { coversUpToSeq, transcript: parts.join("\n\n") };
267
286
  }
287
+ /** Whether a `run_started.trigger` belongs to a run opened by a user/automation message. */
288
+ function isMessageRunTrigger(trigger) {
289
+ return (trigger === undefined ||
290
+ trigger === "message" ||
291
+ trigger === "schedule" ||
292
+ trigger === "automation_event");
293
+ }
268
294
  /**
269
295
  * The user messages that started run `runId`, among those a summary covering up to
270
296
  * `coversUpToSeq` covers (context compaction spec §4.2, revision 2026-11-15): recorded in the
@@ -282,13 +308,8 @@ export function openingSeqs(events, runId, coversUpToSeq, absorbedUpToSeq = Numb
282
308
  const start = sorted.findLast((e) => e.type === "run_started" && e.runId === runId);
283
309
  if (start?.type !== "run_started")
284
310
  return [];
285
- const trigger = start.payload.trigger;
286
- if (trigger !== undefined &&
287
- trigger !== "message" &&
288
- trigger !== "schedule" &&
289
- trigger !== "automation_event") {
311
+ if (!isMessageRunTrigger(start.payload.trigger))
290
312
  return [];
291
- }
292
313
  const first = sorted.find((e) => e.type === "model_call" && e.runId === runId && e.seq > start.seq);
293
314
  const upTo = first?.type === "model_call"
294
315
  ? Math.min(first.payload.request.absorbedUpToSeq, first.seq)
@@ -310,16 +331,13 @@ export function openingSeqs(events, runId, coversUpToSeq, absorbedUpToSeq = Numb
310
331
  /**
311
332
  * The opening messages a manual compaction's summary re-renders (context compaction spec §4.7,
312
333
  * maintainer decision 2026-11-28): a compact run is started by no message, so its own run has none;
313
- * the turn it cuts into is the one the latest run a message started (trigger `message` or
314
- * `schedule`) opened, and {@link openingSeqs} of that run decides which of its opening messages the
315
- * summary covers. None when no such run is in the log.
334
+ * the turn it cuts into is the one the latest run a message started (trigger `message`,
335
+ * `schedule` or `automation_event`) opened, and {@link openingSeqs} of that run decides which of
336
+ * its opening messages the summary covers. None when no such run is in the log.
316
337
  */
317
338
  export function manualOpeningSeqs(events, coversUpToSeq, absorbedUpToSeq) {
318
339
  const start = events
319
- .filter((e) => e.type === "run_started" &&
320
- (e.payload.trigger === undefined ||
321
- e.payload.trigger === "message" ||
322
- e.payload.trigger === "schedule"))
340
+ .filter((e) => e.type === "run_started" && isMessageRunTrigger(e.payload.trigger))
323
341
  .reduce((a, e) => (a === null || e.seq > a.seq ? e : a), null);
324
342
  if (start?.runId == null)
325
343
  return [];
@@ -693,7 +711,9 @@ function splitLine(line, max) {
693
711
  * which the caller narrows to the model's own cap (context compaction spec §4.8); omitted, it is
694
712
  * the built-in default. `retry` is the one retry after a call stopped at the output token limit:
695
713
  * 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).
714
+ * sent back, so the request stays inside the same input budget). `params` are the summarizer's
715
+ * request parameters: a compaction model's mapping, sanitized against its declarations (compaction
716
+ * model spec §4.5); the conversation model summarizes with none (`{}`, the default).
697
717
  */
698
718
  export function buildCompactionRequest(transcript, model, maxOutputTokens = COMPACTION_MAX_OUTPUT_TOKENS, opts = {}) {
699
719
  return {
@@ -712,7 +732,7 @@ export function buildCompactionRequest(transcript, model, maxOutputTokens = COMP
712
732
  ],
713
733
  tools: [],
714
734
  maxOutputTokens,
715
- params: {},
735
+ params: opts.params ?? {},
716
736
  purpose: "compaction",
717
737
  };
718
738
  }
@@ -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
  }