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

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 (85) 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/marketplaces.service.d.ts +1 -1
  5. package/dist/catalog/requests.service.d.ts +6 -5
  6. package/dist/catalog/requests.service.js +7 -6
  7. package/dist/config/load.d.ts +6 -0
  8. package/dist/config/load.js +26 -0
  9. package/dist/config/schema.js +5 -5
  10. package/dist/conversations/events.d.ts +10 -0
  11. package/dist/conversations/events.js +23 -1
  12. package/dist/ctx/create-ctx.d.ts +26 -4
  13. package/dist/ctx/create-ctx.js +54 -34
  14. package/dist/devices/devices.controller.js +3 -2
  15. package/dist/devices/devices.service.d.ts +17 -5
  16. package/dist/devices/devices.service.js +24 -13
  17. package/dist/devices/dto.d.ts +7 -6
  18. package/dist/devices/dto.js +6 -5
  19. package/dist/errors.d.ts +6 -1
  20. package/dist/errors.js +6 -1
  21. package/dist/evals/reconstruct.js +18 -8
  22. package/dist/extensions/bootstrap.d.ts +1 -1
  23. package/dist/extensions/bootstrap.js +7 -1
  24. package/dist/extensions/installs.js +4 -1
  25. package/dist/extensions/permission-set.d.ts +7 -6
  26. package/dist/extensions/permission-set.js +9 -6
  27. package/dist/extensions/permission-view.d.ts +4 -4
  28. package/dist/extensions/permission-view.js +10 -5
  29. package/dist/http/app.d.ts +8 -2
  30. package/dist/http/app.js +12 -2
  31. package/dist/http/plugin-dispatch.d.ts +55 -18
  32. package/dist/http/plugin-dispatch.js +124 -29
  33. package/dist/http/plugin-route-access.d.ts +56 -0
  34. package/dist/http/plugin-route-access.js +192 -0
  35. package/dist/identity/auth.guard.d.ts +26 -12
  36. package/dist/identity/auth.guard.js +62 -33
  37. package/dist/infra/throttler/named-throttlers.d.ts +3 -0
  38. package/dist/infra/throttler/named-throttlers.js +16 -0
  39. package/dist/infra/throttler/throttler.guard.d.ts +2 -1
  40. package/dist/infra/throttler/throttler.guard.js +2 -1
  41. package/dist/kernel.module.js +3 -0
  42. package/dist/lifecycle/kernel-lifecycle.js +1 -3
  43. package/dist/net/public-address.d.ts +14 -4
  44. package/dist/net/public-address.js +22 -12
  45. package/dist/net/safe-fetch.d.ts +2 -1
  46. package/dist/net/safe-fetch.js +16 -4
  47. package/dist/overrides.d.ts +3 -0
  48. package/dist/overrides.js +2 -0
  49. package/dist/packages/npm.d.ts +28 -9
  50. package/dist/packages/npm.js +30 -19
  51. package/dist/packages/provenance.d.ts +3 -1
  52. package/dist/packages/provenance.js +7 -3
  53. package/dist/platform/ops/devices.ops.js +1 -1
  54. package/dist/platform/ops/platform.ops.d.ts +3 -1
  55. package/dist/platform/ops/platform.ops.js +11 -13
  56. package/dist/runtime/context/build.d.ts +10 -1
  57. package/dist/runtime/context/build.js +44 -10
  58. package/dist/runtime/context/compaction.d.ts +27 -8
  59. package/dist/runtime/context/compaction.js +133 -58
  60. package/dist/runtime/context/fit.d.ts +54 -22
  61. package/dist/runtime/context/fit.js +116 -40
  62. package/dist/runtime/model-call.d.ts +0 -8
  63. package/dist/runtime/model-call.js +185 -83
  64. package/dist/sandbox/review/classifier.d.ts +2 -0
  65. package/dist/sandbox/review/classifier.js +12 -1
  66. package/dist/sandbox/review/index.d.ts +3 -3
  67. package/dist/sandbox/review/index.js +3 -3
  68. package/dist/sandbox/review/review.service.d.ts +12 -4
  69. package/dist/sandbox/review/review.service.js +88 -19
  70. package/dist/sandbox/review/rules.d.ts +6 -0
  71. package/dist/sandbox/review/rules.js +1013 -95
  72. package/dist/sandbox/review/types.d.ts +21 -4
  73. package/dist/sandbox/review/types.js +41 -5
  74. package/dist/sandbox/sandbox.service.d.ts +8 -7
  75. package/dist/sandbox/sandbox.service.js +16 -16
  76. package/dist/setup/kernel-checks.js +3 -2
  77. package/dist/setup/oauth-token-probe.d.ts +1 -8
  78. package/dist/setup/oauth-token-probe.js +0 -16
  79. package/dist/tools/builtins/sandbox/common.d.ts +1 -1
  80. package/dist/tools/builtins/sandbox/common.js +1 -1
  81. package/dist/tools/builtins/tool-search.js +4 -3
  82. package/dist/tools/oauth/discovery.d.ts +38 -16
  83. package/dist/tools/oauth/discovery.js +59 -33
  84. package/dist/tools/pipeline.js +17 -13
  85. package/package.json +3 -3
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,
@@ -188,7 +188,7 @@ export declare function headsToResolve(entries: readonly MarketplaceEntry[], imp
188
188
  /** The host versions (an entry's `minKernel` is judged against them). */
189
189
  export declare const HOST_VERSIONS: {
190
190
  readonly kernel: string;
191
- readonly sdk: "0.1.0-rc.22";
191
+ readonly sdk: "0.1.0-rc.23";
192
192
  };
193
193
  /** Whether this deployment satisfies the entry's `minKernel`. */
194
194
  export declare const entryCompatible: (e: Pick<MarketplaceEntry, "minKernel">) => boolean;
@@ -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"]),
@@ -1,10 +1,11 @@
1
- import { type ExtensionContext, type ExtensionManifest, type ExtensionPointRef, type Logger, resolveUiSlots, type SetupCheckArgs, type SetupGuidePlace, type ToolHandler, type ToolSpec } from "@capybara-hq/plugin-sdk";
1
+ import { type EmbedClaims, type ExtensionContext, type ExtensionManifest, type ExtensionPointRef, type HttpAccess, type Logger, type RouteCaller, resolveUiSlots, type SetupCheckArgs, type SetupGuidePlace, type ToolHandler, type ToolSpec } from "@capybara-hq/plugin-sdk";
2
2
  import type { Redis } from "ioredis";
3
3
  import { Kysely } from "kysely";
4
4
  import { type RegisteredHook } from "../extensions/hooks.js";
5
5
  import { RegistrationLedger } from "../extensions/ledger.js";
6
6
  import type { LockService } from "../infra/lock/lock.service.js";
7
7
  import type { ModelEmbeddings } from "../models/embeddings.js";
8
+ import type { OrgRole } from "../orgs/roles.js";
8
9
  import type { HookRunner } from "../runtime/hook-calls.js";
9
10
  import type { EmbedTokens } from "../ui/embed-token.js";
10
11
  import { type UiActionHandler, type UiRender } from "../ui/registry.js";
@@ -41,11 +42,24 @@ export interface KernelDeps {
41
42
  debug?(msg: string, fields?: Record<string, unknown>): void;
42
43
  };
43
44
  }
44
- /** 插件 HTTP 路由;`path` 已含 `/plugins/<name>` 前缀。 */
45
+ /**
46
+ * What `ctx.ui.verifyEmbedToken` returns for a valid token: the signed claims, with an org
47
+ * token's `role` replaced by the caller's role at verification time.
48
+ */
49
+ export type VerifiedEmbedClaims = EmbedClaims;
50
+ /**
51
+ * An extension HTTP route as registered through `ctx.http.route`. `path` is the full mounted path:
52
+ * `/plugins/<name>/orgs/:orgId<path>` for `member` / `admin`, `/plugins/<name><path>` for `public`
53
+ * / `embed`. `verifyEmbed` is the extension's own `ctx.ui.verifyEmbedToken` (the dispatch checks
54
+ * an `embed` route's token with it).
55
+ */
45
56
  export type Route = {
57
+ plugin: string;
46
58
  method: "GET" | "POST" | "PUT" | "DELETE";
47
59
  path: string;
48
- handler: (req: Request) => Promise<Response>;
60
+ access: HttpAccess;
61
+ handler: (req: Request, caller: RouteCaller) => Promise<Response>;
62
+ verifyEmbed: (token: string) => Promise<VerifiedEmbedClaims | null>;
49
63
  };
50
64
  /** 插件经 `ctx.tools.register` 注册的工具。 */
