@capybara-hq/kernel 0.1.0-rc.33 → 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 (68) hide show
  1. package/bootstrap.json +3 -3
  2. package/dist/admin/outbox-dead.service.d.ts +2 -0
  3. package/dist/admin/outbox-dead.service.js +34 -0
  4. package/dist/catalog/marketplaces.service.d.ts +1 -1
  5. package/dist/catalog/requests.service.d.ts +8 -6
  6. package/dist/catalog/requests.service.js +52 -29
  7. package/dist/config/schema.d.ts +4 -0
  8. package/dist/config/schema.js +7 -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/devices/devices.service.js +8 -4
  13. package/dist/infra/database/transaction-host.d.ts +1 -0
  14. package/dist/infra/database/transaction-host.js +13 -2
  15. package/dist/infra/outbox/registry.d.ts +17 -0
  16. package/dist/infra/outbox/registry.js +11 -0
  17. package/dist/local-devices/local-device-gateway.d.ts +1 -1
  18. package/dist/local-devices/local-device-gateway.js +1 -1
  19. package/dist/local-devices/local-device-provider.d.ts +2 -2
  20. package/dist/local-devices/local-device-provider.js +7 -5
  21. package/dist/local-devices/network-grants.d.ts +1 -1
  22. package/dist/local-devices/network-grants.js +2 -3
  23. package/dist/orgs/offboarding.d.ts +2 -0
  24. package/dist/orgs/offboarding.js +4 -0
  25. package/dist/orgs/orgs.service.d.ts +3 -1
  26. package/dist/orgs/orgs.service.js +23 -10
  27. package/dist/orgs/settings.controller.d.ts +3 -1
  28. package/dist/orgs/settings.controller.js +7 -3
  29. package/dist/orgs/settings.service.d.ts +78 -31
  30. package/dist/orgs/settings.service.js +109 -52
  31. package/dist/platform/ops/org-settings.ops.js +20 -10
  32. package/dist/runtime/checkpointer.js +3 -0
  33. package/dist/runtime/context/compaction.js +5 -5
  34. package/dist/runtime/conversation-lock.d.ts +4 -11
  35. package/dist/runtime/conversation-lock.js +14 -18
  36. package/dist/runtime/maintenance.d.ts +3 -1
  37. package/dist/runtime/maintenance.js +17 -10
  38. package/dist/runtime/project/knowledge.service.js +2 -2
  39. package/dist/runtime/run-deletion.d.ts +23 -0
  40. package/dist/runtime/run-deletion.js +130 -0
  41. package/dist/runtime/run-execution.d.ts +23 -0
  42. package/dist/runtime/run-execution.js +105 -0
  43. package/dist/runtime/run-finish.js +17 -4
  44. package/dist/runtime/run-jobs.js +11 -0
  45. package/dist/runtime/run-orphan-check.job.d.ts +12 -12
  46. package/dist/runtime/run-orphan-check.job.js +94 -26
  47. package/dist/runtime/run-queue.js +14 -0
  48. package/dist/runtime/run-worker.d.ts +9 -5
  49. package/dist/runtime/run-worker.js +90 -44
  50. package/dist/runtime/runtime.module.js +6 -0
  51. package/dist/runtime/stream.js +8 -2
  52. package/dist/runtime/subagents/tree-jobs.d.ts +4 -3
  53. package/dist/runtime/subagents/tree-jobs.js +4 -4
  54. package/dist/sandbox/modes.d.ts +31 -19
  55. package/dist/sandbox/modes.js +43 -24
  56. package/dist/sandbox/sandbox.service.d.ts +4 -1
  57. package/dist/sandbox/sandbox.service.js +11 -0
  58. package/dist/schedules/grant-rules.d.ts +2 -0
  59. package/dist/schedules/grant-rules.js +3 -1
  60. package/dist/schedules/schedule-math.js +21 -2
  61. package/dist/schedules/scheduled-tasks.service.js +3 -1
  62. package/dist/tools/network-asks.d.ts +7 -0
  63. package/dist/tools/network-asks.js +11 -1
  64. package/dist/tools/pipeline.js +14 -2
  65. package/package.json +3 -3
  66. package/src/migrations/0134_org_cloud_network_delta.sql +38 -0
  67. package/src/migrations/0135_run_execution_claim.sql +2 -0
  68. package/src/migrations/0136_run_recovery_cursor.sql +6 -0
package/bootstrap.json CHANGED
@@ -3,7 +3,7 @@
3
3
  "schemaVersion": 1,
4
4
  "marketplace": {
5
5
  "url": "https://github.com/capybara-hq/plugins.git",
6
- "commit": "08074e9ffafb9c4d8cc4252a9d4bc18cba37e53c"
6
+ "commit": "85aaf6598bee6f27ed9da9836084e2295eb29e03"
7
7
  },
