@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,312 @@
1
+ import { SANDBOX_TAG_RE, validateAllowHost, validateSandboxPathShape, } from "./device-provider.js";
2
+ /** Accepts only the supported permission profile names. */
3
+ export function isPermissionProfile(value) {
4
+ return value === "request-approval" || value === "approve-for-me" || value === "full-access";
5
+ }
6
+ /** The provider cannot enforce the requested permission profile. */
7
+ export class SandboxPermissionUnsupportedError extends Error {
8
+ sandboxPermissionUnsupported = true;
9
+ constructor(message, opts) {
10
+ super(message, opts && "cause" in opts ? { cause: opts.cause } : undefined);
11
+ this.name = "SandboxPermissionUnsupportedError";
12
+ }
13
+ }
14
+ /**
15
+ * Recognizes the inherited tag across SDK copies without requiring this class's identity, so every
16
+ * subclass counts too (for example {@link SandboxWorkUnsettledError}: the same definite refusal).
17
+ */
18
+ export function isSandboxPermissionUnsupportedError(e) {
19
+ return (e instanceof Error &&
20
+ e.sandboxPermissionUnsupported === true);
21
+ }
22
+ /**
23
+ * Earlier work on the device has not settled, so it refused to start a new operation. It extends
24
+ * {@link SandboxPermissionUnsupportedError} so every check that treats that error as a definite
25
+ * refusal (nothing ran) treats this one the same way.
26
+ */
27
+ export class SandboxWorkUnsettledError extends SandboxPermissionUnsupportedError {
28
+ sandboxWorkUnsettled = true;
29
+ constructor(message, opts) {
30
+ super(message, opts);
31
+ this.name = "SandboxWorkUnsettledError";
32
+ }
33
+ }
34
+ /** Recognizes the name and tag across SDK copies without requiring this class's identity. */
35
+ export function isSandboxWorkUnsettledError(e) {
36
+ return (e instanceof Error &&
37
+ e.name === "SandboxWorkUnsettledError" &&
38
+ e.sandboxWorkUnsettled === true);
39
+ }
40
+ /** The requested operation is outside the permitted scope. */
41
+ export class SandboxScopeDeniedError extends Error {
42
+ sandboxScopeDenied = true;
43
+ constructor(message, opts) {
44
+ super(message, opts && "cause" in opts ? { cause: opts.cause } : undefined);
45
+ this.name = "SandboxScopeDeniedError";
46
+ }
47
+ }
48
+ /** Recognizes the name and tag across SDK copies without requiring this class's identity. */
49
+ export function isSandboxScopeDeniedError(e) {
50
+ return (e instanceof Error &&
51
+ e.name === "SandboxScopeDeniedError" &&
52
+ e.sandboxScopeDenied === true);
53
+ }
54
+ /**
55
+ * A request refused because the machine's connection changed before it was sent: the request
56
+ * never reached the machine, so it ran nothing. A scope refusal (it keeps that error's name, so
57
+ * every scope check treats it as the definite pre-effect failure it is) that the operation path
58
+ * records as `not_sent`, never as an unknown outcome. It says nothing about an earlier request of
59
+ * the same operation, so a recovery tells it apart ({@link isDeviceRequestNotSent}).
60
+ *
61
+ * A provider throws it too when it finds the instance gone before contacting the machine (for
62
+ * example the machine's runtime changed since the instance was created), with a
63
+ * `SandboxGoneError` as its `cause`: nothing ran, and the kernel also rebuilds the instance so a
64
+ * retry of the call runs on the new one. A gone instance found after the request was sent is a
65
+ * bare `SandboxGoneError` (its outcome is unknown).
66
+ */
67
+ export class DeviceRequestNotSentError extends SandboxScopeDeniedError {
68
+ notSent = true;
69
+ }
70
+ /** Recognizes {@link DeviceRequestNotSentError} by its scope refusal's name and tags, across SDK copies. */
71
+ export function isDeviceRequestNotSent(e) {
72
+ return isSandboxScopeDeniedError(e) && e.notSent === true;
73
+ }
74
+ /** A scope or execution reference is malformed; validate it before performing any effects. */
75
+ export class SandboxScopeValidationError extends Error {
76
+ sandboxScopeValidation = true;
77
+ constructor(message, opts) {
78
+ super(message, opts && "cause" in opts ? { cause: opts.cause } : undefined);
79
+ this.name = "SandboxScopeValidationError";
80
+ }
81
+ }
82
+ /** Recognizes validation errors across SDK copies. */
83
+ export function isSandboxScopeValidationError(e) {
84
+ return (e instanceof Error &&
85
+ e.name === "SandboxScopeValidationError" &&
86
+ e.sandboxScopeValidation === true);
87
+ }
88
+ /** An operation was consumed but its outcome is unknown. Never automatically retry with a new ID. */
89
+ export class SandboxOperationOutcomeUnknownError extends Error {
90
+ sandboxOperationOutcomeUnknown = true;
91
+ constructor(message, opts) {
92
+ super(message, opts && "cause" in opts ? { cause: opts.cause } : undefined);
93
+ this.name = "SandboxOperationOutcomeUnknownError";
94
+ }
95
+ }
96
+ /** Recognizes unknown outcomes across SDK copies; an unknown outcome is not a gone instance. */
97
+ export function isSandboxOperationOutcomeUnknownError(e) {
98
+ return (e instanceof Error &&
99
+ e.name === "SandboxOperationOutcomeUnknownError" &&
100
+ e.sandboxOperationOutcomeUnknown === true);
101
+ }
102
+ /**
103
+ * Whether a report is a supported instance boundary: `boundary: "instance"` with no
104
+ * `unavailableReason`. An instance report naming a reason (a stale image, a digest mismatch)
105
+ * claims nothing, so a device reporting it is unsupported, never the whole-instance sandbox.
106
+ */
107
+ export function instanceSupported(report) {
108
+ return report.boundary === "instance" && report.unavailableReason === undefined;
109
+ }
110
+ function invalid(field, requirement) {
111
+ throw new SandboxScopeValidationError(`Invalid ${field}: ${requirement}. Supply a valid scope or reference before retrying.`);
112
+ }
113
+ function record(value, keys, field) {
114
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
115
+ return invalid(field, "expected an object");
116
+ }
117
+ const prototype = Object.getPrototypeOf(value);
118
+ if (prototype !== Object.prototype && prototype !== null)
119
+ return invalid(field, "expected a plain object");
120
+ const result = Object.create(null);
121
+ for (const key of Reflect.ownKeys(value)) {
122
+ if (typeof key !== "string" || !keys.includes(key))
123
+ return invalid(field, "unknown fields are not allowed");
124
+ const descriptor = Object.getOwnPropertyDescriptor(value, key);
125
+ if (!descriptor || !("value" in descriptor))
126
+ return invalid(field, "accessor fields are not allowed");
127
+ result[key] = descriptor.value;
128
+ }
129
+ return result;
130
+ }
131
+ function id(value, field) {
132
+ if (typeof value !== "string" || value.length === 0 || value.length > 128) {
133
+ return invalid(field, "expected a nonempty string of at most 128 characters");
134
+ }
135
+ return value;
136
+ }
137
+ function integer(value, minimum, field) {
138
+ if (typeof value !== "number" || !Number.isSafeInteger(value) || value < minimum) {
139
+ return invalid(field, `expected a safe integer greater than or equal to ${minimum}`);
140
+ }
141
+ return value;
142
+ }
143
+ function tag(value) {
144
+ if (typeof value !== "string" || !SANDBOX_TAG_RE.test(value))
145
+ return invalid("tag", "expected 1–64 lowercase letters, digits or hyphens");
146
+ return value;
147
+ }
148
+ function strings(value, maximum, check, field) {
149
+ if (!Array.isArray(value) || value.length > maximum)
150
+ return invalid(field, `expected an array of at most ${maximum} entries`);
151
+ if (Reflect.ownKeys(value).length !== value.length + 1)
152
+ return invalid(field, "sparse arrays and extra fields are not allowed");
153
+ const result = [];
154
+ for (let i = 0; i < value.length; i++) {
155
+ const descriptor = Object.getOwnPropertyDescriptor(value, i);
156
+ if (!descriptor || !("value" in descriptor))
157
+ return invalid(field, "expected array data entries");
158
+ const item = descriptor.value;
159
+ if (typeof item !== "string")
160
+ return invalid(field, "expected string entries");
161
+ const errors = check(item);
162
+ if (errors.length > 0)
163
+ return invalid(field, errors.join("; "));
164
+ result.push(item);
165
+ }
166
+ return Object.freeze(result);
167
+ }
168
+ function roots(value, field) {
169
+ return strings(value, 64, validateSandboxPathShape, field);
170
+ }
171
+ function projectRoot(value) {
172
+ if (value === null)
173
+ return null;
174
+ if (typeof value !== "string")
175
+ return invalid("filesystem.projectRoot", "expected an absolute path or null");
176
+ const errors = validateSandboxPathShape(value);
177
+ if (errors.length > 0)
178
+ return invalid("filesystem.projectRoot", errors.join("; "));
179
+ return value;
180
+ }
181
+ function fileScope(value) {
182
+ const v = record(value, ["kind", "projectRoot", "writeRoots"], "filesystem");
183
+ if (v.kind === "device") {
184
+ record(value, ["kind"], "filesystem");
185
+ return Object.freeze({ kind: "device" });
186
+ }
187
+ if (v.kind !== "scoped")
188
+ return invalid("filesystem.kind", "expected scoped or device");
189
+ return Object.freeze({
190
+ kind: "scoped",
191
+ projectRoot: projectRoot(v.projectRoot),
192
+ writeRoots: roots(v.writeRoots, "filesystem.writeRoots"),
193
+ });
194
+ }
195
+ function networkScope(value) {
196
+ const v = record(value, ["kind", "hosts"], "network");
197
+ if (v.kind === "none" || v.kind === "open-public" || v.kind === "environment") {
198
+ record(value, ["kind"], "network");
199
+ return Object.freeze({ kind: v.kind });
200
+ }
201
+ if (v.kind !== "allowlist")
202
+ return invalid("network.kind", "expected none, allowlist, open-public or environment");
203
+ return Object.freeze({
204
+ kind: "allowlist",
205
+ hosts: strings(v.hosts, 100, validateAllowHost, "network.hosts"),
206
+ });
207
+ }
208
+ function actor(value) {
209
+ const v = record(value, ["accountId", "conversationId", "runId"], "actor");
210
+ return Object.freeze({
211
+ accountId: id(v.accountId, "actor.accountId"),
212
+ conversationId: id(v.conversationId, "actor.conversationId"),
213
+ ...(Object.hasOwn(v, "runId") ? { runId: id(v.runId, "actor.runId") } : {}),
214
+ });
215
+ }
216
+ function operationRef(v) {
217
+ return {
218
+ operationId: id(v.operationId, "operationId"),
219
+ admitBeforeMs: integer(v.admitBeforeMs, 1, "admitBeforeMs"),
220
+ };
221
+ }
222
+ /** Pure structural validation and a frozen copy; no clock lookup or authority resolution. */
223
+ export function parseSandboxOperationRef(value) {
224
+ return Object.freeze(operationRef(record(value, ["operationId", "admitBeforeMs"], "operation reference")));
225
+ }
226
+ /**
227
+ * Validates a scope and returns a deeply frozen copy, throwing SandboxScopeValidationError.
228
+ * IDs and ceiling revisions are bounded to 128 characters; roots to 64 paths of at most 4096 characters;
229
+ * hosts to 100 entries passing validateAllowHost. Empty grants stay empty, including deny-all.
230
+ * Performs no I/O, authority lookup or deadline refresh. Unknown fields are rejected at every level.
231
+ * The `environment` network and the `device` filesystem are accepted only together.
232
+ */
233
+ export function parseSandboxOperationScope(value) {
234
+ const v = record(value, [
235
+ "operationId",
236
+ "admitBeforeMs",
237
+ "deviceId",
238
+ "rootConversationId",
239
+ "profileRevision",
240
+ "ceilingRevision",
241
+ "profile",
242
+ "actor",
243
+ "tag",
244
+ "filesystem",
245
+ "network",
246
+ ], "operation scope");
247
+ if (!isPermissionProfile(v.profile))
248
+ return invalid("profile", "expected request-approval, approve-for-me or full-access");
249
+ const filesystem = fileScope(v.filesystem);
250
+ const network = networkScope(v.network);
251
+ // The device filesystem and the environment network are the two halves of the escalated call:
252
+ // neither ever pairs with a sandboxed counterpart.
253
+ if (network.kind === "environment" && filesystem.kind !== "device")
254
+ return invalid("network.kind: environment requires the device filesystem", "a scoped filesystem takes none, allowlist or open-public");
255
+ if (filesystem.kind === "device" && network.kind !== "environment")
256
+ return invalid("filesystem.kind: device requires the environment network", "the device filesystem is only the escalated call's");
257
+ return Object.freeze({
258
+ ...operationRef(v),
259
+ deviceId: id(v.deviceId, "deviceId"),
260
+ rootConversationId: id(v.rootConversationId, "rootConversationId"),
261
+ profileRevision: integer(v.profileRevision, 0, "profileRevision"),
262
+ ceilingRevision: id(v.ceilingRevision, "ceilingRevision"),
263
+ profile: v.profile,
264
+ actor: actor(v.actor),
265
+ tag: tag(v.tag),
266
+ filesystem,
267
+ network,
268
+ });
269
+ }
270
+ /** Validates an owner browsing grant and returns a deeply frozen copy; no conversation is required. */
271
+ export function parseSandboxBrowseScope(value) {
272
+ const v = record(value, [
273
+ "operationId",
274
+ "admitBeforeMs",
275
+ "deviceId",
276
+ "accountId",
277
+ "ceilingRevision",
278
+ "readRoots",
279
+ "tag",
280
+ ], "browse scope");
281
+ return Object.freeze({
282
+ ...operationRef(v),
283
+ deviceId: id(v.deviceId, "deviceId"),
284
+ accountId: id(v.accountId, "accountId"),
285
+ ceilingRevision: id(v.ceilingRevision, "ceilingRevision"),
286
+ readRoots: roots(v.readRoots, "readRoots"),
287
+ tag: tag(v.tag),
288
+ });
289
+ }
290
+ /** Validates trusted staging structure and returns a deeply frozen copy; does not authorize its roots. */
291
+ export function parseSandboxPreparationScope(value) {
292
+ const v = record(value, ["operationId", "deviceId", "purpose", "writeRoots", "tag"], "preparation scope");
293
+ if (v.purpose !== "skills" && v.purpose !== "attachments")
294
+ return invalid("purpose", "expected skills or attachments");
295
+ return Object.freeze({
296
+ operationId: id(v.operationId, "operationId"),
297
+ deviceId: id(v.deviceId, "deviceId"),
298
+ purpose: v.purpose,
299
+ writeRoots: roots(v.writeRoots, "writeRoots"),
300
+ tag: tag(v.tag),
301
+ });
302
+ }
303
+ /** Validates all four bounded locator fields and returns a frozen copy; does not authenticate the caller. */
304
+ export function parseSandboxExecutionRef(value) {
305
+ const v = record(value, ["executionId", "operationId", "instanceId", "instanceGeneration"], "execution reference");
306
+ return Object.freeze({
307
+ executionId: id(v.executionId, "executionId"),
308
+ operationId: id(v.operationId, "operationId"),
309
+ instanceId: id(v.instanceId, "instanceId"),
310
+ instanceGeneration: id(v.instanceGeneration, "instanceGeneration"),
311
+ });
312
+ }
@@ -1,54 +1,71 @@
1
1
  /**
2
- * Device protocol v1: the WebSocket frames between the kernel and a `capybara-device` program
2
+ * The device protocol: the WebSocket frames between the kernel and a `capybara-device` program
3
3
  * (a connected machine that serves as a device). Pure types and hand-written guards.
4
+ *
5
+ * The bodies of the dial-in envelope are parsed by `parseDeviceFrame` (second half of this file);
6
+ * the per-operation argument and result guards of the first half are its value guards.
4
7
  */
5
- import { type ExecResult, type SandboxActor, type SandboxLimits, type SandboxRoots } from "./sandbox.js";
6
- /** The protocol version carried in `X-Capybara-Device-Protocol` and the hello frame. */
7
- export declare const DEVICE_PROTOCOL_VERSION = 1;
8
+ import { type SandboxPermissionSupport } from "./device-operation.js";
9
+ import { type ExecResult, type SandboxActor, type SandboxLimits, type SandboxRoots } from "./device-provider.js";
10
+ /** The major version of {@link DEVICE_DIAL_IN_PROTOCOL}. */
11
+ export declare const DEVICE_PROTOCOL_VERSION = 6;
12
+ /**
13
+ * The dial-in protocol `capybara-device` speaks (`<name>/<major>`, see `DIAL_IN_PROTOCOL_RE`): the
14
+ * value of the `X-Capybara-Device-Protocol` header, of the hello envelope's `protocol` and of the
15
+ * sign-in's `protocol`. The provider serving its devices declares it as `permissions.dialIn`.
16
+ * The kernel checks only the envelope (`DialInMachineFrame`); the bodies the envelope carries are
17
+ * this module's ({@link parseDeviceFrame}).
18
+ */
19
+ export declare const DEVICE_DIAL_IN_PROTOCOL: "capybara-device/6";
8
20
  /** The operations the kernel asks a device to run. */
9
- export type DeviceOp = "create" | "exec" | "readFile" | "writeFile" | "stat" | "killTagged" | "killAll" | "stop";
10
- /** First frame from the device after the WebSocket opens. */
11
- export interface DeviceHello {
12
- type: "hello";
13
- protocol: number;
14
- programVersion: string;
15
- os: "darwin" | "linux";
16
- arch: string;
17
- mode: "os" | "docker";
18
- roots: SandboxRoots;
19
- sessionIsolation: boolean;
21
+ export type DeviceOp = "create" | "exec" | "readFile" | "writeFile" | "stat" | "killTagged" | "killAll" | "stop" | "list" | "scan";
22
+ /**
23
+ * Optional capabilities a device announces in its hello: `networkReport` means exec results may
24
+ * carry `network`; `projects` means the device serves `list` and `scan` (the provider never sends
25
+ * `list` or `scan` to a device that did not announce `projects`); `loopbackPorts` means the device
26
+ * accepts `service.ensure` `network.loopbackPorts` (the provider never sends that key to a device
27
+ * that did not announce it).
28
+ */
29
+ export type DeviceFeature = "networkReport" | "projects" | "loopbackPorts";
30
+ /**
31
+ * What a device knows of its local policy and reports (in the hello or a `policy` event). The owner
32
+ * ceiling travels separately, in the owner report ({@link DeviceOwnerCeiling}).
33
+ */
34
+ export interface DeviceLocalPolicySummary {
35
+ /** The device's sandbox allowlist (the owner's `allowedDomains`). */
36
+ allowedDomains: string[];
37
+ /**
38
+ * This connection's project directories that another connection on the same machine also uses,
39
+ * only those the owner listed explicitly for this connection (its `projectPaths`): a directory
40
+ * the deployment picked itself is never reported, shared or not (absolute paths,
41
+ * {@link validateSandboxPathShape}; at most {@link MAX_DEVICE_SHARED_PROJECT_ROOTS}). Never names
42
+ * the other connection. Absent from an older device; a malformed value is dropped by the parser
43
+ * (the rest of the summary is kept).
44
+ */
45
+ sharedProjectRoots?: string[];
20
46
  }
47
+ /** The most project directories a policy summary's `sharedProjectRoots` lists. */
48
+ export declare const MAX_DEVICE_SHARED_PROJECT_ROOTS = 256;
49
+ /**
50
+ * A directory a `scan` found that looks like a project (it holds `.git` or `AGENTS.md`): a
51
+ * suggestion, not a project. `path` is absolute ({@link validateSandboxPathShape});
52
+ * `suggestedName` is a guess from its basename ({@link isDeviceProjectName}) the owner may change.
53
+ */
54
+ export interface DeviceProjectCandidate {
55
+ path: string;
56
+ suggestedName: string;
57
+ }
58
+ /** The most blocked hosts an exec result reports; the parser cuts longer lists. */
59
+ export declare const MAX_NETWORK_BLOCKED_HOSTS = 20;
60
+ /**
61
+ * The identity of a host's OS boot or of a program run: 1 to 128 characters of letters, digits,
62
+ * `.`, `_`, `:` and `-`.
63
+ */
64
+ export declare const DEVICE_BOOT_ID_RE: RegExp;
65
+ /** Whether `v` is a well-formed boot or program-run identity ({@link DEVICE_BOOT_ID_RE}). */
66
+ export declare function isDeviceBootId(v: unknown): v is string;
21
67
  /** Error kinds a device reports for a failed request. */
22
68
  export type DeviceErrorKind = "gone" | "fs_gone" | "policy" | "error";
23
- /** The device's answer to a {@link KernelReq}. */
24
- export type DeviceRes = {
25
- type: "res";
26
- id: string;
27
- ok: true;
28
- result: unknown;
29
- } | {
30
- type: "res";
31
- id: string;
32
- ok: false;
33
- error: {
34
- kind: DeviceErrorKind;
35
- message: string;
36
- };
37
- };
38
- /** A request from the kernel. */
39
- export interface KernelReq {
40
- type: "req";
41
- id: string;
42
- op: DeviceOp;
43
- args: unknown;
44
- deadlineMs: number;
45
- }
46
- /** The kernel gives up on a request (abort or deadline). */
47
- export interface KernelCancel {
48
- type: "cancel";
49
- id: string;
50
- }
51
- export type DeviceFrame = DeviceHello | DeviceRes | KernelReq | KernelCancel;
52
69
  export interface DeviceExecArgs {
53
70
  command: string;
54
71
  cwd?: string;
@@ -58,6 +75,22 @@ export interface DeviceExecArgs {
58
75
  tag: string;
59
76
  actor: SandboxActor;
60
77
  limits: SandboxLimits;
78
+ /**
79
+ * Hosts the kernel allows for this command beyond the local policy (a run's "Allow this time" or
80
+ * a
81
+ * scheduled task's grants). A device applies them only in sandbox mode, within `limits`; a
82
+ * device without the feature ignores the field.
83
+ */
84
+ grants?: DeviceExecGrants;
85
+ }
86
+ /** Extra hosts for one exec and where they come from (logged by the device with the command). */
87
+ export interface DeviceExecGrants {
88
+ hosts: string[];
89
+ source: {
90
+ kind: "run" | "task";
91
+ id: string;
92
+ accountId: string;
93
+ };
61
94
  }
62
95
  export type DeviceExecResult = ExecResult;
63
96
  export interface DeviceReadFileArgs {
@@ -93,7 +126,50 @@ export interface DeviceCreateResult {
93
126
  export interface DeviceStopArgs {
94
127
  reason: "revoked" | "deleted";
95
128
  }
96
- /** A frame that is not valid protocol v1 (or came from the wrong side). */
129
+ /**
130
+ * Lists one directory (absolute `path`, {@link validateSandboxPathShape}): at most `limit` entries
131
+ * (at most {@link MAX_DEVICE_LIST_ENTRIES}), read within the operation's scope. See
132
+ * `DeviceProvider.list` for the semantics.
133
+ */
134
+ export interface DeviceListArgs {
135
+ path: string;
136
+ limit: number;
137
+ }
138
+ /**
139
+ * One entry of a listed directory: `name` is never empty, `.` or `..` and holds no `/`. `isDir`
140
+ * follows symbolic links (stat semantics): a link to a directory is `true`, a dangling link `false`,
141
+ * and so is a link whose target the request's mode cannot reach.
142
+ */
143
+ export interface DeviceListEntry {
144
+ name: string;
145
+ isDir: boolean;
146
+ }
147
+ /**
148
+ * The directory's entries sorted by code unit, `truncated` when more than `limit` exist; null only
149
+ * when the path does not exist and the request's mode could reach it (like `stat` / `readFile`).
150
+ * A file, an unreadable directory, or a path the request's mode cannot reach is an error (the
151
+ * latter a `policy` refusal), never null.
152
+ */
153
+ export type DeviceListResult = {
154
+ entries: DeviceListEntry[];
155
+ truncated: boolean;
156
+ } | null;
157
+ /**
158
+ * Looks for project-like directories under `base` (absolute, {@link validateSandboxPathShape}),
159
+ * read within the operation's scope. A `base` that does not exist answers `[]`; a `base` that is a
160
+ * file, unreadable, or outside the request's scope is an error. See `DeviceProvider.scan` for the
161
+ * traversal.
162
+ */
163
+ export interface DeviceScanArgs {
164
+ base: string;
165
+ }
166
+ /**
167
+ * `base` itself and the directories at most {@link MAX_DEVICE_SCAN_DEPTH} levels below it that
168
+ * hold a `.git` entry or an `AGENTS.md` file, sorted by `path` in code-unit order and cut to the
169
+ * first {@link MAX_DEVICE_SCAN_RESULTS}. Never file contents. See `DeviceProvider.scan`.
170
+ */
171
+ export type DeviceScanResult = DeviceProjectCandidate[];
172
+ /** A frame that is not valid device protocol (or came from the wrong side). */
97
173
  export declare class DeviceProtocolError extends Error {
98
174
  constructor(message: string);
99
175
  }
@@ -107,12 +183,173 @@ export interface DeviceOpResults {
107
183
  killTagged: null;
108
184
  killAll: null;
109
185
  stop: null;
186
+ list: DeviceListResult;
187
+ scan: DeviceScanResult;
110
188
  }
111
189
  /** Validates the `result` of a successful `res` for `op`; throws {@link DeviceProtocolError}. */
112
190
  export declare function parseOpResult<Op extends DeviceOp>(op: Op, result: unknown): DeviceOpResults[Op];
113
191
  /**
114
- * Parses one WebSocket text frame. `from` is the sender: a device may send `hello` and `res`, the
115
- * kernel `req` and `cancel`. Throws {@link DeviceProtocolError} on bad JSON, an unknown `type`,
116
- * missing fields or a frame of the wrong direction.
192
+ * The operations the kernel asks a protocol 6 device to run: every user operation carries its
193
+ * admitted scope; there is no broad kill (`killTagged` / `killAll`) and no deployment-side change
194
+ * of the machine's policy: the owner changes it on the machine and the device reports the change
195
+ * ({@link DevicePolicyChanged}).
196
+ */
197
+ export type DeviceOperation = Exclude<DeviceOp, "killTagged" | "killAll"> | "prepareReadFile" | "prepareWriteFile" | "prepareStat" | "browseStat" | "browseList" | "browseScan" | "backgroundStart" | "backgroundStatus" | "backgroundTail" | "backgroundReadOutput" | "backgroundStop" | "revokeOperation" | "bindInstance";
198
+ /**
199
+ * How far a connection's project paths reach: `machine` (any path the deny list leaves), `paths`
200
+ * (the listed project paths) or `workspace` (the connection's working directory only).
201
+ */
202
+ export type DeviceProjectReach = "machine" | "paths" | "workspace";
203
+ /** Why a device refused a project path: the `refusal` of a `project_refused` outcome. */
204
+ export type DeviceProjectRefusal = "other-connection" | "outside-reach" | "denied";
205
+ /** The sandbox network of a device: the open public internet or an allowlist. */
206
+ export type DeviceNetworkMode = "open" | "allowlist";
207
+ /**
208
+ * The owner ceiling of protocol 6 (approval-only profiles design, "Settings model"): the device
209
+ * sandbox for every profile. `outsideSandbox` is whether a call may be granted escalation outside
210
+ * the sandbox; `network` and `allowedDomains` are the sandbox network.
211
+ */
212
+ export interface DeviceOwnerCeiling {
213
+ readonly version: 3;
214
+ readonly sequence: number;
215
+ readonly revision: string;
216
+ readonly outsideSandbox: boolean;
217
+ readonly network: DeviceNetworkMode;
218
+ readonly allowedDomains: readonly string[];
219
+ readonly projectReach: DeviceProjectReach;
220
+ }
221
+ /**
222
+ * An event body (the envelope's `event`): the owner changed the machine's policy or owner ceiling
223
+ * while connected. `policy` is absent when the summary was unreadable.
224
+ */
225
+ export interface DevicePolicyChanged {
226
+ type: "policy";
227
+ policy?: DeviceLocalPolicySummary;
228
+ ownerCeiling: DeviceOwnerCeiling;
229
+ }
230
+ /**
231
+ * The hello body (the envelope's `hello` carries the program facts: protocol, program version,
232
+ * os, arch, boot and run identities, frame capacity). `policy` and `ownerCeiling` are the
233
+ * machine's own narrowing, read by the provider serving the device.
234
+ */
235
+ export interface DeviceHello {
236
+ mode: "os" | "docker";
237
+ roots: SandboxRoots;
238
+ sessionIsolation: boolean;
239
+ /** Optional capabilities (unknown entries are dropped by the parser). */
240
+ features?: DeviceFeature[];
241
+ /** The device's local policy summary (dropped by the parser when unreadable). */
242
+ policy?: DeviceLocalPolicySummary;
243
+ /**
244
+ * The owner's home directory, an absolute path (a local device; the base of an auto-mode
245
+ * project's relative path). A malformed value is dropped by the parser.
246
+ */
247
+ home?: string;
248
+ permissionSupport: SandboxPermissionSupport;
249
+ ownerCeiling: DeviceOwnerCeiling;
250
+ instanceGeneration: string | null;
251
+ /** Absent until the program can attest actual installed runtime/helper/environment bytes. */
252
+ runtimeIdentity?: DeviceRuntimeIdentity;
253
+ }
254
+ /** A verified installed runtime/helper/environment identity bound to one instance generation. */
255
+ export interface DeviceRuntimeIdentity {
256
+ runtimeHash: string;
257
+ helperHash: string;
258
+ imageFingerprint: string;
259
+ instanceGeneration: string;
260
+ }
261
+ /**
262
+ * Private lifecycle request (permission runtime cutover B4): binds the kernel's committed instance
263
+ * generation to the device after commit. It carries no path, policy or manifest.
264
+ */
265
+ export interface BindInstanceRequest {
266
+ instanceId: string;
267
+ instanceGeneration: string;
268
+ bindingId: string;
269
+ expectedPreviousGeneration: string | null;
270
+ }
271
+ export interface BindInstanceResult {
272
+ instanceId: string;
273
+ instanceGeneration: string;
274
+ bindingId: string;
275
+ runtimeIdentity: DeviceRuntimeIdentity;
276
+ permissionSupport: SandboxPermissionSupport;
277
+ ownerCeiling: DeviceOwnerCeiling;
278
+ }
279
+ export interface BackgroundReadOutputRequest {
280
+ offset: number;
281
+ maxBytes: number;
282
+ }
283
+ export type BackgroundReadOutputResult = {
284
+ dataB64: string;
285
+ offset: number;
286
+ nextOffset: number;
287
+ totalBytes: number;
288
+ } | {
289
+ unavailable: "lost" | "expired";
290
+ };
291
+ /** A request body (the envelope's `req`): one operation and its arguments. */
292
+ export interface DeviceRequestBody {
293
+ op: DeviceOperation;
294
+ args: Readonly<Record<string, unknown>>;
295
+ }
296
+ /** A request as the device serves it: its body with the envelope's `id` and `deadlineMs`. */
297
+ export interface KernelRequest extends DeviceRequestBody {
298
+ type: "req";
299
+ id: string;
300
+ deadlineMs: number;
301
+ }
302
+ /** A response body (the envelope's `res`): the result, or the typed failure. */
303
+ export type DeviceResponseBody = {
304
+ ok: true;
305
+ result: unknown;
306
+ } | {
307
+ ok: false;
308
+ error: {
309
+ /**
310
+ * The typed failure: `denied`, `unsupported`, `unknown` and `invalid` carry the SDK's
311
+ * scope denial, unsupported permission, unknown outcome and scope validation errors.
312
+ * `invalid` never proves the operation had no effect (a skewed device may have parsed
313
+ * part of it): it must never join the not-run refusals (`isRefusal`, `failureKindOf`).
314
+ */
315
+ kind: "gone" | "fs_gone" | "policy" | "error" | "denied" | "unsupported" | "unsettled" | "unknown" | "invalid" | "project_refused";
316
+ message: string;
317
+ /** Present on `project_refused` only: why the project path was refused. */
318
+ refusal?: DeviceProjectRefusal;
319
+ };
320
+ };
321
+ /** A response as the device produces it: its body with the envelope's `id`. */
322
+ export type DeviceResponse = {
323
+ type: "res";
324
+ id: string;
325
+ } & DeviceResponseBody;
326
+ /** The bodies of protocol 6, by the envelope frame that carries them. */
327
+ export interface DeviceBodies {
328
+ hello: DeviceHello;
329
+ req: DeviceRequestBody;
330
+ res: DeviceResponseBody;
331
+ event: DevicePolicyChanged;
332
+ }
333
+ /**
334
+ * Strictly parses a runtime permission report, version 2 (the protocol 4 `permissionSupport`, also
335
+ * the shape a cloud provider reports), and returns a frozen copy; throws {@link DeviceProtocolError}.
336
+ * Restricted support is all four claims or `null`; per-operation hosts need the allowlist; an
337
+ * operation boundary without restricted support claims no sandbox network at all. An
338
+ * instance boundary is the whole instance: it claims no restricted per-operation scope, no
339
+ * outside-sandbox escalation and no per-operation hosts (a host joins the device's list instead).
340
+ */
341
+ export declare function parseSandboxPermissionSupport(value: unknown): SandboxPermissionSupport;
342
+ /**
343
+ * Strictly parses one authenticated owner-ceiling report of protocol 6 and returns a frozen copy;
344
+ * throws {@link DeviceProtocolError}. Unknown fields (the protocol 3 `fullAccess` and
345
+ * `restrictedAllowedDomains` among them) are refused.
346
+ */
347
+ export declare function parseOwnerCeilingReport(value: unknown): DeviceOwnerCeiling;
348
+ /**
349
+ * Strictly parses one protocol 6 body, as carried by the dial-in envelope frame of type `kind`
350
+ * (`hello`, `event` and `res` from the device, `req` from the kernel), and returns a frozen copy;
351
+ * throws {@link DeviceProtocolError}. The envelope (its ids, deadline and size bound) is checked
352
+ * before: `parseDialInMachineFrame` on the kernel, `parseDialInKernelFrame` on the machine.
117
353
  */
118
- export declare function parseDeviceFrame(raw: string, from: "device" | "kernel"): DeviceFrame;
354
+ export declare function parseDeviceFrame<K extends keyof DeviceBodies>(body: unknown, kind: K): DeviceBodies[K];
355
+ export declare function parseOperationResult(op: DeviceOperation, result: unknown, request?: BackgroundReadOutputRequest | BindInstanceRequest): unknown;