withruntime 0.46.2 → 0.47.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.
package/dist/cli.js CHANGED
@@ -2299,6 +2299,26 @@ async function sandbox(argv, env, out) {
2299
2299
  print(describe(sbx.info), sbx.info);
2300
2300
  return 0;
2301
2301
  }
2302
+ case "never-park": {
2303
+ // Runtime's own operator only, so not in the help: the release path's
2304
+ // sandboxes (the release signer's, the agents' hub) are never parked to
2305
+ // make room (Marc, 28 October 2026). The API refuses it for any other
2306
+ // organization, and for a key that is not an owner's, an admin's or
2307
+ // account-wide (20261028190617_cloud_never_park.sql).
2308
+ const args = parse(rest, [], []);
2309
+ const value = args.positional[1];
2310
+ if (args.positional.length !== 2 || (value !== "on" && value !== "off"))
2311
+ throw usage("runtime sandboxes never-park <id> on|off");
2312
+ const sbx = await get(args.positional[0]);
2313
+ const info = await runtime.transport.json({
2314
+ method: "POST",
2315
+ path: `/v1/sandboxes/${encodeURIComponent(sbx.id)}:update`,
2316
+ body: {},
2317
+ headers: { "runtime-never-park": value === "on" ? "true" : "false" },
2318
+ });
2319
+ print(`${sbx.id} never parked: ${info.neverPark === true ? "on" : "off"}`, info);
2320
+ return 0;
2321
+ }
2302
2322
  case "extend": {
2303
2323
  const sbx = await get(rest[0]);
2304
2324
  const seconds = Number(need(rest[1], "seconds, e.g. runtime sandboxes extend <id> 600"));
@@ -0,0 +1,32 @@
1
+ /** RFC 6455 close code 1012, Service Restart. */
2
+ export declare const SERVICE_RESTART = 1012;
3
+ /** How long reconnecting may take before the socket is reported closed:
4
+ * within the token's 30 s, after which the API ends the process. */
5
+ export declare const RESUME_MS = 25000;
6
+ type Message = {
7
+ data: string | ArrayBuffer;
8
+ };
9
+ type Closed = {
10
+ code: number;
11
+ reason: string;
12
+ };
13
+ /** The part of WebSocket that Terminal and Tunnel use. */
14
+ export declare class ResumableSocket {
15
+ #private;
16
+ binaryType: string;
17
+ onmessage: ((event: Message) => void) | null;
18
+ onclose: ((event: Closed) => void) | null;
19
+ onerror: ((event: unknown) => void) | null;
20
+ /** Times this socket resumed, and of those how many replayed input the
21
+ * API had not yet written, for tests and diagnostics. */
22
+ resumes: number;
23
+ replays: number;
24
+ private constructor();
25
+ /** `open` opens the API's WebSocket, with `resume` once there is a token. */
26
+ static open(open: (resume?: string) => Promise<WebSocket>): Promise<ResumableSocket>;
27
+ /** OPEN (1) while it is open or resuming, CLOSED (3) once it closed. */
28
+ get readyState(): number;
29
+ send(data: string | Uint8Array): void;
30
+ close(code?: number, reason?: string): void;
31
+ }
32
+ export {};
@@ -0,0 +1,201 @@
1
+ /* A terminal's or tunnel's WebSocket that outlives a restart of the API
2
+ behind it. The API hands each open socket to the instance that serves next
3
+ (packages/cloud/src/api/tunnels.ts, "Hand-off"):
4
+
5
+ 1. it sends {"type":"restart"}; this side stops sending, buffers what the
6
+ caller writes, and answers {"type":"restart"};
7
+ 2. it sends {"type":"resume","token":...,"replay":...} and closes with
8
+ 1012 (Service Restart);
9
+ 3. this side opens the socket again with ?resume=<token>, sends
10
+ {"type":"replay","data":...} first when there was input the API had not
11
+ yet written, then what it buffered.
12
+
13
+ The terminal's output and the tunnel's streams continue from the exact
14
+ byte they stopped at; nothing is lost or repeated, and the caller sees no
15
+ close. A socket closed with anything else, or without a token, closes as
16
+ before. */
17
+ /** RFC 6455 close code 1012, Service Restart. */
18
+ export const SERVICE_RESTART = 1012;
19
+ /** How long reconnecting may take before the socket is reported closed:
20
+ * within the token's 30 s, after which the API ends the process. */
21
+ export const RESUME_MS = 25_000;
22
+ /** The part of WebSocket that Terminal and Tunnel use. */
23
+ export class ResumableSocket {
24
+ binaryType = "arraybuffer";
25
+ onmessage = null;
26
+ onclose = null;
27
+ onerror = null;
28
+ #socket;
29
+ #open;
30
+ #paused = false;
31
+ #outbox = [];
32
+ #token;
33
+ #replay;
34
+ #closed = false;
35
+ /** Times this socket resumed, and of those how many replayed input the
36
+ * API had not yet written, for tests and diagnostics. */
37
+ resumes = 0;
38
+ replays = 0;
39
+ constructor(socket, open) {
40
+ this.#socket = socket;
41
+ this.#open = open;
42
+ this.#attach(socket);
43
+ }
44
+ /** `open` opens the API's WebSocket, with `resume` once there is a token. */
45
+ static async open(open) {
46
+ return new ResumableSocket(await open(), open);
47
+ }
48
+ /** OPEN (1) while it is open or resuming, CLOSED (3) once it closed. */
49
+ get readyState() {
50
+ return this.#closed ? 3 : this.#socket.readyState === 0 ? 0 : 1;
51
+ }
52
+ send(data) {
53
+ if (this.#closed)
54
+ return;
55
+ if (this.#paused)
56
+ this.#outbox.push(data);
57
+ else
58
+ this.#socket.send(data);
59
+ }
60
+ close(code = 1000, reason) {
61
+ if (this.#closed)
62
+ return;
63
+ this.#closed = true;
64
+ this.#outbox = [];
65
+ try {
66
+ this.#socket.close(code, reason);
67
+ }
68
+ catch {
69
+ // Closed already.
70
+ }
71
+ // A socket closed while resuming has no close event of its own to wait for.
72
+ if (this.#paused)
73
+ this.onclose?.({ code, reason: reason ?? "" });
74
+ }
75
+ #attach(socket) {
76
+ socket.binaryType = "arraybuffer";
77
+ socket.onmessage = (event) => {
78
+ if (socket !== this.#socket)
79
+ return;
80
+ if (typeof event.data === "string") {
81
+ let message;
82
+ try {
83
+ message = JSON.parse(event.data);
84
+ }
85
+ catch {
86
+ message = undefined;
87
+ }
88
+ if (message?.type === "restart") {
89
+ this.#paused = true;
90
+ socket.send(JSON.stringify({ type: "restart" }));
91
+ return;
92
+ }
93
+ if (message?.type === "resume" && typeof message.token === "string") {
94
+ this.#token = message.token;
95
+ this.#replay = typeof message.replay === "string" ? message.replay : undefined;
96
+ return;
97
+ }
98
+ }
99
+ this.onmessage?.({ data: event.data });
100
+ };
101
+ socket.onclose = (event) => {
102
+ if (socket !== this.#socket || this.#closed)
103
+ return;
104
+ if (event.code === SERVICE_RESTART && this.#token)
105
+ return void this.#resume();
106
+ this.#closed = true;
107
+ this.onclose?.({ code: event.code, reason: event.reason });
108
+ };
109
+ socket.onerror = (event) => {
110
+ if (socket === this.#socket)
111
+ this.onerror?.(event);
112
+ };
113
+ }
114
+ async #resume() {
115
+ const token = this.#token;
116
+ const replay = this.#replay;
117
+ this.#token = this.#replay = undefined;
118
+ const deadline = Date.now() + RESUME_MS;
119
+ let failure = { code: 1006, reason: "The connection could not be resumed." };
120
+ for (let wait = 50; Date.now() < deadline && !this.#closed; wait = Math.min(wait * 2, 1000)) {
121
+ const answer = await this.#reopen(token, replay);
122
+ if ("socket" in answer)
123
+ return;
124
+ if (answer.final) {
125
+ // The API refused this resume for good (the sandbox stopped, say):
126
+ // its error is the caller's, as on any socket.
127
+ this.onmessage?.({ data: answer.final });
128
+ failure = answer.closed;
129
+ break;
130
+ }
131
+ failure = answer.closed;
132
+ await new Promise((resolve) => setTimeout(resolve, wait));
133
+ }
134
+ if (this.#closed)
135
+ return;
136
+ this.#closed = true;
137
+ this.#outbox = [];
138
+ this.onclose?.(failure);
139
+ }
140
+ #resumed(socket, replay) {
141
+ this.#socket = socket;
142
+ this.#attach(socket);
143
+ this.resumes++;
144
+ if (replay) {
145
+ this.replays++;
146
+ socket.send(JSON.stringify({ type: "replay", data: replay }));
147
+ }
148
+ const outbox = this.#outbox;
149
+ this.#outbox = [];
150
+ this.#paused = false;
151
+ for (const data of outbox)
152
+ socket.send(data);
153
+ }
154
+ /** One attempt: the socket, in use once the API said it resumed, or how it
155
+ * ended. */
156
+ async #reopen(token, replay) {
157
+ let socket;
158
+ try {
159
+ socket = await this.#open(token);
160
+ }
161
+ catch (error) {
162
+ return {
163
+ closed: {
164
+ code: 1006,
165
+ reason: error instanceof Error ? error.message : "The connection could not be resumed.",
166
+ },
167
+ };
168
+ }
169
+ socket.binaryType = "arraybuffer";
170
+ return new Promise((resolve) => {
171
+ let final;
172
+ socket.onmessage = (event) => {
173
+ if (typeof event.data !== "string")
174
+ return;
175
+ let message;
176
+ try {
177
+ message = JSON.parse(event.data);
178
+ }
179
+ catch {
180
+ return;
181
+ }
182
+ if (message?.type === "ready" && message.resumed === true) {
183
+ // Taken over here, before the next frame: output may follow in the
184
+ // same read, delivered before any promise settles.
185
+ if (this.#closed)
186
+ socket.close(1000);
187
+ else
188
+ this.#resumed(socket, replay);
189
+ resolve({ socket });
190
+ }
191
+ else if (message?.type === "error")
192
+ final = event.data;
193
+ };
194
+ socket.onclose = (event) => resolve({
195
+ closed: { code: event.code, reason: event.reason },
196
+ ...(final ? { final } : {}),
197
+ });
198
+ socket.onerror = () => undefined;
199
+ });
200
+ }
201
+ }
package/dist/sandbox.js CHANGED
@@ -4,6 +4,7 @@ import { sandboxWatches, watchDirectory, } from "./products/watch.js";
4
4
  import { Transport, timeoutSignal } from "./transport.js";
5
5
  import { sandboxFactories } from "./products/index.js";
6
6
  import { Tunnel } from "./tunnel.js";
7
+ import { ResumableSocket } from "./resumable.js";
7
8
  import { pause } from "./wait.js";
8
9
  import { Machine, machinePage, requestOnly } from "./machine.js";
9
10
  /** Sandboxes, as a product of the machine engine (machine.ts). */
@@ -318,14 +319,18 @@ export class Sandbox extends Machine {
318
319
  /** An interactive terminal over a WebSocket. Bytes you write are typed;
319
320
  * onData receives what the terminal prints. */
320
321
  async terminal(options = {}) {
321
- const socket = await this.#t.websocket(`/v1/sandboxes/${enc(this.id)}/terminal`, {
322
- cols: options.cols,
323
- rows: options.rows,
324
- command: options.command,
325
- cwd: options.cwd,
326
- user: options.user,
327
- processId: options.processId,
328
- });
322
+ const path = `/v1/sandboxes/${enc(this.id)}/terminal`;
323
+ // Resumes across a restart of the API with nothing lost (resumable.ts).
324
+ const socket = await ResumableSocket.open((resume) => this.#t.websocket(path, resume
325
+ ? { resume }
326
+ : {
327
+ cols: options.cols,
328
+ rows: options.rows,
329
+ command: options.command,
330
+ cwd: options.cwd,
331
+ user: options.user,
332
+ processId: options.processId,
333
+ }));
329
334
  return Terminal.open(socket, options.onData);
330
335
  }
331
336
  /** A tunnel into the sandbox: TCP connections to any port on its loopback,
@@ -333,7 +338,9 @@ export class Sandbox extends Machine {
333
338
  * internet. `tunnel.connect(5432)` gives one connection;
334
339
  * `tunnel.forward(5432)` listens locally (Node and Bun). */
335
340
  async tunnel() {
336
- return Tunnel.open(await this.#t.websocket(`/v1/sandboxes/${enc(this.id)}/tunnel`));
341
+ const path = `/v1/sandboxes/${enc(this.id)}/tunnel`;
342
+ const socket = await ResumableSocket.open((resume) => this.#t.websocket(path, resume ? { resume } : undefined));
343
+ return Tunnel.open(socket);
337
344
  }
338
345
  /** Listens on a local port (the same number unless `localPort` says, 0 for
339
346
  * any) and forwards each connection to `port` inside the sandbox, until
@@ -1,5 +1,5 @@
1
1
  import { RuntimeError } from "./errors.js";
2
- export declare const VERSION = "0.46.2";
2
+ export declare const VERSION = "0.47.0";
3
3
  export declare const DEFAULT_BASE_URL = "https://api.withruntime.com";
4
4
  /** Runtime's API as code inside a Runtime sandbox reaches it: the sandbox's
5
5
  * own host sends each request on to DEFAULT_BASE_URL over HTTPS. The API runs
@@ -47,6 +47,9 @@ export type Call = RequestOptions & {
47
47
  /** Seconds the server may hold the answer for a long-running result. */
48
48
  wait?: number;
49
49
  accept?: string;
50
+ /** Internal: headers of Runtime's own operator calls (the never-park mark,
51
+ * `runtime sandboxes never-park`), which the API refuses for anyone else. */
52
+ headers?: Record<string, string>;
50
53
  /** Sent as the Bearer token instead of the client's API key: a webhook
51
54
  * trigger's secret, which is all its calls carry. */
52
55
  bearer?: string;
package/dist/transport.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import { ConnectionError, DELIBERATE, errorFor, NOTHING_RAN, RuntimeError, WAITS_FOR_ROOM, } from "./errors.js";
2
2
  import { describeRoute, envFetch, openWebSocket, untrustedCertificate } from "./proxy.js";
3
3
  import { warningText } from "./product-renames.js";
4
- export const VERSION = "0.46.2";
4
+ export const VERSION = "0.47.0";
5
5
  export const DEFAULT_BASE_URL = "https://api.withruntime.com";
6
6
  /** Runtime's API as code inside a Runtime sandbox reaches it: the sandbox's
7
7
  * own host sends each request on to DEFAULT_BASE_URL over HTTPS. The API runs
@@ -298,6 +298,7 @@ export class Transport {
298
298
  }
299
299
  #headers(call, key, apiKey) {
300
300
  return {
301
+ ...call.headers,
301
302
  authorization: `Bearer ${apiKey}`,
302
303
  accept: call.accept ?? "application/json",
303
304
  "x-runtime-client": this.#client,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "withruntime",
3
- "version": "0.46.2",
3
+ "version": "0.47.0",
4
4
  "license": "Apache-2.0",
5
5
  "mcpName": "com.withruntime/runtime",
6
6
  "type": "module",