@capybara-hq/plugin-sdk 0.1.0-rc.52 → 0.1.0-rc.54

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.
@@ -2,60 +2,32 @@
2
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
4
  *
5
- * Protocol 4 (the scope-bearing operations, `parseDeviceFrame`) is defined in the second half of
6
- * this file. Protocol 2's frames keep a `Legacy` prefix where a newer name replaced them
7
- * (`LegacyDeviceHello`, `parseLegacyDeviceFrame`, ...); protocol 4 reuses their value guards, and
8
- * they go with the legacy device surface.
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.
9
7
  */
10
8
  import { parseSandboxBrowseScope, parseSandboxExecutionRef, parseSandboxOperationRef, parseSandboxOperationScope, parseSandboxPreparationScope, } from "./device-operation.js";
11
- import { isDeviceProjectName, MAX_DEVICE_PROJECT_NAME_LENGTH, MAX_DEVICE_SCAN_DEPTH, MAX_DEVICE_SCAN_RESULTS, validateAllowHost, validateSandboxPathShape, } from "./device-provider.js";
12
- /** The protocol version carried in `X-Capybara-Device-Protocol` and the hello frame. */
9
+ import { isDeviceProjectName, MAX_DEVICE_LIST_ENTRIES, MAX_DEVICE_PROJECT_NAME_LENGTH, MAX_DEVICE_SCAN_DEPTH, MAX_DEVICE_SCAN_RESULTS, validateAllowHost, validateSandboxPathShape, } from "./device-provider.js";
10
+ /** The major version of {@link DEVICE_DIAL_IN_PROTOCOL}. */
13
11
  export const DEVICE_PROTOCOL_VERSION = 5;
14
12
  /**
15
- * Protocol 4's version, which a deployment speaking {@link DEVICE_PROTOCOL_VERSION} refuses (426
16
- * on the header, a protocol close on the hello): its operation frames carry read roots in the
17
- * filesystem scope, which protocol 5 replaced with the project root, so a protocol 4 program must
18
- * be updated.
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}).
19
18
  */
20
- export const LEGACY_DEVICE_PROTOCOL_VERSION = 4;
21
- const DEVICE_OPS = [
22
- "create",
23
- "exec",
24
- "readFile",
25
- "writeFile",
26
- "stat",
27
- "killTagged",
28
- "killAll",
29
- "stop",
30
- "policy",
31
- "policyStatus",
32
- "list",
33
- "scan",
34
- ];
35
- const DEVICE_FEATURES = [
36
- "networkReport",
37
- "policyOp",
38
- "policyOpId",
39
- "projects",
40
- ];
41
- /** The most entries a `list` op may ask for and its result may carry. */
42
- export const MAX_DEVICE_LIST_ENTRIES = 1000;
19
+ export const DEVICE_DIAL_IN_PROTOCOL = `capybara-device/${DEVICE_PROTOCOL_VERSION}`;
20
+ const DEVICE_FEATURES = ["networkReport", "projects"];
43
21
  /** The most blocked hosts an exec result reports; the parser cuts longer lists. */
44
22
  export const MAX_NETWORK_BLOCKED_HOSTS = 20;
45
- /** The most hosts a `policy` op's `remove` or an exec's `grants` may carry. */
23
+ /** The most hosts an exec's `grants` may carry. */
46
24
  const MAX_POLICY_HOSTS = 100;
47
25
  /**
48
- * Why a `policy` op naming hosts to `add` is refused: the deployment may only narrow a local
49
- * device's sandbox; its owner widens it on the machine.
26
+ * The identity of a host's OS boot or of a program run: 1 to 128 characters of letters, digits,
27
+ * `.`, `_`, `:` and `-`.
50
28
  */
51
- export const POLICY_ADD_REFUSED = "The deployment may not add hosts to a device's sandbox allowlist: widening happens only on the machine (capybara-device policy add allowedDomains <host>)";
52
- /** The longest `opId` a `policy` / `policyStatus` op may carry. */
53
- export const MAX_POLICY_OP_ID_LENGTH = 128;
54
- /** The most entries a hello's `recentOps` carries; the parser keeps the newest. */
55
- export const MAX_RECENT_POLICY_OPS = 100;
56
- /** A hello's `bootId`: 1 to 128 characters of letters, digits, `.`, `_`, `:` and `-`. */
57
29
  export const DEVICE_BOOT_ID_RE = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/;
58
- /** Whether `v` is a well-formed {@link LegacyDeviceHello.bootId}. */
30
+ /** Whether `v` is a well-formed boot or program-run identity ({@link DEVICE_BOOT_ID_RE}). */
59
31
  export function isDeviceBootId(v) {
60
32
  return typeof v === "string" && DEVICE_BOOT_ID_RE.test(v);
61
33
  }
@@ -234,53 +206,15 @@ function parsePolicySummary(v) {
234
206
  const o = obj(v, 'field "policy"');
235
207
  return { allowedDomains: strArray(o, "allowedDomains") };
236
208
  }
237
- /**
238
- * Whether `v` is a valid policy op id: non-empty, no `:`, at most
239
- * {@link MAX_POLICY_OP_ID_LENGTH} characters.
240
- */
241
- export function isPolicyOpId(v) {
242
- return (typeof v === "string" && v !== "" && v.length <= MAX_POLICY_OP_ID_LENGTH && !v.includes(":"));
243
- }
244
- function opId(o) {
245
- const v = o.opId;
246
- if (!isPolicyOpId(v)) {
247
- throw new DeviceProtocolError(`field "opId" must be a non-empty string without ":" of at most ${MAX_POLICY_OP_ID_LENGTH} characters`);
248
- }
249
- return v;
250
- }
251
- const OP_OUTCOMES = ["applied", "refused", "started"];
252
- /**
253
- * The valid entries of a hello's `recentOps`, one per op id (the last listed), the newest
254
- * {@link MAX_RECENT_POLICY_OPS}.
255
- */
256
- function parseRecentOps(v) {
257
- // one entry per op id: the last one listed (the newest outcome), where it is listed
258
- const byId = new Map();
259
- for (const e of v) {
260
- if (!isRecord(e) || !isPolicyOpId(e.opId))
261
- continue;
262
- if (!OP_OUTCOMES.includes(e.outcome))
263
- continue;
264
- byId.delete(e.opId);
265
- byId.set(e.opId, { opId: e.opId, outcome: e.outcome });
266
- }
267
- return [...byId.values()].slice(-MAX_RECENT_POLICY_OPS);
268
- }
269
209
  /** Optional hello fields: malformed values are ignored so old and new peers interoperate. */
270
210
  function optionalHelloFields(o) {
271
211
  const out = {};
272
212
  if (Array.isArray(o.features)) {
273
213
  out.features = DEVICE_FEATURES.filter((f) => o.features.includes(f));
274
214
  }
275
- if (Array.isArray(o.recentOps))
276
- out.recentOps = parseRecentOps(o.recentOps);
277
215
  if (typeof o.home === "string" && validateSandboxPathShape(o.home).length === 0) {
278
216
  out.home = o.home;
279
217
  }
280
- if (isDeviceBootId(o.bootId))
281
- out.bootId = o.bootId;
282
- if (isDeviceBootId(o.programRunId))
283
- out.programRunId = o.programRunId;
284
218
  return { ...out, ...optionalPolicy(o.policy) };
285
219
  }
286
220
  /** A summary field that is dropped when absent or unreadable. */
@@ -323,58 +257,6 @@ function parseNetworkReport(v) {
323
257
  }
324
258
  return { blocked };
325
259
  }
326
- function parseHello(o) {
327
- const os = str(o, "os");
328
- if (os !== "darwin" && os !== "linux")
329
- throw new DeviceProtocolError(`unsupported os "${os}"`);
330
- const mode = str(o, "mode");
331
- if (mode !== "os" && mode !== "docker") {
332
- throw new DeviceProtocolError(`unsupported mode "${mode}"`);
333
- }
334
- if (typeof o.sessionIsolation !== "boolean") {
335
- throw new DeviceProtocolError('field "sessionIsolation" must be a boolean');
336
- }
337
- return {
338
- type: "hello",
339
- protocol: posInt(o, "protocol"),
340
- programVersion: str(o, "programVersion"),
341
- os,
342
- arch: str(o, "arch"),
343
- mode,
344
- roots: parseRoots(o.roots),
345
- sessionIsolation: o.sessionIsolation,
346
- ...optionalHelloFields(o),
347
- };
348
- }
349
- function parseRes(o) {
350
- const id = nonEmptyStr(o, "id");
351
- if (o.ok === true)
352
- return { type: "res", id, ok: true, result: o.result };
353
- if (o.ok !== false)
354
- throw new DeviceProtocolError('field "ok" must be a boolean');
355
- const e = o.error;
356
- if (!isRecord(e))
357
- throw new DeviceProtocolError('field "error" must be an object');
358
- const kind = str(e, "kind");
359
- if (kind !== "gone" && kind !== "fs_gone" && kind !== "policy" && kind !== "error") {
360
- throw new DeviceProtocolError(`unknown error kind "${kind}"`);
361
- }
362
- return { type: "res", id, ok: false, error: { kind, message: str(e, "message") } };
363
- }
364
- function parseReq(o) {
365
- const op = str(o, "op");
366
- if (!DEVICE_OPS.includes(op))
367
- throw new DeviceProtocolError(`unknown op "${op}"`);
368
- const args = obj(o.args, 'field "args"');
369
- validateArgs(op, args);
370
- return {
371
- type: "req",
372
- id: nonEmptyStr(o, "id"),
373
- op: op,
374
- args,
375
- deadlineMs: posInt(o, "deadlineMs"),
376
- };
377
- }
378
260
  function validateArgs(op, a) {
379
261
  switch (op) {
380
262
  case "exec": {
@@ -438,27 +320,6 @@ function validateArgs(op, a) {
438
320
  }
439
321
  return;
440
322
  }
441
- case "policy": {
442
- opId(a);
443
- if (a.add !== undefined)
444
- throw new DeviceProtocolError(POLICY_ADD_REFUSED);
445
- if (a.mode !== undefined)
446
- throw new DeviceProtocolError('field "mode" is not part of device protocol 4; narrow with "ownerCeiling" instead');
447
- if (a.remove !== undefined)
448
- hostArray(a, "remove");
449
- const src = obj(a.source, 'field "source"');
450
- nonEmptyStr(src, "accountId");
451
- str(src, "accountName");
452
- const via = str(src, "via");
453
- if (via !== "web" && via !== "im")
454
- throw new DeviceProtocolError(`unknown via "${via}"`);
455
- if (src.approvalId !== undefined)
456
- str(src, "approvalId");
457
- return;
458
- }
459
- case "policyStatus":
460
- opId(a);
461
- return;
462
323
  case "list": {
463
324
  absolutePath(a.path, 'field "path"');
464
325
  const limit = posInt(a, "limit");
@@ -493,19 +354,6 @@ export function parseOpResult(op, result) {
493
354
  out.network = network;
494
355
  return out;
495
356
  }
496
- case "policy":
497
- return { policy: parsePolicySummary(obj(result, "policy result").policy) };
498
- case "policyStatus": {
499
- const r = obj(result, "policyStatus result");
500
- const out = {
501
- outcome: oneOf(r, "outcome", [...OP_OUTCOMES, "unknown"]),
502
- };
503
- if (r.policy !== undefined)
504
- out.policy = parsePolicySummary(r.policy);
505
- if (r.message !== undefined)
506
- out.message = str(r, "message");
507
- return out;
508
- }
509
357
  case "readFile": {
510
358
  if (result === null)
511
359
  return null;
@@ -530,41 +378,6 @@ export function parseOpResult(op, result) {
530
378
  return null;
531
379
  }
532
380
  }
533
- /**
534
- * Parses one WebSocket text frame. `from` is the sender: a device may send `hello`, `res` and
535
- * `policy`, the
536
- * kernel `req` and `cancel`. Throws {@link DeviceProtocolError} on bad JSON, an unknown `type`,
537
- * missing fields or a frame of the wrong direction.
538
- */
539
- export function parseLegacyDeviceFrame(raw, from) {
540
- let o;
541
- try {
542
- o = JSON.parse(raw);
543
- }
544
- catch {
545
- throw new DeviceProtocolError("frame is not valid JSON");
546
- }
547
- if (!isRecord(o))
548
- throw new DeviceProtocolError("frame must be a JSON object");
549
- const type = o.type;
550
- switch (type) {
551
- case "hello":
552
- case "res":
553
- case "policy":
554
- if (from !== "device")
555
- throw new DeviceProtocolError(`"${type}" must come from the device`);
556
- if (type === "policy")
557
- return { type, ...optionalPolicy(o.policy) };
558
- return type === "hello" ? parseHello(o) : parseRes(o);
559
- case "req":
560
- case "cancel":
561
- if (from !== "kernel")
562
- throw new DeviceProtocolError(`"${type}" must come from the kernel`);
563
- return type === "req" ? parseReq(o) : { type: "cancel", id: nonEmptyStr(o, "id") };
564
- default:
565
- throw new DeviceProtocolError(`unknown frame type "${String(type)}"`);
566
- }
567
- }
568
381
  const object = (value) => {
569
382
  if (!value || typeof value !== "object" || Array.isArray(value))
570
383
  throw new DeviceProtocolError("Expected an object");
@@ -792,17 +605,15 @@ function identity(value) {
792
605
  return o;
793
606
  }
794
607
  const natives = ["exec", "readFile", "writeFile", "stat", "list", "scan"];
795
- const legacy = ["create", "stop", "policy", "policyStatus"];
796
- function request(o) {
797
- keys(o, ["type", "id", "op", "args", "deadlineMs"]);
798
- const id = string(o.id), op = string(o.op), a = object(o.args), deadlineMs = integer(o.deadlineMs, 1);
799
- if (legacy.includes(op)) {
800
- if (op === "policy" && a.ownerCeiling !== undefined)
801
- a.ownerCeiling = parseOwnerCeilingNarrowing(a.ownerCeiling);
802
- const parsed = parseLegacyDeviceFrame(JSON.stringify(o), "kernel");
803
- if (parsed.type !== "req")
804
- throw new DeviceProtocolError("Expected request");
805
- return freeze({ ...parsed, op: op, args: object(parsed.args) });
608
+ /** The machine lifecycle operations, checked by the protocol 2 argument guards. */
609
+ const lifecycle = ["create", "stop"];
610
+ function requestBody(value) {
611
+ const o = object(value);
612
+ keys(o, ["op", "args"]);
613
+ const op = string(o.op), a = object(o.args);
614
+ if (lifecycle.includes(op)) {
615
+ validateArgs(op, a);
616
+ return freeze({ op: op, args: a });
806
617
  }
807
618
  if (op === "bindInstance") {
808
619
  keys(a, ["instanceId", "instanceGeneration", "bindingId", "expectedPreviousGeneration"]);
@@ -869,11 +680,11 @@ function request(o) {
869
680
  }
870
681
  }
871
682
  // Reuse the legacy pure value guards on the native fields.
872
- parseLegacyDeviceFrame(JSON.stringify({ type: "req", id, op: native, args: validated, deadlineMs }), "kernel");
683
+ validateArgs(native, validated);
873
684
  if (native === "writeFile" && (typeof a.dataB64 !== "string" || !isBase64(a.dataB64)))
874
685
  throw new DeviceProtocolError("Invalid base64 payload");
875
686
  }
876
- return freeze({ type: "req", id, op: op, args: a, deadlineMs });
687
+ return freeze({ op: op, args: a });
877
688
  }
878
689
  /**
879
690
  * Padded standard base64: whole quartets of `A-Z a-z 0-9 + /`, the last one possibly ending in
@@ -895,111 +706,121 @@ function isBase64(value) {
895
706
  }
896
707
  return true;
897
708
  }
898
- /** Strictly parses one protocol 4 frame; throws {@link DeviceProtocolError}. */
899
- export function parseDeviceFrame(raw, from, maxFrameBytes) {
900
- if (maxFrameBytes !== undefined &&
901
- new TextEncoder().encode(raw).byteLength > integer(maxFrameBytes, 1))
902
- throw new DeviceProtocolError("Frame exceeds negotiated capacity; check device and deployment frame limits");
903
- let parsed;
709
+ const RESPONSE_KINDS = [
710
+ "gone",
711
+ "fs_gone",
712
+ "policy",
713
+ "error",
714
+ "denied",
715
+ "unsupported",
716
+ "unsettled",
717
+ "unknown",
718
+ "invalid",
719
+ ];
720
+ function helloBody(value) {
721
+ const o = object(value);
722
+ keys(o, [
723
+ "mode",
724
+ "roots",
725
+ "sessionIsolation",
726
+ "features",
727
+ "policy",
728
+ "home",
729
+ "permissionSupport",
730
+ "ownerCeiling",
731
+ "instanceGeneration",
732
+ "runtimeIdentity",
733
+ ]);
734
+ const mode = o.mode;
735
+ if (mode !== "os" && mode !== "docker")
736
+ throw new DeviceProtocolError("Unsupported mode");
737
+ if (typeof o.sessionIsolation !== "boolean")
738
+ throw new DeviceProtocolError('field "sessionIsolation" must be a boolean');
739
+ const permissionSupport = parseSandboxPermissionSupport(o.permissionSupport);
740
+ if (o.instanceGeneration === null &&
741
+ (o.runtimeIdentity !== undefined ||
742
+ permissionSupport.restricted !== null ||
743
+ permissionSupport.outsideSandbox ||
744
+ permissionSupport.network.openPublic ||
745
+ permissionSupport.network.allowlist ||
746
+ permissionSupport.network.perOperationHosts ||
747
+ permissionSupport.background ||
748
+ !permissionSupport.unavailableReason))
749
+ throw new DeviceProtocolError("Unbound hello cannot advertise runtime capability");
750
+ let runtimeIdentity;
751
+ if (o.runtimeIdentity !== undefined) {
752
+ runtimeIdentity = identity(o.runtimeIdentity);
753
+ if (runtimeIdentity.instanceGeneration !== string(o.instanceGeneration))
754
+ throw new DeviceProtocolError("Runtime identity generation mismatch");
755
+ }
756
+ const optional = optionalHelloFields({ features: o.features, policy: o.policy, home: o.home });
757
+ return freeze({
758
+ mode,
759
+ roots: parseRoots(o.roots),
760
+ sessionIsolation: o.sessionIsolation,
761
+ ...(optional.features && { features: optional.features }),
762
+ ...(optional.policy && { policy: optional.policy }),
763
+ ...(optional.home !== undefined && { home: optional.home }),
764
+ permissionSupport,
765
+ ownerCeiling: parseOwnerCeilingReport(o.ownerCeiling),
766
+ instanceGeneration: o.instanceGeneration === null ? null : string(o.instanceGeneration),
767
+ ...(runtimeIdentity && { runtimeIdentity }),
768
+ });
769
+ }
770
+ function responseBody(value) {
771
+ const o = object(value);
772
+ if (o.ok === true) {
773
+ keys(o, ["ok", "result"]);
774
+ return freeze({ ok: true, result: o.result });
775
+ }
776
+ if (o.ok !== false)
777
+ throw new DeviceProtocolError('field "ok" must be a boolean');
778
+ keys(o, ["ok", "error"]);
779
+ const e = object(o.error);
780
+ keys(e, ["kind", "message"]);
781
+ if (!RESPONSE_KINDS.includes(String(e.kind)))
782
+ throw new DeviceProtocolError("Unknown outcome kind");
783
+ return freeze({
784
+ ok: false,
785
+ error: {
786
+ kind: e.kind,
787
+ message: string(e.message, 8192),
788
+ },
789
+ });
790
+ }
791
+ function eventBody(value) {
792
+ const o = object(value);
793
+ if (o.type !== "policy")
794
+ throw new DeviceProtocolError("Unknown event type");
795
+ keys(o, ["type", "policy", "ownerCeiling"]);
796
+ return freeze({
797
+ type: "policy",
798
+ ...optionalPolicy(o.policy),
799
+ ownerCeiling: parseOwnerCeilingReport(o.ownerCeiling),
800
+ });
801
+ }
802
+ export function parseDeviceFrame(body, kind) {
803
+ // a JSON snapshot: plain data only (no accessor runs twice, no prototype), never aliasing the
804
+ // caller's objects, which the parsed copy freezes
805
+ let copy;
904
806
  try {
905
- parsed = JSON.parse(raw);
807
+ copy = JSON.parse(JSON.stringify(body));
906
808
  }
907
809
  catch {
908
- throw new DeviceProtocolError("Frame is not valid JSON");
810
+ throw new DeviceProtocolError("Body is not JSON data");
909
811
  }
910
- const o = object(parsed);
911
- if (o.type === "ready") {
912
- if (from !== "kernel")
913
- throw new DeviceProtocolError("Ready must come from kernel");
914
- keys(o, ["type", "connectionId", "maxFrameBytes"]);
915
- return freeze({
916
- type: "ready",
917
- connectionId: string(o.connectionId),
918
- maxFrameBytes: integer(o.maxFrameBytes, 1024),
919
- });
920
- }
921
- if (o.type === "req") {
922
- if (from !== "kernel")
923
- throw new DeviceProtocolError("Request must come from kernel");
924
- return request(o);
925
- }
926
- if (o.type === "hello") {
927
- if (from !== "device" || o.protocol !== DEVICE_PROTOCOL_VERSION)
928
- throw new DeviceProtocolError(`Expected protocol ${DEVICE_PROTOCOL_VERSION} hello`);
929
- const transport = object(o.transport);
930
- keys(transport, ["maxFrameBytes"]);
931
- const maxFrameBytes = integer(transport.maxFrameBytes, 1024);
932
- const permissionSupport = parseSandboxPermissionSupport(o.permissionSupport);
933
- if (o.instanceGeneration === null &&
934
- (o.runtimeIdentity !== undefined ||
935
- permissionSupport.restricted !== null ||
936
- permissionSupport.outsideSandbox ||
937
- permissionSupport.network.openPublic ||
938
- permissionSupport.network.allowlist ||
939
- permissionSupport.network.perOperationHosts ||
940
- permissionSupport.background ||
941
- !permissionSupport.unavailableReason))
942
- throw new DeviceProtocolError("Unbound hello cannot advertise runtime capability");
943
- const base = parseLegacyDeviceFrame(raw, from);
944
- if (base.type !== "hello")
945
- throw new DeviceProtocolError("Expected hello");
946
- let runtimeIdentity;
947
- if (o.runtimeIdentity !== undefined) {
948
- runtimeIdentity = identity(o.runtimeIdentity);
949
- if (runtimeIdentity.instanceGeneration !== string(o.instanceGeneration))
950
- throw new DeviceProtocolError("Runtime identity generation mismatch");
951
- }
952
- return freeze({
953
- ...base,
954
- protocol: DEVICE_PROTOCOL_VERSION,
955
- permissionSupport,
956
- transport: { maxFrameBytes },
957
- ownerCeiling: parseOwnerCeilingReport(o.ownerCeiling),
958
- instanceGeneration: o.instanceGeneration === null ? null : string(o.instanceGeneration),
959
- ...(runtimeIdentity && { runtimeIdentity }),
960
- });
961
- }
962
- if (o.type === "policy") {
963
- if (from !== "device")
964
- throw new DeviceProtocolError("Policy must come from device");
965
- keys(o, ["type", "policy", "ownerCeiling"]);
966
- const base = parseLegacyDeviceFrame(JSON.stringify({ type: "policy", policy: o.policy }), from);
967
- if (base.type !== "policy")
968
- throw new DeviceProtocolError("Expected policy");
969
- return freeze({ ...base, ownerCeiling: parseOwnerCeilingReport(o.ownerCeiling) });
970
- }
971
- if (o.type === "res" && o.ok === false) {
972
- if (from !== "device")
973
- throw new DeviceProtocolError("Response must come from device");
974
- keys(o, ["type", "id", "ok", "error"]);
975
- const e = object(o.error);
976
- keys(e, ["kind", "message"]);
977
- if (![
978
- "gone",
979
- "fs_gone",
980
- "policy",
981
- "error",
982
- "denied",
983
- "unsupported",
984
- "unsettled",
985
- "unknown",
986
- "invalid",
987
- ].includes(String(e.kind)))
988
- throw new DeviceProtocolError("Unknown outcome kind");
989
- return freeze({
990
- type: "res",
991
- id: string(o.id),
992
- ok: false,
993
- error: {
994
- kind: e.kind,
995
- message: string(e.message, 8192),
996
- },
997
- });
812
+ switch (kind) {
813
+ case "hello":
814
+ return helloBody(copy);
815
+ case "req":
816
+ return requestBody(copy);
817
+ case "res":
818
+ return responseBody(copy);
819
+ case "event":
820
+ return eventBody(copy);
821
+ default:
822
+ throw new DeviceProtocolError(`Unknown body kind ${String(kind)}`);
998
823
  }
999
- const base = parseLegacyDeviceFrame(raw, from);
1000
- if (base.type === "hello" || base.type === "req" || base.type === "policy")
1001
- throw new DeviceProtocolError("Expected staged frame");
1002
- return freeze(base);
1003
824
  }
1004
825
  export function parseOperationResult(op, result, request) {
1005
826
  if (op === "bindInstance") {
@@ -1088,30 +909,14 @@ export function parseOperationResult(op, result, request) {
1088
909
  throw new DeviceProtocolError("Invalid stopped execution status");
1089
910
  return freeze(o);
1090
911
  }
1091
- if (op === "policy") {
1092
- const o = object(result);
1093
- keys(o, ["policy", "ownerCeiling"]);
1094
- return freeze({
1095
- ...parseOpResult("policy", { policy: o.policy }),
1096
- ownerCeiling: parseOwnerCeilingReport(o.ownerCeiling),
1097
- });
1098
- }
1099
- if (op === "policyStatus") {
1100
- const o = object(result);
1101
- keys(o, ["outcome", "policy", "message", "ownerCeiling"]);
1102
- const { ownerCeiling, ...rest } = o;
1103
- const status = parseOpResult("policyStatus", rest);
1104
- if (status.outcome === "applied" && ownerCeiling === undefined)
1105
- throw new DeviceProtocolError("An applied policy status carries the owner report");
1106
- if (ownerCeiling !== undefined)
1107
- status.ownerCeiling = parseOwnerCeilingReport(ownerCeiling);
1108
- return freeze(status);
1109
- }
1110
912
  if (op === "revokeOperation") {
1111
913
  if (result !== null)
1112
914
  throw new DeviceProtocolError("Revoke result must be null");
1113
915
  return null;
1114
916
  }
1115
917
  const raw = op.startsWith("prepare") ? op.slice(7) : op.startsWith("browse") ? op.slice(6) : op;
1116
- return parseOpResult((raw.charAt(0).toLowerCase() + raw.slice(1)), result);
918
+ const native = raw.charAt(0).toLowerCase() + raw.slice(1);
919
+ if (!natives.includes(native) && !lifecycle.includes(native))
920
+ throw new DeviceProtocolError(`Unknown operation ${op}`);
921
+ return parseOpResult(native, result);
1117
922
  }
@@ -9,6 +9,7 @@
9
9
  * (`create`) attach to it and come and go (`destroy` drops the instance and keeps the files).
10
10
  */
11
11
  import type { SandboxBackground, SandboxBrowse, SandboxBrowseScope, SandboxOperation, SandboxOperationRef, SandboxOperationScope, SandboxPermissionSupport, SandboxPreparation, SandboxPreparationScope } from "./device-operation.js";
12
+ import type { DialInHandler } from "./dial-in.js";
12
13
  /** Device provider extension point ref. */
13
14
  export declare const DEVICE_PROVIDER_EXTENSION_POINT = "device-provider@1";
14
15
  /** The roots inside the sandbox the model may access. */
@@ -255,6 +256,11 @@ export interface DeviceProvider {
255
256
  * {@link parseDeviceReport}. Must respond to `signal`.
256
257
  */
257
258
  report(device: DeviceRef, signal: AbortSignal): Promise<DeviceReport>;
259
+ /**
260
+ * The dial-in side of the provider, for an extension declaring `permissions.dialIn`: the kernel
261
+ * hands it the hellos and unsolicited frames of the machines serving its devices.
262
+ */
263
+ readonly dialIn?: DialInHandler;
258
264
  /**
259
265
  * Whether the provider isolates the sessions of one device from each other inside the
260
266
  * instance (a declared capability; absent means false).
@@ -424,6 +430,11 @@ export interface DeviceProvider {
424
430
  suggestedName: string;
425
431
  }[]>;
426
432
  }
433
+ /**
434
+ * The most entries a `list` may ask for and its result may carry ({@link DeviceProvider.list}):
435
+ * part of the provider contract, which the device protocol's `list` op also honors.
436
+ */
437
+ export declare const MAX_DEVICE_LIST_ENTRIES = 1000;
427
438
  /** The longest project name, in UTF-16 code units. */
428
439
  export declare const MAX_DEVICE_PROJECT_NAME_LENGTH = 64;
429
440
  /** The most candidates a `scan` answers ({@link DeviceProvider.scan}). */
@@ -156,6 +156,11 @@ export function isProjectPathRefusedError(e) {
156
156
  }
157
157
  // biome-ignore lint/suspicious/noControlCharactersInRegex: control characters are exactly what must be blocked
158
158
  const CONTROL = /[\u0000-\u001f\u007f]/;
159
+ /**
160
+ * The most entries a `list` may ask for and its result may carry ({@link DeviceProvider.list}):
161
+ * part of the provider contract, which the device protocol's `list` op also honors.
162
+ */
163
+ export const MAX_DEVICE_LIST_ENTRIES = 1000;
159
164
  /** The longest project name, in UTF-16 code units. */
160
165
  export const MAX_DEVICE_PROJECT_NAME_LENGTH = 64;
161
166
  /** The most candidates a `scan` answers ({@link DeviceProvider.scan}). */