8
8
  "plugins": [
9
9
  {
@@ -90,8 +90,8 @@
90
90
  "name": "sandbox-docker",
91
91
  "source": "npm",
92
92
  "npm": "@capybara-hq/plugin-sandbox-docker",
93
- "version": "0.1.0-rc.15",
94
- "integrity": "sha512-GeOxDSp51kMQW7cGZz9CRNFFn3fh7OUUVI1Dwul+fioHdEc+mEXckiapHrjc/cFwfnKTPb+R/yA+LVVgbFe9Vg==",
93
+ "version": "0.1.0-rc.16",
94
+ "integrity": "sha512-6LQ9TA4wRbqYJ7cfzYXrD4A+ICBvwDck9QmREal7M9kneO/Bb25hoSPsBpCxJT8/d6K+Gg7gmUd3+8rsueHeKg==",
95
95
  "required": false
96
96
  },
97
97
  {
@@ -58,6 +58,8 @@ export declare class OutboxDeadService {
58
58
  outcome: OutboxRetryOutcome;
59
59
  }>;
60
60
  private retryOnce;
61
+ /** A run-job retry is a new delivery generation, serialized with its terminal transition. */
62
+ private lockRunRetryIn;
61
63
  /** Deletes a dead row: its job is never delivered. `outbox.not_found` (404) when none. */
62
64
  discard(id: string, actor: WriteActor, detail?: Record<string, unknown>): Promise<void>;
63
65
  /** The dead row `id`, locked for the transaction; `outbox.not_found` when it is not dead. */
@@ -111,6 +111,7 @@ let OutboxDeadService = class OutboxDeadService {
111
111
  }
112
112
  }
113
113
  async retryOnce(id, actor, detail) {
114
+ await this.lockRunRetryIn(id);
114
115
  const row = await this.lockDead(id);
115
116
  const owed = await this.db.db
116
117
  .selectFrom("outbox")
@@ -136,6 +137,36 @@ let OutboxDeadService = class OutboxDeadService {
136
137
  await this.audit("outbox.retried", id, row, actor, { ...detail, outcome });
137
138
  return { outcome };
138
139
  }
140
+ /** A run-job retry is a new delivery generation, serialized with its terminal transition. */
141
+ async lockRunRetryIn(id) {
142
+ // Read before taking any outbox lock: the lock order is conversation, then outbox. The
143
+ // subsequent lockDead rechecks this row, so a concurrent discard/retry rolls this back.
144
+ const row = await this.db
145
+ .selectFrom("outbox")
146
+ .select(["job_name", "job_id", "data"])
147
+ .where("id", "=", id)
148
+ .where("dead_at", "is not", null)
149
+ .executeTakeFirst();
150
+ if (row?.job_name !== "run" || row.data === null || typeof row.data !== "object")
151
+ return;
152
+ const data = row.data;
153
+ if (typeof data.conversationId !== "string" || typeof data.runId !== "string")
154
+ return;
155
+ await this.db
156
+ .selectFrom("conversations")
157
+ .select("id")
158
+ .where("id", "=", data.conversationId)
159
+ .forUpdate()
160
+ .execute();
161
+ await this.db
162
+ .updateTable("runs")
163
+ .set({ queued_at: sql `clock_timestamp()` })
164
+ .where("id", "=", data.runId)
165
+ .where("conversation_id", "=", data.conversationId)
166
+ .where("status", "=", "queued")
167
+ .where(sql `COALESCE(job_id, 'run-' || conversation_id || '-' || trigger_seq::text) = ${row.job_id}`)
168
+ .execute();
169
+ }
139
170
  /** Deletes a dead row: its job is never delivered. `outbox.not_found` (404) when none. */
140
171
  async discard(id, actor, detail = {}) {
141
172
  const row = await this.lockDead(id);
@@ -178,6 +209,9 @@ let OutboxDeadService = class OutboxDeadService {
178
209
  __decorate([
179
210
  Transactional()
180
211
  ], OutboxDeadService.prototype, "retryOnce", null);
212
+ __decorate([
213
+ Transactional({ propagation: "mandatory" })
214
+ ], OutboxDeadService.prototype, "lockRunRetryIn", null);
181
215
  __decorate([
182
216
  Transactional()
183
217
  ], OutboxDeadService.prototype, "discard", null);
@@ -188,7 +188,7 @@ export declare function headsToResolve(entries: readonly MarketplaceEntry[], imp
188
188
  /** The host versions (an entry's `minKernel` is judged against them). */
189
189
  export declare const HOST_VERSIONS: {
190
190
  readonly kernel: string;
191
- readonly sdk: "0.1.0-rc.24";
191
+ readonly sdk: "0.1.0-rc.25";
192
192
  };
193
193
  /** Whether this deployment satisfies the entry's `minKernel`. */
194
194
  export declare const entryCompatible: (e: Pick<MarketplaceEntry, "minKernel">) => boolean;
@@ -265,12 +265,14 @@ export declare class CatalogRequestsService {
265
265
  private writeDecision;
266
266
  /**
267
267
  * Approves a `network_allowlist` request inside its decision's transaction: the hosts the org's
268
- * sandbox allowlist does not hold yet are added to the host list of the org's `cloudNetwork`,
269
- * through {@link OrgSettingsService.update} (audited `org.settings_updated` with `requestId`).
270
- * An org following the deployment default starts from the deployment's list (it keeps its own
271
- * list from then on). The org's network mode is kept: the list caps local sandbox devices, and
272
- * approving a host never turns an open cloud network into an allowlist (auto mode hardening
273
- * spec K1). The platform kill switch, more
268
+ * sandbox allowlist does not hold yet are added to the org's `cloudNetwork` delta (an extra
269
+ * host, or out of the exclusions for a platform host the org had dropped), through
270
+ * {@link OrgSettingsService.update} (audited `org.settings_updated` with `requestId`). The
271
+ * platform's list is never copied, so the org keeps following it (org egress ceiling spec §D1).
272
+ * The org's network mode is kept: the hosts cap local sandbox devices, and approving a host
273
+ * never turns an open cloud network into an allowlist (auto mode hardening spec K1). A host
274
+ * beyond the platform's ceiling (`orgHosts: within`) refuses the whole request. The platform
275
+ * kill switch, more
274
276
  * than {@link ORG_SANDBOX_ALLOW_HOSTS_MAX} hosts -> `catalog.request_invalid`; decided with an API
275
277
  * token -> `org.sandbox_egress_not_allowed` (only a person widens the network). Hosts all allowed
276
278
  * already: nothing is written.
@@ -24,7 +24,7 @@ import { orgAllows } from "../local-devices/network-grants.js";
24
24
  import { OrgLock } from "../orgs/org-lock.js";
25
25
  import { roleAtLeast } from "../orgs/roles.js";
26
26
  import { ORG_SANDBOX_ALLOW_HOSTS_MAX, OrgSettingsService, readOrgSettings, } from "../orgs/settings.service.js";
27
- import { orgSandboxNetwork } from "../sandbox/modes.js";
27
+ import { orgEffectiveHosts, orgHostOutsideCeiling } from "../sandbox/modes.js";
28
28
  import { CatalogService } from "./catalog.service.js";
29
29
  import { CatalogScopeService } from "./catalog-scope.service.js";
30
30
  import { assertEntryNotDeprecated, loadMarketplaceEntry } from "./marketplaces.service.js";
@@ -43,19 +43,16 @@ const alreadyDecided = () => new ApiError("catalog.request_decided", "This reque
43
43
  const pendingExists = () => new ApiError("catalog.request_pending", "This organization already has a pending request of this kind for it");
44
44
  const deploymentEgressNone = () => new ApiError("catalog.request_invalid", "The platform turned sandbox network off; only a super admin can turn it on");
45
45
  /**
46
- * The allowlist the organization's sandbox-mode devices reach (auto mode spec §4.1, §5.2): the
47
- * hosts of `orgSandboxNetwork` when the org or the deployment chose an allowlist, else the org's
48
- * own hosts (the deployment's list when the org gave none). An open cloud network does not make a
49
- * host "already allowed": a local device in sandbox mode always receives the allowlist, so a host
50
- * its network ask tells the person to ask an admin about must be addable (network ask spec §5.3).
46
+ * The allowlist the organization's sandbox-mode devices reach (org egress ceiling spec §D3): the
47
+ * org's effective hosts, whatever its cloud mode. An open cloud network does not make a host
48
+ * "already allowed": a local device in sandbox mode always receives the allowlist, so a host its
49
+ * network ask tells the person to ask an admin about must be addable (network ask spec §5.3).
51
50
  */
52
- function sandboxAllowlist(deployment, org) {
53
- const network = orgSandboxNetwork(deployment, org);
54
- return {
55
- kind: "allowlist",
56
- hosts: network.kind === "allowlist" ? network.hosts : (org?.allowHosts ?? deployment.allowHosts),
57
- };
51
+ function sandboxAllowlist(limits, org) {
52
+ return { kind: "allowlist", hosts: orgEffectiveHosts(limits, org) };
58
53
  }
54
+ /** Hosts beyond the platform's ceiling: only a super admin adds them (spec §D2). */
55
+ const outsideCeiling = (hosts) => new ApiError("catalog.request_invalid", `The platform limits sandbox hosts to its allowlist; only a super admin can add ${hosts.join(", ")} (sandbox.limits.allowHosts)`);
59
56
  /** A unique violation (the partial index of pending requests). */
60
57
  const isUniqueViolation = (e) => typeof e === "object" && e !== null && e.code === "23505";
61
58
  /** The deployment-level kinds (decided by the super admin). */
@@ -215,14 +212,17 @@ let CatalogRequestsService = class CatalogRequestsService {
215
212
  const t = this.db;
216
213
  await this.orgLock.lockAndAuthorize(orgId, actor, "catalog.request");
217
214
  const hosts = [...new Set(input.hosts.map((h) => h.toLowerCase()))].sort();
218
- if (this.config.get().sandbox.limits.egress === "none")
215
+ const limits = this.config.get().sandbox.limits;
216
+ if (limits.egress === "none")
219
217
  throw deploymentEgressNone();
220
- const deployment = (await this.orgSettings.deployment()).cloudNetwork;
221
218
  const settings = await readOrgSettings(t, orgId);
222
- const network = sandboxAllowlist(deployment, settings.cloudNetwork);
219
+ const network = sandboxAllowlist(limits, settings.cloudNetwork);
223
220
  if (hosts.every((h) => orgAllows(h, { network }))) {
224
221
  throw new ApiError("catalog.request_invalid", "This organization's sandbox network already allows these hosts; nothing to request");
225
222
  }
223
+ const beyond = hosts.filter((h) => orgHostOutsideCeiling(limits, h));
224
+ if (beyond.length > 0)
225
+ throw outsideCeiling(beyond);
226
226
  if (input.conversationId !== undefined) {
227
227
  const c = await t
228
228
  .selectFrom("conversations")
@@ -621,36 +621,59 @@ let CatalogRequestsService = class CatalogRequestsService {
621
621
  }
622
622
  /**
623
623
  * Approves a `network_allowlist` request inside its decision's transaction: the hosts the org's
624
- * sandbox allowlist does not hold yet are added to the host list of the org's `cloudNetwork`,
625
- * through {@link OrgSettingsService.update} (audited `org.settings_updated` with `requestId`).
626
- * An org following the deployment default starts from the deployment's list (it keeps its own
627
- * list from then on). The org's network mode is kept: the list caps local sandbox devices, and
628
- * approving a host never turns an open cloud network into an allowlist (auto mode hardening
629
- * spec K1). The platform kill switch, more
624
+ * sandbox allowlist does not hold yet are added to the org's `cloudNetwork` delta (an extra
625
+ * host, or out of the exclusions for a platform host the org had dropped), through
626
+ * {@link OrgSettingsService.update} (audited `org.settings_updated` with `requestId`). The
627
+ * platform's list is never copied, so the org keeps following it (org egress ceiling spec §D1).
628
+ * The org's network mode is kept: the hosts cap local sandbox devices, and approving a host
629
+ * never turns an open cloud network into an allowlist (auto mode hardening spec K1). A host
630
+ * beyond the platform's ceiling (`orgHosts: within`) refuses the whole request. The platform
631
+ * kill switch, more
630
632
  * than {@link ORG_SANDBOX_ALLOW_HOSTS_MAX} hosts -> `catalog.request_invalid`; decided with an API
631
633
  * token -> `org.sandbox_egress_not_allowed` (only a person widens the network). Hosts all allowed
632
634
  * already: nothing is written.
633
635
  */
634
636
  async approveNetwork(orgId, actor, requestId, detail, opts) {
635
637
  const hosts = detail?.hosts ?? [];
636
- if (this.config.get().sandbox.limits.egress === "none")
638
+ const limits = this.config.get().sandbox.limits;
639
+ if (limits.egress === "none")
637
640
  throw deploymentEgressNone();
638
- const deployment = (await this.orgSettings.deployment()).cloudNetwork;
639
641
  const current = (await readOrgSettings(this.db, orgId)).cloudNetwork;
640
642
  // the hosts the org's sandbox-mode devices reach now (an open cloud network still gives them
641
643
  // the allowlist: a host their network ask names must be addable)
642
- const network = sandboxAllowlist(deployment, current);
644
+ const network = sandboxAllowlist(limits, current);
643
645
  const missing = hosts.filter((h) => !orgAllows(h, { network }));
644
646
  if (missing.length === 0)
645
647
  return;
646
- const base = current?.allowHosts ?? deployment.allowHosts;
647
- const allowHosts = [...new Set([...base, ...missing])];
648
- if (allowHosts.length > ORG_SANDBOX_ALLOW_HOSTS_MAX) {
649
- throw new ApiError("catalog.request_invalid", `The organization's sandbox allowlist would exceed ${ORG_SANDBOX_ALLOW_HOSTS_MAX} hosts; remove some in the organization settings first`);
648
+ // the whole request is refused when a host is beyond the platform's ceiling (never partly)
649
+ const beyond = missing.filter((h) => orgHostOutsideCeiling(limits, h));
650
+ if (beyond.length > 0)
651
+ throw outsideCeiling(beyond);
652
+ // a delta, never a copy of the platform's list: a host the org had dropped from the platform's
653
+ // list comes back out of the exclusions (base platform), any other becomes an extra
654
+ const excluded = current?.excludedHosts ?? [];
655
+ const platformBase = (current?.base ?? "platform") === "platform";
656
+ const readmit = platformBase
657
+ ? missing.filter((h) => excluded.includes(h) && limits.allowHosts.includes(h))
658
+ : [];
659
+ const added = missing.filter((h) => !readmit.includes(h));
660
+ const extraHosts = [...new Set([...(current?.extraHosts ?? []), ...added])];
661
+ if (extraHosts.length > ORG_SANDBOX_ALLOW_HOSTS_MAX) {
662
+ throw new ApiError("catalog.request_invalid", `The organization's sandbox allowlist would exceed ${ORG_SANDBOX_ALLOW_HOSTS_MAX} extra hosts; remove some in the organization settings first`);
650
663
  }
664
+ const excludedHosts = excluded.filter((h) => !readmit.includes(h));
665
+ // the stored value is sent back whole with the hosts changed; the mode is never written
666
+ // (approving a host never turns an open cloud network into an allowlist, K1)
667
+ const cloudNetwork = {
668
+ ...current,
669
+ ...(extraHosts.length > 0 ? { extraHosts } : {}),
670
+ ...(excludedHosts.length > 0 ? { excludedHosts } : {}),
671
+ };
672
+ if (excludedHosts.length === 0)
673
+ delete cloudNetwork.excludedHosts;
651
674
  // approving widens the org's network allowlist: only a person in a session does that, never an
652
675
  // API token (auto mode spec §4.3; the Platform tool has no decide operation at all)
653
- await this.orgSettings.update(orgId, { cloudNetwork: { mode: current?.mode ?? deployment.mode, allowHosts } }, actor, opts.actorTokenId, { requestId }, { onlyNarrows: opts.actorTokenId !== undefined });
676
+ await this.orgSettings.update(orgId, { cloudNetwork }, actor, opts.actorTokenId, { requestId }, { onlyNarrows: opts.actorTokenId !== undefined });
654
677
  }
655
678
  /**
656
679
  * The requester dismisses a decided request from the inbox (`POST /orgs/:orgId/
@@ -241,6 +241,10 @@ export declare const KernelConfigSchema: z.ZodObject<{
241
241
  none: "none";
242
242
  }>>;
243
243
  allowHosts: z.ZodDefault<z.ZodArray<z.ZodString>>;
244
+ orgHosts: z.ZodDefault<z.ZodEnum<{
245
+ extend: "extend";
246
+ within: "within";
247
+ }>>;
244
248
  }, z.core.$strip>>;
245
249
  }, z.core.$strip>>;
246
250
  devices: z.ZodPrefault<z.ZodObject<{
@@ -1337,7 +1337,13 @@ export const KernelConfigSchema = z.object({
1337
1337
  });
1338
1338
  })
1339
1339
  .meta(meta({
1340
- description: "Default host list of the allowlist: in sandbox mode, the hosts a cloud device instance may reach on allowlist (the default of an organization's cloud network, used in sandbox mode only) and a local device's allowlist; lowercase hostnames, optional leading '*.', no IPs, ports or internal-only names; applies to instances created after the change",
1340
+ description: "Host list of the allowlist: in sandbox mode, the hosts a cloud device instance may reach on allowlist and a local device's allowlist; organizations follow it, adding or dropping hosts of their own (see orgHosts); lowercase hostnames, optional leading '*.', no IPs, ports or internal-only names; applies to instances created after the change",
1341
+ })),
1342
+ orgHosts: z
1343
+ .enum(["extend", "within"])
1344
+ .default("extend")
1345
+ .meta(meta({
1346
+ description: "Whether organizations may go beyond allowHosts in sandbox mode: extend (the default: an organization may use the open cloud network and add hosts, and its admins approve network requests) or within (allowHosts is the ceiling: an organization's cloud network in sandbox mode is the allowlist, and it may only keep or drop hosts the list covers; only a super admin adds others). Auto mode is not limited by it: devices.autoMode governs auto mode's open network, so set devices.autoMode off as well for a hard ceiling",
1341
1347
  })),
1342
1348
  })
1343
1349
  .prefault({}),
@@ -2,7 +2,6 @@ import type { ConversationSource } from "@capybara-hq/plugin-sdk";
2
2
  import { AgentLookup } from "../agents/agent-lookup.js";
3
3
  import type { ModelRef } from "../agents/definition.js";
4
4
  import type { AgentAvatar } from "../agents/profile.js";
5
- import { BackgroundTaskStopper } from "../background/stop.js";
6
5
  import type { TitleSource } from "../db/kernel-schema.js";
7
6
  import { ConversationDevices, type NewConversationDevice } from "../devices/conversation-devices.js";
8
7
  import { DeviceProjectsService } from "../devices/device-projects.service.js";
@@ -10,6 +9,7 @@ import { KernelDb } from "../infra/database/kernel-db.js";
10
9
  import { TransactionHost } from "../infra/database/transaction-host.js";
11
10
  import { KernelEvents } from "../infra/events/kernel-events.js";
12
11
  import { ProviderRegistry } from "../runtime/providers.js";
12
+ import { RunDeletion } from "../runtime/run-deletion.js";
13
13
  import type { ScheduleMarker } from "../schedules/types.js";
14
14
  import { type RenderedInvocation, SkillInvoker } from "../skills/invoke.js";
15
15
  import { type ApprovalRecord, ApprovalsService } from "../tools/approvals.service.js";
@@ -288,7 +288,7 @@ export declare class ConversationsService {
288
288
  /** Renders a person's skill invocation (phase D). */
289
289
  private readonly invoker;
290
290
  /** Stops a deleted conversation's background tasks. */
291
- private readonly background;
291
+ private readonly deletion;
292
292
  /** The device a new conversation is bound to (environments spec §4.1 item 1). */
293
293
  private readonly devices;
294
294
  /** The project of that device a new conversation is bound to (project root design §4.3). */
@@ -311,7 +311,7 @@ export declare class ConversationsService {
311
311
  /** Renders a person's skill invocation (phase D). */
312
312
  invoker: Pick<SkillInvoker, "prepare">,
313
313
  /** Stops a deleted conversation's background tasks. */
314
- background: Pick<BackgroundTaskStopper, "stopForDeletedConversation">,
314
+ deletion: Pick<RunDeletion, "stopTree">,
315
315
  /** The device a new conversation is bound to (environments spec §4.1 item 1). */
316
316
  devices: Pick<ConversationDevices, "forNew">,
317
317
  /** The project of that device a new conversation is bound to (project root design §4.3). */
@@ -11,7 +11,6 @@ import { randomUUID } from "node:crypto";
11
11
  import { Inject, Injectable } from "@nestjs/common";
12
12
  import { sql } from "kysely";
13
13
  import { AgentLookup, visibleTo } from "../agents/agent-lookup.js";
14
- import { BackgroundTaskStopper } from "../background/stop.js";
15
14
  import { unbindConversation } from "../channels/threads.js";
16
15
  import { ConversationDevices, } from "../devices/conversation-devices.js";
17
16
  import { DeviceProjectsService } from "../devices/device-projects.service.js";
@@ -22,6 +21,7 @@ import { Transactional } from "../infra/database/transactional.decorator.js";
22
21
  import { KernelEvents } from "../infra/events/kernel-events.js";
23
22
  import { ProviderRegistry } from "../runtime/providers.js";
24
23
  import { RunControl as RunControlService } from "../runtime/run-control.js";
24
+ import { RunDeletion } from "../runtime/run-deletion.js";
25
25
  import { rootConversationOf } from "../runtime/subagents/child.js";
26
26
  import { SkillInvoker } from "../skills/invoke.js";
27
27
  import { ApprovalsService } from "../tools/approvals.service.js";
@@ -33,7 +33,7 @@ import { AttachmentsService } from "./attachments.service.js";
33
33
  import { EventLog } from "./event-log.js";
34
34
  import { userMessageIdemKey } from "./idem-keys.js";
35
35
  import { readMessageContext, } from "./message-context.js";
36
- import { NO_SELECTION, planSelection, readSelection } from "./selection.js";
36
+ import { NO_SELECTION, planSelection, readSelection, sameSelection, } from "./selection.js";
37
37
  import { conversationTree } from "./tree.js";
38
38
  /**
39
39
  * SQL for the {@link ProjectState} of the conversation row aliased/named `ref` (a correlated
@@ -157,7 +157,7 @@ let ConversationsService = class ConversationsService {
157
157
  content;
158
158
  attachments;
159
159
  invoker;
160
- background;
160
+ deletion;
161
161
  devices;
162
162
  projects;
163
163
  questions;
@@ -176,7 +176,7 @@ let ConversationsService = class ConversationsService {
176
176
  /** Renders a person's skill invocation (phase D). */
177
177
  invoker,
178
178
  /** Stops a deleted conversation's background tasks. */
179
- background,
179
+ deletion,
180
180
  /** The device a new conversation is bound to (environments spec §4.1 item 1). */
181
181
  devices,
182
182
  /** The project of that device a new conversation is bound to (project root design §4.3). */
@@ -194,7 +194,7 @@ let ConversationsService = class ConversationsService {
194
194
  this.content = content;
195
195
  this.attachments = attachments;
196
196
  this.invoker = invoker;
197
- this.background = background;
197
+ this.deletion = deletion;
198
198
  this.devices = devices;
199
199
  this.projects = projects;
200
200
  this.questions = questions;
@@ -409,25 +409,26 @@ let ConversationsService = class ConversationsService {
409
409
  * log, runs and trajectory stay (super admins still see them).
410
410
  */
411
411
  async remove(orgId, conversationId, accountId) {
412
- const conv = await this.writable(orgId, conversationId, accountId);
413
- // the root's own run only: the tree stops below, after the mark (a sub-agent's conversation
414
- // is read-only, so `writable` refused it)
415
- if (conv.parentConversationId === null) {
416
- await this.abortRootRun(conversationId, accountId);
417
- }
412
+ await this.writable(orgId, conversationId, accountId);
413
+ // Close entrances before the direct stop. The outbox owes the same claim-revoking cleanup.
418
414
  await this.markDeleted(orgId, conversationId, accountId);
419
- // after the mark, so no finish or delivery of the stops below can start a run on the deleted
420
- // root (`ensureRun` refuses it). The sandbox's tasks stop first, so the sub-agents' tasks end
421
- // as a deletion; the tree stop then only stops a task a sub-agent started in between
422
- // (`stoppedBy: "subagent_end"`, which never wakes either)
423
- await this.background.stopForDeletedConversation(conversationId);
424
- // the whole tree stops (agent map spec §10)
425
- await this.runs.stopTree(conversationId, accountId, { includeSelf: false });
415
+ await this.deletion.stopTree(conversationId, accountId);
426
416
  await this.eventLog.publishChanged(conversationId, "deleted");
427
417
  }
428
418
  // the publish happens after the commit, in the caller; the tree stop after it is owed here
429
419
  // (transactional outbox spec §6), so a process that dies before it still stops the tree
430
420
  async markDeleted(orgId, conversationId, accountId) {
421
+ const row = await this.db
422
+ .selectFrom("conversations")
423
+ .select("id")
424
+ .where("id", "=", conversationId)
425
+ .where("org_id", "=", orgId)
426
+ .where("account_id", "=", accountId)
427
+ .where("deleted_at", "is", null)
428
+ .forUpdate()
429
+ .executeTakeFirst();
430
+ if (!row)
431
+ throw notFound();
431
432
  await this.db
432
433
  .updateTable("conversations")
433
434
  .set({ deleted_at: sql `now()` })
@@ -781,11 +782,8 @@ let ConversationsService = class ConversationsService {
781
782
  */
782
783
  async postUserMessage(orgId, conversationId, accountId, input) {
783
784
  const conv = await this.writable(orgId, conversationId, accountId);
784
- const refs = input.attachments ?? [];
785
- const files = input.files ?? [];
786
- // A retry returns the written event (no resource read, no file check, no skill resolution)
787
- if ((refs.length > 0 || files.length > 0 || input.skill !== undefined) &&
788
- input.clientMessageId !== undefined) {
785
+ // A retry returns the written event before resolving today's model or resources.
786
+ if (input.clientMessageId !== undefined) {
789
787
  const existing = await this.eventLog.findByIdem(conversationId, userMessageIdemKey(input.clientMessageId));
790
788
  if (existing) {
791
789
  await this.startRun(conversationId);
@@ -796,16 +794,29 @@ let ConversationsService = class ConversationsService {
796
794
  const agent = needsAgent
797
795
  ? (await this.agents.get(orgId, conv.agentId, accountId)).definition
798
796
  : undefined;
799
- const next = agent === undefined || (input.model === undefined && input.effort === undefined)
800
- ? null
801
- : await this.planSwitch(orgId, agent, conv.selection, input);
802
797
  const extra = await this.resolveExtra(orgId, accountId, input);
803
798
  const invoked = agent === undefined
804
799
  ? undefined
805
800
  : await this.prepareSkill(orgId, accountId, conv.agentId, conversationId, agent, input);
806
801
  // one transaction: the sender, time zone and language are read with the message's write
807
802
  // (run context spec §3.2)
808
- const { event, skipped, toSeq } = await this.postIn(orgId, conversationId, accountId, input, next, extra, invoked);
803
+ let current = conv.selection;
804
+ let posted;
805
+ let next = null;
806
+ for (let attempt = 0; attempt < 3; attempt++) {
807
+ next = agent === undefined ? null : await this.planSwitch(orgId, agent, current, input);
808
+ const result = await this.postIn(orgId, conversationId, accountId, input, next, extra, invoked, input.model !== undefined || input.effort !== undefined ? current : undefined);
809
+ if ("selection" in result) {
810
+ current = result.selection;
811
+ continue;
812
+ }
813
+ posted = result;
814
+ break;
815
+ }
816
+ if (posted === undefined) {
817
+ throw new ApiError("conflict", "The conversation selection changed; send the message again");
818
+ }
819
+ const { event, skipped, toSeq } = posted;
809
820
  await this.eventLog.notify(conversationId, toSeq);
810
821
  await this.announceSkipped(skipped);
811
822
  if (next !== null)
@@ -827,7 +838,25 @@ let ConversationsService = class ConversationsService {
827
838
  * (after its `model_switched` when it switches).
828
839
  */
829
840
  // its own transaction: the caller notifies and publishes after the commit
830
- async postIn(orgId, conversationId, accountId, input, next, extra, invoked) {
841
+ async postIn(orgId, conversationId, accountId, input, next, extra, invoked, expectedSelection) {
842
+ // Serialize the partial pick with the append. Provider resolution runs outside this
843
+ // transaction; if another send changed the selection, revalidate its model before retrying.
844
+ const row = await this.db
845
+ .selectFrom("conversations")
846
+ .select("id")
847
+ .where("id", "=", conversationId)
848
+ .where("org_id", "=", orgId)
849
+ .where("account_id", "=", accountId)
850
+ .where("deleted_at", "is", null)
851
+ .forUpdate()
852
+ .executeTakeFirst();
853
+ if (!row)
854
+ throw notFound();
855
+ if (expectedSelection !== undefined) {
856
+ const selection = await readSelection(this.db.db, conversationId);
857
+ if (!sameSelection(expectedSelection, selection))
858
+ return { selection };
859
+ }
831
860
  const blocks = await this.bindIn(orgId, conversationId, accountId, input.files ?? []);
832
861
  const written = await this.writeMessage(orgId, conversationId, accountId, input, next, extra, blocks, invoked);
833
862
  const event = written.events.at(-1);
@@ -1204,7 +1233,7 @@ ConversationsService = __decorate([
1204
1233
  __param(6, Inject(ConnectorContent)),
1205
1234
  __param(7, Inject(AttachmentsService)),
1206
1235
  __param(8, Inject(SkillInvoker)),
1207
- __param(9, Inject(BackgroundTaskStopper)),
1236
+ __param(9, Inject(RunDeletion)),
1208
1237
  __param(10, Inject(ConversationDevices)),
1209
1238
  __param(11, Inject(DeviceProjectsService)),
1210
1239
  __param(12, Inject(QuestionsService)),
@@ -342,7 +342,14 @@ export interface ConversationEventsTable {
342
342
  created_at: Ts;
343
343
  }
344
344
  /** 0006_conversations.sql:一次 agent 运行。 */
345
+ export interface RunRecoveryCursorsTable {
346
+ name: string;
347
+ since: TsNullable;
348
+ run_id: string | null;
349
+ }
345
350
  export interface RunsTable {
351
+ /** 0135: the worker acquisition currently authorized to mutate this run. */
352
+ execution_id: string | null;
346
353
  id: string;
347
354
  conversation_id: string;
348
355
  status: "queued" | "running" | "waiting" | "completed" | "failed" | "aborted";
@@ -1312,6 +1319,7 @@ export interface KernelDatabase {
1312
1319
  file_previewers: FilePreviewersTable;
1313
1320
  org_extension_point_defaults: OrgExtensionPointDefaultsTable;
1314
1321
  runs: RunsTable;
1322
+ run_recovery_cursors: RunRecoveryCursorsTable;
1315
1323
  subagent_dispatches: SubagentDispatchesTable;
1316
1324
  agent_templates: AgentTemplatesTable;
1317
1325
  agent_template_versions: AgentTemplateVersionsTable;
@@ -1043,16 +1043,20 @@ killSwitch = false) {
1043
1043
  const networkKind = local ? "allowlist" : policy.network.kind;
1044
1044
  const org = settings.cloudNetwork;
1045
1045
  // "org" only when the org supplied what is in effect: the kill switch always wins; auto mode
1046
- // ignores the org's network; a local device's list is the org's only when the org gave hosts;
1047
- // a sandbox cloud device's kind is the org's when it matches the mode the org chose
1046
+ // ignores the org's network; a local device's list is the org's only when the org changed the
1047
+ // platform's (its own base or a delta); a sandbox cloud device's kind is the org's when it
1048
+ // matches the mode the org chose (the platform ceiling may force the allowlist)
1049
+ const orgHosts = org?.base === "none" ||
1050
+ (org?.extraHosts?.length ?? 0) > 0 ||
1051
+ (org?.excludedHosts?.length ?? 0) > 0;
1048
1052
  const source = killSwitch
1049
1053
  ? "platform"
1050
1054
  : local
1051
- ? policy.mode === "sandbox" && org?.allowHosts !== undefined
1055
+ ? policy.mode === "sandbox" && orgHosts
1052
1056
  ? "org"
1053
1057
  : "platform"
1054
1058
  : policy.mode === "sandbox" &&
1055
- org !== undefined &&
1059
+ org?.mode !== undefined &&
1056
1060
  (org.mode === "open" ? networkKind === "open-public" : networkKind === "allowlist")
1057
1061
  ? "org"
1058
1062
  : "platform";
@@ -9,6 +9,7 @@ interface TransactionStore {
9
9
  /** Set once the transaction settled: continuations that outlive it must not use it. */
10
10
  done: boolean;
11
11
  }
12
+ export declare function withTransactionFence<T>(fence: () => Promise<void>, fn: () => Promise<T>): Promise<T>;
12
13
  export type Propagation = "required" | "requires_new" | "mandatory";
13
14
  export interface TransactionOptions {
14
15
  /**
@@ -14,6 +14,11 @@ import { Inject, Injectable } from "@nestjs/common";
14
14
  import { KERNEL_LOGGER, KERNEL_POOL } from "../tokens.js";
15
15
  /** One store for the process: `afterCommit` (a free function) reads it without a host instance. */
16
16
  const storage = new AsyncLocalStorage();
17
+ /** A caller's execution authority, checked inside every new transaction before domain writes. */
18
+ const fences = new AsyncLocalStorage();
19
+ export function withTransactionFence(fence, fn) {
20
+ return fences.run(fence, fn);
21
+ }
17
22
  /** Logger for hook failures outside a transaction; set by `TransactionHost`, console until then. */
18
23
  let hookLog = {
19
24
  error: (msg, fields) => console.error(`[afterCommit] ${msg}`, fields ?? ""),
@@ -51,7 +56,7 @@ export function currentStore() {
51
56
  * join (or write through) a transaction that may already be committed or rolled back.
52
57
  */
53
58
  export function runOutsideTransaction(fn) {
54
- return storage.exit(fn);
59
+ return fences.exit(() => storage.exit(fn));
55
60
  }
56
61
  let TransactionHost = class TransactionHost {
57
62
  pool;
@@ -97,7 +102,13 @@ let TransactionHost = class TransactionHost {
97
102
  builder = builder.setAccessMode(opts.accessMode);
98
103
  result = await builder.execute((trx) => {
99
104
  store = { pool: this.pool, trx, hooks, done: false };
100
- return storage.run(store, fn);
105
+ return storage.run(store, async () => {
106
+ // PostgreSQL forbids row locks in a read-only snapshot and enforces that it cannot
107
+ // mutate. Every later mutation or external dispatch still enters a writable fence.
108
+ if (opts.accessMode !== "read only")
109
+ await fences.getStore()?.();
110
+ return fn();
111
+ });
101
112
  });
102
113
  }
103
114
  finally {
@@ -66,6 +66,23 @@ export declare const OUTBOX_JOBS: {
66
66
  readonly removeOnFail: true;
67
67
  };
68
68
  };
69
+ readonly "stop-deleted-org": {
70
+ readonly queue: "cap-kernel-maintenance";
71
+ readonly idempotent: "only active runs are settled and only running background tasks are stopped";
72
+ readonly processedIn: "packages/kernel/src/runtime/maintenance.ts";
73
+ readonly opts: {
74
+ readonly attempts: 5;
75
+ readonly backoff: {
76
+ readonly type: "exponential";
77
+ readonly delay: 5000;
78
+ };
79
+ readonly removeOnComplete: true;
80
+ readonly removeOnFail: {
81
+ readonly age: number;
82
+ readonly count: 1000;
83
+ };
84
+ };
85
+ };
69
86
  readonly "run-stop": {
70
87
  readonly queue: "cap-kernel-maintenance";
71
88
  readonly idempotent: "stopping a finished run is a no-op";
@@ -56,6 +56,17 @@ export const OUTBOX_JOBS = {
56
56
  },
57
57
  // `orgs/offboarding.ts` RUN_STOP_JOB: owed by the offboard transaction for each of the departed
58
58
  // member's active runs in the org, under `runStopJobId` (spec §8.1)
59
+ "stop-deleted-org": {
60
+ queue: "cap-kernel-maintenance",
61
+ idempotent: "only active runs are settled and only running background tasks are stopped",
62
+ processedIn: "packages/kernel/src/runtime/maintenance.ts",
63
+ opts: {
64
+ attempts: 5,
65
+ backoff: { type: "exponential", delay: 5_000 },
66
+ removeOnComplete: true,
67
+ removeOnFail: { age: 7 * 86_400, count: 1_000 },
68
+ },
69
+ },
59
70
  "run-stop": {
60
71
  queue: "cap-kernel-maintenance",
61
72
  idempotent: "stopping a finished run is a no-op",