@capybara-hq/plugin-sdk 0.1.0-rc.7 → 0.1.0-rc.71

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 (146) hide show
  1. package/README.md +1 -1
  2. package/agent-docs/agent-templates.md +14 -2
  3. package/agent-docs/concepts.md +14 -5
  4. package/agent-docs/connector-templates.md +11 -3
  5. package/agent-docs/extension-points/channel.md +1 -1
  6. package/agent-docs/extension-points/context.md +15 -0
  7. package/agent-docs/extension-points/device-provider.md +15 -0
  8. package/agent-docs/extension-points/file-preview.md +3 -1
  9. package/agent-docs/extension-points/model-provider.md +3 -1
  10. package/agent-docs/extension-points/object-store.md +2 -0
  11. package/agent-docs/extension-points/push-provider.md +17 -0
  12. package/agent-docs/extensions.md +77 -4
  13. package/agent-docs/plugin-format.md +51 -12
  14. package/agent-docs/setup.md +54 -0
  15. package/dist/agent-template.d.ts +15 -6
  16. package/dist/agent-template.js +32 -13
  17. package/dist/avatar-presets.d.ts +8 -0
  18. package/dist/avatar-presets.js +17 -0
  19. package/dist/bootstrap.d.ts +109 -1
  20. package/dist/bootstrap.js +185 -2
  21. package/dist/cards.d.ts +60 -13
  22. package/dist/cards.js +88 -18
  23. package/dist/channel.d.ts +128 -47
  24. package/dist/channel.js +10 -5
  25. package/dist/client-css.d.ts +36 -0
  26. package/dist/client-css.js +326 -0
  27. package/dist/client-section.d.ts +35 -0
  28. package/dist/client-section.js +133 -0
  29. package/dist/config-ui.d.ts +28 -6
  30. package/dist/config-ui.js +88 -25
  31. package/dist/config-url-fetch.d.ts +19 -0
  32. package/dist/config-url-fetch.js +43 -0
  33. package/dist/connector-auth.d.ts +13 -2
  34. package/dist/connector-auth.js +82 -8
  35. package/dist/connector.d.ts +74 -32
  36. package/dist/context.d.ts +40 -0
  37. package/dist/context.js +2 -0
  38. package/dist/ctx.d.ts +210 -30
  39. package/dist/ctx.js +9 -1
  40. package/dist/define-extension.d.ts +23 -13
  41. package/dist/define-extension.js +19 -5
  42. package/dist/device-denied-paths.d.ts +20 -0
  43. package/dist/device-denied-paths.js +118 -0
  44. package/dist/device-operation.d.ts +339 -0
  45. package/dist/device-operation.js +312 -0
  46. package/dist/device-protocol.d.ts +285 -50
  47. package/dist/device-protocol.js +755 -90
  48. package/dist/device-provider.d.ts +708 -0
  49. package/dist/device-provider.js +325 -0
  50. package/dist/device-service.d.ts +52 -0
  51. package/dist/device-service.js +105 -0
  52. package/dist/dial-in.d.ts +239 -0
  53. package/dist/dial-in.js +155 -0
  54. package/dist/directory.d.ts +15 -12
  55. package/dist/extension-point.d.ts +2 -0
  56. package/dist/extension-point.js +7 -3
  57. package/dist/field-meta.d.ts +19 -0
  58. package/dist/field-meta.js +54 -0
  59. package/dist/file-preview.d.ts +43 -10
  60. package/dist/git-hosts.d.ts +53 -0
  61. package/dist/git-hosts.js +98 -0
  62. package/dist/hooks.d.ts +125 -20
  63. package/dist/hooks.js +5 -0
  64. package/dist/http-access.d.ts +71 -0
  65. package/dist/http-access.js +12 -0
  66. package/dist/identity.d.ts +38 -9
  67. package/dist/identity.js +21 -1
  68. package/dist/index.d.ts +31 -4
  69. package/dist/index.js +31 -4
  70. package/dist/model-params.d.ts +41 -22
  71. package/dist/model-params.js +28 -15
  72. package/dist/model.d.ts +210 -75
  73. package/dist/model.js +152 -19
  74. package/dist/net.d.ts +52 -0
  75. package/dist/net.js +34 -0
  76. package/dist/network-classes.d.ts +98 -0
  77. package/dist/network-classes.js +291 -0
  78. package/dist/permissions.d.ts +65 -22
  79. package/dist/permissions.js +139 -43
  80. package/dist/platform-only.d.ts +27 -0
  81. package/dist/platform-only.js +35 -0
  82. package/dist/plugin-manifest.d.ts +40 -9
  83. package/dist/plugin-manifest.js +171 -60
  84. package/dist/plugin-package.d.ts +82 -39
  85. package/dist/plugin-package.js +68 -41
  86. package/dist/push.d.ts +75 -0
  87. package/dist/push.js +87 -0
  88. package/dist/sandbox-linux-runtime-source.d.ts +1 -0
  89. package/dist/sandbox-linux-runtime-source.js +2343 -0
  90. package/dist/sandbox-native-runtime-source.d.ts +10 -0
  91. package/dist/sandbox-native-runtime-source.js +476 -0
  92. package/dist/sandbox-runtime-source.d.ts +47 -0
  93. package/dist/sandbox-runtime-source.js +73 -0
  94. package/dist/sandbox-write-denies.d.ts +139 -0
  95. package/dist/sandbox-write-denies.js +869 -0
  96. package/dist/secret.d.ts +8 -2
  97. package/dist/secret.js +11 -4
  98. package/dist/setup-check.d.ts +128 -0
  99. package/dist/setup-check.js +142 -0
  100. package/dist/setup-guide-parse.d.ts +121 -0
  101. package/dist/setup-guide-parse.js +356 -0
  102. package/dist/setup-guide-render.d.ts +45 -0
  103. package/dist/setup-guide-render.js +351 -0
  104. package/dist/setup-guide.d.ts +86 -72
  105. package/dist/setup-guide.js +340 -108
  106. package/dist/shell-capabilities.d.ts +211 -0
  107. package/dist/shell-capabilities.js +44 -0
  108. package/dist/shell-environment.d.ts +57 -0
  109. package/dist/shell-environment.js +21 -0
  110. package/dist/skill.d.ts +27 -17
  111. package/dist/skill.js +40 -26
  112. package/dist/storage.d.ts +52 -25
  113. package/dist/svg-viewbox.d.ts +10 -0
  114. package/dist/svg-viewbox.js +24 -0
  115. package/dist/theme-assets.d.ts +55 -0
  116. package/dist/theme-assets.js +489 -0
  117. package/dist/theme-readability.d.ts +37 -0
  118. package/dist/theme-readability.js +145 -0
  119. package/dist/theme-tokens.generated.d.ts +299 -0
  120. package/dist/theme-tokens.generated.js +184 -0
  121. package/dist/theme.d.ts +190 -0
  122. package/dist/theme.js +471 -0
  123. package/dist/tool.d.ts +104 -30
  124. package/dist/tool.js +29 -9
  125. package/dist/ui-parts.d.ts +23 -0
  126. package/dist/ui-parts.js +385 -0
  127. package/dist/ui-resolve.d.ts +35 -0
  128. package/dist/ui-resolve.js +42 -0
  129. package/dist/ui-slots.d.ts +65 -0
  130. package/dist/ui-slots.js +261 -0
  131. package/dist/ui.d.ts +232 -77
  132. package/dist/ui.js +104 -27
  133. package/dist/url.d.ts +4 -1
  134. package/dist/url.js +4 -1
  135. package/dist/web.d.ts +26 -20
  136. package/package.json +13 -1
  137. package/schemas/bootstrap-extra.v1.schema.json +186 -0
  138. package/schemas/bootstrap.v1.schema.json +20 -0
  139. package/schemas/connector-template.v1.schema.json +62 -4
  140. package/schemas/plugin.v1.schema.json +93 -143
  141. package/schemas/theme.v1.schema.json +302 -0
  142. package/agent-docs/extension-points/sandbox.md +0 -15
  143. package/dist/org-access.d.ts +0 -27
  144. package/dist/org-access.js +0 -35
  145. package/dist/sandbox.d.ts +0 -254
  146. package/dist/sandbox.js +0 -153
@@ -0,0 +1,708 @@
1
+ /**
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
+ * primitives below; the kernel builds `glob` / `grep` / `edit` from `exec` plus `readFile` /
5
+ * `writeFile`.
6
+ *
7
+ * A device separates its **file system** from its **instance**: the file system
8
+ * (`createFileSystem`) lives until the device is deleted (`destroyFileSystem`); instances
9
+ * (`create`) attach to it and come and go (`destroy` drops the instance and keeps the files).
10
+ */
11
+ import type { SandboxBackground, SandboxBrowse, SandboxBrowseScope, SandboxOperation, SandboxOperationRef, SandboxOperationScope, SandboxPermissionSupport, SandboxPreparation, SandboxPreparationScope } from "./device-operation.js";
12
+ import type { DialInHandler } from "./dial-in.js";
13
+ /** Device provider extension point ref. */
14
+ export declare const DEVICE_PROVIDER_EXTENSION_POINT = "device-provider@1";
15
+ /** The roots inside the sandbox the model may access. */
16
+ export declare const SANDBOX_ROOTS: readonly ["/workspace", "/skills", "/tmp"];
17
+ /**
18
+ * Sandbox resource and network limits: what lifecycle create and update carry (resources and the
19
+ * outer network only; each operation's scope says how it runs). A provider that ignores `network`
20
+ * still runs: it then behaves as an allowlisted sandbox (the safe direction).
21
+ */
22
+ export interface SandboxLimits {
23
+ cpu: number;
24
+ memoryMb: number;
25
+ diskMb: number;
26
+ /**
27
+ * The network the instance (cloud) must enforce, or the allowlist a local device's sandbox
28
+ * intersects with its own list (`open-public` is for cloud instances only). Each entry of
29
+ * `hosts` passes {@link validateAllowHost}.
30
+ */
31
+ network: {
32
+ kind: "open-public" | "allowlist";
33
+ hosts: string[];
34
+ };
35
+ }
36
+ /** The absolute roots inside one instance (a device may place them anywhere on its host). */
37
+ export interface SandboxRoots {
38
+ workspace: string;
39
+ skills: string;
40
+ tmp: string;
41
+ }
42
+ /** The roots every container-like provider uses; the same paths as {@link SANDBOX_ROOTS}. */
43
+ export declare const DEFAULT_SANDBOX_ROOTS: Readonly<SandboxRoots>;
44
+ /** The provider's instance handle. */
45
+ export interface SandboxHandle {
46
+ /** The provider's instance id. */
47
+ id: string;
48
+ /** The instance's roots; absent means {@link DEFAULT_SANDBOX_ROOTS}. */
49
+ roots?: SandboxRoots;
50
+ }
51
+ /** The roots of an instance, falling back to {@link DEFAULT_SANDBOX_ROOTS}. */
52
+ export declare function rootsOf(h: SandboxHandle): SandboxRoots;
53
+ /** The provider's file system handle (a device's files, independent of any instance). */
54
+ export interface FileSystemHandle {
55
+ /** The provider's file system id. */
56
+ id: string;
57
+ }
58
+ /** Who runs an `exec` (informational in phase 1: audit and attribution). */
59
+ export interface SandboxActor {
60
+ accountId: string;
61
+ conversationId: string;
62
+ /**
63
+ * The run the command serves. The kernel uses it to route run grants (network hosts allowed
64
+ * for the rest of a run) to a connected device; informational for other providers.
65
+ */
66
+ runId?: string;
67
+ }
68
+ /**
69
+ * The layer that refused a network host: `device` (the org allows it, the device's local policy
70
+ * does not), `org` (not in the org's effective egress), `address` (an IP literal or a name that
71
+ * points to a private or local address; never grantable), `unknown`.
72
+ */
73
+ export type NetworkBlockLayer = "device" | "org" | "address" | "unknown";
74
+ /** A host a command was refused, as the provider reports it. */
75
+ export interface NetworkBlockedHost {
76
+ /** The host as the proxy saw it (IPv6 literals bracketed). */
77
+ host: string;
78
+ port: number;
79
+ layer: NetworkBlockLayer;
80
+ }
81
+ /** Result of a command. */
82
+ export interface ExecResult {
83
+ /** null on timeout or when aborted while running (`timedOut` is then true / false). */
84
+ exitCode: number | null;
85
+ stdout: string;
86
+ stderr: string;
87
+ truncated: boolean;
88
+ timedOut: boolean;
89
+ /**
90
+ * Network refusals during the command (optional for every provider): at most
91
+ * `MAX_NETWORK_BLOCKED_HOSTS` hosts, deduped by host. The kernel recomputes the `org` layer
92
+ * itself and never trusts a provider's word that the org allows a host.
93
+ */
94
+ network?: {
95
+ blocked: NetworkBlockedHost[];
96
+ };
97
+ }
98
+ /**
99
+ * The instance is definitely gone on the provider's side (container removed, E2B sandbox expired).
100
+ * `exec` / `readFile` / `writeFile` / `stat` must throw it (not a plain Error) when they find the
101
+ * instance gone; the kernel then rebuilds the instance and retries once. A transient connection
102
+ * failure throws a plain error. In a managed operation (`operation()`), a gone instance found
103
+ * **before** the request reached the machine throws a `DeviceRequestNotSentError` with this error
104
+ * as its `cause`: the operation is then recorded as not started rather than as an unknown outcome,
105
+ * and the instance is still rebuilt, so the call can be retried on it.
106
+ */
107
+ export declare class SandboxGoneError extends Error {
108
+ readonly sandboxGone: true;
109
+ constructor(message: string, opts?: {
110
+ cause?: unknown;
111
+ });
112
+ }
113
+ /** Duck-typed check (not instanceof), so a plugin bundling another plugin-sdk copy still matches. */
114
+ export declare function isSandboxGoneError(e: unknown): e is SandboxGoneError;
115
+ /**
116
+ * A lifecycle call's fence (device update fencing design §3): the kernel passes it to `update`,
117
+ * `create`, `destroy` and `destroyByName` made under the device's exclusive lease, so a provider
118
+ * can refuse a call from a holder whose lease ended while the call was in flight.
119
+ */
120
+ export interface DeviceFence {
121
+ /**
122
+ * The device's fencing generation as the calling holder last wrote it: a non-negative safe
123
+ * integer, strictly higher for every later exclusive holder of the device, never lower for later
124
+ * calls of the same holder.
125
+ */
126
+ readonly token: number;
127
+ }
128
+ /**
129
+ * Thrown by a lifecycle call whose {@link DeviceFence} token is lower than one the instance
130
+ * already applied: the caller is a stale holder, and nothing was changed. The kernel handles it as
131
+ * a lost lease (never as a reason to recreate). `current` is the token the instance holds, when the
132
+ * provider knows it.
133
+ */
134
+ export declare class StaleFenceError extends Error {
135
+ readonly staleFence: true;
136
+ readonly current: number | undefined;
137
+ constructor(message: string, opts?: {
138
+ cause?: unknown;
139
+ current?: number;
140
+ });
141
+ }
142
+ /** Duck-typed check (not instanceof), so a plugin bundling another plugin-sdk copy still matches. */
143
+ export declare function isStaleFenceError(e: unknown): e is StaleFenceError;
144
+ /**
145
+ * The file system is definitely gone on the provider's side (volume removed, E2B sandbox killed).
146
+ * `create` throws it instead of attaching the instance to a new, empty file system; the kernel then
147
+ * reports the device's files as lost rather than handing out a silently empty workspace.
148
+ */
149
+ export declare class FileSystemGoneError extends Error {
150
+ readonly fileSystemGone: true;
151
+ constructor(message: string, opts?: {
152
+ cause?: unknown;
153
+ });
154
+ }
155
+ /** Duck-typed check (not instanceof), so a plugin bundling another plugin-sdk copy still matches. */
156
+ export declare function isFileSystemGoneError(e: unknown): e is FileSystemGoneError;
157
+ /**
158
+ * A holder tag (`exec` argument `tag`, {@link DeviceProvider.killTagged}): the kernel passes its
159
+ * lease tokens (UUIDs). Providers check tags against it before putting them in a command line or a
160
+ * kill pattern.
161
+ */
162
+ export declare const SANDBOX_TAG_RE: RegExp;
163
+ /** Text in English with an optional Chinese translation (what a person reads). */
164
+ export interface DeviceText {
165
+ en: string;
166
+ zh?: string;
167
+ }
168
+ /** The device a provider answers about: the kernel's device id, its org and the instance, if any. */
169
+ export interface DeviceRef {
170
+ deviceId: string;
171
+ orgId: string;
172
+ /** The current instance, or null when the device has none. */
173
+ handle: SandboxHandle | null;
174
+ }
175
+ /**
176
+ * One limit line of a {@link DeviceReport} (shown as is; the provider enforces it). `value` is
177
+ * text too: words in it get a Chinese form; pure data (a path, a size) may carry `en` only.
178
+ */
179
+ export interface DeviceReportLimit {
180
+ label: DeviceText;
181
+ value: DeviceText;
182
+ }
183
+ /**
184
+ * What a provider tells about a device ({@link DeviceProvider.report}): shown to people, never
185
+ * used for enforcement. `revision` must change whenever anything that affects what was approved
186
+ * against the report changes (how operations are confined, what the device may reach): a new
187
+ * revision invalidates the approvals, grants and pending admissions bound to the old one.
188
+ * Display-only facts (for example the shared project roots shown as a limit line) may change
189
+ * without a revision change: announce such a change with `ctx.devices.reportChanged`, and the
190
+ * kernel stores the new text without invalidating anything. `home` is the owner's home directory
191
+ * (absolute) or null; `reset` says whether the provider can reset the device's files.
192
+ *
193
+ * `changeHint` (optional) says in the provider's own words who can change the device's limits and
194
+ * how (for a local connection: the machine's owner, with a command on that machine; for a
195
+ * container: the super admin's deployment config of the extension). The device page shows it
196
+ * under the limits, and the kernel appends it to a refusal that cites the report (an escalated
197
+ * call the provider does not allow now), so a person and the model learn the way out. State the
198
+ * mechanism, not advice for one situation.
199
+ */
200
+ export interface DeviceReport {
201
+ revision: string;
202
+ description: DeviceText;
203
+ home: string | null;
204
+ limits: DeviceReportLimit[];
205
+ reset: boolean;
206
+ changeHint?: DeviceText;
207
+ }
208
+ /** Size limits {@link parseDeviceReport} enforces. */
209
+ export declare const DEVICE_REPORT_LIMITS: Readonly<{
210
+ revisionChars: 128;
211
+ descriptionChars: 300;
212
+ limits: 8;
213
+ limitLabelChars: 60;
214
+ limitValueChars: 60;
215
+ homeChars: 4096;
216
+ changeHintChars: 400;
217
+ }>;
218
+ /** Checks a provider's report; throws `TypeError` on any other shape, returns a clean copy. */
219
+ export declare function parseDeviceReport(value: unknown): DeviceReport;
220
+ /**
221
+ * The provider refuses a project directory (`projects` operations: it lies where the provider
222
+ * will not serve, for example another connection's directory). `reason` is shown to the person.
223
+ * The kernel answers it as `device.project_refused` (422).
224
+ */
225
+ export declare class ProjectPathRefusedError extends Error {
226
+ readonly projectPathRefused: true;
227
+ readonly reason: DeviceText;
228
+ constructor(reason: DeviceText, opts?: {
229
+ cause?: unknown;
230
+ });
231
+ }
232
+ /** Duck-typed check (not instanceof), so a plugin bundling another plugin-sdk copy still matches. */
233
+ export declare function isProjectPathRefusedError(e: unknown): e is ProjectPathRefusedError;
234
+ /** A device service name: 1 to 32 characters, a lower-case letter then letters, digits and `-`. */
235
+ export declare const DEVICE_SERVICE_NAME_RE: RegExp;
236
+ /**
237
+ * A long-lived service process in a device ({@link DeviceProvider.ensureService}), started on an
238
+ * extension's behalf. It runs under the device's own sandbox (not under any one conversation's
239
+ * operation scope), writes only in its own state directory (outside every project root; `files`
240
+ * are written before start into its code directory, read only for the service where the provider
241
+ * can separate code from state, else the state directory), reaches the network through the
242
+ * device's network setting, and is killed with the instance on suspend and destroy. It speaks the service socket protocol
243
+ * (`device-service.ts`).
244
+ */
245
+ export interface DeviceServiceSpec {
246
+ /** One service per name per device; matches {@link DEVICE_SERVICE_NAME_RE}. */
247
+ name: string;
248
+ /** The provider supplies Node 22 or later. */
249
+ runtime: "node";
250
+ /**
251
+ * The script to run: one of the `files` keys. The process runs
252
+ * `node <codeDir ?? stateDir>/<entry>` (the code directory where the provider keeps code apart,
253
+ * else the state directory) with the state directory as its working directory; that exact command passes the command review.
254
+ */
255
+ entry: string;
256
+ args: string[];
257
+ /**
258
+ * Written into the service's code directory before start (read only for the service where the
259
+ * provider separates code from state, else the state directory), keyed by relative path: no
260
+ * absolute path, no `..` or `.` segment, no empty segment, no backslash, no NUL (the kernel
261
+ * refuses a spec that breaks this before any provider call).
262
+ */
263
+ files: Record<string, Uint8Array>;
264
+ /**
265
+ * Extra environment of the process (shown to the command review as `env K=V …`). The kernel
266
+ * refuses `NODE_*`, `PATH`, `SSL_CERT_FILE`, `SSL_CERT_DIR`, `OPENSSL_CONF`, `OPENSSL_ENGINES`,
267
+ * `LD_*`, `DYLD_*`, `CAPYBARA_*` and the proxy variables (`HTTP_PROXY`, `HTTPS_PROXY`,
268
+ * `NO_PROXY`, `ALL_PROXY`, `FTP_PROXY`), any case: they change what runs or what it trusts, or
269
+ * the provider sets them itself.
270
+ */
271
+ env?: Record<string, string>;
272
+ }
273
+ /** A device service's state ({@link DeviceProvider.ensureService}). */
274
+ export interface DeviceServiceStatus {
275
+ name: string;
276
+ state: "running" | "stopped";
277
+ /** ISO 8601 time the running process started; null when stopped. */
278
+ startedAt: string | null;
279
+ /**
280
+ * The service's state directory in the device (absolute), also when it is stopped: its working
281
+ * directory and write root (its `files` too, unless the provider keeps code apart). The kernel
282
+ * reviews the launch against it.
283
+ */
284
+ stateDir: string;
285
+ /**
286
+ * The directory the entry runs from (absolute), when the provider keeps the service's code
287
+ * apart from its state (read only for the service); absent: the state directory. Known before
288
+ * the first start like `stateDir`. The kernel's launch review shows
289
+ * `node <codeDir ?? stateDir>/<entry>`, so a provider runs exactly that.
290
+ */
291
+ codeDir?: string;
292
+ }
293
+ /**
294
+ * A message stream to a device service ({@link DeviceProvider.openStream},
295
+ * `DialInChannel.openStream`): whole messages both ways, flow-controlled by credit.
296
+ */
297
+ export interface DeviceStream {
298
+ /** Sends one message; resolves when the peer has credit for it (backpressure). */
299
+ send(message: Uint8Array): Promise<void>;
300
+ /** The peer's messages, in order; ends when the stream closes. */
301
+ readonly messages: AsyncIterable<Uint8Array>;
302
+ /** Closes the stream (idempotent); `reason` reaches the peer. */
303
+ close(reason?: string): void;
304
+ /** Resolves once the stream is closed, by either side, with the reason. */
305
+ readonly closed: Promise<{
306
+ reason: string;
307
+ }>;
308
+ }
309
+ /**
310
+ * The `device-provider@1` implementation (provided by a sandbox plugin such as Docker or E2B).
311
+ *
312
+ * **File systems and instances.** `createFileSystem` makes a device's files; they live until
313
+ * `destroyFileSystem` (the device is deleted). `create` makes an instance attached to an
314
+ * existing file system; `destroy` / `destroyByName` drop the instance only and keep the files, and
315
+ * `suspend` keeps them too. When the file system is gone, `create` must throw
316
+ * {@link FileSystemGoneError} and never create an empty one in its place (a Docker provider checks
317
+ * its volumes exist before mounting them, because Docker would otherwise create empty volumes).
318
+ *
319
+ * **Gone instances.** When the instance is definitely gone: `resume` returns `gone`; `exec` /
320
+ * `readFile` / `writeFile` / `stat` / `killAll` / `killTagged` throw {@link SandboxGoneError};
321
+ * `suspend` / `destroy` succeed as usual.
322
+ *
323
+ * **Auto-start**: when the instance still exists but is stopped or paused (for a reason outside the
324
+ * kernel: host or daemon restart, a process in the sandbox stopping its init, an idle sweep that
325
+ * stopped the instance before recording `suspended`...), `exec` / `readFile` / `writeFile` /
326
+ * `stat` / `killAll` / `killTagged` must start it transparently first (like `resume`, files kept)
327
+ * and then run, never fail: the kernel trusts only the `running` it recorded itself. Auto-start
328
+ * must be idempotent under concurrent calls: two calls that both find the instance stopped both
329
+ * start it without failing.
330
+ *
331
+ * **Time limits apply inside the sandbox too**: besides stopping a command after `timeoutMs` on the
332
+ * provider's side, `exec` must make the command in the sandbox kill itself shortly (a few seconds)
333
+ * after `timeoutMs`. When a kernel replica crashes, the provider-side timer goes with it, and a
334
+ * dropped connection does not end the command; the in-sandbox limit keeps it from running
335
+ * indefinitely next to the next holder's commands.
336
+ *
337
+ * **Abort**: every method must respond to `signal` promptly (fail at once when already aborted, end
338
+ * with the abort reason as soon as possible when aborted mid-way): the kernel relies on it to stop
339
+ * on lock loss, run abort or timeout, and ignoring it may let two holders operate on one instance.
340
+ * An aborted `exec` must kill its running command (and the processes it spawned), not just stop
341
+ * waiting for its output; an `exec` aborted after its command started resolves normally with
342
+ * `exitCode: null`, `timedOut: false` (and the output collected so far), it does not reject. An
343
+ * `exec` called with an already aborted signal rejects at once.
344
+ *
345
+ * **Fencing** (device update fencing design §4): `update`, `create`, `destroy` and
346
+ * `destroyByName` get a {@link DeviceFence} from the kernel. A provider that keeps per-instance
347
+ * state it can update conditionally must store the highest token it applied next to that state,
348
+ * compare and store in one atomic step, and throw {@link StaleFenceError} for a lower token (an
349
+ * equal token is the same holder and is accepted); `create` seeds the new instance's token and
350
+ * should refuse when the instance it would replace carries a higher one; `destroy` /
351
+ * `destroyByName` should refuse an instance carrying a higher token. A provider that cannot (no
352
+ * conditional write in its backend) ignores the token and states the residual race in its README;
353
+ * it should implement {@link DeviceProvider.appliedNetwork}, so the kernel narrows a late stale
354
+ * `update` again at the next lifecycle step.
355
+ * The fence is `undefined` only from an older kernel that sends none: freshness is then unproven,
356
+ * so a provider answers `recreate` to an in-place change it would otherwise fence, seeds 0 at
357
+ * `create` and destroys without a check. `null` (destroy only) means the kernel has no fence for
358
+ * the call (no device record, or the one-off legacy cleanup): destroy without a check.
359
+ *
360
+ * **Concurrent use** (required in `@2`): the sessions of one device share its instance, so the
361
+ * kernel calls `exec`, `readFile`, `writeFile` and `stat` concurrently on one instance. Those four
362
+ * methods must be safe to call concurrently. Each `exec` labels its command with its `tag`, and an
363
+ * aborted `exec` kills only its own command.
364
+ */
365
+ export interface DeviceProvider {
366
+ /** Runtime permission support for this instance; does not grant consent or provision an instance. */
367
+ permissionSupport?(h: SandboxHandle, signal: AbortSignal): Promise<SandboxPermissionSupport>;
368
+ /**
369
+ * Fresh immutable grant for one actual method invocation. Lightweight until a method is called;
370
+ * never cache grants on the handle or fall back to raw methods when unsupported.
371
+ */
372
+ operation?(h: SandboxHandle, scope: SandboxOperationScope, signal: AbortSignal): Promise<SandboxOperation>;
373
+ /** Trusted skill/attachment staging only; never exposed to user operations. */
374
+ prepare?(h: SandboxHandle, scope: SandboxPreparationScope, signal: AbortSignal): Promise<SandboxPreparation>;
375
+ /** Owner-authenticated metadata browsing without conversation/profile consent. */
376
+ browse?(h: SandboxHandle, scope: SandboxBrowseScope, signal: AbortSignal): Promise<SandboxBrowse>;
377
+ /**
378
+ * Required for permission support: idempotently persist an operation-ID tombstone before
379
+ * cancelling exact owned work. A delayed launch checks it before effects; retain it through
380
+ * admitBeforeMs and any owned execution's lifetime, including across kernel restarts.
381
+ */
382
+ revokeOperation?(h: SandboxHandle, ref: SandboxOperationRef, signal: AbortSignal): Promise<void>;
383
+ /** Exact registered background ownership; missing support must not fall back to shell launch. */
384
+ background?: SandboxBackground;
385
+ /** `exec` / `readFile` / `writeFile` / `stat` may run concurrently on one instance (required). */
386
+ readonly concurrentExec: true;
387
+ /**
388
+ * Declares that the provider enforces `limits.network` allowlists (required, always `true`):
389
+ * a provider that cannot restrict outbound hosts does not implement `device-provider@1`.
390
+ */
391
+ readonly networkAllowlist: true;
392
+ /**
393
+ * What the provider tells about the device: a description, the owner's home, limits and whether
394
+ * files can be reset ({@link DeviceReport}). Shown to people only; the answer passes
395
+ * {@link parseDeviceReport}. Must respond to `signal`.
396
+ */
397
+ report(device: DeviceRef, signal: AbortSignal): Promise<DeviceReport>;
398
+ /**
399
+ * The dial-in side of the provider, for an extension declaring `permissions.dialIn`: the kernel
400
+ * hands it the hellos and unsolicited frames of the machines serving its devices.
401
+ */
402
+ readonly dialIn?: DialInHandler;
403
+ /**
404
+ * Whether the provider isolates the sessions of one device from each other inside the
405
+ * instance (a declared capability; absent means false).
406
+ */
407
+ readonly sessionIsolation?: boolean;
408
+ /**
409
+ * Where `create`-time limits are fixed: `instance` (absent; Docker: a new instance applies new
410
+ * limits) or `fileSystem` (E2B: the instance is the file system, so only a file reset applies
411
+ * them without {@link DeviceProvider.update}).
412
+ */
413
+ readonly limitsApplyAt?: "instance" | "fileSystem";
414
+ /**
415
+ * Applies new limits to a running instance without recreating it (optional). `recreate` asks
416
+ * the kernel to destroy the instance and create one on the same files instead.
417
+ *
418
+ * `updated` means the instance now enforces `limits.network`, and no later rebuild of the
419
+ * instance (resume, auto-start, a lost egress component) can enforce a wider network than this
420
+ * one. For a narrowing (a host removed, or a kind that allows less), answer `updated` only once
421
+ * no connection to a removed host survives and no new one can open; otherwise answer `recreate`
422
+ * or throw. A thrown `update` is the kernel's to handle (recreate, or quarantine and retry on the
423
+ * next use), so a repeated call with the same limits must be safe.
424
+ *
425
+ * `fence`: a provider that can must refuse a token lower than the one the instance applied last
426
+ * with {@link StaleFenceError}, checked and stored in the same atomic step as the new limits (see
427
+ * "Fencing" above); an equal or higher token with limits already in force raises the stored
428
+ * token and answers `updated`. Any answer to a call whose token is not lower (`updated` or
429
+ * `recreate`) leaves the stored token at least that high, so an older call arriving later is
430
+ * still refused.
431
+ */
432
+ update?(h: SandboxHandle, limits: SandboxLimits, signal: AbortSignal, fence: DeviceFence): Promise<"updated" | "recreate">;
433
+ /**
434
+ * The network the instance `h` enforces now, as the provider's backend reports it, or null when
435
+ * the provider cannot tell (optional; read only with {@link DeviceProvider.update}). A read
436
+ * only: it must not resume, start or change the instance, and must respond to `signal`.
437
+ *
438
+ * For a provider whose `update` cannot honor the fence (no conditional write in its backend), a
439
+ * stale holder's late `update` can leave the instance wider than the kernel's record. At a
440
+ * lifecycle step under the exclusive lease (a resumed instance, a running one the use holds
441
+ * exclusively, an instance created on kept files whose limits are fixed at the file system)
442
+ * the kernel compares this answer with the limits it recorded and, when it allows more (the
443
+ * open public network over an allowlist, or a host the record does not cover), is null or
444
+ * fails, applies the desired limits again through `update` with its own fence (a provider bound
445
+ * to its file system that cannot apply them is stopped until it can). Equal or narrower changes
446
+ * nothing. Since null forces that `update` at every such step, answer null only for a state the
447
+ * provider really cannot read, never as a routine answer. Shared uses of a running instance read
448
+ * nothing, so a late call that lands while the instance keeps running is narrowed at its next
449
+ * resume or rebuild (at the latest after the kernel's maximum running time).
450
+ */
451
+ appliedNetwork?(h: SandboxHandle, signal: AbortSignal): Promise<SandboxLimits["network"] | null>;
452
+ /**
453
+ * Creates a device's file system. `name` looks like `cap-device-<deviceId>`. If a file
454
+ * system with this name already exists, return it.
455
+ */
456
+ createFileSystem(args: {
457
+ name: string;
458
+ limits: SandboxLimits;
459
+ signal: AbortSignal;
460
+ }): Promise<FileSystemHandle>;
461
+ /** Deletes the file system and its files. Succeeds when it does not exist. */
462
+ destroyFileSystem(fs: FileSystemHandle, signal: AbortSignal): Promise<void>;
463
+ /**
464
+ * Deletes the file system made under `name` by `createFileSystem`; succeeds when there is none.
465
+ * The kernel uses it when it has no handle (`createFileSystem` finished on the provider's side
466
+ * but the kernel stopped before recording the handle), and in its one-off cleanup of
467
+ * per-conversation sandboxes with `cap-<conversationId>` names that a `sandbox@1` provider's
468
+ * `create` made together with their files (Docker: the `cap-<conversationId>-workspace` and
469
+ * `-skills` volumes); a provider removes those under the same call.
470
+ */
471
+ destroyFileSystemByName(name: string, signal: AbortSignal): Promise<void>;
472
+ /**
473
+ * Creates an instance attached to `fileSystem`. Without `image` the provider uses its own
474
+ * published image. Throws {@link FileSystemGoneError} when the file system is gone.
475
+ *
476
+ * `fence`: the new instance starts with this token stored (so a stale `update` is refused
477
+ * against it); a provider should throw {@link StaleFenceError}, leaving everything as it is,
478
+ * when an instance it would replace under `name` carries a higher token.
479
+ */
480
+ create(args: {
481
+ name: string;
482
+ image?: string;
483
+ limits: SandboxLimits;
484
+ fileSystem: FileSystemHandle;
485
+ signal: AbortSignal;
486
+ fence: DeviceFence;
487
+ }): Promise<SandboxHandle>;
488
+ /** `gone` means the provider no longer has this instance. */
489
+ resume(h: SandboxHandle, signal: AbortSignal): Promise<"resumed" | "gone">;
490
+ /** Files must be kept. Succeeds when the instance does not exist. */
491
+ suspend(h: SandboxHandle, signal: AbortSignal): Promise<void>;
492
+ /**
493
+ * Drops the instance only; the file system and its files are kept. Succeeds when it does not
494
+ * exist. `fence`: a provider should throw {@link StaleFenceError} when the instance carries a
495
+ * higher token; `null` when the kernel has no fence for the call (nothing to compare).
496
+ */
497
+ destroy(h: SandboxHandle, signal: AbortSignal, fence: DeviceFence | null): Promise<void>;
498
+ /**
499
+ * Drops the instance made under `name` by `create` (instance only, files kept); succeeds when
500
+ * there is none. The kernel uses it when it has no handle (`create` finished on the provider's
501
+ * side but the kernel stopped before recording the handle), and in its one-off cleanup of
502
+ * per-conversation sandboxes with `cap-<conversationId>` names made by a `sandbox@1` provider's
503
+ * `create`. `fence` as for {@link DeviceProvider.destroy} (`null` in that one-off cleanup,
504
+ * which has no device record).
505
+ */
506
+ destroyByName(name: string, signal: AbortSignal, fence: DeviceFence | null): Promise<void>;
507
+ /**
508
+ * Kills every running command started through `exec` in this instance (and the processes they
509
+ * spawned that did not start their own session). The kernel calls it only when no other holder
510
+ * can be running commands (an instance just resumed from `suspended`, or under the exclusive
511
+ * lease), never while another session may be; to clean up after one crashed holder it uses
512
+ * {@link DeviceProvider.killTagged}. Processes a command put in the background in their own
513
+ * session are not guaranteed to be killed.
514
+ */
515
+ killAll(h: SandboxHandle, signal: AbortSignal): Promise<void>;
516
+ /**
517
+ * Kills every running `exec` command labelled with one of `tags` (and its process tree), leaving
518
+ * other commands running. The kernel calls it for the tags of holders that crashed while live
519
+ * holders keep running commands. Tags match {@link SANDBOX_TAG_RE}. Match whole tags: one tag
520
+ * may be a prefix of another (`ab` of `ab-cd`), and killing `ab` must not touch `ab-cd`'s
521
+ * commands.
522
+ */
523
+ killTagged(h: SandboxHandle, tags: string[], signal: AbortSignal): Promise<void>;
524
+ /**
525
+ * Runs a command. `maxOutputBytes` caps stdout and stderr **combined**; the rest is dropped and
526
+ * `truncated` is true.
527
+ */
528
+ exec(h: SandboxHandle, args: {
529
+ command: string;
530
+ cwd?: string;
531
+ env?: Record<string, string>;
532
+ timeoutMs: number;
533
+ maxOutputBytes: number;
534
+ signal: AbortSignal;
535
+ /**
536
+ * The holder's tag ({@link SANDBOX_TAG_RE}); label the command with it so
537
+ * {@link DeviceProvider.killTagged} can find it.
538
+ */
539
+ tag: string;
540
+ /** Who runs the command; informational in phase 1 (record it, do not act on it). */
541
+ actor: SandboxActor;
542
+ }): Promise<ExecResult>;
543
+ /**
544
+ * Reads a file (at most `maxBytes`; longer files are truncated and `truncated` is true). Returns
545
+ * null when it does not exist or is a directory.
546
+ */
547
+ readFile(h: SandboxHandle, path: string, opts: {
548
+ maxBytes: number;
549
+ signal: AbortSignal;
550
+ }): Promise<{
551
+ data: Uint8Array;
552
+ truncated: boolean;
553
+ } | null>;
554
+ /** Parent directories are created. */
555
+ writeFile(h: SandboxHandle, path: string, data: Uint8Array, signal: AbortSignal): Promise<void>;
556
+ stat(h: SandboxHandle, path: string, signal: AbortSignal): Promise<{
557
+ size: number;
558
+ isDir: boolean;
559
+ } | null>;
560
+ /**
561
+ * Lists one directory's entries — each entry's `name` and whether it `isDir` — sorted by code
562
+ * unit (locale-independent), at most `limit` of them; `truncated` is true when the directory has
563
+ * more. Entries only: never file contents, never a recursive walk. A `name` is never `.` or `..`;
564
+ * `isDir` follows symbolic links (stat semantics: a link to a directory is `true`, a dangling link
565
+ * `false`, and so is a link whose target the device cannot reach). Returns null only when the
566
+ * path does not exist and the device could reach it; a path it cannot reach throws (a policy
567
+ * refusal), as does a path that is a file or a directory that cannot be read.
568
+ *
569
+ * Optional: a provider without it (or without {@link DeviceProvider.scan}) offers no projects,
570
+ * and its conversations stay in free mode.
571
+ */
572
+ list?(h: SandboxHandle, path: string, opts: {
573
+ limit: number;
574
+ signal: AbortSignal;
575
+ }): Promise<{
576
+ entries: {
577
+ name: string;
578
+ isDir: boolean;
579
+ }[];
580
+ truncated: boolean;
581
+ } | null>;
582
+ /**
583
+ * Looks for project-like directories, read as for {@link DeviceProvider.list}. Every provider
584
+ * traverses the same way:
585
+ *
586
+ * - Candidates are `base` itself and the directories at most {@link MAX_DEVICE_SCAN_DEPTH}
587
+ * levels below it that hold a `.git` entry (directory or file) or an `AGENTS.md` file.
588
+ * - The walk does not follow symbolic links and does not enter hidden directories (names
589
+ * starting with `.`); a candidate does not stop the descent (a monorepo's sub-projects are
590
+ * candidates too). It never enters a directory named in {@link DEVICE_SCAN_SKIPPED_DIRS}, at
591
+ * any depth, nor one named in {@link DEVICE_SCAN_SKIPPED_BASE_DIRS} directly under `base`;
592
+ * every provider skips exactly these. Paths under `base` the device cannot reach are skipped,
593
+ * never an error.
594
+ * - A directory whose basename does not satisfy {@link isDeviceProjectName} is not returned as
595
+ * a candidate (never with a changed name), but it is still traversed.
596
+ * - Directories are visited breadth-first, each level in code-unit order of `path`, `base`
597
+ * counting as the first visit (visiting a directory reads its entries; one that cannot be read
598
+ * still counts as a visit); the walk stops after {@link MAX_DEVICE_SCAN_DIRS} visits, so a
599
+ * huge tree answers what was found by then.
600
+ * - Each candidate is its absolute `path` and its basename as `suggestedName`; the candidates
601
+ * found are sorted by `path` in code-unit order and cut to the first
602
+ * {@link MAX_DEVICE_SCAN_RESULTS}.
603
+ *
604
+ * Directory entries only, never file contents. A `base` that does not exist answers `[]`; a
605
+ * `base` that is a file, cannot be read, or lies outside what the device reaches throws.
606
+ * Optional, like `list`.
607
+ */
608
+ scan?(h: SandboxHandle, base: string, opts: {
609
+ signal: AbortSignal;
610
+ }): Promise<{
611
+ path: string;
612
+ suggestedName: string;
613
+ }[]>;
614
+ /**
615
+ * Starts the named service in the instance, or finds it running (optional, with
616
+ * {@link DeviceProvider.stopService} and {@link DeviceProvider.serviceRequest}): writes
617
+ * `spec.files` into the service's code directory, then runs `spec.entry` with Node, the
618
+ * service socket and state directory named in its environment (`DEVICE_SERVICE_SOCKET_ENV`,
619
+ * `DEVICE_SERVICE_STATE_ENV`). A service already running under the name is kept as is. The
620
+ * kernel has passed the launch through the command review before it calls this.
621
+ *
622
+ * With `opts.ifRunning` it never starts anything and reads only `spec.name` (the kernel sends
623
+ * `{ name, runtime: "node", entry: "", args: [], files: {} }`, which must not be refused): a
624
+ * running service is kept and the device's current network limits are applied to it again,
625
+ * a restart for that runs the spec it was launched with and its stored code (the kernel calls
626
+ * this after the device's allowlist changed, and before reviewing a launch); a stopped one
627
+ * answers its `stopped` status (with `stateDir`, and `codeDir` where kept apart) and stays
628
+ * stopped.
629
+ */
630
+ ensureService?(h: SandboxHandle, spec: DeviceServiceSpec, signal: AbortSignal, opts?: {
631
+ ifRunning?: boolean;
632
+ }): Promise<DeviceServiceStatus>;
633
+ /** Stops the named service; succeeds when it is not running. */
634
+ stopService?(h: SandboxHandle, name: string, signal: AbortSignal): Promise<void>;
635
+ /**
636
+ * The named service's state in the instance, without starting it (optional; the kernel's
637
+ * status reads). Whether a launch is reviewed is decided by `ensureService` with
638
+ * `ifRunning`, which is race-free.
639
+ */
640
+ serviceStatus?(h: SandboxHandle, name: string, signal: AbortSignal): Promise<DeviceServiceStatus>;
641
+ /**
642
+ * One `request` connection to the named service's socket: sends `body`, resolves the service's
643
+ * one answer. Throws when the service is not running, on timeout and on abort.
644
+ */
645
+ serviceRequest?(h: SandboxHandle, name: string, body: Uint8Array, opts: {
646
+ timeoutMs: number;
647
+ signal: AbortSignal;
648
+ }): Promise<Uint8Array>;
649
+ /**
650
+ * Opens a `stream` connection to the named service's socket (optional; the browser's live view
651
+ * needs it). The target is always a service of the device, never a general port forward.
652
+ * `signal` bounds the opening only; the stream lives until either side closes it.
653
+ */
654
+ openStream?(h: SandboxHandle, target: {
655
+ service: string;
656
+ }, signal: AbortSignal): Promise<DeviceStream>;
657
+ }
658
+ /**
659
+ * The most entries a `list` may ask for and its result may carry ({@link DeviceProvider.list}):
660
+ * part of the provider contract, which the device protocol's `list` op also honors.
661
+ */
662
+ export declare const MAX_DEVICE_LIST_ENTRIES = 1000;
663
+ /** The longest project name, in UTF-16 code units. */
664
+ export declare const MAX_DEVICE_PROJECT_NAME_LENGTH = 64;
665
+ /** The most candidates a `scan` answers ({@link DeviceProvider.scan}). */
666
+ export declare const MAX_DEVICE_SCAN_RESULTS = 50;
667
+ /**
668
+ * Directory names a `scan` never enters, at any depth ({@link DeviceProvider.scan}): dependency
669
+ * trees, not projects. Every provider skips exactly these.
670
+ */
671
+ export declare const DEVICE_SCAN_SKIPPED_DIRS: readonly string[];
672
+ /**
673
+ * Directory names a `scan` does not enter directly under its `base` ({@link DeviceProvider.scan}):
674
+ * the owner's macOS `Library` (app data, huge, partly privacy-protected) is not where projects
675
+ * live. Every provider skips exactly these.
676
+ */
677
+ export declare const DEVICE_SCAN_SKIPPED_BASE_DIRS: readonly string[];
678
+ /** How far below its base a `scan` looks: the base's children and their children. */
679
+ export declare const MAX_DEVICE_SCAN_DEPTH = 2;
680
+ /**
681
+ * The most directories one `scan` visits (reads the entries of), its `base` included
682
+ * ({@link DeviceProvider.scan}): breadth-first, each level in code-unit order of path.
683
+ */
684
+ export declare const MAX_DEVICE_SCAN_DIRS = 500;
685
+ /**
686
+ * Whether `v` is a valid project name (a project's identity on its device, and a `scan`
687
+ * candidate's `suggestedName`): non-empty, at most {@link MAX_DEVICE_PROJECT_NAME_LENGTH} UTF-16
688
+ * code units, not `.` or `..`, no `/`, no control characters, and no leading or trailing
689
+ * whitespace.
690
+ */
691
+ export declare function isDeviceProjectName(v: unknown): v is string;
692
+ /**
693
+ * The root-independent checks of a path inside an instance (non-empty, at most 4096 characters, no
694
+ * control characters or backslashes, absolute, no empty or `..` segments); returns the errors,
695
+ * empty when valid. {@link validateSandboxPath} adds root membership.
696
+ */
697
+ export declare function validateSandboxPathShape(p: string): string[];
698
+ /**
699
+ * Checks a path inside an instance; returns the errors, empty when valid: the
700
+ * {@link validateSandboxPathShape} checks, then root membership. `roots`: the instance's roots
701
+ * ({@link rootsOf}); absent means {@link SANDBOX_ROOTS}. The path must be one of them or under one.
702
+ */
703
+ export declare function validateSandboxPath(p: string, roots?: SandboxRoots): string[];
704
+ /**
705
+ * Validates an outbound allowlist host name: lowercase, no protocol or port, optional leading `*.`,
706
+ * IDN accepted only as punycode.
707
+ */
708
+ export declare function validateAllowHost(h: string): string[];