@capybara-hq/kernel 0.1.0-rc.34 → 0.1.0-rc.35

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 (44) hide show
  1. package/dist/admin/outbox-dead.service.d.ts +2 -0
  2. package/dist/admin/outbox-dead.service.js +34 -0
  3. package/dist/catalog/marketplaces.service.d.ts +1 -1
  4. package/dist/conversations/conversations.service.d.ts +3 -3
  5. package/dist/conversations/conversations.service.js +58 -29
  6. package/dist/db/kernel-schema.d.ts +8 -0
  7. package/dist/infra/database/transaction-host.d.ts +1 -0
  8. package/dist/infra/database/transaction-host.js +13 -2
  9. package/dist/infra/outbox/registry.d.ts +17 -0
  10. package/dist/infra/outbox/registry.js +11 -0
  11. package/dist/local-devices/local-device-gateway.d.ts +1 -1
  12. package/dist/local-devices/local-device-gateway.js +1 -1
  13. package/dist/local-devices/local-device-provider.d.ts +2 -2
  14. package/dist/local-devices/local-device-provider.js +7 -5
  15. package/dist/orgs/offboarding.d.ts +2 -0
  16. package/dist/orgs/offboarding.js +4 -0
  17. package/dist/orgs/orgs.service.d.ts +3 -1
  18. package/dist/orgs/orgs.service.js +23 -10
  19. package/dist/runtime/checkpointer.js +3 -0
  20. package/dist/runtime/context/compaction.js +5 -5
  21. package/dist/runtime/conversation-lock.d.ts +4 -11
  22. package/dist/runtime/conversation-lock.js +14 -18
  23. package/dist/runtime/maintenance.d.ts +3 -1
  24. package/dist/runtime/maintenance.js +17 -10
  25. package/dist/runtime/project/knowledge.service.js +2 -2
  26. package/dist/runtime/run-deletion.d.ts +23 -0
  27. package/dist/runtime/run-deletion.js +130 -0
  28. package/dist/runtime/run-execution.d.ts +23 -0
  29. package/dist/runtime/run-execution.js +105 -0
  30. package/dist/runtime/run-finish.js +17 -4
  31. package/dist/runtime/run-jobs.js +11 -0
  32. package/dist/runtime/run-orphan-check.job.d.ts +12 -12
  33. package/dist/runtime/run-orphan-check.job.js +94 -26
  34. package/dist/runtime/run-queue.js +14 -0
  35. package/dist/runtime/run-worker.d.ts +9 -5
  36. package/dist/runtime/run-worker.js +90 -44
  37. package/dist/runtime/runtime.module.js +6 -0
  38. package/dist/runtime/stream.js +8 -2
  39. package/dist/runtime/subagents/tree-jobs.d.ts +4 -3
  40. package/dist/runtime/subagents/tree-jobs.js +4 -4
  41. package/dist/tools/pipeline.js +7 -1
  42. package/package.json +3 -3
  43. package/src/migrations/0135_run_execution_claim.sql +2 -0
  44. package/src/migrations/0136_run_recovery_cursor.sql +6 -0
@@ -5,6 +5,7 @@ export declare const CONVERSATION_LOCK_TTL_MS = 30000;
5
5
  export interface Lease {
6
6
  readonly conversationId: string;
7
7
  readonly runId: string;
8
+ readonly executionId: string;
8
9
  /** 续租时发现锁已不属于自己(过期后被他人取得,或续租一直失败到过期);此后不再续租。 */
9
10
  readonly lost: boolean;
10
11
  /** 立即续租一次;锁已不属于自己 → false(并标记 lost)。 */
@@ -18,7 +19,7 @@ export interface Lease {
18
19
  }
19
20
  /**
20
21
  * A per-conversation lease on {@link LockService.hold}: key `<prefix><conversationId>`, value the
21
- * holder's run id (other replicas read it with {@link holder}), renewed every TTL/3 by the lock
22
+ * holder's run id plus a unique acquisition id (`holder` exposes the run id), renewed every TTL/3 by the lock
22
23
  * service while held; a crashed holder's key expires within the TTL and another replica can take
23
24
  * it. Built by {@link ConversationLock} (the run lock) and its {@link ConversationLock.scoped}
24
25
  * views (the same lock for another purpose, e.g. the channel delivery `capk:channel-deliver:`).
@@ -30,18 +31,10 @@ export declare class ConversationLeases {
30
31
  constructor(locks: LockService, keyPrefix: string);
31
32
  private lockKey;
32
33
  acquire(conversationId: string, runId: string, ttlMs?: number): Promise<Lease | null>;
33
- /**
34
- * 释放某个运行持有的锁(只在仍由该 runId 持有时删除),不需要 Lease:用于 BullMQ 已判定任务失败
35
- * (例如持有者崩溃、stalled 次数超限)后清理死去持有者留下的锁,不必等 TTL 过期。
36
- */
37
- releaseFor(conversationId: string, runId: string): Promise<void>;
38
- /** 当前持有者的 runId;无人持有 → null。 */
34
+ /** The current holder's run id, independent of its unique acquisition token. */
39
35
  holder(conversationId: string): Promise<string | null>;
40
36
  }
