@capybara-hq/plugin-sdk 0.1.0-rc.69 → 0.1.0-rc.70

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
@@ -1,4 +1,5 @@
1
1
  import type { Kysely } from "kysely";
2
+ import type { DeviceServiceSpec, DeviceServiceStatus } from "./device-provider.js";
2
3
  import type { DevicesCtx, DialInChannel } from "./dial-in.js";
3
4
  import type { ExtensionPointRef } from "./extension-point.js";
4
5
  import type { AvailableHook, HookHandler, HookOptions } from "./hooks.js";
@@ -7,7 +8,7 @@ import type { ImageAspectRatio, ImageMediaType, ImageSize, ModelEmbeddingInfo, M
7
8
  import type { ExtensionNet } from "./net.js";
8
9
  import type { SetupCheckDefinition } from "./setup-check.js";
9
10
  import type { ObjectHead, PresignedUpload, PresignGetOptions } from "./storage.js";
10
- import type { ToolHandler, ToolSpec } from "./tool.js";
11
+ import type { ToolCallContext, ToolHandler, ToolSpec } from "./tool.js";
11
12
  import type { EmbedClaims, UiActionArgs, UiActionResult, UiRenderArgs, UiView } from "./ui.js";
12
13
  /** Logger interface. */
13
14
  export interface Logger {
@@ -171,6 +172,77 @@ export interface ExtensionModels {
171
172
  purpose: string;
172
173
  }): Promise<ExtensionModelTarget | null>;
173
174
  }
175
+ /**
176
+ * The org, conversation and account a {@link DeviceAccessCtx} call from outside a tool call is for
177
+ * (`orgId` must be the conversation's org).
178
+ */
179
+ export type DeviceAccessScope = {
180
+ orgId: string;
181
+ conversationId: string;
182
+ accountId: string;
183
+ };
184
+ /**
185
+ * `ctx.deviceAccess` (requires `permissions.deviceAccess`): the extension's services in the
186
+ * conversation's device. Every call works on the device of the conversation it names (a tool
187
+ * call's, or `scope.conversationId`), only for a service listed in
188
+ * `permissions.deviceAccess.services`, and only when the account (the tool call's trigger account,
189
+ * or `scope.accountId`) is the conversation's owner. A refusal throws {@link DeviceAccessError}.
190
+ */
191
+ export interface DeviceAccessCtx {
192
+ /**
193
+ * Starts the service in the call's device, or finds it running: the kernel writes the spec's
194
+ * files into the service's state directory, passes the launch through the command review (fail
195
+ * closed) and starts it through the device's provider.
196
+ */
197
+ ensureService(call: ToolCallContext, spec: DeviceServiceSpec): Promise<DeviceServiceStatus>;
198
+ /** One request to the service's socket; resolves its answer. */
199
+ request(call: ToolCallContext, req: {
200
+ service: string;
201
+ body: Uint8Array;
202
+ timeoutMs: number;
203
+ }): Promise<Uint8Array>;
204
+ /**
205
+ * The service saw requests to `hosts` refused by the device's network allowlist during this
206
+ * call: the kernel raises the network ask in the call's conversation once the handler returns
207
+ * (and runs the call again once the person approves). Only an ask. `opts.url` is the page the
208
+ * refusals came from, shown with the ask.
209
+ */
210
+ reportBlockedHosts(call: ToolCallContext, hosts: string[], opts?: {
211
+ url?: string;
212
+ }): void;
213
+ /**
214
+ * A short-lived, single-use ticket for one viewer stream to the service (the person's panel
215
+ * opens `url` as a WebSocket). The account must be the conversation's owner.
216
+ */
217
+ streamTicket(scope: DeviceAccessScope & {
218
+ service: string;
219
+ }): Promise<{
220
+ url: string;
221
+ expiresAt: string;
222
+ }>;
223
+ /**
224
+ * Adds hosts to the device's network allowlist (owner only, platform and org ceilings apply);
225
+ * the extension's running services get the device's new limits applied. Exact host names
226
+ * only, as an approved network ask grants: a `*.` wildcard is refused.
227
+ */
228
+ addNetworkHosts(scope: DeviceAccessScope & {
229
+ hosts: string[];
230
+ }): Promise<void>;
231
+ /** Answers the handoff question of this extension's tool call `callId` from the panel. */
232
+ answerHandoff(scope: DeviceAccessScope & {
233
+ callId: string;
234
+ done: boolean;
235
+ }): Promise<void>;
236
+ }
237
+ /** Why a {@link DeviceAccessCtx} call was refused. */
238
+ export type DeviceAccessErrorCode = "no_device" | "provider_unavailable" | "capability_missing" | "not_owner" | "service_not_declared";
239
+ /** A {@link DeviceAccessCtx} call was refused; the message is actionable English for the model. */
240
+ export declare class DeviceAccessError extends Error {
241
+ readonly code: DeviceAccessErrorCode;
242
+ constructor(code: DeviceAccessErrorCode, message: string, opts?: {
243
+ cause?: unknown;
244
+ });
245
+ }
174
246
  /**
175
247
  * The context passed to a plugin's `setup`. It provides no timers or in-process shared state; kv
176
248
  * writes must carry a TTL.
@@ -322,6 +394,11 @@ export interface ExtensionContext {
322
394
  * `device-provider@1`, see {@link DevicesCtx}).
323
395
  */
324
396
  devices: DevicesCtx;
397
+ /**
398
+ * The extension's services in the conversation's device (requires `permissions.deviceAccess`,
399
+ * see {@link DeviceAccessCtx}).
400
+ */
401
+ deviceAccess: DeviceAccessCtx;
325
402
  provide(extensionPoint: ExtensionPointRef, impl: unknown): void;
326
403
  /**
327
404
  * The lifecycle signal of this plugin instance: aborted when the instance is revoked (disabled,
package/dist/ctx.js CHANGED
@@ -1 +1,9 @@
1
- export {};
1
+ /** A {@link DeviceAccessCtx} call was refused; the message is actionable English for the model. */
2
+ export class DeviceAccessError extends Error {
3
+ code;
4
+ constructor(code, message, opts) {
5
+ super(message, opts && "cause" in opts ? { cause: opts.cause } : undefined);
6
+ this.name = "DeviceAccessError";
7
+ this.code = code;
8
+ }
9
+ }
@@ -231,6 +231,81 @@ export declare class ProjectPathRefusedError extends Error {
231
231
  }
232
232
  /** Duck-typed check (not instanceof), so a plugin bundling another plugin-sdk copy still matches. */
233
233
  export declare function isProjectPathRefusedError(e: unknown): e is ProjectPathRefusedError;
234
+ /** A device service name: 1 to 32 characters, a lower-case letter then letters, digits and `-`. */
235
+ export declare const DEVICE_SERVICE_NAME_RE: RegExp;
236
+ /**
237
+ * A long-lived service process in a device ({@link DeviceProvider.ensureService}), started on an
238
+ * extension's behalf. It runs under the device's own sandbox (not under any one conversation's
239
+ * operation scope), writes only in its own state directory (outside every project root; `files`
240
+ * are written before start into its code directory, read only for the service where the provider
241
+ * can separate code from state, else the state directory), reaches the network through the
242
+ * device's network setting, and is killed with the instance on suspend and destroy. It speaks the service socket protocol
243
+ * (`device-service.ts`).
244
+ */
245
+ export interface DeviceServiceSpec {
246
+ /** One service per name per device; matches {@link DEVICE_SERVICE_NAME_RE}. */
247
+ name: string;
248
+ /** The provider supplies Node 22 or later. */
249
+ runtime: "node";
250
+ /**
251
+ * The script to run: one of the `files` keys. The process runs
252
+ * `node <codeDir ?? stateDir>/<entry>` (the code directory where the provider keeps code apart,
253
+ * else the state directory) with the state directory as its working directory; that exact command passes the command review.
254
+ */
255
+ entry: string;
256
+ args: string[];
257
+ /**
258
+ * Written into the service's code directory before start (read only for the service where the
259
+ * provider separates code from state, else the state directory), keyed by relative path: no
260
+ * absolute path, no `..` or `.` segment, no empty segment, no backslash, no NUL (the kernel
261
+ * refuses a spec that breaks this before any provider call).
262
+ */
263
+ files: Record<string, Uint8Array>;
264
+ /**
265
+ * Extra environment of the process (shown to the command review as `env K=V …`). The kernel
266
+ * refuses `NODE_*`, `PATH`, `SSL_CERT_FILE`, `SSL_CERT_DIR`, `OPENSSL_CONF`, `OPENSSL_ENGINES`,
267
+ * `LD_*`, `DYLD_*`, `CAPYBARA_*` and the proxy variables (`HTTP_PROXY`, `HTTPS_PROXY`,
268
+ * `NO_PROXY`, `ALL_PROXY`, `FTP_PROXY`), any case: they change what runs or what it trusts, or
269
+ * the provider sets them itself.
270
+ */
271
+ env?: Record<string, string>;
272
+ }
273
+ /** A device service's state ({@link DeviceProvider.ensureService}). */
274
+ export interface DeviceServiceStatus {
275
+ name: string;
276
+ state: "running" | "stopped";
277
+ /** ISO 8601 time the running process started; null when stopped. */
278
+ startedAt: string | null;
279
+ /**
280
+ * The service's state directory in the device (absolute), also when it is stopped: its working
281
+ * directory and write root (its `files` too, unless the provider keeps code apart). The kernel
282
+ * reviews the launch against it.
283
+ */
284
+ stateDir: string;
285
+ /**
286
+ * The directory the entry runs from (absolute), when the provider keeps the service's code
287
+ * apart from its state (read only for the service); absent: the state directory. Known before
288
+ * the first start like `stateDir`. The kernel's launch review shows
289
+ * `node <codeDir ?? stateDir>/<entry>`, so a provider runs exactly that.
290
+ */
291
+ codeDir?: string;
292
+ }
293
+ /**
294
+ * A message stream to a device service ({@link DeviceProvider.openStream},
295
+ * `DialInChannel.openStream`): whole messages both ways, flow-controlled by credit.
296
+ */
297
+ export interface DeviceStream {
298
+ /** Sends one message; resolves when the peer has credit for it (backpressure). */
299
+ send(message: Uint8Array): Promise<void>;
300
+ /** The peer's messages, in order; ends when the stream closes. */
301
+ readonly messages: AsyncIterable<Uint8Array>;
302
+ /** Closes the stream (idempotent); `reason` reaches the peer. */
303
+ close(reason?: string): void;
304
+ /** Resolves once the stream is closed, by either side, with the reason. */
305
+ readonly closed: Promise<{
306
+ reason: string;
307
+ }>;
308
+ }
234
309
  /**
235
310
  * The `device-provider@1` implementation (provided by a sandbox plugin such as Docker or E2B).
236
311
  *
@@ -536,6 +611,49 @@ export interface DeviceProvider {
536
611
  path: string;
537
612
  suggestedName: string;
538
613
  }[]>;
614
+ /**
615
+ * Starts the named service in the instance, or finds it running (optional, with
616
+ * {@link DeviceProvider.stopService} and {@link DeviceProvider.serviceRequest}): writes
617
+ * `spec.files` into the service's code directory, then runs `spec.entry` with Node, the
618
+ * service socket and state directory named in its environment (`DEVICE_SERVICE_SOCKET_ENV`,
619
+ * `DEVICE_SERVICE_STATE_ENV`). A service already running under the name is kept as is. The
620
+ * kernel has passed the launch through the command review before it calls this.
621
+ *
622
+ * With `opts.ifRunning` it never starts anything and reads only `spec.name` (the kernel sends
623
+ * `{ name, runtime: "node", entry: "", args: [], files: {} }`, which must not be refused): a
624
+ * running service is kept and the device's current network limits are applied to it again,
625
+ * a restart for that runs the spec it was launched with and its stored code (the kernel calls
626
+ * this after the device's allowlist changed, and before reviewing a launch); a stopped one
627
+ * answers its `stopped` status (with `stateDir`, and `codeDir` where kept apart) and stays
628
+ * stopped.
629
+ */
630
+ ensureService?(h: SandboxHandle, spec: DeviceServiceSpec, signal: AbortSignal, opts?: {
631
+ ifRunning?: boolean;
632
+ }): Promise<DeviceServiceStatus>;
633
+ /** Stops the named service; succeeds when it is not running. */
634
+ stopService?(h: SandboxHandle, name: string, signal: AbortSignal): Promise<void>;
635
+ /**
636
+ * The named service's state in the instance, without starting it (optional; the kernel's
637
+ * status reads). Whether a launch is reviewed is decided by `ensureService` with
638
+ * `ifRunning`, which is race-free.
639
+ */
640
+ serviceStatus?(h: SandboxHandle, name: string, signal: AbortSignal): Promise<DeviceServiceStatus>;
641
+ /**
642
+ * One `request` connection to the named service's socket: sends `body`, resolves the service's
643
+ * one answer. Throws when the service is not running, on timeout and on abort.
644
+ */
645
+ serviceRequest?(h: SandboxHandle, name: string, body: Uint8Array, opts: {
646
+ timeoutMs: number;
647
+ signal: AbortSignal;
648
+ }): Promise<Uint8Array>;
649
+ /**
650
+ * Opens a `stream` connection to the named service's socket (optional; the browser's live view
651
+ * needs it). The target is always a service of the device, never a general port forward.
652
+ * `signal` bounds the opening only; the stream lives until either side closes it.
653
+ */
654
+ openStream?(h: SandboxHandle, target: {
655
+ service: string;
656
+ }, signal: AbortSignal): Promise<DeviceStream>;
539
657
  }
