@capybara-hq/plugin-sdk 0.1.0-rc.1 → 0.1.0-rc.11

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 (97) hide show
  1. package/README.md +1 -1
  2. package/agent-docs/agent-templates.md +47 -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/counter.md +15 -0
  9. package/agent-docs/extension-points/directory.md +15 -0
  10. package/agent-docs/extension-points/file-preview.md +15 -0
  11. package/agent-docs/extension-points/identity-source.md +15 -0
  12. package/agent-docs/extension-points/model-provider.md +15 -0
  13. package/agent-docs/extension-points/object-store.md +15 -0
  14. package/agent-docs/extension-points/sandbox.md +15 -0
  15. package/agent-docs/extension-points/secret-store.md +15 -0
  16. package/agent-docs/extension-points/web-fetch.md +15 -0
  17. package/agent-docs/extension-points/web-search.md +15 -0
  18. package/agent-docs/extensions.md +87 -0
  19. package/agent-docs/plugin-format.md +100 -0
  20. package/agent-docs/setup.md +46 -0
  21. package/agent-docs/skills.md +44 -0
  22. package/agent-docs/tool-naming.md +21 -0
  23. package/dist/agent-template.d.ts +85 -0
  24. package/dist/agent-template.js +361 -2
  25. package/dist/cards.d.ts +7 -0
  26. package/dist/cards.js +4 -4
  27. package/dist/channel.d.ts +20 -1
  28. package/dist/client-css.d.ts +36 -0
  29. package/dist/client-css.js +326 -0
  30. package/dist/client-section.d.ts +35 -0
  31. package/dist/client-section.js +133 -0
  32. package/dist/config-ui.d.ts +131 -0
  33. package/dist/config-ui.js +602 -0
  34. package/dist/connector-auth.d.ts +2 -0
  35. package/dist/connector-auth.js +15 -0
  36. package/dist/ctx.d.ts +86 -4
  37. package/dist/define-extension.d.ts +5 -1
  38. package/dist/define-extension.js +1 -0
  39. package/dist/device-protocol.d.ts +118 -0
  40. package/dist/device-protocol.js +276 -0
  41. package/dist/directory.d.ts +11 -2
  42. package/dist/extension-point.d.ts +9 -0
  43. package/dist/extension-point.js +17 -12
  44. package/dist/file-preview.d.ts +9 -1
  45. package/dist/hooks.d.ts +76 -16
  46. package/dist/index.d.ts +18 -1
  47. package/dist/index.js +18 -1
  48. package/dist/marketplace.d.ts +55 -2
  49. package/dist/marketplace.js +73 -3
  50. package/dist/model.d.ts +60 -2
  51. package/dist/model.js +22 -0
  52. package/dist/org-access.d.ts +27 -0
  53. package/dist/org-access.js +35 -0
  54. package/dist/permissions.d.ts +32 -7
  55. package/dist/permissions.js +86 -22
  56. package/dist/plugin-manifest.d.ts +70 -5
  57. package/dist/plugin-manifest.js +186 -6
  58. package/dist/sandbox.d.ts +164 -62
  59. package/dist/sandbox.js +71 -14
  60. package/dist/secret.d.ts +4 -1
  61. package/dist/secret.js +5 -2
  62. package/dist/setup-check.d.ts +115 -0
  63. package/dist/setup-check.js +142 -0
  64. package/dist/setup-guide-parse.d.ts +121 -0
  65. package/dist/setup-guide-parse.js +350 -0
  66. package/dist/setup-guide-render.d.ts +45 -0
  67. package/dist/setup-guide-render.js +351 -0
  68. package/dist/setup-guide.d.ts +94 -0
  69. package/dist/setup-guide.js +336 -0
  70. package/dist/skill-invocation.d.ts +9 -5
  71. package/dist/skill-invocation.js +18 -8
  72. package/dist/skill.d.ts +23 -3
  73. package/dist/skill.js +31 -6
  74. package/dist/theme-assets.d.ts +39 -0
  75. package/dist/theme-assets.js +449 -0
  76. package/dist/theme-readability.d.ts +37 -0
  77. package/dist/theme-readability.js +145 -0
  78. package/dist/theme-tokens.generated.d.ts +275 -0
  79. package/dist/theme-tokens.generated.js +167 -0
  80. package/dist/theme.d.ts +152 -0
  81. package/dist/theme.js +392 -0
  82. package/dist/tool.d.ts +11 -3
  83. package/dist/ui-parts.d.ts +23 -0
  84. package/dist/ui-parts.js +238 -0
  85. package/dist/ui-resolve.d.ts +40 -0
  86. package/dist/ui-resolve.js +54 -0
  87. package/dist/ui-slots.d.ts +55 -0
  88. package/dist/ui-slots.js +247 -0
  89. package/dist/ui.d.ts +143 -37
  90. package/dist/ui.js +65 -5
  91. package/dist/web.d.ts +105 -0
  92. package/dist/web.js +135 -0
  93. package/package.json +10 -2
  94. package/schemas/connector-template.v1.schema.json +3 -0
  95. package/schemas/marketplace.v1.schema.json +50 -0
  96. package/schemas/plugin.v1.schema.json +164 -4
  97. package/schemas/theme.v1.schema.json +225 -0
