@capybara-hq/plugin-sdk 0.1.0-rc.2 → 0.1.0-rc.20

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 (104) hide show
  1. package/README.md +1 -1
  2. package/agent-docs/agent-templates.md +59 -0
  3. package/agent-docs/concepts.md +63 -0
  4. package/agent-docs/connector-templates.md +48 -0
  5. package/agent-docs/extension-points/channel.md +15 -0
  6. package/agent-docs/extension-points/config-source.md +15 -0
  7. package/agent-docs/extension-points/connector.md +15 -0
  8. package/agent-docs/extension-points/context.md +15 -0
  9. package/agent-docs/extension-points/counter.md +15 -0
  10. package/agent-docs/extension-points/directory.md +15 -0
  11. package/agent-docs/extension-points/file-preview.md +15 -0
  12. package/agent-docs/extension-points/identity-source.md +15 -0
  13. package/agent-docs/extension-points/model-provider.md +15 -0
  14. package/agent-docs/extension-points/object-store.md +15 -0
  15. package/agent-docs/extension-points/sandbox.md +15 -0
  16. package/agent-docs/extension-points/secret-store.md +15 -0
  17. package/agent-docs/extension-points/web-fetch.md +15 -0
  18. package/agent-docs/extension-points/web-search.md +15 -0
  19. package/agent-docs/extensions.md +88 -0
  20. package/agent-docs/plugin-format.md +100 -0
  21. package/agent-docs/setup.md +46 -0
  22. package/agent-docs/skills.md +44 -0
  23. package/agent-docs/tool-naming.md +21 -0
  24. package/dist/agent-template.d.ts +96 -2
  25. package/dist/agent-template.js +381 -3
  26. package/dist/bootstrap.d.ts +15 -1
  27. package/dist/bootstrap.js +17 -1
  28. package/dist/cards.d.ts +39 -5
  29. package/dist/cards.js +70 -11
  30. package/dist/channel.d.ts +20 -1
  31. package/dist/client-css.d.ts +36 -0
  32. package/dist/client-css.js +326 -0
  33. package/dist/client-section.d.ts +35 -0
  34. package/dist/client-section.js +133 -0
  35. package/dist/config-ui.d.ts +24 -1
  36. package/dist/config-ui.js +89 -11
  37. package/dist/connector-auth.d.ts +2 -0
  38. package/dist/connector-auth.js +15 -0
  39. package/dist/context.d.ts +40 -0
  40. package/dist/context.js +2 -0
  41. package/dist/ctx.d.ts +86 -4
  42. package/dist/define-extension.d.ts +5 -1
  43. package/dist/define-extension.js +1 -0
  44. package/dist/dev-hosts.d.ts +6 -0
  45. package/dist/dev-hosts.js +48 -0
  46. package/dist/device-protocol.d.ts +260 -0
  47. package/dist/device-protocol.js +496 -0
  48. package/dist/directory.d.ts +11 -2
  49. package/dist/extension-point.d.ts +6 -0
  50. package/dist/extension-point.js +19 -14
  51. package/dist/file-preview.d.ts +9 -1
  52. package/dist/hooks.d.ts +111 -15
  53. package/dist/hooks.js +5 -0
  54. package/dist/index.d.ts +18 -1
  55. package/dist/index.js +18 -1
  56. package/dist/marketplace.d.ts +55 -2
  57. package/dist/marketplace.js +73 -3
  58. package/dist/model.d.ts +60 -2
  59. package/dist/model.js +22 -0
  60. package/dist/org-access.d.ts +27 -0
  61. package/dist/org-access.js +35 -0
  62. package/dist/permissions.d.ts +33 -8
  63. package/dist/permissions.js +89 -22
  64. package/dist/plugin-manifest.d.ts +60 -7
  65. package/dist/plugin-manifest.js +178 -7
  66. package/dist/sandbox.d.ts +239 -62
  67. package/dist/sandbox.js +99 -14
  68. package/dist/setup-check.d.ts +115 -0
  69. package/dist/setup-check.js +142 -0
  70. package/dist/setup-guide-parse.d.ts +121 -0
  71. package/dist/setup-guide-parse.js +350 -0
  72. package/dist/setup-guide-render.d.ts +45 -0
  73. package/dist/setup-guide-render.js +351 -0
  74. package/dist/setup-guide.d.ts +94 -0
  75. package/dist/setup-guide.js +336 -0
  76. package/dist/skill-invocation.d.ts +9 -5
  77. package/dist/skill-invocation.js +18 -8
  78. package/dist/skill.d.ts +23 -3
  79. package/dist/skill.js +31 -6
  80. package/dist/theme-assets.d.ts +39 -0
  81. package/dist/theme-assets.js +449 -0
  82. package/dist/theme-readability.d.ts +37 -0
  83. package/dist/theme-readability.js +145 -0
  84. package/dist/theme-tokens.generated.d.ts +275 -0
  85. package/dist/theme-tokens.generated.js +172 -0
  86. package/dist/theme.d.ts +152 -0
  87. package/dist/theme.js +392 -0
  88. package/dist/tool.d.ts +26 -3
  89. package/dist/tool.js +8 -0
  90. package/dist/ui-parts.d.ts +23 -0
  91. package/dist/ui-parts.js +337 -0
  92. package/dist/ui-resolve.d.ts +40 -0
  93. package/dist/ui-resolve.js +54 -0
  94. package/dist/ui-slots.d.ts +55 -0
  95. package/dist/ui-slots.js +247 -0
  96. package/dist/ui.d.ts +143 -37
  97. package/dist/ui.js +65 -5
  98. package/dist/web.d.ts +30 -5
  99. package/package.json +10 -2
  100. package/schemas/bootstrap.v1.schema.json +6 -0
  101. package/schemas/connector-template.v1.schema.json +3 -0
  102. package/schemas/marketplace.v1.schema.json +50 -0
  103. package/schemas/plugin.v1.schema.json +144 -7
  104. package/schemas/theme.v1.schema.json +225 -0
package/dist/sandbox.d.ts CHANGED
@@ -1,39 +1,131 @@
1
1
  /**
2
- * Sandbox contract `sandbox@1`: a single-select, brokered extension point (extensions may not
2
+ * Sandbox contract `sandbox@2`: a single-select, brokered extension point (extensions may not
3
3
  * `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
+ *
7
+ * `@2` separates a device's **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).
6
10
  */
7
11
  /** Sandbox extension point ref. */
8
- export declare const SANDBOX_EXTENSION_POINT = "sandbox@1";
9
- /** 沙箱内允许模型访问的根目录。 */
12
+ export declare const SANDBOX_EXTENSION_POINT = "sandbox@2";
13
+ /** The roots inside the sandbox the model may access. */
10
14
  export declare const SANDBOX_ROOTS: readonly ["/workspace", "/skills", "/tmp"];
11
- /** 沙箱资源与出站限制。 */
15
+ /**
16
+ * A sandbox tier, ordered `strict` < `dev` < `open`: how much a device's commands may reach.
17
+ * `strict` is the org's allowlist only; `dev` adds the dev hosts (`DEV_HOSTS`) and local
18
+ * development affordances; `open` reaches any public host.
19
+ */
20
+ export type SandboxTier = "strict" | "dev" | "open";
21
+ /** Every tier, lowest first. */
22
+ export declare const SANDBOX_TIERS: readonly SandboxTier[];
23
+ /** Whether `v` is a {@link SandboxTier}. */
24
+ export declare function isSandboxTier(v: unknown): v is SandboxTier;
25
+ /** Negative when `a` is lower than `b`, 0 when equal, positive when higher. */
26
+ export declare function compareTiers(a: SandboxTier, b: SandboxTier): number;
27
+ /** Whether `a` is at most `b`. */
28
+ export declare function tierAtMost(a: SandboxTier, b: SandboxTier): boolean;
29
+ /** The lowest of the given tiers. */
30
+ export declare function minTier(first: SandboxTier, ...rest: SandboxTier[]): SandboxTier;
31
+ /** Sandbox resource and egress limits. */
12
32
  export interface SandboxLimits {
13
33
  cpu: number;
14
34
  memoryMb: number;
15
35
  diskMb: number;
16
36
  egress: "none" | "allowlist" | "open";
17
- /** 出站白名单(`egress` 为 `allowlist` 时生效);每项须通过 {@link validateAllowHost}。 */
37
+ /** Egress allowlist (used when `egress` is `allowlist`); each entry passes {@link validateAllowHost}. */
18
38
  allowHosts: string[];
39
+ /**
40
+ * The effective tier (cloud `create`) or the ceiling the device may reach (local exec args). A
41
+ * provider that ignores it behaves as `strict` plus whatever `egress` says.
42
+ */
43
+ tier: SandboxTier;
44
+ /** Local exec args only: the org's default tier, used when the device chose none. */
45
+ defaultTier?: SandboxTier;
46
+ /**
47
+ * Local exec args only: whether this command may run without a sandbox (the platform and the
48
+ * org allow it, the ceiling is `open`, and an unattended run has the `tier:open` grant). A device
49
+ * whose local policy asks for no sandbox refuses the command unless this is `true` (absent counts
50
+ * as `false`), with {@link UNSANDBOXED_NOT_ALLOWED_MESSAGE}.
51
+ */
52
+ allowUnsandboxed?: boolean;
53
+ /** The dev hosts preset; cloud providers ignore it (`allowHosts` is final for them). */
54
+ devHosts: string[];
55
+ }
56
+ /**
57
+ * The refusal of a command that would run without a sandbox where the org does not allow it
58
+ * (sandbox dev tiers spec §4.3): the kernel's `device.unsandboxed_not_allowed` text, and the
59
+ * message a device sends with a `policy` error when `allowUnsandboxed` is not `true`.
60
+ */
61
+ export declare const UNSANDBOXED_NOT_ALLOWED_MESSAGE = "This device runs commands without a sandbox, which your organization does not allow. Its owner can turn the sandbox back on with `capybara-device policy set isolation sandbox`.";
62
+ /** The absolute roots inside one instance (a device may place them anywhere on its host). */
63
+ export interface SandboxRoots {
64
+ workspace: string;
65
+ skills: string;
66
+ tmp: string;
19
67
  }
