@capybara-hq/plugin-sdk 0.1.0-rc.34 → 0.1.0-rc.36

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,407 @@ 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" &&
760
+ (typeof a.dataB64 !== "string" ||
761
+ !/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(a.dataB64)))
762
+ throw new DeviceProtocolError("Invalid base64 payload");
763
+ }
764
+ return freeze({ type: "req", id, op: op, args: a, deadlineMs });
765
+ }
766
+ /** Strictly parses one protocol 3 frame; throws {@link DeviceProtocolError}. */
767
+ export function parseDeviceFrame(raw, from, maxFrameBytes) {
768
+ if (maxFrameBytes !== undefined &&
769
+ new TextEncoder().encode(raw).byteLength > integer(maxFrameBytes, 1))
770
+ throw new DeviceProtocolError("Frame exceeds negotiated capacity; check device and deployment frame limits");
771
+ let parsed;
772
+ try {
773
+ parsed = JSON.parse(raw);
774
+ }
775
+ catch {
776
+ throw new DeviceProtocolError("Frame is not valid JSON");
777
+ }
778
+ const o = object(parsed);
779
+ if (o.type === "ready") {
780
+ if (from !== "kernel")
781
+ throw new DeviceProtocolError("Ready must come from kernel");
782
+ keys(o, ["type", "connectionId", "maxFrameBytes"]);
783
+ return freeze({
784
+ type: "ready",
785
+ connectionId: string(o.connectionId),
786
+ maxFrameBytes: integer(o.maxFrameBytes, 1024),
787
+ });
788
+ }
789
+ if (o.type === "req") {
790
+ if (from !== "kernel")
791
+ throw new DeviceProtocolError("Request must come from kernel");
792
+ return request(o);
793
+ }
794
+ if (o.type === "hello") {
795
+ if (from !== "device" || o.protocol !== 3)
796
+ throw new DeviceProtocolError("Expected protocol 3 hello");
797
+ const transport = object(o.transport);
798
+ keys(transport, ["maxFrameBytes"]);
799
+ const maxFrameBytes = integer(transport.maxFrameBytes, 1024);
800
+ const permissionSupport = support(o.permissionSupport);
801
+ if (o.instanceGeneration === null &&
802
+ (o.runtimeIdentity !== undefined ||
803
+ permissionSupport.restricted !== null ||
804
+ permissionSupport.fullAccess ||
805
+ permissionSupport.background ||
806
+ !permissionSupport.unavailableReason))
807
+ throw new DeviceProtocolError("Unbound hello cannot advertise runtime capability");
808
+ const base = parseLegacyDeviceFrame(raw, from);
809
+ if (base.type !== "hello")
810
+ throw new DeviceProtocolError("Expected hello");
811
+ let runtimeIdentity;
812
+ if (o.runtimeIdentity !== undefined) {
813
+ runtimeIdentity = identity(o.runtimeIdentity);
814
+ if (runtimeIdentity.instanceGeneration !== string(o.instanceGeneration))
815
+ throw new DeviceProtocolError("Runtime identity generation mismatch");
816
+ }
817
+ return freeze({
818
+ ...base,
819
+ protocol: 3,
820
+ permissionSupport,
821
+ transport: { maxFrameBytes },
822
+ ownerCeiling: owner(o.ownerCeiling),
823
+ instanceGeneration: o.instanceGeneration === null ? null : string(o.instanceGeneration),
824
+ ...(runtimeIdentity && { runtimeIdentity }),
825
+ });
826
+ }
827
+ if (o.type === "policy") {
828
+ if (from !== "device")
829
+ throw new DeviceProtocolError("Policy must come from device");
830
+ keys(o, ["type", "policy", "ownerCeiling"]);
831
+ const base = parseLegacyDeviceFrame(JSON.stringify({ type: "policy", policy: o.policy }), from);
832
+ if (base.type !== "policy")
833
+ throw new DeviceProtocolError("Expected policy");
834
+ return freeze({ ...base, ownerCeiling: owner(o.ownerCeiling) });
835
+ }
836
+ if (o.type === "res" && o.ok === false) {
837
+ if (from !== "device")
838
+ throw new DeviceProtocolError("Response must come from device");
839
+ keys(o, ["type", "id", "ok", "error"]);
840
+ const e = object(o.error);
841
+ keys(e, ["kind", "message"]);
842
+ if (!["gone", "fs_gone", "policy", "error", "denied", "unsupported", "unknown"].includes(String(e.kind)))
843
+ throw new DeviceProtocolError("Unknown outcome kind");
844
+ return freeze({
845
+ type: "res",
846
+ id: string(o.id),
847
+ ok: false,
848
+ error: {
849
+ kind: e.kind,
850
+ message: string(e.message, 8192),
851
+ },
852
+ });
853
+ }
854
+ const base = parseLegacyDeviceFrame(raw, from);
855
+ if (base.type === "hello" || base.type === "req" || base.type === "policy")
856
+ throw new DeviceProtocolError("Expected staged frame");
857
+ return freeze(base);
858
+ }
859
+ export function parseOperationResult(op, result, request) {
860
+ if (op === "bindInstance") {
861
+ if (!request || !("bindingId" in request))
862
+ throw new DeviceProtocolError("Binding validation requires the exact request");
863
+ const o = object(result);
864
+ keys(o, [
865
+ "instanceId",
866
+ "instanceGeneration",
867
+ "bindingId",
868
+ "runtimeIdentity",
869
+ "permissionSupport",
870
+ "ownerCeiling",
871
+ ]);
872
+ const runtimeIdentity = identity(o.runtimeIdentity);
873
+ if (o.instanceId !== request.instanceId ||
874
+ o.instanceGeneration !== request.instanceGeneration ||
875
+ o.bindingId !== request.bindingId ||
876
+ runtimeIdentity.instanceGeneration !== request.instanceGeneration)
877
+ throw new DeviceProtocolError("Binding answer belongs to another instance generation");
878
+ return freeze({
879
+ instanceId: request.instanceId,
880
+ instanceGeneration: request.instanceGeneration,
881
+ bindingId: request.bindingId,
882
+ runtimeIdentity,
883
+ permissionSupport: support(o.permissionSupport),
884
+ ownerCeiling: owner(o.ownerCeiling),
885
+ });
886
+ }
887
+ if (op === "backgroundReadOutput") {
888
+ if (!request || !("offset" in request))
889
+ throw new DeviceProtocolError("Output validation requires the exact request bounds");
890
+ const offset = integer(request.offset), maxBytes = integer(request.maxBytes, 0, 65536);
891
+ const o = object(result);
892
+ if ("unavailable" in o) {
893
+ keys(o, ["unavailable"]);
894
+ if (o.unavailable !== "lost" && o.unavailable !== "expired")
895
+ throw new DeviceProtocolError("Invalid output outcome");
896
+ return freeze(o);
897
+ }
898
+ keys(o, ["dataB64", "offset", "nextOffset", "totalBytes"]);
899
+ const total = integer(o.totalBytes), next = integer(o.nextOffset);
900
+ if (integer(o.offset) !== offset ||
901
+ typeof o.dataB64 !== "string" ||
902
+ o.dataB64.length > 87384 ||
903
+ !/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(o.dataB64))
904
+ throw new DeviceProtocolError("Invalid output range or base64");
905
+ const decoded = atob(o.dataB64);
906
+ if (btoa(decoded) !== o.dataB64 ||
907
+ decoded.length !== Math.min(maxBytes, Math.max(total - offset, 0)) ||
908
+ !Number.isSafeInteger(offset + decoded.length) ||
909
+ next !== offset + decoded.length)
910
+ throw new DeviceProtocolError("Inconsistent output range; retry from the same offset");
911
+ return freeze(o);
912
+ }
913
+ if (op === "backgroundStart")
914
+ return parseSandboxExecutionRef(result);
915
+ if (op === "backgroundStatus") {
916
+ const o = object(result);
917
+ keys(o, ["state", "exitCode", "timedOut"]);
918
+ if (o.state === "running" || o.state === "lost")
919
+ return freeze({ state: o.state });
920
+ if (o.state !== "exited" ||
921
+ (o.exitCode !== null && !Number.isInteger(o.exitCode)) ||
922
+ typeof o.timedOut !== "boolean")
923
+ throw new DeviceProtocolError("Invalid execution status");
924
+ return freeze(o);
925
+ }
926
+ if (op === "backgroundTail") {
927
+ if (result && typeof result === "object" && "unavailable" in result) {
928
+ const o = object(result);
929
+ keys(o, ["unavailable"]);
930
+ if (o.unavailable !== "lost" && o.unavailable !== "expired")
931
+ throw new DeviceProtocolError("Invalid output outcome");
932
+ return freeze(o);
933
+ }
934
+ return parseOpResult("readFile", result);
935
+ }
936
+ if (op === "backgroundStop") {
937
+ const o = object(result);
938
+ keys(o, ["outcome", "exitCode", "timedOut"]);
939
+ if (!["already-exited", "stopped", "cancel-pending", "lost"].includes(String(o.outcome)))
940
+ throw new DeviceProtocolError("Invalid stop outcome");
941
+ if (o.outcome === "already-exited" &&
942
+ ((o.exitCode !== null && !Number.isInteger(o.exitCode)) || typeof o.timedOut !== "boolean"))
943
+ throw new DeviceProtocolError("Invalid stopped execution status");
944
+ return freeze(o);
945
+ }
946
+ if (op === "policy") {
947
+ const o = object(result);
948
+ keys(o, ["policy", "ownerCeiling"]);
949
+ return freeze({
950
+ ...parseOpResult("policy", { policy: o.policy }),
951
+ ownerCeiling: owner(o.ownerCeiling),
952
+ });
953
+ }
954
+ if (op === "policyStatus") {
955
+ const o = object(result);
956
+ keys(o, ["outcome", "policy", "message", "ownerCeiling"]);
957
+ const { ownerCeiling, ...rest } = o;
958
+ const status = parseOpResult("policyStatus", rest);
959
+ if (status.outcome === "applied" && ownerCeiling === undefined)
960
+ throw new DeviceProtocolError("An applied policy status carries the owner report");
961
+ if (ownerCeiling !== undefined)
962
+ status.ownerCeiling = owner(ownerCeiling);
963
+ return freeze(status);
964
+ }
965
+ if (op === "revokeOperation") {
966
+ if (result !== null)
967
+ throw new DeviceProtocolError("Revoke result must be null");
968
+ return null;
969
+ }
970
+ const raw = op.startsWith("prepare") ? op.slice(7) : op.startsWith("browse") ? op.slice(6) : op;
971
+ return parseOpResult((raw.charAt(0).toLowerCase() + raw.slice(1)), result);
972
+ }
package/dist/hooks.d.ts CHANGED
@@ -39,9 +39,11 @@ export interface HookScope {
39
39
  * that writes a conversation's title after its first completed run (no run: `runId` is "", `step` 0,
40
40
  * `attempt` 1), `web_fetch` is the call that extracts an answer from a fetched web page for the
