@inferencesh/sdk 0.39.1 → 0.39.2

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/api/files.js CHANGED
@@ -137,7 +137,14 @@ export class FilesAPI {
137
137
  if (!file.upload_url) {
138
138
  throw new Error('No upload URL provided by the server');
139
139
  }
140
- await putToSignedUrl(file.upload_url, resolved.body);
140
+ try {
141
+ await putToSignedUrl(file.upload_url, resolved.body);
142
+ }
143
+ catch (err) {
144
+ // The record was counted at its size and holds nothing: drop it.
145
+ await this.delete(file.id).catch(() => undefined);
146
+ throw err;
147
+ }
141
148
  return file;
142
149
  }
143
150
  /**
@@ -1,6 +1,95 @@
1
1
  import { HttpClient } from '../http/client.js';
2
2
  import type { Response } from '../http/response.js';
3
- import { CreateSandboxRequest, CursorListRequest, CursorListResponse, SandboxDTO } from '../types.js';
3
+ import type { FilesAPI } from './files.js';
4
+ import { CreateSandboxRequest, CursorListRequest, CursorListResponse, EnforcementMode, EntitlementType, FileDTO as File, SandboxDTO } from '../types.js';
5
+ /** One command run on a remote (the API's ExecRunDTO, the fields read here). */
6
+ export interface SandboxExecRun {
7
+ id: string;
8
+ status: 'pending' | 'running' | 'exited' | 'killed' | 'denied';
9
+ exit_code?: number;
10
+ timed_out?: boolean;
11
+ error?: string;
12
+ [key: string]: unknown;
13
+ }
14
+ /** The result of {@link SandboxesAPI.exec}: the run, and the last MiB of each stream. */
15
+ export interface SandboxExecResult {
16
+ run: SandboxExecRun;
17
+ /**
18
+ * false: the command was still running when the wait ran out; it keeps
19
+ * running. Read from `run.status` (the API answers no `done`).
20
+ */
21
+ done: boolean;
22
+ stdout: string;
23
+ stderr: string;
24
+ }
25
+ export interface SandboxExecOptions {
26
+ args?: string[];
27
+ cwd?: string;
28
+ /** KEY=VALUE entries. */
29
+ env?: string[];
30
+ /** Kill the command after this long (ms). */
31
+ timeoutMs?: number;
32
+ /** How long to wait for it to finish, whole seconds from 1 to 600. Default 60. */
33
+ waitSeconds?: number;
34
+ }
35
+ /** One entry of a directory on a running sandbox. */
36
+ export interface SandboxFileEntry {
37
+ name: string;
38
+ kind: 'file' | 'dir' | 'link' | 'other';
39
+ size: number;
40
+ /** Octal permission bits, e.g. "644". */
41
+ mode: string;
42
+ modified_at?: string;
43
+ }
44
+ /**
45
+ * An import or an export: the path on the box, the platform file on the
46
+ * other side (its `size` is the file's) and, for an export, a short-lived
47
+ * URL that downloads it.
48
+ */
49
+ export interface SandboxFileTransfer {
50
+ path: string;
51
+ file?: File;
52
+ download_url?: string;
53
+ }
54
+ /**
55
+ * One team limit and its use now (the API's ResourceUsage). A `warn` limit
56
+ * (kept disks, snapshots) is soft: going past it is not refused.
57
+ * TODO(models): use the generated ResourceUsage once the models release carries it.
58
+ */
59
+ export interface SandboxResourceUsage {
60
+ /** "sandboxes", "sandbox_vcpus", or another sandbox_* resource. */
61
+ resource: string;
62
+ label: string;
63
+ unit?: string;
64
+ type: EntitlementType;
65
+ usage: number;
66
+ /** Not read when `unlimited`. */
67
+ limit: number;
68
+ unlimited: boolean;
69
+ enabled: boolean;
70
+ mode?: EnforcementMode;
71
+ }
72
+ export interface SandboxRange {
73
+ default: number;
74
+ max: number;
75
+ }
76
+ /** What the team may run now, and the sizes one sandbox may ask for. */
77
+ export interface SandboxLimits {
78
+ /**
79
+ * `sandboxes` (running at once) and every sandbox_* limit (e.g.
80
+ * `sandbox_vcpus`), sorted by resource.
81
+ */
82
+ limits: SandboxResourceUsage[];
83
+ vcpus_per_sandbox: SandboxRange;
84
+ memory_mib: SandboxRange;
85
+ disk_mib: SandboxRange;
86
+ /** Seconds; 0 never stops. */
87
+ idle_timeout_default: number;
88
+ idle_timeout_min: number;
89
+ idle_timeout_max: number;
90
+ /** Seconds a stopped sandbox's disk is kept. */
91
+ disk_kept_for: number;
92
+ }
4
93
  /**
5
94
  * Sandboxes API
6
95
  *
@@ -10,7 +99,11 @@ import { CreateSandboxRequest, CursorListRequest, CursorListResponse, SandboxDTO
10
99
  */