@@ -1,12 +1,18 @@
1
1
  import semver from "semver";
2
2
  import { z } from "zod";
3
3
  import { AGENT_TEMPLATE_LIMITS } from "./agent-template.js";
4
+ import { validateClientSection } from "./client-section.js";
5
+ import { CONFIG_UI_LIMITS } from "./config-ui.js";
4
6
  import { defineExtension, EXTENSION_NAME_RE } from "./define-extension.js";
5
7
  import { CATALOG_ITEM_NAME_RE, CONNECTOR_TEMPLATE_LIMITS, isSafePackagePath, SEMVER_VERSION_RE, validateConnectorTemplate, } from "./plugin-package.js";
6
8
  import { hasUpperBound } from "./semver-range.js";
9
+ import { SETUP_GUIDE_LIMITS, SETUP_GUIDE_PLACES } from "./setup-guide.js";
10
+ import { THEME_LIMITS, themeIdOf } from "./theme.js";
11
+ import { parseSlotRef, uiSlot } from "./ui-slots.js";
7
12
  /**
8
13
  * The plugin manifest `.capybara-plugin/plugin.json` (package ecosystem spec §4.1). A plugin is a
9
- * bundle of at most one extension, skills and connector templates, packed as an npm-pack tgz:
14
+ * bundle of at most one extension, skills, connector templates, agent templates and themes, packed as
15
+ * an npm-pack tgz:
10
16
  *
11
17
  * ```
12
18
  * package/package.json npm metadata; version equals plugin.json version
@@ -14,13 +20,14 @@ import { hasUpperBound } from "./semver-range.js";
14
20
  * package/skills/<name>/SKILL.md skills
15
21
  * package/connectors/<id>.json connector templates ({@link ConnectorTemplateFile})
16
22
  * package/agents/<name>.md agent templates (parsed by `parseAgentTemplate`)
23
+ * package/themes/<id>.json themes (parsed by `parseThemeFile`)
17
24
  * package/dist/index.mjs extension entry (only with an extension)
18
25
  * package/migrations/*.sql, package/ui/**
19
26
  * ```
20
27
  *
21
28
  * Paths start with `./` and stay inside the plugin root. Omitting `skills` / `connectorTemplates`
22
- * / `agents` means "scan `skills/*\/SKILL.md` / `connectors/*.json` / `agents/*.md`" (done by the
23
- * kernel when it reads the package). `extension` is written by the packer, never by hand.
29
+ * / `agents` / `themes` means "scan `skills/*\/SKILL.md` / `connectors/*.json` / `agents/*.md` /
30
+ * `themes/*.json`" (done by the kernel when it reads the package). `extension` is written by the packer, never by hand.
24
31
  *
25
32
  * The committed JSON Schema (`schemas/plugin.v1.schema.json`) is generated from
26
33
  * {@link PluginManifestSchema} by `pnpm gen:package-schemas` and drift-checked by
@@ -42,14 +49,23 @@ export const PLUGIN_MANIFEST_LIMITS = {
42
49
  connectorTemplates: 20,
43
50
  /** Agent templates ({@link AGENT_TEMPLATE_LIMITS}`.perPlugin`). */
44
51
  agents: AGENT_TEMPLATE_LIMITS.perPlugin,
52
+ /** Themes ({@link THEME_LIMITS}`.perPlugin`). */
53
+ themes: THEME_LIMITS.perPlugin,
45
54
  descriptionChars: 1024,
46
55
  publisherChars: 100,
47
56
  displayNameChars: 100,
48
57
  pathChars: 512,
58
+ /** Entries of `suggestedAppearance.replacements`. */
59
+ appearanceReplacements: 8,
49
60
  };
61
+ /** A plugin description as `{ en, zh? }` (a plain string is the English text). */
62
+ export function pluginDescription(d) {
63
+ return typeof d === "string" ? { en: d } : { en: d.en, ...(d.zh !== undefined && { zh: d.zh }) };
64
+ }
50
65
  const L = PLUGIN_MANIFEST_LIMITS;
51
66
  const MAX_ERRORS = 50;
52
67
  const ICON_RE = /\.(?:svg|png)$/i;
68
+ const COMPONENT_ID_RE = /^[a-z][a-z0-9-]{0,39}$/;
53
69
  const HTTPS_URL_RE = /^https:\/\/\S+$/;
54
70
  const text = (max, what) => z
55
71
  .string()
@@ -87,6 +103,40 @@ const staticExtensionManifest = z.strictObject({
87
103
  ui: z.array(z.record(z.string(), z.unknown())).optional(),
88
104
  config: z.strictObject({ deployment: configFields, org: configFields }),
89
105
  });
