@capybara-hq/plugin-sdk 0.1.0-rc.30 → 0.1.0-rc.32

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.
package/dist/ctx.d.ts CHANGED
@@ -2,7 +2,7 @@ import type { Kysely } from "kysely";
2
2
  import type { ExtensionPointRef } from "./extension-point.js";
3
3
  import type { AvailableHook, HookHandler, HookOptions } from "./hooks.js";
4
4
  import type { RouteCaller } from "./http-access.js";
5
- import type { ModelEmbeddingInfo, ModelKind } from "./model.js";
5
+ import type { ImageAspectRatio, ImageMediaType, ImageSize, ModelEmbeddingInfo, ModelImageGenerationInfo, ModelKind } from "./model.js";
6
6
  import type { ExtensionNet } from "./net.js";
7
7
  import type { SetupCheckDefinition } from "./setup-check.js";
8
8
  import type { ObjectHead, PresignedUpload, PresignGetOptions } from "./storage.js";
@@ -94,6 +94,39 @@ export interface ExtensionEmbedResult {
94
94
  };
95
95
  dimensions: number;
96
96
  }
97
+ /** A `ctx.models.generateImage` request: images generated for one org with the model of a purpose. */
98
+ export interface ExtensionImageGenerateRequest {
99
+ orgId: string;
100
+ /** A purpose this extension declared in `permissions.models` with `kind: "image_generation"`. */
101
+ purpose: string;
102
+ prompt: string;
103
+ /** An exact size the model offers; rejected otherwise. Wins over `aspectRatio`. */
104
+ size?: ImageSize;
105
+ /** The closest size the model offers; the model's default size when neither is given. */
106
+ aspectRatio?: ImageAspectRatio;
107
+ /** Images to produce (default 1, at most the model's `maxImages`). */
108
+ n?: number;
109
+ /** Base64 reference images, at most the model's `maxReferenceImages`. */
110
+ referenceImages?: {
111
+ mediaType: ImageMediaType;
112
+ data: string;
113
+ }[];
114
+ /** Aborts this call; combined with `ctx.signal`. */
115
+ signal?: AbortSignal;
116
+ }
117
+ /** A `ctx.models.generateImage` result. */
118
+ export interface ExtensionImageGenerateResult {
119
+ images: {
120
+ mediaType: ImageMediaType;
121
+ data: string;
122
+ }[];
123
+ revisedPrompt?: string;
124
+ model: {
125
+ provider: string;
126
+ id: string;
127
+ };
128
+ size: ImageSize;
129
+ }
97
130
  /** The model a purpose maps to in an org (`ctx.models.describe`). */
98
131
  export interface ExtensionModelTarget {
99
132
  provider: string;
@@ -101,13 +134,16 @@ export interface ExtensionModelTarget {
101
134
  kind: ModelKind;
102
135
  /** Present for an embedding model. */
103
136
  embedding?: ModelEmbeddingInfo;
137
+ /** Present for an image generation model. */
138
+ imageGeneration?: ModelImageGenerationInfo;
104
139
  }
105
140
  /**
106
141
  * Models by purpose (`permissions.models`): the purpose → model mapping is chosen by org admins
107
142
  * (and the deployment default by the super admin), never by the extension. Only purposes this
108
- * extension declared with `kind: "embedding"` are accepted (`model.purpose_unknown` otherwise), and
143
+ * extension declared with a matching `kind` (`embedding` for `embed`, `image_generation` for
144
+ * `generateImage`) are accepted (`model.purpose_unknown` otherwise), and
109
145
  * only for an org that enabled the extension (`extension.not_enabled`). Usage is recorded by the
110
- * kernel and reported through `usage.report` (purpose `embedding`).
146
+ * kernel and reported through `usage.report` (purpose `embedding`, or `image` for `generateImage`).
111
147
  */
112
148
  export interface ExtensionModels {
113
149
  /**
@@ -120,6 +156,14 @@ export interface ExtensionModels {
120
156
  * extension route), and nothing is sent or billed.
121
157
  */
122
158
  embed(req: ExtensionEmbedRequest): Promise<ExtensionEmbedResult>;
159
+ /**
160
+ * Generates images with the org's effective model for `purpose`. Rejects with
161
+ * `model.unconfigured` when the purpose maps to no usable model, `validation_failed` for a size,
162
+ * count or reference count the model does not offer, and a `ModelError` when the provider fails
163
+ * (kind `refusal` when it declines the prompt). Not retried. Fires `model.request` first
164
+ * (`purpose: "image"`); a policy denial rejects with `model.hook_denied`.
165
+ */
166
+ generateImage(req: ExtensionImageGenerateRequest): Promise<ExtensionImageGenerateResult>;
123
167
  /** The org's effective model for `purpose`, or null when it maps to no model the org can use. */
124
168
  describe(req: {
125
169
  orgId: string;
@@ -0,0 +1,117 @@
1
+ /** Development staging only. Task 8 replaces v2 and removes this module and its staged names together. */
2
+ import { type DeviceHello, type DeviceLocalPolicySummary, type DeviceOp, type DevicePolicyArgs, type DevicePolicyStatus, type DeviceRes, type KernelCancel } from "./device-protocol.js";
3
+ import { type SandboxPermissionSupport } from "./sandbox-operation.js";
4
+ export declare const STAGED_DEVICE_PROTOCOL_VERSION = 3;
5
+ export type DeviceOperationV3 = Exclude<DeviceOp, "killTagged" | "killAll"> | "prepareReadFile" | "prepareWriteFile" | "prepareStat" | "browseStat" | "browseList" | "browseScan" | "backgroundStart" | "backgroundStatus" | "backgroundTail" | "backgroundReadOutput" | "backgroundStop" | "revokeOperation" | "bindInstance";
6
+ export interface DeviceOwnerCeilingV3 {
7
+ readonly version: 2;
8
+ readonly sequence: number;
9
+ readonly restrictedProjectReach: "workspace" | "os-user";
10
+ readonly revision: string;
11
+ readonly fullAccess: boolean;
12
+ readonly restrictedAllowedDomains: readonly string[];
13
+ }
14
+ /**
15
+ * The only owner-ceiling change the kernel may ask of a machine (B2): narrowing. Widening is decided
16
+ * on the machine by its owner (`capybara-device ceiling set`), never over the wire.
17
+ */
18
+ export interface DeviceOwnerCeilingNarrowingV3 {
19
+ readonly fullAccess?: false;
20
+ readonly restrictedProjectReach?: "workspace";
21
+ }
22
+ /** A staged `policy` op: the protocol 2 change plus an optional owner-ceiling narrowing. */
23
+ export interface DevicePolicyArgsV3 extends DevicePolicyArgs {
24
+ ownerCeiling?: DeviceOwnerCeilingNarrowingV3;
25
+ }
26
+ /** A staged `policy` answer: the policy as written and the owner report issued for it. */
27
+ export interface DevicePolicyResultV3 {
28
+ policy: DeviceLocalPolicySummary;
29
+ ownerCeiling: DeviceOwnerCeilingV3;
30
+ }
31
+ /** A staged `policyStatus` answer: an `applied` outcome carries the current owner report. */
32
+ export interface DevicePolicyStatusV3 extends DevicePolicyStatus {
33
+ ownerCeiling?: DeviceOwnerCeilingV3;
34
+ }
35
+ /** The device pushed a policy change: the owner report for the newly observed revision. */
36
+ export interface DevicePolicyChangedV3 {
37
+ type: "policy";
38
+ policy?: DeviceLocalPolicySummary;
39
+ ownerCeiling: DeviceOwnerCeilingV3;
40
+ }
41
+ export interface DeviceHelloV3 extends DeviceHello {
42
+ protocol: 3;
43
+ permissionSupport: SandboxPermissionSupport;
44
+ ownerCeiling: DeviceOwnerCeilingV3;
45
+ instanceGeneration: string | null;
46
+ transport: {
47
+ maxFrameBytes: number;
48
+ };
49
+ /** Absent until the program can attest actual installed runtime/helper/environment bytes. */
50
+ runtimeIdentity?: DeviceRuntimeIdentityV3;
51
+ }
52
+ /** A verified installed runtime/helper/environment identity bound to one instance generation. */
53
+ export interface DeviceRuntimeIdentityV3 {
54
+ runtimeHash: string;
55
+ helperHash: string;
56
+ imageFingerprint: string;
57
+ instanceGeneration: string;
58
+ }
59
+ /**
60
+ * Private lifecycle request (permission runtime cutover B4): binds the kernel's committed instance
61
+ * generation to the device after commit. It carries no path, policy or manifest.
62
+ */
63
+ export interface BindInstanceRequestV3 {
64
+ instanceId: string;
65
+ instanceGeneration: string;
66
+ bindingId: string;
67
+ expectedPreviousGeneration: string | null;
68
+ }
69
+ export interface BindInstanceResultV3 {
70
+ instanceId: string;
71
+ instanceGeneration: string;
72
+ bindingId: string;
73
+ runtimeIdentity: DeviceRuntimeIdentityV3;
74
+ permissionSupport: SandboxPermissionSupport;
75
+ ownerCeiling: DeviceOwnerCeilingV3;
76
+ }
77
+ export interface KernelReadyV3 {
78
+ type: "ready";
79
+ connectionId: string;
80
+ maxFrameBytes: number;
81
+ }
82
+ export interface BackgroundReadOutputRequestV3 {
83
+ offset: number;
84
+ maxBytes: number;
85
+ }
86
+ export type BackgroundReadOutputResultV3 = {
87
+ dataB64: string;
88
+ offset: number;
89
+ nextOffset: number;
90
+ totalBytes: number;
91
+ } | {
92
+ unavailable: "lost" | "expired";
93
+ };
94
+ export interface KernelRequestV3 {
95
+ type: "req";
96
+ id: string;
97
+ op: DeviceOperationV3;
98
+ args: Readonly<Record<string, unknown>>;
99
+ deadlineMs: number;
100
+ }
101
+ export type DeviceResponseV3 = Exclude<DeviceRes, {
102
+ ok: false;
103
+ }> | {
104
+ type: "res";
105
+ id: string;
106
+ ok: false;
107
+ error: {
108
+ kind: "gone" | "fs_gone" | "policy" | "error" | "denied" | "unsupported" | "unknown";
109
+ message: string;
110
+ };
111
+ };
112
+ export type DeviceFrameV3 = DeviceHelloV3 | KernelReadyV3 | KernelRequestV3 | KernelCancel | DeviceResponseV3 | DevicePolicyChangedV3;
113
+ /** Strictly parses one authenticated owner-ceiling report (B2); throws {@link DeviceProtocolError}. */
114
+ export declare function parseOwnerCeilingReportV3(value: unknown): DeviceOwnerCeilingV3;
115
+ /** Strict scope-bearing frames; active parseDeviceFrame still speaks v2. */
116
+ export declare function parseDeviceFrameV3(raw: string, from: "device" | "kernel", maxFrameBytes?: number): DeviceFrameV3;
117
+ export declare function parseOperationResultV3(op: DeviceOperationV3, result: unknown, request?: BackgroundReadOutputRequestV3 | BindInstanceRequestV3): unknown;
@@ -0,0 +1,409 @@
1
+ /** Development staging only. Task 8 replaces v2 and removes this module and its staged names together. */
2
+ import { DeviceProtocolError, parseDeviceFrame, parseOpResult, } from "./device-protocol.js";
3
+ import { validateAllowHost, validateSandboxPathShape } from "./sandbox.js";
4
+ import { parseSandboxBrowseScope, parseSandboxExecutionRef, parseSandboxOperationRef, parseSandboxOperationScope, parseSandboxPreparationScope, } from "./sandbox-operation.js";
5
+ export const STAGED_DEVICE_PROTOCOL_VERSION = 3;
6
+ const object = (value) => {
7
+ if (!value || typeof value !== "object" || Array.isArray(value))
8
+ throw new DeviceProtocolError("Expected an object");
9
+ return value;
10
+ };
11
+ function keys(value, allowed) {
12
+ for (const key of Object.keys(value))
13
+ if (!allowed.includes(key))
14
+ throw new DeviceProtocolError(`Unknown field ${key}`);
15
+ }
16
+ function string(value, max = 128) {
17
+ if (typeof value !== "string" || !value.length || value.length > max)
18
+ throw new DeviceProtocolError("Expected a bounded nonempty string");
19
+ return value;
20
+ }
21
+ function integer(value, min = 0, max = Number.MAX_SAFE_INTEGER) {
22
+ if (typeof value !== "number" || !Number.isSafeInteger(value) || value < min || value > max)
23
+ throw new DeviceProtocolError("Expected a bounded integer");
24
+ return value;
25
+ }
26
+ function path(value) {
27
+ if (typeof value !== "string" || validateSandboxPathShape(value).length)
28
+ throw new DeviceProtocolError("Expected an absolute filesystem path");
29
+ }
30
+ function freeze(value) {
31
+ if (value !== null && typeof value === "object") {
32
+ for (const v of Object.values(value))
33
+ freeze(v);
34
+ Object.freeze(value);
35
+ }
36
+ return value;
37
+ }
38
+ function support(value) {
39
+ const o = object(value);
40
+ keys(o, ["version", "restricted", "fullAccess", "background", "unavailableReason"]);
41
+ if (o.version !== 1 || typeof o.fullAccess !== "boolean" || typeof o.background !== "boolean")
42
+ throw new DeviceProtocolError("Invalid runtime permission report");
43
+ if (o.restricted !== null) {
44
+ const r = object(o.restricted);
45
+ keys(r, ["filesystem", "network", "native", "concurrentScopes"]);
46
+ for (const k of ["filesystem", "network", "native", "concurrentScopes"])
47
+ if (r[k] !== true)
48
+ throw new DeviceProtocolError("Incomplete restricted runtime report");
49
+ }
50
+ if (o.unavailableReason !== undefined)
51
+ string(o.unavailableReason, 4096);
52
+ return o;
53
+ }
54
+ /** Strictly parses one authenticated owner-ceiling report (B2); throws {@link DeviceProtocolError}. */
55
+ export function parseOwnerCeilingReportV3(value) {
56
+ return freeze(structuredClone(owner(value)));
57
+ }
58
+ function narrowing(value) {
59
+ const o = object(value);
60
+ keys(o, ["fullAccess", "restrictedProjectReach"]);
61
+ if ((o.fullAccess !== undefined && o.fullAccess !== false) ||
62
+ (o.restrictedProjectReach !== undefined && o.restrictedProjectReach !== "workspace"))
63
+ throw new DeviceProtocolError("The deployment may only narrow the owner ceiling");
64
+ return o;
65
+ }
66
+ function owner(value) {
67
+ const o = object(value);
68
+ keys(o, [
69
+ "version",
70
+ "sequence",
71
+ "revision",
72
+ "fullAccess",
73
+ "restrictedProjectReach",
74
+ "restrictedAllowedDomains",
75
+ ]);
76
+ integer(o.sequence);
77
+ if (o.version !== 2 || !["workspace", "os-user"].includes(String(o.restrictedProjectReach)))
78
+ throw new DeviceProtocolError("Invalid owner ceiling report version or project reach");
79
+ string(o.revision, 512);
80
+ if (typeof o.fullAccess !== "boolean" ||
81
+ !Array.isArray(o.restrictedAllowedDomains) ||
82
+ o.restrictedAllowedDomains.length > 100 ||
83
+ o.restrictedAllowedDomains.some((h) => typeof h !== "string" || validateAllowHost(h).length))
84
+ throw new DeviceProtocolError("Invalid owner ceiling");
85
+ return o;
86
+ }
87
+ const GENERATION = /^[0-9]{1,16}$/;
88
+ const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
89
+ function generation(value) {
90
+ if (typeof value !== "string" || !GENERATION.test(value))
91
+ throw new DeviceProtocolError("Expected an instance generation");
92
+ return value;
93
+ }
94
+ function bindRequest(a) {
95
+ string(a.instanceId);
96
+ generation(a.instanceGeneration);
97
+ if (typeof a.bindingId !== "string" || !UUID.test(a.bindingId))
98
+ throw new DeviceProtocolError("Expected a binding id");
99
+ if (a.expectedPreviousGeneration !== null) {
100
+ generation(a.expectedPreviousGeneration);
101
+ if (BigInt(a.expectedPreviousGeneration) >= BigInt(a.instanceGeneration))
102
+ throw new DeviceProtocolError("Previous generation must precede the bound generation");
103
+ }
104
+ return a;
105
+ }
106
+ function identity(value) {
107
+ const o = object(value);
108
+ keys(o, ["runtimeHash", "helperHash", "imageFingerprint", "instanceGeneration"]);
109
+ for (const key of ["runtimeHash", "helperHash", "imageFingerprint"])
110
+ if (typeof o[key] !== "string" || !/^[a-f0-9]{64}$/.test(o[key]))
111
+ throw new DeviceProtocolError("Incomplete runtime identity");
112
+ string(o.instanceGeneration);
113
+ return o;
114
+ }
115
+ const natives = ["exec", "readFile", "writeFile", "stat", "list", "scan"];
116
+ const legacy = ["create", "stop", "policy", "policyStatus"];
117
+ function request(o) {
118
+ keys(o, ["type", "id", "op", "args", "deadlineMs"]);
119
+ const id = string(o.id), op = string(o.op), a = object(o.args), deadlineMs = integer(o.deadlineMs, 1);
120
+ if (legacy.includes(op)) {
121
+ if (op === "policy" && a.ownerCeiling !== undefined)
122
+ narrowing(a.ownerCeiling);
123
+ const parsed = parseDeviceFrame(JSON.stringify(o), "kernel");
124
+ if (parsed.type !== "req")
125
+ throw new DeviceProtocolError("Expected request");
126
+ return freeze({ ...parsed, op: op, args: object(parsed.args) });
127
+ }
128
+ if (op === "bindInstance") {
129
+ keys(a, ["instanceId", "instanceGeneration", "bindingId", "expectedPreviousGeneration"]);
130
+ bindRequest(a);
131
+ }
132
+ else if (op === "revokeOperation") {
133
+ keys(a, ["ref"]);
134
+ a.ref = parseSandboxOperationRef(a.ref);
135
+ }
136
+ else if (["backgroundStatus", "backgroundTail", "backgroundReadOutput", "backgroundStop"].includes(op)) {
137
+ keys(a, [
138
+ "ref",
139
+ ...(op === "backgroundReadOutput" ? ["offset", "maxBytes"] : []),
140
+ ...(op === "backgroundTail" ? ["maxBytes"] : op === "backgroundStop" ? ["graceMs"] : []),
141
+ ]);
142
+ a.ref = parseSandboxExecutionRef(a.ref);
143
+ if (op === "backgroundTail" || op === "backgroundReadOutput")
144
+ integer(a.maxBytes, 0, 65536);
145
+ if (op === "backgroundReadOutput")
146
+ integer(a.offset);
147
+ if (op === "backgroundStop")
148
+ integer(a.graceMs, 0, 60000);
149
+ }
150
+ else {
151
+ const preparation = op.startsWith("prepare"), browsing = op.startsWith("browse"), background = op === "backgroundStart";
152
+ const method = background ? "exec" : preparation ? op.slice(7) : browsing ? op.slice(6) : op;
153
+ const native = method[0]?.toLowerCase() + method.slice(1);
154
+ if (!natives.includes(native) ||
155
+ (preparation && !["readFile", "writeFile", "stat"].includes(native)) ||
156
+ (browsing && !["stat", "list", "scan"].includes(native)))
157
+ throw new DeviceProtocolError("Unknown operation");
158
+ a.scope = preparation
159
+ ? parseSandboxPreparationScope(a.scope)
160
+ : browsing
161
+ ? parseSandboxBrowseScope(a.scope)
162
+ : parseSandboxOperationScope(a.scope);
163
+ const fields = native === "exec"
164
+ ? ["command", "cwd", "env", "timeoutMs", "maxOutputBytes", "limits", "grants"]
165
+ : native === "readFile"
166
+ ? ["path", "maxBytes"]
167
+ : native === "writeFile"
168
+ ? ["path", "dataB64"]
169
+ : native === "stat"
170
+ ? ["path"]
171
+ : native === "list"
172
+ ? ["path", "limit"]
173
+ : ["base"];
174
+ keys(a, ["scope", ...fields, ...(background ? ["taskId", "outputPath", "retainUntilMs"] : [])]);
175
+ if (native !== "exec")
176
+ path(a[native === "scan" ? "base" : "path"]);
177
+ const validated = { ...a };
178
+ delete validated.scope;
179
+ if (native === "exec") {
180
+ const scope = parseSandboxOperationScope(a.scope);
181
+ validated.tag = scope.tag;
182
+ validated.actor = scope.actor;
183
+ if (background) {
184
+ string(a.taskId);
185
+ path(a.outputPath);
186
+ integer(a.retainUntilMs, scope.admitBeforeMs);
187
+ delete validated.taskId;
188
+ delete validated.outputPath;
189
+ delete validated.retainUntilMs;
190
+ }
191
+ }
192
+ else if (native !== "writeFile")
193
+ validated.limits = { mode: "sandbox" };
194
+ // Reuse v2's pure value guards; inserted mode is never returned or used as authority.
195
+ parseDeviceFrame(JSON.stringify({ type: "req", id, op: native, args: validated, deadlineMs }), "kernel");
196
+ if (native === "writeFile" &&
197
+ (typeof a.dataB64 !== "string" ||
198
+ !/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(a.dataB64)))
199
+ throw new DeviceProtocolError("Invalid base64 payload");
200
+ }
201
+ return freeze({ type: "req", id, op: op, args: a, deadlineMs });
202
+ }
203
+ /** Strict scope-bearing frames; active parseDeviceFrame still speaks v2. */
204
+ export function parseDeviceFrameV3(raw, from, maxFrameBytes) {
205
+ if (maxFrameBytes !== undefined &&
206
+ new TextEncoder().encode(raw).byteLength > integer(maxFrameBytes, 1))
207
+ throw new DeviceProtocolError("Frame exceeds negotiated capacity; check device and deployment frame limits");
208
+ let parsed;
209
+ try {
210
+ parsed = JSON.parse(raw);
211
+ }
212
+ catch {
213
+ throw new DeviceProtocolError("Frame is not valid JSON");
214
+ }
215
+ const o = object(parsed);
216
+ if (o.type === "ready") {
217
+ if (from !== "kernel")
218
+ throw new DeviceProtocolError("Ready must come from kernel");
219
+ keys(o, ["type", "connectionId", "maxFrameBytes"]);
220
+ return freeze({
221
+ type: "ready",
222
+ connectionId: string(o.connectionId),
223
+ maxFrameBytes: integer(o.maxFrameBytes, 1024),
224
+ });
225
+ }
226
+ if (o.type === "req") {
227
+ if (from !== "kernel")
228
+ throw new DeviceProtocolError("Request must come from kernel");
229
+ return request(o);
230
+ }
231
+ if (o.type === "hello") {
232
+ if (from !== "device" || o.protocol !== 3)
233
+ throw new DeviceProtocolError("Expected protocol 3 hello");
234
+ const transport = object(o.transport);
235
+ keys(transport, ["maxFrameBytes"]);
236
+ const maxFrameBytes = integer(transport.maxFrameBytes, 1024);
237
+ const permissionSupport = support(o.permissionSupport);
238
+ if (o.instanceGeneration === null &&
239
+ (o.runtimeIdentity !== undefined ||
240
+ permissionSupport.restricted !== null ||
241
+ permissionSupport.fullAccess ||
242
+ permissionSupport.background ||
243
+ !permissionSupport.unavailableReason))
244
+ throw new DeviceProtocolError("Unbound hello cannot advertise runtime capability");
245
+ const base = parseDeviceFrame(raw, from);
246
+ if (base.type !== "hello")
247
+ throw new DeviceProtocolError("Expected hello");
248
+ let runtimeIdentity;
249
+ if (o.runtimeIdentity !== undefined) {
250
+ runtimeIdentity = identity(o.runtimeIdentity);
251
+ if (runtimeIdentity.instanceGeneration !== string(o.instanceGeneration))
252
+ throw new DeviceProtocolError("Runtime identity generation mismatch");
253
+ }
254
+ return freeze({
255
+ ...base,
256
+ protocol: 3,
257
+ permissionSupport,
258
+ transport: { maxFrameBytes },
259
+ ownerCeiling: owner(o.ownerCeiling),
260
+ instanceGeneration: o.instanceGeneration === null ? null : string(o.instanceGeneration),
261
+ ...(runtimeIdentity && { runtimeIdentity }),
262
+ });
263
+ }
264
+ if (o.type === "policy") {
265
+ if (from !== "device")
266
+ throw new DeviceProtocolError("Policy must come from device");
267
+ keys(o, ["type", "policy", "ownerCeiling"]);
268
+ const base = parseDeviceFrame(JSON.stringify({ type: "policy", policy: o.policy }), from);
269
+ if (base.type !== "policy")
270
+ throw new DeviceProtocolError("Expected policy");
271
+ return freeze({ ...base, ownerCeiling: owner(o.ownerCeiling) });
272
+ }
273
+ if (o.type === "res" && o.ok === false) {
274
+ if (from !== "device")
275
+ throw new DeviceProtocolError("Response must come from device");
276
+ keys(o, ["type", "id", "ok", "error"]);
277
+ const e = object(o.error);
278
+ keys(e, ["kind", "message"]);
279
+ if (!["gone", "fs_gone", "policy", "error", "denied", "unsupported", "unknown"].includes(String(e.kind)))
280
+ throw new DeviceProtocolError("Unknown outcome kind");
281
+ return freeze({
282
+ type: "res",
283
+ id: string(o.id),
284
+ ok: false,
285
+ error: {
286
+ kind: e.kind,
287
+ message: string(e.message, 8192),
288
+ },
289
+ });
290
+ }
291
+ const base = parseDeviceFrame(raw, from);
292
+ if (base.type === "hello" || base.type === "req" || base.type === "policy")
293
+ throw new DeviceProtocolError("Expected staged frame");
294
+ return freeze(base);
295
+ }
296
+ export function parseOperationResultV3(op, result, request) {
297
+ if (op === "bindInstance") {
298
+ if (!request || !("bindingId" in request))
299
+ throw new DeviceProtocolError("Binding validation requires the exact request");
300
+ const o = object(result);
301
+ keys(o, [
302
+ "instanceId",
303
+ "instanceGeneration",
304
+ "bindingId",
305
+ "runtimeIdentity",
306
+ "permissionSupport",
307
+ "ownerCeiling",
308
+ ]);
309
+ const runtimeIdentity = identity(o.runtimeIdentity);
310
+ if (o.instanceId !== request.instanceId ||
311
+ o.instanceGeneration !== request.instanceGeneration ||
312
+ o.bindingId !== request.bindingId ||
313
+ runtimeIdentity.instanceGeneration !== request.instanceGeneration)
314
+ throw new DeviceProtocolError("Binding answer belongs to another instance generation");
315
+ return freeze({
316
+ instanceId: request.instanceId,
317
+ instanceGeneration: request.instanceGeneration,
318
+ bindingId: request.bindingId,
319
+ runtimeIdentity,
320
+ permissionSupport: support(o.permissionSupport),
321
+ ownerCeiling: owner(o.ownerCeiling),
322
+ });
323
+ }
324
+ if (op === "backgroundReadOutput") {
325
+ if (!request || !("offset" in request))
326
+ throw new DeviceProtocolError("Output validation requires the exact request bounds");
327
+ const offset = integer(request.offset), maxBytes = integer(request.maxBytes, 0, 65536);
328
+ const o = object(result);
329
+ if ("unavailable" in o) {
330
+ keys(o, ["unavailable"]);
331
+ if (o.unavailable !== "lost" && o.unavailable !== "expired")
332
+ throw new DeviceProtocolError("Invalid output outcome");
333
+ return freeze(o);
334
+ }
335
+ keys(o, ["dataB64", "offset", "nextOffset", "totalBytes"]);
336
+ const total = integer(o.totalBytes), next = integer(o.nextOffset);
337
+ if (integer(o.offset) !== offset ||
338
+ typeof o.dataB64 !== "string" ||
339
+ o.dataB64.length > 87384 ||
340
+ !/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(o.dataB64))
341
+ throw new DeviceProtocolError("Invalid output range or base64");
342
+ const decoded = atob(o.dataB64);
343
+ if (btoa(decoded) !== o.dataB64 ||
344
+ decoded.length !== Math.min(maxBytes, Math.max(total - offset, 0)) ||
345
+ !Number.isSafeInteger(offset + decoded.length) ||
346
+ next !== offset + decoded.length)
347
+ throw new DeviceProtocolError("Inconsistent output range; retry from the same offset");
348
+ return freeze(o);
349
+ }
350
+ if (op === "backgroundStart")
351
+ return parseSandboxExecutionRef(result);
352
+ if (op === "backgroundStatus") {
353
+ const o = object(result);
354
+ keys(o, ["state", "exitCode", "timedOut"]);
355
+ if (o.state === "running" || o.state === "lost")
356
+ return freeze({ state: o.state });
357
+ if (o.state !== "exited" ||
358
+ (o.exitCode !== null && !Number.isInteger(o.exitCode)) ||
359
+ typeof o.timedOut !== "boolean")
360
+ throw new DeviceProtocolError("Invalid execution status");
361
+ return freeze(o);
362
+ }
363
+ if (op === "backgroundTail") {
364
+ if (result && typeof result === "object" && "unavailable" in result) {
365
+ const o = object(result);
366
+ keys(o, ["unavailable"]);
367
+ if (o.unavailable !== "lost" && o.unavailable !== "expired")
368
+ throw new DeviceProtocolError("Invalid output outcome");
369
+ return freeze(o);
370
+ }
371
+ return parseOpResult("readFile", result);
372
+ }
373
+ if (op === "backgroundStop") {
374
+ const o = object(result);
375
+ keys(o, ["outcome", "exitCode", "timedOut"]);
376
+ if (!["already-exited", "stopped", "cancel-pending", "lost"].includes(String(o.outcome)))
377
+ throw new DeviceProtocolError("Invalid stop outcome");
378
+ if (o.outcome === "already-exited" &&
379
+ ((o.exitCode !== null && !Number.isInteger(o.exitCode)) || typeof o.timedOut !== "boolean"))
380
+ throw new DeviceProtocolError("Invalid stopped execution status");
381
+ return freeze(o);
382
+ }
383
+ if (op === "policy") {
384
+ const o = object(result);
385
+ keys(o, ["policy", "ownerCeiling"]);
386
+ return freeze({
387
+ ...parseOpResult("policy", { policy: o.policy }),
388
+ ownerCeiling: owner(o.ownerCeiling),
389
+ });
390
+ }
391
+ if (op === "policyStatus") {
392
+ const o = object(result);
393
+ keys(o, ["outcome", "policy", "message", "ownerCeiling"]);
394
+ const { ownerCeiling, ...rest } = o;
395
+ const status = parseOpResult("policyStatus", rest);
396
+ if (status.outcome === "applied" && ownerCeiling === undefined)
397
+ throw new DeviceProtocolError("An applied policy status carries the owner report");
398
+ if (ownerCeiling !== undefined)
399
+ status.ownerCeiling = owner(ownerCeiling);
400
+ return freeze(status);
401
+ }
402
+ if (op === "revokeOperation") {
403
+ if (result !== null)
404
+ throw new DeviceProtocolError("Revoke result must be null");
405
+ return null;
406
+ }
407
+ const raw = op.startsWith("prepare") ? op.slice(7) : op.startsWith("browse") ? op.slice(6) : op;
408
+ return parseOpResult((raw.charAt(0).toLowerCase() + raw.slice(1)), result);
409
+ }
@@ -91,7 +91,18 @@ export interface DeviceHello {
91
91
  * project's relative path). A malformed value is dropped by the parser.
92
92
  */
93
93
  home?: string;
94
+ /**
95
+ * The identity of the host's current OS boot (Linux `/proc/sys/kernel/random/boot_id`; macOS
96
+ * `kern.bootsessionuuid`): a value that differs from an earlier one of the
97
+ * same machine proves the host restarted since, so no process of that earlier boot can exist.
98
+ * A malformed value is dropped by the parser.
99
+ */
100
+ bootId?: string;
94
101
  }
102
+ /** A hello's `bootId`: 1 to 128 characters of letters, digits, `.`, `_`, `:` and `-`. */
103
+ export declare const DEVICE_BOOT_ID_RE: RegExp;
104
+ /** Whether `v` is a well-formed {@link DeviceHello.bootId}. */
105
+ export declare function isDeviceBootId(v: unknown): v is string;
95
106
  /** Error kinds a device reports for a failed request. */
96
107
  export type DeviceErrorKind = "gone" | "fs_gone" | "policy" | "error";
97
108
  /** The device's answer to a {@link KernelReq}. */
@@ -46,6 +46,12 @@ const MAX_POLICY_HOSTS = 100;
46
46
  export const MAX_POLICY_OP_ID_LENGTH = 128;
47
47
  /** The most entries a hello's `recentOps` carries; the parser keeps the newest. */
48
48
  export const MAX_RECENT_POLICY_OPS = 100;
49
+ /** A hello's `bootId`: 1 to 128 characters of letters, digits, `.`, `_`, `:` and `-`. */
50
+ export const DEVICE_BOOT_ID_RE = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/;
51
+ /** Whether `v` is a well-formed {@link DeviceHello.bootId}. */
52
+ export function isDeviceBootId(v) {
53
+ return typeof v === "string" && DEVICE_BOOT_ID_RE.test(v);
54
+ }
49
55
  /** A frame that is not valid device protocol (or came from the wrong side). */
50
56
  export class DeviceProtocolError extends Error {
51
57
  constructor(message) {
@@ -268,6 +274,8 @@ function optionalHelloFields(o) {
268
274
  if (typeof o.home === "string" && validateSandboxPathShape(o.home).length === 0) {
269
275
  out.home = o.home;
270
276
  }
277
+ if (isDeviceBootId(o.bootId))
278
+ out.bootId = o.bootId;
271
279
  return { ...out, ...optionalPolicy(o.policy) };
272
280
  }
273
281
  /** A summary field that is dropped when absent or unreadable. */