@capybara-hq/kernel 0.1.0-rc.85 → 0.1.0-rc.87

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 (71) hide show
  1. package/bootstrap.json +5 -5
  2. package/dist/catalog/marketplaces.service.d.ts +1 -1
  3. package/dist/channels/cards.d.ts +7 -3
  4. package/dist/channels/cards.js +9 -4
  5. package/dist/channels/phrases.d.ts +10 -0
  6. package/dist/channels/phrases.js +10 -0
  7. package/dist/config/docs.js +1 -1
  8. package/dist/config/schema.d.ts +3 -0
  9. package/dist/config/schema.js +18 -12
  10. package/dist/ctx/create-ctx.d.ts +10 -1
  11. package/dist/ctx/create-ctx.js +42 -2
  12. package/dist/device-access/device-access.module.d.ts +7 -0
  13. package/dist/device-access/device-access.module.js +41 -0
  14. package/dist/device-access/device-access.service.d.ts +142 -0
  15. package/dist/device-access/device-access.service.js +464 -0
  16. package/dist/device-access/token.d.ts +6 -0
  17. package/dist/device-access/token.js +6 -0
  18. package/dist/device-access/viewer-routes.d.ts +45 -0
  19. package/dist/device-access/viewer-routes.js +81 -0
  20. package/dist/device-access/viewer.d.ts +244 -0
  21. package/dist/device-access/viewer.js +844 -0
  22. package/dist/dial-in/access.d.ts +19 -0
  23. package/dist/dial-in/access.js +23 -0
  24. package/dist/dial-in/gateway.d.ts +48 -6
  25. package/dist/dial-in/gateway.js +145 -10
  26. package/dist/dial-in/keys.d.ts +7 -0
  27. package/dist/dial-in/keys.js +7 -0
  28. package/dist/dial-in/routes.d.ts +11 -3
  29. package/dist/dial-in/routes.js +15 -4
  30. package/dist/dial-in/streams.d.ts +58 -0
  31. package/dist/dial-in/streams.js +283 -0
  32. package/dist/errors.d.ts +2 -0
  33. package/dist/errors.js +2 -0
  34. package/dist/extensions/host.d.ts +13 -1
  35. package/dist/extensions/host.js +20 -1
  36. package/dist/extensions/permission-set.d.ts +15 -1
  37. package/dist/extensions/permission-set.js +13 -1
  38. package/dist/extensions/permission-view.d.ts +6 -4
  39. package/dist/extensions/permission-view.js +6 -1
  40. package/dist/http/error.filter.js +2 -0
  41. package/dist/http/gateway-routes.d.ts +8 -4
  42. package/dist/http/gateway-routes.js +4 -3
  43. package/dist/infra/lock/lock.service.d.ts +5 -1
  44. package/dist/infra/lock/lock.service.js +10 -4
  45. package/dist/infra/throttler/named-throttlers.d.ts +3 -0
  46. package/dist/infra/throttler/named-throttlers.js +16 -0
  47. package/dist/kernel.module.js +3 -0
  48. package/dist/roles/gateway-role.d.ts +13 -6
  49. package/dist/roles/gateway-role.js +27 -9
  50. package/dist/roles/gateway.module.d.ts +2 -1
  51. package/dist/roles/gateway.module.js +13 -3
  52. package/dist/sandbox/device-services.d.ts +62 -0
  53. package/dist/sandbox/device-services.js +183 -0
  54. package/dist/sandbox/leases.d.ts +18 -1
  55. package/dist/sandbox/leases.js +75 -1
  56. package/dist/sandbox/network-grants.js +5 -2
  57. package/dist/sandbox/sandbox.module.d.ts +2 -1
  58. package/dist/sandbox/sandbox.module.js +5 -2
  59. package/dist/sandbox/sandbox.service.d.ts +44 -1
  60. package/dist/sandbox/sandbox.service.js +142 -5
  61. package/dist/tools/approvals.service.d.ts +45 -20
  62. package/dist/tools/approvals.service.js +19 -9
  63. package/dist/tools/call-scope.d.ts +60 -0
  64. package/dist/tools/call-scope.js +23 -0
  65. package/dist/tools/network-asks.d.ts +13 -0
  66. package/dist/tools/network-asks.js +26 -2
  67. package/dist/tools/pipeline.d.ts +30 -1
  68. package/dist/tools/pipeline.js +285 -54
  69. package/dist/tools/questions.service.d.ts +24 -3
  70. package/dist/tools/questions.service.js +3 -1
  71. 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": "727f62bd821702a1b9d6ce0fb672d998dbb9d6d5"
6
+ "commit": "5aaf63862524b2796bf55cd3ab550932e1fbcfbf"
7
7
  },
