@boxide/protocol-rbep 0.1.0 → 0.1.1

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/index.d.mts CHANGED
@@ -2161,6 +2161,66 @@ declare const RbepService: GenService<{
2161
2161
  output: typeof SessionResponseSchema;
2162
2162
  };
2163
2163
  }>;
2164
+ interface ExecStartedInfo {
2165
+ readonly pid: bigint;
2166
+ /** Server-assigned handle for `ExecAttach` when `exec.hold` is active; empty otherwise. */
2167
+ readonly process: string;
2168
+ }
2169
+ type ExecExitStatus = {
2170
+ readonly code: number;
2171
+ readonly signal?: undefined;
2172
+ } | {
2173
+ readonly code?: undefined;
2174
+ readonly signal: string;
2175
+ };
2176
+ interface ExecOptions {
2177
+ clearEnv?: boolean;
2178
+ cwd?: string;
2179
+ env?: Record<string, string>;
2180
+ extensions?: Record<string, Uint8Array>;
2181
+ noStdin?: boolean;
2182
+ }
2183
+ interface PtyOptions {
2184
+ clearEnv?: boolean;
2185
+ cols?: number;
2186
+ cwd?: string;
2187
+ env?: Record<string, string>;
2188
+ extensions?: Record<string, Uint8Array>;
2189
+ rows?: number;
2190
+ }
2191
+ /**
2192
+ * Programmatic handle for a piped remote process (separate `stdout` and `stderr`,
2193
+ * writable `stdin`, and pull-based RBEP credit backpressure via Web Streams).
2194
+ */
2195
+ interface ExecProcess {
2196
+ close: (code?: StatusCode, message?: string) => void;
2197
+ eof: () => Promise<void>;
2198
+ readonly exited: Promise<ExecExitStatus>;
2199
+ readonly id: number;
2200
+ kill: () => Promise<void>;
2201
+ signal: (name: string) => Promise<void>;
2202
+ readonly started: Promise<ExecStartedInfo>;
2203
+ readonly stderr: ReadableStream<Uint8Array>;
2204
+ readonly stdin: WritableStream<Uint8Array>;
2205
+ readonly stdout: ReadableStream<Uint8Array>;
2206
+ write: (data: Uint8Array | string) => Promise<void>;
2207
+ }
2208
+ /**
2209
+ * Programmatic handle for an interactive remote PTY session (combined `output`
2210
+ * stream, writable `input`, `resize`, and pull-based RBEP credit backpressure).
2211
+ */
2212
+ interface PtySession {
2213
+ close: (code?: StatusCode, message?: string) => void;
2214
+ readonly exited: Promise<ExecExitStatus>;
2215
+ readonly id: number;
2216
+ readonly input: WritableStream<Uint8Array>;
2217
+ kill: () => Promise<void>;
2218
+ readonly output: ReadableStream<Uint8Array>;
2219
+ resize: (rows: number, cols: number) => Promise<void>;
2220
+ signal: (name: string) => Promise<void>;
2221
+ readonly started: Promise<ExecStartedInfo>;
2222
+ write: (data: Uint8Array | string) => Promise<void>;
2223
+ }
2164
2224
  declare const PROTOCOL_MAJOR = 1;
2165
2225
  declare const PROTOCOL_MINOR = 0;
2166
2226
  /** Spec §4: liveness. */
