@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
@@ -19,6 +19,7 @@ import { KernelDb } from "../infra/database/kernel-db.js";
19
19
  import { TransactionHost } from "../infra/database/transaction-host.js";
20
20
  import { Transactional } from "../infra/database/transactional.decorator.js";
21
21
  import { KERNEL_LOGGER } from "../infra/tokens.js";
22
+ import { coversHost, orgCloudMode, orgEffectiveHosts, orgHostOutsideCeiling, } from "../sandbox/modes.js";
22
23
  import { readDevicesAutoMode, } from "../sandbox/platform-auto-mode.js";
23
24
  import { assertThemeOnIn } from "../themes/theme-state.js";
24
25
  import { IanaTimeZone } from "../time-zone.js";
@@ -35,9 +36,9 @@ import { OrgLock, OrgLockModule } from "./org-lock.js";
35
36
  * - `autoMode`: whether devices of the org may run in auto mode (auto mode spec §4.3); absent
36
37
  * follows the platform's `devices.autoMode`, and an invalid stored value reads as `off`
37
38
  * (narrower, never wider). Setting `allowed` while the platform is `off` is refused.
38
- * - `cloudNetwork`: the org's network for cloud devices (auto mode spec §4.3): `open` (any public
39
- * host; the default) or `allowlist` with `allowHosts` (the deployment's list when omitted). An
40
- * invalid stored value reads as `{ mode: "allowlist", allowHosts: [] }` (narrower, never wider).
39
+ * - `cloudNetwork`: the org's sandbox-mode network as a delta over the platform's allowlist (org
40
+ * egress ceiling spec §D1, {@link CloudNetworkSettingSchema}). An invalid stored value reads as
41
+ * `{ mode: "allowlist", base: "none" }`, the empty allowlist (narrower, never wider).
41
42
  * - `platformTool`: the `Platform` builtin for the whole org (Platform tool spec §3): `on`,
42
43
  * `read-only` (writes listed as unavailable) or `off` (default `on`).
43
44
  * - `timeZone`: the org's default time zone (IANA; absent = UTC) for senders without one of their
@@ -51,37 +52,48 @@ import { OrgLock, OrgLockModule } from "./org-lock.js";
51
52
  */
52
53
  /** The org cloud-network allowlist's host limit. */
53
54
  export const ORG_SANDBOX_ALLOW_HOSTS_MAX = 200;
55
+ /** One host list of the org's cloud network: at most {@link ORG_SANDBOX_ALLOW_HOSTS_MAX} valid, unique hosts. */
56
+ const orgHostList = (name) => z
57
+ .array(z.string())
58
+ .max(ORG_SANDBOX_ALLOW_HOSTS_MAX)
59
+ .superRefine((hosts, ctx) => {
60
+ hosts.forEach((h, i) => {
61
+ for (const message of validateAllowHost(h)) {
62
+ ctx.addIssue({ code: "custom", path: [i], message: `${h}: ${message}` });
63
+ }
64
+ });
65
+ if (new Set(hosts).size !== hosts.length) {
66
+ ctx.addIssue({ code: "custom", message: `${name} must not contain duplicates` });
67
+ }
68
+ })
69
+ .optional();
54
70
  /**
55
- * The org's network for cloud devices (auto mode spec §4.3): `open` (any public host; loopback,
56
- * private and cloud metadata addresses are blocked outside the container) or `allowlist` with
57
- * `allowHosts`. `allowHosts` given **replaces** the deployment's list (the org may drop the presets
58
- * and add its own hosts); omitted, the deployment's `sandbox.limits.allowHosts` applies.
59
- * The host list is also the ceiling a local device in sandbox mode reaches (the device intersects
60
- * it with its own list), so narrowing it limits local sandbox devices too.
71
+ * The org's sandbox-mode network (org egress ceiling spec §D1), stored as a delta over the
72
+ * platform's `sandbox.limits.allowHosts`, never a copy of it, so platform changes keep reaching the
73
+ * org:
74
+ * - `mode`: the cloud network of a cloud device in sandbox mode, `open` (any public host; loopback,
75
+ * private and cloud metadata addresses are blocked outside the container) or `allowlist`; absent
76
+ * follows the platform's default (open). `sandbox.limits.orgHosts: within` makes it the allowlist.
77
+ * - `base`: `platform` (the default: start from the platform's list) or `none` (only the org's own
78
+ * hosts).
79
+ * - `extraHosts`: hosts the org adds (ignored outside the platform list under `within`).
80
+ * - `excludedHosts`: platform entries the org drops (exact entries; any host is accepted, since the
81
+ * platform may drop an entry later).
82
+ * The effective hosts ({@link orgEffectiveHosts} in `sandbox/modes.ts`) are also the ceiling a local
83
+ * device in sandbox mode reaches (the device intersects them with its own list).
61
84
  */
62
85
  export const CloudNetworkSettingSchema = z
63
86
  .object({
64
- mode: z.enum(["open", "allowlist"]),
65
- allowHosts: z
66
- .array(z.string())
67
- .max(ORG_SANDBOX_ALLOW_HOSTS_MAX)
68
- .superRefine((hosts, ctx) => {
69
- hosts.forEach((h, i) => {
70
- for (const message of validateAllowHost(h)) {
71
- ctx.addIssue({ code: "custom", path: [i], message: `${h}: ${message}` });
72
- }
73
- });
74
- if (new Set(hosts).size !== hosts.length) {
75
- ctx.addIssue({ code: "custom", message: "allowHosts must not contain duplicates" });
76
- }
77
- })
78
- .optional(),
87
+ mode: z.enum(["open", "allowlist"]).optional(),
88
+ base: z.enum(["platform", "none"]).optional(),
89
+ extraHosts: orgHostList("extraHosts"),
90
+ excludedHosts: orgHostList("excludedHosts"),
79
91
  })
80
92
  .strict();
81
93
  /** What an invalid stored `cloudNetwork` reads as: the allowlist with no host (never wider). */
82
94
  export const invalidCloudNetwork = () => ({
83
95
  mode: "allowlist",
84
- allowHosts: [],
96
+ base: "none",
85
97
  });
86
98
  /**
87
99
  * The org's auto-mode switch (auto mode spec §4.3): `allowed` or `off`; absent follows the
@@ -268,6 +280,28 @@ export function invalidStoredCloudNetwork(raw) {
268
280
  const v = asObject(raw).cloudNetwork;
269
281
  return v !== undefined && !CloudNetworkSettingSchema.safeParse(v).success;
270
282
  }
283
+ /**
284
+ * Whether `next` (absent: follow the platform) widens `prev` (spec §D3), both normalized (mode
285
+ * open, base platform, empty lists): the open mode where it was the allowlist; base none to
286
+ * platform; with base platform, dropping one of the stored exclusions; an extra host no stored
287
+ * extra covers. Over-strict on purpose: moving to base none with a platform entry as an extra is a
288
+ * narrowing these rules refuse (a token cannot pin a platform host the platform may drop later).
289
+ */
290
+ export function cloudNetworkWidens(prev, next) {
291
+ const mode = (v) => v?.mode ?? "open";
292
+ const base = (v) => v?.base ?? "platform";
293
+ if (mode(next) === "open" && mode(prev) !== "open")
294
+ return true;
295
+ if (base(next) === "platform" && base(prev) === "none")
296
+ return true;
297
+ if (base(next) === "platform") {
298
+ const kept = new Set(next?.excludedHosts ?? []);
299
+ if ((prev?.excludedHosts ?? []).some((h) => !kept.has(h)))
300
+ return true;
301
+ }
302
+ const prevExtra = (prev?.extraHosts ?? []).map((h) => h.toLowerCase());
303
+ return (next?.extraHosts ?? []).some((h) => !prevExtra.some((p) => coversHost(p, h.toLowerCase())));
304
+ }
271
305
  /** 组织设置服务:读取与修改(修改需 `org.update`,锁内实时复核角色,写审计)。 */
272
306
  let OrgSettingsService = class OrgSettingsService {
273
307
  db;
@@ -310,14 +344,27 @@ let OrgSettingsService = class OrgSettingsService {
310
344
  ]);
311
345
  return {
312
346
  autoMode,
313
- cloudNetwork: lim.egress === "none"
314
- ? { mode: "allowlist", allowHosts: [] }
315
- : { mode: "open", allowHosts: [...lim.allowHosts] },
347
+ cloudNetwork: {
348
+ allowHosts: [...lim.allowHosts],
349
+ orgHosts: lim.orgHosts,
350
+ off: lim.egress === "none",
351
+ },
316
352
  attribution,
317
353
  publicUrl: this.config.get().http.publicUrl !== undefined,
318
354
  compaction,
319
355
  };
320
356
  }
357
+ /**
358
+ * The org's effective sandbox-mode network (spec §D3): the cloud network's mode and the hosts,
359
+ * from the platform's `sandbox.limits` and the org's stored delta.
360
+ */
361
+ effectiveNetwork(settings) {
362
+ const lim = this.config.get().sandbox.limits;
363
+ return {
364
+ mode: orgCloudMode(lim, settings.cloudNetwork),
365
+ hosts: orgEffectiveHosts(lim, settings.cloudNetwork),
366
+ };
367
+ }
321
368
  /** 组织实际生效的沙箱 cpu / 内存(只读;由超级管理员在部署设置里覆盖)。 */
322
369
  async sandboxLimits(orgId) {
323
370
  const lim = this.config.get().sandbox.limits;
@@ -339,7 +386,10 @@ let OrgSettingsService = class OrgSettingsService {
339
386
  throw new ApiError("org.not_found", "Organization not found");
340
387
  return this.parseStored(orgId, row.settings);
341
388
  }
342
- /** The refusals of {@link update} that need no read of the org (the Platform tool's precheck). */
389
+ /**
390
+ * The refusals of {@link update} that need no read of the org (the Platform tool's precheck):
391
+ * auto mode where the platform turned it off.
392
+ */
343
393
  async check(patch) {
344
394
  // turning auto mode on where the platform turned it off is wider than the platform allows
345
395
  if (patch.autoMode === "allowed") {
@@ -349,6 +399,29 @@ let OrgSettingsService = class OrgSettingsService {
349
399
  }
350
400
  }
351
401
  }
402
+ /**
403
+ * Under `sandbox.limits.orgHosts: within` (spec §D2), refuses what would widen past the platform
404
+ * ceiling compared with the stored value `before`: the open cloud network where the org did not
405
+ * store it, or an extra host outside the platform's allowlist that the org did not store. Stored
406
+ * values are sent back as they are (the PATCH replaces `cloudNetwork` whole) and have no effect
407
+ * under the ceiling (they are filtered on read), so they never block a write.
408
+ */
409
+ assertWithinCeiling(before, patch) {
410
+ const cn = patch.cloudNetwork;
411
+ if (cn == null)
412
+ return;
413
+ const lim = this.config.get().sandbox.limits;
414
+ if (lim.orgHosts !== "within")
415
+ return;
416
+ if (cn.mode === "open" && before.cloudNetwork?.mode !== "open") {
417
+ throw new ApiError("org.sandbox_egress_not_allowed", "The platform limits sandbox networks to its allowlist; the open cloud network is not available", [{ reason: "open_not_allowed" }]);
418
+ }
419
+ const stored = new Set(before.cloudNetwork?.extraHosts ?? []);
420
+ const outside = (cn.extraHosts ?? []).filter((h) => !stored.has(h) && orgHostOutsideCeiling(lim, h));
421
+ if (outside.length > 0) {
422
+ throw new ApiError("org.sandbox_egress_not_allowed", `The platform limits sandbox hosts to its allowlist; ask a super admin to add ${outside.join(", ")} to sandbox.limits.allowHosts`, [{ reason: "outside_ceiling", hosts: outside }]);
423
+ }
424
+ }
352
425
  async update(orgId, patch, actorAccountId, actorTokenId,
353
426
  /** Merged into the audit detail (the Platform tool's `via: "agent"`). */
354
427
  auditDetail,
@@ -365,15 +438,9 @@ let OrgSettingsService = class OrgSettingsService {
365
438
  * never the Platform tool or an API token):
366
439
  * - `autoMode`: `allowed` where the organization runs `off` (an absent value follows the
367
440
  * platform); clearing it follows the platform too, never wider than the platform allows;
368
- * - `cloudNetwork`: `open` where the network is the allowlist, or a host the current allowlist
369
- * does not have (the deployment's `sandbox.limits.allowHosts` when the org gives none).
370
- * `cloudNetwork.allowHosts` is also the local sandbox-mode ceiling (`orgAllowedDomains` in
371
- * `sandbox/modes.ts` becomes `deviceLimits.localAllowedDomains`, which the device intersects
372
- * with its own list): an org with no `cloudNetwork` still caps its local devices at the
373
- * deployment's list, and an org whose network is `open` still caps them at its own `allowHosts`.
374
- * The host comparison therefore applies to both shapes, whatever the target mode: a patch may
375
- * only keep or lower the host set. Switching from `open` is a widening by itself, and the host
376
- * set must not grow even when the target stays `open` (spec §4.2, §4.3).
441
+ * - `cloudNetwork`: compared as stored deltas ({@link cloudNetworkWidens}), never as effective
442
+ * values: under the kill switch or the platform ceiling the effective values hide a widening
443
+ * that takes effect when the platform relaxes (org egress ceiling spec §D3).
377
444
  */
378
445
  async assertOnlyNarrows(before, patch) {
379
446
  if (patch.autoMode !== undefined) {
@@ -383,20 +450,9 @@ let OrgSettingsService = class OrgSettingsService {
383
450
  throw autoModeNotAllowed("Turning auto mode on needs a person in the organization settings.");
384
451
  }
385
452
  }
386
- if (patch.cloudNetwork !== undefined) {
387
- const lim = this.config.get().sandbox.limits;
388
- const defaultMode = lim.egress === "none" ? "allowlist" : "open";
389
- const defaultHosts = lim.egress === "none" ? [] : [...lim.allowHosts];
390
- const prev = before.cloudNetwork;
391
- const next = patch.cloudNetwork ?? undefined;
392
- const modeOf = (v) => v?.mode ?? defaultMode;
393
- const hostsOf = (v) => v?.allowHosts ?? defaultHosts;
394
- const nextMode = next?.mode ?? defaultMode;
395
- const widens = (nextMode === "open" && modeOf(prev) !== "open") ||
396
- !hostsOf(next).every((h) => hostsOf(prev).includes(h));
397
- if (widens) {
398
- throw new ApiError("org.sandbox_egress_not_allowed", "Widening the cloud network needs a person in the organization settings.");
399
- }
453
+ if (patch.cloudNetwork !== undefined &&
454
+ cloudNetworkWidens(before.cloudNetwork, patch.cloudNetwork ?? undefined)) {
455
+ throw new ApiError("org.sandbox_egress_not_allowed", "Widening the cloud network needs a person in the organization settings.");
400
456
  }
401
457
  }
402
458
  async updateIn(orgId, patch, actorAccountId, actorTokenId, auditDetail, opts) {
@@ -411,6 +467,7 @@ let OrgSettingsService = class OrgSettingsService {
411
467
  // again under the org lock: a hot config reload may have lowered the platform since
412
468
  await this.check(patch);
413
469
  // under the org lock, so the comparison is with the value the write replaces
470
+ this.assertWithinCeiling(before, patch);
414
471
  if (opts?.onlyNarrows)
415
472
  await this.assertOnlyNarrows(before, patch);
416
473
  const changes = Object.fromEntries(Object.entries(patch)
@@ -39,21 +39,25 @@ let OrgSettingsOperations = class OrgSettingsOperations {
39
39
  this.registry.register([
40
40
  defineOperation({
41
41
  id: "org-settings.get",
42
- description: "Read this org's settings: toolSearch, locale, sandboxToolPolicy, platformTool (on, read-only or off), autoMode (allowed or off: whether the org's devices may run in auto mode; absent follows the deployment's switch, and the org may never exceed it), cloudNetwork (the network of a cloud device in sandbox mode: open, or allowlist with its hosts; open means any public host, while loopback, private and cloud metadata addresses stay blocked), wakeOnBackgroundTask (absent means it follows the deployment), theme (the org's default theme id, null or absent following the platform, and personal: allowed or locked), uiArrangement (per list slot, the extension contributions the org hides and their order; per single slot, the contribution that replaces the built-in as use, null for the built-in; a slot not listed follows the platform), the deployment's auto-mode switch and cloud-network defaults, and the sandbox cpu / memory limits in effect.",
42
+ description: "Read this org's settings: toolSearch, locale, sandboxToolPolicy, platformTool (on, read-only or off), autoMode (allowed or off: whether the org's devices may run in auto mode; absent follows the deployment's switch, and the org may never exceed it), cloudNetwork (the org's sandbox-mode network stored as a delta over the platform's allowlist: mode open or allowlist for a cloud device in sandbox mode, absent following the platform; base platform or none; extraHosts the org adds; excludedHosts platform hosts it drops; open means any public host, while loopback, private and cloud metadata addresses stay blocked), wakeOnBackgroundTask (absent means it follows the deployment), theme (the org's default theme id, null or absent following the platform, and personal: allowed or locked), uiArrangement (per list slot, the extension contributions the org hides and their order; per single slot, the contribution that replaces the built-in as use, null for the built-in; a slot not listed follows the platform), the deployment's auto-mode switch and network (its allowlist, orgHosts: extend lets the org go beyond it, within makes it the ceiling, and off for the platform kill switch), effectiveNetwork (the mode and hosts the org's sandbox mode really gets), and the sandbox cpu / memory limits in effect.",
43
43
  input: z.object({}).strict(),
44
44
  example: {},
45
45
  authz: { orgAction: "org.read" },
46
46
  mirrors: ["GET /api/v1/orgs/:orgId/settings"],
47
47
  confirm: "read",
48
- run: async (_input, ctx) => ({
49
- settings: await this.settings.get(ctx.orgId),
50
- deployment: await this.settings.deployment(),
51
- sandboxLimits: await this.settings.sandboxLimits(ctx.orgId),
52
- }),
48
+ run: async (_input, ctx) => {
49
+ const settings = await this.settings.get(ctx.orgId);
50
+ return {
51
+ settings,
52
+ deployment: await this.settings.deployment(),
53
+ effectiveNetwork: this.settings.effectiveNetwork(settings),
54
+ sandboxLimits: await this.settings.sandboxLimits(ctx.orgId),
55
+ };
56
+ },
53
57
  }),
54
58
  defineOperation({
55
59
  id: "org-settings.update",
56
- description: "Change this org's settings (org admins). Give only the settings to change; null clears autoMode, cloudNetwork or wakeOnBackgroundTask so they follow the deployment again (refused when the deployment value is wider than what this tool may set). autoMode (allowed or off; the platform must allow it) and cloudNetwork ({ mode: open | allowlist, allowHosts? }, replaced whole, hosts left out following the deployment's list) may only narrow the org's devices here: turning auto mode on where the org has it off, switching the cloud network from allowlist to open, or adding a network host is refused and needs a person in the organization settings on the web. theme: { id, personal } sets the org's default theme (a theme id from themes.list, or null to follow the platform) and whether members may pick their own (allowed) or not (locked); null clears it. uiArrangement: { <slot>: { hidden, order } } (a list slot) or { <slot>: { use } } (a single slot: shell.brand, conversation.empty, conversation.composer.frame) replaces that slot's entry, where hidden, order and use name contribution keys <extension>/<contribution> (hidden ones are not listed in the web UI but their pages still open by URL; use null is the built-in); null for a slot makes it follow the platform again; platform.page is refused. Setting platformTool to off or read-only takes effect from the next call and cuts this Platform tool off in the org, so say so before asking; an org admin switches it back on in the web settings.",
60
+ description: "Change this org's settings (org admins). Give only the settings to change; null clears autoMode, cloudNetwork or wakeOnBackgroundTask so they follow the deployment again (refused when the deployment value is wider than what this tool may set). autoMode (allowed or off; the platform must allow it) and cloudNetwork ({ mode?, base?: platform | none, extraHosts?, excludedHosts? }, replaced whole, so send the stored fields you keep) may only narrow the org's devices here: turning auto mode on where the org has it off, switching the cloud network from allowlist to open, adding an extra host, dropping an exclusion or moving base from none to platform is refused and needs a person in the organization settings on the web. theme: { id, personal } sets the org's default theme (a theme id from themes.list, or null to follow the platform) and whether members may pick their own (allowed) or not (locked); null clears it. uiArrangement: { <slot>: { hidden, order } } (a list slot) or { <slot>: { use } } (a single slot: shell.brand, conversation.empty, conversation.composer.frame) replaces that slot's entry, where hidden, order and use name contribution keys <extension>/<contribution> (hidden ones are not listed in the web UI but their pages still open by URL; use null is the built-in); null for a slot makes it follow the platform again; platform.page is refused. Setting platformTool to off or read-only takes effect from the next call and cuts this Platform tool off in the org, so say so before asking; an org admin switches it back on in the web settings.",
57
61
  input: OrgSettingsPatchSchema.refine((i) => Object.values(i).some((v) => v !== undefined), {
58
62
  message: "give at least one setting",
59
63
  }),
@@ -64,7 +68,7 @@ let OrgSettingsOperations = class OrgSettingsOperations {
64
68
  errors: [
65
69
  {
66
70
  code: "org.sandbox_egress_not_allowed",
67
- next: "Through this tool the org's cloud network may only be narrowed: the host list may keep or lose hosts, and an open network may become an allowlist of hosts that list already has, but no change may add a host or switch an allowlist back to open (the host list is the local sandbox-mode ceiling whatever the cloud mode). To widen it, ask an org admin to change it in the organization settings on the web.",
71
+ next: "Through this tool the org's cloud network may only be narrowed: it may drop extra hosts, exclude platform hosts, move base to none or switch open to allowlist, but never add an extra host, drop an exclusion or switch back to open (the hosts are the local sandbox-mode ceiling whatever the cloud mode). To widen it, ask an org admin to change it in the organization settings on the web. When the platform limits hosts to its allowlist (deployment.cloudNetwork.orgHosts within), a host outside it needs a super admin.",
68
72
  },
69
73
  {
70
74
  code: "org.auto_mode_not_allowed",
@@ -81,7 +85,9 @@ let OrgSettingsOperations = class OrgSettingsOperations {
81
85
  ],
82
86
  precheck: (i, ctx) => precheckBy(async () => {
83
87
  await this.settings.check(i);
84
- await this.settings.assertOnlyNarrows(await this.settings.get(ctx.orgId), i);
88
+ const before = await this.settings.get(ctx.orgId);
89
+ this.settings.assertWithinCeiling(before, i);
90
+ await this.settings.assertOnlyNarrows(before, i);
85
91
  }),
86
92
  summary: async (i, ctx) => {
87
93
  const { theme, ...rest } = i;
@@ -119,7 +125,11 @@ let OrgSettingsOperations = class OrgSettingsOperations {
119
125
  const note = input.platformTool === undefined
120
126
  ? undefined
121
127
  : PLATFORM_TOOL_NOTE[settings.platformTool];
122
- return { settings, ...(note !== undefined && { note }) };
128
+ return {
129
+ settings,
130
+ effectiveNetwork: this.settings.effectiveNetwork(settings),
131
+ ...(note !== undefined && { note }),
132
+ };
123
133
  },
124
134
  }),
125
135
  ]);
@@ -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
+ }