@capybara-hq/plugin-sdk 0.1.0-rc.35 → 0.1.0-rc.37

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.
@@ -1,10 +1,21 @@
1
1
  /**
2
- * Device protocol v2: 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
+ * Protocol 3 (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 protocol 3 name replaced them
7
+ * (`LegacyDeviceHello`, `parseLegacyDeviceFrame`, ...); protocol 3 reuses their value guards, and
8
+ * they go with the legacy device surface.
4
9
  */
5
10
  import { isDeviceProjectName, MAX_DEVICE_PROJECT_NAME_LENGTH, MAX_DEVICE_SCAN_DEPTH, MAX_DEVICE_SCAN_RESULTS, validateAllowHost, validateSandboxPathShape, } from "./sandbox.js";
11
+ import { parseSandboxBrowseScope, parseSandboxExecutionRef, parseSandboxOperationRef, parseSandboxOperationScope, parseSandboxPreparationScope, } from "./sandbox-operation.js";
6
12
  /** The protocol version carried in `X-Capybara-Device-Protocol` and the hello frame. */
7
- export const DEVICE_PROTOCOL_VERSION = 2;
13
+ export const DEVICE_PROTOCOL_VERSION = 3;
14
+ /**
15
+ * Protocol 2's version, which a deployment speaking {@link DEVICE_PROTOCOL_VERSION} refuses (426
16
+ * on the header, a protocol close on the hello). Kept only for the legacy device surface.
17
+ */
18
+ export const LEGACY_DEVICE_PROTOCOL_VERSION = 2;
8
19
  const DEVICE_OPS = [
9
20
  "create",
10
21
  "exec",
@@ -28,16 +39,6 @@ const DEVICE_FEATURES = [
28
39
  ];
29
40
  /** The most entries a `list` op may ask for and its result may carry. */
30
41
  export const MAX_DEVICE_LIST_ENTRIES = 1000;
31
- /**
32
- * The first line of the kernel's background task launch command (`Bash` `run_in_background`), a
33
- * shell comment. A device kills what a foreground exec leaves running once the exec ends; an exec
34
- * whose command starts with this line detaches a task on purpose, and its processes are left alone.
35
- */
36
- export const BACKGROUND_LAUNCH_LINE = "# capybara: background task launch";
37
- /** Whether an exec's command is a background task launch ({@link BACKGROUND_LAUNCH_LINE}). */
38
- export function isBackgroundLaunch(command) {
39
- return command === BACKGROUND_LAUNCH_LINE || command.startsWith(`${BACKGROUND_LAUNCH_LINE}\n`);
40
- }
41
42
  /** The most blocked hosts an exec result reports; the parser cuts longer lists. */
42
43
  export const MAX_NETWORK_BLOCKED_HOSTS = 20;
43
44
  /** The most hosts a `policy` op's `add` / `remove` or an exec's `grants` may carry. */
@@ -48,7 +49,7 @@ export const MAX_POLICY_OP_ID_LENGTH = 128;
48
49
  export const MAX_RECENT_POLICY_OPS = 100;
49
50
  /** A hello's `bootId`: 1 to 128 characters of letters, digits, `.`, `_`, `:` and `-`. */
50
51
  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
+ /** Whether `v` is a well-formed {@link LegacyDeviceHello.bootId}. */
52
53
  export function isDeviceBootId(v) {
53
54
  return typeof v === "string" && DEVICE_BOOT_ID_RE.test(v);
54
55
  }
@@ -536,7 +537,7 @@ export function parseOpResult(op, result) {
536
537
  * kernel `req` and `cancel`. Throws {@link DeviceProtocolError} on bad JSON, an unknown `type`,
537
538
  * missing fields or a frame of the wrong direction.
538
539
  */
539
- export function parseDeviceFrame(raw, from) {
540
+ export function parseLegacyDeviceFrame(raw, from) {
540
541
  let o;
541
542
  try {
542
543
  o = JSON.parse(raw);
@@ -565,3 +566,425 @@ export function parseDeviceFrame(raw, from) {
565
566
  throw new DeviceProtocolError(`unknown frame type "${String(type)}"`);
566
567
  }
567
568
  }
569
+ const object = (value) => {
570
+ if (!value || typeof value !== "object" || Array.isArray(value))
571
+ throw new DeviceProtocolError("Expected an object");
572
+ return value;
573
+ };
574
+ function keys(value, allowed) {
575
+ for (const key of Object.keys(value))
576
+ if (!allowed.includes(key))
577
+ throw new DeviceProtocolError(`Unknown field ${key}`);
578
+ }
579
+ function string(value, max = 128) {
580
+ if (typeof value !== "string" || !value.length || value.length > max)
581
+ throw new DeviceProtocolError("Expected a bounded nonempty string");
582
+ return value;
583
+ }
584
+ function integer(value, min = 0, max = Number.MAX_SAFE_INTEGER) {
585
+ if (typeof value !== "number" || !Number.isSafeInteger(value) || value < min || value > max)
586
+ throw new DeviceProtocolError("Expected a bounded integer");
587
+ return value;
588
+ }
589
+ function path(value) {
590
+ if (typeof value !== "string" || validateSandboxPathShape(value).length)
591
+ throw new DeviceProtocolError("Expected an absolute filesystem path");
592
+ }
593
+ function freeze(value) {
594
+ if (value !== null && typeof value === "object") {
595
+ for (const v of Object.values(value))
596
+ freeze(v);
597
+ Object.freeze(value);
598
+ }
599
+ return value;
600
+ }
601
+ function support(value) {
602
+ const o = object(value);
603
+ keys(o, ["version", "restricted", "fullAccess", "background", "unavailableReason"]);
604
+ if (o.version !== 1 || typeof o.fullAccess !== "boolean" || typeof o.background !== "boolean")
605
+ throw new DeviceProtocolError("Invalid runtime permission report");
606
+ if (o.restricted !== null) {
607
+ const r = object(o.restricted);
608
+ keys(r, ["filesystem", "network", "native", "concurrentScopes"]);
609
+ for (const k of ["filesystem", "network", "native", "concurrentScopes"])
610
+ if (r[k] !== true)
611
+ throw new DeviceProtocolError("Incomplete restricted runtime report");
612
+ }
613
+ if (o.unavailableReason !== undefined)
614
+ string(o.unavailableReason, 4096);
615
+ return o;
616
+ }
617
+ /** Strictly parses one authenticated owner-ceiling report (B2); throws {@link DeviceProtocolError}. */
618
+ export function parseOwnerCeilingReport(value) {
619
+ return freeze(structuredClone(owner(value)));
620
+ }
621
+ function narrowing(value) {
622
+ const o = object(value);
623
+ keys(o, ["fullAccess", "restrictedProjectReach"]);
624
+ if ((o.fullAccess !== undefined && o.fullAccess !== false) ||
625
+ (o.restrictedProjectReach !== undefined && o.restrictedProjectReach !== "workspace"))
626
+ throw new DeviceProtocolError("The deployment may only narrow the owner ceiling");
627
+ return o;
628
+ }
629
+ function owner(value) {
630
+ const o = object(value);
631
+ keys(o, [
632
+ "version",
633
+ "sequence",
634
+ "revision",
635
+ "fullAccess",
636
+ "restrictedProjectReach",
637
+ "restrictedAllowedDomains",
638
+ ]);
639
+ integer(o.sequence);
640
+ if (o.version !== 2 || !["workspace", "os-user"].includes(String(o.restrictedProjectReach)))
641
+ throw new DeviceProtocolError("Invalid owner ceiling report version or project reach");
642
+ string(o.revision, 512);
643
+ if (typeof o.fullAccess !== "boolean" ||
644
+ !Array.isArray(o.restrictedAllowedDomains) ||
645
+ o.restrictedAllowedDomains.length > 100 ||
646
+ o.restrictedAllowedDomains.some((h) => typeof h !== "string" || validateAllowHost(h).length))
647
+ throw new DeviceProtocolError("Invalid owner ceiling");
648
+ return o;
649
+ }
650
+ const GENERATION = /^[0-9]{1,16}$/;
651
+ const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
652
+ function generation(value) {
653
+ if (typeof value !== "string" || !GENERATION.test(value))
654
+ throw new DeviceProtocolError("Expected an instance generation");
655
+ return value;
656
+ }
657
+ function bindRequest(a) {
658
+ string(a.instanceId);
659
+ generation(a.instanceGeneration);
660
+ if (typeof a.bindingId !== "string" || !UUID.test(a.bindingId))
661
+ throw new DeviceProtocolError("Expected a binding id");
662
+ if (a.expectedPreviousGeneration !== null) {
663
+ generation(a.expectedPreviousGeneration);
664
+ if (BigInt(a.expectedPreviousGeneration) >= BigInt(a.instanceGeneration))
665
+ throw new DeviceProtocolError("Previous generation must precede the bound generation");
666
+ }
667
+ return a;
668
+ }
669
+ function identity(value) {
670
+ const o = object(value);
671
+ keys(o, ["runtimeHash", "helperHash", "imageFingerprint", "instanceGeneration"]);
672
+ for (const key of ["runtimeHash", "helperHash", "imageFingerprint"])
673
+ if (typeof o[key] !== "string" || !/^[a-f0-9]{64}$/.test(o[key]))
674
+ throw new DeviceProtocolError("Incomplete runtime identity");
675
+ string(o.instanceGeneration);
676
+ return o;
677
+ }
678
+ const natives = ["exec", "readFile", "writeFile", "stat", "list", "scan"];
679
+ const legacy = ["create", "stop", "policy", "policyStatus"];
680
+ function request(o) {
681
+ keys(o, ["type", "id", "op", "args", "deadlineMs"]);
682
+ const id = string(o.id), op = string(o.op), a = object(o.args), deadlineMs = integer(o.deadlineMs, 1);
683
+ if (legacy.includes(op)) {
684
+ if (op === "policy" && a.ownerCeiling !== undefined)
685
+ narrowing(a.ownerCeiling);
686
+ const parsed = parseLegacyDeviceFrame(JSON.stringify(o), "kernel");
687
+ if (parsed.type !== "req")
688
+ throw new DeviceProtocolError("Expected request");
689
+ return freeze({ ...parsed, op: op, args: object(parsed.args) });
690
+ }
691
+ if (op === "bindInstance") {
692
+ keys(a, ["instanceId", "instanceGeneration", "bindingId", "expectedPreviousGeneration"]);
693
+ bindRequest(a);
694
+ }
695
+ else if (op === "revokeOperation") {
696
+ keys(a, ["ref"]);
697
+ a.ref = parseSandboxOperationRef(a.ref);
698
+ }
699
+ else if (["backgroundStatus", "backgroundTail", "backgroundReadOutput", "backgroundStop"].includes(op)) {
700
+ keys(a, [
701
+ "ref",
702
+ ...(op === "backgroundReadOutput" ? ["offset", "maxBytes"] : []),
703
+ ...(op === "backgroundTail" ? ["maxBytes"] : op === "backgroundStop" ? ["graceMs"] : []),
704
+ ]);
705
+ a.ref = parseSandboxExecutionRef(a.ref);
706
+ if (op === "backgroundTail" || op === "backgroundReadOutput")
707
+ integer(a.maxBytes, 0, 65536);
708
+ if (op === "backgroundReadOutput")
709
+ integer(a.offset);
710
+ if (op === "backgroundStop")
711
+ integer(a.graceMs, 0, 60000);
712
+ }
713
+ else {
714
+ const preparation = op.startsWith("prepare"), browsing = op.startsWith("browse"), background = op === "backgroundStart";
715
+ const method = background ? "exec" : preparation ? op.slice(7) : browsing ? op.slice(6) : op;
716
+ const native = method[0]?.toLowerCase() + method.slice(1);
717
+ if (!natives.includes(native) ||
718
+ (preparation && !["readFile", "writeFile", "stat"].includes(native)) ||
719
+ (browsing && !["stat", "list", "scan"].includes(native)))
720
+ throw new DeviceProtocolError("Unknown operation");
721
+ a.scope = preparation
722
+ ? parseSandboxPreparationScope(a.scope)
723
+ : browsing
724
+ ? parseSandboxBrowseScope(a.scope)
725
+ : parseSandboxOperationScope(a.scope);
726
+ const fields = native === "exec"
727
+ ? ["command", "cwd", "env", "timeoutMs", "maxOutputBytes", "limits", "grants"]
728
+ : native === "readFile"
729
+ ? ["path", "maxBytes"]
730
+ : native === "writeFile"
731
+ ? ["path", "dataB64"]
732
+ : native === "stat"
733
+ ? ["path"]
734
+ : native === "list"
735
+ ? ["path", "limit"]
736
+ : ["base"];
737
+ keys(a, ["scope", ...fields, ...(background ? ["taskId", "outputPath", "retainUntilMs"] : [])]);
738
+ if (native !== "exec")
739
+ path(a[native === "scan" ? "base" : "path"]);
740
+ const validated = { ...a };
741
+ delete validated.scope;
742
+ if (native === "exec") {
743
+ const scope = parseSandboxOperationScope(a.scope);
744
+ validated.tag = scope.tag;
745
+ validated.actor = scope.actor;
746
+ if (background) {
747
+ string(a.taskId);
748
+ path(a.outputPath);
749
+ integer(a.retainUntilMs, scope.admitBeforeMs);
750
+ delete validated.taskId;
751
+ delete validated.outputPath;
752
+ delete validated.retainUntilMs;
753
+ }
754
+ }
755
+ else if (native !== "writeFile")
756
+ validated.limits = { mode: "sandbox" };
757
+ // Reuse v2's pure value guards; inserted mode is never returned or used as authority.
758
+ parseLegacyDeviceFrame(JSON.stringify({ type: "req", id, op: native, args: validated, deadlineMs }), "kernel");
759
+ if (native === "writeFile" && (typeof a.dataB64 !== "string" || !isBase64(a.dataB64)))
760
+ throw new DeviceProtocolError("Invalid base64 payload");
761
+ }
762
+ return freeze({ type: "req", id, op: op, args: a, deadlineMs });
763
+ }
764
+ /**
765
+ * Padded standard base64: whole quartets of `A-Z a-z 0-9 + /`, the last one possibly ending in
766
+ * `=` or `==`. One linear pass: a regex with a repeated group exhausts the engine's backtracking
767
+ * stack on payloads of a few megabytes.
768
+ */
769
+ function isBase64(value) {
770
+ if (value.length % 4 !== 0)
771
+ return false;
772
+ const padding = value.endsWith("==") ? 2 : value.endsWith("=") ? 1 : 0;
773
+ for (let i = 0; i < value.length - padding; i++) {
774
+ const c = value.charCodeAt(i);
775
+ if (!((c >= 65 && c <= 90) ||
776
+ (c >= 97 && c <= 122) ||
777
+ (c >= 48 && c <= 57) ||
778
+ c === 43 ||
779
+ c === 47))
780
+ return false;
781
+ }
782
+ return true;
783
+ }
784
+ /** Strictly parses one protocol 3 frame; throws {@link DeviceProtocolError}. */
785
+ export function parseDeviceFrame(raw, from, maxFrameBytes) {
786
+ if (maxFrameBytes !== undefined &&
787
+ new TextEncoder().encode(raw).byteLength > integer(maxFrameBytes, 1))
788
+ throw new DeviceProtocolError("Frame exceeds negotiated capacity; check device and deployment frame limits");
789
+ let parsed;
790
+ try {
791
+ parsed = JSON.parse(raw);
792
+ }
793
+ catch {
794
+ throw new DeviceProtocolError("Frame is not valid JSON");
795
+ }
796
+ const o = object(parsed);
797
+ if (o.type === "ready") {
798
+ if (from !== "kernel")
799
+ throw new DeviceProtocolError("Ready must come from kernel");
800
+ keys(o, ["type", "connectionId", "maxFrameBytes"]);
801
+ return freeze({
802
+ type: "ready",
803
+ connectionId: string(o.connectionId),
804
+ maxFrameBytes: integer(o.maxFrameBytes, 1024),
805
+ });
806
+ }
807
+ if (o.type === "req") {
808
+ if (from !== "kernel")
809
+ throw new DeviceProtocolError("Request must come from kernel");
810
+ return request(o);
811
+ }
812
+ if (o.type === "hello") {
813
+ if (from !== "device" || o.protocol !== 3)
814
+ throw new DeviceProtocolError("Expected protocol 3 hello");
815
+ const transport = object(o.transport);
816
+ keys(transport, ["maxFrameBytes"]);
817
+ const maxFrameBytes = integer(transport.maxFrameBytes, 1024);
818
+ const permissionSupport = support(o.permissionSupport);
819
+ if (o.instanceGeneration === null &&
820
+ (o.runtimeIdentity !== undefined ||
821
+ permissionSupport.restricted !== null ||
822
+ permissionSupport.fullAccess ||
823
+ permissionSupport.background ||
824
+ !permissionSupport.unavailableReason))
825
+ throw new DeviceProtocolError("Unbound hello cannot advertise runtime capability");
826
+ const base = parseLegacyDeviceFrame(raw, from);
827
+ if (base.type !== "hello")
828
+ throw new DeviceProtocolError("Expected hello");
829
+ let runtimeIdentity;
830
+ if (o.runtimeIdentity !== undefined) {
831
+ runtimeIdentity = identity(o.runtimeIdentity);
832
+ if (runtimeIdentity.instanceGeneration !== string(o.instanceGeneration))
833
+ throw new DeviceProtocolError("Runtime identity generation mismatch");
834
+ }
835
+ return freeze({
836
+ ...base,
837
+ protocol: 3,
838
+ permissionSupport,
839
+ transport: { maxFrameBytes },
840
+ ownerCeiling: owner(o.ownerCeiling),
841
+ instanceGeneration: o.instanceGeneration === null ? null : string(o.instanceGeneration),
842
+ ...(runtimeIdentity && { runtimeIdentity }),
843
+ });
844
+ }
845
+ if (o.type === "policy") {
846
+ if (from !== "device")
847
+ throw new DeviceProtocolError("Policy must come from device");
848
+ keys(o, ["type", "policy", "ownerCeiling"]);
849
+ const base = parseLegacyDeviceFrame(JSON.stringify({ type: "policy", policy: o.policy }), from);
850
+ if (base.type !== "policy")
851
+ throw new DeviceProtocolError("Expected policy");
852
+ return freeze({ ...base, ownerCeiling: owner(o.ownerCeiling) });
853
+ }
854
+ if (o.type === "res" && o.ok === false) {
855
+ if (from !== "device")
856
+ throw new DeviceProtocolError("Response must come from device");
857
+ keys(o, ["type", "id", "ok", "error"]);
858
+ const e = object(o.error);
859
+ keys(e, ["kind", "message"]);
860
+ if (!["gone", "fs_gone", "policy", "error", "denied", "unsupported", "unknown"].includes(String(e.kind)))
861
+ throw new DeviceProtocolError("Unknown outcome kind");
862
+ return freeze({
863
+ type: "res",
864
+ id: string(o.id),
865
+ ok: false,
866
+ error: {
867
+ kind: e.kind,
868
+ message: string(e.message, 8192),
869
+ },
870
+ });
871
+ }
872
+ const base = parseLegacyDeviceFrame(raw, from);
873
+ if (base.type === "hello" || base.type === "req" || base.type === "policy")
874
+ throw new DeviceProtocolError("Expected staged frame");
875
+ return freeze(base);
876
+ }
877
+ export function parseOperationResult(op, result, request) {
878
+ if (op === "bindInstance") {
879
+ if (!request || !("bindingId" in request))
880
+ throw new DeviceProtocolError("Binding validation requires the exact request");
881
+ const o = object(result);
882
+ keys(o, [
883
+ "instanceId",
884
+ "instanceGeneration",
885
+ "bindingId",
886
+ "runtimeIdentity",
887
+ "permissionSupport",
888
+ "ownerCeiling",
889
+ ]);
890
+ const runtimeIdentity = identity(o.runtimeIdentity);
891
+ if (o.instanceId !== request.instanceId ||
892
+ o.instanceGeneration !== request.instanceGeneration ||
893
+ o.bindingId !== request.bindingId ||
894
+ runtimeIdentity.instanceGeneration !== request.instanceGeneration)
895
+ throw new DeviceProtocolError("Binding answer belongs to another instance generation");
896
+ return freeze({
897
+ instanceId: request.instanceId,
898
+ instanceGeneration: request.instanceGeneration,
899
+ bindingId: request.bindingId,
900
+ runtimeIdentity,
901
+ permissionSupport: support(o.permissionSupport),
902
+ ownerCeiling: owner(o.ownerCeiling),
903
+ });
904
+ }
905
+ if (op === "backgroundReadOutput") {
906
+ if (!request || !("offset" in request))
907
+ throw new DeviceProtocolError("Output validation requires the exact request bounds");
908
+ const offset = integer(request.offset), maxBytes = integer(request.maxBytes, 0, 65536);
909
+ const o = object(result);
910
+ if ("unavailable" in o) {
911
+ keys(o, ["unavailable"]);
912
+ if (o.unavailable !== "lost" && o.unavailable !== "expired")
913
+ throw new DeviceProtocolError("Invalid output outcome");
914
+ return freeze(o);
915
+ }
916
+ keys(o, ["dataB64", "offset", "nextOffset", "totalBytes"]);
917
+ const total = integer(o.totalBytes), next = integer(o.nextOffset);
918
+ if (integer(o.offset) !== offset ||
919
+ typeof o.dataB64 !== "string" ||
920
+ o.dataB64.length > 87384 ||
921
+ !isBase64(o.dataB64))
922
+ throw new DeviceProtocolError("Invalid output range or base64");
923
+ const decoded = atob(o.dataB64);
924
+ if (btoa(decoded) !== o.dataB64 ||
925
+ decoded.length !== Math.min(maxBytes, Math.max(total - offset, 0)) ||
926
+ !Number.isSafeInteger(offset + decoded.length) ||
927
+ next !== offset + decoded.length)
928
+ throw new DeviceProtocolError("Inconsistent output range; retry from the same offset");
929
+ return freeze(o);
930
+ }
931
+ if (op === "backgroundStart")
932
+ return parseSandboxExecutionRef(result);
933
+ if (op === "backgroundStatus") {
934
+ const o = object(result);
935
+ keys(o, ["state", "exitCode", "timedOut"]);
936
+ if (o.state === "running" || o.state === "lost")
937
+ return freeze({ state: o.state });
938
+ if (o.state !== "exited" ||
939
+ (o.exitCode !== null && !Number.isInteger(o.exitCode)) ||
940
+ typeof o.timedOut !== "boolean")
941
+ throw new DeviceProtocolError("Invalid execution status");
942
+ return freeze(o);
943
+ }
944
+ if (op === "backgroundTail") {
945
+ if (result && typeof result === "object" && "unavailable" in result) {
946
+ const o = object(result);
947
+ keys(o, ["unavailable"]);
948
+ if (o.unavailable !== "lost" && o.unavailable !== "expired")
949
+ throw new DeviceProtocolError("Invalid output outcome");
950
+ return freeze(o);
951
+ }
952
+ return parseOpResult("readFile", result);
953
+ }
954
+ if (op === "backgroundStop") {
955
+ const o = object(result);
956
+ keys(o, ["outcome", "exitCode", "timedOut"]);
957
+ if (!["already-exited", "stopped", "cancel-pending", "lost"].includes(String(o.outcome)))
958
+ throw new DeviceProtocolError("Invalid stop outcome");
959
+ if (o.outcome === "already-exited" &&
960
+ ((o.exitCode !== null && !Number.isInteger(o.exitCode)) || typeof o.timedOut !== "boolean"))
961
+ throw new DeviceProtocolError("Invalid stopped execution status");
962
+ return freeze(o);
963
+ }
964
+ if (op === "policy") {
965
+ const o = object(result);
966
+ keys(o, ["policy", "ownerCeiling"]);
967
+ return freeze({
968
+ ...parseOpResult("policy", { policy: o.policy }),
969
+ ownerCeiling: owner(o.ownerCeiling),
970
+ });
971
+ }
972
+ if (op === "policyStatus") {
973
+ const o = object(result);
974
+ keys(o, ["outcome", "policy", "message", "ownerCeiling"]);
975
+ const { ownerCeiling, ...rest } = o;
976
+ const status = parseOpResult("policyStatus", rest);
977
+ if (status.outcome === "applied" && ownerCeiling === undefined)
978
+ throw new DeviceProtocolError("An applied policy status carries the owner report");
979
+ if (ownerCeiling !== undefined)
980
+ status.ownerCeiling = owner(ownerCeiling);
981
+ return freeze(status);
982
+ }
983
+ if (op === "revokeOperation") {
984
+ if (result !== null)
985
+ throw new DeviceProtocolError("Revoke result must be null");
986
+ return null;
987
+ }
988
+ const raw = op.startsWith("prepare") ? op.slice(7) : op.startsWith("browse") ? op.slice(6) : op;
989
+ return parseOpResult((raw.charAt(0).toLowerCase() + raw.slice(1)), result);
990
+ }
package/dist/hooks.d.ts CHANGED
@@ -41,9 +41,10 @@ export interface HookScope {
41
41
  * `WebFetch` tool, `review` is the command-review classifier's call (`review` purpose, no run
42
42
  * step; absent = no classifier), `suggestion` is the prompt suggestion side request after a
43
43
  * completed web run (`runId` the run, `step` 0, `attempt` 1; a denial skips it and is recorded only
44
- * in the audit log).
44
+ * in the audit log), `vision` is the call that reads an image for a model without vision, made by
45
+ * the `Read` tool (also for a pasted image, read by its `file_id`; the `vision` purpose's model).
45
46
  */
46
- export type ModelCallPurpose = "step" | "compaction" | "title" | "web_fetch" | "review" | "image" | "suggestion";
47
+ export type ModelCallPurpose = "step" | "compaction" | "title" | "web_fetch" | "review" | "image" | "vision" | "suggestion";
47
48
  /**
48
49
  * What a reported or requested model call was for: the {@link ModelCallPurpose} values, or
49
50
  * `embedding` for an embedding call an extension made through `ctx.models` (`usage.report`, and
@@ -91,7 +92,7 @@ export type HookModelRequest = Omit<ModelRequest, "messages"> & {
91
92
  * denial skips the title and is recorded only in the audit log), once for each `WebFetch`
92
93
  * extraction call (`purpose: "web_fetch"`) and once for each prompt suggestion call
93
94
  * (`purpose: "suggestion"`, `step` 0, `attempt` 1; a denial skips the suggestion and is recorded
94
- * only in the audit log).
95
+ * only in the audit log) and once for each vision call (`purpose: "vision"`).
95
96
  * `request` is the request as sent, except that images and documents are placeholders
96
97
  * ({@link HookMediaPlaceholder}): no media bytes, no attachment ids.
97
98
  */
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- export declare const SDK_VERSION = "0.1.0-rc.35";
1
+ export declare const SDK_VERSION = "0.1.0-rc.37";
2
2
  export * from "./agent-template.js";
3
3
  export * from "./bootstrap.js";
4
4
  export * from "./cards.js";
@@ -11,8 +11,8 @@ export * from "./connector-auth.js";
11
11
  export * from "./context.js";
12
12
  export * from "./ctx.js";
13
13
  export * from "./define-extension.js";
14
+ export { DEVICE_DEFAULT_STATE_PATH, DEVICE_DENIED_SECRET_PATHS } from "./device-denied-paths.js";
14
15
  export * from "./device-protocol.js";
15
- export { type BackgroundReadOutputRequestV3, type BackgroundReadOutputResultV3, type BindInstanceRequestV3, type BindInstanceResultV3, type DeviceFrameV3, type DeviceHelloV3, type DeviceOperationV3, type DeviceOwnerCeilingNarrowingV3, type DeviceOwnerCeilingV3, type DevicePolicyArgsV3, type DevicePolicyChangedV3, type DevicePolicyResultV3, type DevicePolicyStatusV3, type DeviceResponseV3, type DeviceRuntimeIdentityV3, type KernelReadyV3, type KernelRequestV3, parseDeviceFrameV3, parseOperationResultV3, parseOwnerCeilingReportV3, STAGED_DEVICE_PROTOCOL_VERSION, } from "./device-protocol-v3.js";
16
16
  export * from "./directory.js";
17
17
  export * from "./extension-point.js";
18
18
  export * from "./file-preview.js";
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- export const SDK_VERSION = "0.1.0-rc.35";
1
+ export const SDK_VERSION = "0.1.0-rc.37";
2
2
  export * from "./agent-template.js";
3
3
  export * from "./bootstrap.js";
4
4
  export * from "./cards.js";
@@ -11,9 +11,8 @@ export * from "./connector-auth.js";
11
11
  export * from "./context.js";
12
12
  export * from "./ctx.js";
13
13
  export * from "./define-extension.js";
14
+ export { DEVICE_DEFAULT_STATE_PATH, DEVICE_DENIED_SECRET_PATHS } from "./device-denied-paths.js";
14
15
  export * from "./device-protocol.js";
15
- // Development staging: removed with the coordinated device protocol v3 activation.
16
- export { parseDeviceFrameV3, parseOperationResultV3, parseOwnerCeilingReportV3, STAGED_DEVICE_PROTOCOL_VERSION, } from "./device-protocol-v3.js";
17
16
  export * from "./directory.js";
18
17
  export * from "./extension-point.js";
19
18
  export * from "./file-preview.js";
package/dist/model.d.ts CHANGED
@@ -69,7 +69,7 @@ export interface ModelInfo {
69
69
  * Whether `document` blocks are accepted (default false). Images are governed by `vision`. When
70
70
  * the model does not support them the kernel replaces media blocks with English text
71
71
  * placeholders
72
- * (e.g. `[Attached image "<name>" — this model cannot view images.]`; `text/*` documents are
72
+ * (e.g. `[Attached image "<name>" — this model cannot view images. Read with file_id <id> sends it to the organization's vision model, if one is set.]`; `text/*` documents are
73
73
  * inlined as truncated text instead),
74
74
  * and never sends the bytes to it.
75
75
  */
@@ -179,11 +179,15 @@ export interface SandboxBackground {
179
179
  * Persist exact ownership before acknowledging; retries of the same generation/operation/input
180
180
  * return the same reference. Retain starting grants for the lifetime of the owned execution.
181
181
  * Validate outputPath inside the scope. retainUntilMs bounds status/output record retention.
182
+ * instanceGeneration is the kernel's generation of the held instance `h` (the kernel always
183
+ * passes it, and allocates it only after `create` returns): a provider that keeps no generation
184
+ * of its own (a cloud provider) returns it in the reference and keys start idempotency by it.
182
185
  */
183
186
  start(h: SandboxHandle, scope: SandboxOperationScope, args: SandboxExecOptions & {
184
187
  taskId: string;
185
188
  outputPath: string;
186
189
  retainUntilMs: number;
190
+ instanceGeneration?: string;
187
191
  }): Promise<SandboxExecutionRef>;
188
192
  status(h: SandboxHandle, ref: SandboxExecutionRef, signal: AbortSignal): Promise<SandboxExecutionStatus>;
189
193
  /** At most 65,536 bytes, preserving UTF-8 boundaries and existing final-line limits; no caller path. */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@capybara-hq/plugin-sdk",
3
- "version": "0.1.0-rc.35",
3
+ "version": "0.1.0-rc.37",
4
4
  "description": "Capybara plugin SDK: the types and pure functions plugins are written against",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {