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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/dist/admin/admin.schemas.d.ts +3 -0
  2. package/dist/background/wake-rules.js +2 -0
  3. package/dist/conversations/conversations.service.js +4 -2
  4. package/dist/conversations/event-log.js +11 -1
  5. package/dist/conversations/events.d.ts +5 -0
  6. package/dist/conversations/events.js +11 -2
  7. package/dist/conversations/prompt-suggestion-store.d.ts +3 -1
  8. package/dist/conversations/prompt-suggestion-store.js +5 -1
  9. package/dist/db/kernel-schema.d.ts +7 -0
  10. package/dist/identity/accounts.d.ts +8 -9
  11. package/dist/identity/accounts.js +18 -3
  12. package/dist/identity/me.controller.d.ts +4 -2
  13. package/dist/identity/me.controller.js +4 -2
  14. package/dist/identity/me.schemas.d.ts +3 -0
  15. package/dist/identity/me.schemas.js +5 -0
  16. package/dist/identity/settings.d.ts +15 -0
  17. package/dist/identity/settings.js +12 -0
  18. package/dist/infra/outbox/registry.d.ts +14 -0
  19. package/dist/infra/outbox/registry.js +14 -0
  20. package/dist/orgs/settings.service.d.ts +6 -0
  21. package/dist/platform/ops/org-settings.ops.js +1 -1
  22. package/dist/platform/ops/platform.ops.js +9 -3
  23. package/dist/push/recipients.js +4 -2
  24. package/dist/runtime/abort.d.ts +22 -3
  25. package/dist/runtime/abort.js +37 -17
  26. package/dist/runtime/compaction.service.d.ts +43 -12
  27. package/dist/runtime/compaction.service.js +60 -16
  28. package/dist/runtime/context/idle-compaction-rules.d.ts +94 -0
  29. package/dist/runtime/context/idle-compaction-rules.js +84 -0
  30. package/dist/runtime/idle-arm.d.ts +38 -0
  31. package/dist/runtime/idle-arm.js +269 -0
  32. package/dist/runtime/idle-compaction-jobs.d.ts +25 -0
  33. package/dist/runtime/idle-compaction-jobs.js +21 -0
  34. package/dist/runtime/idle-compaction.d.ts +43 -0
  35. package/dist/runtime/idle-compaction.js +316 -0
  36. package/dist/runtime/idle-return.d.ts +62 -0
  37. package/dist/runtime/idle-return.js +170 -0
  38. package/dist/runtime/maintenance.d.ts +5 -2
  39. package/dist/runtime/maintenance.js +14 -4
  40. package/dist/runtime/model-call.d.ts +113 -5
  41. package/dist/runtime/model-call.js +119 -71
  42. package/dist/runtime/run-finish.d.ts +16 -1
  43. package/dist/runtime/run-finish.js +27 -4
  44. package/dist/runtime/run-queue.d.ts +56 -2
  45. package/dist/runtime/run-queue.js +257 -8
  46. package/dist/runtime/run-worker.d.ts +22 -8
  47. package/dist/runtime/run-worker.js +75 -28
  48. package/dist/runtime/runtime.module.js +11 -0
  49. package/dist/runtime/waits.js +1 -1
  50. package/package.json +1 -1
  51. package/src/migrations/0195_idle_compaction.sql +7 -0
@@ -15,13 +15,14 @@ export const RUN_ABORT_TOPIC = "run.abort";
15
15
  const ABORT_TTL_SECONDS = 3600;
16
16
  const abortKey = (runId) => `capk:run-abort:${runId}`;
17
17
  const detailOf = (v) => v === "wait_timeout" ? { detail: v } : {};
