@capybara-hq/kernel 0.1.0-rc.29 → 0.1.0-rc.30

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 (62) hide show
  1. package/bootstrap.json +27 -27
  2. package/dist/admin/admin.schemas.d.ts +7 -0
  3. package/dist/config/schema.d.ts +0 -2
  4. package/dist/config/schema.js +0 -16
  5. package/dist/conversations/conversations.controller.d.ts +11 -1
  6. package/dist/conversations/conversations.controller.js +25 -1
  7. package/dist/conversations/conversations.schemas.d.ts +8 -0
  8. package/dist/conversations/conversations.schemas.js +14 -0
  9. package/dist/conversations/conversations.service.d.ts +12 -0
  10. package/dist/conversations/conversations.service.js +10 -0
  11. package/dist/conversations/event-log.d.ts +14 -0
  12. package/dist/conversations/events.d.ts +12 -0
  13. package/dist/conversations/events.js +35 -3
  14. package/dist/db/kernel-schema.d.ts +5 -0
  15. package/dist/errors.d.ts +3 -0
  16. package/dist/errors.js +3 -0
  17. package/dist/evals/plan.d.ts +20 -15
  18. package/dist/evals/plan.js +29 -6
  19. package/dist/evals/reconstruct.d.ts +16 -1
  20. package/dist/evals/reconstruct.js +55 -1
  21. package/dist/evals/sets.service.d.ts +3 -2
  22. package/dist/evals/sets.service.js +16 -2
  23. package/dist/evals/step-replay.d.ts +6 -0
  24. package/dist/evals/step-replay.js +5 -0
  25. package/dist/evals/trajectory.d.ts +5 -1
  26. package/dist/evals/trajectory.js +3 -1
  27. package/dist/evals/worker.js +2 -1
  28. package/dist/identity/settings.d.ts +64 -0
  29. package/dist/identity/settings.js +86 -2
  30. package/dist/orgs/roles.d.ts +1 -1
  31. package/dist/orgs/roles.js +2 -0
  32. package/dist/orgs/settings.service.d.ts +17 -0
  33. package/dist/orgs/settings.service.js +31 -3
  34. package/dist/platform/ops/admin.ops.js +8 -2
  35. package/dist/platform/ops/conversations.ops.js +34 -0
  36. package/dist/platform/ops/evals.ops.js +12 -1
  37. package/dist/platform/ops/orgs.ops.js +1 -0
  38. package/dist/runtime/compaction-progress.d.ts +62 -0
  39. package/dist/runtime/compaction-progress.js +82 -0
  40. package/dist/runtime/compaction-settings.service.d.ts +16 -0
  41. package/dist/runtime/compaction-settings.service.js +42 -0
  42. package/dist/runtime/compaction.service.d.ts +50 -0
  43. package/dist/runtime/compaction.service.js +75 -0
  44. package/dist/runtime/context/compaction.d.ts +90 -12
  45. package/dist/runtime/context/compaction.js +256 -21
  46. package/dist/runtime/context/fit.d.ts +79 -0
  47. package/dist/runtime/context/fit.js +202 -0
  48. package/dist/runtime/model-call.d.ts +134 -5
  49. package/dist/runtime/model-call.js +766 -335
  50. package/dist/runtime/run-control.d.ts +6 -1
  51. package/dist/runtime/run-control.js +7 -0
  52. package/dist/runtime/run-queue.d.ts +14 -0
  53. package/dist/runtime/run-queue.js +75 -0
  54. package/dist/runtime/run-steps.d.ts +3 -1
  55. package/dist/runtime/run-steps.js +9 -2
  56. package/dist/runtime/run-worker.d.ts +14 -2
  57. package/dist/runtime/run-worker.js +160 -33
  58. package/dist/runtime/runtime.module.js +11 -0
  59. package/dist/runtime/stream.js +15 -0
  60. package/dist/tools/pipeline.js +6 -3
  61. package/package.json +1 -1
  62. package/src/migrations/0132_compact_runs.sql +6 -0