@@ -2308,6 +2368,16 @@ declare class ClientSession extends SessionCore<ClientStream> {
2308
2368
  connect(): Promise<Welcome>;
2309
2369
  /** Opens an exec stream and returns a handle for sending stdin/resize/signals. */
2310
2370
  openExec(start: MessageInitShape<typeof ExecStartSchema>, handlers: ExecStreamHandlers): ExecStreamHandle;
2371
+ /**
2372
+ * Opens a piped remote process with Web Streams `stdin`/`stdout`/`stderr`
2373
+ * and pull-based RBEP credit backpressure.
2374
+ */
2375
+ exec(argv: string[], options?: ExecOptions): ExecProcess;
2376
+ /**
2377
+ * Opens an interactive remote PTY session with Web Streams `input`/`output`,
2378
+ * `resize`, and pull-based RBEP credit backpressure.
2379
+ */
2380
+ pty(argv?: string[], options?: PtyOptions): PtySession;
2311
2381
  close(code?: StatusCode, message?: string): void;
2312
2382
  protected dispatch(frame: Frame): void;
2313
2383
  protected onFinish(reason: {
@@ -2400,4 +2470,4 @@ declare class FrameDecoder {
2400
2470
  /** A WebSocket message holds whole frames only: none may span two messages (spec §3). */
2401
2471
  message(data: Uint8Array): Frame[];
2402
2472
  }
2403
- export { type BaseStream, ClientSession, type ClientSessionOptions, Credit, CreditSchema, ExecAttach, ExecAttachSchema, ExecExited, ExecExitedSchema, ExecGap, ExecGapSchema, ExecInput, ExecInputSchema, ExecOutput, ExecOutputSchema, ExecStart, ExecStartSchema, ExecStarted, ExecStartedSchema, type ExecStreamHandle, type ExecStreamHandlers, Frame, type FrameBody, FrameDecoder, FrameSchema, FsAttr, FsAttrReply, FsAttrReplySchema, FsAttrSchema, FsCreate, FsCreateAndWrite, FsCreateAndWriteSchema, FsCreateSchema, FsCreated, FsCreatedSchema, FsData, FsDataSchema, FsDirEntry, FsDirEntrySchema, FsEntry, FsEntrySchema, FsError, FsErrorSchema, FsFileType, FsFileTypeSchema, FsFlush, FsFlushSchema, FsForget, FsForgetItem, FsForgetItemSchema, FsForgetSchema, FsFsync, FsFsyncSchema, FsGetAttr, FsGetAttrSchema, FsGetLock, FsGetLockSchema, FsLink, FsLinkSchema, FsLinkTarget, FsLinkTargetSchema, FsLockMode, FsLockModeSchema, FsLockRange, FsLockRangeSchema, FsLockReply, FsLockReplySchema, FsLockType, FsLockTypeSchema, FsLookup, FsLookupSchema, FsMkdir, FsMkdirSchema, FsMount, FsMountSchema, FsMounted, FsMountedSchema, FsOk, FsOkSchema, FsOpen, FsOpenSchema, FsOpened, FsOpenedSchema, FsPrefetchDir, FsPrefetchDirSchema, FsPrefetchTree, FsPrefetchTreeReply, FsPrefetchTreeReplySchema, FsPrefetchTreeSchema, FsRead, FsReadDirPlus, FsReadDirPlusReply, FsReadDirPlusReplySchema, FsReadDirPlusSchema, FsReadLink, FsReadLinkSchema, FsReadSchema, FsRelease, FsReleaseSchema, FsRename, FsRenameSchema, FsRequest, FsRequestSchema, FsResponse, FsResponseSchema, FsRmdir, FsRmdirSchema, FsSetAttr, FsSetAttrSchema, FsSetLock, FsSetLockSchema, FsStatFs, FsStatFsReply, FsStatFsReplySchema, FsStatFsSchema, FsSymlink, FsSymlinkSchema, FsUnlink, FsUnlinkSchema, FsWrite, FsWriteSchema, FsWritten, FsWrittenSchema, Hello, HelloSchema, Implementation, ImplementationSchema, MIN_FRAME_BYTES, MISSED_PONGS, PING_INTERVAL_MS, PROTOCOL_MAJOR, PROTOCOL_MINOR, Ping, PingSchema, Pong, PongSchema, RbepService, Refusal, type ServerOptions, ServerSession, SessionClosed, SessionCore, type SessionCoreOptions, SessionRequest, SessionRequestSchema, SessionResponse, SessionResponseSchema, StatusCode, StatusCodeSchema, StreamClose, StreamCloseSchema, type StreamContext, type StreamHandler, StreamOpen, StreamOpenSchema, Version, VersionSchema, Welcome, WelcomeSchema, WindowSize, WindowSizeSchema, WireError, creditedBytes, encodeFrameBatches, encodeFrames, file_rbep_v1_exec, file_rbep_v1_fs, file_rbep_v1_session, frameLimit, initialSessionCredit, initialStreamCredit };
2473
+ export { type BaseStream, ClientSession, type ClientSessionOptions, Credit, CreditSchema, ExecAttach, ExecAttachSchema, type ExecExitStatus, ExecExited, ExecExitedSchema, ExecGap, ExecGapSchema, ExecInput, ExecInputSchema, type ExecOptions, ExecOutput, ExecOutputSchema, type ExecProcess, ExecStart, ExecStartSchema, ExecStarted, type ExecStartedInfo, ExecStartedSchema, type ExecStreamHandle, type ExecStreamHandlers, Frame, type FrameBody, FrameDecoder, FrameSchema, FsAttr, FsAttrReply, FsAttrReplySchema, FsAttrSchema, FsCreate, FsCreateAndWrite, FsCreateAndWriteSchema, FsCreateSchema, FsCreated, FsCreatedSchema, FsData, FsDataSchema, FsDirEntry, FsDirEntrySchema, FsEntry, FsEntrySchema, FsError, FsErrorSchema, FsFileType, FsFileTypeSchema, FsFlush, FsFlushSchema, FsForget, FsForgetItem, FsForgetItemSchema, FsForgetSchema, FsFsync, FsFsyncSchema, FsGetAttr, FsGetAttrSchema, FsGetLock, FsGetLockSchema, FsLink, FsLinkSchema, FsLinkTarget, FsLinkTargetSchema, FsLockMode, FsLockModeSchema, FsLockRange, FsLockRangeSchema, FsLockReply, FsLockReplySchema, FsLockType, FsLockTypeSchema, FsLookup, FsLookupSchema, FsMkdir, FsMkdirSchema, FsMount, FsMountSchema, FsMounted, FsMountedSchema, FsOk, FsOkSchema, FsOpen, FsOpenSchema, FsOpened, FsOpenedSchema, FsPrefetchDir, FsPrefetchDirSchema, FsPrefetchTree, FsPrefetchTreeReply, FsPrefetchTreeReplySchema, FsPrefetchTreeSchema, FsRead, FsReadDirPlus, FsReadDirPlusReply, FsReadDirPlusReplySchema, FsReadDirPlusSchema, FsReadLink, FsReadLinkSchema, FsReadSchema, FsRelease, FsReleaseSchema, FsRename, FsRenameSchema, FsRequest, FsRequestSchema, FsResponse, FsResponseSchema, FsRmdir, FsRmdirSchema, FsSetAttr, FsSetAttrSchema, FsSetLock, FsSetLockSchema, FsStatFs, FsStatFsReply, FsStatFsReplySchema, FsStatFsSchema, FsSymlink, FsSymlinkSchema, FsUnlink, FsUnlinkSchema, FsWrite, FsWriteSchema, FsWritten, FsWrittenSchema, Hello, HelloSchema, Implementation, ImplementationSchema, MIN_FRAME_BYTES, MISSED_PONGS, PING_INTERVAL_MS, PROTOCOL_MAJOR, PROTOCOL_MINOR, Ping, PingSchema, Pong, PongSchema, type PtyOptions, type PtySession, RbepService, Refusal, type ServerOptions, ServerSession, SessionClosed, SessionCore, type SessionCoreOptions, SessionRequest, SessionRequestSchema, SessionResponse, SessionResponseSchema, StatusCode, StatusCodeSchema, StreamClose, StreamCloseSchema, type StreamContext, type StreamHandler, StreamOpen, StreamOpenSchema, Version, VersionSchema, Welcome, WelcomeSchema, WindowSize, WindowSizeSchema, WireError, creditedBytes, encodeFrameBatches, encodeFrames, file_rbep_v1_exec, file_rbep_v1_fs, file_rbep_v1_session, frameLimit, initialSessionCredit, initialStreamCredit };
package/dist/index.mjs CHANGED
@@ -837,6 +837,390 @@ var SessionCore = class {
837
837
  this.coreOptions.end();
838
838
  }
839
839
  };
840
+ // src/session.ts
841
+ /**
842
+ * The server side of one RBEP session over a byte transport (stdio, or a
843
+ * WebSocket whose messages the caller feeds whole through `message`).
844
+ */
845
+ var ServerSession = class extends SessionCore {
846
+ options;
847
+ granted = /* @__PURE__ */ new Set();
848
+ welcomed = false;
849
+ constructor(options) {
850
+ super(options);
851
+ this.options = options;
852
+ }
853
+ dispatch(frame) {
854
+ if (!this.welcomed) {
855
+ if (frame.stream !== 0 || frame.body.case !== "hello") {
856
+ this.finish(3, "the first frame must be Hello on stream 0");
857
+ return;
858
+ }
859
+ this.hello(frame.body.value);
860
+ return;
861
+ }
862
+ if (frame.stream === 0) {
863
+ this.sessionFrame(frame);
864
+ return;
865
+ }
866
+ if (frame.body.case === "open") {
867
+ this.openStream(frame.stream, frame.body.value);
868
+ return;
869
+ }
870
+ const stream = this.streams.get(frame.stream);
871
+ if (!stream) return;
872
+ switch (frame.body.case) {
873
+ case "credit":
874
+ stream.sendAvailable += Number(frame.body.value.bytes);
875
+ this.drainSendWaiters();
876
+ return;
877
+ case "close":
878
+ this.streams.delete(frame.stream);
879
+ this.rejectWaitersFor(stream, new SessionClosed("stream closed"));
880
+ stream.handler?.closed({
881
+ code: frame.body.value.code,
882
+ message: frame.body.value.message
883
+ });
884
+ return;
885
+ default:
886
+ if (this.consumed(frame, stream) === void 0) return;
887
+ stream.handler?.frame(frame);
888
+ }
889
+ }
890
+ hello(hello) {
891
+ if (!hello.versions.find((v) => v.major === 1)) {
892
+ this.finish(6, `no common major version (server speaks 1)`);
893
+ return;
894
+ }
895
+ if (!this.options.checkToken(hello.token)) {
896
+ this.finish(5, "session token refused");
897
+ return;
898
+ }
899
+ const own = new Set(this.options.capabilities);
900
+ this.granted = new Set(hello.capabilities.filter((c) => own.has(c)));
901
+ this.peerFrameLimit = frameLimit(hello.maxFrameBytes);
902
+ this.sessionSendAvailable = initialSessionCredit(this.peerFrameLimit);
903
+ this.welcomed = true;
904
+ this.enqueue(create(FrameSchema, {
905
+ body: {
906
+ case: "welcome",
907
+ value: {
908
+ capabilities: [...this.granted],
909
+ extensions: [],
910
+ holdBufferBytes: 0n,
911
+ holdMs: 0,
912
+ implementation: this.options.implementation,
913
+ maxFrameBytes: this.ownFrameLimit,
914
+ termGraceMs: this.options.termGraceMs ?? 0,
915
+ version: {
916
+ major: 1,
917
+ minor: 0
918
+ }
919
+ }
920
+ },
921
+ stream: 0
922
+ }));
923
+ this.startPinger();
924
+ }
925
+ openStream(id, open) {
926
+ if (id % 2 === 0 || this.streams.has(id)) {
927
+ this.finish(3, `stream ${id} cannot be opened by the client`);
928
+ return;
929
+ }
930
+ const stream = {
931
+ closedBySelf: false,
932
+ recvRemaining: initialStreamCredit(this.ownFrameLimit),
933
+ sendAvailable: initialStreamCredit(this.peerFrameLimit)
934
+ };
935
+ this.streams.set(id, stream);
936
+ const context = {
937
+ close: (code, message = "") => {
938
+ if (stream.closedBySelf || !this.streams.has(id)) return;
939
+ stream.closedBySelf = true;
940
+ this.streams.delete(id);
941
+ this.rejectWaitersFor(stream, new SessionClosed("stream closed"));
942
+ this.enqueue(create(FrameSchema, {
943
+ body: {
944
+ case: "close",
945
+ value: {
946
+ code,
947
+ message
948
+ }
949
+ },
950
+ stream: id
951
+ }));
952
+ },
953
+ granted: this.granted,
954
+ id,
955
+ ownFrameLimit: this.ownFrameLimit,
956
+ peerFrameLimit: this.peerFrameLimit,
957
+ send: (body) => this.sendOnStream(id, stream, body)
958
+ };
959
+ try {
960
+ stream.handler = this.options.open(open, context);
961
+ } catch (error) {
962
+ const refusal = error instanceof Refusal ? error : new Refusal(8, String(error));
963
+ context.close(refusal.code, refusal.message);
964
+ }
965
+ }
966
+ onFinish(reason) {
967
+ for (const stream of this.streams.values()) stream.handler?.closed(reason);
968
+ }
969
+ };
970
+ /** Thrown by `open` to refuse a stream with a status. */
971
+ var Refusal = class extends Error {
972
+ code;
973
+ constructor(code, message) {
974
+ super(message);
975
+ this.code = code;
976
+ }
977
+ };
978
+ // src/process.ts
979
+ const textEncoder = new TextEncoder();
980
+ const createByteStream = (highWaterMark = 16) => {
981
+ let ctrl;
982
+ let closed = false;
983
+ let canceled = false;
984
+ let pullResolve;
985
+ const wakePull = () => {
986
+ if (pullResolve) {
987
+ const resolve = pullResolve;
988
+ pullResolve = void 0;
989
+ resolve();
990
+ }
991
+ };
992
+ return {
993
+ close() {
994
+ if (closed) return;
995
+ closed = true;
996
+ wakePull();
997
+ try {
998
+ ctrl.close();
999
+ } catch {}
1000
+ },
1001
+ error(err) {
1002
+ if (closed) return;
1003
+ closed = true;
1004
+ wakePull();
1005
+ try {
1006
+ ctrl.error(err);
1007
+ } catch {}
1008
+ },
1009
+ push(chunk) {
1010
+ if (closed || canceled) return;
1011
+ ctrl.enqueue(chunk);
1012
+ if (ctrl.desiredSize !== null && ctrl.desiredSize <= 0) return new Promise((resolve) => {
1013
+ pullResolve = resolve;
1014
+ });
1015
+ },
1016
+ stream: new ReadableStream({
1017
+ cancel() {
1018
+ canceled = true;
1019
+ closed = true;
1020
+ wakePull();
1021
+ },
1022
+ pull() {
1023
+ wakePull();
1024
+ },
1025
+ start(controller) {
1026
+ ctrl = controller;
1027
+ }
1028
+ }, { highWaterMark })
1029
+ };
1030
+ };
1031
+ const toBytes = (data) => typeof data === "string" ? textEncoder.encode(data) : data;
1032
+ const createWritableStdin = (handle) => new WritableStream({
1033
+ abort() {
1034
+ handle.close(2, "stdin aborted");
1035
+ },
1036
+ close() {
1037
+ return handle.sendStdinEof();
1038
+ },
1039
+ write(chunk) {
1040
+ return handle.sendStdin(chunk);
1041
+ }
1042
+ });
1043
+ const closeError = (reason) => reason.code === 7 ? new SessionClosed(reason.message || "session closed") : new Refusal(reason.code, reason.message || `stream closed (${reason.code})`);
1044
+ function createExecProcess(session, argv, options = {}) {
1045
+ const stdout = createByteStream();
1046
+ const stderr = createByteStream();
1047
+ let startedSettled = false;
1048
+ let resolveStarted;
1049
+ let rejectStarted;
1050
+ const started = new Promise((resolve, reject) => {
1051
+ resolveStarted = resolve;
1052
+ rejectStarted = reject;
1053
+ });
1054
+ let exitedSettled = false;
1055
+ let resolveExited;
1056
+ let rejectExited;
1057
+ const exited = new Promise((resolve, reject) => {
1058
+ resolveExited = resolve;
1059
+ rejectExited = reject;
1060
+ });
1061
+ const handle = session.openExec({
1062
+ argv,
1063
+ clearEnv: options.clearEnv ?? false,
1064
+ cwd: options.cwd ?? "",
1065
+ env: options.env ?? {},
1066
+ extensions: options.extensions ?? {},
1067
+ noStdin: options.noStdin ?? false
1068
+ }, {
1069
+ onClose: (reason) => {
1070
+ if (reason.code !== 1 && !exitedSettled) {
1071
+ const err = closeError(reason);
1072
+ if (!startedSettled) {
1073
+ startedSettled = true;
1074
+ rejectStarted(err);
1075
+ }
1076
+ exitedSettled = true;
1077
+ rejectExited(err);
1078
+ stdout.error(err);
1079
+ stderr.error(err);
1080
+ return;
1081
+ }
1082
+ stdout.close();
1083
+ stderr.close();
1084
+ if (!startedSettled) {
1085
+ startedSettled = true;
1086
+ rejectStarted(new SessionClosed("exec stream closed before started"));
1087
+ }
1088
+ if (!exitedSettled) {
1089
+ exitedSettled = true;
1090
+ rejectExited(new SessionClosed("exec stream closed before exit status"));
1091
+ }
1092
+ },
1093
+ onOutput: (output) => {
1094
+ switch (output.body.case) {
1095
+ case "started":
1096
+ if (!startedSettled) {
1097
+ startedSettled = true;
1098
+ resolveStarted({
1099
+ pid: output.body.value.pid,
1100
+ process: output.body.value.process
1101
+ });
1102
+ }
1103
+ return;
1104
+ case "stdout": return stdout.push(output.body.value);
1105
+ case "stderr": return stderr.push(output.body.value);
1106
+ case "exited":
1107
+ if (!exitedSettled) {
1108
+ exitedSettled = true;
1109
+ const status = output.body.value.status;
1110
+ if (status.case === "code") resolveExited({ code: status.value });
1111
+ else if (status.case === "signal") resolveExited({ signal: status.value });
1112
+ else resolveExited({ code: 0 });
1113
+ }
1114
+ return;
1115
+ default: return;
1116
+ }
1117
+ }
1118
+ });
1119
+ started.catch(() => {});
1120
+ return {
1121
+ close: (code, message) => handle.close(code, message),
1122
+ eof: () => handle.sendStdinEof(),
1123
+ exited,
1124
+ id: handle.id,
1125
+ kill: () => handle.signal("KILL"),
1126
+ signal: (name) => handle.signal(name),
1127
+ started,
1128
+ stderr: stderr.stream,
1129
+ stdin: createWritableStdin(handle),
1130
+ stdout: stdout.stream,
1131
+ write: (data) => handle.sendStdin(toBytes(data))
1132
+ };
1133
+ }
1134
+ function createPtySession(session, argv = [], options = {}) {
1135
+ const output = createByteStream();
1136
+ let startedSettled = false;
1137
+ let resolveStarted;
1138
+ let rejectStarted;
1139
+ const started = new Promise((resolve, reject) => {
1140
+ resolveStarted = resolve;
1141
+ rejectStarted = reject;
1142
+ });
1143
+ let exitedSettled = false;
1144
+ let resolveExited;
1145
+ let rejectExited;
1146
+ const exited = new Promise((resolve, reject) => {
1147
+ resolveExited = resolve;
1148
+ rejectExited = reject;
1149
+ });
1150
+ const handle = session.openExec({
1151
+ argv,
1152
+ clearEnv: options.clearEnv ?? false,
1153
+ cwd: options.cwd ?? "",
1154
+ env: options.env ?? {},
1155
+ extensions: options.extensions ?? {},
1156
+ noStdin: false,
1157
+ tty: {
1158
+ cols: options.cols ?? 80,
1159
+ rows: options.rows ?? 24
1160
+ }
1161
+ }, {
1162
+ onClose: (reason) => {
1163
+ if (reason.code !== 1 && !exitedSettled) {
1164
+ const err = closeError(reason);
1165
+ if (!startedSettled) {
1166
+ startedSettled = true;
1167
+ rejectStarted(err);
1168
+ }
1169
+ exitedSettled = true;
1170
+ rejectExited(err);
1171
+ output.error(err);
1172
+ return;
1173
+ }
1174
+ output.close();
1175
+ if (!startedSettled) {
1176
+ startedSettled = true;
1177
+ rejectStarted(new SessionClosed("pty stream closed before started"));
1178
+ }
1179
+ if (!exitedSettled) {
1180
+ exitedSettled = true;
1181
+ rejectExited(new SessionClosed("pty stream closed before exit status"));
1182
+ }
1183
+ },
1184
+ onOutput: (msg) => {
1185
+ switch (msg.body.case) {
1186
+ case "started":
1187
+ if (!startedSettled) {
1188
+ startedSettled = true;
1189
+ resolveStarted({
1190
+ pid: msg.body.value.pid,
1191
+ process: msg.body.value.process
1192
+ });
1193
+ }
1194
+ return;
1195
+ case "stdout":
1196
+ case "stderr": return output.push(msg.body.value);
1197
+ case "exited":
1198
+ if (!exitedSettled) {
1199
+ exitedSettled = true;
1200
+ const status = msg.body.value.status;
1201
+ if (status.case === "code") resolveExited({ code: status.value });
1202
+ else if (status.case === "signal") resolveExited({ signal: status.value });
1203
+ else resolveExited({ code: 0 });
1204
+ }
1205
+ return;
1206
+ default: return;
1207
+ }
1208
+ }
1209
+ });
1210
+ started.catch(() => {});
1211
+ return {
1212
+ close: (code, message) => handle.close(code, message),
1213
+ exited,
1214
+ id: handle.id,
1215
+ input: createWritableStdin(handle),
1216
+ kill: () => handle.signal("KILL"),
1217
+ output: output.stream,
1218
+ resize: (rows, cols) => handle.resize(rows, cols),
1219
+ signal: (name) => handle.signal(name),
1220
+ started,
1221
+ write: (data) => handle.sendStdin(toBytes(data))
1222
+ };
1223
+ }
840
1224
  // src/client.ts
841
1225
  /**
842
1226
  * The client side of one RBEP v1 session over a byte transport (stdio via
@@ -1004,6 +1388,20 @@ var ClientSession = class extends SessionCore {
1004
1388
  })
1005
1389
  };
1006
1390
  }
1391
+ /**
1392
+ * Opens a piped remote process with Web Streams `stdin`/`stdout`/`stderr`
1393
+ * and pull-based RBEP credit backpressure.
1394
+ */
1395
+ exec(argv, options) {
1396
+ return createExecProcess(this, argv, options);
1397
+ }
1398
+ /**
1399
+ * Opens an interactive remote PTY session with Web Streams `input`/`output`,
1400
+ * `resize`, and pull-based RBEP credit backpressure.
1401
+ */
1402
+ pty(argv = [], options) {
1403
+ return createPtySession(this, argv, options);
1404
+ }
1007
1405
  close(code = 1, message = "") {
1008
1406
  this.finish(code, message, true);
1009
1407
  }
@@ -1067,142 +1465,4 @@ var ClientSession = class extends SessionCore {
1067
1465
  else stream.onClose?.(reason);
1068
1466
  }
1069
1467
  };
1070
- // src/session.ts
1071
- /**
1072
- * The server side of one RBEP session over a byte transport (stdio, or a
1073
- * WebSocket whose messages the caller feeds whole through `message`).
1074
- */
1075
- var ServerSession = class extends SessionCore {
1076
- options;
1077
- granted = /* @__PURE__ */ new Set();
1078
- welcomed = false;
1079
- constructor(options) {
1080
- super(options);
1081
- this.options = options;
1082
- }
1083
- dispatch(frame) {
1084
- if (!this.welcomed) {
1085
- if (frame.stream !== 0 || frame.body.case !== "hello") {
1086
- this.finish(3, "the first frame must be Hello on stream 0");
1087
- return;
1088
- }
1089
- this.hello(frame.body.value);
1090
- return;
1091
- }
1092
- if (frame.stream === 0) {
1093
- this.sessionFrame(frame);
1094
- return;
1095
- }
1096
- if (frame.body.case === "open") {
1097
- this.openStream(frame.stream, frame.body.value);
1098
- return;
1099
- }
1100
- const stream = this.streams.get(frame.stream);
1101
- if (!stream) return;
1102
- switch (frame.body.case) {
1103
- case "credit":
1104
- stream.sendAvailable += Number(frame.body.value.bytes);
1105
- this.drainSendWaiters();
1106
- return;
1107
- case "close":
1108
- this.streams.delete(frame.stream);
1109
- this.rejectWaitersFor(stream, new SessionClosed("stream closed"));
1110
- stream.handler?.closed({
1111
- code: frame.body.value.code,
1112
- message: frame.body.value.message
1113
- });
1114
- return;
1115
- default:
1116
- if (this.consumed(frame, stream) === void 0) return;
1117
- stream.handler?.frame(frame);
1118
- }
1119
- }
1120
- hello(hello) {
1121
- if (!hello.versions.find((v) => v.major === 1)) {
1122
- this.finish(6, `no common major version (server speaks 1)`);
1123
- return;
1124
- }
1125
- if (!this.options.checkToken(hello.token)) {
1126
- this.finish(5, "session token refused");
1127
- return;
1128
- }
1129
- const own = new Set(this.options.capabilities);
1130
- this.granted = new Set(hello.capabilities.filter((c) => own.has(c)));
1131
- this.peerFrameLimit = frameLimit(hello.maxFrameBytes);
1132
- this.sessionSendAvailable = initialSessionCredit(this.peerFrameLimit);
1133
- this.welcomed = true;
1134
- this.enqueue(create(FrameSchema, {
1135
- body: {
1136
- case: "welcome",
1137
- value: {
1138
- capabilities: [...this.granted],
1139
- extensions: [],
1140
- holdBufferBytes: 0n,
1141
- holdMs: 0,
1142
- implementation: this.options.implementation,
1143
- maxFrameBytes: this.ownFrameLimit,
1144
- termGraceMs: this.options.termGraceMs ?? 0,
1145
- version: {
1146
- major: 1,
1147
- minor: 0
1148
- }
1149
- }
1150
- },
1151
- stream: 0
1152
- }));
1153
- this.startPinger();
1154
- }
1155
- openStream(id, open) {
1156
- if (id % 2 === 0 || this.streams.has(id)) {
1157
- this.finish(3, `stream ${id} cannot be opened by the client`);
1158
- return;
1159
- }
1160
- const stream = {
1161
- closedBySelf: false,
1162
- recvRemaining: initialStreamCredit(this.ownFrameLimit),
1163
- sendAvailable: initialStreamCredit(this.peerFrameLimit)
1164
- };
1165
- this.streams.set(id, stream);
1166
- const context = {
1167
- close: (code, message = "") => {
1168
- if (stream.closedBySelf || !this.streams.has(id)) return;
1169
- stream.closedBySelf = true;
1170
- this.streams.delete(id);
1171
- this.rejectWaitersFor(stream, new SessionClosed("stream closed"));
1172
- this.enqueue(create(FrameSchema, {
1173
- body: {
1174
- case: "close",
1175
- value: {
1176
- code,
1177
- message
1178
- }
1179
- },
1180
- stream: id
1181
- }));
1182
- },
1183
- granted: this.granted,
1184
- id,
1185
- ownFrameLimit: this.ownFrameLimit,
1186
- peerFrameLimit: this.peerFrameLimit,
1187
- send: (body) => this.sendOnStream(id, stream, body)
1188
- };
1189
- try {
1190
- stream.handler = this.options.open(open, context);
1191
- } catch (error) {
1192
- const refusal = error instanceof Refusal ? error : new Refusal(8, String(error));
1193
- context.close(refusal.code, refusal.message);
1194
- }
1195
- }
1196
- onFinish(reason) {
1197
- for (const stream of this.streams.values()) stream.handler?.closed(reason);
1198
- }
1199
- };
1200
- /** Thrown by `open` to refuse a stream with a status. */
1201
- var Refusal = class extends Error {
1202
- code;
1203
- constructor(code, message) {
1204
- super(message);
1205
- this.code = code;
1206
- }
1207
- };
1208
1468
  export { ClientSession, CreditSchema, ExecAttachSchema, ExecExitedSchema, ExecGapSchema, ExecInputSchema, ExecOutputSchema, ExecStartSchema, ExecStartedSchema, FrameDecoder, FrameSchema, FsAttrReplySchema, FsAttrSchema, FsCreateAndWriteSchema, FsCreateSchema, FsCreatedSchema, FsDataSchema, FsDirEntrySchema, FsEntrySchema, FsErrorSchema, FsFileType, FsFileTypeSchema, FsFlushSchema, FsForgetItemSchema, FsForgetSchema, FsFsyncSchema, FsGetAttrSchema, FsGetLockSchema, FsLinkSchema, FsLinkTargetSchema, FsLockMode, FsLockModeSchema, FsLockRangeSchema, FsLockReplySchema, FsLockType, FsLockTypeSchema, FsLookupSchema, FsMkdirSchema, FsMountSchema, FsMountedSchema, FsOkSchema, FsOpenSchema, FsOpenedSchema, FsPrefetchDirSchema, FsPrefetchTreeReplySchema, FsPrefetchTreeSchema, FsReadDirPlusReplySchema, FsReadDirPlusSchema, FsReadLinkSchema, FsReadSchema, FsReleaseSchema, FsRenameSchema, FsRequestSchema, FsResponseSchema, FsRmdirSchema, FsSetAttrSchema, FsSetLockSchema, FsStatFsReplySchema, FsStatFsSchema, FsSymlinkSchema, FsUnlinkSchema, FsWriteSchema, FsWrittenSchema, HelloSchema, ImplementationSchema, MIN_FRAME_BYTES, MISSED_PONGS, PING_INTERVAL_MS, PROTOCOL_MAJOR, PROTOCOL_MINOR, PingSchema, PongSchema, RbepService, Refusal, ServerSession, SessionClosed, SessionCore, SessionRequestSchema, SessionResponseSchema, StatusCode, StatusCodeSchema, StreamCloseSchema, StreamOpenSchema, VersionSchema, WelcomeSchema, WindowSizeSchema, WireError, creditedBytes, encodeFrameBatches, encodeFrames, file_rbep_v1_exec, file_rbep_v1_fs, file_rbep_v1_session, frameLimit, initialSessionCredit, initialStreamCredit };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@boxide/protocol-rbep",
3
- "version": "0.1.0",
3
+ "version": "0.1.1",
4
4
  "description": "Runtime-agnostic RBEP v1 wire framing, session state machines, and Protobuf types",
5
5
  "type": "module",
6
6
  "license": "Apache-2.0",