@capybara-hq/plugin-sdk 0.1.0-rc.6 → 0.1.0-rc.61

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 (136) 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 +7 -1
  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 +2 -0
  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 +29 -3
  13. package/agent-docs/plugin-format.md +52 -2
  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 +67 -13
  22. package/dist/cards.js +91 -21
  23. package/dist/channel.d.ts +148 -48
  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 +22 -0
  30. package/dist/config-ui.js +64 -4
  31. package/dist/connector-auth.d.ts +15 -2
  32. package/dist/connector-auth.js +97 -8
  33. package/dist/connector.d.ts +74 -32
  34. package/dist/context.d.ts +40 -0
  35. package/dist/context.js +2 -0
  36. package/dist/ctx.d.ts +132 -29
  37. package/dist/define-extension.d.ts +26 -12
  38. package/dist/define-extension.js +12 -5
  39. package/dist/device-denied-paths.d.ts +18 -0
  40. package/dist/device-denied-paths.js +84 -0
  41. package/dist/device-operation.d.ts +333 -0
  42. package/dist/device-operation.js +312 -0
  43. package/dist/device-protocol.d.ts +285 -50
  44. package/dist/device-protocol.js +755 -90
  45. package/dist/device-provider.d.ts +503 -0
  46. package/dist/device-provider.js +302 -0
  47. package/dist/dial-in.d.ts +176 -0
  48. package/dist/dial-in.js +115 -0
  49. package/dist/extension-point.d.ts +2 -0
  50. package/dist/extension-point.js +6 -2
  51. package/dist/file-preview.d.ts +23 -6
  52. package/dist/git-hosts.d.ts +53 -0
  53. package/dist/git-hosts.js +98 -0
  54. package/dist/hooks.d.ts +125 -20
  55. package/dist/hooks.js +5 -0
  56. package/dist/http-access.d.ts +62 -0
  57. package/dist/http-access.js +12 -0
  58. package/dist/identity.d.ts +38 -9
  59. package/dist/identity.js +21 -1
  60. package/dist/index.d.ts +29 -3
  61. package/dist/index.js +29 -3
  62. package/dist/marketplace.d.ts +26 -0
  63. package/dist/marketplace.js +43 -1
  64. package/dist/model-params.d.ts +41 -22
  65. package/dist/model-params.js +28 -15
  66. package/dist/model.d.ts +206 -71
  67. package/dist/model.js +152 -19
  68. package/dist/net.d.ts +52 -0
  69. package/dist/net.js +34 -0
  70. package/dist/network-classes.d.ts +98 -0
  71. package/dist/network-classes.js +291 -0
  72. package/dist/permissions.d.ts +54 -22
  73. package/dist/permissions.js +119 -43
  74. package/dist/plugin-manifest.d.ts +45 -5
  75. package/dist/plugin-manifest.js +174 -6
  76. package/dist/plugin-package.d.ts +82 -38
  77. package/dist/plugin-package.js +61 -29
  78. package/dist/push.d.ts +75 -0
  79. package/dist/push.js +87 -0
  80. package/dist/sandbox-linux-runtime-source.d.ts +1 -0
  81. package/dist/sandbox-linux-runtime-source.js +2318 -0
  82. package/dist/sandbox-native-runtime-source.d.ts +10 -0
  83. package/dist/sandbox-native-runtime-source.js +476 -0
  84. package/dist/sandbox-runtime-source.d.ts +19 -0
  85. package/dist/sandbox-runtime-source.js +28 -0
  86. package/dist/sandbox-write-denies.d.ts +139 -0
  87. package/dist/sandbox-write-denies.js +869 -0
  88. package/dist/secret.d.ts +4 -1
  89. package/dist/secret.js +4 -1
  90. package/dist/setup-check.d.ts +128 -0
  91. package/dist/setup-check.js +142 -0
  92. package/dist/setup-guide-parse.d.ts +121 -0
  93. package/dist/setup-guide-parse.js +356 -0
  94. package/dist/setup-guide-render.d.ts +45 -0
  95. package/dist/setup-guide-render.js +351 -0
  96. package/dist/setup-guide.d.ts +108 -0
  97. package/dist/setup-guide.js +367 -0
  98. package/dist/shell-capabilities.d.ts +211 -0
  99. package/dist/shell-capabilities.js +44 -0
  100. package/dist/shell-environment.d.ts +57 -0
  101. package/dist/shell-environment.js +21 -0
  102. package/dist/skill.d.ts +27 -17
  103. package/dist/skill.js +40 -26
  104. package/dist/storage.d.ts +52 -25
  105. package/dist/svg-viewbox.d.ts +10 -0
  106. package/dist/svg-viewbox.js +24 -0
  107. package/dist/theme-assets.d.ts +55 -0
  108. package/dist/theme-assets.js +489 -0
  109. package/dist/theme-readability.d.ts +37 -0
  110. package/dist/theme-readability.js +145 -0
  111. package/dist/theme-tokens.generated.d.ts +299 -0
  112. package/dist/theme-tokens.generated.js +184 -0
  113. package/dist/theme.d.ts +190 -0
  114. package/dist/theme.js +471 -0
  115. package/dist/tool.d.ts +99 -26
  116. package/dist/tool.js +29 -9
  117. package/dist/ui-parts.d.ts +23 -0
  118. package/dist/ui-parts.js +385 -0
  119. package/dist/ui-resolve.d.ts +35 -0
  120. package/dist/ui-resolve.js +42 -0
  121. package/dist/ui-slots.d.ts +65 -0
  122. package/dist/ui-slots.js +261 -0
  123. package/dist/ui.d.ts +212 -76
  124. package/dist/ui.js +101 -27
  125. package/dist/url.d.ts +4 -1
  126. package/dist/url.js +4 -1
  127. package/package.json +13 -1
  128. package/schemas/bootstrap-extra.v1.schema.json +186 -0
  129. package/schemas/bootstrap.v1.schema.json +20 -0
  130. package/schemas/connector-template.v1.schema.json +35 -0
  131. package/schemas/marketplace.v1.schema.json +14 -0
  132. package/schemas/plugin.v1.schema.json +122 -3
  133. package/schemas/theme.v1.schema.json +302 -0
  134. package/agent-docs/extension-points/sandbox.md +0 -15
  135. package/dist/sandbox.d.ts +0 -254
  136. package/dist/sandbox.js +0 -153
@@ -0,0 +1,302 @@
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
+ /** Device provider extension point ref. */
12
+ export const DEVICE_PROVIDER_EXTENSION_POINT = "device-provider@1";
13
+ /** The roots inside the sandbox the model may access. */
14
+ export const SANDBOX_ROOTS = ["/workspace", "/skills", "/tmp"];
15
+ const MAX_PATH_LENGTH = 4096;
16
+ /** The roots every container-like provider uses; the same paths as {@link SANDBOX_ROOTS}. */
17
+ export const DEFAULT_SANDBOX_ROOTS = Object.freeze({
18
+ workspace: "/workspace",
19
+ skills: "/skills",
20
+ tmp: "/tmp",
21
+ });
22
+ /** The roots of an instance, falling back to {@link DEFAULT_SANDBOX_ROOTS}. */
23
+ export function rootsOf(h) {
24
+ return h.roots ?? DEFAULT_SANDBOX_ROOTS;
25
+ }
26
+ /**
27
+ * The instance is definitely gone on the provider's side (container removed, E2B sandbox expired).
28
+ * `exec` / `readFile` / `writeFile` / `stat` must throw it (not a plain Error) when they find the
29
+ * instance gone; the kernel then rebuilds the instance and retries once. A transient connection
30
+ * failure throws a plain error. In a managed operation (`operation()`), a gone instance found
31
+ * **before** the request reached the machine throws a `DeviceRequestNotSentError` with this error
32
+ * as its `cause`: the operation is then recorded as not started rather than as an unknown outcome,
33
+ * and the instance is still rebuilt, so the call can be retried on it.
34
+ */
35
+ export class SandboxGoneError extends Error {
36
+ sandboxGone = true;
37
+ constructor(message, opts) {
38
+ super(message, opts && "cause" in opts ? { cause: opts.cause } : undefined);
39
+ this.name = "SandboxGoneError";
40
+ }
41
+ }
42
+ /** Duck-typed check (not instanceof), so a plugin bundling another plugin-sdk copy still matches. */
43
+ export function isSandboxGoneError(e) {
44
+ return (e instanceof Error &&
45
+ e.name === "SandboxGoneError" &&
46
+ e.sandboxGone === true);
47
+ }
48
+ /**
49
+ * The file system is definitely gone on the provider's side (volume removed, E2B sandbox killed).
50
+ * `create` throws it instead of attaching the instance to a new, empty file system; the kernel then
51
+ * reports the device's files as lost rather than handing out a silently empty workspace.
52
+ */
53
+ export class FileSystemGoneError extends Error {
54
+ fileSystemGone = true;
55
+ constructor(message, opts) {
56
+ super(message, opts && "cause" in opts ? { cause: opts.cause } : undefined);
57
+ this.name = "FileSystemGoneError";
58
+ }
59
+ }
60
+ /** Duck-typed check (not instanceof), so a plugin bundling another plugin-sdk copy still matches. */
61
+ export function isFileSystemGoneError(e) {
62
+ return (e instanceof Error &&
63
+ e.name === "FileSystemGoneError" &&
64
+ e.fileSystemGone === true);
65
+ }
66
+ /**
67
+ * A holder tag (`exec` argument `tag`, {@link DeviceProvider.killTagged}): the kernel passes its
68
+ * lease tokens (UUIDs). Providers check tags against it before putting them in a command line or a
69
+ * kill pattern.
70
+ */
71
+ export const SANDBOX_TAG_RE = /^[a-z0-9-]{1,64}$/;
72
+ /** Size limits {@link parseDeviceReport} enforces. */
73
+ export const DEVICE_REPORT_LIMITS = Object.freeze({
74
+ revisionChars: 128,
75
+ descriptionChars: 300,
76
+ limits: 8,
77
+ limitLabelChars: 60,
78
+ limitValueChars: 60,
79
+ homeChars: 4096,
80
+ changeHintChars: 400,
81
+ });
82
+ const isRecord = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
83
+ function exactKeys(v, keys, what) {
84
+ for (const k of Object.keys(v)) {
85
+ if (!keys.includes(k))
86
+ throw new TypeError(`${what}: unknown key ${k}`);
87
+ }
88
+ }
89
+ function parseText(v, max, what) {
90
+ if (!isRecord(v))
91
+ throw new TypeError(`${what} must be an object`);
92
+ exactKeys(v, ["en", "zh"], what);
93
+ const { en, zh } = v;
94
+ if (typeof en !== "string" || en === "" || en.length > max) {
95
+ throw new TypeError(`${what}.en must be a non-empty string of at most ${max} characters`);
96
+ }
97
+ if (zh === undefined)
98
+ return { en };
99
+ if (typeof zh !== "string" || zh === "" || zh.length > max) {
100
+ throw new TypeError(`${what}.zh must be a non-empty string of at most ${max} characters`);
101
+ }
102
+ return { en, zh };
103
+ }
104
+ /** Checks a provider's report; throws `TypeError` on any other shape, returns a clean copy. */
105
+ export function parseDeviceReport(value) {
106
+ const L = DEVICE_REPORT_LIMITS;
107
+ if (!isRecord(value))
108
+ throw new TypeError("device report must be an object");
109
+ exactKeys(value, ["revision", "description", "home", "limits", "reset", "changeHint"], "device report");
110
+ const { revision, home, limits, reset } = value;
111
+ if (typeof revision !== "string" || revision === "" || revision.length > L.revisionChars) {
112
+ throw new TypeError(`device report revision must be a non-empty string of at most ${L.revisionChars} characters`);
113
+ }
114
+ const description = parseText(value.description, L.descriptionChars, "device report description");
115
+ if (home !== null) {
116
+ if (typeof home !== "string" || home.length > L.homeChars) {
117
+ throw new TypeError("device report home must be an absolute path or null");
118
+ }
119
+ const errors = validateSandboxPathShape(home);
120
+ if (errors.length > 0)
121
+ throw new TypeError(`device report home: ${errors.join("; ")}`);
122
+ }
123
+ if (!Array.isArray(limits) || limits.length > L.limits) {
124
+ throw new TypeError(`device report limits must be an array of at most ${L.limits} entries`);
125
+ }
126
+ const parsedLimits = limits.map((raw, i) => {
127
+ const what = `device report limits[${i}]`;
128
+ if (!isRecord(raw))
129
+ throw new TypeError(`${what} must be an object`);
130
+ exactKeys(raw, ["label", "value"], what);
131
+ return {
132
+ label: parseText(raw.label, L.limitLabelChars, `${what}.label`),
133
+ value: parseText(raw.value, L.limitValueChars, `${what}.value`),
134
+ };
135
+ });
136
+ if (typeof reset !== "boolean")
137
+ throw new TypeError("device report reset must be a boolean");
138
+ const changeHint = value.changeHint === undefined
139
+ ? undefined
140
+ : parseText(value.changeHint, L.changeHintChars, "device report changeHint");
141
+ return {
142
+ revision,
143
+ description,
144
+ home,
145
+ limits: parsedLimits,
146
+ reset,
147
+ ...(changeHint !== undefined && { changeHint }),
148
+ };
149
+ }
150
+ /**
151
+ * The provider refuses a project directory (`projects` operations: it lies where the provider
152
+ * will not serve, for example another connection's directory). `reason` is shown to the person.
153
+ * The kernel answers it as `device.project_refused` (422).
154
+ */
155
+ export class ProjectPathRefusedError extends Error {
156
+ projectPathRefused = true;
157
+ reason;
158
+ constructor(reason, opts) {
159
+ super(reason.en, opts && "cause" in opts ? { cause: opts.cause } : undefined);
160
+ this.name = "ProjectPathRefusedError";
161
+ this.reason = reason;
162
+ }
163
+ }
164
+ /** Duck-typed check (not instanceof), so a plugin bundling another plugin-sdk copy still matches. */
165
+ export function isProjectPathRefusedError(e) {
166
+ return (e instanceof Error &&
167
+ e.name === "ProjectPathRefusedError" &&
168
+ e.projectPathRefused === true &&
169
+ isRecord(e.reason));
170
+ }
171
+ // biome-ignore lint/suspicious/noControlCharactersInRegex: control characters are exactly what must be blocked
172
+ const CONTROL = /[\u0000-\u001f\u007f]/;
173
+ /**
174
+ * The most entries a `list` may ask for and its result may carry ({@link DeviceProvider.list}):
175
+ * part of the provider contract, which the device protocol's `list` op also honors.
176
+ */
177
+ export const MAX_DEVICE_LIST_ENTRIES = 1000;
178
+ /** The longest project name, in UTF-16 code units. */
179
+ export const MAX_DEVICE_PROJECT_NAME_LENGTH = 64;
180
+ /** The most candidates a `scan` answers ({@link DeviceProvider.scan}). */
181
+ export const MAX_DEVICE_SCAN_RESULTS = 50;
182
+ /**
183
+ * Directory names a `scan` never enters, at any depth ({@link DeviceProvider.scan}): dependency
184
+ * trees, not projects. Every provider skips exactly these.
185
+ */
186
+ export const DEVICE_SCAN_SKIPPED_DIRS = Object.freeze(["node_modules"]);
187
+ /**
188
+ * Directory names a `scan` does not enter directly under its `base` ({@link DeviceProvider.scan}):
189
+ * the owner's macOS `Library` (app data, huge, partly privacy-protected) is not where projects
190
+ * live. Every provider skips exactly these.
191
+ */
192
+ export const DEVICE_SCAN_SKIPPED_BASE_DIRS = Object.freeze(["Library"]);
193
+ /** How far below its base a `scan` looks: the base's children and their children. */
194
+ export const MAX_DEVICE_SCAN_DEPTH = 2;
195
+ /**
196
+ * The most directories one `scan` visits (reads the entries of), its `base` included
197
+ * ({@link DeviceProvider.scan}): breadth-first, each level in code-unit order of path.
198
+ */
199
+ export const MAX_DEVICE_SCAN_DIRS = 500;
200
+ /**
201
+ * Whether `v` is a valid project name (a project's identity on its device, and a `scan`
202
+ * candidate's `suggestedName`): non-empty, at most {@link MAX_DEVICE_PROJECT_NAME_LENGTH} UTF-16
203
+ * code units, not `.` or `..`, no `/`, no control characters, and no leading or trailing
204
+ * whitespace.
205
+ */
206
+ export function isDeviceProjectName(v) {
207
+ return (typeof v === "string" &&
208
+ v !== "" &&
209
+ v !== "." &&
210
+ v !== ".." &&
211
+ v.length <= MAX_DEVICE_PROJECT_NAME_LENGTH &&
212
+ !CONTROL.test(v) &&
213
+ !v.includes("/") &&
214
+ !/^\s|\s$/.test(v));
215
+ }
216
+ /**
217
+ * The root-independent checks of a path inside an instance (non-empty, at most 4096 characters, no
218
+ * control characters or backslashes, absolute, no empty or `..` segments); returns the errors,
219
+ * empty when valid. {@link validateSandboxPath} adds root membership.
220
+ */
221
+ export function validateSandboxPathShape(p) {
222
+ if (typeof p !== "string" || p.length === 0)
223
+ return ["path must be a non-empty string"];
224
+ if (p.length > MAX_PATH_LENGTH)
225
+ return [`path must be at most ${MAX_PATH_LENGTH} characters`];
226
+ if (CONTROL.test(p))
227
+ return ["path must not contain control characters"];
228
+ if (p.includes("\\"))
229
+ return ["path must not contain backslashes"];
230
+ if (!p.startsWith("/"))
231
+ return ["path must be absolute"];
232
+ if (p.includes("//"))
233
+ return ["path must not contain empty segments"];
234
+ for (const seg of p.split("/")) {
235
+ let decoded = seg;
236
+ try {
237
+ decoded = decodeURIComponent(seg);
238
+ }
239
+ catch {
240
+ // invalid percent-encoding is taken literally
241
+ }
242
+ if (seg === ".." || decoded === ".." || decoded.includes("/") || decoded.includes("\\")) {
243
+ return ["path must not contain '..' segments"];
244
+ }
245
+ }
246
+ return [];
247
+ }
248
+ /** A structural error after which {@link validateSandboxPath} stops (before the root check). */
249
+ const STOPS = new Set([
250
+ "path must be a non-empty string",
251
+ `path must be at most ${MAX_PATH_LENGTH} characters`,
252
+ "path must not contain control characters",
253
+ "path must not contain backslashes",
254
+ "path must be absolute",
255
+ "path must not contain empty segments",
256
+ ]);
257
+ /**
258
+ * Checks a path inside an instance; returns the errors, empty when valid: the
259
+ * {@link validateSandboxPathShape} checks, then root membership. `roots`: the instance's roots
260
+ * ({@link rootsOf}); absent means {@link SANDBOX_ROOTS}. The path must be one of them or under one.
261
+ */
262
+ export function validateSandboxPath(p, roots) {
263
+ const errors = validateSandboxPathShape(p);
264
+ if (errors.some((e) => STOPS.has(e)))
265
+ return errors;
266
+ const allowed = roots === undefined ? SANDBOX_ROOTS : [roots.workspace, roots.skills, roots.tmp];
267
+ if (!allowed.some((r) => p === r || p.startsWith(`${r}/`))) {
268
+ errors.push(`path must be under ${allowed.join(", ")}`);
269
+ }
270
+ return errors;
271
+ }
272
+ const LABEL = /^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/;
273
+ /**
274
+ * Validates an outbound allowlist host name: lowercase, no protocol or port, optional leading `*.`,
275
+ * IDN accepted only as punycode.
276
+ */
277
+ export function validateAllowHost(h) {
278
+ if (typeof h !== "string" || h.length === 0)
279
+ return ["host must be a non-empty string"];
280
+ if (h.length > 253)
281
+ return ["host must be at most 253 characters"];
282
+ const name = h.startsWith("*.") ? h.slice(2) : h;
283
+ if (name.length === 0)
284
+ return ["wildcard must be followed by a domain"];
285
+ const labels = name.split(".");
286
+ if (labels.every((l) => LABEL.test(l))) {
287
+ const tld = labels[labels.length - 1];
288
+ if (labels.length < 2)
289
+ return ["host must have at least two labels (no single-label names)"];
290
+ // The last label must start with a letter: this blocks the decimal / octal / hexadecimal
291
+ // spellings of IPv4
292
+ if (!/^[a-z]/.test(tld))
293
+ return ["host must not be an IP address literal"];
294
+ if (["local", "internal", "localhost"].includes(tld)) {
295
+ return ["host must not be in an internal-only domain (.local, .internal, .localhost)"];
296
+ }
297
+ return [];
298
+ }
299
+ return [
300
+ "host must be a lowercase hostname without scheme, port or path (optional leading '*.'; IDN as punycode)",
301
+ ];
302
+ }
@@ -0,0 +1,176 @@
1
+ /**
2
+ * The dial-in channel: the kernel's generic way for a machine to connect to a deployment and
3
+ * serve one device of a `device-provider@1` extension that declares `permissions.dialIn`. The
4
+ * kernel signs the machine in, holds its socket on the gateway role, bounds every frame by the
5
+ * negotiated size and relays the frames' opaque `body` between the machine and the device's
6
+ * provider. It never reads a body: what a body means is the provider's protocol, named by
7
+ * `permissions.dialIn.protocol` and by the machine's hello.
8
+ */
9
+ /**
10
+ * A dial-in protocol: `<name>/<major>`, a lower-case name of 1 to 41 characters and a major
11
+ * version from 1 to 9999 (for example `capybara-device/6`). A machine's hello must name exactly
12
+ * the protocol of the provider serving its device.
13
+ */
14
+ export declare const DIAL_IN_PROTOCOL_RE: RegExp;
15
+ /** A frame from the machine. The kernel checks the envelope; `body` is the provider's. */
16
+ export type DialInMachineFrame = {
17
+ /** The first frame after the socket opens. */
18
+ type: "hello";
19
+ /** Must equal the serving provider's `permissions.dialIn.protocol`. */
20
+ protocol: string;
21
+ /** Random per run of the machine's program, the same on each of its connections. */
22
+ programRunId: string;
23
+ program: {
24
+ version: string;
25
+ os: string;
26
+ arch: string;
27
+ bootId?: string;
28
+ };
29
+ /** The largest frame, in UTF-8 bytes, the machine accepts. */
30
+ transport: {
31
+ maxFrameBytes: number;
32
+ };
33
+ body: unknown;
34
+ }
35
+ /** The answer to the kernel's `req` with the same `id`. */
36
+ | {
37
+ type: "res";
38
+ id: string;
39
+ body: unknown;
40
+ }
41
+ /** An unsolicited frame, handed to {@link DialInHandler.onFrame}. */
42
+ | {
43
+ type: "event";
44
+ body: unknown;
45
+ };
46
+ /** A frame from the kernel to the machine. */
47
+ export type DialInKernelFrame =
48
+ /**
49
+ * The kernel accepted the hello (the provider's `onHello` answered ok). `maxFrameBytes` is the
50
+ * connection's effective frame capacity: the smaller of the machine's `transport.maxFrameBytes`
51
+ * and the kernel's limit. Neither side sends a larger frame on this connection.
52
+ */
53
+ {
54
+ type: "ready";
55
+ connectionId: string;
56
+ maxFrameBytes: number;
57
+ }
58
+ /** A provider's request ({@link DialInChannel.request}); answered by a `res` with its `id`. */
59
+ | {
60
+ type: "req";
61
+ id: string;
62
+ deadlineMs: number;
63
+ body: unknown;
64
+ }
65
+ /** The kernel no longer waits for request `id` (aborted or timed out). */
66
+ | {
67
+ type: "cancel";
68
+ id: string;
69
+ }
70
+ /** The machine should finish its work and disconnect (`drain`) or stop at once (`stop`). */
71
+ | {
72
+ type: "stop";
73
+ reason: "drain" | "stop";
74
+ };
75
+ /** A machine frame that is not a valid dial-in envelope. The kernel closes the socket on it. */
76
+ export declare class DialInProtocolError extends Error {
77
+ constructor(message: string);
78
+ }
79
+ /**
80
+ * Strictly parses one machine frame: the text must be at most `maxBytes` UTF-8 bytes (checked
81
+ * before `JSON.parse`), an object of a known `type` with exactly that type's keys. `body` is kept
82
+ * as parsed, never inspected. Throws {@link DialInProtocolError}; a `maxBytes` that is not a
83
+ * positive integer throws a `RangeError`.
84
+ */
85
+ export declare function parseDialInMachineFrame(text: string, maxBytes: number): DialInMachineFrame;
86
+ /**
87
+ * The machine's side of {@link parseDialInMachineFrame}: strictly parses one kernel frame, at most
88
+ * `maxBytes` UTF-8 bytes (checked before `JSON.parse`), an object of a known `type` with exactly
89
+ * that type's keys; `body` is kept as parsed. Throws {@link DialInProtocolError}; a `maxBytes`
90
+ * that is not a positive integer throws a `RangeError`.
91
+ */
92
+ export declare function parseDialInKernelFrame(text: string, maxBytes: number): DialInKernelFrame;
93
+ /**
94
+ * The provider's side of the dial-in channel: `DeviceProvider.dialIn`, required when the extension
95
+ * declares `permissions.dialIn = { protocol: "<name>/<major>" }`.
96
+ */
97
+ export interface DialInHandler {
98
+ /**
99
+ * Called on the gateway replica holding the socket, after the kernel authenticated it.
100
+ * `connection` names the machine and the connection the hello arrived on.
101
+ */
102
+ onHello(deviceId: string, hello: unknown, signal: AbortSignal, connection: DialInConnectionInfo): Promise<{
103
+ ok: true;
104
+ } | {
105
+ ok: false;
106
+ code: string;
107
+ message: string;
108
+ }>;
109
+ /** Unsolicited frames from the machine (not responses to requests), with their connection. */
110
+ onFrame?(deviceId: string, frame: unknown, connection: DialInConnectionInfo): Promise<void>;
111
+ /**
112
+ * The connection whose hello this provider accepted closed. `connection` is that connection's,
113
+ * so a `replaced` close names the old machine, never the one that replaced it.
114
+ */
115
+ onClose?(deviceId: string, reason: "offline" | "replaced" | "revoked" | "deleted", connection: DialInConnectionInfo): void;
116
+ }
117
+ /** Which machine and which of its connections a {@link DialInHandler} call is about. */
118
+ export interface DialInConnectionInfo {
119
+ /**
120
+ * The kernel's id of the signed-in machine (its credential): a machine signing in again to the
121
+ * same device, or another machine replacing it, gets another id.
122
+ */
123
+ machineId: string;
124
+ /** The connection id, the same the kernel sends to the machine in `ready`. */
125
+ connectionId: string;
126
+ }
127
+ /**
128
+ * `ctx.dialIn` (requires `permissions.dialIn`): talks to the machines serving this extension's
129
+ * devices. Each call checks that the device is served by the calling extension.
130
+ */
131
+ export interface DialInChannel {
132
+ /**
133
+ * Sends `frame` as the body of a `req` and resolves the body of the machine's `res`. Throws
134
+ * {@link DeviceOfflineError} when no machine holds the device within the reconnect grace.
135
+ */
136
+ request(deviceId: string, frame: unknown, opts: {
137
+ timeoutMs: number;
138
+ signal?: AbortSignal;
139
+ }): Promise<unknown>;
140
+ online(deviceId: string): Promise<boolean>;
141
+ /**
142
+ * The negotiated frame capacity of the machine's current connection: the `maxFrameBytes` the
143
+ * kernel sent in that connection's `ready` (the smaller of the machine's announced
144
+ * `transport.maxFrameBytes` and the deployment's limit). A provider sizes its request bodies
145
+ * and the answers it asks for by it: a `req` frame larger than this is refused. Null when no
146
+ * machine holds the device now. Read from shared state at every call, so a reconnect with
147
+ * another capacity shows at once; it can change between this call and a later request.
148
+ */
149
+ capacity(deviceId: string): Promise<{
150
+ maxFrameBytes: number;
151
+ } | null>;
152
+ stop(deviceId: string, reason: "drain" | "stop"): Promise<void>;
153
+ }
154
+ /**
155
+ * `ctx.devices` (requires `provides: ["device-provider@1"]`): what a device provider tells the
156
+ * kernel about its devices.
157
+ */
158
+ export interface DevicesCtx {
159
+ /**
160
+ * The device's report (`DeviceProvider.report`) or its permission support may have changed: the
161
+ * kernel reads the report (and the permission support of the device's instance, if any) again
162
+ * and stores them. When the revision changed, it invalidates what was approved against the old
163
+ * one; when only display text changed under the same revision, the new text is stored and no
164
+ * approval is invalidated.
165
+ */
166
+ reportChanged(deviceId: string): Promise<void>;
167
+ }
168
+ /** No machine serves the device (it is not connected, and did not reconnect within the grace). */
169
+ export declare class DeviceOfflineError extends Error {
170
+ readonly code = "device.offline";
171
+ constructor(deviceId: string, opts?: {
172
+ cause?: unknown;
173
+ });
174
+ }
175
+ /** Recognizes {@link DeviceOfflineError} by name and code, so another SDK copy's error matches. */
176
+ export declare function isDeviceOfflineError(e: unknown): e is DeviceOfflineError;
@@ -0,0 +1,115 @@
1
+ /**
2
+ * The dial-in channel: the kernel's generic way for a machine to connect to a deployment and
3
+ * serve one device of a `device-provider@1` extension that declares `permissions.dialIn`. The
4
+ * kernel signs the machine in, holds its socket on the gateway role, bounds every frame by the
5
+ * negotiated size and relays the frames' opaque `body` between the machine and the device's
6
+ * provider. It never reads a body: what a body means is the provider's protocol, named by
7
+ * `permissions.dialIn.protocol` and by the machine's hello.
8
+ */
9
+ import { z } from "zod";
10
+ /**
11
+ * A dial-in protocol: `<name>/<major>`, a lower-case name of 1 to 41 characters and a major
12
+ * version from 1 to 9999 (for example `capybara-device/6`). A machine's hello must name exactly
13
+ * the protocol of the provider serving its device.
14
+ */
15
+ export const DIAL_IN_PROTOCOL_RE = /^[a-z][a-z0-9-]{0,40}\/[1-9][0-9]{0,3}$/;
16
+ /** A machine frame that is not a valid dial-in envelope. The kernel closes the socket on it. */
17
+ export class DialInProtocolError extends Error {
18
+ constructor(message) {
19
+ super(message);
20
+ this.name = "DialInProtocolError";
21
+ }
22
+ }
23
+ /** Ids, `programRunId` and `bootId`: 1 to 128 letters, digits, `.`, `_`, `:` and `-`. */
24
+ const ID_RE = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/;
25
+ const id = z.string().regex(ID_RE);
26
+ const label = z.string().min(1).max(64);
27
+ // a frame without a body is malformed (JSON has no undefined, so this is a missing key)
28
+ const body = z.unknown().refine((v) => v !== undefined, "body is required");
29
+ const machineFrame = z.discriminatedUnion("type", [
30
+ z.strictObject({
31
+ type: z.literal("hello"),
32
+ protocol: z.string().regex(DIAL_IN_PROTOCOL_RE),
33
+ programRunId: id,
34
+ program: z.strictObject({
35
+ version: label,
36
+ os: label,
37
+ arch: label,
38
+ bootId: id.optional(),
39
+ }),
40
+ transport: z.strictObject({
41
+ maxFrameBytes: z.number().int().min(1024).max(Number.MAX_SAFE_INTEGER),
42
+ }),
43
+ body,
44
+ }),
45
+ z.strictObject({ type: z.literal("res"), id, body }),
46
+ z.strictObject({ type: z.literal("event"), body }),
47
+ ]);
48
+ /**
49
+ * Strictly parses one machine frame: the text must be at most `maxBytes` UTF-8 bytes (checked
50
+ * before `JSON.parse`), an object of a known `type` with exactly that type's keys. `body` is kept
51
+ * as parsed, never inspected. Throws {@link DialInProtocolError}; a `maxBytes` that is not a
52
+ * positive integer throws a `RangeError`.
53
+ */
54
+ export function parseDialInMachineFrame(text, maxBytes) {
55
+ return parseFrame(machineFrame, text, maxBytes);
56
+ }
57
+ function parseFrame(schema, text, maxBytes) {
58
+ if (!Number.isSafeInteger(maxBytes) || maxBytes < 1)
59
+ throw new RangeError(`maxBytes must be a positive integer, got ${maxBytes}`);
60
+ // a UTF-16 code unit is at least one UTF-8 byte: the length alone may already decide it
61
+ if (text.length > maxBytes || new TextEncoder().encode(text).byteLength > maxBytes)
62
+ throw new DialInProtocolError(`frame exceeds ${maxBytes} bytes`);
63
+ let parsed;
64
+ try {
65
+ parsed = JSON.parse(text);
66
+ }
67
+ catch {
68
+ throw new DialInProtocolError("frame is not valid JSON");
69
+ }
70
+ const r = schema.safeParse(parsed);
71
+ if (!r.success) {
72
+ const issue = r.error.issues[0];
73
+ const at = issue?.path.length ? ` at ${issue.path.join(".")}` : "";
74
+ throw new DialInProtocolError(`invalid dial-in frame${at}: ${issue?.message ?? "malformed"}`);
75
+ }
76
+ return r.data;
77
+ }
78
+ const kernelFrame = z.discriminatedUnion("type", [
79
+ z.strictObject({
80
+ type: z.literal("ready"),
81
+ connectionId: id,
82
+ maxFrameBytes: z.number().int().min(1024).max(Number.MAX_SAFE_INTEGER),
83
+ }),
84
+ z.strictObject({
85
+ type: z.literal("req"),
86
+ id,
87
+ deadlineMs: z.number().int().min(1).max(Number.MAX_SAFE_INTEGER),
88
+ body,
89
+ }),
90
+ z.strictObject({ type: z.literal("cancel"), id }),
91
+ z.strictObject({ type: z.literal("stop"), reason: z.enum(["drain", "stop"]) }),
92
+ ]);
93
+ /**
94
+ * The machine's side of {@link parseDialInMachineFrame}: strictly parses one kernel frame, at most
95
+ * `maxBytes` UTF-8 bytes (checked before `JSON.parse`), an object of a known `type` with exactly
96
+ * that type's keys; `body` is kept as parsed. Throws {@link DialInProtocolError}; a `maxBytes`
97
+ * that is not a positive integer throws a `RangeError`.
98
+ */
99
+ export function parseDialInKernelFrame(text, maxBytes) {
100
+ return parseFrame(kernelFrame, text, maxBytes);
101
+ }
102
+ /** No machine serves the device (it is not connected, and did not reconnect within the grace). */
103
+ export class DeviceOfflineError extends Error {
104
+ code = "device.offline";
105
+ constructor(deviceId, opts) {
106
+ super(`Device ${deviceId} is offline: no machine is connected for it. Reconnect the machine and retry.`, opts && "cause" in opts ? { cause: opts.cause } : undefined);
107
+ this.name = "DeviceOfflineError";
108
+ }
109
+ }
110
+ /** Recognizes {@link DeviceOfflineError} by name and code, so another SDK copy's error matches. */
111
+ export function isDeviceOfflineError(e) {
112
+ return (e instanceof Error &&
113
+ e.name === "DeviceOfflineError" &&
114
+ e.code === "device.offline");
115
+ }
@@ -31,6 +31,8 @@ export declare const CHANNEL_EXTENSION_POINT = "channel@1";
31
31
  export declare const IDENTITY_SOURCE_EXTENSION_POINT = "identity-source@1";