540
658
  /**
541
659
  * The most entries a `list` may ask for and its result may carry ({@link DeviceProvider.list}):
@@ -189,6 +189,8 @@ export function isProjectPathRefusedError(e) {
189
189
  e.projectPathRefused === true &&
190
190
  isRecord(e.reason));
191
191
  }
192
+ /** A device service name: 1 to 32 characters, a lower-case letter then letters, digits and `-`. */
193
+ export const DEVICE_SERVICE_NAME_RE = /^[a-z][a-z0-9-]{0,31}$/;
192
194
  // biome-ignore lint/suspicious/noControlCharactersInRegex: control characters are exactly what must be blocked
193
195
  const CONTROL = /[\u0000-\u001f\u007f]/;
194
196
  /**
@@ -0,0 +1,52 @@
1
+ /**
2
+ * The device service socket protocol: how a device provider (or the machine program serving a
3
+ * dial-in device) talks to a service it started with `DeviceProvider.ensureService`. Every
4
+ * provider and every service speaks it, so a service runs the same on every provider.
5
+ *
6
+ * The provider starts the service with {@link DEVICE_SERVICE_SOCKET_ENV} naming the unix socket
7
+ * the service listens on and {@link DEVICE_SERVICE_STATE_ENV} naming its state directory (the
8
+ * only place it may write besides the workspace downloads). The spec's files are written before
9
+ * start into the service's code directory: a directory the service can only read where the
10
+ * provider can separate code from state, else the state directory. On a connection,
11
+ * both sides exchange length-prefixed messages ({@link encodeServiceMessage}). The first message
12
+ * from the provider is JSON whose `kind` is one of {@link SERVICE_CONNECTION_KINDS}:
13
+ *
14
+ * - `{"kind":"request"}`: the next provider message is the request body; the service answers
15
+ * with exactly one message and closes the connection.
16
+ * - `{"kind":"stream"}`: both sides keep exchanging messages until either side closes.
17
+ */
18
+ /** Names the unix socket path the service listens on. */
19
+ export declare const DEVICE_SERVICE_SOCKET_ENV = "CAPYBARA_SERVICE_SOCKET";
20
+ /** Names the service's state directory (its own data, its write root; not where its code is). */
21
+ export declare const DEVICE_SERVICE_STATE_ENV = "CAPYBARA_SERVICE_STATE";
22
+ /**
23
+ * Names the device's workspace root. Every provider sets it for every service (a spec cannot set
24
+ * it); a service confines the files it takes in (uploads) and lets out (downloads) to it.
25
+ */
26
+ export declare const DEVICE_SERVICE_WORKSPACE_ENV = "CAPYBARA_SERVICE_WORKSPACE";
27
+ /** The largest message body, in bytes, either side may send on a service connection. */
28
+ export declare const DEVICE_SERVICE_MAX_MESSAGE: number;
29
+ /** The kinds a connection's first message may name. */
30
+ export declare const SERVICE_CONNECTION_KINDS: readonly ["request", "stream"];
31
+ /** A service connection kind ({@link SERVICE_CONNECTION_KINDS}). */
32
+ export type ServiceConnectionKind = (typeof SERVICE_CONNECTION_KINDS)[number];
33
+ /**
34
+ * Frames one message: a 4-byte big-endian length followed by `body`. Throws a `RangeError` for a
35
+ * body above {@link DEVICE_SERVICE_MAX_MESSAGE}.
36
+ */
37
+ export declare function encodeServiceMessage(body: Uint8Array): Uint8Array;
38
+ /**
39
+ * Splits a byte stream into the messages {@link encodeServiceMessage} framed, whatever the chunk
40
+ * boundaries. `push` returns the messages completed by `chunk` (copies, safe to keep). A declared
41
+ * length above {@link DEVICE_SERVICE_MAX_MESSAGE} throws a `RangeError` as soon as the header is
42
+ * read; the connection should then be closed (the decoder is not usable afterwards).
43
+ */
44
+ export declare class ServiceMessageDecoder {
45
+ private chunks;
46
+ private first;
47
+ private pending;
48
+ private need;
49
+ push(chunk: Uint8Array): Uint8Array[];
50
+ /** Removes the first `n` (at most `pending`) bytes into one new array, copying each byte once. */
51
+ private take;
52
+ }
@@ -0,0 +1,105 @@
1
+ /**
2
+ * The device service socket protocol: how a device provider (or the machine program serving a
3
+ * dial-in device) talks to a service it started with `DeviceProvider.ensureService`. Every
4
+ * provider and every service speaks it, so a service runs the same on every provider.
5
+ *
6
+ * The provider starts the service with {@link DEVICE_SERVICE_SOCKET_ENV} naming the unix socket
7
+ * the service listens on and {@link DEVICE_SERVICE_STATE_ENV} naming its state directory (the
8
+ * only place it may write besides the workspace downloads). The spec's files are written before
9
+ * start into the service's code directory: a directory the service can only read where the
10
+ * provider can separate code from state, else the state directory. On a connection,
11
+ * both sides exchange length-prefixed messages ({@link encodeServiceMessage}). The first message
12
+ * from the provider is JSON whose `kind` is one of {@link SERVICE_CONNECTION_KINDS}:
13
+ *
14
+ * - `{"kind":"request"}`: the next provider message is the request body; the service answers
15
+ * with exactly one message and closes the connection.
16
+ * - `{"kind":"stream"}`: both sides keep exchanging messages until either side closes.
17
+ */
18
+ /** Names the unix socket path the service listens on. */
19
+ export const DEVICE_SERVICE_SOCKET_ENV = "CAPYBARA_SERVICE_SOCKET";
20
+ /** Names the service's state directory (its own data, its write root; not where its code is). */
21
+ export const DEVICE_SERVICE_STATE_ENV = "CAPYBARA_SERVICE_STATE";
22
+ /**
23
+ * Names the device's workspace root. Every provider sets it for every service (a spec cannot set
24
+ * it); a service confines the files it takes in (uploads) and lets out (downloads) to it.
25
+ */
26
+ export const DEVICE_SERVICE_WORKSPACE_ENV = "CAPYBARA_SERVICE_WORKSPACE";
27
+ /** The largest message body, in bytes, either side may send on a service connection. */
28
+ export const DEVICE_SERVICE_MAX_MESSAGE = 8 * 1024 * 1024;
29
+ /** The kinds a connection's first message may name. */
30
+ export const SERVICE_CONNECTION_KINDS = ["request", "stream"];
31
+ const HEADER = 4;
32
+ /**
33
+ * Frames one message: a 4-byte big-endian length followed by `body`. Throws a `RangeError` for a
34
+ * body above {@link DEVICE_SERVICE_MAX_MESSAGE}.
35
+ */
36
+ export function encodeServiceMessage(body) {
37
+ if (body.byteLength > DEVICE_SERVICE_MAX_MESSAGE)
38
+ throw new RangeError(`service message of ${body.byteLength} bytes exceeds ${DEVICE_SERVICE_MAX_MESSAGE} bytes`);
39
+ const out = new Uint8Array(HEADER + body.byteLength);
40
+ new DataView(out.buffer).setUint32(0, body.byteLength);
41
+ out.set(body, HEADER);
42
+ return out;
43
+ }
44
+ /**
45
+ * Splits a byte stream into the messages {@link encodeServiceMessage} framed, whatever the chunk
46
+ * boundaries. `push` returns the messages completed by `chunk` (copies, safe to keep). A declared
47
+ * length above {@link DEVICE_SERVICE_MAX_MESSAGE} throws a `RangeError` as soon as the header is
48
+ * read; the connection should then be closed (the decoder is not usable afterwards).
49
+ */
50
+ export class ServiceMessageDecoder {
51
+ // unread bytes, oldest first from index `first`; `pending` is their total length
52
+ chunks = [];
53
+ first = 0;
54
+ pending = 0;
55
+ // the declared length of the message being read, once its header is complete
56
+ need = null;
57
+ push(chunk) {
58
+ if (chunk.byteLength > 0) {
59
+ this.chunks.push(chunk.slice());
60
+ this.pending += chunk.byteLength;
61
+ }
62
+ const out = [];
63
+ for (;;) {
64
+ if (this.need === null) {
65
+ if (this.pending < HEADER)
66
+ break;
67
+ const header = this.take(HEADER);
68
+ const len = new DataView(header.buffer, header.byteOffset, HEADER).getUint32(0);
69
+ if (len > DEVICE_SERVICE_MAX_MESSAGE)
70
+ throw new RangeError(`service message of ${len} bytes exceeds ${DEVICE_SERVICE_MAX_MESSAGE} bytes`);
71
+ this.need = len;
72
+ }
73
+ if (this.pending < this.need)
74
+ break;
75
+ out.push(this.take(this.need));
76
+ this.need = null;
77
+ }
78
+ return out;
79
+ }
80
+ /** Removes the first `n` (at most `pending`) bytes into one new array, copying each byte once. */
81
+ take(n) {
82
+ const out = new Uint8Array(n);
83
+ let at = 0;
84
+ while (at < n) {
85
+ // never undefined: callers take at most `pending` bytes
86
+ const head = this.chunks[this.first];
87
+ if (head === undefined)
88
+ break;
89
+ const k = Math.min(head.byteLength, n - at);
90
+ out.set(head.subarray(0, k), at);
91
+ at += k;
92
+ if (k === head.byteLength)
93
+ this.first++;
94
+ else
95
+ this.chunks[this.first] = head.subarray(k);
96
+ }
97
+ // drop consumed chunks in one go (no per-chunk shift)
98
+ if (this.first > 64 || this.first === this.chunks.length) {
99
+ this.chunks = this.chunks.slice(this.first);
100
+ this.first = 0;
101
+ }
102
+ this.pending -= n;
103
+ return out;
104
+ }
105
+ }
package/dist/dial-in.d.ts CHANGED
@@ -6,12 +6,40 @@
6
6
  * provider. It never reads a body: what a body means is the provider's protocol, named by