41
41
  * `WebFetch` tool, `review` is the command-review classifier's call (`review` purpose, no run
42
- * step; absent = no classifier).
42
+ * step; absent = no classifier), `suggestion` is the prompt suggestion side request after a
43
+ * completed web run (`runId` the run, `step` 0, `attempt` 1; a denial skips it and is recorded only
44
+ * in the audit log).
43
45
  */
44
- export type ModelCallPurpose = "step" | "compaction" | "title" | "web_fetch" | "review" | "image";
46
+ export type ModelCallPurpose = "step" | "compaction" | "title" | "web_fetch" | "review" | "image" | "suggestion";
45
47
  /**
46
48
  * What a reported or requested model call was for: the {@link ModelCallPurpose} values, or
47
49
  * `embedding` for an embedding call an extension made through `ctx.models` (`usage.report`, and
@@ -86,8 +88,10 @@ export type HookModelRequest = Omit<ModelRequest, "messages"> & {
86
88
  * `model.request` of a chat model call (see {@link ModelRequestHookPayload}): once per attempt of a
87
89
  * step (`purpose: "step"`), once for each compaction call (`purpose: "compaction"`, `attempt` 1),
88
90
  * once for each conversation title call (`purpose: "title"`, `runId` "", `step` 0, `attempt` 1; a
89
- * denial skips the title and is recorded only in the audit log) and once for each `WebFetch`
90
- * extraction call (`purpose: "web_fetch"`).
91
+ * denial skips the title and is recorded only in the audit log), once for each `WebFetch`
92
+ * extraction call (`purpose: "web_fetch"`) and once for each prompt suggestion call
93
+ * (`purpose: "suggestion"`, `step` 0, `attempt` 1; a denial skips the suggestion and is recorded
94
+ * only in the audit log).
91
95
  * `request` is the request as sent, except that images and documents are placeholders
92
96
  * ({@link HookMediaPlaceholder}): no media bytes, no attachment ids.
93
97
  */
@@ -198,10 +202,11 @@ export interface ImageResponseHookPayload {
198
202
  export type ModelRequestHookPayload = ModelCallRequestHookPayload | EmbeddingRequestHookPayload | ImageRequestHookPayload;
199
203
  /**
200
204
  * `model.response`: after a sent model call finished or failed, with its usage when known (step
201
- * attempts, compaction and title calls, see `purpose`). Not fired for a call the user aborted (the run was
202
- * stopped while the call was in flight), nor for a call that was never sent (denied, or failed
203
- * before sending), so a `model.request` can have no matching `model.response`. The mount's payload
204
- * is this or, for an image generation call, an {@link ImageResponseHookPayload}.
205
+ * attempts, compaction, title and suggestion calls, see `purpose`). Not fired for a call the user
206
+ * aborted (the run was stopped while the call was in flight), nor for a call that was never sent
207
+ * (denied, or failed before sending), so a `model.request` can have no matching `model.response`.
208
+ * The mount's payload is this or, for an image generation call, an
209
+ * {@link ImageResponseHookPayload}.
205
210
  */
206
211
  export interface ModelResponseHookPayload extends HookScope {
207
212
  purpose: Exclude<ModelCallPurpose, "image">;
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- export declare const SDK_VERSION = "0.1.0-rc.34";
1
+ export declare const SDK_VERSION = "0.1.0-rc.36";
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.34";
1
+ export const SDK_VERSION = "0.1.0-rc.36";
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
@@ -255,9 +255,10 @@ export interface ModelRequest {
255
255
  */
256
256
  params: Record<string, ParamValue>;
257
257
  /**
258
- * What this call is for, when the kernel says so: `"compaction"` for a conversation summary call.
259
- * Absent on ordinary step calls. Informational (a scripted test model keys on it); real providers
260
- * ignore it and must not forward it to a vendor API.
258
+ * What this call is for, when the kernel says so: `"compaction"` for a conversation summary call,
259
+ * `"suggestion"` for a prompt suggestion call. Absent on ordinary step calls. Informational (a
260
+ * scripted test model keys on it); real providers ignore it and must not forward it to a vendor
261
+ * API.
261
262
  */
262
263
  purpose?: ModelCallPurpose;
263
264
  }
@@ -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.34",
3
+ "version": "0.1.0-rc.36",
4
4
  "description": "Capybara plugin SDK: the types and pure functions plugins are written against",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {