@capybara-hq/plugin-sdk 0.1.0-rc.50 → 0.1.0-rc.52

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.
package/README.md CHANGED
@@ -1,7 +1,7 @@
1
1
  # @capybara-hq/plugin-sdk
2
2
 
3
3
  The SDK for writing plugins for [Capybara](https://github.com/capybara-hq/core), an open-source enterprise agent platform. It holds
4
- the types, extension point contracts (`model-provider@2`, `channel@1`, `connector@1`, `sandbox@2`,
4
+ the types, extension point contracts (`model-provider@2`, `channel@1`, `connector@1`, `device-provider@1`,
5
5
  `object-store@1` and others) and pure functions that a plugin's extension is written against, and the
6
6
  package formats: the plugin manifest `.capybara-plugin/plugin.json` (`parsePluginManifest`),
7
7
  connector template files `connectors/<id>.json` (`parseConnectorTemplateFile`) and the marketplace
@@ -55,8 +55,8 @@ on the web. Agents can file requests but never decide them.
55
55
  ## Devices
56
56
 
57
57
  Agents run commands and keep files on a **device**: one instance plus a file system that is kept
58
- until the device is deleted. A device is a cloud sandbox (from the deployment's sandbox provider)
59
- or a machine connected with `capybara-device`, and the conversations that use it share its files.
58
+ until the device is deleted. A device comes from a device provider (a cloud sandbox such as Docker or E2B)
59
+ or is a machine connected with `capybara-device`, and the conversations that use it share its files.
60
60
  A device runs in one of two modes: auto (the environment's own capability) or sandbox (an OS
61
61
  sandbox with an allowlist network). Skill files are read-only in the device's skills directory;
62
62
  each conversation is told the device's directories, mode and network. Sandbox limits and the
@@ -43,6 +43,9 @@ Fields of `template`:
43
43
  tenant id). List only what really differs per org.
44
44
  - `auth`: the auth method without credentials: `none`, `bearer`, `basic`, `api_key`, `headers`,
45
45
  `oauth_code` or `oauth_client`, plus `ownership` (`org` or per member).
46
+ `oauth_code` may add `authorizationParams`, extra query parameters of the authorize request
47
+ (e.g. `{ "access_type": "offline", "prompt": "consent" }` for Google): at most 10, lowercase
48
+ names, plain values, never a secret, none of `OAUTH_RESERVED_AUTHORIZATION_PARAMS`.
46
49
  - `defaultToolPolicies`: tool name to `allow`, `ask` or `deny`. When unsure, do not write `allow`.
47
50
 
48
51
  Credentials and secret config are entered by the person on the `Platform` confirmation card (name
@@ -0,0 +1,15 @@
1
+ # Authoring: extension point device-provider
2
+
3
+ <!-- generated:extension-point -->
4
+ - Name: `device-provider` (a ref is `device-provider@<major>`)
5
+ - Provides devices (an instance plus kept files) agents run commands in: containers, microVMs, connected machines.
6
+ - Providers: several
7
+ - Enabled per org: yes
8
+ - Brokered by the platform: yes (extensions use it only through `ctx`)
9
+ <!-- /generated -->
10
+
11
+ Contract: DeviceProvider (`device-provider.ts`)
12
+
13
+ The kernel accepts `device-provider@1`; several providers may be loaded side by side and each device keeps the provider that made it. A device is one instance plus a file system that outlives it. Implement the file system (`createFileSystem`, `destroyFileSystem`, `destroyFileSystemByName`), the instance on it (`create`, which throws `FileSystemGoneError` when the file system is gone instead of making an empty one; `resume`, `suspend`; `destroy` and `destroyByName`, which drop the instance and keep the files), and the instance's `exec`, `readFile`, `writeFile`, `stat`, `killAll` and `killTagged` (`concurrentExec` is required: several conversations share one instance). Declare `networkAllowlist: true` (you enforce `limits.network` allowlists) and implement `report(device, signal)`, which answers a `DeviceReport` (revision, description, home, limits, reset) shown to people; the kernel refuses a provider without them. A `projects` call may throw `ProjectPathRefusedError` with a reason when a directory is not yours to serve. Aborting a command must kill it. Locking, suspension timing and destruction are the kernel's job, not yours.
14
+
15
+ See `extensions` for the rules every extension follows.
@@ -68,7 +68,7 @@ look like `channel@1`: name and major version. The registered points:
68
68
  <!-- generated:extension-points -->
69
69
  | Extension point | Providers | Per org | What it is |
70
70
  |---|---|---|---|
71
- | `sandbox` | single | no | Runs a device's instance and keeps its files for agents' commands (Docker, E2B). |
71
+ | `device-provider` | multi | yes | Provides devices (an instance plus kept files) agents run commands in: containers, microVMs, connected machines. |
72
72
  | `config-source` | single | no | Supplies deployment configuration from an external store such as Nacos. |
73
73
  | `secret-store` | single | no | Stores and resolves secrets (connector credentials, secret config) outside the database. |
74
74
  | `object-store` | single | no | Stores files and artifacts in S3-compatible object storage, with presigned uploads. |
@@ -66,8 +66,9 @@ Rules that the schema cannot show:
66
66
  detail; the extension must provide `channel@1`; one per plugin), `connector-template`
67
67
  (`template` names one of the plugin's `connectors/<id>.json`; one per template) or
68
68
  `extension-deployment` (the super admin's page of the extension; its checks get the extension's
69
- platform deployment config and `orgId: null`, for credentials such as a push provider's key). See
70
- "Setup guides" below.
69
+ platform deployment config and `orgId: null`, for credentials such as a push provider's key) or
70
+ `device-connection` (how a member connects a machine through a device provider). See "Setup
71
+ guides" below.
71
72
  - `extension` is written by the packer; never write it by hand.
72
73
 
73
74
  ## Setup guides
@@ -80,7 +81,8 @@ A guide is CommonMark + GFM:
80
81
  `orgName`, `pluginName`, `pluginVersion`, `mode`; `channel-connection` adds `webhookUrl`,
81
82
  `signInCallbackUrl`, `connectionName`; `connector-template` adds `oauthCallbackUrl`,
82
83
  `signInCallbackUrl`, `templateId`, `templateName`, `connectorName`; `extension-deployment` adds
83
- none (no modes, admin audience only). In `yaml` / `json` code put a
84
+ none (no modes, admin audience only); `device-connection` has only `publicUrl`, `orgId`,
85
+ `orgName`, `pluginName` (no modes, member audience only). In `yaml` / `json` code put a
84
86
  variable inside double quotes. Directive lines and fence info strings hold no variables.
85
87
  - Sections: a line `::: mode webhook` (modes `long_connection`, `webhook`; channel guides) or
86
88
  `::: audience member` (audiences `admin`, `member`; connector template guides) opens one, `:::`
@@ -93,7 +95,10 @@ A guide is CommonMark + GFM:
93
95
  `connector-connected`, `oauth-token-endpoint`). The label is plain text, at most 80 characters.
94
96
  - Code fences: `<language> title="<text>"`; every block gets a copy button. Indented code blocks are
95
97
  refused. Raw HTML shows as text, images are never loaded, and only `https:` links stay links.
96
- - The zh document has the same sections, the same check ids and byte-equal code blocks.
98
+ - Shell actions (`device-connection` guides only): a line `::shell-action connect-this-machine
99
+ <label>` in column 0 is a button that asks the native shell to connect the machine the page runs
100
+ on; at most 4 per document, the label is plain text (at most 80 characters, no variables).
101
+ - The zh document has the same sections, the same check ids, the same shell actions and byte-equal code blocks.
97
102
  - Limits: 64 KiB per document, 24 code blocks, 16 checks, 16 sections.
98
103
 
99
104
  `capybara-plugin pack` and `check` validate the documents; `capybara-plugin guide <id> [--locale zh]
@@ -1,4 +1,11 @@
1
1
  import { z } from "zod";
2
+ /**
3
+ * Authorization request parameters the kernel sets itself, or that would change what the callback
4
+ * or the token exchange relies on, or that never belong on a URL. `oauth_code`
5
+ * `authorizationParams` cannot use them, nor can the query of a manual `authorizationUrl`; the kernel
6
+ * checks the list again before it builds an authorize URL.
7
+ */
8
+ export declare const OAUTH_RESERVED_AUTHORIZATION_PARAMS: readonly ["response_type", "client_id", "redirect_uri", "state", "code_challenge", "code_challenge_method", "scope", "resource", "response_mode", "request", "request_uri", "nonce", "dpop_jkt", "authorization_details", "client_secret", "client_assertion", "client_assertion_type", "code", "code_verifier", "grant_type", "refresh_token"];
2
9
  /**
3
10
  * Authentication method: only the type and non-secret fields; credential values go through the
4
11
  * kernel's `credential` / credentials API.
@@ -54,6 +61,7 @@ export declare const ConnectorAuthSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{
54
61
  client_secret_post: "client_secret_post";
55
62
  }>>;
56
63
  tokenTypes: z.ZodOptional<z.ZodArray<z.ZodString>>;
64
+ authorizationParams: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodString>>;
57
65
  }, z.core.$strict>, z.ZodObject<{
58
66
  type: z.ZodLiteral<"oauth_client">;
59
67
  ownership: z.ZodLiteral<"org">;
@@ -39,6 +39,54 @@ const TokenTypes = z
39
39
  .regex(/^[A-Za-z][A-Za-z0-9_.-]*$/, "Invalid token type")
40
40
  .refine((t) => t.toLowerCase() !== "dpop", "DPoP tokens are not bearer tokens"))
41
41
  .max(5);
42
+ /**
43
+ * Authorization request parameters the kernel sets itself, or that would change what the callback
44
+ * or the token exchange relies on, or that never belong on a URL. `oauth_code`
45
+ * `authorizationParams` cannot use them, nor can the query of a manual `authorizationUrl`; the kernel
46
+ * checks the list again before it builds an authorize URL.
47
+ */
48
+ export const OAUTH_RESERVED_AUTHORIZATION_PARAMS = [
49
+ // set by the kernel's authorize request
50
+ "response_type",
51
+ "client_id",
52
+ "redirect_uri",
53
+ "state",
54
+ "code_challenge",
55
+ "code_challenge_method",
56
+ "scope",
57
+ "resource",
58
+ // would change what the callback or the token exchange relies on
59
+ "response_mode",
60
+ "request",
61
+ "request_uri",
62
+ "nonce",
63
+ "dpop_jkt",
64
+ "authorization_details",
65
+ // credentials and token-endpoint names
66
+ "client_secret",
67
+ "client_assertion",
68
+ "client_assertion_type",
69
+ "code",
70
+ "code_verifier",
71
+ "grant_type",
72
+ "refresh_token",
73
+ ];
74
+ const RESERVED_PARAMS = new Set(OAUTH_RESERVED_AUTHORIZATION_PARAMS);
75
+ const reservedParamMessage = (name) => `"${name}" is set by the kernel and cannot be an authorization parameter`;
76
+ const MAX_AUTHORIZATION_PARAMS = 10;
77
+ /**
78
+ * Extra query parameters of the authorize request (e.g. Google's `access_type: "offline"`,
79
+ * `prompt: "consent"`): names `[a-z][a-z0-9_]` up to 40 characters, values 1-200 printable ASCII
80
+ * characters, at most 10, none of {@link OAUTH_RESERVED_AUTHORIZATION_PARAMS}. Not secrets: they
81
+ * are stored in plain JSON and shown in the browser's address bar.
82
+ */
83
+ const AuthorizationParams = z
84
+ .record(z.string().regex(/^[a-z][a-z0-9_]{0,39}$/, "Invalid authorization parameter name"), z.string().regex(/^[\x20-\x7E]{1,200}$/, "Invalid authorization parameter value"))
85
+ .refine((p) => Object.keys(p).length <= MAX_AUTHORIZATION_PARAMS, {
86
+ message: `At most ${MAX_AUTHORIZATION_PARAMS} authorization parameters`,
87
+ })
88
+ .describe("Extra query parameters of the OAuth authorize request (e.g. access_type, prompt). " +
89
+ "Never put a secret here.");
42
90
  /**
43
91
  * Authentication method: only the type and non-secret fields; credential values go through the
44
92
  * kernel's `credential` / credentials API.
@@ -77,9 +125,29 @@ export const ConnectorAuthSchema = z.discriminatedUnion("type", [
77
125
  client: z.enum(["dcr", "manual"]),
78
126
  tokenAuthMethod: TokenAuthMethod.optional(),
79
127
  tokenTypes: TokenTypes.optional(),
128
+ authorizationParams: AuthorizationParams.optional(),
80
129
  })
81
130
  .strict()
82
131
  .superRefine((a, ctx) => {
132
+ for (const name of Object.keys(a.authorizationParams ?? {})) {
133
+ if (RESERVED_PARAMS.has(name))
134
+ ctx.addIssue({
135
+ code: "custom",
136
+ path: ["authorizationParams", name],
137
+ message: reservedParamMessage(name),
138
+ });
139
+ }
140
+ // A query in a manual endpoint stays (RFC 6749 §3.1), but never with a name the kernel owns
141
+ if (a.authorizationUrl !== undefined && URL.canParse(a.authorizationUrl)) {
142
+ for (const name of new Set(new URL(a.authorizationUrl).searchParams.keys())) {
143
+ if (RESERVED_PARAMS.has(name.toLowerCase()))
144
+ ctx.addIssue({
145
+ code: "custom",
146
+ path: ["authorizationUrl"],
147
+ message: reservedParamMessage(name),
148
+ });
149
+ }
150
+ }
83
151
  if (a.discovery === "manual") {
84
152
  for (const k of ["authorizationUrl", "tokenUrl"]) {
85
153
  if (a[k] === undefined)
@@ -1,4 +1,4 @@
1
- import { type ExecResult, type SandboxActor, type SandboxHandle, type SandboxProvider } from "./sandbox.js";
1
+ import { type DeviceProvider, type ExecResult, type SandboxActor, type SandboxHandle } from "./device-provider.js";
2
2
  /** The permission profile selected for a conversation. */
3
3
  export type PermissionProfile = "request-approval" | "approve-for-me" | "full-access";
4
4
  /** Accepts only the supported permission profile names. */
@@ -45,10 +45,14 @@ export declare class SandboxOperationOutcomeUnknownError extends Error {
45
45
  }
46
46
  /** Recognizes unknown outcomes across SDK copies; an unknown outcome is not a gone instance. */
47
47
  export declare function isSandboxOperationOutcomeUnknownError(e: unknown): e is SandboxOperationOutcomeUnknownError;
48
- /** Writable roots are also readable. Device scope uses the device's OS authority, never its host's. */
48
+ /**
49
+ * A scoped operation names the project root (null in free mode) and the roots it may write; what
50
+ * it may read is the provider's rule. Writable roots are also readable. Device scope uses the
51
+ * device's OS authority, never its host's.
52
+ */
49
53
  export type SandboxFileScope = {
50
54
  readonly kind: "scoped";
51
- readonly readRoots: readonly string[];
55
+ readonly projectRoot: string | null;
52
56
  readonly writeRoots: readonly string[];
53
57
  } | {
54
58
  readonly kind: "device";
@@ -129,7 +133,7 @@ export interface SandboxPermissionSupport {
129
133
  */
130
134
  export declare function instanceSupported(report: SandboxPermissionSupport): boolean;
131
135
  /** Actor and tag come only from the immutable operation scope. */
132
- export type SandboxExecOptions = Omit<Parameters<SandboxProvider["exec"]>[1], "tag" | "actor">;
136
+ export type SandboxExecOptions = Omit<Parameters<DeviceProvider["exec"]>[1], "tag" | "actor">;
133
137
  /**
134
138
  * A lightweight factory result: no worker opens until a method is called. Factory and method
135
139
  * signals jointly end the operation. Every method consumes its operation ID before effects;
@@ -1,4 +1,4 @@
1
- import { SANDBOX_TAG_RE, validateAllowHost, validateSandboxPathShape, } from "./sandbox.js";
1
+ import { SANDBOX_TAG_RE, validateAllowHost, validateSandboxPathShape, } from "./device-provider.js";
2
2
  /** Accepts only the supported permission profile names. */
3
3
  export function isPermissionProfile(value) {
4
4
  return value === "request-approval" || value === "approve-for-me" || value === "full-access";
@@ -148,8 +148,18 @@ function strings(value, maximum, check, field) {
148
148
  function roots(value, field) {
149
149
  return strings(value, 64, validateSandboxPathShape, field);
150
150
  }
151
+ function projectRoot(value) {
152
+ if (value === null)
153
+ return null;
154
+ if (typeof value !== "string")
155
+ return invalid("filesystem.projectRoot", "expected an absolute path or null");
156
+ const errors = validateSandboxPathShape(value);
157
+ if (errors.length > 0)
158
+ return invalid("filesystem.projectRoot", errors.join("; "));
159
+ return value;
160
+ }
151
161
  function fileScope(value) {
152
- const v = record(value, ["kind", "readRoots", "writeRoots"], "filesystem");
162
+ const v = record(value, ["kind", "projectRoot", "writeRoots"], "filesystem");
153
163
  if (v.kind === "device") {
154
164
  record(value, ["kind"], "filesystem");
155
165
  return Object.freeze({ kind: "device" });
@@ -158,7 +168,7 @@ function fileScope(value) {
158
168
  return invalid("filesystem.kind", "expected scoped or device");
159
169
  return Object.freeze({
160
170
  kind: "scoped",
161
- readRoots: roots(v.readRoots, "filesystem.readRoots"),
171
+ projectRoot: projectRoot(v.projectRoot),
162
172
  writeRoots: roots(v.writeRoots, "filesystem.writeRoots"),
163
173
  });
164
174
  }
@@ -7,16 +7,17 @@
7
7
  * (`LegacyDeviceHello`, `parseLegacyDeviceFrame`, ...); protocol 4 reuses their value guards, and
8
8
  * they go with the legacy device surface.
9
9
  */
10
- import { type ExecResult, type SandboxActor, type SandboxLimits, type SandboxRoots } from "./sandbox.js";
11
- import { type SandboxPermissionSupport } from "./sandbox-operation.js";
10
+ import { type SandboxPermissionSupport } from "./device-operation.js";
11
+ import { type ExecResult, type SandboxActor, type SandboxLimits, type SandboxRoots } from "./device-provider.js";
12
12
  /** The protocol version carried in `X-Capybara-Device-Protocol` and the hello frame. */
13
- export declare const DEVICE_PROTOCOL_VERSION = 4;
13
+ export declare const DEVICE_PROTOCOL_VERSION = 5;
14
14
  /**
15
- * Protocol 3's version, which a deployment speaking {@link DEVICE_PROTOCOL_VERSION} refuses (426
16
- * on the header, a protocol close on the hello): its owner report and runtime support describe the
17
- * removed Full access ceiling, so a protocol 3 program must be updated.
15
+ * Protocol 4's version, which a deployment speaking {@link DEVICE_PROTOCOL_VERSION} refuses (426
16
+ * on the header, a protocol close on the hello): its operation frames carry read roots in the
17
+ * filesystem scope, which protocol 5 replaced with the project root, so a protocol 4 program must
18
+ * be updated.
18
19
  */
19
- export declare const LEGACY_DEVICE_PROTOCOL_VERSION = 3;
20
+ export declare const LEGACY_DEVICE_PROTOCOL_VERSION = 4;
20
21
  /** The operations the kernel asks a device to run. */
21
22
  export type DeviceOp = "create" | "exec" | "readFile" | "writeFile" | "stat" | "killTagged" | "killAll" | "stop" | "policy" | "policyStatus" | "list" | "scan";
22
23
  /**
@@ -259,7 +260,7 @@ export interface LegacyDevicePolicyStatus {
259
260
  /**
260
261
  * Lists one directory (absolute `path`, {@link validateSandboxPathShape}): at most `limit` entries
261
262
  * (at most {@link MAX_DEVICE_LIST_ENTRIES}), read within the operation's scope. See
262
- * `SandboxProvider.list` for the semantics.
263
+ * `DeviceProvider.list` for the semantics.
263
264
  */
264
265
  export interface DeviceListArgs {
265
266
  path: string;
@@ -287,7 +288,7 @@ export type DeviceListResult = {
287
288
  /**
288
289
  * Looks for project-like directories under `base` (absolute, {@link validateSandboxPathShape}),
289
290
  * read within the operation's scope. A `base` that does not exist answers `[]`; a `base` that is a
290
- * file, unreadable, or outside the request's scope is an error. See `SandboxProvider.scan` for the
291
+ * file, unreadable, or outside the request's scope is an error. See `DeviceProvider.scan` for the
291
292
  * traversal.
292
293
  */
293
294
  export interface DeviceScanArgs {
@@ -296,7 +297,7 @@ export interface DeviceScanArgs {
296
297
  /**
297
298
  * `base` itself and the directories at most {@link MAX_DEVICE_SCAN_DEPTH} levels below it that
298
299
  * hold a `.git` entry or an `AGENTS.md` file, sorted by `path` in code-unit order and cut to the
299
- * first {@link MAX_DEVICE_SCAN_RESULTS}. Never file contents. See `SandboxProvider.scan`.
300
+ * first {@link MAX_DEVICE_SCAN_RESULTS}. Never file contents. See `DeviceProvider.scan`.
300
301
  */
301
302
  export type DeviceScanResult = DeviceProjectCandidate[];
302
303
  /** A frame that is not valid device protocol (or came from the wrong side). */
@@ -385,7 +386,7 @@ export interface DevicePolicyChanged {
385
386
  ownerCeiling: DeviceOwnerCeiling;
386
387
  }
387
388
  export interface DeviceHello extends LegacyDeviceHello {
388
- protocol: 4;
389
+ protocol: typeof DEVICE_PROTOCOL_VERSION;
389
390
  permissionSupport: SandboxPermissionSupport;
390
391
  ownerCeiling: DeviceOwnerCeiling;
391
392
  instanceGeneration: string | null;
@@ -7,16 +7,17 @@
7
7
  * (`LegacyDeviceHello`, `parseLegacyDeviceFrame`, ...); protocol 4 reuses their value guards, and
8
8
  * they go with the legacy device surface.
9
9
  */
10
- import { isDeviceProjectName, MAX_DEVICE_PROJECT_NAME_LENGTH, MAX_DEVICE_SCAN_DEPTH, MAX_DEVICE_SCAN_RESULTS, validateAllowHost, validateSandboxPathShape, } from "./sandbox.js";
11
- import { parseSandboxBrowseScope, parseSandboxExecutionRef, parseSandboxOperationRef, parseSandboxOperationScope, parseSandboxPreparationScope, } from "./sandbox-operation.js";
10
+ import { parseSandboxBrowseScope, parseSandboxExecutionRef, parseSandboxOperationRef, parseSandboxOperationScope, parseSandboxPreparationScope, } from "./device-operation.js";
11
+ import { isDeviceProjectName, MAX_DEVICE_PROJECT_NAME_LENGTH, MAX_DEVICE_SCAN_DEPTH, MAX_DEVICE_SCAN_RESULTS, validateAllowHost, validateSandboxPathShape, } from "./device-provider.js";
12
12
  /** The protocol version carried in `X-Capybara-Device-Protocol` and the hello frame. */
13
- export const DEVICE_PROTOCOL_VERSION = 4;
13
+ export const DEVICE_PROTOCOL_VERSION = 5;
14
14
  /**
15
- * Protocol 3's version, which a deployment speaking {@link DEVICE_PROTOCOL_VERSION} refuses (426
16
- * on the header, a protocol close on the hello): its owner report and runtime support describe the
17
- * removed Full access ceiling, so a protocol 3 program must be updated.
15
+ * Protocol 4's version, which a deployment speaking {@link DEVICE_PROTOCOL_VERSION} refuses (426
16
+ * on the header, a protocol close on the hello): its operation frames carry read roots in the
17
+ * filesystem scope, which protocol 5 replaced with the project root, so a protocol 4 program must
18
+ * be updated.
18
19
  */
19
- export const LEGACY_DEVICE_PROTOCOL_VERSION = 3;
20
+ export const LEGACY_DEVICE_PROTOCOL_VERSION = 4;
20
21
  const DEVICE_OPS = [
21
22
  "create",
22
23
  "exec",
@@ -1,16 +1,16 @@
1
1
  /**
2
- * Sandbox contract `sandbox@2`: a single-select, brokered extension point (extensions may not
3
- * `requires` it; the kernel's `SandboxService` consumes it). The provider implements only the
2
+ * Device provider contract `device-provider@1`: a multi, brokered, org-scoped extension point
3
+ * (extensions may not `requires` it; the kernel's `SandboxService` consumes it). The provider implements only the
4
4
  * primitives below; the kernel builds `glob` / `grep` / `edit` from `exec` plus `readFile` /
5
5
  * `writeFile`.
6
6
  *
7
- * `@2` separates a device's **file system** from its **instance**: the file system
7
+ * A device separates its **file system** from its **instance**: the file system
8
8
  * (`createFileSystem`) lives until the device is deleted (`destroyFileSystem`); instances
9
9
  * (`create`) attach to it and come and go (`destroy` drops the instance and keeps the files).
10
10
  */
11
- import type { SandboxBackground, SandboxBrowse, SandboxBrowseScope, SandboxOperation, SandboxOperationRef, SandboxOperationScope, SandboxPermissionSupport, SandboxPreparation, SandboxPreparationScope } from "./sandbox-operation.js";
12
- /** Sandbox extension point ref. */
13
- export declare const SANDBOX_EXTENSION_POINT = "sandbox@2";
11
+ import type { SandboxBackground, SandboxBrowse, SandboxBrowseScope, SandboxOperation, SandboxOperationRef, SandboxOperationScope, SandboxPermissionSupport, SandboxPreparation, SandboxPreparationScope } from "./device-operation.js";
12
+ /** Device provider extension point ref. */
13
+ export declare const DEVICE_PROVIDER_EXTENSION_POINT = "device-provider@1";
14
14
  /** The roots inside the sandbox the model may access. */
15
15
  export declare const SANDBOX_ROOTS: readonly ["/workspace", "/skills", "/tmp"];
16
16
  /**
@@ -122,13 +122,67 @@ export declare class FileSystemGoneError extends Error {
122
122
  /** Duck-typed check (not instanceof), so a plugin bundling another plugin-sdk copy still matches. */
123
123
  export declare function isFileSystemGoneError(e: unknown): e is FileSystemGoneError;
124
124
  /**
125
- * A holder tag (`exec` argument `tag`, {@link SandboxProvider.killTagged}): the kernel passes its
125
+ * A holder tag (`exec` argument `tag`, {@link DeviceProvider.killTagged}): the kernel passes its
126
126
  * lease tokens (UUIDs). Providers check tags against it before putting them in a command line or a
127
127
  * kill pattern.
128
128
  */
129
129
  export declare const SANDBOX_TAG_RE: RegExp;
130
+ /** Text in English with an optional Chinese translation (what a person reads). */
131
+ export interface DeviceText {
132
+ en: string;
133
+ zh?: string;
134
+ }
135
+ /** The device a provider answers about: the kernel's device id, its org and the instance, if any. */
136
+ export interface DeviceRef {
137
+ deviceId: string;
138
+ orgId: string;
139
+ /** The current instance, or null when the device has none. */
140
+ handle: SandboxHandle | null;
141
+ }
142
+ /** One limit line of a {@link DeviceReport} (shown as is; the provider enforces it). */
143
+ export interface DeviceReportLimit {
144
+ label: DeviceText;
145
+ value: string;
146
+ }
147
+ /**
148
+ * What a provider tells about a device ({@link DeviceProvider.report}): shown to people, never
149
+ * used for enforcement. `revision` changes whenever the rest changes; `home` is the owner's home
150
+ * directory (absolute) or null; `reset` says whether the provider can reset the device's files.
151
+ */
152
+ export interface DeviceReport {
153
+ revision: string;
154
+ description: DeviceText;
155
+ home: string | null;
156
+ limits: DeviceReportLimit[];
157
+ reset: boolean;
158
+ }
159
+ /** Size limits {@link parseDeviceReport} enforces. */
160
+ export declare const DEVICE_REPORT_LIMITS: Readonly<{
161
+ revisionChars: 128;
162
+ descriptionChars: 300;
163
+ limits: 8;
164
+ limitLabelChars: 60;
165
+ limitValueChars: 60;
166
+ homeChars: 4096;
167
+ }>;
168
+ /** Checks a provider's report; throws `TypeError` on any other shape, returns a clean copy. */
169
+ export declare function parseDeviceReport(value: unknown): DeviceReport;
170
+ /**
171
+ * The provider refuses a project directory (`projects` operations: it lies where the provider
172
+ * will not serve, for example another connection's directory). `reason` is shown to the person.
173
+ * The kernel answers it as `device.project_refused` (422).
174
+ */
175
+ export declare class ProjectPathRefusedError extends Error {
176
+ readonly projectPathRefused: true;
177
+ readonly reason: DeviceText;
178
+ constructor(reason: DeviceText, opts?: {
179
+ cause?: unknown;
180
+ });
181
+ }
182
+ /** Duck-typed check (not instanceof), so a plugin bundling another plugin-sdk copy still matches. */
183
+ export declare function isProjectPathRefusedError(e: unknown): e is ProjectPathRefusedError;
130
184
  /**
131
- * The `sandbox@2` implementation (provided by a sandbox plugin such as Docker or E2B).
185
+ * The `device-provider@1` implementation (provided by a sandbox plugin such as Docker or E2B).
132
186
  *
133
187
  * **File systems and instances.** `createFileSystem` makes a device's files; they live until
134
188
  * `destroyFileSystem` (the device is deleted). `create` makes an instance attached to an
@@ -168,7 +222,7 @@ export declare const SANDBOX_TAG_RE: RegExp;
168
222
  * methods must be safe to call concurrently. Each `exec` labels its command with its `tag`, and an
169
223
  * aborted `exec` kills only its own command.
170
224
  */
171
- export interface SandboxProvider {
225
+ export interface DeviceProvider {
172
226
  /** Runtime permission support for this instance; does not grant consent or provision an instance. */
173
227
  permissionSupport?(h: SandboxHandle, signal: AbortSignal): Promise<SandboxPermissionSupport>;
174
228
  /**
@@ -190,6 +244,17 @@ export interface SandboxProvider {
190
244
  background?: SandboxBackground;
191
245
  /** `exec` / `readFile` / `writeFile` / `stat` may run concurrently on one instance (required). */
192
246
  readonly concurrentExec: true;
247
+ /**
248
+ * Declares that the provider enforces `limits.network` allowlists (required, always `true`):
249
+ * a provider that cannot restrict outbound hosts does not implement `device-provider@1`.
250
+ */
251
+ readonly networkAllowlist: true;
252
+ /**
253
+ * What the provider tells about the device: a description, the owner's home, limits and whether
254
+ * files can be reset ({@link DeviceReport}). Shown to people only; the answer passes
255
+ * {@link parseDeviceReport}. Must respond to `signal`.
256
+ */
257
+ report(device: DeviceRef, signal: AbortSignal): Promise<DeviceReport>;
193
258
  /**
194
259
  * Whether the provider isolates the sessions of one device from each other inside the
195
260
  * instance (a declared capability; absent means false).
@@ -198,7 +263,7 @@ export interface SandboxProvider {
198
263
  /**
199
264
  * Where `create`-time limits are fixed: `instance` (absent; Docker: a new instance applies new
200
265
  * limits) or `fileSystem` (E2B: the instance is the file system, so only a file reset applies
201
- * them without {@link SandboxProvider.update}).
266
+ * them without {@link DeviceProvider.update}).
202
267
  */
203
268
  readonly limitsApplyAt?: "instance" | "fileSystem";
204
269
  /**
@@ -256,7 +321,7 @@ export interface SandboxProvider {
256
321
  * spawned that did not start their own session). The kernel calls it only when no other holder
257
322
  * can be running commands (an instance just resumed from `suspended`, or under the exclusive
258
323
  * lease), never while another session may be; to clean up after one crashed holder it uses
259
- * {@link SandboxProvider.killTagged}. Processes a command put in the background in their own
324
+ * {@link DeviceProvider.killTagged}. Processes a command put in the background in their own
260
325
  * session are not guaranteed to be killed.
261
326
  */
262
327
  killAll(h: SandboxHandle, signal: AbortSignal): Promise<void>;
@@ -281,7 +346,7 @@ export interface SandboxProvider {
281
346
  signal: AbortSignal;
282
347
  /**
283
348
  * The holder's tag ({@link SANDBOX_TAG_RE}); label the command with it so
284
- * {@link SandboxProvider.killTagged} can find it.
349
+ * {@link DeviceProvider.killTagged} can find it.
285
350
  */
286
351
  tag: string;
287
352
  /** Who runs the command; informational in phase 1 (record it, do not act on it). */
@@ -313,7 +378,7 @@ export interface SandboxProvider {
313
378
  * path does not exist and the device could reach it; a path it cannot reach throws (a policy
314
379
  * refusal), as does a path that is a file or a directory that cannot be read.
315
380
  *
316
- * Optional: a provider without it (or without {@link SandboxProvider.scan}) offers no projects,
381
+ * Optional: a provider without it (or without {@link DeviceProvider.scan}) offers no projects,
317
382
  * and its conversations stay in free mode.
318
383
  */
319
384
  list?(h: SandboxHandle, path: string, opts: {
@@ -327,7 +392,8 @@ export interface SandboxProvider {
327
392
  truncated: boolean;
328
393
  } | null>;
329
394
  /**
330
- * Looks for project-like directories, read as for {@link SandboxProvider.list}. Every provider traverses the same way:
395
+ * Looks for project-like directories, read as for {@link DeviceProvider.list}. Every provider
396
+ * traverses the same way:
331
397
  *
332
398
  * - Candidates are `base` itself and the directories at most {@link MAX_DEVICE_SCAN_DEPTH}
333
399
  * levels below it that hold a `.git` entry (directory or file) or an `AGENTS.md` file.
@@ -360,15 +426,15 @@ export interface SandboxProvider {
360
426
  }
361
427
  /** The longest project name, in UTF-16 code units. */
362
428
  export declare const MAX_DEVICE_PROJECT_NAME_LENGTH = 64;
363
- /** The most candidates a `scan` answers ({@link SandboxProvider.scan}). */
429
+ /** The most candidates a `scan` answers ({@link DeviceProvider.scan}). */
364
430
  export declare const MAX_DEVICE_SCAN_RESULTS = 50;
365
431
  /**
366
- * Directory names a `scan` never enters, at any depth ({@link SandboxProvider.scan}): dependency
432
+ * Directory names a `scan` never enters, at any depth ({@link DeviceProvider.scan}): dependency
367
433
  * trees, not projects. Every provider skips exactly these.
368
434
  */
369
435
  export declare const DEVICE_SCAN_SKIPPED_DIRS: readonly string[];
370
436
  /**
371
- * Directory names a `scan` does not enter directly under its `base` ({@link SandboxProvider.scan}):
437
+ * Directory names a `scan` does not enter directly under its `base` ({@link DeviceProvider.scan}):
372
438
  * the owner's macOS `Library` (app data, huge, partly privacy-protected) is not where projects
373
439
  * live. Every provider skips exactly these.
374
440
  */
@@ -377,7 +443,7 @@ export declare const DEVICE_SCAN_SKIPPED_BASE_DIRS: readonly string[];
377
443
  export declare const MAX_DEVICE_SCAN_DEPTH = 2;
378
444
  /**
379
445
  * The most directories one `scan` visits (reads the entries of), its `base` included
380
- * ({@link SandboxProvider.scan}): breadth-first, each level in code-unit order of path.
446
+ * ({@link DeviceProvider.scan}): breadth-first, each level in code-unit order of path.
381
447
  */
382
448
  export declare const MAX_DEVICE_SCAN_DIRS = 500;
383
449
  /**
@@ -1,15 +1,15 @@
1
1
  /**
2
- * Sandbox contract `sandbox@2`: a single-select, brokered extension point (extensions may not
3
- * `requires` it; the kernel's `SandboxService` consumes it). The provider implements only the
2
+ * Device provider contract `device-provider@1`: a multi, brokered, org-scoped extension point
3
+ * (extensions may not `requires` it; the kernel's `SandboxService` consumes it). The provider implements only the
4
4
  * primitives below; the kernel builds `glob` / `grep` / `edit` from `exec` plus `readFile` /
5
5
  * `writeFile`.
6
6
  *
7
- * `@2` separates a device's **file system** from its **instance**: the file system
7
+ * A device separates its **file system** from its **instance**: the file system
8
8
  * (`createFileSystem`) lives until the device is deleted (`destroyFileSystem`); instances
9
9
  * (`create`) attach to it and come and go (`destroy` drops the instance and keeps the files).
10
10
  */
11
- /** Sandbox extension point ref. */
12
- export const SANDBOX_EXTENSION_POINT = "sandbox@2";
11
+ /** Device provider extension point ref. */
12
+ export const DEVICE_PROVIDER_EXTENSION_POINT = "device-provider@1";
13
13
  /** The roots inside the sandbox the model may access. */
14
14
  export const SANDBOX_ROOTS = ["/workspace", "/skills", "/tmp"];
15
15
  const MAX_PATH_LENGTH = 4096;
@@ -61,24 +61,112 @@ export function isFileSystemGoneError(e) {
61
61
  e.fileSystemGone === true);
62
62
  }
63
63
  /**
64
- * A holder tag (`exec` argument `tag`, {@link SandboxProvider.killTagged}): the kernel passes its
64
+ * A holder tag (`exec` argument `tag`, {@link DeviceProvider.killTagged}): the kernel passes its
65
65
  * lease tokens (UUIDs). Providers check tags against it before putting them in a command line or a
66
66
  * kill pattern.
67
67
  */
68
68
  export const SANDBOX_TAG_RE = /^[a-z0-9-]{1,64}$/;
69
+ /** Size limits {@link parseDeviceReport} enforces. */
70
+ export const DEVICE_REPORT_LIMITS = Object.freeze({
71
+ revisionChars: 128,
72
+ descriptionChars: 300,
73
+ limits: 8,
74
+ limitLabelChars: 60,
75
+ limitValueChars: 60,
76
+ homeChars: 4096,
77
+ });
78
+ const isRecord = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
79
+ function exactKeys(v, keys, what) {
80
+ for (const k of Object.keys(v)) {
81
+ if (!keys.includes(k))
82
+ throw new TypeError(`${what}: unknown key ${k}`);
83
+ }
84
+ }
85
+ function parseText(v, max, what) {
86
+ if (!isRecord(v))
87
+ throw new TypeError(`${what} must be an object`);
88
+ exactKeys(v, ["en", "zh"], what);
89
+ const { en, zh } = v;
90
+ if (typeof en !== "string" || en === "" || en.length > max) {
91
+ throw new TypeError(`${what}.en must be a non-empty string of at most ${max} characters`);
92
+ }
93
+ if (zh === undefined)
94
+ return { en };
95
+ if (typeof zh !== "string" || zh === "" || zh.length > max) {
96
+ throw new TypeError(`${what}.zh must be a non-empty string of at most ${max} characters`);
97
+ }
98
+ return { en, zh };
99
+ }
100
+ /** Checks a provider's report; throws `TypeError` on any other shape, returns a clean copy. */
101
+ export function parseDeviceReport(value) {
102
+ const L = DEVICE_REPORT_LIMITS;
103
+ if (!isRecord(value))
104
+ throw new TypeError("device report must be an object");
105
+ exactKeys(value, ["revision", "description", "home", "limits", "reset"], "device report");
106
+ const { revision, home, limits, reset } = value;
107
+ if (typeof revision !== "string" || revision === "" || revision.length > L.revisionChars) {
108
+ throw new TypeError(`device report revision must be a non-empty string of at most ${L.revisionChars} characters`);
109
+ }
110
+ const description = parseText(value.description, L.descriptionChars, "device report description");
111
+ if (home !== null) {
112
+ if (typeof home !== "string" || home.length > L.homeChars) {
113
+ throw new TypeError("device report home must be an absolute path or null");
114
+ }
115
+ const errors = validateSandboxPathShape(home);
116
+ if (errors.length > 0)
117
+ throw new TypeError(`device report home: ${errors.join("; ")}`);
118
+ }
119
+ if (!Array.isArray(limits) || limits.length > L.limits) {
120
+ throw new TypeError(`device report limits must be an array of at most ${L.limits} entries`);
121
+ }
122
+ const parsedLimits = limits.map((raw, i) => {
123
+ const what = `device report limits[${i}]`;
124
+ if (!isRecord(raw))
125
+ throw new TypeError(`${what} must be an object`);
126
+ exactKeys(raw, ["label", "value"], what);
127
+ if (typeof raw.value !== "string" || raw.value === "" || raw.value.length > L.limitValueChars) {
128
+ throw new TypeError(`${what}.value must be a non-empty string of at most ${L.limitValueChars} characters`);
129
+ }
130
+ return { label: parseText(raw.label, L.limitLabelChars, `${what}.label`), value: raw.value };
131
+ });
132
+ if (typeof reset !== "boolean")
133
+ throw new TypeError("device report reset must be a boolean");
134
+ return { revision, description, home, limits: parsedLimits, reset };
135
+ }
136
+ /**
137
+ * The provider refuses a project directory (`projects` operations: it lies where the provider
138
+ * will not serve, for example another connection's directory). `reason` is shown to the person.
139
+ * The kernel answers it as `device.project_refused` (422).
140
+ */
141
+ export class ProjectPathRefusedError extends Error {
142
+ projectPathRefused = true;
143
+ reason;
144
+ constructor(reason, opts) {
145
+ super(reason.en, opts && "cause" in opts ? { cause: opts.cause } : undefined);
146
+ this.name = "ProjectPathRefusedError";
147
+ this.reason = reason;
148
+ }
149
+ }
150
+ /** Duck-typed check (not instanceof), so a plugin bundling another plugin-sdk copy still matches. */
151
+ export function isProjectPathRefusedError(e) {
152
+ return (e instanceof Error &&
153
+ e.name === "ProjectPathRefusedError" &&
154
+ e.projectPathRefused === true &&
155
+ isRecord(e.reason));
156
+ }
69
157
  // biome-ignore lint/suspicious/noControlCharactersInRegex: control characters are exactly what must be blocked
70
158
  const CONTROL = /[\u0000-\u001f\u007f]/;
71
159
  /** The longest project name, in UTF-16 code units. */
72
160
  export const MAX_DEVICE_PROJECT_NAME_LENGTH = 64;
73
- /** The most candidates a `scan` answers ({@link SandboxProvider.scan}). */
161
+ /** The most candidates a `scan` answers ({@link DeviceProvider.scan}). */
74
162
  export const MAX_DEVICE_SCAN_RESULTS = 50;
75
163
  /**
76
- * Directory names a `scan` never enters, at any depth ({@link SandboxProvider.scan}): dependency
164
+ * Directory names a `scan` never enters, at any depth ({@link DeviceProvider.scan}): dependency
77
165
  * trees, not projects. Every provider skips exactly these.
78
166
  */
79
167
  export const DEVICE_SCAN_SKIPPED_DIRS = Object.freeze(["node_modules"]);
80
168
  /**
81
- * Directory names a `scan` does not enter directly under its `base` ({@link SandboxProvider.scan}):
169
+ * Directory names a `scan` does not enter directly under its `base` ({@link DeviceProvider.scan}):
82
170
  * the owner's macOS `Library` (app data, huge, partly privacy-protected) is not where projects
83
171
  * live. Every provider skips exactly these.
84
172
  */
@@ -87,7 +175,7 @@ export const DEVICE_SCAN_SKIPPED_BASE_DIRS = Object.freeze(["Library"]);
87
175
  export const MAX_DEVICE_SCAN_DEPTH = 2;
88
176
  /**
89
177
  * The most directories one `scan` visits (reads the entries of), its `base` included
90
- * ({@link SandboxProvider.scan}): breadth-first, each level in code-unit order of path.
178
+ * ({@link DeviceProvider.scan}): breadth-first, each level in code-unit order of path.
91
179
  */
92
180
  export const MAX_DEVICE_SCAN_DIRS = 500;
93
181
  /**
@@ -8,7 +8,7 @@ const info = (majors, description, cardinality, brokered = false, orgScoped = fa
8
8
  });
9
9
  /** The registered extension points. */
10
10
  export const EXTENSION_POINTS = {
11
- sandbox: info([2], "Runs a device's instance and keeps its files for agents' commands (Docker, E2B).", "single", true),
11
+ "device-provider": info([1], "Provides devices (an instance plus kept files) agents run commands in: containers, microVMs, connected machines.", "multi", true, true),
12
12
  "config-source": info([1], "Supplies deployment configuration from an external store such as Nacos.", "single"),
13
13
  "secret-store": info([1], "Stores and resolves secrets (connector credentials, secret config) outside the database.", "single", true),
14
14
  "object-store": info([1], "Stores files and artifacts in S3-compatible object storage, with presigned uploads.", "single", true),
package/dist/git-hosts.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { z } from "zod";
2
- import { validateAllowHost } from "./sandbox.js";
2
+ import { validateAllowHost } from "./device-provider.js";
3
3
  /**
4
4
  * The git source of a connector: the git hosts a connector's credential may be used for, and the
5
5
  * HTTP basic username to present for each (spec 2026-11-12-sandbox-git-credentials §6.1). Pure
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- export declare const SDK_VERSION = "0.1.0-rc.50";
1
+ export declare const SDK_VERSION = "0.1.0-rc.52";
2
2
  export * from "./agent-template.js";
3
3
  export * from "./avatar-presets.js";
4
4
  export * from "./bootstrap.js";
@@ -13,7 +13,9 @@ export * from "./context.js";
13
13
  export * from "./ctx.js";
14
14
  export * from "./define-extension.js";
15
15
  export { DEVICE_DEFAULT_STATE_PATH, DEVICE_DENIED_SECRET_PATHS } from "./device-denied-paths.js";
16
+ export * from "./device-operation.js";
16
17
  export * from "./device-protocol.js";
18
+ export * from "./device-provider.js";
17
19
  export * from "./directory.js";
18
20
  export * from "./extension-point.js";
19
21
  export * from "./file-preview.js";
@@ -31,8 +33,6 @@ export * from "./permissions.js";
31
33
  export * from "./plugin-manifest.js";
32
34
  export * from "./plugin-package.js";
33
35
  export * from "./push.js";
34
- export * from "./sandbox.js";
35
- export * from "./sandbox-operation.js";
36
36
  export { SANDBOX_RUNTIME_SOURCE } from "./sandbox-runtime-source.js";
37
37
  export { isSandboxHomeWriteDenied, isSandboxMoveDenied, isSandboxWriteDenied, SANDBOX_GIT_ALLOWED_DIRECTORIES, SANDBOX_GIT_ALLOWED_FILES, SANDBOX_GIT_DENIED_INTERNALS, SANDBOX_HOME_WRITE_DENIES, SANDBOX_MANDATORY_WRITE_DENIES, SANDBOX_PROTECTED_PATH_NAMES, SANDBOX_RESERVED_NAME_PREFIX, SANDBOX_RUNTIME_DIRECTORIES, SANDBOX_SYSTEM_WRITE_DENIES, sandboxRuntimeDirectoryOf, } from "./sandbox-write-denies.js";
38
38
  export * from "./secret.js";
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- export const SDK_VERSION = "0.1.0-rc.50";
1
+ export const SDK_VERSION = "0.1.0-rc.52";
2
2
  export * from "./agent-template.js";
3
3
  export * from "./avatar-presets.js";
4
4
  export * from "./bootstrap.js";
@@ -13,7 +13,9 @@ export * from "./context.js";
13
13
  export * from "./ctx.js";
14
14
  export * from "./define-extension.js";
15
15
  export { DEVICE_DEFAULT_STATE_PATH, DEVICE_DENIED_SECRET_PATHS } from "./device-denied-paths.js";
16
+ export * from "./device-operation.js";
16
17
  export * from "./device-protocol.js";
18
+ export * from "./device-provider.js";
17
19
  export * from "./directory.js";
18
20
  export * from "./extension-point.js";
19
21
  export * from "./file-preview.js";
@@ -31,8 +33,6 @@ export * from "./permissions.js";
31
33
  export * from "./plugin-manifest.js";
32
34
  export * from "./plugin-package.js";
33
35
  export * from "./push.js";
34
- export * from "./sandbox.js";
35
- export * from "./sandbox-operation.js";
36
36
  export { SANDBOX_RUNTIME_SOURCE } from "./sandbox-runtime-source.js";
37
37
  export { isSandboxHomeWriteDenied, isSandboxMoveDenied, isSandboxWriteDenied, SANDBOX_GIT_ALLOWED_DIRECTORIES, SANDBOX_GIT_ALLOWED_FILES, SANDBOX_GIT_DENIED_INTERNALS, SANDBOX_HOME_WRITE_DENIES, SANDBOX_MANDATORY_WRITE_DENIES, SANDBOX_PROTECTED_PATH_NAMES, SANDBOX_RESERVED_NAME_PREFIX, SANDBOX_RUNTIME_DIRECTORIES, SANDBOX_SYSTEM_WRITE_DENIES, sandboxRuntimeDirectoryOf, } from "./sandbox-write-denies.js";
38
38
  export * from "./secret.js";
@@ -1,4 +1,4 @@
1
- import { DEVICE_SCAN_SKIPPED_BASE_DIRS, DEVICE_SCAN_SKIPPED_DIRS, MAX_DEVICE_PROJECT_NAME_LENGTH, MAX_DEVICE_SCAN_DEPTH, MAX_DEVICE_SCAN_DIRS, MAX_DEVICE_SCAN_RESULTS, } from "./sandbox.js";
1
+ import { DEVICE_SCAN_SKIPPED_BASE_DIRS, DEVICE_SCAN_SKIPPED_DIRS, MAX_DEVICE_PROJECT_NAME_LENGTH, MAX_DEVICE_SCAN_DEPTH, MAX_DEVICE_SCAN_DIRS, MAX_DEVICE_SCAN_RESULTS, } from "./device-provider.js";
2
2
  import { SANDBOX_WRITE_POLICY_PYTHON } from "./sandbox-write-denies.js";
3
3
  /**
4
4
  * Private Python 3 transport: one JSON request on stdin, one result/error on stdout.
@@ -39,6 +39,14 @@ export interface SetupGuideCheckLine {
39
39
  /** Index of the innermost enclosing section, or null. */
40
40
  section: number | null;
41
41
  }
42
+ /** A `::shell-action` line of a document. */
43
+ export interface SetupGuideShellActionLine {
44
+ action: string;
45
+ label: string;
46
+ line: number;
47
+ /** Index of the innermost enclosing section, or null. */
48
+ section: number | null;
49
+ }
42
50
  /** A fenced code block of a document. */
43
51
  export interface SetupGuideCodeBlock {
44
52
  /** The info string's first word; empty when missing. */
@@ -55,11 +63,12 @@ export interface ParsedSetupGuide {
55
63
  title: string | null;
56
64
  sections: SetupGuideSection[];
57
65
  checks: SetupGuideCheckLine[];
66
+ shellActions: SetupGuideShellActionLine[];
58
67
  codeBlocks: SetupGuideCodeBlock[];
59
68
  /** Structural problems (place independent: modes, audiences and variables are not judged). */
60
69
  issues: SetupGuideParseIssue[];
61
70
  }
62
- type LineKind = "text" | "fence" | "section-open" | "section-close" | "check";
71
+ type LineKind = "text" | "fence" | "section-open" | "section-close" | "check" | "shell-action";
63
72
  /** @internal The scanner's result. */
64
73
  export interface GuideScan {
65
74
  lines: string[];
@@ -68,8 +77,11 @@ export interface GuideScan {
68
77
  stacks: number[][];
69
78
  /** Check index of each check line. */
70
79
  checkAt: Map<number, number>;
80
+ /** Shell action index of each shell action line. */
81
+ shellActionAt: Map<number, number>;
71
82
  sections: SetupGuideSection[];
72
83
  checks: SetupGuideCheckLine[];
84
+ shellActions: SetupGuideShellActionLine[];
73
85
  issues: SetupGuideParseIssue[];
74
86
  }
75
87
  /** LF line endings. */
@@ -87,6 +99,8 @@ export declare function preparedGuideText(scan: GuideScan, include: (i: number)
87
99
  export declare function parseGuideMarkdown(text: string): Root;
88
100
  /** @internal The check index of a marker heading, or undefined. */
89
101
  export declare function checkMarkerIndex(node: Nodes): number | undefined;
102
+ /** @internal The shell action index of a marker heading, or undefined. */
103
+ export declare function shellActionMarkerIndex(node: Nodes): number | undefined;
90
104
  /** @internal The plain text of a node (values and image alts, joined). */
91
105
  export declare function nodeText(node: Nodes): string;
92
106
  /** @internal Visits nodes depth first in document order, with their depth (root's children = 1). */
@@ -6,6 +6,7 @@ import { SETUP_CHECK_ID_RE } from "./setup-check.js";
6
6
  const LIMITS = {
7
7
  codeBlocks: 24,
8
8
  checks: 16,
9
+ shellActions: 4,
9
10
  sections: 16,
10
11
  titleChars: 100,
11
12
  checkLabelChars: 80,
@@ -24,12 +25,15 @@ const FENCE_OPEN_RE = /^( {0,3})(`{3,}|~{3,})(.*)$/;
24
25
  const FENCE_CLOSE_RE = /^ {0,3}(`{3,}|~{3,})[ \t]*$/;
25
26
  const SECTION_RE = /^(mode|audience)[ \t]+(\S+)$/;
26
27
  const CHECK_LINE_RE = /^::check[ \t]+(\S+)(?:[ \t]+(.*?))?[ \t]*$/;
28
+ const SHELL_ACTION_LINE_RE = /^::shell-action[ \t]+(\S+)(?:[ \t]+(.*?))?[ \t]*$/;
27
29
  const FENCE_TITLE_RE = /^title="([^"]*)"$/;
28
30
  /** Variable sentinel: `<n>`, n indexing the occurrences. */
29
31
  export const SENTINEL_RE = /(\d+)/g;
30
32
  /** The same sentinel percent-encoded, as micromark leaves it in a link destination. */
31
33
  export const ENCODED_SENTINEL_RE = /%EE%80%80(\d+)%EE%80%81/gi;
32
34
  const CHECK_MARKER_RE = /^(\d+)$/;
35
+ // a shell action line is a marker heading of its own: a different private-use pair than a check's
36
+ const SHELL_ACTION_MARKER_RE = /^(\d+)$/;
33
37
  /** LF line endings. */
34
38
  export function normalizeGuideSource(source) {
35
39
  return source.replace(/\r\n?/g, "\n");
@@ -40,8 +44,10 @@ export function scanGuide(source) {
40
44
  const kinds = [];
41
45
  const stacks = [];
42
46
  const checkAt = new Map();
47
+ const shellActionAt = new Map();
43
48
  const sections = [];
44
49
  const checks = [];
50
+ const shellActions = [];
45
51
  const issues = [];
46
52
  const err = (line, message) => issues.push({ level: "error", line, message });
47
53
  const stack = [];
@@ -131,13 +137,35 @@ export function scanGuide(source) {
131
137
  kinds.push("check");
132
138
  return;
133
139
  }
140
+ if (/^::shell-action(?:\s|$)/.test(text)) {
141
+ const m = SHELL_ACTION_LINE_RE.exec(text);
142
+ if (m === null) {
143
+ err(line, "a shell action line is `::shell-action <action> <label>`");
144
+ kinds.push("text");
145
+ return;
146
+ }
147
+ const action = m[1];
148
+ const label = (m[2] ?? "").trim();
149
+ if (label === "") {
150
+ err(line, `shell action ${action} needs a label: \`::shell-action ${action} <label>\``);
151
+ }
152
+ else if ([...label].length > LIMITS.checkLabelChars) {
153
+ err(line, `the label of shell action ${action} is longer than ${LIMITS.checkLabelChars} characters`);
154
+ }
155
+ if (text.includes("{{"))
156
+ err(line, "directive lines hold no variables (shell action labels are plain text)");
157
+ shellActions.push({ action, label, line, section: stack.at(-1) ?? null });
158
+ shellActionAt.set(i, shellActions.length - 1);
159
+ kinds.push("shell-action");
160
+ return;
161
+ }
134
162
  kinds.push("text");
135
163
  });
136
164
  for (const open of stack) {
137
165
  const s = sections[open];
138
166
  err(s.line, `the section "::: ${s.type} ${s.value}" opened at line ${s.line} is not closed`);
139
167
  }
140
- return { lines, kinds, stacks, checkAt, sections, checks, issues };
168
+ return { lines, kinds, stacks, checkAt, shellActionAt, sections, checks, shellActions, issues };
141
169
  }
142
170
  /** @internal Whether line `i` is in the sections of `mode` and `audience`. */
143
171
  export function lineSelected(scan, i, mode, audience) {
@@ -162,6 +190,8 @@ export function preparedGuideText(scan, include, subst = (t) => t) {
162
190
  return "";
163
191
  if (kind === "check")
164
192
  return `###### ${scan.checkAt.get(i)}`;
193
+ if (kind === "shell-action")
194
+ return `###### ${scan.shellActionAt.get(i)}`;
165
195
  return subst(text, i);
166
196
  })
167
197
  .join("\n");
@@ -180,6 +210,16 @@ export function checkMarkerIndex(node) {
180
210
  const m = CHECK_MARKER_RE.exec(t.value);
181
211
  return m === null ? undefined : Number(m[1]);
182
212
  }
213
+ /** @internal The shell action index of a marker heading, or undefined. */
214
+ export function shellActionMarkerIndex(node) {
215
+ if (node.type !== "heading" || node.depth !== 6 || node.children.length !== 1)
216
+ return undefined;
217
+ const t = node.children[0];
218
+ if (t?.type !== "text")
219
+ return undefined;
220
+ const m = SHELL_ACTION_MARKER_RE.exec(t.value);
221
+ return m === null ? undefined : Number(m[1]);
222
+ }
183
223
  /** @internal The plain text of a node (values and image alts, joined). */
184
224
  export function nodeText(node) {
185
225
  if ("value" in node)
@@ -266,6 +306,8 @@ export function analyzeSetupGuide(source) {
266
306
  if (node.type === "heading") {
267
307
  if (checkMarkerIndex(node) !== undefined)
268
308
  return;
309
+ if (shellActionMarkerIndex(node) !== undefined)
310
+ return;
269
311
  if (node === first && title !== null)
270
312
  return;
271
313
  if (node.depth === 1) {
@@ -321,6 +363,17 @@ export function analyzeSetupGuide(source) {
321
363
  err(c.line, `check ${c.id} is inside raw HTML and would not show; end the HTML with a blank line before the check line`);
322
364
  }
323
365
  });
366
+ const placedActions = new Set();
367
+ for (const n of tree.children) {
368
+ const a = shellActionMarkerIndex(n);
369
+ if (a !== undefined)
370
+ placedActions.add(a);
371
+ }
372
+ scan.shellActions.forEach((a, i) => {
373
+ if (!placedActions.has(i)) {
374
+ err(a.line, `shell action ${a.action} is inside raw HTML and would not show; end the HTML with a blank line before the line`);
375
+ }
376
+ });
324
377
  if (deepest > LIMITS.depth)
325
378
  err(deepLine, `content is nested deeper than ${LIMITS.depth} levels`);
326
379
  if (codeBlocks.length > LIMITS.codeBlocks) {
@@ -329,12 +382,22 @@ export function analyzeSetupGuide(source) {
329
382
  if (scan.checks.length > LIMITS.checks) {
330
383
  err(undefined, `the document has ${scan.checks.length} check lines; at most ${LIMITS.checks}`);
331
384
  }
385
+ if (scan.shellActions.length > LIMITS.shellActions) {
386
+ err(undefined, `the document has ${scan.shellActions.length} shell action lines; at most ${LIMITS.shellActions}`);
387
+ }
332
388
  if (scan.sections.length > LIMITS.sections) {
333
389
  err(undefined, `the document has ${scan.sections.length} sections; at most ${LIMITS.sections}`);
334
390
  }
335
391
  issues.sort((a, b) => (a.line ?? 0) - (b.line ?? 0));
336
392
  return {
337
- parsed: { title, sections: scan.sections, checks: scan.checks, codeBlocks, issues },
393
+ parsed: {
394
+ title,
395
+ sections: scan.sections,
396
+ checks: scan.checks,
397
+ shellActions: scan.shellActions,
398
+ codeBlocks,
399
+ issues,
400
+ },
338
401
  scan,
339
402
  tree,
340
403
  uses,
@@ -1,5 +1,6 @@
1
- import { type SetupGuideAudience, type SetupGuidePlace } from "./setup-guide.js";
2
- /** A block of a rendered guide: sanitized Markdown, a code block, or a check row. */
1
+ import { type SetupGuideAudience, type SetupGuidePlace, type SetupGuideShellAction } from "./setup-guide.js";
2
+ /** A block of a rendered guide: sanitized Markdown, a code block, a check row, or a
3
+ * shell action button. */
3
4
  export type SetupGuideBlock = {
4
5
  kind: "markdown";
5
6
  text: string;
@@ -12,6 +13,10 @@ export type SetupGuideBlock = {
12
13
  kind: "check";
13
14
  id: string;
14
15
  label: string;
16
+ } | {
17
+ kind: "shell-action";
18
+ action: SetupGuideShellAction;
19
+ label: string;
15
20
  };
16
21
  /** A guide document rendered for one mode, audience and set of values. */
17
22
  export interface RenderedSetupGuideDoc {
@@ -1,7 +1,7 @@
1
1
  import { gfmToMarkdown } from "mdast-util-gfm";
2
2
  import { toMarkdown } from "mdast-util-to-markdown";
3
3
  import { SETUP_GUIDE_LIMITS, SETUP_GUIDE_PLACE_INFO, } from "./setup-guide.js";
4
- import { checkMarkerIndex, fenceTitle, lineSelected, nodeText, normalizeGuideSource, parseGuideMarkdown, preparedGuideText, revertSentinels, SETUP_GUIDE_VARIABLE_RE, scanGuide, } from "./setup-guide-parse.js";
4
+ import { checkMarkerIndex, fenceTitle, lineSelected, nodeText, normalizeGuideSource, parseGuideMarkdown, preparedGuideText, revertSentinels, SETUP_GUIDE_VARIABLE_RE, scanGuide, shellActionMarkerIndex, } from "./setup-guide-parse.js";
5
5
  // biome-ignore lint/suspicious/noControlCharactersInRegex: control characters are what is replaced
6
6
  const CONTROL_RE = /[\u0000-\u001f\u007f-\u009f\u2028\u2029]/g;
7
7
  /** What `JSON.stringify` leaves raw but a YAML parser may refuse or read as a line break. */
@@ -321,6 +321,22 @@ export function renderSetupGuide(source, input) {
321
321
  }
322
322
  continue;
323
323
  }
324
+ const a = shellActionMarkerIndex(node);
325
+ if (a !== undefined) {
326
+ const sa = scan.shellActions[a];
327
+ if (sa !== undefined) {
328
+ flush();
329
+ // the validator limits the action to the place's; a stored guide of another shape is skipped
330
+ if (info.shellActions.includes(sa.action)) {
331
+ blocks.push({
332
+ kind: "shell-action",
333
+ action: sa.action,
334
+ label: sa.label,
335
+ });
336
+ }
337
+ }
338
+ continue;
339
+ }
324
340
  if (node.type === "code") {
325
341
  flush();
326
342
  const lang = revert(node.lang ?? "");
@@ -2,9 +2,10 @@
2
2
  * Where a guide is shown. `channel-connection`: "New channel" and the channel detail page;
3
3
  * `connector-template`: the pages of a connector template and the connectors made from it;
4
4
  * `extension-deployment`: the super admin's page of the extension, whose checks verify the
5
- * platform deployment config (a push provider's credentials).
5
+ * platform deployment config (a push provider's credentials); `device-connection`: the guide of a
6
+ * device provider's connection (how a member connects a machine through it).
6
7
  */
7
- export declare const SETUP_GUIDE_PLACES: readonly ["channel-connection", "connector-template", "extension-deployment"];
8
+ export declare const SETUP_GUIDE_PLACES: readonly ["channel-connection", "connector-template", "extension-deployment", "device-connection"];
8
9
  export type SetupGuidePlace = (typeof SETUP_GUIDE_PLACES)[number];
9
10
  /** Who the rendered text is for: `admin` sets the integration up, `member` uses it. */
10
11
  export type SetupGuideAudience = "admin" | "member";
@@ -13,12 +14,22 @@ export type SetupGuideAudience = "admin" | "member";
13
14
  * `text` values hold whatever a person typed (names), `token` values are ids and enum values.
14
15
  */
15
16
  export type SetupGuideVariableType = "url" | "text" | "token";
16
- /** What a place defines: its modes, audiences and variables, and whether its targets record acks. */
17
+ /**
18
+ * An action a guide's `::shell-action` line asks the native shell to run. `connect-this-machine`:
19
+ * connect the machine the page runs on as a device (the web shows the button only where the shell
20
+ * declares the capability).
21
+ */
22
+ export type SetupGuideShellAction = "connect-this-machine";
23
+ /**
24
+ * What a place defines: its modes, audiences and variables, whether its targets record acks, and
25
+ * the shell actions its guides may use.
26
+ */
17
27
  export interface SetupGuidePlaceInfo {
18
28
  modes: readonly string[];
19
29
  audiences: readonly SetupGuideAudience[];
20
30
  variables: Readonly<Record<string, SetupGuideVariableType>>;
21
31
  drift: boolean;
32
+ shellActions: readonly SetupGuideShellAction[];
22
33
  }
23
34
  /** The place registry. None of the variables is a secret. */
24
35
  export declare const SETUP_GUIDE_PLACE_INFO: Readonly<Record<SetupGuidePlace, SetupGuidePlaceInfo>>;
@@ -32,6 +43,8 @@ export declare const SETUP_GUIDE_LIMITS: {
32
43
  readonly codeBlocks: 24;
33
44
  /** Check lines per document. */
34
45
  readonly checks: 16;
46
+ /** Shell action lines per document. */
47
+ readonly shellActions: 4;
35
48
  /** Sections per document. */
36
49
  readonly sections: 16;
37
50
  /** Characters of the title and of a heading. */
@@ -15,12 +15,14 @@ import { analyzeSetupGuide, checkMarkerIndex, ENCODED_SENTINEL_RE, lineSelected,
15
15
  * Where a guide is shown. `channel-connection`: "New channel" and the channel detail page;
16
16
  * `connector-template`: the pages of a connector template and the connectors made from it;
17
17
  * `extension-deployment`: the super admin's page of the extension, whose checks verify the
18
- * platform deployment config (a push provider's credentials).
18
+ * platform deployment config (a push provider's credentials); `device-connection`: the guide of a
19
+ * device provider's connection (how a member connects a machine through it).
19
20
  */
20
21
  export const SETUP_GUIDE_PLACES = [
21
22
  "channel-connection",
22
23
  "connector-template",
23
24
  "extension-deployment",
25
+ "device-connection",
24
26
  ];
25
27
  const COMMON_VARIABLES = {
26
28
  publicUrl: "url",
@@ -41,6 +43,7 @@ export const SETUP_GUIDE_PLACE_INFO = {
41
43
  connectionName: "text",
42
44
  },
43
45
  drift: true,
46
+ shellActions: [],
44
47
  },
45
48
  "connector-template": {
46
49
  modes: [],
@@ -54,12 +57,21 @@ export const SETUP_GUIDE_PLACE_INFO = {
54
57
  connectorName: "text",
55
58
  },
56
59
  drift: true,
60
+ shellActions: [],
57
61
  },
58
62
  "extension-deployment": {
59
63
  modes: [],
60
64
  audiences: ["admin"],
61
65
  variables: { ...COMMON_VARIABLES, pluginName: "text" },
62
66
  drift: false,
67
+ shellActions: [],
68
+ },
69
+ "device-connection": {
70
+ modes: [],
71
+ audiences: ["member"],
72
+ variables: { publicUrl: "url", orgId: "token", orgName: "text", pluginName: "token" },
73
+ drift: false,
74
+ shellActions: ["connect-this-machine"],
63
75
  },
64
76
  };
65
77
  /** Limits of setup guides. */
@@ -72,6 +84,8 @@ export const SETUP_GUIDE_LIMITS = {
72
84
  codeBlocks: 24,
73
85
  /** Check lines per document. */
74
86
  checks: 16,
87
+ /** Shell action lines per document. */
88
+ shellActions: 4,
75
89
  /** Sections per document. */
76
90
  sections: 16,
77
91
  /** Characters of the title and of a heading. */
@@ -164,6 +178,14 @@ export function validateSetupGuide(input) {
164
178
  err(s.line, `audience "${s.value}" is not one of the audiences of place ${input.place}: ${info.audiences.join(", ")}`);
165
179
  }
166
180
  }
181
+ for (const a of parsed.shellActions) {
182
+ if (info.shellActions.length === 0) {
183
+ err(a.line, `shell actions are not allowed in place ${input.place}`);
184
+ }
185
+ else if (!info.shellActions.includes(a.action)) {
186
+ err(a.line, `unknown shell action "${a.action}" (known: ${info.shellActions.join(", ")})`);
187
+ }
188
+ }
167
189
  if (input.pluginChecks !== undefined) {
168
190
  for (const c of parsed.checks) {
169
191
  if (c.source === "plugin" && !input.pluginChecks.includes(c.id)) {
@@ -281,6 +303,13 @@ export function validateSetupGuide(input) {
281
303
  message: `${zhFile}: the checks differ from ${enFile}; both languages need the same check ids in the same sections`,
282
304
  });
283
305
  }
306
+ const act = (p) => JSON.stringify(p.shellActions.map((a) => [a.section, a.action]));
307
+ if (act(en) !== act(zh)) {
308
+ out.push({
309
+ level: "error",
310
+ message: `${zhFile}: the shell actions differ from ${enFile}; both languages need the same actions in the same sections`,
311
+ });
312
+ }
284
313
  if (en.codeBlocks.length !== zh.codeBlocks.length) {
285
314
  out.push({
286
315
  level: "error",
package/dist/skill.js CHANGED
@@ -23,9 +23,9 @@
23
23
  * `/skills/<name>@<digest>/` ({@link skillSandboxDir}, {@link skillDigest}).
24
24
  */
25
25
  import { createHash } from "node:crypto";
26
+ import { validateSandboxPath } from "./device-provider.js";
26
27
  import { readFrontmatter } from "./frontmatter.js";
27
28
  import { hasControlChars } from "./model.js";
28
- import { validateSandboxPath } from "./sandbox.js";
29
29
  import { argumentHintText, SKILL_ARGUMENT_NAME_RE } from "./skill-keys.js";
30
30
  /** Limits of a skill package. */
31
31
  export const SKILL_LIMITS = {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@capybara-hq/plugin-sdk",
3
- "version": "0.1.0-rc.50",
3
+ "version": "0.1.0-rc.52",
4
4
  "description": "Capybara plugin SDK: the types and pure functions plugins are written against",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
@@ -225,7 +225,8 @@
225
225
  "enum": [
226
226
  "channel-connection",
227
227
  "connector-template",
228
- "extension-deployment"
228
+ "extension-deployment",
229
+ "device-connection"
229
230
  ]
230
231
  },
231
232
  "template": {
@@ -1,15 +0,0 @@
1
- # Authoring: extension point sandbox
2
-
3
- <!-- generated:extension-point -->
4
- - Name: `sandbox` (a ref is `sandbox@<major>`)
5
- - Runs a device's instance and keeps its files for agents' commands (Docker, E2B).
6
- - Providers: one at a time
7
- - Enabled per org: no
8
- - Brokered by the platform: yes (extensions use it only through `ctx`)
9
- <!-- /generated -->
10
-
11
- Contract: SandboxProvider (`sandbox.ts`)
12
-
13
- The kernel accepts only `sandbox@2`. A device is one instance plus a file system that outlives it. Implement the file system (`createFileSystem`, `destroyFileSystem`, `destroyFileSystemByName`), the instance on it (`create`, which throws `FileSystemGoneError` when the file system is gone instead of making an empty one; `resume`, `suspend`; `destroy` and `destroyByName`, which drop the instance and keep the files), and the instance's `exec`, `readFile`, `writeFile`, `stat`, `killAll` and `killTagged` (`concurrentExec` is required: several conversations share one instance). Aborting a command must kill it. Locking, suspension timing and destruction are the kernel's job, not yours.
14
-
15
- See `extensions` for the rules every extension follows.