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

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/outbox-dead.service.d.ts +2 -0
  2. package/dist/admin/outbox-dead.service.js +34 -0
  3. package/dist/agents/agents.module.js +3 -0
  4. package/dist/agents/readiness.controller.d.ts +8 -11
  5. package/dist/agents/readiness.controller.js +11 -17
  6. package/dist/agents/readiness.service.d.ts +30 -0
  7. package/dist/agents/readiness.service.js +61 -0
  8. package/dist/catalog/marketplaces.service.d.ts +1 -1
  9. package/dist/conversations/conversations.service.d.ts +3 -3
  10. package/dist/conversations/conversations.service.js +58 -29
  11. package/dist/db/kernel-schema.d.ts +8 -0
  12. package/dist/infra/database/transaction-host.d.ts +1 -0
  13. package/dist/infra/database/transaction-host.js +13 -2
  14. package/dist/infra/outbox/registry.d.ts +17 -0
  15. package/dist/infra/outbox/registry.js +11 -0
  16. package/dist/local-devices/local-device-gateway.d.ts +1 -1
  17. package/dist/local-devices/local-device-gateway.js +1 -1
  18. package/dist/local-devices/local-device-provider.d.ts +2 -2
  19. package/dist/local-devices/local-device-provider.js +7 -5
  20. package/dist/orgs/offboarding.d.ts +2 -0
  21. package/dist/orgs/offboarding.js +4 -0
  22. package/dist/orgs/orgs.service.d.ts +3 -1
  23. package/dist/orgs/orgs.service.js +23 -10
  24. package/dist/platform/ops/agents.ops.d.ts +3 -3
  25. package/dist/platform/ops/agents.ops.js +7 -10
  26. package/dist/runtime/checkpointer.js +3 -0
  27. package/dist/runtime/context/compaction.js +5 -5
  28. package/dist/runtime/conversation-lock.d.ts +4 -11
  29. package/dist/runtime/conversation-lock.js +14 -18
  30. package/dist/runtime/maintenance.d.ts +3 -1
  31. package/dist/runtime/maintenance.js +17 -10
  32. package/dist/runtime/project/knowledge.service.js +2 -2
  33. package/dist/runtime/run-deletion.d.ts +23 -0
  34. package/dist/runtime/run-deletion.js +130 -0
  35. package/dist/runtime/run-execution.d.ts +23 -0
  36. package/dist/runtime/run-execution.js +105 -0
  37. package/dist/runtime/run-finish.js +17 -4
  38. package/dist/runtime/run-jobs.js +11 -0
  39. package/dist/runtime/run-orphan-check.job.d.ts +12 -12
  40. package/dist/runtime/run-orphan-check.job.js +94 -26
  41. package/dist/runtime/run-queue.js +14 -0
  42. package/dist/runtime/run-worker.d.ts +9 -5
  43. package/dist/runtime/run-worker.js +90 -44
  44. package/dist/runtime/runtime.module.js +6 -0
  45. package/dist/runtime/stream.js +8 -2
  46. package/dist/runtime/subagents/tree-jobs.d.ts +4 -3
  47. package/dist/runtime/subagents/tree-jobs.js +4 -4
  48. package/dist/tools/pipeline.js +7 -1
  49. package/package.json +3 -3
  50. package/src/migrations/0135_run_execution_claim.sql +2 -0
  51. package/src/migrations/0136_run_recovery_cursor.sql +6 -0
@@ -162,9 +162,10 @@ let LocalDeviceProvider = class LocalDeviceProvider {
162
162
  return { ...result, network: { blocked: relayer(result.network.blocked, limits) } };
163
163
  }
164
164
  async readFile(h, path, opts) {
165
+ const { limits } = await this.currentLimits(h.id);
165
166
  // the answer must fit one frame: a larger file comes back truncated (Deliver: too large)
166
167
  const maxBytes = Math.min(opts.maxBytes, maxReadBytes(this.config.get().devices.local.maxFrameBytes));
167
- const r = await this.relay.call(h.id, "readFile", { path, maxBytes }, { deadlineMs: OP_DEADLINE_MS, signal: opts.signal });
168
+ const r = await this.relay.call(h.id, "readFile", { path, maxBytes, limits: { mode: limits.mode } }, { deadlineMs: OP_DEADLINE_MS, signal: opts.signal });
168
169
  return r === null ? null : { data: bytesOf(r.dataB64), truncated: r.truncated };
169
170
  }
170
171
  async writeFile(h, path, data, signal) {
@@ -172,7 +173,8 @@ let LocalDeviceProvider = class LocalDeviceProvider {
172
173
  await this.relay.call(h.id, "writeFile", { path, dataB64 }, { deadlineMs: OP_DEADLINE_MS, signal });
173
174
  }
174
175
  async stat(h, path, signal) {
175
- return this.relay.call(h.id, "stat", { path }, { deadlineMs: OP_DEADLINE_MS, signal });
176
+ const { limits } = await this.currentLimits(h.id);
177
+ return this.relay.call(h.id, "stat", { path, limits: { mode: limits.mode } }, { deadlineMs: OP_DEADLINE_MS, signal });
176
178
  }
177
179
  /**
178
180
  * Lists one directory on the machine (the `list` op, project root §4.1), read in the mode the
@@ -201,10 +203,10 @@ let LocalDeviceProvider = class LocalDeviceProvider {
201
203
  }
202
204
  }
203
205
  /**
204
- * The device's org and the limits of one exec now (ruling R27): the effective policy's
206
+ * The device's org and current limits for an exec or file read (ruling R27): the effective policy's
205
207
  * `allowedMode` and the sandbox-mode allowlist. A deleted device is not found. A machine whose
206
208
  * local policy is auto mode while the organization allows only sandbox mode is refused here, at
207
- * every exec, so a machine switched locally is not used until it is switched back.
209
+ * every such operation, so a machine switched locally is not used until it is switched back.
208
210
  */
209
211
  async currentLimits(deviceId) {
210
212
  const orgId = await this.targets.orgOf(deviceId);
@@ -215,7 +217,7 @@ let LocalDeviceProvider = class LocalDeviceProvider {
215
217
  this.grants.reportedMode(deviceId),
216
218
  ]);
217
219
  if (policy.allowedMode === "sandbox" && reported === "auto") {
218
- this.log.warn("command refused on a machine that reports auto mode", { deviceId });
220
+ this.log.warn("device operation refused on a machine that reports auto mode", { deviceId });
219
221
  throw new ApiError("device.auto_mode_not_allowed", AUTO_MODE_NOT_ALLOWED_TEXT);
220
222
  }
221
223
  return {
@@ -49,6 +49,8 @@ export interface OffboardingRunControl {
49
49
  export declare const RUN_STOP_JOB = "run-stop";
50
50
  /** The `run-stop` job's data. */
51
51
  export interface RunStopJobData {
52
+ /** A deletion already settled PG; cancellation still needs delivery to its old worker. */
53
+ deleted?: true;
52
54
  conversationId: string;
53
55
  runId: string;
54
56
  }
@@ -406,6 +406,10 @@ let Offboarding = class Offboarding {
406
406
  * A failure throws (the job is retried).
407
407
  */
408
408
  async stopRun(data) {
409
+ if (data.deleted) {
410
+ await this.runs.requestAbort(data.runId, null);
411
+ return;
412
+ }
409
413
  const run = await this.db
410
414
  .selectFrom("runs")
411
415
  .select("status")
@@ -8,6 +8,7 @@ import { SettingsService } from "../identity/settings.js";
8
8
  import { KernelDb } from "../infra/database/kernel-db.js";
9
9
  import { TransactionHost } from "../infra/database/transaction-host.js";
10
10
  import { KernelEvents } from "../infra/events/kernel-events.js";
11
+ import { OutboxService } from "../infra/outbox/outbox.service.js";
11
12
  import { OrgLock } from "./org-lock.js";
12
13
  import type { OrgRole } from "./roles.js";
13
14
  export type Org = {
@@ -26,6 +27,7 @@ export declare function slugFromName(name: string): string;
26
27
  */
27
28
  export declare class OrgsService {
28
29
  private readonly db;
30
+ private readonly outbox;
29
31
  readonly txHost: TransactionHost;
30
32
  private readonly settings;
31
33
  private readonly apiTokens;
@@ -39,7 +41,7 @@ export declare class OrgsService {
39
41
  private readonly ownedItems;
40
42
  /** Records `org.deleted` for the subscribing plugins in the delete's transaction. */
41
43
  private readonly lifecycle;
42
- constructor(db: KernelDb, txHost: TransactionHost, settings: SettingsService, apiTokens: ApiTokenService, orgLock: OrgLock, events: KernelEvents,
44
+ constructor(db: KernelDb, outbox: Pick<OutboxService, "add">, txHost: TransactionHost, settings: SettingsService, apiTokens: ApiTokenService, orgLock: OrgLock, events: KernelEvents,
43
45
  /** Cancels the deleted org's running eval runs (in the delete's transaction). */
44
46
  evalBudget: Pick<EvalBudget, "cancelRuns">,
45
47
  /** A new org gets the plugins its scope offers it (the scope sync, owed with the org). */
@@ -24,6 +24,9 @@ import { KernelDb } from "../infra/database/kernel-db.js";
24
24
  import { TransactionHost } from "../infra/database/transaction-host.js";
25
25
  import { Transactional } from "../infra/database/transactional.decorator.js";
26
26
  import { KernelEvents } from "../infra/events/kernel-events.js";
27
+ import { OutboxService } from "../infra/outbox/outbox.service.js";
28
+ import { MAINTENANCE_QUEUE_NAME } from "../runtime/maintenance-queue.js";
29
+ import { STOP_DELETED_ORG_JOB } from "../runtime/run-deletion.js";
27
30
  import { USAGE_REPORT_QUEUE } from "../runtime/usage-report-jobs.js";
28
31
  import { OrgLock } from "./org-lock.js";
29
32
  /** 组织 slug:小写字母数字与 `-`,首尾不能是 `-`,1–40 个字符。 */
@@ -79,6 +82,7 @@ async function slugGuard(p) {
79
82
  */
80
83
  let OrgsService = class OrgsService {
81
84
  db;
85
+ outbox;
82
86
  txHost;
83
87
  settings;
84
88
  apiTokens;
@@ -88,7 +92,7 @@ let OrgsService = class OrgsService {
88
92
  scopeSync;
89
93
  ownedItems;
90
94
  lifecycle;
91
- constructor(db, txHost, settings, apiTokens, orgLock, events,
95
+ constructor(db, outbox, txHost, settings, apiTokens, orgLock, events,
92
96
  /** Cancels the deleted org's running eval runs (in the delete's transaction). */
93
97
  evalBudget,
94
98
  /** A new org gets the plugins its scope offers it (the scope sync, owed with the org). */
@@ -98,6 +102,7 @@ let OrgsService = class OrgsService {
98
102
  /** Records `org.deleted` for the subscribing plugins in the delete's transaction. */
99
103
  lifecycle) {
100
104
  this.db = db;
105
+ this.outbox = outbox;
101
106
  this.txHost = txHost;
102
107
  this.settings = settings;
103
108
  this.apiTokens = apiTokens;
@@ -236,6 +241,7 @@ let OrgsService = class OrgsService {
236
241
  await this.softDeleteIn(orgId, actor, actorTokenId);
237
242
  }
238
243
  async softDeleteIn(orgId, actor, actorTokenId) {
244
+ // The same org authorization lock admits fenced worker writes before conversation locks.
239
245
  await this.orgLock.lockAndAuthorize(orgId, actor.id, "org.delete");
240
246
  await this.db
241
247
  .updateTable("orgs")
@@ -251,6 +257,12 @@ let OrgsService = class OrgsService {
251
257
  .where("dead_at", "is", null)
252
258
  .where("queue", "<>", USAGE_REPORT_QUEUE)
253
259
  .execute();
260
+ await this.outbox.add({
261
+ queue: MAINTENANCE_QUEUE_NAME,
262
+ name: STOP_DELETED_ORG_JOB,
263
+ jobId: `stop-deleted-org-${orgId}`,
264
+ data: { orgId, byAccountId: actor.id },
265
+ });
254
266
  // after the org is marked deleted, so it counts as no user of what it shared (P3-18)
255
267
  await this.ownedItems.onOrgDeleted(orgId, actor.id, {
256
268
  ...(actorTokenId !== undefined && { actorTokenId }),
@@ -290,14 +302,15 @@ __decorate([
290
302
  OrgsService = __decorate([
291
303
  Injectable(),
292
304
  __param(0, Inject(KernelDb)),
293
- __param(1, Inject(TransactionHost)),
294
- __param(2, Inject(SettingsService)),
295
- __param(3, Inject(ApiTokenService)),
296
- __param(4, Inject(OrgLock)),
297
- __param(5, Inject(KernelEvents)),
298
- __param(6, Inject(EvalBudget)),
299
- __param(7, Inject(PluginScopeSync)),
300
- __param(8, Inject(OwnedItems)),
301
- __param(9, Inject(LifecycleHooks))
305
+ __param(1, Inject(OutboxService)),
306
+ __param(2, Inject(TransactionHost)),
307
+ __param(3, Inject(SettingsService)),
308
+ __param(4, Inject(ApiTokenService)),
309
+ __param(5, Inject(OrgLock)),
310
+ __param(6, Inject(KernelEvents)),
311
+ __param(7, Inject(EvalBudget)),
312
+ __param(8, Inject(PluginScopeSync)),
313
+ __param(9, Inject(OwnedItems)),
314
+ __param(10, Inject(LifecycleHooks))
302
315
  ], OrgsService);
303
316
  export { OrgsService };
@@ -4,9 +4,9 @@ import { AgentsService } from "../../agents/agents.service.js";
4
4
  import { AgentsFromTemplate } from "../../agents/from-template.service.js";
5
5
  import { OrgAgentTemplates } from "../../agents/org-templates.js";
6
6
  import { PendingConnectorsService } from "../../agents/pending-connectors.service.js";
7
+ import { ReadinessService } from "../../agents/readiness.service.js";
7
8
  import { CatalogRequestsService } from "../../catalog/requests.service.js";
8
9
  import { KernelDb } from "../../infra/database/kernel-db.js";
9
- import { ProviderRegistry } from "../../runtime/providers.js";
10
10
  import { ConnectorsService } from "../../tools/connectors.service.js";
11
11
  import { PlatformOperations } from "../registry.js";
12
12
  /** Agent operations of the `Platform` tool (spec §7); visibility is the person's own agents. */
@@ -19,9 +19,9 @@ export declare class AgentsOperations implements OnModuleInit {
19
19
  private readonly pending;
20
20
  private readonly requests;
21
21
  private readonly connectors;
22
- private readonly providers;
22
+ private readonly readiness;
23
23
  private readonly kdb;
24
- constructor(registry: PlatformOperations, agents: AgentsService, profiles: AgentProfileService, fromTemplate: AgentsFromTemplate, orgTemplates: OrgAgentTemplates, pending: PendingConnectorsService, requests: CatalogRequestsService, connectors: ConnectorsService, providers: ProviderRegistry, kdb: KernelDb);
24
+ constructor(registry: PlatformOperations, agents: AgentsService, profiles: AgentProfileService, fromTemplate: AgentsFromTemplate, orgTemplates: OrgAgentTemplates, pending: PendingConnectorsService, requests: CatalogRequestsService, connectors: ConnectorsService, readiness: ReadinessService, kdb: KernelDb);
25
25
  /**
26
26
  * The edit rule the service enforces, read before the card: the agent is visible, and the actor
27
27
  * owns it or is an org admin. Returns the agent too for the checks that follow.
@@ -18,10 +18,10 @@ import { AgentsFromTemplate } from "../../agents/from-template.service.js";
18
18
  import { OrgAgentTemplates } from "../../agents/org-templates.js";
19
19
  import { PendingConnectorsService } from "../../agents/pending-connectors.service.js";
20
20
  import { PresetAvatarSchema } from "../../agents/profile.js";
21
+ import { ReadinessService } from "../../agents/readiness.service.js";
21
22
  import { CatalogRequestsService } from "../../catalog/requests.service.js";
22
23
  import { KernelDb } from "../../infra/database/kernel-db.js";
23
24
  import { roleAtLeast } from "../../orgs/roles.js";
24
- import { ProviderRegistry } from "../../runtime/providers.js";
25
25
  import { rootConversationOf } from "../../runtime/subagents/child.js";
26
26
  import { ConnectorsService } from "../../tools/connectors.service.js";
27
27
  import { defineOperation, } from "../operation.js";
@@ -113,9 +113,9 @@ let AgentsOperations = class AgentsOperations {
113
113
  pending;
114
114
  requests;
115
115
  connectors;
116
- providers;
116
+ readiness;
117
117
  kdb;
118
- constructor(registry, agents, profiles, fromTemplate, orgTemplates, pending, requests, connectors, providers, kdb) {
118
+ constructor(registry, agents, profiles, fromTemplate, orgTemplates, pending, requests, connectors, readiness, kdb) {
119
119
  this.registry = registry;
120
120
  this.agents = agents;
121
121
  this.profiles = profiles;
@@ -124,7 +124,7 @@ let AgentsOperations = class AgentsOperations {
124
124
  this.pending = pending;
125
125
  this.requests = requests;
126
126
  this.connectors = connectors;
127
- this.providers = providers;
127
+ this.readiness = readiness;
128
128
  this.kdb = kdb;
129
129
  }
130
130
  /**
@@ -696,16 +696,13 @@ let AgentsOperations = class AgentsOperations {
696
696
  }),
697
697
  defineOperation({
698
698
  id: "agents.readiness",
699
- description: "Whether the org can run agents: modelProvider is ready when a model provider is available in the org (none otherwise), and how many agents you can see.",
699
+ description: "Whether the org can run agents: modelProvider is ready when a model provider is available in the org (none otherwise); orgCanAddModel is true when an org admin can make one available on the org's extensions page (switch on a provider the platform offers, or fill its org config), false when only the super admin can; and how many agents you can see.",
700
700
  input: z.object({}).strict(),
701
701
  example: {},
702
702
  authz: { orgAction: "org.read" },
703
703
  mirrors: ["GET /api/v1/orgs/:orgId/readiness"],
704
704
  confirm: "read",
705
- run: async (_input, ctx) => ({
706
- modelProvider: (await this.providers.hasProvider(ctx.orgId)) ? "ready" : "none",
707
- agents: (await this.agents.listVisible(ctx.orgId, ctx.actorAccountId)).length,
708
- }),
705
+ run: (_input, ctx) => this.readiness.get(ctx.orgId, ctx.actorAccountId),
709
706
  }),
710
707
  ]);
711
708
  }
@@ -720,7 +717,7 @@ AgentsOperations = __decorate([
720
717
  __param(5, Inject(PendingConnectorsService)),
721
718
  __param(6, Inject(CatalogRequestsService)),
722
719
  __param(7, Inject(ConnectorsService)),
723
- __param(8, Inject(ProviderRegistry)),
720
+ __param(8, Inject(ReadinessService)),
724
721
  __param(9, Inject(KernelDb))
725
722
  ], AgentsOperations);
726
723
  export { AgentsOperations };
@@ -258,6 +258,9 @@ let KyselyCheckpointSaver = class KyselyCheckpointSaver extends BaseCheckpointSa
258
258
  versions.length > 0 ? maxChannelVersion(...versions) : this.getNextVersion(undefined);
259
259
  }
260
260
  };
261
+ __decorate([
262
+ Transactional({ propagation: "requires_new" })
263
+ ], KyselyCheckpointSaver.prototype, "put", null);
261
264
  __decorate([
262
265
  Transactional({ propagation: "requires_new" })
263
266
  ], KyselyCheckpointSaver.prototype, "insertWrites", null);
@@ -369,13 +369,13 @@ function renderBlocks(blocks) {
369
369
  * result fails the attempt.
370
370
  */
371
371
  export function extractSummary(text) {
372
- const block = /<summary>([\s\S]*?)<\/summary>/i.exec(text);
372
+ // Strip scratchpads before looking for a summary: a truncated analysis can itself contain
373
+ // summary-shaped draft text. An unclosed analysis consumes the rest of the response.
374
+ const answer = text.replace(/<analysis>[\s\S]*?(?:<\/analysis>|$)/gi, "");
375
+ const block = /<summary>([\s\S]*?)<\/summary>/i.exec(answer);
373
376
  if (block)
374
377
  return (block[1] ?? "").trim();
375
- return text
376
- .replace(/<analysis>[\s\S]*?<\/analysis>/gi, "")
377
- .replace(/<\/?summary>/gi, "")
378
- .trim();
378
+ return answer.replace(/<\/?summary>/gi, "").trim();
379
379
  }
380
380
  /** The marker a hard-split line carries where it was cut (context compaction spec §4.5). */
381
381
  const CHUNK_SPLIT_MARKER = "\n[chunk split]\n";
@@ -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
+ }