8
8
  "plugins": [
9
9
  {
@@ -90,16 +90,16 @@
90
90
  "name": "device-docker",
91
91
  "source": "npm",
92
92
  "npm": "@capybara-hq/plugin-device-docker",
93
- "version": "0.1.0-rc.28",
94
- "integrity": "sha512-AMmRgf+D8Aap5RKdrhNvPH+1ItvTtQohOCzr6B0xaSzOYD78BbYZxKniOZzEqphGxOymoZe+LCqfTSnKGdKRWg==",
93
+ "version": "0.1.0-rc.29",
94
+ "integrity": "sha512-TGdSjzofH1KNP8t0fgzFqd7Jf19nrDSJ+l+G+0oLc36PI3GGk2pzp97m9K1XfAlaIWrABghZytjE3myCXpvdBw==",
95
95
  "required": false
96
96
  },
97
97
  {
98
98
  "name": "device-local",
99
99
  "source": "npm",
100
100
  "npm": "@capybara-hq/plugin-device-local",
101
- "version": "0.1.0-rc.8",
102
- "integrity": "sha512-TA84YgBO3gpzZUumpR3ZdwFVa1Vytre9oaDWslFN9J3tE4ch3F1HdDKCstNgxhgogwHRLAyy6nwOIiGn7XXurw==",
101
+ "version": "0.1.0-rc.9",
102
+ "integrity": "sha512-sOjOsA5bSZsbsNLzxRIsFhgZig0YNnfBIPIgQ4YbVXYT5lAEt3OTzLsOJr2SxsnxkvmGV95nHFJOTMEGRn2K4Q==",
103
103
  "required": false,
104
104
  "scope": "all"
105
105
  },
@@ -208,7 +208,7 @@ export declare function headsToResolve(entries: readonly MarketplaceEntry[], imp
208
208
  /** The host versions (an entry's `minKernel` is judged against them). */
209
209
  export declare const HOST_VERSIONS: {
210
210
  readonly kernel: string;
211
- readonly sdk: "0.1.0-rc.69";
211
+ readonly sdk: "0.1.0-rc.70";
212
212
  };
213
213
  /** Whether this deployment satisfies the entry's `minKernel`. */
214
214
  export declare const entryCompatible: (e: Pick<MarketplaceEntry, "minKernel">) => boolean;
@@ -2,7 +2,7 @@ import { type ChannelCard, type FormAnswer, type InputForm, type OutboundMessage
2
2
  import type { KernelSchemaDb } from "../db/kernel-schema.js";
3
3
  import type { FileCardDetail } from "../platform/file-ref.js";
4
4
  import type { PermissionEscalation } from "../sandbox/permission-call-types.js";
5
- import type { ApprovalsService, ApprovalView, CommandAskDetail, GitAskView, NetworkAskView } from "../tools/approvals.service.js";
5
+ import { type ApprovalsService, type ApprovalView, type CommandAskDetail, type CommandNetworkAskDetail, type GitAskView, type ServiceNetworkAskDetail } from "../tools/approvals.service.js";
6
6
  import { type ToolInfo } from "../tools/info.js";
7
7
  import type { ToolRegistry } from "../tools/registry.js";
8
8
  import { type ChannelLocale } from "./phrases.js";
@@ -65,15 +65,18 @@ export interface NetworkCardText {
65
65
  inputPreview: string;
66
66
  scopeLabels: Partial<Record<"once" | "session" | "always", string>>;
67
67
  }
68
+ /** What a network ask's card reads: a command's or a device service's view, its `appliesAt` optional. */
69
+ type NetworkCardDetail = (Pick<CommandNetworkAskDetail, "kind" | "hosts" | "command"> & Partial<Pick<CommandNetworkAskDetail, "appliesAt">>) | (Pick<ServiceNetworkAskDetail, "kind" | "hosts" | "url"> & Partial<Pick<ServiceNetworkAskDetail, "appliesAt">>);
68
70
  /**
69
- * A network ask's card text: the title names the host (or the number of hosts); the preview lists
71
+ * A network ask's card text (a device service's: browser use spec §7.1, its own title and a note
72
+ * that open network mode stops the asks): the title names the host (or the number of hosts); the preview lists
70
73
  * the hosts, then the command clipped to {@link CARD_SUMMARY_MAX}, for several hosts that the
71
74
  * decision applies to all of them (an IM card has no per-host choice) and, when `scopes` offers
72
75
  * "add to this device's list", when that applies (device-provider spec §6.3). Model-controlled
73
76
  * values are redacted by `redact` (the connection's secret values); the description stays on the
74
77
  * web.
75
78
  */
76
- export declare function networkCardText(detail: Pick<NetworkAskView, "hosts" | "command"> & Partial<Pick<NetworkAskView, "appliesAt">>, locale: ChannelLocale, redact?: (s: string) => string, scopes?: readonly string[]): NetworkCardText;
79
+ export declare function networkCardText(detail: NetworkCardDetail, locale: ChannelLocale, redact?: (s: string) => string, scopes?: readonly string[]): NetworkCardText;
77
80
  /**
78
81
  * A git push ask's card text (sandbox git credentials spec §7): the title names the repository;
79
82
  * the preview is `<host>/<repo>`, the refs (`refs/heads/` dropped) and the command clipped to
@@ -123,3 +126,4 @@ textReply?: "plain" | "mention"): Extract<ChannelCard, {
123
126
  }>;
124
127
  /** 一条只带一张卡片的消息(随附文本为固定话术)。 */
125
128
  export declare const cardMessage: (text: string, card: ChannelCard) => OutboundMessage;
129
+ export {};
@@ -1,5 +1,6 @@
1
1
  import { parseToolKey, } from "@capybara-hq/plugin-sdk";
2
2
  import { escalationAskReason, quotedJustification, } from "../sandbox/review/permission-candidate.js";
3
+ import { networkAskHosts, } from "../tools/approvals.service.js";
3
4
  import { toolInfo } from "../tools/info.js";
4
5
  import { phrase } from "./phrases.js";
5
6
  /** The longest call line of an approval card (characters, the ellipsis included). */
@@ -196,7 +197,8 @@ async function displayName(db, accountId) {
196
197
  return r?.display_name || undefined;
197
198
  }
198
199
  /**
199
- * A network ask's card text: the title names the host (or the number of hosts); the preview lists
200
+ * A network ask's card text (a device service's: browser use spec §7.1, its own title and a note
201
+ * that open network mode stops the asks): the title names the host (or the number of hosts); the preview lists
200
202
  * the hosts, then the command clipped to {@link CARD_SUMMARY_MAX}, for several hosts that the
201
203
  * decision applies to all of them (an IM card has no per-host choice) and, when `scopes` offers
202
204
  * "add to this device's list", when that applies (device-provider spec §6.3). Model-controlled
@@ -204,11 +206,13 @@ async function displayName(db, accountId) {
204
206
  * web.
205
207
  */
206
208
  export function networkCardText(detail, locale, redact = (s) => s, scopes = []) {
207
- const hosts = [...new Set(detail.hosts.map((h) => redact(h.host)))];
209
+ const service = detail.kind === "service";
210
+ const hosts = [...new Set(networkAskHosts(detail).map(redact))];
208
211
  const title = hosts.length === 1
209
- ? phrase("networkTitleOne", locale).replace("{host}", hosts[0])
212
+ ? phrase(service ? "networkServiceTitle" : "networkTitleOne", locale).replace("{host}", hosts[0])
210
213
  : phrase("networkTitleMany", locale).replace("{n}", String(hosts.length));
211
- const command = cut(redact(detail.command.trim()), CARD_SUMMARY_MAX);
214
+ // a service ask shows the page it was loading (when known) where a command ask shows the command
215
+ const command = cut(redact((detail.kind === "service" ? (detail.url ?? "") : detail.command).trim()), CARD_SUMMARY_MAX);
212
216
  const applies = scopes.includes("always") && detail.appliesAt !== undefined
213
217
  ? phrase("networkAppliesLine", locale)
214
218
  .replace("{label}", phrase("networkAddToDevice", locale))
@@ -221,6 +225,7 @@ export function networkCardText(detail, locale, redact = (s) => s, scopes = [])
221
225
  ...(command !== "" ? ["", command] : []),
222
226
  ...(hosts.length > 1 ? ["", phrase("networkAllHosts", locale)] : []),
223
227
  ...(applies !== null ? ["", applies] : []),
228
+ ...(service ? ["", phrase("networkServiceNote", locale)] : []),
224
229
  ].join("\n"),
225
230
  // what the device's provider enforces: a run grant, the device's own list, or both
226
231
  scopeLabels: {
@@ -102,6 +102,16 @@ export declare const CHANNEL_PHRASES: {
102
102
  readonly zh: "智能体想访问 {n} 个域名,允许吗?";
103
103
  readonly en: "The agent wants to reach {n} domains. Allow?";
104
104
  };
105
+ /** A device service's network ask, one host (`{host}`; browser use spec §7.1). */
106
+ readonly networkServiceTitle: {
107
+ readonly zh: "智能体的浏览器想访问 {host}";
108
+ readonly en: "The agent's browser wants to reach {host}";
109
+ };
110
+ /** Under a device service's network ask: open network mode stops the asks. */
111
+ readonly networkServiceNote: {
112
+ readonly zh: "开放网络模式下不会再询问";
113
+ readonly en: "Open network mode stops these asks";
114
+ };
105
115
  /** Under a network ask's host list: an IM card has no per-host choice (spec §6.4). */
106
116
  readonly networkAllHosts: {
107
117
  readonly zh: "这个决定对以上所有域名生效";
@@ -88,6 +88,16 @@ export const CHANNEL_PHRASES = {
88
88
  zh: "智能体想访问 {n} 个域名,允许吗?",
89
89
  en: "The agent wants to reach {n} domains. Allow?",
90
90
  },
91
+ /** A device service's network ask, one host (`{host}`; browser use spec §7.1). */
92
+ networkServiceTitle: {
93
+ zh: "智能体的浏览器想访问 {host}",
94
+ en: "The agent's browser wants to reach {host}",
95
+ },
96
+ /** Under a device service's network ask: open network mode stops the asks. */
97
+ networkServiceNote: {
98
+ zh: "开放网络模式下不会再询问",
99
+ en: "Open network mode stops these asks",
100
+ },
91
101
  /** Under a network ask's host list: an IM card has no per-host choice (spec §6.4). */
92
102
  networkAllHosts: {
93
103
  zh: "这个决定对以上所有域名生效",
@@ -82,7 +82,7 @@ export function renderConfigDocs(schema) {
82
82
  "| `CAPYBARA_WEB_OBJECT_STORE_URL` | Object storage on the web origin: the object store's address as web reaches it (e.g. `http://seaweedfs-s3:8333`). When set, web proxies `/<bucket>/**` (and `/<bucket>` itself for POST only) there, so browsers upload attachments (presigned POST) and download attachments and artifacts (presigned GET) through web; set the object-store extension's `publicEndpoint` to the web origin with `forcePathStyle: true`. Only GET, HEAD and POST; the path is forwarded unchanged; cookies and authorization are not forwarded; responses carry `X-Content-Type-Options: nosniff` and `Content-Security-Policy: sandbox`; uploads are capped at `CAPYBARA_WEB_MAX_PACKAGE_BYTES`. Unset (default): off |",
83
83
  "| `CAPYBARA_WEB_OBJECT_STORE_BUCKET` | With `CAPYBARA_WEB_OBJECT_STORE_URL`: the bucket, equal to the object-store extension's `bucket` (it is the first path segment web proxies) |",
84
84
  "| `CAPYBARA_WEB_OBJECT_STORE_PUBLIC_HOST` | With `CAPYBARA_WEB_OBJECT_STORE_URL`: the host of the extension's `publicEndpoint` (a host such as `capybara.example.com`, or that URL). Sent upstream as `Host` instead of the incoming one, because presigned URLs sign the host they were issued for and front proxies rewrite it |",
85
- "| `CAPYBARA_WEB_GATEWAY_URL` | Local devices on the web origin: a `gateway` replica's address as web reaches it (an http(s) URL, e.g. `http://gateway:8080`). WebSocket upgrades on exactly `/device/connect` are forwarded to it (`capybara-device` connects at `<http.publicUrl>/device/connect`). Unset, they go to `CAPYBARA_KERNEL_URL` (the kernel runs every role unless the deployment splits them), so only deployments with separate gateway replicas set it (compose does). A malformed value stops the web tier at startup |",
85
+ "| `CAPYBARA_WEB_GATEWAY_URL` | Local devices on the web origin: a `gateway` replica's address as web reaches it (an http(s) URL, e.g. `http://gateway:8080`). WebSocket upgrades on exactly `/device/connect` and `/device/stream` are forwarded to it (`capybara-device` connects at `<http.publicUrl>/device/connect`; the browser live view opens `/device/stream?ticket=…`, query intact). Unset, they go to `CAPYBARA_KERNEL_URL` (the kernel runs every role unless the deployment splits them), so only deployments with separate gateway replicas set it (compose does). A malformed value stops the web tier at startup |",
86
86
  "| `CAPYBARA_DEV_UI` | When set to `1`, production builds also serve the `/dev/ui` component catalog page (off by default) |",
87
87
  "",
88
88
  ].join("\n");
@@ -192,6 +192,9 @@ export declare const KernelConfigSchema: z.ZodObject<{
192
192
  fileMaxBytes: z.ZodDefault<z.ZodNumber>;
193
193
  fileConcurrency: z.ZodDefault<z.ZodNumber>;
194
194
  }, z.core.$strict>>;
195
+ gateway: z.ZodPrefault<z.ZodObject<{
196
+ internalUrl: z.ZodOptional<z.ZodURL>;
197
+ }, z.core.$strict>>;
195
198
  storage: z.ZodDefault<z.ZodObject<{
196
199
  purgeDeletedOrgsAfterDays: z.ZodDefault<z.ZodNumber>;
197
200
  }, z.core.$strict>>;
@@ -305,6 +305,13 @@ export function trustProxyEntryProblem(entry) {
305
305
  return `"${entry}" has an out-of-range prefix`;
306
306
  return undefined;
307
307
  }
308
+ /** An http or https origin: no path, query, fragment or credentials. */
309
+ function httpOrigin() {
310
+ return z.url({ protocol: /^https?$/ }).refine((u) => {
311
+ const x = URL.canParse(u) ? new URL(u) : null;
312
+ return x !== null && x.pathname === "/" && !x.search && !x.hash && !x.username && !x.password;
313
+ }, { message: "must be an origin: no path, query, fragment or credentials" });
314
+ }
308
315
  export const KernelConfigSchema = z.strictObject({
309
316
  platform: z
310
317
  .strictObject({
@@ -654,7 +661,7 @@ export const KernelConfigSchema = z.strictObject({
654
661
  ]))
655
662
  .default(false)
656
663
  .meta(meta({
657
- description: "Which X-Forwarded-For hops to trust for the client IP (login rate limiting, session records): false (use the socket address), a hop count, or a list of trusted proxy IPs/CIDRs (recommended; a JSON array or a comma-separated string; a /0 prefix is refused). true trusts any client-supplied X-Forwarded-For and lets clients spoof their IP. A hop count is only safe when the service is reachable solely through exactly that many proxies",
664
+ description: "Which X-Forwarded-For hops to trust for the client IP (login rate limiting, session records): false (use the socket address), a hop count, or a list of trusted proxy IPs/CIDRs (recommended; a JSON array or a comma-separated string; a /0 prefix is refused). true trusts any client-supplied X-Forwarded-For and lets clients spoof their IP. A hop count is only safe when the service is reachable solely through exactly that many proxies. On a gateway replica it also decides the per-client limit of browser live views (`/device/stream`): set it to the web tier's address or CIDR as the gateway sees it (compose: CAPYBARA_GATEWAY_TRUST_PROXY) to enable that limit; while it is false the limit is off",
658
665
  })),
659
666
  // 环境变量按 JSON 解析,CAPYBARA_HTTP__REPLICA_ID=0 会得到数字,所以也接受非负整数(输出头时转字符串)
660
667
  replicaId: z
@@ -972,17 +979,7 @@ export const KernelConfigSchema = z.strictObject({
972
979
  hot: true,
973
980
  description: "Serve the git gateway that lets sandboxes clone and push over HTTPS with run tickets; when off the gateway refuses every request",
974
981
  })),
975
- gatewayUrl: z
976
- .url({ protocol: /^https?$/ })
977
- .refine((u) => {
978
- const x = URL.canParse(u) ? new URL(u) : null;
979
- return (x !== null &&
980
- x.pathname === "/" &&
981
- !x.search &&
982
- !x.hash &&
983
- !x.username &&
984
- !x.password);
985
- }, { message: "must be an origin: no path, query, fragment or credentials" })
982
+ gatewayUrl: httpOrigin()
986
983
  .optional()
987
984
  .meta(meta({
988
985
  description: "Origin (http or https, no path, query or credentials) of the kernel as sandboxes reach it, e.g. https://kernel.internal:8080; when unset the kernel uses http.publicUrl",
@@ -1144,6 +1141,15 @@ export const KernelConfigSchema = z.strictObject({
1144
1141
  fileMaxBytes: 20_971_520,
1145
1142
  fileConcurrency: 4,
1146
1143
  }),
1144
+ gateway: z
1145
+ .strictObject({
1146
+ internalUrl: httpOrigin()
1147
+ .optional()
1148
+ .meta(meta({
1149
+ description: "Origin (http or https, no path, query or credentials) other gateway replicas use to reach this replica for device stream hops, e.g. http://10.0.0.5:8080; default http://<hostname>:<http.port>. The hop is plain http unless this is https: keep the gateways on a private network or give them an https origin",
1150
+ })),
1151
+ })
1152
+ .prefault({}),
1147
1153
  storage: z
1148
1154
  .strictObject({
1149
1155
  purgeDeletedOrgsAfterDays: z
@@ -1,6 +1,7 @@
1
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
+ import type { DeviceAccessService } from "../device-access/device-access.service.js";
4
5
  import type { DialInAccess } from "../dial-in/access.js";
5
6
  import { type RegisteredHook } from "../extensions/hooks.js";
6
7
  import { RegistrationLedger } from "../extensions/ledger.js";
@@ -62,19 +63,27 @@ export interface KernelDeps {
62
63
  * served by the calling extension. Absent (a ctx built alone in a test): `ctx.dialIn` calls
63
64
  * reject.
64
65
  */
65
- dialIn?: Pick<DialInAccess, "serves" | "request" | "online" | "capacity" | "stop">;
66
+ dialIn?: Pick<DialInAccess, "serves" | "request" | "online" | "capacity" | "stop" | "openStream">;
66
67
  /**
67
68
  * What `ctx.devices` is built from (`DeviceReports`): `changed` reads a device's report again
68
69
  * from the calling provider and refuses (`not-served`) a device bound to another one. Absent
69
70
  * (a ctx built alone in a test): `ctx.devices` calls reject.
70
71
  */
71
72
  devices?: Pick<DeviceReports, "changed">;
73
+ /**
74
+ * What `ctx.deviceAccess` calls through (`DeviceAccessService`), found at the time of use (the
75
+ * service's module sits above the host). Absent, or resolving to undefined (a ctx built alone in
76
+ * a test, the CLI): `ctx.deviceAccess` calls are refused.
77
+ */
78
+ deviceAccess?: () => DeviceAccessBackend | undefined;
72
79
  runWorkers: boolean;
73
80
  /** 内核 logger(`debug` 可选:插件 Logger 没有它,测试可不给)。 */
74
81
  log: Logger & {
75
82
  debug?(msg: string, fields?: Record<string, unknown>): void;
76
83
  };
77
84
  }
85
+ /** What `ctx.deviceAccess` calls through (`DeviceAccessService`). */
86
+ export type DeviceAccessBackend = Pick<DeviceAccessService, "ensureService" | "request" | "reportBlockedHosts" | "streamTicket" | "addNetworkHosts" | "answerHandoff">;
78
87
  /**
79
88
  * What `ctx.ui.verifyEmbedToken` returns for a valid token: the signed claims, with an org
80
89
  * token's `role` replaced by the caller's role at verification time.
@@ -1,4 +1,4 @@
1
- import { DEVICE_PROVIDER_EXTENSION_POINT, EXTENSION_POINTS, ExtensionPermissionError, ExtensionPointUnavailableError, FILE_PREVIEW_EXTENSION_POINT, OBJECT_STORE_EXTENSION_POINT, parseExtensionPoint, resolveUiSlots, SETUP_CHECK_ID_RE, SETUP_GUIDE_PLACES, validateFilePreviewProvider, validateToolSpec, } from "@capybara-hq/plugin-sdk";
1
+ import { DEVICE_PROVIDER_EXTENSION_POINT, DeviceAccessError, EXTENSION_POINTS, ExtensionPermissionError, ExtensionPointUnavailableError, FILE_PREVIEW_EXTENSION_POINT, OBJECT_STORE_EXTENSION_POINT, parseExtensionPoint, resolveUiSlots, SETUP_CHECK_ID_RE, SETUP_GUIDE_PLACES, validateFilePreviewProvider, validateToolSpec, } from "@capybara-hq/plugin-sdk";
2
2
  import { Command, ConnectionBuilder, ControlledTransactionBuilder, Kysely, TransactionBuilder, } from "kysely";
3
3
  import { conversationTopic } from "../conversations/event-log.js";
4
4
  import { kernelDb } from "../db/kernel-schema.js";
@@ -320,6 +320,24 @@ export function createExtensionContext(deps, manifest, deploymentConfig, extensi
320
320
  throw new TypeError(`plugin ${name}: ctx.dialIn.stop reason must be drain or stop`);
321
321
  await access.stop(await served(deviceId), reason);
322
322
  },
323
+ // only on the gateway replica holding the machine's socket (DialInGateway); elsewhere
324
+ // DialInStreamElsewhereError. The extension's end closes its streams.
325
+ openStream: async (deviceId, body, opts) => {
326
+ const id = await served(deviceId);
327
+ // the SDK requires the signal: an open nobody can abort is refused up front
328
+ if (!(opts?.signal instanceof AbortSignal))
329
+ throw new TypeError(`plugin ${name}: ctx.dialIn.openStream needs opts.signal`);
330
+ const signal = AbortSignal.any([lifecycle.signal, opts.signal]);
331
+ const stream = await access.openStream(id, body, signal);
332
+ const onEnd = () => stream.close("extension stopped");
333
+ if (lifecycle.signal.aborted)
334
+ onEnd();
335
+ else {
336
+ lifecycle.signal.addEventListener("abort", onEnd, { once: true });
337
+ void stream.closed.then(() => lifecycle.signal.removeEventListener("abort", onEnd));
338
+ }
339
+ return stream;
340
+ },
323
341
  };
324
342
  })()
325
343
  : undefined;
@@ -346,6 +364,27 @@ export function createExtensionContext(deps, manifest, deploymentConfig, extensi
346
364
  },
347
365
  }
348
366
  : undefined;
367
+ // ctx.deviceAccess: only with permissions.deviceAccess, and each call only for a service the
368
+ // approved manifest declares and only for the conversation's owner (DeviceAccessService checks)
369
+ const deviceAccessApi = perms.deviceAccess
370
+ ? (() => {
371
+ const caller = { extension: name, services: [...(perms.deviceAccess?.services ?? [])] };
372
+ const backend = () => {
373
+ const b = deps.deviceAccess?.();
374
+ if (!b)
375
+ throw new DeviceAccessError("capability_missing", "Device services are not available in this process.");
376
+ return b;
377
+ };
378
+ return {
379
+ ensureService: async (call, spec) => backend().ensureService(caller, call, spec),
380
+ request: async (call, req) => backend().request(caller, call, req),
381
+ reportBlockedHosts: (call, hosts, opts) => backend().reportBlockedHosts(call, hosts, opts),
382
+ streamTicket: async (scope) => backend().streamTicket(caller, scope),
383
+ addNetworkHosts: async (scope) => backend().addNetworkHosts(caller, scope),
384
+ answerHandoff: async (scope) => backend().answerHandoff(caller, scope),
385
+ };
386
+ })()
387
+ : undefined;
349
388
  // "METHOD path" -> the access the manifest declares for it (the approved manifest)
350
389
  const declaredRoutes = new Map((perms.http ?? []).map((r) => [`${r.method} ${r.path}`, r.access]));
351
390
  const declaredTools = new Set(perms.tools ?? []);
@@ -791,7 +830,7 @@ export function createExtensionContext(deps, manifest, deploymentConfig, extensi
791
830
  return closing;
792
831
  },
793
832
  };
794
- // secrets / storage / models / dialIn / devices: a plain property when declared; otherwise a
833
+ // secrets / storage / models / dialIn / devices / deviceAccess: a plain property when declared; otherwise a
795
834
  // non-enumerable getter that throws, so spreading or printing ctx triggers no denial and no audit
796
835
  const gated = (key, api, item = `permissions.${key}`) => {
797
836
  if (api) {
@@ -809,6 +848,7 @@ export function createExtensionContext(deps, manifest, deploymentConfig, extensi
809
848
  gated("models", modelsApi);
810
849
  gated("dialIn", dialInApi);
811
850
  gated("devices", devicesApi, `provides ${DEVICE_PROVIDER_EXTENSION_POINT}`);
851
+ gated("deviceAccess", deviceAccessApi);
812
852
  return ctx;
813
853
  }
814
854
  /**
@@ -0,0 +1,7 @@
1
+ /**
2
+ * `ctx.deviceAccess` (browser use spec §7): {@link DeviceAccessService}. The extension host finds
3
+ * it at the time of use (`ModuleRef`, {@link DEVICE_ACCESS_BACKEND}), since this module sits
4
+ * above the host (sandbox, devices and tools all import the extensions module).
5
+ */
6
+ export declare class ExtensionDeviceAccessModule {
7
+ }
@@ -0,0 +1,41 @@
1
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
2
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
4
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
5
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
6
+ };
7
+ import { Module } from "@nestjs/common";
8
+ import { DevicesModule } from "../devices/devices.module.js";
9
+ import { ExtensionRegistryModule } from "../extensions/registry.js";
10
+ import { SandboxProviderRegistryModule } from "../sandbox/providers.module.js";
11
+ import { SandboxModule } from "../sandbox/sandbox.module.js";
12
+ import { ToolsModule } from "../tools/tools.module.js";
13
+ import { DeviceAccessService } from "./device-access.service.js";
14
+ import { DEVICE_ACCESS_BACKEND } from "./token.js";
15
+ /**
16
+ * `ctx.deviceAccess` (browser use spec §7): {@link DeviceAccessService}. The extension host finds
17
+ * it at the time of use (`ModuleRef`, {@link DEVICE_ACCESS_BACKEND}), since this module sits
18
+ * above the host (sandbox, devices and tools all import the extensions module).
19
+ */
20
+ let ExtensionDeviceAccessModule = class ExtensionDeviceAccessModule {
21
+ };
22
+ ExtensionDeviceAccessModule = __decorate([
23
+ Module({
24
+ // SandboxModule: device services and the command review; DevicesModule: the conversation's
25
+ // device, who may use it and its allowlist write; ToolsModule: the questions;
26
+ // ExtensionRegistryModule: an extension's approved manifest when a viewer opens
27
+ imports: [
28
+ SandboxModule,
29
+ SandboxProviderRegistryModule,
30
+ DevicesModule,
31
+ ToolsModule,
32
+ ExtensionRegistryModule,
33
+ ],
34
+ providers: [
35
+ DeviceAccessService,
36
+ { provide: DEVICE_ACCESS_BACKEND, useExisting: DeviceAccessService },
37
+ ],
38
+ exports: [DeviceAccessService, DEVICE_ACCESS_BACKEND],
39
+ })
40
+ ], ExtensionDeviceAccessModule);
41
+ export { ExtensionDeviceAccessModule };
@@ -0,0 +1,142 @@
1
+ import { type DeviceAccessScope, type DeviceServiceSpec, type DeviceServiceStatus, type Logger, type ToolCallContext } from "@capybara-hq/plugin-sdk";
2
+ import type { Redis } from "ioredis";
3
+ import { DeviceAccess } from "../devices/access.js";
4
+ import { ConversationDevices } from "../devices/conversation-devices.js";
5
+ import { DevicesService } from "../devices/devices.service.js";
6
+ import { ExtensionRegistry } from "../extensions/registry.js";
7
+ import { KernelConfigService } from "../infra/config/kernel-config.service.js";
8
+ import { KernelDb } from "../infra/database/kernel-db.js";
9
+ import { DeviceServices } from "../sandbox/device-services.js";
10
+ import { DeviceProviders } from "../sandbox/providers.js";
11
+ import { CommandReviewService } from "../sandbox/review/review.service.js";
12
+ import { QuestionsService } from "../tools/questions.service.js";
13
+ /** What every `ctx.deviceAccess` call refuses a run another member triggered with. */
14
+ export declare const DEVICE_ACCESS_NOT_OWNER_TEXT = "Browser tools only run for the conversation's owner on their own device.";
15
+ /** A viewer ticket's key prefix (`capk:device-stream-ticket:<id>`, single use, GETDEL). */
16
+ export declare const DEVICE_STREAM_TICKET_PREFIX = "capk:device-stream-ticket:";
17
+ /** How long a viewer ticket lives, in seconds. */
18
+ export declare const DEVICE_STREAM_TICKET_TTL_SECONDS = 60;
19
+ /** What a viewer ticket records: the viewer opens exactly this service of exactly this device. */
20
+ export interface DeviceStreamTicket {
21
+ orgId: string;
22
+ accountId: string;
23
+ conversationId: string;
24
+ deviceId: string;
25
+ providerName: string;
26
+ service: string;
27
+ extension: string;
28
+ }
29
+ /** The calling extension and the services its approved manifest declares. */
30
+ export interface DeviceAccessCaller {
31
+ extension: string;
32
+ services: readonly string[];
33
+ }
34
+ /**
35
+ * `ctx.deviceAccess` (browser use spec §7): an extension's device services in the conversation's
36
+ * device, limited to the conversation's owner on their own personal device and to the service
37
+ * names the extension's approved manifest declares. A service launch passes the command review
38
+ * (fail closed: only `allow` starts it), once per start; requests ride the provider's request
39
+ * path; refused hosts land in the call scope for the pipeline's network ask; viewer tickets are
40
+ * single-use Redis records; the allowlist write and the handoff answer go through the device page's
41
+ * and the questions' own services (their checks and audits apply).
42
+ */
43
+ export declare class DeviceAccessService {
44
+ private readonly kdb;
45
+ private readonly redis;
46
+ private readonly config;
47
+ private readonly services;
48
+ private readonly review;
49
+ private readonly devices;
50
+ private readonly access;
51
+ private readonly deviceWrites;
52
+ private readonly questions;
53
+ private readonly providers;
54
+ private readonly log;
55
+ private readonly registry;
56
+ constructor(kdb: KernelDb, redis: Redis, config: Pick<KernelConfigService, "get">, services: DeviceServices, review: Pick<CommandReviewService, "review">, devices: Pick<ConversationDevices, "forTool" | "reviewFacts">, access: Pick<DeviceAccess, "usable">, deviceWrites: Pick<DevicesService, "addNetworkHostsIn">, questions: Pick<QuestionsService, "answer">, providers: Pick<DeviceProviders, "forDevice">, log: Logger, registry: Pick<ExtensionRegistry, "current">);
57
+ private get db();
58
+ /**
59
+ * Starts the service in the call's device, or finds it running. An `ifRunning` ensure first
60
+ * (never starts anything): a running service is kept with no review. A stopped one is
61
+ * launched only after the command review saw the command as it runs
62
+ * (`env K=V … node <codeDir ?? stateDir>/<entry> <args…>`, the state directory as its working
63
+ * directory) and allowed it; anything else refuses it (fail closed). The verdict is recorded
64
+ * on the call (the call scope) and a start is audited `device.service_started`.
65
+ */
66
+ ensureService(caller: DeviceAccessCaller, call: ToolCallContext, spec: DeviceServiceSpec): Promise<DeviceServiceStatus>;
67
+ /** One request to the service's socket in the call's device. */
68
+ request(caller: DeviceAccessCaller, call: ToolCallContext, req: {
69
+ service: string;
70
+ body: Uint8Array;
71
+ timeoutMs: number;
72
+ }): Promise<Uint8Array>;
73
+ /**
74
+ * Records refused hosts in the call scope (synchronous: the pipeline reads it once the handler
75
+ * returns) on the device this call's own `ctx.deviceAccess` calls resolved, if any.
76
+ */
77
+ reportBlockedHosts(call: ToolCallContext, hosts: string[], opts?: {
78
+ url?: string;
79
+ }): void;
80
+ /** A single-use viewer ticket for the service (the person's panel opens `url`). */
81
+ streamTicket(caller: DeviceAccessCaller, scope: DeviceAccessScope & {
82
+ service: string;
83
+ }): Promise<{
84
+ url: string;
85
+ expiresAt: string;
86
+ }>;
87
+ /**
88
+ * Mints a viewer ticket: `capk:device-stream-ticket:<id>` for
89
+ * {@link DEVICE_STREAM_TICKET_TTL_SECONDS} seconds, taken once ({@link takeTicket}). Refused
90
+ * unless the account owns the conversation and its personal device, and the device's provider
91
+ * can open streams.
92
+ */
93
+ mintTicket(scope: DeviceAccessScope, service: string, caller: DeviceAccessCaller): Promise<{
94
+ id: string;
95
+ url: string;
96
+ expiresAt: string;
97
+ }>;
98
+ /** Takes a viewer ticket (GETDEL: a second take finds nothing); null when unknown or used. */
99
+ takeTicket(id: string): Promise<DeviceStreamTicket | null>;
100
+ /**
101
+ * Whether a taken viewer ticket's record still stands when its viewer opens (the checks of
102
+ * {@link mintTicket} again, binding nothing): the conversation live and owned by the record's
103
+ * account, its device still the record's device on the record's provider and the account's
104
+ * own, the record's extension still enabled in the org and its approved manifest as loaded now
105
+ * (not the record's copy) still declaring the service in `permissions.deviceAccess.services`.
106
+ * False when any of that no longer holds; other failures (the database) are thrown.
107
+ */
108
+ ticketStands(t: DeviceStreamTicket): Promise<boolean>;
109
+ /**
110
+ * {@link ticketStands} with the reason when it does not: `provider_off` when the device's
111
+ * provider is no longer usable in the org (switched off, or no provider), `revoked` for
112
+ * everything else (the conversation, its owner or device, the extension or its declared
113
+ * services). An open viewer re-checks with it while it lives. Other failures are thrown.
114
+ */
115
+ ticketCheck(t: DeviceStreamTicket): Promise<"stands" | "revoked" | "provider_off">;
116
+ /**
117
+ * Adds hosts to the conversation's device allowlist through the device page's own write
118
+ * (ceilings, validation, the `device.network_changed` audit), owner only. Exact host names
119
+ * only, as an approved network ask grants: a wildcard is refused before anything is read.
120
+ */
121
+ addNetworkHosts(caller: DeviceAccessCaller, scope: DeviceAccessScope & {
122
+ hosts: string[];
123
+ }): Promise<void>;
124
+ /**
125
+ * Answers the pending question of tool call `callId` in the conversation with `{ done }`, under
126
+ * the questions' own rules (only the run's starter answers, the form validates the answer); only
127
+ * a question one of this extension's tools raised.
128
+ */
129
+ answerHandoff(caller: DeviceAccessCaller, scope: DeviceAccessScope & {
130
+ callId: string;
131
+ done: boolean;
132
+ }): Promise<void>;
133
+ /** The use of the call's device (bound now when the conversation has none yet, as tools do). */
134
+ private callUse;
135
+ /**
136
+ * The device of a scope-based call: the conversation live, the account its owner, the
137
+ * extension enabled in its org, its (root) conversation bound to a personal device the account
138
+ * may use now. Binds nothing.
139
+ */
140
+ private scopedDevice;
141
+ private rootOf;
142
+ }