@@ -17,13 +17,18 @@ export declare class RunControl {
17
17
  /** Owes a deleted root's tree stop in the delete's transaction. */
18
18
  private readonly outbox;
19
19
  private readonly log;
20
- constructor(queue: Pick<RunQueue, "ensureRun" | "oweEnsureRun" | "abortIfOrphaned" | "abortQueued" | "wakeHeldTree" | "oweHeldTreeIn">, waits: Pick<Waits, "abortWaiting" | "childFinished" | "stopChildren" | "stopTree">, abort: Pick<RunAbort, "request">,
20
+ constructor(queue: Pick<RunQueue, "ensureRun" | "oweEnsureRun" | "abortIfOrphaned" | "abortQueued" | "wakeHeldTree" | "oweHeldTreeIn" | "startCompaction">, waits: Pick<Waits, "abortWaiting" | "childFinished" | "stopChildren" | "stopTree">, abort: Pick<RunAbort, "request">,
21
21
  /** The resume of a waiting run in a decision's transaction (a reply's skips). */
22
22
  resumes: Pick<RunResume, "resumeIn">,
23
23
  /** Owes a deleted root's tree stop in the delete's transaction. */
24
24
  outbox: Pick<OutboxService, "add">, log: Pick<KernelLogger, "error">);
25
25
  /** 有未消费的消息且没有进行中的运行时投递一轮运行;返回 runId 或 null。 */
26
26
  ensureRun(conversationId: string): Promise<string | null>;
27
+ /**
28
+ * A manual compaction run (context compaction spec §4.7): the run already queued/running, or a
29
+ * new `compact` run; `conversation.busy` while an ordinary run is active.
30
+ */
31
+ startCompaction(conversationId: string, accountId: string): Promise<string>;
27
32
  /**
28
33
  * The direct `ensureRun` right after a commit that owes the ensure-run backstop (a message, a
29
34
  * queue change): a failure (Redis unreachable) is logged and never thrown, since the committed
@@ -42,6 +42,13 @@ let RunControl = class RunControl {
42
42
  ensureRun(conversationId) {
43
43
  return this.queue.ensureRun(conversationId);
44
44
  }
45
+ /**
46
+ * A manual compaction run (context compaction spec §4.7): the run already queued/running, or a
47
+ * new `compact` run; `conversation.busy` while an ordinary run is active.
48
+ */
49
+ startCompaction(conversationId, accountId) {
50
+ return this.queue.startCompaction(conversationId, accountId);
51
+ }
45
52
  /**
46
53
  * The direct `ensureRun` right after a commit that owes the ensure-run backstop (a message, a
47
54
  * queue change): a failure (Redis unreachable) is logged and never thrown, since the committed
@@ -60,6 +60,20 @@ export declare class RunQueue {
60
60
  opts?: {
61
61
  wakeRetry?: number;
62
62
  }): Promise<string | null>;
63
+ /**
64
+ * Starts a manual compaction run (context compaction spec §4.7): a `queued` run marked
65
+ * `compact` whose worker path calls the shared compaction execution and finishes without a model
66
+ * step. Returns its id.
67
+ *
68
+ * Under the conversation row lock (the one `ensureRun` takes), so a concurrent start serializes:
69
+ * a compact run already queued or running is returned as is (a second request is a no-op), and
70
+ * an ordinary active run is `conversation.busy` — the compact run must not share the
71
+ * conversation with a model step. The run's boundary (`trigger_seq`) is the current
72
+ * `consumed_seq`: it consumes no message.
73
+ */
74
+ startCompaction(conversationId: string, accountId: string): Promise<string>;
75
+ /** {@link startCompaction}'s transaction: the active-run check, the run row and its owed job. */
76
+ private startCompactionIn;
63
77
  /** {@link ensureRun}'s transaction: what it decided goes back through `st`. */
64
78
  private ensureRunIn;
65
79
  /**
@@ -15,6 +15,7 @@ import { wakeDecisionIn } from "../background/wake-rules.js";
15
15
  import { EventLog } from "../conversations/event-log.js";
16
16
  import { dispatchQueuedIn, pauseQueueWith } from "../conversations/queue.js";
17
17
  import { conversationTree } from "../conversations/tree.js";
18
+ import { ApiError } from "../errors.js";
18
19
  import { KernelConfigService } from "../infra/config/kernel-config.service.js";
19
20
  import { KernelDb } from "../infra/database/kernel-db.js";
20
21
  import { TransactionHost } from "../infra/database/transaction-host.js";
@@ -116,6 +117,77 @@ let RunQueue = class RunQueue {
116
117
  }
117
118
  return created;
118
119
  }
120
+ /**
121
+ * Starts a manual compaction run (context compaction spec §4.7): a `queued` run marked
122
+ * `compact` whose worker path calls the shared compaction execution and finishes without a model
123
+ * step. Returns its id.
124
+ *
125
+ * Under the conversation row lock (the one `ensureRun` takes), so a concurrent start serializes:
126
+ * a compact run already queued or running is returned as is (a second request is a no-op), and
127
+ * an ordinary active run is `conversation.busy` — the compact run must not share the
128
+ * conversation with a model step. The run's boundary (`trigger_seq`) is the current
129
+ * `consumed_seq`: it consumes no message.
130
+ */
131
+ async startCompaction(conversationId, accountId) {
132
+ return this.startCompactionIn(conversationId, accountId);
133
+ }
134
+ /** {@link startCompaction}'s transaction: the active-run check, the run row and its owed job. */
135
+ async startCompactionIn(conversationId, accountId) {
136
+ const t = this.db;
137
+ const conv = await t
138
+ .selectFrom("conversations")
139
+ .select(["org_id", "agent_id", "kind", "consumed_seq", "deleted_at"])
140
+ .where("id", "=", conversationId)
141
+ .forUpdate()
142
+ .executeTakeFirst();
143
+ // a deleted conversation, or a sub-agent's / eval one, has no manual compaction
144
+ if (!conv || conv.deleted_at !== null || conv.kind !== "chat") {
145
+ throw new ApiError("conversation.not_found", "Conversation not found");
146
+ }
147
+ const active = await t
148
+ .selectFrom("runs")
149
+ .select(["id", "compact"])
150
+ .where("conversation_id", "=", conversationId)
151
+ .where("status", "in", ACTIVE_RUN_STATUSES)
152
+ .orderBy("created_at", "desc")
153
+ .execute();
154
+ // a compact run already queued or running: the same request again
155
+ const compact = active.find((r) => r.compact);
156
+ if (compact)
157
+ return compact.id;
158
+ if (active.length > 0) {
159
+ throw new ApiError("conversation.busy", "A run is active in this conversation");
160
+ }
161
+ const agent = await t
162
+ .selectFrom("agents")
163
+ .select(["current_version", "deleted_at"])
164
+ .where("id", "=", conv.agent_id)
165
+ .executeTakeFirst();
166
+ if (!agent || agent.deleted_at !== null) {
167
+ throw new ApiError("conversation.not_found", "Conversation not found");
168
+ }
169
+ // the compact run's own job id: a later run of the same trigger has `<runJobId>-<n>` (R34), so
170
+ // it never collides with the ordinary run of that seq nor with an earlier compact run
171
+ const jobId = await this.jobIdFor(conversationId, Number(conv.consumed_seq));
172
+ const runId = randomUUID();
173
+ if (!(await this.oweJob(conversationId, runId, jobId.id, "chat", conv.org_id))) {
174
+ throw new ApiError("conversation.busy", "A run is already queued for this conversation");
175
+ }
176
+ await t
177
+ .insertInto("runs")
178
+ .values({
179
+ id: runId,
180
+ conversation_id: conversationId,
181
+ status: "queued",
182
+ agent_version: agent.current_version,
183
+ trigger_account_id: accountId,
184
+ trigger_seq: Number(conv.consumed_seq),
185
+ job_id: jobId.recorded,
186
+ compact: true,
187
+ })
188
+ .execute();
189
+ return runId;
190
+ }
119
191
  /** {@link ensureRun}'s transaction: what it decided goes back through `st`. */
120
192
  async ensureRunIn(conversationId, st) {
121
193
  const t = this.db;
@@ -642,6 +714,9 @@ let RunQueue = class RunQueue {
642
714
  .catch((err) => this.log.warn("checkpoint delete failed", { runId, err }));
643
715
  }
644
716
  };
717
+ __decorate([
718
+ Transactional({ propagation: "requires_new" })
719
+ ], RunQueue.prototype, "startCompactionIn", null);
645
720
  __decorate([
646
721
  Transactional({ propagation: "requires_new" })
647
722
  ], RunQueue.prototype, "ensureRunIn", null);
@@ -7,6 +7,8 @@ import type { KernelLogger } from "../log.js";
7
7
  import { ToolPipeline } from "../tools/pipeline.js";
8
8
  import { ToolRegistry } from "../tools/registry.js";
9
9
  import { KyselyCheckpointSaver } from "./checkpointer.js";
10
+ import { CompactionProgressService } from "./compaction-progress.js";
11
+ import { CompactionSettingsService } from "./compaction-settings.service.js";
10
12
  import { type LoopDeps } from "./langgraph-loop.js";
11
13
  import type { AgentLoop } from "./loop.js";
12
14
  import { ProviderRegistry } from "./providers.js";
@@ -34,5 +36,5 @@ export declare class AgentLoops {
34
36
  */
35
37
  export declare class RunSteps {
36
38
  readonly deps: LoopDeps;
37
- constructor(kdb: KernelDb, eventLog: EventLog, stepLog: StepLog, registry: ProviderRegistry, tools: ToolRegistry, config: KernelConfigService, log: KernelLogger, toolPipeline: ToolPipeline, host: ExtensionHost, subagents: SubagentsService, attachments: AttachmentsService);
39
+ constructor(kdb: KernelDb, eventLog: EventLog, stepLog: StepLog, registry: ProviderRegistry, tools: ToolRegistry, config: KernelConfigService, log: KernelLogger, toolPipeline: ToolPipeline, host: ExtensionHost, subagents: SubagentsService, attachments: AttachmentsService, compactionSettings: CompactionSettingsService, compactionProgress: CompactionProgressService);
38
40
  }
@@ -17,6 +17,8 @@ import { KERNEL_LOGGER } from "../infra/tokens.js";
17
17
  import { ToolPipeline } from "../tools/pipeline.js";
18
18
  import { ToolRegistry } from "../tools/registry.js";
19
19
  import { KyselyCheckpointSaver } from "./checkpointer.js";
20
+ import { CompactionProgressService } from "./compaction-progress.js";
21
+ import { CompactionSettingsService } from "./compaction-settings.service.js";
20
22
  import { LangGraphLoop } from "./langgraph-loop.js";
21
23
  import { ProviderRegistry } from "./providers.js";
22
24
  import { StepLog } from "./step-log.js";
@@ -51,7 +53,7 @@ export { AgentLoops };
51
53
  */
52
54
  let RunSteps = class RunSteps {
53
55
  deps;
54
- constructor(kdb, eventLog, stepLog, registry, tools, config, log, toolPipeline, host, subagents, attachments) {
56
+ constructor(kdb, eventLog, stepLog, registry, tools, config, log, toolPipeline, host, subagents, attachments, compactionSettings, compactionProgress) {
55
57
  this.deps = {
56
58
  get db() {
57
59
  return kdb.db;
@@ -61,6 +63,9 @@ let RunSteps = class RunSteps {
61
63
  registry,
62
64
  tools,
63
65
  config,
66
+ compactionSettings,
67
+ // ephemeral, display-only: the run's progress on its own conversation's stream
68
+ compactionProgress,
64
69
  log,
65
70
  toolPipeline,
66
71
  // plugin hooks for chat runs; the full-run replay drops them (P-18)
@@ -88,6 +93,8 @@ RunSteps = __decorate([
88
93
  __param(7, Inject(ToolPipeline)),
89
94
  __param(8, Inject(ExtensionHost)),
90
95
  __param(9, Inject(SubagentsService)),
91
- __param(10, Inject(AttachmentsService))
96
+ __param(10, Inject(AttachmentsService)),
97
+ __param(11, Inject(CompactionSettingsService)),
98
+ __param(12, Inject(CompactionProgressService))
92
99
  ], RunSteps);
93
100
  export { RunSteps };
@@ -11,6 +11,7 @@ import { SkillsCatalogService } from "../skills/catalog.js";
11
11
  import { ToolRegistry } from "../tools/registry.js";
12
12
  import { RunAbort } from "./abort.js";
13
13
  import { KyselyCheckpointSaver } from "./checkpointer.js";
14
+ import { CompactionService } from "./compaction.service.js";
14
15
  import { ConversationLock } from "./conversation-lock.js";
15
16
  import { PluginContextService } from "./plugin-context.service.js";
16
17
  import { ProviderRegistry } from "./providers.js";
@@ -56,6 +57,7 @@ export declare class RunWorker {
56
57
  private readonly abort;
57
58
  private readonly queue;
58
59
  private readonly settings;
60
+ private readonly compaction;
59
61
  private readonly config;
60
62
  private readonly log;
61
63
  private readonly bus;
@@ -91,7 +93,7 @@ export declare class RunWorker {
91
93
  /** close() 开始时触发:ensureRun 重试不再等待退避间隔。 */
92
94
  private readonly closingSignal;
93
95
  private readonly loop;
94
- constructor(kdb: KernelDb, eventLog: EventLog, lock: ConversationLock, quota: OrgQuota, abort: RunAbort, queue: Pick<RunQueue, "ensureRun">, settings: Pick<SettingsService, "get">, loops: AgentLoops, steps: RunSteps, config: KernelConfigService, log: Logger, bus: ExtensionContext["bus"],
96
+ constructor(kdb: KernelDb, eventLog: EventLog, lock: ConversationLock, quota: OrgQuota, abort: RunAbort, queue: Pick<RunQueue, "ensureRun">, settings: Pick<SettingsService, "get">, loops: AgentLoops, steps: RunSteps, compaction: Pick<CompactionService, "force">, config: KernelConfigService, log: Logger, bus: ExtensionContext["bus"],
95
97
  /** 运行到达终态后删除该运行(thread_id = runId)的 checkpoint thread(只用于续跑,结束后无用)。 */
96
98
  checkpoints: Pick<KyselyCheckpointSaver, "deleteThread">,
97
99
  /** loop 返回 `suspended` 后把运行置为 waiting(释放会话锁与配额之后); the child lifecycle. */
@@ -176,6 +178,15 @@ export declare class RunWorker {
176
178
  /** One run job (the `@Processor`s of both run queues call it). */
177
179
  process(job: Job<RunJobData>, token: string | undefined): Promise<ProcessResult>;
178
180
  private execute;
181
+ /**
182
+ * A manual compaction run (context compaction spec §4.7): starts it (`run_started` with
183
+ * `trigger: "compact"`, no skills/run/plugin context — nothing reaches the model as a request),
184
+ * runs the shared compaction execution with the conversation's effective definition, and writes
185
+ * the terminal state. The run records the summary and its usage only; nothing is absorbed and no
186
+ * model step runs. A person's stop aborts it (`run_aborted`, no partial summary); a shutdown or a
187
+ * lost lease leaves it to another replica.
188
+ */
189
+ private executeCompaction;
179
190
  private completed;
180
191
  /**
181
192
  * The run's extension tool keys by plugin, resolved as a chat run's first step lists them
@@ -198,7 +209,8 @@ export declare class RunWorker {
198
209
  private endedUnderLocks;
199
210
  /**
200
211
  * `run_started` under the conversation row lock, with the model / effort switch in effect then
201
- * (a chat run's `saved` version under the conversation's selection): what the run uses.
212
+ * (a chat run's `saved` version under the conversation's selection): what the run uses. A
213
+ * `compact` run is marked `trigger: "compact"` (context compaction spec §4.7).
202
214
  */
203
215
  private appendRunStarted;
204
216
  /** {@link fallBackIfUnavailable}'s write: null when the person switched again meanwhile. */
@@ -28,6 +28,7 @@ import { normalizeStoredDefinitionIn } from "../tools/legacy-data.js";
28
28
  import { ToolRegistry } from "../tools/registry.js";
29
29
  import { RunAbort } from "./abort.js";
30
30
  import { KyselyCheckpointSaver } from "./checkpointer.js";
31
+ import { CompactionService } from "./compaction.service.js";
31
32
  import { ConversationLock } from "./conversation-lock.js";
32
33
  import { runDeadline, tightestLimit } from "./limits.js";
33
34
  import { RunError } from "./model-call.js";
@@ -88,6 +89,7 @@ let RunWorker = class RunWorker {
88
89
  abort;
89
90
  queue;
90
91
  settings;
92
+ compaction;
91
93
  config;
92
94
  log;
93
95
  bus;
@@ -113,7 +115,7 @@ let RunWorker = class RunWorker {
113
115
  /** close() 开始时触发:ensureRun 重试不再等待退避间隔。 */
114
116
  closingSignal = new AbortController();
115
117
  loop;
116
- constructor(kdb, eventLog, lock, quota, abort, queue, settings, loops, steps, config, log, bus,
118
+ constructor(kdb, eventLog, lock, quota, abort, queue, settings, loops, steps, compaction, config, log, bus,
117
119
  /** 运行到达终态后删除该运行(thread_id = runId)的 checkpoint thread(只用于续跑,结束后无用)。 */
118
120
  checkpoints,
119
121
  /** loop 返回 `suspended` 后把运行置为 waiting(释放会话锁与配额之后); the child lifecycle. */
@@ -141,6 +143,7 @@ let RunWorker = class RunWorker {
141
143
  this.abort = abort;
142
144
  this.queue = queue;
143
145
  this.settings = settings;
146
+ this.compaction = compaction;
144
147
  this.config = config;
145
148
  this.log = log;
146
149
  this.bus = bus;
@@ -391,6 +394,7 @@ let RunWorker = class RunWorker {
391
394
  "started_at",
392
395
  "waited_ms",
393
396
  "budget_run_id",
397
+ "compact",
394
398
  ])
395
399
  .where("id", "=", runId)
396
400
  .executeTakeFirst();
@@ -617,6 +621,11 @@ let RunWorker = class RunWorker {
617
621
  if (existingStart && saved !== undefined) {
618
622
  agent = effectiveDefinition(saved, await readSelection(this.db, conversationId, existingStart.seq));
619
623
  }
624
+ // a manual compaction run (context compaction spec §4.7): the shared compaction execution
625
+ // instead of the agent loop, no model step, nothing absorbed
626
+ if (run.compact) {
627
+ return this.executeCompaction(run, conv, agent, saved, startedAt, state);
628
+ }
620
629
  if (run.status === "queued" || startedAt === null) {
621
630
  if (!existingStart) {
622
631
  await this.hooks?.beforeRunStarted?.(runId, conversationId);
@@ -865,6 +874,118 @@ let RunWorker = class RunWorker {
865
874
  await unwatch?.().catch((err) => this.log.warn("abort unwatch failed", { runId, err }));
866
875
  }
867
876
  }
877
+ /**
878
+ * A manual compaction run (context compaction spec §4.7): starts it (`run_started` with
879
+ * `trigger: "compact"`, no skills/run/plugin context — nothing reaches the model as a request),
880
+ * runs the shared compaction execution with the conversation's effective definition, and writes
881
+ * the terminal state. The run records the summary and its usage only; nothing is absorbed and no
882
+ * model step runs. A person's stop aborts it (`run_aborted`, no partial summary); a shutdown or a
883
+ * lost lease leaves it to another replica.
884
+ */
885
+ async executeCompaction(run, conv, agent, saved, startedAt, state) {
886
+ const runId = run.id;
887
+ const conversationId = conv.id;
888
+ const existingStart = await this.eventLog.findByIdem(conversationId, `run_started:${runId}`);
889
+ if (run.status === "queued" || startedAt === null) {
890
+ if (!existingStart) {
891
+ await this.hooks?.beforeRunStarted?.(runId, conversationId);
892
+ const started = await this.appendRunStarted(conversationId, run, agent, saved, true);
893
+ // a stop that ended the run meanwhile (a queued run's direct abort) wins
894
+ if (started.terminal)
895
+ return "finished";
896
+ agent = started.agent;
897
+ if (started.toSeq !== undefined)
898
+ await this.eventLog.notify(conversationId, started.toSeq);
899
+ }
900
+ await this.hooks?.beforeRunning?.(runId, conversationId);
901
+ // never over a terminal status: a run finished meanwhile stays finished
902
+ const updated = await this.db
903
+ .updateTable("runs")
904
+ .set({ status: "running", started_at: sql `COALESCE(started_at, now())` })
905
+ .where("id", "=", runId)
906
+ .where("status", "in", ["queued", "running"])
907
+ .returning("started_at")
908
+ .executeTakeFirst();
909
+ if (updated === undefined)
910
+ return "finished";
911
+ }
912
+ // the conversation lock is held: nothing absorbed the trigger seq meanwhile, and the summary
913
+ // request's boundary is the current consumed position
914
+ const { consumed_seq } = await this.db
915
+ .selectFrom("conversations")
916
+ .select("consumed_seq")
917
+ .where("id", "=", conversationId)
918
+ .executeTakeFirstOrThrow();
919
+ const ac = new AbortController();
920
+ let abortedBy;
921
+ let abortDetail;
922
+ const unwatch = await this.abort.watch(runId, (by, detail) => {
923
+ abortedBy = by;
924
+ abortDetail = detail;
925
+ ac.abort();
926
+ });
927
+ // a shutdown (or a lost lease, which aborts this signal too) stops at the stream boundary
928
+ const stopForShutdown = () => ac.abort();
929
+ state.shutdown.signal.addEventListener("abort", stopForShutdown, { once: true });
930
+ // the shutdown may have begun before the listener was added (it would never fire): leave the
931
+ // run to another replica instead of compacting through the stop
932
+ if (state.shutdown.signal.aborted) {
933
+ state.shutdown.signal.removeEventListener("abort", stopForShutdown);
934
+ await unwatch().catch((err) => this.log.warn("abort unwatch failed", { runId, err }));
935
+ return "interrupted";
936
+ }
937
+ try {
938
+ await this.compaction.force({
939
+ orgId: conv.org_id,
940
+ conversationId,
941
+ runId,
942
+ accountId: run.trigger_account_id,
943
+ agentId: conv.agent_id,
944
+ agent,
945
+ agentVersion: run.agent_version,
946
+ source: conv.source,
947
+ conversationKind: "chat",
948
+ absorbedUpToSeq: Number(consumed_seq),
949
+ signal: ac.signal,
950
+ });
951
+ }
952
+ catch (err) {
953
+ if (state.abandoned)
954
+ return "abandoned";
955
+ if (state.leaseLost)
956
+ return "interrupted";
957
+ if (abortedBy === undefined) {
958
+ // a shutdown abort: nothing terminal, the job goes back for another replica
959
+ if (state.shutdown.signal.aborted)
960
+ return "interrupted";
961
+ throw err;
962
+ }
963
+ await this.finish(conversationId, runId, "aborted", null, {
964
+ type: "run_aborted",
965
+ payload: {
966
+ byAccountId: abortedBy,
967
+ reason: "user",
968
+ ...(abortDetail !== undefined && { detail: abortDetail }),
969
+ },
970
+ });
971
+ return "finished";
972
+ }
973
+ finally {
974
+ await unwatch().catch((err) => this.log.warn("abort unwatch failed", { runId, err }));
975
+ state.shutdown.signal.removeEventListener("abort", stopForShutdown);
976
+ }
977
+ if (state.abandoned)
978
+ return "abandoned";
979
+ if (state.leaseLost)
980
+ return "interrupted";
981
+ // a failed compaction is still a finished compact run: it wrote `compaction_failed` and the
982
+ // next step falls back to the fit guard, exactly as after an automatic one
983
+ await this.finish(conversationId, runId, "completed", null, {
984
+ type: "run_finished",
985
+ payload: { reason: "completed", consumedUpToSeq: Number(consumed_seq) },
986
+ });
987
+ return "finished";
988
+ }
868
989
  completed(conversationId) {
869
990
  // a completed run enqueues the conversation's title job (never throws)
870
991
  void this.titles.maybeEnqueue(conversationId);
@@ -945,11 +1066,12 @@ let RunWorker = class RunWorker {
945
1066
  }
946
1067
  /**
947
1068
  * `run_started` under the conversation row lock, with the model / effort switch in effect then
948
- * (a chat run's `saved` version under the conversation's selection): what the run uses.
1069
+ * (a chat run's `saved` version under the conversation's selection): what the run uses. A
1070
+ * `compact` run is marked `trigger: "compact"` (context compaction spec §4.7).
949
1071
  */
950
1072
  async appendRunStarted(conversationId, run,
951
1073
  /** The definition so far (a sub-agent's frozen one is final). */
952
- current, saved) {
1074
+ current, saved, compact = false) {
953
1075
  const t = this.db;
954
1076
  if (await this.endedUnderLocks(conversationId, run.id)) {
955
1077
  return { toSeq: undefined, agent: current, terminal: true };
@@ -974,19 +1096,23 @@ let RunWorker = class RunWorker {
974
1096
  agentVersion: run.agent_version,
975
1097
  model: agent.model,
976
1098
  triggerAccountId: run.trigger_account_id,
977
- ...(boundary?.type === "background_task_finished" && {
978
- trigger: "background_task",
979
- triggerSeq: Number(run.trigger_seq),
980
- }),
981
- ...(boundary?.type === "subagent_delivery" && {
982
- trigger: "subagent",
983
- triggerSeq: Number(run.trigger_seq),
984
- }),
985
- // a scheduled task's message (scheduled tasks spec §6); display only
986
- ...(boundary?.type === "user_message" &&
987
- boundary.payload.schedule !== undefined && {
988
- trigger: "schedule",
989
- }),
1099
+ ...(compact
1100
+ ? { trigger: "compact" }
1101
+ : {
1102
+ ...(boundary?.type === "background_task_finished" && {
1103
+ trigger: "background_task",
1104
+ triggerSeq: Number(run.trigger_seq),
1105
+ }),
1106
+ ...(boundary?.type === "subagent_delivery" && {
1107
+ trigger: "subagent",
1108
+ triggerSeq: Number(run.trigger_seq),
1109
+ }),
1110
+ // a scheduled task's message (scheduled tasks spec §6); display only
1111
+ ...(boundary?.type === "user_message" &&
1112
+ boundary.payload.schedule !== undefined && {
1113
+ trigger: "schedule",
1114
+ }),
1115
+ }),
990
1116
  },
991
1117
  },
992
1118
  ]);
@@ -1061,22 +1187,23 @@ RunWorker = __decorate([
1061
1187
  __param(6, Inject(SettingsService)),
1062
1188
  __param(7, Inject(AgentLoops)),
1063
1189
  __param(8, Inject(RunSteps)),
1064
- __param(9, Inject(KernelConfigService)),
1065
- __param(10, Inject(KERNEL_LOGGER)),
1066
- __param(11, Inject(KERNEL_BUS)),
1067
- __param(12, Inject(KyselyCheckpointSaver)),
1068
- __param(13, Inject(Waits)),
1069
- __param(14, Inject(KernelEvents)),
1070
- __param(15, Inject(TitleQueue)),
1071
- __param(16, Inject(ProviderRegistry)),
1072
- __param(17, Inject(SkillsCatalogService)),
1073
- __param(18, Inject(RunContextService)),
1074
- __param(19, Inject(PluginContextService)),
1075
- __param(20, Inject(ToolRegistry)),
1076
- __param(21, Inject(RunFinish)),
1077
- __param(22, Inject(TransactionHost)),
1078
- __param(23, Inject(RunDrafts)),
1079
- __param(24, Optional()),
1080
- __param(24, Inject(RUN_HOOKS))
1190
+ __param(9, Inject(CompactionService)),
1191
+ __param(10, Inject(KernelConfigService)),
1192
+ __param(11, Inject(KERNEL_LOGGER)),
1193
+ __param(12, Inject(KERNEL_BUS)),
1194
+ __param(13, Inject(KyselyCheckpointSaver)),
1195
+ __param(14, Inject(Waits)),
1196
+ __param(15, Inject(KernelEvents)),
1197
+ __param(16, Inject(TitleQueue)),
1198
+ __param(17, Inject(ProviderRegistry)),
1199
+ __param(18, Inject(SkillsCatalogService)),
1200
+ __param(19, Inject(RunContextService)),
1201
+ __param(20, Inject(PluginContextService)),
1202
+ __param(21, Inject(ToolRegistry)),
1203
+ __param(22, Inject(RunFinish)),
1204
+ __param(23, Inject(TransactionHost)),
1205
+ __param(24, Inject(RunDrafts)),
1206
+ __param(25, Optional()),
1207
+ __param(25, Inject(RUN_HOOKS))
1081
1208
  ], RunWorker);
1082
1209
  export { RunWorker };
@@ -22,6 +22,9 @@ import { SkillsModule } from "../skills/skills.module.js";
22
22
  import { ToolsModule } from "../tools/tools.module.js";
23
23
  import { RunAbort } from "./abort.js";
24
24
  import { KyselyCheckpointSaver } from "./checkpointer.js";
25
+ import { CompactionService } from "./compaction.service.js";
26
+ import { CompactionProgressService } from "./compaction-progress.js";
27
+ import { CompactionSettingsService } from "./compaction-settings.service.js";
25
28
  import { ConversationLock } from "./conversation-lock.js";
26
29
  import { MAINTENANCE_QUEUE_NAME } from "./maintenance-queue.js";
27
30
  import { PluginContextService } from "./plugin-context.service.js";
@@ -88,6 +91,12 @@ RuntimeModule = __decorate([
88
91
  RunContextService,
89
92
  PluginContextService,
90
93
  RunWorker,
94
+ // the org's effective compaction settings, one read per model step
95
+ CompactionSettingsService,
96
+ // ephemeral compaction progress for the conversation SSE (spec 2026-11-14 §4.6)
97
+ CompactionProgressService,
98
+ // the manual compaction execution of a compact run (spec 2026-11-14 §4.7)
99
+ CompactionService,
91
100
  // a finished background task wakes an idle conversation (background Bash spec §3)
92
101
  BackgroundWake,
93
102
  // one quota per key prefix (the org run quota, the org eval quota)
@@ -116,6 +125,8 @@ RuntimeModule = __decorate([
116
125
  AgentLoops,
117
126
  RunSteps,
118
127
  RunWorker,
128
+ CompactionSettingsService,
129
+ CompactionService,
119
130
  RUN_QUOTA,
120
131
  EVAL_QUOTA,
121
132
  ProvidersModule,
@@ -53,6 +53,14 @@ function isBusMessage(m) {
53
53
  typeof x.step === "number" &&
54
54
  typeof x.toolCalls === "number");
55
55
  }
56
+ if (k === "compaction_progress") {
57
+ const x = m;
58
+ return (typeof x.runId === "string" &&
59
+ typeof x.conversationId === "string" &&
60
+ typeof x.step === "number" &&
61
+ typeof x.startedAt === "number" &&
62
+ (x.phase === "preparing" || x.phase === "summarizing" || x.phase === "writing"));
63
+ }
56
64
  return k === "delta" && typeof m.runId === "string";
57
65
  }
58
66
  const eventFrame = (e) => `id: ${e.seq}\nevent: event\ndata: ${JSON.stringify(e)}\n\n`;
@@ -256,6 +264,13 @@ class Connection {
256
264
  this.enqueue(() => this.write(frame));
257
265
  return;
258
266
  }
267
+ if (m.kind === "compaction_progress") {
268
+ // a run of this conversation is compacting (§4.6): display-only, never in the log
269
+ const { kind: _k, ...progress } = m;
270
+ const frame = `event: compaction\ndata: ${JSON.stringify(progress)}\n\n`;
271
+ this.enqueue(() => this.write(frame));
272
+ return;
273
+ }
259
274
  const { kind: _kind, ...delta } = m;
260
275
  this.enqueue(() => this.write(`event: delta\ndata: ${JSON.stringify(delta)}\n\n`));
261
276
  }
@@ -29,7 +29,7 @@ import { NetworkGrants } from "../local-devices/network-grants.js";
29
29
  import { UNKNOWN_RESULT_TEXT } from "../runtime/context/pairing.js";
30
30
  import { fireObserve, hookDeniedAudit, hookDeniedEvent, hookScope, } from "../runtime/hook-calls.js";
31
31
  import { subagentWaitingIdemKey } from "../runtime/loop.js";
32
- import { assistantIdemKey, MAX_MODEL_ATTEMPTS, modelCallIdemKey } from "../runtime/model-call.js";
32
+ import { assistantIdemKey, MAX_STEP_MODEL_CALLS, modelCallIdemKey } from "../runtime/model-call.js";
33
33
  import { rootSurfaceOf } from "../runtime/subagents/child.js";
34
34
  import { SubagentMessages } from "../runtime/subagents/messages.js";
35
35
  import { pairStoppedForks } from "../runtime/subagents/skill-fork.js";
@@ -1230,7 +1230,8 @@ let ToolPipeline = class ToolPipeline {
1230
1230
  * old key that was offered (in flight across the rename) from one that never was.
1231
1231
  */
1232
1232
  async requestToolKeys(ctx) {
1233
- for (let attempt = MAX_MODEL_ATTEMPTS; attempt >= 1; attempt--) {
1233
+ // attempts can reach MAX_STEP_MODEL_CALLS after reactive overflow fix-ups; scan from the top
1234
+ for (let attempt = MAX_STEP_MODEL_CALLS; attempt >= 1; attempt--) {
1234
1235
  const e = await this.deps.eventLog.findByIdem(ctx.conversationId, modelCallIdemKey(ctx.runId, ctx.step, attempt));
1235
1236
  if (e?.type !== "model_call")
1236
1237
  continue;
@@ -1245,7 +1246,9 @@ let ToolPipeline = class ToolPipeline {
1245
1246
  * 或找不到 model_call 时返回 null(不做加载检查)。已加载集合由此从日志得出,不放进程内存。
1246
1247
  */
1247
1248
  async sentTools(ctx) {
1248
- for (let attempt = MAX_MODEL_ATTEMPTS; attempt >= 1; attempt--) {
1249
+ // attempts can reach MAX_STEP_MODEL_CALLS after reactive overflow fix-ups; the assistant_message
1250
+ // comes from the last attempt, so scan from the top
1251
+ for (let attempt = MAX_STEP_MODEL_CALLS; attempt >= 1; attempt--) {
1249
1252
  const e = await this.deps.eventLog.findByIdem(ctx.conversationId, modelCallIdemKey(ctx.runId, ctx.step, attempt));
1250
1253
  if (e?.type !== "model_call")
1251
1254
  continue;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@capybara-hq/kernel",
3
- "version": "0.1.0-rc.29",
3
+ "version": "0.1.0-rc.30",
4
4
  "description": "Capybara kernel: config, database, plugin host and HTTP API of the Capybara agent platform",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
@@ -0,0 +1,6 @@
1
+ -- A compact run (context compaction spec §4.7): the manual `POST .../compact` run takes the
2
+ -- conversation lock, runs the same compaction execution as a step's automatic path with
3
+ -- `force: true`, and writes only `compaction_summary` / `compaction_failed` + usage. Its
4
+ -- `run_started` is marked `trigger: "compact"`; `runs.compact` tells the run worker which path to
5
+ -- take. An ordinary run is `false` (not null), so every reader can test the column directly.
6
+ ALTER TABLE runs ADD COLUMN IF NOT EXISTS compact boolean NOT NULL DEFAULT false;