@capybara-hq/kernel 0.1.0-rc.30 → 0.1.0-rc.31

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 (63) hide show
  1. package/bootstrap.json +3 -3
  2. package/dist/catalog/marketplace-fetch.d.ts +5 -2
  3. package/dist/catalog/marketplace-fetch.js +4 -1
  4. package/dist/catalog/requests.service.d.ts +6 -5
  5. package/dist/catalog/requests.service.js +7 -6
  6. package/dist/config/load.d.ts +6 -0
  7. package/dist/config/load.js +26 -0
  8. package/dist/config/schema.js +5 -5
  9. package/dist/conversations/events.d.ts +10 -0
  10. package/dist/conversations/events.js +23 -1
  11. package/dist/devices/devices.controller.js +3 -2
  12. package/dist/devices/devices.service.d.ts +17 -5
  13. package/dist/devices/devices.service.js +24 -13
  14. package/dist/devices/dto.d.ts +7 -6
  15. package/dist/devices/dto.js +6 -5
  16. package/dist/errors.d.ts +6 -1
  17. package/dist/errors.js +6 -1
  18. package/dist/evals/reconstruct.js +18 -8
  19. package/dist/extensions/bootstrap.d.ts +1 -1
  20. package/dist/extensions/bootstrap.js +7 -1
  21. package/dist/extensions/installs.js +4 -1
  22. package/dist/lifecycle/kernel-lifecycle.js +1 -3
  23. package/dist/net/public-address.d.ts +14 -4
  24. package/dist/net/public-address.js +22 -12
  25. package/dist/net/safe-fetch.d.ts +2 -1
  26. package/dist/net/safe-fetch.js +16 -4
  27. package/dist/packages/npm.d.ts +28 -9
  28. package/dist/packages/npm.js +30 -19
  29. package/dist/packages/provenance.d.ts +3 -1
  30. package/dist/packages/provenance.js +7 -3
  31. package/dist/platform/ops/devices.ops.js +1 -1
  32. package/dist/platform/ops/platform.ops.d.ts +3 -1
  33. package/dist/platform/ops/platform.ops.js +11 -13
  34. package/dist/runtime/context/build.d.ts +10 -1
  35. package/dist/runtime/context/build.js +44 -10
  36. package/dist/runtime/context/compaction.d.ts +27 -8
  37. package/dist/runtime/context/compaction.js +133 -58
  38. package/dist/runtime/context/fit.d.ts +54 -22
  39. package/dist/runtime/context/fit.js +116 -40
  40. package/dist/runtime/model-call.d.ts +0 -8
  41. package/dist/runtime/model-call.js +185 -83
  42. package/dist/sandbox/review/classifier.d.ts +2 -0
  43. package/dist/sandbox/review/classifier.js +12 -1
  44. package/dist/sandbox/review/index.d.ts +3 -3
  45. package/dist/sandbox/review/index.js +3 -3
  46. package/dist/sandbox/review/review.service.d.ts +12 -4
  47. package/dist/sandbox/review/review.service.js +88 -19
  48. package/dist/sandbox/review/rules.d.ts +6 -0
  49. package/dist/sandbox/review/rules.js +1013 -95
  50. package/dist/sandbox/review/types.d.ts +21 -4
  51. package/dist/sandbox/review/types.js +41 -5
  52. package/dist/sandbox/sandbox.service.d.ts +8 -7
  53. package/dist/sandbox/sandbox.service.js +16 -16
  54. package/dist/setup/kernel-checks.js +3 -2
  55. package/dist/setup/oauth-token-probe.d.ts +1 -8
  56. package/dist/setup/oauth-token-probe.js +0 -16
  57. package/dist/tools/builtins/sandbox/common.d.ts +1 -1
  58. package/dist/tools/builtins/sandbox/common.js +1 -1
  59. package/dist/tools/builtins/tool-search.js +4 -3
  60. package/dist/tools/oauth/discovery.d.ts +38 -16
  61. package/dist/tools/oauth/discovery.js +59 -33
  62. package/dist/tools/pipeline.js +17 -13
  63. package/package.json +1 -1
@@ -15,12 +15,23 @@ export interface RuleHit {
15
15
  reason: string;
16
16
  }
17
17
  /**
18
- * Whether a rule id may back the person's `本会话允许同类` grant: one concrete rule class, never a
19
- * catch-all. The `unsure.*` hits (`unsure.uncovered`, `unsure.unparsed`) stand for "no rule decided
20
- * this", so remembering one would allow every future parser-unreadable command for the conversation
21
- * — the bucket the review keeps fail-closed. A classifier ask has no rule at all.
18
+ * Whether a rule id may back the person's `本会话允许同类` grant: one concrete rule class the person
19
+ * can reason about, never a catch-all. The `unsure.*` hits stand for "no rule decided this", so
20
+ * remembering one would allow every future parser-unreadable command for the conversation — the
21
+ * bucket the review keeps fail-closed. A classifier ask has no rule at all.
22
22
  */
23
23
  export declare const isSessionGrantableRule: (rule: string | null) => rule is string;
24
+ /**
25
+ * The rule outcome once the person's session grants are applied (hardening spec 2026-11-15 R4): an
26
+ * `ask` line is allowed only when **every** ask hit's class is granted and **no** `unsure` hit is
27
+ * left — a grant for one class never lets another class, or an unread part of the line, through.
28
+ * Otherwise the outcome stays, and `hit` is the first hit the grants did not cover (the one the
29
+ * person or the classifier must decide). Not for `deny` or `allow` lines, which grants never touch.
30
+ */
31
+ export declare function applySessionGrants(result: ReviewResult, granted: (rule: string) => boolean): {
32
+ outcome: RuleOutcome;
33
+ hit: RuleHit | undefined;
34
+ };
24
35
  /**
25
36
  * The facts of the run the rules read. Commands run in a device's workspace; `mode` says whether
26
37
  * the OS sandbox is on (the rules are the same in both modes), and `attended` says whether a
@@ -33,6 +44,12 @@ export interface ReviewFacts {
33
44
  attended: boolean;
34
45
  /** The directory the command runs in; default: the workspace. */
35
46
  cwd?: string;
47
+ /**
48
+ * Absolute paths this conversation's own tool calls wrote (`Write` / `Edit`, and the write
49
+ * targets of its earlier `Bash` lines): running one of them with an interpreter is not a
50
+ * development command but code the run itself produced (hardening spec R1).
51
+ */
52
+ written?: readonly string[];
36
53
  }
37
54
  /** One shell redirection of a simple command. */
38
55
  export interface Redirect {
@@ -4,9 +4,45 @@
4
4
  * calls it and the classifier for `unsure` are separate (spec §5.3).
5
5
  */
6
6
  /**
7
- * Whether a rule id may back the person's `本会话允许同类` grant: one concrete rule class, never a
8
- * catch-all. The `unsure.*` hits (`unsure.uncovered`, `unsure.unparsed`) stand for "no rule decided
9
- * this", so remembering one would allow every future parser-unreadable command for the conversation
10
- * — the bucket the review keeps fail-closed. A classifier ask has no rule at all.
7
+ * The ask classes a person is asked about every time, never remembered for the session: printing or
8
+ * copying a credential (or a credential file), a link to a secret or a persistence location, a dynamic path argument (the floor of
9
+ * spec §5.2: what it names is only known when it runs) and `sudo` (any command at all). Remembering
10
+ * one would allow the next, different command of that class without the person seeing it.
11
11
  */
12
- export const isSessionGrantableRule = (rule) => rule !== null && !rule.startsWith("unsure.");
12
+ const NEVER_SESSION_CLASSES = new Set([
13
+ "ask.credential-print",
14
+ "ask.secret-file",
15
+ "ask.credential-link",
16
+ "ask.ssh",
17
+ "ask.outside-link",
18
+ "ask.dynamic-arg",
19
+ "ask.sudo",
20
+ ]);
21
+ /**
22
+ * Whether a rule id may back the person's `本会话允许同类` grant: one concrete rule class the person
23
+ * can reason about, never a catch-all. The `unsure.*` hits stand for "no rule decided this", so
24
+ * remembering one would allow every future parser-unreadable command for the conversation — the
25
+ * bucket the review keeps fail-closed. A classifier ask has no rule at all.
26
+ */
27
+ export const isSessionGrantableRule = (rule) => rule !== null && !rule.startsWith("unsure.") && !NEVER_SESSION_CLASSES.has(rule);
28
+ /**
29
+ * The rule outcome once the person's session grants are applied (hardening spec 2026-11-15 R4): an
30
+ * `ask` line is allowed only when **every** ask hit's class is granted and **no** `unsure` hit is
31
+ * left — a grant for one class never lets another class, or an unread part of the line, through.
32
+ * Otherwise the outcome stays, and `hit` is the first hit the grants did not cover (the one the
33
+ * person or the classifier must decide). Not for `deny` or `allow` lines, which grants never touch.
34
+ */
35
+ export function applySessionGrants(result, granted) {
36
+ if (result.outcome !== "ask") {
37
+ return { outcome: result.outcome, hit: result.hits.find((h) => h.outcome === result.outcome) };
38
+ }
39
+ const open = result.hits.filter((h) => h.outcome === "unsure" ||
40
+ (h.outcome === "ask" && !(isSessionGrantableRule(h.id) && granted(h.id))));
41
+ const ask = open.find((h) => h.outcome === "ask");
42
+ if (ask !== undefined)
43
+ return { outcome: "ask", hit: ask };
44
+ const unsure = open.find((h) => h.outcome === "unsure");
45
+ if (unsure !== undefined)
46
+ return { outcome: "unsure", hit: unsure };
47
+ return { outcome: "allow", hit: result.hits.find((h) => h.outcome === "ask") };
48
+ }
@@ -108,8 +108,8 @@ export declare const deviceNotFound: () => ApiError;
108
108
  export declare const deviceFilesLost: (local?: boolean) => ApiError;
109
109
  /**
110
110
  * A cloud sandbox provider refused to make (or move) an instance with the open public network
111
- * (409; auto mode spec §4.2): above all a provider set to refuse it (sandbox-docker /
112
- * sandbox-e2b `openEgress: "off"`). The provider's own error goes only to the log: it may name
111
+ * (409; auto mode spec §4.2): a provider that cannot or is set not to offer it. The text is
112
+ * provider-neutral (hardening spec K5); the provider's own error goes only to the log: it may name
113
113
  * the provider's settings.
114
114
  */
115
115
  export declare const sandboxOpenNetworkRefused: () => ApiError;
@@ -128,13 +128,14 @@ export declare const isInstance: (row: Pick<Row, "handle" | "created_at">, gone:
128
128
  * Sandbox config problems to tell operators at startup (English log lines):
129
129
  * - `runtime.maxRunSeconds` below `sandbox.limits.maxCommandSeconds`: long commands are cut by the
130
130
  * run time limit (Ruling M20);
131
- * - auto mode is allowed but the current provider plugin sets `openEgress: "off"`: every creation
132
- * of a cloud device with the open public network is refused.
131
+ * - the current provider plugin refuses the open public network (`refuseOpenNetwork: true` in its
132
+ * startup config) while an org can be on it: auto mode always is, and a sandbox-mode cloud device
133
+ * keeps its org's cloud network, open by default, so turning auto mode off does not avoid it
134
+ * (auto mode hardening spec K3). Only the kill switch (`sandbox.limits.egress: none`) does.
133
135
  * No run duration limit (`runtime.maxRunSeconds` 0, the default) cuts no command, so there is
134
- * nothing to tell. `autoAllowed`: whether the deployment allows auto mode now (read live; the
135
- * startup config alone when absent).
136
+ * nothing to tell.
136
137
  */
137
- export declare function sandboxConfigWarnings(cfg: Pick<KernelConfig, "runtime" | "sandbox" | "devices" | "extensionConfig">, providerPlugin?: string, autoAllowed?: boolean): {
138
+ export declare function sandboxConfigWarnings(cfg: Pick<KernelConfig, "runtime" | "sandbox" | "extensionConfig">, providerPlugin?: string): {
138
139
  level: "warn";
139
140
  message: string;
140
141
  }[];
@@ -60,11 +60,11 @@ export const deviceFilesLost = (local = false) => local
60
60
  : new ApiError("device.files_lost", "The device's files are gone; reset its files from the devices page to start with an empty workspace.");
61
61
  /**
62
62
  * A cloud sandbox provider refused to make (or move) an instance with the open public network
63
- * (409; auto mode spec §4.2): above all a provider set to refuse it (sandbox-docker /
64
- * sandbox-e2b `openEgress: "off"`). The provider's own error goes only to the log: it may name
63
+ * (409; auto mode spec §4.2): a provider that cannot or is set not to offer it. The text is
64
+ * provider-neutral (hardening spec K5); the provider's own error goes only to the log: it may name
65
65
  * the provider's settings.
66
66
  */
67
- export const sandboxOpenNetworkRefused = () => new ApiError("sandbox.open_network_refused", "The cloud sandbox provider cannot give this device the open network: it refused to create the sandbox. An org admin can switch the organization's cloud network to the allowlist, or a super admin can allow the open network in the sandbox extension's settings.");
67
+ export const sandboxOpenNetworkRefused = () => new ApiError("sandbox.open_network_refused", "The cloud sandbox provider refused to give this device the open network, so its sandbox was not created. An org admin can switch the organization's cloud network to an allowlist, with the device in sandbox mode (its owner switches it, or the org turns auto mode off), or a super admin can use a sandbox provider that offers the open network.");
68
68
  /**
69
69
  * A cloud sandbox provider failed to make a device's file system or instance for another reason
70
70
  * (502): often its deployment config (image, runtime, network), sometimes a passing fault. The
@@ -89,10 +89,10 @@ function providerRefusal(log, err, facts, limits, signal) {
89
89
  err instanceof ApiError) {
90
90
  return err;
91
91
  }
92
- // a provider set to refuse the open network (`openEgress: "off"`) fails on it in either mode:
93
- // auto always has it, a narrowed cloud device has it while the org's network is open
92
+ // a provider that refuses the open network fails on it in either mode: auto always has it, a
93
+ // narrowed cloud device has it while the org's network is open
94
94
  if (limits.network.kind === "open-public") {
95
- log.warn("the sandbox provider refused an instance with the open public network; check its openEgress setting or switch the org's cloud network to the allowlist", { ...facts, err });
95
+ log.warn("the sandbox provider refused an instance with the open public network; check the provider's network settings or switch the org's cloud network to the allowlist", { ...facts, err });
96
96
  return sandboxOpenNetworkRefused();
97
97
  }
98
98
  if (facts.op === "update")
@@ -127,21 +127,21 @@ function tagged(impl, tag, actor, before) {
127
127
  * Sandbox config problems to tell operators at startup (English log lines):
128
128
  * - `runtime.maxRunSeconds` below `sandbox.limits.maxCommandSeconds`: long commands are cut by the
129
129
  * run time limit (Ruling M20);
130
- * - auto mode is allowed but the current provider plugin sets `openEgress: "off"`: every creation
131
- * of a cloud device with the open public network is refused.
130
+ * - the current provider plugin refuses the open public network (`refuseOpenNetwork: true` in its
131
+ * startup config) while an org can be on it: auto mode always is, and a sandbox-mode cloud device
132
+ * keeps its org's cloud network, open by default, so turning auto mode off does not avoid it
133
+ * (auto mode hardening spec K3). Only the kill switch (`sandbox.limits.egress: none`) does.
132
134
  * No run duration limit (`runtime.maxRunSeconds` 0, the default) cuts no command, so there is
133
- * nothing to tell. `autoAllowed`: whether the deployment allows auto mode now (read live; the
134
- * startup config alone when absent).
135
+ * nothing to tell.
135
136
  */
136
- export function sandboxConfigWarnings(cfg, providerPlugin, autoAllowed = cfg.devices.autoMode !== "off") {
137
+ export function sandboxConfigWarnings(cfg, providerPlugin) {
137
138
  const out = [];
138
- if (autoAllowed && providerPlugin !== undefined) {
139
- // absent means the plugin's default ("proxy"), which creates open instances
139
+ if (providerPlugin !== undefined && cfg.sandbox.limits.egress !== "none") {
140
140
  const pc = cfg.extensionConfig[providerPlugin];
141
- if (pc?.openEgress === "off") {
141
+ if (pc?.refuseOpenNetwork === true) {
142
142
  out.push({
143
143
  level: "warn",
144
- message: `auto mode is allowed but extensionConfig."${providerPlugin}".openEgress is "off": the ${providerPlugin} plugin refuses to create cloud devices with the open public network; set openEgress to "proxy" (or "direct" for trusted deployments only), or switch the organization's cloud network to the allowlist`,
144
+ message: `extensionConfig."${providerPlugin}".refuseOpenNetwork is true: the ${providerPlugin} plugin refuses cloud devices on the open public network, which every device in auto mode and every sandbox-mode device of an organization whose cloudNetwork is open (the default) uses; set refuseOpenNetwork to false, or turn auto mode off (devices.autoMode) and have every organization switch its cloudNetwork to the allowlist`,
145
145
  });
146
146
  }
147
147
  }
@@ -1521,7 +1521,7 @@ let SandboxService = class SandboxService {
1521
1521
  // the instance may run with half-applied limits and cannot be recreated here: stop it,
1522
1522
  // so the next use resumes it and applies them again
1523
1523
  await this.quarantine(held, id, handle, p, fence);
1524
- // a provider bound to its file system that refuses the new network (E2B, `openEgress: "off"`)
1524
+ // a provider bound to its file system that refuses the new network (E2B)
1525
1525
  throw providerRefusal(this.log, err, { deviceId: id, provider: p.plugin, op: "update" }, want, signal);
1526
1526
  }
1527
1527
  else {
@@ -20,8 +20,9 @@ import { KernelConfigService } from "../infra/config/kernel-config.service.js";
20
20
  import { KernelDb } from "../infra/database/kernel-db.js";
21
21
  import { REDIS } from "../infra/tokens.js";
22
22
  import { Credentials } from "../tools/credentials.js";
23
+ import { oauthNetPolicy } from "../tools/oauth/discovery.js";
23
24
  import { callbackUrl } from "../tools/oauth/flow-paths.js";
24
- import { probeNetPolicy, probeTokenEndpoint } from "./oauth-token-probe.js";
25
+ import { probeTokenEndpoint } from "./oauth-token-probe.js";
25
26
  import { checkRedactor } from "./redact-check.js";
26
27
  import { SetupCheckRegistry } from "./setup-check-registry.js";
27
28
  const text = (en, zh) => ({ en, zh });
@@ -271,7 +272,7 @@ let KernelChecks = class KernelChecks {
271
272
  return probeTokenEndpoint({
272
273
  client,
273
274
  redirectUri: callbackUrl(publicUrl),
274
- net: probeNetPolicy(config),
275
+ net: oauthNetPolicy(config),
275
276
  signal: a.signal,
276
277
  });
277
278
  }
@@ -1,5 +1,4 @@
1
1
  import type { SetupCheckResult, SetupCheckText } from "@capybara-hq/plugin-sdk";
2
- import type { KernelConfig } from "../config/schema.js";
3
2
  import type { NetPolicy } from "../net/public-address.js";
4
3
  import { safeFetch } from "../net/safe-fetch.js";
5
4
  import { type OAuthClientRecord } from "../tools/oauth/tokens.js";
@@ -20,18 +19,12 @@ export declare const PROBE_TEXTS: {
20
19
  * its limit makes the result invalid, which the kernel answers as unknown.)
21
20
  */
22
21
  export declare const redirectFix: (callbackUrl: string) => SetupCheckText;
23
- /**
24
- * The network rules of the probe: the deployment's egress proxy (`net.httpsProxy` /
25
- * `net.noProxy`), its private host exemptions (`marketplaces.allowPrivateHosts`, the one list of
26
- * internal hosts the kernel may reach) and loopback http only under
27
- * `tools.oauthAllowInsecureLoopback` (tests), as for every other OAuth URL.
28
- */
29
- export declare function probeNetPolicy(config: KernelConfig): NetPolicy;
30
22
  export interface TokenProbeInput {
31
23
  /** The stored client: its `tokenEndpoint` is the one the connect flow posts codes to. */
32
24
  client: OAuthClientRecord;
33
25
  /** The connect flow's redirect URI (`http.publicUrl` + the callback path). */
34
26
  redirectUri: string;
27
+ /** The OAuth network rules (`oauthNetPolicy`), as for every other OAuth round trip. */
35
28
  net: NetPolicy;
36
29
  /** The run's signal (the kernel's time limit). */
37
30
  signal: AbortSignal;
@@ -38,22 +38,6 @@ export const PROBE_TEXTS = {
38
38
  * its limit makes the result invalid, which the kernel answers as unknown.)
39
39
  */
40
40
  export const redirectFix = (callbackUrl) => text(`Add ${callbackUrl} to the app's redirect URLs.`, `把 ${callbackUrl} 加到应用的重定向地址(Redirect URLs)里。`);
41
- /**
42
- * The network rules of the probe: the deployment's egress proxy (`net.httpsProxy` /
43
- * `net.noProxy`), its private host exemptions (`marketplaces.allowPrivateHosts`, the one list of
44
- * internal hosts the kernel may reach) and loopback http only under
45
- * `tools.oauthAllowInsecureLoopback` (tests), as for every other OAuth URL.
46
- */
47
- export function probeNetPolicy(config) {
48
- return {
49
- allowInsecureLoopback: config.tools.oauthAllowInsecureLoopback,
50
- allowPrivateHosts: config.marketplaces.allowPrivateHosts,
51
- trustedOrigins: [],
52
- ...(config.net.httpsProxy !== undefined && {
53
- proxy: { url: config.net.httpsProxy, noProxy: config.net.noProxy },
54
- }),
55
- };
56
- }
57
41
  /**
58
42
  * Probes the token endpoint (spec §10.6 table): `invalid_grant` / Slack `invalid_code` → ok; a
59
43
  * refused client (or any other 401) → failing with the copy-again fix; a refused redirect URI →
@@ -100,7 +100,7 @@ export declare const SANDBOX_CONNECTION_DROPPED_TEXT = "The connection to the sa
100
100
  * A cloud provider refused the device's open public network (`sandbox.open_network_refused`): the
101
101
  * fixed text, never the provider's own message (it may name its settings).
102
102
  */
103
- export declare const SANDBOX_OPEN_NETWORK_REFUSED_TEXT = "The cloud sandbox provider cannot give this device the open public network and refused to create it, so nothing ran in the sandbox and retrying won't help. Ask the person to have an org admin switch the organization's cloud network to the allowlist, or a super admin allow the open network in the sandbox extension's settings (Admin console \u2192 Extensions). Continue without the sandbox meanwhile.";
103
+ export declare const SANDBOX_OPEN_NETWORK_REFUSED_TEXT = "The cloud sandbox provider refused to give this device the open public network, so nothing ran in the sandbox and retrying won't help. Ask the person to switch this device to sandbox mode and have an org admin switch the organization's cloud network to an allowlist, or have a super admin use a sandbox provider that offers the open network. Continue without the sandbox meanwhile.";
104
104
  /** A cloud provider failed to create the device's sandbox otherwise (`sandbox.create_failed`). */
105
105
  export declare const SANDBOX_CREATE_FAILED_TEXT = "The cloud sandbox provider could not create this device's sandbox, so nothing ran in it. Retry once; if it fails again, continue without the sandbox and ask the person to have a super admin check the sandbox extension's settings (Admin console \u2192 Extensions).";
106
106
  /** The directory of attachments in the device (each conversation has a subdirectory). */
@@ -51,7 +51,7 @@ const deviceProtocolText = (detail) => `The device's machine sent an answer the
51
51
  * A cloud provider refused the device's open public network (`sandbox.open_network_refused`): the
52
52
  * fixed text, never the provider's own message (it may name its settings).
53
53
  */
54
- export const SANDBOX_OPEN_NETWORK_REFUSED_TEXT = "The cloud sandbox provider cannot give this device the open public network and refused to create it, so nothing ran in the sandbox and retrying won't help. Ask the person to have an org admin switch the organization's cloud network to the allowlist, or a super admin allow the open network in the sandbox extension's settings (Admin console → Extensions). Continue without the sandbox meanwhile.";
54
+ export const SANDBOX_OPEN_NETWORK_REFUSED_TEXT = "The cloud sandbox provider refused to give this device the open public network, so nothing ran in the sandbox and retrying won't help. Ask the person to switch this device to sandbox mode and have an org admin switch the organization's cloud network to an allowlist, or have a super admin use a sandbox provider that offers the open network. Continue without the sandbox meanwhile.";
55
55
  /** A cloud provider failed to create the device's sandbox otherwise (`sandbox.create_failed`). */
56
56
  export const SANDBOX_CREATE_FAILED_TEXT = "The cloud sandbox provider could not create this device's sandbox, so nothing ran in it. Retry once; if it fails again, continue without the sandbox and ask the person to have a super admin check the sandbox extension's settings (Admin console → Extensions).";
57
57
  const LOCK_LOST_TEXT = "The sandbox operation was interrupted because the sandbox lock was lost; check the sandbox state and retry.";
@@ -41,9 +41,10 @@ export const TOOL_SEARCH_SPEC = {
41
41
  annotations: { readOnlyHint: true },
42
42
  };
43
43
  /** 目录(system 第二个块)的开头说明(模型可见,英文)。 */
44
- export const CATALOG_HEADER = "More tools are available but not loaded. To use one, first call ToolSearch with keywords; " +
45
- "it returns the full definitions and loads the matching tools for your next step. " +
46
- "Calling a tool that is not loaded returns an error. Tool catalog:";
44
+ export const CATALOG_HEADER = "More tools are available but not loaded, even when your instructions name them. Your tool " +
45
+ "list is the only set you can call: any other tool is not loaded and calling it returns an " +
46
+ "error. To use one, call ToolSearch first with keywords (the app, object or action); it " +
47
+ "returns the full definitions and loads the matching tools for your next step. Tool catalog:";
47
48
  /** 调用目录里尚未加载的工具(模型可见,英文;spec 5.5:不自动加载)。 */
48
49
  export const notLoadedText = (key) => `Tool "${key}" is not loaded. Call ToolSearch first with keywords for this tool, then call it in a later step.`;
49
50
  /**
@@ -1,30 +1,49 @@
1
1
  import type { KernelConfig } from "../../config/schema.js";
2
+ import { type LookupFn, type NetPolicy } from "../../net/public-address.js";
2
3
  import type { OAuthClientRecord, TokenAuthMethod } from "./tokens.js";
3
4
  /**
4
- * MCP OAuth 发现与动态注册(MCP 授权规范):
5
- * RFC 9728 受保护资源元数据(401 的 `WWW-Authenticate: Bearer resource_metadata=…`,或
6
- * `/.well-known/oauth-protected-resource[/<path>]`)→ RFC 8414 授权服务器元数据(OpenID 发现文档作回退)
7
- * → RFC 7591 动态客户端注册。
5
+ * MCP OAuth discovery and dynamic registration (the MCP authorization spec):
6
+ * RFC 9728 protected resource metadata (a 401's `WWW-Authenticate: Bearer resource_metadata=…`, or
7
+ * `/.well-known/oauth-protected-resource[/<path>]`) -> RFC 8414 authorization server metadata
8
+ * (the OpenID discovery document as a fallback) -> RFC 7591 dynamic client registration.
8
9
  *
9
- * 自己实现而不引库:内核只需要这几次 HTTP 往返,且要统一「不跟随重定向、限时、限响应大小、只允许 https」
10
- * 与错误映射(错误只带原因码与英文说明,不带对方响应正文)。`oauth4webapi` 默认禁止 http、自带错误模型,
11
- * 换来的代码量并不少;MCP SDK 的 client auth 帮助函数围绕交互式 `OAuthClientProvider`,且会把 MCP SDK
12
- * 拉进与协议无关的内核。
10
+ * Written here rather than taken from a library: the kernel needs only these few round trips, and
11
+ * they must share one set of rules ("no redirects, a time limit, a body cap, https only, the
12
+ * deployment's network rules") and one error mapping (a reason code and an English message, never
13
+ * the remote's body). `oauth4webapi` forbids http by default and brings its own error model for
14
+ * about as much code; the MCP SDK's client auth helpers revolve around an interactive
15
+ * `OAuthClientProvider` and would pull the MCP SDK into a protocol-agnostic kernel.
16
+ *
17
+ * Every round trip goes through `packages/kernel/src/net` ({@link safeFetch}): the host must
18
+ * resolve to public addresses (or be exempt by `marketplaces.allowPrivateHosts`), the connection is
19
+ * pinned to the checked address, `net.httpsProxy` tunnels https, and redirects are never followed.
13
20
  */
14
21
  export interface OAuthHttpOptions {
15
- /** 允许本机(127.0.0.1 / localhost / [::1])的 http,仅开发与测试。 */
16
- allowInsecureLoopback: boolean;
22
+ /** The network rules ({@link oauthNetPolicy}). */
23
+ net: NetPolicy;
17
24
  timeoutMs: number;
25
+ /** Tests only: replaces the DNS lookup. */
26
+ lookup?: LookupFn;
18
27
  }
19
- /** OAuth 往返的限时:工具超时与 30 秒取小。 */
28
+ /**
29
+ * The network rules of every OAuth round trip (discovery, registration, token endpoint, the setup
30
+ * check's token probe): the deployment's egress proxy (`net.httpsProxy` / `net.noProxy`), its
31
+ * private host exemptions (`marketplaces.allowPrivateHosts`, the one list of internal hosts the
32
+ * kernel may reach) and loopback http only under `tools.oauthAllowInsecureLoopback` (tests).
33
+ */
34
+ export declare function oauthNetPolicy(cfg: KernelConfig): NetPolicy;
35
+ /** The OAuth round trip options: the network rules, and the tool timeout capped at 30 seconds. */
20
36
  export declare function oauthHttpOptions(cfg: KernelConfig): OAuthHttpOptions;
21
- export type OAuthSetupReason = "insecure_url" | "discovery_failed" | "dcr_unsupported" | "dcr_failed" | "token_failed";
22
- /** 发现 / 注册 / 安装时取 token 失败:原因码供向导分支(如 `dcr_unsupported` 改为手填 client),说明为英文。 */
37
+ export type OAuthSetupReason = "insecure_url" | "address_refused" | "discovery_failed" | "dcr_unsupported" | "dcr_failed" | "token_failed";
38
+ /**
39
+ * Discovery / registration / the install-time token request failed: the reason code lets the
40
+ * wizard branch (e.g. `dcr_unsupported` -> a manual client), the message is English.
41
+ */
23
42
  export declare class OAuthSetupError extends Error {
24
43
  readonly reason: OAuthSetupReason;
25
44
  constructor(reason: OAuthSetupReason, message: string);
26
45
  }
27
- /** 只接受 https(放行时本机 http 也可),不允许 URL 里带用户信息。 */
46
+ /** https only (loopback http when allowed), and no user information in the URL. */
28
47
  export declare function checkOAuthUrl(raw: string, http: OAuthHttpOptions): URL;
29
48
  export interface OAuthResponse {
30
49
  status: number;
@@ -32,8 +51,11 @@ export interface OAuthResponse {
32
51
  text: string;
33
52
  }
34
53
  /**
35
- * OAuth 往返:校验 URL、不跟随重定向(3xx 原样返回,调用方按失败处理)、限时、正文超过 1 MiB 即中止。
36
- * 网络错误 / 超时原样抛出。
54
+ * One OAuth round trip through {@link safeFetch}: the URL is checked, a time limit applies and a
55
+ * body over 1 MiB aborts. An address the network rules refuse (private / reserved, or not https)
56
+ * is an {@link OAuthSetupError} `address_refused` / `insecure_url` with an actionable English
57
+ * message. A redirect is never followed: it throws a plain error, as a network error or a timeout
58
+ * does, so callers handle it as "this location did not answer".
37
59
  */
38
60
  export declare function oauthFetch(url: string, init: RequestInit, http: OAuthHttpOptions): Promise<OAuthResponse>;
39
61
  /** 发现结果:授权服务器端点 + 资源标识(RFC 8707 `resource` 参数)。 */
@@ -1,11 +1,32 @@
1
- /** OAuth 往返的限时:工具超时与 30 秒取小。 */
2
- export function oauthHttpOptions(cfg) {
1
+ import { NetDeniedError } from "../../net/public-address.js";
2
+ import { NetBodyTooLargeError, safeFetch } from "../../net/safe-fetch.js";
3
+ /**
4
+ * The network rules of every OAuth round trip (discovery, registration, token endpoint, the setup
5
+ * check's token probe): the deployment's egress proxy (`net.httpsProxy` / `net.noProxy`), its
6
+ * private host exemptions (`marketplaces.allowPrivateHosts`, the one list of internal hosts the
7
+ * kernel may reach) and loopback http only under `tools.oauthAllowInsecureLoopback` (tests).
8
+ */
9
+ export function oauthNetPolicy(cfg) {
3
10
  return {
4
11
  allowInsecureLoopback: cfg.tools.oauthAllowInsecureLoopback,
12
+ allowPrivateHosts: cfg.marketplaces.allowPrivateHosts,
13
+ trustedOrigins: [],
14
+ ...(cfg.net.httpsProxy !== undefined && {
15
+ proxy: { url: cfg.net.httpsProxy, noProxy: cfg.net.noProxy },
16
+ }),
17
+ };
18
+ }
19
+ /** The OAuth round trip options: the network rules, and the tool timeout capped at 30 seconds. */
20
+ export function oauthHttpOptions(cfg) {
21
+ return {
22
+ net: oauthNetPolicy(cfg),
5
23
  timeoutMs: Math.min(cfg.tools.timeoutMs, 30_000),
6
24
  };
7
25
  }
8
- /** 发现 / 注册 / 安装时取 token 失败:原因码供向导分支(如 `dcr_unsupported` 改为手填 client),说明为英文。 */
26
+ /**
27
+ * Discovery / registration / the install-time token request failed: the reason code lets the
28
+ * wizard branch (e.g. `dcr_unsupported` -> a manual client), the message is English.
29
+ */
9
30
  export class OAuthSetupError extends Error {
10
31
  reason;
11
32
  constructor(reason, message) {
@@ -15,9 +36,9 @@ export class OAuthSetupError extends Error {
15
36
  }
16
37
  }
17
38
  const LOOPBACK = new Set(["127.0.0.1", "localhost", "[::1]"]);
18
- /** 元数据 / 令牌响应的大小上限。 */
39
+ /** The size cap of a metadata / token answer. */
19
40
  const MAX_BODY_BYTES = 1024 * 1024;
20
- /** 只接受 https(放行时本机 http 也可),不允许 URL 里带用户信息。 */
41
+ /** https only (loopback http when allowed), and no user information in the URL. */
21
42
  export function checkOAuthUrl(raw, http) {
22
43
  let u;
23
44
  try {
@@ -27,7 +48,7 @@ export function checkOAuthUrl(raw, http) {
27
48
  throw new OAuthSetupError("discovery_failed", "An OAuth URL is not a valid absolute URL");
28
49
  }
29
50
  const ok = u.protocol === "https:" ||
30
- (u.protocol === "http:" && http.allowInsecureLoopback && LOOPBACK.has(u.hostname));
51
+ (u.protocol === "http:" && http.net.allowInsecureLoopback && LOOPBACK.has(u.hostname));
31
52
  if (!ok) {
32
53
  throw new OAuthSetupError("insecure_url", `OAuth URLs must use https (got ${u.protocol}//${u.host})`);
33
54
  }
@@ -37,38 +58,40 @@ export function checkOAuthUrl(raw, http) {
37
58
  return u;
38
59
  }
39
60
  /**
40
- * OAuth 往返:校验 URL、不跟随重定向(3xx 原样返回,调用方按失败处理)、限时、正文超过 1 MiB 即中止。
41
- * 网络错误 / 超时原样抛出。
61
+ * One OAuth round trip through {@link safeFetch}: the URL is checked, a time limit applies and a
62
+ * body over 1 MiB aborts. An address the network rules refuse (private / reserved, or not https)
63
+ * is an {@link OAuthSetupError} `address_refused` / `insecure_url` with an actionable English
64
+ * message. A redirect is never followed: it throws a plain error, as a network error or a timeout
65
+ * does, so callers handle it as "this location did not answer".
42
66
  */
43
67
  export async function oauthFetch(url, init, http) {
44
68
  checkOAuthUrl(url, http);
45
- const res = await fetch(url, {
46
- ...init,
47
- redirect: "manual",
48
- signal: AbortSignal.timeout(http.timeoutMs),
49
- });
50
- const declared = Number(res.headers.get("content-length"));
51
- if (Number.isFinite(declared) && declared > MAX_BODY_BYTES) {
52
- await res.body?.cancel();
53
- throw new Error("OAuth response is too large");
69
+ let res;
70
+ try {
71
+ res = await safeFetch(url, { ...init, signal: AbortSignal.timeout(http.timeoutMs) }, http.net, {
72
+ maxBytes: MAX_BODY_BYTES,
73
+ ...(http.lookup !== undefined && { lookup: http.lookup }),
74
+ });
54
75
  }
55
- const chunks = [];
56
- let size = 0;
57
- if (res.body) {
58
- const reader = res.body.getReader();
59
- for (;;) {
60
- const { done, value } = await reader.read();
61
- if (done)
62
- break;
63
- size += value.byteLength;
64
- if (size > MAX_BODY_BYTES) {
65
- await reader.cancel().catch(() => { });
66
- throw new Error("OAuth response is too large");
67
- }
68
- chunks.push(value);
76
+ catch (e) {
77
+ if (e instanceof NetDeniedError && e.code === "net.private_address") {
78
+ throw new OAuthSetupError("address_refused", `OAuth: ${e.message}`);
69
79
  }
80
+ if (e instanceof NetDeniedError && e.code === "net.insecure_url") {
81
+ throw new OAuthSetupError("insecure_url", `OAuth: ${e.message}`);
82
+ }
83
+ throw e;
70
84
  }
71
- return { status: res.status, headers: res.headers, text: Buffer.concat(chunks).toString("utf8") };
85
+ let text;
86
+ try {
87
+ text = await res.text();
88
+ }
89
+ catch (e) {
90
+ if (e instanceof NetBodyTooLargeError)
91
+ throw new Error("OAuth response is too large");
92
+ throw e;
93
+ }
94
+ return { status: res.status, headers: res.headers, text };
72
95
  }
73
96
  const isObj = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
74
97
  const parseJson = (text) => {
@@ -156,7 +179,10 @@ export async function discoverMcp(endpointUrl, http) {
156
179
  catch (e) {
157
180
  if (e instanceof OAuthSetupError)
158
181
  throw e;
159
- throw failed("Could not reach the connector's server for OAuth discovery");
182
+ // a redirect is not followed and carries no challenge: fall back to the well-known locations
183
+ if (!(e instanceof NetDeniedError && e.code === "net.redirect")) {
184
+ throw failed("Could not reach the connector's server for OAuth discovery");
185
+ }
160
186
  }
161
187
  const metadataUrl = challengeParam(challenge, "resource_metadata");
162
188
  const prmCandidates = [];
@@ -93,7 +93,7 @@ export const commandUnattendedText = (reason, kind) => kind === "write"
93
93
  */
94
94
  export const commandTooLongReason = (chars) => `The command is ${chars} characters long; commands over ${COMMAND_ASK_MAX_CHARS} are too long to review and approve.`;
95
95
  /** The model-visible result of a command over the ask ceiling (actionable, English). */
96
- export const commandTooLongText = (chars) => `This command is too long to review (${chars} characters; the limit is ${COMMAND_ASK_MAX_CHARS}). Shorten it, or write it to a script file and run that instead.`;
96
+ export const commandTooLongText = (chars) => `This command is too long to review (${chars} characters; the limit is ${COMMAND_ASK_MAX_CHARS}). Split it into shorter commands; long inline scripts are reviewed as code the review cannot read.`;
97
97
  /** The person declined a held command or write (P-D12); `reason` is what they said, if anything. */
98
98
  export const commandDeclinedText = (reason, kind) => {
99
99
  const what = kind === "write" ? "this write" : "to run this command";
@@ -531,10 +531,11 @@ let ToolPipeline = class ToolPipeline {
531
531
  async runCall(ctx, call, resolved, attempt, resume) {
532
532
  // the command review's record for this call's result (absent: not reviewed, or no device)
533
533
  let review;
534
- const fail = async (content, key = call.name) => {
534
+ const fail = async (content, key = call.name, view) => {
535
535
  await this.writeResult(ctx, call.id, key, {
536
536
  content,
537
537
  isError: true,
538
+ ...(view !== undefined && { view }),
538
539
  ...(review !== undefined && { review }),
539
540
  });
540
541
  return undefined;
@@ -569,10 +570,11 @@ let ToolPipeline = class ToolPipeline {
569
570
  const outKey = legacy ? call.name : tool.key;
570
571
  // ToolSearch 模式下,模型只能调用请求里带了完整定义的工具:目录里有、但发出本次调用的请求没加载 →
571
572
  // 明确错误,不自动加载(spec 5.5 / 6.3)。同一步里先 ToolSearch 再调用刚加载的工具同样报错。
573
+ // This is the protocol working, not a failure: the `not_loaded` view lets the row read neutral.
572
574
  if (!legacy && resolved.toolSearch === true && !isAlwaysLoaded(tool.key)) {
573
575
  const sent = await this.sentTools(ctx);
574
576
  if (sent !== null && !sent.has(tool.key))
575
- return fail(notLoadedText(tool.key), outKey);
577
+ return fail(notLoadedText(tool.key), outKey, { kind: "not_loaded" });
576
578
  }
577
579
  const rawInput = legacy ? legacyToolInput(call.name, call.input) : call.input;
578
580
  let input;
@@ -985,6 +987,18 @@ let ToolPipeline = class ToolPipeline {
985
987
  return { kind: "continue" }; // no device: the tool fails on its own
986
988
  const kind = reviewKindOf(tool.key);
987
989
  const attended = ctx.unattended == null && ctx.accountId === facts.ownerAccountId;
990
+ // a command over the ceiling is refused before any review: no stage reads it in full, and no
991
+ // approval could bind a text the person cannot see (hardening spec R8)
992
+ if (kind === "command") {
993
+ const text = textField(input, "command");
994
+ if (text.length > COMMAND_ASK_MAX_CHARS) {
995
+ return {
996
+ kind: "result",
997
+ content: commandTooLongText(text.length),
998
+ review: denyRecord("rule", null, commandTooLongReason(text.length)),
999
+ };
1000
+ }
1001
+ }
988
1002
  const verdict = await review.review({
989
1003
  orgId: ctx.orgId,
990
1004
  conversationId: rootConversationId,
@@ -1023,16 +1037,6 @@ let ToolPipeline = class ToolPipeline {
1023
1037
  }
1024
1038
  // ask
1025
1039
  const command = kind === "command" ? textField(input, "command") : tool.key;
1026
- // a command over the ceiling cannot be shown in full, and an approval must bind exactly what
1027
- // runs: refuse it (no approval, no grant) rather than approve a text the person cannot see
1028
- if (kind === "command" && command.length > COMMAND_ASK_MAX_CHARS) {
1029
- const reason = commandTooLongReason(command.length);
1030
- return {
1031
- kind: "result",
1032
- content: commandTooLongText(command.length),
1033
- review: denyRecord(verdict.by, null, reason),
1034
- };
1035
- }
1036
1040
  if (!attended) {
1037
1041
  const reason = verdict.reason;
1038
1042
  return {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@capybara-hq/kernel",
3
- "version": "0.1.0-rc.30",
3
+ "version": "0.1.0-rc.31",
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": {