@agentproto/acp 0.1.0-alpha.2 → 0.1.0

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.
@@ -81,6 +81,10 @@ interface SpawnFrame {
81
81
  * line-delimited JSON-RPC.
82
82
  */
83
83
  pty?: boolean;
84
+ /** Initial PTY column width. Ignored when `pty` is false. Default 80. */
85
+ cols?: number;
86
+ /** Initial PTY row height. Ignored when `pty` is false. Default 24. */
87
+ rows?: number;
84
88
  }
85
89
  interface StdinFrame {
86
90
  t: "stdin";
@@ -130,6 +134,20 @@ interface HttpRequestFrame {
130
134
  /**
131
135
  * Generic HTTP-over-tunnel response (DAEMON → HOST). Mirrors
132
136
  * `HttpRequestFrame` — see its docs.
137
+ *
138
+ * Two-frame protocol:
139
+ * - SHORT RESPONSES (most HTTP): daemon emits a single `http_response`
140
+ * with body inline. The buffered `forwardHttp` resolves directly
141
+ * from this frame.
142
+ * - STREAMED RESPONSES (text/event-stream, long-lived chunked
143
+ * transfers, large downloads): daemon emits `http_response_head`
144
+ * first with status+headers, then one or more `http_response_chunk`
145
+ * frames, the last of which has `end: true`. The streaming
146
+ * `forwardHttpStream` builds a `ReadableStream` from the chunks.
147
+ *
148
+ * Hosts that only support the legacy buffered API can detect the
149
+ * stream protocol by looking for `http_response_head` and either
150
+ * pull the chunks into a buffer (compat) or refuse to handle.
133
151
  */
134
152
  interface HttpResponseFrame {
135
153
  t: "http_response";
@@ -146,6 +164,43 @@ interface HttpResponseFrame {
146
164
  message: string;
147
165
  }>;
148
166
  }
167
+ /**
168
+ * Streaming HTTP response head (DAEMON → HOST). Sent ONCE per
169
+ * streaming response, before any chunk frames. Carries status +
170
+ * headers so the host can finalize the response shape (e.g. write
171
+ * Content-Type) before any body bytes arrive.
172
+ */
173
+ interface HttpResponseHeadFrame {
174
+ t: "http_response_head";
175
+ reqId: string;
176
+ status: number;
177
+ headers?: Readonly<Record<string, string>>;
178
+ }
179
+ /**
180
+ * Streaming HTTP response body chunk (DAEMON → HOST). Each chunk
181
+ * carries some bytes of the response body. The terminal chunk has
182
+ * `end: true` and MAY include final bytes. An immediate `end: true`
183
+ * with no data signals empty-body close.
184
+ *
185
+ * `error` set on a chunk frame indicates the daemon's upstream
186
+ * failed mid-stream; host SHOULD propagate it as a stream error.
187
+ */
188
+ interface HttpResponseChunkFrame {
189
+ t: "http_response_chunk";
190
+ reqId: string;
191
+ /** Base64-encoded chunk bytes. Omitted on pure end-of-stream
192
+ * markers (those carry `end: true` only). */
193
+ data?: string;
194
+ /** Set on the last chunk. After this frame the host SHOULD ignore
195
+ * any further frames for this reqId. */
196
+ end?: boolean;
197
+ /** Set when the upstream failed mid-stream. Host surfaces this as
198
+ * a stream error and closes the readable. */
199
+ error?: Readonly<{
200
+ code: string;
201
+ message: string;
202
+ }>;
203
+ }
149
204
  interface HelloFrame {
150
205
  t: "hello";
151
206
  version: typeof TUNNEL_VERSION;
@@ -155,6 +210,10 @@ interface HelloFrame {
155
210
  */
156
211
  capabilities: Readonly<{
157
212
  pty: boolean;
213
+ /** Daemon can bridge browser-WS upgrades to its local upstream via
214
+ * `ws_open` / `ws_message` / `ws_close`. Hosts MUST gate
215
+ * `forwardWebSocket()` on this — older daemons ignore the frames. */
216
+ wsForward?: boolean;
158
217
  }>;
159
218
  /** User-friendly daemon label, surfaced in host UIs. */
160
219
  label?: string;
@@ -209,8 +268,99 @@ interface PongFrame {
209
268
  t: "pong";
210
269
  nonce: string;
211
270
  }
212
- type HostToDaemonFrame = SpawnFrame | StdinFrame | KillFrame | ResizeFrame | HttpRequestFrame | PingFrame | PongFrame | ErrorFrame;
213
- type DaemonToHostFrame = HelloFrame | SpawnedFrame | StdoutFrame | StderrFrame | ExitFrame | HttpResponseFrame | PingFrame | PongFrame | ErrorFrame;
271
+ /**
272
+ * HOST DAEMON. Graceful drain signal sent during host rollover (e.g.
273
+ * Kubernetes preStop). On receipt the daemon SHOULD:
274
+ * 1. Stop accepting new in-flight work where it can.
275
+ * 2. Close the WS cleanly (does not need to wait — host will follow
276
+ * up with a `close(1012, "service_restart")` ~2 s later as a
277
+ * hard backstop).
278
+ * 3. Reconnect IMMEDIATELY without the usual exponential backoff —
279
+ * the host is mid-deploy, the new replica is already listening.
280
+ *
281
+ * Backward-compatible: daemons that don't know the frame just ignore
282
+ * it (parseFrame returns null for unknown types). The host's close
283
+ * then triggers the daemon's normal backoff loop — worst case ~30 s
284
+ * reconnect gap instead of ~2 s with the handler.
285
+ */
286
+ interface ReconnectSoonFrame {
287
+ t: "reconnect_soon";
288
+ /** Hint of how long the host plans to wait before forcing close.
289
+ * Optional — daemons MAY use it to decide whether to finish
290
+ * in-flight work or close immediately. */
291
+ reasonMs?: number;
292
+ }
293
+ /**
294
+ * HOST → DAEMON. Open a WS connection to the daemon's upstream.
295
+ * Path semantics match `HttpRequestFrame` — absolute URLs rejected,
296
+ * daemon prepends its `ws://<upstream>` base. Headers forwarded as-is
297
+ * (cookies are typically NOT forwarded since the daemon's upstream is
298
+ * loopback; cookie passthrough is opt-in via daemon config).
299
+ */
300
+ interface WsOpenFrame {
301
+ t: "ws_open";
302
+ /** Correlates every WS frame in both directions for this connection. */
303
+ reqId: string;
304
+ /** Path + querystring on the daemon-local upstream, e.g.
305
+ * `/sessions/abc/pty?cols=80&rows=24`. */
306
+ path: string;
307
+ /** Headers to set on the upstream WS request. Hop-by-hop headers
308
+ * (Connection, Upgrade, Sec-WebSocket-*) MUST be stripped — the
309
+ * daemon's `ws` client manages those. */
310
+ headers?: Readonly<Record<string, string>>;
311
+ /** Subprotocols requested by the browser; forwarded to upstream. */
312
+ protocols?: readonly string[];
313
+ }
314
+ /**
315
+ * DAEMON → HOST. Result of a `ws_open`. On success the upstream WS is
316
+ * connected and frames can flow. On failure `error` is set; no further
317
+ * frames for this `reqId` will arrive.
318
+ */
319
+ interface WsOpenAckFrame {
320
+ t: "ws_open_ack";
321
+ reqId: string;
322
+ /** HTTP status from the upstream upgrade. 101 on success; 4xx/5xx
323
+ * when the upstream refused the upgrade. */
324
+ status: number;
325
+ /** Selected subprotocol, if any. */
326
+ protocol?: string;
327
+ /** Set when the daemon couldn't open the upstream (DNS failure,
328
+ * refused, timeout). Distinct from a clean upstream-side close,
329
+ * which arrives as `ws_close`. */
330
+ error?: Readonly<{
331
+ code: string;
332
+ message: string;
333
+ }>;
334
+ }
335
+ /**
336
+ * Either direction. One application-level WS frame's payload. Text
337
+ * frames carry UTF-8 bytes (`binary: false`); binary frames carry
338
+ * arbitrary bytes (`binary: true`). The `data` field is base64-encoded
339
+ * either way so the transport stays JSON.
340
+ */
341
+ interface WsMessageFrame {
342
+ t: "ws_message";
343
+ reqId: string;
344
+ /** Base64-encoded WS frame payload. */
345
+ data: string;
346
+ /** True for binary frames; false (or omitted) for text. */
347
+ binary?: boolean;
348
+ }
349
+ /**
350
+ * Either direction. Close the bridged WS connection. Includes the
351
+ * close code (1000 normal, 1006 abnormal, etc.) and optional reason.
352
+ * After sending or receiving this frame, neither side will send
353
+ * further frames for `reqId`.
354
+ */
355
+ interface WsCloseFrame {
356
+ t: "ws_close";
357
+ reqId: string;
358
+ /** WebSocket close code. */
359
+ code: number;
360
+ reason?: string;
361
+ }
362
+ type HostToDaemonFrame = SpawnFrame | StdinFrame | KillFrame | ResizeFrame | HttpRequestFrame | WsOpenFrame | WsMessageFrame | WsCloseFrame | PingFrame | PongFrame | ErrorFrame | ReconnectSoonFrame;
363
+ type DaemonToHostFrame = HelloFrame | SpawnedFrame | StdoutFrame | StderrFrame | ExitFrame | HttpResponseFrame | HttpResponseHeadFrame | HttpResponseChunkFrame | WsOpenAckFrame | WsMessageFrame | WsCloseFrame | PingFrame | PongFrame | ErrorFrame;
214
364
  type TunnelFrame = HostToDaemonFrame | DaemonToHostFrame;
215
365
  /**
216
366
  * Parse a raw WS message into a `TunnelFrame`. Returns null when the
@@ -294,11 +444,23 @@ interface TunnelServerOptions {
294
444
  /** User-friendly label sent in the hello frame. */
295
445
  label?: string;
296
446
  /**
297
- * Whether this daemon advertises PTY support. v0 always reports
298
- * false PTY allocation needs node-pty (optional dep) and we
299
- * haven't wired that side yet.
447
+ * Whether this daemon advertises PTY support. Set to true only when
448
+ * `spawnPty` is also provided.
300
449
  */
301
450
  pty?: boolean;
451
+ /**
452
+ * Factory for PTY-backed processes. When provided (and `pty: true`),
453
+ * spawn frames with `pty: true` use this instead of node:child_process.
454
+ * Injected from the CLI layer so the ACP package stays native-free.
455
+ */
456
+ spawnPty?: (opts: {
457
+ command: string;
458
+ args: string[];
459
+ cwd?: string;
460
+ env?: Record<string, string>;
461
+ cols: number;
462
+ rows: number;
463
+ }) => PtyProcess;
302
464
  /**
303
465
  * Optional hook fired once per successful spawn — after authorize
304
466
  * passed and the ChildProcess has emitted its `spawn` event.
@@ -316,6 +478,68 @@ interface TunnelServerOptions {
316
478
  child: ChildProcess;
317
479
  request: SpawnFrame;
318
480
  }) => void;
481
+ /**
482
+ * Optional hook fired when the host sends a `reconnect_soon` frame —
483
+ * graceful drain signal during host rollover. The daemon SHOULD
484
+ * close + reconnect immediately (skipping any backoff) so the new
485
+ * host replica picks it up. Default: ignore (the host follows up
486
+ * with `close(1012)` and the daemon's own reconnect supervisor
487
+ * handles it via normal backoff, ~30 s gap).
488
+ *
489
+ * Implementations typically call into their connection supervisor
490
+ * to mark the next reconnect as "no-backoff" then close the sink.
491
+ * `reasonMs` is the host's hint for how long it will wait before
492
+ * forcing close — daemons MAY use it to drain in-flight RPCs first.
493
+ */
494
+ onReconnectSoon?: (info: {
495
+ reasonMs?: number;
496
+ }) => void;
497
+ /**
498
+ * Factory that dials a WS connection to the local upstream. When
499
+ * provided (and `httpUpstream` is set), the daemon advertises
500
+ * `wsForward` capability and handles `ws_open` frames by piping the
501
+ * upstream WS through the tunnel. Injected so `@agentproto/acp`
502
+ * stays free of a hard `ws` dependency — the CLI provides this
503
+ * factory using its already-pulled-in `ws` package.
504
+ */
505
+ dialUpstreamWs?: (params: {
506
+ url: string;
507
+ protocols?: readonly string[];
508
+ headers?: Readonly<Record<string, string>>;
509
+ }) => Promise<UpstreamWebSocket>;
510
+ }
511
+ /**
512
+ * Minimal upstream WS surface — satisfied by the `ws` library's
513
+ * client socket. Daemons supplying `dialUpstreamWs` resolve into
514
+ * one of these as soon as the WS is OPEN. `protocol` is the
515
+ * subprotocol negotiated by the upstream (empty string when none).
516
+ */
517
+ interface UpstreamWebSocket {
518
+ readonly protocol: string;
519
+ /** Send a frame to the upstream. */
520
+ send(data: Buffer | string, opts: {
521
+ binary: boolean;
522
+ }): void;
523
+ /** Close the upstream connection. */
524
+ close(code?: number, reason?: string): void;
525
+ /** Subscribe to inbound frames. */
526
+ onMessage(handler: (data: Buffer, isBinary: boolean) => void): void;
527
+ /** Subscribe to upstream close. */
528
+ onClose(handler: (code: number, reason: string) => void): void;
529
+ /** Subscribe to transport errors. */
530
+ onError(handler: (err: Error) => void): void;
531
+ }
532
+ /** Minimal PTY process surface — satisfied by node-pty's IPty. */
533
+ interface PtyProcess {
534
+ readonly pid: number;
535
+ write(data: string): void;
536
+ resize(cols: number, rows: number): void;
537
+ kill(signal?: string): void;
538
+ onData(handler: (data: string) => void): void;
539
+ onExit(handler: (event: {
540
+ exitCode: number;
541
+ signal?: number;
542
+ }) => void): void;
319
543
  }
320
544
  interface TunnelServer {
321
545
  /** Currently-live execId → ChildProcess. Read-only diagnostic. */
@@ -352,6 +576,16 @@ interface TunnelHttpResponse {
352
576
  message: string;
353
577
  }>;
354
578
  }
579
+ /** Resolved response from `forwardHttpStream`. Body is a Web
580
+ * `ReadableStream<Uint8Array>` — consume it to receive chunks as
581
+ * they arrive from the daemon's upstream (SSE, long-poll, NDJSON).
582
+ * The stream closes when the daemon's upstream closes OR an upstream
583
+ * error occurs (surfaced as a stream error on the reader). */
584
+ interface TunnelHttpStreamResponse {
585
+ status: number;
586
+ headers: Readonly<Record<string, string>>;
587
+ body: ReadableStream<Uint8Array>;
588
+ }
355
589
  interface TunnelHttpRequest {
356
590
  method: string;
357
591
  path: string;
@@ -360,6 +594,44 @@ interface TunnelHttpRequest {
360
594
  /** Per-request timeout in ms. Default 30_000. */
361
595
  timeoutMs?: number;
362
596
  }
597
+ interface TunnelWebSocketOpenRequest {
598
+ /** Path + querystring on the daemon-local upstream. Daemon prepends
599
+ * its `ws://<upstream>` base; absolute URLs are rejected. */
600
+ path: string;
601
+ /** Headers forwarded to the upstream upgrade. Hop-by-hop / Sec-* are
602
+ * stripped by the daemon. Cookies are NOT forwarded unless the
603
+ * daemon was started with `--upstream-cookies`. */
604
+ headers?: Readonly<Record<string, string>>;
605
+ /** Subprotocols requested. Echoed in `protocol` on success. */
606
+ protocols?: readonly string[];
607
+ /** How long to wait for the upstream upgrade before erroring. The
608
+ * message stream itself has no timeout (WS lives as long as either
609
+ * end keeps it open). Default 30_000. */
610
+ openTimeoutMs?: number;
611
+ }
612
+ /**
613
+ * Bridged WS connection. Mirrors the surface of a browser WebSocket
614
+ * minus URL/protocol bookkeeping — the host already chose those when
615
+ * calling `forwardWebSocket`. Messages are typed as text (UTF-8 string)
616
+ * or binary (Uint8Array); the bridge preserves the upstream's framing.
617
+ */
618
+ interface TunnelWebSocket {
619
+ /** True until `close` runs in either direction. */
620
+ readonly readyState: "open" | "closing" | "closed";
621
+ /** Selected subprotocol from the upstream's upgrade response, if any. */
622
+ readonly protocol: string | null;
623
+ /** Send a frame to the daemon's upstream. No-op when not open. */
624
+ send(data: string | Uint8Array): void;
625
+ /** Initiate a clean close. Idempotent. */
626
+ close(code?: number, reason?: string): void;
627
+ /** Subscribe to inbound frames. Returns an unsubscribe fn. */
628
+ onMessage(listener: (data: Buffer, isBinary: boolean) => void): () => void;
629
+ /** Subscribe to close. Fires exactly once (after either side closes
630
+ * OR the tunnel itself drops). Returns an unsubscribe fn. */
631
+ onClose(listener: (code: number, reason: string) => void): () => void;
632
+ /** Subscribe to transport-level errors. Closes follow shortly. */
633
+ onError(listener: (err: Error) => void): () => void;
634
+ }
363
635
  interface TunnelClientOptions {
364
636
  sink: FrameSink;
365
637
  /**
@@ -374,6 +646,10 @@ interface TunnelSpawnOptions {
374
646
  env?: Readonly<Record<string, string>>;
375
647
  /** Allocate a PTY on the daemon. Requires `hello.capabilities.pty`. */
376
648
  pty?: boolean;
649
+ /** Initial PTY column width (ignored when `pty` is false). Default 80. */
650
+ cols?: number;
651
+ /** Initial PTY row height (ignored when `pty` is false). Default 24. */
652
+ rows?: number;
377
653
  }
378
654
  /**
379
655
  * Minimal ChildProcess-shaped duck. Covers the surface our ACP arm
@@ -389,6 +665,8 @@ interface TunnelChildProcess {
389
665
  on(event: "exit", listener: (code: number | null, signal: string | null) => void): this;
390
666
  on(event: "error", listener: (err: Error) => void): this;
391
667
  kill(signal?: NodeJS.Signals | number): boolean;
668
+ /** Send a terminal resize to the daemon. No-op if the exec isn't PTY-backed. */
669
+ resize(cols: number, rows: number): void;
392
670
  }
393
671
  interface TunnelClient {
394
672
  /**
@@ -405,8 +683,31 @@ interface TunnelClient {
405
683
  * which this promise resolves to. Rejects on tunnel-transport
406
684
  * failure; the daemon-reported HTTP status (incl. 5xx) is returned
407
685
  * in the resolved value.
686
+ *
687
+ * Streaming responses (text/event-stream, NDJSON) are buffered into
688
+ * the returned Buffer. For real streaming, use `forwardHttpStream`.
408
689
  */
409
690
  forwardHttp(req: TunnelHttpRequest): Promise<TunnelHttpResponse>;
691
+ /**
692
+ * Stream an HTTP response through the tunnel. The promise resolves
693
+ * as soon as the response head (status + headers) arrives — the
694
+ * body chunks then flow through `body` (a ReadableStream) until the
695
+ * daemon's upstream closes. Required for SSE / NDJSON / long-poll
696
+ * upstreams where buffering until the end would defeat the point.
697
+ * For one-shot HTTP, prefer `forwardHttp`.
698
+ */
699
+ forwardHttpStream(req: TunnelHttpRequest): Promise<TunnelHttpStreamResponse>;
700
+ /**
701
+ * Open a bridged WebSocket through the tunnel. The promise resolves
702
+ * once the daemon has completed the upstream upgrade; from that
703
+ * point messages flow via the returned `TunnelWebSocket`.
704
+ *
705
+ * Rejects on:
706
+ * - missing `hello.capabilities.wsForward` — older daemon, no bridge
707
+ * - upstream upgrade failure (4xx/5xx) — `cause` carries the status
708
+ * - timeout waiting for `ws_open_ack`
709
+ */
710
+ forwardWebSocket(req: TunnelWebSocketOpenRequest): Promise<TunnelWebSocket>;
410
711
  close(): Promise<void>;
411
712
  }
412
713
  declare function createTunnelClient(opts: TunnelClientOptions): TunnelClient;
@@ -439,4 +740,4 @@ interface WebSocketLike {
439
740
  }
440
741
  declare function wrapWebSocket(ws: WebSocketLike): FrameSink;
441
742
 
442
- export { type DaemonToHostFrame, type ErrorFrame, type ExitFrame, type FrameSink, type HelloFrame, type HostToDaemonFrame, type KillFrame, type PingFrame, type PongFrame, type ResizeFrame, type SpawnFrame, type SpawnedFrame, type StderrFrame, type StdinFrame, type StdoutFrame, TUNNEL_VERSION, type TunnelChildProcess, type TunnelClient, type TunnelClientOptions, type TunnelFrame, type TunnelServer, type TunnelServerOptions, type TunnelSpawnOptions, type WebSocketLike, createTunnelClient, createTunnelServer, decodeData, encodeData, encodeFrame, parseFrame, wrapWebSocket };
743
+ export { type DaemonToHostFrame, type ErrorFrame, type ExitFrame, type FrameSink, type HelloFrame, type HostToDaemonFrame, type KillFrame, type PingFrame, type PongFrame, type PtyProcess, type ReconnectSoonFrame, type ResizeFrame, type SpawnFrame, type SpawnedFrame, type StderrFrame, type StdinFrame, type StdoutFrame, TUNNEL_VERSION, type TunnelChildProcess, type TunnelClient, type TunnelClientOptions, type TunnelFrame, type TunnelHttpRequest, type TunnelHttpResponse, type TunnelHttpStreamResponse, type TunnelServer, type TunnelServerOptions, type TunnelSpawnOptions, type TunnelWebSocket, type TunnelWebSocketOpenRequest, type UpstreamWebSocket, type WebSocketLike, type WsCloseFrame, type WsMessageFrame, type WsOpenAckFrame, type WsOpenFrame, createTunnelClient, createTunnelServer, decodeData, encodeData, encodeFrame, parseFrame, wrapWebSocket };