11
100
  export declare class SandboxesAPI {
12
101
  private readonly http;
13
- constructor(http: HttpClient);
102
+ private readonly files?;
103
+ /** files uploads and deletes the storage copy writeFile and readFile move bytes through. */
104
+ constructor(http: HttpClient, files?: FilesAPI | undefined);
105
+ /** Each sandbox's remote id, as exec last found it. */
106
+ private readonly remoteIds;
14
107
  /**
15
108
  * List the caller's sandboxes with cursor-based pagination
16
109
  */
@@ -35,4 +128,42 @@ export declare class SandboxesAPI {
35
128
  * Stop a sandbox, then remove the record and its remote
36
129
  */
37
130
  delete(id: string): Promise<Response<void>>;
131
+ /**
132
+ * Run a command on a running sandbox and wait for it (up to
133
+ * `waitSeconds`, default 60). Returns the run with the last MiB of stdout
134
+ * and stderr; `done` is false when it is still running.
135
+ */
136
+ exec(id: string, command: string, options?: SandboxExecOptions): Promise<SandboxExecResult>;
137
+ /** The remote of a running sandbox, looked up and kept for the next exec. */
138
+ private remoteId;
139
+ /** List the directory at an absolute path on a running sandbox. */
140
+ listFiles(id: string, path: string): Promise<Response<SandboxFileEntry[]>>;
141
+ /** Delete a file (not a directory) on a running sandbox. */
142
+ deleteFile(id: string, path: string): Promise<void>;
143
+ /**
144
+ * Have a running sandbox download a platform file (see `files.upload`) to
145
+ * an absolute path. The bytes go from storage to the box directly.
146
+ */
147
+ importFile(id: string, path: string, fileId: string): Promise<SandboxFileTransfer>;
148
+ /**
149
+ * Have a running sandbox upload the file at an absolute path into a new
150
+ * platform file of yours; `download_url` fetches it for 15 minutes.
151
+ */
152
+ exportFile(id: string, path: string): Promise<SandboxFileTransfer>;
153
+ /**
154
+ * Read a file from a running sandbox. It goes through your file storage
155
+ * (an export, then a download); the storage copy is deleted after.
156
+ */
157
+ readFile(id: string, path: string): Promise<Uint8Array>;
158
+ /** Read a UTF-8 text file from a running sandbox; a leading BOM is kept. */
159
+ readTextFile(id: string, path: string): Promise<string>;
160
+ /**
161
+ * Write a file on a running sandbox, making its directory. It goes
162
+ * through your file storage (an upload, then an import), so it can be as
163
+ * large as one upload; the storage copy is deleted after. Storage takes
164
+ * no empty upload: make an empty file with {@link exec} (`touch`).
165
+ */
166
+ writeFile(id: string, path: string, content: Uint8Array | string | Blob): Promise<SandboxFileTransfer>;
167
+ /** What the team may run now, and the sizes one sandbox may ask for. */
168
+ limits(): Promise<Response<SandboxLimits>>;
38
169
  }
@@ -1,3 +1,9 @@
1
+ import { InferenceError } from '../http/errors.js';
2
+ /** A run's statuses once it has finished. */
3
+ const EXEC_RUN_FINISHED = new Set(['exited', 'killed', 'denied']);
4
+ /** The longest {@link SandboxExecOptions.waitSeconds} the API holds a request. */
5
+ const EXEC_WAIT_MAX = 600;
6
+ const filesPath = (id, path) => `/sandboxes/${encodeURIComponent(id)}/files?path=${encodeURIComponent(path)}`;
1
7
  /**
2
8
  * Sandboxes API
3
9
  *
@@ -6,8 +12,12 @@
6
12
  * start, stop and delete answer at once and the status follows.
7
13
  */
8
14
  export class SandboxesAPI {
9
- constructor(http) {
15
+ /** files uploads and deletes the storage copy writeFile and readFile move bytes through. */
16
+ constructor(http, files) {
10
17
  this.http = http;
18
+ this.files = files;
19
+ /** Each sandbox's remote id, as exec last found it. */
20
+ this.remoteIds = new Map();
11
21
  }
12
22
  /**
13
23
  * List the caller's sandboxes with cursor-based pagination
@@ -37,12 +47,145 @@ export class SandboxesAPI {
37
47
  * Stop a sandbox. The record and its remote stay.
38
48
  */
39
49
  async stop(id) {
50
+ this.remoteIds.delete(id);
40
51
  return this.http.request('post', `/sandboxes/${id}/stop`);
41
52
  }
42
53
  /**
43
54
  * Stop a sandbox, then remove the record and its remote
44
55
  */
45
56
  async delete(id) {
57
+ this.remoteIds.delete(id);
46
58
  return this.http.request('delete', `/sandboxes/${id}`);
47
59
  }
60
+ /**
61
+ * Run a command on a running sandbox and wait for it (up to
62
+ * `waitSeconds`, default 60). Returns the run with the last MiB of stdout
63
+ * and stderr; `done` is false when it is still running.
64
+ */
65
+ async exec(id, command, options = {}) {
66
+ const wait = options.waitSeconds ?? 60;
67
+ // 0 would answer the bare run, not a result: the API waits only for 1 or more.
68
+ if (!Number.isInteger(wait) || wait < 1 || wait > EXEC_WAIT_MAX) {
69
+ throw new RangeError(`waitSeconds is whole seconds from 1 to ${EXEC_WAIT_MAX}, not ${wait}`);
70
+ }
71
+ const run = async (remoteId) => {
72
+ const res = await this.http.request('post', `/remotes/${encodeURIComponent(remoteId)}/execs`, {
73
+ params: { wait },
74
+ data: { command, args: options.args, cwd: options.cwd, env: options.env, timeout_ms: options.timeoutMs },
75
+ });
76
+ return { ...res.data, done: EXEC_RUN_FINISHED.has(res.data.run.status) };
77
+ };
78
+ const cached = this.remoteIds.get(id);
79
+ if (cached) {
80
+ try {
81
+ return await run(cached);
82
+ }
83
+ catch (err) {
84
+ // The remote went away or is not connected: look the sandbox up again.
85
+ if (!(err instanceof InferenceError) || (err.statusCode !== 404 && err.statusCode !== 409)) {
86
+ throw err;
87
+ }
88
+ this.remoteIds.delete(id);
89
+ }
90
+ }
91
+ return run(await this.remoteId(id));
92
+ }
93
+ /** The remote of a running sandbox, looked up and kept for the next exec. */
94
+ async remoteId(id) {
95
+ const sandbox = (await this.get(id)).data;
96
+ if (sandbox.status !== 'running') {
97
+ throw new Error(`sandbox ${id} is ${sandbox.status}, not running; start it first`);
98
+ }
99
+ if (!sandbox.remote_id) {
100
+ throw new Error(`sandbox ${id} has no remote yet; wait until it is running`);
101
+ }
102
+ this.remoteIds.set(id, sandbox.remote_id);
103
+ return sandbox.remote_id;
104
+ }
105
+ /** List the directory at an absolute path on a running sandbox. */
106
+ async listFiles(id, path) {
107
+ return this.http.request('get', filesPath(id, path));
108
+ }
109
+ /** Delete a file (not a directory) on a running sandbox. */
110
+ async deleteFile(id, path) {
111
+ await this.http.request('delete', filesPath(id, path));
112
+ }
113
+ /**
114
+ * Have a running sandbox download a platform file (see `files.upload`) to
115
+ * an absolute path. The bytes go from storage to the box directly.
116
+ */
117
+ async importFile(id, path, fileId) {
118
+ const res = await this.http.request('post', `/sandboxes/${encodeURIComponent(id)}/files/import`, {
119
+ data: { path, file_id: fileId },
120
+ });
121
+ return res.data;
122
+ }
123
+ /**
124
+ * Have a running sandbox upload the file at an absolute path into a new
125
+ * platform file of yours; `download_url` fetches it for 15 minutes.
126
+ */
127
+ async exportFile(id, path) {
128
+ const res = await this.http.request('post', `/sandboxes/${encodeURIComponent(id)}/files/export`, {
129
+ data: { path },
130
+ });
131
+ return res.data;
132
+ }
133
+ /**
134
+ * Read a file from a running sandbox. It goes through your file storage
135
+ * (an export, then a download); the storage copy is deleted after.
136
+ */
137
+ async readFile(id, path) {
138
+ // Without it the export's storage copy could not be deleted after.
139
+ if (!this.files) {
140
+ throw new Error('readFile needs the files API: use the client\'s sandboxes, not a bare SandboxesAPI');
141
+ }
142
+ const files = this.files;
143
+ const t = await this.exportFile(id, path);
144
+ try {
145
+ if (!t.download_url) {
146
+ throw new Error(`the export of ${path} returned no download URL`);
147
+ }
148
+ const res = await fetch(t.download_url);
149
+ if (!res.ok) {
150
+ throw new Error(`downloading ${path} from storage: HTTP ${res.status}`);
151
+ }
152
+ return new Uint8Array(await res.arrayBuffer());
153
+ }
154
+ finally {
155
+ if (t.file?.id) {
156
+ await files.delete(t.file.id).catch(() => undefined);
157
+ }
158
+ }
159
+ }
160
+ /** Read a UTF-8 text file from a running sandbox; a leading BOM is kept. */
161
+ async readTextFile(id, path) {
162
+ return new TextDecoder('utf-8', { ignoreBOM: true }).decode(await this.readFile(id, path));
163
+ }
164
+ /**
165
+ * Write a file on a running sandbox, making its directory. It goes
166
+ * through your file storage (an upload, then an import), so it can be as
167
+ * large as one upload; the storage copy is deleted after. Storage takes
168
+ * no empty upload: make an empty file with {@link exec} (`touch`).
169
+ */
170
+ async writeFile(id, path, content) {
171
+ if (!this.files) {
172
+ throw new Error('writeFile needs the files API: use the client\'s sandboxes, not a bare SandboxesAPI');
173
+ }
174
+ const blob = content instanceof Blob ? content : new Blob([typeof content === 'string' ? new TextEncoder().encode(content) : content]);
175
+ if (blob.size === 0) {
176
+ throw new RangeError(`${path}: an empty file is not uploaded; make it with exec('touch')`);
177
+ }
178
+ const name = path.split('/').pop() || 'file';
179
+ const file = await this.files.upload(blob, { filename: name });
180
+ try {
181
+ return await this.importFile(id, path, file.id);
182
+ }
183
+ finally {
184
+ await this.files.delete(file.id).catch(() => undefined);
185
+ }
186
+ }
187
+ /** What the team may run now, and the sizes one sandbox may ask for. */
188
+ async limits() {
189
+ return this.http.request('get', '/sandboxes/limits');
190
+ }
48
191
  }
@@ -262,6 +262,12 @@ export class HttpClient {
262
262
  if (response.status === 204 || !responseText) {
263
263
  return { data: undefined, messages: [] };
264
264
  }
265
+ // A held request (exec wait, file import/export) answers 200 before its
266
+ // outcome; when it fails, the body under that 200 is a problem.
267
+ const heldStatus = problemStatus(data);
268
+ if (heldStatus !== undefined) {
269
+ throw this.responseError(heldStatus, responseText, data);
270
+ }
265
271
  // Unwrap V3 envelope: {"data": <dto>, "messages": [...]}
266
272
  if (data && typeof data === 'object' && 'data' in data && !Array.isArray(data)) {
267
273
  const messages = data.messages ?? [];
@@ -316,6 +322,20 @@ export class HttpClient {
316
322
  return Promise.resolve(new EventSource(this.streamUrl(targetUrl), { fetch: doFetch }));
317
323
  }
318
324
  }
325
+ /**
326
+ * The status of a problem+json body (RFC 9457): an object with a numeric
327
+ * `status` of 400 or more and a `title`, `detail` or `type`.
328
+ */
329
+ function problemStatus(data) {
330
+ if (!data || typeof data !== 'object' || Array.isArray(data))
331
+ return undefined;
332
+ const d = data;
333
+ if (typeof d.status !== 'number' || d.status < 400)
334
+ return undefined;
335
+ if (typeof d.title !== 'string' && typeof d.detail !== 'string' && typeof d.type !== 'string')
336
+ return undefined;
337
+ return d.status;
338
+ }
319
339
  /**
320
340
  * Create an HTTP client instance
321
341
  */
package/dist/index.d.ts CHANGED
@@ -27,6 +27,7 @@ export { SearchAPI } from './api/search.js';
27
27
  export { ProjectsAPI } from './api/projects.js';
28
28
  export { MCPServersAPI } from './api/mcp-servers.js';
29
29
  export { SandboxesAPI } from './api/sandboxes.js';
30
+ export type { SandboxExecRun, SandboxExecResult, SandboxExecOptions, SandboxFileEntry, SandboxFileTransfer, SandboxResourceUsage, SandboxRange, SandboxLimits, } from './api/sandboxes.js';
30
31
  export { PublicationsAPI } from './api/publications.js';
31
32
  export { LiveSession, accessUrl } from './live/session.js';
32
33
  export type { LiveState, LiveEnd, LiveHandlers, LiveSessionOptions, RealtimeOptions, LiveUpdate, WebSocketLike, WebSocketConstructor } from './live/session.js';
package/dist/index.js CHANGED
@@ -111,7 +111,7 @@ export class Inference {
111
111
  this.search = new SearchAPI(this.http);
112
112
  this.projects = new ProjectsAPI(this.http);
113
113
  this.mcpServers = new MCPServersAPI(this.http);
114
- this.sandboxes = new SandboxesAPI(this.http);
114
+ this.sandboxes = new SandboxesAPI(this.http, this.files);
115
115
  this.publications = new PublicationsAPI(this.http);
116
116
  this.sockets = new SocketsAPI(this.http, this.tasks);
117
117
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@inferencesh/sdk",
3
- "version": "0.39.1",
3
+ "version": "0.39.2",
4
4
  "description": "Official JavaScript/TypeScript SDK for inference.sh - Run AI models with a simple API",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",