51
65
  export type RegisteredTool = {
@@ -81,6 +95,13 @@ export interface ExtensionPointAccess {
81
95
  * required bootstrap plugins, see `extensions/enabled.ts`), not cached.
82
96
  */
83
97
  export declare function queryEnabledPlugins(db: Kysely<any>, orgId: string): Promise<Set<string>>;
98
+ /**
99
+ * One query for a person's live org role on behalf of an extension: the extension enabled in the
100
+ * org, the org not deleted, the account active and still a member; returns the role now, or
101
+ * undefined when any of that fails. An embed token's verification and the `member` / `admin`
102
+ * route check (plugin-route-access.ts) both use it.
103
+ */
104
+ export declare function currentOrgRole(db: KernelDeps["db"], plugin: string, orgId: string, accountId: string): Promise<OrgRole | undefined>;
84
105
  /**
85
106
  * Whether the account is, right now, an active super admin (one query): what a platform embed
86
107
  * token and the platform refresh stream re-check.
@@ -139,7 +160,8 @@ export declare class LiveConfig {
139
160
  * - Granted automatically: `kv`, `lock`, `bus`, `queue`, `log`, `db`, `config`, `provide`;
140
161
  * - `secrets` only with `permissions.secrets`, `storage` only with `permissions.storage`, `models`
141
162
  * only with `permissions.models` (and only its `embedding` purposes, through `deps.models`); `http.route`
142
- * only the method + path declared in `permissions.http`; `tools.register` only names declared in
163
+ * only the method + path declared in `permissions.http` (the record carries the declared access and
164
+ * its mount, see {@link Route}); `tools.register` only names declared in
143
165
  * `permissions.tools`; `ui.view` / `ui.action` only ids declared in `permissions.ui.views` or
144
166
  * `permissions.ui.components` (a component's server view; during setup only); `setup.check` only
145
167
  * ids declared in `permissions.setupChecks` (during setup only, `place` and `run` read once and
@@ -23,9 +23,12 @@ export async function queryEnabledPlugins(db, orgId) {
23
23
  return new Set(rows.map((r) => r.plugin));
24
24
  }
25
25
  /**
26
- * 嵌入令牌校验时的一条查询:插件在该组织启用、组织未删除、账号 active、仍是成员;返回此刻的角色,不满足返回 undefined。
26
+ * One query for a person's live org role on behalf of an extension: the extension enabled in the
27
+ * org, the org not deleted, the account active and still a member; returns the role now, or
28
+ * undefined when any of that fails. An embed token's verification and the `member` / `admin`
29
+ * route check (plugin-route-access.ts) both use it.
27
30
  */
28
- async function currentEmbedRole(db, plugin, orgId, accountId) {
31
+ export async function currentOrgRole(db, plugin, orgId, accountId) {
29
32
  const row = await kernelDb(db)
30
33
  .selectFrom("memberships")
31
34
  .innerJoin("orgs", "orgs.id", "memberships.org_id")
@@ -180,7 +183,8 @@ export class LiveConfig {
180
183
  * - Granted automatically: `kv`, `lock`, `bus`, `queue`, `log`, `db`, `config`, `provide`;
181
184
  * - `secrets` only with `permissions.secrets`, `storage` only with `permissions.storage`, `models`
182
185
  * only with `permissions.models` (and only its `embedding` purposes, through `deps.models`); `http.route`
183
- * only the method + path declared in `permissions.http`; `tools.register` only names declared in
186
+ * only the method + path declared in `permissions.http` (the record carries the declared access and
187
+ * its mount, see {@link Route}); `tools.register` only names declared in
184
188
  * `permissions.tools`; `ui.view` / `ui.action` only ids declared in `permissions.ui.views` or
185
189
  * `permissions.ui.components` (a component's server view; during setup only); `setup.check` only
186
190
  * ids declared in `permissions.setupChecks` (during setup only, `place` and `run` read once and
@@ -253,7 +257,8 @@ export function createExtensionContext(deps, manifest, deploymentConfig, extensi
253
257
  },
254
258
  }
255
259
  : undefined;
256
- const declaredRoutes = new Set((perms.http ?? []).map((r) => `${r.method} ${r.path}`));
260
+ // "METHOD path" -> the access the manifest declares for it (the approved manifest)
261
+ const declaredRoutes = new Map((perms.http ?? []).map((r) => [`${r.method} ${r.path}`, r.access]));
257
262
  const declaredTools = new Set(perms.tools ?? []);
258
263
  const declaredHooks = new Set(perms.hooks ?? []);
259
264
  const declaredPolicyHooks = new Set(perms.policyHooks ?? []);
@@ -268,6 +273,36 @@ export function createExtensionContext(deps, manifest, deploymentConfig, extensi
268
273
  const embedTokens = deps.embedTokens;
269
274
  const uiResolution = resolveUiSlots(manifest.ui);
270
275
  const uiSlots = new Map(uiResolution.resolved.map((r) => [r.contribution.id, r.slot]));
276
+ // `ctx.ui.verifyEmbedToken`, also every route record's `verifyEmbed`. Accepts only a token signed
277
+ // for this extension, unexpired and untampered (see ui/embed-token.ts); then one query checks the
278
+ // present: the extension still enabled in that org, the org not deleted, the account active and
279
+ // still a member (PG every time, never cached: tokens already issued stop working at once when the
280
+ // extension is switched off, the member leaves or the account is disabled). The returned role is
281
+ // the current one; a token whose current role is below the minRole of its contribution's slot is
282
+ // refused (A38, UI slots spec §7). A platform token: the contribution is a `platform.page` and the
283
+ // account is still an active super admin. A token of one scope never verifies for the other's
284
+ // slots. Anything else is null.
285
+ const verifyEmbedToken = async (token) => {
286
+ const claims = embedTokens.verify(token, name);
287
+ if (claims === null)
288
+ return null;
289
+ const slot = uiSlots.get(claims.contribution);
290
+ if (claims.scope === "platform") {
291
+ if (slot?.id !== "platform.page")
292
+ return null;
293
+ return (await currentPlatformAccount(deps.db, claims.accountId)) ? claims : null;
294
+ }
295
+ if (claims.scope !== "org" || claims.orgId === undefined)
296
+ return null;
297
+ // the contribution's slot as loaded now: never `platform.page` through an org token, and the
298
+ // current role still meets the slot's minRole (a demoted caller's token stops working)
299
+ if (slot === undefined || slot.id === "platform.page")
300
+ return null;
301
+ const role = await currentOrgRole(deps.db, name, claims.orgId, claims.accountId);
302
+ if (role === undefined || !canUseSlot(slot, role))
303
+ return null;
304
+ return { ...claims, role };
305
+ };
271
306
  /** Ids of the extension's `platform.page` contributions (their invalidate takes no orgId). */
272
307
  const platformUi = new Set([...uiSlots].filter(([, s]) => s.id === "platform.page").map(([id]) => id));
273
308
  /** 校验能力可取用(非 brokered、已在清单声明),返回其登记信息。 */
@@ -400,13 +435,23 @@ export function createExtensionContext(deps, manifest, deploymentConfig, extensi
400
435
  if (typeof path !== "string" || !path.startsWith("/")) {
401
436
  throw new Error(`plugin ${name}: route path "${path}" must start with "/"`);
402
437
  }
403
- if (!declaredRoutes.has(`${method} ${path}`))
404
- deny(`permissions.http ${method} ${path}`);
405
- const full = `/plugins/${name}${path}`;
438
+ const access = declaredRoutes.get(`${method} ${path}`);
439
+ if (access === undefined)
440
+ return deny(`permissions.http ${method} ${path}`);
441
+ const full = access === "member" || access === "admin"
442
+ ? `/plugins/${name}/orgs/:orgId${path}`
443
+ : `/plugins/${name}${path}`;
406
444
  if (routes.some((r) => r.method === method && r.path === full)) {
407
445
  throw new Error(`plugin ${name}: duplicate route ${method} ${path}`);
408
446
  }
409
- const route = { method, path: full, handler };
447
+ const route = {
448
+ plugin: name,
449
+ method,
450
+ path: full,
451
+ access,
452
+ handler,
453
+ verifyEmbed: verifyEmbedToken,
454
+ };
410
455
  routes.push(route);
411
456
  ledger.add({
412
457
  kind: "route",
@@ -568,32 +613,7 @@ export function createExtensionContext(deps, manifest, deploymentConfig, extensi
568
613
  ? conversationTopic(t.conversationId)
569
614
  : orgUiTopic(t.orgId), msg);
570
615
  },
571
- // 只认签给本插件、未过期、未篡改的令牌(见 ui/embed-token.ts);再用一条查询核对此刻:本插件仍在该组织
572
- // 启用、组织未删除、账号 active 且仍是成员(每次查 PG、不缓存:停用插件、离职、停用账号后已签出的令牌立即失效)。
573
- // 返回的 role 是此刻的角色;令牌在此刻的角色低于贡献所在位置的 minRole 时失效(A38, UI slots spec §7)。
574
- // A platform token: the contribution is a `platform.page` and the account is still an active
575
- // super admin. A token of one scope never verifies for the other's slots. 其余一律 null
576
- async verifyEmbedToken(token) {
577
- const claims = embedTokens.verify(token, name);
578
- if (claims === null)
579
- return null;
580
- const slot = uiSlots.get(claims.contribution);
581
- if (claims.scope === "platform") {
582
- if (slot?.id !== "platform.page")
583
- return null;
584
- return (await currentPlatformAccount(deps.db, claims.accountId)) ? claims : null;
585
- }
586
- if (claims.scope !== "org" || claims.orgId === undefined)
587
- return null;
588
- // the contribution's slot as loaded now: never `platform.page` through an org token, and the
589
- // current role still meets the slot's minRole (a demoted caller's token stops working)
590
- if (slot === undefined || slot.id === "platform.page")
591
- return null;
592
- const role = await currentEmbedRole(deps.db, name, claims.orgId, claims.accountId);
593
- if (role === undefined || !canUseSlot(slot, role))
594
- return null;
595
- return { ...claims, role };
596
- },
616
+ verifyEmbedToken,
597
617
  },
598
618
  provide(extensionPoint, impl) {
599
619
  if (!manifest.provides.includes(extensionPoint)) {
@@ -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;