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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (146) hide show
  1. package/README.md +1 -1
  2. package/agent-docs/agent-templates.md +14 -2
  3. package/agent-docs/concepts.md +14 -5
  4. package/agent-docs/connector-templates.md +11 -3
  5. package/agent-docs/extension-points/channel.md +1 -1
  6. package/agent-docs/extension-points/context.md +15 -0
  7. package/agent-docs/extension-points/device-provider.md +15 -0
  8. package/agent-docs/extension-points/file-preview.md +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 +76 -3
  13. package/agent-docs/plugin-format.md +51 -12
  14. package/agent-docs/setup.md +54 -0
  15. package/dist/agent-template.d.ts +15 -6
  16. package/dist/agent-template.js +32 -13
  17. package/dist/avatar-presets.d.ts +8 -0
  18. package/dist/avatar-presets.js +17 -0
  19. package/dist/bootstrap.d.ts +109 -1
  20. package/dist/bootstrap.js +185 -2
  21. package/dist/cards.d.ts +60 -13
  22. package/dist/cards.js +88 -18
  23. package/dist/channel.d.ts +128 -47
  24. package/dist/channel.js +10 -5
  25. package/dist/client-css.d.ts +36 -0
  26. package/dist/client-css.js +326 -0
  27. package/dist/client-section.d.ts +35 -0
  28. package/dist/client-section.js +133 -0
  29. package/dist/config-ui.d.ts +28 -6
  30. package/dist/config-ui.js +88 -25
  31. package/dist/config-url-fetch.d.ts +19 -0
  32. package/dist/config-url-fetch.js +43 -0
  33. package/dist/connector-auth.d.ts +13 -2
  34. package/dist/connector-auth.js +82 -8
  35. package/dist/connector.d.ts +74 -32
  36. package/dist/context.d.ts +40 -0
  37. package/dist/context.js +2 -0
  38. package/dist/ctx.d.ts +210 -30
  39. package/dist/ctx.js +9 -1
  40. package/dist/define-extension.d.ts +23 -13
  41. package/dist/define-extension.js +19 -5
  42. package/dist/device-denied-paths.d.ts +20 -0
  43. package/dist/device-denied-paths.js +118 -0
  44. package/dist/device-operation.d.ts +339 -0
  45. package/dist/device-operation.js +312 -0
  46. package/dist/device-protocol.d.ts +285 -50
  47. package/dist/device-protocol.js +755 -90
  48. package/dist/device-provider.d.ts +708 -0
  49. package/dist/device-provider.js +325 -0
  50. package/dist/device-service.d.ts +52 -0
  51. package/dist/device-service.js +105 -0
  52. package/dist/dial-in.d.ts +239 -0
  53. package/dist/dial-in.js +155 -0
  54. package/dist/directory.d.ts +15 -12
  55. package/dist/extension-point.d.ts +2 -0
  56. package/dist/extension-point.js +6 -2
  57. package/dist/field-meta.d.ts +19 -0
  58. package/dist/field-meta.js +54 -0
  59. package/dist/file-preview.d.ts +26 -10
  60. package/dist/git-hosts.d.ts +53 -0
  61. package/dist/git-hosts.js +98 -0
  62. package/dist/hooks.d.ts +125 -20
  63. package/dist/hooks.js +5 -0
  64. package/dist/http-access.d.ts +62 -0
  65. package/dist/http-access.js +12 -0
  66. package/dist/identity.d.ts +38 -9
  67. package/dist/identity.js +21 -1
  68. package/dist/index.d.ts +31 -4
  69. package/dist/index.js +31 -4
  70. package/dist/model-params.d.ts +41 -22
  71. package/dist/model-params.js +28 -15
  72. package/dist/model.d.ts +210 -75
  73. package/dist/model.js +152 -19
  74. package/dist/net.d.ts +52 -0
  75. package/dist/net.js +34 -0
  76. package/dist/network-classes.d.ts +98 -0
  77. package/dist/network-classes.js +291 -0
  78. package/dist/permissions.d.ts +65 -22
  79. package/dist/permissions.js +139 -43
  80. package/dist/platform-only.d.ts +27 -0
  81. package/dist/platform-only.js +35 -0
  82. package/dist/plugin-manifest.d.ts +40 -9
  83. package/dist/plugin-manifest.js +171 -60
  84. package/dist/plugin-package.d.ts +82 -39
  85. package/dist/plugin-package.js +68 -41
  86. package/dist/push.d.ts +75 -0
  87. package/dist/push.js +87 -0
  88. package/dist/sandbox-linux-runtime-source.d.ts +1 -0
  89. package/dist/sandbox-linux-runtime-source.js +2343 -0
  90. package/dist/sandbox-native-runtime-source.d.ts +10 -0
  91. package/dist/sandbox-native-runtime-source.js +476 -0
  92. package/dist/sandbox-runtime-source.d.ts +47 -0
  93. package/dist/sandbox-runtime-source.js +73 -0
  94. package/dist/sandbox-write-denies.d.ts +139 -0
  95. package/dist/sandbox-write-denies.js +869 -0
  96. package/dist/secret.d.ts +8 -2
  97. package/dist/secret.js +11 -4
  98. package/dist/setup-check.d.ts +128 -0
  99. package/dist/setup-check.js +142 -0
  100. package/dist/setup-guide-parse.d.ts +121 -0
  101. package/dist/setup-guide-parse.js +356 -0
  102. package/dist/setup-guide-render.d.ts +45 -0
  103. package/dist/setup-guide-render.js +351 -0
  104. package/dist/setup-guide.d.ts +86 -72
  105. package/dist/setup-guide.js +340 -108
  106. package/dist/shell-capabilities.d.ts +211 -0
  107. package/dist/shell-capabilities.js +44 -0
  108. package/dist/shell-environment.d.ts +57 -0
  109. package/dist/shell-environment.js +21 -0
  110. package/dist/skill.d.ts +27 -17
  111. package/dist/skill.js +40 -26
  112. package/dist/storage.d.ts +52 -25
  113. package/dist/svg-viewbox.d.ts +10 -0
  114. package/dist/svg-viewbox.js +24 -0
  115. package/dist/theme-assets.d.ts +55 -0
  116. package/dist/theme-assets.js +489 -0
  117. package/dist/theme-readability.d.ts +37 -0
  118. package/dist/theme-readability.js +145 -0
  119. package/dist/theme-tokens.generated.d.ts +299 -0
  120. package/dist/theme-tokens.generated.js +184 -0
  121. package/dist/theme.d.ts +190 -0
  122. package/dist/theme.js +471 -0
  123. package/dist/tool.d.ts +104 -30
  124. package/dist/tool.js +29 -9
  125. package/dist/ui-parts.d.ts +23 -0
  126. package/dist/ui-parts.js +385 -0
  127. package/dist/ui-resolve.d.ts +35 -0
  128. package/dist/ui-resolve.js +42 -0
  129. package/dist/ui-slots.d.ts +65 -0
  130. package/dist/ui-slots.js +261 -0
  131. package/dist/ui.d.ts +221 -77
  132. package/dist/ui.js +104 -27
  133. package/dist/url.d.ts +4 -1
  134. package/dist/url.js +4 -1
  135. package/dist/web.d.ts +26 -20
  136. package/package.json +13 -1
  137. package/schemas/bootstrap-extra.v1.schema.json +186 -0
  138. package/schemas/bootstrap.v1.schema.json +20 -0
  139. package/schemas/connector-template.v1.schema.json +62 -4
  140. package/schemas/plugin.v1.schema.json +93 -143
  141. package/schemas/theme.v1.schema.json +302 -0
  142. package/agent-docs/extension-points/sandbox.md +0 -15
  143. package/dist/org-access.d.ts +0 -27
  144. package/dist/org-access.js +0 -35
  145. package/dist/sandbox.d.ts +0 -254
  146. package/dist/sandbox.js +0 -153