7
7
  * `permissions.dialIn.protocol` and by the machine's hello.
8
8
  */
9
+ import type { DeviceStream } from "./device-provider.js";
9
10
  /**
10
11
  * A dial-in protocol: `<name>/<major>`, a lower-case name of 1 to 41 characters and a major
11
12
  * version from 1 to 9999 (for example `capybara-device/6`). A machine's hello must name exactly
12
13
  * the protocol of the provider serving its device.
13
14
  */
14
15
  export declare const DIAL_IN_PROTOCOL_RE: RegExp;
16
+ /**
17
+ * The credit, in messages, each side of a dial-in stream starts with for the other: a side sends a
18
+ * `stream-data` only while it holds credit, and grants more with `stream-credit` as it consumes
19
+ * messages, so one stream cannot fill the connection and starve the machine's other frames.
20
+ */
21
+ export declare const DIAL_IN_STREAM_INITIAL_CREDIT = 8;
22
+ /**
23
+ * The stream frames both sides send ({@link DialInChannel.openStream}). `data` is one whole message
24
+ * in standard base64; the frame, like every frame, fits the connection's `maxFrameBytes`.
25
+ */
26
+ export type DialInStreamFrame = {
27
+ type: "stream-data";
28
+ streamId: string;
29
+ data: string;
30
+ }
31
+ /** Grants the peer `messages` more `stream-data` frames on the stream. */
32
+ | {
33
+ type: "stream-credit";
34
+ streamId: string;
35
+ messages: number;
36
+ }
37
+ /** Either side ends the stream; no frame of it follows. */
38
+ | {
39
+ type: "stream-close";
40
+ streamId: string;
41
+ reason: string;
42
+ };
15
43
  /** A frame from the machine. The kernel checks the envelope; `body` is the provider's. */