106
+ const configSchemaJson = z
107
+ .record(z.string(), z.unknown())
108
+ .refine((v) => new TextEncoder().encode(JSON.stringify(v)).length <= CONFIG_UI_LIMITS.configSchemaBytes, {
109
+ message: `must be at most ${CONFIG_UI_LIMITS.configSchemaBytes} bytes of JSON (${CONFIG_UI_LIMITS.configSchemaBytes / 1024} KiB)`,
110
+ });
111
+ const setupGuide = z.strictObject({
112
+ id: z.string().regex(CATALOG_ITEM_NAME_RE, {
113
+ message: "id must match ^[a-z0-9][a-z0-9-]{0,63}$",
114
+ }),
115
+ place: z.enum(SETUP_GUIDE_PLACES),
116
+ template: z
117
+ .string()
118
+ .regex(CATALOG_ITEM_NAME_RE, { message: "template must match ^[a-z0-9][a-z0-9-]{0,63}$" })
119
+ .optional(),
120
+ });
121
+ const clientSection = z
122
+ .strictObject({
123
+ entry: z.string().max(L.pathChars).optional(),
124
+ styles: z.array(z.string().max(L.pathChars)).max(64).optional(),
125
+ assets: z.array(z.string().max(L.pathChars)).max(256).optional(),
126
+ integrity: z.record(z.string().max(L.pathChars), z.string().max(128)),
127
+ apiVersion: z.number().int().min(1),
128
+ })
129
+ .superRefine((c, ctx) => {
130
+ for (const e of validateClientSection(c))
131
+ ctx.addIssue({ code: "custom", path: [], message: e });
132
+ });
133
+ const suggestedAppearance = z.strictObject({
134
+ theme: z
135
+ .string()
136
+ .regex(CATALOG_ITEM_NAME_RE, { message: "theme must match ^[a-z0-9][a-z0-9-]{0,63}$" })
137
+ .optional(),
138
+ replacements: z.record(z.string().max(100), z.string().max(100)).optional(),
139
+ });
90
140
  const extensionSection = z.strictObject({
91
141
  entry: dotPath("entry").refine((p) => p.endsWith(".mjs"), {
92
142
  message: "entry must be a .mjs file",
@@ -94,6 +144,10 @@ const extensionSection = z.strictObject({
94
144
  manifest: staticExtensionManifest,
95
145
  migrations: dotPath("migrations").optional(),
96
146
  ui: dotPath("ui").optional(),
147
+ configSchemas: z
148
+ .strictObject({ deployment: configSchemaJson.optional(), org: configSchemaJson.optional() })
149
+ .optional(),
150
+ client: clientSection.optional(),
97
151
  });
98
152
  const schema = z
99
153
  .strictObject({
@@ -107,7 +161,13 @@ const schema = z
107
161
  .max(256)
108
162
  .regex(SEMVER_VERSION_RE, { message: "version must be an exact semver version" }),
109
163
  publisher: text(L.publisherChars, "publisher"),
110
- description: text(L.descriptionChars, "description"),
164
+ description: z.union([
165
+ text(L.descriptionChars, "description"),
166
+ z.strictObject({
167
+ en: text(L.descriptionChars, "description.en"),
168
+ zh: text(L.descriptionChars, "description.zh").optional(),
169
+ }),
170
+ ]),
111
171
  displayName: localized.optional(),
112
172
  icon: dotPath("icon")
113
173
  .regex(ICON_RE, { message: "icon must be a .svg or .png file" })
@@ -149,6 +209,14 @@ const schema = z
149
209
  }))
150
210
  .max(L.agents)
151
211
  .optional(),
212
+ themes: z
213
+ .array(z.strictObject({
214
+ path: dotPath("path").refine((p) => p.endsWith(".json") && CATALOG_ITEM_NAME_RE.test(themeIdOf(p)), { message: "path must be a <id>.json file with id matching ^[a-z0-9][a-z0-9-]{0,63}$" }),
215
+ }))
216
+ .max(L.themes)
217
+ .optional(),
218
+ setupGuides: z.array(setupGuide).max(SETUP_GUIDE_LIMITS.guides).optional(),
219
+ suggestedAppearance: suggestedAppearance.optional(),
152
220
  extension: extensionSection.optional(),
153
221
  })
154
222
  .superRefine((m, ctx) => {
@@ -187,16 +255,117 @@ const schema = z
187
255
  issue(["agents", i, "path"], `duplicate agent template path ${a.path}`);
188
256
  agentPaths.add(a.path);
189
257
  });
258
+ const themeIds = new Set();
259
+ m.themes?.forEach((t, i) => {
260
+ const id = themeIdOf(t.path);
261
+ if (themeIds.has(id))
262
+ issue(["themes", i, "path"], `duplicate theme id ${id}`);
263
+ themeIds.add(id);
264
+ });
265
+ const guideIds = new Set();
266
+ const guideTemplates = new Set();
267
+ let channelGuides = 0;
268
+ m.setupGuides?.forEach((g, i) => {
269
+ if (guideIds.has(g.id))
270
+ issue(["setupGuides", i, "id"], `duplicate setup guide id ${g.id}`);
271
+ guideIds.add(g.id);
272
+ if (g.place === "connector-template") {
273
+ if (g.template === undefined) {
274
+ issue(["setupGuides", i, "template"], "template is required for a connector-template guide");
275
+ }
276
+ else {
277
+ if (m.connectorTemplates !== undefined && !ids.has(g.template)) {
278
+ issue(["setupGuides", i, "template"], `template ${g.template} is not one of the plugin's connector templates`);
279
+ }
280
+ if (guideTemplates.has(g.template)) {
281
+ issue(["setupGuides", i, "template"], `at most one setup guide per connector template (${g.template} has two)`);
282
+ }
283
+ guideTemplates.add(g.template);
284
+ }
285
+ }
286
+ else if (g.template !== undefined) {
287
+ issue(["setupGuides", i, "template"], "template is only for connector-template guides");
288
+ }
289
+ if (g.place === "channel-connection") {
290
+ channelGuides++;
291
+ if (channelGuides === 2) {
292
+ issue(["setupGuides", i, "place"], "a plugin has at most one channel-connection guide");
293
+ }
294
+ }
295
+ if (g.place === "channel-connection" &&
296
+ m.extension !== undefined &&
297
+ !m.extension.manifest.provides.some((p) => p.startsWith("channel@"))) {
298
+ issue(["setupGuides", i, "place"], "a channel-connection guide needs the plugin's extension to provide channel@1");
299
+ }
300
+ });
301
+ const sa = m.suggestedAppearance;
302
+ if (sa !== undefined) {
303
+ const at = ["suggestedAppearance"];
304
+ if (sa.theme === undefined && sa.replacements === undefined) {
305
+ issue(at, "suggestedAppearance needs theme or replacements");
306
+ }
307
+ if (sa.theme !== undefined && m.themes !== undefined && !themeIds.has(sa.theme)) {
308
+ issue([...at, "theme"], `suggestedAppearance.theme names ${sa.theme}, which is not a theme of the plugin`);
309
+ }
310
+ if (sa.replacements !== undefined) {
311
+ const entries = Object.entries(sa.replacements);
312
+ if (m.extension === undefined) {
313
+ issue([...at, "replacements"], "suggestedAppearance.replacements needs an extension");
314
+ }
315
+ if (entries.length > L.appearanceReplacements) {
316
+ issue([...at, "replacements"], `suggestedAppearance.replacements has ${entries.length} entries; the limit is ${L.appearanceReplacements}`);
317
+ }
318
+ const seen = new Set();
319
+ for (const [slot, id] of entries) {
320
+ const ref = parseSlotRef(slot);
321
+ if (ref === null) {
322
+ issue([...at, "replacements"], `suggestedAppearance.replacements: ${slot} is not a slot ref`);
323
+ continue;
324
+ }
325
+ if (seen.has(ref.id)) {
326
+ issue([...at, "replacements"], `suggestedAppearance.replacements: ${slot} names the slot ${ref.id} again; give each slot once`);
327
+ continue;
328
+ }
329
+ seen.add(ref.id);
330
+ if (!COMPONENT_ID_RE.test(id)) {
331
+ issue([...at, "replacements"], `suggestedAppearance.replacements: ${slot} names ${id}, which is not a contribution id`);
332
+ continue;
333
+ }
334
+ const known = uiSlot(ref.id);
335
+ if (known === undefined)
336
+ continue;
337
+ if (known.cardinality !== "single") {
338
+ issue([...at, "replacements"], `suggestedAppearance.replacements: ${slot} is not a replaceable slot`);
339
+ continue;
340
+ }
341
+ const ok = (m.extension?.manifest.ui ?? []).some((u) => {
342
+ const us = typeof u.slot === "string" ? parseSlotRef(u.slot) : null;
343
+ return u.id === id && u.kind === "component" && us?.id === ref.id;
344
+ });
345
+ if (!ok) {
346
+ issue([...at, "replacements"], `suggestedAppearance.replacements: ${slot} names ${id}, which is not a component contribution in that slot`);
347
+ }
348
+ }
349
+ }
350
+ }
190
351
  if (m.extension === undefined &&
191
352
  m.skills?.length === 0 &&
192
353
  m.connectorTemplates?.length === 0 &&
193
- (m.agents === undefined || m.agents.length === 0)) {
194
- issue([], "a plugin must contain an extension, a skill, a connector template or an agent template");
354
+ (m.agents === undefined || m.agents.length === 0) &&
355
+ (m.themes === undefined || m.themes.length === 0)) {
356
+ issue([], "a plugin must contain an extension, a skill, a connector template, an agent template or a theme");
195
357
  }
196
358
  const ext = m.extension;
197
359
  if (ext === undefined)
198
360
  return;
199
361
  const em = ext.manifest;
362
+ const hasClientPermission = em.permissions.client === true;
363
+ if (ext.client !== undefined && !hasClientPermission) {
364
+ issue(["extension", "client"], "extension.client needs permissions.client: true");
365
+ }
366
+ if (ext.client === undefined && hasClientPermission) {
367
+ issue(["extension", "manifest", "permissions", "client"], "permissions.client is true but extension.client is missing (pack the plugin with its client code, or drop permissions.client)");
368
+ }
200
369
  if (!EXTENSION_NAME_RE.test(m.name)) {
201
370
  issue(["name"], `a plugin with an extension needs an extension name (${EXTENSION_NAME_RE})`);
202
371
  }
@@ -262,6 +431,7 @@ const templateFile = z
262
431
  message: "icon must be a relative .svg or .png path inside the plugin",
263
432
  })
264
433
  .optional(),
434
+ defaultEnabled: z.boolean().optional(),
265
435
  template,
266
436
  })
267
437
  // Field rules (no credentials, auth presets, editableEndpoint, ...) belong to validateConnectorTemplate.
@@ -320,3 +490,13 @@ export function parsePluginManifest(json) {
320
490
  export function parseConnectorTemplateFile(json) {
321
491
  return parseWith(ConnectorTemplateFileSchema, json, "connector template file");
322
492
  }
493
+ /**
494
+ * The theme check of `suggestedAppearance` after the themes are known (the manifest may omit
495
+ * `themes` and let the scan find them): shared by the packer and the kernel.
496
+ */
497
+ export function appearanceIssues(manifest, themeIds) {
498
+ const theme = manifest.suggestedAppearance?.theme;
499
+ if (theme === undefined || themeIds.includes(theme))
500
+ return [];
501
+ return [`suggestedAppearance.theme names ${theme}, which is not a theme of the plugin`];
502
+ }
package/dist/sandbox.d.ts CHANGED
@@ -1,30 +1,56 @@
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
+ /** Sandbox resource and egress limits. */
12
16
  export interface SandboxLimits {
13
17
  cpu: number;
14
18
  memoryMb: number;
15
19
  diskMb: number;
16
20
  egress: "none" | "allowlist" | "open";
17
- /** 出站白名单(`egress` 为 `allowlist` 时生效);每项须通过 {@link validateAllowHost}。 */
21
+ /** Egress allowlist (used when `egress` is `allowlist`); each entry passes {@link validateAllowHost}. */
18
22
  allowHosts: string[];
19
23
  }
20
- /** 提供方的实例句柄。 */
24
+ /** The absolute roots inside one instance (a device may place them anywhere on its host). */
25
+ export interface SandboxRoots {
26
+ workspace: string;
27
+ skills: string;
28
+ tmp: string;
29
+ }
30
+ /** The roots every container-like provider uses; the same paths as {@link SANDBOX_ROOTS}. */
31
+ export declare const DEFAULT_SANDBOX_ROOTS: Readonly<SandboxRoots>;
32
+ /** The provider's instance handle. */
21
33
  export interface SandboxHandle {
22
- /** 提供方的实例 id。 */
34
+ /** The provider's instance id. */
35
+ id: string;
36
+ /** The instance's roots; absent means {@link DEFAULT_SANDBOX_ROOTS}. */
37
+ roots?: SandboxRoots;
38
+ }
39
+ /** The roots of an instance, falling back to {@link DEFAULT_SANDBOX_ROOTS}. */
40
+ export declare function rootsOf(h: SandboxHandle): SandboxRoots;
41
+ /** The provider's file system handle (a device's files, independent of any instance). */
42
+ export interface FileSystemHandle {
43
+ /** The provider's file system id. */
23
44
  id: string;
24
45
  }
25
- /** 命令执行结果。 */
46
+ /** Who runs an `exec` (informational in phase 1: audit and attribution). */
47
+ export interface SandboxActor {
48
+ accountId: string;
49
+ conversationId: string;
50
+ }
51
+ /** Result of a command. */
26
52
  export interface ExecResult {
27
- /** 超时或在执行中被中止为 null(此时 `timedOut` 分别为 true / false)。 */
53
+ /** null on timeout or when aborted while running (`timedOut` is then true / false). */
28
54
  exitCode: number | null;
29
55
  stdout: string;
30
56
  stderr: string;
@@ -32,8 +58,10 @@ export interface ExecResult {
32
58
  timedOut: boolean;
33
59
  }
34
60
  /**
35
- * 实例在提供方那边确定已经不在了(容器被删、E2B 沙箱过期)。`exec` / `readFile` / `writeFile` / `stat`
36
- * 发现实例不在时必须抛它(而不是普通 Error),内核据此重建沙箱并重试一次;只是暂时连不上时抛普通错误。
61
+ * The instance is definitely gone on the provider's side (container removed, E2B sandbox expired).
62
+ * `exec` / `readFile` / `writeFile` / `stat` must throw it (not a plain Error) when they find the
63
+ * instance gone; the kernel then rebuilds the instance and retries once. A transient connection
64
+ * failure throws a plain error.
37
65
  */
38
66
  export declare class SandboxGoneError extends Error {
39
67
  readonly sandboxGone: true;
@@ -41,8 +69,21 @@ export declare class SandboxGoneError extends Error {
41
69
  cause?: unknown;
42
70
  });
43
71
  }
44
- /** 鸭子类型判断(不用 instanceof),兼容插件自带另一份 plugin-sdk 副本的情况。 */
72
+ /** Duck-typed check (not instanceof), so a plugin bundling another plugin-sdk copy still matches. */
45
73
  export declare function isSandboxGoneError(e: unknown): e is SandboxGoneError;
74
+ /**
75
+ * The file system is definitely gone on the provider's side (volume removed, E2B sandbox killed).
76
+ * `create` throws it instead of attaching the instance to a new, empty file system; the kernel then
77
+ * reports the device's files as lost rather than handing out a silently empty workspace.
78
+ */
79
+ export declare class FileSystemGoneError extends Error {
80
+ readonly fileSystemGone: true;
81
+ constructor(message: string, opts?: {
82
+ cause?: unknown;
83
+ });
84
+ }
85
+ /** Duck-typed check (not instanceof), so a plugin bundling another plugin-sdk copy still matches. */
86
+ export declare function isFileSystemGoneError(e: unknown): e is FileSystemGoneError;
46
87
  /**
47
88
  * A holder tag (`exec` argument `tag`, {@link SandboxProvider.killTagged}): the kernel passes its
48
89
  * lease tokens (UUIDs). Providers check tags against it before putting them in a command line or a
@@ -50,73 +91,119 @@ export declare function isSandboxGoneError(e: unknown): e is SandboxGoneError;
50
91
  */
51
92
  export declare const SANDBOX_TAG_RE: RegExp;
52
93
  /**
53
- * `sandbox@1` 的实现(由沙箱插件提供,如 Docker、E2B)。
54
- * 实例确定不在时:`resume` 返回 `gone`;`exec` / `readFile` / `writeFile` / `stat` 抛 {@link SandboxGoneError};
55
- * `suspend` / `destroy` 照常成功。
94
+ * The `sandbox@2` implementation (provided by a sandbox plugin such as Docker or E2B).
56
95
  *
57
- * **自动启动**:实例还在、但已停止 / 暂停(被内核之外的原因停掉:宿主机重启、守护进程重启、沙箱里的进程把
58
- * 自己的 init 弄停了、休眠扫描停了实例却没来得及记下 `suspended`……)时,`exec` / `readFile` / `writeFile` /
59
- * `stat` 必须先透明地把它启动起来(同 `resume`,文件保留)再执行,而不是报错——内核只信自己记的 `running`。
96
+ * **File systems and instances.** `createFileSystem` makes a device's files; they live until
97
+ * `destroyFileSystem` (the device is deleted). `create` makes an instance attached to an
98
+ * existing file system; `destroy` / `destroyByName` drop the instance only and keep the files, and
99
+ * `suspend` keeps them too. When the file system is gone, `create` must throw
100
+ * {@link FileSystemGoneError} and never create an empty one in its place (a Docker provider checks
101
+ * its volumes exist before mounting them, because Docker would otherwise create empty volumes).
60
102
  *
61
- * **命令时限在沙箱里也要生效**:`exec` 除了在提供方这边按 `timeoutMs` 停掉命令,还必须让沙箱里的命令自己在
62
- * `timeoutMs` 之后不久(几秒的余量)被杀掉。内核副本崩溃时提供方这边的计时随之消失,断开连接也不会结束命令;
63
- * 沙箱里的时限保证它不会无限期地与下一个持锁方的命令同时运行。
103
+ * **Gone instances.** When the instance is definitely gone: `resume` returns `gone`; `exec` /
104
+ * `readFile` / `writeFile` / `stat` / `killAll` / `killTagged` throw {@link SandboxGoneError};
105
+ * `suspend` / `destroy` succeed as usual.
64
106
  *
65
- * **中止**:每个方法都必须及时响应 `signal`(已中止就立即失败,进行中被中止就尽快以中止原因结束)——内核在锁丢失、
66
- * 运行被中止或超时时靠它停下,不响应就可能与新的持锁方同时操作同一实例。`exec` 被中止时必须杀掉正在跑的命令
67
- * (连同它派生的进程),而不只是不再等待它的输出;命令启动后才被中止的 `exec` 以 `exitCode: null`、
68
- * `timedOut: false` 正常 resolve(带上已收集的输出),不 reject。调用时 signal 已中止则立即 reject。
107
+ * **Auto-start**: when the instance still exists but is stopped or paused (for a reason outside the
108
+ * kernel: host or daemon restart, a process in the sandbox stopping its init, an idle sweep that
109
+ * stopped the instance before recording `suspended`...), `exec` / `readFile` / `writeFile` /
110
+ * `stat` / `killAll` / `killTagged` must start it transparently first (like `resume`, files kept)
111
+ * and then run, never fail: the kernel trusts only the `running` it recorded itself. Auto-start
112
+ * must be idempotent under concurrent calls: two calls that both find the instance stopped both
113
+ * start it without failing.
69
114
  *
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).
115
+ * **Time limits apply inside the sandbox too**: besides stopping a command after `timeoutMs` on the
116
+ * provider's side, `exec` must make the command in the sandbox kill itself shortly (a few seconds)
117
+ * after `timeoutMs`. When a kernel replica crashes, the provider-side timer goes with it, and a
118
+ * dropped connection does not end the command; the in-sandbox limit keeps it from running
119
+ * indefinitely next to the next holder's commands.
120
+ *
121
+ * **Abort**: every method must respond to `signal` promptly (fail at once when already aborted, end
122
+ * with the abort reason as soon as possible when aborted mid-way): the kernel relies on it to stop
123
+ * on lock loss, run abort or timeout, and ignoring it may let two holders operate on one instance.
124
+ * An aborted `exec` must kill its running command (and the processes it spawned), not just stop
125
+ * waiting for its output; an `exec` aborted after its command started resolves normally with
126
+ * `exitCode: null`, `timedOut: false` (and the output collected so far), it does not reject. An
127
+ * `exec` called with an already aborted signal rejects at once.
128
+ *
129
+ * **Concurrent use** (required in `@2`): the sessions of one device share its instance, so the
130
+ * kernel calls `exec`, `readFile`, `writeFile` and `stat` concurrently on one instance. Those four
131
+ * methods must be safe to call concurrently. Each `exec` labels its command with its `tag`, and an
132
+ * aborted `exec` kills only its own command.
78
133
  */
79
134
  export interface SandboxProvider {
135
+ /** `exec` / `readFile` / `writeFile` / `stat` may run concurrently on one instance (required). */
136
+ readonly concurrentExec: true;
137
+ /**
138
+ * Whether the provider isolates the sessions of one device from each other inside the
139
+ * instance (a declared capability; absent means false).
140
+ */
141
+ readonly sessionIsolation?: boolean;
142
+ /**
143
+ * Creates a device's file system. `name` looks like `cap-device-<deviceId>`. If a file
144
+ * system with this name already exists, return it.
145
+ */
146
+ createFileSystem(args: {
147
+ name: string;
148
+ limits: SandboxLimits;
149
+ signal: AbortSignal;
150
+ }): Promise<FileSystemHandle>;
151
+ /** Deletes the file system and its files. Succeeds when it does not exist. */
152
+ destroyFileSystem(fs: FileSystemHandle, signal: AbortSignal): Promise<void>;
153
+ /**
154
+ * Deletes the file system made under `name` by `createFileSystem`; succeeds when there is none.
155
+ * The kernel uses it when it has no handle (`createFileSystem` finished on the provider's side
156
+ * but the kernel stopped before recording the handle), and in its one-off cleanup of
157
+ * per-conversation sandboxes with `cap-<conversationId>` names that a `sandbox@1` provider's
158
+ * `create` made together with their files (Docker: the `cap-<conversationId>-workspace` and
159
+ * `-skills` volumes); a provider removes those under the same call.
160
+ */
161
+ destroyFileSystemByName(name: string, signal: AbortSignal): Promise<void>;
80
162
  /**
81
- * Declares that `exec` / `readFile` / `writeFile` / `stat` may run concurrently on one instance
82
- * (see the contract above). Requires {@link SandboxProvider.killTagged}.
163
+ * Creates an instance attached to `fileSystem`. Without `image` the provider uses its own
164
+ * published image. Throws {@link FileSystemGoneError} when the file system is gone.
83
165
  */
84
- readonly concurrentExec?: boolean;
85
- /** `name` 形如 `cap-<conversationId>`。 */
86
166
  create(args: {
87
167
  name: string;
88
- image: string;
168
+ image?: string;
89
169
  limits: SandboxLimits;
170
+ fileSystem: FileSystemHandle;
90
171
  signal: AbortSignal;
91
172
  }): Promise<SandboxHandle>;
92
- /** `gone` 表示提供方那边已经没有这个实例。 */
173
+ /** `gone` means the provider no longer has this instance. */
93
174
  resume(h: SandboxHandle, signal: AbortSignal): Promise<"resumed" | "gone">;
94
- /** 文件必须保留。实例不存在也算成功。 */
175
+ /** Files must be kept. Succeeds when the instance does not exist. */
95
176
  suspend(h: SandboxHandle, signal: AbortSignal): Promise<void>;
96
- /** 不存在也算成功。 */
177
+ /** Drops the instance only; the file system and its files are kept. Succeeds when it does not exist. */
97
178
  destroy(h: SandboxHandle, signal: AbortSignal): Promise<void>;
98
179
  /**
99
- * 可选:按 `create` 时的 `name`(`cap-<conversationId>`)销毁实例,不存在也算成功。
100
- * 内核在拿不到句柄时用它清理(例如 `create` 已在提供方那边完成、内核却在记下句柄前退出)。
180
+ * Drops the instance made under `name` by `create` (instance only, files kept); succeeds when
181
+ * there is none. The kernel uses it when it has no handle (`create` finished on the provider's
182
+ * side but the kernel stopped before recording the handle), and in its one-off cleanup of
183
+ * per-conversation sandboxes with `cap-<conversationId>` names made by a `sandbox@1` provider's
184
+ * `create`.
101
185
  */
102
- destroyByName?(name: string, signal: AbortSignal): Promise<void>;
186
+ destroyByName(name: string, signal: AbortSignal): Promise<void>;
103
187
  /**
104
- * 可选:杀掉这个实例里经 `exec` 启动、仍在运行的全部命令(连同它们派生的、没有自己另起会话的进程)。
105
- * 内核在接手一个前任持锁方没有正常结束的沙箱(前任崩溃)时、第一次执行前调用,清掉前任遗留的命令;
106
- * 命令自己放到后台、另起会话的进程不保证被杀。实例已停止时同样先启动;不在时抛 {@link SandboxGoneError}。
188
+ * Kills every running command started through `exec` in this instance (and the processes they
189
+ * spawned that did not start their own session). The kernel calls it only when no other holder
190
+ * can be running commands (an instance just resumed from `suspended`, or under the exclusive
191
+ * lease), never while another session may be; to clean up after one crashed holder it uses
192
+ * {@link SandboxProvider.killTagged}. Processes a command put in the background in their own
193
+ * session are not guaranteed to be killed.
107
194
  */
108
- killAll?(h: SandboxHandle, signal: AbortSignal): Promise<void>;
195
+ killAll(h: SandboxHandle, signal: AbortSignal): Promise<void>;
109
196
  /**
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.
197
+ * Kills every running `exec` command labelled with one of `tags` (and its process tree), leaving
198
+ * other commands running. The kernel calls it for the tags of holders that crashed while live
199
+ * holders keep running commands. Tags match {@link SANDBOX_TAG_RE}. Match whole tags: one tag
200
+ * may be a prefix of another (`ab` of `ab-cd`), and killing `ab` must not touch `ab-cd`'s
201
+ * commands.
116
202
  */
117
- killTagged?(h: SandboxHandle, tags: string[], signal: AbortSignal): Promise<void>;
203
+ killTagged(h: SandboxHandle, tags: string[], signal: AbortSignal): Promise<void>;
118
204
  /**
119
- * 执行一条命令。`maxOutputBytes` 是 stdout 与 stderr **合计**最多收集的字节,超出的丢弃、`truncated` 为 true。
205
+ * Runs a command. `maxOutputBytes` caps stdout and stderr **combined**; the rest is dropped and
206
+ * `truncated` is true.
120
207
  */
121
208
  exec(h: SandboxHandle, args: {
122
209
  command: string;
@@ -127,11 +214,16 @@ export interface SandboxProvider {
127
214
  signal: AbortSignal;
128
215
  /**
129
216
  * 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.
217
+ * {@link SandboxProvider.killTagged} can find it.
131
218
  */
132
- tag?: string;
219
+ tag: string;
220
+ /** Who runs the command; informational in phase 1 (record it, do not act on it). */
221
+ actor: SandboxActor;
133
222
  }): Promise<ExecResult>;
134
- /** 读文件(最多 `maxBytes` 字节,更长的截断、`truncated` 为 true)。不存在、或是目录时返回 null。 */
223
+ /**
224
+ * Reads a file (at most `maxBytes`; longer files are truncated and `truncated` is true). Returns
225
+ * null when it does not exist or is a directory.
226
+ */
135
227
  readFile(h: SandboxHandle, path: string, opts: {
136
228
  maxBytes: number;
137
229
  signal: AbortSignal;
@@ -139,14 +231,24 @@ export interface SandboxProvider {
139
231
  data: Uint8Array;
140
232
  truncated: boolean;
141
233
  } | null>;
142
- /** 父目录自动创建。 */
234
+ /** Parent directories are created. */
143
235
  writeFile(h: SandboxHandle, path: string, data: Uint8Array, signal: AbortSignal): Promise<void>;
144
236
  stat(h: SandboxHandle, path: string, signal: AbortSignal): Promise<{
145
237
  size: number;
146
238
  isDir: boolean;
147
239
  } | null>;
148
240
  }
149
- /** 校验沙箱内路径:返回错误列表,空数组表示合法。 */
150
- export declare function validateSandboxPath(p: string): string[];
241
+ /**
242
+ * The root-independent checks of a path inside an instance (non-empty, at most 4096 characters, no
243
+ * control characters or backslashes, absolute, no empty or `..` segments); returns the errors,
244
+ * empty when valid. {@link validateSandboxPath} adds root membership.
245
+ */
246
+ export declare function validateSandboxPathShape(p: string): string[];
247
+ /**
248
+ * Checks a path inside an instance; returns the errors, empty when valid: the
249
+ * {@link validateSandboxPathShape} checks, then root membership. `roots`: the instance's roots
250
+ * ({@link rootsOf}); absent means {@link SANDBOX_ROOTS}. The path must be one of them or under one.
251
+ */
252
+ export declare function validateSandboxPath(p: string, roots?: SandboxRoots): string[];
151
253
  /** 校验出站白名单主机名:小写、无协议与端口、可选前导 `*.`、IDN 只认 punycode。 */
152
254
  export declare function validateAllowHost(h: string): string[];