@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
@@ -287,10 +287,11 @@ class Connection {
287
287
  });
288
288
  this.close("abort");
289
289
  });
290
+ return this.chain;
290
291
  }
291
292
  /** 读 lastSeq 之后的全部事件并发送(按 seq 去重:只发大于已发送值的)。 */
292
- async catchUp() {
293
- for (;;) {
293
+ async catchUp(maxPages = Number.POSITIVE_INFINITY) {
294
+ for (let page = 0; page < maxPages; page++) {
294
295
  const evs = await this.d.eventLog.readAfter(this.p.conversationId, this.lastSeq, PAGE);
295
296
  for (const e of evs) {
296
297
  if (this.closed)
@@ -357,6 +358,11 @@ class Connection {
357
358
  const denied = await authorize(this.d, this.p);
358
359
  if (denied !== null)
359
360
  this.fail(denied);
361
+ else {
362
+ // Pub/sub is a hint: a lost final notification must not leave an open stream stale.
363
+ // One page per authorized recheck bounds PG work; the shared chain deduplicates hints.
364
+ await this.enqueue(() => this.catchUp(1));
365
+ }
360
366
  }
361
367
  catch (err) {
362
368
  this.d.log.warn("conversation stream access re-check failed; closing", {
@@ -1,4 +1,5 @@
1
1
  import type { OutboxService } from "../../infra/outbox/outbox.service.js";
2
+ import type { RunDeletion } from "../run-deletion.js";
2
3
  import type { Waits } from "../waits.js";
3
4
  /**
4
5
  * The stops a transaction owes a sub-agent tree (transactional outbox spec §6 "Sub-agents"), on
@@ -6,8 +7,8 @@ import type { Waits } from "../waits.js";
6
7
  * - `{ runId }`: what a run's terminal transaction owes its children: its active fork invocation
7
8
  * child stops (`Waits.stopChildren`, sub-agents spec §12), and a sub-agent run a person stopped
8
9
  * stops its descendants (`Waits.stopDescendantsOfStopped`, agent map spec §6);
9
- * - `{ conversationId, byAccountId }`: a deleted root's whole tree below it stops
10
- * (`Waits.stopTree` without the root, agent map spec §10).
10
+ * - `{ conversationId, byAccountId }`: a deleted root's whole tree including the root stops
11
+ * (`Waits.stopTree` including the root, agent map spec §10).
11
12
  *
12
13
  * The caller still stops them right after its commit; the job is the backstop for a process that
13
14
  * died in between, {@link TREE_JOB_BACKSTOP_MS} later.
@@ -53,7 +54,7 @@ export declare function oweDeliverToParent(outbox: Pick<OutboxService, "add">, c
53
54
  * The `stop-tree` job (`MaintenanceProcessor`): every stop reads the active runs and stops only
54
55
  * those, so a run the direct call already stopped is not stopped again.
55
56
  */
56
- export declare function processStopTree(waits: Pick<Waits, "stopChildren" | "stopDescendantsOfStopped" | "stopTree">, data: StopTreeJobData): Promise<void>;
57
+ export declare function processStopTree(waits: Pick<Waits, "stopChildren" | "stopDescendantsOfStopped" | "stopTree">, data: StopTreeJobData, deletion: Pick<RunDeletion, "stopTree">): Promise<void>;
57
58
  /**
58
59
  * The `deliver-to-parent` job (`MaintenanceProcessor`): `Waits.childFinished` writes the delivery
59
60
  * once by the child run (idempotency keys under the parent conversation's row lock).
@@ -5,8 +5,8 @@ import { MAINTENANCE_QUEUE_NAME } from "../maintenance-queue.js";
5
5
  * - `{ runId }`: what a run's terminal transaction owes its children: its active fork invocation
6
6
  * child stops (`Waits.stopChildren`, sub-agents spec §12), and a sub-agent run a person stopped
7
7
  * stops its descendants (`Waits.stopDescendantsOfStopped`, agent map spec §6);
8
- * - `{ conversationId, byAccountId }`: a deleted root's whole tree below it stops
9
- * (`Waits.stopTree` without the root, agent map spec §10).
8
+ * - `{ conversationId, byAccountId }`: a deleted root's whole tree including the root stops
9
+ * (`Waits.stopTree` including the root, agent map spec §10).
10
10
  *
11
11
  * The caller still stops them right after its commit; the job is the backstop for a process that
12
12
  * died in between, {@link TREE_JOB_BACKSTOP_MS} later.
@@ -69,13 +69,13 @@ export function oweDeliverToParent(outbox, childRunId, orgId) {
69
69
  * The `stop-tree` job (`MaintenanceProcessor`): every stop reads the active runs and stops only
70
70
  * those, so a run the direct call already stopped is not stopped again.
71
71
  */
72
- export async function processStopTree(waits, data) {
72
+ export async function processStopTree(waits, data, deletion) {
73
73
  if ("runId" in data) {
74
74
  await waits.stopChildren(data.runId, null);
75
75
  await waits.stopDescendantsOfStopped(data.runId);
76
76
  return;
77
77
  }
78
- await waits.stopTree(data.conversationId, data.byAccountId, { includeSelf: false });
78
+ await deletion.stopTree(data.conversationId, data.byAccountId);
79
79
  }
80
80
  /**
81
81
  * The `deliver-to-parent` job (`MaintenanceProcessor`): `Waits.childFinished` writes the delivery
@@ -1,7 +1,7 @@
1
1
  import type { KernelConfig } from "../config/schema.js";
2
2
  import type { KernelSchemaDb } from "../db/kernel-schema.js";
3
3
  import type { KernelConfigService } from "../infra/config/kernel-config.service.js";
4
- import type { OrgSettings } from "../orgs/settings.service.js";
4
+ import type { CloudNetworkSetting, OrgSettings } from "../orgs/settings.service.js";
5
5
  import { type DevicesAutoMode } from "./platform-auto-mode.js";
6
6
  /**
7
7
  * Device modes (auto mode spec §4.1–§4.3): who may choose auto mode, and the network each mode
@@ -24,8 +24,33 @@ export interface DeviceNetwork {
24
24
  */
25
25
  export interface DeploymentDevicePolicy {
26
26
  autoMode: DevicesAutoMode;
27
- limits: Pick<KernelConfig["sandbox"]["limits"], "egress" | "allowHosts">;
27
+ limits: NetworkLimits;
28
28
  }
29
+ /**
30
+ * The platform's network fields (`sandbox.limits`): the kill switch, the allowlist and whether
31
+ * organizations may go beyond it (org egress ceiling spec §D2).
32
+ */
33
+ export type NetworkLimits = Pick<KernelConfig["sandbox"]["limits"], "egress" | "allowHosts" | "orgHosts">;
34
+ /** Whether the allowlist entry `pattern` admits `host` (`*.x.com`: subdomains, never the apex). */
35
+ export declare const coversHost: (pattern: string, host: string) => boolean;
36
+ /**
37
+ * Whether `host` is beyond the platform's ceiling: `sandbox.limits.orgHosts` is `within` and no
38
+ * entry of `sandbox.limits.allowHosts` covers it (a wildcard host is covered by a wider wildcard).
39
+ * Only a super admin can allow such a host.
40
+ */
41
+ export declare function orgHostOutsideCeiling(limits: NetworkLimits, host: string): boolean;
42
+ /**
43
+ * The org's effective allowlist (org egress ceiling spec §D1): empty under the kill switch; else
44
+ * the org's extras (only those inside the ceiling under `within`) on top of the platform's list
45
+ * minus the org's exclusions, or the extras alone when the org's base is `none`. The one place
46
+ * that combines the platform's hosts with the org's.
47
+ */
48
+ export declare function orgEffectiveHosts(limits: NetworkLimits, org: CloudNetworkSetting | undefined): string[];
49
+ /**
50
+ * The org's cloud network in sandbox mode (spec §D2): the allowlist under the kill switch or the
51
+ * platform ceiling (`orgHosts: within`), else the org's mode (open by default).
52
+ */
53
+ export declare function orgCloudMode(limits: NetworkLimits, org: CloudNetworkSetting | undefined): "open" | "allowlist";
29
54
  /**
30
55
  * The platform side of the policy, read live: the effective auto-mode switch and the
31
56
  * `sandbox.limits` network fields (in the caller's transaction when there is one).
@@ -52,27 +77,14 @@ export interface EffectiveDevicePolicy {
52
77
  }
53
78
  /** The mode the platform and the org allow: `auto` only when neither turns it off. */
54
79
  export declare function allowedDeviceMode(platform: DevicesAutoMode, org: OrgDeviceSettings["autoMode"]): SandboxMode;
55
- /**
56
- * The org's allowlist (the hosts a local device in sandbox mode may reach): the org's own list when
57
- * it gave one, else `sandbox.limits.allowHosts`; empty under the platform kill switch.
58
- */
80
+ /** The org's allowlist (the hosts a local device in sandbox mode may reach): {@link orgEffectiveHosts}. */
59
81
  export declare function orgAllowedDomains(deployment: DeploymentDevicePolicy, org: OrgDeviceSettings): string[];
60
82
  /**
61
- * The cloud network (auto mode spec §4.3): `open-public` in auto mode while the org's
62
- * `cloudNetwork` is `open` (the default), else the org's allowlist. `sandbox.limits.egress: none`
63
- * forces an empty allowlist (the platform kill switch, R20).
83
+ * The cloud network (auto mode spec §4.3): `open-public` in auto mode; in sandbox mode the org's
84
+ * cloud network ({@link orgCloudMode}). `sandbox.limits.egress: none` forces an empty allowlist
85
+ * (the platform kill switch, R20).
64
86
  */
65
87
  export declare function deviceNetwork(deployment: DeploymentDevicePolicy, org: OrgDeviceSettings, mode: SandboxMode): DeviceNetwork;
66
- /**
67
- * The org's sandbox-mode network, from the deployment default, the org's `cloudNetwork` choice and
68
- * the platform kill switch: `sandbox.limits.egress: "none"` forces an empty allowlist (R20, every
69
- * read); otherwise `open-public` when either says open, else the org's hosts over the deployment's
70
- * list.
71
- */
72
- export declare function orgSandboxNetwork(deployment: {
73
- mode: "open" | "allowlist";
74
- allowHosts: string[];
75
- }, org: OrgDeviceSettings["cloudNetwork"], egress?: "none" | "allowlist"): DeviceNetwork;
76
88
  /**
77
89
  * The effective device policy. `deviceMode` is the device's own choice (a local machine's
78
90
  * reported mode; null = follow the platform and the org). A stored mode the ceiling forbids is cut,
@@ -1,4 +1,41 @@
1
1
  import { readDevicesAutoMode } from "./platform-auto-mode.js";
2
+ /** Whether the allowlist entry `pattern` admits `host` (`*.x.com`: subdomains, never the apex). */
3
+ export const coversHost = (pattern, host) => pattern === host || (pattern.startsWith("*.") && host.endsWith(pattern.slice(1)));
4
+ /**
5
+ * Whether `host` is beyond the platform's ceiling: `sandbox.limits.orgHosts` is `within` and no
6
+ * entry of `sandbox.limits.allowHosts` covers it (a wildcard host is covered by a wider wildcard).
7
+ * Only a super admin can allow such a host.
8
+ */
9
+ export function orgHostOutsideCeiling(limits, host) {
10
+ if (limits.orgHosts !== "within")
11
+ return false;
12
+ const h = host.toLowerCase();
13
+ return !limits.allowHosts.some((p) => coversHost(p.toLowerCase(), h));
14
+ }
15
+ /**
16
+ * The org's effective allowlist (org egress ceiling spec §D1): empty under the kill switch; else
17
+ * the org's extras (only those inside the ceiling under `within`) on top of the platform's list
18
+ * minus the org's exclusions, or the extras alone when the org's base is `none`. The one place
19
+ * that combines the platform's hosts with the org's.
20
+ */
21
+ export function orgEffectiveHosts(limits, org) {
22
+ if (limits.egress === "none")
23
+ return [];
24
+ const extra = (org?.extraHosts ?? []).filter((h) => !orgHostOutsideCeiling(limits, h));
25
+ if (org?.base === "none")
26
+ return [...new Set(extra)];
27
+ const excluded = new Set(org?.excludedHosts ?? []);
28
+ return [...new Set([...limits.allowHosts.filter((h) => !excluded.has(h)), ...extra])];
29
+ }
30
+ /**
31
+ * The org's cloud network in sandbox mode (spec §D2): the allowlist under the kill switch or the
32
+ * platform ceiling (`orgHosts: within`), else the org's mode (open by default).
33
+ */
34
+ export function orgCloudMode(limits, org) {
35
+ if (limits.egress === "none" || limits.orgHosts === "within")
36
+ return "allowlist";
37
+ return org?.mode ?? "open";
38
+ }
2
39
  /**
3
40
  * The platform side of the policy, read live: the effective auto-mode switch and the
4
41
  * `sandbox.limits` network fields (in the caller's transaction when there is one).
@@ -11,19 +48,14 @@ export async function readDeploymentDevicePolicy(db, config) {
11
48
  export function allowedDeviceMode(platform, org) {
12
49
  return platform === "allowed" && org !== "off" ? "auto" : "sandbox";
13
50
  }
14
- /**
15
- * The org's allowlist (the hosts a local device in sandbox mode may reach): the org's own list when
16
- * it gave one, else `sandbox.limits.allowHosts`; empty under the platform kill switch.
17
- */
51
+ /** The org's allowlist (the hosts a local device in sandbox mode may reach): {@link orgEffectiveHosts}. */
18
52
  export function orgAllowedDomains(deployment, org) {
19
- if (deployment.limits.egress === "none")
20
- return [];
21
- return [...(org.cloudNetwork?.allowHosts ?? deployment.limits.allowHosts)];
53
+ return orgEffectiveHosts(deployment.limits, org.cloudNetwork);
22
54
  }
23
55
  /**
24
- * The cloud network (auto mode spec §4.3): `open-public` in auto mode while the org's
25
- * `cloudNetwork` is `open` (the default), else the org's allowlist. `sandbox.limits.egress: none`
26
- * forces an empty allowlist (the platform kill switch, R20).
56
+ * The cloud network (auto mode spec §4.3): `open-public` in auto mode; in sandbox mode the org's
57
+ * cloud network ({@link orgCloudMode}). `sandbox.limits.egress: none` forces an empty allowlist
58
+ * (the platform kill switch, R20).
27
59
  */
28
60
  export function deviceNetwork(deployment, org, mode) {
29
61
  if (deployment.limits.egress === "none")
@@ -31,24 +63,11 @@ export function deviceNetwork(deployment, org, mode) {
31
63
  // auto mode is 开放挡内网 whatever the org says; only sandbox mode applies `cloudNetwork`
32
64
  if (mode === "auto")
33
65
  return { kind: "open-public", hosts: [] };
34
- if ((org.cloudNetwork?.mode ?? "open") === "open") {
66
+ if (orgCloudMode(deployment.limits, org.cloudNetwork) === "open") {
35
67
  return { kind: "open-public", hosts: [] };
36
68
  }
37
69
  return { kind: "allowlist", hosts: orgAllowedDomains(deployment, org) };
38
70
  }
39
- /**
40
- * The org's sandbox-mode network, from the deployment default, the org's `cloudNetwork` choice and
41
- * the platform kill switch: `sandbox.limits.egress: "none"` forces an empty allowlist (R20, every
42
- * read); otherwise `open-public` when either says open, else the org's hosts over the deployment's
43
- * list.
44
- */
45
- export function orgSandboxNetwork(deployment, org, egress = "allowlist") {
46
- if (egress === "none")
47
- return { kind: "allowlist", hosts: [] };
48
- if ((org?.mode ?? deployment.mode) === "open")
49
- return { kind: "open-public", hosts: [] };
50
- return { kind: "allowlist", hosts: [...(org?.allowHosts ?? deployment.allowHosts)] };
51
- }
52
71
  /**
53
72
  * The effective device policy. `deviceMode` is the device's own choice (a local machine's
54
73
  * reported mode; null = follow the platform and the org). A stored mode the ceiling forbids is cut,
@@ -139,10 +139,13 @@ export declare const isInstance: (row: Pick<Row, "handle" | "created_at">, gone:
139
139
  * startup config) while an org can be on it: auto mode always is, and a sandbox-mode cloud device
140
140
  * keeps its org's cloud network, open by default, so turning auto mode off does not avoid it
141
141
  * (auto mode hardening spec K3). Only the kill switch (`sandbox.limits.egress: none`) does.
142
+ * - `sandbox.limits.orgHosts: within` while the startup config does not turn auto mode off: the
143
+ * ceiling limits sandbox mode only, and auto mode (the default of every device) keeps the open
144
+ * network (org egress ceiling spec §D2). The admin console's runtime choice is not seen here.
142
145
  * No run duration limit (`runtime.maxRunSeconds` 0, the default) cuts no command, so there is
143
146
  * nothing to tell.
144
147
  */
145
- export declare function sandboxConfigWarnings(cfg: Pick<KernelConfig, "runtime" | "sandbox" | "extensionConfig">, providerPlugin?: string): {
148
+ export declare function sandboxConfigWarnings(cfg: Pick<KernelConfig, "runtime" | "sandbox" | "extensionConfig"> & Partial<Pick<KernelConfig, "devices">>, providerPlugin?: string): {
146
149
  level: "warn";
147
150
  message: string;
148
151
  }[];
@@ -151,6 +151,9 @@ function tagged(impl, tag, actor, before) {
151
151
  * startup config) while an org can be on it: auto mode always is, and a sandbox-mode cloud device
152
152
  * keeps its org's cloud network, open by default, so turning auto mode off does not avoid it
153
153
  * (auto mode hardening spec K3). Only the kill switch (`sandbox.limits.egress: none`) does.
154
+ * - `sandbox.limits.orgHosts: within` while the startup config does not turn auto mode off: the
155
+ * ceiling limits sandbox mode only, and auto mode (the default of every device) keeps the open
156
+ * network (org egress ceiling spec §D2). The admin console's runtime choice is not seen here.
154
157
  * No run duration limit (`runtime.maxRunSeconds` 0, the default) cuts no command, so there is
155
158
  * nothing to tell.
156
159
  */
@@ -165,6 +168,14 @@ export function sandboxConfigWarnings(cfg, providerPlugin) {
165
168
  });
166
169
  }
167
170
  }
171
+ if (cfg.sandbox.limits.orgHosts === "within" &&
172
+ cfg.sandbox.limits.egress !== "none" &&
173
+ cfg.devices?.autoMode !== "off") {
174
+ out.push({
175
+ level: "warn",
176
+ message: "sandbox.limits.orgHosts is within but devices.autoMode is not off: the platform allowlist limits sandbox mode only; devices in auto mode (the default) still reach the open public network. Set devices.autoMode to off (or turn auto mode off in the admin console) for a hard ceiling",
177
+ });
178
+ }
168
179
  const run = cfg.runtime.maxRunSeconds;
169
180
  const cmd = cfg.sandbox.limits.maxCommandSeconds;
170
181
  if (run > 0 && run < cmd) {
@@ -51,6 +51,8 @@ export interface NetworkGrantContext {
51
51
  * command may reach in sandbox mode.
52
52
  */
53
53
  limits: Pick<SandboxLimits, "network">;
54
+ /** Whether a host is beyond the platform's ceiling (org egress ceiling spec §D2). */
55
+ outsideCeiling?: (host: string) => boolean;
54
56
  }
55
57
  /**
56
58
  * Why `host` cannot be one of a task's network grants (network ask-to-allow spec §8.1), or null
@@ -80,7 +80,9 @@ export function networkGrantRefusal(host, ctx) {
80
80
  if (!orgAllows(host, ctx.limits)) {
81
81
  return {
82
82
  code: "needs_admin",
83
- message: `${host} is not in the organization's network allowlist; only an organization admin can add it`,
83
+ message: ctx.outsideCeiling?.(host) === true
84
+ ? `${host} is not in the platform's network allowlist, which limits this organization; only a super admin can add it`
85
+ : `${host} is not in the organization's network allowlist; only an organization admin can add it`,
84
86
  };
85
87
  }
86
88
  return null;
@@ -113,6 +113,22 @@ export function tickerOf(t) {
113
113
  }
114
114
  /** How far back a DST transition can move a tick: longer than any gap (spec §5). */
115
115
  const TRANSITION_LOOKBACK_MS = 6 * 3600_000;
116
+ /**
117
+ * The cron library's search for the next date, or null when it gives up: it refuses to look more
118
+ * than a few years past the current date ("No execution date was found in the next 8 years"),
119
+ * which a yearly or Feb 29 expression reaches while the gap sample walks ahead. Any other error
120
+ * is thrown.
121
+ */
122
+ function nextOrNull(search) {
123
+ try {
124
+ return search();
125
+ }
126
+ catch (e) {
127
+ if (e instanceof Error && /No execution date was found/.test(e.message))
128
+ return null;
129
+ throw e;
130
+ }
131
+ }
116
132
  /**
117
133
  * {@link nextTick} for one trigger, with its `CronTime`s built once: callers that walk many ticks
118
134
  * (the gap sample, the catch-up enumeration) reuse one ticker instead of rebuilding per tick.
@@ -129,7 +145,10 @@ function ticker(t) {
129
145
  return (after) => {
130
146
  let cursor = after;
131
147
  for (let i = 0; i < 10; i++) {
132
- const tick = new Date(time.getNextDateFrom(cursor, t.timeZone).toMillis());
148
+ const next = nextOrNull(() => time.getNextDateFrom(cursor, t.timeZone).toMillis());
149
+ if (next === null)
150
+ return null;
151
+ const tick = new Date(next);
133
152
  const ms = tick.getTime();
134
153
  // CronTime moves a tick that falls in a DST gap to the next valid instant; the spec says a
135
154
  // skipped local time does not fire, so keep only ticks whose wall clock the expression
@@ -138,7 +157,7 @@ function ticker(t) {
138
157
  return tick;
139
158
  }
140
159
  const wall = localWallClock(tick, t.timeZone);
141
- if (wallTime.getNextDateFrom(new Date(wall - 1000), "UTC").toMillis() === wall)
160
+ if (nextOrNull(() => wallTime.getNextDateFrom(new Date(wall - 1000), "UTC").toMillis()) === wall)
142
161
  return tick;
143
162
  cursor = tick;
144
163
  }
@@ -27,6 +27,7 @@ import { orgAllows } from "../local-devices/network-grants.js";
27
27
  import { OrgLock } from "../orgs/org-lock.js";
28
28
  import { can, roleAtLeast } from "../orgs/roles.js";
29
29
  import { ProviderRegistry } from "../runtime/providers.js";
30
+ import { orgHostOutsideCeiling } from "../sandbox/modes.js";
30
31
  import { SandboxService } from "../sandbox/sandbox.service.js";
31
32
  import { isTimeZone } from "../time-zone.js";
32
33
  import { ToolRegistry } from "../tools/registry.js";
@@ -1111,7 +1112,8 @@ let ScheduledTasksService = class ScheduledTasksService {
1111
1112
  */
1112
1113
  async networkGrantContext(orgId) {
1113
1114
  const limits = await this.sandbox.ceilingLimits(orgId);
1114
- return { limits };
1115
+ const platform = this.config.get().sandbox.limits;
1116
+ return { limits, outsideCeiling: (h) => orgHostOutsideCeiling(platform, h) };
1115
1117
  }
1116
1118
  /**
1117
1119
  * The device a task's runs use, as far as the task tells: a `new` task's own device, a
@@ -44,6 +44,8 @@ export declare const localOnlyNote: (hosts: readonly string[]) => string;
44
44
  export declare const alwaysRefusedNote: (hosts: readonly string[]) => string;
45
45
  /** The org layer (spec §6.6): only an org admin can lift it. */
46
46
  export declare const orgLayerNote: (hosts: readonly string[]) => string;
47
+ /** An org-layer host beyond the platform's ceiling (org egress ceiling spec §D2): only a super admin. */
48
+ export declare const platformCeilingNote: (hosts: readonly string[]) => string;
47
49
  /** The address layer (spec §6.6): nobody can lift it. */
48
50
  export declare const addressLayerNote: (hosts: readonly string[]) => string;
49
51
  /**
@@ -63,6 +65,11 @@ export interface NetworkPlanContext {
63
65
  } | null;
64
66
  /** The scheduled task run the run serves (null / undefined: attended). */
65
67
  unattended: UnattendedRun | null | undefined;
68
+ /**
69
+ * Whether a host is beyond the platform's ceiling (`sandbox.limits.orgHosts: within`, org egress
70
+ * ceiling spec §D2): only a super admin can add it, so its note names the super admin.
71
+ */
72
+ outsideCeiling?: (host: string) => boolean;
66
73
  }
67
74
  /** What to do with a command's refused hosts. */
68
75
  export interface NetworkPlan {
@@ -54,6 +54,10 @@ export const alwaysRefusedNote = (hosts) => `${blockedLead(hosts)} The user allo
54
54
  export const orgLayerNote = (hosts) => one(hosts)
55
55
  ? `[network] ${list(hosts)} is not in the organization's network allowlist. Only an organization admin can add it; the user can ask an admin from the conversation. Continue without it or tell the user.`
56
56
  : `[network] ${list(hosts)} are not in the organization's network allowlist. Only an organization admin can add them; the user can ask an admin from the conversation. Continue without them or tell the user.`;
57
+ /** An org-layer host beyond the platform's ceiling (org egress ceiling spec §D2): only a super admin. */
58
+ export const platformCeilingNote = (hosts) => one(hosts)
59
+ ? `[network] ${list(hosts)} is not in the platform's network allowlist, which limits this organization. Only a super admin can add it; organization admins cannot. Continue without it or tell the user.`
60
+ : `[network] ${list(hosts)} are not in the platform's network allowlist, which limits this organization. Only a super admin can add them; organization admins cannot. Continue without them or tell the user.`;
57
61
  /** The address layer (spec §6.6): nobody can lift it. */
58
62
  export const addressLayerNote = (hosts) => one(hosts)
59
63
  ? `[network] ${list(hosts)} is a private or local address, which commands can never reach.`
@@ -102,6 +106,7 @@ export function blockedEventHosts(blocked) {
102
106
  export function planNetworkAsk(blocked, run, ctx) {
103
107
  const address = [];
104
108
  const org = [];
109
+ const platform = [];
105
110
  const refused = [];
106
111
  const unattended = [];
107
112
  const taskIgnored = [];
@@ -115,7 +120,10 @@ export function planNetworkAsk(blocked, run, ctx) {
115
120
  if (b.layer === "address")
116
121
  address.push(b.host);
117
122
  else if (b.layer === "org") {
118
- org.push(b.host);
123
+ if (ctx.outsideCeiling?.(b.host) === true)
124
+ platform.push(b.host);
125
+ else
126
+ org.push(b.host);
119
127
  if (unattendedRules(ctx.unattended))
120
128
  missingGrants.push(networkGrantKey(b.host));
121
129
  }
@@ -157,6 +165,8 @@ export function planNetworkAsk(blocked, run, ctx) {
157
165
  }
158
166
  if (org.length > 0)
159
167
  notes.push(orgLayerNote(org));
168
+ if (platform.length > 0)
169
+ notes.push(platformCeilingNote(platform));
160
170
  if (address.length > 0)
161
171
  notes.push(addressLayerNote(address));
162
172
  return { ask, scopes: ["once", "always"], notes, missingGrants };
@@ -35,6 +35,7 @@ import { rootSurfaceOf } from "../runtime/subagents/child.js";
35
35
  import { SubagentMessages } from "../runtime/subagents/messages.js";
36
36
  import { pairStoppedForks } from "../runtime/subagents/skill-fork.js";
37
37
  import { SubagentsService } from "../runtime/subagents/subagents.service.js";
38
+ import { orgHostOutsideCeiling } from "../sandbox/modes.js";
38
39
  import { isSessionGrantableRule, } from "../sandbox/review/index.js";
39
40
  import { CommandReviewService } from "../sandbox/review/review.service.js";
40
41
  import { appendMissingGrant, connectionGrantKey, UNATTENDED_CONNECTION_ERROR, UNATTENDED_ELICITATION_NOTE, UNATTENDED_QUESTION_ERROR, unattendedFails, unattendedRunOf, } from "../schedules/unattended.js";
@@ -1191,7 +1192,12 @@ let ToolPipeline = class ToolPipeline {
1191
1192
  const run = hosts.some((h) => h.layer === "device")
1192
1193
  ? await network.grants.runState(ctx.runId, report.deviceId)
1193
1194
  : null;
1194
- const plan = planNetworkAsk(hosts, run, { device, unattended: ctx.unattended });
1195
+ const limits = this.config.get().sandbox.limits;
1196
+ const plan = planNetworkAsk(hosts, run, {
1197
+ device,
1198
+ unattended: ctx.unattended,
1199
+ outsideCeiling: (h) => orgHostOutsideCeiling(limits, h),
1200
+ });
1195
1201
  if (ctx.unattended != null) {
1196
1202
  for (const key of plan.missingGrants) {
1197
1203
  await appendMissingGrant(this.deps.db, ctx.unattended.taskRunId, key);
@@ -1424,7 +1430,11 @@ let ToolPipeline = class ToolPipeline {
1424
1430
  }
1425
1431
  config = { config: effective.config };
1426
1432
  }
1427
- const r = await this.bounded(ctx.signal, (signal) => handler(input, { ...base, ...config, signal }), undefined, timeoutMs);
1433
+ const r = await this.bounded(ctx.signal, async (signal) => {
1434
+ await this.txHost.run(async () => { });
1435
+ signal.throwIfAborted();
1436
+ return handler(input, { ...base, ...config, signal });
1437
+ }, undefined, timeoutMs);
1428
1438
  if (r === "timeout") {
1429
1439
  return { kind: "error", message: timeoutText(tool.key, timeoutMs) };
1430
1440
  }
@@ -1569,6 +1579,8 @@ let ToolPipeline = class ToolPipeline {
1569
1579
  },
1570
1580
  });
1571
1581
  const session = await opened;
1582
+ await this.txHost.run(async () => { });
1583
+ signal.throwIfAborted();
1572
1584
  return source.resources
1573
1585
  ? runResourceTool(session, source.name, input)
1574
1586
  : // 交回已复核的定义(connector_tools.spec,含 connectorData):连接器按它路由,远端变化须先经漂移复核
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@capybara-hq/kernel",
3
- "version": "0.1.0-rc.33",
3
+ "version": "0.1.0-rc.35",
4
4
  "description": "Capybara kernel: config, database, plugin host and HTTP API of the Capybara agent platform",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
@@ -65,7 +65,7 @@
65
65
  "yaml": "^2.9.1",
66
66
  "yauzl": "3.4.0",
67
67
  "zod": "^4.6.7",
68
- "@capybara-hq/plugin-sdk": "^0.1.0-rc.24"
68
+ "@capybara-hq/plugin-sdk": "^0.1.0-rc.25"
69
69
  },
70
70
  "devDependencies": {
71
71
  "@langchain/langgraph-checkpoint-validation": "^1.2.0",
@@ -74,7 +74,7 @@
74
74
  "@types/ws": "^8.18.2",
75
75
  "@types/yauzl": "3.4.0",
76
76
  "ws": "^8.22.0",
77
- "@capybara-hq/testing": "0.1.0-rc.19"
77
+ "@capybara-hq/testing": "0.1.0-rc.20"
78
78
  },
79
79
  "scripts": {
80
80
  "build": "tsc -b"
@@ -0,0 +1,38 @@
1
+ -- Org egress ceiling (spec 2026-11-15-org-egress-ceiling-design.md §D5): an org's cloudNetwork
2
+ -- stops replacing the platform's allowlist with a copy (`allowHosts`) and stores a delta over it
3
+ -- (`base`, `extraHosts`, `excludedHosts`). A migration cannot read the deployment's config, so a
4
+ -- stored list is kept exactly: `base: none` (only the org's own hosts) with the list as its extras,
5
+ -- never wider than before. An org admin re-attaches to the platform by following it again.
6
+ --
7
+ -- Only an object cloudNetwork whose allowHosts is an array of distinct strings is converted, in its
8
+ -- order. Anything else (a non-array allowHosts copied in by 0130, duplicates, non-string elements)
9
+ -- is left alone: the old reader already read it as invalid, the empty allowlist, and so does the
10
+ -- new one; converting it would widen it. Idempotent: a converted row has no allowHosts left.
11
+ UPDATE orgs
12
+ SET settings = jsonb_set(
13
+ settings,
14
+ '{cloudNetwork}',
15
+ ((settings->'cloudNetwork') - 'allowHosts')
16
+ || '{"base":"none"}'::jsonb
17
+ || COALESCE(
18
+ (
19
+ SELECT jsonb_build_object('extraHosts', jsonb_agg(h ORDER BY first_pos))
20
+ FROM (
21
+ SELECT e.value AS h, min(e.pos) AS first_pos
22
+ FROM jsonb_array_elements(settings->'cloudNetwork'->'allowHosts')
23
+ WITH ORDINALITY AS e(value, pos)
24
+ WHERE jsonb_typeof(e.value) = 'string'
25
+ GROUP BY e.value
26
+ ) AS uniq
27
+ HAVING count(*) > 0
28
+ ),
29
+ '{}'::jsonb
30
+ )
31
+ )
32
+ WHERE jsonb_typeof(settings->'cloudNetwork') = 'object'
33
+ AND jsonb_typeof(settings->'cloudNetwork'->'allowHosts') = 'array'
34
+ AND jsonb_array_length(settings->'cloudNetwork'->'allowHosts') = (
35
+ SELECT count(DISTINCT e.value)
36
+ FROM jsonb_array_elements(settings->'cloudNetwork'->'allowHosts') AS e(value)
37
+ WHERE jsonb_typeof(e.value) = 'string'
38
+ );
@@ -0,0 +1,2 @@
1
+ -- A new acquisition of the same run revokes all older worker transactions.
2
+ ALTER TABLE runs ADD COLUMN IF NOT EXISTS execution_id text;
@@ -0,0 +1,6 @@
1
+ -- A shared rotating cursor bounds each recovery pass without starving later active runs.
2
+ CREATE TABLE IF NOT EXISTS run_recovery_cursors (
3
+ name text PRIMARY KEY,
4
+ since timestamptz,
5
+ run_id text
6
+ );