41
- /**
42
- * 会话级运行锁(spec 4.3「同一会话同一时刻只跑一轮」):Redis 键 `capk:conv-run:<id>`,值为 runId,
43
- * 带 TTL,由 {@link LockService} 每 TTL/3 续租。持有方崩溃时停止续租,锁在 TTL 后过期,其他副本可以取得。
44
- */
37
+ /** The run lease: each acquisition has its own token, even when the same run is taken over. */
45
38
  export declare class ConversationLock extends ConversationLeases {
46
39
  constructor(locks: LockService);
47
40
  /** The same per-conversation lease under another key prefix (another purpose). */
@@ -7,6 +7,7 @@ var __decorate = (this && this.__decorate) || function (decorators, target, key,
7
7
  var __param = (this && this.__param) || function (paramIndex, decorator) {
8
8
  return function (target, key) { decorator(target, key, paramIndex); }
9
9
  };
10
+ import { randomUUID } from "node:crypto";
10
11
  import { Inject, Injectable } from "@nestjs/common";
11
12
  import { LockService } from "../infra/lock/lock.service.js";
12
13
  /** 会话运行锁的默认 TTL(毫秒):持有方每 `ttlMs / 3` 续租一次。 */
@@ -15,7 +16,7 @@ export const CONVERSATION_LOCK_TTL_MS = 30_000;
15
16
  const RUN_LOCK_PREFIX = "capk:conv-run:";
16
17
  /**
17
18
  * A per-conversation lease on {@link LockService.hold}: key `<prefix><conversationId>`, value the
18
- * holder's run id (other replicas read it with {@link holder}), renewed every TTL/3 by the lock
19
+ * holder's run id plus a unique acquisition id (`holder` exposes the run id), renewed every TTL/3 by the lock
19
20
  * service while held; a crashed holder's key expires within the TTL and another replica can take
20
21
  * it. Built by {@link ConversationLock} (the run lock) and its {@link ConversationLock.scoped}
21
22
  * views (the same lock for another purpose, e.g. the channel delivery `capk:channel-deliver:`).
@@ -32,27 +33,25 @@ export class ConversationLeases {
32
33
  return `${this.keyPrefix}${conversationId}`;
33
34
  }
34
35
  async acquire(conversationId, runId, ttlMs = CONVERSATION_LOCK_TTL_MS) {
35
- const held = await this.locks.hold(this.lockKey(conversationId), runId, ttlMs);
36
+ const executionId = randomUUID();
37
+ const held = await this.locks.hold(this.lockKey(conversationId), `${runId}/${executionId}`, ttlMs);
36
38
  if (!held)
37
39
  return null;
38
- return toLease(held, conversationId, runId);
40
+ return toLease(held, conversationId, runId, executionId);
39
41
  }
40
- /**
41
- * 释放某个运行持有的锁(只在仍由该 runId 持有时删除),不需要 Lease:用于 BullMQ 已判定任务失败
42
- * (例如持有者崩溃、stalled 次数超限)后清理死去持有者留下的锁,不必等 TTL 过期。
43
- */
44
- async releaseFor(conversationId, runId) {
45
- await this.locks.releaseIf(this.lockKey(conversationId), runId);
46
- }
47
- /** 当前持有者的 runId;无人持有 → null。 */
48
- holder(conversationId) {
49
- return this.locks.holderOf(this.lockKey(conversationId));
42
+ /** The current holder's run id, independent of its unique acquisition token. */
43
+ async holder(conversationId) {
44
+ const value = await this.locks.holderOf(this.lockKey(conversationId));
45
+ return value === null
46
+ ? null
47
+ : value.slice(0, value.lastIndexOf("/") < 0 ? value.length : value.lastIndexOf("/"));
50
48
  }
51
49
  }
52
- function toLease(held, conversationId, runId) {
50
+ function toLease(held, conversationId, runId, executionId) {
53
51
  return {
54
52
  conversationId,
55
53
  runId,
54
+ executionId,
56
55
  get lost() {
57
56
  return held.lost.aborted;
58
57
  },
@@ -67,10 +66,7 @@ function toLease(held, conversationId, runId) {
67
66
  },
68
67
  };
69
68
  }
70
- /**
71
- * 会话级运行锁(spec 4.3「同一会话同一时刻只跑一轮」):Redis 键 `capk:conv-run:<id>`,值为 runId,
72
- * 带 TTL,由 {@link LockService} 每 TTL/3 续租。持有方崩溃时停止续租,锁在 TTL 后过期,其他副本可以取得。
73
- */
69
+ /** The run lease: each acquisition has its own token, even when the same run is taken over. */
74
70
  let ConversationLock = class ConversationLock extends ConversationLeases {
75
71
  constructor(locks) {
76
72
  super(locks, RUN_LOCK_PREFIX);
@@ -9,6 +9,7 @@ import { SandboxService } from "../sandbox/sandbox.service.js";
9
9
  import { ScheduledTaskFirer } from "../schedules/fire.js";
10
10
  import { DeviceOpResolver } from "../tools/device-op-resolver.js";
11
11
  import { ToolDrift } from "../tools/drift.js";
12
+ import { RunDeletion } from "./run-deletion.js";
12
13
  import { RunQueue } from "./run-queue.js";
13
14
  import { Waits } from "./waits.js";
14
15
  export { MAINTENANCE_QUEUE_NAME } from "./maintenance-queue.js";
@@ -33,6 +34,7 @@ export declare class MaintenanceProcessor extends WorkerHost<Worker> {
33
34
  private readonly sandbox;
34
35
  private readonly drift;
35
36
  private readonly directory;
37
+ private readonly deletion;
36
38
  private readonly offboarding;
37
39
  private readonly runs;
38
40
  private readonly ownedCleanup;
@@ -41,7 +43,7 @@ export declare class MaintenanceProcessor extends WorkerHost<Worker> {
41
43
  private readonly scheduled;
42
44
  private readonly log;
43
45
  private readonly queue;
44
- constructor(waits: Pick<Waits, "processTimeout" | "childFinished" | "stopChildren" | "stopDescendantsOfStopped" | "stopTree">, sandbox: Pick<SandboxService, "destroyDevice" | "resetFileSystem">, drift: Pick<ToolDrift, "check">, directory: Pick<DirectorySync, "runSyncJob">, offboarding: Pick<Offboarding, "stopRun">, runs: Pick<RunQueue, "ensureRun">, ownedCleanup: Pick<OwnedPluginCleanup, "run">, scheduledTasks: Pick<ScheduledTaskFirer, "fire" | "settle">, deviceOps: Pick<DeviceOpResolver, "resolve">, scheduled: Pick<ScheduledRuns, "runNow">, log: Pick<KernelLogger, "error" | "warn">, queue: Pick<Queue, "removeJobScheduler">);
46
+ constructor(waits: Pick<Waits, "processTimeout" | "childFinished" | "stopChildren" | "stopDescendantsOfStopped" | "stopTree">, sandbox: Pick<SandboxService, "destroyDevice" | "resetFileSystem">, drift: Pick<ToolDrift, "check">, directory: Pick<DirectorySync, "runSyncJob">, deletion: Pick<RunDeletion, "stopOrg" | "stopTree">, offboarding: Pick<Offboarding, "stopRun">, runs: Pick<RunQueue, "ensureRun">, ownedCleanup: Pick<OwnedPluginCleanup, "run">, scheduledTasks: Pick<ScheduledTaskFirer, "fire" | "settle">, deviceOps: Pick<DeviceOpResolver, "resolve">, scheduled: Pick<ScheduledRuns, "runNow">, log: Pick<KernelLogger, "error" | "warn">, queue: Pick<Queue, "removeJobScheduler">);
45
47
  /**
46
48
  * Removes the retired job schedulers (`RETIRED_SCHEDULER_IDS`, runtime/retired-schedulers.ts): every fixed-period
47
49
  * maintenance job is a `@LockedCron` / `@LockedInterval` now. Idempotent; called once when a
@@ -34,6 +34,7 @@ import { DRIFT_CONNECTOR_JOB } from "../tools/job-ids.js";
34
34
  import { ToolsModule } from "../tools/tools.module.js";
35
35
  import { MAINTENANCE_QUEUE_NAME } from "./maintenance-queue.js";
36
36
  import { RETIRED_SCHEDULER_IDS } from "./retired-schedulers.js";
37
+ import { RunDeletion, STOP_DELETED_ORG_JOB } from "./run-deletion.js";
37
38
  import { ENSURE_RUN_JOB, RunQueue } from "./run-queue.js";
38
39
  import { RuntimeModule } from "./runtime.module.js";
39
40
  import { DELIVER_TO_PARENT_JOB, processDeliverToParent, processStopTree, STOP_TREE_JOB, } from "./subagents/tree-jobs.js";
@@ -60,6 +61,7 @@ let MaintenanceProcessor = class MaintenanceProcessor extends WorkerHost {
60
61
  sandbox;
61
62
  drift;
62
63
  directory;
64
+ deletion;
63
65
  offboarding;
64
66
  runs;
65
67
  ownedCleanup;
@@ -68,12 +70,13 @@ let MaintenanceProcessor = class MaintenanceProcessor extends WorkerHost {
68
70
  scheduled;
69
71
  log;
70
72
  queue;
71
- constructor(waits, sandbox, drift, directory, offboarding, runs, ownedCleanup, scheduledTasks, deviceOps, scheduled, log, queue) {
73
+ constructor(waits, sandbox, drift, directory, deletion, offboarding, runs, ownedCleanup, scheduledTasks, deviceOps, scheduled, log, queue) {
72
74
  super();
73
75
  this.waits = waits;
74
76
  this.sandbox = sandbox;
75
77
  this.drift = drift;
76
78
  this.directory = directory;
79
+ this.deletion = deletion;
77
80
  this.offboarding = offboarding;
78
81
  this.runs = runs;
79
82
  this.ownedCleanup = ownedCleanup;
@@ -100,6 +103,9 @@ let MaintenanceProcessor = class MaintenanceProcessor extends WorkerHost {
100
103
  }
101
104
  async dispatch(job, token) {
102
105
  switch (job.name) {
106
+ case STOP_DELETED_ORG_JOB:
107
+ await this.deletion.stopOrg(job.data);
108
+ return;
103
109
  case WAIT_TIMEOUT_JOB:
104
110
  await this.waits.processTimeout(job, token);
105
111
  return;
@@ -147,7 +153,7 @@ let MaintenanceProcessor = class MaintenanceProcessor extends WorkerHost {
147
153
  return;
148
154
  // the stops a run's end or a root's delete owes its sub-agent tree (outbox spec §6)
149
155
  case STOP_TREE_JOB:
150
- await processStopTree(this.waits, job.data);
156
+ await processStopTree(this.waits, job.data, this.deletion);
151
157
  return;
152
158
  // a finished sub-agent run's delivery to its parent (transactional outbox spec §6)
153
159
  case DELIVER_TO_PARENT_JOB:
@@ -198,14 +204,15 @@ MaintenanceProcessor = __decorate([
198
204
  __param(1, Inject(SandboxService)),
199
205
  __param(2, Inject(ToolDrift)),
200
206
  __param(3, Inject(DirectorySync)),
201
- __param(4, Inject(Offboarding)),
202
- __param(5, Inject(RunQueue)),
203
- __param(6, Inject(OwnedPluginCleanup)),
204
- __param(7, Inject(ScheduledTaskFirer)),
205
- __param(8, Inject(DeviceOpResolver)),
206
- __param(9, Inject(ScheduledRuns)),
207
- __param(10, Inject(KERNEL_LOGGER)),
208
- __param(11, Inject(getQueueToken(MAINTENANCE_QUEUE_NAME)))
207
+ __param(4, Inject(RunDeletion)),
208
+ __param(5, Inject(Offboarding)),
209
+ __param(6, Inject(RunQueue)),
210
+ __param(7, Inject(OwnedPluginCleanup)),
211
+ __param(8, Inject(ScheduledTaskFirer)),
212
+ __param(9, Inject(DeviceOpResolver)),
213
+ __param(10, Inject(ScheduledRuns)),
214
+ __param(11, Inject(KERNEL_LOGGER)),
215
+ __param(12, Inject(getQueueToken(MAINTENANCE_QUEUE_NAME)))
209
216
  ], MaintenanceProcessor);
210
217
  export { MaintenanceProcessor };
211
218
  /**
@@ -173,8 +173,8 @@ let ProjectKnowledgeService = class ProjectKnowledgeService {
173
173
  });
174
174
  return unavailableProject(bound.project, bound.root, projectUnavailable.unsupported());
175
175
  }
176
- // stat / readFile carry no ceiling: a machine running a wider mode than the org allows is
177
- // not read unasked (exec refuses it too)
176
+ // A machine reporting a wider mode than the org allows is not read unasked. The local
177
+ // provider rechecks the current ceiling on every readFile / stat request as well.
178
178
  if (scope.widerThanAllowed) {
179
179
  this.log.warn("project knowledge not read: the device runs a wider mode than allowed", {
180
180
  ...where,
@@ -0,0 +1,23 @@
1
+ import { BackgroundTaskStopper } from "../background/stop.js";
2
+ import { KernelDb } from "../infra/database/kernel-db.js";
3
+ import { TransactionHost } from "../infra/database/transaction-host.js";
4
+ import { OutboxService } from "../infra/outbox/outbox.service.js";
5
+ import { RunFinish } from "./run-finish.js";
6
+ export declare const STOP_DELETED_ORG_JOB = "stop-deleted-org";
7
+ export interface StopDeletedOrgData {
8
+ orgId: string;
9
+ byAccountId: string;
10
+ }
11
+ /** Platform-owned deletion work: it survives the org's outbox purge and process death. */
12
+ export declare class RunDeletion {
13
+ private readonly db;
14
+ readonly txHost: TransactionHost;
15
+ private readonly outbox;
16
+ private readonly finisher;
17
+ private readonly background;
18
+ constructor(db: KernelDb, txHost: TransactionHost, outbox: OutboxService, finisher: RunFinish, background: BackgroundTaskStopper);
19
+ stopOrg(data: StopDeletedOrgData): Promise<void>;
20
+ stopTree(conversationId: string, byAccountId: string | null): Promise<void>;
21
+ stopDeletedConversation(conversationId: string, byAccountId: string | null): Promise<void>;
22
+ private stopConversationIn;
23
+ }
@@ -0,0 +1,130 @@
1
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
2
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
4
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
5
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
6
+ };
7
+ var __param = (this && this.__param) || function (paramIndex, decorator) {
8
+ return function (target, key) { decorator(target, key, paramIndex); }
9
+ };
10
+ import { Inject, Injectable } from "@nestjs/common";
11
+ import { BackgroundTaskStopper } from "../background/stop.js";
12
+ import { conversationTree } from "../conversations/tree.js";
13
+ import { KernelDb } from "../infra/database/kernel-db.js";
14
+ import { TransactionHost } from "../infra/database/transaction-host.js";
15
+ import { Transactional } from "../infra/database/transactional.decorator.js";
16
+ import { OutboxService } from "../infra/outbox/outbox.service.js";
17
+ import { MAINTENANCE_QUEUE_NAME } from "./maintenance-queue.js";
18
+ import { RunFinish } from "./run-finish.js";
19
+ export const STOP_DELETED_ORG_JOB = "stop-deleted-org";
20
+ /** Platform-owned deletion work: it survives the org's outbox purge and process death. */
21
+ let RunDeletion = class RunDeletion {
22
+ db;
23
+ txHost;
24
+ outbox;
25
+ finisher;
26
+ background;
27
+ constructor(db, txHost, outbox, finisher, background) {
28
+ this.db = db;
29
+ this.txHost = txHost;
30
+ this.outbox = outbox;
31
+ this.finisher = finisher;
32
+ this.background = background;
33
+ }
34
+ async stopOrg(data) {
35
+ const org = await this.db
36
+ .selectFrom("orgs")
37
+ .select("deleted_at")
38
+ .where("id", "=", data.orgId)
39
+ .executeTakeFirst();
40
+ if (!org || org.deleted_at === null)
41
+ return;
42
+ let after = "";
43
+ for (;;) {
44
+ const rows = await this.db
45
+ .selectFrom("conversations")
46
+ .select("id")
47
+ .where("org_id", "=", data.orgId)
48
+ .where("kind", "in", ["chat", "subagent"])
49
+ .where("id", ">", after)
50
+ .orderBy("id")
51
+ .limit(100)
52
+ .execute();
53
+ for (const row of rows) {
54
+ await this.stopConversationIn(row.id, data.byAccountId);
55
+ await this.background.stopForDeletedConversation(row.id);
56
+ }
57
+ if (rows.length < 100)
58
+ return;
59
+ after = rows[rows.length - 1]?.id ?? after;
60
+ }
61
+ }
62
+ async stopTree(conversationId, byAccountId) {
63
+ const root = await this.db
64
+ .selectFrom("conversations")
65
+ .select("deleted_at")
66
+ .where("id", "=", conversationId)
67
+ .executeTakeFirst();
68
+ if (!root || root.deleted_at === null)
69
+ return;
70
+ for (const conv of await conversationTree(this.db.db, conversationId)) {
71
+ await this.stopConversationIn(conv.id, byAccountId);
72
+ await this.background.stopForDeletedConversation(conv.id);
73
+ }
74
+ }
75
+ async stopDeletedConversation(conversationId, byAccountId) {
76
+ const deleted = await this.db
77
+ .selectFrom("conversations as c")
78
+ .innerJoin("orgs as o", "o.id", "c.org_id")
79
+ .select(["c.deleted_at as conversation_deleted", "o.deleted_at as org_deleted"])
80
+ .where("c.id", "=", conversationId)
81
+ .executeTakeFirst();
82
+ if (!deleted || (deleted.conversation_deleted === null && deleted.org_deleted === null))
83
+ return;
84
+ await this.stopConversationIn(conversationId, byAccountId);
85
+ await this.background.stopForDeletedConversation(conversationId);
86
+ }
87
+ async stopConversationIn(conversationId, byAccountId) {
88
+ await this.db
89
+ .selectFrom("conversations")
90
+ .select("id")
91
+ .where("id", "=", conversationId)
92
+ .forUpdate()
93
+ .execute();
94
+ const runs = await this.db
95
+ .selectFrom("runs")
96
+ .select("id")
97
+ .where("conversation_id", "=", conversationId)
98
+ .where("status", "in", ["queued", "running", "waiting"])
99
+ .orderBy("id")
100
+ .execute();
101
+ for (const run of runs) {
102
+ await this.finisher.finishIn({
103
+ conversationId,
104
+ runId: run.id,
105
+ status: "aborted",
106
+ consumed: null,
107
+ event: { type: "run_aborted", payload: { byAccountId, reason: "user" } },
108
+ });
109
+ // Cancellation must still be delivered after the terminal commit revoked its claim.
110
+ await this.outbox.add({
111
+ queue: MAINTENANCE_QUEUE_NAME,
112
+ name: "run-stop",
113
+ jobId: `stop-deleted-run-${run.id}`,
114
+ data: { conversationId, runId: run.id, deleted: true },
115
+ });
116
+ }
117
+ }
118
+ };
119
+ __decorate([
120
+ Transactional({ propagation: "requires_new" })
121
+ ], RunDeletion.prototype, "stopConversationIn", null);
122
+ RunDeletion = __decorate([
123
+ Injectable(),
124
+ __param(0, Inject(KernelDb)),
125
+ __param(1, Inject(TransactionHost)),
126
+ __param(2, Inject(OutboxService)),
127
+ __param(3, Inject(RunFinish)),
128
+ __param(4, Inject(BackgroundTaskStopper))
129
+ ], RunDeletion);
130
+ export { RunDeletion };
@@ -0,0 +1,23 @@
1
+ import { KernelDb } from "../infra/database/kernel-db.js";
2
+ import { TransactionHost } from "../infra/database/transaction-host.js";
3
+ export interface ExecutionClaim {
4
+ runId: string;
5
+ conversationId: string;
6
+ orgId: string;
7
+ rootId: string;
8
+ executionId: string;
9
+ }
10
+ /** Internal interruption: a revoked execution must never write its own terminal failure. */
11
+ export declare class ExecutionRevoked extends Error {
12
+ constructor();
13
+ }
14
+ /** Claims serialize on the same conversation lock as the event log and all fenced writes. */
15
+ export declare class RunExecution {
16
+ private readonly db;
17
+ readonly txHost: TransactionHost;
18
+ constructor(db: KernelDb, txHost: TransactionHost);
19
+ claim(conversationId: string, runId: string, executionId: string, live?: () => boolean): Promise<ExecutionClaim | null>;
20
+ withClaim<T>(claim: ExecutionClaim, live: () => boolean, fn: () => Promise<T>): Promise<T>;
21
+ /** Org, root, current conversation; allow FK references while excluding deletion and writes. */
22
+ private lockLiveConversation;
23
+ }
@@ -0,0 +1,105 @@
1
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
2
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
4
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
5
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
6
+ };
7
+ var __param = (this && this.__param) || function (paramIndex, decorator) {
8
+ return function (target, key) { decorator(target, key, paramIndex); }
9
+ };
10
+ import { Inject, Injectable } from "@nestjs/common";
11
+ import { KernelDb } from "../infra/database/kernel-db.js";
12
+ import { TransactionHost, withTransactionFence } from "../infra/database/transaction-host.js";
13
+ import { Transactional } from "../infra/database/transactional.decorator.js";
14
+ import { rootConversationOf } from "./subagents/child.js";
15
+ /** Internal interruption: a revoked execution must never write its own terminal failure. */
16
+ export class ExecutionRevoked extends Error {
17
+ constructor() {
18
+ super("execution revoked");
19
+ }
20
+ }
21
+ /** Claims serialize on the same conversation lock as the event log and all fenced writes. */
22
+ let RunExecution = class RunExecution {
23
+ db;
24
+ txHost;
25
+ constructor(db, txHost) {
26
+ this.db = db;
27
+ this.txHost = txHost;
28
+ }
29
+ async claim(conversationId, runId, executionId, live = () => true) {
30
+ if (!live())
31
+ return null;
32
+ const conv = await this.db
33
+ .selectFrom("conversations")
34
+ .select("org_id")
35
+ .where("id", "=", conversationId)
36
+ .executeTakeFirst();
37
+ if (!conv)
38
+ return null;
39
+ const rootId = await rootConversationOf(this.db.db, conversationId);
40
+ const claim = { conversationId, runId, executionId, orgId: conv.org_id, rootId };
41
+ if (!(await this.lockLiveConversation(claim)) || !live())
42
+ return null;
43
+ const run = await this.db
44
+ .updateTable("runs")
45
+ .set({ execution_id: executionId })
46
+ .where("id", "=", runId)
47
+ .where("conversation_id", "=", conversationId)
48
+ .where("status", "in", ["queued", "running"])
49
+ .returning("id")
50
+ .executeTakeFirst();
51
+ return run ? claim : null;
52
+ }
53
+ withClaim(claim, live, fn) {
54
+ return withTransactionFence(async () => {
55
+ if (!live() || !(await this.lockLiveConversation(claim)))
56
+ throw new ExecutionRevoked();
57
+ const run = await this.db
58
+ .selectFrom("runs")
59
+ .select("execution_id")
60
+ .where("id", "=", claim.runId)
61
+ .where("conversation_id", "=", claim.conversationId)
62
+ .executeTakeFirst();
63
+ if (run?.execution_id !== claim.executionId || !live())
64
+ throw new ExecutionRevoked();
65
+ }, fn);
66
+ }
67
+ /** Org, root, current conversation; allow FK references while excluding deletion and writes. */
68
+ async lockLiveConversation(claim) {
69
+ const org = await this.db
70
+ .selectFrom("orgs")
71
+ .select("deleted_at")
72
+ .where("id", "=", claim.orgId)
73
+ .forNoKeyUpdate()
74
+ .executeTakeFirst();
75
+ if (!org || org.deleted_at !== null)
76
+ return false;
77
+ const root = await this.db
78
+ .selectFrom("conversations")
79
+ .select("deleted_at")
80
+ .where("id", "=", claim.rootId)
81
+ .forNoKeyUpdate()
82
+ .executeTakeFirst();
83
+ if (!root || root.deleted_at !== null)
84
+ return false;
85
+ if (claim.rootId === claim.conversationId)
86
+ return true;
87
+ const conv = await this.db
88
+ .selectFrom("conversations")
89
+ .select("deleted_at")
90
+ .where("id", "=", claim.conversationId)
91
+ .where("org_id", "=", claim.orgId)
92
+ .forNoKeyUpdate()
93
+ .executeTakeFirst();
94
+ return conv !== undefined && conv.deleted_at === null;
95
+ }
96
+ };
97
+ __decorate([
98
+ Transactional({ propagation: "requires_new" })
99
+ ], RunExecution.prototype, "claim", null);
100
+ RunExecution = __decorate([
101
+ Injectable(),
102
+ __param(0, Inject(KernelDb)),
103
+ __param(1, Inject(TransactionHost))
104
+ ], RunExecution);
105
+ export { RunExecution };
@@ -87,7 +87,18 @@ let RunFinish = class RunFinish {
87
87
  const t = this.kdb.db;
88
88
  const conv = await t
89
89
  .selectFrom("conversations")
90
- .select(["kind", "org_id"])
90
+ .select((eb) => [
91
+ "kind",
92
+ "org_id",
93
+ "deleted_at",
94
+ eb
95
+ .exists(eb
96
+ .selectFrom("orgs")
97
+ .select("orgs.id")
98
+ .whereRef("orgs.id", "=", "conversations.org_id")
99
+ .where("orgs.deleted_at", "is", null))
100
+ .as("org_live"),
101
+ ])
91
102
  .where("id", "=", a.conversationId)
92
103
  .forUpdate()
93
104
  .executeTakeFirst();
@@ -124,7 +135,7 @@ let RunFinish = class RunFinish {
124
135
  .execute();
125
136
  await t
126
137
  .updateTable("runs")
127
- .set({ status: a.status, finished_at: sql `now()` })
138
+ .set({ status: a.status, finished_at: sql `now()`, execution_id: null })
128
139
  .where("id", "=", a.runId)
129
140
  .execute();
130
141
  await this.taskRuns.onRunFinished(a.runId, a.status, failureMessage(a.event));
@@ -137,10 +148,12 @@ let RunFinish = class RunFinish {
137
148
  // what arrived during the run starts the next one after the commit (the run worker's post-job
138
149
  // ensureRun); owed here too, for when that never happens (an eval's hidden conversation never
139
150
  // starts runs)
140
- if (conv && (conv.kind === "chat" || conv.kind === "subagent")) {
151
+ if (conv?.org_live &&
152
+ conv.deleted_at === null &&
153
+ (conv.kind === "chat" || conv.kind === "subagent")) {
141
154
  await oweEnsureRun(this.outbox, a.conversationId, seq, conv.org_id);
142
155
  }
143
- if (conv)
156
+ if (conv?.org_live)
144
157
  await this.oweTreeWork(a, conv.kind, conv.org_id);
145
158
  return seq;
146
159
  }
@@ -207,6 +207,17 @@ let RunResume = class RunResume {
207
207
  .where("id", "=", runId)
208
208
  .forUpdate()
209
209
  .executeTakeFirst();
210
+ const live = await t
211
+ .selectFrom("runs as r")
212
+ .innerJoin("conversations as c", "c.id", "r.conversation_id")
213
+ .innerJoin("orgs as o", "o.id", "c.org_id")
214
+ .select("r.id")
215
+ .where("r.id", "=", runId)
216
+ .where("c.deleted_at", "is", null)
217
+ .where("o.deleted_at", "is", null)
218
+ .executeTakeFirst();
219
+ if (!live)
220
+ return "not-waiting";
210
221
  if (run?.status === "running")
211
222
  return "still-running";
212
223
  if (run?.status !== "waiting")
@@ -9,6 +9,7 @@ import type { KernelLogger } from "../log.js";
9
9
  import { KyselyCheckpointSaver } from "./checkpointer.js";
10
10
  import { ConversationLock } from "./conversation-lock.js";
11
11
  import { QueueLostJobs } from "./queue-lost-jobs.js";
12
+ import { RunDeletion } from "./run-deletion.js";
12
13
  import { RunFinish } from "./run-finish.js";
13
14
  import { RunJobs } from "./run-jobs.js";
14
15
  import { RunQueue } from "./run-queue.js";
@@ -27,7 +28,7 @@ export declare const RUN_ORPHAN_CHECK_BATCH = 500;
27
28
  /**
28
29
  * The most pages one pass reads: a bound on its work. Healthy long runs and queued runs waiting
29
30
  * for a quota slot are passed over page by page, so a real orphan behind them is still reached;
30
- * beyond this many candidates the rest wait for the next minute.
31
+ * the shared cursor resumes after the last inspected row on the next pass.
31
32
  */
32
33
  export declare const RUN_ORPHAN_CHECK_MAX_PAGES = 10;
33
34
  /** The error the canary logs (transactional outbox spec §8.3). */
@@ -46,6 +47,7 @@ export interface OrphanCandidate {
46
47
  orgId: string;
47
48
  kind: ConversationKind;
48
49
  status: "queued" | "running";
50
+ deleted: boolean;
49
51
  /** The run's job id (a resume's `runs.job_id`, else its trigger's) and queue. */
50
52
  jobId: string;
51
53
  queue: string;
@@ -55,16 +57,11 @@ export interface OrphanCandidate {
55
57
  /**
56
58
  * One page of the active runs of chat and sub-agent conversations in `statuses` that entered their
57
59
  * state more than `minAgeMs` ago, by (state start, id), after `after` (an eval's hidden
58
- * conversation drives its runs itself). A deleted org's runs are never candidates, running ones
59
- * included: its deletion purged its owed jobs on purpose, so their absence is no lost job and
60
- * nothing is re-added, and the org's data is invisible from then on, so a running orphan is left
61
- * as it is rather than failed.
60
+ * conversation drives its runs itself). Deleted rows are included for cancellation recovery;
61
+ * their intentionally removed jobs are never interpreted as queue loss or re-added.
62
62
  */
63
63
  export declare function orphanCandidates(db: KernelSchemaDb, statuses: readonly ("queued" | "running")[], minAgeMs: number, limit: number, after?: Pick<OrphanCandidate, "since" | "runId">): Promise<OrphanCandidate[]>;
64
- /**
65
- * Whether the outbox holds the job `jobId` on `queue`: a pending row (it is still owed) or a dead
66
- * one (the outbox gave up on it; the super admin sees it under `outbox_dead` and retries or
67
- * discards it, so it is not a job the queue lost).
64
+ /** Whether delivery is still owed by a pending outbox row; dead copies are not active work.
68
65
  */
69
66
  export declare function jobInOutbox(db: KernelSchemaDb, queue: string, jobId: string): Promise<boolean>;
70
67
  /**
@@ -88,7 +85,7 @@ export declare function queuedRunsWithoutJob(db: KernelSchemaDb, jobExists: (que
88
85
  * `run.orphaned` (its terminal transaction cancels its waits and owes what every run end owes),
89
86
  * then, after the commit, its checkpoints are dropped, its fork child stopped (`run.orphaned`), a
90
87
  * sub-agent's failure delivered to its parent at once and the conversation's next run started.
91
- * - `queued`, with no outbox row either (pending or dead): a canary. Every queued run has its job
88
+ * - `queued`, with no pending or current-generation dead delivery: a canary. Every queued run has its job
92
89
  * owed in its own transaction, so this means Redis lost data. It is logged as an error, counted
93
90
  * for the admin overview ({@link QueueLostJobs}) and its job owed again so the run is not stuck.
94
91
  * Redis is read before each repair's transaction, which then re-reads the run under its
@@ -106,6 +103,7 @@ export declare class RunOrphanCheck {
106
103
  private readonly waits;
107
104
  /** The conversation's next run, after a repaired run's end. */
108
105
  private readonly queue;
106
+ private readonly deletion;
109
107
  private readonly lostJobs;
110
108
  private readonly events;
111
109
  readonly txHost: TransactionHost;
@@ -116,14 +114,16 @@ export declare class RunOrphanCheck {
116
114
  /** A failed sub-agent run reports to its parent at once ({@link Waits.childFinished}). */
117
115
  waits: Pick<Waits, "childFinished">,
118
116
  /** The conversation's next run, after a repaired run's end. */
119
- queue: Pick<RunQueue, "ensureRun">, lostJobs: Pick<QueueLostJobs, "report">, events: KernelEvents, txHost: TransactionHost, config: KernelConfigService, lockService: LockService, log: KernelLogger);
117
+ queue: Pick<RunQueue, "ensureRun">, deletion: Pick<RunDeletion, "stopDeletedConversation">, lostJobs: Pick<QueueLostJobs, "report">, events: KernelEvents, txHost: TransactionHost, config: KernelConfigService, lockService: LockService, log: KernelLogger);
120
118
  private get db();
121
119
  run(): Promise<void>;
122
120
  /** One pass: repairs the orphans it finds (each on its own; a failure is logged). */
123
121
  check(): Promise<RunOrphanCheckResult>;
122
+ private saveCursorIn;
123
+ private hasDeadDelivery;
124
124
  /**
125
125
  * Neither a conversation lock holder nor the run's job in BullMQ (nor, queued, in the outbox: an
126
- * owed row is delivered by the relay, a dead one waits for the super admin).
126
+ * owed row is delivered by the relay; a dead current delivery is settled visibly).
127
127
  */
128
128
  private withoutJobOrHolder;
129
129
  /**