32
32
  /** Directory sync extension point ref (see `directory.ts`). */
33
33
  export declare const DIRECTORY_EXTENSION_POINT = "directory@1";
34
+ /** Context provider extension point ref (see `context.ts`). */
35
+ export declare const CONTEXT_EXTENSION_POINT = "context@1";
34
36
  /** Parses an extension point ref; throws when the format is invalid. */
35
37
  export declare function parseExtensionPoint(ref: string): {
36
38
  name: string;
@@ -8,19 +8,21 @@ const info = (majors, description, cardinality, brokered = false, orgScoped = fa
8
8
  });
9
9
  /** The registered extension points. */
10
10
  export const EXTENSION_POINTS = {
11
- sandbox: info([2], "Runs an environment's instance and keeps its files for agents' commands (Docker, E2B).", "single", true),
11
+ "device-provider": info([1], "Provides devices (an instance plus kept files) agents run commands in: containers, microVMs, connected machines.", "multi", true, true),
12
12
  "config-source": info([1], "Supplies deployment configuration from an external store such as Nacos.", "single"),
13
13
  "secret-store": info([1], "Stores and resolves secrets (connector credentials, secret config) outside the database.", "single", true),
14
14
  "object-store": info([1], "Stores files and artifacts in S3-compatible object storage, with presigned uploads.", "single", true),
15
15
  channel: info([1], "Connects an instant-messaging platform (Slack, Lark): inbound events, replies and cards.", "multi", false, true),
16
- "model-provider": info([1, 2], "Calls a model vendor's API and streams the result back to the runtime.", "multi", true),
16
+ "model-provider": info([2], "Calls a model vendor's API and streams the result back to the runtime.", "multi", true),
17
17
  "identity-source": info([1], "Signs people in through an external identity provider (SSO).", "multi"),
18
18
  directory: info([1], "Syncs members and departments from an external company directory.", "multi", false, true),
19
19
  counter: info([1], "Counts usage so quotas and reports can be built on it.", "multi"),
20
20
  connector: info([1], "Speaks one protocol (MCP, OpenAPI) to external systems and exposes their tools to agents.", "multi", true),
21
21
  "file-preview": info([1], "Renders previews of files of given types in the conversation UI.", "multi", false, true),
22
22
  "web-search": info([1], "Searches the web for the WebSearch tool; each org picks a default provider.", "multi", true, true, "org-default"),
23
+ context: info([1], "Adds text to the model's context at run start in conversations of orgs that enable it.", "multi", true, true),
23
24
  "web-fetch": info([1], "Fetches and extracts web pages for the WebFetch tool; each org picks a default provider.", "multi", true, true, "org-default"),
25
+ "push-provider": info([1], "Delivers push notifications to people's mobile apps through one channel (APNs, FCM, an aggregator).", "multi", true),
24
26
  };
25
27
  /** Cardinality of the registered extension points (derived from EXTENSION_POINTS). */
26
28
  export const EXTENSION_POINT_CARDINALITY = Object.fromEntries(Object.entries(EXTENSION_POINTS).map(([k, v]) => [k, v.cardinality]));
@@ -32,6 +34,8 @@ export const CHANNEL_EXTENSION_POINT = "channel@1";
32
34
  export const IDENTITY_SOURCE_EXTENSION_POINT = "identity-source@1";
33
35
  /** Directory sync extension point ref (see `directory.ts`). */
34
36
  export const DIRECTORY_EXTENSION_POINT = "directory@1";
37
+ /** Context provider extension point ref (see `context.ts`). */
38
+ export const CONTEXT_EXTENSION_POINT = "context@1";
35
39
  /** Parses an extension point ref; throws when the format is invalid. */
36
40
  export function parseExtensionPoint(ref) {
37
41
  const m = /^([a-z][a-z0-9-]*)@(\d+)$/.exec(ref);