parpaing 1.1.1 → 2.0.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/README.md CHANGED
@@ -8,14 +8,32 @@ npm install parpaing
8
8
 
9
9
  ```ts
10
10
  import { Parpaing } from "parpaing";
11
+ import { setTimeout as sleep } from "node:timers/promises";
12
+
13
+ const parpaing = new Parpaing({ url: "http://127.0.0.1:8090" });
14
+ const { id } = await parpaing.create(); // debian:trixie-slim
15
+
16
+ // 1. Run a command, get its result
17
+ const { stdout } = await parpaing.exec(id, ["echo", "hello"]);
18
+ console.log(stdout); // hello
19
+
20
+ // 2. Watch the output live
21
+ await parpaing.exec(id, ["sh", "-c", "for i in 1 2 3; do echo $i; sleep 1; done"], {
22
+ onOutput: (data) => process.stdout.write(data),
23
+ });
24
+
25
+ // 3. Start in the background, read what it printed, stop it
26
+ const { id: cid } = await parpaing.start(id, ["sh", "-c", "while true; do date; sleep 1; done"]);
27
+ await sleep(3000);
28
+ await parpaing.output(id, cid, { onOutput: (data) => process.stdout.write(data) });
29
+ await parpaing.stop(id, cid);
11
30
 
12
- const parpaing = new Parpaing({ url: "http://127.0.0.1:8090", key: process.env.PARPAING_API_KEY });
13
- const { id } = await parpaing.create({ image: "node:24" });
14
- await parpaing.exec(id, ["node", "-v"]); // { exitCode, stdout, stderr, truncated }
15
- await parpaing.exec(id, ["npm", "test"], { onOutput: (data) => process.stdout.write(data) }); // live, then { exitCode }
16
31
  await parpaing.delete(id);
17
32
  ```
18
33
 
34
+ - **Run it**: save it as `demo.mjs`, then `node demo.mjs`.
35
+ - **With an API key**: `new Parpaing({ url: "http://127.0.0.1:8090", key: process.env.PARPAING_API_KEY })`.
36
+
19
37
  | Method | Route | Returns |
20
38
  |---|---|---|
21
39
  | `info()` | `GET /info` | Version, engines, capacity, sandbox count |
@@ -23,14 +41,25 @@ await parpaing.delete(id);
23
41
  | `list()` | `GET /sandboxes` | `[{ id, state }]` |
24
42
  | `get(id)` | `GET /sandboxes/:id` | The sandbox and its limits |
25
43
  | `delete(id)` | `DELETE /sandboxes/:id` | |
26
- | `exec(id, cmd)` | `POST /sandboxes/:id/exec` | `{ exitCode, stdout, stderr, truncated }`, each output cut past 10 MB |
27
- | `exec(id, cmd, { onOutput })` | the same, with `stream: true` | `{ exitCode }`, the output live |
44
+ | `exec(id, cmd)` | `start`, then `output` with `follow` to the end | `{ exitCode, stdout, stderr, skipped? }` |
45
+ | `exec(id, cmd, { onOutput })` | the same | `{ exitCode, skipped? }`, the output live |
46
+ | `start(id, cmd)` | `POST /sandboxes/:id/commands` | `{ id }`, at once |
47
+ | `commands(id)` | `GET /sandboxes/:id/commands` | `[{ id, cmd, state, exitCode }]`, the running and the last 50 finished |
48
+ | `command(id, cid)` | `GET /sandboxes/:id/commands/:cid` | `{ id, cmd, state, exitCode, outputSize }` |
49
+ | `output(id, cid, { from, follow, onOutput })` | `GET /sandboxes/:id/commands/:cid/output` | `{ exitCode?, next, skipped? }`, each piece to `onOutput` |
50
+ | `stop(id, cid)` | `POST /sandboxes/:id/commands/:cid/stop` | SIGTERM, SIGKILL 10 s later |
28
51
  | `readFolder(id, path)` | `GET /sandboxes/:id/archive` | The folder as a tar stream |
29
52
  | `writeFolder(id, path, tar)` | `PUT /sandboxes/:id/archive` | The tar (bytes, Blob or stream) unpacked in the folder |
30
53
 
31
54
  - **`image`**: any image Docker can pull, `debian:trixie-slim` by default: `node:24`, `user/image:tag`, `ghcr.io/owner/image:tag`.
32
55
  - **Refusals** throw a `ParpaingError` with the API's `status` and message.
33
- - **`signal`** on `exec` stops waiting, not the command.
56
+ - **Errors while reading output**: the `ParpaingError` carries `next`, the position to resume from with `from`.
57
+ - **`exec`** resumes by itself after a network failure or a 5xx answer, never after another error.
58
+ - **`exec` without `onOutput`** keeps at most the last 10 MiB of each stream.
59
+ - **`onOutput` errors** reach the caller unchanged and are not retried.
60
+ - **`output`** resumes where an earlier read stopped with `from: next`; `exitCode` comes once the output is finished.
61
+ - **`skipped`**: the bytes of output not in the result: those the daemon no longer kept, when a read started before them, plus those the SDK dropped. A command keeps at least its last 50 MiB of output, at most about 100 MiB.
62
+ - **`signal`** on `exec` and `output` stops reading, not the command: `stop` ends it.
34
63
 
35
64
  ## License
36
65
 
package/dist/index.d.ts CHANGED
@@ -32,8 +32,31 @@ export interface CommandResult {
32
32
  exitCode: number;
33
33
  stdout: string;
34
34
  stderr: string;
35
- /** stdout or stderr went past 10 MB and was cut. */
36
- truncated: boolean;
35
+ /**
36
+ * Bytes of output not in this result, only when some were: those the command no longer kept (it keeps at least its last
37
+ * 50 MiB, at most about 100 MiB) plus those exec dropped to keep only the last 10 MiB of each stream.
38
+ */
39
+ skipped?: number;
40
+ }
41
+ export interface CommandItem {
42
+ id: string;
43
+ cmd: string[];
44
+ /** exited once the main process has ended; processes it left behind may still add output. */
45
+ state: "running" | "exited";
46
+ /** null while the command runs; 128 + the signal number when a signal killed it. */
47
+ exitCode: number | null;
48
+ }
49
+ export interface Command extends CommandItem {
50
+ /** Bytes of output so far, stdout and stderr together. */
51
+ outputSize: number;
52
+ }
53
+ export interface OutputOptions {
54
+ /** The byte position to read from, 0 by default: the `next` of an earlier read resumes it. */
55
+ from?: number;
56
+ /** false by default: stop once caught up. true: wait for more output, until the end or about 50 s of silence. */
57
+ follow?: boolean;
58
+ onOutput?: OnOutput;
59
+ signal?: AbortSignal;
37
60
  }
38
61
  export interface Info {
39
62
  name: string;
@@ -50,10 +73,17 @@ export interface Info {
50
73
  };
51
74
  }
52
75
  export type OnOutput = (data: string, stream: "stdout" | "stderr") => void;
53
- /** A refusal from parpaing, with its HTTP status (400, 401, 404, 409, 503...) and its message. */
76
+ /**
77
+ * A refusal from parpaing, with its HTTP status (400, 401, 404, 409, 410, 503...) and its message. A read of the output that
78
+ * breaks (a broken connection or relay: 502, or a 5xx) also says `next`, where to resume with `from`.
79
+ */
54
80
  export declare class ParpaingError extends Error {
55
81
  readonly status: number;
56
- constructor(status: number, message: string);
82
+ readonly next?: number;
83
+ constructor(status: number, message: string, { next, cause }?: {
84
+ next?: number;
85
+ cause?: unknown;
86
+ });
57
87
  }
58
88
  export declare class Parpaing {
59
89
  #private;
@@ -73,8 +103,11 @@ export declare class Parpaing {
73
103
  get(id: string): Promise<Sandbox>;
74
104
  delete(id: string): Promise<void>;
75
105
  /**
76
- * Runs a command to its end and answers once. With `onOutput`, the output comes live instead, chunk by chunk, and only
77
- * the exit code is returned. Aborting `signal` stops waiting, not the command.
106
+ * Runs a command to its end and answers once, with the last 10 MiB of each stream. With `onOutput`, the output comes live
107
+ * instead, piece by piece, and only the exit code is returned. `skipped` counts the bytes of output not in the answer,
108
+ * when some were. A broken connection or a 5xx resumes where it stopped, 3 times in a row without progress at most; then
109
+ * the ParpaingError says `next`. An error thrown by `onOutput` ends exec as it is. Aborting `signal` stops reading, not
110
+ * the command.
78
111
  */
79
112
  exec(id: string, cmd: string[], options?: {
80
113
  signal?: AbortSignal;
@@ -84,7 +117,27 @@ export declare class Parpaing {
84
117
  signal?: AbortSignal;
85
118
  }): Promise<{
86
119
  exitCode: number;
120
+ skipped?: number;
121
+ }>;
122
+ /** Starts a command and answers its id at once. It runs until it ends or is stopped, whoever reads it. */
123
+ start(id: string, cmd: string[], signal?: AbortSignal): Promise<{
124
+ id: string;
125
+ }>;
126
+ /** The running commands and the last 50 finished ones, in start order. */
127
+ commands(id: string): Promise<CommandItem[]>;
128
+ command(id: string, cid: string): Promise<Command>;
129
+ /**
130
+ * Reads a command's output once, from `from`: each piece goes to `onOutput`. Answers `next`, where to resume, the exit
131
+ * code once the output is finished, and `skipped`, the bytes no longer kept, when the read started before what is kept.
132
+ * A read that breaks throws a ParpaingError saying `next`; an error thrown by `onOutput` is thrown as it is.
133
+ */
134
+ output(id: string, cid: string, { from, follow, onOutput, signal }?: OutputOptions): Promise<{
135
+ exitCode?: number;
136
+ next: number;
137
+ skipped?: number;
87
138
  }>;
139
+ /** SIGTERM to the command, SIGKILL 10 s later. Answers at once. */
140
+ stop(id: string, cid: string): Promise<void>;
88
141
  /** A folder of the sandbox as a tar archive, streamed. The image needs tar. */
89
142
  readFolder(id: string, path: string): Promise<ReadableStream<Uint8Array>>;
90
143
  /** Unpacks a tar archive (bytes, a Blob or a stream) into a folder of the sandbox, created if missing. */
package/dist/index.js CHANGED
@@ -1,14 +1,22 @@
1
1
  // parpaing's TypeScript SDK: one method per API route, no dependency. It needs fetch and web streams only, so it runs on
2
2
  // Node 18+, Deno, Bun and in browsers. The API reference is /docs on a running parpaing.
3
- /** A refusal from parpaing, with its HTTP status (400, 401, 404, 409, 503...) and its message. */
3
+ /**
4
+ * A refusal from parpaing, with its HTTP status (400, 401, 404, 409, 410, 503...) and its message. A read of the output that
5
+ * breaks (a broken connection or relay: 502, or a 5xx) also says `next`, where to resume with `from`.
6
+ */
4
7
  export class ParpaingError extends Error {
5
8
  status;
6
- constructor(status, message) {
7
- super(message);
9
+ next;
10
+ constructor(status, message, { next, cause } = {}) {
11
+ super(message, cause === undefined ? undefined : { cause });
8
12
  this.name = "ParpaingError";
9
13
  this.status = status;
14
+ if (next !== undefined)
15
+ this.next = next;
10
16
  }
11
17
  }
18
+ // exec without onOutput keeps the last 10 MiB of each stream.
19
+ const KEPT = 10 * 1024 * 1024;
12
20
  export class Parpaing {
13
21
  #url;
14
22
  #key;
@@ -61,23 +69,123 @@ export class Parpaing {
61
69
  await this.#call("DELETE", `/sandboxes/${encodeURIComponent(id)}`);
62
70
  }
63
71
  async exec(id, cmd, { onOutput, signal } = {}) {
64
- const json = { cmd, stream: onOutput !== undefined };
65
- const res = await this.#call("POST", `/sandboxes/${encodeURIComponent(id)}/exec`, { json, signal });
66
- if (!onOutput)
67
- return res.json();
68
- let exitCode;
69
- for await (const line of lines(res.body)) {
72
+ // Without onOutput, the pieces of each stream are kept up to KEPT bytes, the oldest dropped first.
73
+ const kept = { stdout: { data: [], sizes: [], bytes: 0 }, stderr: { data: [], sizes: [], bytes: 0 } };
74
+ let dropped = 0;
75
+ let thrown = false;
76
+ const show = (data, stream, bytes) => {
77
+ if (onOutput) {
78
+ try {
79
+ return onOutput(data, stream);
80
+ }
81
+ catch (error) {
82
+ thrown = true;
83
+ throw error;
84
+ }
85
+ }
86
+ const k = kept[stream];
87
+ k.data.push(data);
88
+ k.sizes.push(bytes);
89
+ k.bytes += bytes;
90
+ while (k.bytes > KEPT) {
91
+ k.data.shift();
92
+ const size = k.sizes.shift();
93
+ k.bytes -= size;
94
+ dropped += size;
95
+ }
96
+ };
97
+ const { id: cid } = await this.start(id, cmd, signal);
98
+ const at = { next: 0, skipped: 0 };
99
+ for (let failures = 0;;) {
100
+ const before = at.next;
101
+ try {
102
+ const { exitCode } = await this.#read(id, cid, at, true, show, signal);
103
+ const skipped = at.skipped + dropped ? { skipped: at.skipped + dropped } : {};
104
+ if (exitCode !== undefined) {
105
+ if (onOutput)
106
+ return { exitCode, ...skipped };
107
+ return { exitCode, stdout: kept.stdout.data.join(""), stderr: kept.stderr.data.join(""), ...skipped };
108
+ }
109
+ failures = 0;
110
+ }
111
+ catch (error) {
112
+ // onOutput's error, an abort or a refusal ends here; a broken connection or relay and a 5xx are tried again, 3 times
113
+ // in a row without progress at most.
114
+ if (thrown || signal?.aborted || !(error instanceof ParpaingError && error.status >= 500))
115
+ throw error;
116
+ failures = at.next === before ? failures + 1 : 0;
117
+ if (failures >= 3)
118
+ throw error;
119
+ // The pause ends at once when signal aborts.
120
+ await new Promise((resolve) => {
121
+ const done = () => {
122
+ clearTimeout(timer);
123
+ signal?.removeEventListener("abort", done);
124
+ resolve();
125
+ };
126
+ const timer = setTimeout(done, 500);
127
+ signal?.addEventListener("abort", done, { once: true });
128
+ });
129
+ signal?.throwIfAborted();
130
+ }
131
+ }
132
+ }
133
+ /** Starts a command and answers its id at once. It runs until it ends or is stopped, whoever reads it. */
134
+ async start(id, cmd, signal) {
135
+ return (await this.#call("POST", commands(id), { json: { cmd }, signal })).json();
136
+ }
137
+ /** The running commands and the last 50 finished ones, in start order. */
138
+ async commands(id) {
139
+ return (await this.#call("GET", commands(id))).json();
140
+ }
141
+ async command(id, cid) {
142
+ return (await this.#call("GET", commands(id, cid))).json();
143
+ }
144
+ /**
145
+ * Reads a command's output once, from `from`: each piece goes to `onOutput`. Answers `next`, where to resume, the exit
146
+ * code once the output is finished, and `skipped`, the bytes no longer kept, when the read started before what is kept.
147
+ * A read that breaks throws a ParpaingError saying `next`; an error thrown by `onOutput` is thrown as it is.
148
+ */
149
+ async output(id, cid, { from = 0, follow = false, onOutput, signal } = {}) {
150
+ const at = { next: from, skipped: 0 };
151
+ const { exitCode } = await this.#read(id, cid, at, follow, onOutput && ((data, stream) => onOutput(data, stream)), signal);
152
+ return { ...(exitCode === undefined ? {} : { exitCode }), next: at.next, ...(at.skipped ? { skipped: at.skipped } : {}) };
153
+ }
154
+ /** SIGTERM to the command, SIGKILL 10 s later. Answers at once. */
155
+ async stop(id, cid) {
156
+ await this.#call("POST", `${commands(id, cid)}/stop`, { json: {} });
157
+ }
158
+ // One read of the output from at.next; at.next follows each line once handled, so a read that breaks still says how far
159
+ // it got. A skipped line adds to at.skipped and the read goes on. A broken connection, a broken relay or a 5xx throws a
160
+ // ParpaingError with next; an abort, a refusal and onOutput's errors are thrown as they are.
161
+ async #read(id, cid, at, follow, onOutput, signal) {
162
+ const broken = (error) => {
163
+ if (signal?.aborted || (error instanceof ParpaingError && error.status < 500))
164
+ return error;
165
+ if (error instanceof ParpaingError)
166
+ return new ParpaingError(error.status, error.message, { next: at.next });
167
+ return new ParpaingError(502, `the connection to parpaing broke: ${error?.message}`, { next: at.next, cause: error });
168
+ };
169
+ let res;
170
+ try {
171
+ res = await this.#call("GET", `${commands(id, cid)}/output?from=${at.next}&follow=${follow}`, { signal });
172
+ }
173
+ catch (error) {
174
+ throw broken(error);
175
+ }
176
+ for await (const line of lines(res.body, broken)) {
70
177
  const item = JSON.parse(line);
71
- if (item.data !== undefined)
72
- onOutput(item.data, item.stream);
73
- else if (item.exitCode !== undefined)
74
- exitCode = item.exitCode;
75
- else if (item.error !== undefined)
76
- throw new ParpaingError(500, item.error);
178
+ if (item.error !== undefined)
179
+ throw new ParpaingError(502, item.error, { next: item.next ?? at.next });
180
+ if (item.stream !== undefined)
181
+ onOutput?.(item.data, item.stream, item.next - at.next);
182
+ else if (item.skipped !== undefined)
183
+ at.skipped += item.skipped;
184
+ at.next = item.next;
185
+ if (item.stream === undefined && item.skipped === undefined)
186
+ return { exitCode: item.exitCode };
77
187
  }
78
- if (exitCode === undefined)
79
- throw new ParpaingError(502, "the output ended without an exit code");
80
- return { exitCode };
188
+ throw new ParpaingError(502, "the output ended without a closing line", { next: at.next });
81
189
  }
82
190
  /** A folder of the sandbox as a tar archive, streamed. The image needs tar. */
83
191
  async readFolder(id, path) {
@@ -88,23 +196,37 @@ export class Parpaing {
88
196
  await this.#call("PUT", archive(id, path), { tar });
89
197
  }
90
198
  }
199
+ const commands = (id, cid) => `/sandboxes/${encodeURIComponent(id)}/commands` + (cid === undefined ? "" : `/${encodeURIComponent(cid)}`);
91
200
  const archive = (id, path) => `/sandboxes/${encodeURIComponent(id)}/archive?path=${encodeURIComponent(path)}`;
92
- // The lines of an NDJSON body, whole even when a chunk cuts one in two.
93
- async function* lines(body) {
201
+ // The lines of an NDJSON body, whole even when a chunk cuts one in two. A failed read throws broken(error). The body is
202
+ // released when the iteration stops, even early.
203
+ async function* lines(body, broken) {
94
204
  const reader = body.getReader();
95
205
  const decoder = new TextDecoder();
96
206
  let rest = "";
97
- for (;;) {
98
- const { done, value } = await reader.read();
99
- // stream: a character cut between two chunks waits for its end.
100
- const parts = (rest + decoder.decode(value, { stream: !done })).split("\n");
101
- rest = parts.pop() ?? "";
102
- for (const part of parts)
103
- if (part)
104
- yield part;
105
- if (done)
106
- break;
107
- }
108
- if (rest)
109
- yield rest;
207
+ try {
208
+ for (;;) {
209
+ let chunk;
210
+ try {
211
+ chunk = await reader.read();
212
+ }
213
+ catch (error) {
214
+ throw broken(error);
215
+ }
216
+ const { done, value } = chunk;
217
+ // stream: a character cut between two chunks waits for its end.
218
+ const parts = (rest + decoder.decode(value, { stream: !done })).split("\n");
219
+ rest = parts.pop() ?? "";
220
+ for (const part of parts)
221
+ if (part)
222
+ yield part;
223
+ if (done)
224
+ break;
225
+ }
226
+ if (rest)
227
+ yield rest;
228
+ }
229
+ finally {
230
+ reader.cancel().catch(() => { });
231
+ }
110
232
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "parpaing",
3
- "version": "1.1.1",
3
+ "version": "2.0.1",
4
4
  "description": "TypeScript SDK for parpaing: self-hosted sandboxes for AI agents, driven by an HTTP API.",
5
5
  "license": "Apache-2.0",
6
6
  "type": "module",