@capybara-hq/plugin-sdk 0.1.0-rc.9 → 0.1.0-rc.90

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 (159) hide show
  1. package/README.md +3 -1
  2. package/agent-docs/agent-templates.md +14 -2
  3. package/agent-docs/concepts.md +14 -5
  4. package/agent-docs/connector-templates.md +11 -3
  5. package/agent-docs/extension-points/channel.md +1 -1
  6. package/agent-docs/extension-points/context.md +15 -0
  7. package/agent-docs/extension-points/device-provider.md +15 -0
  8. package/agent-docs/extension-points/file-preview.md +3 -1
  9. package/agent-docs/extension-points/identity-source.md +2 -0
  10. package/agent-docs/extension-points/model-provider.md +5 -1
  11. package/agent-docs/extension-points/object-store.md +2 -0
  12. package/agent-docs/extension-points/push-provider.md +17 -0
  13. package/agent-docs/extension-points/trigger-source.md +19 -0
  14. package/agent-docs/extensions.md +98 -4
  15. package/agent-docs/plugin-format.md +45 -10
  16. package/agent-docs/setup.md +54 -0
  17. package/api/plugin-sdk.api.md +5983 -0
  18. package/dist/agent-template.d.ts +15 -6
  19. package/dist/agent-template.js +32 -13
  20. package/dist/agents-ctx.d.ts +116 -0
  21. package/dist/agents-ctx.js +22 -0
  22. package/dist/avatar-presets.d.ts +8 -0
  23. package/dist/avatar-presets.js +17 -0
  24. package/dist/bootstrap.d.ts +109 -1
  25. package/dist/bootstrap.js +185 -2
  26. package/dist/cards.d.ts +121 -13
  27. package/dist/cards.js +161 -19
  28. package/dist/channel.d.ts +133 -47
  29. package/dist/channel.js +10 -5
  30. package/dist/client-css.d.ts +36 -0
  31. package/dist/client-css.js +326 -0
  32. package/dist/client-section.d.ts +35 -0
  33. package/dist/client-section.js +133 -0
  34. package/dist/config-ui.d.ts +28 -6
  35. package/dist/config-ui.js +88 -25
  36. package/dist/config-url-fetch.d.ts +19 -0
  37. package/dist/config-url-fetch.js +43 -0
  38. package/dist/connector-auth.d.ts +13 -2
  39. package/dist/connector-auth.js +82 -8
  40. package/dist/connector.d.ts +74 -32
  41. package/dist/context.d.ts +40 -0
  42. package/dist/context.js +2 -0
  43. package/dist/ctx.d.ts +344 -31
  44. package/dist/ctx.js +9 -1
  45. package/dist/define-extension.d.ts +18 -12
  46. package/dist/define-extension.js +18 -5
  47. package/dist/device-denied-paths.d.ts +20 -0
  48. package/dist/device-denied-paths.js +118 -0
  49. package/dist/device-operation.d.ts +348 -0
  50. package/dist/device-operation.js +312 -0
  51. package/dist/device-protocol.d.ts +286 -49
  52. package/dist/device-protocol.js +766 -89
  53. package/dist/device-provider.d.ts +820 -0
  54. package/dist/device-provider.js +432 -0
  55. package/dist/device-service.d.ts +204 -0
  56. package/dist/device-service.js +291 -0
  57. package/dist/dial-in.d.ts +286 -0
  58. package/dist/dial-in.js +213 -0
  59. package/dist/directory.d.ts +15 -12
  60. package/dist/extension-point.d.ts +2 -0
  61. package/dist/extension-point.js +8 -3
  62. package/dist/field-meta.d.ts +19 -0
  63. package/dist/field-meta.js +54 -0
  64. package/dist/file-preview.d.ts +46 -9
  65. package/dist/git-hosts.d.ts +53 -0
  66. package/dist/git-hosts.js +98 -0
  67. package/dist/hooks.d.ts +185 -22
  68. package/dist/hooks.js +6 -0
  69. package/dist/http-access.d.ts +71 -0
  70. package/dist/http-access.js +12 -0
  71. package/dist/identity.d.ts +70 -9
  72. package/dist/identity.js +46 -1
  73. package/dist/inbox.d.ts +103 -0
  74. package/dist/inbox.js +173 -0
  75. package/dist/index.d.ts +30 -4
  76. package/dist/index.js +30 -4
  77. package/dist/model-params.d.ts +41 -22
  78. package/dist/model-params.js +28 -15
  79. package/dist/model.d.ts +295 -77
  80. package/dist/model.js +249 -21
  81. package/dist/native-failure.d.ts +13 -0
  82. package/dist/native-failure.js +31 -0
  83. package/dist/net.d.ts +52 -0
  84. package/dist/net.js +34 -0
  85. package/dist/network-classes.d.ts +98 -0
  86. package/dist/network-classes.js +291 -0
  87. package/dist/permissions.d.ts +95 -25
  88. package/dist/permissions.js +175 -54
  89. package/dist/platform-only.d.ts +27 -0
  90. package/dist/platform-only.js +35 -0
  91. package/dist/plugin-manifest.d.ts +30 -6
  92. package/dist/plugin-manifest.js +147 -55
  93. package/dist/plugin-package.d.ts +82 -39
  94. package/dist/plugin-package.js +68 -41
  95. package/dist/push.d.ts +75 -0
  96. package/dist/push.js +87 -0
  97. package/dist/sandbox-linux-runtime-source.d.ts +1 -0
  98. package/dist/sandbox-linux-runtime-source.js +2343 -0
  99. package/dist/sandbox-native-runtime-source.d.ts +10 -0
  100. package/dist/sandbox-native-runtime-source.js +480 -0
  101. package/dist/sandbox-runtime-source.d.ts +47 -0
  102. package/dist/sandbox-runtime-source.js +73 -0
  103. package/dist/sandbox-write-denies.d.ts +139 -0
  104. package/dist/sandbox-write-denies.js +869 -0
  105. package/dist/secret.d.ts +8 -2
  106. package/dist/secret.js +11 -4
  107. package/dist/setup-check.d.ts +128 -0
  108. package/dist/setup-check.js +142 -0
  109. package/dist/setup-guide-parse.d.ts +121 -0
  110. package/dist/setup-guide-parse.js +356 -0
  111. package/dist/setup-guide-render.d.ts +45 -0
  112. package/dist/setup-guide-render.js +351 -0
  113. package/dist/setup-guide.d.ts +86 -72
  114. package/dist/setup-guide.js +340 -108
  115. package/dist/shell-capabilities.d.ts +216 -0
  116. package/dist/shell-capabilities.js +44 -0
  117. package/dist/shell-environment.d.ts +57 -0
  118. package/dist/shell-environment.js +21 -0
  119. package/dist/skill-invocation.d.ts +5 -0
  120. package/dist/skill-invocation.js +4 -3
  121. package/dist/skill.d.ts +27 -17
  122. package/dist/skill.js +40 -26
  123. package/dist/storage.d.ts +52 -25
  124. package/dist/svg-viewbox.d.ts +10 -0
  125. package/dist/svg-viewbox.js +24 -0
  126. package/dist/theme-assets.d.ts +25 -9
  127. package/dist/theme-assets.js +87 -47
  128. package/dist/theme-tokens.generated.d.ts +40 -12
  129. package/dist/theme-tokens.generated.js +36 -8
  130. package/dist/theme.d.ts +56 -10
  131. package/dist/theme.js +117 -23
  132. package/dist/tool.d.ts +242 -28
  133. package/dist/tool.js +135 -13
  134. package/dist/trigger-source.d.ts +35 -0
  135. package/dist/trigger-source.js +2 -0
  136. package/dist/triggers.d.ts +88 -0
  137. package/dist/triggers.js +71 -0
  138. package/dist/ui-parts.d.ts +23 -0
  139. package/dist/ui-parts.js +374 -0
  140. package/dist/ui-resolve.d.ts +2 -7
  141. package/dist/ui-resolve.js +7 -19
  142. package/dist/ui-slots.d.ts +27 -5
  143. package/dist/ui-slots.js +112 -19
  144. package/dist/ui.d.ts +203 -64
  145. package/dist/ui.js +117 -23
  146. package/dist/url.d.ts +4 -1
  147. package/dist/url.js +4 -1
  148. package/dist/web.d.ts +26 -20
  149. package/package.json +13 -1
  150. package/schemas/bootstrap-extra.v1.schema.json +186 -0
  151. package/schemas/bootstrap.v1.schema.json +20 -0
  152. package/schemas/connector-template.v1.schema.json +62 -4
  153. package/schemas/plugin.v1.schema.json +74 -143
  154. package/schemas/theme.v1.schema.json +77 -0
  155. package/agent-docs/extension-points/sandbox.md +0 -15
  156. package/dist/org-access.d.ts +0 -27
  157. package/dist/org-access.js +0 -35
  158. package/dist/sandbox.d.ts +0 -254
  159. package/dist/sandbox.js +0 -153
@@ -0,0 +1,432 @@
1
+ /**
2
+ * Device provider contract `device-provider@1`: a multi, brokered, org-scoped extension point
3
+ * (extensions may not `requires` it; the kernel's `SandboxService` consumes it). The provider implements only the
4
+ * primitives below; the kernel builds `glob` / `grep` / `edit` from `exec` plus `readFile` /
5
+ * `writeFile`.
6
+ *
7
+ * A device separates its **file system** from its **instance**: the file system
8
+ * (`createFileSystem`) lives until the device is deleted (`destroyFileSystem`); instances
9
+ * (`create`) attach to it and come and go (`destroy` drops the instance and keeps the files).
10
+ */
11
+ import { createHash } from "node:crypto";
12
+ /** Device provider extension point ref. */
13
+ export const DEVICE_PROVIDER_EXTENSION_POINT = "device-provider@1";
14
+ /** The roots inside the sandbox the model may access. */
15
+ export const SANDBOX_ROOTS = ["/workspace", "/skills", "/tmp"];
16
+ const MAX_PATH_LENGTH = 4096;
17
+ /** The roots every container-like provider uses; the same paths as {@link SANDBOX_ROOTS}. */
18
+ export const DEFAULT_SANDBOX_ROOTS = Object.freeze({
19
+ workspace: "/workspace",
20
+ skills: "/skills",
21
+ tmp: "/tmp",
22
+ });
23
+ /** The roots of an instance, falling back to {@link DEFAULT_SANDBOX_ROOTS}. */
24
+ export function rootsOf(h) {
25
+ return h.roots ?? DEFAULT_SANDBOX_ROOTS;
26
+ }
27
+ /**
28
+ * The only hosts a loopback port grant reaches (`ctx.deviceAccess.grantLoopbackPort`): the IPv4
29
+ * and IPv6 loopback literals and the name `localhost`, which the device dials without DNS. Every
30
+ * other loopback literal (`127.0.0.2`) and every private, link-local or metadata address stays
31
+ * closed.
32
+ */
33
+ export const LOOPBACK_GRANT_HOSTS = Object.freeze(["127.0.0.1", "::1", "localhost"]);
34
+ /**
35
+ * Whether `host` is one of {@link LOOPBACK_GRANT_HOSTS}: `::1` may also be written `[::1]`, and
36
+ * `localhost` matches case-insensitively. A trailing dot, a subdomain of `localhost` or an
37
+ * IPv4-mapped address is not one.
38
+ */
39
+ export function isLoopbackGrantHost(host) {
40
+ const h = host.toLowerCase();
41
+ return h === "127.0.0.1" || h === "::1" || h === "[::1]" || h === "localhost";
42
+ }
43
+ /**
44
+ * Well-known database ports (PostgreSQL, MySQL, Redis, MongoDB): a grant to one is allowed but
45
+ * flagged (`LoopbackGrantView.database`) and named in the approval and review texts.
46
+ */
47
+ export const LOOPBACK_DATABASE_PORTS = Object.freeze([5432, 3306, 6379, 27017]);
48
+ /** The most live loopback port grants one device service holds at once. */
49
+ export const LOOPBACK_MAX_PORTS_PER_SERVICE = 32;
50
+ /**
51
+ * The layer of a refusal by a device's sandbox proxy, read from the reason the proxy gives: the
52
+ * status phrase of its 403 answer to a CONNECT, or the reason in its violation line
53
+ * (`deny network-outbound <host>:<port> (<reason>)`).
54
+ *
55
+ * - `address`: the destination's address is closed (an IP literal in a closed class, or a name
56
+ * resolving to a private or local address: "address is …", "resolved to …"), or the host is
57
+ * malformed. No host grant reaches it, only a command run outside the sandbox.
58
+ * - `device`: the host is not on the operation's allowlist ("host is not on the allow list").
59
+ * - `unknown`: any other reason (a proxy that names none, a failed fake-IP lookup).
60
+ */
61
+ export function sandboxProxyRefusalLayer(reason) {
62
+ const r = reason.trim().toLowerCase();
63
+ if (r.startsWith("address is ") || r.startsWith("resolved to ") || r === "malformed host")
64
+ return "address";
65
+ if (r === "host is not on the allow list")
66
+ return "device";
67
+ return "unknown";
68
+ }
69
+ /**
70
+ * The instance is definitely gone on the provider's side (container removed, E2B sandbox expired).
71
+ * `exec` / `readFile` / `writeFile` / `stat` must throw it (not a plain Error) when they find the
72
+ * instance gone; the kernel then rebuilds the instance and retries once. A transient connection
73
+ * failure throws a plain error. In a managed operation (`operation()`), a gone instance found
74
+ * **before** the request reached the machine throws a `DeviceRequestNotSentError` with this error
75
+ * as its `cause`: the operation is then recorded as not started rather than as an unknown outcome,
76
+ * and the instance is still rebuilt, so the call can be retried on it.
77
+ */
78
+ export class SandboxGoneError extends Error {
79
+ sandboxGone = true;
80
+ constructor(message, opts) {
81
+ super(message, opts && "cause" in opts ? { cause: opts.cause } : undefined);
82
+ this.name = "SandboxGoneError";
83
+ }
84
+ }
85
+ /** Duck-typed check (not instanceof), so a plugin bundling another plugin-sdk copy still matches. */
86
+ export function isSandboxGoneError(e) {
87
+ return (e instanceof Error &&
88
+ e.name === "SandboxGoneError" &&
89
+ e.sandboxGone === true);
90
+ }
91
+ /**
92
+ * Thrown by a lifecycle call whose {@link DeviceFence} token is lower than one the instance
93
+ * already applied: the caller is a stale holder, and nothing was changed. The kernel handles it as
94
+ * a lost lease (never as a reason to recreate). `current` is the token the instance holds, when the
95
+ * provider knows it.
96
+ */
97
+ export class StaleFenceError extends Error {
98
+ staleFence = true;
99
+ current;
100
+ constructor(message, opts) {
101
+ super(message, opts && "cause" in opts ? { cause: opts.cause } : undefined);
102
+ this.name = "StaleFenceError";
103
+ this.current = opts?.current;
104
+ }
105
+ }
106
+ /** Duck-typed check (not instanceof), so a plugin bundling another plugin-sdk copy still matches. */
107
+ export function isStaleFenceError(e) {
108
+ return (e instanceof Error &&
109
+ e.name === "StaleFenceError" &&
110
+ e.staleFence === true);
111
+ }
112
+ /**
113
+ * The file system is definitely gone on the provider's side (volume removed, E2B sandbox killed).
114
+ * `create` throws it instead of attaching the instance to a new, empty file system; the kernel then
115
+ * reports the device's files as lost rather than handing out a silently empty workspace.
116
+ */
117
+ export class FileSystemGoneError extends Error {
118
+ fileSystemGone = true;
119
+ constructor(message, opts) {
120
+ super(message, opts && "cause" in opts ? { cause: opts.cause } : undefined);
121
+ this.name = "FileSystemGoneError";
122
+ }
123
+ }
124
+ /** Duck-typed check (not instanceof), so a plugin bundling another plugin-sdk copy still matches. */
125
+ export function isFileSystemGoneError(e) {
126
+ return (e instanceof Error &&
127
+ e.name === "FileSystemGoneError" &&
128
+ e.fileSystemGone === true);
129
+ }
130
+ /**
131
+ * A holder tag (`exec` argument `tag`, {@link DeviceProvider.killTagged}): the kernel passes its
132
+ * lease tokens (UUIDs). Providers check tags against it before putting them in a command line or a
133
+ * kill pattern.
134
+ */
135
+ export const SANDBOX_TAG_RE = /^[a-z0-9-]{1,64}$/;
136
+ /** Size limits {@link parseDeviceReport} enforces. */
137
+ export const DEVICE_REPORT_LIMITS = Object.freeze({
138
+ revisionChars: 128,
139
+ descriptionChars: 300,
140
+ limits: 8,
141
+ limitLabelChars: 60,
142
+ limitValueChars: 60,
143
+ homeChars: 4096,
144
+ changeHintChars: 400,
145
+ });
146
+ const isRecord = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
147
+ function exactKeys(v, keys, what) {
148
+ for (const k of Object.keys(v)) {
149
+ if (!keys.includes(k))
150
+ throw new TypeError(`${what}: unknown key ${k}`);
151
+ }
152
+ }
153
+ function parseText(v, max, what) {
154
+ if (!isRecord(v))
155
+ throw new TypeError(`${what} must be an object`);
156
+ exactKeys(v, ["en", "zh"], what);
157
+ const { en, zh } = v;
158
+ if (typeof en !== "string" || en === "" || en.length > max) {
159
+ throw new TypeError(`${what}.en must be a non-empty string of at most ${max} characters`);
160
+ }
161
+ if (zh === undefined)
162
+ return { en };
163
+ if (typeof zh !== "string" || zh === "" || zh.length > max) {
164
+ throw new TypeError(`${what}.zh must be a non-empty string of at most ${max} characters`);
165
+ }
166
+ return { en, zh };
167
+ }
168
+ /** Checks a provider's report; throws `TypeError` on any other shape, returns a clean copy. */
169
+ export function parseDeviceReport(value) {
170
+ const L = DEVICE_REPORT_LIMITS;
171
+ if (!isRecord(value))
172
+ throw new TypeError("device report must be an object");
173
+ exactKeys(value, ["revision", "description", "home", "limits", "reset", "changeHint"], "device report");
174
+ const { revision, home, limits, reset } = value;
175
+ if (typeof revision !== "string" || revision === "" || revision.length > L.revisionChars) {
176
+ throw new TypeError(`device report revision must be a non-empty string of at most ${L.revisionChars} characters`);
177
+ }
178
+ const description = parseText(value.description, L.descriptionChars, "device report description");
179
+ if (home !== null) {
180
+ if (typeof home !== "string" || home.length > L.homeChars) {
181
+ throw new TypeError("device report home must be an absolute path or null");
182
+ }
183
+ const errors = validateSandboxPathShape(home);
184
+ if (errors.length > 0)
185
+ throw new TypeError(`device report home: ${errors.join("; ")}`);
186
+ }
187
+ if (!Array.isArray(limits) || limits.length > L.limits) {
188
+ throw new TypeError(`device report limits must be an array of at most ${L.limits} entries`);
189
+ }
190
+ const parsedLimits = limits.map((raw, i) => {
191
+ const what = `device report limits[${i}]`;
192
+ if (!isRecord(raw))
193
+ throw new TypeError(`${what} must be an object`);
194
+ exactKeys(raw, ["label", "value"], what);
195
+ return {
196
+ label: parseText(raw.label, L.limitLabelChars, `${what}.label`),
197
+ value: parseText(raw.value, L.limitValueChars, `${what}.value`),
198
+ };
199
+ });
200
+ if (typeof reset !== "boolean")
201
+ throw new TypeError("device report reset must be a boolean");
202
+ const changeHint = value.changeHint === undefined
203
+ ? undefined
204
+ : parseText(value.changeHint, L.changeHintChars, "device report changeHint");
205
+ return {
206
+ revision,
207
+ description,
208
+ home,
209
+ limits: parsedLimits,
210
+ reset,
211
+ ...(changeHint !== undefined && { changeHint }),
212
+ };
213
+ }
214
+ /**
215
+ * The provider refuses a project directory (`projects` operations: it lies where the provider
216
+ * will not serve, for example another connection's directory). `reason` is shown to the person.
217
+ * The kernel answers it as `device.project_refused` (422).
218
+ */
219
+ export class ProjectPathRefusedError extends Error {
220
+ projectPathRefused = true;
221
+ reason;
222
+ constructor(reason, opts) {
223
+ super(reason.en, opts && "cause" in opts ? { cause: opts.cause } : undefined);
224
+ this.name = "ProjectPathRefusedError";
225
+ this.reason = reason;
226
+ }
227
+ }
228
+ /** Duck-typed check (not instanceof), so a plugin bundling another plugin-sdk copy still matches. */
229
+ export function isProjectPathRefusedError(e) {
230
+ return (e instanceof Error &&
231
+ e.name === "ProjectPathRefusedError" &&
232
+ e.projectPathRefused === true &&
233
+ isRecord(e.reason));
234
+ }
235
+ /**
236
+ * A device service name as an extension declares it (`permissions.deviceAccess.services`) and
237
+ * names it in `ctx.deviceAccess`: 1 to 32 characters, a lower-case letter then letters, digits
238
+ * and `-`.
239
+ */
240
+ export const DEVICE_SERVICE_NAME_RE = /^[a-z][a-z0-9-]{0,31}$/;
241
+ /**
242
+ * A device service id: what a device provider receives as the service's name. The kernel
243
+ * namespaces every extension's service names by the extension (`<extension>.<name>`,
244
+ * {@link deviceServiceId}), so two extensions declaring the same name never start, stop or reach
245
+ * each other's process; the provider keys everything of a service (its state and code
246
+ * directories, its socket, its process) by the id. At most 74 characters, one path segment.
247
+ */
248
+ export const DEVICE_SERVICE_ID_RE = /^[a-z][a-z0-9-]{1,40}\.[a-z][a-z0-9-]{0,31}$/;
249
+ /**
250
+ * The device service id of an extension's service (`<extension>.<name>`,
251
+ * {@link DEVICE_SERVICE_ID_RE}). Throws a `TypeError` for an extension name that is not one or a
252
+ * service name breaking {@link DEVICE_SERVICE_NAME_RE}.
253
+ */
254
+ export function deviceServiceId(extension, name) {
255
+ const id = `${extension}.${name}`;
256
+ if (!DEVICE_SERVICE_NAME_RE.test(name) || !DEVICE_SERVICE_ID_RE.test(id))
257
+ throw new TypeError(`Invalid device service ${JSON.stringify(name)} of extension ${JSON.stringify(extension)}`);
258
+ return id;
259
+ }
260
+ /**
261
+ * The digest of a service's files: `sha256:` and the hex SHA-256 over each file in path order
262
+ * (path, NUL, byte length, NUL, bytes). Providers report it in {@link DeviceServiceStatus} and
263
+ * may send it to a machine instead of the files.
264
+ */
265
+ export function deviceServiceFilesDigest(files) {
266
+ const cached = digests.get(files);
267
+ if (cached !== undefined)
268
+ return cached;
269
+ const digest = digestOf(files);
270
+ digests.set(files, digest);
271
+ return digest;
272
+ }
273
+ /**
274
+ * Digests already computed, by files object: a plugin passes the same `files` object on every
275
+ * call (its service files are read once), and a browser's are megabytes. Callers never mutate a
276
+ * spec's files after building it.
277
+ */
278
+ const digests = new WeakMap();
279
+ /**
280
+ * A fixed input and its {@link deviceServiceFilesDigest}, for the tests of every implementation
281
+ * of the digest (the SDK's, capybara-device's, a provider's own): one that disagrees would restart
282
+ * every running service at every ensure.
283
+ */
284
+ export const DEVICE_SERVICE_FILES_DIGEST_VECTOR = Object.freeze({
285
+ files: Object.freeze({
286
+ "main.js": "console.log(1)\n",
287
+ "lib/a.js": "export const a = 1;\n",
288
+ empty: "",
289
+ }),
290
+ digest: "sha256:7b3959ff2e10237b9f1a255bbecb5dacebd31422fe734b2867403e42913432a5",
291
+ });
292
+ function digestOf(files) {
293
+ const h = createHash("sha256");
294
+ for (const path of Object.keys(files).sort()) {
295
+ const data = files[path];
296
+ h.update(`${path}\0${data.byteLength}\0`);
297
+ h.update(data);
298
+ }
299
+ return `sha256:${h.digest("hex")}`;
300
+ }
301
+ // biome-ignore lint/suspicious/noControlCharactersInRegex: control characters are exactly what must be blocked
302
+ const CONTROL = /[\u0000-\u001f\u007f]/;
303
+ /**
304
+ * The most entries a `list` may ask for and its result may carry ({@link DeviceProvider.list}):
305
+ * part of the provider contract, which the device protocol's `list` op also honors.
306
+ */
307
+ export const MAX_DEVICE_LIST_ENTRIES = 1000;
308
+ /** The longest project name, in UTF-16 code units. */
309
+ export const MAX_DEVICE_PROJECT_NAME_LENGTH = 64;
310
+ /** The most candidates a `scan` answers ({@link DeviceProvider.scan}). */
311
+ export const MAX_DEVICE_SCAN_RESULTS = 50;
312
+ /**
313
+ * Directory names a `scan` never enters, at any depth ({@link DeviceProvider.scan}): dependency
314
+ * trees, not projects. Every provider skips exactly these.
315
+ */
316
+ export const DEVICE_SCAN_SKIPPED_DIRS = Object.freeze(["node_modules"]);
317
+ /**
318
+ * Directory names a `scan` does not enter directly under its `base` ({@link DeviceProvider.scan}):
319
+ * the owner's macOS `Library` (app data, huge, partly privacy-protected) is not where projects
320
+ * live. Every provider skips exactly these.
321
+ */
322
+ export const DEVICE_SCAN_SKIPPED_BASE_DIRS = Object.freeze(["Library"]);
323
+ /** How far below its base a `scan` looks: the base's children and their children. */
324
+ export const MAX_DEVICE_SCAN_DEPTH = 2;
325
+ /**
326
+ * The most directories one `scan` visits (reads the entries of), its `base` included
327
+ * ({@link DeviceProvider.scan}): breadth-first, each level in code-unit order of path.
328
+ */
329
+ export const MAX_DEVICE_SCAN_DIRS = 500;
330
+ /**
331
+ * Whether `v` is a valid project name (a project's identity on its device, and a `scan`
332
+ * candidate's `suggestedName`): non-empty, at most {@link MAX_DEVICE_PROJECT_NAME_LENGTH} UTF-16
333
+ * code units, not `.` or `..`, no `/`, no control characters, and no leading or trailing
334
+ * whitespace.
335
+ */
336
+ export function isDeviceProjectName(v) {
337
+ return (typeof v === "string" &&
338
+ v !== "" &&
339
+ v !== "." &&
340
+ v !== ".." &&
341
+ v.length <= MAX_DEVICE_PROJECT_NAME_LENGTH &&
342
+ !CONTROL.test(v) &&
343
+ !v.includes("/") &&
344
+ !/^\s|\s$/.test(v));
345
+ }
346
+ /**
347
+ * The root-independent checks of a path inside an instance (non-empty, at most 4096 characters, no
348
+ * control characters or backslashes, absolute, no empty or `..` segments); returns the errors,
349
+ * empty when valid. {@link validateSandboxPath} adds root membership.
350
+ */
351
+ export function validateSandboxPathShape(p) {
352
+ if (typeof p !== "string" || p.length === 0)
353
+ return ["path must be a non-empty string"];
354
+ if (p.length > MAX_PATH_LENGTH)
355
+ return [`path must be at most ${MAX_PATH_LENGTH} characters`];
356
+ if (CONTROL.test(p))
357
+ return ["path must not contain control characters"];
358
+ if (p.includes("\\"))
359
+ return ["path must not contain backslashes"];
360
+ if (!p.startsWith("/"))
361
+ return ["path must be absolute"];
362
+ if (p.includes("//"))
363
+ return ["path must not contain empty segments"];
364
+ for (const seg of p.split("/")) {
365
+ let decoded = seg;
366
+ try {
367
+ decoded = decodeURIComponent(seg);
368
+ }
369
+ catch {
370
+ // invalid percent-encoding is taken literally
371
+ }
372
+ if (seg === ".." || decoded === ".." || decoded.includes("/") || decoded.includes("\\")) {
373
+ return ["path must not contain '..' segments"];
374
+ }
375
+ }
376
+ return [];
377
+ }
378
+ /** A structural error after which {@link validateSandboxPath} stops (before the root check). */
379
+ const STOPS = new Set([
380
+ "path must be a non-empty string",
381
+ `path must be at most ${MAX_PATH_LENGTH} characters`,
382
+ "path must not contain control characters",
383
+ "path must not contain backslashes",
384
+ "path must be absolute",
385
+ "path must not contain empty segments",
386
+ ]);
387
+ /**
388
+ * Checks a path inside an instance; returns the errors, empty when valid: the
389
+ * {@link validateSandboxPathShape} checks, then root membership. `roots`: the instance's roots
390
+ * ({@link rootsOf}); absent means {@link SANDBOX_ROOTS}. The path must be one of them or under one.
391
+ */
392
+ export function validateSandboxPath(p, roots) {
393
+ const errors = validateSandboxPathShape(p);
394
+ if (errors.some((e) => STOPS.has(e)))
395
+ return errors;
396
+ const allowed = roots === undefined ? SANDBOX_ROOTS : [roots.workspace, roots.skills, roots.tmp];
397
+ if (!allowed.some((r) => p === r || p.startsWith(`${r}/`))) {
398
+ errors.push(`path must be under ${allowed.join(", ")}`);
399
+ }
400
+ return errors;
401
+ }
402
+ const LABEL = /^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/;
403
+ /**
404
+ * Validates an outbound allowlist host name: lowercase, no protocol or port, optional leading `*.`,
405
+ * IDN accepted only as punycode.
406
+ */
407
+ export function validateAllowHost(h) {
408
+ if (typeof h !== "string" || h.length === 0)
409
+ return ["host must be a non-empty string"];
410
+ if (h.length > 253)
411
+ return ["host must be at most 253 characters"];
412
+ const name = h.startsWith("*.") ? h.slice(2) : h;
413
+ if (name.length === 0)
414
+ return ["wildcard must be followed by a domain"];
415
+ const labels = name.split(".");
416
+ if (labels.every((l) => LABEL.test(l))) {
417
+ const tld = labels[labels.length - 1];
418
+ if (labels.length < 2)
419
+ return ["host must have at least two labels (no single-label names)"];
420
+ // The last label must start with a letter: this blocks the decimal / octal / hexadecimal
421
+ // spellings of IPv4
422
+ if (!/^[a-z]/.test(tld))
423
+ return ["host must not be an IP address literal"];
424
+ if (["local", "internal", "localhost"].includes(tld)) {
425
+ return ["host must not be in an internal-only domain (.local, .internal, .localhost)"];
426
+ }
427
+ return [];
428
+ }
429
+ return [
430
+ "host must be a lowercase hostname without scheme, port or path (optional leading '*.'; IDN as punycode)",
431
+ ];
432
+ }
@@ -0,0 +1,204 @@
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
+ * **Viewer streams.** On a stream the kernel opens for a viewer (a person's panel, through a
19
+ * viewer ticket), the first stream message after `{"kind":"stream"}` is written by the kernel, not
20
+ * the panel: the viewer context {@link DeviceServiceViewerContext},
21
+ * `{"kind":"viewer","conversationId":"<id>","rootConversationId":"<id>"}`, naming the ticket's
22
+ * conversation (checked at mint to be owned by the viewing person) and the root of its
23
+ * conversation tree (the conversation itself outside sub-agents). The panel's own messages
24
+ * follow, unchanged and in order. A service reads only that first message as context
25
+ * ({@link parseViewerContext}); a later message of the same shape comes from the panel and is
26
+ * never context. Providers and the device program pass the viewer context through like any
27
+ * stream message.
28
+ *
29
+ * **Kernel requests.** Besides the extension's own requests (`ctx.deviceAccess.request`), the
30
+ * kernel sends two request bodies of its own: the roll check ({@link DEVICE_SERVICE_ROLL_CHECK})
31
+ * and the conversation-deleted notice ({@link encodeConversationDeleted}).
32
+ */
33
+ /**
34
+ * The network a device service runs under (`service.ensure`): the device's network setting plus
35
+ * the service's live loopback port grants, which let it reach the loopback grant hosts
36
+ * (`LOOPBACK_GRANT_HOSTS`) on exactly those ports. The set is always sent whole, so an absent or
37
+ * empty one closes every loopback port again.
38
+ */
39
+ export interface DeviceServiceNetwork {
40
+ kind: "open-public" | "allowlist";
41
+ hosts: string[];
42
+ /**
43
+ * Live granted loopback ports, sorted ascending, unique, 1–65535, at most
44
+ * {@link LOOPBACK_MAX_PORTS_PER_SERVICE}.
45
+ */
46
+ loopbackPorts?: number[];
47
+ }
48
+ /**
49
+ * Strictly parses a set of loopback ports ({@link DeviceServiceNetwork.loopbackPorts}): an array
50
+ * of unique integers 1–65535, at most {@link LOOPBACK_MAX_PORTS_PER_SERVICE}; returns a sorted
51
+ * copy. Throws a `TypeError` naming `what` otherwise.
52
+ */
53
+ export declare function parseLoopbackPorts(value: unknown, what: string): number[];
54
+ /**
55
+ * The request body the kernel sends a running service before restarting it on new files (an
56
+ * upgraded extension, {@link DeviceServiceRollCheck}). A service that answers
57
+ * `{"busy":true,"reason":"…"}` is kept running (a person is using it); the kernel asks again at a
58
+ * later ensure. Any other answer, an error or no answer within a few seconds lets the restart go
59
+ * ahead, so a service that does not know the check is restarted as before. Every service gets
60
+ * this body on its request connection, so a service must ignore a request body it does not know
61
+ * (answer an error, act on nothing), never treat an arbitrary body as a command.
62
+ */
63
+ export declare const DEVICE_SERVICE_ROLL_CHECK = "{\"capybara\":\"roll-check\"}";
64
+ /** A service's answer to {@link DEVICE_SERVICE_ROLL_CHECK}. */
65
+ export interface DeviceServiceRollCheck {
66
+ /** True while restarting now would lose something a person is doing (a takeover, a handoff). */
67
+ busy: boolean;
68
+ /** What keeps it busy, for the kernel's log. */
69
+ reason?: string;
70
+ }
71
+ /** Whether `body` is the kernel's {@link DEVICE_SERVICE_ROLL_CHECK} request. */
72
+ export declare function isRollCheck(body: Uint8Array | string): boolean;
73
+ /** Reads a service's answer to the roll check: busy only for `{"busy":true}` (never throws). */
74
+ export declare function parseRollCheck(body: Uint8Array | string): DeviceServiceRollCheck;
75
+ /**
76
+ * How long a service may restore state it saved (after a restart, or when its device resumes):
77
+ * state saved longer ago than this is not restored. The kernel keeps a
78
+ * {@link encodeConversationDeleted} notice owed for at least this long after the deletion while
79
+ * the service is not running, so a service that restores within it still learns of the deletion.
80
+ */
81
+ export declare const DEVICE_SERVICE_RESTORE_MAX_AGE_MS: number;
82
+ /**
83
+ * The kernel's notice that a conversation was deleted: a request body the kernel sends every
84
+ * running service of an extension on the deleted conversation's device, at least once, soon after
85
+ * the deletion (a device that is offline gets it when it is back; a service that is stopped gets
86
+ * it when it runs again within {@link DEVICE_SERVICE_RESTORE_MAX_AGE_MS}). The kernel builds it
87
+ * from the deleted conversation's id. It arrives on a **request** connection only: a stream
88
+ * message of this shape is a viewer's (panel) input and never the notice, so a service parses it
89
+ * only on request connections. As with the roll check, the extension's own requests
90
+ * (`ctx.deviceAccess.request`) reach the same connection kind: a body of this shape sent by the
91
+ * extension is the extension's to answer for. The service forgets what it keeps for that
92
+ * conversation and for the conversations whose tree root it is (closes their pages, drops their
93
+ * state; never shared data such as a browser profile) and answers with any message: the kernel
94
+ * reads no more than that it answered. Handling it twice must be harmless. A service that does
95
+ * not know it ignores it, as any unknown body.
96
+ */
97
+ export interface DeviceServiceConversationDeleted {
98
+ capybara: "conversation-deleted";
99
+ conversationId: string;
100
+ }
101
+ /** The body of the kernel's conversation-deleted notice (UTF-8 JSON; the provider frames it). */
102
+ export declare function encodeConversationDeleted(conversationId: string): Uint8Array;
103
+ /**
104
+ * Reads a request body as the kernel's conversation-deleted notice: `capybara` is
105
+ * `"conversation-deleted"` and `conversationId` a non-empty string. Null for anything else (not
106
+ * UTF-8, not JSON, another shape, the roll check); never throws.
107
+ */
108
+ export declare function parseConversationDeleted(body: Uint8Array | string): DeviceServiceConversationDeleted | null;
109
+ /** Names the unix socket path the service listens on. */
110
+ export declare const DEVICE_SERVICE_SOCKET_ENV = "CAPYBARA_SERVICE_SOCKET";
111
+ /** Names the service's state directory (its own data, its write root; not where its code is). */
112
+ export declare const DEVICE_SERVICE_STATE_ENV = "CAPYBARA_SERVICE_STATE";
113
+ /**
114
+ * Names the device's workspace root. Every provider sets it for every service (a spec cannot set
115
+ * it); a service confines the files it takes in (uploads) and lets out (downloads) to it.
116
+ */
117
+ export declare const DEVICE_SERVICE_WORKSPACE_ENV = "CAPYBARA_SERVICE_WORKSPACE";
118
+ /**
119
+ * Names the service's install directory, where the provider gives it one (device-local does;
120
+ * absent elsewhere): a place for what the service fetches once and then only runs, such as a
121
+ * browser, apart from its state. The service may write it until it creates the regular file
122
+ * {@link DEVICE_SERVICE_INSTALL_SEAL} in it; from its next start on the directory is read only
123
+ * for the service, so nothing the service later runs (a compromised browser included) can
124
+ * replace what was installed. The provider empties it at every start that does not find it
125
+ * sealed under the service's current files (unsealed, or a plugin upgrade since; under its
126
+ * {@link DEVICE_SERVICE_INSTALL_KEY_FILE} where the service ships one), so a service
127
+ * installs afresh while unsealed and never trusts what it finds there. The process that seals
128
+ * keeps its write access until it exits, so a service runs no untrusted input (no web page) while
129
+ * unsealed, seals only a complete install and then exits; the next start, reviewed again, runs it
130
+ * read only.
131
+ */
132
+ export declare const DEVICE_SERVICE_INSTALL_ENV = "CAPYBARA_SERVICE_INSTALL";
133
+ /** The file that seals a service's install directory ({@link DEVICE_SERVICE_INSTALL_ENV}). */
134
+ export declare const DEVICE_SERVICE_INSTALL_SEAL = ".sealed";
135
+ /**
136
+ * A service file naming what its install directory holds ({@link DEVICE_SERVICE_INSTALL_ENV}): one
137
+ * line matching {@link DEVICE_SERVICE_INSTALL_KEY_RE}, such as the browser revision. capybara-device
138
+ * (the device-local provider's machine program, capybara-hq/plugins#311) keeps such installs in a
139
+ * machine-wide cache of the OS user and keys them by it instead of by the service's files, so a
140
+ * plugin upgrade that keeps the key reuses the sealed install, and so do the other devices of the
141
+ * same deployment (its URL's origin and path) on that machine. Services of other deployments,
142
+ * platforms or launch environments never see it. The provider still hands an unsealed install out
143
+ * empty and private to one start, publishes it only once the service exits sealed (every link
144
+ * inside it, no hard link, no special file) and verifies it before every reuse. It assumes the
145
+ * unsealed install is the service's own code running no untrusted input, as the seal does: a
146
+ * child that left its process group could still write through an open file after the digest
147
+ * (the next reuse's verification catches it). Absent (or malformed): the install is keyed by the
148
+ * files.
149
+ */
150
+ export declare const DEVICE_SERVICE_INSTALL_KEY_FILE = "capybara-install-key";
151
+ /** What {@link DEVICE_SERVICE_INSTALL_KEY_FILE} holds: lower case, so it is one name on every file system. */
152
+ export declare const DEVICE_SERVICE_INSTALL_KEY_RE: RegExp;
153
+ /**
154
+ * Names the Mach service allowances the provider's sandbox gives the service (macOS: device-local
155
+ * sets it, a spec cannot). Its value {@link DEVICE_SERVICE_MACH_CHROMIUM} means the full Chromium
156
+ * build can start there (its `MachPortRendezvousServer` check-in is allowed); absent, a service
157
+ * must not count on it (an older capybara-device refuses it).
158
+ */
159
+ export declare const DEVICE_SERVICE_MACH_ENV = "CAPYBARA_SERVICE_MACH";
160
+ /** {@link DEVICE_SERVICE_MACH_ENV}'s value for the full Chromium build's Mach services. */
161
+ export declare const DEVICE_SERVICE_MACH_CHROMIUM = "chromium";
162
+ /** The largest message body, in bytes, either side may send on a service connection. */
163
+ export declare const DEVICE_SERVICE_MAX_MESSAGE: number;
164
+ /** The kinds a connection's first message may name. */
165
+ export declare const SERVICE_CONNECTION_KINDS: readonly ["request", "stream"];
166
+ /** A service connection kind ({@link SERVICE_CONNECTION_KINDS}). */
167
+ export type ServiceConnectionKind = (typeof SERVICE_CONNECTION_KINDS)[number];
168
+ /**
169
+ * Frames one message: a 4-byte big-endian length followed by `body`. Throws a `RangeError` for a
170
+ * body above {@link DEVICE_SERVICE_MAX_MESSAGE}.
171
+ */
172
+ export declare function encodeServiceMessage(body: Uint8Array): Uint8Array;
173
+ /**
174
+ * Splits a byte stream into the messages {@link encodeServiceMessage} framed, whatever the chunk
175
+ * boundaries. `push` returns the messages completed by `chunk` (copies, safe to keep). A declared
176
+ * length above {@link DEVICE_SERVICE_MAX_MESSAGE} throws a `RangeError` as soon as the header is
177
+ * read; the connection should then be closed (the decoder is not usable afterwards).
178
+ */
179
+ export declare class ServiceMessageDecoder {
180
+ private chunks;
181
+ private first;
182
+ private pending;
183
+ private need;
184
+ push(chunk: Uint8Array): Uint8Array[];
185
+ /** Removes the first `n` (at most `pending`) bytes into one new array, copying each byte once. */
186
+ private take;
187
+ }
188
+ /**
189
+ * The first stream message of a viewer stream, written by the kernel (see the protocol above):
190
+ * the ticket's conversation and the root of its conversation tree.
191
+ */
192
+ export interface DeviceServiceViewerContext {
193
+ kind: "viewer";
194
+ conversationId: string;
195
+ rootConversationId: string;
196
+ }
197
+ /** The body of the viewer context stream message (UTF-8 JSON; the provider frames it). */
198
+ export declare function encodeViewerContext(ctx: DeviceServiceViewerContext): Uint8Array;
199
+ /**
200
+ * Reads a stream message body as the viewer context: `kind` is `"viewer"` and both ids are
201
+ * non-empty strings; only those three fields are returned. Null for anything else (not UTF-8,
202
+ * not JSON, another shape).
203
+ */
204
+ export declare function parseViewerContext(body: Uint8Array | string): DeviceServiceViewerContext | null;