16
44
  export type DialInMachineFrame = {
17
45
  /** The first frame after the socket opens. */
@@ -42,7 +70,14 @@ export type DialInMachineFrame = {
42
70
  | {
43
71
  type: "event";
44
72
  body: unknown;
45
- };
73
+ }
74
+ /** The answer to the kernel's `stream-open`: the machine opened the stream, or why not. */
75
+ | {
76
+ type: "stream-opened";
77
+ streamId: string;
78
+ ok: boolean;
79
+ error?: string;
80
+ } | DialInStreamFrame;
46
81
  /** A frame from the kernel to the machine. */
47
82
  export type DialInKernelFrame =
48
83
  /**
@@ -71,7 +106,13 @@ export type DialInKernelFrame =
71
106
  | {
72
107
  type: "stop";
73
108
  reason: "drain" | "stop";
74
- };
109
+ }
110
+ /** Opens a stream on the machine; `body` names the target in the provider's protocol. */
111
+ | {
112
+ type: "stream-open";
113
+ streamId: string;
114
+ body: unknown;
115
+ } | DialInStreamFrame;
75
116
  /** A machine frame that is not a valid dial-in envelope. The kernel closes the socket on it. */
76
117
  export declare class DialInProtocolError extends Error {
77
118
  constructor(message: string);
@@ -150,6 +191,28 @@ export interface DialInChannel {
150
191
  maxFrameBytes: number;
151
192
  } | null>;
152
193
  stop(deviceId: string, reason: "drain" | "stop"): Promise<void>;
194
+ /**
195
+ * Opens a stream to the machine serving the device: sends `stream-open` with `body` (the
196
+ * target, in the provider's protocol) and resolves once the machine answers `stream-opened` ok.
197
+ * Stream frames go straight over the machine's socket, never through shared state, so this
198
+ * works only on the gateway replica holding that socket: elsewhere it throws
199
+ * {@link DialInStreamElsewhereError}. Throws {@link DeviceOfflineError} when no machine holds the
200
+ * device. Each message must fit the connection's frame capacity once base64-encoded in a
201
+ * `stream-data` frame. `signal` bounds the opening only.
202
+ */
203
+ openStream(deviceId: string, body: unknown, opts: {
204
+ signal: AbortSignal;
205
+ }): Promise<DeviceStream>;
206
+ }
207
+ /**
208
+ * {@link DialInChannel.openStream} was called on a replica that does not hold the machine's
209
+ * socket: the caller must reach the holding gateway replica instead.
210
+ */
211
+ export declare class DialInStreamElsewhereError extends Error {
212
+ readonly code = "device.stream_elsewhere";
213
+ constructor(deviceId: string, opts?: {
214
+ cause?: unknown;
215
+ });
153
216
  }
154
217
  /**
155
218
  * `ctx.devices` (requires `provides: ["device-provider@1"]`): what a device provider tells the
package/dist/dial-in.js CHANGED
@@ -13,6 +13,12 @@ import { z } from "zod";
13
13
  * the protocol of the provider serving its device.
14
14
  */
15
15
  export const DIAL_IN_PROTOCOL_RE = /^[a-z][a-z0-9-]{0,40}\/[1-9][0-9]{0,3}$/;
16
+ /**
17
+ * The credit, in messages, each side of a dial-in stream starts with for the other: a side sends a
18
+ * `stream-data` only while it holds credit, and grants more with `stream-credit` as it consumes
19
+ * messages, so one stream cannot fill the connection and starve the machine's other frames.
20
+ */
21
+ export const DIAL_IN_STREAM_INITIAL_CREDIT = 8;
16
22
  /** A machine frame that is not a valid dial-in envelope. The kernel closes the socket on it. */
17
23
  export class DialInProtocolError extends Error {
18
24
  constructor(message) {
@@ -26,6 +32,20 @@ const id = z.string().regex(ID_RE);
26
32
  const label = z.string().min(1).max(64);
27
33
  // a frame without a body is malformed (JSON has no undefined, so this is a missing key)
28
34
  const body = z.unknown().refine((v) => v !== undefined, "body is required");
35
+ // standard base64, padded; empty is an empty message
36
+ const base64 = z
37
+ .string()
38
+ .regex(/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/, "data must be base64");
39
+ const reason = z.string().max(500);
40
+ const streamFrames = [
41
+ z.strictObject({ type: z.literal("stream-data"), streamId: id, data: base64 }),
42
+ z.strictObject({
43
+ type: z.literal("stream-credit"),
44
+ streamId: id,
45
+ messages: z.number().int().min(1).max(1_000_000),
46
+ }),
47
+ z.strictObject({ type: z.literal("stream-close"), streamId: id, reason }),
48
+ ];
29
49
  const machineFrame = z.discriminatedUnion("type", [
30
50
  z.strictObject({
31
51
  type: z.literal("hello"),
@@ -44,6 +64,13 @@ const machineFrame = z.discriminatedUnion("type", [
44
64
  }),
45
65
  z.strictObject({ type: z.literal("res"), id, body }),
46
66
  z.strictObject({ type: z.literal("event"), body }),
67
+ z.strictObject({
68
+ type: z.literal("stream-opened"),
69
+ streamId: id,
70
+ ok: z.boolean(),
71
+ error: reason.optional(),
72
+ }),
73
+ ...streamFrames,
47
74
  ]);
48
75
  /**
49
76
  * Strictly parses one machine frame: the text must be at most `maxBytes` UTF-8 bytes (checked
@@ -89,6 +116,8 @@ const kernelFrame = z.discriminatedUnion("type", [
89
116
  }),
90
117
  z.strictObject({ type: z.literal("cancel"), id }),
91
118
  z.strictObject({ type: z.literal("stop"), reason: z.enum(["drain", "stop"]) }),
119
+ z.strictObject({ type: z.literal("stream-open"), streamId: id, body }),
120
+ ...streamFrames,
92
121
  ]);
93
122
  /**
94
123
  * The machine's side of {@link parseDialInMachineFrame}: strictly parses one kernel frame, at most
@@ -99,6 +128,17 @@ const kernelFrame = z.discriminatedUnion("type", [
99
128
  export function parseDialInKernelFrame(text, maxBytes) {
100
129
  return parseFrame(kernelFrame, text, maxBytes);
101
130
  }
131
+ /**
132
+ * {@link DialInChannel.openStream} was called on a replica that does not hold the machine's
133
+ * socket: the caller must reach the holding gateway replica instead.
134
+ */
135
+ export class DialInStreamElsewhereError extends Error {
136
+ code = "device.stream_elsewhere";
137
+ constructor(deviceId, opts) {
138
+ super(`Device ${deviceId}'s machine is connected to another gateway replica; open the stream there.`, opts && "cause" in opts ? { cause: opts.cause } : undefined);
139
+ this.name = "DialInStreamElsewhereError";
140
+ }
141
+ }
102
142
  /** No machine serves the device (it is not connected, and did not reconnect within the grace). */
103
143
  export class DeviceOfflineError extends Error {
104
144
  code = "device.offline";
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- export declare const SDK_VERSION = "0.1.0-rc.69";
1
+ export declare const SDK_VERSION = "0.1.0-rc.70";
2
2
  export * from "./agent-template.js";
3
3
  export * from "./avatar-presets.js";
4
4
  export * from "./bootstrap.js";
@@ -16,6 +16,7 @@ export * from "./define-extension.js";
16
16
  export { DEVICE_DEFAULT_STATE_PATH, DEVICE_DENIED_SECRET_PATHS } from "./device-denied-paths.js";
17
17
  export * from "./device-operation.js";
18
18
  export * from "./device-provider.js";
19
+ export * from "./device-service.js";
19
20
  export * from "./dial-in.js";
20
21
  export * from "./directory.js";
21
22
  export * from "./extension-point.js";
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- export const SDK_VERSION = "0.1.0-rc.69";
1
+ export const SDK_VERSION = "0.1.0-rc.70";
2
2
  export * from "./agent-template.js";
3
3
  export * from "./avatar-presets.js";
4
4
  export * from "./bootstrap.js";
@@ -16,6 +16,7 @@ export * from "./define-extension.js";
16
16
  export { DEVICE_DEFAULT_STATE_PATH, DEVICE_DENIED_SECRET_PATHS } from "./device-denied-paths.js";
17
17
  export * from "./device-operation.js";
18
18
  export * from "./device-provider.js";
19
+ export * from "./device-service.js";
19
20
  export * from "./dial-in.js";
20
21
  export * from "./directory.js";
21
22
  export * from "./extension-point.js";
@@ -67,7 +67,18 @@ export interface ExtensionPermissions {
67
67
  dialIn?: {
68
68
  protocol: string;
69
69
  };
70
+ /**
71
+ * `ctx.deviceAccess`: services this extension runs in the conversation's device and reaches
72
+ * through requests and viewer streams. `services` lists 1 to
73
+ * {@link DEVICE_ACCESS_MAX_SERVICES} service names ({@link DEVICE_SERVICE_NAME_RE}); a service
74
+ * not listed is refused. Any extension may declare it (no `provides` needed).
75
+ */
76
+ deviceAccess?: {
77
+ services: string[];
78
+ };
70
79
  }
80
+ /** The most services `permissions.deviceAccess.services` may list. */
81
+ export declare const DEVICE_ACCESS_MAX_SERVICES = 4;
71
82
  /** Hook mount points (a closed list, see the overall design 2.4). */
72
83
  export declare const HOOK_MOUNT_POINTS: readonly ["session.start", "session.end", "agent.preStep", "model.request", "model.response", "tool.preExecute", "tool.postExecute", "usage.report", "org.member_removed", "agent.deleted", "org.deleted"];
73
84
  /** A hook mount point name. */
@@ -1,10 +1,12 @@
1
- import { DEVICE_PROVIDER_EXTENSION_POINT } from "./device-provider.js";
1
+ import { DEVICE_PROVIDER_EXTENSION_POINT, DEVICE_SERVICE_NAME_RE } from "./device-provider.js";
2
2
  import { DIAL_IN_PROTOCOL_RE } from "./dial-in.js";
3
3
  import { POLICY_HOOKS } from "./hooks.js";
4
4
  import { HTTP_ACCESS } from "./http-access.js";
5
5
  import { SETUP_CHECK_ID_RE, SETUP_CHECK_LIMITS } from "./setup-check.js";
6
6
  import { UI_ICONS } from "./ui.js";
7
7
  import { isCompactForm, parseSlotRef, uiSlot } from "./ui-slots.js";
8
+ /** The most services `permissions.deviceAccess.services` may list. */
9
+ export const DEVICE_ACCESS_MAX_SERVICES = 4;
8
10
  /** Hook mount points (a closed list, see the overall design 2.4). */
9
11
  export const HOOK_MOUNT_POINTS = [
10
12
  "session.start",
@@ -47,6 +49,7 @@ const KEYS = new Set([
47
49
  "client",
48
50
  "setupChecks",
49
51
  "dialIn",
52
+ "deviceAccess",
50
53
  ]);
51
54
  const POLICY = new Set(POLICY_HOOKS);
52
55
  const METHODS = new Set(["GET", "POST", "PUT", "DELETE"]);
@@ -215,6 +218,23 @@ export function validatePermissions(plugin, p, provides = []) {
215
218
  errs.push(`permissions.dialIn needs "${DEVICE_PROVIDER_EXTENSION_POINT}" in provides`);
216
219
  }
217
220
  }
221
+ if (p.deviceAccess !== undefined) {
222
+ if (!isObj(p.deviceAccess) || Object.keys(p.deviceAccess).some((k) => k !== "services")) {
223
+ errs.push("permissions.deviceAccess must be { services: string[] }");
224
+ }
225
+ else {
226
+ const names = strList("permissions.deviceAccess.services", p.deviceAccess.services, errs);
227
+ if (Array.isArray(p.deviceAccess.services)) {
228
+ const n = p.deviceAccess.services.length;
229
+ if (n < 1 || n > DEVICE_ACCESS_MAX_SERVICES)
230
+ errs.push(`permissions.deviceAccess.services must list 1 to ${DEVICE_ACCESS_MAX_SERVICES} services`);
231
+ }
232
+ for (const name of names) {
233
+ if (!DEVICE_SERVICE_NAME_RE.test(name))
234
+ errs.push(`permissions.deviceAccess.services entry "${name}" must match ${DEVICE_SERVICE_NAME_RE}`);
235
+ }
236
+ }
237
+ }
218
238
  return errs;
219
239
  }
220
240
  const UI_ID_RE = /^[a-z][a-z0-9-]{0,39}$/;
package/dist/tool.d.ts CHANGED
@@ -157,8 +157,10 @@ export type FormAnswer = Record<string, string | number | boolean | string[]>;
157
157
  * person, may then decide to call the tool again: that is a new call with a new `callId`.
158
158
  *
159
159
  * One logical call may still invoke the handler more than once: each `InputRequired` round
160
- * resumes it with `resume`. `callId` and `idempotencyKey` stay the same across those
161
- * invocations. A tool with an external side effect passes `idempotencyKey` downstream (for
160
+ * resumes it with `resume`, and a call whose device service reported refused hosts
161
+ * (`ctx.deviceAccess.reportBlockedHosts`) runs again, without `resume`, once the person approved
162
+ * the network ask and the hosts are in force. `callId` and `idempotencyKey` stay the same across
163
+ * those invocations. A tool with an external side effect passes `idempotencyKey` downstream (for
162
164
  * example as an `Idempotency-Key` header, or stored with the record it creates) so the effect
163
165
  * applies once per logical call and an unknown outcome can be checked against the external
164
166
  * system before retrying.
@@ -178,7 +180,8 @@ export interface ToolCallContext {
178
180
  * The key of this logical call for idempotent side effects: 64 lowercase hex characters derived
179
181
  * from the conversation, the run and `callId`. The same for every invocation of the call
180
182
  * (each `InputRequired` round), different for every other call, including a later call the
181
- * model makes to retry it.
183
+ * model makes to retry it. A re-run of the same call after its network ask was approved
184
+ * (`ctx.deviceAccess.reportBlockedHosts`) keeps the key too.
182
185
  */
183
186
  idempotencyKey?: string;
184
187
  signal: AbortSignal;
package/dist/ui.d.ts CHANGED
@@ -5,7 +5,7 @@ import type { CompactForm, UiSlotId, UiSlotScope } from "./ui-slots.js";
5
5
  * Icons a contribution may use (design system icon names; `puzzle` is the default and is drawn as
6
6
  * the design `extension` icon). The title-bar button of a panel shows it.
7
7
  */
8
- export declare const UI_ICONS: readonly ["list-checks", "layout-grid", "file", "chart", "calendar", "users", "bot", "book", "message-square", "puzzle"];
8
+ export declare const UI_ICONS: readonly ["list-checks", "layout-grid", "file", "chart", "calendar", "users", "bot", "book", "message-square", "globe", "puzzle"];
9
9
  export type UiIcon = (typeof UI_ICONS)[number];
10
10
  /**
11
11
  * An "open" target: a `conversation.panel` contribution of the same extension, scrolled to the
@@ -399,6 +399,15 @@ export type EmbedChildMessage =
399
399
  protocol: typeof EMBED_PROTOCOL;
400
400
  type: "toast";
401
401
  text: string;
402
+ }
403
+ /**
404
+ * Asks the host to maximise (`true`) or restore (`false`) the conversation's right panel; only an
405
+ * embed in the `conversation.panel` slot is honoured.
406
+ */
407
+ | {
408
+ protocol: typeof EMBED_PROTOCOL;
409
+ type: "panel-mode";
410
+ full: boolean;
402
411
  };
403
412
  /**
404
413
  * Parses a message sent by the iframe: returns it only when protocol, type and fields are all right
package/dist/ui.js CHANGED
@@ -14,6 +14,7 @@ export const UI_ICONS = [
14
14
  "bot",
15
15
  "book",
16
16
  "message-square",
17
+ "globe",
17
18
  "puzzle",
18
19
  ];
19
20
  /**
@@ -426,6 +427,8 @@ export function parseEmbedChildMessage(m) {
426
427
  return typeof m.text === "string" && m.text !== "" && m.text.length <= TOAST_MAX
427
428
  ? { protocol, type: "toast", text: m.text }
428
429
  : null;
430
+ case "panel-mode":
431
+ return typeof m.full === "boolean" ? { protocol, type: "panel-mode", full: m.full } : null;
429
432
  default:
430
433
  return null;
431
434
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@capybara-hq/plugin-sdk",
3
- "version": "0.1.0-rc.69",
3
+ "version": "0.1.0-rc.70",
4
4
  "description": "Capybara plugin SDK: the types and pure functions plugins are written against",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {