@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,6 +15,7 @@ import { parseBootstrapManifest, SDK_VERSION, } from "@capybara-hq/plugin-sdk";
15
15
  import { Inject, Injectable, Optional } from "@nestjs/common";
16
16
  import { sql } from "kysely";
17
17
  import semver from "semver";
18
+ import { marketplaceNetPolicy } from "../catalog/marketplace-fetch.js";
18
19
  import { otherNameOwner } from "../catalog/ownership.js";
19
20
  import { catalogPackageError } from "../catalog/plugin-import.js";
20
21
  import { PluginPackageError, readPluginPackage } from "../catalog/plugin-package.js";
@@ -181,7 +182,12 @@ export async function resolveBootstrapPackages(manifest, o) {
181
182
  const registry = registryOrigin(npmRegistry);
182
183
  const offlineHint = `to install offline, put the package tgz (npm pack ${e.npm}@${e.version}, any file name) in ${where}`;
183
184
  try {
184
- const r = await fetchPackage({ registry: npmRegistry, ...(npmToken !== undefined && { token: npmToken }), maxBytes }, e.npm, e.version, signal, { expectedIntegrity: e.integrity });
185
+ const r = await fetchPackage({
186
+ registry: npmRegistry,
187
+ ...(npmToken !== undefined && { token: npmToken }),
188
+ maxBytes,
189
+ net: marketplaceNetPolicy(o.config),
190
+ }, e.npm, e.version, signal, { expectedIntegrity: e.integrity });
185
191
  return r.bytes;
186
192
  }
187
193
  catch (err) {
@@ -10,6 +10,7 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
10
10
  import { SDK_VERSION } from "@capybara-hq/plugin-sdk";
11
11
  import { Inject, Injectable } from "@nestjs/common";
12
12
  import { sql } from "kysely";
13
+ import { marketplaceNetPolicy } from "../catalog/marketplace-fetch.js";
13
14
  import { configFields } from "../config/fields.js";
14
15
  import { ApiError } from "../errors.js";
15
16
  import { audit } from "../identity/audit.js";
@@ -221,6 +222,7 @@ let ExtensionInstalls = class ExtensionInstalls {
221
222
  const cfg = {
222
223
  registry: c.packages.npmRegistry,
223
224
  maxBytes: c.packages.maxBytes,
225
+ net: marketplaceNetPolicy(c),
224
226
  ...(c.packages.npmToken !== undefined && { token: c.packages.npmToken }),
225
227
  };
226
228
  const timeout = AbortSignal.timeout(NPM_TIMEOUT_MS);
@@ -262,6 +264,7 @@ let ExtensionInstalls = class ExtensionInstalls {
262
264
  const cfg = {
263
265
  registry: c.packages.npmRegistry,
264
266
  maxBytes: c.packages.maxBytes,
267
+ net: marketplaceNetPolicy(c),
265
268
  ...(c.packages.npmToken !== undefined && { token: c.packages.npmToken }),
266
269
  };
267
270
  const timeout = AbortSignal.timeout(PROVENANCE_TIMEOUT_MS);
@@ -272,7 +275,7 @@ let ExtensionInstalls = class ExtensionInstalls {
272
275
  const cfg = {
273
276
  registry: c.packages.npmRegistry,
274
277
  maxBytes: c.packages.maxBytes,
275
- allowInsecureLoopback: c.marketplaces.allowInsecureLoopback,
278
+ net: marketplaceNetPolicy(c),
276
279
  ...(c.packages.npmToken !== undefined && { token: c.packages.npmToken }),
277
280
  };
278
281
  const timeout = AbortSignal.timeout(NPM_TIMEOUT_MS);
@@ -37,7 +37,6 @@ import { KERNEL_MIGRATIONS_DIR, KERNEL_SCHEMA } from "../kernel.js";
37
37
  import { GatewayRole } from "../roles/gateway-role.js";
38
38
  import { WorkerRole } from "../roles/worker-role.js";
39
39
  import { UsageReporter } from "../runtime/usage-report.js";
40
- import { readDevicesAutoMode } from "../sandbox/platform-auto-mode.js";
41
40
  import { sandboxConfigWarnings } from "../sandbox/sandbox.service.js";
42
41
  import { warnLegacyToolKeys } from "../tools/legacy-data.js";
43
42
  import { KERNEL_APP_OPTIONS } from "./tokens.js";
@@ -248,8 +247,7 @@ let KernelLifecycle = class KernelLifecycle {
248
247
  .list("sandbox")
249
248
  .find((x) => x.capability === SANDBOX_EXTENSION_POINT);
250
249
  if (sandboxEntry !== undefined) {
251
- const autoAllowed = (await readDevicesAutoMode(this.kdb.db, this.configService, this.log)).mode === "allowed";
252
- for (const w of sandboxConfigWarnings(cfg(), sandboxEntry.plugin, autoAllowed)) {
250
+ for (const w of sandboxConfigWarnings(cfg(), sandboxEntry.plugin)) {
253
251
  this.log[w.level](w.message);
254
252
  }
255
253
  }
@@ -16,7 +16,11 @@ export type NetPolicy = {
16
16
  * name that resolves there (an attacker's name could point into the range).
17
17
  */
18
18
  allowPrivateHosts: string[];
19
- /** Origins configured by the admin (the npm registry): their hosts may resolve to private addresses. */
19
+ /**
20
+ * Origins configured by the admin (the npm registry): a request to exactly such an origin
21
+ * (scheme, host and port) may resolve to private addresses, and an origin configured as
22
+ * `http://` may be fetched over http. The same host on another port or scheme is not trusted.
23
+ */
20
24
  trustedOrigins: string[];
21
25
  /**
22
26
  * `net.httpsProxy` / `net.noProxy`: https downloads tunnel through this proxy (see `proxy.ts`);
@@ -36,7 +40,11 @@ export type NetDeniedCode = "net.private_address" | "net.dns_failed" | "net.redi
36
40
  export declare class NetDeniedError extends Error {
37
41
  readonly code: NetDeniedCode;
38
42
  readonly host: string;
39
- constructor(code: NetDeniedCode, host: string, message: string);
43
+ /** The HTTP status of a refused redirect (`net.redirect`). */
44
+ readonly status?: number | undefined;
45
+ constructor(code: NetDeniedCode, host: string, message: string,
46
+ /** The HTTP status of a refused redirect (`net.redirect`). */
47
+ status?: number | undefined);
40
48
  }
41
49
  /** The shortest prefix an `allowPrivateHosts` CIDR may have, per family. */
42
50
  export declare const MIN_CIDR_PREFIX: {
@@ -54,7 +62,9 @@ export declare function privateHostEntryProblem(entry: string): string | null;
54
62
  export declare function isPrivateHostEntry(entry: string): boolean;
55
63
  /**
56
64
  * Resolves `host` (an IP literal is taken as is) and returns every address, in resolution order,
57
- * after checking that each is public or exempt by `policy`. Throws {@link NetDeniedError}
65
+ * after checking that each is public or exempt by `policy`. `origin` is the request URL's origin:
66
+ * only when it equals a `policy.trustedOrigins` entry does that trust apply (without it, trusted
67
+ * origins exempt nothing). Throws {@link NetDeniedError}
58
68
  * `net.dns_failed` (no answer) or `net.private_address` (some address is private and not exempt).
59
69
  */
60
- export declare function resolvePublic(host: string, policy: NetPolicy, lookup?: LookupFn): Promise<string[]>;
70
+ export declare function resolvePublic(host: string, policy: NetPolicy, lookup?: LookupFn, origin?: string): Promise<string[]>;
@@ -140,10 +140,14 @@ export function isLoopbackHost(host) {
140
140
  export class NetDeniedError extends Error {
141
141
  code;
142
142
  host;
143
- constructor(code, host, message) {
143
+ status;
144
+ constructor(code, host, message,
145
+ /** The HTTP status of a refused redirect (`net.redirect`). */
146
+ status) {
144
147
  super(message);
145
148
  this.code = code;
146
149
  this.host = host;
150
+ this.status = status;
147
151
  this.name = "NetDeniedError";
148
152
  }
149
153
  }
@@ -187,7 +191,7 @@ export function privateHostEntryProblem(entry) {
187
191
  export function isPrivateHostEntry(entry) {
188
192
  return privateHostEntryProblem(entry) === null;
189
193
  }
190
- function exemptions(host, policy) {
194
+ function exemptions(host, policy, origin) {
191
195
  const cidrs = new BlockList();
192
196
  let all = false;
193
197
  const literal = isIP(host) !== 0;
@@ -214,13 +218,17 @@ function exemptions(host, policy) {
214
218
  all = true;
215
219
  }
216
220
  }
217
- for (const origin of policy.trustedOrigins) {
218
- try {
219
- if (normalizeHost(new URL(origin).hostname) === host)
220
- all = true;
221
- }
222
- catch {
223
- // an unparseable origin trusts nothing
221
+ // a trusted origin exempts that exact origin (scheme, host and port), never its host on
222
+ // another port or scheme: a manifest URL there is judged like any other host
223
+ if (origin !== undefined) {
224
+ for (const trusted of policy.trustedOrigins) {
225
+ try {
226
+ if (new URL(trusted).origin === origin)
227
+ all = true;
228
+ }
229
+ catch {
230
+ // an unparseable origin trusts nothing
231
+ }
224
232
  }
225
233
  }
226
234
  return { all, cidrs };
@@ -242,10 +250,12 @@ function allowedBy(cidrs, ip) {
242
250
  }
243
251
  /**
244
252
  * Resolves `host` (an IP literal is taken as is) and returns every address, in resolution order,
245
- * after checking that each is public or exempt by `policy`. Throws {@link NetDeniedError}
253
+ * after checking that each is public or exempt by `policy`. `origin` is the request URL's origin:
254
+ * only when it equals a `policy.trustedOrigins` entry does that trust apply (without it, trusted
255
+ * origins exempt nothing). Throws {@link NetDeniedError}
246
256
  * `net.dns_failed` (no answer) or `net.private_address` (some address is private and not exempt).
247
257
  */
248
- export async function resolvePublic(host, policy, lookup = defaultLookup) {
258
+ export async function resolvePublic(host, policy, lookup = defaultLookup, origin) {
249
259
  const h = normalizeHost(host);
250
260
  let addrs;
251
261
  if (isIP(h) !== 0) {
@@ -261,7 +271,7 @@ export async function resolvePublic(host, policy, lookup = defaultLookup) {
261
271
  if (addrs.length === 0)
262
272
  throw new NetDeniedError("net.dns_failed", h, `Cannot resolve ${h}.`);
263
273
  }
264
- const ex = exemptions(h, policy);
274
+ const ex = exemptions(h, policy, origin);
265
275
  const refused = (a) => isForbiddenAddress(a) && (isLinkLocalAddress(a) || (!ex.all && !allowedBy(ex.cidrs, a)));
266
276
  if (addrs.some(refused)) {
267
277
  throw new NetDeniedError("net.private_address", h, addrs.some(isLinkLocalAddress)
@@ -2,7 +2,8 @@ import { Agent } from "undici";
2
2
  import { type LookupFn, type NetPolicy } from "./public-address.js";
3
3
  /**
4
4
  * `fetch` for URLs that come from a marketplace or an admin (spec §5.1):
5
- * - https only; plain http only for a loopback host under `allowInsecureLoopback` (testing);
5
+ * - https only; plain http only for a loopback host under `allowInsecureLoopback` (testing), or
6
+ * to exactly a `trustedOrigins` origin the admin configured as http (an internal npm registry);
6
7
  * - the host is resolved once by {@link resolvePublic} and the connection goes to the checked
7
8
  * addresses: a per-request undici `Agent` whose `connect.lookup` answers only those addresses,
8
9
  * so there is no second DNS lookup (no rebinding), while the Host header and TLS SNI keep the
@@ -4,7 +4,8 @@ import { bypassesProxy, proxyAgent } from "./proxy.js";
4
4
  import { isLoopbackHost, NetDeniedError, normalizeHost, resolvePublic, } from "./public-address.js";
5
5
  /**
6
6
  * `fetch` for URLs that come from a marketplace or an admin (spec §5.1):
7
- * - https only; plain http only for a loopback host under `allowInsecureLoopback` (testing);
7
+ * - https only; plain http only for a loopback host under `allowInsecureLoopback` (testing), or
8
+ * to exactly a `trustedOrigins` origin the admin configured as http (an internal npm registry);
8
9
  * - the host is resolved once by {@link resolvePublic} and the connection goes to the checked
9
10
  * addresses: a per-request undici `Agent` whose `connect.lookup` answers only those addresses,
10
11
  * so there is no second DNS lookup (no rebinding), while the Host header and TLS SNI keep the
@@ -47,6 +48,15 @@ export function pinnedAgent(ips, tls = {}) {
47
48
  connect: { lookup: pinnedLookup(ips), ...(tls.ca !== undefined && { ca: tls.ca }) },
48
49
  });
49
50
  }
51
+ /** The origin of a configured URL; null when it does not parse (it then trusts nothing). */
52
+ function originOf(url) {
53
+ try {
54
+ return new URL(url).origin;
55
+ }
56
+ catch {
57
+ return null;
58
+ }
59
+ }
50
60
  const NULL_BODY_STATUS = new Set([101, 103, 204, 205, 304]);
51
61
  function capBody(body, maxBytes) {
52
62
  let seen = 0;
@@ -69,7 +79,9 @@ export async function safeFetch(url, init, policy, opts = {}) {
69
79
  throw new NetDeniedError("net.insecure_url", "", "The URL is not valid.");
70
80
  }
71
81
  const host = normalizeHost(target.hostname);
72
- const insecureOk = policy.allowInsecureLoopback && target.protocol === "http:" && isLoopbackHost(host);
82
+ const insecureOk = target.protocol === "http:" &&
83
+ ((policy.allowInsecureLoopback && isLoopbackHost(host)) ||
84
+ policy.trustedOrigins.some((o) => originOf(o) === target.origin));
73
85
  if (target.protocol !== "https:" && !insecureOk) {
74
86
  throw new NetDeniedError("net.insecure_url", host, `The URL must use https (${host}).`);
75
87
  }
@@ -89,7 +101,7 @@ export async function safeFetch(url, init, policy, opts = {}) {
89
101
  try {
90
102
  // behind the proxy only an IP literal is checked here (no lookup); the proxy resolves names
91
103
  if (!proxied || isIP(host) !== 0) {
92
- ips = await Promise.race([resolvePublic(host, policy, opts.lookup), aborted]);
104
+ ips = await Promise.race([resolvePublic(host, policy, opts.lookup, target.origin), aborted]);
93
105
  }
94
106
  }
95
107
  finally {
@@ -116,7 +128,7 @@ export async function safeFetch(url, init, policy, opts = {}) {
116
128
  void agent.close().catch(() => { });
117
129
  if (res.status >= 300 && res.status < 400 && res.status !== 304) {
118
130
  await res.body?.cancel().catch(() => { });
119
- throw new NetDeniedError("net.redirect", host, `${host} responded with a redirect (${res.status}); redirects are not followed.`);
131
+ throw new NetDeniedError("net.redirect", host, `${host} responded with a redirect (${res.status}); redirects are not followed.`, res.status);
120
132
  }
121
133
  const max = opts.maxBytes;
122
134
  if (max !== undefined) {
@@ -1,11 +1,20 @@
1
+ import { type LookupFn, type NetPolicy } from "../net/public-address.js";
1
2
  /**
2
- * 从 npm registry 下载插件包(D14 / C21 / C26)。registry 地址来自配置(可信),但它返回的内容一律当作外部输入:
3
- * - 不跟随重定向(3xx 直接失败):否则 registry 的一次重定向就能把下载(连同令牌)引到任意地址;
4
- * - 元数据与 tarball 都边读边计数,超过上限立即中止;
5
- * - 没有 `opts` 时 tarball 必须与 registry 同源(令牌只发往该源),并按 packument 的 `dist.integrity`
6
- * (sha512 SRI)校验;给了 `opts.expectedIntegrity`(清单引入,T24)时只认它;
7
- * - `opts.tarballUrl`(清单直接给出的下载地址)必须是 https,测试里可经 `allowInsecureLoopback` 允许回环 http,
8
- * 且必须同时给出 `expectedIntegrity`;不会带 registry 令牌。
3
+ * Downloads plugin packages from an npm registry (D14 / C21 / C26). The registry URL comes from
4
+ * the config (trusted), but whatever it returns is external input:
5
+ * - every request goes through `packages/kernel/src/net` ({@link safeFetch}) under `cfg.net`
6
+ * (the kernel passes `marketplaceNetPolicy`: the registry's origin is trusted, any other host
7
+ * must resolve to public addresses unless `marketplaces.allowPrivateHosts` exempts it, https
8
+ * tunnels through `net.httpsProxy`, and the connection is pinned to the checked address);
9
+ * - redirects are never followed (a 3xx fails): one registry redirect could otherwise send the
10
+ * download (and the token) anywhere;
11
+ * - metadata and tarball are counted while read and aborted past their caps;
12
+ * - without `opts` the tarball must be on the registry's origin (the only origin the token goes
13
+ * to) and is verified against the packument's `dist.integrity` (sha512 SRI); with
14
+ * `opts.expectedIntegrity` (marketplace imports, T24) only that integrity counts;
15
+ * - `opts.tarballUrl` (a download URL the marketplace gives) must be https (loopback http in tests
16
+ * under `net.allowInsecureLoopback`), needs `expectedIntegrity`, and never gets the registry
17
+ * token unless it is on the registry's origin.
9
18
  */
10
19
  /** 下载或校验失败(HTTP 层映射为 `packages.npm_failed`,502)。消息为英文,不含令牌。 */
11
20
  export declare class NpmFetchError extends Error {
@@ -28,13 +37,23 @@ export interface NpmFetchConfig {
28
37
  registry: string;
29
38
  token?: string;
30
39
  maxBytes: number;
31
- /** 只供测试:允许 `opts.tarballUrl` 用回环地址上的 http。 */
32
- allowInsecureLoopback?: boolean;
40
+ /**
41
+ * The network rules of every request (`marketplaceNetPolicy` in the kernel, which trusts the
42
+ * registry's origin). `allowInsecureLoopback` also lets `opts.tarballUrl` use loopback http.
43
+ */
44
+ net: NetPolicy;
45
+ /** Tests only: replaces the DNS lookup. */
46
+ lookup?: LookupFn;
33
47
  }
34
48
  /** 回环地址(`localhost`、`127.*`、`::1`)。 */
35
49
  export declare const isLoopback: (host: string) => boolean;
36
50
  /** 读响应体,累计超过 `max` 立即取消并抛 `onTooLarge()`。 */
37
51
  export declare function readCapped(res: Response, max: number, onTooLarge: () => Error): Promise<Buffer>;
52
+ /**
53
+ * One GET through {@link safeFetch} under `cfg.net` (no redirects, the network rules); a refusal,
54
+ * a network error or a non-2xx answer is an {@link NpmFetchError} with an English message.
55
+ */
56
+ export declare function npmGet(cfg: Pick<NpmFetchConfig, "net" | "lookup">, url: URL, headers: Record<string, string>, signal: AbortSignal, what: string): Promise<Response>;
38
57
  /**
39
58
  * 下载 `name@version`(`version` 可以是精确版本、dist-tag 或范围,缺省 `latest`),返回 tgz 字节、解析出的版本与
40
59
  * 实际校验所用的 integrity。失败抛 {@link NpmFetchError}(含 {@link IntegrityMismatchError})或
@@ -1,14 +1,24 @@
1
1
  import { createHash, timingSafeEqual } from "node:crypto";
2
2
  import { isIP } from "node:net";
3
3
  import semver from "semver";
4
+ import { NetDeniedError } from "../net/public-address.js";
5
+ import { safeFetch } from "../net/safe-fetch.js";
4
6
  /**
5
- * 从 npm registry 下载插件包(D14 / C21 / C26)。registry 地址来自配置(可信),但它返回的内容一律当作外部输入:
6
- * - 不跟随重定向(3xx 直接失败):否则 registry 的一次重定向就能把下载(连同令牌)引到任意地址;
7
- * - 元数据与 tarball 都边读边计数,超过上限立即中止;
8
- * - 没有 `opts` 时 tarball 必须与 registry 同源(令牌只发往该源),并按 packument 的 `dist.integrity`
9
- * (sha512 SRI)校验;给了 `opts.expectedIntegrity`(清单引入,T24)时只认它;
10
- * - `opts.tarballUrl`(清单直接给出的下载地址)必须是 https,测试里可经 `allowInsecureLoopback` 允许回环 http,
11
- * 且必须同时给出 `expectedIntegrity`;不会带 registry 令牌。
7
+ * Downloads plugin packages from an npm registry (D14 / C21 / C26). The registry URL comes from
8
+ * the config (trusted), but whatever it returns is external input:
9
+ * - every request goes through `packages/kernel/src/net` ({@link safeFetch}) under `cfg.net`
10
+ * (the kernel passes `marketplaceNetPolicy`: the registry's origin is trusted, any other host
11
+ * must resolve to public addresses unless `marketplaces.allowPrivateHosts` exempts it, https
12
+ * tunnels through `net.httpsProxy`, and the connection is pinned to the checked address);
13
+ * - redirects are never followed (a 3xx fails): one registry redirect could otherwise send the
14
+ * download (and the token) anywhere;
15
+ * - metadata and tarball are counted while read and aborted past their caps;
16
+ * - without `opts` the tarball must be on the registry's origin (the only origin the token goes
17
+ * to) and is verified against the packument's `dist.integrity` (sha512 SRI); with
18
+ * `opts.expectedIntegrity` (marketplace imports, T24) only that integrity counts;
19
+ * - `opts.tarballUrl` (a download URL the marketplace gives) must be https (loopback http in tests
20
+ * under `net.allowInsecureLoopback`), needs `expectedIntegrity`, and never gets the registry
21
+ * token unless it is on the registry's origin.
12
22
  */
13
23
  /** 下载或校验失败(HTTP 层映射为 `packages.npm_failed`,502)。消息为英文,不含令牌。 */
14
24
  export class NpmFetchError extends Error {
@@ -77,18 +87,21 @@ export async function readCapped(res, max, onTooLarge) {
77
87
  }
78
88
  return Buffer.concat(chunks);
79
89
  }
80
- async function get(url, headers, signal, what) {
90
+ /**
91
+ * One GET through {@link safeFetch} under `cfg.net` (no redirects, the network rules); a refusal,
92
+ * a network error or a non-2xx answer is an {@link NpmFetchError} with an English message.
93
+ */
94
+ export async function npmGet(cfg, url, headers, signal, what) {
81
95
  let res;
82
96
  try {
83
- res = await fetch(url, { headers, redirect: "manual", signal });
97
+ res = await safeFetch(url.toString(), { headers, signal }, cfg.net, cfg.lookup !== undefined ? { lookup: cfg.lookup } : {});
84
98
  }
85
99
  catch (e) {
100
+ if (e instanceof NetDeniedError && e.code === "net.redirect") {
101
+ throw new NpmFetchError(`the ${what} responded with a redirect (${e.status}); redirects are not followed`, { cause: e });
102
+ }
86
103
  throw new NpmFetchError(`cannot fetch the ${what}: ${errMsg(e)}`, { cause: e });
87
104
  }
88
- if (res.status >= 300 && res.status < 400) {
89
- await res.body?.cancel().catch(() => { });
90
- throw new NpmFetchError(`the ${what} responded with a redirect (${res.status}); redirects are not followed`);
91
- }
92
105
  if (!res.ok) {
93
106
  await res.body?.cancel().catch(() => { });
94
107
  throw new NpmFetchError(`the ${what} responded with HTTP ${res.status}`);
@@ -145,13 +158,11 @@ export async function fetchNpmPackage(cfg, name, version, signal, opts = {}) {
145
158
  catch {
146
159
  throw new NpmFetchError("the tarball URL is not a valid URL");
147
160
  }
148
- const insecureOk = cfg.allowInsecureLoopback === true &&
149
- tarball.protocol === "http:" &&
150
- isLoopback(tarball.hostname);
161
+ const insecureOk = cfg.net.allowInsecureLoopback && tarball.protocol === "http:" && isLoopback(tarball.hostname);
151
162
  if (tarball.protocol !== "https:" && !insecureOk) {
152
163
  throw new NpmFetchError("the tarball URL must use https");
153
164
  }
154
- // 令牌只发给 registry 源
165
+ // the token goes only to the registry origin
155
166
  if (tarball.origin !== registry.origin)
156
167
  tarballHeaders = {};
157
168
  resolved = version;
@@ -160,7 +171,7 @@ export async function fetchNpmPackage(cfg, name, version, signal, opts = {}) {
160
171
  else {
161
172
  // scope 包名里的 `/` 按 npm 客户端的写法编码为 %2f
162
173
  const docUrl = new URL(name.replace("/", "%2f"), registry);
163
- const res = await get(docUrl, { ...authHeaders, accept: "application/json" }, signal, "npm registry");
174
+ const res = await npmGet(cfg, docUrl, { ...authHeaders, accept: "application/json" }, signal, "npm registry");
164
175
  const raw = await readCapped(res, MAX_METADATA_BYTES, () => new NpmFetchError("the npm package metadata is too large"));
165
176
  let doc;
166
177
  try {
@@ -207,7 +218,7 @@ export async function fetchNpmPackage(cfg, name, version, signal, opts = {}) {
207
218
  throw new NpmFetchError(`npm package ${name}@${picked} has no integrity to verify`);
208
219
  resolved = picked;
209
220
  }
210
- const res = await get(tarball, tarballHeaders, signal, "package tarball");
221
+ const res = await npmGet(cfg, tarball, tarballHeaders, signal, "package tarball");
211
222
  const bytes = await readCapped(res, cfg.maxBytes, tooLarge);
212
223
  verify(bytes, integrity, opts.expectedIntegrity !== undefined ? "the expected integrity" : "the npm dist.integrity");
213
224
  return {
@@ -6,7 +6,9 @@ import { type NpmFetchConfig } from "./npm.js";
6
6
  * workflow it was built from. This is display only: the sigstore signatures are not verified, and
7
7
  * nothing here ever fails an import. A registry without provenance, a network error, a timeout, an
8
8
  * oversized or malformed answer all give `{ checked: false, reason }` ("provenance not checked").
9
- * The registry token goes only to the registry (the attestation URL is always on its origin).
9
+ * The registry token goes only to the registry (the attestation URL is always on its origin). The
10
+ * request goes through `packages/kernel/src/net` under `cfg.net` like every npm download (no
11
+ * redirects, the network rules, `net.httpsProxy`); a refused address is "not checked" too.
10
12
  */
11
13
  /** What the SLSA provenance of an npm package says about its build. */
12
14
  export interface Provenance {
@@ -1,3 +1,5 @@
1
+ import { NetDeniedError } from "../net/public-address.js";
2
+ import { safeFetch } from "../net/safe-fetch.js";
1
3
  import { readCapped } from "./npm.js";
2
4
  /** The predicate type of an SLSA v1 provenance statement. */
3
5
  export const SLSA_PROVENANCE_V1 = "https://slsa.dev/provenance/v1";
@@ -38,14 +40,13 @@ export async function fetchProvenance(cfg, name, version, signal, opts = {}) {
38
40
  const registry = new URL(cfg.registry.endsWith("/") ? cfg.registry : `${cfg.registry}/`);
39
41
  // the npm client's escaping: a scoped name's `/` is %2f
40
42
  const url = new URL(`-/npm/v1/attestations/${name.replace("/", "%2f")}@${encodeURIComponent(version)}`, registry);
41
- const res = await fetch(url, {
43
+ const res = await safeFetch(url.toString(), {
42
44
  headers: {
43
45
  accept: "application/json",
44
46
  ...(cfg.token !== undefined && { authorization: `Bearer ${cfg.token}` }),
45
47
  },
46
- redirect: "manual",
47
48
  signal,
48
- });
49
+ }, cfg.net, cfg.lookup !== undefined ? { lookup: cfg.lookup } : {});
49
50
  if (res.status === 404) {
50
51
  await res.body?.cancel().catch(() => { });
51
52
  return notChecked("the registry has no provenance for this version");
@@ -60,6 +61,9 @@ export async function fetchProvenance(cfg, name, version, signal, opts = {}) {
60
61
  catch (e) {
61
62
  if (signal.aborted)
62
63
  return notChecked("the registry did not answer in time");
64
+ if (e instanceof NetDeniedError) {
65
+ return notChecked(`the network rules refused the attestations: ${e.message}`);
66
+ }
63
67
  return notChecked(`cannot read the attestations: ${errMsg(e)}`);
64
68
  }
65
69
  try {
@@ -131,7 +131,7 @@ let DevicesOperations = class DevicesOperations {
131
131
  }),
132
132
  defineOperation({
133
133
  id: "devices.get",
134
- description: "Read one of your devices with its source (cloud or local), provider, state, instance, the machine of a local one and whether it is online, limits, its mode (the one its commands run at and the one this org allows, and which layer allows auto mode), its network and where that comes from, a pending change that applies on its next use, its recent mode and policy changes, and creation time. Takes the id from devices.list. Only the person changes a device's mode: a local device's on the machine, a cloud device's on the web and to sandbox only; enabling auto mode happens on the machine.",
134
+ description: "Read one of your devices with its source (cloud or local), provider, state, instance, the machine of a local one and whether it is online, limits, its mode (the one its commands run at and the one this org allows, and which layer allows auto mode), its network and where that comes from, a pending change that applies on its next use, its recent mode and policy changes, and creation time. Takes the id from devices.list. Only the person changes a device's mode: a local device's on the machine (auto mode is enabled only there), a cloud device's on its device page (to sandbox, or back to following the org's mode).",
135
135
  input: DeviceId,
136
136
  example: { deviceId: "4e8a0c1d-6b2f-4a37-8d19-3c5e7f9a1b20" },
137
137
  authz: { orgAction: "agents.use" },
@@ -1,6 +1,7 @@
1
1
  import { type OnModuleInit } from "@nestjs/common";
2
2
  import { AgentsService } from "../../agents/agents.service.js";
3
3
  import { AccountsService } from "../../identity/accounts.js";
4
+ import { KernelConfigService } from "../../infra/config/kernel-config.service.js";
4
5
  import { KernelDb } from "../../infra/database/kernel-db.js";
5
6
  import { OrgSettingsService } from "../../orgs/settings.service.js";
6
7
  import { ThemesService } from "../../themes/themes.service.js";
@@ -20,7 +21,8 @@ export declare class PlatformOperationsProvider implements OnModuleInit {
20
21
  private readonly accounts;
21
22
  private readonly themes;
22
23
  private readonly db;
23
- constructor(registry: PlatformOperations, actor: PlatformActor, agents: AgentsService, settings: OrgSettingsService, tools: ToolRegistry, accounts: AccountsService, themes: ThemesService, db: KernelDb);
24
+ private readonly config;
25
+ constructor(registry: PlatformOperations, actor: PlatformActor, agents: AgentsService, settings: OrgSettingsService, tools: ToolRegistry, accounts: AccountsService, themes: ThemesService, db: KernelDb, config: KernelConfigService);
24
26
  /**
25
27
  * The skills in the agent's catalog now, by the names a run's catalog lists them, each with its
26
28
  * plugin (skills default-on spec §11): the resolver's result for this conversation, as the next
@@ -13,9 +13,11 @@ import { AgentsService } from "../../agents/agents.service.js";
13
13
  import { conversationSourceOf } from "../../conversations/source.js";
14
14
  import { AccountsService } from "../../identity/accounts.js";
15
15
  import { PreferencesSchema } from "../../identity/me.schemas.js";
16
+ import { KernelConfigService } from "../../infra/config/kernel-config.service.js";
16
17
  import { KernelDb } from "../../infra/database/kernel-db.js";
17
18
  import { can } from "../../orgs/roles.js";
18
19
  import { OrgSettingsService } from "../../orgs/settings.service.js";
20
+ import { effectiveDevicePolicy, readDeploymentDevicePolicy } from "../../sandbox/modes.js";
19
21
  import { resolveEffectiveSkills } from "../../skills/catalog.js";
20
22
  import { ThemesService } from "../../themes/themes.service.js";
21
23
  import { SANDBOX_TOOL_NAMES } from "../../tools/builtin-names.js";
@@ -53,7 +55,8 @@ let PlatformOperationsProvider = class PlatformOperationsProvider {
53
55
  accounts;
54
56
  themes;
55
57
  db;
56
- constructor(registry, actor, agents, settings, tools, accounts, themes, db) {
58
+ config;
59
+ constructor(registry, actor, agents, settings, tools, accounts, themes, db, config) {
57
60
  this.registry = registry;
58
61
  this.actor = actor;
59
62
  this.agents = agents;
@@ -62,6 +65,7 @@ let PlatformOperationsProvider = class PlatformOperationsProvider {
62
65
  this.accounts = accounts;
63
66
  this.themes = themes;
64
67
  this.db = db;
68
+ this.config = config;
65
69
  }
66
70
  /**
67
71
  * The skills in the agent's catalog now, by the names a run's catalog lists them, each with its
@@ -149,10 +153,9 @@ let PlatformOperationsProvider = class PlatformOperationsProvider {
149
153
  this.skillNames(ctx, d),
150
154
  ]);
151
155
  const sandbox = toolKeys.some((k) => SANDBOX_TOOL_NAMES.includes(k));
152
- const org = await this.settings.get(ctx.orgId);
153
- // a new device's mode and network (auto mode spec §4.3)
154
- const deployment = await this.settings.deployment();
155
- const mode = deployment.autoMode.mode === "allowed" && org.autoMode !== "off" ? "auto" : "sandbox";
156
+ // a new device's mode and network (auto mode spec §4.3): the one derivation the
157
+ // devices use, so a sandbox-mode device on the open network reads as open
158
+ const policy = effectiveDevicePolicy(await readDeploymentDevicePolicy(this.db.db, this.config), await this.settings.get(ctx.orgId), null);
156
159
  return {
157
160
  id: agent.id,
158
161
  name: d.name,
@@ -168,13 +171,7 @@ let PlatformOperationsProvider = class PlatformOperationsProvider {
168
171
  disabledSkills: d.disabledSkills ?? [],
169
172
  subagents: d.subagents ?? null,
170
173
  sandbox: sandbox
171
- ? {
172
- enabled: true,
173
- mode,
174
- network: mode === "auto" && deployment.cloudNetwork.mode === "open"
175
- ? "open-public"
176
- : "allowlist",
177
- }
174
+ ? { enabled: true, mode: policy.mode, network: policy.network.kind }
178
175
  : { enabled: false },
179
176
  profile: {
180
177
  avatar: agent.profile.avatar,
@@ -258,6 +255,7 @@ PlatformOperationsProvider = __decorate([
258
255
  __param(4, Inject(ToolRegistry)),
259
256
  __param(5, Inject(AccountsService)),
260
257
  __param(6, Inject(ThemesService)),
261
- __param(7, Inject(KernelDb))
258
+ __param(7, Inject(KernelDb)),
259
+ __param(8, Inject(KernelConfigService))
262
260
  ], PlatformOperationsProvider);
263
261
  export { PlatformOperationsProvider };
@@ -217,6 +217,14 @@ type SummaryEvent = ConversationEvent & {
217
217
  type: "compaction_summary";
218
218
  payload: EventPayload<"compaction_summary">;
219
219
  };
220
+ /**
221
+ * The user messages a summary re-renders after its text (context compaction spec §4.2, revision
222
+ * 2026-11-15): exactly the ones its `openingSeqs` names, in seq order, decided when the summary was
223
+ * written. A summary without the field (every older log) re-renders nothing. `events` sorted by seq.
224
+ */
225
+ export declare function summaryOpeners(events: readonly ConversationEvent[], summary: SummaryEvent | null): (ConversationEvent & {
226
+ type: "user_message";
227
+ })[];
220
228
  /** 最近一条 `compaction_summary` 事件(按 seq);没有则 null。 */
221
229
  export declare function latestSummary(events: ConversationEvent[]): SummaryEvent | null;
222
230
  /** 摘要作为首条 user 消息时的文本。 */
@@ -229,7 +237,8 @@ export declare function summaryText(summary: string): string;
229
237
  * 第二个块是工具目录(见 {@link BuildModelRequestInput.toolSearch});
230
238
  * - 之后的 `skills_catalog` 在所在位置渲染为 system 变更提醒;被压缩摘要覆盖的,若摘要时生效的目录与 system 里的
231
239
  * 不同,紧随摘要补一条完整的当前目录;
232
- * - messages:最近一条摘要(若有)作为首条 user 消息,其后按 seq 回放 `coversUpToSeq` 之后的
240
+ * - messages:最近一条摘要(若有)作为首条 user 消息(摘要切在用户轮次内部时,该轮的开头消息按普通
241
+ * user_message 的渲染接在摘要文本之后、同一条消息里:摘要的 `openingSeqs`,{@link summaryOpeners}),其后按 seq 回放 `coversUpToSeq` 之后的
233
242
  * `user_message` / `assistant_message`(content 原样,含 opaque;aborted 的也回放;媒体引用按
234
243
  * {@link resolveMedia} 换成 base64 或文字占位)/ `reminder`
235
244
  * (`role: "system"`,放在它所在的位置)/ `tools_changed` (`role: "system"`, the text of {@link toolsChangedText}, at its position) /