@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
package/bootstrap.json CHANGED
@@ -3,7 +3,7 @@
3
3
  "schemaVersion": 1,
4
4
  "marketplace": {
5
5
  "url": "https://github.com/capybara-hq/plugins.git",
6
- "commit": "ce9c71ed59616520447edda01117252dfbc45680"
6
+ "commit": "08074e9ffafb9c4d8cc4252a9d4bc18cba37e53c"
7
7
  },
8
8
  "plugins": [
9
9
  {
@@ -90,8 +90,8 @@
90
90
  "name": "sandbox-docker",
91
91
  "source": "npm",
92
92
  "npm": "@capybara-hq/plugin-sandbox-docker",
93
- "version": "0.1.0-rc.14",
94
- "integrity": "sha512-e64Re3gnU5uxQT/JH3mUolSyz0/Njen5CzMKl9brcsqouV7cY0sIjReLpnkBV0zNxmpMvK73WAO7OT7CZd5Kbg==",
93
+ "version": "0.1.0-rc.15",
94
+ "integrity": "sha512-GeOxDSp51kMQW7cGZz9CRNFFn3fh7OUUVI1Dwul+fioHdEc+mEXckiapHrjc/cFwfnKTPb+R/yA+LVVgbFe9Vg==",
95
95
  "required": false
96
96
  },
97
97
  {
@@ -25,8 +25,11 @@ export type MarketplaceNetCode = "marketplace.private_address" | "marketplace.re
25
25
  * marketplace codes (an invalid URL or a DNS failure is an ordinary fetch failure).
26
26
  */
27
27
  export declare function marketplaceNetCode(e: NetDeniedError): MarketplaceNetCode | undefined;
28
- /** The network rules for marketplace downloads from the kernel config. */
29
- export declare function marketplaceNetPolicy(config: KernelConfig): NetPolicy;
28
+ /**
29
+ * The network rules for marketplace downloads from the kernel config; npm registry downloads
30
+ * (packages, provenance, bootstrap plugins) use them too, with the registry's origin trusted.
31
+ */
32
+ export declare function marketplaceNetPolicy(config: Pick<KernelConfig, "marketplaces" | "net" | "packages">): NetPolicy;
30
33
  /**
31
34
  * The fetch failed (network, HTTP status, redirect, size, timeout). English message, no token.
32
35
  * `code` is set when the network rules refused the request.
@@ -15,7 +15,10 @@ export function marketplaceNetCode(e) {
15
15
  return "marketplace.redirect";
16
16
  return undefined;
17
17
  }
18
- /** The network rules for marketplace downloads from the kernel config. */
18
+ /**
19
+ * The network rules for marketplace downloads from the kernel config; npm registry downloads
20
+ * (packages, provenance, bootstrap plugins) use them too, with the registry's origin trusted.
21
+ */
19
22
  export function marketplaceNetPolicy(config) {
20
23
  return {
21
24
  allowInsecureLoopback: config.marketplaces.allowInsecureLoopback,
@@ -265,11 +265,12 @@ export declare class CatalogRequestsService {
265
265
  private writeDecision;
266
266
  /**
267
267
  * Approves a `network_allowlist` request inside its decision's transaction: the hosts the org's
268
- * sandbox allowlist does not hold yet are added to the org's `cloudNetwork` as an allowlist with
269
- * them, through {@link OrgSettingsService.update} (audited `org.settings_updated` with
270
- * `requestId`). An org following the deployment default starts from the deployment's list (it
271
- * keeps its own list from then on); an org whose cloud network is open is narrowed to the
272
- * allowlist, which is what its sandbox-mode devices already use. The platform kill switch, more
268
+ * sandbox allowlist does not hold yet are added to the host list of the org's `cloudNetwork`,
269
+ * through {@link OrgSettingsService.update} (audited `org.settings_updated` with `requestId`).
270
+ * An org following the deployment default starts from the deployment's list (it keeps its own
271
+ * list from then on). The org's network mode is kept: the list caps local sandbox devices, and
272
+ * approving a host never turns an open cloud network into an allowlist (auto mode hardening
273
+ * spec K1). The platform kill switch, more
273
274
  * than {@link ORG_SANDBOX_ALLOW_HOSTS_MAX} hosts -> `catalog.request_invalid`; decided with an API
274
275
  * token -> `org.sandbox_egress_not_allowed` (only a person widens the network). Hosts all allowed
275
276
  * already: nothing is written.
@@ -621,11 +621,12 @@ let CatalogRequestsService = class CatalogRequestsService {
621
621
  }
622
622
  /**
623
623
  * Approves a `network_allowlist` request inside its decision's transaction: the hosts the org's
624
- * sandbox allowlist does not hold yet are added to the org's `cloudNetwork` as an allowlist with
625
- * them, through {@link OrgSettingsService.update} (audited `org.settings_updated` with
626
- * `requestId`). An org following the deployment default starts from the deployment's list (it
627
- * keeps its own list from then on); an org whose cloud network is open is narrowed to the
628
- * allowlist, which is what its sandbox-mode devices already use. The platform kill switch, more
624
+ * sandbox allowlist does not hold yet are added to the host list of the org's `cloudNetwork`,
625
+ * through {@link OrgSettingsService.update} (audited `org.settings_updated` with `requestId`).
626
+ * An org following the deployment default starts from the deployment's list (it keeps its own
627
+ * list from then on). The org's network mode is kept: the list caps local sandbox devices, and
628
+ * approving a host never turns an open cloud network into an allowlist (auto mode hardening
629
+ * spec K1). The platform kill switch, more
629
630
  * than {@link ORG_SANDBOX_ALLOW_HOSTS_MAX} hosts -> `catalog.request_invalid`; decided with an API
630
631
  * token -> `org.sandbox_egress_not_allowed` (only a person widens the network). Hosts all allowed
631
632
  * already: nothing is written.
@@ -649,7 +650,7 @@ let CatalogRequestsService = class CatalogRequestsService {
649
650
  }
650
651
  // approving widens the org's network allowlist: only a person in a session does that, never an
651
652
  // API token (auto mode spec §4.3; the Platform tool has no decide operation at all)
652
- await this.orgSettings.update(orgId, { cloudNetwork: { mode: "allowlist", allowHosts } }, actor, opts.actorTokenId, { requestId }, { onlyNarrows: opts.actorTokenId !== undefined });
653
+ await this.orgSettings.update(orgId, { cloudNetwork: { mode: current?.mode ?? deployment.mode, allowHosts } }, actor, opts.actorTokenId, { requestId }, { onlyNarrows: opts.actorTokenId !== undefined });
653
654
  }
654
655
  /**
655
656
  * The requester dismisses a decided request from the inbox (`POST /orgs/:orgId/
@@ -6,6 +6,12 @@ export { ConfigError, type ConfigSource };
6
6
  export declare function selectConfigSource(env: NodeJS.ProcessEnv): ConfigSource;
7
7
  /** 深合并:对象递归合并,其余(含数组)由 override 整体替换。 */
8
8
  export declare function deepMerge(base: unknown, override: unknown): unknown;
9
+ /**
10
+ * Removed sandbox keys still present in the loaded config (file, Nacos or environment), each with
11
+ * the setting that replaces it (auto mode hardening spec K3). The schema would strip an unknown
12
+ * key silently, and an ignored security key reads as a widening, so the config fails instead.
13
+ */
14
+ export declare function removedConfigProblems(merged: unknown): string[];
9
15
  /** 原始配置深合并环境变量覆盖(优先级最高)后校验;热更新与启动共用。错误只列路径不列值。 */
10
16
  export declare function resolveConfig(raw: unknown, env: NodeJS.ProcessEnv): KernelConfig;
11
17
  /** 选来源 → 深合并环境变量覆盖(优先级最高)→ 校验。 */
@@ -63,11 +63,37 @@ export function deepMerge(base, override) {
63
63
  }
64
64
  return out;
65
65
  }
66
+ /**
67
+ * Removed sandbox keys still present in the loaded config (file, Nacos or environment), each with
68
+ * the setting that replaces it (auto mode hardening spec K3). The schema would strip an unknown
69
+ * key silently, and an ignored security key reads as a widening, so the config fails instead.
70
+ */
71
+ export function removedConfigProblems(merged) {
72
+ const sandbox = isPlainObject(merged) ? merged.sandbox : undefined;
73
+ if (!isPlainObject(sandbox))
74
+ return [];
75
+ const limits = isPlainObject(sandbox.limits) ? sandbox.limits : {};
76
+ const out = [];
77
+ if (sandbox.tiers !== undefined) {
78
+ out.push("sandbox.tiers: removed; auto mode replaces the sandbox tiers. Set devices.autoMode (allowed | off) for the platform; each organization chooses its autoMode and its cloud network (cloudNetwork: open | allowlist) in its settings");
79
+ }
80
+ if (limits.devHosts !== undefined) {
81
+ out.push("sandbox.limits.devHosts: removed with the dev tier; put the hosts in sandbox.limits.allowHosts (the default allowlist) or in an organization's cloudNetwork hosts");
82
+ }
83
+ if (limits.egress === "open") {
84
+ out.push('sandbox.limits.egress: "open" was removed; the open public network is set by devices.autoMode (auto mode reaches public hosts) and by an organization\'s cloudNetwork; use "allowlist" or "none" here');
85
+ }
86
+ return out;
87
+ }
66
88
  /** 原始配置深合并环境变量覆盖(优先级最高)后校验;热更新与启动共用。错误只列路径不列值。 */
67
89
  export function resolveConfig(raw, env) {
68
90
  if (!isPlainObject(raw))
69
91
  throw new ConfigError("config file root must be a mapping");
70
92
  const merged = deepMerge(raw, envOverrides(env));
93
+ const removed = removedConfigProblems(merged);
94
+ if (removed.length > 0) {
95
+ throw new ConfigError(`invalid configuration:\n${removed.map((l) => ` - ${l}`).join("\n")}`);
96
+ }
71
97
  const result = KernelConfigSchema.safeParse(merged);
72
98
  if (!result.success) {
73
99
  const lines = result.error.issues.map((i) => ` - ${i.path.map(String).join(".") || "(root)"}: ${i.message}`);
@@ -402,7 +402,7 @@ export const KernelConfigSchema = z.object({
402
402
  .optional()
403
403
  .meta(meta({
404
404
  secret: true,
405
- description: "HTTP(S) egress proxy for marketplace, archive and git downloads, e.g. http://user:password@proxy.internal:3128. https downloads tunnel through it with CONNECT and the kernel no longer resolves their hosts: the proxy does, so blocking private and internal addresses becomes the proxy's job (IP-literal URLs are still checked against marketplaces.allowPrivateHosts). Loopback hosts never use it. Credentials in the URL are sent as Basic Proxy-Authorization and never logged",
405
+ description: "HTTP(S) egress proxy for marketplace, archive and git downloads, npm registry downloads (packages, provenance, bootstrap plugins) and OAuth requests (discovery, registration, token endpoints), e.g. http://user:password@proxy.internal:3128. https downloads tunnel through it with CONNECT and the kernel no longer resolves their hosts: the proxy does, so blocking private and internal addresses becomes the proxy's job (IP-literal URLs are still checked against marketplaces.allowPrivateHosts). Loopback hosts never use it, nor does an http:// npm registry; list an internal https registry in net.noProxy. HTTPS_PROXY / NODE_USE_ENV_PROXY are not read. Credentials in the URL are sent as Basic Proxy-Authorization and never logged",
406
406
  })),
407
407
  noProxy: z
408
408
  .array(z
@@ -1319,7 +1319,7 @@ export const KernelConfigSchema = z.object({
1319
1319
  egress: z
1320
1320
  .enum(["none", "allowlist"], {
1321
1321
  error: (iss) => iss.input === "open"
1322
- ? 'sandbox.limits.egress does not take "open": the open public network is a cloud device\'s default in auto mode; use "allowlist" or "none"'
1322
+ ? 'sandbox.limits.egress does not take "open": the open public network is set by devices.autoMode and an organization\'s cloudNetwork; use "allowlist" or "none"'
1323
1323
  : undefined,
1324
1324
  })
1325
1325
  .default("allowlist")
@@ -1346,8 +1346,8 @@ export const KernelConfigSchema = z.object({
1346
1346
  devices: z
1347
1347
  .object({
1348
1348
  /**
1349
- * The platform's auto-mode switch (auto mode spec §4.3): the default for a new local device,
1350
- * and a cloud device's network follows it. Also a deployment setting the super admin changes
1349
+ * The platform's auto-mode switch (auto mode spec §4.3): whether a device may run in auto
1350
+ * mode; when off, a cloud device keeps its org's cloudNetwork (open by default). Also a deployment setting the super admin changes
1351
1351
  * in the admin console; the startup config wins over it, so this field is optional with no
1352
1352
  * schema default (the default `allowed` is applied by `readDevicesAutoMode`: a schema default
1353
1353
  * would be indistinguishable from a value the config source set, and the stored choice may
@@ -1358,7 +1358,7 @@ export const KernelConfigSchema = z.object({
1358
1358
  .optional()
1359
1359
  .meta(meta({
1360
1360
  hot: true,
1361
- description: "Whether devices may run in auto mode (default allowed): auto mode is the default of a new local device, and a cloud device's network opens to public hosts when it is allowed (the allowlist when off). An organization may turn it off and follow the platform; only capybara-device on the machine turns auto mode on, and the web may switch a local device to sandbox mode. Set here, it is read-only in the admin console",
1361
+ description: "Whether devices may run in auto mode (default allowed): auto mode is the default of a new local device and of a cloud device, whose network in auto mode is the open public network (private and internal addresses blocked). When off, devices run in sandbox mode: local devices on their allowlist, cloud devices on their organization's cloud network (cloudNetwork, open by default, or the allowlist the organization sets). An organization may turn it off and follow the platform; only capybara-device on the machine turns auto mode on for a local device. Set here, it is read-only in the admin console",
1362
1362
  })),
1363
1363
  maxPersonal: z
1364
1364
  .number()
@@ -157,6 +157,9 @@ export type LogContentBlock = Exclude<ContentBlock, MediaBlock> | (MediaBlock ex
157
157
  * `guard`: `Edit` / `Write` refused by the read-before-write check (`not_read`: the file was never
158
158
  * read in the conversation, `modified`: it changed since). The result stays `isError: true` for
159
159
  * the model; the web shows the refusal as a neutral outcome, not a failure.
160
+ * `not_loaded`: a call to a tool the catalog holds but the step's request did not carry
161
+ * (ToolSearch mode, spec 5.5): expected behaviour, the model is told to load it first. The result
162
+ * stays `isError: true` for the model; the web shows it as a neutral outcome too.
160
163
  */
161
164
  export declare const ToolViewSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{
162
165
  kind: z.ZodLiteral<"command">;
@@ -203,6 +206,8 @@ export declare const ToolViewSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{
203
206
  modified: "modified";
204
207
  not_read: "not_read";
205
208
  }>;
209
+ }, z.core.$strip>, z.ZodObject<{
210
+ kind: z.ZodLiteral<"not_loaded">;
206
211
  }, z.core.$strip>], "kind">;
207
212
  export type ToolView = z.infer<typeof ToolViewSchema>;
208
213
  /**
@@ -790,6 +795,8 @@ export declare const ConversationEventSchema: z.ZodDiscriminatedUnion<[z.ZodObje
790
795
  modified: "modified";
791
796
  not_read: "not_read";
792
797
  }>;
798
+ }, z.core.$strip>, z.ZodObject<{
799
+ kind: z.ZodLiteral<"not_loaded">;
793
800
  }, z.core.$strip>], "kind">>;
794
801
  card: z.ZodOptional<z.ZodObject<{
795
802
  plugin: z.ZodString;
@@ -1292,12 +1299,15 @@ export declare const ConversationEventSchema: z.ZodDiscriminatedUnion<[z.ZodObje
1292
1299
  coversUpToSeq: z.ZodNumber;
1293
1300
  text: z.ZodString;
1294
1301
  savedTokens: z.ZodOptional<z.ZodNumber>;
1302
+ openingSeqs: z.ZodOptional<z.ZodArray<z.ZodNumber>>;
1303
+ step: z.ZodOptional<z.ZodNumber>;
1295
1304
  }, z.core.$strip>;
1296
1305
  }, z.core.$strip>, z.ZodObject<{
1297
1306
  type: z.ZodLiteral<"compaction_failed">;
1298
1307
  payload: z.ZodObject<{
1299
1308
  attempt: z.ZodNumber;
1300
1309
  reason: z.ZodString;
1310
+ step: z.ZodOptional<z.ZodNumber>;
1301
1311
  }, z.core.$strip>;
1302
1312
  }, z.core.$strip>, z.ZodObject<{
1303
1313
  type: z.ZodLiteral<"run_finished">;
@@ -158,6 +158,9 @@ const FileStateViewSchema = z.object({
158
158
  * `guard`: `Edit` / `Write` refused by the read-before-write check (`not_read`: the file was never
159
159
  * read in the conversation, `modified`: it changed since). The result stays `isError: true` for
160
160
  * the model; the web shows the refusal as a neutral outcome, not a failure.
161
+ * `not_loaded`: a call to a tool the catalog holds but the step's request did not carry
162
+ * (ToolSearch mode, spec 5.5): expected behaviour, the model is told to load it first. The result
163
+ * stays `isError: true` for the model; the web shows it as a neutral outcome too.
161
164
  */
162
165
  export const ToolViewSchema = z.discriminatedUnion("kind", [
163
166
  z.object({
@@ -198,6 +201,7 @@ export const ToolViewSchema = z.discriminatedUnion("kind", [
198
201
  kind: z.literal("guard"),
199
202
  reason: z.enum(["not_read", "modified"]),
200
203
  }),
204
+ z.object({ kind: z.literal("not_loaded") }),
201
205
  ]);
202
206
  const ModelUsageShape = {
203
207
  inputTokens: count,
@@ -1081,8 +1085,26 @@ export const ConversationEventSchema = z.discriminatedUnion("type", [
1081
1085
  * logs have none.
1082
1086
  */
1083
1087
  savedTokens: count.optional(),
1088
+ /**
1089
+ * The user messages that started the run being compacted, when the summary covers them
1090
+ * (context compaction spec §4.2, revision 2026-11-15), in seq order: request building
1091
+ * re-renders exactly these after the summary text. Decided when the summary is written, so a
1092
+ * request never depends on later events. Optional: older logs (and summaries that cover no
1093
+ * opening message) have none and re-render nothing.
1094
+ */
1095
+ openingSeqs: z.array(seqNo).optional(),
1096
+ /**
1097
+ * The step the compaction ran in (0 for a manual compact run), so a later compaction in the
1098
+ * same step takes the next idempotency key. Optional: older logs have none.
1099
+ */
1100
+ step: count.optional(),
1101
+ })),
1102
+ ev("compaction_failed", z.object({
1103
+ attempt: count,
1104
+ reason: z.string(),
1105
+ /** The step the compaction ran in, as on `compaction_summary`. Optional: older logs. */
1106
+ step: count.optional(),
1084
1107
  })),
1085
- ev("compaction_failed", z.object({ attempt: count, reason: z.string() })),
1086
1108
  ev("run_finished", z.object({
1087
1109
  /** `budget`: a sub-agent stopped at its parent run's token cap (phase C, spec §8.3). */
1088
1110
  reason: z.enum(["completed", "max_steps", "max_duration", "budget"]),
@@ -62,9 +62,10 @@ let DevicesController = class DevicesController {
62
62
  async update(principal, org, params, body) {
63
63
  const p = requireUser(principal);
64
64
  const tokenId = patTokenId(p);
65
- // a person changes their device's mode in a session (auto mode spec §4.3)
65
+ // a person changes their device's mode in a web session, narrowing or widening (auto mode
66
+ // spec §4.3, hardening D2): never an API token
66
67
  if (body.mode !== undefined && tokenId !== undefined) {
67
- throw new ApiError("auth.session_required", "A device's mode is changed by its owner on the web, not with an API token");
68
+ throw new ApiError("device.mode_requires_session", "A device's mode is changed by its owner on the device page, not with an API token");
68
69
  }
69
70
  return {
70
71
  device: await this.devices.update(org.orgId, p.account.id, params.id, {
@@ -9,7 +9,7 @@ import { DevicePolicyService } from "../local-devices/device-policy.service.js";
9
9
  import { MachinesService } from "../local-devices/machines.js";
10
10
  import type { DeviceModeLevel } from "../runtime/context/device-paths.js";
11
11
  import { SandboxJobs } from "../sandbox/jobs.js";
12
- import { type EffectiveDevicePolicy, type NetworkKind, type OrgDeviceSettings, type SandboxMode } from "../sandbox/modes.js";
12
+ import { type DeviceNetwork, type EffectiveDevicePolicy, type NetworkKind, type OrgDeviceSettings, type SandboxMode } from "../sandbox/modes.js";
13
13
  import { SandboxProviders } from "../sandbox/providers.js";
14
14
  import { SandboxService } from "../sandbox/sandbox.service.js";
15
15
  import { DeviceAccess } from "./access.js";
@@ -94,6 +94,15 @@ export interface DeviceModeView {
94
94
  reported: SandboxMode | null;
95
95
  allowedDomains: string[];
96
96
  } | null;
97
+ /**
98
+ * A cloud device: the network sandbox mode gives it, whatever mode it runs at now (the org's
99
+ * `cloudNetwork`, open by default; the kill switch empties it), so the page names what a switch
100
+ * to sandbox reaches before it is made (hardening spec D3). Null for a local device.
101
+ */
102
+ sandboxNetwork: {
103
+ kind: NetworkKind;
104
+ hosts: string[];
105
+ } | null;
97
106
  /**
98
107
  * A cloud device's instance runs another mode or network kind: its next use updates or recreates
99
108
  * it, files kept (「下次使用时生效,文件保留」).
@@ -150,11 +159,12 @@ export interface DevicePolicyChange {
150
159
  export interface DevicePatch {
151
160
  name?: string;
152
161
  /**
153
- * A narrowing mode change (`sandbox` only): a cloud device stores it and applies the org's
154
- * `cloudNetwork`; a local device refuses it here (`device.mode_on_device`, its mode is its
155
- * machine's).
162
+ * A cloud device's mode choice: `sandbox` narrows it (the org's `cloudNetwork` applies), `null`
163
+ * clears the choice so it follows the org and the platform again (auto when they allow it;
164
+ * hardening spec D2). Only a person in a web session sends it (the controller refuses a token).
165
+ * A local device refuses it here (`device.mode_on_device`, its mode is its machine's).
156
166
  */
157
- mode?: "sandbox";
167
+ mode?: "sandbox" | null;
158
168
  }
159
169
  /** The machine connected to a local device, as its owner sees it. */
160
170
  export interface DeviceMachineView {
@@ -404,6 +414,8 @@ export declare function deviceModeViewOf(policy: EffectiveDevicePolicy, settings
404
414
  pendingNextUse: boolean;
405
415
  pendingFilesReset: boolean;
406
416
  recent: DeviceModeChangeView[];
417
+ /** The network sandbox mode gives a cloud device ({@link deviceNetwork} for `sandbox`). */
418
+ sandboxNetwork: DeviceNetwork;
407
419
  },
408
420
  /** The platform kill switch (`sandbox.limits.egress: none`): the network is the platform's. */
409
421
  killSwitch?: boolean): DeviceModeView;
@@ -25,7 +25,7 @@ import { MachinesService } from "../local-devices/machines.js";
25
25
  import { deviceFeaturesOf, localModeOf, localPolicyOf } from "../local-devices/policy-summary.js";
26
26
  import { readOrgSettings } from "../orgs/settings.service.js";
27
27
  import { oweDeviceDestroy, SandboxJobs } from "../sandbox/jobs.js";
28
- import { effectiveDevicePolicy, readDeploymentDevicePolicy, } from "../sandbox/modes.js";
28
+ import { deviceNetwork, effectiveDevicePolicy, readDeploymentDevicePolicy, } from "../sandbox/modes.js";
29
29
  import { isInternalProvider, LOCAL_PROVIDER, SandboxProviders } from "../sandbox/providers.js";
30
30
  import { deviceNotFound, SandboxService } from "../sandbox/sandbox.service.js";
31
31
  import { DeviceAccess, demotedProvider, deviceProvider, deviceUnavailable, inUseForDefault, } from "./access.js";
@@ -261,27 +261,29 @@ let DevicesService = class DevicesService {
261
261
  async updateIn(orgId, accountId, id, patch, actorTokenId) {
262
262
  const before = await this.lockOwn(orgId, accountId, id);
263
263
  if (patch.mode !== undefined) {
264
- // A cloud device's switch only narrows (auto → sandbox); a local device's mode lives on its
265
- // machine (auto mode spec §4.3).
264
+ // A cloud device's owner narrows it to sandbox or clears the choice to follow the org (auto
265
+ // mode spec §4.3, hardening D2); a local device's mode lives on its machine.
266
266
  if (before.source !== "cloud") {
267
267
  throw new ApiError("device.mode_on_device", "This device's mode is kept on its connected machine: switch to sandbox mode from the device page (sent to the machine) or run capybara-device mode sandbox there.");
268
268
  }
269
- if (before.mode !== "sandbox") {
270
- // `from` is the mode it ran at before, which may already be sandbox (the org turned it off)
271
- const effective = await this.sandbox.devicePolicy({ orgId, deviceId: id });
269
+ if ((before.mode ?? null) !== patch.mode) {
270
+ // `from` / `to` are the modes it runs at: the org may cap both at sandbox, and then the
271
+ // stored choice changes without a mode change, so nothing is audited
272
+ const from = (await this.sandbox.devicePolicy({ orgId, deviceId: id })).mode;
272
273
  await this.db
273
274
  .updateTable("devices")
274
- .set({ mode: "sandbox", updated_at: sql `now()` })
275
+ .set({ mode: patch.mode, updated_at: sql `now()` })
275
276
  .where("id", "=", id)
276
277
  .execute();
277
- if (effective.mode !== "sandbox") {
278
+ const to = (await this.sandbox.devicePolicy({ orgId, deviceId: id })).mode;
279
+ if (from !== to) {
278
280
  await audit(this.db.db, {
279
281
  actorAccountId: accountId,
280
282
  ...(actorTokenId !== undefined && { actorTokenId }),
281
283
  orgId,
282
284
  action: "device.mode_changed",
283
285
  target: id,
284
- detail: { from: effective.mode, to: "sandbox", by: accountId, via: "web" },
286
+ detail: { from, to, by: accountId, via: "web" },
285
287
  });
286
288
  }
287
289
  }
@@ -487,8 +489,13 @@ let DevicesService = class DevicesService {
487
489
  if (inUseForDefault(live) || current === undefined)
488
490
  return live.id;
489
491
  const former = await this.formerDefaults(orgId, accountId, current);
490
- if (!former.some((f) => f.holdsFiles))
491
- return live.id;
492
+ // Two unlocked reads: a swap committed between them leaves `live` demoted and the restored
493
+ // default out of `former`. Only a default still live after `former` is the answer; else
494
+ // the locked path decides.
495
+ if (!former.some((f) => f.holdsFiles)) {
496
+ if ((await this.defaultOf(orgId, accountId))?.id === live.id)
497
+ return live.id;
498
+ }
492
499
  }
493
500
  return this.insertDefault(orgId, accountId);
494
501
  }
@@ -766,9 +773,10 @@ let DevicesService = class DevicesService {
766
773
  readDeploymentDevicePolicy(this.db.db, this.config),
767
774
  ]);
768
775
  const summaryOf = (r) => r.source === "local" ? localPolicyOf(r.machine_local_policy) : null;
769
- /** The mode the device chose: its machine's report (local) or its switch (cloud, sandbox only). */
776
+ /** The mode the device chose: its machine's report (local) or its switch (cloud: sandbox, or null to follow the org). */
770
777
  const chosenOf = (r) => r.source === "local" ? localModeOf(r.machine_features, r.machine_local_policy) : r.mode;
771
778
  const policyOf = (r) => effectiveDevicePolicy(deployment, settings, chosenOf(r));
779
+ const sandboxNetwork = deviceNetwork(deployment, settings, "sandbox");
772
780
  // each device's limits and its instance's pending change
773
781
  const perDevice = new Map(await Promise.all(rows.map(async (r) => {
774
782
  const policy = policyOf(r);
@@ -827,6 +835,7 @@ let DevicesService = class DevicesService {
827
835
  pendingNextUse: perDevice.get(r.id)?.state.pendingNextUse ?? false,
828
836
  pendingFilesReset: perDevice.get(r.id)?.state.pendingFilesReset ?? false,
829
837
  recent: recent.get(r.id) ?? [],
838
+ sandboxNetwork,
830
839
  }, this.config.get().sandbox.limits.egress === "none"),
831
840
  // a local device's machine decides it; cloud devices have none in phase 2
832
841
  sessionIsolation: r.machine_session_isolation ?? false,
@@ -1030,6 +1039,7 @@ function modeChangeOf(action, at, d, by) {
1030
1039
  export function deviceModeViewOf(policy, settings, local, summary, extra,
1031
1040
  /** The platform kill switch (`sandbox.limits.egress: none`): the network is the platform's. */
1032
1041
  killSwitch = false) {
1042
+ const { sandboxNetwork, ...rest } = extra;
1033
1043
  const networkKind = local ? "allowlist" : policy.network.kind;
1034
1044
  const org = settings.cloudNetwork;
1035
1045
  // "org" only when the org supplied what is in effect: the kill switch always wins; auto mode
@@ -1064,6 +1074,7 @@ killSwitch = false) {
1064
1074
  allowedDomains: [...(summary?.allowedDomains ?? [])],
1065
1075
  }
1066
1076
  : null,
1067
- ...extra,
1077
+ sandboxNetwork: local ? null : { kind: sandboxNetwork.kind, hosts: [...sandboxNetwork.hosts] },
1078
+ ...rest,
1068
1079
  };
1069
1080
  }
@@ -8,14 +8,15 @@ export declare const DeviceParams: z.ZodObject<{
8
8
  id: z.ZodString;
9
9
  }, z.core.$strip>;
10
10
  /**
11
- * `PATCH /devices/:id`: a new name, and a cloud device's narrowing `mode` (`sandbox` only: auto
12
- * mode is never set from the web, auto mode spec §4.3). A local device's mode lives on its machine,
13
- * so the service refuses a `mode` for it (`device.mode_on_device`). The mode is a person's choice
14
- * in a web session: an API token gets `auth.session_required`.
11
+ * `PATCH /devices/:id`: a new name, and a cloud device's `mode`: `sandbox` narrows it, `null`
12
+ * follows the org and the platform again (auto when they allow it; hardening spec D2). `auto` is
13
+ * never stored. A local device's mode lives on its machine, so the service refuses a `mode` for it
14
+ * (`device.mode_on_device`). The mode is a person's choice in a web session: an API token gets
15
+ * `device.mode_requires_session`, and the Platform operation (`devices.rename`) omits it.
15
16
  */
16
17
  export declare const DevicePatchBody: z.ZodObject<{
17
18
  name: z.ZodOptional<z.ZodString>;
18
- mode: z.ZodOptional<z.ZodLiteral<"sandbox">>;
19
+ mode: z.ZodOptional<z.ZodNullable<z.ZodLiteral<"sandbox">>>;
19
20
  }, z.core.$strict>;
20
21
  /**
21
22
  * `POST /devices/:id/policy` (network ask-to-allow spec §7; auto mode spec §4.1): the device
@@ -35,7 +36,7 @@ export declare class DeviceCreateBodyDto extends DeviceCreateBodyDto_base {
35
36
  }
36
37
  declare const DevicePatchBodyDto_base: import("../infra/validation/create-zod-dto.js").ZodDtoClass<z.ZodObject<{
37
38
  name: z.ZodOptional<z.ZodString>;
38
- mode: z.ZodOptional<z.ZodLiteral<"sandbox">>;
39
+ mode: z.ZodOptional<z.ZodNullable<z.ZodLiteral<"sandbox">>>;
39
40
  }, z.core.$strict>>;
40
41
  export declare class DevicePatchBodyDto extends DevicePatchBodyDto_base {
41
42
  }
@@ -7,13 +7,14 @@ export const DeviceName = z.string().trim().min(1).max(64);
7
7
  export const DeviceNameBody = z.object({ name: DeviceName }).strict();
8
8
  export const DeviceParams = z.object({ id: z.string().min(1).max(100) });
9
9
  /**
10
- * `PATCH /devices/:id`: a new name, and a cloud device's narrowing `mode` (`sandbox` only: auto
11
- * mode is never set from the web, auto mode spec §4.3). A local device's mode lives on its machine,
12
- * so the service refuses a `mode` for it (`device.mode_on_device`). The mode is a person's choice
13
- * in a web session: an API token gets `auth.session_required`.
10
+ * `PATCH /devices/:id`: a new name, and a cloud device's `mode`: `sandbox` narrows it, `null`
11
+ * follows the org and the platform again (auto when they allow it; hardening spec D2). `auto` is
12
+ * never stored. A local device's mode lives on its machine, so the service refuses a `mode` for it
13
+ * (`device.mode_on_device`). The mode is a person's choice in a web session: an API token gets
14
+ * `device.mode_requires_session`, and the Platform operation (`devices.rename`) omits it.
14
15
  */
15
16
  export const DevicePatchBody = z
16
- .object({ name: DeviceName.optional(), mode: z.literal("sandbox").optional() })
17
+ .object({ name: DeviceName.optional(), mode: z.literal("sandbox").nullable().optional() })
17
18
  .strict()
18
19
  .refine((b) => b.name !== undefined || b.mode !== undefined, {
19
20
  message: "Give at least one of name or mode",
package/dist/errors.d.ts CHANGED
@@ -334,7 +334,7 @@ export declare const ERROR_CODES: {
334
334
  readonly "attachment.too_many_pending": 429;
335
335
  readonly "sandbox.unavailable": 503;
336
336
  readonly "sandbox.busy": 409;
337
- /** A cloud sandbox provider refused an instance with the open public network (its `openEgress` is `off`). */
337
+ /** A cloud sandbox provider refused an instance with the open public network. */
338
338
  readonly "sandbox.open_network_refused": 409;
339
339
  /** A cloud sandbox provider failed to create a device's sandbox for another reason. */
340
340
  readonly "sandbox.create_failed": 502;
@@ -386,6 +386,11 @@ export declare const ERROR_CODES: {
386
386
  * (`capybara-device mode` or the device page's policy op), and a cloud device has none to choose.
387
387
  */
388
388
  readonly "device.mode_on_device": 409;
389
+ /**
390
+ * A cloud device's mode (`PATCH /devices/:id` `mode`, sandbox or null) sent with an API token:
391
+ * only its owner in a web session changes it (hardening spec D2, K4).
392
+ */
393
+ readonly "device.mode_requires_session": 403;
389
394
  /** Device sign-in (RFC 8628 style): the person has not approved the code yet; keep polling. */
390
395
  readonly "device_sign_in.authorization_pending": 400;
391
396
  /** Device sign-in: the program polls faster than the interval; add 5 seconds and keep polling. */
package/dist/errors.js CHANGED
@@ -334,7 +334,7 @@ export const ERROR_CODES = {
334
334
  "attachment.too_many_pending": 429,
335
335
  "sandbox.unavailable": 503,
336
336
  "sandbox.busy": 409,
337
- /** A cloud sandbox provider refused an instance with the open public network (its `openEgress` is `off`). */
337
+ /** A cloud sandbox provider refused an instance with the open public network. */
338
338
  "sandbox.open_network_refused": 409,
339
339
  /** A cloud sandbox provider failed to create a device's sandbox for another reason. */
340
340
  "sandbox.create_failed": 502,
@@ -386,6 +386,11 @@ export const ERROR_CODES = {
386
386
  * (`capybara-device mode` or the device page's policy op), and a cloud device has none to choose.
387
387
  */
388
388
  "device.mode_on_device": 409,
389
+ /**
390
+ * A cloud device's mode (`PATCH /devices/:id` `mode`, sandbox or null) sent with an API token:
391
+ * only its owner in a web session changes it (hardening spec D2, K4).
392
+ */
393
+ "device.mode_requires_session": 403,
389
394
  /** Device sign-in (RFC 8628 style): the person has not approved the code yet; keep polling. */
390
395
  "device_sign_in.authorization_pending": 400,
391
396
  /** Device sign-in: the program polls faster than the interval; add 5 seconds and keep polling. */
@@ -4,7 +4,7 @@ import { sameModel, selectionAt } from "../conversations/selection.js";
4
4
  import { ApiError } from "../errors.js";
5
5
  import { COMPACTION_SETTINGS } from "../identity/settings.js";
6
6
  import { mediaRefs, planMedia, } from "../runtime/context/build.js";
7
- import { applyFit, clampOutput, planFit } from "../runtime/context/fit.js";
7
+ import { applyFit, estimateAfterFit, planFit, planningBounds, planSqueezedFit, sentOutputCap, } from "../runtime/context/fit.js";
8
8
  import { estimateTokens } from "../runtime/context/tokens.js";
9
9
  import { assembleModelRequest } from "../runtime/model-call.js";
10
10
  import { CHILD_REMOVED_TOOLS } from "../runtime/subagents/definition.js";
@@ -206,22 +206,32 @@ export function reconstructRequest(s, modelCallSeq, opts) {
206
206
  });
207
207
  const { request, meta, mediaTokens } = built;
208
208
  if (!baseline) {
209
- // The hard fit guard against the candidate's window (spec §4.9): clamp the output cap and the
210
- // reserve to that window, apply the fit the candidate would have used, and report
211
- // `context_fit` when the plan differs from the recorded one.
209
+ // The hard fit guard against the candidate's window (spec §4.9), as the runtime runs it: plan
210
+ // against the planning target `W - O_p - R_p` (squeezed to `W - 1 - R_p` when out of reach),
211
+ // apply the fit the candidate would have used, then clamp the output cap from the post-fit
212
+ // estimate keeping the reserve; report `context_fit` when the plan differs from the recorded
213
+ // one. A forced compaction the runtime would run first is not modelled (step replay writes
214
+ // nothing).
212
215
  const reserve = opts.reserveTokens ?? DEFAULT_RESERVE_TOKENS;
213
216
  const estimate = estimateTokens(request.messages, request.system, request.tools, mediaTokens);
214
- request.maxOutputTokens = clampOutput(opts.model.contextWindow, request.maxOutputTokens, estimate);
215
- const recomputed = planFit({
217
+ const output = request.maxOutputTokens;
218
+ const fitInput = {
216
219
  events: inputEvents(all, call),
217
220
  request,
218
221
  model: opts.model,
219
- maxOutputTokens: request.maxOutputTokens,
222
+ maxOutputTokens: output,
220
223
  reserveTokens: reserve,
221
224
  estimate,
222
- });
225
+ };
226
+ const { target } = planningBounds(opts.model.contextWindow, output, reserve);
227
+ let recomputed = planFit(fitInput);
228
+ if (recomputed !== null && estimateAfterFit(request, estimate, recomputed) > target) {
229
+ recomputed = planSqueezedFit(fitInput).plan;
230
+ }
223
231
  if (!samePlan(recomputed, rec.fit))
224
232
  drift.add("context_fit");
233
+ const after = recomputed === null ? estimate : estimateAfterFit(request, estimate, recomputed);
234
+ request.maxOutputTokens = sentOutputCap(opts.model.contextWindow, output, after, reserve);
225
235
  if (recomputed !== null) {
226
236
  request.messages = applyFit(request, recomputed).messages;
227
237
  }
@@ -132,7 +132,7 @@ export interface BootstrapResolveOptions {
132
132
  * Omitted or missing: no offline packages.
133
133
  */
134
134
  dir?: string;
135
- config: Pick<KernelConfig, "packages">;
135
+ config: Pick<KernelConfig, "packages" | "marketplaces" | "net">;
136
136
  signal?: AbortSignal;
137
137
  log?: Pick<Logger, "warn">;
138
138
  /** The npm download (default {@link fetchNpmPackage}; tests replace it). */