@@ -0,0 +1,325 @@
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
+ * Thrown by a lifecycle call whose {@link DeviceFence} token is lower than one the instance
50
+ * already applied: the caller is a stale holder, and nothing was changed. The kernel handles it as
51
+ * a lost lease (never as a reason to recreate). `current` is the token the instance holds, when the
52
+ * provider knows it.
53
+ */
54
+ export class StaleFenceError extends Error {
55
+ staleFence = true;
56
+ current;
57
+ constructor(message, opts) {
58
+ super(message, opts && "cause" in opts ? { cause: opts.cause } : undefined);
59
+ this.name = "StaleFenceError";
60
+ this.current = opts?.current;
61
+ }
62
+ }
63
+ /** Duck-typed check (not instanceof), so a plugin bundling another plugin-sdk copy still matches. */
64
+ export function isStaleFenceError(e) {
65
+ return (e instanceof Error &&
66
+ e.name === "StaleFenceError" &&
67
+ e.staleFence === true);
68
+ }
69
+ /**
70
+ * The file system is definitely gone on the provider's side (volume removed, E2B sandbox killed).
71
+ * `create` throws it instead of attaching the instance to a new, empty file system; the kernel then
72
+ * reports the device's files as lost rather than handing out a silently empty workspace.
73
+ */
74
+ export class FileSystemGoneError extends Error {
75
+ fileSystemGone = true;
76
+ constructor(message, opts) {
77
+ super(message, opts && "cause" in opts ? { cause: opts.cause } : undefined);
78
+ this.name = "FileSystemGoneError";
79
+ }
80
+ }
81
+ /** Duck-typed check (not instanceof), so a plugin bundling another plugin-sdk copy still matches. */
82
+ export function isFileSystemGoneError(e) {
83
+ return (e instanceof Error &&
84
+ e.name === "FileSystemGoneError" &&
85
+ e.fileSystemGone === true);
86
+ }
87
+ /**
88
+ * A holder tag (`exec` argument `tag`, {@link DeviceProvider.killTagged}): the kernel passes its
89
+ * lease tokens (UUIDs). Providers check tags against it before putting them in a command line or a
90
+ * kill pattern.
91
+ */
92
+ export const SANDBOX_TAG_RE = /^[a-z0-9-]{1,64}$/;
93
+ /** Size limits {@link parseDeviceReport} enforces. */
94
+ export const DEVICE_REPORT_LIMITS = Object.freeze({
95
+ revisionChars: 128,
96
+ descriptionChars: 300,
97
+ limits: 8,
98
+ limitLabelChars: 60,
99
+ limitValueChars: 60,
100
+ homeChars: 4096,
101
+ changeHintChars: 400,
102
+ });
103
+ const isRecord = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
104
+ function exactKeys(v, keys, what) {
105
+ for (const k of Object.keys(v)) {
106
+ if (!keys.includes(k))
107
+ throw new TypeError(`${what}: unknown key ${k}`);
108
+ }
109
+ }
110
+ function parseText(v, max, what) {
111
+ if (!isRecord(v))
112
+ throw new TypeError(`${what} must be an object`);
113
+ exactKeys(v, ["en", "zh"], what);
114
+ const { en, zh } = v;
115
+ if (typeof en !== "string" || en === "" || en.length > max) {
116
+ throw new TypeError(`${what}.en must be a non-empty string of at most ${max} characters`);
117
+ }
118
+ if (zh === undefined)
119
+ return { en };
120
+ if (typeof zh !== "string" || zh === "" || zh.length > max) {
121
+ throw new TypeError(`${what}.zh must be a non-empty string of at most ${max} characters`);
122
+ }
123
+ return { en, zh };
124
+ }
125
+ /** Checks a provider's report; throws `TypeError` on any other shape, returns a clean copy. */
126
+ export function parseDeviceReport(value) {
127
+ const L = DEVICE_REPORT_LIMITS;
128
+ if (!isRecord(value))
129
+ throw new TypeError("device report must be an object");
130
+ exactKeys(value, ["revision", "description", "home", "limits", "reset", "changeHint"], "device report");
131
+ const { revision, home, limits, reset } = value;
132
+ if (typeof revision !== "string" || revision === "" || revision.length > L.revisionChars) {
133
+ throw new TypeError(`device report revision must be a non-empty string of at most ${L.revisionChars} characters`);
134
+ }
135
+ const description = parseText(value.description, L.descriptionChars, "device report description");
136
+ if (home !== null) {
137
+ if (typeof home !== "string" || home.length > L.homeChars) {
138
+ throw new TypeError("device report home must be an absolute path or null");
139
+ }
140
+ const errors = validateSandboxPathShape(home);
141
+ if (errors.length > 0)
142
+ throw new TypeError(`device report home: ${errors.join("; ")}`);
143
+ }
144
+ if (!Array.isArray(limits) || limits.length > L.limits) {
145
+ throw new TypeError(`device report limits must be an array of at most ${L.limits} entries`);
146
+ }
147
+ const parsedLimits = limits.map((raw, i) => {
148
+ const what = `device report limits[${i}]`;
149
+ if (!isRecord(raw))
150
+ throw new TypeError(`${what} must be an object`);
151
+ exactKeys(raw, ["label", "value"], what);
152
+ return {
153
+ label: parseText(raw.label, L.limitLabelChars, `${what}.label`),
154
+ value: parseText(raw.value, L.limitValueChars, `${what}.value`),
155
+ };
156
+ });
157
+ if (typeof reset !== "boolean")
158
+ throw new TypeError("device report reset must be a boolean");
159
+ const changeHint = value.changeHint === undefined
160
+ ? undefined
161
+ : parseText(value.changeHint, L.changeHintChars, "device report changeHint");
162
+ return {
163
+ revision,
164
+ description,
165
+ home,
166
+ limits: parsedLimits,
167
+ reset,
168
+ ...(changeHint !== undefined && { changeHint }),
169
+ };
170
+ }
171
+ /**
172
+ * The provider refuses a project directory (`projects` operations: it lies where the provider
173
+ * will not serve, for example another connection's directory). `reason` is shown to the person.
174
+ * The kernel answers it as `device.project_refused` (422).
175
+ */
176
+ export class ProjectPathRefusedError extends Error {
177
+ projectPathRefused = true;
178
+ reason;
179
+ constructor(reason, opts) {
180
+ super(reason.en, opts && "cause" in opts ? { cause: opts.cause } : undefined);
181
+ this.name = "ProjectPathRefusedError";
182
+ this.reason = reason;
183
+ }
184
+ }
185
+ /** Duck-typed check (not instanceof), so a plugin bundling another plugin-sdk copy still matches. */
186
+ export function isProjectPathRefusedError(e) {
187
+ return (e instanceof Error &&
188
+ e.name === "ProjectPathRefusedError" &&
189
+ e.projectPathRefused === true &&
190
+ isRecord(e.reason));
191
+ }
192
+ /** A device service name: 1 to 32 characters, a lower-case letter then letters, digits and `-`. */
193
+ export const DEVICE_SERVICE_NAME_RE = /^[a-z][a-z0-9-]{0,31}$/;
194
+ // biome-ignore lint/suspicious/noControlCharactersInRegex: control characters are exactly what must be blocked
195
+ const CONTROL = /[\u0000-\u001f\u007f]/;
196
+ /**
197
+ * The most entries a `list` may ask for and its result may carry ({@link DeviceProvider.list}):
198
+ * part of the provider contract, which the device protocol's `list` op also honors.
199
+ */
200
+ export const MAX_DEVICE_LIST_ENTRIES = 1000;
201
+ /** The longest project name, in UTF-16 code units. */
202
+ export const MAX_DEVICE_PROJECT_NAME_LENGTH = 64;
203
+ /** The most candidates a `scan` answers ({@link DeviceProvider.scan}). */
204
+ export const MAX_DEVICE_SCAN_RESULTS = 50;
205
+ /**
206
+ * Directory names a `scan` never enters, at any depth ({@link DeviceProvider.scan}): dependency
207
+ * trees, not projects. Every provider skips exactly these.
208
+ */
209
+ export const DEVICE_SCAN_SKIPPED_DIRS = Object.freeze(["node_modules"]);
210
+ /**
211
+ * Directory names a `scan` does not enter directly under its `base` ({@link DeviceProvider.scan}):
212
+ * the owner's macOS `Library` (app data, huge, partly privacy-protected) is not where projects
213
+ * live. Every provider skips exactly these.
214
+ */
215
+ export const DEVICE_SCAN_SKIPPED_BASE_DIRS = Object.freeze(["Library"]);
216
+ /** How far below its base a `scan` looks: the base's children and their children. */
217
+ export const MAX_DEVICE_SCAN_DEPTH = 2;
218
+ /**
219
+ * The most directories one `scan` visits (reads the entries of), its `base` included
220
+ * ({@link DeviceProvider.scan}): breadth-first, each level in code-unit order of path.
221
+ */
222
+ export const MAX_DEVICE_SCAN_DIRS = 500;
223
+ /**
224
+ * Whether `v` is a valid project name (a project's identity on its device, and a `scan`
225
+ * candidate's `suggestedName`): non-empty, at most {@link MAX_DEVICE_PROJECT_NAME_LENGTH} UTF-16
226
+ * code units, not `.` or `..`, no `/`, no control characters, and no leading or trailing
227
+ * whitespace.
228
+ */
229
+ export function isDeviceProjectName(v) {
230
+ return (typeof v === "string" &&
231
+ v !== "" &&
232
+ v !== "." &&
233
+ v !== ".." &&
234
+ v.length <= MAX_DEVICE_PROJECT_NAME_LENGTH &&
235
+ !CONTROL.test(v) &&
236
+ !v.includes("/") &&
237
+ !/^\s|\s$/.test(v));
238
+ }
239
+ /**
240
+ * The root-independent checks of a path inside an instance (non-empty, at most 4096 characters, no
241
+ * control characters or backslashes, absolute, no empty or `..` segments); returns the errors,
242
+ * empty when valid. {@link validateSandboxPath} adds root membership.
243
+ */
244
+ export function validateSandboxPathShape(p) {
245
+ if (typeof p !== "string" || p.length === 0)
246
+ return ["path must be a non-empty string"];
247
+ if (p.length > MAX_PATH_LENGTH)
248
+ return [`path must be at most ${MAX_PATH_LENGTH} characters`];
249
+ if (CONTROL.test(p))
250
+ return ["path must not contain control characters"];
251
+ if (p.includes("\\"))
252
+ return ["path must not contain backslashes"];
253
+ if (!p.startsWith("/"))
254
+ return ["path must be absolute"];
255
+ if (p.includes("//"))
256
+ return ["path must not contain empty segments"];
257
+ for (const seg of p.split("/")) {
258
+ let decoded = seg;
259
+ try {
260
+ decoded = decodeURIComponent(seg);
261
+ }
262
+ catch {
263
+ // invalid percent-encoding is taken literally
264
+ }
265
+ if (seg === ".." || decoded === ".." || decoded.includes("/") || decoded.includes("\\")) {
266
+ return ["path must not contain '..' segments"];
267
+ }
268
+ }
269
+ return [];
270
+ }
271
+ /** A structural error after which {@link validateSandboxPath} stops (before the root check). */
272
+ const STOPS = new Set([
273
+ "path must be a non-empty string",
274
+ `path must be at most ${MAX_PATH_LENGTH} characters`,
275
+ "path must not contain control characters",
276
+ "path must not contain backslashes",
277
+ "path must be absolute",
278
+ "path must not contain empty segments",
279
+ ]);
280
+ /**
281
+ * Checks a path inside an instance; returns the errors, empty when valid: the
282
+ * {@link validateSandboxPathShape} checks, then root membership. `roots`: the instance's roots
283
+ * ({@link rootsOf}); absent means {@link SANDBOX_ROOTS}. The path must be one of them or under one.
284
+ */
285
+ export function validateSandboxPath(p, roots) {
286
+ const errors = validateSandboxPathShape(p);
287
+ if (errors.some((e) => STOPS.has(e)))
288
+ return errors;
289
+ const allowed = roots === undefined ? SANDBOX_ROOTS : [roots.workspace, roots.skills, roots.tmp];
290
+ if (!allowed.some((r) => p === r || p.startsWith(`${r}/`))) {
291
+ errors.push(`path must be under ${allowed.join(", ")}`);
292
+ }
293
+ return errors;
294
+ }
295
+ const LABEL = /^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/;
296
+ /**
297
+ * Validates an outbound allowlist host name: lowercase, no protocol or port, optional leading `*.`,
298
+ * IDN accepted only as punycode.
299
+ */
300
+ export function validateAllowHost(h) {
301
+ if (typeof h !== "string" || h.length === 0)
302
+ return ["host must be a non-empty string"];
303
+ if (h.length > 253)
304
+ return ["host must be at most 253 characters"];
305
+ const name = h.startsWith("*.") ? h.slice(2) : h;
306
+ if (name.length === 0)
307
+ return ["wildcard must be followed by a domain"];
308
+ const labels = name.split(".");
309
+ if (labels.every((l) => LABEL.test(l))) {
310
+ const tld = labels[labels.length - 1];
311
+ if (labels.length < 2)
312
+ return ["host must have at least two labels (no single-label names)"];
313
+ // The last label must start with a letter: this blocks the decimal / octal / hexadecimal
314
+ // spellings of IPv4
315
+ if (!/^[a-z]/.test(tld))
316
+ return ["host must not be an IP address literal"];
317
+ if (["local", "internal", "localhost"].includes(tld)) {
318
+ return ["host must not be in an internal-only domain (.local, .internal, .localhost)"];
319
+ }
320
+ return [];
321
+ }
322
+ return [
323
+ "host must be a lowercase hostname without scheme, port or path (optional leading '*.'; IDN as punycode)",
324
+ ];
325
+ }
@@ -0,0 +1,52 @@
1
+ /**
2
+ * The device service socket protocol: how a device provider (or the machine program serving a
3
+ * dial-in device) talks to a service it started with `DeviceProvider.ensureService`. Every
4
+ * provider and every service speaks it, so a service runs the same on every provider.
5
+ *
6
+ * The provider starts the service with {@link DEVICE_SERVICE_SOCKET_ENV} naming the unix socket
7
+ * the service listens on and {@link DEVICE_SERVICE_STATE_ENV} naming its state directory (the
8
+ * only place it may write besides the workspace downloads). The spec's files are written before
9
+ * start into the service's code directory: a directory the service can only read where the
10
+ * provider can separate code from state, else the state directory. On a connection,
11
+ * both sides exchange length-prefixed messages ({@link encodeServiceMessage}). The first message
12
+ * from the provider is JSON whose `kind` is one of {@link SERVICE_CONNECTION_KINDS}:
13
+ *
14
+ * - `{"kind":"request"}`: the next provider message is the request body; the service answers
15
+ * with exactly one message and closes the connection.
16
+ * - `{"kind":"stream"}`: both sides keep exchanging messages until either side closes.
17
+ */
18
+ /** Names the unix socket path the service listens on. */
19
+ export declare const DEVICE_SERVICE_SOCKET_ENV = "CAPYBARA_SERVICE_SOCKET";
20
+ /** Names the service's state directory (its own data, its write root; not where its code is). */
21
+ export declare const DEVICE_SERVICE_STATE_ENV = "CAPYBARA_SERVICE_STATE";
22
+ /**
23
+ * Names the device's workspace root. Every provider sets it for every service (a spec cannot set
24
+ * it); a service confines the files it takes in (uploads) and lets out (downloads) to it.
25
+ */
26
+ export declare const DEVICE_SERVICE_WORKSPACE_ENV = "CAPYBARA_SERVICE_WORKSPACE";
27
+ /** The largest message body, in bytes, either side may send on a service connection. */
28
+ export declare const DEVICE_SERVICE_MAX_MESSAGE: number;
29
+ /** The kinds a connection's first message may name. */
30
+ export declare const SERVICE_CONNECTION_KINDS: readonly ["request", "stream"];
31
+ /** A service connection kind ({@link SERVICE_CONNECTION_KINDS}). */
32
+ export type ServiceConnectionKind = (typeof SERVICE_CONNECTION_KINDS)[number];
33
+ /**
34
+ * Frames one message: a 4-byte big-endian length followed by `body`. Throws a `RangeError` for a
35
+ * body above {@link DEVICE_SERVICE_MAX_MESSAGE}.
36
+ */
37
+ export declare function encodeServiceMessage(body: Uint8Array): Uint8Array;
38
+ /**
39
+ * Splits a byte stream into the messages {@link encodeServiceMessage} framed, whatever the chunk
40
+ * boundaries. `push` returns the messages completed by `chunk` (copies, safe to keep). A declared
41
+ * length above {@link DEVICE_SERVICE_MAX_MESSAGE} throws a `RangeError` as soon as the header is
42
+ * read; the connection should then be closed (the decoder is not usable afterwards).
43
+ */
44
+ export declare class ServiceMessageDecoder {
45
+ private chunks;
46
+ private first;
47
+ private pending;
48
+ private need;
49
+ push(chunk: Uint8Array): Uint8Array[];
50
+ /** Removes the first `n` (at most `pending`) bytes into one new array, copying each byte once. */
51
+ private take;
52
+ }
@@ -0,0 +1,105 @@
1
+ /**
2
+ * The device service socket protocol: how a device provider (or the machine program serving a
3
+ * dial-in device) talks to a service it started with `DeviceProvider.ensureService`. Every
4
+ * provider and every service speaks it, so a service runs the same on every provider.
5
+ *
6
+ * The provider starts the service with {@link DEVICE_SERVICE_SOCKET_ENV} naming the unix socket
7
+ * the service listens on and {@link DEVICE_SERVICE_STATE_ENV} naming its state directory (the
8
+ * only place it may write besides the workspace downloads). The spec's files are written before
9
+ * start into the service's code directory: a directory the service can only read where the
10
+ * provider can separate code from state, else the state directory. On a connection,
11
+ * both sides exchange length-prefixed messages ({@link encodeServiceMessage}). The first message
12
+ * from the provider is JSON whose `kind` is one of {@link SERVICE_CONNECTION_KINDS}:
13
+ *
14
+ * - `{"kind":"request"}`: the next provider message is the request body; the service answers
15
+ * with exactly one message and closes the connection.
16
+ * - `{"kind":"stream"}`: both sides keep exchanging messages until either side closes.
17
+ */
18
+ /** Names the unix socket path the service listens on. */
19
+ export const DEVICE_SERVICE_SOCKET_ENV = "CAPYBARA_SERVICE_SOCKET";
20
+ /** Names the service's state directory (its own data, its write root; not where its code is). */
21
+ export const DEVICE_SERVICE_STATE_ENV = "CAPYBARA_SERVICE_STATE";
22
+ /**
23
+ * Names the device's workspace root. Every provider sets it for every service (a spec cannot set
24
+ * it); a service confines the files it takes in (uploads) and lets out (downloads) to it.
25
+ */
26
+ export const DEVICE_SERVICE_WORKSPACE_ENV = "CAPYBARA_SERVICE_WORKSPACE";
27
+ /** The largest message body, in bytes, either side may send on a service connection. */
28
+ export const DEVICE_SERVICE_MAX_MESSAGE = 8 * 1024 * 1024;
29
+ /** The kinds a connection's first message may name. */
30
+ export const SERVICE_CONNECTION_KINDS = ["request", "stream"];
31
+ const HEADER = 4;
32
+ /**
33
+ * Frames one message: a 4-byte big-endian length followed by `body`. Throws a `RangeError` for a
34
+ * body above {@link DEVICE_SERVICE_MAX_MESSAGE}.
35
+ */
36
+ export function encodeServiceMessage(body) {
37
+ if (body.byteLength > DEVICE_SERVICE_MAX_MESSAGE)
38
+ throw new RangeError(`service message of ${body.byteLength} bytes exceeds ${DEVICE_SERVICE_MAX_MESSAGE} bytes`);
39
+ const out = new Uint8Array(HEADER + body.byteLength);
40
+ new DataView(out.buffer).setUint32(0, body.byteLength);
41
+ out.set(body, HEADER);
42
+ return out;
43
+ }
44
+ /**
45
+ * Splits a byte stream into the messages {@link encodeServiceMessage} framed, whatever the chunk
46
+ * boundaries. `push` returns the messages completed by `chunk` (copies, safe to keep). A declared
47
+ * length above {@link DEVICE_SERVICE_MAX_MESSAGE} throws a `RangeError` as soon as the header is
48
+ * read; the connection should then be closed (the decoder is not usable afterwards).
49
+ */
50
+ export class ServiceMessageDecoder {
51
+ // unread bytes, oldest first from index `first`; `pending` is their total length
52
+ chunks = [];
53
+ first = 0;
54
+ pending = 0;
55
+ // the declared length of the message being read, once its header is complete
56
+ need = null;
57
+ push(chunk) {
58
+ if (chunk.byteLength > 0) {
59
+ this.chunks.push(chunk.slice());
60
+ this.pending += chunk.byteLength;
61
+ }
62
+ const out = [];
63
+ for (;;) {
64
+ if (this.need === null) {
65
+ if (this.pending < HEADER)
66
+ break;
67
+ const header = this.take(HEADER);
68
+ const len = new DataView(header.buffer, header.byteOffset, HEADER).getUint32(0);
69
+ if (len > DEVICE_SERVICE_MAX_MESSAGE)
70
+ throw new RangeError(`service message of ${len} bytes exceeds ${DEVICE_SERVICE_MAX_MESSAGE} bytes`);
71
+ this.need = len;
72
+ }
73
+ if (this.pending < this.need)
74
+ break;
75
+ out.push(this.take(this.need));
76
+ this.need = null;
77
+ }
78
+ return out;
79
+ }
80
+ /** Removes the first `n` (at most `pending`) bytes into one new array, copying each byte once. */
81
+ take(n) {
82
+ const out = new Uint8Array(n);
83
+ let at = 0;
84
+ while (at < n) {
85
+ // never undefined: callers take at most `pending` bytes
86
+ const head = this.chunks[this.first];
87
+ if (head === undefined)
88
+ break;
89
+ const k = Math.min(head.byteLength, n - at);
90
+ out.set(head.subarray(0, k), at);
91
+ at += k;
92
+ if (k === head.byteLength)
93
+ this.first++;
94
+ else
95
+ this.chunks[this.first] = head.subarray(k);
96
+ }
97
+ // drop consumed chunks in one go (no per-chunk shift)
98
+ if (this.first > 64 || this.first === this.chunks.length) {
99
+ this.chunks = this.chunks.slice(this.first);
100
+ this.first = 0;
101
+ }
102
+ this.pending -= n;
103
+ return out;
104
+ }
105
+ }