@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
@@ -23,6 +23,7 @@ import { KernelDb } from "../infra/database/kernel-db.js";
23
23
  import { TransactionHost } from "../infra/database/transaction-host.js";
24
24
  import { Transactional } from "../infra/database/transactional.decorator.js";
25
25
  import { KERNEL_LOGGER } from "../infra/tokens.js";
26
+ import { RunAbort } from "./abort.js";
26
27
  import { KyselyCheckpointSaver } from "./checkpointer.js";
27
28
  import { ConversationLock } from "./conversation-lock.js";
28
29
  import { notifyFinished, RunFinish } from "./run-finish.js";
@@ -52,10 +53,13 @@ let RunQueue = class RunQueue {
52
53
  log;
53
54
  txHost;
54
55
  config;
56
+ abort;
55
57
  ensureFails;
56
58
  constructor(kdb, eventLog, lock, jobs, finisher,
57
59
  /** An orphan aborted directly loses its checkpoint thread (thread_id = runId). */
58
- checkpoints, log, txHost, config, ensureFails = () => false) {
60
+ checkpoints, log, txHost, config,
61
+ /** Preemption of an idle compact run: the cross-replica stop its worker watches. */
62
+ abort, ensureFails = () => false) {
59
63
  this.kdb = kdb;
60
64
  this.eventLog = eventLog;
61
65
  this.lock = lock;
@@ -65,6 +69,7 @@ let RunQueue = class RunQueue {
65
69
  this.log = log;
66
70
  this.txHost = txHost;
67
71
  this.config = config;
72
+ this.abort = abort;
68
73
  this.ensureFails = ensureFails;
69
74
  }
70
75
  get db() {
@@ -88,22 +93,41 @@ let RunQueue = class RunQueue {
88
93
  * never call it.
89
94
  *
90
95
  * A conversation whose agent is soft-deleted starts no run.
96
+ *
97
+ * Pending input (an unconsumed message, a queue head that goes out, a wake) preempts an active
98
+ * idle compact run (idle compaction spec §5.2): one nobody claimed yet is ended in this call's
99
+ * transaction and the input's run is created in its place; one a worker runs (the conversation
100
+ * lock is held, so this call returns before its transaction) hears a `superseded` stop through
101
+ * {@link RunAbort} after the commit, and its finish starts the input's run.
91
102
  */
92
103
  async ensureRun(conversationId,
93
104
  /** From the `bg-wake` job: it fired `wakeRetry - 1` times before its window ended. */
94
105
  opts = {}) {
95
106
  if (this.ensureFails())
96
107
  throw new Error("ensureRun failure (test seam)");
97
- if ((await this.lock.holder(conversationId)) !== null)
108
+ if ((await this.lock.holder(conversationId)) !== null) {
109
+ // a worker holds the conversation: an idle compact run it runs is preempted from here (S2)
110
+ const idle = await this.preemptIdleIn(conversationId);
111
+ if (idle !== null)
112
+ await this.supersede(idle);
98
113
  return null;
114
+ }
99
115
  const st = {
100
116
  dispatchedSeq: null,
101
117
  dispatchedSwitch: false,
102
118
  dispatchedUnarchived: false,
103
119
  pausedNow: false,
104
120
  wakeRetry: opts.wakeRetry ?? 0,
121
+ preempt: null,
122
+ superseded: null,
105
123
  };
106
124
  const created = await this.ensureRunIn(conversationId, st);
125
+ if (st.superseded !== null) {
126
+ await notifyFinished(this.eventLog, conversationId, st.superseded.toSeq, "aborted");
127
+ await this.dropCheckpoints(st.superseded.runId);
128
+ }
129
+ if (st.preempt !== null)
130
+ await this.supersede(st.preempt);
107
131
  const { dispatchedSeq, dispatchedSwitch, dispatchedUnarchived, pausedNow } = st;
108
132
  // a pause is published too (batch 5 review I1): the page shows the reason without a reload
109
133
  if (pausedNow)
@@ -191,6 +215,113 @@ let RunQueue = class RunQueue {
191
215
  trigger_seq: Number(conv.consumed_seq),
192
216
  job_id: jobId.recorded,
193
217
  compact: true,
218
+ compact_origin: "manual",
219
+ })
220
+ .execute();
221
+ return runId;
222
+ }
223
+ /**
224
+ * Starts an idle compact run (idle compaction spec §5.1), or returns null and never throws: the
225
+ * idle job calls it at fire time, and a refusal or a failure only means no idle compaction now
226
+ * (the next run's finish arms again). Under the conversation row lock (the one `ensureRun` and
227
+ * {@link startCompaction} take) it re-checks that the conversation, its org and its agent are
228
+ * live, that its owner can still use it (active, the agent visible to them), that nothing but a run-less side-call `usage` (`isIdleNeutralEvent`, S1) was written
229
+ * after `armedSeq`, and that the conversation is not busy: no active run (queued, running or
230
+ * waiting), no unconsumed message, no queue head. The run is a `compact` run with
231
+ * `compact_origin = 'idle'`, run as the conversation's owner, its boundary the current
232
+ * `consumed_seq`, exactly as a manual one.
233
+ */
234
+ async startIdleCompaction(conversationId, armedSeq) {
235
+ try {
236
+ return await this.startIdleCompactionIn(conversationId, armedSeq);
237
+ }
238
+ catch (err) {
239
+ this.log.warn("idle compaction run not started", { conversationId, err });
240
+ return null;
241
+ }
242
+ }
243
+ /** {@link startIdleCompaction}'s transaction: the re-checks, the run row and its owed job. */
244
+ // org-filter: the idle-compaction job's kernel-written conversation id (owed by the run finish
245
+ // that armed it), run in runJob under the job's org; the conversation's own org is read under its
246
+ // row lock
247
+ async startIdleCompactionIn(conversationId, armedSeq) {
248
+ const t = this.db;
249
+ const conv = await t
250
+ .selectFrom("conversations")
251
+ .select(["org_id", "agent_id", "account_id", "kind", "consumed_seq", "deleted_at"])
252
+ .where("id", "=", conversationId)
253
+ .forUpdate()
254
+ .executeTakeFirst();
255
+ if (!conv || !isLive(conv.deleted_at) || conv.kind !== "chat")
256
+ return null;
257
+ if (!(await orgIsLive(t, conv.org_id)))
258
+ return null;
259
+ // stale: an event after the armed seq other than a run-less side-call usage (the predicate of
260
+ // isIdleNeutralEvent, in SQL)
261
+ const later = await t
262
+ .selectFrom("conversation_events")
263
+ .select("seq")
264
+ .where("conversation_id", "=", conversationId)
265
+ .where("seq", ">", String(armedSeq))
266
+ .where((eb) => eb.not(eb.and([eb("type", "=", "usage"), eb("run_id", "is", null)])))
267
+ .limit(1)
268
+ .executeTakeFirst();
269
+ if (later)
270
+ return null;
271
+ const active = await t
272
+ .selectFrom("runs")
273
+ .select("id")
274
+ .where("conversation_id", "=", conversationId)
275
+ .where("status", "in", ACTIVE_RUN_STATUSES)
276
+ .limit(1)
277
+ .executeTakeFirst();
278
+ if (active)
279
+ return null;
280
+ const unconsumed = await t
281
+ .selectFrom("conversation_events")
282
+ .select("seq")
283
+ .where("conversation_id", "=", conversationId)
284
+ .where("type", "=", "user_message")
285
+ .where("seq", ">", conv.consumed_seq)
286
+ .limit(1)
287
+ .executeTakeFirst();
288
+ if (unconsumed)
289
+ return null;
290
+ const head = await t
291
+ .selectFrom("conversation_queue")
292
+ .select("id")
293
+ .where("conversation_id", "=", conversationId)
294
+ .limit(1)
295
+ .executeTakeFirst();
296
+ if (head)
297
+ return null;
298
+ const agent = await t
299
+ .selectFrom("agents")
300
+ .select(["current_version", "deleted_at"])
301
+ .where("id", "=", conv.agent_id)
302
+ .where("org_id", "=", conv.org_id)
303
+ .executeTakeFirst();
304
+ if (!agent || agent.deleted_at !== null)
305
+ return null;
306
+ // the run runs as the owner: only while they can still use the conversation (ensureRunIn's rule)
307
+ if (!(await authorCanSend(t, conversationId, conv.account_id)))
308
+ return null;
309
+ const jobId = await this.jobIdFor(conversationId, Number(conv.consumed_seq));
310
+ const runId = randomUUID();
311
+ if (!(await this.oweJob(conversationId, runId, jobId.id, "chat", conv.org_id)))
312
+ return null;
313
+ await t
314
+ .insertInto("runs")
315
+ .values({
316
+ id: runId,
317
+ conversation_id: conversationId,
318
+ status: "queued",
319
+ agent_version: agent.current_version,
320
+ trigger_account_id: conv.account_id,
321
+ trigger_seq: Number(conv.consumed_seq),
322
+ job_id: jobId.recorded,
323
+ compact: true,
324
+ compact_origin: "idle",
194
325
  })
195
326
  .execute();
196
327
  return runId;
@@ -242,9 +373,22 @@ let RunQueue = class RunQueue {
242
373
  accountId: newest.payload.authorAccountId,
243
374
  };
244
375
  // an active run (one waiting for approval or an answer too) takes what arrives at its next
245
- // step or is followed by the next run after its end
246
- if (await this.activeRun(t, conversationId))
247
- return null;
376
+ // step or is followed by the next run after its end; an idle compact run is preempted instead
377
+ const active = await this.activeRun(t, conversationId);
378
+ if (active) {
379
+ if (active.compact_origin !== "idle")
380
+ return null;
381
+ if (!(await this.inputPendingIn(conversationId, conv)))
382
+ return null;
383
+ if (!(await this.endQueuedIdleIn(conversationId, active, st))) {
384
+ st.preempt = active.id;
385
+ return null;
386
+ }
387
+ // the idle run is over: the input's run is decided below, as on an idle conversation. Rarely
388
+ // the input was a queue head that dispatchQueuedIn then pauses on (a skill that can no
389
+ // longer be invoked): the idle run is ended for nothing, which is harmless (the next run's
390
+ // finish arms again)
391
+ }
248
392
  if (!last || Number(last.seq) <= Number(conv.consumed_seq)) {
249
393
  // Nothing unconsumed: the queue's head goes out when the queue is not paused. Interjections
250
394
  // are always unconsumed messages, so the queue never jumps ahead of them.
@@ -383,6 +527,104 @@ let RunQueue = class RunQueue {
383
527
  }
384
528
  return runId;
385
529
  }
530
+ /**
531
+ * {@link ensureRun}'s check while a worker holds the conversation (idle compaction spec §5.2,
532
+ * S2): the id of the active idle compact run when input is pending, else null. Reads only (no row
533
+ * lock): a run that ends meanwhile gets a stop it never hears, and its finish's own `ensureRun`
534
+ * starts the input's run. Any active status counts: a queued one is claimed by the lock holder,
535
+ * whose watch reads the stored stop when it starts the compaction.
536
+ */
537
+ // org-filter: ensure-run is keyed by a kernel-resolved conversation id (after a write that checked
538
+ // the org, or an owed outbox job); the conversation's own org is read from its row
539
+ async preemptIdleIn(conversationId) {
540
+ const t = this.db;
541
+ const idle = await t
542
+ .selectFrom("runs")
543
+ .select("id")
544
+ .where("conversation_id", "=", conversationId)
545
+ .where("status", "in", ACTIVE_RUN_STATUSES)
546
+ .where("compact_origin", "=", "idle")
547
+ .executeTakeFirst();
548
+ if (!idle)
549
+ return null;
550
+ const conv = await t
551
+ .selectFrom("conversations")
552
+ .select(["consumed_seq", "org_id", "queue_paused", "account_id", "kind", "deleted_at"])
553
+ .where("id", "=", conversationId)
554
+ .executeTakeFirst();
555
+ if (conv?.kind !== "chat" || !isLive(conv.deleted_at))
556
+ return null;
557
+ return (await this.inputPendingIn(conversationId, conv)) ? idle.id : null;
558
+ }
559
+ /**
560
+ * Whether input waits for a chat conversation (idle compaction spec §5.2): an unconsumed message,
561
+ * a queue head that would go out (queue not paused, its author can still send), or a wake-eligible
562
+ * finished background task or delivery outside its wake window. Reads only: a wake inside its
563
+ * window owes nothing here (the idle run's finish re-derives it).
564
+ */
565
+ async inputPendingIn(conversationId, conv) {
566
+ const t = this.db;
567
+ const message = await t
568
+ .selectFrom("conversation_events")
569
+ .select("seq")
570
+ .where("conversation_id", "=", conversationId)
571
+ .where("type", "=", "user_message")
572
+ .where("seq", ">", conv.consumed_seq)
573
+ .limit(1)
574
+ .executeTakeFirst();
575
+ if (message)
576
+ return true;
577
+ if (!conv.queue_paused) {
578
+ const head = await t
579
+ .selectFrom("conversation_queue")
580
+ .select("id")
581
+ .where("conversation_id", "=", conversationId)
582
+ .limit(1)
583
+ .executeTakeFirst();
584
+ if (head)
585
+ return authorCanSend(t, conversationId, conv.account_id);
586
+ }
587
+ const wake = await wakeDecisionIn(t, { id: conversationId, orgId: conv.org_id, rootId: conversationId }, Number(conv.consumed_seq), this.config.get().runtime.wakeOnBackgroundTask, (accountId) => authorCanSend(t, conversationId, accountId));
588
+ return wake?.kind === "wake";
589
+ }
590
+ /**
591
+ * Ends a `queued` idle compact run no worker started yet (no `run_started`), in
592
+ * {@link ensureRunIn}'s transaction under the conversation row lock: `run_aborted { byAccountId:
593
+ * null, reason: "superseded" }`, which pauses nothing (S3). True when it did; false when a worker
594
+ * already started it (or it is past `queued`): the caller sends the stop after the commit. A
595
+ * worker that read it as queued re-checks it under the row locks before its `run_started`
596
+ * ({@link abortQueuedIn}'s rule).
597
+ */
598
+ async endQueuedIdleIn(conversationId, active, st) {
599
+ if (active.status !== "queued")
600
+ return false;
601
+ const started = await this.db
602
+ .selectFrom("conversation_events")
603
+ .select("seq")
604
+ .where("conversation_id", "=", conversationId)
605
+ .where("idem_key", "=", `run_started:${active.id}`)
606
+ .executeTakeFirst();
607
+ if (started)
608
+ return false;
609
+ const toSeq = await this.finisher.finishIn({
610
+ conversationId,
611
+ runId: active.id,
612
+ status: "aborted",
613
+ consumed: null,
614
+ event: { type: "run_aborted", payload: { byAccountId: null, reason: "superseded" } },
615
+ });
616
+ if (toSeq !== null)
617
+ st.superseded = { runId: active.id, toSeq };
618
+ return true;
619
+ }
620
+ /**
621
+ * Sends the `superseded` stop of an idle compact run, after the commit that decided it. A stop
622
+ * already requested (a person's, racing the input) is left as it is: it is never relabelled
623
+ * (SET NX on the marker, {@link RunAbort.requestIfAbsent}).
624
+ */
625
+ async supersede(runId) {
626
+ await this.abort.requestIfAbsent(runId, null, { reason: "superseded" });
627
+ }
386
628
  /**
387
629
  * The job id of a new run for `seq` (in {@link ensureRunIn}'s transaction, read from PG only):
388
630
  * the trigger's `runJobId` for its first run; a later run of the same trigger (a run that hit its
@@ -728,7 +970,7 @@ let RunQueue = class RunQueue {
728
970
  activeRun(t, conversationId) {
729
971
  return t
730
972
  .selectFrom("runs")
731
- .select(["id", "status", "trigger_seq", "job_id"])
973
+ .select(["id", "status", "trigger_seq", "job_id", "compact_origin"])
732
974
  .where("conversation_id", "=", conversationId)
733
975
  .where("status", "in", ACTIVE_RUN_STATUSES)
734
976
  .executeTakeFirst();
@@ -755,9 +997,15 @@ let RunQueue = class RunQueue {
755
997
  __decorate([
756
998
  Transactional({ propagation: "requires_new" })
757
999
  ], RunQueue.prototype, "startCompactionIn", null);
1000
+ __decorate([
1001
+ Transactional({ propagation: "requires_new" })
1002
+ ], RunQueue.prototype, "startIdleCompactionIn", null);
758
1003
  __decorate([
759
1004
  Transactional({ propagation: "requires_new" })
760
1005
  ], RunQueue.prototype, "ensureRunIn", null);
1006
+ __decorate([
1007
+ Transactional({ propagation: "requires_new" })
1008
+ ], RunQueue.prototype, "preemptIdleIn", null);
761
1009
  __decorate([
762
1010
  Transactional({ propagation: "mandatory" })
763
1011
  ], RunQueue.prototype, "oweHeldTreeIn", null);
@@ -778,8 +1026,9 @@ RunQueue = __decorate([
778
1026
  __param(6, Inject(KERNEL_LOGGER)),
779
1027
  __param(7, Inject(TransactionHost)),
780
1028
  __param(8, Inject(KernelConfigService)),
781
- __param(9, Optional()),
782
- __param(9, Inject(ENSURE_RUN_FAILS))
1029
+ __param(9, Inject(RunAbort)),
1030
+ __param(10, Optional()),
1031
+ __param(10, Inject(ENSURE_RUN_FAILS))
783
1032
  ], RunQueue);
784
1033
  export { RunQueue };
785
1034
  /** The conversation's owner is active and can still see its agent (`isAccessible`'s rule). */
@@ -14,6 +14,8 @@ import { RunAbort } from "./abort.js";
14
14
  import { KyselyCheckpointSaver } from "./checkpointer.js";
15
15
  import { CompactionService } from "./compaction.service.js";
16
16
  import { ConversationLock } from "./conversation-lock.js";
17
+ import { IdleArm } from "./idle-arm.js";
18
+ import { IdleReturn } from "./idle-return.js";
17
19
  import { PluginContextService } from "./plugin-context.service.js";
18
20
  import { ProjectKnowledgeService } from "./project/knowledge.service.js";
19
21
  import { ProviderRegistry } from "./providers.js";
@@ -91,6 +93,10 @@ export declare class RunWorker {
91
93
  readonly txHost: TransactionHost;
92
94
  /** The steps' live drafts this process writes for the runs it executes. */
93
95
  private readonly drafts;
96
+ /** A chat run's finish decides, outside any transaction, whether it arms idle compaction. */
97
+ private readonly idleArm;
98
+ /** A chat run's start logs a return to an idle conversation (best effort). */
99
+ private readonly idleReturn;
94
100
  private readonly hooks?;
95
101
  /** The two run queues' BullMQ workers (spec §7.4), once {@link start}ed on the worker role. */
96
102
  private workers;
@@ -125,7 +131,11 @@ export declare class RunWorker {
125
131
  /** The run's resolved tools, for the plugin context's `tools` (chat runs with providers). */
126
132
  tools: Pick<ToolRegistry, "forAgent">, execution: RunExecution, finisher: Pick<RunFinish, "finish">, txHost: TransactionHost,
127
133
  /** The steps' live drafts this process writes for the runs it executes. */
128
- drafts: RunDrafts, hooks?: RunHooks | undefined);
134
+ drafts: RunDrafts,
135
+ /** A chat run's finish decides, outside any transaction, whether it arms idle compaction. */
136
+ idleArm: Pick<IdleArm, "decide">,
137
+ /** A chat run's start logs a return to an idle conversation (best effort). */
138
+ idleReturn: Pick<IdleReturn, "record">, hooks?: RunHooks | undefined);
129
139
  private get db();
130
140
  /**
131
141
  * Starts consuming (worker role only): `workers` are the `@Processor` workers of both run queues
@@ -191,12 +201,15 @@ export declare class RunWorker {
191
201
  process(job: Job<RunJobData>, token: string | undefined): Promise<ProcessResult>;
192
202
  private execute;
193
203
  /**
194
- * A manual compaction run (context compaction spec §4.7): starts it (`run_started` with
195
- * `trigger: "compact"`, no skills/run/plugin context — nothing reaches the model as a request),
196
- * runs the shared compaction execution with the conversation's effective definition, and writes
197
- * the terminal state. The run records the summary and its usage only; nothing is absorbed and no
198
- * model step runs. A person's stop aborts it (`run_aborted`, no partial summary); a shutdown or a
199
- * lost lease leaves it to another replica.
204
+ * A compaction run (context compaction spec §4.7, a person's; idle compaction spec §5.1, the
205
+ * idle job's): starts it (`run_started` with `trigger: "compact"`, and `compactOrigin: "idle"`
206
+ * for an idle one; no skills/run/plugin context — nothing reaches the model as a request), runs
207
+ * the shared compaction execution with the conversation's effective definition (an idle run
208
+ * requires the in-context summary and never falls back to the transcript), and writes the
209
+ * terminal state. The run records the summary and its usage only; nothing is absorbed and no
210
+ * model step runs. A person's stop aborts it (`run_aborted`, no partial summary), and so does
211
+ * input preempting an idle run (`reason: "superseded"`, no account); a shutdown or a lost lease
212
+ * leaves it to another replica.
200
213
  */
201
214
  private executeCompaction;
202
215
  private completed;
@@ -222,7 +235,8 @@ export declare class RunWorker {
222
235
  /**
223
236
  * `run_started` under the conversation row lock, with the model / effort switch in effect then
224
237
  * (a chat run's `saved` version under the conversation's selection): what the run uses. A
225
- * `compact` run is marked `trigger: "compact"` (context compaction spec §4.7).
238
+ * compact run (`compact` its origin) is marked `trigger: "compact"` (context compaction spec
239
+ * §4.7), an idle one also `compactOrigin: "idle"` (absent = manual; idle compaction spec §5.1).
226
240
  */
227
241
  private appendRunStarted;
228
242
  /** {@link fallBackIfUnavailable}'s write: null when the person switched again meanwhile. */
@@ -31,6 +31,8 @@ import { RunAbort } from "./abort.js";
31
31
  import { KyselyCheckpointSaver } from "./checkpointer.js";
32
32
  import { CompactionService } from "./compaction.service.js";
33
33
  import { ConversationLock } from "./conversation-lock.js";
34
+ import { IdleArm } from "./idle-arm.js";
35
+ import { IdleReturn } from "./idle-return.js";
34
36
  import { runDeadline, tightestLimit } from "./limits.js";
35
37
  import { RunError } from "./model-call.js";
36
38
  import { PluginContextService } from "./plugin-context.service.js";
@@ -113,6 +115,8 @@ let RunWorker = class RunWorker {
113
115
  finisher;
114
116
  txHost;
115
117
  drafts;
118
+ idleArm;
119
+ idleReturn;
116
120
  hooks;
117
121
  /** The two run queues' BullMQ workers (spec §7.4), once {@link start}ed on the worker role. */
118
122
  workers = [];
@@ -147,7 +151,11 @@ let RunWorker = class RunWorker {
147
151
  /** The run's resolved tools, for the plugin context's `tools` (chat runs with providers). */
148
152
  tools, execution, finisher, txHost,
149
153
  /** The steps' live drafts this process writes for the runs it executes. */
150
- drafts, hooks) {
154
+ drafts,
155
+ /** A chat run's finish decides, outside any transaction, whether it arms idle compaction. */
156
+ idleArm,
157
+ /** A chat run's start logs a return to an idle conversation (best effort). */
158
+ idleReturn, hooks) {
151
159
  this.kdb = kdb;
152
160
  this.eventLog = eventLog;
153
161
  this.lock = lock;
@@ -174,6 +182,8 @@ let RunWorker = class RunWorker {
174
182
  this.finisher = finisher;
175
183
  this.txHost = txHost;
176
184
  this.drafts = drafts;
185
+ this.idleArm = idleArm;
186
+ this.idleReturn = idleReturn;
177
187
  this.hooks = hooks;
178
188
  this.loop = loops.create(steps.deps);
179
189
  }
@@ -411,6 +421,7 @@ let RunWorker = class RunWorker {
411
421
  "waited_ms",
412
422
  "budget_run_id",
413
423
  "compact",
424
+ "compact_origin",
414
425
  ])
415
426
  .where("id", "=", runId)
416
427
  .executeTakeFirst();
@@ -690,6 +701,10 @@ let RunWorker = class RunWorker {
690
701
  const toSeq = started.toSeq;
691
702
  if (toSeq !== undefined)
692
703
  await this.eventLog.notify(conversationId, toSeq);
704
+ // a return to an idle conversation (idle compaction spec S11): off the run's path, never
705
+ // throws; this branch is a non-compact run's first start
706
+ if (conv.kind === "chat")
707
+ this.track(this.idleReturn.record(conv, runId));
693
708
  }
694
709
  // Skills catalog snapshot (ruling M17): written before the run is running, and again on a
695
710
  // crash retry (deduped by its idem key). Both records re-read the run under the conversation
@@ -919,7 +934,14 @@ let RunWorker = class RunWorker {
919
934
  // 超时只消费 loop 实际吸收的消息,不按触发消息兜底(R34):截止时间可能在第一次吸收之前就已过
920
935
  // (如续跑时已超过 started_at + maxRunSeconds),这些消息没有被回复,留给结束后的 ensureRun 起新一轮。
921
936
  const consumed = Math.max(outcome.consumedUpToSeq, startConsumed);
922
- await this.finish(conversationId, runId, "completed", consumed, { type: "run_finished", payload: { reason: outcome.kind, consumedUpToSeq: consumed } }, true, false);
937
+ // idle compaction spec §4.2 (S4): decided before the terminal transaction, never throws
938
+ const idleCompaction = await this.idleArm.decide(run, conv, outcome.kind);
939
+ // decide awaited (possibly the model registry): the lease may have gone meanwhile
940
+ if (state.abandoned)
941
+ return "abandoned";
942
+ if (state.leaseLost)
943
+ return "interrupted";
944
+ await this.finish(conversationId, runId, "completed", consumed, { type: "run_finished", payload: { reason: outcome.kind, consumedUpToSeq: consumed } }, true, false, idleCompaction);
923
945
  this.completed(conversationId, runId, outcome.kind);
924
946
  break;
925
947
  }
@@ -927,10 +949,13 @@ let RunWorker = class RunWorker {
927
949
  // completed / max_steps / budget: the loop always absorbed the trigger message; still
928
950
  // floor to it
929
951
  const consumed = Math.max(outcome.consumedUpToSeq, Number(run.trigger_seq));
930
- await this.finish(conversationId, runId, "completed", consumed, {
931
- type: "run_finished",
932
- payload: { reason: outcome.kind, consumedUpToSeq: consumed },
933
- });
952
+ const idleCompaction = await this.idleArm.decide(run, conv, outcome.kind);
953
+ // decide awaited (possibly the model registry): the lease may have gone meanwhile
954
+ if (state.abandoned)
955
+ return "abandoned";
956
+ if (state.leaseLost)
957
+ return "interrupted";
958
+ await this.finish(conversationId, runId, "completed", consumed, { type: "run_finished", payload: { reason: outcome.kind, consumedUpToSeq: consumed } }, true, true, idleCompaction);
934
959
  this.completed(conversationId, runId, outcome.kind);
935
960
  }
936
961
  }
@@ -942,21 +967,26 @@ let RunWorker = class RunWorker {
942
967
  }
943
968
  }
944
969
  /**
945
- * A manual compaction run (context compaction spec §4.7): starts it (`run_started` with
946
- * `trigger: "compact"`, no skills/run/plugin context — nothing reaches the model as a request),
947
- * runs the shared compaction execution with the conversation's effective definition, and writes
948
- * the terminal state. The run records the summary and its usage only; nothing is absorbed and no
949
- * model step runs. A person's stop aborts it (`run_aborted`, no partial summary); a shutdown or a
950
- * lost lease leaves it to another replica.
970
+ * A compaction run (context compaction spec §4.7, a person's; idle compaction spec §5.1, the
971
+ * idle job's): starts it (`run_started` with `trigger: "compact"`, and `compactOrigin: "idle"`
972
+ * for an idle one; no skills/run/plugin context — nothing reaches the model as a request), runs
973
+ * the shared compaction execution with the conversation's effective definition (an idle run
974
+ * requires the in-context summary and never falls back to the transcript), and writes the
975
+ * terminal state. The run records the summary and its usage only; nothing is absorbed and no
976
+ * model step runs. A person's stop aborts it (`run_aborted`, no partial summary), and so does
977
+ * input preempting an idle run (`reason: "superseded"`, no account); a shutdown or a lost lease
978
+ * leaves it to another replica.
951
979
  */
952
980
  async executeCompaction(run, conv, agent, saved, startedAt, state) {
953
981
  const runId = run.id;
954
982
  const conversationId = conv.id;
983
+ // a compact run from before 0195 (no origin) is a person's
984
+ const origin = run.compact_origin ?? "manual";
955
985
  const existingStart = await this.eventLog.findByIdem(conversationId, `run_started:${runId}`);
956
986
  if (run.status === "queued" || startedAt === null) {
957
987
  if (!existingStart) {
958
988
  await this.hooks?.beforeRunStarted?.(runId, conversationId);
959
- const started = await this.appendRunStarted(conversationId, run, agent, saved, true);
989
+ const started = await this.appendRunStarted(conversationId, run, agent, saved, origin);
960
990
  // a stop that ended the run meanwhile (a queued run's direct abort) wins
961
991
  if (started.terminal)
962
992
  return "finished";
@@ -981,9 +1011,11 @@ let RunWorker = class RunWorker {
981
1011
  const ac = new AbortController();
982
1012
  let abortedBy;
983
1013
  let abortDetail;
984
- const unwatch = await this.abort.watch(runId, (by, detail) => {
1014
+ let abortReason;
1015
+ const unwatch = await this.abort.watch(runId, (by, detail, reason) => {
985
1016
  abortedBy = by;
986
1017
  abortDetail = detail;
1018
+ abortReason = reason;
987
1019
  ac.abort();
988
1020
  });
989
1021
  // a shutdown (or a lost lease, which aborts this signal too) stops at the stream boundary
@@ -1009,7 +1041,9 @@ let RunWorker = class RunWorker {
1009
1041
  conversationKind: "chat",
1010
1042
  absorbedUpToSeq: Number(consumed_seq),
1011
1043
  signal: ac.signal,
1012
- });
1044
+ },
1045
+ // R13: an idle run requires the in-context summary and never sets `manual`
1046
+ origin);
1013
1047
  }
1014
1048
  catch (err) {
1015
1049
  if (state.abandoned)
@@ -1024,11 +1058,14 @@ let RunWorker = class RunWorker {
1024
1058
  }
1025
1059
  await this.finish(conversationId, runId, "aborted", null, {
1026
1060
  type: "run_aborted",
1027
- payload: {
1028
- byAccountId: abortedBy,
1029
- reason: "user",
1030
- ...(abortDetail !== undefined && { detail: abortDetail }),
1031
- },
1061
+ // input preempted an idle run (idle compaction spec §5.2): no account, no queue pause
1062
+ payload: abortReason === "superseded"
1063
+ ? { byAccountId: null, reason: "superseded" }
1064
+ : {
1065
+ byAccountId: abortedBy,
1066
+ reason: "user",
1067
+ ...(abortDetail !== undefined && { detail: abortDetail }),
1068
+ },
1032
1069
  });
1033
1070
  return "finished";
1034
1071
  }
@@ -1132,11 +1169,12 @@ let RunWorker = class RunWorker {
1132
1169
  /**
1133
1170
  * `run_started` under the conversation row lock, with the model / effort switch in effect then
1134
1171
  * (a chat run's `saved` version under the conversation's selection): what the run uses. A
1135
- * `compact` run is marked `trigger: "compact"` (context compaction spec §4.7).
1172
+ * compact run (`compact` its origin) is marked `trigger: "compact"` (context compaction spec
1173
+ * §4.7), an idle one also `compactOrigin: "idle"` (absent = manual; idle compaction spec §5.1).
1136
1174
  */
1137
1175
  async appendRunStarted(conversationId, run,
1138
1176
  /** The definition so far (a sub-agent's frozen one is final). */
1139
- current, saved, compact = false) {
1177
+ current, saved, compact = null) {
1140
1178
  const t = this.db;
1141
1179
  if (await this.endedUnderLocks(conversationId, run.id)) {
1142
1180
  return { toSeq: undefined, agent: current, terminal: true };
@@ -1161,8 +1199,11 @@ let RunWorker = class RunWorker {
1161
1199
  agentVersion: run.agent_version,
1162
1200
  model: agent.model,
1163
1201
  triggerAccountId: run.trigger_account_id,
1164
- ...(compact
1165
- ? { trigger: "compact" }
1202
+ ...(compact !== null
1203
+ ? {
1204
+ trigger: "compact",
1205
+ ...(compact === "idle" && { compactOrigin: "idle" }),
1206
+ }
1166
1207
  : {
1167
1208
  ...(boundary?.type === "background_task_finished" && {
1168
1209
  trigger: "background_task",
@@ -1237,8 +1278,11 @@ let RunWorker = class RunWorker {
1237
1278
  * 写终态(见 `finishRun`:运行仍未结束才写,同一事务内推进 `consumed_seq` 并更新 `runs.status`),
1238
1279
  * 提交后发布会话通知,然后调用测试钩子。返回终态事件 seq;运行已是终态 → null。
1239
1280
  */
1240
- async finish(conversationId, runId, status, consumed, event, hook = true, floorToTrigger = true) {
1241
- // the terminal transaction also writes the run's open fork report and cancels its waits
1281
+ async finish(conversationId, runId, status, consumed, event, hook = true, floorToTrigger = true,
1282
+ /** A chat run's armed idle compaction intent ({@link IdleArm.decide}). */
1283
+ idleCompaction) {
1284
+ // the terminal transaction also writes the run's open fork report and cancels its waits, and
1285
+ // owes the idle compaction job when the run armed one
1242
1286
  const toSeq = await this.finisher.finish({
1243
1287
  conversationId,
1244
1288
  runId,
@@ -1246,6 +1290,7 @@ let RunWorker = class RunWorker {
1246
1290
  consumed,
1247
1291
  event,
1248
1292
  floorToTrigger,
1293
+ ...(idleCompaction !== undefined && { idleCompaction }),
1249
1294
  });
1250
1295
  if (hook)
1251
1296
  await this.hooks?.beforeRelease?.(runId, conversationId);
@@ -1291,7 +1336,9 @@ RunWorker = __decorate([
1291
1336
  __param(25, Inject(RunFinish)),
1292
1337
  __param(26, Inject(TransactionHost)),
1293
1338
  __param(27, Inject(RunDrafts)),
1294
- __param(28, Optional()),
1295
- __param(28, Inject(RUN_HOOKS))
1339
+ __param(28, Inject(IdleArm)),
1340
+ __param(29, Inject(IdleReturn)),
1341
+ __param(30, Optional()),
1342
+ __param(30, Inject(RUN_HOOKS))
1296
1343
  ], RunWorker);
1297
1344
  export { RunWorker };