20
- /** 提供方的实例句柄。 */
68
+ /** The roots every container-like provider uses; the same paths as {@link SANDBOX_ROOTS}. */
69
+ export declare const DEFAULT_SANDBOX_ROOTS: Readonly<SandboxRoots>;
70
+ /** The provider's instance handle. */
21
71
  export interface SandboxHandle {
22
- /** 提供方的实例 id。 */
72
+ /** The provider's instance id. */
73
+ id: string;
74
+ /** The instance's roots; absent means {@link DEFAULT_SANDBOX_ROOTS}. */
75
+ roots?: SandboxRoots;
76
+ }
77
+ /** The roots of an instance, falling back to {@link DEFAULT_SANDBOX_ROOTS}. */
78
+ export declare function rootsOf(h: SandboxHandle): SandboxRoots;
79
+ /** The provider's file system handle (a device's files, independent of any instance). */
80
+ export interface FileSystemHandle {
81
+ /** The provider's file system id. */
23
82
  id: string;
24
83
  }
25
- /** 命令执行结果。 */
84
+ /** Who runs an `exec` (informational in phase 1: audit and attribution). */
85
+ export interface SandboxActor {
86
+ accountId: string;
87
+ conversationId: string;
88
+ /**
89
+ * The run the command serves. The kernel uses it to route run grants (network hosts allowed
90
+ * for the rest of a run) to a connected device; informational for other providers.
91
+ */
92
+ runId?: string;
93
+ }
94
+ /**
95
+ * The layer that refused a network host: `device` (the org allows it, the device's local policy
96
+ * does not), `org` (not in the org's effective egress), `address` (an IP literal or a name that
97
+ * points to a private or local address; never grantable), `unknown`.
98
+ */
99
+ export type NetworkBlockLayer = "device" | "org" | "address" | "unknown";
100
+ /** A host a command was refused, as the provider reports it. */
101
+ export interface NetworkBlockedHost {
102
+ /** The host as the proxy saw it (IPv6 literals bracketed). */
103
+ host: string;
104
+ port: number;
105
+ layer: NetworkBlockLayer;
106
+ }
107
+ /** Result of a command. */
26
108
  export interface ExecResult {
27
- /** 超时或在执行中被中止为 null(此时 `timedOut` 分别为 true / false)。 */
109
+ /** null on timeout or when aborted while running (`timedOut` is then true / false). */
28
110
  exitCode: number | null;
29
111
  stdout: string;
30
112
  stderr: string;
31
113
  truncated: boolean;
32
114
  timedOut: boolean;
115
+ /**
116
+ * Network refusals during the command (optional for every provider): at most
117
+ * `MAX_NETWORK_BLOCKED_HOSTS` hosts, deduped by host. The kernel recomputes the `org` layer
118
+ * itself and never trusts a provider's word that the org allows a host.
119
+ */
120
+ network?: {
121
+ blocked: NetworkBlockedHost[];
122
+ };
33
123
  }
34
124
  /**
35
- * 实例在提供方那边确定已经不在了(容器被删、E2B 沙箱过期)。`exec` / `readFile` / `writeFile` / `stat`
36
- * 发现实例不在时必须抛它(而不是普通 Error),内核据此重建沙箱并重试一次;只是暂时连不上时抛普通错误。
125
+ * The instance is definitely gone on the provider's side (container removed, E2B sandbox expired).
126
+ * `exec` / `readFile` / `writeFile` / `stat` must throw it (not a plain Error) when they find the
127
+ * instance gone; the kernel then rebuilds the instance and retries once. A transient connection
128
+ * failure throws a plain error.
37
129
  */
38
130
  export declare class SandboxGoneError extends Error {
39
131
  readonly sandboxGone: true;
@@ -41,8 +133,21 @@ export declare class SandboxGoneError extends Error {
41
133
  cause?: unknown;
42
134
  });
43
135
  }
44
- /** 鸭子类型判断(不用 instanceof),兼容插件自带另一份 plugin-sdk 副本的情况。 */
136
+ /** Duck-typed check (not instanceof), so a plugin bundling another plugin-sdk copy still matches. */
45
137
  export declare function isSandboxGoneError(e: unknown): e is SandboxGoneError;
138
+ /**
139
+ * The file system is definitely gone on the provider's side (volume removed, E2B sandbox killed).
140
+ * `create` throws it instead of attaching the instance to a new, empty file system; the kernel then
141
+ * reports the device's files as lost rather than handing out a silently empty workspace.
142
+ */
143
+ export declare class FileSystemGoneError extends Error {
144
+ readonly fileSystemGone: true;
145
+ constructor(message: string, opts?: {
146
+ cause?: unknown;
147
+ });
148
+ }
149
+ /** Duck-typed check (not instanceof), so a plugin bundling another plugin-sdk copy still matches. */
150
+ export declare function isFileSystemGoneError(e: unknown): e is FileSystemGoneError;
46
151
  /**
47
152
  * A holder tag (`exec` argument `tag`, {@link SandboxProvider.killTagged}): the kernel passes its
48
153
  * lease tokens (UUIDs). Providers check tags against it before putting them in a command line or a
@@ -50,73 +155,130 @@ export declare function isSandboxGoneError(e: unknown): e is SandboxGoneError;
50
155
  */
51
156
  export declare const SANDBOX_TAG_RE: RegExp;
52
157
  /**
53
- * `sandbox@1` 的实现(由沙箱插件提供,如 Docker、E2B)。
54
- * 实例确定不在时:`resume` 返回 `gone`;`exec` / `readFile` / `writeFile` / `stat` 抛 {@link SandboxGoneError};
55
- * `suspend` / `destroy` 照常成功。
158
+ * The `sandbox@2` implementation (provided by a sandbox plugin such as Docker or E2B).
159
+ *
160
+ * **File systems and instances.** `createFileSystem` makes a device's files; they live until
161
+ * `destroyFileSystem` (the device is deleted). `create` makes an instance attached to an
162
+ * existing file system; `destroy` / `destroyByName` drop the instance only and keep the files, and
163
+ * `suspend` keeps them too. When the file system is gone, `create` must throw
164
+ * {@link FileSystemGoneError} and never create an empty one in its place (a Docker provider checks
165
+ * its volumes exist before mounting them, because Docker would otherwise create empty volumes).
56
166
  *
57
- * **自动启动**:实例还在、但已停止 / 暂停(被内核之外的原因停掉:宿主机重启、守护进程重启、沙箱里的进程把
58
- * 自己的 init 弄停了、休眠扫描停了实例却没来得及记下 `suspended`……)时,`exec` / `readFile` / `writeFile` /
59
- * `stat` 必须先透明地把它启动起来(同 `resume`,文件保留)再执行,而不是报错——内核只信自己记的 `running`。
167
+ * **Gone instances.** When the instance is definitely gone: `resume` returns `gone`; `exec` /
168
+ * `readFile` / `writeFile` / `stat` / `killAll` / `killTagged` throw {@link SandboxGoneError};
169
+ * `suspend` / `destroy` succeed as usual.
60
170
  *
61
- * **命令时限在沙箱里也要生效**:`exec` 除了在提供方这边按 `timeoutMs` 停掉命令,还必须让沙箱里的命令自己在
62
- * `timeoutMs` 之后不久(几秒的余量)被杀掉。内核副本崩溃时提供方这边的计时随之消失,断开连接也不会结束命令;
63
- * 沙箱里的时限保证它不会无限期地与下一个持锁方的命令同时运行。
171
+ * **Auto-start**: when the instance still exists but is stopped or paused (for a reason outside the
172
+ * kernel: host or daemon restart, a process in the sandbox stopping its init, an idle sweep that
173
+ * stopped the instance before recording `suspended`...), `exec` / `readFile` / `writeFile` /
174
+ * `stat` / `killAll` / `killTagged` must start it transparently first (like `resume`, files kept)
175
+ * and then run, never fail: the kernel trusts only the `running` it recorded itself. Auto-start
176
+ * must be idempotent under concurrent calls: two calls that both find the instance stopped both
177
+ * start it without failing.
64
178
  *
65
- * **中止**:每个方法都必须及时响应 `signal`(已中止就立即失败,进行中被中止就尽快以中止原因结束)——内核在锁丢失、
66
- * 运行被中止或超时时靠它停下,不响应就可能与新的持锁方同时操作同一实例。`exec` 被中止时必须杀掉正在跑的命令
67
- * (连同它派生的进程),而不只是不再等待它的输出;命令启动后才被中止的 `exec` 以 `exitCode: null`、
68
- * `timedOut: false` 正常 resolve(带上已收集的输出),不 reject。调用时 signal 已中止则立即 reject。
179
+ * **Time limits apply inside the sandbox too**: besides stopping a command after `timeoutMs` on the
180
+ * provider's side, `exec` must make the command in the sandbox kill itself shortly (a few seconds)
181
+ * after `timeoutMs`. When a kernel replica crashes, the provider-side timer goes with it, and a
182
+ * dropped connection does not end the command; the in-sandbox limit keeps it from running
183
+ * indefinitely next to the next holder's commands.
69
184
  *
70
- * **Concurrent use (optional)**: a provider that declares {@link SandboxProvider.concurrentExec}
71
- * lets the kernel call `exec`, `readFile`, `writeFile` and `stat` concurrently on one instance
72
- * (commands of parallel sub-agents sharing their parent conversation's sandbox). Then those four
73
- * methods must be safe to call concurrently, and **auto-start must be idempotent under concurrent
74
- * calls**: two calls that both find the instance stopped both start it without failing. Each
75
- * `exec` labels its command with its `tag`, and an aborted `exec` kills only its own command.
76
- * `concurrentExec` requires {@link SandboxProvider.killTagged}; a provider that declares one
77
- * without the other, or neither, is used one call at a time (the behavior without them).
185
+ * **Abort**: every method must respond to `signal` promptly (fail at once when already aborted, end
186
+ * with the abort reason as soon as possible when aborted mid-way): the kernel relies on it to stop
187
+ * on lock loss, run abort or timeout, and ignoring it may let two holders operate on one instance.
188
+ * An aborted `exec` must kill its running command (and the processes it spawned), not just stop
189
+ * waiting for its output; an `exec` aborted after its command started resolves normally with
190
+ * `exitCode: null`, `timedOut: false` (and the output collected so far), it does not reject. An
191
+ * `exec` called with an already aborted signal rejects at once.
192
+ *
193
+ * **Concurrent use** (required in `@2`): the sessions of one device share its instance, so the
194
+ * kernel calls `exec`, `readFile`, `writeFile` and `stat` concurrently on one instance. Those four
195
+ * methods must be safe to call concurrently. Each `exec` labels its command with its `tag`, and an
196
+ * aborted `exec` kills only its own command.
78
197
  */
79
198
  export interface SandboxProvider {
199
+ /** `exec` / `readFile` / `writeFile` / `stat` may run concurrently on one instance (required). */
200
+ readonly concurrentExec: true;
201
+ /**
202
+ * Whether the provider isolates the sessions of one device from each other inside the
203
+ * instance (a declared capability; absent means false).
204
+ */
205
+ readonly sessionIsolation?: boolean;
80
206
  /**
81
- * Declares that `exec` / `readFile` / `writeFile` / `stat` may run concurrently on one instance
82
- * (see the contract above). Requires {@link SandboxProvider.killTagged}.
207
+ * Where `create`-time limits are fixed: `instance` (absent; Docker: a new instance applies new
208
+ * limits) or `fileSystem` (E2B: the instance is the file system, so only a file reset applies
209
+ * them without {@link SandboxProvider.update}).
210
+ */
211
+ readonly limitsApplyAt?: "instance" | "fileSystem";
212
+ /**
213
+ * Applies new limits to a running instance without recreating it (optional). `recreate` asks
214
+ * the kernel to destroy the instance and create one on the same files instead.
215
+ */
216
+ update?(h: SandboxHandle, limits: SandboxLimits, signal: AbortSignal): Promise<"updated" | "recreate">;
217
+ /**
218
+ * Creates a device's file system. `name` looks like `cap-device-<deviceId>`. If a file
219
+ * system with this name already exists, return it.
220
+ */
221
+ createFileSystem(args: {
222
+ name: string;
223
+ limits: SandboxLimits;
224
+ signal: AbortSignal;
225
+ }): Promise<FileSystemHandle>;
226
+ /** Deletes the file system and its files. Succeeds when it does not exist. */
227
+ destroyFileSystem(fs: FileSystemHandle, signal: AbortSignal): Promise<void>;
228
+ /**
229
+ * Deletes the file system made under `name` by `createFileSystem`; succeeds when there is none.
230
+ * The kernel uses it when it has no handle (`createFileSystem` finished on the provider's side
231
+ * but the kernel stopped before recording the handle), and in its one-off cleanup of
232
+ * per-conversation sandboxes with `cap-<conversationId>` names that a `sandbox@1` provider's
233
+ * `create` made together with their files (Docker: the `cap-<conversationId>-workspace` and
234
+ * `-skills` volumes); a provider removes those under the same call.
235
+ */
236
+ destroyFileSystemByName(name: string, signal: AbortSignal): Promise<void>;
237
+ /**
238
+ * Creates an instance attached to `fileSystem`. Without `image` the provider uses its own
239
+ * published image. Throws {@link FileSystemGoneError} when the file system is gone.
83
240
  */
84
- readonly concurrentExec?: boolean;
85
- /** `name` 形如 `cap-<conversationId>`。 */
86
241
  create(args: {
87
242
  name: string;
88
- image: string;
243
+ image?: string;
89
244
  limits: SandboxLimits;
245
+ fileSystem: FileSystemHandle;
90
246
  signal: AbortSignal;
91
247
  }): Promise<SandboxHandle>;
92
- /** `gone` 表示提供方那边已经没有这个实例。 */
248
+ /** `gone` means the provider no longer has this instance. */
93
249
  resume(h: SandboxHandle, signal: AbortSignal): Promise<"resumed" | "gone">;
94
- /** 文件必须保留。实例不存在也算成功。 */
250
+ /** Files must be kept. Succeeds when the instance does not exist. */
95
251
  suspend(h: SandboxHandle, signal: AbortSignal): Promise<void>;
96
- /** 不存在也算成功。 */
252
+ /** Drops the instance only; the file system and its files are kept. Succeeds when it does not exist. */
97
253
  destroy(h: SandboxHandle, signal: AbortSignal): Promise<void>;
98
254
  /**
99
- * 可选:按 `create` 时的 `name`(`cap-<conversationId>`)销毁实例,不存在也算成功。
100
- * 内核在拿不到句柄时用它清理(例如 `create` 已在提供方那边完成、内核却在记下句柄前退出)。
255
+ * Drops the instance made under `name` by `create` (instance only, files kept); succeeds when
256
+ * there is none. The kernel uses it when it has no handle (`create` finished on the provider's
257
+ * side but the kernel stopped before recording the handle), and in its one-off cleanup of
258
+ * per-conversation sandboxes with `cap-<conversationId>` names made by a `sandbox@1` provider's
259
+ * `create`.
101
260
  */
102
- destroyByName?(name: string, signal: AbortSignal): Promise<void>;
261
+ destroyByName(name: string, signal: AbortSignal): Promise<void>;
103
262
  /**
104
- * 可选:杀掉这个实例里经 `exec` 启动、仍在运行的全部命令(连同它们派生的、没有自己另起会话的进程)。
105
- * 内核在接手一个前任持锁方没有正常结束的沙箱(前任崩溃)时、第一次执行前调用,清掉前任遗留的命令;
106
- * 命令自己放到后台、另起会话的进程不保证被杀。实例已停止时同样先启动;不在时抛 {@link SandboxGoneError}。
263
+ * Kills every running command started through `exec` in this instance (and the processes they
264
+ * spawned that did not start their own session). The kernel calls it only when no other holder
265
+ * can be running commands (an instance just resumed from `suspended`, or under the exclusive
266
+ * lease), never while another session may be; to clean up after one crashed holder it uses
267
+ * {@link SandboxProvider.killTagged}. Processes a command put in the background in their own
268
+ * session are not guaranteed to be killed.
107
269
  */
108
- killAll?(h: SandboxHandle, signal: AbortSignal): Promise<void>;
270
+ killAll(h: SandboxHandle, signal: AbortSignal): Promise<void>;
109
271
  /**
110
- * Optional: kill every running `exec` command labelled with one of `tags` (and its process
111
- * tree), leaving other commands running. The kernel calls it for the tags of holders that
112
- * crashed while live holders keep running commands. Tags match {@link SANDBOX_TAG_RE}. Match
113
- * whole tags: one tag may be a prefix of another (`ab` of `ab-cd`), and killing `ab` must not
114
- * touch `ab-cd`'s commands. Starts a stopped instance first; throws {@link SandboxGoneError}
115
- * when the instance is gone.
272
+ * Kills every running `exec` command labelled with one of `tags` (and its process tree), leaving
273
+ * other commands running. The kernel calls it for the tags of holders that crashed while live
274
+ * holders keep running commands. Tags match {@link SANDBOX_TAG_RE}. Match whole tags: one tag
275
+ * may be a prefix of another (`ab` of `ab-cd`), and killing `ab` must not touch `ab-cd`'s
276
+ * commands.
116
277
  */
117
- killTagged?(h: SandboxHandle, tags: string[], signal: AbortSignal): Promise<void>;
278
+ killTagged(h: SandboxHandle, tags: string[], signal: AbortSignal): Promise<void>;
118
279
  /**
119
- * 执行一条命令。`maxOutputBytes` 是 stdout 与 stderr **合计**最多收集的字节,超出的丢弃、`truncated` 为 true。
280
+ * Runs a command. `maxOutputBytes` caps stdout and stderr **combined**; the rest is dropped and
281
+ * `truncated` is true.
120
282
  */
121
283
  exec(h: SandboxHandle, args: {
122
284
  command: string;
@@ -127,11 +289,16 @@ export interface SandboxProvider {
127
289
  signal: AbortSignal;
128
290
  /**
129
291
  * The holder's tag ({@link SANDBOX_TAG_RE}); label the command with it so
130
- * {@link SandboxProvider.killTagged} can find it. Absent from kernels before phase C.
292
+ * {@link SandboxProvider.killTagged} can find it.
131
293
  */
132
- tag?: string;
294
+ tag: string;
295
+ /** Who runs the command; informational in phase 1 (record it, do not act on it). */
296
+ actor: SandboxActor;
133
297
  }): Promise<ExecResult>;
134
- /** 读文件(最多 `maxBytes` 字节,更长的截断、`truncated` 为 true)。不存在、或是目录时返回 null。 */
298
+ /**
299
+ * Reads a file (at most `maxBytes`; longer files are truncated and `truncated` is true). Returns
300
+ * null when it does not exist or is a directory.
301
+ */
135
302
  readFile(h: SandboxHandle, path: string, opts: {
136
303
  maxBytes: number;
137
304
  signal: AbortSignal;
@@ -139,14 +306,24 @@ export interface SandboxProvider {
139
306
  data: Uint8Array;
140
307
  truncated: boolean;
141
308
  } | null>;
142
- /** 父目录自动创建。 */
309
+ /** Parent directories are created. */
143
310
  writeFile(h: SandboxHandle, path: string, data: Uint8Array, signal: AbortSignal): Promise<void>;
144
311
  stat(h: SandboxHandle, path: string, signal: AbortSignal): Promise<{
145
312
  size: number;
146
313
  isDir: boolean;
147
314
  } | null>;
148
315
  }
149
- /** 校验沙箱内路径:返回错误列表,空数组表示合法。 */
150
- export declare function validateSandboxPath(p: string): string[];
316
+ /**
317
+ * The root-independent checks of a path inside an instance (non-empty, at most 4096 characters, no
318
+ * control characters or backslashes, absolute, no empty or `..` segments); returns the errors,
319
+ * empty when valid. {@link validateSandboxPath} adds root membership.
320
+ */
321
+ export declare function validateSandboxPathShape(p: string): string[];
322
+ /**
323
+ * Checks a path inside an instance; returns the errors, empty when valid: the
324
+ * {@link validateSandboxPathShape} checks, then root membership. `roots`: the instance's roots
325
+ * ({@link rootsOf}); absent means {@link SANDBOX_ROOTS}. The path must be one of them or under one.
326
+ */
327
+ export declare function validateSandboxPath(p: string, roots?: SandboxRoots): string[];
151
328
  /** 校验出站白名单主机名:小写、无协议与端口、可选前导 `*.`、IDN 只认 punycode。 */
152
329
  export declare function validateAllowHost(h: string): string[];
package/dist/sandbox.js CHANGED
@@ -1,17 +1,61 @@
1
1
  /**
2
- * Sandbox contract `sandbox@1`: a single-select, brokered extension point (extensions may not
2
+ * Sandbox contract `sandbox@2`: a single-select, brokered extension point (extensions may not
3
3
  * `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
+ *
7
+ * `@2` separates a device's **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).
6
10
  */
7
11
  /** Sandbox extension point ref. */
8
- export const SANDBOX_EXTENSION_POINT = "sandbox@1";
9
- /** 沙箱内允许模型访问的根目录。 */
12
+ export const SANDBOX_EXTENSION_POINT = "sandbox@2";
13
+ /** The roots inside the sandbox the model may access. */
10
14
  export const SANDBOX_ROOTS = ["/workspace", "/skills", "/tmp"];
11
15
  const MAX_PATH_LENGTH = 4096;
16
+ /** Every tier, lowest first. */
17
+ export const SANDBOX_TIERS = Object.freeze(["strict", "dev", "open"]);
18
+ /** Whether `v` is a {@link SandboxTier}. */
19
+ export function isSandboxTier(v) {
20
+ return typeof v === "string" && SANDBOX_TIERS.includes(v);
21
+ }
22
+ /** Negative when `a` is lower than `b`, 0 when equal, positive when higher. */
23
+ export function compareTiers(a, b) {
24
+ return SANDBOX_TIERS.indexOf(a) - SANDBOX_TIERS.indexOf(b);
25
+ }
26
+ /** Whether `a` is at most `b`. */
27
+ export function tierAtMost(a, b) {
28
+ return compareTiers(a, b) <= 0;
29
+ }
30
+ /** The lowest of the given tiers. */
31
+ export function minTier(first, ...rest) {
32
+ let out = first;
33
+ for (const t of rest)
34
+ if (compareTiers(t, out) < 0)
35
+ out = t;
36
+ return out;
37
+ }
38
+ /**
39
+ * The refusal of a command that would run without a sandbox where the org does not allow it
40
+ * (sandbox dev tiers spec §4.3): the kernel's `device.unsandboxed_not_allowed` text, and the
41
+ * message a device sends with a `policy` error when `allowUnsandboxed` is not `true`.
42
+ */
43
+ export const UNSANDBOXED_NOT_ALLOWED_MESSAGE = "This device runs commands without a sandbox, which your organization does not allow. Its owner can turn the sandbox back on with `capybara-device policy set isolation sandbox`.";
44
+ /** The roots every container-like provider uses; the same paths as {@link SANDBOX_ROOTS}. */
45
+ export const DEFAULT_SANDBOX_ROOTS = Object.freeze({
46
+ workspace: "/workspace",
47
+ skills: "/skills",
48
+ tmp: "/tmp",
49
+ });
50
+ /** The roots of an instance, falling back to {@link DEFAULT_SANDBOX_ROOTS}. */
51
+ export function rootsOf(h) {
52
+ return h.roots ?? DEFAULT_SANDBOX_ROOTS;
53
+ }
12
54
  /**
13
- * 实例在提供方那边确定已经不在了(容器被删、E2B 沙箱过期)。`exec` / `readFile` / `writeFile` / `stat`
14
- * 发现实例不在时必须抛它(而不是普通 Error),内核据此重建沙箱并重试一次;只是暂时连不上时抛普通错误。
55
+ * The instance is definitely gone on the provider's side (container removed, E2B sandbox expired).
56
+ * `exec` / `readFile` / `writeFile` / `stat` must throw it (not a plain Error) when they find the
57
+ * instance gone; the kernel then rebuilds the instance and retries once. A transient connection
58
+ * failure throws a plain error.
15
59
  */
16
60
  export class SandboxGoneError extends Error {
17
61
  sandboxGone = true;
@@ -20,12 +64,30 @@ export class SandboxGoneError extends Error {
20
64
  this.name = "SandboxGoneError";
21
65
  }
22
66
  }
23
- /** 鸭子类型判断(不用 instanceof),兼容插件自带另一份 plugin-sdk 副本的情况。 */
67
+ /** Duck-typed check (not instanceof), so a plugin bundling another plugin-sdk copy still matches. */
24
68
  export function isSandboxGoneError(e) {
25
69
  return (e instanceof Error &&
26
70
  e.name === "SandboxGoneError" &&
27
71
  e.sandboxGone === true);
28
72
  }
73
+ /**
74
+ * The file system is definitely gone on the provider's side (volume removed, E2B sandbox killed).
75
+ * `create` throws it instead of attaching the instance to a new, empty file system; the kernel then
76
+ * reports the device's files as lost rather than handing out a silently empty workspace.
77
+ */
78
+ export class FileSystemGoneError extends Error {
79
+ fileSystemGone = true;
80
+ constructor(message, opts) {
81
+ super(message, opts && "cause" in opts ? { cause: opts.cause } : undefined);
82
+ this.name = "FileSystemGoneError";
83
+ }
84
+ }
85
+ /** Duck-typed check (not instanceof), so a plugin bundling another plugin-sdk copy still matches. */
86
+ export function isFileSystemGoneError(e) {
87
+ return (e instanceof Error &&
88
+ e.name === "FileSystemGoneError" &&
89
+ e.fileSystemGone === true);
90
+ }
29
91
  /**
30
92
  * A holder tag (`exec` argument `tag`, {@link SandboxProvider.killTagged}): the kernel passes its
31
93
  * lease tokens (UUIDs). Providers check tags against it before putting them in a command line or a
@@ -34,8 +96,12 @@ export function isSandboxGoneError(e) {
34
96
  export const SANDBOX_TAG_RE = /^[a-z0-9-]{1,64}$/;
35
97
  // biome-ignore lint/suspicious/noControlCharactersInRegex: 正是要拦控制字符
36
98
  const CONTROL = /[\u0000-\u001f\u007f]/;
37
- /** 校验沙箱内路径:返回错误列表,空数组表示合法。 */
38
- export function validateSandboxPath(p) {
99
+ /**
100
+ * The root-independent checks of a path inside an instance (non-empty, at most 4096 characters, no
101
+ * control characters or backslashes, absolute, no empty or `..` segments); returns the errors,
102
+ * empty when valid. {@link validateSandboxPath} adds root membership.
103
+ */
104
+ export function validateSandboxPathShape(p) {
39
105
  if (typeof p !== "string" || p.length === 0)
40
106
  return ["path must be a non-empty string"];
41
107
  if (p.length > MAX_PATH_LENGTH)
@@ -48,22 +114,41 @@ export function validateSandboxPath(p) {
48
114
  return ["path must be absolute"];
49
115
  if (p.includes("//"))
50
116
  return ["path must not contain empty segments"];
51
- const errors = [];
52
117
  for (const seg of p.split("/")) {
53
118
  let decoded = seg;
54
119
  try {
55
120
  decoded = decodeURIComponent(seg);
56
121
  }
57
122
  catch {
58
- // 非法百分号编码按字面处理
123
+ // invalid percent-encoding is taken literally
59
124
  }
60
125
  if (seg === ".." || decoded === ".." || decoded.includes("/") || decoded.includes("\\")) {
61
- errors.push("path must not contain '..' segments");
62
- break;
126
+ return ["path must not contain '..' segments"];
63
127
  }
64
128
  }
65
- if (!SANDBOX_ROOTS.some((r) => p === r || p.startsWith(`${r}/`))) {
66
- errors.push(`path must be under ${SANDBOX_ROOTS.join(", ")}`);
129
+ return [];
130
+ }
131
+ /** A structural error after which {@link validateSandboxPath} stops (before the root check). */
132
+ const STOPS = new Set([
133
+ "path must be a non-empty string",
134
+ `path must be at most ${MAX_PATH_LENGTH} characters`,
135
+ "path must not contain control characters",
136
+ "path must not contain backslashes",
137
+ "path must be absolute",
138
+ "path must not contain empty segments",
139
+ ]);
140
+ /**
141
+ * Checks a path inside an instance; returns the errors, empty when valid: the
142
+ * {@link validateSandboxPathShape} checks, then root membership. `roots`: the instance's roots
143
+ * ({@link rootsOf}); absent means {@link SANDBOX_ROOTS}. The path must be one of them or under one.
144
+ */
145
+ export function validateSandboxPath(p, roots) {
146
+ const errors = validateSandboxPathShape(p);
147
+ if (errors.some((e) => STOPS.has(e)))
148
+ return errors;
149
+ const allowed = roots === undefined ? SANDBOX_ROOTS : [roots.workspace, roots.skills, roots.tmp];
150
+ if (!allowed.some((r) => p === r || p.startsWith(`${r}/`))) {
151
+ errors.push(`path must be under ${allowed.join(", ")}`);
67
152
  }
68
153
  return errors;
69
154
  }