18
- const parseStored = (stored) => {
19
- const m = JSON.parse(stored);
20
- return {
21
- byAccountId: typeof m.byAccountId === "string" ? m.byAccountId : null,
22
- ...detailOf(m.detail),
23
- };
24
- };
18
+ const reasonOf = (v) => v === "superseded" ? { reason: v } : {};
19
+ /** A stored marker or a bus message, read defensively (either may come from another version). */
20
+ const parseBy = (m) => ({
21
+ byAccountId: typeof m.byAccountId === "string" ? m.byAccountId : null,
22
+ ...detailOf(m.detail),
23
+ ...reasonOf(m.reason),
24
+ });
25
+ const parseStored = (stored) => parseBy(JSON.parse(stored));
25
26
  /**
26
27
  * 跨副本中止(spec 4.3「中止信号经 Redis 广播」):`request` 先写标记键再广播;
27
28
  * `watch` 先订阅、再检查一次标记键,订阅之前发出的中止也不会丢。
@@ -33,15 +34,38 @@ let RunAbort = class RunAbort {
33
34
  this.redis = redis;
34
35
  this.bus = bus;
35
36
  }
36
- async request(runId, byAccountId, detail) {
37
- const by = { byAccountId, ...(detail !== undefined && { detail }) };
37
+ async request(runId, byAccountId, opts = {}) {
38
+ const by = {
39
+ byAccountId,
40
+ ...(opts.detail !== undefined && { detail: opts.detail }),
41
+ ...(opts.reason !== undefined && { reason: opts.reason }),
42
+ };
38
43
  await this.redis.set(abortKey(runId), JSON.stringify(by), "EX", ABORT_TTL_SECONDS);
39
44
  const msg = { runId, ...by };
40
45
  await this.bus.publish(RUN_ABORT_TOPIC, msg);
41
46
  }
47
+ /**
48
+ * Requests the kernel's stop of a run only when no stop was requested yet: the marker is written
49
+ * with SET NX (atomic, so a person's stop racing it is never relabelled) and broadcast only when
50
+ * this call wrote it. True when it did. A plain {@link request} still overwrites the marker, so a
51
+ * person's later stop replaces a kernel one.
52
+ */
53
+ async requestIfAbsent(runId, byAccountId, opts = {}) {
54
+ const by = {
55
+ byAccountId,
56
+ ...(opts.detail !== undefined && { detail: opts.detail }),
57
+ ...(opts.reason !== undefined && { reason: opts.reason }),
58
+ };
59
+ const set = await this.redis.set(abortKey(runId), JSON.stringify(by), "EX", ABORT_TTL_SECONDS, "NX");
60
+ if (set === null)
61
+ return false;
62
+ const msg = { runId, ...by };
63
+ await this.bus.publish(RUN_ABORT_TOPIC, msg);
64
+ return true;
65
+ }
42
66
  /**
43
67
  * Whether a stop of this run was requested (reads the marker key): who asked (and why, when the
44
- * kernel did), or null. For the moments without a subscriber (a run that just suspended and is
68
+ * kernel did: `detail`, `reason`), or null. For the moments without a subscriber (a run that just suspended and is
45
69
  * about to become `waiting`), to pick up a stop that arrived meanwhile.
46
70
  */
47
71
  async requested(runId) {
@@ -57,16 +81,12 @@ let RunAbort = class RunAbort {
57
81
  if (fired)
58
82
  return;
59
83
  fired = true;
60
- onAbort(by.byAccountId, by.detail);
84
+ onAbort(by.byAccountId, by.detail, by.reason);
61
85
  };
62
86
  const unsubscribe = await this.bus.subscribe(RUN_ABORT_TOPIC, (payload) => {
63
87
  const m = payload;
64
- if (m?.runId === runId) {
65
- fire({
66
- byAccountId: typeof m.byAccountId === "string" ? m.byAccountId : null,
67
- ...detailOf(m.detail),
68
- });
69
- }
88
+ if (m?.runId === runId)
89
+ fire(parseBy(m));
70
90
  });
71
91
  try {
72
92
  const stored = await this.redis.get(abortKey(runId));
@@ -26,24 +26,47 @@ export interface ForceCompactionInput {
26
26
  absorbedUpToSeq: number;
27
27
  signal: AbortSignal;
28
28
  }
29
+ /**
30
+ * Who started a compact run (idle compaction spec §5.1): a person (`manual`, the compact route) or
31
+ * the idle compaction job (`idle`).
32
+ */
33
+ export type CompactOrigin = "manual" | "idle";
34
+ /** What {@link CompactionService.probeIdle} reads from the conversation. */
35
+ export type IdleProbeInput = Omit<ForceCompactionInput, "runId" | "signal" | "accountId">;
36
+ /**
37
+ * The dry run of an idle compaction (idle compaction spec §4.3 checks 8 and 9): the calibrated
38
+ * estimate of the next request, the model's window, the tokens no summary covers yet (`growth`),
39
+ * whether a plan exists, and whether the in-context summary request was built (no skip).
40
+ */
41
+ export interface IdleProbe {
42
+ estimate: number;
43
+ window: number;
44
+ growth: number;
45
+ planned: boolean;
46
+ inContext: boolean;
47
+ }
29
48
  /** What the compact run recorded: the `compaction_summary` it wrote, and whether it failed. */
30
49
  export interface ForcedCompaction {
31
50
  summarySeq: number | null;
32
51
  failed: boolean;
33
52
  }
34
53
  /**
35
- * The manual compaction a compact run executes (context compaction spec §4.7). It prepares the same
36
- * environment a model step has (the events, the effective definition's tools, the org's compaction
37
- * settings) and calls the shared {@link runCompaction} with `force: true`: the trigger,
38
- * `enabled: false` and the failure backoff are bypassed, the compaction plan is still required, with
39
- * the manual rule (`manual: true`: every turn before the latest summarized, about a fifth of the
40
- * window of the latest turn kept; maintainer decision 2026-11-28). A manual compaction always
41
- * summarizes the transcript with that plan, on a model the in-context gate lists too (ruling R13,
42
- * idle compaction spec §9.4).
54
+ * The compaction a compact run executes (context compaction spec §4.7, idle compaction spec §5). It
55
+ * prepares the same environment a model step has (the events, the effective definition's tools, the
56
+ * org's compaction settings) and calls the shared {@link runCompaction} with `force: true`: the
57
+ * trigger, `enabled: false` and the failure backoff are bypassed, the compaction plan is still
58
+ * required.
43
59
  *
44
- * The run writes only its outcome, with `step: 0`: `compaction_summary` / `compaction_failed` + the
45
- * summary calls' `usage`, or `compaction_skipped` when there is nothing to summarize (maintainer
46
- * decision 2026-11-28); no user message and no model step.
60
+ * - `manual` adds `manual: true`: the manual rule (every turn before the latest summarized, about a
61
+ * fifth of the window of the latest turn kept; maintainer decision 2026-11-28), always on the
62
+ * transcript, also on a model the in-context gate lists (ruling R13, idle compaction spec §9.4).
63
+ * The run writes only its outcome, with `step: 0`: `compaction_summary` / `compaction_failed` +
64
+ * the summary calls' `usage`, or `compaction_skipped` when there is nothing to summarize
65
+ * (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).
47
70
  */
48
71
  export declare class CompactionService {
49
72
  private readonly steps;
@@ -51,5 +74,13 @@ export declare class CompactionService {
51
74
  private readonly config;
52
75
  private readonly settings;
53
76
  constructor(steps: RunSteps, eventLog: EventLog, config: KernelConfigService, settings: CompactionSettingsService);
54
- force(input: ForceCompactionInput): Promise<ForcedCompaction>;
77
+ force(input: ForceCompactionInput, origin?: CompactOrigin): Promise<ForcedCompaction>;
78
+ /**
79
+ * 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).
82
+ */
83
+ probeIdle(input: IdleProbeInput): Promise<IdleProbe | null>;
84
+ /** The step environment a compact run (or its probe) prepares, as a model step has it. */
85
+ private environment;
55
86
  }
@@ -11,21 +11,27 @@ import { Inject, Injectable } from "@nestjs/common";
11
11
  import { EventLog } from "../conversations/event-log.js";
12
12
  import { KernelConfigService } from "../infra/config/kernel-config.service.js";
13
13
  import { CompactionSettingsService } from "./compaction-settings.service.js";
14
- import { readAllEvents, resolveAgentTools, runCompaction, stepToolsOf, } from "./model-call.js";
14
+ import { prepareCompaction, readAllEvents, resolveAgentTools, runCompaction, stepToolsOf, } from "./model-call.js";
15
15
  import { RunSteps } from "./run-steps.js";
16
+ /** The run id a probe's step input carries: never written (a probe writes nothing). */
17
+ const PROBE_RUN_ID = "00000000-0000-0000-0000-000000000000";
16
18
  /**
17
- * The manual compaction a compact run executes (context compaction spec §4.7). It prepares the same
18
- * environment a model step has (the events, the effective definition's tools, the org's compaction
19
- * settings) and calls the shared {@link runCompaction} with `force: true`: the trigger,
20
- * `enabled: false` and the failure backoff are bypassed, the compaction plan is still required, with
21
- * the manual rule (`manual: true`: every turn before the latest summarized, about a fifth of the
22
- * window of the latest turn kept; maintainer decision 2026-11-28). A manual compaction always
23
- * summarizes the transcript with that plan, on a model the in-context gate lists too (ruling R13,
24
- * idle compaction spec §9.4).
19
+ * The compaction a compact run executes (context compaction spec §4.7, idle compaction spec §5). It
20
+ * prepares the same environment a model step has (the events, the effective definition's tools, the
21
+ * org's compaction settings) and calls the shared {@link runCompaction} with `force: true`: the
22
+ * trigger, `enabled: false` and the failure backoff are bypassed, the compaction plan is still
23
+ * required.
25
24
  *
26
- * The run writes only its outcome, with `step: 0`: `compaction_summary` / `compaction_failed` + the
27
- * summary calls' `usage`, or `compaction_skipped` when there is nothing to summarize (maintainer
28
- * decision 2026-11-28); no user message and no model step.
25
+ * - `manual` adds `manual: true`: the manual rule (every turn before the latest summarized, about a
26
+ * fifth of the window of the latest turn kept; maintainer decision 2026-11-28), always on the
27
+ * transcript, also on a model the in-context gate lists (ruling R13, idle compaction spec §9.4).
28
+ * The run writes only its outcome, with `step: 0`: `compaction_summary` / `compaction_failed` +
29
+ * the summary calls' `usage`, or `compaction_skipped` when there is nothing to summarize
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).
29
35
  */
30
36
  let CompactionService = class CompactionService {
31
37
  steps;
@@ -38,7 +44,46 @@ let CompactionService = class CompactionService {
38
44
  this.config = config;
39
45
  this.settings = settings;
40
46
  }
41
- async force(input) {
47
+ async force(input, origin = "manual") {
48
+ const env = await this.environment(input);
49
+ const opts = origin === "manual" ? { force: true, manual: true } : { force: true, requireInContext: true };
50
+ const out = await runCompaction(this.steps.deps, env.stepInput, env.events, this.config.get().runtime, env.compaction, env.tools, opts);
51
+ return { summarySeq: out.summarySeq, failed: out.failed };
52
+ }
53
+ /**
54
+ * 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).
57
+ */
58
+ async probeIdle(input) {
59
+ const env = await this.environment({
60
+ ...input,
61
+ runId: PROBE_RUN_ID,
62
+ // the probe sends nothing: a signal that never aborts
63
+ signal: new AbortController().signal,
64
+ });
65
+ const prepared = await prepareCompaction(this.steps.deps, env.stepInput, env.events, this.config.get().runtime, env.compaction, env.tools, { force: true, requireInContext: true });
66
+ if ("skipped" in prepared) {
67
+ if (prepared.skipped !== "no_plan")
68
+ return null;
69
+ return {
70
+ estimate: prepared.estimate,
71
+ window: prepared.window,
72
+ growth: 0,
73
+ planned: false,
74
+ inContext: false,
75
+ };
76
+ }
77
+ return {
78
+ estimate: prepared.estimate,
79
+ window: prepared.window,
80
+ growth: prepared.growthTokens,
81
+ planned: true,
82
+ inContext: !("skip" in prepared.inContext),
83
+ };
84
+ }
85
+ /** The step environment a compact run (or its probe) prepares, as a model step has it. */
86
+ async environment(input) {
42
87
  // the run's steps environment (the model registry, the tool registry, media, hooks, progress);
43
88
  // no step state is kept on it, so a compact run may share it with the steps of other runs
44
89
  const deps = this.steps.deps;
@@ -56,7 +101,7 @@ let CompactionService = class CompactionService {
56
101
  sink: () => { },
57
102
  absorbedUpToSeq: input.absorbedUpToSeq,
58
103
  agentId: input.agentId,
59
- accountId: input.accountId,
104
+ ...(input.accountId !== undefined && { accountId: input.accountId }),
60
105
  source: input.source,
61
106
  conversationKind: input.conversationKind,
62
107
  };
@@ -64,8 +109,7 @@ let CompactionService = class CompactionService {
64
109
  // step's request would (spec §4.7)
65
110
  const tools = stepToolsOf(await resolveAgentTools(deps, stepInput, events), stepInput, deps);
66
111
  const compaction = await this.settings.resolve(input.orgId);
67
- const out = await runCompaction(deps, stepInput, events, this.config.get().runtime, compaction, tools, { force: true, manual: true });
68
- return { summarySeq: out.summarySeq, failed: out.failed };
112
+ return { stepInput, events, tools, compaction };
69
113
  }
70
114
  };
71
115
  CompactionService = __decorate([
@@ -0,0 +1,94 @@
1
+ import type { ConversationEvent } from "../../conversations/events.js";
2
+ import type { CompactionSettings } from "../../identity/settings.js";
3
+ import { type CacheExpiry } from "./cache-expiry.js";
4
+ /** Idle compaction only beats the expiry of a cache that lives at least this long, in seconds. */
5
+ export declare const IDLE_MIN_CACHE_TTL = 1800;
6
+ /** The next request must have grown at least this much over the summarized part, in tokens. */
7
+ export declare const IDLE_MIN_GROWTH_TOKENS = 20000;
8
+ /** `run_started.trigger` (the field is optional: absent reads as a person's message). */
9
+ export type RunStartedTrigger = NonNullable<Extract<ConversationEvent, {
10
+ type: "run_started";
11
+ }>["payload"]["trigger"]>;
12
+ /** `max(idleMinTokensFloor, idleMinWindowRatio × window)` (idle compaction spec §4.1). */
13
+ export declare function idleMinTokens(window: number, s: Pick<CompactionSettings, "idleMinTokensFloor" | "idleMinWindowRatio">): number;
14
+ /**
15
+ * An event that does not make an armed idle job stale (S1): a side-call `usage` event written
16
+ * without a run (the title and prompt-suggestion jobs append them after a run ended).
17
+ */
18
+ export declare function isIdleNeutralEvent(e: Pick<ConversationEvent, "type" | "runId">): boolean;
19
+ export type IdleArmSkip = "kind" | "trigger" | "automation" | "outcome" | "disabled" | "personal_off" | "no_cache" | "short_ttl" | "small" | "quality_gate" | "fit_plan" | "unsettled";
20
+ export interface IdleArmFacts {
21
+ conversationKind: "chat" | "subagent" | "eval";
22
+ /** `run_started.trigger`. */
23
+ trigger: RunStartedTrigger | undefined;
24
+ /** `runs.automation_run_id` (S5). */
25
+ automationRunId: string | null;
26
+ outcome: "completed" | "max_steps" | "max_duration" | "budget" | "max_output";
27
+ /** Effective for the org. */
28
+ settings: CompactionSettings;
29
+ /** `accounts.idle_compaction = 'off'` of the owner. */
30
+ personalOff: boolean;
31
+ /** `deriveCacheExpiry` over the run's calls (S6). */
32
+ expiry: CacheExpiry | null;
33
+ lastCall: {
34
+ provider: string;
35
+ model: string;
36
+ window: number;
37
+ input: number;
38
+ cacheRead: number;
39
+ cacheWrite: number;
40
+ output: number;
41
+ } | null;
42
+ /** `inContextSummaryAllowed(provider, model)` (S7). */
43
+ inContextAllowed: boolean;
44
+ /**
45
+ * The last step call's request recorded a fit plan: its prefix is not the plain history, so an
46
+ * in-context summary cannot reuse it (the fire-time build skips it as `fit_plan`, S7).
47
+ */
48
+ fitPlan: boolean;
49
+ /** No unanswered tool results after the last reply at the run's end (S7). */
50
+ settled: boolean;
51
+ }
52
+ /** Whether a finished run owes an idle compaction job, and when it should fire. */
53
+ export declare function idleArmDecision(f: IdleArmFacts): {
54
+ arm: true;
55
+ runAt: number;
56
+ expiresAt: number;
57
+ cacheCallSeq: number;
58
+ } | {
59
+ arm: false;
60
+ reason: IdleArmSkip;
61
+ };
62
+ export type IdleFireOutcome = "gone" | "obsolete" | "busy" | "disabled" | "expired" | "backoff" | "no_model" | "small" | "no_prefix";
63
+ export interface IdleFireFacts {
64
+ /** Org, conversation (chat) and agent are not deleted. */
65
+ live: boolean;
66
+ /** An event after `armedSeq` that `isIdleNeutralEvent` rejects (S1). */
67
+ stale: boolean;
68
+ /** An active run, an unconsumed message, or a queue head. */
69
+ busy: boolean;
70
+ /** Effective `enabled && idleEnabled && !personalOff`, read live. */
71
+ enabled: boolean;
72
+ now: number;
73
+ expiresAt: number;
74
+ /** The latest compaction record after the latest summary is `compaction_failed`. */
75
+ backoff: boolean;
76
+ /** The effective definition's model resolves, is enabled and equals the armed call's. */
77
+ sameModel: boolean;
78
+ probe: {
79
+ estimate: number;
80
+ window: number;
81
+ growth: number;
82
+ planned: boolean;
83
+ } | null;
84
+ /** The probe's in-context build applied (no skip). */
85
+ inContext: boolean;
86
+ settings: CompactionSettings;
87
+ }
88
+ /** The fire-time checks of idle compaction spec §4.3, in order; the first failure names the outcome. */
89
+ export declare function idleFireDecision(f: IdleFireFacts): {
90
+ fire: true;
91
+ } | {
92
+ fire: false;
93
+ outcome: IdleFireOutcome;
94
+ };
@@ -0,0 +1,84 @@
1
+ import { CACHE_EXPIRY_MARGIN_MS } from "./cache-expiry.js";
2
+ /** Idle compaction only beats the expiry of a cache that lives at least this long, in seconds. */
3
+ export const IDLE_MIN_CACHE_TTL = 1800;
4
+ /** The next request must have grown at least this much over the summarized part, in tokens. */
5
+ export const IDLE_MIN_GROWTH_TOKENS = 20_000;
6
+ /** `max(idleMinTokensFloor, idleMinWindowRatio × window)` (idle compaction spec §4.1). */
7
+ export function idleMinTokens(window, s) {
8
+ return Math.max(s.idleMinTokensFloor, Math.round(s.idleMinWindowRatio * window));
9
+ }
10
+ /**
11
+ * An event that does not make an armed idle job stale (S1): a side-call `usage` event written
12
+ * without a run (the title and prompt-suggestion jobs append them after a run ended).
13
+ */
14
+ export function isIdleNeutralEvent(e) {
15
+ return e.type === "usage" && e.runId === null;
16
+ }
17
+ const ARMING_TRIGGERS = new Set([
18
+ undefined,
19
+ "message",
20
+ "background_task",
21
+ "subagent",
22
+ ]);
23
+ /** Whether a finished run owes an idle compaction job, and when it should fire. */
24
+ export function idleArmDecision(f) {
25
+ if (f.conversationKind !== "chat")
26
+ return { arm: false, reason: "kind" };
27
+ if (!ARMING_TRIGGERS.has(f.trigger))
28
+ return { arm: false, reason: "trigger" };
29
+ if (f.automationRunId !== null)
30
+ return { arm: false, reason: "automation" };
31
+ if (f.outcome === "budget")
32
+ return { arm: false, reason: "outcome" };
33
+ if (!(f.settings.enabled && f.settings.idleEnabled))
34
+ return { arm: false, reason: "disabled" };
35
+ if (f.personalOff)
36
+ return { arm: false, reason: "personal_off" };
37
+ if (f.expiry === null || f.lastCall === null)
38
+ return { arm: false, reason: "no_cache" };
39
+ if (f.expiry.ttl < IDLE_MIN_CACHE_TTL)
40
+ return { arm: false, reason: "short_ttl" };
41
+ const c = f.lastCall;
42
+ if (c.input + c.cacheRead + c.cacheWrite + c.output < idleMinTokens(c.window, f.settings)) {
43
+ return { arm: false, reason: "small" };
44
+ }
45
+ if (!f.inContextAllowed)
46
+ return { arm: false, reason: "quality_gate" };
47
+ if (f.fitPlan)
48
+ return { arm: false, reason: "fit_plan" };
49
+ if (!f.settled)
50
+ return { arm: false, reason: "unsettled" };
51
+ return {
52
+ arm: true,
53
+ runAt: f.expiry.fireAt,
54
+ expiresAt: f.expiry.expiresAt,
55
+ cacheCallSeq: f.expiry.callSeq,
56
+ };
57
+ }
58
+ /** The fire-time checks of idle compaction spec §4.3, in order; the first failure names the outcome. */
59
+ export function idleFireDecision(f) {
60
+ if (!f.live)
61
+ return { fire: false, outcome: "gone" };
62
+ if (f.stale)
63
+ return { fire: false, outcome: "obsolete" };
64
+ if (f.busy)
65
+ return { fire: false, outcome: "busy" };
66
+ if (!f.enabled)
67
+ return { fire: false, outcome: "disabled" };
68
+ if (f.now >= f.expiresAt - CACHE_EXPIRY_MARGIN_MS)
69
+ return { fire: false, outcome: "expired" };
70
+ if (f.backoff)
71
+ return { fire: false, outcome: "backoff" };
72
+ if (!f.sameModel)
73
+ return { fire: false, outcome: "no_model" };
74
+ const p = f.probe;
75
+ if (p === null ||
76
+ !p.planned ||
77
+ p.estimate < idleMinTokens(p.window, f.settings) ||
78
+ p.growth < IDLE_MIN_GROWTH_TOKENS) {
79
+ return { fire: false, outcome: "small" };
80
+ }
81
+ if (!f.inContext)
82
+ return { fire: false, outcome: "no_prefix" };
83
+ return { fire: true };
84
+ }
@@ -0,0 +1,38 @@
1
+ import type { ConversationKind } from "../db/kernel-schema.js";
2
+ import { AccountsService } from "../identity/accounts.js";
3
+ import { KernelDb } from "../infra/database/kernel-db.js";
4
+ import type { KernelLogger } from "../log.js";
5
+ import { CompactionSettingsService } from "./compaction-settings.service.js";
6
+ import { type IdleArmFacts } from "./context/idle-compaction-rules.js";
7
+ import { ProviderRegistry } from "./providers.js";
8
+ import type { IdleCompactionIntent } from "./run-finish.js";
9
+ /** How a chat run ended, as the run worker's finish branches that write `run_finished` see it. */
10
+ export type IdleArmOutcome = IdleArmFacts["outcome"];
11
+ /**
12
+ * The arm decision of idle compaction at a chat run's finish (idle compaction spec §4.2, S4–S7):
13
+ * gathers {@link IdleArmFacts} and asks {@link idleArmDecision} whether the run's terminal
14
+ * 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
+ */
17
+ export declare class IdleArm {
18
+ private readonly kdb;
19
+ private readonly compaction;
20
+ private readonly accounts;
21
+ private readonly models;
22
+ private readonly log;
23
+ constructor(kdb: KernelDb, compaction: Pick<CompactionSettingsService, "resolve">, accounts: Pick<AccountsService, "idleCompactionOff">, models: Pick<ProviderRegistry, "resolve">, log: Pick<KernelLogger, "debug" | "warn">);
24
+ /**
25
+ * The intent `RunFinish.finishIn` owes the job from, or undefined when the run does not arm.
26
+ * Never throws: any failure is logged at `warn` and arms nothing, so arming never fails or holds
27
+ * up a finish (Review Focus 6). Reads cheapest first and stops at the first failing fact.
28
+ */
29
+ decide(run: {
30
+ id: string;
31
+ }, conv: {
32
+ id: string;
33
+ org_id: string;
34
+ kind: ConversationKind;
35
+ account_id: string | null;
36
+ }, outcome: IdleArmOutcome): Promise<IdleCompactionIntent | undefined>;
37
+ private decideOrSkip;
38
+ }